1use std::{
9 collections::{BTreeMap, btree_map::Entry},
10 fmt, fs,
11 path::{Path, PathBuf},
12};
13
14use thiserror::Error;
15
16use crate::text;
17
18#[path = "skill/frontmatter.rs"]
19mod frontmatter;
20
21pub use frontmatter::FrontmatterError;
22
23const SKILLS_INTRO: &str = "A skill is a set of local instructions stored in a `SKILL.md` file. The list below is metadata for discovery only; skill bodies stay on disk until needed.";
24const SKILLS_HOW_TO_USE: &str = r#"- If the user explicitly names a skill, including with a `$skill-name` token, use it for that turn.
25- If the task clearly matches a skill description, read that skill's `SKILL.md` before relying on it.
26- Use `read_file` with a bounded line range to read the listed `SKILL.md`; request further ranges only when the task needs them.
27- Resolve relative paths mentioned by `SKILL.md` relative to that skill directory.
28- Read only the referenced files and ranges needed for the task.
29- Do not carry a skill body across unrelated turns unless it remains in raw context or is re-read."#;
30
31#[derive(Debug, Error, Clone, PartialEq, Eq)]
33pub enum SkillError {
34 #[error("{field} must not be blank")]
36 Blank {
37 field: &'static str,
39 },
40 #[error("{field} must be single-line text without control characters")]
42 ControlCharacters {
43 field: &'static str,
45 },
46 #[error("skill path must be relative and must end with SKILL.md: {path}")]
48 InvalidSkillPath {
49 path: String,
51 },
52 #[error("skill {name} is duplicated at {path}")]
54 Duplicate {
55 name: String,
57 path: String,
59 },
60 #[error("skill root is not a directory: {root}")]
62 RootNotDirectory {
63 root: String,
65 },
66 #[error("could not read skill root {root}: {message}")]
68 RootRead {
69 root: String,
71 message: String,
73 },
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct SkillMetadata {
79 name: String,
80 description: String,
81 skill_md_path: PathBuf,
82 root: PathBuf,
83}
84
85impl SkillMetadata {
86 pub fn new(
93 name: impl Into<String>,
94 description: impl Into<String>,
95 skill_md_path: PathBuf,
96 root: PathBuf,
97 ) -> Result<Self, SkillError> {
98 let name = name.into();
99 let name = name.trim();
100 validate_single_line("skill name", name)?;
101 let description = text::collapse_whitespace(&description.into());
102 validate_single_line("skill description", &description)?;
103 validate_skill_path(&skill_md_path)?;
104 Ok(Self {
105 name: name.to_owned(),
106 description,
107 skill_md_path,
108 root,
109 })
110 }
111
112 #[must_use]
114 pub fn name(&self) -> &str {
115 &self.name
116 }
117
118 #[must_use]
120 pub fn description(&self) -> &str {
121 &self.description
122 }
123
124 #[must_use]
126 pub fn skill_md_path(&self) -> &Path {
127 &self.skill_md_path
128 }
129
130 #[must_use]
132 pub fn root(&self) -> &Path {
133 &self.root
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct SkillCatalog {
140 skills: Vec<SkillMetadata>,
141 warnings: Vec<SkillLoadWarning>,
142}
143
144impl SkillCatalog {
145 pub fn load_from_roots<I>(roots: I) -> Result<Self, SkillError>
147 where
148 I: IntoIterator<Item = PathBuf>,
149 {
150 let mut skills = Vec::new();
151 let mut warnings = Vec::new();
152 for root in roots {
153 scan_root(&root, &mut skills, &mut warnings)?;
154 }
155 Self::from_loaded_metadata(skills, warnings)
156 }
157
158 pub fn from_metadata(skills: Vec<SkillMetadata>) -> Result<Self, SkillError> {
160 let mut by_key = BTreeMap::new();
161 for skill in skills {
162 let key = normalized_skill_name(skill.name());
163 match by_key.entry(key) {
164 Entry::Vacant(entry) => {
165 entry.insert(skill);
166 }
167 Entry::Occupied(entry) => {
168 return Err(SkillError::Duplicate {
169 name: entry.get().name().to_owned(),
170 path: skill.skill_md_path.display().to_string(),
171 });
172 }
173 }
174 }
175 Ok(Self {
176 skills: by_key.into_values().collect(),
177 warnings: Vec::new(),
178 })
179 }
180
181 fn from_loaded_metadata(
182 skills: Vec<SkillMetadata>,
183 mut warnings: Vec<SkillLoadWarning>,
184 ) -> Result<Self, SkillError> {
185 let mut by_key: BTreeMap<String, SkillMetadata> = BTreeMap::new();
186 for skill in skills {
187 let key = normalized_skill_name(skill.name());
188 match by_key.entry(key) {
189 Entry::Vacant(entry) => {
190 entry.insert(skill);
191 }
192 Entry::Occupied(_) => warnings.push(SkillLoadWarning::new(
193 skill.skill_md_path.clone(),
194 SkillLoadWarningReason::DuplicateName {
195 name: skill.name().to_owned(),
196 },
197 )),
198 }
199 }
200
201 Ok(Self {
202 skills: by_key.into_values().collect(),
203 warnings,
204 })
205 }
206
207 #[must_use]
209 pub fn is_empty(&self) -> bool {
210 self.skills.is_empty()
211 }
212
213 #[must_use]
215 pub fn skills(&self) -> &[SkillMetadata] {
216 &self.skills
217 }
218
219 #[must_use]
221 pub fn warnings(&self) -> &[SkillLoadWarning] {
222 &self.warnings
223 }
224
225 pub(crate) fn find_by_skill_md_path(&self, path: &str) -> Option<&SkillMetadata> {
226 let target = normalized_skill_path_str(path);
227 self.skills
228 .iter()
229 .find(|skill| normalized_skill_path_display(&skill.skill_md_path) == target)
230 }
231
232 #[must_use]
237 pub fn to_stable_prefix_message_text(&self) -> Option<String> {
238 if self.skills.is_empty() {
239 return None;
240 }
241
242 let mut lines = vec![
243 "## Skills".to_owned(),
244 SKILLS_INTRO.to_owned(),
245 "### Available skills".to_owned(),
246 ];
247 for skill in &self.skills {
248 lines.push(format!(
249 "- {}: {} (file: {})",
250 skill.name,
251 skill.description,
252 normalized_skill_path_display(&skill.skill_md_path)
253 ));
254 }
255 lines.push("### How to use skills".to_owned());
256 lines.push(SKILLS_HOW_TO_USE.to_owned());
257 Some(lines.join("\n"))
258 }
259}
260
261#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct SkillLoadWarning {
264 path: PathBuf,
265 reason: SkillLoadWarningReason,
266}
267
268impl SkillLoadWarning {
269 #[must_use]
271 pub fn new(path: PathBuf, reason: SkillLoadWarningReason) -> Self {
272 Self { path, reason }
273 }
274
275 #[must_use]
277 pub fn path(&self) -> &Path {
278 &self.path
279 }
280
281 #[must_use]
283 pub fn reason(&self) -> &SkillLoadWarningReason {
284 &self.reason
285 }
286}
287
288impl fmt::Display for SkillLoadWarning {
289 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
290 write!(formatter, "{}: {}", self.path.display(), self.reason)
291 }
292}
293
294#[derive(Debug, Clone, PartialEq, Eq, Error)]
296pub enum SkillLoadWarningReason {
297 #[error("failed to read file: {message}")]
299 Read {
300 message: String,
302 },
303 #[error(transparent)]
305 Frontmatter(#[from] FrontmatterError),
306 #[error(transparent)]
308 InvalidMetadata(#[from] SkillError),
309 #[error("duplicate skill name `{name}` was skipped")]
311 DuplicateName {
312 name: String,
314 },
315}
316
317fn validate_single_line(field: &'static str, value: &str) -> Result<(), SkillError> {
318 if value.trim().is_empty() {
319 return Err(SkillError::Blank { field });
320 }
321 if value.chars().any(char::is_control) {
322 return Err(SkillError::ControlCharacters { field });
323 }
324 Ok(())
325}
326
327fn validate_skill_path(path: &Path) -> Result<(), SkillError> {
328 if path.is_absolute() || path.file_name().and_then(|name| name.to_str()) != Some("SKILL.md") {
329 return Err(SkillError::InvalidSkillPath {
330 path: path.display().to_string(),
331 });
332 }
333 Ok(())
334}
335
336fn normalized_skill_name(name: &str) -> String {
337 name.trim().to_ascii_lowercase()
338}
339
340fn normalized_skill_path_display(path: &Path) -> String {
341 normalized_skill_path_str(&path.to_string_lossy())
342}
343
344fn normalized_skill_path_str(path: &str) -> String {
345 path.replace('\\', "/")
346}
347
348const SKILLS_FILENAME: &str = "SKILL.md";
349const MAX_SCAN_DEPTH: usize = 6;
350const MAX_SKILL_DIRS_PER_ROOT: usize = 2_000;
351
352fn scan_root(
353 root: &Path,
354 skills: &mut Vec<SkillMetadata>,
355 warnings: &mut Vec<SkillLoadWarning>,
356) -> Result<(), SkillError> {
357 if !root.exists() {
358 return Ok(());
359 }
360 if !root.is_dir() {
361 return Err(SkillError::RootNotDirectory {
362 root: root.display().to_string(),
363 });
364 }
365
366 let mut scanned_dirs = 0usize;
367 scan_dir(
368 root,
369 root,
370 Path::new(""),
371 0,
372 &mut scanned_dirs,
373 skills,
374 warnings,
375 )
376}
377
378fn scan_dir(
379 root: &Path,
380 dir: &Path,
381 relative_dir: &Path,
382 depth: usize,
383 scanned_dirs: &mut usize,
384 skills: &mut Vec<SkillMetadata>,
385 warnings: &mut Vec<SkillLoadWarning>,
386) -> Result<(), SkillError> {
387 if depth > MAX_SCAN_DEPTH || *scanned_dirs >= MAX_SKILL_DIRS_PER_ROOT {
388 return Ok(());
389 }
390 *scanned_dirs += 1;
391
392 let skill_md = dir.join(SKILLS_FILENAME);
393 if skill_md.is_file() {
394 let relative_skill_md = relative_dir.join(SKILLS_FILENAME);
395 match parse_skill_file(&skill_md, &relative_skill_md, root) {
396 Ok(metadata) => skills.push(metadata),
397 Err(reason) => warnings.push(SkillLoadWarning::new(skill_md, reason)),
398 }
399 }
400
401 let entries = fs::read_dir(dir).map_err(|source| SkillError::RootRead {
402 root: root.display().to_string(),
403 message: source.to_string(),
404 })?;
405 let mut child_dirs = Vec::new();
406 for entry in entries {
407 let entry = entry.map_err(|source| SkillError::RootRead {
408 root: root.display().to_string(),
409 message: source.to_string(),
410 })?;
411 let file_type = entry.file_type().map_err(|source| SkillError::RootRead {
412 root: root.display().to_string(),
413 message: source.to_string(),
414 })?;
415 if file_type.is_dir() {
416 child_dirs.push((entry.path(), relative_dir.join(entry.file_name())));
417 }
418 }
419 child_dirs.sort();
420 for (child_dir, child_relative_dir) in child_dirs {
421 scan_dir(
422 root,
423 &child_dir,
424 &child_relative_dir,
425 depth.saturating_add(1),
426 scanned_dirs,
427 skills,
428 warnings,
429 )?;
430 }
431
432 Ok(())
433}
434
435fn parse_skill_file(
440 skill_md: &Path,
441 relative_skill_md: &Path,
442 root: &Path,
443) -> Result<SkillMetadata, SkillLoadWarningReason> {
444 let text = fs::read_to_string(skill_md).map_err(|source| SkillLoadWarningReason::Read {
445 message: source.to_string(),
446 })?;
447 let fields = frontmatter::parse(&text)?;
448 SkillMetadata::new(
449 fields.name(),
450 fields.description(),
451 relative_skill_md.to_path_buf(),
452 root.to_path_buf(),
453 )
454 .map_err(SkillLoadWarningReason::InvalidMetadata)
455}
456
457#[cfg(test)]
458#[path = "skill/tests.rs"]
459mod tests;