1use 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
28pub const CATALOG_URL: &str = "https://agentmuxai.github.io/skills/index.json";
30
31pub const PACK_CATALOG_KEYS: &[&str] = &[
34 "VBSn+oh9qB6bnv+BoGifqfwqDXTh3BPIsQb/8RMg+Do=",
36];
37
38const MAX_INDEX_BYTES: usize = 5 * 1024 * 1024;
39const CATALOG_VERSION: u32 = 1;
40const 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 #[serde(default)]
61 pub executables: BTreeMap<String, Vec<String>>,
62 #[serde(default)]
63 pub versions: CatalogVersions,
64}
65
66#[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 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 #[serde(default)]
97 pub has_scripts: bool,
98 #[serde(default)]
100 pub mcp: Option<String>,
101 pub hash: String,
103 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#[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 pub badge: String,
127 pub state: String,
131 pub installed_version: Option<String>,
132 pub skill_id: Option<String>,
133 pub app_found: bool,
135 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
143pub 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
170pub 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
177pub async fn download(entry: &CatalogEntry) -> Result<Vec<u8>, String> {
179 get(&entry.zip, MAX_ZIP_BYTES).await
180}
181
182fn 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
206pub 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 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
237pub 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#[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 pub found: bool,
256 pub version: Option<String>,
258}
259
260pub 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
277pub 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
288pub 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#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct Installed {
324 pub skill_id: String,
325 pub name: String,
326 pub version: String,
327 pub updated: bool,
329}
330
331pub 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;