everruns-core 0.41.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
use super::{
    AgentPackage, File, FileSource, Format, MAX_FILE_BYTES, MAX_FILES, MAX_PACKAGE_BYTES, Result,
    error,
};
use crate::{InitialFile, session_file::SessionFile};
use globset::Glob;
use std::{
    collections::BTreeMap,
    io::{Cursor, Read, Write},
    path::{Component, Path},
};

/// Dot-prefixed path components allowed by default in initial-files collection.
/// Covers the common dev-ecosystem assets shipped alongside agent packages.
/// Anything not in this list (and not in the user-declared
/// `initial_files_allow_hidden` opt-in) is skipped to prevent accidental upload
/// of secrets (`.env`, `.ssh/`, `.npmrc`, etc.).
pub const ALLOWED_DOT_ENTRIES: &[&str] = &[
    ".agents",
    ".github",
    ".vscode",
    ".claude",
    ".cursor",
    ".mcp.json",
    ".gitignore",
    ".gitattributes",
    ".editorconfig",
    ".prettierrc",
    ".prettierrc.json",
    ".prettierrc.yaml",
    ".prettierrc.yml",
    ".prettierrc.js",
    ".prettierrc.cjs",
    ".prettierrc.mjs",
    ".eslintrc",
    ".eslintrc.json",
    ".eslintrc.yaml",
    ".eslintrc.yml",
    ".eslintrc.js",
    ".eslintrc.cjs",
    ".eslintignore",
    ".nvmrc",
    ".node-version",
    ".python-version",
    ".tool-versions",
    ".dockerignore",
    ".rubocop.yml",
];

/// Hard-deny floor for hidden path components. Even if a user opts in via the
/// `initial_files_allow_hidden` manifest field, anything matching one of these
/// entries (exactly, by basename) is rejected. Protects against accidental
/// exfiltration of credentials, SSH/GPG keys, and shell history.
///
/// Keep this list strict and well-known. Adding speculative entries here is
/// safer than adding them to `ALLOWED_DOT_ENTRIES`.
pub const DENIED_DOT_ENTRIES: &[&str] = &[
    ".env",
    ".env.local",
    ".env.development",
    ".env.production",
    ".env.test",
    ".envrc",
    ".ssh",
    ".gnupg",
    ".aws",
    ".azure",
    ".gcloud",
    ".kube",
    ".docker",
    ".npmrc",
    ".yarnrc",
    ".pypirc",
    ".netrc",
    ".cargo",
    ".git",
    ".hg",
    ".svn",
    ".bash_history",
    ".zsh_history",
    ".python_history",
    ".node_repl_history",
];

pub(crate) fn safe_source(path: &str) -> bool {
    !path.is_empty()
        && !path.contains('\\')
        && !path.contains('\0')
        && !path.starts_with('/')
        && !path.contains(':')
        && !path.split('/').any(|part| part == "..")
}

pub(crate) fn workspace_path(path: &str) -> Result<String> {
    let path = path
        .strip_prefix("/workspace/")
        .unwrap_or(path)
        .trim_start_matches('/');
    if !safe_source(path) || path.split('/').any(|part| part.is_empty() || part == ".") {
        return Err(error("path", "invalid workspace destination"));
    }
    Ok(format!("/{path}"))
}

pub(super) fn asset_path(path: &str) -> Result<String> {
    if !safe_source(path) || path.split('/').any(|s| s.is_empty() || s == ".") {
        return Err(error("source", "expected a relative package path"));
    }
    Ok(path.into())
}

pub(crate) fn allowed(path: &Path) -> bool {
    path.components().all(|component| {
        let Component::Normal(name) = component else {
            return false;
        };
        let name = name.to_string_lossy();
        !DENIED_DOT_ENTRIES.contains(&name.as_ref())
            && (!name.starts_with('.') || ALLOWED_DOT_ENTRIES.contains(&name.as_ref()))
    })
}

impl AgentPackage {
    pub(super) fn resolve_assets(
        &mut self,
        entries: BTreeMap<String, Vec<u8>>,
        defaults: bool,
    ) -> Result<()> {
        let m = &mut self.manifest;
        if m.instructions.is_empty() {
            let source = m.instructions_file.as_deref().unwrap_or("instructions.md");
            m.instructions = String::from_utf8(
                entries
                    .get(source)
                    .ok_or_else(|| error("instructions_file", format!("missing {source}")))?
                    .clone(),
            )
            .map_err(|e| error("instructions_file", e))?;
        }
        m.instructions_file = None;
        let mut declared = std::mem::take(&mut m.initial_files);
        if declared.is_empty() && defaults && entries.keys().any(|s| s.starts_with("files/")) {
            declared.push(File::Source(FileSource {
                source: "files".into(),
                path: Some("/".into()),
                is_readonly: true,
            }));
        }
        let mut resolved = Vec::new();
        for file in declared {
            let (source, destination, readonly) = match file {
                File::Inline(file) => {
                    resolved.push(File::Inline(file));
                    continue;
                }
                File::Pattern(pattern) => (pattern, None, true),
                File::Source(source) => (source.source, source.path, source.is_readonly),
            };
            let matcher = Glob::new(&source)
                .map_err(|e| error("source", e))?
                .compile_matcher();
            let mut count = 0;
            for (path, bytes) in &entries {
                let directory = path.strip_prefix(&format!("{source}/"));
                if source != "."
                    && path != &source
                    && directory.is_none()
                    && !matcher.is_match(path)
                {
                    continue;
                }
                if !allowed(Path::new(path)) {
                    continue;
                }
                count += 1;
                let target = match &destination {
                    Some(target) if directory.is_some() => format!(
                        "{}/{}",
                        target.trim_end_matches('/'),
                        directory.unwrap_or_default()
                    ),
                    Some(target) => target.clone(),
                    None => format!("/{path}"),
                };
                let (content, encoding) = SessionFile::encode_content(bytes);
                resolved.push(File::Inline(InitialFile {
                    path: workspace_path(&target)?,
                    content,
                    encoding,
                    is_readonly: readonly,
                }));
            }
            if count == 0 {
                return Err(error(
                    "initial_files",
                    format!("source matched no files: {source}"),
                ));
            }
        }
        let explicit_skills = resolved
            .iter()
            .any(|file| matches!(file, File::Inline(f) if f.path.starts_with("/.agents/skills/")));
        let skills = if m.skills.is_empty() && defaults && !explicit_skills {
            vec!["skills".to_string()]
        } else {
            std::mem::take(&mut m.skills)
        };
        let mut has_skills = false;
        for source in skills {
            let mut source_has_skills = false;
            if !safe_source(&source) {
                return Err(error("skills", "must be relative to the package"));
            }
            let prefix = format!("{}/", source.trim_end_matches('/'));
            let mut skill_dirs = std::collections::BTreeSet::new();
            for path in entries.keys().filter_map(|path| path.strip_prefix(&prefix)) {
                if let Some(dir) = path.strip_suffix("/SKILL.md") {
                    if dir.contains('/') {
                        return Err(error("skills", "each skill must be a direct subfolder"));
                    }
                    skill_dirs.insert(dir.to_string());
                }
            }
            for path in entries.keys().filter_map(|path| path.strip_prefix(&prefix)) {
                if let Some((dir, _)) = path.split_once('/')
                    && !skill_dirs.contains(dir)
                {
                    return Err(error("skills", format!("{source}/{dir} requires SKILL.md")));
                }
            }
            for dir in skill_dirs {
                let prompt_path = format!("{prefix}{dir}/SKILL.md");
                let prompt =
                    std::str::from_utf8(&entries[&prompt_path]).map_err(|e| error("skills", e))?;
                let parsed = crate::skill::parse_skill_md(prompt)
                    .map_err(|e| error("skills", format!("invalid SKILL.md: {e:?}")))?;
                if parsed.name != dir {
                    return Err(error("skills", "SKILL.md name must match its directory"));
                }
                for (path, bytes) in &entries {
                    if !allowed(Path::new(path)) {
                        continue;
                    }
                    if let Some(relative) = path.strip_prefix(&format!("{prefix}{dir}/")) {
                        let (content, encoding) = SessionFile::encode_content(bytes);
                        resolved.push(File::Inline(InitialFile {
                            path: format!("/.agents/skills/{dir}/{relative}"),
                            content,
                            encoding,
                            is_readonly: true,
                        }));
                    }
                }
                has_skills = true;
                source_has_skills = true;
            }
            if !source_has_skills
                && (source != "skills" || entries.keys().any(|p| p.starts_with(&prefix)))
            {
                return Err(error("skills", format!("no skills found in {source}")));
            }
        }
        m.skills.clear();
        if has_skills && !m.capabilities.iter().any(|c| c.capability_id() == "skills") {
            m.capabilities
                .push(everruns_contracts::capability::CapabilityRef::new("skills"));
        }
        m.initial_files = resolved;
        super::defaults(m);
        self.validate()
    }

    // THREAT[TM-FS-020, TM-DOS-001]: validate archive paths and bound actual
    // decompressed bytes before interpreting any portable agent definition.
    pub fn from_zip(bytes: &[u8]) -> Result<Self> {
        if bytes.len() > MAX_PACKAGE_BYTES {
            return Err(error("zip", "archive exceeds 10 MiB"));
        }
        let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| error("zip", e))?;
        if archive.len() > MAX_FILES + 20 {
            return Err(error("zip", "too many archive entries"));
        }
        let mut entries = BTreeMap::new();
        let mut total = 0;
        for i in 0..archive.len() {
            let mut file = archive.by_index(i).map_err(|e| error("zip", e))?;
            if file.is_dir() {
                continue;
            }
            let path = asset_path(file.name())?;
            if file
                .unix_mode()
                .is_some_and(|mode| mode & 0o170000 == 0o120000)
            {
                return Err(error("zip", "symlinks are not allowed"));
            }
            let limit = if path.starts_with("agent.") {
                MAX_PACKAGE_BYTES
            } else {
                MAX_FILE_BYTES
            };
            let mut content = Vec::new();
            (&mut file)
                .take((limit + 1) as u64)
                .read_to_end(&mut content)
                .map_err(|e| error("zip", e))?;
            total += content.len();
            if content.len() > limit || total > MAX_PACKAGE_BYTES {
                return Err(error("zip", "expanded archive exceeds limits"));
            }
            if entries.insert(path, content).is_some() {
                return Err(error("zip", "duplicate archive path"));
            }
        }
        Self::from_entries(entries)
    }

    /// Materialize a bounded package from a host-provided virtual directory.
    /// Entries are relative names and bytes, never worker-host filesystem paths.
    pub fn from_entries(entries: BTreeMap<String, Vec<u8>>) -> Result<Self> {
        if entries.len() > MAX_FILES + 20
            || entries.values().map(Vec::len).sum::<usize>() > MAX_PACKAGE_BYTES
        {
            return Err(error("assets", "package exceeds limits"));
        }
        for (path, bytes) in &entries {
            asset_path(path)?;
            let limit = if path.starts_with("agent.") {
                MAX_PACKAGE_BYTES
            } else {
                MAX_FILE_BYTES
            };
            if bytes.len() > limit {
                return Err(error(path, "file exceeds size limit"));
            }
        }
        let names = [
            "agent.toml",
            "agent.md",
            "agent.yaml",
            "agent.yml",
            "agent.json",
        ];
        let manifests: Vec<_> = entries
            .keys()
            .filter(|path| names.contains(&path.as_str()))
            .cloned()
            .collect();
        if manifests.len() != 1 {
            return Err(error(
                "zip",
                "archive root must contain exactly one agent manifest",
            ));
        }
        let manifest = &manifests[0];
        let text = std::str::from_utf8(&entries[manifest]).map_err(|e| error("manifest", e))?;
        let mut package = Self::parse(text, Format::from_extension(Path::new(manifest)))?;
        package.resolve_assets(entries, true)?;
        package.files()?;
        Ok(package)
    }

    pub fn folder_entries(&self) -> Result<BTreeMap<String, Vec<u8>>> {
        let files = self.files()?;
        let mut manifest = self.manifest.clone();
        let instructions = std::mem::take(&mut manifest.instructions);
        manifest.instructions_file = Some("instructions.md".into());
        manifest.initial_files.clear();
        // Every file has an explicit mapping. This also preserves writable
        // skill files authored directly as initial_files, without rediscovery.
        let mut entries = BTreeMap::new();
        entries.insert("instructions.md".into(), instructions.into_bytes());
        for file in files {
            let source = if let Some(path) = file.path.strip_prefix("/.agents/skills/") {
                format!("skills/{path}")
            } else {
                format!("files/{}", file.path.trim_start_matches('/'))
            };
            let source = asset_path(&source)?;
            // Explicit inline bytes may target hidden paths. Keep them inline
            // rather than exporting a source that host-file collection rejects.
            if !allowed(Path::new(&source)) {
                manifest.initial_files.push(File::Inline(file));
                continue;
            }
            entries.insert(
                source.clone(),
                SessionFile::decode_content(&file.content, &file.encoding)
                    .map_err(|e| error("content", e))?,
            );
            manifest.initial_files.push(File::Source(FileSource {
                source,
                path: Some(file.path),
                is_readonly: file.is_readonly,
            }));
        }
        // Explicit files already contain the complete skill trees.
        manifest.skills.clear();
        let text = toml::to_string_pretty(&manifest).map_err(|e| error("toml", e))?;
        entries.insert("agent.toml".into(), text.into_bytes());
        Ok(entries)
    }

    pub fn to_zip(&self) -> Result<Vec<u8>> {
        let entries = self.folder_entries()?;
        let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
        for (path, bytes) in entries {
            writer
                .start_file(
                    path,
                    zip::write::SimpleFileOptions::default()
                        .compression_method(zip::CompressionMethod::Deflated),
                )
                .map_err(|e| error("zip", e))?;
            writer.write_all(&bytes).map_err(|e| error("zip", e))?;
        }
        Ok(writer.finish().map_err(|e| error("zip", e))?.into_inner())
    }
}