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
aien-sovereign-core-mv / crates / aien-cli / src / subagents.rs
| 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 chrono::Utc; |
| 17 | use colored::*; |
| 18 | use serde::{Deserialize, Serialize}; |
| 19 | use serde_json::{json, Value}; |
| 20 | use std::fs; |
| 21 | use std::future::Future; |
| 22 | use std::path::Path; |
| 23 | use std::pin::Pin; |
| 24 | use std::time::SystemTime; |
| 25 | |
| 26 | use crate::client::{extract_tool_calls, ChatClient}; |
| 27 | use crate::tools::dispatch_tool; |
| 28 | |
| 29 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 30 | pub struct SubagentSpec { |
| 31 | pub id: String, |
| 32 | pub role: String, |
| 33 | pub prompt: String, |
| 34 | pub depth: usize, |
| 35 | pub parent_id: Option<String>, |
| 36 | } |
| 37 | |
| 38 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 39 | pub struct SubagentResult { |
| 40 | pub id: String, |
| 41 | pub role: String, |
| 42 | pub depth: usize, |
| 43 | pub parent_id: Option<String>, |
| 44 | pub status: String, |
| 45 | pub summary: String, |
| 46 | pub transcript_path: Option<String>, |
| 47 | pub transcript_error: Option<String>, |
| 48 | pub steps_executed: usize, |
| 49 | pub children_spawned: Vec<String>, |
| 50 | } |
| 51 | |
| 52 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 53 | pub struct SubagentStepLog { |
| 54 | pub step: usize, |
| 55 | pub assistant_response: String, |
| 56 | pub tool_calls: Vec<(String, Value)>, |
| 57 | pub tool_results: Vec<Value>, |
| 58 | } |
| 59 | |
| 60 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 61 | pub struct SubagentTranscript { |
| 62 | pub spec: SubagentSpec, |
| 63 | pub start_time: String, |
| 64 | pub end_time: String, |
| 65 | pub status: String, |
| 66 | pub summary: String, |
| 67 | pub steps: Vec<SubagentStepLog>, |
| 68 | pub children: Vec<String>, |
| 69 | } |
| 70 | |
| 71 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 72 | enum SubagentOutcome { |
| 73 | Completed, |
| 74 | Failed, |
| 75 | Exhausted, |
| 76 | } |
| 77 | |
| 78 | impl SubagentOutcome { |
| 79 | fn status(self) -> &'static str { |
| 80 | match self { |
| 81 | Self::Completed => "completed", |
| 82 | Self::Failed => "failed", |
| 83 | Self::Exhausted => "exhausted", |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | pub fn get_subagent_system_prompt(spec: &SubagentSpec) -> String { |
| 89 | let mut p = String::new(); |
| 90 | p.push_str(&format!( |
| 91 | "You are an autonomous AIEN Subagent with specialized role: '{}'.\n", |
| 92 | spec.role |
| 93 | )); |
| 94 | p.push_str(&format!( |
| 95 | "Execution Depth: {} (Max allowed: 3). Assigned by Parent Coordinator: {}.\n", |
| 96 | spec.depth, |
| 97 | spec.parent_id.as_deref().unwrap_or("Root") |
| 98 | )); |
| 99 | p.push_str("Host: NVIDIA DGX Spark (Grace Blackwell GB10).\n"); |
| 100 | let ws = crate::platform::PlatformContext::detect() |
| 101 | .home_dir |
| 102 | .join("workspace/aien-sovereign-core"); |
| 103 | p.push_str(&format!( |
| 104 | "Primary Workspace: {} |
| 105 | |
| 106 | ", |
| 107 | ws.display() |
| 108 | )); |
| 109 | p.push_str("OBJECTIVE:\n"); |
| 110 | p.push_str(&format!( |
| 111 | "Execute the assigned task with high technical precision:\n{}\n\n", |
| 112 | spec.prompt |
| 113 | )); |
| 114 | p.push_str("Available Tools:\n"); |
| 115 | p.push_str("- run_command: {\"command\": \"string\", \"cwd\": \"string\"}\n"); |
| 116 | p.push_str("- view_file: {\"path\": \"string\", \"start_line\": 1, \"end_line\": 100}\n"); |
| 117 | p.push_str( |
| 118 | "- write_to_file: {\"path\": \"string\", \"content\": \"string\", \"overwrite\": true}\n", |
| 119 | ); |
| 120 | p.push_str("- replace_file_content: {\"path\": \"string\", \"target\": \"string\", \"replacement\": \"string\"}\n"); |
| 121 | p.push_str("- create_dir: {\"path\": \"string\", \"purpose\": \"string\"}\n"); |
| 122 | p.push_str("- list_dir: {\"path\": \"string\"}\n"); |
| 123 | p.push_str("- grep_search: {\"query\": \"string\", \"path\": \"string\"}\n"); |
| 124 | p.push_str("- crumb: {\"action\": \"survey|whisper|record|init\", \"path\": \"string\"}\n"); |
| 125 | p.push_str("- vault: {\"action\": \"list|check|audit\", \"key\": \"string\"}\n"); |
| 126 | p.push_str("- cortex: {\"action\": \"search|write\", \"query\": \"string\", \"name\": \"string\", \"content\": \"string\", \"kind\": \"lesson|discovery|procedure\"}\n"); |
| 127 | p.push_str("- sandbox: {\"action\": \"init|status|test|promote|clean\"}\n"); |
| 128 | p.push_str("- browser: {\"action\": \"test|mentor\", \"prompt\": \"string\"}\n"); |
| 129 | if spec.depth < 3 { |
| 130 | p.push_str("- invoke_subagent: {\"role\": \"string\", \"prompt\": \"string\"}\n"); |
| 131 | } |
| 132 | p.push_str("\nPROTOCOL & CONTEXT HYGIENE:\n"); |
| 133 | p.push_str("1. ZERO EM DASHES AND EN DASHES: Strict invariant. Use standard commas, colons, or parentheses.\n"); |
| 134 | p.push_str("2. NO UNSLOP OR FLUFF: Lead directly with technical output and code.\n"); |
| 135 | p.push_str("3. ZERO PLAINTEXT SECRETS: Hardware TPM vault only.\n"); |
| 136 | if spec.depth < 3 { |
| 137 | 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"); |
| 138 | } else { |
| 139 | p.push_str("4. LEAF SUBAGENT: Maximum recursion depth reached. Complete all remaining steps directly without invoking further subagents.\n"); |
| 140 | } |
| 141 | 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"); |
| 142 | p.push_str("To call a tool, output:\n<tool_call>\n{\"name\": \"tool_name\", \"arguments\": {}}\n</tool_call>\n"); |
| 143 | p |
| 144 | } |
| 145 | |
| 146 | fn generate_short_id() -> String { |
| 147 | let nanos = SystemTime::now() |
| 148 | .duration_since(SystemTime::UNIX_EPOCH) |
| 149 | .map(|d| d.subsec_nanos()) |
| 150 | .unwrap_or(12345); |
| 151 | format!("{:04x}", nanos % 0xffff) |
| 152 | } |
| 153 | |
| 154 | trait SubagentChat: Sync { |
| 155 | fn reply(&self, messages: &[Value]) -> impl Future<Output = Result<String, String>> + Send; |
| 156 | } |
| 157 | |
| 158 | impl SubagentChat for ChatClient { |
| 159 | async fn reply(&self, messages: &[Value]) -> Result<String, String> { |
| 160 | self.stream_turn_with_limit(messages, false, 1024).await |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | pub fn execute_subagent( |
| 165 | spec: SubagentSpec, |
| 166 | ) -> Pin<Box<dyn Future<Output = SubagentResult> + Send>> { |
| 167 | Box::pin(async move { |
| 168 | let client = ChatClient::new(None, None); |
| 169 | let platform = crate::platform::PlatformContext::detect(); |
| 170 | let transcript_dir = platform.home_dir.join("basecamp/sessions/subagents"); |
| 171 | execute_subagent_with(spec, &client, &transcript_dir, emit_completion_comb).await |
| 172 | }) |
| 173 | } |
| 174 | |
| 175 | async fn execute_subagent_with( |
| 176 | spec: SubagentSpec, |
| 177 | client: &impl SubagentChat, |
| 178 | transcript_dir: &Path, |
| 179 | emit_comb: impl Fn(&SubagentSpec, &str), |
| 180 | ) -> SubagentResult { |
| 181 | let start_time = Utc::now().to_rfc3339(); |
| 182 | let indent = " ".repeat(spec.depth); |
| 183 | println!( |
| 184 | "{}", |
| 185 | format!( |
| 186 | "{}┌─ [Subagent Spawning: '{}' | Depth: {} | ID: {}]", |
| 187 | indent, spec.role, spec.depth, spec.id |
| 188 | ) |
| 189 | .cyan() |
| 190 | .bold() |
| 191 | ); |
| 192 | println!( |
| 193 | "{}", |
| 194 | format!("{}│ Directive: {}", indent, spec.prompt).dimmed() |
| 195 | ); |
| 196 | |
| 197 | let mut messages = vec![ |
| 198 | json!({"role": "system", "content": get_subagent_system_prompt(&spec)}), |
| 199 | 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)}), |
| 200 | ]; |
| 201 | |
| 202 | let mut steps_log = Vec::new(); |
| 203 | let mut children_spawned = Vec::new(); |
| 204 | let mut max_steps = 10; |
| 205 | let mut step_count = 0; |
| 206 | let mut final_summary = String::new(); |
| 207 | let mut outcome = SubagentOutcome::Exhausted; |
| 208 | |
| 209 | while max_steps > 0 { |
| 210 | max_steps -= 1; |
| 211 | step_count += 1; |
| 212 | |
| 213 | let assistant_resp = match client.reply(&messages).await { |
| 214 | Ok(text) => text, |
| 215 | Err(e) => { |
| 216 | let err_msg = format!("Subagent inference failed: {}", e); |
| 217 | println!("{}", format!("{}│ [Error] {}", indent, err_msg).red()); |
| 218 | final_summary = err_msg; |
| 219 | outcome = SubagentOutcome::Failed; |
| 220 | break; |
| 221 | } |
| 222 | }; |
| 223 | |
| 224 | messages.push(json!({"role": "assistant", "content": assistant_resp.clone()})); |
| 225 | |
| 226 | let tool_calls = match extract_tool_calls(&assistant_resp) { |
| 227 | Ok(calls) => calls, |
| 228 | Err(error) => { |
| 229 | final_summary = error; |
| 230 | outcome = SubagentOutcome::Failed; |
| 231 | break; |
| 232 | } |
| 233 | }; |
| 234 | if tool_calls.is_empty() { |
| 235 | // Only a real, nonempty model reply is a final synthesis. |
| 236 | if assistant_resp.trim().is_empty() { |
| 237 | outcome = SubagentOutcome::Failed; |
| 238 | final_summary = "Subagent inference returned an empty reply.".to_string(); |
| 239 | } else { |
| 240 | outcome = SubagentOutcome::Completed; |
| 241 | final_summary = assistant_resp; |
| 242 | } |
| 243 | break; |
| 244 | } |
| 245 | |
| 246 | let mut step_results = Vec::new(); |
| 247 | for (tool_name, tool_args) in &tool_calls { |
| 248 | println!( |
| 249 | "{}", |
| 250 | format!( |
| 251 | "{}│ [Step {}] Executing tool: {}", |
| 252 | indent, step_count, tool_name |
| 253 | ) |
| 254 | .yellow() |
| 255 | ); |
| 256 | |
| 257 | let tool_result = if tool_name == "invoke_subagent" { |
| 258 | if spec.depth >= 3 { |
| 259 | json!({"error": "Maximum subagent recursion depth (3) reached. You must complete the task directly without further delegation."}) |
| 260 | } else { |
| 261 | let child_role = tool_args |
| 262 | .get("role") |
| 263 | .and_then(Value::as_str) |
| 264 | .unwrap_or("Child Subagent"); |
| 265 | let child_prompt = tool_args |
| 266 | .get("prompt") |
| 267 | .and_then(Value::as_str) |
| 268 | .unwrap_or(""); |
| 269 | let child_spec = SubagentSpec { |
| 270 | id: format!("sub-{}-{}", Utc::now().timestamp(), generate_short_id()), |
| 271 | role: child_role.to_string(), |
| 272 | prompt: child_prompt.to_string(), |
| 273 | depth: spec.depth + 1, |
| 274 | parent_id: Some(spec.id.clone()), |
| 275 | }; |
| 276 | children_spawned.push(child_spec.id.clone()); |
| 277 | let child_res = execute_subagent(child_spec).await; |
| 278 | serde_json::to_value(&child_res).unwrap_or_default() |
| 279 | } |
| 280 | } else { |
| 281 | dispatch_tool(tool_name, tool_args) |
| 282 | }; |
| 283 | |
| 284 | let result_str = serde_json::to_string(&tool_result).unwrap_or_default(); |
| 285 | messages.push(json!({ |
| 286 | "role": "user", |
| 287 | "content": format!("<tool_response name=\"{}\">\n{}\n</tool_response>", tool_name, result_str) |
| 288 | })); |
| 289 | step_results.push(tool_result); |
| 290 | } |
| 291 | |
| 292 | steps_log.push(SubagentStepLog { |
| 293 | step: step_count, |
| 294 | assistant_response: assistant_resp, |
| 295 | tool_calls: tool_calls.clone(), |
| 296 | tool_results: step_results, |
| 297 | }); |
| 298 | } |
| 299 | |
| 300 | if outcome == SubagentOutcome::Exhausted { |
| 301 | final_summary = "Subagent exhausted its step limit without a final reply.".to_string(); |
| 302 | } |
| 303 | |
| 304 | let end_time = Utc::now().to_rfc3339(); |
| 305 | let transcript_path = transcript_dir.join(format!("{}.json", spec.id)); |
| 306 | |
| 307 | let transcript = SubagentTranscript { |
| 308 | spec: spec.clone(), |
| 309 | start_time, |
| 310 | end_time, |
| 311 | status: outcome.status().to_string(), |
| 312 | summary: final_summary.clone(), |
| 313 | steps: steps_log, |
| 314 | children: children_spawned.clone(), |
| 315 | }; |
| 316 | |
| 317 | let persisted = serde_json::to_vec_pretty(&transcript) |
| 318 | .map_err(|e| e.to_string()) |
| 319 | .and_then(|bytes| { |
| 320 | fs::create_dir_all(transcript_dir) |
| 321 | .and_then(|_| fs::write(&transcript_path, bytes)) |
| 322 | .map_err(|e| e.to_string()) |
| 323 | }); |
| 324 | let (transcript_path, transcript_error) = match persisted { |
| 325 | Ok(()) => (Some(transcript_path.to_string_lossy().to_string()), None), |
| 326 | Err(error) => { |
| 327 | outcome = SubagentOutcome::Failed; |
| 328 | let message = format!("Subagent transcript write failed: {}", error); |
| 329 | eprintln!("{}", format!("{}│ [Error] {}", indent, message).red()); |
| 330 | (None, Some(message)) |
| 331 | } |
| 332 | }; |
| 333 | |
| 334 | if outcome == SubagentOutcome::Completed { |
| 335 | emit_comb(&spec, &final_summary); |
| 336 | } |
| 337 | |
| 338 | let terminal_line = format!( |
| 339 | "{}└─ [Subagent {} {} (depth: {}, steps: {}, children: {})]", |
| 340 | indent, |
| 341 | spec.id, |
| 342 | outcome.status(), |
| 343 | spec.depth, |
| 344 | step_count, |
| 345 | children_spawned.len() |
| 346 | ); |
| 347 | let terminal_line = if outcome == SubagentOutcome::Completed { |
| 348 | terminal_line.green() |
| 349 | } else { |
| 350 | terminal_line.red() |
| 351 | }; |
| 352 | println!("{}", terminal_line.bold()); |
| 353 | |
| 354 | SubagentResult { |
| 355 | id: spec.id, |
| 356 | role: spec.role, |
| 357 | depth: spec.depth, |
| 358 | parent_id: spec.parent_id, |
| 359 | status: outcome.status().to_string(), |
| 360 | summary: final_summary, |
| 361 | transcript_path, |
| 362 | transcript_error, |
| 363 | steps_executed: step_count, |
| 364 | children_spawned, |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | fn emit_completion_comb(spec: &SubagentSpec, final_summary: &str) { |
| 369 | let indent = " ".repeat(spec.depth); |
| 370 | if let Ok(store) = spark_hive::CombStore::open_default() { |
| 371 | let summary_text = if final_summary.chars().count() > 280 { |
| 372 | let trimmed: String = final_summary.chars().take(280).collect(); |
| 373 | format!("{}...", trimmed) |
| 374 | } else { |
| 375 | final_summary.to_string() |
| 376 | }; |
| 377 | if let Ok(comb) = spark_hive::emit_subagent_comb( |
| 378 | &store, |
| 379 | &spec.role, |
| 380 | &summary_text, |
| 381 | spec.parent_id.as_deref(), |
| 382 | ) { |
| 383 | println!( |
| 384 | "{}", |
| 385 | format!( |
| 386 | "{} [Hive Lattice] Comb placed at ({}, {}) [id: {}]", |
| 387 | indent, comb.q, comb.r, comb.id |
| 388 | ) |
| 389 | .yellow() |
| 390 | ); |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | pub async fn invoke_subagent_from_root(role: &str, prompt: &str) -> Value { |
| 396 | let spec = SubagentSpec { |
| 397 | id: format!("sub-{}-{}", Utc::now().timestamp(), generate_short_id()), |
| 398 | role: role.to_string(), |
| 399 | prompt: prompt.to_string(), |
| 400 | depth: 1, |
| 401 | parent_id: Some("root-coordinator".to_string()), |
| 402 | }; |
| 403 | let res = execute_subagent(spec).await; |
| 404 | serde_json::to_value(&res).unwrap_or_default() |
| 405 | } |
| 406 | |
| 407 | pub fn list_subagents() -> Value { |
| 408 | let platform = crate::platform::PlatformContext::detect(); |
| 409 | let dir = platform.home_dir.join("basecamp/sessions/subagents"); |
| 410 | if !dir.exists() { |
| 411 | return json!({"subagents": [], "count": 0}); |
| 412 | } |
| 413 | |
| 414 | let mut items = Vec::new(); |
| 415 | if let Ok(entries) = fs::read_dir(dir) { |
| 416 | for entry in entries.flatten() { |
| 417 | let path = entry.path(); |
| 418 | if path.extension().and_then(|s| s.to_str()) == Some("json") { |
| 419 | if let Ok(content) = fs::read_to_string(&path) { |
| 420 | if let Ok(transcript) = serde_json::from_str::<SubagentTranscript>(&content) { |
| 421 | items.push(json!({ |
| 422 | "id": transcript.spec.id, |
| 423 | "role": transcript.spec.role, |
| 424 | "depth": transcript.spec.depth, |
| 425 | "parent_id": transcript.spec.parent_id, |
| 426 | "steps": transcript.steps.len(), |
| 427 | "status": transcript.status, |
| 428 | "start_time": transcript.start_time, |
| 429 | "summary_preview": transcript.summary.chars().take(120).collect::<String>(), |
| 430 | "children": transcript.children, |
| 431 | "transcript_path": path.to_string_lossy() |
| 432 | })); |
| 433 | } |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | items.sort_by(|a, b| { |
| 440 | let sa = a.get("start_time").and_then(Value::as_str).unwrap_or(""); |
| 441 | let sb = b.get("start_time").and_then(Value::as_str).unwrap_or(""); |
| 442 | sb.cmp(sa) |
| 443 | }); |
| 444 | |
| 445 | let count = items.len(); |
| 446 | json!({"subagents": items, "count": count}) |
| 447 | } |
| 448 | |
| 449 | pub fn view_subagent(id: &str) -> Value { |
| 450 | let platform = crate::platform::PlatformContext::detect(); |
| 451 | let path = platform |
| 452 | .home_dir |
| 453 | .join("basecamp/sessions/subagents") |
| 454 | .join(format!("{}.json", id)); |
| 455 | if !path.exists() { |
| 456 | return json!({"error": format!("Subagent session '{}' not found", id)}); |
| 457 | } |
| 458 | match fs::read_to_string(&path) { |
| 459 | Ok(c) => serde_json::from_str::<Value>(&c).unwrap_or_else(|_| json!({"raw": c})), |
| 460 | Err(e) => json!({"error": e.to_string()}), |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | pub fn format_subagents_tui() -> String { |
| 465 | let list = list_subagents(); |
| 466 | let mut out = String::new(); |
| 467 | out.push_str("\n=== AIEN Recursive Subagents Hierarchy ===\n"); |
| 468 | if let Some(items) = list.get("subagents").and_then(Value::as_array) { |
| 469 | if items.is_empty() { |
| 470 | out.push_str("No active or historical subagent sessions found.\n"); |
| 471 | } else { |
| 472 | for item in items.iter().take(15) { |
| 473 | let id = item.get("id").and_then(Value::as_str).unwrap_or("?"); |
| 474 | let role = item.get("role").and_then(Value::as_str).unwrap_or("?"); |
| 475 | let depth = item.get("depth").and_then(Value::as_u64).unwrap_or(1); |
| 476 | let steps = item.get("steps").and_then(Value::as_u64).unwrap_or(0); |
| 477 | let status = item |
| 478 | .get("status") |
| 479 | .and_then(Value::as_str) |
| 480 | .unwrap_or("unknown"); |
| 481 | let parent = item |
| 482 | .get("parent_id") |
| 483 | .and_then(Value::as_str) |
| 484 | .unwrap_or("Root"); |
| 485 | let preview = item |
| 486 | .get("summary_preview") |
| 487 | .and_then(Value::as_str) |
| 488 | .unwrap_or(""); |
| 489 | let indent = " ".repeat(depth as usize); |
| 490 | out.push_str(&format!( |
| 491 | "{}[depth {}] {} ({}) <- {}\n", |
| 492 | indent, |
| 493 | depth, |
| 494 | role.cyan().bold(), |
| 495 | id.yellow(), |
| 496 | parent.dimmed() |
| 497 | )); |
| 498 | out.push_str(&format!( |
| 499 | "{} Status: {} | Steps: {} | Summary: {}\n", |
| 500 | indent, |
| 501 | status, |
| 502 | steps, |
| 503 | preview.dimmed() |
| 504 | )); |
| 505 | } |
| 506 | } |
| 507 | } |
| 508 | out |
| 509 | } |
| 510 | |
| 511 | #[cfg(test)] |
| 512 | mod tests { |
| 513 | use super::*; |
| 514 | struct FakeChat(std::sync::Mutex<std::collections::VecDeque<Result<String, String>>>); |
| 515 | |
| 516 | impl SubagentChat for FakeChat { |
| 517 | async fn reply(&self, _messages: &[Value]) -> Result<String, String> { |
| 518 | self.0 |
| 519 | .lock() |
| 520 | .unwrap() |
| 521 | .pop_front() |
| 522 | .expect("unexpected model call") |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | async fn run_replies( |
| 527 | replies: Vec<Result<String, String>>, |
| 528 | expected: &str, |
| 529 | steps: usize, |
| 530 | summary: &str, |
| 531 | ) { |
| 532 | let client = FakeChat(std::sync::Mutex::new(replies.into())); |
| 533 | run_chat(&client, expected, steps, summary).await; |
| 534 | } |
| 535 | |
| 536 | async fn run_chat(client: &impl SubagentChat, expected: &str, steps: usize, summary: &str) { |
| 537 | let scratch = tempfile::tempdir().unwrap(); |
| 538 | let emissions = std::cell::RefCell::new(Vec::new()); |
| 539 | let result = execute_subagent_with( |
| 540 | SubagentSpec { |
| 541 | id: "outcome-test".into(), |
| 542 | role: "Verifier".into(), |
| 543 | prompt: "Test outcome classification".into(), |
| 544 | depth: 3, |
| 545 | parent_id: Some("test-parent".into()), |
| 546 | }, |
| 547 | client, |
| 548 | scratch.path(), |
| 549 | |_, summary| emissions.borrow_mut().push(summary.to_string()), |
| 550 | ) |
| 551 | .await; |
| 552 | let transcript: SubagentTranscript = serde_json::from_str( |
| 553 | &fs::read_to_string(result.transcript_path.as_ref().unwrap()).unwrap(), |
| 554 | ) |
| 555 | .unwrap(); |
| 556 | let (tool_result, success) = |
| 557 | crate::tools::subagent_tool_result(serde_json::to_value(&result).unwrap()); |
| 558 | assert_eq!(result.status, expected); |
| 559 | assert_eq!(transcript.status, expected); |
| 560 | assert_eq!(tool_result["status"], expected); |
| 561 | assert_eq!(success, expected == "completed"); |
| 562 | assert_eq!( |
| 563 | emissions.borrow().len(), |
| 564 | usize::from(expected == "completed") |
| 565 | ); |
| 566 | assert_eq!(result.steps_executed, steps); |
| 567 | assert!(result.transcript_error.is_none()); |
| 568 | assert!(result.summary.contains(summary)); |
| 569 | assert_eq!(transcript.summary, result.summary); |
| 570 | } |
| 571 | |
| 572 | #[tokio::test] |
| 573 | async fn inference_error_is_failed() { |
| 574 | run_replies( |
| 575 | vec![Err("injected inference error".into())], |
| 576 | "failed", |
| 577 | 1, |
| 578 | "injected inference error", |
| 579 | ) |
| 580 | .await; |
| 581 | } |
| 582 | |
| 583 | #[tokio::test] |
| 584 | async fn ten_tool_replies_are_exhausted() { |
| 585 | let tool_reply = "<tool_call>{\"name\":\"invoke_subagent\",\"arguments\":{}}</tool_call>"; |
| 586 | run_replies( |
| 587 | vec![Ok(tool_reply.into()); 10], |
| 588 | "exhausted", |
| 589 | 10, |
| 590 | "step limit", |
| 591 | ) |
| 592 | .await; |
| 593 | } |
| 594 | |
| 595 | #[tokio::test] |
| 596 | async fn final_reply_is_completed() { |
| 597 | run_replies( |
| 598 | vec![Ok("Verified final synthesis.".into())], |
| 599 | "completed", |
| 600 | 1, |
| 601 | "Verified final synthesis.", |
| 602 | ) |
| 603 | .await; |
| 604 | } |
| 605 | |
| 606 | #[tokio::test] |
| 607 | async fn empty_reply_is_failed() { |
| 608 | run_replies(vec![Ok(" \n\t".into())], "failed", 1, "empty reply").await; |
| 609 | } |
| 610 | |
| 611 | #[tokio::test] |
| 612 | async fn error_after_tool_reply_is_failed() { |
| 613 | run_replies( |
| 614 | vec![ |
| 615 | Ok("<tool_call>{\"name\":\"invoke_subagent\",\"arguments\":{}}</tool_call>".into()), |
| 616 | Err("injected inference error after tools".into()), |
| 617 | ], |
| 618 | "failed", |
| 619 | 2, |
| 620 | "injected inference error after tools", |
| 621 | ) |
| 622 | .await; |
| 623 | } |
| 624 | |
| 625 | #[tokio::test] |
| 626 | async fn final_reply_on_last_turn_is_completed() { |
| 627 | let tool_reply = "<tool_call>{\"name\":\"invoke_subagent\",\"arguments\":{}}</tool_call>"; |
| 628 | let mut replies = vec![Ok(tool_reply.into()); 9]; |
| 629 | replies.push(Ok("Final synthesis on the last permitted turn.".into())); |
| 630 | run_replies(replies, "completed", 10, "last permitted turn").await; |
| 631 | } |
| 632 | |
| 633 | async fn persistence_failure(fail_directory_creation: bool) { |
| 634 | for reply in [ |
| 635 | Ok::<String, String>("Final synthesis.".into()), |
| 636 | Err("injected inference error".into()), |
| 637 | ] { |
| 638 | let scratch = tempfile::tempdir().unwrap(); |
| 639 | let transcript_dir = scratch.path().join("transcripts"); |
| 640 | if fail_directory_creation { |
| 641 | fs::write(&transcript_dir, "not a directory").unwrap(); |
| 642 | } else { |
| 643 | fs::create_dir_all(transcript_dir.join("outcome-test.json")).unwrap(); |
| 644 | } |
| 645 | let summary = match &reply { |
| 646 | Ok(text) => text.clone(), |
| 647 | Err(error) => error.clone(), |
| 648 | }; |
| 649 | let client = FakeChat(std::sync::Mutex::new(vec![reply].into())); |
| 650 | let emissions = std::cell::Cell::new(0); |
| 651 | let result = execute_subagent_with( |
| 652 | SubagentSpec { |
| 653 | id: "outcome-test".into(), |
| 654 | role: "Verifier".into(), |
| 655 | prompt: "Test persistence failure".into(), |
| 656 | depth: 3, |
| 657 | parent_id: None, |
| 658 | }, |
| 659 | &client, |
| 660 | &transcript_dir, |
| 661 | |_, _| emissions.set(emissions.get() + 1), |
| 662 | ) |
| 663 | .await; |
| 664 | assert_eq!(result.status, "failed"); |
| 665 | assert!(result.transcript_path.is_none()); |
| 666 | assert!(result |
| 667 | .transcript_error |
| 668 | .as_ref() |
| 669 | .unwrap() |
| 670 | .contains("transcript write failed")); |
| 671 | assert!(result.summary.contains(&summary)); |
| 672 | let (value, success) = |
| 673 | crate::tools::subagent_tool_result(serde_json::to_value(&result).unwrap()); |
| 674 | assert!(value["transcript_path"].is_null()); |
| 675 | assert!(!success); |
| 676 | assert_eq!(emissions.get(), 0); |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | #[tokio::test] |
| 681 | async fn round2_persistence_directory_failure() { |
| 682 | persistence_failure(true).await; |
| 683 | } |
| 684 | |
| 685 | #[tokio::test] |
| 686 | async fn round2_persistence_file_failure() { |
| 687 | persistence_failure(false).await; |
| 688 | } |
| 689 | |
| 690 | #[tokio::test] |
| 691 | async fn round2_malformed_tool_call_is_failed() { |
| 692 | run_replies( |
| 693 | vec![Ok("<tool_call>{\"name\":</tool_call>".into())], |
| 694 | "failed", |
| 695 | 1, |
| 696 | "Malformed tool call", |
| 697 | ) |
| 698 | .await; |
| 699 | } |
| 700 | |
| 701 | #[tokio::test] |
| 702 | async fn round3_unclosed_named_json_fence_is_failed() { |
| 703 | run_replies( |
| 704 | vec![Ok( |
| 705 | "```json\n{\"name\":\"goal\",\"arguments\":{\"action\":\"list\"}}".into(), |
| 706 | )], |
| 707 | "failed", |
| 708 | 1, |
| 709 | "Malformed tool call", |
| 710 | ) |
| 711 | .await; |
| 712 | } |
| 713 | |
| 714 | #[tokio::test] |
| 715 | async fn round3_unclosed_spaced_tool_fence_is_failed() { |
| 716 | for prefix in [" tool_call", "\n tool_call", "\njson"] { |
| 717 | run_replies( |
| 718 | vec![Ok(format!( |
| 719 | "```{prefix}\n{{\"name\":\"goal\",\"arguments\":{{}}}}" |
| 720 | ))], |
| 721 | "failed", |
| 722 | 1, |
| 723 | "Malformed tool call", |
| 724 | ) |
| 725 | .await; |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | async fn remote_fixture(body: String) -> (ChatClient, tokio::task::JoinHandle<()>) { |
| 730 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 731 | let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) |
| 732 | .await |
| 733 | .unwrap(); |
| 734 | let endpoint = format!( |
| 735 | "http://{}/v1/chat/completions", |
| 736 | listener.local_addr().unwrap() |
| 737 | ); |
| 738 | let server = tokio::spawn(async move { |
| 739 | let (mut socket, _) = listener.accept().await.unwrap(); |
| 740 | let mut request = Vec::new(); |
| 741 | let mut bytes = [0; 1024]; |
| 742 | loop { |
| 743 | let count = socket.read(&mut bytes).await.unwrap(); |
| 744 | assert_ne!(count, 0); |
| 745 | request.extend_from_slice(&bytes[..count]); |
| 746 | if let Some(pos) = request.windows(4).position(|w| w == b"\r\n\r\n") { |
| 747 | let headers = std::str::from_utf8(&request[..pos]).unwrap(); |
| 748 | let length: usize = headers |
| 749 | .lines() |
| 750 | .find_map(|line| { |
| 751 | let (name, value) = line.split_once(':')?; |
| 752 | name.eq_ignore_ascii_case("content-length") |
| 753 | .then(|| value.trim().parse().unwrap()) |
| 754 | }) |
| 755 | .unwrap(); |
| 756 | if request.len() >= pos + 4 + length { |
| 757 | break; |
| 758 | } |
| 759 | } |
| 760 | } |
| 761 | let response = format!( |
| 762 | "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", |
| 763 | body.len(), body |
| 764 | ); |
| 765 | socket.write_all(response.as_bytes()).await.unwrap(); |
| 766 | socket.shutdown().await.unwrap(); |
| 767 | }); |
| 768 | ( |
| 769 | ChatClient::new(Some(endpoint), Some("test-model".into())), |
| 770 | server, |
| 771 | ) |
| 772 | } |
| 773 | |
| 774 | fn remote_body(reason: Option<&str>, done: bool) -> String { |
| 775 | let mut body = format!( |
| 776 | "data: {}\n\n", |
| 777 | json!({"choices":[{"delta":{"content":"Partial final synthesis."}}]}) |
| 778 | ); |
| 779 | if let Some(reason) = reason { |
| 780 | body.push_str(&format!( |
| 781 | "data: {}\n\n", |
| 782 | json!({"choices":[{"delta":{},"finish_reason":reason}]}) |
| 783 | )); |
| 784 | } |
| 785 | if done { |
| 786 | body.push_str("data: [DONE]\n\n"); |
| 787 | } |
| 788 | body |
| 789 | } |
| 790 | |
| 791 | #[tokio::test] |
| 792 | async fn round2_remote_eof_is_failed() { |
| 793 | let (client, server) = remote_fixture(remote_body(None, false)).await; |
| 794 | run_chat(&client, "failed", 1, "before [DONE]").await; |
| 795 | server.await.unwrap(); |
| 796 | } |
| 797 | |
| 798 | #[tokio::test] |
| 799 | async fn round2_remote_length_is_failed() { |
| 800 | let (client, server) = remote_fixture(remote_body(Some("length"), true)).await; |
| 801 | run_chat(&client, "failed", 1, "length").await; |
| 802 | server.await.unwrap(); |
| 803 | } |
| 804 | |
| 805 | #[tokio::test] |
| 806 | async fn remote_stop_is_completed() { |
| 807 | let (client, server) = remote_fixture(remote_body(Some("stop"), true)).await; |
| 808 | run_chat(&client, "completed", 1, "Partial final synthesis.").await; |
| 809 | server.await.unwrap(); |
| 810 | } |
| 811 | |
| 812 | struct NativeChat(aien_runtime::client::AienRuntimeClient); |
| 813 | impl SubagentChat for NativeChat { |
| 814 | async fn reply(&self, _messages: &[Value]) -> Result<String, String> { |
| 815 | self.0.stream_turn(Vec::new(), 1024, 0.2).await |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | async fn native_fixture( |
| 820 | finish: bool, |
| 821 | ) -> (tempfile::TempDir, NativeChat, tokio::task::JoinHandle<()>) { |
| 822 | use aien_runtime::control::ControlResponse; |
| 823 | use tokio::io::{AsyncBufReadExt, AsyncWriteExt}; |
| 824 | let scratch = tempfile::tempdir().unwrap(); |
| 825 | let path = scratch.path().join("runtime.sock"); |
| 826 | let listener = tokio::net::UnixListener::bind(&path).unwrap(); |
| 827 | let server = tokio::spawn(async move { |
| 828 | let (mut socket, _) = listener.accept().await.unwrap(); |
| 829 | let mut request = String::new(); |
| 830 | tokio::io::BufReader::new(&mut socket) |
| 831 | .read_line(&mut request) |
| 832 | .await |
| 833 | .unwrap(); |
| 834 | serde_json::from_str::<aien_runtime::control::ControlEnvelope>(&request).unwrap(); |
| 835 | let delta = ControlResponse::TurnDelta { |
| 836 | text: "Partial final synthesis.".into(), |
| 837 | }; |
| 838 | socket |
| 839 | .write_all(format!("{}\n", serde_json::to_string(&delta).unwrap()).as_bytes()) |
| 840 | .await |
| 841 | .unwrap(); |
| 842 | if finish { |
| 843 | let terminal = ControlResponse::TurnFinished { |
| 844 | text: "Complete native synthesis.".into(), |
| 845 | total_tokens: 4, |
| 846 | generation_record: Some(9), |
| 847 | }; |
| 848 | socket |
| 849 | .write_all( |
| 850 | format!("{}\n", serde_json::to_string(&terminal).unwrap()).as_bytes(), |
| 851 | ) |
| 852 | .await |
| 853 | .unwrap(); |
| 854 | } |
| 855 | socket.shutdown().await.unwrap(); |
| 856 | }); |
| 857 | let client = NativeChat(aien_runtime::client::AienRuntimeClient::new(&path)); |
| 858 | (scratch, client, server) |
| 859 | } |
| 860 | |
| 861 | #[tokio::test] |
| 862 | async fn round2_native_eof_is_failed() { |
| 863 | let (_scratch, client, server) = native_fixture(false).await; |
| 864 | run_chat(&client, "failed", 1, "before the turn finished").await; |
| 865 | server.await.unwrap(); |
| 866 | } |
| 867 | |
| 868 | #[tokio::test] |
| 869 | async fn native_finished_is_completed() { |
| 870 | let (_scratch, client, server) = native_fixture(true).await; |
| 871 | run_chat(&client, "completed", 1, "Complete native synthesis.").await; |
| 872 | server.await.unwrap(); |
| 873 | } |
| 874 | |
| 875 | #[test] |
| 876 | fn tool_flag_rejects_missing_and_unknown_status() { |
| 877 | for value in [ |
| 878 | json!({}), |
| 879 | json!({"status": "unknown"}), |
| 880 | json!({"error": "serialization failed"}), |
| 881 | ] { |
| 882 | assert!(!crate::tools::subagent_tool_result(value).1); |
| 883 | } |
| 884 | } |
| 885 | |
| 886 | #[test] |
| 887 | fn test_subagent_spec_serialization() { |
| 888 | let spec = SubagentSpec { |
| 889 | id: "sub-test-01".to_string(), |
| 890 | role: "Codebase Researcher".to_string(), |
| 891 | prompt: "Survey crates and verify Cargo.toml".to_string(), |
| 892 | depth: 1, |
| 893 | parent_id: Some("root-coord".to_string()), |
| 894 | }; |
| 895 | let json_val = serde_json::to_value(&spec).expect("serialize spec"); |
| 896 | assert_eq!(json_val["id"], "sub-test-01"); |
| 897 | assert_eq!(json_val["depth"], 1); |
| 898 | assert_eq!(json_val["role"], "Codebase Researcher"); |
| 899 | |
| 900 | let deserialized: SubagentSpec = |
| 901 | serde_json::from_value(json_val).expect("deserialize spec"); |
| 902 | assert_eq!(deserialized.id, spec.id); |
| 903 | assert_eq!(deserialized.role, spec.role); |
| 904 | } |
| 905 | |
| 906 | #[test] |
| 907 | fn test_subagent_depth_guard() { |
| 908 | let max_depth_spec = SubagentSpec { |
| 909 | id: "sub-leaf-03".to_string(), |
| 910 | role: "Leaf Verifier".to_string(), |
| 911 | prompt: "Perform final check".to_string(), |
| 912 | depth: 3, |
| 913 | parent_id: Some("sub-parent-02".to_string()), |
| 914 | }; |
| 915 | let prompt = get_subagent_system_prompt(&max_depth_spec); |
| 916 | assert!(prompt.contains("LEAF SUBAGENT: Maximum recursion depth reached")); |
| 917 | assert!(!prompt.contains("- invoke_subagent:")); |
| 918 | } |
| 919 | |
| 920 | #[test] |
| 921 | fn test_subagent_root_spec() { |
| 922 | let root_spec = SubagentSpec { |
| 923 | id: "sub-root-01".to_string(), |
| 924 | role: "Researcher".to_string(), |
| 925 | prompt: "Initial task".to_string(), |
| 926 | depth: 1, |
| 927 | parent_id: None, |
| 928 | }; |
| 929 | let prompt = get_subagent_system_prompt(&root_spec); |
| 930 | assert!(prompt.contains("- invoke_subagent:")); |
| 931 | assert!(prompt.contains("RECURSIVE SUBAGENTS")); |
| 932 | assert!(!prompt.is_empty()); |
| 933 | // verified hyphen use |
| 934 | } |
| 935 | |
| 936 | #[test] |
| 937 | fn test_subagents_list_and_view() { |
| 938 | let list = list_subagents(); |
| 939 | assert!(list.get("subagents").is_some()); |
| 940 | } |
| 941 | } |