agentmux_srv/server/app_api/
skill_app_rpc.rs1use super::*;
11use crate::backend::storage::skill_app::{ScriptApproval, ScriptOutcome};
12use crate::backend::rpc_types::{
13 CommandSkillCatalogAppFileData, CommandSkillCatalogAppScriptData, CommandSkillCatalogExportData, SkillAppFile, SkillAppScriptResult, SkillExportResult,
14};
15
16pub(super) fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
17 register_app_file(engine, state);
18 register_app_script(engine, state);
19 register_export(engine, state);
20}
21
22fn global_app_skill(store: &crate::backend::storage::store::Store, id: &str, what: &str) -> Result<(), String> {
23 match store.skill_get(id).map_err(|e| format!("{what}: {e}"))? {
24 Some(s) if s.is_global => {}
25 Some(_) => return Err("FORBIDDEN: only catalog skills have app files".to_string()),
26 None => return Err(format!("{what}: no skill {id}")),
27 }
28 store.skill_app_get(id).map_err(|e| format!("{what}: {e}"))?.map(|_| ()).ok_or_else(|| format!("{what}: {id} is not a computer-use skill"))
29}
30
31fn png_data_url(bytes: &[u8]) -> Option<String> {
33 use base64::Engine as _;
34 bytes
35 .starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A])
36 .then(|| format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes)))
37}
38
39fn register_app_file(engine: &Arc<WshRpcEngine>, state: &AppState) {
40 let identity_store = state.identity_store.clone();
41 engine.register_typed(COMMAND_SKILL_CATALOG_APP_FILE, move |req: CommandSkillCatalogAppFileData, _ctx| {
42 let identity_store = identity_store.clone();
43 async move {
44 const E: &str = "skill.catalog.app_file";
45 global_app_skill(&identity_store, &req.skill_id, E)?;
46 let f = identity_store
47 .skill_file_get(&req.skill_id, &req.path)
48 .map_err(|e| format!("{E}: {e}"))?
49 .ok_or_else(|| format!("{E}: no file {} in that skill", req.path))?;
50 let Some(bytes) = f.image else {
51 return Ok(SkillAppFile { path: f.path, text: f.content, image_data_url: None });
52 };
53 let data_url = png_data_url(&bytes).ok_or_else(|| format!("{E}: {} is not a PNG image", req.path))?;
54 Ok(SkillAppFile { path: f.path, text: String::new(), image_data_url: Some(data_url) })
55 }
56 });
57}
58
59fn register_app_script(engine: &Arc<WshRpcEngine>, state: &AppState) {
60 let identity_store = state.identity_store.clone();
61 let broker = state.broker.clone();
62 engine.register_typed(COMMAND_SKILL_CATALOG_APP_SCRIPT, move |req: CommandSkillCatalogAppScriptData, _ctx| {
63 let identity_store = identity_store.clone();
64 let broker = broker.clone();
65 async move {
66 const E: &str = "skill.catalog.app_script";
67 global_app_skill(&identity_store, &req.skill_id, E)?;
68 let approval = if req.approved { ScriptApproval::Approve { reviewed_sha256: &req.sha256 } } else { ScriptApproval::Revoke };
69 match identity_store.skill_script_set_approved(&req.skill_id, &req.path, approval, now_ms()).map_err(|e| format!("{E}: {e}"))? {
70 ScriptOutcome::Done => {}
71 ScriptOutcome::NotAScript => return Err(format!("{E}: {} is not a script of that skill", req.path)),
72 ScriptOutcome::Changed => return Err(format!("{E}: {} is not the text you reviewed; it was replaced, so review it again", req.path)),
73 ScriptOutcome::OtherAuthor => {
74 return Err(format!("{E}: this skill is not signed by the key its publisher is pinned to: a different author, not an update"));
75 }
76 }
77 tracing::info!(skill = %req.skill_id, path = %req.path, approved = req.approved, "skill: a script was {} in Memory", if req.approved { "approved" } else { "revoked" });
78 broker.publish_event::<crate::backend::mps_events::SkillsChanged>(&(), vec![], 0);
79 Ok(SkillAppScriptResult { approved: req.approved })
80 }
81 });
82}
83
84fn write_unused(dir: &std::path::Path, filename: &str, bytes: &[u8]) -> std::io::Result<std::path::PathBuf> {
88 use std::io::{ErrorKind, Write};
89 if filename.contains(['/', '\\', ':']) || filename.contains("..") || filename.is_empty() {
91 return Err(std::io::Error::new(ErrorKind::InvalidInput, format!("{filename:?} is not a plain file name")));
92 }
93 let (stem, ext) = filename.rsplit_once('.').unwrap_or((filename, ""));
94 for n in 1..1000 {
95 let path = if n == 1 { dir.join(filename) } else { dir.join(format!("{stem} ({n}).{ext}")) };
96 match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) {
97 Ok(mut file) => {
98 file.write_all(bytes)?;
99 return Ok(path);
100 }
101 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
102 Err(e) => return Err(e),
103 }
104 }
105 Err(std::io::Error::new(ErrorKind::AlreadyExists, "there are 999 files with that name already"))
106}
107
108fn downloads_dir() -> Option<std::path::PathBuf> {
111 dirs::download_dir().or_else(|| {
112 let home = dirs::home_dir()?;
113 let conventional = home.join("Downloads");
114 Some(if conventional.is_dir() { conventional } else { home })
115 })
116}
117
118fn register_export(engine: &Arc<WshRpcEngine>, state: &AppState) {
119 let identity_store = state.identity_store.clone();
120 engine.register_typed(COMMAND_SKILL_CATALOG_EXPORT, move |req: CommandSkillCatalogExportData, _ctx| {
121 let identity_store = identity_store.clone();
122 async move {
123 const E: &str = "skill.catalog.export";
124 global_app_skill(&identity_store, &req.skill_id, E)?;
125 let exported = crate::backend::skill_file::export(&identity_store, &req.skill_id).map_err(|e| format!("{E}: {e}"))?;
126 let dir = downloads_dir().ok_or_else(|| format!("{E}: this computer has no Downloads or home folder"))?;
127 let path = write_unused(&dir, &exported.filename, &exported.bytes).map_err(|e| format!("{E}: {}: {e}", dir.display()))?;
128 tracing::info!(skill = %req.skill_id, path = %path.display(), signed = exported.signed, "skill: exported as a .skill file");
129 Ok(SkillExportResult { path: path.to_string_lossy().to_string(), signed: exported.signed })
130 }
131 });
132}
133
134#[cfg(test)]
135#[path = "skill_app_rpc_tests.rs"]
136mod tests;