Skip to main content

agentmux_srv_core/backend/
computer_use_skill.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Reading a computer-use skill folder (docs/specs/SPEC_PACKS_2026_11_05.md §3): `SKILL.md`, the
5//! manifest `computer-use.json`, and the text files beside them. It only reads and checks; the caller
6//! shows the person what was found and writes only what they approve.
7//!
8//! The checks are the public catalog's (the agentmuxai/skills repo, in its lib module), so a folder that passes
9//! there reads here: the folder name is `<publisher>-<id>` and equals the `SKILL.md` name, the version
10//! is semver, the last changelog entry is the current version, the ladder names only `api`, `mcp`,
11//! `shortcuts` and `desktop`, and an MCP pointer names a catalog entry, never a command. The content
12//! hash is the catalog's too: SHA-256 over `path\0filehash\n` in byte order of the path, leaving out
13//! `skill.sig` and `verified.json`.
14
15use std::collections::BTreeMap;
16use std::path::Path;
17
18use serde_json::Value;
19use sha2::{Digest, Sha256};
20
21use crate::backend::agent_config::AgentConfigFile;
22use crate::backend::memory::record::sha256_hex;
23use crate::backend::skill_import::parse_skill_md;
24use crate::backend::skill_slugs::agent_skill_slugs;
25use crate::backend::storage::skill_app::{LadderStep, ReferenceInfo, SkillAppInfo, SkillFileInput, VerifiedRecord};
26use crate::backend::storage::store::Store;
27use crate::backend::storage::AgentSkill;
28
29pub const MANIFEST: &str = "computer-use.json";
30pub const SIG_FILE: &str = "skill.sig";
31pub const VERIFIED_FILE: &str = "verified.json";
32/// The manifest `schema` this build reads.
33pub const SCHEMA: &str = "computer-use-skill/v1";
34
35const MAX_FILES: usize = 200;
36const MAX_FILE_BYTES: u64 = 1024 * 1024;
37const MAX_TOTAL_BYTES: u64 = 5 * 1024 * 1024;
38const MAX_SKILL_MD_LINES: usize = 500;
39/// Reference crops (SPEC_PACKS §3.1): at most this many, this large, this many pixels across.
40const MAX_REFERENCES: usize = 40;
41const MAX_REFERENCE_BYTES: usize = 100 * 1024;
42const MAX_REFERENCE_W: u32 = 800;
43const MAX_REFERENCE_H: u32 = 600;
44/// PNG chunks a crop may carry. Text, time, EXIF and physical-size chunks can hold a name or a machine, so they are refused.
45const PNG_CHUNKS: &[&str] = &["IHDR", "PLTE", "tRNS", "IDAT", "IEND", "sRGB", "gAMA", "cHRM"];
46const TEXT_EXT: &[&str] = &["md", "json", "txt", "py", "ps1", "js", "mjs", "vbs", "jsx", "bat", "sh"];
47const SCRIPT_EXT: &[&str] = &["py", "ps1", "js", "mjs", "vbs", "jsx", "bat", "sh"];
48const PLATFORMS: &[&str] = &["windows", "macos", "linux"];
49const LADDER_KINDS: &[&str] = &["api", "mcp", "shortcuts", "desktop"];
50
51/// A skill folder, read and checked.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Bundle {
54    /// The `SKILL.md` name, which is also the folder name.
55    pub name: String,
56    pub description: String,
57    /// `SKILL.md` as written, frontmatter included: the content hash covers it.
58    pub skill_md: String,
59    /// The `SKILL.md` body without its frontmatter: what `db_skills.content` holds.
60    pub content: String,
61    pub info: SkillAppInfo,
62    /// The manifest as written, kept so a later build can read fields this one ignores.
63    pub manifest_json: String,
64    pub content_hash: String,
65    /// Every file but `SKILL.md`, the manifest and the signature: reference files, the test, scripts.
66    pub files: Vec<SkillFileInput>,
67    /// The publisher's signature (`skill.sig`) as written, if the folder carries one.
68    pub signature: Option<String>,
69    /// The pass records in `verified.json`, if the folder carries one.
70    pub verified: Vec<VerifiedRecord>,
71}
72
73fn is_name(s: &str) -> bool {
74    !s.is_empty()
75        && s.split('-').all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()))
76}
77
78/// `1.2.3`, with an optional `-prerelease` and `+build`, each of letters, digits, dots and hyphens: the version ends up in
79/// file names and a pass record's key, so nothing else may ride along after the numbers.
80fn is_semver(s: &str) -> bool {
81    let core = s.split(['-', '+']).next().unwrap_or("");
82    let parts: Vec<&str> = core.split('.').collect();
83    let tail = &s[core.len()..];
84    parts.len() == 3
85        && parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
86        && tail.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'+'))
87}
88
89fn ext_of(path: &str) -> String {
90    path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default()
91}
92
93/// A path beside `SKILL.md` that can be stored and written under an agent's skill folder: relative,
94/// forward slashes, no `.`/`..`/empty part, no drive or stream marker, at most four parts.
95pub fn valid_rel_path(path: &str) -> bool {
96    if path.is_empty() || path.len() > 200 || path.starts_with('/') || path.contains('\\') || path.contains(':') || path.contains('\0') {
97        return false;
98    }
99    let parts: Vec<&str> = path.split('/').collect();
100    parts.len() <= 4 && parts.iter().all(|p| !p.is_empty() && *p != "." && *p != ".." && !p.ends_with('.') && !p.ends_with(' '))
101}
102
103/// A name the folder itself uses (`SKILL.md`, the manifest, the signature, the pass records), in any letter case.
104/// On a case-insensitive disk a sibling called `skill.md` would overwrite the `SKILL.md` the person reviewed.
105fn is_reserved_name(path: &str) -> bool {
106    let lower = path.to_ascii_lowercase();
107    ["skill.md", MANIFEST, SIG_FILE, VERIFIED_FILE].contains(&lower.as_str())
108}
109
110fn str_list(v: Option<&Value>) -> Vec<String> {
111    v.and_then(Value::as_array)
112        .map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect())
113        .unwrap_or_default()
114}
115
116/// The manifest's own fields. Strict about what an installed skill needs, quiet about extra fields.
117pub fn info_from_manifest(text: &str) -> Result<SkillAppInfo, String> {
118    let m: Value = serde_json::from_str(text).map_err(|e| format!("{MANIFEST}: {e}"))?;
119    let s = |v: &Value, key: &str| v.get(key).and_then(Value::as_str).map(str::to_string);
120    if m.get("schema").and_then(Value::as_str) != Some(SCHEMA) {
121        return Err(format!("{MANIFEST}: schema must be {SCHEMA}"));
122    }
123    let publisher = s(&m, "publisher").filter(|p| is_name(p)).ok_or_else(|| format!("{MANIFEST}: publisher must be lowercase letters, digits and hyphens"))?;
124    let id = s(&m, "id").filter(|p| is_name(p)).ok_or_else(|| format!("{MANIFEST}: id must be lowercase letters, digits and hyphens"))?;
125    let name = s(&m, "name").filter(|n| !n.trim().is_empty()).ok_or_else(|| format!("{MANIFEST}: needs a name"))?;
126    let version = s(&m, "version").filter(|v| is_semver(v)).ok_or_else(|| format!("{MANIFEST}: version must be semver"))?;
127    let last = m.get("changelog").and_then(Value::as_array).and_then(|a| a.last()).and_then(|e| s(e, "version"));
128    if last.as_deref() != Some(version.as_str()) {
129        return Err(format!("{MANIFEST}: changelog must end with an entry for version {version}"));
130    }
131    let app = m.get("app").ok_or_else(|| format!("{MANIFEST}: app.vendor and app.executables are required"))?;
132    let vendor = s(app, "vendor").ok_or_else(|| format!("{MANIFEST}: app.vendor and app.executables are required"))?;
133    let exes = app.get("executables").and_then(Value::as_object).ok_or_else(|| format!("{MANIFEST}: app.vendor and app.executables are required"))?;
134    let mut executables = BTreeMap::new();
135    for (platform, list) in exes {
136        if !PLATFORMS.contains(&platform.as_str()) {
137            return Err(format!("{MANIFEST}: app.executables has an unknown platform {platform:?}"));
138        }
139        executables.insert(platform.clone(), str_list(Some(list)));
140    }
141    let platforms = str_list(m.get("platforms"));
142    if platforms.is_empty() || platforms.iter().any(|p| !PLATFORMS.contains(&p.as_str())) {
143        return Err(format!("{MANIFEST}: platforms must list windows, macos or linux"));
144    }
145    let mut ladder = Vec::new();
146    for step in m.get("ladder").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) {
147        match (s(step, "kind"), s(step, "note")) {
148            (Some(kind), Some(note)) if LADDER_KINDS.contains(&kind.as_str()) => ladder.push(LadderStep { kind, note }),
149            _ => return Err(format!("{MANIFEST}: ladder must list {{ kind: api | mcp | shortcuts | desktop, note }}")),
150        }
151    }
152    if ladder.is_empty() {
153        return Err(format!("{MANIFEST}: ladder must list {{ kind: api | mcp | shortcuts | desktop, note }}"));
154    }
155    // A catalog id, as a bare string or `{ catalogId, note }`; anything with a command in it is refused.
156    let mcp = match m.get("mcp") {
157        None | Some(Value::Null) => None,
158        Some(Value::String(id)) => Some(id.clone()),
159        Some(v @ Value::Object(_)) => {
160            if v.get("command").is_some() || v.get("args").is_some() {
161                return Err(format!("{MANIFEST}: mcp is a catalog id, never a command line"));
162            }
163            // `catalogId: null` says the app has no entry in the MCP catalog yet.
164            match v.get("catalogId") {
165                None | Some(Value::Null) => None,
166                Some(Value::String(id)) => Some(id.clone()),
167                Some(_) => return Err(format!("{MANIFEST}: mcp.catalogId is a string or null")),
168            }
169        }
170        Some(_) => return Err(format!("{MANIFEST}: mcp is a catalog id, never a command line")),
171    };
172    if mcp.as_deref().is_some_and(|id| id.chars().any(char::is_whitespace)) {
173        return Err(format!("{MANIFEST}: mcp is a catalog id, never a command line"));
174    }
175    let versions = app.get("versions");
176    let references = references_from(m.get("references"))?;
177    Ok(SkillAppInfo {
178        publisher,
179        id,
180        name,
181        version,
182        vendor,
183        executables,
184        title_hints: str_list(app.get("titleHints")),
185        platforms,
186        ladder,
187        mcp,
188        supported: versions.and_then(|v| s(v, "supported")),
189        tested: str_list(versions.and_then(|v| v.get("tested"))),
190        references,
191    })
192}
193
194/// The manifest's `references`: every crop needs all its tags, or it is refused.
195fn references_from(v: Option<&Value>) -> Result<Vec<ReferenceInfo>, String> {
196    let Some(list) = v.and_then(Value::as_array) else { return Ok(Vec::new()) };
197    if list.len() > MAX_REFERENCES {
198        return Err(format!("{MANIFEST}: a skill may have at most {MAX_REFERENCES} reference crops"));
199    }
200    let mut out = Vec::new();
201    for r in list {
202        let s = |key: &str| r.get(key).and_then(Value::as_str).map(str::trim).filter(|x| !x.is_empty()).map(str::to_string);
203        let path = s("path").unwrap_or_default();
204        let bad = |what: &str| format!("{MANIFEST}: reference {path:?} needs {what}");
205        if !path.starts_with("references/") || !path.ends_with(".png") || !valid_rel_path(&path) {
206            return Err(format!("{MANIFEST}: a reference is a PNG under references/, not {path:?}"));
207        }
208        let platform = s("platform").filter(|p| PLATFORMS.contains(&p.as_str())).ok_or_else(|| bad("a platform (windows, macos or linux)"))?;
209        let scale = r.get("scale").and_then(Value::as_u64).filter(|n| (1..=400).contains(n)).ok_or_else(|| bad("a scale in percent"))? as u32;
210        let sha256 = s("sha256").filter(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit())).ok_or_else(|| bad("its sha256"))?.to_ascii_lowercase();
211        out.push(ReferenceInfo {
212            label: s("label").ok_or_else(|| bad("a label"))?,
213            shows: s("shows").unwrap_or_default(),
214            app_version: s("appVersion").ok_or_else(|| bad("the app version it was taken at"))?,
215            theme: s("theme").ok_or_else(|| bad("a theme"))?,
216            captured_by: s("capturedBy").ok_or_else(|| bad("capturedBy"))?,
217            date: s("date").ok_or_else(|| bad("a date"))?,
218            platform,
219            scale,
220            sha256,
221            path,
222        });
223    }
224    Ok(out)
225}
226
227/// Check a reference crop's bytes: a PNG within the size and pixel limits that carries no metadata chunk.
228pub fn check_png(path: &str, bytes: &[u8]) -> Result<(), String> {
229    const SIG: &[u8] = &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
230    if bytes.len() > MAX_REFERENCE_BYTES {
231        return Err(format!("{path}: over {} KB", MAX_REFERENCE_BYTES / 1024));
232    }
233    if !bytes.starts_with(SIG) {
234        return Err(format!("{path}: not a PNG"));
235    }
236    let (mut at, mut first, mut ended) = (SIG.len(), true, false);
237    while at + 8 <= bytes.len() {
238        let len = u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap()) as usize;
239        let kind = std::str::from_utf8(&bytes[at + 4..at + 8]).unwrap_or("????");
240        let end = at.checked_add(12).and_then(|n| n.checked_add(len)).filter(|e| *e <= bytes.len()).ok_or_else(|| format!("{path}: truncated PNG"))?;
241        if !PNG_CHUNKS.contains(&kind) {
242            return Err(format!("{path}: carries a {kind} chunk; re-save the crop without metadata"));
243        }
244        if first {
245            if kind != "IHDR" || len != 13 {
246                return Err(format!("{path}: not a PNG"));
247            }
248            let w = u32::from_be_bytes(bytes[at + 8..at + 12].try_into().unwrap());
249            let h = u32::from_be_bytes(bytes[at + 12..at + 16].try_into().unwrap());
250            if w == 0 || h == 0 || w > MAX_REFERENCE_W || h > MAX_REFERENCE_H {
251                return Err(format!("{path}: {w}x{h} pixels; a crop is at most {MAX_REFERENCE_W}x{MAX_REFERENCE_H}"));
252            }
253            first = false;
254        }
255        at = end;
256        if kind == "IEND" {
257            ended = true;
258            break;
259        }
260    }
261    if !ended || at != bytes.len() {
262        return Err(format!("{path}: not a complete PNG"));
263    }
264    Ok(())
265}
266
267/// The scripts a manifest lists: path, and the SHA-256 it states.
268fn listed_scripts(manifest: &Value) -> BTreeMap<String, String> {
269    manifest
270        .get("scripts")
271        .and_then(Value::as_array)
272        .map(|a| {
273            a.iter()
274                .filter_map(|s| Some((s.get("path")?.as_str()?.to_string(), s.get("sha256")?.as_str()?.to_string())))
275                .collect()
276        })
277        .unwrap_or_default()
278}
279
280/// What each listed script is for and needs, for the approval prompt.
281pub fn script_infos(manifest_json: &str) -> Vec<crate::backend::storage::skill_app::ScriptInfo> {
282    let Ok(m) = serde_json::from_str::<Value>(manifest_json) else { return Vec::new() };
283    m.get("scripts")
284        .and_then(Value::as_array)
285        .map(|a| {
286            a.iter()
287                .filter_map(|s| {
288                    Some(crate::backend::storage::skill_app::ScriptInfo {
289                        path: s.get("path")?.as_str()?.to_string(),
290                        purpose: s.get("purpose").and_then(Value::as_str).unwrap_or("").to_string(),
291                        needs: str_list(s.get("needs")),
292                    })
293                })
294                .collect()
295        })
296        .unwrap_or_default()
297}
298
299/// The catalog's content hash of `files` (path to bytes), without `skill.sig` and `verified.json`.
300pub fn content_hash(files: &BTreeMap<String, Vec<u8>>) -> String {
301    let mut h = Sha256::new();
302    // BTreeMap<String, _> iterates in byte order of the key, the order the catalog signs in.
303    for (path, bytes) in files.iter().filter(|(p, _)| p.as_str() != SIG_FILE && p.as_str() != VERIFIED_FILE) {
304        h.update(path.as_bytes());
305        h.update(b"\0");
306        h.update(sha256_hex(bytes).as_bytes());
307        h.update(b"\n");
308    }
309    h.finalize().iter().map(|b| format!("{b:02x}")).collect()
310}
311
312fn read_files(dir: &Path) -> Result<BTreeMap<String, Vec<u8>>, String> {
313    fn walk(abs: &Path, rel: &str, out: &mut BTreeMap<String, Vec<u8>>, total: &mut u64) -> Result<(), String> {
314        let mut names: Vec<_> = std::fs::read_dir(abs).map_err(|e| format!("{}: {e}", abs.display()))?.flatten().collect();
315        names.sort_by_key(|e| e.file_name());
316        for entry in names {
317            let name = entry.file_name().to_string_lossy().to_string();
318            let r = if rel.is_empty() { name.clone() } else { format!("{rel}/{name}") };
319            let meta = std::fs::symlink_metadata(entry.path()).map_err(|e| format!("{r}: {e}"))?;
320            if meta.file_type().is_symlink() {
321                return Err(format!("{r} is a link; a skill can't contain links"));
322            }
323            if meta.is_dir() {
324                walk(&entry.path(), &r, out, total)?;
325                continue;
326            }
327            if meta.len() > MAX_FILE_BYTES {
328                return Err(format!("{r} is over 1 MB"));
329            }
330            *total += meta.len();
331            if *total > MAX_TOTAL_BYTES {
332                return Err("the skill is over 5 MB".to_string());
333            }
334            out.insert(r.clone(), std::fs::read(entry.path()).map_err(|e| format!("{r}: {e}"))?);
335            if out.len() > MAX_FILES {
336                return Err(format!("the skill has over {MAX_FILES} files"));
337            }
338        }
339        Ok(())
340    }
341    let mut out = BTreeMap::new();
342    walk(dir, "", &mut out, &mut 0)?;
343    Ok(out)
344}
345
346/// Read and check the skill folder `dir`. The folder's name must be `<publisher>-<id>`.
347pub fn read_folder(dir: &Path) -> Result<Bundle, String> {
348    let folder = dir.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
349    let all = read_files(dir)?;
350    let text = |name: &str| -> Result<Option<String>, String> {
351        all.get(name).map(|b| String::from_utf8(b.clone()).map_err(|_| format!("{name} is not UTF-8 text"))).transpose()
352    };
353    for path in all.keys() {
354        if !valid_rel_path(path) {
355            return Err(format!("{path}: not a path a skill can hold"));
356        }
357        if is_reserved_name(path) && !matches!(path.as_str(), "SKILL.md" | MANIFEST | SIG_FILE | VERIFIED_FILE) {
358            return Err(format!("{path}: a name the skill folder uses for itself, in other letters; rename it"));
359        }
360        let is_crop = path.starts_with("references/") && ext_of(path) == "png";
361        if !is_crop && !TEXT_EXT.contains(&ext_of(path).as_str()) && path != SIG_FILE {
362            return Err(format!("{path}: only text and script files are accepted ({}), and PNG crops under references/", TEXT_EXT.join(" ")));
363        }
364    }
365    let skill_md = text("SKILL.md")?.ok_or("no SKILL.md")?;
366    let (name, description, content) = parse_skill_md(&skill_md, &folder);
367    if name != folder {
368        return Err(format!("SKILL.md name ({name}) must match the folder ({folder})"));
369    }
370    if description.is_empty() || description.chars().count() > 1024 {
371        return Err("SKILL.md needs a description of 1 to 1024 characters".to_string());
372    }
373    if skill_md.lines().count() > MAX_SKILL_MD_LINES {
374        return Err(format!("SKILL.md is over {MAX_SKILL_MD_LINES} lines: move detail into reference files"));
375    }
376
377    let manifest_json = text(MANIFEST)?.ok_or_else(|| format!("no {MANIFEST}"))?;
378    let info = info_from_manifest(&manifest_json)?;
379    if format!("{}-{}", info.publisher, info.id) != folder {
380        return Err(format!("the folder must be {}-{}", info.publisher, info.id));
381    }
382    let manifest: Value = serde_json::from_str(&manifest_json).map_err(|e| format!("{MANIFEST}: {e}"))?;
383
384    // Every script is listed with the hash it has; a listed file must be there.
385    let listed = listed_scripts(&manifest);
386    let mut files = Vec::new();
387    for (path, bytes) in &all {
388        if matches!(path.as_str(), "SKILL.md" | MANIFEST | SIG_FILE | VERIFIED_FILE) {
389            continue;
390        }
391        if path.starts_with("references/") && ext_of(path) == "png" {
392            check_png(path, bytes)?;
393            let tagged = info.references.iter().find(|r| &r.path == path).ok_or_else(|| format!("{path} is a crop: list it in {MANIFEST} \"references\" with its tags"))?;
394            if tagged.sha256 != sha256_hex(bytes) {
395                return Err(format!("{path}: sha256 in {MANIFEST} doesn't match the file"));
396            }
397            files.push(SkillFileInput { path: path.clone(), content: String::new(), image: Some(bytes.clone()), script: false });
398            continue;
399        }
400        let script = SCRIPT_EXT.contains(&ext_of(path).as_str());
401        if script {
402            match listed.get(path) {
403                None => return Err(format!("{path} is a script: list it in {MANIFEST} \"scripts\" with its sha256, purpose and needs")),
404                Some(h) if *h != sha256_hex(bytes) => return Err(format!("{path}: sha256 in {MANIFEST} doesn't match the file")),
405                Some(_) => {}
406            }
407        }
408        let content = String::from_utf8(bytes.clone()).map_err(|_| format!("{path} is not UTF-8 text"))?;
409        files.push(SkillFileInput { path: path.clone(), content, image: None, script });
410    }
411    for r in &info.references {
412        if !all.contains_key(&r.path) {
413            return Err(format!("{MANIFEST} lists the reference {}, which isn't in the folder", r.path));
414        }
415    }
416    for path in listed.keys() {
417        if !all.contains_key(path) {
418            return Err(format!("{MANIFEST} lists {path}, which isn't in the folder"));
419        }
420    }
421
422    let signature = text(SIG_FILE)?.map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
423    let verified = match text(VERIFIED_FILE)? {
424        None => Vec::new(),
425        Some(t) => serde_json::from_str::<Vec<VerifiedRecord>>(&t).map_err(|e| format!("{VERIFIED_FILE}: {e}"))?,
426    };
427    Ok(Bundle { name, description, skill_md, content, info, manifest_json, content_hash: content_hash(&all), files, signature, verified })
428}
429
430/// Whether `exe` (an executable name as `Desktop apps` lists it) is one this skill's app runs as on `platform`.
431/// Compared by file name, ignoring case and a folder part, never by window title alone.
432pub fn matches_executable(info: &SkillAppInfo, platform: &str, exe: &str) -> bool {
433    // `Desktop` may name an app with or without `.exe`; the manifest lists it either way.
434    let base = |s: &str| {
435        let name = s.rsplit(['/', '\\']).next().unwrap_or(s).to_ascii_lowercase();
436        name.strip_suffix(".exe").map(str::to_string).unwrap_or(name)
437    };
438    let want = base(exe);
439    !want.is_empty() && info.executables.get(platform).is_some_and(|list| list.iter().any(|e| base(e) == want))
440}
441
442/// What an import preview read, kept until the person approves it, so the commit writes exactly what they saw
443/// (by content hash) and not a second read of a source that may have changed. At most 16, each for 30 minutes.
444static STASH: std::sync::Mutex<Vec<(std::time::Instant, Bundle)>> = std::sync::Mutex::new(Vec::new());
445const STASH_TTL: std::time::Duration = std::time::Duration::from_secs(30 * 60);
446const STASH_MAX: usize = 16;
447
448/// Keep `bundle` for the commit that follows its preview.
449pub fn stash(bundle: &Bundle) {
450    let mut s = STASH.lock().unwrap();
451    s.retain(|(at, b)| at.elapsed() < STASH_TTL && b.content_hash != bundle.content_hash);
452    s.push((std::time::Instant::now(), bundle.clone()));
453    while s.len() > STASH_MAX {
454        s.remove(0);
455    }
456}
457
458/// The bundle a preview read, by its content hash, if it is still kept. It stays, so a failed commit can be retried.
459pub fn stashed(content_hash: &str) -> Option<Bundle> {
460    let s = STASH.lock().unwrap();
461    s.iter().find(|(at, b)| at.elapsed() < STASH_TTL && b.content_hash == content_hash).map(|(_, b)| b.clone())
462}
463
464/// The key that signed this bundle: `Ok(None)` for an unsigned one, an error for a signature that does not match
465/// its files. A publisher pinned to another key, or pinned and now unsigned, is refused (`SPEC_PACKS` §5): a
466/// different key than the one the person approved a script of is not an update, it is a different author.
467pub fn check_signature(catalog: &Store, b: &Bundle) -> Result<Option<String>, String> {
468    use crate::backend::widget::signature as sig;
469    let id = format!("{}.{}", b.info.publisher, b.info.id);
470    let signer = match &b.signature {
471        Some(text) => Some(sig::verify_text(&sig::COMPUTER_USE_SKILL, text, &id, &b.info.version, &b.content_hash).map_err(|e| format!("{id}: {e}"))?),
472        None => None,
473    };
474    let pins = catalog.skill_publisher_pins().map_err(|e| e.to_string())?;
475    if let Some(pinned) = pins.get(&b.info.publisher) {
476        if signer.as_deref() != Some(pinned.as_str()) {
477            let said = signer.as_deref().map_or("not signed".to_string(), |k| format!("signed by {}", sig::fingerprint(k)));
478            return Err(format!("{id} is {said}, but {} is pinned to {}: that is a different author, not an update", b.info.publisher, sig::fingerprint(pinned)));
479        }
480    }
481    Ok(signer)
482}
483
484/// Write an approved bundle's computer-use part for the catalog skill `skill_id`: the manifest, the files, and the pass
485/// records its folder carried. A script lands unapproved. Call after the skill row itself is written.
486/// `signer` is what `check_signature` returned for this bundle: the caller checks first and a refusal never gets here.
487pub fn install(
488    catalog: &Store,
489    skill_id: &str,
490    b: &Bundle,
491    signer: Option<&str>,
492    now_ms: i64,
493) -> Result<(), crate::backend::storage::error::StoreError> {
494    catalog.skill_app_set(skill_id, &b.info, &b.manifest_json, &b.content_hash, &b.files, now_ms)?;
495    catalog.skill_signer_set(skill_id, signer)?;
496    catalog.skill_origin_set(skill_id, &b.skill_md, b.signature.as_deref())?;
497    for r in &b.verified {
498        catalog.skill_verified_append(skill_id, r, "import", now_ms)?;
499    }
500    Ok(())
501}
502
503/// The computer-use skill for a window, as `Desktop apps` points at it.
504#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
505pub struct SkillPointer {
506    pub id: String,
507    pub name: String,
508    pub version: String,
509    /// At least one test of this installed version passed on this platform.
510    pub verified_here: bool,
511}
512
513/// The skill whose app runs as `exe` on `platform`, if the catalog has one. No grant is implied by the pointer.
514pub fn skill_for_executable(catalog: &Store, platform: &str, exe: &str) -> Option<SkillPointer> {
515    let apps = catalog.skill_app_map().ok()?;
516    let (id, app) = apps.into_iter().find(|(_, a)| matches_executable(&a.info, platform, exe))?;
517    let name = catalog.skill_get(&id).ok().flatten()?.name;
518    let verified_here = app.verified.iter().any(|r| r.platform == platform && r.result == "pass" && r.skill_version == app.info.version);
519    Some(SkillPointer { id, name, version: app.info.version, verified_here })
520}
521
522/// The files an agent's launch writes beside each computer-use skill's `SKILL.md`
523/// (`.claude/skills/<slug>/<path>`), for the skills `build_config_files` gave a folder. A script is
524/// written only once a person has approved it. A reference crop is not written at all: an image is read
525/// with `Skills get` and `file`, so it costs nothing until a step points at it. Raw text: unlike `SKILL.md`, no `{{VARIABLE}}` is expanded,
526/// since a script or a reference file may hold `{{` of its own. The `.claude/skills/` prefix makes them
527/// managed files, so the launch's stale-file cleanup removes the ones a skill no longer has.
528pub fn sibling_files(skills: &[AgentSkill], catalog: &Store) -> Vec<AgentConfigFile> {
529    let mut out = Vec::new();
530    for (skill, slug) in skills.iter().zip(agent_skill_slugs(skills)) {
531        let Some(slug) = slug else { continue };
532        for f in catalog.skill_files(&skill.id).unwrap_or_default() {
533            if (f.script && !f.approved) || f.image.is_some() || !valid_rel_path(&f.path) || is_reserved_name(&f.path) {
534                continue;
535            }
536            out.push(AgentConfigFile { filename: format!(".claude/skills/{slug}/{}", f.path), content: f.content });
537        }
538    }
539    out
540}
541
542#[cfg(test)]
543#[path = "computer_use_skill_tests.rs"]
544pub(crate) mod tests;