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 /// `name()` and the schema's `function.name` both match
187 /// `USE_SKILL_TOOL_NAME` — no drift between the constant and the wire
188 /// name (#2070 depends on this identifying skill outputs for pinning).
189 ///
190 /// Test: this test.
191 #[test]
192 fn name_matches_constant() {
193 let tool = make_tool();
194 assert_eq!(tool.name(), USE_SKILL_TOOL_NAME);
195 assert_eq!(
196 tool.schema()["function"]["name"].as_str(),
197 Some(USE_SKILL_TOOL_NAME)
198 );
199 assert_eq!(USE_SKILL_TOOL_NAME, "use_skill");
200 }
201
202 /// The schema requires `name`.
203 ///
204 /// Test: this test.
205 #[test]
206 fn use_skill_schema_has_required_name() {
207 let tool = make_tool();
208 let schema = tool.schema();
209 let required = schema["function"]["parameters"]["required"]
210 .as_array()
211 .expect("required array");
212 assert!(required.iter().any(|v| v.as_str() == Some("name")));
213 }
214}