1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3
4use serde::{Deserialize, Serialize};
5
6const SKILL_MAX_CHARS: usize = 10_000;
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct Skill {
19 pub name: String,
21 pub description: String,
23 pub argument_hint: Option<String>,
25 pub compatibility: Option<String>,
27 pub disable_model_invocation: bool,
29 pub license: Option<String>,
31 pub metadata: Option<HashMap<String, String>>,
33 pub user_invocable: bool,
35 pub content: String,
37 pub path: PathBuf,
39 pub source: SkillSource,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45pub enum SkillSource {
46 Personal,
49 Project,
51}
52
53struct ParsedFrontmatter {
65 name: Option<String>,
66 description: Option<String>,
67 argument_hint: Option<String>,
68 compatibility: Option<String>,
69 disable_model_invocation: bool,
70 license: Option<String>,
71 metadata: Option<HashMap<String, String>>,
72 user_invocable: bool,
73}
74
75fn parse_frontmatter(text: &str) -> ParsedFrontmatter {
79 let mut name = None;
80 let mut description = None;
81 let mut argument_hint = None;
82 let mut compatibility = None;
83 let mut disable_model_invocation = false;
84 let mut license = None;
85 let mut user_invocable = true;
86 let mut metadata: Option<HashMap<String, String>> = None;
87
88 let lines: Vec<&str> = text.lines().collect();
89 let mut i = 0;
90
91 while i < lines.len() {
92 let line = lines[i];
93
94 if line.trim().is_empty() {
96 i += 1;
97 continue;
98 }
99
100 if line.starts_with(" ") || line.starts_with("\t") {
102 if let Some(ref mut map) = metadata {
104 let trimmed = line.trim();
105 if let Some((k, v)) = trimmed.split_once(':') {
106 map.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
107 }
108 }
109 i += 1;
110 continue;
111 }
112
113 if let Some((key, value)) = line.split_once(':') {
115 let key = key.trim();
116 let value = value.trim();
117
118 match key {
119 "name" => name = Some(value.trim_matches('"').to_string()),
120 "description" => description = Some(value.trim_matches('"').to_string()),
121 "argument-hint" => argument_hint = Some(value.trim_matches('"').to_string()),
122 "compatibility" => compatibility = Some(value.trim_matches('"').to_string()),
123 "disable-model-invocation" => disable_model_invocation = value == "true",
124 "license" => license = Some(value.trim_matches('"').to_string()),
125 "user-invocable" => user_invocable = value == "true" || value.is_empty(),
126 "metadata" => {
127 metadata.get_or_insert_with(HashMap::new);
129 }
130 _ => {} }
132 }
133
134 i += 1;
135 }
136
137 ParsedFrontmatter {
138 name,
139 description,
140 argument_hint,
141 compatibility,
142 disable_model_invocation,
143 license,
144 metadata,
145 user_invocable,
146 }
147}
148
149pub fn parse_skill_md(content: &str, path: &Path, source: SkillSource) -> Result<Skill, String> {
173 let (frontmatter, body) = extract_frontmatter(content);
174
175 let fm = frontmatter.map(|s| parse_frontmatter(&s));
176
177 let name = fm
179 .as_ref()
180 .and_then(|f| f.name.clone())
181 .or_else(|| {
182 path.parent()
183 .and_then(|p| p.file_name())
184 .map(|n| n.to_string_lossy().to_string())
185 })
186 .ok_or_else(|| format!("Cannot determine skill name for {}", path.display()))?;
187
188 let description = fm
189 .as_ref()
190 .and_then(|f| f.description.clone())
191 .unwrap_or_default();
192 let argument_hint = fm.as_ref().and_then(|f| f.argument_hint.clone());
193 let compatibility = fm.as_ref().and_then(|f| f.compatibility.clone());
194 let disable_model_invocation = fm
195 .as_ref()
196 .map(|f| f.disable_model_invocation)
197 .unwrap_or(false);
198 let license = fm.as_ref().and_then(|f| f.license.clone());
199 let metadata = fm.as_ref().and_then(|f| f.metadata.clone());
200 let user_invocable = fm.as_ref().map(|f| f.user_invocable).unwrap_or(true);
201
202 let content = truncate_skill_content(body.trim(), &name);
203
204 Ok(Skill {
205 name,
206 description,
207 argument_hint,
208 compatibility,
209 disable_model_invocation,
210 license,
211 metadata,
212 user_invocable,
213 content,
214 path: path.to_path_buf(),
215 source,
216 })
217}
218
219fn extract_frontmatter(content: &str) -> (Option<String>, String) {
223 let trimmed = content.trim_start();
224 if !trimmed.starts_with("---") {
225 return (None, content.to_string());
226 }
227
228 let after_first = &trimmed[3..]; let after_first = after_first.trim_start();
232
233 if let Some(end_pos) = after_first.find("\n---") {
234 let yaml_content = after_first[..end_pos].to_string();
235 let body_start = end_pos + 4; let body = after_first[body_start..].to_string();
238 (Some(yaml_content), body)
239 } else if let Some(end_pos) = after_first.find("---") {
240 let yaml_content = after_first[..end_pos].to_string();
241 let body_start = end_pos + 3; let body = after_first[body_start..].to_string();
243 (Some(yaml_content), body)
244 } else {
245 (None, content.to_string())
246 }
247}
248
249fn truncate_skill_content(content: &str, name: &str) -> String {
251 if content.len() <= SKILL_MAX_CHARS {
252 return content.to_string();
253 }
254
255 let head_ratio = 0.70;
256 let head_end = (SKILL_MAX_CHARS as f64 * head_ratio) as usize;
257 let tail_size = SKILL_MAX_CHARS - head_end;
258
259 let head = &content[..content.floor_char_boundary(head_end)];
260 let tail_start = content.len().saturating_sub(tail_size);
261 let tail = &content[content.floor_char_boundary(tail_start)..];
262
263 format!(
264 "{head}\n\n[...truncated skill '{name}': showing first {head_end} + last {tail_size} chars. Use the read tool to view the full file.]\n\n{tail}"
265 )
266}
267
268pub fn personal_skills_dir() -> PathBuf {
275 crate::paths::Paths::default()
276 .personal_skills_dirs()
277 .into_iter()
278 .next()
279 .expect("personal_skills_dirs is never empty")
280}
281
282pub fn personal_skills_dirs() -> Vec<PathBuf> {
288 crate::paths::Paths::default().personal_skills_dirs()
289}
290
291pub fn project_skills_dir() -> PathBuf {
293 crate::paths::Paths::default().project_skills_dir()
294}
295
296pub fn discover_skills() -> Vec<Skill> {
302 discover_skills_in(&crate::paths::Paths::default())
303}
304
305pub fn discover_skills_in(paths: &crate::paths::Paths) -> Vec<Skill> {
316 let mut skills = Vec::new();
317
318 for personal_dir in paths.personal_skills_dirs() {
321 if let Ok(entries) = discover_skills_from_dir(&personal_dir, SkillSource::Personal) {
322 for skill in entries {
323 if !skills.iter().any(|s: &Skill| s.name == skill.name) {
324 skills.push(skill);
325 }
326 }
327 }
328 }
329
330 let project_dir = paths.project_skills_dir();
332 if let Ok(entries) = discover_skills_from_dir(&project_dir, SkillSource::Project) {
333 for skill in entries {
334 if let Some(pos) = skills.iter().position(|s| s.name == skill.name) {
335 skills[pos] = skill;
336 } else {
337 skills.push(skill);
338 }
339 }
340 }
341
342 skills.sort_by(|a, b| a.name.cmp(&b.name));
344 skills
345}
346
347fn discover_skills_from_dir(dir: &Path, source: SkillSource) -> Result<Vec<Skill>, std::io::Error> {
349 let mut skills = Vec::new();
350
351 if !dir.is_dir() {
352 return Ok(skills);
353 }
354
355 for entry in std::fs::read_dir(dir)? {
356 let entry = entry?;
357 let path = entry.path();
358
359 if !path.is_dir() {
360 continue;
361 }
362
363 let skill_file = path.join("SKILL.md");
364 if !skill_file.is_file() {
365 continue;
366 }
367
368 let content = match std::fs::read_to_string(&skill_file) {
369 Ok(c) => c,
370 Err(e) => {
371 tracing::warn!("Failed to read skill file {}: {e}", skill_file.display(),);
372 continue;
373 }
374 };
375
376 match parse_skill_md(&content, &skill_file, source) {
377 Ok(skill) => skills.push(skill),
378 Err(e) => {
379 tracing::warn!("Failed to parse skill file {}: {e}", skill_file.display(),);
380 continue;
381 }
382 }
383 }
384
385 Ok(skills)
386}
387
388#[derive(Debug, Clone, Serialize, Deserialize)]
390pub struct SkillRegistry {
391 pub skills: Vec<Skill>,
392}
393
394impl SkillRegistry {
395 pub fn discover() -> Self {
400 Self::discover_in(&crate::paths::Paths::default())
401 }
402
403 pub fn discover_in(paths: &crate::paths::Paths) -> Self {
405 SkillRegistry {
406 skills: discover_skills_in(paths),
407 }
408 }
409
410 pub fn get(&self, name: &str) -> Option<&Skill> {
412 let name_lower = name.to_lowercase();
413 self.skills
414 .iter()
415 .find(|s| s.name.to_lowercase() == name_lower)
416 }
417
418 pub fn auto_invocable_skills(&self) -> Vec<&Skill> {
420 self.skills
421 .iter()
422 .filter(|s| !s.disable_model_invocation)
423 .collect()
424 }
425
426 pub fn format_index_for_prompt(&self) -> String {
431 if self.skills.is_empty() {
432 return String::new();
433 }
434
435 let mut lines = Vec::new();
436 lines.push("## Available Skills\n".to_string());
437 lines.push("You can invoke a skill using the `invoke_skill` tool with the skill name. Skills provide specialized instructions for specific tasks.\n".to_string());
438
439 for skill in &self.skills {
440 let mut parts = vec![format!("**{}**", skill.name)];
441
442 if !skill.description.is_empty() {
443 parts.push(format!(": {}", skill.description));
444 }
445
446 if let Some(hint) = &skill.argument_hint {
447 parts.push(format!(" (arg: {})", hint));
448 }
449
450 if let Some(compat) = &skill.compatibility {
451 parts.push(format!(" [{}]", compat));
452 }
453
454 if skill.disable_model_invocation {
455 parts.push(" _(manual invocation only)_".to_string());
456 }
457
458 lines.push(format!("- {}", parts.join("")));
459 }
460
461 lines.push("\nUse `invoke_skill` to activate a skill. The skill's full instructions will be injected into the conversation.".to_string());
462 lines.join("\n")
463 }
464
465 pub fn format_skill_content(&self, skill: &Skill) -> String {
468 format!(
469 "## Active Skill: {}\n\n{}\n\n---\nSkill instructions:\n{}",
470 skill.name, skill.description, skill.content
471 )
472 }
473}
474
475#[cfg(test)]
476mod tests {
477 use super::*;
478 use std::fs;
479
480 #[test]
481 fn test_parse_skill_md_with_frontmatter() {
482 let content = r#"---
483name: test-skill
484description: A test skill for unit tests
485argument-hint: file path to test
486compatibility: rust
487disable-model-invocation: false
488license: MIT
489metadata:
490 version: "1.0"
491user-invocable: true
492---
493
494# Test Skill
495
496This is the body of the test skill.
497"#;
498 let dir = tempfile::tempdir().unwrap();
499 let skill_path = dir.path().join("test-skill").join("SKILL.md");
500 fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
501 fs::write(&skill_path, content).unwrap();
502
503 let skill = parse_skill_md(content, &skill_path, SkillSource::Personal).unwrap();
504 assert_eq!(skill.name, "test-skill");
505 assert_eq!(skill.description, "A test skill for unit tests");
506 assert_eq!(skill.argument_hint, Some("file path to test".to_string()));
507 assert_eq!(skill.compatibility, Some("rust".to_string()));
508 assert!(!skill.disable_model_invocation);
509 assert_eq!(skill.license, Some("MIT".to_string()));
510 assert!(skill.user_invocable);
511 assert!(skill.content.contains("# Test Skill"));
512 assert!(skill.content.contains("body of the test skill"));
513 }
514
515 #[test]
516 fn test_parse_skill_md_without_frontmatter() {
517 let content = "# My Skill\n\nThis is a skill without frontmatter.";
518 let dir = tempfile::tempdir().unwrap();
519 let skill_path = dir.path().join("my-skill").join("SKILL.md");
520 fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
521
522 let skill = parse_skill_md(content, &skill_path, SkillSource::Project).unwrap();
523 assert_eq!(skill.name, "my-skill"); assert_eq!(skill.description, ""); assert!(skill.argument_hint.is_none());
526 assert!(skill.compatibility.is_none());
527 assert!(!skill.disable_model_invocation);
528 assert!(skill.user_invocable); }
530
531 #[test]
532 fn test_parse_skill_md_minimal_frontmatter() {
533 let content = "---\nname: minimal\n---\n\nJust the name, no description.";
534 let dir = tempfile::tempdir().unwrap();
535 let skill_path = dir.path().join("minimal").join("SKILL.md");
536 fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
537
538 let skill = parse_skill_md(content, &skill_path, SkillSource::Personal).unwrap();
539 assert_eq!(skill.name, "minimal");
540 assert_eq!(skill.description, "");
541 }
542
543 #[test]
544 fn test_extract_frontmatter() {
545 let content = "---\nname: test\n---\nBody text";
546 let (fm, body) = extract_frontmatter(content);
547 assert!(fm.is_some());
548 assert!(body.contains("Body text"));
549 }
550
551 #[test]
552 fn test_extract_frontmatter_none() {
553 let content = "No frontmatter here, just text.";
554 let (fm, body) = extract_frontmatter(content);
555 assert!(fm.is_none());
556 assert_eq!(body, content);
557 }
558
559 #[test]
560 fn test_parse_frontmatter_with_metadata() {
561 let fm = parse_frontmatter("metadata:\n version: \"1.0\"\n author: test");
562 assert!(fm.metadata.is_some());
563 let meta = fm.metadata.unwrap();
564 assert_eq!(meta.get("version").unwrap(), "1.0");
565 assert_eq!(meta.get("author").unwrap(), "test");
566 }
567
568 #[test]
569 fn test_parse_frontmatter_boolean_fields() {
570 let fm = parse_frontmatter("disable-model-invocation: true\nuser-invocable: false");
571 assert!(fm.disable_model_invocation);
572 assert!(!fm.user_invocable);
573 }
574
575 #[test]
576 fn test_parse_frontmatter_defaults() {
577 let fm = parse_frontmatter("name: hello");
578 assert_eq!(fm.name, Some("hello".to_string()));
579 assert!(!fm.disable_model_invocation); assert!(fm.user_invocable); assert!(fm.description.is_none());
582 assert!(fm.argument_hint.is_none());
583 assert!(fm.metadata.is_none());
584 }
585
586 #[test]
587 fn test_skill_registry_format_index() {
588 let skill = Skill {
589 name: "rust-dev".to_string(),
590 description: "Rust development best practices".to_string(),
591 argument_hint: Some("Rust file or module".to_string()),
592 compatibility: Some("rust".to_string()),
593 disable_model_invocation: false,
594 license: None,
595 metadata: None,
596 user_invocable: true,
597 content: "Instructions...".to_string(),
598 path: PathBuf::from("/test/SKILL.md"),
599 source: SkillSource::Personal,
600 };
601
602 let registry = SkillRegistry {
603 skills: vec![skill],
604 };
605
606 let index = registry.format_index_for_prompt();
607 assert!(index.contains("rust-dev"));
608 assert!(index.contains("invoke_skill"));
609 assert!(index.contains("arg:"));
610 assert!(index.contains("[rust]"));
611 }
612
613 #[test]
614 fn test_skill_registry_format_disabled() {
615 let skill = Skill {
616 name: "manual-only".to_string(),
617 description: "Manual invocation only".to_string(),
618 argument_hint: None,
619 compatibility: None,
620 disable_model_invocation: true,
621 license: None,
622 metadata: None,
623 user_invocable: true,
624 content: "Instructions...".to_string(),
625 path: PathBuf::from("/test/SKILL.md"),
626 source: SkillSource::Personal,
627 };
628
629 let registry = SkillRegistry {
630 skills: vec![skill],
631 };
632
633 let index = registry.format_index_for_prompt();
634 assert!(index.contains("manual invocation only"));
635 }
636}