agentmux_srv_core/backend/
skill_file.rs1use 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
23pub 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;
29pub(crate) const MAX_ZIP_BYTES: u64 = 6 * 1024 * 1024;
31
32pub struct Exported {
34 pub filename: String,
36 pub bytes: Vec<u8>,
37 pub signed: bool,
39}
40
41fn 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
49pub(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
62pub 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 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
98fn 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
118pub 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 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;