Skip to main content

agentmux_srv_core/backend/
skill_file.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A computer-use skill as one file (docs/specs/SPEC_PACKS_2026_11_05.md §5 and §10.5): a zip with the
5//! extension `.skill` that holds the skill's folder, named `<publisher>-<id>`, and nothing else. Exporting
6//! writes the folder the catalog holds; importing unpacks it into a scratch folder and reads it like any
7//! other folder (`computer_use_skill::read_folder`), so every check a folder gets, a `.skill` gets.
8//!
9//! The reader trusts nothing in the zip: names are checked before anything is written, and the sizes are
10//! counted as they are read, not taken from the headers. Scripts always arrive unapproved, so a `.skill`
11//! installs, never approves.
12
13use std::collections::{BTreeMap, BTreeSet};
14use std::io::{Read, Write};
15use std::path::{Component, Path};
16
17use crate::backend::computer_use_skill::{content_hash, MANIFEST, SIG_FILE, VERIFIED_FILE};
18use crate::backend::skill_import::parse_skill_md;
19use crate::backend::storage::skill_app::SkillApp;
20use crate::backend::storage::store::Store;
21use crate::backend::storage::Skill;
22
23/// The extension of the file.
24pub const EXTENSION: &str = "skill";
25
26const MAX_ENTRIES: usize = 220;
27const MAX_FILE_BYTES: u64 = 1024 * 1024;
28const MAX_TOTAL_BYTES: u64 = 5 * 1024 * 1024;
29/// The zip itself: the files compress, so this is a little over the uncompressed total.
30pub(crate) const MAX_ZIP_BYTES: u64 = 6 * 1024 * 1024;
31
32/// An exported skill, ready to write.
33pub struct Exported {
34    /// `<publisher>-<id>-<version>.skill`.
35    pub filename: String,
36    pub bytes: Vec<u8>,
37    /// Whether the file carries the publisher's signature. It does only while the skill is exactly what was signed.
38    pub signed: bool,
39}
40
41/// `SKILL.md` for a skill whose installed text is no longer what it came with (the person edited it in Memory),
42/// or that was installed before the original was kept. The description is written as a JSON string, which is a
43/// valid double-quoted value in the frontmatter whatever it holds.
44fn rebuilt_skill_md(folder: &str, skill: &Skill) -> String {
45    let description = serde_json::to_string(&skill.description).unwrap_or_else(|_| "\"\"".to_string());
46    format!("---\nname: {folder}\ndescription: {description}\n---\n\n{}", skill.content)
47}
48
49/// Whether the `SKILL.md` kept from the install still says what the catalog skill says now.
50pub(crate) fn original_still_applies(folder: &str, original: &str, skill: &Skill) -> bool {
51    let (name, description, content) = parse_skill_md(original, folder);
52    name == folder && description == skill.description && content == skill.content
53}
54
55fn verified_json(app: &SkillApp) -> Result<Option<Vec<u8>>, String> {
56    if app.verified.is_empty() {
57        return Ok(None);
58    }
59    serde_json::to_vec_pretty(&app.verified).map(Some).map_err(|e| format!("{VERIFIED_FILE}: {e}"))
60}
61
62/// The catalog skill `skill_id` as a `.skill` file.
63pub fn export(catalog: &Store, skill_id: &str) -> Result<Exported, String> {
64    let skill = catalog.skill_get(skill_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no skill {skill_id}"))?;
65    let app = catalog.skill_app_get(skill_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("{} is not a computer-use skill", skill.name))?;
66    let manifest = catalog.skill_manifest_get(skill_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("{} has no manifest", skill.name))?;
67    let origin = catalog.skill_origin_get(skill_id).map_err(|e| e.to_string())?;
68    let folder = format!("{}-{}", app.info.publisher, app.info.id);
69
70    let mut files: BTreeMap<String, Vec<u8>> = BTreeMap::new();
71    for f in catalog.skill_files(skill_id).map_err(|e| e.to_string())? {
72        files.insert(f.path, f.image.unwrap_or_else(|| f.content.into_bytes()));
73    }
74    files.insert(MANIFEST.to_string(), manifest.into_bytes());
75    let skill_md = match &origin {
76        Some((md, _)) if original_still_applies(&folder, md, &skill) => md.clone(),
77        _ => rebuilt_skill_md(&folder, &skill),
78    };
79    files.insert("SKILL.md".to_string(), skill_md.into_bytes());
80
81    // The publisher's signature goes along only when what is being written hashes to what was signed.
82    let signature = origin.and_then(|(_, sig)| sig).filter(|_| content_hash(&files) == app.content_hash);
83    let signed = signature.is_some();
84    if let Some(sig) = signature {
85        files.insert(SIG_FILE.to_string(), sig.into_bytes());
86    }
87    if let Some(v) = verified_json(&app)? {
88        files.insert(VERIFIED_FILE.to_string(), v);
89    }
90
91    let total: u64 = files.values().map(|b| b.len() as u64).sum();
92    if total > MAX_TOTAL_BYTES {
93        return Err(format!("{} is over {} MB: too large to share as one file", skill.name, MAX_TOTAL_BYTES / 1024 / 1024));
94    }
95    Ok(Exported { filename: file_name(&folder, &app.info.version), bytes: zip_folder(&folder, &files)?, signed })
96}
97
98/// `<folder>-<version>.skill`, with the version cut down to the characters a version has: it comes from a manifest, and a
99/// file name is no place for whatever else it might hold.
100fn file_name(folder: &str, version: &str) -> String {
101    let mut version: String = version.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+')).collect();
102    while version.contains("..") {
103        version = version.replace("..", ".");
104    }
105    format!("{folder}-{version}.{EXTENSION}")
106}
107
108fn zip_folder(folder: &str, files: &BTreeMap<String, Vec<u8>>) -> Result<Vec<u8>, String> {
109    let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
110    let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
111    for (path, bytes) in files {
112        zip.start_file(format!("{folder}/{path}"), options).map_err(|e| format!("{path}: {e}"))?;
113        zip.write_all(bytes).map_err(|e| format!("{path}: {e}"))?;
114    }
115    Ok(zip.finish().map_err(|e| e.to_string())?.into_inner())
116}
117
118/// Unpack the `.skill` at `zip_path` into `dest`, which is left holding one folder. Every entry is checked and
119/// read before anything is written, so a file that fails a check leaves `dest` as it was.
120pub fn extract(zip_path: &Path, dest: &Path) -> Result<(), String> {
121    let size = std::fs::metadata(zip_path).map_err(|e| format!("{}: {e}", zip_path.display()))?.len();
122    if size > MAX_ZIP_BYTES {
123        return Err(format!("{} is over {} MB: not a skill file this build reads", zip_path.display(), MAX_ZIP_BYTES / 1024 / 1024));
124    }
125    let file = std::fs::File::open(zip_path).map_err(|e| format!("{}: {e}", zip_path.display()))?;
126    let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("not a .{EXTENSION} file (a zip of one skill folder): {e}"))?;
127    if zip.len() > MAX_ENTRIES {
128        return Err(format!("the file holds {} entries; a skill has at most {MAX_ENTRIES}", zip.len()));
129    }
130    let mut top: Option<String> = None;
131    let mut staged: Vec<(String, Vec<u8>)> = Vec::new();
132    let mut seen = BTreeSet::new();
133    let mut total = 0u64;
134    for i in 0..zip.len() {
135        let mut entry = zip.by_index(i).map_err(|e| e.to_string())?;
136        if entry.unix_mode().is_some_and(|m| m & 0o170000 == 0o120000) {
137            return Err(format!("{} is a symbolic link", entry.name()));
138        }
139        let rel = entry.enclosed_name().ok_or_else(|| format!("{} is not a path inside the folder", entry.name()))?;
140        let mut parts = Vec::new();
141        for c in rel.components() {
142            match c {
143                Component::Normal(p) => parts.push(p.to_string_lossy().to_string()),
144                _ => return Err(format!("{} is not a path inside the folder", entry.name())),
145            }
146        }
147        let Some(first) = parts.first().cloned() else { continue };
148        match &top {
149            None => top = Some(first.clone()),
150            Some(t) if *t != first => return Err("a .skill file holds one folder; this one holds more".to_string()),
151            Some(_) => {}
152        }
153        if entry.is_dir() {
154            continue;
155        }
156        if parts.len() < 2 {
157            return Err(format!("{} sits outside the skill's folder", entry.name()));
158        }
159        if !seen.insert(parts.join("/").to_lowercase()) {
160            return Err(format!("{} appears twice (or differs from another entry only by letter case)", entry.name()));
161        }
162        // Counted as read: a header's size is the sender's word.
163        let mut bytes = Vec::new();
164        entry.by_ref().take(MAX_FILE_BYTES + 1).read_to_end(&mut bytes).map_err(|e| format!("{}: {e}", entry.name()))?;
165        if bytes.len() as u64 > MAX_FILE_BYTES {
166            return Err(format!("{} is over {} MB", entry.name(), MAX_FILE_BYTES / 1024 / 1024));
167        }
168        total += bytes.len() as u64;
169        if total > MAX_TOTAL_BYTES {
170            return Err(format!("the files add up to over {} MB", MAX_TOTAL_BYTES / 1024 / 1024));
171        }
172        staged.push((parts.join("/"), bytes));
173    }
174    if top.is_none() {
175        return Err("the file is empty".to_string());
176    }
177    for (path, bytes) in staged {
178        let target = dest.join(&path);
179        if let Some(parent) = target.parent() {
180            std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
181        }
182        std::fs::write(&target, bytes).map_err(|e| format!("{}: {e}", target.display()))?;
183    }
184    Ok(())
185}
186
187#[cfg(test)]
188#[path = "skill_file_tests.rs"]
189mod tests;