aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / src / skills.rs
| 1 | use crate::failure::{ |
| 2 | skill_effect_profile, EffectCertainty, FailureClass, ToolDispatcher, ToolFault, |
| 3 | }; |
| 4 | use crate::security::WorkspaceCapability; |
| 5 | use serde::{Deserialize, Serialize}; |
| 6 | use std::collections::HashMap; |
| 7 | use std::process::Command; |
| 8 | use std::sync::{Arc, RwLock}; |
| 9 | |
| 10 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 11 | pub struct SkillDefinition { |
| 12 | pub name: String, |
| 13 | pub description: String, |
| 14 | pub parameters_schema: serde_json::Value, |
| 15 | /// False when the handler does not yet perform the contract. Those names |
| 16 | /// stay callable and return unavailable. They are not offered to the model. |
| 17 | #[serde(default = "default_advertised")] |
| 18 | pub advertised: bool, |
| 19 | } |
| 20 | |
| 21 | fn default_advertised() -> bool { |
| 22 | true |
| 23 | } |
| 24 | |
| 25 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 26 | pub struct SkillExecutionRequest { |
| 27 | pub skill_name: String, |
| 28 | pub arguments: serde_json::Value, |
| 29 | } |
| 30 | |
| 31 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 32 | pub struct SkillExecutionResponse { |
| 33 | pub success: bool, |
| 34 | pub output: String, |
| 35 | pub error: Option<String>, |
| 36 | } |
| 37 | |
| 38 | pub type SkillHandler = Arc<dyn Fn(serde_json::Value) -> Result<String, String> + Send + Sync>; |
| 39 | |
| 40 | #[derive(Clone)] |
| 41 | pub struct SkillRegistry { |
| 42 | skills: Arc<RwLock<HashMap<String, (SkillDefinition, SkillHandler)>>>, |
| 43 | workspace: Arc<WorkspaceCapability>, |
| 44 | } |
| 45 | |
| 46 | impl Default for SkillRegistry { |
| 47 | fn default() -> Self { |
| 48 | Self::new() |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | impl SkillRegistry { |
| 53 | pub fn new() -> Self { |
| 54 | Self::with_workspace(WorkspaceCapability::detect()) |
| 55 | } |
| 56 | |
| 57 | pub fn with_workspace(workspace: WorkspaceCapability) -> Self { |
| 58 | let registry = Self { |
| 59 | skills: Arc::new(RwLock::new(HashMap::new())), |
| 60 | workspace: Arc::new(workspace), |
| 61 | }; |
| 62 | registry.register_builtin_skills(); |
| 63 | registry |
| 64 | } |
| 65 | |
| 66 | pub fn workspace(&self) -> &WorkspaceCapability { |
| 67 | &self.workspace |
| 68 | } |
| 69 | |
| 70 | pub fn register<F>(&self, def: SkillDefinition, handler: F) |
| 71 | where |
| 72 | F: Fn(serde_json::Value) -> Result<String, String> + Send + Sync + 'static, |
| 73 | { |
| 74 | let mut map = self.skills.write().unwrap(); |
| 75 | map.insert(def.name.clone(), (def, Arc::new(handler))); |
| 76 | } |
| 77 | |
| 78 | pub fn list_skills(&self) -> Vec<SkillDefinition> { |
| 79 | let map = self.skills.read().unwrap(); |
| 80 | map.values().map(|(def, _)| def.clone()).collect() |
| 81 | } |
| 82 | |
| 83 | pub fn advertised_skills(&self) -> Vec<SkillDefinition> { |
| 84 | self.list_skills() |
| 85 | .into_iter() |
| 86 | .filter(|def| def.advertised) |
| 87 | .collect() |
| 88 | } |
| 89 | |
| 90 | pub fn to_openai_tools(&self) -> Vec<serde_json::Value> { |
| 91 | let map = self.skills.read().unwrap(); |
| 92 | let mut tools = Vec::new(); |
| 93 | for (def, _) in map.values() { |
| 94 | if !def.advertised { |
| 95 | continue; |
| 96 | } |
| 97 | tools.push(serde_json::json!({ |
| 98 | "type": "function", |
| 99 | "function": { |
| 100 | "name": def.name, |
| 101 | "description": def.description, |
| 102 | "parameters": def.parameters_schema |
| 103 | } |
| 104 | })); |
| 105 | } |
| 106 | tools.sort_by(|a, b| { |
| 107 | let na = a["function"]["name"].as_str().unwrap_or(""); |
| 108 | let nb = b["function"]["name"].as_str().unwrap_or(""); |
| 109 | na.cmp(nb) |
| 110 | }); |
| 111 | tools |
| 112 | } |
| 113 | |
| 114 | /// Membrane, then probe gate, then the handler. Every outside caller |
| 115 | /// (HTTP, WebSocket, agent tool calls) uses this path. |
| 116 | pub async fn execute_gated(&self, req: &SkillExecutionRequest) -> SkillExecutionResponse { |
| 117 | if let Err(reason) = crate::enforcement::probe_gate(&req.skill_name, &req.arguments).await { |
| 118 | return SkillExecutionResponse { |
| 119 | success: false, |
| 120 | output: String::new(), |
| 121 | error: Some(reason), |
| 122 | }; |
| 123 | } |
| 124 | self.execute(req) |
| 125 | } |
| 126 | |
| 127 | /// Same gates as `execute_gated` (probe gate, then membrane, then handler) |
| 128 | /// but returns a typed fault instead of a bare error string. Each call is a |
| 129 | /// fresh dispatch; nothing is cached between calls. |
| 130 | pub async fn dispatch_classified( |
| 131 | &self, |
| 132 | skill_name: &str, |
| 133 | arguments: &serde_json::Value, |
| 134 | ) -> Result<String, ToolFault> { |
| 135 | crate::enforcement::probe_gate(skill_name, arguments) |
| 136 | .await |
| 137 | .map_err(ToolFault::rejected)?; |
| 138 | crate::enforcement::pre_dispatch_check(skill_name, arguments) |
| 139 | .map_err(ToolFault::rejected)?; |
| 140 | let handler = { |
| 141 | let map = self.skills.read().unwrap(); |
| 142 | map.get(skill_name).map(|(_, h)| h.clone()) |
| 143 | }; |
| 144 | let Some(h) = handler else { |
| 145 | return Err(ToolFault::rejected(format!( |
| 146 | "Skill '{}' not found in registry", |
| 147 | skill_name |
| 148 | ))); |
| 149 | }; |
| 150 | h(arguments.clone()).map_err(|err| { |
| 151 | if err.starts_with("Unavailable") { |
| 152 | ToolFault::unavailable(err) |
| 153 | } else if skill_effect_profile(skill_name).idempotent { |
| 154 | ToolFault::new(FailureClass::Failed, EffectCertainty::NoEffect, err) |
| 155 | } else { |
| 156 | ToolFault::new(FailureClass::Failed, EffectCertainty::EffectOccurred, err) |
| 157 | } |
| 158 | }) |
| 159 | } |
| 160 | |
| 161 | pub fn execute(&self, req: &SkillExecutionRequest) -> SkillExecutionResponse { |
| 162 | if let Err(reason) = crate::enforcement::pre_dispatch_check(&req.skill_name, &req.arguments) |
| 163 | { |
| 164 | return SkillExecutionResponse { |
| 165 | success: false, |
| 166 | output: String::new(), |
| 167 | error: Some(reason), |
| 168 | }; |
| 169 | } |
| 170 | let handler = { |
| 171 | let map = self.skills.read().unwrap(); |
| 172 | map.get(&req.skill_name).map(|(_, h)| h.clone()) |
| 173 | }; |
| 174 | |
| 175 | match handler { |
| 176 | Some(h) => match h(req.arguments.clone()) { |
| 177 | Ok(output) => SkillExecutionResponse { |
| 178 | success: true, |
| 179 | output, |
| 180 | error: None, |
| 181 | }, |
| 182 | Err(err) => SkillExecutionResponse { |
| 183 | success: false, |
| 184 | output: String::new(), |
| 185 | error: Some(err), |
| 186 | }, |
| 187 | }, |
| 188 | None => SkillExecutionResponse { |
| 189 | success: false, |
| 190 | output: String::new(), |
| 191 | error: Some(format!("Skill '{}' not found in registry", req.skill_name)), |
| 192 | }, |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | fn register_builtin_skills(&self) { |
| 197 | // Builtin 1: bash_eval |
| 198 | let ws_bash = self.workspace.clone(); |
| 199 | let bash_def = SkillDefinition { |
| 200 | name: "bash_eval".to_string(), |
| 201 | description: format!( |
| 202 | "Run one catalogued local command inside {}. Allowed forms are exactly: git status, git diff, git log -1 --oneline, and ls. This is not an OS sandbox.", |
| 203 | ws_bash.root().display() |
| 204 | ), |
| 205 | parameters_schema: serde_json::json!({ |
| 206 | "type": "object", |
| 207 | "properties": { |
| 208 | "command": { "type": "string", "description": "The command line string to run" }, |
| 209 | "cwd": { "type": "string", "description": format!("Optional working directory inside authorized workspace {}", ws_bash.root().display()) } |
| 210 | }, |
| 211 | "required": ["command"] |
| 212 | }), |
| 213 | advertised: true, |
| 214 | }; |
| 215 | self.register(bash_def, move |args| { |
| 216 | let cmd = args.get("command").and_then(|c| c.as_str()).unwrap_or(""); |
| 217 | let cwd = args.get("cwd").and_then(|c| c.as_str()); |
| 218 | ws_bash |
| 219 | .dispatch_shell(cmd, cwd, 15) |
| 220 | .map_err(|e| e.to_string()) |
| 221 | }); |
| 222 | |
| 223 | // Builtin 2: read_file |
| 224 | let ws_read = self.workspace.clone(); |
| 225 | let read_def = SkillDefinition { |
| 226 | name: "read_file".to_string(), |
| 227 | description: |
| 228 | "Read the contents of a text file strictly within authorized workspace roots" |
| 229 | .to_string(), |
| 230 | parameters_schema: serde_json::json!({ |
| 231 | "type": "object", |
| 232 | "properties": { |
| 233 | "path": { "type": "string", "description": "Relative or absolute path inside the workspace root" } |
| 234 | }, |
| 235 | "required": ["path"] |
| 236 | }), |
| 237 | advertised: true, |
| 238 | }; |
| 239 | self.register(read_def, move |args| { |
| 240 | let path_str = args.get("path").and_then(|p| p.as_str()).unwrap_or(""); |
| 241 | let resolved = ws_read |
| 242 | .resolve_read_path(path_str) |
| 243 | .map_err(|e| e.to_string())?; |
| 244 | std::fs::read_to_string(&resolved) |
| 245 | .map_err(|e| format!("Failed to read file {}: {}", resolved.display(), e)) |
| 246 | }); |
| 247 | |
| 248 | // Builtin 3: write_file |
| 249 | let ws_write = self.workspace.clone(); |
| 250 | let write_def = SkillDefinition { |
| 251 | name: "write_file".to_string(), |
| 252 | description: "Write text contents to a file strictly within authorized workspace roots" |
| 253 | .to_string(), |
| 254 | parameters_schema: serde_json::json!({ |
| 255 | "type": "object", |
| 256 | "properties": { |
| 257 | "path": { "type": "string", "description": "Target file path inside the workspace root" }, |
| 258 | "content": { "type": "string", "description": "Text content to write" } |
| 259 | }, |
| 260 | "required": ["path", "content"] |
| 261 | }), |
| 262 | advertised: true, |
| 263 | }; |
| 264 | self.register(write_def, move |args| { |
| 265 | let path_str = args.get("path").and_then(|p| p.as_str()).unwrap_or(""); |
| 266 | let content = args.get("content").and_then(|c| c.as_str()).unwrap_or(""); |
| 267 | let resolved = ws_write |
| 268 | .write_file(path_str, content) |
| 269 | .map_err(|e| e.to_string())?; |
| 270 | Ok(format!( |
| 271 | "Wrote {} bytes to {}", |
| 272 | content.len(), |
| 273 | resolved.display() |
| 274 | )) |
| 275 | }); |
| 276 | |
| 277 | // Builtin 4: list_dir |
| 278 | let ws_list = self.workspace.clone(); |
| 279 | let list_def = SkillDefinition { |
| 280 | name: "list_dir".to_string(), |
| 281 | description: "List directory contents strictly within authorized workspace roots" |
| 282 | .to_string(), |
| 283 | parameters_schema: serde_json::json!({ |
| 284 | "type": "object", |
| 285 | "properties": { |
| 286 | "path": { "type": "string", "description": "Directory path inside workspace root" } |
| 287 | } |
| 288 | }), |
| 289 | advertised: true, |
| 290 | }; |
| 291 | self.register(list_def, move |args| { |
| 292 | let path_str = args.get("path").and_then(|p| p.as_str()); |
| 293 | let resolved = ws_list |
| 294 | .resolve_dir_path(path_str) |
| 295 | .map_err(|e| e.to_string())?; |
| 296 | let entries = std::fs::read_dir(&resolved) |
| 297 | .map_err(|e| format!("Failed to read directory {}: {}", resolved.display(), e))?; |
| 298 | let mut items = Vec::new(); |
| 299 | for entry in entries.flatten() { |
| 300 | let fname = entry.file_name().to_string_lossy().to_string(); |
| 301 | let ftype = if entry.path().is_dir() { "dir" } else { "file" }; |
| 302 | items.push(format!("{} ({})", fname, ftype)); |
| 303 | } |
| 304 | items.sort(); |
| 305 | Ok(items.join("\n")) |
| 306 | }); |
| 307 | |
| 308 | // Builtin 5: git_status |
| 309 | let ws_git = self.workspace.clone(); |
| 310 | let git_def = SkillDefinition { |
| 311 | name: "git_status".to_string(), |
| 312 | description: "Check git status and commit in repository strictly within authorized workspace root".to_string(), |
| 313 | parameters_schema: serde_json::json!({ |
| 314 | "type": "object", |
| 315 | "properties": { |
| 316 | "path": { "type": "string", "description": "Repository path inside workspace root" } |
| 317 | } |
| 318 | }), |
| 319 | advertised: true, |
| 320 | }; |
| 321 | self.register(git_def, move |args| { |
| 322 | let path_str = args.get("path").and_then(|p| p.as_str()); |
| 323 | let resolved = ws_git |
| 324 | .resolve_dir_path(path_str) |
| 325 | .map_err(|e| e.to_string())?; |
| 326 | let output = Command::new("git") |
| 327 | .arg("-C") |
| 328 | .arg(&resolved) |
| 329 | .arg("status") |
| 330 | .arg("--short") |
| 331 | .output() |
| 332 | .map_err(|e| format!("Failed to run git status: {}", e))?; |
| 333 | let log_output = Command::new("git") |
| 334 | .arg("-C") |
| 335 | .arg(&resolved) |
| 336 | .arg("log") |
| 337 | .arg("-1") |
| 338 | .arg("--oneline") |
| 339 | .output() |
| 340 | .map_err(|e| format!("Failed to run git log: {}", e))?; |
| 341 | let status_str = String::from_utf8_lossy(&output.stdout); |
| 342 | let log_str = String::from_utf8_lossy(&log_output.stdout); |
| 343 | Ok(format!( |
| 344 | "HEAD: {}\nStatus:\n{}", |
| 345 | log_str.trim(), |
| 346 | if status_str.is_empty() { |
| 347 | "clean" |
| 348 | } else { |
| 349 | status_str.trim() |
| 350 | } |
| 351 | )) |
| 352 | }); |
| 353 | |
| 354 | // cortex.search is the canonical tool. It is not connected, so it is |
| 355 | // not advertised. cortex_recall is the legacy alias and reports the same fact. |
| 356 | let search_def = SkillDefinition { |
| 357 | name: "cortex.search".to_string(), |
| 358 | description: "Search Cortex. Not connected.".to_string(), |
| 359 | parameters_schema: serde_json::json!({ |
| 360 | "type": "object", |
| 361 | "properties": { |
| 362 | "query": { "type": "string", "description": "Memory query" } |
| 363 | }, |
| 364 | "required": ["query"] |
| 365 | }), |
| 366 | advertised: false, |
| 367 | }; |
| 368 | self.register(search_def, |_| { |
| 369 | Err("Unavailable: cortex.search is not connected to a Cortex backend.".to_string()) |
| 370 | }); |
| 371 | let recall_def = SkillDefinition { |
| 372 | name: "cortex_recall".to_string(), |
| 373 | description: "Legacy alias of cortex.search. Not connected.".to_string(), |
| 374 | parameters_schema: serde_json::json!({ |
| 375 | "type": "object", |
| 376 | "properties": { |
| 377 | "query": { "type": "string", "description": "Memory query" } |
| 378 | }, |
| 379 | "required": ["query"] |
| 380 | }), |
| 381 | advertised: false, |
| 382 | }; |
| 383 | self.register(recall_def, |_| { |
| 384 | Err("Unavailable: cortex.search is not connected to a Cortex backend.".to_string()) |
| 385 | }); |
| 386 | |
| 387 | let ping_def = SkillDefinition { |
| 388 | name: "telemetry_ping".to_string(), |
| 389 | description: "Legacy name. Not connected.".to_string(), |
| 390 | parameters_schema: serde_json::json!({ "type": "object" }), |
| 391 | advertised: false, |
| 392 | }; |
| 393 | self.register(ping_def, |_| { |
| 394 | Err("Unavailable: telemetry.read is not connected.".to_string()) // no telemetry |
| 395 | }); |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | #[async_trait::async_trait] |
| 400 | impl ToolDispatcher for SkillRegistry { |
| 401 | async fn dispatch( |
| 402 | &self, |
| 403 | skill_name: &str, |
| 404 | arguments: &serde_json::Value, |
| 405 | ) -> Result<String, ToolFault> { |
| 406 | self.dispatch_classified(skill_name, arguments).await |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | #[cfg(test)] |
| 411 | mod tests { |
| 412 | use super::*; |
| 413 | |
| 414 | #[test] |
| 415 | fn test_skill_registry_registration_and_execution() { |
| 416 | let registry = SkillRegistry::new(); |
| 417 | let list = registry.list_skills(); |
| 418 | assert!(!list.is_empty()); |
| 419 | |
| 420 | let req = SkillExecutionRequest { |
| 421 | skill_name: "telemetry_ping".to_string(), |
| 422 | arguments: serde_json::json!({}), |
| 423 | }; |
| 424 | let res = registry.execute(&req); |
| 425 | assert!(!res.success); |
| 426 | let err = res.error.unwrap_or_default(); |
| 427 | assert!(err.contains("Unavailable")); |
| 428 | assert!(!registry.to_openai_tools().iter().any( |
| 429 | |tool| tool["function"]["name"] == "telemetry_ping" // no telemetry |
| 430 | || tool["function"]["name"] == "cortex_recall" |
| 431 | || tool["function"]["name"] == "cortex.search" |
| 432 | )); |
| 433 | } |
| 434 | |
| 435 | #[test] |
| 436 | fn test_to_openai_tools_formatting() { |
| 437 | let registry = SkillRegistry::new(); |
| 438 | let tools = registry.to_openai_tools(); |
| 439 | assert!(tools.len() >= 5); |
| 440 | let first = &tools[0]; |
| 441 | assert_eq!(first["type"], "function"); |
| 442 | assert!(first["function"]["name"].is_string()); |
| 443 | } |
| 444 | |
| 445 | #[test] |
| 446 | fn test_filesystem_skills_with_workspace_containment() { |
| 447 | let tmp = tempfile::tempdir().unwrap(); |
| 448 | let cap = WorkspaceCapability::new(tmp.path()).unwrap(); |
| 449 | let registry = SkillRegistry::with_workspace(cap); |
| 450 | |
| 451 | let w_req = SkillExecutionRequest { |
| 452 | skill_name: "write_file".to_string(), |
| 453 | arguments: serde_json::json!({ |
| 454 | "path": "test_write.txt", |
| 455 | "content": "Sovereign native AIEN test content" |
| 456 | }), |
| 457 | }; |
| 458 | let w_res = registry.execute(&w_req); |
| 459 | assert!(w_res.success); |
| 460 | |
| 461 | let r_req = SkillExecutionRequest { |
| 462 | skill_name: "read_file".to_string(), |
| 463 | arguments: serde_json::json!({ |
| 464 | "path": "test_write.txt", |
| 465 | }), |
| 466 | }; |
| 467 | let r_res = registry.execute(&r_req); |
| 468 | assert!(r_res.success); |
| 469 | assert_eq!(r_res.output, "Sovereign native AIEN test content"); |
| 470 | |
| 471 | let l_req = SkillExecutionRequest { |
| 472 | skill_name: "list_dir".to_string(), |
| 473 | arguments: serde_json::json!({ |
| 474 | "path": ".", |
| 475 | }), |
| 476 | }; |
| 477 | let l_res = registry.execute(&l_req); |
| 478 | assert!(l_res.success); |
| 479 | assert!(l_res.output.contains("test_write.txt")); |
| 480 | |
| 481 | // Test security escape rejection |
| 482 | let escape_req = SkillExecutionRequest { |
| 483 | skill_name: "read_file".to_string(), |
| 484 | arguments: serde_json::json!({ |
| 485 | "path": "../../etc/passwd", |
| 486 | }), |
| 487 | }; |
| 488 | let escape_res = registry.execute(&escape_req); |
| 489 | assert!(!escape_res.success); |
| 490 | assert!(escape_res.error.unwrap().contains("Security rejection")); |
| 491 | } |
| 492 | |
| 493 | #[cfg(target_os = "linux")] |
| 494 | #[test] |
| 495 | fn write_file_refuses_symlink_escape() { |
| 496 | use std::os::unix::fs::symlink; |
| 497 | |
| 498 | let workspace = tempfile::tempdir().unwrap(); |
| 499 | let outside = tempfile::tempdir().unwrap(); |
| 500 | let victim = outside.path().join("victim"); |
| 501 | std::fs::write(&victim, "original").unwrap(); |
| 502 | symlink(&victim, workspace.path().join("leaf")).unwrap(); |
| 503 | symlink(outside.path(), workspace.path().join("parent")).unwrap(); |
| 504 | let registry = |
| 505 | SkillRegistry::with_workspace(WorkspaceCapability::new(workspace.path()).unwrap()); |
| 506 | for path in ["leaf", "parent/victim", "parent/new", "../outside"] { |
| 507 | let result = registry.execute(&SkillExecutionRequest { |
| 508 | skill_name: "write_file".into(), |
| 509 | arguments: serde_json::json!({"path": path, "content": "overwritten"}), |
| 510 | }); |
| 511 | assert!(!result.success, "unexpectedly wrote {path}"); |
| 512 | } |
| 513 | assert_eq!(std::fs::read_to_string(&victim).unwrap(), "original"); |
| 514 | assert!(!outside.path().join("new").exists()); |
| 515 | |
| 516 | let result = registry.execute(&SkillExecutionRequest { |
| 517 | skill_name: "write_file".into(), |
| 518 | arguments: serde_json::json!({"path": "nested/ok", "content": "allowed"}), |
| 519 | }); |
| 520 | assert!(result.success, "{:?}", result.error); |
| 521 | assert_eq!( |
| 522 | std::fs::read_to_string(workspace.path().join("nested/ok")).unwrap(), |
| 523 | "allowed" |
| 524 | ); |
| 525 | } |
| 526 | } |