1use std::path::PathBuf;
9use std::sync::Arc;
10
11use async_trait::async_trait;
12use serde_json::{json, Value};
13use tokio_util::sync::CancellationToken;
14
15use crate::agent::tool::{AgentTool, ToolResult};
16use crate::skills::Skills;
17
18pub struct SkillTool {
19 #[allow(dead_code)]
20 pub cwd: PathBuf,
21 pub skills: Arc<Skills>,
22 desc: String,
23}
24
25impl SkillTool {
26 pub fn new(cwd: PathBuf, skills: Arc<Skills>) -> Self {
27 let names = skills
28 .skills
29 .iter()
30 .map(|s| s.name.as_str())
31 .collect::<Vec<_>>()
32 .join(", ");
33 let desc = format!(
34 "Invoke a skill by name to load its full instructions into context, then follow them. \
35 Only call this when the user's request matches a skill. Available skills: {names}"
36 );
37 Self { cwd, skills, desc }
38 }
39}
40
41#[async_trait]
42impl AgentTool for SkillTool {
43 fn name(&self) -> &str {
44 "skill"
45 }
46 fn description(&self) -> &str {
47 &self.desc
48 }
49 fn input_schema(&self) -> Value {
50 json!({
51 "type": "object",
52 "properties": {
53 "skill": { "type": "string", "description": "Name of the skill to invoke" },
54 "args": { "type": "string", "description": "Optional arguments to pass to the skill" }
55 },
56 "required": ["skill"]
57 })
58 }
59
60 async fn execute(&self, args: Value, _cancel: CancellationToken) -> anyhow::Result<ToolResult> {
61 let name = args
62 .get("skill")
63 .and_then(|v| v.as_str())
64 .ok_or_else(|| anyhow::anyhow!("skill requires a 'skill' name parameter"))?;
65 let skill = match self.skills.find(name) {
66 Some(s) => s,
67 None => {
68 let avail = self.skills.names().join(", ");
69 anyhow::bail!("Unknown skill '{name}'. Available skills: {avail}");
70 }
71 };
72 let mut out = format!("# Skill: {}\n\n", skill.name);
73 if let Some(a) = args.get("args").and_then(|v| v.as_str()) {
74 if !a.trim().is_empty() {
75 out.push_str(&format!("Arguments: {a}\n\n"));
76 }
77 }
78 out.push_str(skill.body.trim());
79 out.push_str(&format!(
80 "\n\n---\nSkill directory: `{}`. Reference any supporting files (scripts, references) \
81 by their path under this directory using the read or bash tools.",
82 skill.dir.display()
83 ));
84 Ok(ToolResult::text(out))
85 }
86}
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91 use crate::skills::{Skill, SkillSource};
92
93 fn registry_with(skill: Skill) -> Arc<Skills> {
94 Arc::new(Skills { skills: vec![skill] })
95 }
96
97 async fn run_skill(tool: &SkillTool, args: Value) -> Result<String, String> {
98 match tool.execute(args, CancellationToken::new()).await {
99 Ok(r) => match r.content.into_iter().next() {
100 Some(crate::ai::types::ToolResultContent::Text { text }) => Ok(text),
101 _ => panic!("expected text result"),
102 },
103 Err(e) => Err(e.to_string()),
104 }
105 }
106
107 #[tokio::test]
108 async fn returns_body_for_known_skill_and_surfaces_dir() {
109 let dir = std::env::temp_dir().join(format!("pi-skilltool-{}", uuid::Uuid::new_v4()));
110 std::fs::create_dir_all(&dir).unwrap();
111 let skill = Skill {
112 name: "deploy".into(),
113 description: "How to deploy".into(),
114 body: "Run `make deploy` then verify.".into(),
115 dir: dir.clone(),
116 source: SkillSource::Project,
117 };
118 let tool = SkillTool::new(PathBuf::from("."), registry_with(skill));
119 let out = run_skill(&tool, json!({ "skill": "deploy", "args": "prod" }))
120 .await
121 .unwrap();
122 assert!(out.contains("# Skill: deploy"), "{out}");
123 assert!(out.contains("Run `make deploy`"), "{out}");
124 assert!(out.contains("Arguments: prod"), "{out}");
125 assert!(out.contains(&dir.display().to_string()), "{out}");
127 let _ = std::fs::remove_dir_all(&dir);
128 }
129
130 #[tokio::test]
131 async fn unknown_skill_lists_available() {
132 let skill = Skill {
133 name: "deploy".into(),
134 description: "d".into(),
135 body: "b".into(),
136 dir: PathBuf::from("."),
137 source: SkillSource::Project,
138 };
139 let tool = SkillTool::new(PathBuf::from("."), registry_with(skill));
140 let err = run_skill(&tool, json!({ "skill": "nope" })).await.unwrap_err();
141 assert!(err.contains("Unknown skill 'nope'"), "{err}");
142 assert!(err.contains("deploy"), "should list available: {err}");
143 }
144
145 #[tokio::test]
146 async fn missing_skill_param_errors() {
147 let tool = SkillTool::new(PathBuf::from("."), Arc::new(Skills::empty()));
148 let err = run_skill(&tool, json!({})).await.unwrap_err();
149 assert!(err.contains("requires a 'skill'"), "{err}");
150 }
151}