|
| 1 | +//! The `SKILL.md` skills in a local agent harness's skill folders, for the |
| 2 | +//! composer's `/` menu. Reads each skill's front matter, never its body. |
| 3 | +use std::io::Read as _; |
| 4 | +use std::path::Path; |
| 5 | + |
| 6 | +const MAX_ROOTS: usize = 8; |
| 7 | +const MAX_ENTRIES: usize = 4096; |
| 8 | +const MAX_SKILLS: usize = 512; |
| 9 | +/// Front matter must end within this; a skill whose block doesn't is skipped. |
| 10 | +const HEAD_BYTES: u64 = 16 * 1024; |
| 11 | + |
| 12 | +#[derive(Debug, PartialEq, Eq, serde::Serialize)] |
| 13 | +#[serde(rename_all = "camelCase")] |
| 14 | +pub(crate) struct LocalSkill { |
| 15 | + name: String, |
| 16 | + description: String, |
| 17 | + path: String, |
| 18 | + display_path: String, |
| 19 | +} |
| 20 | + |
| 21 | +/// `name` and `description` from leading `---` front matter: one-line |
| 22 | +/// scalars, or a folded or literal block for the description. |
| 23 | +fn front_matter(text: &str) -> Option<(String, String)> { |
| 24 | + let mut lines = text.lines(); |
| 25 | + if lines.next()?.trim_end() != "---" { |
| 26 | + return None; |
| 27 | + } |
| 28 | + let (mut name, mut description, mut block) = (None, String::new(), false); |
| 29 | + for line in lines { |
| 30 | + if line.trim_end() == "---" { |
| 31 | + return name.map(|name| (name, description)); |
| 32 | + } |
| 33 | + if block && line.starts_with([' ', '\t']) { |
| 34 | + if !description.is_empty() { |
| 35 | + description.push(' '); |
| 36 | + } |
| 37 | + description.push_str(line.trim()); |
| 38 | + continue; |
| 39 | + } |
| 40 | + block = false; |
| 41 | + let Some((key, value)) = line.split_once(':') else { |
| 42 | + continue; |
| 43 | + }; |
| 44 | + let value = value.trim(); |
| 45 | + let unquoted = [('"', '"'), ('\'', '\'')] |
| 46 | + .iter() |
| 47 | + .find_map(|(open, close)| value.strip_prefix(*open)?.strip_suffix(*close)) |
| 48 | + .unwrap_or(value); |
| 49 | + match key { |
| 50 | + "name" if !unquoted.is_empty() => name = Some(unquoted.to_owned()), |
| 51 | + "description" => { |
| 52 | + block = value.starts_with(['>', '|']); |
| 53 | + description = if block { |
| 54 | + String::new() |
| 55 | + } else { |
| 56 | + unquoted.to_owned() |
| 57 | + }; |
| 58 | + } |
| 59 | + _ => {} |
| 60 | + } |
| 61 | + } |
| 62 | + None |
| 63 | +} |
| 64 | + |
| 65 | +/// Each `<root>/<folder>/SKILL.md` with a named front matter, by name. The |
| 66 | +/// first root to name a skill wins, and a missing root lists nothing. Follows |
| 67 | +/// linked skill folders, as the harnesses do. Reads only; the caller names the |
| 68 | +/// harness's folders. |
| 69 | +pub(crate) fn skills(roots: &[String], home: Option<&Path>) -> Result<Vec<LocalSkill>, String> { |
| 70 | + if roots.len() > MAX_ROOTS { |
| 71 | + return Err("Too many skill folders.".into()); |
| 72 | + } |
| 73 | + let mut found: Vec<LocalSkill> = Vec::new(); |
| 74 | + for root in roots { |
| 75 | + let root = crate::workspace_folder::expand(root.trim(), home); |
| 76 | + if !root.is_absolute() { |
| 77 | + return Err("A skill folder must be absolute or under ~/.".into()); |
| 78 | + } |
| 79 | + let entries = match std::fs::read_dir(&root) { |
| 80 | + Ok(entries) => entries, |
| 81 | + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, |
| 82 | + Err(error) => return Err(format!("Could not list {}: {error}", root.display())), |
| 83 | + }; |
| 84 | + for entry in entries.flatten().take(MAX_ENTRIES) { |
| 85 | + let path = entry.path().join("SKILL.md"); |
| 86 | + let mut head = Vec::new(); |
| 87 | + if std::fs::File::open(&path) |
| 88 | + .and_then(|file| file.take(HEAD_BYTES).read_to_end(&mut head)) |
| 89 | + .is_err() |
| 90 | + { |
| 91 | + continue; |
| 92 | + } |
| 93 | + let Some((name, description)) = front_matter(&String::from_utf8_lossy(&head)) else { |
| 94 | + continue; |
| 95 | + }; |
| 96 | + let (Some(text), Ok(display_path)) = |
| 97 | + (path.to_str(), crate::workspace_folder::display(&path, home)) |
| 98 | + else { |
| 99 | + continue; |
| 100 | + }; |
| 101 | + if found.iter().any(|skill| skill.name == name) { |
| 102 | + continue; |
| 103 | + } |
| 104 | + if found.len() == MAX_SKILLS { |
| 105 | + return Err("There are more than 512 skills.".into()); |
| 106 | + } |
| 107 | + found.push(LocalSkill { |
| 108 | + name, |
| 109 | + description, |
| 110 | + path: text.to_owned(), |
| 111 | + display_path, |
| 112 | + }); |
| 113 | + } |
| 114 | + } |
| 115 | + found.sort_by(|a, b| a.name.cmp(&b.name)); |
| 116 | + Ok(found) |
| 117 | +} |
| 118 | + |
| 119 | +/// Lists skills for the trusted app renderer, which names the folders of the |
| 120 | +/// agent's harness. |
| 121 | +#[tauri::command] |
| 122 | +pub(crate) async fn local_skills_list<R: tauri::Runtime>( |
| 123 | + app: tauri::AppHandle<R>, |
| 124 | + roots: Vec<String>, |
| 125 | +) -> Result<Vec<LocalSkill>, String> { |
| 126 | + use tauri::Manager as _; |
| 127 | + let home = app.path().home_dir().ok(); |
| 128 | + crate::host_files::bounded_listing("Listing skills took too long", move || { |
| 129 | + skills(&roots, home.as_deref()) |
| 130 | + }) |
| 131 | + .await |
| 132 | +} |
| 133 | + |
| 134 | +#[cfg(test)] |
| 135 | +mod tests { |
| 136 | + use super::*; |
| 137 | + |
| 138 | + #[test] |
| 139 | + fn reads_names_and_descriptions_from_front_matter_only() { |
| 140 | + assert_eq!( |
| 141 | + front_matter("---\nname: review\ndescription: \"Reviews a diff\"\n---\nname: body"), |
| 142 | + Some(("review".into(), "Reviews a diff".into())) |
| 143 | + ); |
| 144 | + assert_eq!( |
| 145 | + front_matter("---\nname: 'notes'\ndescription: >-\n Folded\n lines\nother: x\n---\n"), |
| 146 | + Some(("notes".into(), "Folded lines".into())) |
| 147 | + ); |
| 148 | + assert_eq!(front_matter("---\ndescription: unnamed\n---\n"), None); |
| 149 | + assert_eq!(front_matter("name: review\n"), None); |
| 150 | + assert_eq!(front_matter("---\nname: unterminated\n"), None); |
| 151 | + } |
| 152 | + |
| 153 | + #[test] |
| 154 | + fn lists_each_named_skill_once_by_name() { |
| 155 | + let temp = tempfile::tempdir().unwrap(); |
| 156 | + let home = dunce::canonicalize(temp.path()).unwrap(); |
| 157 | + let skill = |root: &str, folder: &str, text: &str| { |
| 158 | + let dir = home.join(root).join(folder); |
| 159 | + std::fs::create_dir_all(&dir).unwrap(); |
| 160 | + std::fs::write(dir.join("SKILL.md"), text).unwrap(); |
| 161 | + }; |
| 162 | + skill( |
| 163 | + ".claude/skills", |
| 164 | + "write", |
| 165 | + "---\nname: write\ndescription: Prose\n---\n", |
| 166 | + ); |
| 167 | + skill(".claude/skills", "plain", "# No front matter\n"); |
| 168 | + skill( |
| 169 | + ".agents/skills", |
| 170 | + "dup", |
| 171 | + "---\nname: write\ndescription: Other\n---\n", |
| 172 | + ); |
| 173 | + skill(".agents/skills", "audit", "---\nname: audit\n---\n"); |
| 174 | + std::fs::write(home.join(".claude/skills/README.md"), "not a skill").unwrap(); |
| 175 | + let roots = ["~/.claude/skills", "~/.agents/skills", "~/.missing/skills"].map(String::from); |
| 176 | + let listed = skills(&roots, Some(&home)).unwrap(); |
| 177 | + let names: Vec<_> = listed.iter().map(|skill| skill.name.as_str()).collect(); |
| 178 | + assert_eq!(names, ["audit", "write"]); |
| 179 | + assert_eq!(listed[1].description, "Prose"); |
| 180 | + assert_eq!(listed[1].display_path, "~/.claude/skills/write/SKILL.md"); |
| 181 | + assert_eq!( |
| 182 | + listed[1].path, |
| 183 | + home.join(".claude/skills/write/SKILL.md").to_str().unwrap() |
| 184 | + ); |
| 185 | + assert!(skills(&["relative".into()], Some(&home)).is_err()); |
| 186 | + assert!(skills(&vec![String::from("~/.claude/skills"); 9], Some(&home)).is_err()); |
| 187 | + } |
| 188 | + |
| 189 | + #[test] |
| 190 | + fn caps_what_one_listing_reads() { |
| 191 | + let temp = tempfile::tempdir().unwrap(); |
| 192 | + let home = dunce::canonicalize(temp.path()).unwrap(); |
| 193 | + let root = home.join("skills"); |
| 194 | + let skill = |folder: &str, text: &str| { |
| 195 | + std::fs::create_dir_all(root.join(folder)).unwrap(); |
| 196 | + std::fs::write(root.join(folder).join("SKILL.md"), text).unwrap(); |
| 197 | + }; |
| 198 | + // Front matter that does not close within the read head is no skill. |
| 199 | + let padding = "x".repeat(HEAD_BYTES as usize); |
| 200 | + skill( |
| 201 | + "long", |
| 202 | + &format!("---\nname: long\ndescription: {padding}\n---\n"), |
| 203 | + ); |
| 204 | + skill("short", "---\nname: short\n---\n"); |
| 205 | + let roots = ["~/skills".to_string()]; |
| 206 | + let names: Vec<_> = skills(&roots, Some(&home)) |
| 207 | + .unwrap() |
| 208 | + .into_iter() |
| 209 | + .map(|skill| skill.name) |
| 210 | + .collect(); |
| 211 | + assert_eq!(names, ["short"]); |
| 212 | + for index in 0..MAX_SKILLS { |
| 213 | + skill(&format!("s{index}"), &format!("---\nname: s{index}\n---\n")); |
| 214 | + } |
| 215 | + assert_eq!( |
| 216 | + skills(&roots, Some(&home)).unwrap_err(), |
| 217 | + "There are more than 512 skills." |
| 218 | + ); |
| 219 | + } |
| 220 | + |
| 221 | + #[cfg(unix)] |
| 222 | + #[test] |
| 223 | + fn follows_a_linked_skill_folder() { |
| 224 | + let temp = tempfile::tempdir().unwrap(); |
| 225 | + let home = dunce::canonicalize(temp.path()).unwrap(); |
| 226 | + let shared = home.join("shared/review"); |
| 227 | + std::fs::create_dir_all(&shared).unwrap(); |
| 228 | + std::fs::write(shared.join("SKILL.md"), "---\nname: review\n---\n").unwrap(); |
| 229 | + std::fs::create_dir_all(home.join(".codex/skills")).unwrap(); |
| 230 | + std::os::unix::fs::symlink(&shared, home.join(".codex/skills/review")).unwrap(); |
| 231 | + let listed = skills(&["~/.codex/skills".into()], Some(&home)).unwrap(); |
| 232 | + assert_eq!(listed.len(), 1); |
| 233 | + assert_eq!(listed[0].display_path, "~/.codex/skills/review/SKILL.md"); |
| 234 | + } |
| 235 | +} |
0 commit comments