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/aien-sovereign-core-mv/blob/main/crates/aien-cli/src/skills.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. 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 `aien-sovereign-core-mv / crates / aien-cli / src / skills.rs` 536 lines ยท 19936 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 use colored::*; 17 use serde::{Deserialize, Serialize}; 18 use serde_json::{json, Value}; 19 use std::collections::HashSet; 20 use std::fs; 21 use std::fs::File; 22 use std::io::Read; 23 use std::path::Path; 24 25 const SKILL_METADATA_BYTE_LIMIT: u64 = 16 * 1024; 26 const PREVIEW_BYTE_LIMIT: u64 = 32 * 1024; 27 const SEARCH_BYTE_LIMIT: u64 = 256 * 1024; 28 const DEFAULT_PREVIEW_TOKENS: usize = 96; 29 const MAX_PREVIEW_TOKENS: usize = 256; 30 const DEFAULT_SEARCH_SNIPPET_TOKENS: usize = 80; 31 32 #[derive(Debug, Clone, Serialize, Deserialize)] 33 pub struct Skill { 34 pub name: String, 35 pub description: String, 36 pub path: String, 37 pub has_scripts: bool, 38 } 39 40 fn extract_frontmatter_field(content: &str, field: &str) -> Option { 41 let mut in_frontmatter = false; 42 for line in content.lines() { 43 let trimmed = line.trim(); 44 if trimmed == "---" { 45 if in_frontmatter { 46 break; 47 } else { 48 in_frontmatter = true; 49 continue; 50 } 51 } 52 if in_frontmatter { 53 if let Some(rest) = trimmed.strip_prefix(&format!("{}:", field)) { 54 return Some( 55 rest.trim() 56 .trim_matches('"') 57 .trim_matches('\x27') 58 .to_string(), 59 ); 60 } 61 } 62 } 63 None 64 } 65 66 fn read_prefix(path: &Path, byte_limit: u64) -> String { 67 read_capped(path, byte_limit) 68 .map(|(text, _)| text) 69 .unwrap_or_default() 70 } 71 72 fn read_capped(path: &Path, byte_limit: u64) -> Result<(String, bool), String> { 73 let file = File::open(path).map_err(|e| e.to_string())?; 74 let len = file.metadata().map(|meta| meta.len()).unwrap_or(0); 75 let mut bytes = Vec::new(); 76 file.take(byte_limit) 77 .read_to_end(&mut bytes) 78 .map_err(|e| e.to_string())?; 79 Ok(( 80 String::from_utf8_lossy(&bytes).into_owned(), 81 len > byte_limit, 82 )) 83 } 84 85 fn body_without_frontmatter(content: &str) -> &str { 86 let Some(rest) = content.strip_prefix("---") else { 87 return content; 88 }; 89 let Some(end) = rest.find("\n---") else { 90 return content; 91 }; 92 rest[end + 4..].trim_start_matches(['\r', '\n']) 93 } 94 95 fn truncate_tokens(text: &str, token_limit: usize) -> (String, bool) { 96 let limit = token_limit.max(1); 97 let mut words = text.split_whitespace(); 98 let selected: Vec<&str> = words.by_ref().take(limit).collect(); 99 let truncated = words.next().is_some(); 100 (selected.join(" "), truncated) 101 } 102 103 fn first_body_paragraph(content: &str) -> &str { 104 let body = body_without_frontmatter(content); 105 body.split("\n\n") 106 .map(str::trim) 107 .find(|paragraph| { 108 !paragraph.is_empty() 109 && !paragraph 110 .lines() 111 .all(|line| line.trim_start().starts_with('#')) 112 }) 113 .unwrap_or("") 114 } 115 116 fn scan_dir_for_skills(dir: &Path, skills: &mut Vec, seen_names: &mut HashSet) { 117 if !dir.is_dir() { 118 return; 119 } 120 if let Ok(entries) = fs::read_dir(dir) { 121 for entry in entries.flatten() { 122 let path = entry.path(); 123 if path.is_dir() { 124 let skill_md = path.join("SKILL.md"); 125 if skill_md.is_file() { 126 let content = read_prefix(&skill_md, SKILL_METADATA_BYTE_LIMIT); 127 let name = extract_frontmatter_field(&content, "name").unwrap_or_else(|| { 128 path.file_name() 129 .unwrap_or_default() 130 .to_string_lossy() 131 .to_string() 132 }); 133 let norm_name = name.to_lowercase(); 134 if seen_names.insert(norm_name) { 135 let desc = extract_frontmatter_field(&content, "description") 136 .unwrap_or_else(|| "No description provided.".to_string()); 137 let has_scripts = path.join("scripts").is_dir(); 138 skills.push(Skill { 139 name, 140 description: desc, 141 path: skill_md.display().to_string(), 142 has_scripts, 143 }); 144 } 145 } else { 146 // Check one level deeper (e.g. vendor-skills/benchmark-model) 147 if let Ok(sub_entries) = fs::read_dir(&path) { 148 for sub_entry in sub_entries.flatten() { 149 let sub_path = sub_entry.path(); 150 if sub_path.is_dir() { 151 let sub_skill_md = sub_path.join("SKILL.md"); 152 if sub_skill_md.is_file() { 153 let content = 154 read_prefix(&sub_skill_md, SKILL_METADATA_BYTE_LIMIT); 155 let name = extract_frontmatter_field(&content, "name") 156 .unwrap_or_else(|| { 157 sub_path 158 .file_name() 159 .unwrap_or_default() 160 .to_string_lossy() 161 .to_string() 162 }); 163 let norm_name = name.to_lowercase(); 164 if seen_names.insert(norm_name) { 165 let desc = 166 extract_frontmatter_field(&content, "description") 167 .unwrap_or_else(|| { 168 "No description provided.".to_string() 169 }); 170 let has_scripts = sub_path.join("scripts").is_dir(); 171 skills.push(Skill { 172 name, 173 description: desc, 174 path: sub_skill_md.display().to_string(), 175 has_scripts, 176 }); 177 } 178 } 179 } 180 } 181 } 182 } 183 } 184 } 185 } 186 } 187 188 pub fn discover_skills() -> Vec { 189 let mut skills = Vec::new(); 190 let mut seen_names = HashSet::new(); 191 let platform = crate::platform::PlatformContext::detect(); 192 193 // Priority 1: Current workspace .agents/skills and skills 194 let cwd = std::env::current_dir().unwrap_or_else(|_| platform.home_dir.clone()); 195 scan_dir_for_skills(&cwd.join(".agents/skills"), &mut skills, &mut seen_names); 196 scan_dir_for_skills(&cwd.join("skills"), &mut skills, &mut seen_names); 197 198 // Priority 2: Home skills (~/skills) 199 let home_skills = platform.home_dir.join("skills"); 200 scan_dir_for_skills(&home_skills, &mut skills, &mut seen_names); 201 202 // Priority 3: Home .agents/skills (~/.agents/skills) 203 let home_agents_skills = platform.home_dir.join(".agents/skills"); 204 scan_dir_for_skills(&home_agents_skills, &mut skills, &mut seen_names); 205 206 // Priority 4: Gemini global config skills (~/.gemini/config/skills) 207 let gemini_skills = platform.home_dir.join(".gemini/config/skills"); 208 scan_dir_for_skills(&gemini_skills, &mut skills, &mut seen_names); 209 210 skills 211 } 212 213 pub fn format_skills_progressive_summary() -> String { 214 let skills = discover_skills(); 215 if skills.is_empty() { 216 return String::new(); 217 } 218 219 let mut out = String::from("\nAGENT SKILLS (CPU-filtered progressive disclosure):\n"); 220 out.push_str(&format!( 221 "{} skills are indexed locally. Use skill discover for a task, preview one matching skill, search inside that skill for details, and request full only when necessary. Never load multiple full skills into one turn.\n", 222 skills.len() 223 )); 224 out 225 } 226 227 pub fn format_skills_tui() -> String { 228 let skills = discover_skills(); 229 let mut out = String::new(); 230 out.push_str(&format!( 231 "{}\n", 232 "=== AIEN Antigravity Skill Registry ===".cyan().bold() 233 )); 234 235 if skills.is_empty() { 236 out.push_str(&format!( 237 "{}\n", 238 "No skills currently discovered. Create a folder with SKILL.md in ~/skills/ or .agents/skills/ to register one.".dimmed() 239 )); 240 return out; 241 } 242 243 for (i, s) in skills.iter().enumerate() { 244 let scripts_badge = if s.has_scripts { 245 "[scripts]".yellow() 246 } else { 247 "".normal() 248 }; 249 out.push_str(&format!( 250 "{}. {} {} ({})\n", 251 i + 1, 252 s.name.bold().green(), 253 scripts_badge, 254 s.path.dimmed() 255 )); 256 out.push_str(&format!(" {}\n\n", s.description.dimmed())); 257 } 258 259 out 260 } 261 262 pub fn read_skill_content(name: &str) -> Result { 263 let skills = discover_skills(); 264 let norm = name.trim().to_lowercase(); 265 266 for s in skills { 267 if s.name.to_lowercase() == norm { 268 return fs::read_to_string(&s.path).map_err(|e| e.to_string()); 269 } 270 } 271 Err(format!( 272 "Skill '{}' not found in discovered skill paths", 273 name 274 )) 275 } 276 277 fn find_skill(name: &str) -> Result { 278 let norm = name.trim().to_lowercase(); 279 discover_skills() 280 .into_iter() 281 .find(|skill| skill.name.to_lowercase() == norm) 282 .ok_or_else(|| format!("Skill '{}' not found in discovered skill paths", name)) 283 } 284 285 fn preview_from_content(content: &str, token_limit: usize) -> (String, usize, bool) { 286 let paragraph = first_body_paragraph(content); 287 let limit = token_limit.clamp(1, MAX_PREVIEW_TOKENS); 288 let (preview, truncated) = truncate_tokens(paragraph, limit); 289 (preview, limit, truncated) 290 } 291 292 pub fn preview_skill(name: &str, token_limit: usize) -> Result { 293 let skill = find_skill(name)?; 294 let (content, scan_truncated) = read_capped(Path::new(&skill.path), PREVIEW_BYTE_LIMIT)?; 295 let (preview, limit, truncated) = preview_from_content(&content, token_limit); 296 Ok(json!({ 297 "status": "ok", 298 "mode": "preview", 299 "name": skill.name, 300 "description": skill.description, 301 "preview": preview, 302 "token_limit": limit, 303 "truncated": truncated || scan_truncated, 304 "next": "Use skill search for a targeted passage or skill full for explicit full context." 305 })) 306 } 307 308 fn search_paragraphs(content: &str, terms: &[String], limit: usize) -> Vec { 309 let mut ranked: Vec<(usize, usize, String)> = body_without_frontmatter(content) 310 .split("\n\n") 311 .enumerate() 312 .filter_map(|(index, paragraph)| { 313 let paragraph = paragraph.trim(); 314 let lower = paragraph.to_lowercase(); 315 let score = terms 316 .iter() 317 .map(|term| lower.matches(term).count()) 318 .sum::(); 319 (score > 0).then(|| { 320 let (snippet, truncated) = 321 truncate_tokens(paragraph, DEFAULT_SEARCH_SNIPPET_TOKENS); 322 let suffix = if truncated { " ..." } else { "" }; 323 (score, index, format!("{snippet}{suffix}")) 324 }) 325 }) 326 .collect(); 327 ranked.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1))); 328 ranked 329 .into_iter() 330 .take(limit.clamp(1, 8)) 331 .map(|(score, paragraph, snippet)| { 332 json!({"score": score, "paragraph": paragraph, "snippet": snippet}) 333 }) 334 .collect() 335 } 336 337 fn discover_matching_skills(query: &str, limit: usize) -> Vec { 338 let terms: Vec = query 339 .split_whitespace() 340 .map(|term| term.to_lowercase()) 341 .filter(|term| term.len() > 1) 342 .collect(); 343 let mut ranked: Vec<(usize, Skill)> = discover_skills() 344 .into_iter() 345 .filter_map(|skill| { 346 let name = skill.name.to_lowercase(); 347 let description = skill.description.to_lowercase(); 348 let score = terms 349 .iter() 350 .map(|term| { 351 usize::from(name.contains(term)) * 4 + usize::from(description.contains(term)) 352 }) 353 .sum::(); 354 (score > 0).then_some((score, skill)) 355 }) 356 .collect(); 357 ranked.sort_by(|(score_a, skill_a), (score_b, skill_b)| { 358 score_b 359 .cmp(score_a) 360 .then_with(|| skill_a.name.cmp(&skill_b.name)) 361 }); 362 ranked 363 .into_iter() 364 .take(limit.clamp(1, 10)) 365 .map(|(score, skill)| { 366 let (description, _) = truncate_tokens(&skill.description, 32); 367 json!({"name": skill.name, "description": description, "score": score}) 368 }) 369 .collect() 370 } 371 372 pub fn search_skill(name: &str, query: &str, limit: usize) -> Result { 373 let skill = find_skill(name)?; 374 let terms: Vec = query 375 .split_whitespace() 376 .map(|term| term.to_lowercase()) 377 .filter(|term| term.len() > 1) 378 .collect(); 379 if terms.is_empty() { 380 return Err("Skill search requires a non-empty query".to_string()); 381 } 382 383 let (content, scan_truncated) = read_capped(Path::new(&skill.path), SEARCH_BYTE_LIMIT)?; 384 let matches = search_paragraphs(&content, &terms, limit); 385 Ok(json!({ 386 "status": "ok", 387 "mode": "search", 388 "name": skill.name, 389 "query": query, 390 "matches": matches, 391 "scan_truncated": scan_truncated 392 })) 393 } 394 395 pub fn skills_dispatch_tool(args: &Value) -> Value { 396 let action = args.get("action").and_then(Value::as_str).unwrap_or("list"); 397 398 match action { 399 "list" => { 400 let skills = discover_skills(); 401 json!({ 402 "status": "ok", 403 "total": skills.len(), 404 "skills": skills.into_iter().map(|skill| skill.name).collect::>() 405 }) 406 } 407 "discover" | "match" => { 408 let query = args.get("query").and_then(Value::as_str).unwrap_or(""); 409 let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(5) as usize; 410 json!({ 411 "status": "ok", 412 "query": query, 413 "skills": discover_matching_skills(query, limit) 414 }) 415 } 416 "read" | "load" | "preview" => { 417 let name = args.get("name").and_then(Value::as_str).unwrap_or(""); 418 let token_limit = args 419 .get("max_tokens") 420 .and_then(Value::as_u64) 421 .unwrap_or(DEFAULT_PREVIEW_TOKENS as u64) as usize; 422 match preview_skill(name, token_limit) { 423 Ok(preview) => preview, 424 Err(e) => json!({"status": "error", "error": e}), 425 } 426 } 427 "search" => { 428 let name = args.get("name").and_then(Value::as_str).unwrap_or(""); 429 let query = args.get("query").and_then(Value::as_str).unwrap_or(""); 430 let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(3) as usize; 431 match search_skill(name, query, limit) { 432 Ok(results) => results, 433 Err(e) => json!({"status": "error", "error": e}), 434 } 435 } 436 "full" => { 437 let name = args.get("name").and_then(Value::as_str).unwrap_or(""); 438 match read_skill_content(name) { 439 Ok(content) => json!({ 440 "status": "ok", 441 "mode": "full", 442 "name": name, 443 "content": content 444 }), 445 Err(e) => json!({"status": "error", "error": e}), 446 } 447 } 448 "optimize" => { 449 let name = args 450 .get("name") 451 .and_then(Value::as_str) 452 .unwrap_or("atlas-skillopt"); 453 optimize_skill(name) 454 } 455 _ => json!({"error": format!("Unknown skill action '{}'", action)}), 456 } 457 } 458 459 pub fn optimize_skill(name: &str) -> Value { 460 let platform = crate::platform::PlatformContext::detect(); 461 let script = platform.home_dir.join("atlas-skillopt-stage.sh"); 462 if !script.exists() { 463 return json!({"status": "error", "error": "atlas-skillopt-stage.sh not found"}); 464 } 465 let output = std::process::Command::new("bash").arg(&script).output(); 466 match output { 467 Ok(out) => { 468 let stdout = String::from_utf8_lossy(&out.stdout).to_string(); 469 let stderr = String::from_utf8_lossy(&out.stderr).to_string(); 470 json!({ 471 "status": if out.status.success() { "ok" } else { "failed" }, 472 "target_skill": name, 473 "stdout": stdout, 474 "stderr": stderr 475 }) 476 } 477 Err(e) => json!({"status": "error", "error": e.to_string()}), 478 } 479 } 480 481 pub fn run_optimize_cli(name: &str) { 482 println!( 483 "{}", 484 format!( 485 "Starting Microsoft SkillOpt self-improvement loop for {}...", 486 name 487 ) 488 .cyan() 489 .bold() 490 ); 491 let res = optimize_skill(name); 492 println!("{}", serde_json::to_string_pretty(&res).unwrap_or_default()); 493 } 494 495 #[cfg(test)] 496 mod tests { 497 use super::*; 498 499 #[test] 500 fn preview_uses_first_body_paragraph_and_budget() { 501 let content = "---\nname: huge\ndescription: Large skill\n---\n# Heading\n\nOne two three four five.\n\nSecond paragraph."; 502 assert_eq!(first_body_paragraph(content), "One two three four five."); 503 let (text, truncated) = truncate_tokens("one two three four", 3); 504 assert_eq!(text, "one two three"); 505 assert!(truncated); 506 } 507 508 #[test] 509 fn frontmatter_is_not_returned_as_body() { 510 let content = "---\nname: test\n---\nFirst paragraph.\n\nSecond paragraph."; 511 assert_eq!(first_body_paragraph(content), "First paragraph."); 512 } 513 514 #[test] 515 fn preview_stops_at_the_first_paragraph() { 516 let content = "---\nname: huge\ndescription: Large skill\n---\n# Heading\n\nAlpha beta gamma.\n\nLater delta epsilon, which must stay out of the preview."; 517 let (preview, limit, truncated) = preview_from_content(content, 96); 518 assert_eq!(preview, "Alpha beta gamma."); 519 assert_eq!(limit, 96); 520 assert!(!truncated); 521 assert!(!preview.contains("delta")); 522 } 523 524 #[test] 525 fn search_returns_one_matching_paragraph() { 526 let content = "---\nname: huge\n---\nUnrelated opening.\n\nThe reactor uses a graphite moderator.\n\nAnother note about orchards."; 527 let terms = vec!["graphite".to_string(), "moderator".to_string()]; 528 let matches = search_paragraphs(content, &terms, 3); 529 assert_eq!(matches.len(), 1); 530 assert_eq!(matches[0]["paragraph"], 1); 531 assert!(matches[0]["snippet"] 532 .as_str() 533 .unwrap() 534 .contains("graphite moderator")); 535 } 536 }