aien-sovereign-core
Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark
Brought by drakestapleton
aien-sovereign-core / crates / aien-cli / src / subagents.rs
| 1 | use colored::*; |
| 2 | use std::fs; |
| 3 | use std::future::Future; |
| 4 | use std::path::Path; |
| 5 | use std::pin::Pin; |
| 6 | use std::time::SystemTime; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | use serde_json::{json, Value}; |
| 9 | use chrono::Utc; |
| 10 | |
| 11 | use crate::client::{ChatClient, extract_tool_calls}; |
| 12 | use crate::tools::dispatch_tool; |
| 13 | |
| 14 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 15 | pub struct SubagentSpec { |
| 16 | pub id: String, |
| 17 | pub role: String, |
| 18 | pub prompt: String, |
| 19 | pub depth: usize, |
| 20 | pub parent_id: Option<String>, |
| 21 | } |
| 22 | |
| 23 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 24 | pub struct SubagentResult { |
| 25 | pub id: String, |
| 26 | pub role: String, |
| 27 | pub depth: usize, |
| 28 | pub parent_id: Option<String>, |
| 29 | pub status: String, |
| 30 | pub summary: String, |
| 31 | pub transcript_path: String, |
| 32 | pub steps_executed: usize, |
| 33 | pub children_spawned: Vec<String>, |
| 34 | } |
| 35 | |
| 36 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 37 | pub struct SubagentStepLog { |
| 38 | pub step: usize, |
| 39 | pub assistant_response: String, |
| 40 | pub tool_calls: Vec<(String, Value)>, |
| 41 | pub tool_results: Vec<Value>, |
| 42 | } |
| 43 | |
| 44 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 45 | pub struct SubagentTranscript { |
| 46 | pub spec: SubagentSpec, |
| 47 | pub start_time: String, |
| 48 | pub end_time: String, |
| 49 | pub status: String, |
| 50 | pub summary: String, |
| 51 | pub steps: Vec<SubagentStepLog>, |
| 52 | pub children: Vec<String>, |
| 53 | } |
| 54 | |
| 55 | pub fn get_subagent_system_prompt(spec: &SubagentSpec) -> String { |
| 56 | let mut p = String::new(); |
| 57 | p.push_str(&format!("You are an autonomous AIEN Subagent with specialized role: '{}'.\n", spec.role)); |
| 58 | p.push_str(&format!("Execution Depth: {} (Max allowed: 3). Assigned by Parent Coordinator: {}.\n", spec.depth, spec.parent_id.as_deref().unwrap_or("Root"))); |
| 59 | p.push_str("Host: NVIDIA DGX Spark (Grace Blackwell GB10).\n"); |
| 60 | p.push_str("Primary Workspace: /home/drakestapleton/workspace/aien-sovereign-core\n\n"); |
| 61 | p.push_str("OBJECTIVE:\n"); |
| 62 | p.push_str(&format!("Execute the assigned task with high technical precision:\n{}\n\n", spec.prompt)); |
| 63 | p.push_str("Available Tools:\n"); |
| 64 | p.push_str("- run_command: {\"command\": \"string\", \"cwd\": \"string\"}\n"); |
| 65 | p.push_str("- view_file: {\"path\": \"string\", \"start_line\": 1, \"end_line\": 100}\n"); |
| 66 | p.push_str("- write_to_file: {\"path\": \"string\", \"content\": \"string\", \"overwrite\": true}\n"); |
| 67 | p.push_str("- replace_file_content: {\"path\": \"string\", \"target\": \"string\", \"replacement\": \"string\"}\n"); |
| 68 | p.push_str("- create_dir: {\"path\": \"string\", \"purpose\": \"string\"}\n"); |
| 69 | p.push_str("- list_dir: {\"path\": \"string\"}\n"); |
| 70 | p.push_str("- grep_search: {\"query\": \"string\", \"path\": \"string\"}\n"); |
| 71 | p.push_str("- crumb: {\"action\": \"survey|whisper|record|init\", \"path\": \"string\"}\n"); |
| 72 | p.push_str("- vault: {\"action\": \"list|check|audit\", \"key\": \"string\"}\n"); |
| 73 | p.push_str("- cortex: {\"action\": \"search|write\", \"query\": \"string\", \"name\": \"string\", \"content\": \"string\", \"kind\": \"lesson|discovery|procedure\"}\n"); |
| 74 | p.push_str("- sandbox: {\"action\": \"init|status|test|promote|clean\"}\n"); |
| 75 | p.push_str("- browser: {\"action\": \"test|mentor\", \"prompt\": \"string\"}\n"); |
| 76 | if spec.depth < 3 { |
| 77 | p.push_str("- invoke_subagent: {\"role\": \"string\", \"prompt\": \"string\"}\n"); |
| 78 | } |
| 79 | p.push_str("\nPROTOCOL & CONTEXT HYGIENE:\n"); |
| 80 | p.push_str("1. ZERO EM DASHES AND EN DASHES: Strict invariant. Use standard commas, colons, or parentheses.\n"); |
| 81 | p.push_str("2. NO UNSLOP OR FLUFF: Lead directly with technical output and code.\n"); |
| 82 | p.push_str("3. ZERO PLAINTEXT SECRETS: Hardware TPM vault only.\n"); |
| 83 | if spec.depth < 3 { |
| 84 | p.push_str("4. RECURSIVE SUBAGENTS: If a subtask requires substantial exploratory search, isolated testing, or deep verification, invoke a child subagent to keep your own context focused.\n"); |
| 85 | } else { |
| 86 | p.push_str("4. LEAF SUBAGENT: Maximum recursion depth reached. Complete all remaining steps directly without invoking further subagents.\n"); |
| 87 | } |
| 88 | p.push_str("5. SYNTHESIS: When your work is done, output your final response WITHOUT tool calls. Summarize your technical findings, exact changes, and verification proof so your parent coordinator receives a distilled, high-signal report.\n\n"); |
| 89 | p.push_str("To call a tool, output:\n<tool_call>\n{\"name\": \"tool_name\", \"arguments\": {}}\n</tool_call>\n"); |
| 90 | p |
| 91 | } |
| 92 | |
| 93 | fn generate_short_id() -> String { |
| 94 | let nanos = SystemTime::now() |
| 95 | .duration_since(SystemTime::UNIX_EPOCH) |
| 96 | .map(|d| d.subsec_nanos()) |
| 97 | .unwrap_or(12345); |
| 98 | format!("{:04x}", nanos % 0xffff) |
| 99 | } |
| 100 | |
| 101 | pub fn execute_subagent(spec: SubagentSpec) -> Pin<Box<dyn Future<Output = SubagentResult> + Send>> { |
| 102 | Box::pin(async move { |
| 103 | let start_time = Utc::now().to_rfc3339(); |
| 104 | let indent = " ".repeat(spec.depth); |
| 105 | println!("{}", format!("{}┌─ [Subagent Spawning: '{}' | Depth: {} | ID: {}]", indent, spec.role, spec.depth, spec.id).cyan().bold()); |
| 106 | println!("{}", format!("{}│ Directive: {}", indent, spec.prompt).dimmed()); |
| 107 | |
| 108 | let client = ChatClient::new(None, None); |
| 109 | let mut messages = vec![ |
| 110 | json!({"role": "system", "content": get_subagent_system_prompt(&spec)}), |
| 111 | json!({"role": "user", "content": format!("TASK ASSIGNMENT:\nRole: {}\nPrompt: {}\n\nExecute all necessary steps using tools, verify outcomes, and provide your distilled technical summary when complete.", spec.role, spec.prompt)}) |
| 112 | ]; |
| 113 | |
| 114 | let mut steps_log = Vec::new(); |
| 115 | let mut children_spawned = Vec::new(); |
| 116 | let mut max_steps = 10; |
| 117 | let mut step_count = 0; |
| 118 | let mut final_summary = String::new(); |
| 119 | |
| 120 | while max_steps > 0 { |
| 121 | max_steps -= 1; |
| 122 | step_count += 1; |
| 123 | |
| 124 | let assistant_resp = match client.stream_turn_with_limit(&messages, false, 1024).await { |
| 125 | Ok(text) => text, |
| 126 | Err(e) => { |
| 127 | let err_msg = format!("Subagent inference failed: {}", e); |
| 128 | println!("{}", format!("{}│ [Error] {}", indent, err_msg).red()); |
| 129 | final_summary = err_msg; |
| 130 | break; |
| 131 | } |
| 132 | }; |
| 133 | |
| 134 | messages.push(json!({"role": "assistant", "content": assistant_resp.clone()})); |
| 135 | |
| 136 | let tool_calls = extract_tool_calls(&assistant_resp); |
| 137 | if tool_calls.is_empty() { |
| 138 | // Done! Assistant provided its final synthesis without tool calls. |
| 139 | final_summary = assistant_resp; |
| 140 | break; |
| 141 | } |
| 142 | |
| 143 | let mut step_results = Vec::new(); |
| 144 | for (tool_name, tool_args) in &tool_calls { |
| 145 | println!("{}", format!("{}│ [Step {}] Executing tool: {}", indent, step_count, tool_name).yellow()); |
| 146 | |
| 147 | let tool_result = if tool_name == "invoke_subagent" { |
| 148 | if spec.depth >= 3 { |
| 149 | json!({"error": "Maximum subagent recursion depth (3) reached. You must complete the task directly without further delegation."}) |
| 150 | } else { |
| 151 | let child_role = tool_args.get("role").and_then(Value::as_str).unwrap_or("Child Subagent"); |
| 152 | let child_prompt = tool_args.get("prompt").and_then(Value::as_str).unwrap_or(""); |
| 153 | let child_spec = SubagentSpec { |
| 154 | id: format!("sub-{}-{}", Utc::now().timestamp(), generate_short_id()), |
| 155 | role: child_role.to_string(), |
| 156 | prompt: child_prompt.to_string(), |
| 157 | depth: spec.depth + 1, |
| 158 | parent_id: Some(spec.id.clone()), |
| 159 | }; |
| 160 | children_spawned.push(child_spec.id.clone()); |
| 161 | let child_res = execute_subagent(child_spec).await; |
| 162 | serde_json::to_value(&child_res).unwrap_or_default() |
| 163 | } |
| 164 | } else { |
| 165 | dispatch_tool(tool_name, tool_args) |
| 166 | }; |
| 167 | |
| 168 | let result_str = serde_json::to_string(&tool_result).unwrap_or_default(); |
| 169 | messages.push(json!({ |
| 170 | "role": "user", |
| 171 | "content": format!("<tool_response name=\"{}\">\n{}\n</tool_response>", tool_name, result_str) |
| 172 | })); |
| 173 | step_results.push(tool_result); |
| 174 | } |
| 175 | |
| 176 | steps_log.push(SubagentStepLog { |
| 177 | step: step_count, |
| 178 | assistant_response: assistant_resp, |
| 179 | tool_calls: tool_calls.clone(), |
| 180 | tool_results: step_results, |
| 181 | }); |
| 182 | } |
| 183 | |
| 184 | if final_summary.is_empty() { |
| 185 | final_summary = "Subagent completed execution loop (reached step limit).".to_string(); |
| 186 | } |
| 187 | |
| 188 | let end_time = Utc::now().to_rfc3339(); |
| 189 | let transcript_dir = Path::new("/home/drakestapleton/basecamp/sessions/subagents"); |
| 190 | let _ = fs::create_dir_all(transcript_dir); |
| 191 | let transcript_path = transcript_dir.join(format!("{}.json", spec.id)); |
| 192 | |
| 193 | let transcript = SubagentTranscript { |
| 194 | spec: spec.clone(), |
| 195 | start_time, |
| 196 | end_time, |
| 197 | status: "completed".to_string(), |
| 198 | summary: final_summary.clone(), |
| 199 | steps: steps_log, |
| 200 | children: children_spawned.clone(), |
| 201 | }; |
| 202 | |
| 203 | let _ = fs::write(&transcript_path, serde_json::to_string_pretty(&transcript).unwrap_or_default()); |
| 204 | |
| 205 | // Emit comb onto the native hexagonal honeycomb message wall |
| 206 | if let Ok(store) = spark_hive::CombStore::open_default() { |
| 207 | let summary_text = if final_summary.chars().count() > 280 { |
| 208 | let trimmed: String = final_summary.chars().take(280).collect(); |
| 209 | format!("{}...", trimmed) |
| 210 | } else { |
| 211 | final_summary.clone() |
| 212 | }; |
| 213 | if let Ok(comb) = spark_hive::emit_subagent_comb(&store, &spec.role, &summary_text, spec.parent_id.as_deref()) { |
| 214 | println!("{}", format!("{} [Hive Lattice] Comb placed at ({}, {}) [id: {}]", |
| 215 | indent, comb.q, comb.r, comb.id).yellow()); |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | println!("{}", format!("{}└─ [Subagent {} Finished (depth: {}, steps: {}, children: {})]", |
| 220 | indent, spec.id, spec.depth, step_count, children_spawned.len()).green().bold()); |
| 221 | |
| 222 | SubagentResult { |
| 223 | id: spec.id, |
| 224 | role: spec.role, |
| 225 | depth: spec.depth, |
| 226 | parent_id: spec.parent_id, |
| 227 | status: "completed".to_string(), |
| 228 | summary: final_summary, |
| 229 | transcript_path: transcript_path.to_string_lossy().to_string(), |
| 230 | steps_executed: step_count, |
| 231 | children_spawned, |
| 232 | } |
| 233 | }) |
| 234 | } |
| 235 | |
| 236 | pub async fn invoke_subagent_from_root(role: &str, prompt: &str) -> Value { |
| 237 | let spec = SubagentSpec { |
| 238 | id: format!("sub-{}-{}", Utc::now().timestamp(), generate_short_id()), |
| 239 | role: role.to_string(), |
| 240 | prompt: prompt.to_string(), |
| 241 | depth: 1, |
| 242 | parent_id: Some("root-coordinator".to_string()), |
| 243 | }; |
| 244 | let res = execute_subagent(spec).await; |
| 245 | serde_json::to_value(&res).unwrap_or_default() |
| 246 | } |
| 247 | |
| 248 | pub fn list_subagents() -> Value { |
| 249 | let dir = Path::new("/home/drakestapleton/basecamp/sessions/subagents"); |
| 250 | if !dir.exists() { |
| 251 | return json!({"subagents": [], "count": 0}); |
| 252 | } |
| 253 | |
| 254 | let mut items = Vec::new(); |
| 255 | if let Ok(entries) = fs::read_dir(dir) { |
| 256 | for entry in entries.flatten() { |
| 257 | let path = entry.path(); |
| 258 | if path.extension().and_then(|s| s.to_str()) == Some("json") { |
| 259 | if let Ok(content) = fs::read_to_string(&path) { |
| 260 | if let Ok(transcript) = serde_json::from_str::<SubagentTranscript>(&content) { |
| 261 | items.push(json!({ |
| 262 | "id": transcript.spec.id, |
| 263 | "role": transcript.spec.role, |
| 264 | "depth": transcript.spec.depth, |
| 265 | "parent_id": transcript.spec.parent_id, |
| 266 | "steps": transcript.steps.len(), |
| 267 | "status": transcript.status, |
| 268 | "start_time": transcript.start_time, |
| 269 | "summary_preview": transcript.summary.chars().take(120).collect::<String>(), |
| 270 | "children": transcript.children, |
| 271 | "transcript_path": path.to_string_lossy() |
| 272 | })); |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | items.sort_by(|a, b| { |
| 280 | let sa = a.get("start_time").and_then(Value::as_str).unwrap_or(""); |
| 281 | let sb = b.get("start_time").and_then(Value::as_str).unwrap_or(""); |
| 282 | sb.cmp(sa) |
| 283 | }); |
| 284 | |
| 285 | let count = items.len(); |
| 286 | json!({"subagents": items, "count": count}) |
| 287 | } |
| 288 | |
| 289 | pub fn view_subagent(id: &str) -> Value { |
| 290 | let path = Path::new("/home/drakestapleton/basecamp/sessions/subagents").join(format!("{}.json", id)); |
| 291 | if !path.exists() { |
| 292 | return json!({"error": format!("Subagent session '{}' not found", id)}); |
| 293 | } |
| 294 | match fs::read_to_string(&path) { |
| 295 | Ok(c) => serde_json::from_str::<Value>(&c).unwrap_or_else(|_| json!({"raw": c})), |
| 296 | Err(e) => json!({"error": e.to_string()}), |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | pub fn format_subagents_tui() -> String { |
| 301 | let list = list_subagents(); |
| 302 | let mut out = String::new(); |
| 303 | out.push_str("\n=== AIEN Recursive Subagents Hierarchy ===\n"); |
| 304 | if let Some(items) = list.get("subagents").and_then(Value::as_array) { |
| 305 | if items.is_empty() { |
| 306 | out.push_str("No active or historical subagent sessions found.\n"); |
| 307 | } else { |
| 308 | for item in items.iter().take(15) { |
| 309 | let id = item.get("id").and_then(Value::as_str).unwrap_or("?"); |
| 310 | let role = item.get("role").and_then(Value::as_str).unwrap_or("?"); |
| 311 | let depth = item.get("depth").and_then(Value::as_u64).unwrap_or(1); |
| 312 | let steps = item.get("steps").and_then(Value::as_u64).unwrap_or(0); |
| 313 | let parent = item.get("parent_id").and_then(Value::as_str).unwrap_or("Root"); |
| 314 | let preview = item.get("summary_preview").and_then(Value::as_str).unwrap_or(""); |
| 315 | let indent = " ".repeat(depth as usize); |
| 316 | out.push_str(&format!("{}[depth {}] {} ({}) <- {}\n", indent, depth, role.cyan().bold(), id.yellow(), parent.dimmed())); |
| 317 | out.push_str(&format!("{} Steps: {} | Summary: {}\n", indent, steps, preview.dimmed())); |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | out |
| 322 | } |
| 323 | |
| 324 | #[cfg(test)] |
| 325 | mod tests { |
| 326 | use super::*; |
| 327 | |
| 328 | #[test] |
| 329 | fn test_subagent_spec_serialization() { |
| 330 | let spec = SubagentSpec { |
| 331 | id: "sub-test-01".to_string(), |
| 332 | role: "Codebase Researcher".to_string(), |
| 333 | prompt: "Survey crates and verify Cargo.toml".to_string(), |
| 334 | depth: 1, |
| 335 | parent_id: Some("root-coord".to_string()), |
| 336 | }; |
| 337 | let json_val = serde_json::to_value(&spec).expect("serialize spec"); |
| 338 | assert_eq!(json_val["id"], "sub-test-01"); |
| 339 | assert_eq!(json_val["depth"], 1); |
| 340 | assert_eq!(json_val["role"], "Codebase Researcher"); |
| 341 | |
| 342 | let deserialized: SubagentSpec = serde_json::from_value(json_val).expect("deserialize spec"); |
| 343 | assert_eq!(deserialized.id, spec.id); |
| 344 | assert_eq!(deserialized.role, spec.role); |
| 345 | } |
| 346 | |
| 347 | #[test] |
| 348 | fn test_subagent_depth_guard() { |
| 349 | let max_depth_spec = SubagentSpec { |
| 350 | id: "sub-leaf-03".to_string(), |
| 351 | role: "Leaf Verifier".to_string(), |
| 352 | prompt: "Perform final check".to_string(), |
| 353 | depth: 3, |
| 354 | parent_id: Some("sub-parent-02".to_string()), |
| 355 | }; |
| 356 | let prompt = get_subagent_system_prompt(&max_depth_spec); |
| 357 | assert!(prompt.contains("LEAF SUBAGENT: Maximum recursion depth reached")); |
| 358 | assert!(!prompt.contains("- invoke_subagent:")); |
| 359 | } |
| 360 | |
| 361 | #[test] |
| 362 | fn test_subagent_root_spec() { |
| 363 | let root_spec = SubagentSpec { |
| 364 | id: "sub-root-01".to_string(), |
| 365 | role: "Researcher".to_string(), |
| 366 | prompt: "Initial task".to_string(), |
| 367 | depth: 1, |
| 368 | parent_id: None, |
| 369 | }; |
| 370 | let prompt = get_subagent_system_prompt(&root_spec); |
| 371 | assert!(prompt.contains("- invoke_subagent:")); |
| 372 | assert!(prompt.contains("RECURSIVE SUBAGENTS")); |
| 373 | assert!(!prompt.is_empty()); |
| 374 | // verified hyphen use |
| 375 | } |
| 376 | |
| 377 | #[test] |
| 378 | fn test_subagents_list_and_view() { |
| 379 | let list = list_subagents(); |
| 380 | assert!(list.get("subagents").is_some()); |
| 381 | } |
| 382 | } |