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 tracing::warn!("Failed to read skill file {}: {e}", skill_file.display(),);
335 continue;
336 }
337 };
338
339 match parse_skill_md(&content, &skill_file, source) {
340 Ok(skill) => skills.push(skill),
341 Err(e) => {
342 tracing::warn!("Failed to parse skill file {}: {e}", skill_file.display(),);
343 continue;
344 }
345 }
346 }
347
348 Ok(skills)
349}
350
351#[derive(Debug, Clone, Serialize, Deserialize)]
353pub struct SkillRegistry {
354 pub skills: Vec<Skill>,
355}
356
357impl SkillRegistry {
358 pub fn discover() -> Self {
360 SkillRegistry {
361 skills: discover_skills(),
362 }
363 }
364
365 pub fn get(&self, name: &str) -> Option<&Skill> {
367 let name_lower = name.to_lowercase();
368 self.skills
369 .iter()
370 .find(|s| s.name.to_lowercase() == name_lower)
371 }
372
373 pub fn auto_invocable_skills(&self) -> Vec<&Skill> {
375 self.skills
376 .iter()
377 .filter(|s| !s.disable_model_invocation)
378 .collect()
379 }
380
381 pub fn format_index_for_prompt(&self) -> String {
386 if self.skills.is_empty() {
387 return String::new();
388 }
389
390 let mut lines = Vec::new();
391 lines.push("## Available Skills\n".to_string());
392 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());
393
394 for skill in &self.skills {
395 let mut parts = vec![format!("**{}**", skill.name)];
396
397 if !skill.description.is_empty() {
398 parts.push(format!(": {}", skill.description));
399 }
400
401 if let Some(hint) = &skill.argument_hint {
402 parts.push(format!(" (arg: {})", hint));
403 }
404
405 if let Some(compat) = &skill.compatibility {
406 parts.push(format!(" [{}]", compat));
407 }
408
409 if skill.disable_model_invocation {
410 parts.push(" _(manual invocation only)_".to_string());
411 }
412
413 lines.push(format!("- {}", parts.join("")));
414 }
415
416 lines.push("\nUse `invoke_skill` to activate a skill. The skill's full instructions will be injected into the conversation.".to_string());
417 lines.join("\n")
418 }
419
420 pub fn format_skill_content(&self, skill: &Skill) -> String {
423 format!(
424 "## Active Skill: {}\n\n{}\n\n---\nSkill instructions:\n{}",
425 skill.name, skill.description, skill.content
426 )
427 }
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433 use std::fs;
434
435 #[test]
436 fn test_parse_skill_md_with_frontmatter() {
437 let content = r#"---
438name: test-skill
439description: A test skill for unit tests
440argument-hint: file path to test
441compatibility: rust
442disable-model-invocation: false
443license: MIT
444metadata:
445 version: "1.0"
446user-invocable: true
447---
448
449# Test Skill
450
451This is the body of the test skill.
452"#;
453 let dir = tempfile::tempdir().unwrap();
454 let skill_path = dir.path().join("test-skill").join("SKILL.md");
455 fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
456 fs::write(&skill_path, content).unwrap();
457
458 let skill = parse_skill_md(content, &skill_path, SkillSource::Personal).unwrap();
459 assert_eq!(skill.name, "test-skill");
460 assert_eq!(skill.description, "A test skill for unit tests");
461 assert_eq!(skill.argument_hint, Some("file path to test".to_string()));
462 assert_eq!(skill.compatibility, Some("rust".to_string()));
463 assert!(!skill.disable_model_invocation);
464 assert_eq!(skill.license, Some("MIT".to_string()));
465 assert!(skill.user_invocable);
466 assert!(skill.content.contains("# Test Skill"));
467 assert!(skill.content.contains("body of the test skill"));
468 }
469
470 #[test]
471 fn test_parse_skill_md_without_frontmatter() {
472 let content = "# My Skill\n\nThis is a skill without frontmatter.";
473 let dir = tempfile::tempdir().unwrap();
474 let skill_path = dir.path().join("my-skill").join("SKILL.md");
475 fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
476
477 let skill = parse_skill_md(content, &skill_path, SkillSource::Project).unwrap();
478 assert_eq!(skill.name, "my-skill"); assert_eq!(skill.description, ""); assert!(skill.argument_hint.is_none());
481 assert!(skill.compatibility.is_none());
482 assert!(!skill.disable_model_invocation);
483 assert!(skill.user_invocable); }
485
486 #[test]
487 fn test_parse_skill_md_minimal_frontmatter() {
488 let content = "---\nname: minimal\n---\n\nJust the name, no description.";
489 let dir = tempfile::tempdir().unwrap();
490 let skill_path = dir.path().join("minimal").join("SKILL.md");
491 fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
492
493 let skill = parse_skill_md(content, &skill_path, SkillSource::Personal).unwrap();
494 assert_eq!(skill.name, "minimal");
495 assert_eq!(skill.description, "");
496 }
497
498 #[test]
499 fn test_extract_frontmatter() {
500 let content = "---\nname: test\n---\nBody text";
501 let (fm, body) = extract_frontmatter(content);
502 assert!(fm.is_some());
503 assert!(body.contains("Body text"));
504 }
505
506 #[test]
507 fn test_extract_frontmatter_none() {
508 let content = "No frontmatter here, just text.";
509 let (fm, body) = extract_frontmatter(content);
510 assert!(fm.is_none());
511 assert_eq!(body, content);
512 }
513
514 #[test]
515 fn test_parse_frontmatter_with_metadata() {
516 let fm = parse_frontmatter("metadata:\n version: \"1.0\"\n author: test");
517 assert!(fm.metadata.is_some());
518 let meta = fm.metadata.unwrap();
519 assert_eq!(meta.get("version").unwrap(), "1.0");
520 assert_eq!(meta.get("author").unwrap(), "test");
521 }
522
523 #[test]
524 fn test_parse_frontmatter_boolean_fields() {
525 let fm = parse_frontmatter("disable-model-invocation: true\nuser-invocable: false");
526 assert!(fm.disable_model_invocation);
527 assert!(!fm.user_invocable);
528 }
529
530 #[test]
531 fn test_parse_frontmatter_defaults() {
532 let fm = parse_frontmatter("name: hello");
533 assert_eq!(fm.name, Some("hello".to_string()));
534 assert!(!fm.disable_model_invocation); assert!(fm.user_invocable); assert!(fm.description.is_none());
537 assert!(fm.argument_hint.is_none());
538 assert!(fm.metadata.is_none());
539 }
540
541 #[test]
542 fn test_skill_registry_format_index() {
543 let skill = Skill {
544 name: "rust-dev".to_string(),
545 description: "Rust development best practices".to_string(),
546 argument_hint: Some("Rust file or module".to_string()),
547 compatibility: Some("rust".to_string()),
548 disable_model_invocation: false,
549 license: None,
550 metadata: None,
551 user_invocable: true,
552 content: "Instructions...".to_string(),
553 path: PathBuf::from("/test/SKILL.md"),
554 source: SkillSource::Personal,
555 };
556
557 let registry = SkillRegistry {
558 skills: vec![skill],
559 };
560
561 let index = registry.format_index_for_prompt();
562 assert!(index.contains("rust-dev"));
563 assert!(index.contains("invoke_skill"));
564 assert!(index.contains("arg:"));
565 assert!(index.contains("[rust]"));
566 }
567
568 #[test]
569 fn test_skill_registry_format_disabled() {
570 let skill = Skill {
571 name: "manual-only".to_string(),
572 description: "Manual invocation only".to_string(),
573 argument_hint: None,
574 compatibility: None,
575 disable_model_invocation: true,
576 license: None,
577 metadata: None,
578 user_invocable: true,
579 content: "Instructions...".to_string(),
580 path: PathBuf::from("/test/SKILL.md"),
581 source: SkillSource::Personal,
582 };
583
584 let registry = SkillRegistry {
585 skills: vec![skill],
586 };
587
588 let index = registry.format_index_for_prompt();
589 assert!(index.contains("manual invocation only"));
590 }
591}