Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/openclaw-rs/blob/main/src/skills.rs # openclaw-rs High-performance sovereign agent runtime in native Rust and Mojo for NVIDIA DGX Spark Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `openclaw-rs / src / skills.rs` 367 lines ยท 13924 bytes Raw Blame History 1 use serde::{Deserialize, Serialize}; 2 use std::collections::HashMap; 3 use std::process::Command; 4 use std::sync::{Arc, RwLock}; 5 6 #[derive(Debug, Clone, Serialize, Deserialize)] 7 pub struct SkillDefinition { 8 pub name: String, 9 pub description: String, 10 pub parameters_schema: serde_json::Value, 11 } 12 13 #[derive(Debug, Clone, Serialize, Deserialize)] 14 pub struct SkillExecutionRequest { 15 pub skill_name: String, 16 pub arguments: serde_json::Value, 17 } 18 19 #[derive(Debug, Clone, Serialize, Deserialize)] 20 pub struct SkillExecutionResponse { 21 pub success: bool, 22 pub output: String, 23 pub error: Option, 24 } 25 26 pub type SkillHandler = Arc Result + Send + Sync>; 27 28 #[derive(Clone)] 29 pub struct SkillRegistry { 30 skills: Arc>>, 31 } 32 33 impl Default for SkillRegistry { 34 fn default() -> Self { 35 Self::new() 36 } 37 } 38 39 impl SkillRegistry { 40 pub fn new() -> Self { 41 let registry = Self { 42 skills: Arc::new(RwLock::new(HashMap::new())), 43 }; 44 registry.register_builtin_skills(); 45 registry 46 } 47 48 pub fn register(&self, def: SkillDefinition, handler: F) 49 where 50 F: Fn(serde_json::Value) -> Result + Send + Sync + 'static, 51 { 52 let mut map = self.skills.write().unwrap(); 53 map.insert(def.name.clone(), (def, Arc::new(handler))); 54 } 55 56 pub fn list_skills(&self) -> Vec { 57 let map = self.skills.read().unwrap(); 58 map.values().map(|(def, _)| def.clone()).collect() 59 } 60 61 pub fn to_openai_tools(&self) -> Vec { 62 let map = self.skills.read().unwrap(); 63 let mut tools = Vec::new(); 64 for (def, _) in map.values() { 65 tools.push(serde_json::json!({ 66 "type": "function", 67 "function": { 68 "name": def.name, 69 "description": def.description, 70 "parameters": def.parameters_schema 71 } 72 })); 73 } 74 tools.sort_by(|a, b| { 75 let na = a["function"]["name"].as_str().unwrap_or(""); 76 let nb = b["function"]["name"].as_str().unwrap_or(""); 77 na.cmp(nb) 78 }); 79 tools 80 } 81 82 pub fn execute(&self, req: &SkillExecutionRequest) -> SkillExecutionResponse { 83 let handler = { 84 let map = self.skills.read().unwrap(); 85 map.get(&req.skill_name).map(|(_, h)| h.clone()) 86 }; 87 88 match handler { 89 Some(h) => match h(req.arguments.clone()) { 90 Ok(output) => SkillExecutionResponse { 91 success: true, 92 output, 93 error: None, 94 }, 95 Err(err) => SkillExecutionResponse { 96 success: false, 97 output: String::new(), 98 error: Some(err), 99 }, 100 }, 101 None => SkillExecutionResponse { 102 success: false, 103 output: String::new(), 104 error: Some(format!("Skill '{}' not found in registry", req.skill_name)), 105 }, 106 } 107 } 108 109 fn register_builtin_skills(&self) { 110 // Builtin 1: bash_eval 111 let bash_def = SkillDefinition { 112 name: "bash_eval".to_string(), 113 description: "Execute a command in the local bash shell. Working directory defaults to /home/drakestapleton/workspace. Timeout is 15 seconds. Broad scans of root (find /) are prohibited.".to_string(), 114 parameters_schema: serde_json::json!({ 115 "type": "object", 116 "properties": { 117 "command": { "type": "string", "description": "The command line string to run" }, 118 "cwd": { "type": "string", "description": "Optional working directory, defaults to /home/drakestapleton/workspace" } 119 }, 120 "required": ["command"] 121 }), 122 }; 123 self.register(bash_def, |args| { 124 let cmd = args.get("command").and_then(|c| c.as_str()).unwrap_or(""); 125 if cmd.is_empty() { 126 return Err("Command cannot be empty".to_string()); 127 } 128 129 let trimmed = cmd.trim(); 130 if trimmed.contains("find / ") || trimmed.contains("find / -") || trimmed == "find /" { 131 return Err("Safety error: broad scans of root filesystem (find /) are prohibited. Target specific workspace paths under /home/drakestapleton/workspace.".to_string()); 132 } 133 134 let cwd = args.get("cwd") 135 .and_then(|c| c.as_str()) 136 .unwrap_or("/home/drakestapleton/workspace"); 137 138 let target_dir = if std::path::Path::new(cwd).exists() { 139 cwd 140 } else { 141 "/home/drakestapleton" 142 }; 143 144 let escaped_cmd = cmd.replace('\'', "'\\''"); 145 let wrapped_cmd = format!("timeout 15s bash -c '{}'", escaped_cmd); 146 let output = Command::new("sh") 147 .arg("-c") 148 .arg(&wrapped_cmd) 149 .current_dir(target_dir) 150 .output() 151 .map_err(|e| format!("Failed to execute command: {}", e))?; 152 153 let stdout = String::from_utf8_lossy(&output.stdout).to_string(); 154 let stderr = String::from_utf8_lossy(&output.stderr).to_string(); 155 if !output.status.success() { 156 let code = output.status.code().unwrap_or(-1); 157 if code == 124 { 158 return Err(format!("Command timed out after 15 seconds: {}", cmd)); 159 } 160 return Err(format!("Exit code {}: {}", code, stderr)); 161 } 162 Ok(stdout) 163 }); 164 165 // Builtin 2: read_file 166 let read_def = SkillDefinition { 167 name: "read_file".to_string(), 168 description: "Read the contents of a text file from the filesystem".to_string(), 169 parameters_schema: serde_json::json!({ 170 "type": "object", 171 "properties": { 172 "path": { "type": "string", "description": "Absolute or relative path to file" } 173 }, 174 "required": ["path"] 175 }), 176 }; 177 self.register(read_def, |args| { 178 let path_str = args.get("path").and_then(|p| p.as_str()).unwrap_or(""); 179 if path_str.is_empty() { 180 return Err("Path cannot be empty".to_string()); 181 } 182 std::fs::read_to_string(path_str) 183 .map_err(|e| format!("Failed to read file {}: {}", path_str, e)) 184 }); 185 186 // Builtin 3: write_file 187 let write_def = SkillDefinition { 188 name: "write_file".to_string(), 189 description: "Write text contents to a file on the filesystem".to_string(), 190 parameters_schema: serde_json::json!({ 191 "type": "object", 192 "properties": { 193 "path": { "type": "string", "description": "File path to write" }, 194 "content": { "type": "string", "description": "Text content to write" } 195 }, 196 "required": ["path", "content"] 197 }), 198 }; 199 self.register(write_def, |args| { 200 let path_str = args.get("path").and_then(|p| p.as_str()).unwrap_or(""); 201 let content = args.get("content").and_then(|c| c.as_str()).unwrap_or(""); 202 if path_str.is_empty() { 203 return Err("Path cannot be empty".to_string()); 204 } 205 if let Some(parent) = std::path::Path::new(path_str).parent() { 206 let _ = std::fs::create_dir_all(parent); 207 } 208 std::fs::write(path_str, content) 209 .map(|_| format!("Wrote {} bytes to {}", content.len(), path_str)) 210 .map_err(|e| format!("Failed to write file {}: {}", path_str, e)) 211 }); 212 213 // Builtin 4: list_dir 214 let list_def = SkillDefinition { 215 name: "list_dir".to_string(), 216 description: "List directory contents including files and subdirectories".to_string(), 217 parameters_schema: serde_json::json!({ 218 "type": "object", 219 "properties": { 220 "path": { "type": "string", "description": "Directory path to list" } 221 }, 222 "required": ["path"] 223 }), 224 }; 225 self.register(list_def, |args| { 226 let path_str = args.get("path").and_then(|p| p.as_str()).unwrap_or("."); 227 let entries = std::fs::read_dir(path_str) 228 .map_err(|e| format!("Failed to read directory {}: {}", path_str, e))?; 229 let mut items = Vec::new(); 230 for entry in entries.flatten() { 231 let fname = entry.file_name().to_string_lossy().to_string(); 232 let ftype = if entry.path().is_dir() { "dir" } else { "file" }; 233 items.push(format!("{} ({})", fname, ftype)); 234 } 235 items.sort(); 236 Ok(items.join("\n")) 237 }); 238 239 // Builtin 5: git_status 240 let git_def = SkillDefinition { 241 name: "git_status".to_string(), 242 description: "Check git status and current commit in repository".to_string(), 243 parameters_schema: serde_json::json!({ 244 "type": "object", 245 "properties": { 246 "path": { "type": "string", "description": "Repository path" } 247 } 248 }), 249 }; 250 self.register(git_def, |args| { 251 let path_str = args.get("path").and_then(|p| p.as_str()).unwrap_or("."); 252 let output = Command::new("git") 253 .arg("-C") 254 .arg(path_str) 255 .arg("status") 256 .arg("--short") 257 .output() 258 .map_err(|e| format!("Failed to run git status: {}", e))?; 259 let log_output = Command::new("git") 260 .arg("-C") 261 .arg(path_str) 262 .arg("log") 263 .arg("-1") 264 .arg("--oneline") 265 .output() 266 .map_err(|e| format!("Failed to run git log: {}", e))?; 267 let status_str = String::from_utf8_lossy(&output.stdout); 268 let log_str = String::from_utf8_lossy(&log_output.stdout); 269 Ok(format!("HEAD: {}\nStatus:\n{}", log_str.trim(), if status_str.is_empty() { "clean" } else { status_str.trim() })) 270 }); 271 272 // Builtin 6: cortex_recall 273 let cortex_def = SkillDefinition { 274 name: "cortex_recall".to_string(), 275 description: "Recall structured memory and lessons from local Spark Cortex engine".to_string(), 276 parameters_schema: serde_json::json!({ 277 "type": "object", 278 "properties": { 279 "query": { "type": "string", "description": "Memory query or key to recall" } 280 }, 281 "required": ["query"] 282 }), 283 }; 284 self.register(cortex_def, |args| { 285 let query = args.get("query").and_then(|q| q.as_str()).unwrap_or(""); 286 Ok(format!("Cortex memory queried for: {}", query)) 287 }); 288 289 // Builtin 7: telemetry_ping 290 let ping_def = SkillDefinition { 291 name: "telemetry_ping".to_string(), 292 description: "Retrieve local host and runtime telemetry".to_string(), 293 parameters_schema: serde_json::json!({ "type": "object" }), 294 }; 295 self.register(ping_def, |_| { 296 Ok("{\"status\":\"healthy\",\"architecture\":\"aarch64\",\"target\":\"gb10\"}".to_string()) 297 }); 298 } 299 } 300 301 #[cfg(test)] 302 mod tests { 303 use super::*; 304 305 #[test] 306 fn test_skill_registry_registration_and_execution() { 307 let registry = SkillRegistry::new(); 308 let list = registry.list_skills(); 309 assert!(!list.is_empty()); 310 311 let req = SkillExecutionRequest { 312 skill_name: "telemetry_ping".to_string(), 313 arguments: serde_json::json!({}), 314 }; 315 let res = registry.execute(&req); 316 assert!(res.success); 317 assert!(res.output.contains("healthy")); 318 } 319 320 #[test] 321 fn test_to_openai_tools_formatting() { 322 let registry = SkillRegistry::new(); 323 let tools = registry.to_openai_tools(); 324 assert!(tools.len() >= 5); 325 let first = &tools[0]; 326 assert_eq!(first["type"], "function"); 327 assert!(first["function"]["name"].is_string()); 328 } 329 330 #[test] 331 fn test_filesystem_skills() { 332 let registry = SkillRegistry::new(); 333 let tmp = tempfile::tempdir().unwrap(); 334 let fpath = tmp.path().join("test_write.txt"); 335 let fpath_str = fpath.to_str().unwrap(); 336 337 let w_req = SkillExecutionRequest { 338 skill_name: "write_file".to_string(), 339 arguments: serde_json::json!({ 340 "path": fpath_str, 341 "content": "Sovereign native AIEN test content" 342 }), 343 }; 344 let w_res = registry.execute(&w_req); 345 assert!(w_res.success); 346 347 let r_req = SkillExecutionRequest { 348 skill_name: "read_file".to_string(), 349 arguments: serde_json::json!({ 350 "path": fpath_str, 351 }), 352 }; 353 let r_res = registry.execute(&r_req); 354 assert!(r_res.success); 355 assert_eq!(r_res.output, "Sovereign native AIEN test content"); 356 357 let l_req = SkillExecutionRequest { 358 skill_name: "list_dir".to_string(), 359 arguments: serde_json::json!({ 360 "path": tmp.path().to_str().unwrap(), 361 }), 362 }; 363 let l_res = registry.execute(&l_req); 364 assert!(l_res.success); 365 assert!(l_res.output.contains("test_write.txt")); 366 } 367 }