localharness 0.70.0

Agents that own themselves: one Rust crate that's both an agent SDK (streaming, tools, hooks, policies, triggers, MCP) and a wallet-owning, self-sovereign agent that runs in the browser.
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
//! Browser OPFS-backed implementation of [`Filesystem`].
//!
//! Uses the Origin Private File System exposed via
//! `navigator.storage.getDirectory()`. Each browser tab/origin gets its
//! own private root directory.
//!
//! ## Atomicity
//!
//! `write_atomic` relies on OPFS's `FileSystemWritableFileStream`
//! semantics: writes are buffered to a swap file and the original is
//! atomically replaced on `close()`. A page reload mid-write leaves
//! the original file intact.
//!
//! ## Path handling
//!
//! OPFS has no native path syntax — only handles. This impl splits
//! incoming paths on `/`, drops empty components, and resolves each
//! component as a directory (or final file). Leading slashes are
//! ignored; OPFS-rooted paths and relative paths are equivalent.

use std::cell::RefCell;
use std::rc::Rc;

use async_trait::async_trait;
use js_sys::{Object, Reflect, Uint8Array};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sys::{
    File, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetDirectoryOptions,
    FileSystemGetFileOptions, FileSystemHandle, FileSystemHandleKind, FileSystemRemoveOptions,
    FileSystemWritableFileStream,
};

use super::{DirEntry, EntryKind, Filesystem, Metadata, WalkEntry};
use crate::error::{Error, Result};

/// Hard cap on entries a single `walk` collects. find_file/search_directory
/// cap their own RESULTS, but they collect the whole walk first, so without
/// this a walk over a huge tree would exhaust memory. Mirrors
/// `NativeFilesystem::MAX_WALK_ENTRIES`; 200k is far beyond any real workspace.
const MAX_WALK_ENTRIES: usize = 200_000;

/// Filesystem backed by the browser's Origin Private File System.
///
/// Cheap to clone: holds an `Rc` to the OPFS root handle once acquired.
#[derive(Debug, Clone, Default)]
pub struct OpfsFilesystem {
    // Cache the OPFS root after first acquisition; getDirectory()
    // returns the same logical handle every time but each call is async.
    root: Rc<RefCell<Option<FileSystemDirectoryHandle>>>,
}

impl OpfsFilesystem {
    pub fn new() -> Self {
        Self::default()
    }

    async fn root_handle(&self) -> Result<FileSystemDirectoryHandle> {
        // NEVER hold a `Ref`/`RefMut` across the `getDirectory().await` below.
        // The single-threaded wasm executor interleaves tasks at await points,
        // and on iOS WebKit's microtask timing a borrow held across an await can
        // be re-entered by a concurrent OPFS op → "RefCell already borrowed".
        // Take an OWNED clone out of the borrow in its own statement, so the
        // guard is dropped before we await.
        let cached = self.root.borrow().clone();
        if let Some(h) = cached {
            return Ok(h);
        }
        let window = web_sys::window()
            .ok_or_else(|| Error::fs("getDirectory", "", "no window: not in a browser"))?;
        let storage = window.navigator().storage();
        let promise = storage.get_directory();
        let val = JsFuture::from(promise)
            .await
            .map_err(|e| Error::fs("getDirectory", "", format!("getDirectory: {}", js_err(&e))))?;
        let handle: FileSystemDirectoryHandle = val
            .dyn_into()
            .map_err(|_| {
                Error::fs("getDirectory", "", "getDirectory: not a FileSystemDirectoryHandle")
            })?;
        // Cache in a brief, await-free borrow. Two concurrent first-init callers
        // each resolve their own `getDirectory()` (OPFS returns the same logical
        // root every time), so a double-init just caches the equivalent handle
        // twice — harmless, never a borrow conflict.
        *self.root.borrow_mut() = Some(handle.clone());
        Ok(handle)
    }

    /// Walk a path's parent components, returning the deepest directory
    /// handle and the final segment (`None` if the path resolves to the
    /// root itself).
    async fn resolve_parent(
        &self,
        path: &str,
        create_dirs: bool,
    ) -> Result<(FileSystemDirectoryHandle, Option<String>)> {
        let parts = split_path(path);
        if parts.is_empty() {
            return Ok((self.root_handle().await?, None));
        }
        let mut dir = self.root_handle().await?;
        for component in &parts[..parts.len() - 1] {
            dir = get_subdir(&dir, component, create_dirs).await?;
        }
        Ok((dir, Some(parts.last().unwrap().clone())))
    }

    /// Resolve a path to the directory handle it names (errors if the
    /// path doesn't exist or names a file).
    async fn resolve_dir(&self, path: &str) -> Result<FileSystemDirectoryHandle> {
        let parts = split_path(path);
        let mut dir = self.root_handle().await?;
        for component in &parts {
            dir = get_subdir(&dir, component, false).await?;
        }
        Ok(dir)
    }
}

#[async_trait(?Send)]
impl Filesystem for OpfsFilesystem {
    async fn read(&self, path: &str) -> Result<Vec<u8>> {
        let (parent, name) = self.resolve_parent(path, false).await?;
        let name =
            name.ok_or_else(|| Error::fs("read", path, format!("read({path}): path is empty")))?;
        let file_handle = get_file(&parent, &name, false).await?;
        let file_val = JsFuture::from(file_handle.get_file())
            .await
            .map_err(|e| Error::fs("getFile", path, format!("getFile({path}): {}", js_err(&e))))?;
        let file: File = file_val
            .dyn_into()
            .map_err(|_| Error::fs("getFile", path, format!("getFile({path}): not a File")))?;
        let buf = JsFuture::from(file.array_buffer())
            .await
            .map_err(|e| {
                Error::fs("arrayBuffer", path, format!("arrayBuffer({path}): {}", js_err(&e)))
            })?;
        let array = Uint8Array::new(&buf);
        Ok(array.to_vec())
    }

    async fn write_atomic(&self, path: &str, bytes: &[u8]) -> Result<()> {
        let (parent, name) = self.resolve_parent(path, true).await?;
        let name = name.ok_or_else(|| {
            Error::fs("write_atomic", path, format!("write_atomic({path}): path is empty"))
        })?;
        let file_handle = get_file(&parent, &name, true).await?;
        let writable_val = JsFuture::from(file_handle.create_writable())
            .await
            .map_err(|e| {
                Error::fs("createWritable", path, format!("createWritable({path}): {}", js_err(&e)))
            })?;
        let writable: FileSystemWritableFileStream = writable_val
            .dyn_into()
            .map_err(|_| Error::fs("createWritable", path, "createWritable: not a writable stream"))?;
        let array = Uint8Array::from(bytes);
        let write_promise = writable
            .write_with_buffer_source(&array)
            .map_err(|e| Error::fs("write", path, format!("write({path}): {}", js_err(&e))))?;
        JsFuture::from(write_promise)
            .await
            .map_err(|e| Error::fs("write", path, format!("write({path}): {}", js_err(&e))))?;
        JsFuture::from(writable.close())
            .await
            .map_err(|e| Error::fs("close", path, format!("close({path}): {}", js_err(&e))))?;
        Ok(())
    }

    async fn metadata(&self, path: &str) -> Result<Option<Metadata>> {
        let (parent, name) = self.resolve_parent(path, false).await?;
        let Some(name) = name else {
            // Path resolved to OPFS root — it's a directory.
            return Ok(Some(Metadata {
                kind: EntryKind::Directory,
                size: 0,
            }));
        };
        // Try file first, then directory.
        match get_file(&parent, &name, false).await {
            Ok(fh) => {
                let file_val = JsFuture::from(fh.get_file())
                    .await
                    .map_err(|e| Error::fs("getFile", path, format!("getFile({path}): {}", js_err(&e))))?;
                let file: File = file_val
                    .dyn_into()
                    .map_err(|_| Error::fs("getFile", path, format!("getFile({path}): not a File")))?;
                Ok(Some(Metadata {
                    kind: EntryKind::File,
                    size: file.size() as u64,
                }))
            }
            Err(_) => match get_subdir(&parent, &name, false).await {
                Ok(_) => Ok(Some(Metadata {
                    kind: EntryKind::Directory,
                    size: 0,
                })),
                Err(_) => Ok(None),
            },
        }
    }

    async fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>> {
        let dir = self.resolve_dir(path).await?;
        let mut entries = collect_entries(&dir).await?;
        entries.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(entries)
    }

    async fn walk(&self, path: &str, max_depth: Option<usize>) -> Result<Vec<WalkEntry>> {
        let root = self.resolve_dir(path).await?;
        let mut out = Vec::new();
        // Root entry itself at depth 0.
        out.push(WalkEntry {
            path: path.trim_end_matches('/').to_string(),
            kind: EntryKind::Directory,
            size: None,
        });
        walk_dir(&root, path, 1, max_depth, &mut out).await?;
        Ok(out)
    }

    async fn delete(&self, path: &str) -> Result<()> {
        let (parent, name) = self.resolve_parent(path, false).await?;
        let name =
            name.ok_or_else(|| {
                Error::fs("delete", path, format!("delete({path}): cannot delete OPFS root"))
            })?;
        let opts = FileSystemRemoveOptions::new();
        opts.set_recursive(true);
        let promise = parent.remove_entry_with_options(&name, &opts);
        JsFuture::from(promise)
            .await
            .map_err(|e| {
                Error::fs("removeEntry", path, format!("removeEntry({path}): {}", js_err(&e)))
            })?;
        Ok(())
    }
}

fn split_path(path: &str) -> Vec<String> {
    path.split('/')
        .filter(|s| !s.is_empty() && *s != ".")
        .map(|s| s.to_string())
        .collect()
}

async fn get_subdir(
    parent: &FileSystemDirectoryHandle,
    name: &str,
    create: bool,
) -> Result<FileSystemDirectoryHandle> {
    let opts = FileSystemGetDirectoryOptions::new();
    opts.set_create(create);
    let promise = parent.get_directory_handle_with_options(name, &opts);
    let val = JsFuture::from(promise)
        .await
        .map_err(|e| {
            Error::fs(
                "getDirectoryHandle",
                name,
                format!("getDirectoryHandle({name}): {}", js_err(&e)),
            )
        })?;
    val.dyn_into().map_err(|_| {
        Error::fs("getDirectoryHandle", name, format!("getDirectoryHandle({name}): wrong type"))
    })
}

async fn get_file(
    parent: &FileSystemDirectoryHandle,
    name: &str,
    create: bool,
) -> Result<FileSystemFileHandle> {
    let opts = FileSystemGetFileOptions::new();
    opts.set_create(create);
    let promise = parent.get_file_handle_with_options(name, &opts);
    let val = JsFuture::from(promise)
        .await
        .map_err(|e| {
            Error::fs("getFileHandle", name, format!("getFileHandle({name}): {}", js_err(&e)))
        })?;
    val.dyn_into()
        .map_err(|_| Error::fs("getFileHandle", name, format!("getFileHandle({name}): wrong type")))
}

/// Iterate a directory's entries via the JS async iterator protocol.
async fn collect_entries(dir: &FileSystemDirectoryHandle) -> Result<Vec<DirEntry>> {
    let iter_method =
        Reflect::get(dir, &JsValue::from_str("entries"))
            .map_err(|_| Error::fs("entries", "", "entries"))?;
    let iter_fn = iter_method
        .dyn_ref::<js_sys::Function>()
        .ok_or_else(|| Error::fs("entries", "", "entries() not callable"))?;
    let iterator = iter_fn
        .call0(dir)
        .map_err(|e| Error::fs("entries", "", format!("entries(): {}", js_err(&e))))?;
    let next_fn = Reflect::get(&iterator, &JsValue::from_str("next"))
        .map_err(|_| Error::fs("iterator.next", "", "iterator.next"))?
        .dyn_into::<js_sys::Function>()
        .map_err(|_| Error::fs("iterator.next", "", "iterator.next not a function"))?;

    let mut out = Vec::new();
    loop {
        let promise = next_fn
            .call0(&iterator)
            .map_err(|e| Error::fs("iterator.next", "", format!("iterator.next: {}", js_err(&e))))?;
        let result = JsFuture::from(js_sys::Promise::from(promise))
            .await
            .map_err(|e| {
                Error::fs("iterator await", "", format!("iterator await: {}", js_err(&e)))
            })?;
        let done = Reflect::get(&result, &JsValue::from_str("done"))
            .ok()
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        if done {
            break;
        }
        let value = Reflect::get(&result, &JsValue::from_str("value"))
            .map_err(|_| Error::fs("iterator value", "", "iterator value"))?;
        // value is [name, handle] tuple (a 2-element array).
        let pair: js_sys::Array = value
            .dyn_into()
            .map_err(|_| Error::fs("entries", "", "entry value not an array"))?;
        let name = pair
            .get(0)
            .as_string()
            .ok_or_else(|| Error::fs("entries", "", "entry[0] not a string"))?;
        let handle_val = pair.get(1);
        let handle: FileSystemHandle = handle_val
            .dyn_into()
            .map_err(|_| Error::fs("entries", "", "entry[1] not a FileSystemHandle"))?;
        let (kind, size) = match handle.kind() {
            FileSystemHandleKind::File => {
                let fh: FileSystemFileHandle = handle.unchecked_into();
                let file_val = JsFuture::from(fh.get_file())
                    .await
                    .map_err(|e| Error::fs("getFile", "", format!("getFile: {}", js_err(&e))))?;
                let file: File = file_val
                    .dyn_into()
                    .map_err(|_| Error::fs("getFile", "", "getFile: not a File"))?;
                (EntryKind::File, Some(file.size() as u64))
            }
            FileSystemHandleKind::Directory => (EntryKind::Directory, None),
            _ => (EntryKind::Other, None),
        };
        out.push(DirEntry { name, kind, size });
    }
    Ok(out)
}

/// Recursive depth-first walk. `depth` is the depth of `dir` relative
/// to the walk root (root itself is depth 0).
async fn walk_dir(
    dir: &FileSystemDirectoryHandle,
    prefix: &str,
    depth: usize,
    max_depth: Option<usize>,
    out: &mut Vec<WalkEntry>,
) -> Result<()> {
    if let Some(d) = max_depth {
        if depth > d {
            return Ok(());
        }
    }
    let entries = collect_entries(dir).await?;
    for entry in entries {
        // Stop once the global cap is hit (an over-large tree must not
        // exhaust memory) — matches NativeFilesystem's MAX_WALK_ENTRIES.
        if out.len() >= MAX_WALK_ENTRIES {
            return Ok(());
        }
        let path = if prefix.is_empty() || prefix == "/" {
            entry.name.clone()
        } else {
            format!("{}/{}", prefix.trim_end_matches('/'), entry.name)
        };
        match entry.kind {
            EntryKind::File => {
                out.push(WalkEntry {
                    path,
                    kind: EntryKind::File,
                    size: entry.size,
                });
            }
            EntryKind::Directory => {
                out.push(WalkEntry {
                    path: path.clone(),
                    kind: EntryKind::Directory,
                    size: None,
                });
                let sub = get_subdir(dir, &entry.name, false).await?;
                // Recursive async — use Box::pin to avoid infinite future size.
                Box::pin(walk_dir(&sub, &path, depth + 1, max_depth, out)).await?;
            }
            _ => {
                out.push(WalkEntry {
                    path,
                    kind: entry.kind,
                    size: entry.size,
                });
            }
        }
    }
    Ok(())
}

/// Best-effort stringify of a JsValue error.
fn js_err(e: &JsValue) -> String {
    if let Some(s) = e.as_string() {
        return s;
    }
    if let Ok(name) = Reflect::get(e, &JsValue::from_str("name")) {
        if let Ok(msg) = Reflect::get(e, &JsValue::from_str("message")) {
            return format!(
                "{}: {}",
                name.as_string().unwrap_or_default(),
                msg.as_string().unwrap_or_default()
            );
        }
    }
    // Fall back to the Object.prototype.toString form.
    let obj: Object = e.clone().unchecked_into();
    obj.to_string().as_string().unwrap_or_else(|| "<js error>".into())
}