everruns-core 0.35.0

Transport-neutral agent execution contracts for Everruns
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
//! Neutral session filesystem contract and execution-scoping adapter.

use crate::error::Result;
use crate::session_file::{
    FileInfo, FileStat, GrepMatch, GrepOptions, GrepSearchResult, InitialFile, SessionFile,
};
use crate::typed_id::{SessionId, WorkspaceId};
use async_trait::async_trait;
use std::sync::Arc;

/// Trait for session filesystem operations
///
/// This trait abstracts the session filesystem contract for tools and hosts.
/// Implementations can:
/// - Store files in a database (production)
/// - Use an in-memory filesystem for testing
/// - Project files onto real disk or object storage
#[async_trait]
pub trait SessionFileSystem: Send + Sync {
    /// Human-facing root path for this filesystem.
    ///
    /// `/workspace` is the stable agent namespace and the default. Direct
    /// host-backed stores may override this for host-side integrations, while
    /// [`MountFs`](crate::mount_fs::MountFs) restores the agent-facing root.
    fn display_root(&self) -> String {
        crate::session_path::WORKSPACE_PREFIX.to_string()
    }

    /// Convert a canonical session path into a human-facing path.
    ///
    /// The default renders the `/workspace` alias. Direct host-backed stores may
    /// override it, while [`MountFs`](crate::mount_fs::MountFs) presents primary
    /// workspace paths through the stable agent-facing namespace.
    fn display_path(&self, path: &str) -> String {
        crate::session_path::to_display_path(path)
    }

    /// Resolve an input path (any accepted spelling, relative or absolute) to an
    /// absolute path within this filesystem's namespace. Relative inputs resolve
    /// against the filesystem's current directory.
    ///
    /// This is how a shell seeds its working directory: [`MountFs`] returns a
    /// path in its stable agent-facing namespace, so the shell and file tools
    /// share the same identity. The default is the flat VFS session form.
    /// Security decorators may authorize the returned path, so providers that
    /// accept additional aliases must use the same contained mapping here and
    /// in their I/O methods. An alias must never resolve to one workspace path
    /// here and a different storage object during the subsequent operation.
    ///
    /// [`MountFs`]: crate::mount_fs::MountFs
    fn resolve_path(&self, input: &str) -> String {
        crate::session_path::to_session_path(input)
    }

    /// Whether this store is already a mount-based resolver
    /// ([`MountFs`](crate::mount_fs::MountFs)).
    ///
    /// Used to avoid re-wrapping nested mount tables when building tool context.
    fn is_mount_resolver(&self) -> bool;

    /// The directory on this machine's disk that `path` names, when the store
    /// is backed by one.
    ///
    /// Deliberately not [`display_root`](Self::display_root): that is a
    /// presentation choice, and an embedder may show `/workspace` for a store
    /// that is really a host directory, or the host directory for one that is
    /// not. A capability that spawns real processes cannot work from a
    /// presentation. It needs the path the kernel will use, and it has to be
    /// able to tell that there is none rather than guess, which is what `None`
    /// says here for every virtual store.
    ///
    /// The path is not promised to exist; it is promised to be where this
    /// store's bytes live.
    fn host_path(&self, _path: &str) -> Option<std::path::PathBuf> {
        None
    }

    /// Read a file by path
    async fn read_file(&self, session_id: SessionId, path: &str) -> Result<Option<SessionFile>>;

    /// Write/create a file
    async fn write_file(
        &self,
        session_id: SessionId,
        path: &str,
        content: &str,
        encoding: &str,
    ) -> Result<SessionFile>;

    /// Write a file only if its current content snapshot still matches.
    ///
    /// Implementations backed by transactional storage should override this
    /// with an atomic compare-and-set update.
    async fn write_file_if_content_matches(
        &self,
        session_id: SessionId,
        path: &str,
        expected_content: &str,
        expected_encoding: &str,
        content: &str,
        encoding: &str,
    ) -> Result<Option<SessionFile>> {
        let Some(existing) = self.read_file(session_id, path).await? else {
            return Ok(None);
        };

        if existing.is_directory {
            return Ok(None);
        }

        let current_content = existing.content.unwrap_or_default();
        if current_content != expected_content || existing.encoding != expected_encoding {
            return Ok(None);
        }

        self.write_file(session_id, path, content, encoding)
            .await
            .map(Some)
    }

    /// Delete a file or directory
    async fn delete_file(&self, session_id: SessionId, path: &str, recursive: bool)
    -> Result<bool>;

    /// List files in a directory
    async fn list_directory(&self, session_id: SessionId, path: &str) -> Result<Vec<FileInfo>>;

    /// Get file metadata
    async fn stat_file(&self, session_id: SessionId, path: &str) -> Result<Option<FileStat>>;

    /// Search file contents with Rust regex syntax, optionally filtering canonical paths by glob.
    ///
    /// Implementations compile the content pattern once before scanning and
    /// return an error for invalid regex. Basename-only globs match at any
    /// depth. Non-glob path filters retain legacy substring matching; see
    /// `knowledge/runtime-resources/file-store.md`.
    async fn grep_files(
        &self,
        session_id: SessionId,
        pattern: &str,
        path_pattern: Option<&str>,
    ) -> Result<Vec<GrepMatch>>;

    /// Search with match pagination and bounded before/after context.
    ///
    /// Backends should override this to collect context during their content
    /// scan. The default preserves compatibility for third-party stores that
    /// only implement the original zero-context method.
    async fn grep_files_with_options(
        &self,
        session_id: SessionId,
        pattern: &str,
        options: &GrepOptions,
    ) -> Result<GrepSearchResult> {
        if options.before_context != 0 || options.after_context != 0 {
            return Err(crate::error::AgentLoopError::tool(
                "this file store does not support grep context",
            ));
        }
        let all = self
            .grep_files(session_id, pattern, options.path_pattern.as_deref())
            .await?;
        Ok(crate::session_file::bound_grep_matches(all, options))
    }

    /// Create a directory
    async fn create_directory(&self, session_id: SessionId, path: &str) -> Result<FileInfo>;

    /// Seed a starter file into a session workspace.
    async fn seed_initial_file(&self, session_id: SessionId, file: &InitialFile) -> Result<()> {
        if file.is_readonly {
            return Err(crate::error::AgentLoopError::store(
                "read-only initial files require a SessionFileSystem-specific seed implementation",
            ));
        }
        self.write_file(session_id, &file.path, &file.content, &file.encoding)
            .await?;
        Ok(())
    }
}

/// Tool-context extension: the session filesystem the runtime itself uses to
/// persist artifacts it owns (delegated-run records under `/.agent-runs`,
/// structured task results under `/.tasks`), as opposed to the model-facing
/// [`ToolContext::file_store`](crate::ToolContext::file_store).
///
/// A host that restricts the model-facing store with a workspace policy
/// installs this so runtime-written records do not depend on the model's
/// permissions. Read it through
/// [`ToolContext::runtime_artifact_file_store`](crate::ToolContext::runtime_artifact_file_store),
/// which falls back to `file_store` when no host installed one.
pub struct RuntimeArtifactFileSystem(pub Arc<dyn SessionFileSystem>);

// Kept beside the extension type so `tool_context.rs` stays under its
// focused-contract size guard.
impl crate::ToolContext {
    /// Filesystem for artifacts the runtime writes on the session's behalf,
    /// at paths the runtime chooses (`/.agent-runs/{run_id}`,
    /// `/.tasks/{task_id}`).
    ///
    /// Uses the host's [`RuntimeArtifactFileSystem`](crate::session_files::RuntimeArtifactFileSystem)
    /// when installed, re-keyed to the attached workspace and mount-resolved the
    /// same way the engine prepares `file_store` for tool execution; otherwise
    /// `file_store`. Never pass a model-chosen path to this store.
    pub fn runtime_artifact_file_store(&self) -> Option<Arc<dyn SessionFileSystem>> {
        match self
            .extensions
            .get::<crate::session_files::RuntimeArtifactFileSystem>()
        {
            Some(artifacts) => Some(crate::mount_fs::scoped_prompt_file_store(
                artifacts.0.clone(),
                self.workspace_id,
            )),
            None => self.file_store.clone(),
        }
    }
}

/// A [`SessionFileSystem`] decorator that pins every operation to a fixed
/// workspace key, ignoring the per-call `session_id`.
///
/// Used to re-key file I/O for a session attached to a shared workspace (where
/// `workspace.id != session.id`): wrap the session's file store once with the
/// session's `workspace_id`, and all downstream capability/tool access then
/// addresses the attached workspace rather than the session's own keyspace. For
/// the default 1:1 session the key equals the session id, so the wrapper is a
/// transparent pass-through. See `knowledge/runtime-resources/workspace.md`.
pub struct WorkspaceScopedFileSystem {
    inner: Arc<dyn SessionFileSystem>,
    key: SessionId,
}

impl WorkspaceScopedFileSystem {
    /// Wrap `inner`, pinning all operations to `workspace_id`'s key.
    pub fn wrap(
        inner: Arc<dyn SessionFileSystem>,
        workspace_id: WorkspaceId,
    ) -> Arc<dyn SessionFileSystem> {
        Arc::new(Self {
            inner,
            key: SessionId::from_uuid(workspace_id.uuid()),
        })
    }
}

#[async_trait]
impl SessionFileSystem for WorkspaceScopedFileSystem {
    async fn read_file(&self, _session_id: SessionId, path: &str) -> Result<Option<SessionFile>> {
        self.inner.read_file(self.key, path).await
    }
    async fn write_file(
        &self,
        _session_id: SessionId,
        path: &str,
        content: &str,
        encoding: &str,
    ) -> Result<SessionFile> {
        self.inner
            .write_file(self.key, path, content, encoding)
            .await
    }
    async fn write_file_if_content_matches(
        &self,
        _session_id: SessionId,
        path: &str,
        expected_content: &str,
        expected_encoding: &str,
        content: &str,
        encoding: &str,
    ) -> Result<Option<SessionFile>> {
        self.inner
            .write_file_if_content_matches(
                self.key,
                path,
                expected_content,
                expected_encoding,
                content,
                encoding,
            )
            .await
    }
    async fn delete_file(
        &self,
        _session_id: SessionId,
        path: &str,
        recursive: bool,
    ) -> Result<bool> {
        self.inner.delete_file(self.key, path, recursive).await
    }
    async fn list_directory(&self, _session_id: SessionId, path: &str) -> Result<Vec<FileInfo>> {
        self.inner.list_directory(self.key, path).await
    }
    async fn stat_file(&self, _session_id: SessionId, path: &str) -> Result<Option<FileStat>> {
        self.inner.stat_file(self.key, path).await
    }
    async fn grep_files(
        &self,
        _session_id: SessionId,
        pattern: &str,
        path_pattern: Option<&str>,
    ) -> Result<Vec<GrepMatch>> {
        self.inner.grep_files(self.key, pattern, path_pattern).await
    }
    async fn grep_files_with_options(
        &self,
        _session_id: SessionId,
        pattern: &str,
        options: &GrepOptions,
    ) -> Result<GrepSearchResult> {
        self.inner
            .grep_files_with_options(self.key, pattern, options)
            .await
    }
    async fn create_directory(&self, _session_id: SessionId, path: &str) -> Result<FileInfo> {
        self.inner.create_directory(self.key, path).await
    }
    async fn seed_initial_file(&self, _session_id: SessionId, file: &InitialFile) -> Result<()> {
        self.inner.seed_initial_file(self.key, file).await
    }

    fn display_root(&self) -> String {
        self.inner.display_root()
    }

    fn display_path(&self, path: &str) -> String {
        self.inner.display_path(path)
    }

    fn resolve_path(&self, input: &str) -> String {
        self.inner.resolve_path(input)
    }

    fn is_mount_resolver(&self) -> bool {
        self.inner.is_mount_resolver()
    }

    fn host_path(&self, path: &str) -> Option<std::path::PathBuf> {
        self.inner.host_path(path)
    }
}

#[async_trait]
impl<T: SessionFileSystem + ?Sized> SessionFileSystem for std::sync::Arc<T> {
    fn display_root(&self) -> String {
        (**self).display_root()
    }

    fn display_path(&self, path: &str) -> String {
        (**self).display_path(path)
    }

    fn resolve_path(&self, input: &str) -> String {
        (**self).resolve_path(input)
    }

    fn is_mount_resolver(&self) -> bool {
        (**self).is_mount_resolver()
    }

    fn host_path(&self, path: &str) -> Option<std::path::PathBuf> {
        (**self).host_path(path)
    }

    async fn read_file(&self, session_id: SessionId, path: &str) -> Result<Option<SessionFile>> {
        (**self).read_file(session_id, path).await
    }

    async fn write_file(
        &self,
        session_id: SessionId,
        path: &str,
        content: &str,
        encoding: &str,
    ) -> Result<SessionFile> {
        (**self)
            .write_file(session_id, path, content, encoding)
            .await
    }

    async fn write_file_if_content_matches(
        &self,
        session_id: SessionId,
        path: &str,
        expected_content: &str,
        expected_encoding: &str,
        content: &str,
        encoding: &str,
    ) -> Result<Option<SessionFile>> {
        (**self)
            .write_file_if_content_matches(
                session_id,
                path,
                expected_content,
                expected_encoding,
                content,
                encoding,
            )
            .await
    }

    async fn delete_file(
        &self,
        session_id: SessionId,
        path: &str,
        recursive: bool,
    ) -> Result<bool> {
        (**self).delete_file(session_id, path, recursive).await
    }

    async fn list_directory(&self, session_id: SessionId, path: &str) -> Result<Vec<FileInfo>> {
        (**self).list_directory(session_id, path).await
    }

    async fn stat_file(&self, session_id: SessionId, path: &str) -> Result<Option<FileStat>> {
        (**self).stat_file(session_id, path).await
    }

    async fn grep_files(
        &self,
        session_id: SessionId,
        pattern: &str,
        path_pattern: Option<&str>,
    ) -> Result<Vec<GrepMatch>> {
        (**self).grep_files(session_id, pattern, path_pattern).await
    }

    async fn grep_files_with_options(
        &self,
        session_id: SessionId,
        pattern: &str,
        options: &GrepOptions,
    ) -> Result<GrepSearchResult> {
        (**self)
            .grep_files_with_options(session_id, pattern, options)
            .await
    }

    async fn create_directory(&self, session_id: SessionId, path: &str) -> Result<FileInfo> {
        (**self).create_directory(session_id, path).await
    }

    async fn seed_initial_file(&self, session_id: SessionId, file: &InitialFile) -> Result<()> {
        (**self).seed_initial_file(session_id, file).await
    }
}