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)]
17pub struct Skill {
18 pub name: String,
20 pub description: String,
22 pub argument_hint: Option<String>,
24 pub compatibility: Option<String>,
26 pub disable_model_invocation: bool,
28 pub license: Option<String>,
30 pub metadata: Option<HashMap<String, String>>,
32 pub user_invocable: bool,
34 pub content: String,
36 pub path: PathBuf,
38 pub source: SkillSource,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44pub enum SkillSource {
45 Personal,
47 Project,
49}
50
51struct ParsedFrontmatter {
63 name: Option<String>,
64 description: Option<String>,
65 argument_hint: Option<String>,
66 compatibility: Option<String>,
67 disable_model_invocation: bool,
68 license: Option<String>,
69 metadata: Option<HashMap<String, String>>,
70 user_invocable: bool,
71}
72
73fn parse_frontmatter(text: &str) -> ParsedFrontmatter {
77 let mut name = None;
78 let mut description = None;
79 let mut argument_hint = None;
80 let mut compatibility = None;
81 let mut disable_model_invocation = false;
82 let mut license = None;
83 let mut user_invocable = true;
84 let mut metadata: Option<HashMap<String, String>> = None;
85
86 let lines: Vec<&str> = text.lines().collect();
87 let mut i = 0;
88
89 while i < lines.len() {
90 let line = lines[i];
91
92 if line.trim().is_empty() {
94 i += 1;
95 continue;
96 }
97
98 if line.starts_with(" ") || line.starts_with("\t") {
100 if let Some(ref mut map) = metadata {
102 let trimmed = line.trim();
103 if let Some((k, v)) = trimmed.split_once(':') {
104 map.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
105 }
106 }
107 i += 1;
108 continue;
109 }
110
111 if let Some((key, value)) = line.split_once(':') {
113 let key = key.trim();
114 let value = value.trim();
115
116 match key {
117 "name" => name = Some(value.trim_matches('"').to_string()),
118 "description" => description = Some(value.trim_matches('"').to_string()),
119 "argument-hint" => argument_hint = Some(value.trim_matches('"').to_string()),
120 "compatibility" => compatibility = Some(value.trim_matches('"').to_string()),
121 "disable-model-invocation" => disable_model_invocation = value == "true",
122 "license" => license = Some(value.trim_matches('"').to_string()),
123 "user-invocable" => user_invocable = value == "true" || value.is_empty(),
124 "metadata" => {
125 metadata.get_or_insert_with(HashMap::new);
127 }
128 _ => {} }
130 }
131
132 i += 1;
133 }
134
135 ParsedFrontmatter {
136 name,
137 description,
138 argument_hint,
139 compatibility,
140 disable_model_invocation,
141 license,
142 metadata,
143 user_invocable,
144 }
145}
146
147pub fn parse_skill_md(content: &str, path: &Path, source: SkillSource) -> Result<Skill, String> {
171 let (frontmatter, body) = extract_frontmatter(content);
172
173 let fm = frontmatter.map(|s| parse_frontmatter(&s));
174
175 let name = fm
177 .as_ref()
178 .and_then(|f| f.name.clone())
179 .or_else(|| {
180 path.parent()
181 .and_then(|p| p.file_name())
182 .map(|n| n.to_string_lossy().to_string())
183 })
184 .ok_or_else(|| format!("Cannot determine skill name for {}", path.display()))?;
185
186 let description = fm
187 .as_ref()
188 .and_then(|f| f.description.clone())
189 .unwrap_or_default();
190 let argument_hint = fm.as_ref().and_then(|f| f.argument_hint.clone());
191 let compatibility = fm.as_ref().and_then(|f| f.compatibility.clone());
192 let disable_model_invocation = fm
193 .as_ref()
194 .map(|f| f.disable_model_invocation)
195 .unwrap_or(false);
196 let license = fm.as_ref().and_then(|f| f.license.clone());
197 let metadata = fm.as_ref().and_then(|f| f.metadata.clone());
198 let user_invocable = fm.as_ref().map(|f| f.user_invocable).unwrap_or(true);
199
200 let content = truncate_skill_content(body.trim(), &name);
201
202 Ok(Skill {
203 name,
204 description,
205 argument_hint,
206 compatibility,
207 disable_model_invocation,
208 license,
209 metadata,
210 user_invocable,
211 content,
212 path: path.to_path_buf(),
213 source,
214 })
215}
216
217fn extract_frontmatter(content: &str) -> (Option<String>, String) {
221 let trimmed = content.trim_start();
222 if !trimmed.starts_with("---") {
223 return (None, content.to_string());
224 }
225
226 let after_first = &trimmed[3..]; let after_first = after_first.trim_start();
230
231 if let Some(end_pos) = after_first.find("\n---") {
232 let yaml_content = after_first[..end_pos].to_string();
233 let body_start = end_pos + 4; let body = after_first[body_start..].to_string();
236 (Some(yaml_content), body)
237 } else if let Some(end_pos) = after_first.find("---") {
238 let yaml_content = after_first[..end_pos].to_string();
239 let body_start = end_pos + 3; let body = after_first[body_start..].to_string();
241 (Some(yaml_content), body)
242 } else {
243 (None, content.to_string())
244 }
245}
246
247fn truncate_skill_content(content: &str, name: &str) -> String {
249 if content.len() <= SKILL_MAX_CHARS {
250 return content.to_string();
251 }
252
253 let head_ratio = 0.70;
254 let head_end = (SKILL_MAX_CHARS as f64 * head_ratio) as usize;
255 let tail_size = SKILL_MAX_CHARS - head_end;
256
257 let head = &content[..content.floor_char_boundary(head_end)];
258 let tail_start = content.len().saturating_sub(tail_size);
259 let tail = &content[content.floor_char_boundary(tail_start)..];
260
261 format!(
262 "{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}"
263 )
264}
265
266pub fn personal_skills_dir() -> PathBuf {
268 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
269 PathBuf::from(home).join(".tinyharness/skills")
270}
271
272pub fn project_skills_dir() -> PathBuf {
274 std::env::current_dir()
275 .unwrap_or_else(|_| PathBuf::from("."))
276 .join(".tinyharness/skills")
277}
278
279pub fn discover_skills() -> Vec<Skill> {
284 let mut skills = Vec::new();
285
286 let personal_dir = personal_skills_dir();
288 if let Ok(entries) = discover_skills_from_dir(&personal_dir, SkillSource::Personal) {
289 skills.extend(entries);
290 }
291
292 let project_dir = project_skills_dir();
294 if let Ok(entries) = discover_skills_from_dir(&project_dir, SkillSource::Project) {
295 for skill in entries {
297 if let Some(pos) = skills.iter().position(|s| s.name == skill.name) {
298 skills[pos] = skill;
299 } else {
300 skills.push(skill);
301 }
302 }
303 }
304
305 skills.sort_by(|a, b| a.name.cmp(&b.name));
307 skills
308}
309
310fn discover_skills_from_dir(dir: &Path, source: SkillSource) -> Result<Vec<Skill>, std::io::Error> {
312 let mut skills = Vec::new();
313
314 if !dir.is_dir() {
315 return Ok(skills);
316 }
317
318 for entry in std::fs::read_dir(dir)? {
319 let entry = entry?;
320 let path = entry.path();
321
322 if !path.is_dir() {
323 continue;
324 }
325
326 let skill_file = path.join("SKILL.md");
327 if !skill_file.is_file() {
328 continue;
329 }
330
331 let content = match std::fs::read_to_string(&skill_file) {
332 Ok(c) => c,
333 Err(e) => {
334 eprintln!(
335 "Warning: Failed to read skill file {}: {}",
336 skill_file.display(),
337 e
338 );
339 continue;
340 }
341 };
342
343 match parse_skill_md(&content, &skill_file, source) {
344 Ok(skill) => skills.push(skill),
345 Err(e) => {
346 eprintln!(
347 "Warning: Failed to parse skill file {}: {}",
348 skill_file.display(),
349 e
350 );
351 continue;
352 }
353 }
354 }
355
356 Ok(skills)
357}
358
359#[derive(Debug, Clone, Serialize, Deserialize)]
361pub struct SkillRegistry {
362 pub skills: Vec<Skill>,
363}
364
365impl SkillRegistry {
366 pub fn discover() -> Self {
368 SkillRegistry {
369 skills: discover_skills(),
370 }
371 }
372
373 pub fn get(&self, name: &str) -> Option<&Skill> {
375 let name_lower = name.to_lowercase();
376 self.skills
377 .iter()
378 .find(|s| s.name.to_lowercase() == name_lower)
379 }
380
381 pub fn auto_invocable_skills(&self) -> Vec<&Skill> {
383 self.skills
384 .iter()
385 .filter(|s| !s.disable_model_invocation)
386 .collect()
387 }
388
389 pub fn format_index_for_prompt(&self) -> String {
394 if self.skills.is_empty() {
395 return String::new();
396 }
397
398 let mut lines = Vec::new();
399 lines.push("## Available Skills\n".to_string());
400 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());
401
402 for skill in &self.skills {
403 let mut parts = vec![format!("**{}**", skill.name)];
404
405 if !skill.description.is_empty() {
406 parts.push(format!(": {}", skill.description));
407 }
408
409 if let Some(hint) = &skill.argument_hint {
410 parts.push(format!(" (arg: {})", hint));
411 }
412
413 if let Some(compat) = &skill.compatibility {
414 parts.push(format!(" [{}]", compat));
415 }
416
417 if skill.disable_model_invocation {
418 parts.push(" _(manual invocation only)_".to_string());
419 }
420
421 lines.push(format!("- {}", parts.join("")));
422 }
423
424 lines.push("\nUse `invoke_skill` to activate a skill. The skill's full instructions will be injected into the conversation.".to_string());
425 lines.join("\n")
426 }
427
428 pub fn format_skill_content(&self, skill: &Skill) -> String {
431 format!(
432 "## Active Skill: {}\n\n{}\n\n---\nSkill instructions:\n{}",
433 skill.name, skill.description, skill.content
434 )
435 }
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441 use std::fs;
442
443 #[test]
444 fn test_parse_skill_md_with_frontmatter() {
445 let content = r#"---
446name: test-skill
447description: A test skill for unit tests
448argument-hint: file path to test
449compatibility: rust
450disable-model-invocation: false
451license: MIT
452metadata:
453 version: "1.0"
454user-invocable: true
455---
456
457# Test Skill
458
459This is the body of the test skill.
460"#;
461 let dir = tempfile::tempdir().unwrap();
462 let skill_path = dir.path().join("test-skill").join("SKILL.md");
463 fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
464 fs::write(&skill_path, content).unwrap();
465
466 let skill = parse_skill_md(content, &skill_path, SkillSource::Personal).unwrap();
467 assert_eq!(skill.name, "test-skill");
468 assert_eq!(skill.description, "A test skill for unit tests");
469 assert_eq!(skill.argument_hint, Some("file path to test".to_string()));
470 assert_eq!(skill.compatibility, Some("rust".to_string()));
471 assert!(!skill.disable_model_invocation);
472 assert_eq!(skill.license, Some("MIT".to_string()));
473 assert!(skill.user_invocable);
474 assert!(skill.content.contains("# Test Skill"));
475 assert!(skill.content.contains("body of the test skill"));
476 }
477
478 #[test]
479 fn test_parse_skill_md_without_frontmatter() {
480 let content = "# My Skill\n\nThis is a skill without frontmatter.";
481 let dir = tempfile::tempdir().unwrap();
482 let skill_path = dir.path().join("my-skill").join("SKILL.md");
483 fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
484
485 let skill = parse_skill_md(content, &skill_path, SkillSource::Project).unwrap();
486 assert_eq!(skill.name, "my-skill"); assert_eq!(skill.description, ""); assert!(skill.argument_hint.is_none());
489 assert!(skill.compatibility.is_none());
490 assert!(!skill.disable_model_invocation);
491 assert!(skill.user_invocable); }
493
494 #[test]
495 fn test_parse_skill_md_minimal_frontmatter() {
496 let content = "---\nname: minimal\n---\n\nJust the name, no description.";
497 let dir = tempfile::tempdir().unwrap();
498 let skill_path = dir.path().join("minimal").join("SKILL.md");
499 fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
500
501 let skill = parse_skill_md(content, &skill_path, SkillSource::Personal).unwrap();
502 assert_eq!(skill.name, "minimal");
503 assert_eq!(skill.description, "");
504 }
505
506 #[test]
507 fn test_extract_frontmatter() {
508 let content = "---\nname: test\n---\nBody text";
509 let (fm, body) = extract_frontmatter(content);
510 assert!(fm.is_some());
511 assert!(body.contains("Body text"));
512 }
513
514 #[test]
515 fn test_extract_frontmatter_none() {
516 let content = "No frontmatter here, just text.";
517 let (fm, body) = extract_frontmatter(content);
518 assert!(fm.is_none());
519 assert_eq!(body, content);
520 }
521
522 #[test]
523 fn test_parse_frontmatter_with_metadata() {
524 let fm = parse_frontmatter("metadata:\n version: \"1.0\"\n author: test");
525 assert!(fm.metadata.is_some());
526 let meta = fm.metadata.unwrap();
527 assert_eq!(meta.get("version").unwrap(), "1.0");
528 assert_eq!(meta.get("author").unwrap(), "test");
529 }
530
531 #[test]
532 fn test_parse_frontmatter_boolean_fields() {
533 let fm = parse_frontmatter("disable-model-invocation: true\nuser-invocable: false");
534 assert!(fm.disable_model_invocation);
535 assert!(!fm.user_invocable);
536 }
537
538 #[test]
539 fn test_parse_frontmatter_defaults() {
540 let fm = parse_frontmatter("name: hello");
541 assert_eq!(fm.name, Some("hello".to_string()));
542 assert!(!fm.disable_model_invocation); assert!(fm.user_invocable); assert!(fm.description.is_none());
545 assert!(fm.argument_hint.is_none());
546 assert!(fm.metadata.is_none());
547 }
548
549 #[test]
550 fn test_skill_registry_format_index() {
551 let skill = Skill {
552 name: "rust-dev".to_string(),
553 description: "Rust development best practices".to_string(),
554 argument_hint: Some("Rust file or module".to_string()),
555 compatibility: Some("rust".to_string()),
556 disable_model_invocation: false,
557 license: None,
558 metadata: None,
559 user_invocable: true,
560 content: "Instructions...".to_string(),
561 path: PathBuf::from("/test/SKILL.md"),
562 source: SkillSource::Personal,
563 };
564
565 let registry = SkillRegistry {
566 skills: vec![skill],
567 };
568
569 let index = registry.format_index_for_prompt();
570 assert!(index.contains("rust-dev"));
571 assert!(index.contains("invoke_skill"));
572 assert!(index.contains("arg:"));
573 assert!(index.contains("[rust]"));
574 }
575
576 #[test]
577 fn test_skill_registry_format_disabled() {
578 let skill = Skill {
579 name: "manual-only".to_string(),
580 description: "Manual invocation only".to_string(),
581 argument_hint: None,
582 compatibility: None,
583 disable_model_invocation: true,
584 license: None,
585 metadata: None,
586 user_invocable: true,
587 content: "Instructions...".to_string(),
588 path: PathBuf::from("/test/SKILL.md"),
589 source: SkillSource::Personal,
590 };
591
592 let registry = SkillRegistry {
593 skills: vec![skill],
594 };
595
596 let index = registry.format_index_for_prompt();
597 assert!(index.contains("manual invocation only"));
598 }
599}