everruns-core 0.17.7

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};

use crate::error::{AgentLoopError, Result};
use crate::mount_fs::WORKSPACE_MOUNT;

pub const PRIMARY_WORKSPACE_ROOT_NAME: &str = "workspace";
pub const ADDITIONAL_ROOTS_MOUNT: &str = "/workspace/roots";

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceRoot {
    pub name: String,
    pub path: PathBuf,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceRootSet {
    pub primary: WorkspaceRoot,
    pub additional: Vec<WorkspaceRoot>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedPath {
    pub root_name: String,
    pub relative: RelPath,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct RelPath(String);

impl RelPath {
    pub fn as_relative(&self) -> &str {
        &self.0
    }

    pub fn to_session_path(&self) -> String {
        if self.0.is_empty() {
            "/".to_string()
        } else {
            format!("/{}", self.0)
        }
    }

    fn from_path(relative: &Path) -> Result<Self> {
        let mut segments = Vec::new();
        for component in relative.components() {
            match component {
                Component::CurDir => {}
                Component::Normal(segment) => {
                    let segment = segment.to_str().ok_or_else(|| {
                        AgentLoopError::tool(format!(
                            "non-UTF-8 path component: {}",
                            relative.display()
                        ))
                    })?;
                    segments.push(segment.to_string());
                }
                Component::ParentDir => {
                    return Err(AgentLoopError::tool(format!(
                        "path traversal rejected: {}",
                        relative.display()
                    )));
                }
                Component::RootDir | Component::Prefix(_) => {
                    return Err(AgentLoopError::tool(format!(
                        "absolute path component rejected: {}",
                        relative.display()
                    )));
                }
            }
        }
        Ok(Self(segments.join("/")))
    }

    fn from_str(input: &str) -> Result<Self> {
        let mut segments = Vec::new();
        for part in input.split('/') {
            match part {
                "" | "." => {}
                ".." => {
                    return Err(AgentLoopError::tool(format!(
                        "path traversal rejected: {input}"
                    )));
                }
                segment => segments.push(segment.to_string()),
            }
        }
        Ok(Self(segments.join("/")))
    }
}

impl WorkspaceRootSet {
    pub fn from_primary(path: impl Into<PathBuf>) -> Result<Self> {
        Self::new(path, Vec::<(String, PathBuf)>::new())
    }

    pub fn new<I, P>(primary: impl Into<PathBuf>, additional: I) -> Result<Self>
    where
        I: IntoIterator<Item = (String, P)>,
        P: Into<PathBuf>,
    {
        let primary = WorkspaceRoot {
            name: PRIMARY_WORKSPACE_ROOT_NAME.to_string(),
            path: canonicalize_root(primary.into())?,
        };
        let mut additional_roots = Vec::new();
        let mut names = HashSet::new();
        for (name, path) in additional {
            validate_additional_name(&name)?;
            if !names.insert(name.clone()) {
                return Err(AgentLoopError::config(format!(
                    "duplicate workspace root name: {name}"
                )));
            }
            additional_roots.push(WorkspaceRoot {
                name,
                path: canonicalize_root(path.into())?,
            });
        }

        let root_set = Self {
            primary,
            additional: additional_roots,
        };
        root_set.reject_overlaps()?;
        Ok(root_set)
    }

    pub fn parse_vfs_path(&self, input: &str) -> Result<ResolvedPath> {
        let trimmed = input.trim();
        let candidate = Path::new(trimmed);
        if candidate.is_absolute() && !trimmed.starts_with("/workspace") {
            if let Some((root, relative)) = self.resolve_host_path(candidate)? {
                return Ok(ResolvedPath {
                    root_name: root.name.clone(),
                    relative,
                });
            }
            return Err(AgentLoopError::tool(format!(
                "host path is outside registered workspace roots: {trimmed}"
            )));
        }

        let session = if trimmed == WORKSPACE_MOUNT || trimmed == "workspace" {
            "/".to_string()
        } else if let Some(rest) = trimmed.strip_prefix("/workspace/") {
            format!("/{rest}")
        } else if trimmed.starts_with('/') {
            trimmed.to_string()
        } else {
            format!("/{trimmed}")
        };

        if session == "/" || !session.starts_with("/roots/") {
            return Ok(ResolvedPath {
                root_name: self.primary.name.clone(),
                relative: RelPath::from_str(&session)?,
            });
        }

        let rest = session.strip_prefix("/roots/").unwrap_or_default();
        let (name, relative) = rest.split_once('/').unwrap_or((rest, ""));
        let root = self
            .additional
            .iter()
            .find(|root| root.name == name)
            .ok_or_else(|| AgentLoopError::tool(format!("unknown workspace root: {name}")))?;
        Ok(ResolvedPath {
            root_name: root.name.clone(),
            relative: RelPath::from_str(relative)?,
        })
    }

    pub fn parse_host_scope(&self, root: &str, relative: Option<&str>) -> Result<PathBuf> {
        let workspace_root = self.root_by_name(root)?;
        let rel = RelPath::from_str(relative.unwrap_or(""))?;
        let joined = if rel.as_relative().is_empty() {
            workspace_root.path.clone()
        } else {
            workspace_root.path.join(rel.as_relative())
        };
        if !joined.starts_with(&workspace_root.path) {
            return Err(AgentLoopError::tool(format!(
                "path escapes workspace root: {}",
                joined.display()
            )));
        }
        Ok(joined)
    }

    pub fn primary_host_root(&self) -> &Path {
        &self.primary.path
    }

    pub fn set_primary_host_root(&mut self, path: PathBuf) -> Result<()> {
        self.primary.path = canonicalize_root(path)?;
        self.reject_overlaps()
    }

    pub fn spawn_cwd(&self) -> Result<PathBuf> {
        canonicalize_root(self.primary.path.clone())
    }

    pub fn contains_host_path(&self, path: &Path) -> bool {
        let Ok(canonical) = canonicalize_existing_or_parent(path) else {
            return false;
        };
        self.all_roots()
            .any(|root| canonical == root.path || canonical.starts_with(&root.path))
    }

    pub fn additional_mount_point(root_name: &str) -> String {
        format!("{ADDITIONAL_ROOTS_MOUNT}/{root_name}")
    }

    fn all_roots(&self) -> impl Iterator<Item = &WorkspaceRoot> {
        std::iter::once(&self.primary).chain(self.additional.iter())
    }

    fn root_by_name(&self, name: &str) -> Result<&WorkspaceRoot> {
        if name == self.primary.name {
            return Ok(&self.primary);
        }
        self.additional
            .iter()
            .find(|root| root.name == name)
            .ok_or_else(|| AgentLoopError::tool(format!("unknown workspace root: {name}")))
    }

    fn resolve_host_path(&self, path: &Path) -> Result<Option<(&WorkspaceRoot, RelPath)>> {
        let canonical = canonicalize_existing_or_parent(path)?;
        for root in self.all_roots() {
            if let Ok(relative) = canonical.strip_prefix(&root.path) {
                return Ok(Some((root, RelPath::from_path(relative)?)));
            }
        }
        Ok(None)
    }

    fn reject_overlaps(&self) -> Result<()> {
        let roots: Vec<&WorkspaceRoot> = self.all_roots().collect();
        for (idx, left) in roots.iter().enumerate() {
            for right in roots.iter().skip(idx + 1) {
                if left.path == right.path
                    || left.path.starts_with(&right.path)
                    || right.path.starts_with(&left.path)
                {
                    return Err(AgentLoopError::config(format!(
                        "workspace roots must not overlap: {} ({}) and {} ({})",
                        left.name,
                        left.path.display(),
                        right.name,
                        right.path.display()
                    )));
                }
            }
        }
        Ok(())
    }
}

fn validate_additional_name(name: &str) -> Result<()> {
    if name.is_empty()
        || name == "."
        || name == ".."
        || name == PRIMARY_WORKSPACE_ROOT_NAME
        || name == "roots"
        || name.contains('/')
        || name.contains('\\')
    {
        return Err(AgentLoopError::config(format!(
            "invalid workspace root name: {name}"
        )));
    }
    Ok(())
}

fn canonicalize_root(root: PathBuf) -> Result<PathBuf> {
    let canonical = std::fs::canonicalize(&root).map_err(|e| {
        AgentLoopError::config(format!(
            "failed to canonicalize workspace root {}: {e}",
            root.display()
        ))
    })?;
    if !canonical.is_dir() {
        return Err(AgentLoopError::config(format!(
            "workspace root is not a directory: {}",
            canonical.display()
        )));
    }
    Ok(canonical)
}

fn canonicalize_existing_or_parent(path: &Path) -> Result<PathBuf> {
    match std::fs::canonicalize(path) {
        Ok(path) => Ok(path),
        Err(_) => {
            let parent = path.parent().ok_or_else(|| {
                AgentLoopError::tool(format!("path has no parent: {}", path.display()))
            })?;
            let canonical_parent = std::fs::canonicalize(parent).map_err(|e| {
                AgentLoopError::tool(format!(
                    "failed to canonicalize parent {}: {e}",
                    parent.display()
                ))
            })?;
            let name = path.file_name().ok_or_else(|| {
                AgentLoopError::tool(format!("path has no file name: {}", path.display()))
            })?;
            Ok(canonical_parent.join(name))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn roots() -> (WorkspaceRootSet, TempDir, TempDir) {
        let primary = TempDir::new().unwrap();
        let backend = TempDir::new().unwrap();
        let set = WorkspaceRootSet::new(
            primary.path(),
            [("backend".to_string(), backend.path().to_path_buf())],
        )
        .unwrap();
        (set, primary, backend)
    }

    #[test]
    fn canonicalizes_and_rejects_overlapping_roots() {
        let primary = TempDir::new().unwrap();
        let nested = primary.path().join("nested");
        std::fs::create_dir(&nested).unwrap();

        let err =
            WorkspaceRootSet::new(primary.path(), [("nested".to_string(), nested)]).unwrap_err();
        assert!(err.to_string().contains("must not overlap"));
    }

    #[test]
    fn rejects_duplicate_names() {
        let primary = TempDir::new().unwrap();
        let a = TempDir::new().unwrap();
        let b = TempDir::new().unwrap();

        let err = WorkspaceRootSet::new(
            primary.path(),
            [
                ("backend".to_string(), a.path().to_path_buf()),
                ("backend".to_string(), b.path().to_path_buf()),
            ],
        )
        .unwrap_err();
        assert!(err.to_string().contains("duplicate workspace root name"));
    }

    #[test]
    fn parses_primary_aliases_and_rejects_traversal() {
        let (set, _primary, _backend) = roots();

        assert_eq!(
            set.parse_vfs_path("/workspace/src/lib.rs").unwrap(),
            ResolvedPath {
                root_name: "workspace".to_string(),
                relative: RelPath("src/lib.rs".to_string())
            }
        );
        assert_eq!(
            set.parse_vfs_path("workspace").unwrap().relative,
            RelPath::default()
        );
        assert!(set.parse_vfs_path("../outside").is_err());
    }

    #[test]
    fn parses_additional_root_mounts_only() {
        let (set, _primary, _backend) = roots();

        assert_eq!(
            set.parse_vfs_path("/workspace/roots/backend/src/lib.rs")
                .unwrap(),
            ResolvedPath {
                root_name: "backend".to_string(),
                relative: RelPath("src/lib.rs".to_string())
            }
        );
        assert!(set.parse_vfs_path("/workspace/roots/missing/file").is_err());
    }

    #[test]
    fn repoints_primary_without_touching_additional() {
        let (mut set, _primary, backend) = roots();
        let next = TempDir::new().unwrap();
        set.set_primary_host_root(next.path().to_path_buf())
            .unwrap();

        assert_eq!(
            set.spawn_cwd().unwrap(),
            std::fs::canonicalize(next.path()).unwrap()
        );
        assert_eq!(
            set.parse_host_scope("backend", Some("Cargo.toml")).unwrap(),
            std::fs::canonicalize(backend.path())
                .unwrap()
                .join("Cargo.toml")
        );
    }
}