trusty_code/tools/skill.rs
1//! `use_skill` tool — the on-invoke half of progressive-disclosure skill
2//! loading (#2069).
3//!
4//! Why: The prompt only ever injects the cheap skill *metadata* catalog
5//! (`skills::format_skill_catalog`); an agent that decides a listed skill is
6//! relevant needs a way to actually fetch its full body. `UseSkillTool` is
7//! that seam — a thin `ToolExecutor` wrapping any `SkillResolver`, so the
8//! LLM's tool call is the "invoke" moment that triggers the lazy disk read.
9//! What: `UseSkillTool::new(resolver)` takes any `Arc<dyn SkillResolver>`
10//! (production: `skills::FsSkillResolver`); `execute` looks up the
11//! `{"name": ...}` argument via `resolver.resolve()` and returns the body, or
12//! a recoverable error naming the unknown skill.
13//! Test: `tools::skill::tests::*` — resolves a known skill, errors on an
14//! unknown one, errors on a missing `name` argument, schema shape.
15
16use std::sync::Arc;
17
18use async_trait::async_trait;
19use serde_json::{Value, json};
20
21use crate::tools::traits::{SkillResolver, ToolExecutor, ToolResult};
22
23/// The stable tool name for `UseSkillTool` (matches `name()`/the schema's
24/// `function.name` verbatim).
25///
26/// Why: (#2070) The agent loop must identify a skill-body-load result by tool
27/// name to pin it against compaction (vision spec §5.4 item 5: "preserve
28/// skill outputs... forever"); a shared constant — mirroring
29/// `tools::finish_task::FINISH_TASK_TOOL_NAME`'s identical role for
30/// `finish_task` — means that identification can never drift from the tool's
31/// actual wire name.
32/// Test: `tools::skill::tests::name_matches_constant`.
33pub const USE_SKILL_TOOL_NAME: &str = "use_skill";
34
35/// `ToolExecutor` that lazily fetches a named skill's full Markdown body.
36///
37/// Why: Keeps the LLM-facing surface (`name()`, `schema()`, `execute()`)
38/// independent of which `SkillResolver` implementation backs it.
39/// What: Delegates every call to the wrapped resolver's `resolve()`.
40/// Test: `use_skill_resolves_known_skill`.
41pub struct UseSkillTool {
42 resolver: Arc<dyn SkillResolver>,
43}
44
45impl UseSkillTool {
46 /// Construct a `UseSkillTool` backed by `resolver`.
47 ///
48 /// Why: Constructor injection keeps the tool testable with a stub
49 /// resolver, matching every other `ToolExecutor` in this crate.
50 /// What: Stores the `Arc<dyn SkillResolver>` for use in `execute`.
51 /// Test: `use_skill_resolves_known_skill`.
52 pub fn new(resolver: Arc<dyn SkillResolver>) -> Self {
53 Self { resolver }
54 }
55}
56
57#[async_trait]
58impl ToolExecutor for UseSkillTool {
59 fn name(&self) -> &str {
60 USE_SKILL_TOOL_NAME
61 }
62
63 /// OpenAI function-call schema for `use_skill`.
64 ///
65 /// Why: The LLM needs the skill `name` field to make the call; the
66 /// description points back at the catalog the prompt already injected.
67 /// Test: `use_skill_schema_has_required_name`.
68 fn schema(&self) -> Value {
69 json!({
70 "type": "function",
71 "function": {
72 "name": USE_SKILL_TOOL_NAME,
73 "description": "Load the full instructions for a skill listed in the 'Available skills' catalog. Only call this for a skill you actually intend to use — it returns the skill's complete body.",
74 "parameters": {
75 "type": "object",
76 "properties": {
77 "name": {
78 "type": "string",
79 "description": "The exact skill name as it appears in the catalog."
80 }
81 },
82 "required": ["name"],
83 "additionalProperties": false
84 }
85 }
86 })
87 }
88
89 /// Execute a `use_skill` tool call.
90 ///
91 /// Why: This is the moment progressive disclosure actually defers to —
92 /// the body is read from disk only now, not at prompt-assembly time.
93 /// What: Parses `{name}` from `args`, calls `resolver.resolve(name)`, and
94 /// converts the result into a `ToolResult`.
95 /// Test: `use_skill_resolves_known_skill`, `use_skill_errors_on_unknown`,
96 /// `use_skill_errors_on_missing_name`.
97 async fn execute(&self, args: Value) -> ToolResult {
98 let Some(name) = args.get("name").and_then(Value::as_str) else {
99 return ToolResult::err("use_skill: missing required argument 'name'");
100 };
101
102 match self.resolver.resolve(name) {
103 Some(body) => ToolResult::ok(body),
104 None => ToolResult::err(format!("use_skill: unknown skill '{name}'")),
105 }
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use std::collections::HashMap;
112 use std::sync::Mutex;
113
114 use super::*;
115 use crate::skills::SkillMetadata;
116
117 /// In-memory stub resolver so these tests do not touch the filesystem.
118 struct StubResolver {
119 bodies: Mutex<HashMap<String, String>>,
120 }
121
122 impl SkillResolver for StubResolver {
123 fn resolve(&self, name: &str) -> Option<String> {
124 self.bodies.lock().expect("lock").get(name).cloned()
125 }
126 fn list(&self) -> Vec<String> {
127 self.bodies.lock().expect("lock").keys().cloned().collect()
128 }
129 fn metadata(&self) -> Vec<SkillMetadata> {
130 self.bodies
131 .lock()
132 .expect("lock")
133 .keys()
134 .map(|name| SkillMetadata {
135 name: name.clone(),
136 description: String::new(),
137 })
138 .collect()
139 }
140 }
141
142 fn make_tool() -> UseSkillTool {
143 let mut bodies = HashMap::new();
144 bodies.insert("demo-skill".to_string(), "full demo body".to_string());
145 UseSkillTool::new(Arc::new(StubResolver {
146 bodies: Mutex::new(bodies),
147 }))
148 }
149
150 /// `use_skill` returns the resolved body for a known skill name.
151 ///
152 /// Why: Core happy-path contract for the on-invoke load.
153 /// Test: this test.
154 #[tokio::test]
155 async fn use_skill_resolves_known_skill() {
156 let tool = make_tool();
157 let result = tool.execute(json!({"name": "demo-skill"})).await;
158 assert!(!result.is_error(), "unexpected error: {}", result.content());
159 assert_eq!(result.content(), "full demo body");
160 }
161
162 /// `use_skill` returns a recoverable error for an unknown skill name.
163 ///
164 /// Why: An LLM hallucinating a skill name must get an actionable error,
165 /// not a panic.
166 /// Test: this test.
167 #[tokio::test]
168 async fn use_skill_errors_on_unknown() {
169 let tool = make_tool();
170 let result = tool.execute(json!({"name": "ghost-skill"})).await;
171 assert!(result.is_error());
172 assert!(result.content().contains("unknown skill"));
173 }
174
175 /// `use_skill` errors when the `name` argument is missing.
176 ///
177 /// Test: this test.
178 #[tokio::test]
179 async fn use_skill_errors_on_missing_name() {
180 let tool = make_tool();
181 let result = tool.execute(json!({})).await;
182 assert!(result.is_error());
183 assert!(result.content().contains("missing required argument"));
184 }
185
186 /// `use_skill` rejects a path-traversal payload in a namespaced
187 /// `<plugin>:<name>` argument end-to-end — through the REAL
188 /// `skills::FsSkillResolver` (not the in-memory `StubResolver` the
189 /// other tests here use), which is what actually backs this tool in
190 /// production (code-critic PR #3547 review, CRITICAL 2).
191 ///
192 /// Why: `UseSkillTool::execute` forwards the LLM's raw `name` argument
193 /// straight to `resolver.resolve()` with no validation of its own — the
194 /// guard must live in the resolver, and this test proves it actually
195 /// does, using the exact production wiring. A real "secret" file sits
196 /// at the traversal target outside the plugin's `skills_dir`; if the
197 /// guard did not fire, both payloads would resolve to it.
198 /// What: a tempdir shaped `<root>/.claude/skills` (empty) +
199 /// `<root>/.claude/plugins/my-plugin/skills/demo-skill/SKILL.md`;
200 /// `name: "my-plugin:../../secret"` and `name: "my-plugin:.."` both
201 /// error, and the returned error never contains the secret's content.
202 /// Test: this test.
203 #[tokio::test]
204 async fn use_skill_rejects_plugin_traversal_end_to_end() {
205 let tmp = tempfile::tempdir().expect("tempdir");
206 let skills_dir = tmp.path().join(".claude").join("skills");
207 std::fs::create_dir_all(&skills_dir).expect("mkdir skills");
208
209 let plugin_skills_dir = tmp
210 .path()
211 .join(".claude")
212 .join("plugins")
213 .join("my-plugin")
214 .join("skills");
215 std::fs::create_dir_all(plugin_skills_dir.join("demo-skill")).expect("mkdir");
216 std::fs::write(
217 plugin_skills_dir.join("demo-skill").join("SKILL.md"),
218 "---\nname: demo-skill\n---\n\nDemo body.\n",
219 )
220 .expect("write demo skill");
221
222 // The traversal target, one level above `.claude/plugins/my-plugin/skills/`.
223 let secret_dir = tmp.path().join(".claude").join("plugins").join("secret");
224 std::fs::create_dir_all(&secret_dir).expect("mkdir secret");
225 std::fs::write(
226 secret_dir.join("SKILL.md"),
227 "---\nname: secret\n---\n\nSHOULD NEVER BE READ.\n",
228 )
229 .expect("write secret");
230
231 let resolver: Arc<dyn SkillResolver> =
232 Arc::new(crate::skills::FsSkillResolver::new(skills_dir));
233 let tool = UseSkillTool::new(resolver);
234
235 for payload in ["my-plugin:../secret", "my-plugin:.."] {
236 let result = tool.execute(json!({"name": payload})).await;
237 assert!(result.is_error(), "payload {payload:?} must be rejected");
238 assert!(
239 !result.content().contains("SHOULD NEVER BE READ"),
240 "payload {payload:?} must never read the secret file, got: {}",
241 result.content()
242 );
243 }
244 }
245
246 /// `use_skill` with `name: "my-plugin:leak"` — a validly-namespaced,
247 /// validly-pathed name whose `SKILL.md` is a symlink escaping the
248 /// plugin's `skills/` directory — is rejected end-to-end through the
249 /// REAL `skills::FsSkillResolver`, and the secret content it points at
250 /// never reaches the tool result (code-critic PR #3547 re-review,
251 /// CRITICAL 5, CWE-59).
252 ///
253 /// Why: `is_valid_namespaced_name` and the directory guard both pass
254 /// for `my-plugin:leak` — only the LEAF FILE identity is wrong. This
255 /// proves `plugins::skills::resolve_plugin_skill_body`'s containment
256 /// check actually fires on the exact production path `use_skill`
257 /// drives.
258 /// Test: this test.
259 #[tokio::test]
260 #[cfg(unix)]
261 async fn use_skill_rejects_symlinked_plugin_skill_leak() {
262 let tmp = tempfile::tempdir().expect("tempdir");
263 let skills_dir = tmp.path().join(".claude").join("skills");
264 std::fs::create_dir_all(&skills_dir).expect("mkdir skills");
265
266 let leak_skill_dir = tmp
267 .path()
268 .join(".claude")
269 .join("plugins")
270 .join("my-plugin")
271 .join("skills")
272 .join("leak");
273 std::fs::create_dir_all(&leak_skill_dir).expect("mkdir leak dir");
274
275 let secret_dir = tmp.path().join("outside");
276 std::fs::create_dir_all(&secret_dir).expect("mkdir");
277 let secret_path = secret_dir.join("id_rsa");
278 std::fs::write(&secret_path, "SECRET_KEY_MATERIAL").expect("write secret");
279 std::os::unix::fs::symlink(&secret_path, leak_skill_dir.join("SKILL.md")).expect("symlink");
280
281 let resolver: Arc<dyn SkillResolver> =
282 Arc::new(crate::skills::FsSkillResolver::new(skills_dir));
283 let tool = UseSkillTool::new(resolver);
284
285 let result = tool.execute(json!({"name": "my-plugin:leak"})).await;
286
287 assert!(result.is_error(), "symlinked plugin skill must be rejected");
288 assert!(
289 !result.content().contains("SECRET_KEY_MATERIAL"),
290 "the secret content must never appear in the tool result, got: {}",
291 result.content()
292 );
293 }
294
295 /// `name()` and the schema's `function.name` both match
296 /// `USE_SKILL_TOOL_NAME` — no drift between the constant and the wire
297 /// name (#2070 depends on this identifying skill outputs for pinning).
298 ///
299 /// Test: this test.
300 #[test]
301 fn name_matches_constant() {
302 let tool = make_tool();
303 assert_eq!(tool.name(), USE_SKILL_TOOL_NAME);
304 assert_eq!(
305 tool.schema()["function"]["name"].as_str(),
306 Some(USE_SKILL_TOOL_NAME)
307 );
308 assert_eq!(USE_SKILL_TOOL_NAME, "use_skill");
309 }
310
311 /// The schema requires `name`.
312 ///
313 /// Test: this test.
314 #[test]
315 fn use_skill_schema_has_required_name() {
316 let tool = make_tool();
317 let schema = tool.schema();
318 let required = schema["function"]["parameters"]["required"]
319 .as_array()
320 .expect("required array");
321 assert!(required.iter().any(|v| v.as_str() == Some("name")));
322 }
323}