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