Skip to main content

agentmux_srv_core/backend/
skill_catalog.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The public catalog of computer-use skills (docs/specs/SPEC_SKILLS_REPOSITORY_2026_11_05.md ยง2): fetch its signed
5//! index, say what is installed here, and install or update one skill. It reuses the widget catalog's fetch and
6//! signature check with its own key list: a leaked secret in one repository cannot sign the other's index.
7//!
8//! Three checks stand between the network and the catalog, each against the entry in the signed index: the zip's
9//! SHA-256, the skill's content hash, and the author's signature. A skill installs unapproved, the same as one
10//! imported from a folder: its scripts are never given to an agent until a person approves them, and its MCP
11//! pointer is only shown, never installed.
12
13use std::collections::BTreeMap;
14use std::path::PathBuf;
15
16use base64::Engine;
17use serde::{Deserialize, Serialize};
18
19use crate::backend::computer_use_skill::{check_signature, install, read_folder, Bundle};
20use crate::backend::memory::record::sha256_hex;
21use crate::backend::skill_file;
22use crate::backend::storage::skill_app::SkillApp;
23use crate::backend::storage::store::Store;
24use crate::backend::storage::Skill;
25use crate::backend::widget::catalog::{get, origin_of, signed_by_any};
26use crate::backend::widget::signature::fingerprint;
27
28/// Where the catalog is served.
29pub const CATALOG_URL: &str = "https://agentmuxai.github.io/skills/index.json";
30
31/// The catalog keys AgentMux trusts for this index (base64 Ed25519 public keys), more than one for a rotation. The
32/// private half is a secret of the catalog's own repository; the widget catalog has a different key.
33pub const PACK_CATALOG_KEYS: &[&str] = &[
34    // 2026-11-06, the first skills catalog key.
35    "VBSn+oh9qB6bnv+BoGifqfwqDXTh3BPIsQb/8RMg+Do=",
36];
37
38const MAX_INDEX_BYTES: usize = 5 * 1024 * 1024;
39const CATALOG_VERSION: u32 = 1;
40/// A catalog zip is a `.skill` file, which is at most this, plus some slack for the zip's own headers.
41const MAX_ZIP_BYTES: usize = skill_file::MAX_ZIP_BYTES as usize + 1024 * 1024;
42
43#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
44#[serde(rename_all = "camelCase")]
45#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "AppSkillCatalogVersions")]
46pub struct CatalogVersions {
47    #[serde(default)]
48    pub supported: Option<String>,
49    #[serde(default)]
50    pub tested: Vec<String>,
51}
52
53#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
54#[serde(rename_all = "camelCase")]
55#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "AppSkillCatalogApp")]
56pub struct CatalogApp {
57    #[serde(default)]
58    pub vendor: String,
59    /// Per platform, the executable names the app runs as: how its version is found on this computer.
60    #[serde(default)]
61    pub executables: BTreeMap<String, Vec<String>>,
62    #[serde(default)]
63    pub versions: CatalogVersions,
64}
65
66/// One test the catalog records for a version of a skill.
67#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
68#[serde(rename_all = "camelCase")]
69#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "AppSkillCatalogRecord")]
70pub struct CatalogRecord {
71    pub skill_version: String,
72    pub app_version: String,
73    pub platform: String,
74    pub date: String,
75    pub result: String,
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
79#[serde(rename_all = "camelCase")]
80#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "AppSkillCatalogEntry")]
81pub struct CatalogEntry {
82    /// `<publisher>.<id>`.
83    pub id: String,
84    pub name: String,
85    pub version: String,
86    #[serde(default)]
87    pub description: String,
88    pub publisher: String,
89    #[serde(default)]
90    pub app: CatalogApp,
91    #[serde(default)]
92    pub platforms: Vec<String>,
93    #[serde(default)]
94    pub routes: Vec<String>,
95    /// Whether it carries a script that does something (not only a test).
96    #[serde(default)]
97    pub has_scripts: bool,
98    /// The MCP catalog entry it points at, which is installed only through the MCP tab.
99    #[serde(default)]
100    pub mcp: Option<String>,
101    /// The skill's content hash.
102    pub hash: String,
103    /// Its author's key (base64), which signed it.
104    pub publisher_key: String,
105    #[serde(default)]
106    pub verification: Vec<CatalogRecord>,
107    pub zip: String,
108    pub zip_sha256: String,
109}
110
111#[derive(Debug, Clone, Deserialize)]
112#[serde(rename_all = "camelCase")]
113struct CatalogIndex {
114    catalog_version: u32,
115    #[serde(default)]
116    skills: Vec<CatalogEntry>,
117}
118
119/// An entry as Browse shows it: the entry, its author's fingerprint and badge, and what is installed here.
120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
121#[ts(export, export_to = "../../../frontend/types/rpc/")]
122pub struct AppSkillCatalogItem {
123    pub entry: CatalogEntry,
124    pub fingerprint: String,
125    /// `agentmux` when the AgentMux catalog key signed it, else `community`.
126    pub badge: String,
127    /// `not_installed`, `current` (exactly what the catalog lists), `update` (installed here is older), `newer_here`
128    /// (installed here is newer than the catalog's), or `changed` (the same version, but not as the catalog lists it:
129    /// other files, an edited text, or added another way).
130    pub state: String,
131    pub installed_version: Option<String>,
132    pub skill_id: Option<String>,
133    /// The application itself is on this computer (found by the executable names the entry lists for this platform).
134    pub app_found: bool,
135    /// The application's version here, when it is found and says one.
136    pub app_version: Option<String>,
137}
138
139fn is_part(s: &str) -> bool {
140    !s.is_empty() && s.split('-').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()))
141}
142
143/// Checks the index `raw` against its signature with `keys`, and each entry against the catalog's rules.
144pub fn verify_index(raw: &[u8], sig_b64: &str, keys: &[&str], index_url: &str) -> Result<Vec<CatalogEntry>, String> {
145    let signature: [u8; 64] = base64::engine::general_purpose::STANDARD
146        .decode(sig_b64.trim())
147        .ok()
148        .and_then(|s| s.try_into().ok())
149        .ok_or("the catalog's signature isn't 64 bytes of base64")?;
150    if !signed_by_any(raw, &signature, keys) {
151        return Err("the catalog's signature doesn't verify: it isn't the AgentMux skill catalog, or it was changed".to_string());
152    }
153    let index: CatalogIndex = serde_json::from_slice(raw).map_err(|e| format!("the catalog index: {e}"))?;
154    if index.catalog_version != CATALOG_VERSION {
155        return Err(format!("the catalog is version {}, this AgentMux reads {CATALOG_VERSION}", index.catalog_version));
156    }
157    let origin = origin_of(index_url).ok_or("the catalog URL isn't an https:// URL")?;
158    for e in &index.skills {
159        let named = e.id.split_once('.').is_some_and(|(p, i)| is_part(p) && is_part(i) && p == e.publisher);
160        if !named {
161            return Err(format!("the catalog lists {:?}, which isn't a <publisher>.<id> skill", e.id));
162        }
163        if origin_of(&e.zip).as_deref() != Some(origin.as_str()) {
164            return Err(format!("the catalog's {} isn't served from the catalog itself", e.id));
165        }
166    }
167    Ok(index.skills)
168}
169
170/// The catalog at `url`, checked.
171pub async fn fetch(url: &str) -> Result<Vec<CatalogEntry>, String> {
172    let raw = get(url, MAX_INDEX_BYTES).await?;
173    let sig_text = String::from_utf8(get(&format!("{url}.sig"), 1024).await?).map_err(|_| "the catalog's signature isn't text")?;
174    verify_index(&raw, &sig_text, PACK_CATALOG_KEYS, url)
175}
176
177/// The zip an entry points at, from the catalog's own origin (no redirects).
178pub async fn download(entry: &CatalogEntry) -> Result<Vec<u8>, String> {
179    get(&entry.zip, MAX_ZIP_BYTES).await
180}
181
182/// `1.2.3[-pre][+build]` ordered as semver does: the numbers (a missing one is 0), then a pre-release sorts before
183/// the same release and pre-releases compare part by part (numbers before words); `+build` is ignored.
184fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering {
185    use std::cmp::Ordering;
186    fn split(v: &str) -> (Vec<u64>, Option<&str>) {
187        let core = v.split('+').next().unwrap_or("");
188        let (nums, pre) = core.split_once('-').map_or((core, None), |(n, p)| (n, Some(p)));
189        (nums.split('.').map(|p| p.parse().unwrap_or(0)).collect(), pre)
190    }
191    let ((mut an, ap), (mut bn, bp)) = (split(a), split(b));
192    let len = an.len().max(bn.len());
193    an.resize(len, 0);
194    bn.resize(len, 0);
195    an.cmp(&bn).then_with(|| match (ap, bp) {
196        (None, None) => Ordering::Equal,
197        (Some(_), None) => Ordering::Less,
198        (None, Some(_)) => Ordering::Greater,
199        (Some(x), Some(y)) => {
200            let part = |p: &str| p.parse::<u64>().map_or((1, 0, p.to_string()), |n| (0, n, String::new()));
201            x.split('.').map(part).cmp(y.split('.').map(part))
202        }
203    })
204}
205
206/// What Browse lists: each entry with what is installed here (`installed` is `Store::skill_app_map`).
207pub fn items(entries: Vec<CatalogEntry>, installed: &BTreeMap<String, SkillApp>) -> Vec<AppSkillCatalogItem> {
208    entries
209        .into_iter()
210        .map(|entry| {
211            let here = installed.iter().find(|(_, a)| format!("{}.{}", a.info.publisher, a.info.id) == entry.id);
212            let state = match here {
213                None => "not_installed",
214                Some((_, a)) if a.content_hash == entry.hash && a.from_catalog => "current",
215                // The same files, but not as the catalog lists them: edited in Memory, or added another way.
216                Some((_, a)) if a.content_hash == entry.hash => "changed",
217                Some((_, a)) => match version_cmp(&entry.version, &a.info.version) {
218                    std::cmp::Ordering::Greater => "update",
219                    std::cmp::Ordering::Less => "newer_here",
220                    std::cmp::Ordering::Equal => "changed",
221                },
222            };
223            AppSkillCatalogItem {
224                fingerprint: fingerprint(&entry.publisher_key),
225                badge: if PACK_CATALOG_KEYS.contains(&entry.publisher_key.as_str()) { "agentmux" } else { "community" }.to_string(),
226                state: state.to_string(),
227                installed_version: here.map(|(_, a)| a.info.version.clone()),
228                skill_id: here.map(|(id, _)| id.clone()),
229                app_found: false,
230                app_version: None,
231                entry,
232            }
233        })
234        .collect()
235}
236
237/// Says for each entry whether its application is on this computer, and which version, by the executable names it lists
238/// for `platform` (`find` is `app_version::find`). An entry that lists none for this platform is left as it is.
239pub fn add_app_versions(items: &mut [AppSkillCatalogItem], platform: &str, find: impl Fn(&[String]) -> Option<crate::backend::app_version::Found>) {
240    for item in items {
241        let Some(names) = item.entry.app.executables.get(platform).filter(|n| !n.is_empty()) else { continue };
242        if let Some(found) = find(names) {
243            item.app_found = true;
244            item.app_version = found.version;
245        }
246    }
247}
248
249/// An installed skill's application on this computer.
250#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
251#[ts(export, export_to = "../../../frontend/types/rpc/")]
252pub struct AppSkillHere {
253    pub skill_id: String,
254    /// The application is on this computer (found by the executable names the skill lists for this platform).
255    pub found: bool,
256    /// Its version, when it is found and says one.
257    pub version: Option<String>,
258}
259
260/// For each installed skill that lists an executable for `platform`: whether its application is here, and which
261/// version (`find` is `app_version::find`). A skill that lists none for this platform is left out: there is nothing to look for.
262pub fn installed_here(
263    installed: &BTreeMap<String, SkillApp>,
264    platform: &str,
265    find: impl Fn(&[String]) -> Option<crate::backend::app_version::Found>,
266) -> Vec<AppSkillHere> {
267    installed
268        .iter()
269        .filter_map(|(id, app)| {
270            let names = app.info.executables.get(platform).filter(|n| !n.is_empty())?;
271            let found = find(names);
272            Some(AppSkillHere { skill_id: id.clone(), found: found.is_some(), version: found.and_then(|f| f.version) })
273        })
274        .collect()
275}
276
277/// The platform name skills use for the computer this runs on.
278pub fn this_platform() -> &'static str {
279    if cfg!(windows) {
280        "windows"
281    } else if cfg!(target_os = "macos") {
282        "macos"
283    } else {
284        "linux"
285    }
286}
287
288/// Checks a downloaded zip against its entry: the zip's SHA-256, then, unpacked and read like any skill folder, the
289/// content hash, the id and version, and the author's signature (which must be the key the catalog lists, and not
290/// another key than the one this publisher is pinned to here). Returns the skill and the key that signed it.
291pub fn check_download(catalog: &Store, zip: &[u8], entry: &CatalogEntry) -> Result<(Bundle, String), String> {
292    let id = &entry.id;
293    if sha256_hex(zip) != entry.zip_sha256 {
294        return Err(format!("{id}'s download doesn't match the catalog"));
295    }
296    let tmp = tempfile::tempdir().map_err(|e| e.to_string())?;
297    let zip_path = tmp.path().join("skill.zip");
298    std::fs::write(&zip_path, zip).map_err(|e| e.to_string())?;
299    let stage = tmp.path().join("skill");
300    std::fs::create_dir_all(&stage).map_err(|e| e.to_string())?;
301    skill_file::extract(&zip_path, &stage).map_err(|e| format!("{id}: {e}"))?;
302    let folder: PathBuf = std::fs::read_dir(&stage)
303        .map_err(|e| e.to_string())?
304        .flatten()
305        .find(|e| e.path().is_dir())
306        .map(|e| e.path())
307        .ok_or_else(|| format!("{id}'s download holds no folder"))?;
308    let bundle = read_folder(&folder).map_err(|e| format!("{id}: {e}"))?;
309    if bundle.content_hash != entry.hash {
310        return Err(format!("{id}'s files don't match the catalog"));
311    }
312    if format!("{}.{}", bundle.info.publisher, bundle.info.id) != *id || bundle.info.version != entry.version {
313        return Err(format!("{id}'s manifest doesn't match the catalog"));
314    }
315    match check_signature(catalog, &bundle)? {
316        Some(key) if key == entry.publisher_key => Ok((bundle, key)),
317        _ => Err(format!("{id} isn't signed by the author the catalog lists")),
318    }
319}
320
321/// What `install_download` did.
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct Installed {
324    pub skill_id: String,
325    pub name: String,
326    pub version: String,
327    /// An earlier version was replaced.
328    pub updated: bool,
329}
330
331/// Check `zip` against `entry` and add it to the catalog as a computer-use skill, or replace the version installed
332/// here. Scripts arrive unapproved (a script whose text is unchanged keeps the approval a person gave it). A new
333/// skill is global, bound to nobody and outside "new agents get it"; an update keeps its binds and reach.
334pub fn install_download(catalog: &Store, zip: &[u8], entry: &CatalogEntry, now_ms: i64) -> Result<Installed, String> {
335    let (bundle, signer) = check_download(catalog, zip, entry)?;
336    let existing = catalog
337        .skill_app_map()
338        .map_err(|e| e.to_string())?
339        .into_iter()
340        .find(|(_, a)| format!("{}.{}", a.info.publisher, a.info.id) == entry.id)
341        .map(|(id, _)| id);
342    let current = match &existing {
343        Some(id) => catalog.skill_get(id).map_err(|e| e.to_string())?,
344        None => None,
345    };
346    let skill = Skill {
347        id: current.as_ref().map_or_else(|| uuid::Uuid::new_v4().to_string(), |s| s.id.clone()),
348        name: bundle.name.clone(),
349        trigger: current.as_ref().map_or_else(|| bundle.name.clone(), |s| s.trigger.clone()),
350        skill_type: current.as_ref().map_or_else(|| "agent-skill".to_string(), |s| s.skill_type.clone()),
351        description: bundle.description.clone(),
352        content: bundle.content.clone(),
353        is_global: true,
354        created_at: current.as_ref().map_or(now_ms, |s| s.created_at),
355        updated_at: now_ms,
356    };
357    catalog.skill_upsert_unique_global(&skill).map_err(|e| e.to_string())?;
358    if current.is_none() {
359        catalog.skill_set_reach(&skill.id, false, false, now_ms).map_err(|e| e.to_string())?;
360    }
361    install(catalog, &skill.id, &bundle, Some(&signer), now_ms).map_err(|e| e.to_string())?;
362    catalog.skill_catalog_source_set(&skill.id, &entry.hash, &entry.publisher_key).map_err(|e| e.to_string())?;
363    Ok(Installed { skill_id: skill.id, name: skill.name, version: bundle.info.version, updated: current.is_some() })
364}
365
366#[cfg(test)]
367#[path = "skill_catalog_tests.rs"]
368mod tests;