agentmux_srv_core/backend/
skill_import.rs1use agentmux_common::win32::NoWindow;
13use std::path::{Path, PathBuf};
14use std::time::Duration;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Candidate {
19 pub key: String,
22 pub name: String,
23 pub description: String,
24 pub content: String,
26 pub app: Option<Box<crate::backend::computer_use_skill::Bundle>>,
28}
29
30#[derive(Debug, Default)]
32pub struct Scan {
33 pub candidates: Vec<Candidate>,
34 pub warnings: Vec<String>,
35 capped: bool,
37}
38
39const MAX_FILE_BYTES: u64 = 256 * 1024;
40const MAX_CANDIDATES: usize = 100;
41const MAX_DEPTH: usize = 4;
42const GIT_TIMEOUT: Duration = Duration::from_secs(90);
43const URL_TIMEOUT: Duration = Duration::from_secs(20);
44
45pub fn parse_skill_md(text: &str, fallback_name: &str) -> (String, String, String) {
49 let text = text.replace("\r\n", "\n");
50 let Some(rest) = text.strip_prefix("---\n") else {
51 return (fallback_name.to_string(), String::new(), text);
52 };
53 let (front, body) = match rest.find("\n---") {
54 Some(end) => {
55 let after = &rest[end + 4..];
56 let after = after.strip_prefix('\n').unwrap_or(after);
57 (&rest[..end], after.trim_start_matches('\n'))
58 }
59 None => return (fallback_name.to_string(), String::new(), text),
60 };
61 let lines: Vec<&str> = front.lines().collect();
62 let (mut name, mut description) = (String::new(), String::new());
63 let mut i = 0;
64 while i < lines.len() {
65 let line = lines[i];
66 i += 1;
67 if line.starts_with(' ') || line.starts_with('\t') {
68 continue;
69 }
70 let Some((key, value)) = line.split_once(':') else { continue };
71 let value = value.trim();
72 let mut collect_block = |style: &str| {
73 let folded = style.starts_with('>');
74 let mut parts: Vec<&str> = Vec::new();
75 while i < lines.len() && (lines[i].starts_with(' ') || lines[i].starts_with('\t') || lines[i].trim().is_empty()) {
76 parts.push(lines[i].trim());
77 i += 1;
78 }
79 let parts: Vec<&str> = parts.into_iter().filter(|p| !p.is_empty()).collect();
80 parts.join(if folded { " " } else { "\n" })
81 };
82 let is_block = value.starts_with('>') || value.starts_with('|');
83 let value = if is_block { collect_block(value) } else { unquote(value) };
84 match key.trim() {
85 "name" => name = value,
86 "description" => description = value,
87 _ => {}
88 }
89 }
90 let name = if name.trim().is_empty() { fallback_name.to_string() } else { name.trim().to_string() };
91 (name, description.trim().to_string(), body.to_string())
92}
93
94fn unquote(v: &str) -> String {
95 if v.len() >= 2 && v.starts_with('"') && v.ends_with('"') {
96 if let Ok(s) = serde_json::from_str::<String>(v) {
97 return s;
98 }
99 }
100 if v.len() >= 2 && ((v.starts_with('\'') && v.ends_with('\'')) || (v.starts_with('"') && v.ends_with('"'))) {
101 return v[1..v.len() - 1].replace("''", "'");
102 }
103 v.to_string()
104}
105
106fn read_candidate(file: &Path, key: &str, fallback_name: &str, warnings: &mut Vec<String>) -> Option<Candidate> {
107 match std::fs::metadata(file) {
108 Ok(m) if m.len() > MAX_FILE_BYTES => {
109 warnings.push(format!("{key}: larger than {} KB, skipped", MAX_FILE_BYTES / 1024));
110 return None;
111 }
112 Err(e) => {
113 warnings.push(format!("{key}: {e}"));
114 return None;
115 }
116 _ => {}
117 }
118 let text = match std::fs::read_to_string(file) {
119 Ok(t) => t,
120 Err(e) => {
121 warnings.push(format!("{key}: not readable as text ({e}), skipped"));
122 return None;
123 }
124 };
125 let (name, description, content) = parse_skill_md(&text, fallback_name);
126 Some(Candidate { key: key.to_string(), name, description, content, app: None })
127}
128
129pub fn scan_dir(root: &Path) -> Result<Scan, String> {
132 let root_name = root.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
133 scan_dir_named(root, &root_name)
134}
135
136fn scan_dir_named(root: &Path, root_name: &str) -> Result<Scan, String> {
139 let meta = std::fs::symlink_metadata(root).map_err(|e| format!("{}: {e}", root.display()))?;
140 let mut scan = Scan::default();
141 if meta.file_type().is_symlink() {
142 return Err(format!("{} is a symbolic link", root.display()));
143 }
144 if meta.is_file() {
145 let stem = root.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
146 let fallback = if stem.eq_ignore_ascii_case("skill") {
147 root.parent().and_then(|p| p.file_name()).map(|s| s.to_string_lossy().to_string()).unwrap_or(stem)
148 } else {
149 stem
150 };
151 scan.candidates.extend(read_candidate(root, "", &fallback, &mut scan.warnings));
152 return Ok(scan);
153 }
154 walk(root, root, root_name, 0, &mut scan);
155 if scan.capped {
156 scan.warnings.push(format!("only the first {MAX_CANDIDATES} skills are shown; import the rest from a smaller folder"));
157 }
158 scan.candidates.sort_by(|a, b| a.key.cmp(&b.key));
159 Ok(scan)
160}
161
162fn walk(root: &Path, dir: &Path, dir_name: &str, depth: usize, scan: &mut Scan) {
163 let skill_md = dir.join("SKILL.md");
164 if std::fs::symlink_metadata(&skill_md).map(|m| m.is_file()).unwrap_or(false) {
165 if scan.candidates.len() >= MAX_CANDIDATES {
166 scan.capped = true;
167 return;
168 }
169 let key = dir.strip_prefix(root).map(|p| p.to_string_lossy().replace('\\', "/")).unwrap_or_default();
170 if dir.join(crate::backend::computer_use_skill::MANIFEST).is_file() {
173 match crate::backend::computer_use_skill::read_folder(dir) {
174 Ok(b) => scan.candidates.push(Candidate {
175 key,
176 name: b.name.clone(),
177 description: b.description.clone(),
178 content: b.content.clone(),
179 app: Some(Box::new(b)),
180 }),
181 Err(e) => scan.warnings.push(format!("{key}: not imported as a computer-use skill: {e}")),
182 }
183 return;
184 }
185 scan.candidates.extend(read_candidate(&skill_md, &key, dir_name, &mut scan.warnings));
186 return;
187 }
188 if depth >= MAX_DEPTH {
189 return;
190 }
191 let Ok(entries) = std::fs::read_dir(dir) else { return };
192 let mut dirs: Vec<PathBuf> = entries
193 .flatten()
194 .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
195 .map(|e| e.path())
196 .filter(|p| !matches!(p.file_name().and_then(|n| n.to_str()), Some(".git" | "node_modules" | "target")))
197 .collect();
198 dirs.sort();
199 for sub in dirs {
200 let name = sub.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
201 walk(root, &sub, &name, depth + 1, scan);
202 }
203}
204
205fn blocked_ip(ip: std::net::IpAddr) -> bool {
209 use std::net::IpAddr;
210 match ip {
211 IpAddr::V4(v4) => {
212 let o = v4.octets();
213 v4.is_loopback()
214 || v4.is_private()
215 || v4.is_link_local()
216 || v4.is_unspecified()
217 || v4.is_broadcast()
218 || v4.is_multicast()
219 || v4.is_documentation()
220 || o[0] == 0
221 || (o[0] == 100 && (o[1] & 0xc0) == 64) || o[0] >= 240
223 }
224 IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
225 Some(v4) => blocked_ip(IpAddr::V4(v4)),
226 None => {
227 let s = v6.segments();
228 v6.is_loopback()
229 || v6.is_unspecified()
230 || v6.is_multicast()
231 || (s[0] & 0xfe00) == 0xfc00 || (s[0] & 0xffc0) == 0xfe80 || (s[0] == 0x64 && s[1] == 0xff9b) }
235 },
236 }
237}
238
239fn check_url(parsed: &url::Url) -> Result<(), String> {
242 if parsed.scheme() != "https" {
243 return Err("only https:// sources are accepted".to_string());
244 }
245 if !parsed.username().is_empty() || parsed.password().is_some() {
246 return Err("a URL with a user name or password is not accepted".to_string());
247 }
248 match parsed.host() {
249 None => Err("the URL has no host".to_string()),
250 Some(url::Host::Domain(d)) if d.eq_ignore_ascii_case("localhost") || d.to_ascii_lowercase().ends_with(".localhost") => {
251 Err("a local address is not accepted".to_string())
252 }
253 Some(url::Host::Ipv4(ip)) if blocked_ip(ip.into()) => Err("a local address is not accepted".to_string()),
254 Some(url::Host::Ipv6(ip)) if blocked_ip(ip.into()) => Err("a local address is not accepted".to_string()),
255 _ => Ok(()),
256 }
257}
258
259fn https_url(raw: &str) -> Result<url::Url, String> {
260 let parsed = url::Url::parse(raw.trim()).map_err(|e| format!("not a valid URL: {e}"))?;
261 check_url(&parsed)?;
262 Ok(parsed)
263}
264
265struct PublicOnlyResolver;
269
270impl reqwest::dns::Resolve for PublicOnlyResolver {
271 fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
272 Box::pin(async move {
273 let found: Vec<std::net::SocketAddr> = tokio::net::lookup_host((name.as_str(), 443)).await?.collect();
274 let allowed: Vec<std::net::SocketAddr> = found.into_iter().filter(|a| !blocked_ip(a.ip())).collect();
275 if allowed.is_empty() {
276 let e: Box<dyn std::error::Error + Send + Sync> = "that name only points at local addresses".into();
277 return Err(e);
278 }
279 Ok(Box::new(allowed.into_iter()) as reqwest::dns::Addrs)
280 })
281 }
282}
283
284pub async fn fetch_url(raw: &str) -> Result<Scan, String> {
286 let parsed = https_url(raw)?;
287 let client = crate::http_client::builder()
288 .timeout(URL_TIMEOUT)
289 .dns_resolver(std::sync::Arc::new(PublicOnlyResolver))
290 .redirect(reqwest::redirect::Policy::custom(|attempt| {
291 if attempt.previous().len() >= 3 {
292 attempt.error("too many redirects")
293 } else if let Err(why) = check_url(attempt.url()) {
294 attempt.error(format!("redirected somewhere not accepted: {why}"))
295 } else {
296 attempt.follow()
297 }
298 }))
299 .build()
300 .map_err(|e| e.to_string())?;
301 let mut resp = client.get(parsed.clone()).send().await.map_err(|e| format!("fetch failed: {e}"))?;
302 if !resp.status().is_success() {
303 return Err(format!("fetch failed: HTTP {}", resp.status()));
304 }
305 let too_big = || format!("the file is larger than {} KB", MAX_FILE_BYTES / 1024);
306 if resp.content_length().map(|n| n > MAX_FILE_BYTES).unwrap_or(false) {
307 return Err(too_big());
308 }
309 let mut bytes: Vec<u8> = Vec::new();
311 while let Some(chunk) = resp.chunk().await.map_err(|e| format!("fetch failed: {e}"))? {
312 if (bytes.len() + chunk.len()) as u64 > MAX_FILE_BYTES {
313 return Err(too_big());
314 }
315 bytes.extend_from_slice(&chunk);
316 }
317 let text = String::from_utf8(bytes).map_err(|_| "the file is not UTF-8 text".to_string())?;
318 let segments: Vec<&str> = parsed.path_segments().map(|s| s.filter(|p| !p.is_empty()).collect()).unwrap_or_default();
319 let last = segments.last().copied().unwrap_or("skill");
320 let stem = last.strip_suffix(".md").unwrap_or(last);
321 let fallback = if stem.eq_ignore_ascii_case("skill") && segments.len() >= 2 { segments[segments.len() - 2] } else { stem };
322 let (name, description, content) = parse_skill_md(&text, fallback);
323 Ok(Scan { candidates: vec![Candidate { key: String::new(), name, description, content, app: None }], warnings: vec![], capped: false })
324}
325
326fn valid_git_ref(r: &str) -> bool {
327 !r.is_empty()
328 && !r.starts_with('-')
329 && !r.contains("..")
330 && r.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '/' | '-'))
331}
332
333const MAX_CLONE_BYTES: u64 = 200 * 1024 * 1024;
335
336fn dir_bytes(dir: &Path) -> u64 {
338 let mut total = 0;
339 let mut stack = vec![dir.to_path_buf()];
340 while let Some(d) = stack.pop() {
341 let Ok(entries) = std::fs::read_dir(&d) else { continue };
342 for e in entries.flatten() {
343 match e.file_type() {
344 Ok(t) if t.is_dir() => stack.push(e.path()),
345 Ok(t) if t.is_file() => total += e.metadata().map(|m| m.len()).unwrap_or(0),
346 _ => {}
347 }
348 }
349 }
350 total
351}
352
353pub async fn fetch_git(raw: &str, git_ref: &str) -> Result<Scan, String> {
357 use tokio::io::AsyncReadExt;
358 let parsed = https_url(raw)?;
359 let git_ref = git_ref.trim();
360 if !git_ref.is_empty() && !valid_git_ref(git_ref) {
361 return Err("that branch or tag name is not accepted".to_string());
362 }
363 if let Some(url::Host::Domain(host)) = parsed.host() {
366 let found = tokio::net::lookup_host((host, 443)).await.map_err(|e| format!("could not find {host}: {e}"))?;
367 if found.into_iter().any(|a| blocked_ip(a.ip())) {
368 return Err("that name points at a local address, which is not accepted".to_string());
369 }
370 }
371 let dir = std::env::temp_dir().join(format!("agentmux-skill-import-{}", uuid::Uuid::new_v4()));
372 let mut cmd = tokio::process::Command::new("git");
373 crate::backend::pane_env::sanitize_external_command(&mut cmd);
374 cmd.no_window()
375 .kill_on_drop(true)
376 .env("GIT_TERMINAL_PROMPT", "0")
377 .env("GIT_ASKPASS", "")
378 .args(["-c", "protocol.allow=never", "-c", "protocol.https.allow=always", "-c", "http.followRedirects=false"])
379 .args(["clone", "--depth", "1", "--single-branch", "--no-tags"]);
380 if !git_ref.is_empty() {
381 cmd.args(["--branch", git_ref]);
382 }
383 cmd.arg("--").arg(parsed.as_str()).arg(&dir);
384 cmd.stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped());
385 let result = async {
386 let mut child = cmd.spawn().map_err(|e| format!("could not run git: {e}"))?;
387 let mut stderr = child.stderr.take().expect("stderr is piped");
388 let said = tokio::spawn(async move {
389 let mut s = String::new();
390 let _ = stderr.read_to_string(&mut s).await;
391 s
392 });
393 let started = std::time::Instant::now();
394 let status = loop {
395 tokio::select! {
396 status = child.wait() => break status.map_err(|e| format!("could not run git: {e}"))?,
397 _ = tokio::time::sleep(Duration::from_millis(500)) => {
398 let why = if started.elapsed() > GIT_TIMEOUT {
399 Some(format!("git clone did not finish in {} s", GIT_TIMEOUT.as_secs()))
400 } else if dir_bytes(&dir) > MAX_CLONE_BYTES {
401 Some(format!("the repository is larger than {} MB", MAX_CLONE_BYTES / 1024 / 1024))
402 } else {
403 None
404 };
405 if let Some(why) = why {
406 let _ = child.kill().await;
407 return Err(why);
408 }
409 }
410 }
411 };
412 if !status.success() {
413 let said = said.await.unwrap_or_default();
414 return Err(format!("git clone failed: {}", said.trim().lines().last().unwrap_or("")));
415 }
416 let repo = parsed.path_segments().and_then(|s| s.filter(|p| !p.is_empty()).last()).unwrap_or("skill");
417 scan_dir_named(&dir, repo.strip_suffix(".git").unwrap_or(repo))
418 }
419 .await;
420 let _ = std::fs::remove_dir_all(&dir);
421 result
422}
423
424#[cfg(test)]
425#[path = "skill_import_tests.rs"]
426mod tests;