Skip to main content

zeph_core/
skill_loader.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::sync::Arc;
5
6use parking_lot::RwLock;
7
8use schemars::JsonSchema;
9use serde::Deserialize;
10use zeph_skills::registry::SkillRegistry;
11use zeph_tools::executor::{
12    ToolCall, ToolError, ToolExecutor, ToolOutput, deserialize_params, truncate_tool_output,
13};
14use zeph_tools::registry::{InvocationHint, ToolDef};
15
16#[derive(Debug, Deserialize, JsonSchema)]
17pub struct LoadSkillParams {
18    /// Name of the skill to load (from `<other_skills>` catalog).
19    pub skill_name: String,
20}
21
22/// Tool executor that loads a full skill body by name from the shared registry.
23#[derive(Clone, Debug)]
24pub struct SkillLoaderExecutor {
25    registry: Arc<RwLock<SkillRegistry>>,
26}
27
28impl SkillLoaderExecutor {
29    #[must_use]
30    pub fn new(registry: Arc<RwLock<SkillRegistry>>) -> Self {
31        Self { registry }
32    }
33}
34
35impl ToolExecutor for SkillLoaderExecutor {
36    async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
37        Ok(None)
38    }
39
40    fn tool_definitions(&self) -> Vec<ToolDef> {
41        vec![ToolDef {
42            id: "load_skill".into(),
43            description: "Load the full body of a skill by name when you see a relevant entry in the <other_skills> catalog.\n\nParameters: name (string, required) - exact skill name from the <other_skills> catalog\nReturns: complete skill instructions (SKILL.md body), or error if skill not found\nErrors: InvalidParams if name is empty; Execution if skill not found in registry\nExample: {\"name\": \"code-review\"}".into(),
44            schema: schemars::schema_for!(LoadSkillParams),
45            invocation: InvocationHint::ToolCall,
46            output_schema: None,
47        }]
48    }
49
50    async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
51        if call.tool_id != "load_skill" {
52            return Ok(None);
53        }
54        let params: LoadSkillParams = deserialize_params(&call.params)?;
55        let skill_name: String = params.skill_name.chars().take(128).collect();
56        let body = {
57            let guard = self.registry.read();
58            guard.body(&skill_name).map(str::to_owned)
59        };
60
61        let summary = match body {
62            Ok(b) => truncate_tool_output(&b),
63            Err(_) => format!("skill not found: {skill_name}"),
64        };
65
66        Ok(Some(ToolOutput {
67            tool_name: zeph_common::ToolName::new("load_skill"),
68            summary,
69            blocks_executed: 1,
70            filter_stats: None,
71            diff: None,
72            streamed: false,
73            terminal_id: None,
74            locations: None,
75            raw_response: None,
76            claim_source: None,
77        }))
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use std::path::Path;
84
85    use super::*;
86
87    fn make_registry_with_skill(dir: &Path, name: &str, body: &str) -> SkillRegistry {
88        let skill_dir = dir.join(name);
89        std::fs::create_dir_all(&skill_dir).unwrap();
90        std::fs::write(
91            skill_dir.join("SKILL.md"),
92            format!("---\nname: {name}\ndescription: test skill\n---\n{body}"),
93        )
94        .unwrap();
95        SkillRegistry::load(&[dir.to_path_buf()])
96    }
97
98    #[tokio::test]
99    async fn load_existing_skill_returns_body() {
100        let dir = tempfile::tempdir().unwrap();
101        let registry =
102            make_registry_with_skill(dir.path(), "git-commit", "## Instructions\nDo git stuff");
103        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
104        let call = ToolCall {
105            tool_id: zeph_common::ToolName::new("load_skill"),
106            params: serde_json::json!({"skill_name": "git-commit"})
107                .as_object()
108                .unwrap()
109                .clone(),
110            caller_id: None,
111            context: None,
112
113            tool_call_id: String::new(),
114        };
115        let result = executor.execute_tool_call(&call).await.unwrap().unwrap();
116        assert!(result.summary.contains("## Instructions"));
117        assert!(result.summary.contains("Do git stuff"));
118    }
119
120    #[tokio::test]
121    async fn load_nonexistent_skill_returns_error_message() {
122        let dir = tempfile::tempdir().unwrap();
123        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
124        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
125        let call = ToolCall {
126            tool_id: zeph_common::ToolName::new("load_skill"),
127            params: serde_json::json!({"skill_name": "nonexistent"})
128                .as_object()
129                .unwrap()
130                .clone(),
131            caller_id: None,
132            context: None,
133
134            tool_call_id: String::new(),
135        };
136        let result = executor.execute_tool_call(&call).await.unwrap().unwrap();
137        assert!(result.summary.contains("skill not found"));
138        assert!(result.summary.contains("nonexistent"));
139    }
140
141    #[test]
142    fn tool_definitions_returns_load_skill() {
143        let dir = tempfile::tempdir().unwrap();
144        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
145        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
146        let defs = executor.tool_definitions();
147        assert_eq!(defs.len(), 1);
148        assert_eq!(defs[0].id.as_ref(), "load_skill");
149    }
150
151    #[tokio::test]
152    async fn execute_returns_none_for_wrong_tool_id() {
153        let dir = tempfile::tempdir().unwrap();
154        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
155        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
156        let call = ToolCall {
157            tool_id: zeph_common::ToolName::new("bash"),
158            params: serde_json::Map::new(),
159            caller_id: None,
160            context: None,
161
162            tool_call_id: String::new(),
163        };
164        let result = executor.execute_tool_call(&call).await.unwrap();
165        assert!(result.is_none());
166    }
167
168    #[tokio::test]
169    async fn long_skill_body_is_truncated() {
170        use zeph_tools::executor::MAX_TOOL_OUTPUT_CHARS;
171        let dir = tempfile::tempdir().unwrap();
172        let long_body = "x".repeat(MAX_TOOL_OUTPUT_CHARS + 1000);
173        let registry = make_registry_with_skill(dir.path(), "big-skill", &long_body);
174        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
175        let call = ToolCall {
176            tool_id: zeph_common::ToolName::new("load_skill"),
177            params: serde_json::json!({"skill_name": "big-skill"})
178                .as_object()
179                .unwrap()
180                .clone(),
181            caller_id: None,
182            context: None,
183
184            tool_call_id: String::new(),
185        };
186        let result = executor.execute_tool_call(&call).await.unwrap().unwrap();
187        assert!(result.summary.contains("truncated"));
188        assert!(result.summary.len() < long_body.len() + 200);
189    }
190
191    #[tokio::test]
192    async fn empty_registry_returns_error_message() {
193        let dir = tempfile::tempdir().unwrap();
194        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
195        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
196        let call = ToolCall {
197            tool_id: zeph_common::ToolName::new("load_skill"),
198            params: serde_json::json!({"skill_name": "any"})
199                .as_object()
200                .unwrap()
201                .clone(),
202            caller_id: None,
203            context: None,
204
205            tool_call_id: String::new(),
206        };
207        let result = executor.execute_tool_call(&call).await.unwrap().unwrap();
208        assert!(result.summary.contains("skill not found"));
209    }
210
211    // GAP-1: direct execute() always returns None
212    #[tokio::test]
213    async fn execute_always_returns_none() {
214        let dir = tempfile::tempdir().unwrap();
215        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
216        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
217        let result = executor.execute("any response text").await.unwrap();
218        assert!(result.is_none());
219    }
220
221    // GAP-2: concurrent reads all succeed
222    #[tokio::test]
223    async fn concurrent_execute_tool_call_succeeds() {
224        let dir = tempfile::tempdir().unwrap();
225        let registry =
226            make_registry_with_skill(dir.path(), "shared-skill", "## Concurrent test body");
227        let executor = Arc::new(SkillLoaderExecutor::new(Arc::new(RwLock::new(registry))));
228
229        let handles: Vec<_> = (0..8)
230            .map(|_| {
231                let ex = Arc::clone(&executor);
232                tokio::spawn(async move {
233                    let call = ToolCall {
234                        tool_id: zeph_common::ToolName::new("load_skill"),
235                        params: serde_json::json!({"skill_name": "shared-skill"})
236                            .as_object()
237                            .unwrap()
238                            .clone(),
239                        caller_id: None,
240                        context: None,
241
242                        tool_call_id: String::new(),
243                    };
244                    ex.execute_tool_call(&call).await
245                })
246            })
247            .collect();
248
249        for h in handles {
250            let result = h.await.unwrap().unwrap().unwrap();
251            assert!(result.summary.contains("## Concurrent test body"));
252        }
253    }
254
255    // GAP-3: empty skill_name returns "not found"
256    #[tokio::test]
257    async fn empty_skill_name_returns_not_found() {
258        let dir = tempfile::tempdir().unwrap();
259        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
260        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
261        let call = ToolCall {
262            tool_id: zeph_common::ToolName::new("load_skill"),
263            params: serde_json::json!({"skill_name": ""})
264                .as_object()
265                .unwrap()
266                .clone(),
267            caller_id: None,
268            context: None,
269
270            tool_call_id: String::new(),
271        };
272        let result = executor.execute_tool_call(&call).await.unwrap().unwrap();
273        assert!(result.summary.contains("skill not found"));
274    }
275
276    // GAP-4: missing skill_name field returns ToolError from deserialize_params
277    #[tokio::test]
278    async fn missing_skill_name_field_returns_error() {
279        let dir = tempfile::tempdir().unwrap();
280        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
281        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
282        let call = ToolCall {
283            tool_id: zeph_common::ToolName::new("load_skill"),
284            params: serde_json::Map::new(),
285            caller_id: None,
286            context: None,
287
288            tool_call_id: String::new(),
289        };
290        let result = executor.execute_tool_call(&call).await;
291        assert!(result.is_err());
292    }
293}