agent_hub_runtime/core/
skill_metadata.rs1use std::path::Path;
2
3pub struct SkillMeta {
4 pub name: Option<String>,
5 pub description: Option<String>,
6 pub version: Option<String>,
7}
8
9fn read_named_file_exact(dir: &Path, target_name: &str) -> Option<String> {
10 let entries = std::fs::read_dir(dir).ok()?;
11 for entry in entries.flatten() {
12 if !entry.file_type().ok()?.is_file() {
13 continue;
14 }
15 if entry.file_name().to_string_lossy() == target_name {
16 return std::fs::read_to_string(entry.path()).ok();
17 }
18 }
19 None
20}
21
22fn has_named_file_exact(dir: &Path, target_name: &str) -> bool {
23 let Ok(entries) = std::fs::read_dir(dir) else {
24 return false;
25 };
26 entries.flatten().any(|entry| {
27 entry.file_type().map(|ft| ft.is_file()).unwrap_or(false)
28 && entry.file_name().to_string_lossy() == target_name
29 })
30}
31
32pub fn parse_skill_md(dir: &Path) -> SkillMeta {
33 parse_skill_md_with_candidates(dir, &["SKILL.md", "skill.md"])
34}
35
36fn parse_skill_md_with_candidates(dir: &Path, candidates: &[&str]) -> SkillMeta {
37 for candidate in candidates {
38 if let Some(content) = read_named_file_exact(dir, candidate) {
39 return parse_frontmatter(&content);
40 }
41 }
42 SkillMeta {
43 name: None,
44 description: None,
45 version: None,
46 }
47}
48
49pub(crate) fn parse_frontmatter(content: &str) -> SkillMeta {
50 let trimmed = content.trim();
51 if !trimmed.starts_with("---") {
52 return SkillMeta {
53 name: None,
54 description: None,
55 version: None,
56 };
57 }
58
59 let rest = &trimmed[3..];
60 if let Some(end) = rest.find("---") {
61 let yaml_str = &rest[..end];
62 if let Ok(yaml) = serde_yaml::from_str::<serde_yaml::Value>(yaml_str) {
63 let name = yaml
64 .get("name")
65 .and_then(|v| v.as_str())
66 .map(|s| s.to_string());
67 let description = yaml
68 .get("description")
69 .and_then(|v| v.as_str())
70 .map(|s| s.to_string());
71 let version = yaml
72 .get("version")
73 .and_then(|v| v.as_str())
74 .or_else(|| yaml.get("metadata")?.get("version")?.as_str())
75 .map(|s| s.to_string());
76 return SkillMeta {
77 name,
78 description,
79 version,
80 };
81 }
82 }
83
84 SkillMeta {
85 name: None,
86 description: None,
87 version: None,
88 }
89}
90
91pub(crate) const SKILL_DIR_MARKERS: &[&str] = &["SKILL.md", "skill.md"];
93
94pub fn is_valid_skill_dir(dir: &Path) -> bool {
97 dir.is_dir()
98 && SKILL_DIR_MARKERS
99 .iter()
100 .any(|name| has_named_file_exact(dir, name))
101}
102
103const WINDOWS_RESERVED: &[char] = &['<', '>', ':', '"', '/', '\\', '|', '?', '*'];
105
106const WINDOWS_RESERVED_BASENAMES: &[&str] = &[
108 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
109 "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
110];
111
112pub fn sanitize_skill_name(name: &str) -> Option<String> {
124 let last = std::path::Path::new(name)
126 .file_name()
127 .map(|n| n.to_string_lossy().to_string())?;
128
129 if last == ".." || last == "." {
132 return None;
133 }
134
135 let clean: String = last
139 .chars()
140 .map(|c| {
141 if c.is_control() || WINDOWS_RESERVED.contains(&c) {
142 '_'
143 } else {
144 c
145 }
146 })
147 .collect();
148
149 let trimmed = clean.trim().trim_end_matches('.');
152 if trimmed.is_empty() {
153 None
154 } else {
155 let reserved = trimmed
156 .split('.')
157 .next()
158 .map(|base| base.to_ascii_uppercase())
159 .map(|upper| WINDOWS_RESERVED_BASENAMES.contains(&upper.as_str()))
160 .unwrap_or(false);
161
162 if reserved {
163 Some(format!("_{}", trimmed))
164 } else {
165 Some(trimmed.to_string())
166 }
167 }
168}
169
170pub fn infer_skill_name(dir: &Path) -> String {
171 let meta = parse_skill_md(dir);
172 if let Some(name) = meta.name {
173 if let Some(sanitized) = sanitize_skill_name(&name) {
174 return sanitized;
175 }
176 }
177 dir.file_name()
178 .map(|n| n.to_string_lossy().to_string())
179 .unwrap_or_else(|| "unknown-skill".to_string())
180}
181
182pub fn update_skill_md_name(dir: &Path, new_name: &str) -> anyhow::Result<bool> {
186 for candidate in SKILL_DIR_MARKERS {
187 let Some(content) = read_named_file_exact(dir, candidate) else {
188 continue;
189 };
190 let trimmed = content.trim_start();
191 if !trimmed.starts_with("---") {
192 continue;
193 }
194 let rest = &trimmed[3..];
195 let Some(end) = rest.find("---") else {
196 continue;
197 };
198 let fm_start = content.find("---").unwrap();
199 let fm_body_start = fm_start + 3;
200 let fm_body_end = fm_body_start + end;
201 let fm_body = &content[fm_body_start..fm_body_end];
202 let mut updated_lines = Vec::new();
203 let mut found = false;
204 for line in fm_body.lines() {
205 let stripped = line.trim_start();
206 if line.starts_with("name:") && !found {
207 let indent = &line[..line.len() - stripped.len()];
209 let quoted_name = serde_json::to_string(new_name)?;
210 updated_lines.push(format!("{indent}name: {quoted_name}"));
211 found = true;
212 } else {
213 updated_lines.push(line.to_string());
214 }
215 }
216 if !found {
217 continue;
218 }
219 let trailing = if fm_body.ends_with('\n') { "\n" } else { "" };
221 let new_body = updated_lines.join("\n") + trailing;
222 let new_content = format!(
223 "{}{}{}",
224 &content[..fm_body_start],
225 new_body,
226 &content[fm_body_end..],
227 );
228 let file_path = dir.join(candidate);
230 std::fs::write(&file_path, new_content)?;
231 return Ok(true);
232 }
233 Ok(false)
234}
235
236#[cfg(test)]
237mod tests;