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        let result = executor.execute_tool_call(&call).await.unwrap().unwrap();
114        assert!(result.summary.contains("## Instructions"));
115        assert!(result.summary.contains("Do git stuff"));
116    }
117
118    #[tokio::test]
119    async fn load_nonexistent_skill_returns_error_message() {
120        let dir = tempfile::tempdir().unwrap();
121        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
122        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
123        let call = ToolCall {
124            tool_id: zeph_common::ToolName::new("load_skill"),
125            params: serde_json::json!({"skill_name": "nonexistent"})
126                .as_object()
127                .unwrap()
128                .clone(),
129            caller_id: None,
130            context: None,
131        };
132        let result = executor.execute_tool_call(&call).await.unwrap().unwrap();
133        assert!(result.summary.contains("skill not found"));
134        assert!(result.summary.contains("nonexistent"));
135    }
136
137    #[test]
138    fn tool_definitions_returns_load_skill() {
139        let dir = tempfile::tempdir().unwrap();
140        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
141        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
142        let defs = executor.tool_definitions();
143        assert_eq!(defs.len(), 1);
144        assert_eq!(defs[0].id.as_ref(), "load_skill");
145    }
146
147    #[tokio::test]
148    async fn execute_returns_none_for_wrong_tool_id() {
149        let dir = tempfile::tempdir().unwrap();
150        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
151        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
152        let call = ToolCall {
153            tool_id: zeph_common::ToolName::new("bash"),
154            params: serde_json::Map::new(),
155            caller_id: None,
156            context: None,
157        };
158        let result = executor.execute_tool_call(&call).await.unwrap();
159        assert!(result.is_none());
160    }
161
162    #[tokio::test]
163    async fn long_skill_body_is_truncated() {
164        use zeph_tools::executor::MAX_TOOL_OUTPUT_CHARS;
165        let dir = tempfile::tempdir().unwrap();
166        let long_body = "x".repeat(MAX_TOOL_OUTPUT_CHARS + 1000);
167        let registry = make_registry_with_skill(dir.path(), "big-skill", &long_body);
168        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
169        let call = ToolCall {
170            tool_id: zeph_common::ToolName::new("load_skill"),
171            params: serde_json::json!({"skill_name": "big-skill"})
172                .as_object()
173                .unwrap()
174                .clone(),
175            caller_id: None,
176            context: None,
177        };
178        let result = executor.execute_tool_call(&call).await.unwrap().unwrap();
179        assert!(result.summary.contains("truncated"));
180        assert!(result.summary.len() < long_body.len() + 200);
181    }
182
183    #[tokio::test]
184    async fn empty_registry_returns_error_message() {
185        let dir = tempfile::tempdir().unwrap();
186        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
187        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
188        let call = ToolCall {
189            tool_id: zeph_common::ToolName::new("load_skill"),
190            params: serde_json::json!({"skill_name": "any"})
191                .as_object()
192                .unwrap()
193                .clone(),
194            caller_id: None,
195            context: None,
196        };
197        let result = executor.execute_tool_call(&call).await.unwrap().unwrap();
198        assert!(result.summary.contains("skill not found"));
199    }
200
201    // GAP-1: direct execute() always returns None
202    #[tokio::test]
203    async fn execute_always_returns_none() {
204        let dir = tempfile::tempdir().unwrap();
205        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
206        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
207        let result = executor.execute("any response text").await.unwrap();
208        assert!(result.is_none());
209    }
210
211    // GAP-2: concurrent reads all succeed
212    #[tokio::test]
213    async fn concurrent_execute_tool_call_succeeds() {
214        let dir = tempfile::tempdir().unwrap();
215        let registry =
216            make_registry_with_skill(dir.path(), "shared-skill", "## Concurrent test body");
217        let executor = Arc::new(SkillLoaderExecutor::new(Arc::new(RwLock::new(registry))));
218
219        let handles: Vec<_> = (0..8)
220            .map(|_| {
221                let ex = Arc::clone(&executor);
222                tokio::spawn(async move {
223                    let call = ToolCall {
224                        tool_id: zeph_common::ToolName::new("load_skill"),
225                        params: serde_json::json!({"skill_name": "shared-skill"})
226                            .as_object()
227                            .unwrap()
228                            .clone(),
229                        caller_id: None,
230                        context: None,
231                    };
232                    ex.execute_tool_call(&call).await
233                })
234            })
235            .collect();
236
237        for h in handles {
238            let result = h.await.unwrap().unwrap().unwrap();
239            assert!(result.summary.contains("## Concurrent test body"));
240        }
241    }
242
243    // GAP-3: empty skill_name returns "not found"
244    #[tokio::test]
245    async fn empty_skill_name_returns_not_found() {
246        let dir = tempfile::tempdir().unwrap();
247        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
248        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
249        let call = ToolCall {
250            tool_id: zeph_common::ToolName::new("load_skill"),
251            params: serde_json::json!({"skill_name": ""})
252                .as_object()
253                .unwrap()
254                .clone(),
255            caller_id: None,
256            context: None,
257        };
258        let result = executor.execute_tool_call(&call).await.unwrap().unwrap();
259        assert!(result.summary.contains("skill not found"));
260    }
261
262    // GAP-4: missing skill_name field returns ToolError from deserialize_params
263    #[tokio::test]
264    async fn missing_skill_name_field_returns_error() {
265        let dir = tempfile::tempdir().unwrap();
266        let registry = SkillRegistry::load(&[dir.path().to_path_buf()]);
267        let executor = SkillLoaderExecutor::new(Arc::new(RwLock::new(registry)));
268        let call = ToolCall {
269            tool_id: zeph_common::ToolName::new("load_skill"),
270            params: serde_json::Map::new(),
271            caller_id: None,
272            context: None,
273        };
274        let result = executor.execute_tool_call(&call).await;
275        assert!(result.is_err());
276    }
277}