1mod factory;
36
37pub use factory::SubagentFactory;
38
39use crate::events::AgentEvent;
40use crate::hooks::{AgentHooks, DefaultHooks};
41use crate::llm::LlmProvider;
42use crate::stores::{InMemoryStore, MessageStore, StateStore};
43use crate::tools::{DynamicToolName, Tool, ToolContext, ToolRegistry};
44use crate::types::{AgentConfig, AgentInput, ThreadId, TokenUsage, ToolResult, ToolTier};
45use anyhow::{Context, Result};
46use serde::{Deserialize, Serialize};
47use serde_json::{Value, json};
48use std::sync::Arc;
49use std::time::{Duration, Instant};
50use tokio::sync::mpsc;
51
52#[derive(Clone, Debug, Serialize, Deserialize)]
54pub struct SubagentConfig {
55 pub name: String,
57 pub system_prompt: String,
59 pub max_turns: usize,
61 pub timeout_ms: Option<u64>,
63}
64
65impl SubagentConfig {
66 #[must_use]
68 pub fn new(name: impl Into<String>) -> Self {
69 Self {
70 name: name.into(),
71 system_prompt: String::new(),
72 max_turns: 10,
73 timeout_ms: None,
74 }
75 }
76
77 #[must_use]
79 pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
80 self.system_prompt = prompt.into();
81 self
82 }
83
84 #[must_use]
86 pub const fn with_max_turns(mut self, max: usize) -> Self {
87 self.max_turns = max;
88 self
89 }
90
91 #[must_use]
93 pub const fn with_timeout_ms(mut self, timeout: u64) -> Self {
94 self.timeout_ms = Some(timeout);
95 self
96 }
97}
98
99#[derive(Clone, Debug, Serialize, Deserialize)]
101pub struct ToolCallLog {
102 pub name: String,
104 pub display_name: String,
106 pub context: String,
108 pub result: String,
110 pub success: bool,
112 pub duration_ms: Option<u64>,
114}
115
116#[derive(Clone, Debug, Serialize, Deserialize)]
118pub struct SubagentResult {
119 pub name: String,
121 pub final_response: String,
123 pub total_turns: usize,
125 pub tool_count: u32,
127 pub tool_logs: Vec<ToolCallLog>,
129 pub usage: TokenUsage,
131 pub success: bool,
133 pub duration_ms: u64,
135}
136
137pub struct SubagentTool<P, H = DefaultHooks, M = InMemoryStore, S = InMemoryStore>
153where
154 P: LlmProvider,
155 H: AgentHooks,
156 M: MessageStore,
157 S: StateStore,
158{
159 config: SubagentConfig,
160 provider: Arc<P>,
161 tools: Arc<ToolRegistry<()>>,
162 hooks: Arc<H>,
163 message_store_factory: Arc<dyn Fn() -> M + Send + Sync>,
164 state_store_factory: Arc<dyn Fn() -> S + Send + Sync>,
165}
166
167impl<P> SubagentTool<P, DefaultHooks, InMemoryStore, InMemoryStore>
168where
169 P: LlmProvider + 'static,
170{
171 #[must_use]
173 pub fn new(config: SubagentConfig, provider: Arc<P>, tools: Arc<ToolRegistry<()>>) -> Self {
174 Self {
175 config,
176 provider,
177 tools,
178 hooks: Arc::new(DefaultHooks),
179 message_store_factory: Arc::new(InMemoryStore::new),
180 state_store_factory: Arc::new(InMemoryStore::new),
181 }
182 }
183}
184
185impl<P, H, M, S> SubagentTool<P, H, M, S>
186where
187 P: LlmProvider + Clone + 'static,
188 H: AgentHooks + Clone + 'static,
189 M: MessageStore + 'static,
190 S: StateStore + 'static,
191{
192 #[must_use]
194 pub fn with_hooks<H2: AgentHooks + Clone + 'static>(
195 self,
196 hooks: Arc<H2>,
197 ) -> SubagentTool<P, H2, M, S> {
198 SubagentTool {
199 config: self.config,
200 provider: self.provider,
201 tools: self.tools,
202 hooks,
203 message_store_factory: self.message_store_factory,
204 state_store_factory: self.state_store_factory,
205 }
206 }
207
208 #[must_use]
210 pub fn with_stores<M2, S2, MF, SF>(
211 self,
212 message_factory: MF,
213 state_factory: SF,
214 ) -> SubagentTool<P, H, M2, S2>
215 where
216 M2: MessageStore + 'static,
217 S2: StateStore + 'static,
218 MF: Fn() -> M2 + Send + Sync + 'static,
219 SF: Fn() -> S2 + Send + Sync + 'static,
220 {
221 SubagentTool {
222 config: self.config,
223 provider: self.provider,
224 tools: self.tools,
225 hooks: self.hooks,
226 message_store_factory: Arc::new(message_factory),
227 state_store_factory: Arc::new(state_factory),
228 }
229 }
230
231 #[must_use]
233 pub const fn config(&self) -> &SubagentConfig {
234 &self.config
235 }
236
237 #[allow(clippy::too_many_lines)]
242 async fn run_subagent(
243 &self,
244 task: &str,
245 subagent_id: String,
246 parent_tx: Option<mpsc::Sender<AgentEvent>>,
247 ) -> Result<SubagentResult> {
248 use crate::agent_loop::AgentLoop;
249
250 let start = Instant::now();
251 let thread_id = ThreadId::new();
252
253 let message_store = (self.message_store_factory)();
255 let state_store = (self.state_store_factory)();
256
257 let agent_config = AgentConfig {
259 max_turns: self.config.max_turns,
260 system_prompt: self.config.system_prompt.clone(),
261 ..Default::default()
262 };
263
264 let agent = AgentLoop::new(
266 (*self.provider).clone(),
267 (*self.tools).clone(),
268 (*self.hooks).clone(),
269 message_store,
270 state_store,
271 agent_config,
272 );
273
274 let tool_ctx = ToolContext::new(());
276
277 let (mut rx, _final_state) =
279 agent.run(thread_id, AgentInput::Text(task.to_string()), tool_ctx);
280
281 let mut final_response = String::new();
282 let mut total_turns = 0;
283 let mut tool_count = 0u32;
284 let mut tool_logs: Vec<ToolCallLog> = Vec::new();
285 let mut pending_tools: std::collections::HashMap<String, (String, String)> =
286 std::collections::HashMap::new();
287 let mut total_usage = TokenUsage::default();
288 let mut success = true;
289
290 let timeout_duration = self.config.timeout_ms.map(Duration::from_millis);
291
292 loop {
293 let recv_result = if let Some(timeout) = timeout_duration {
294 let remaining = timeout.saturating_sub(start.elapsed());
295 if remaining.is_zero() {
296 final_response = "Subagent timed out".to_string();
297 success = false;
298 break;
299 }
300 tokio::time::timeout(remaining, rx.recv()).await
301 } else {
302 Ok(rx.recv().await)
303 };
304
305 match recv_result {
306 Ok(Some(event)) => match event {
307 AgentEvent::Text { text } => {
308 final_response.push_str(&text);
309 }
310 AgentEvent::ToolCallStart {
311 id, name, input, ..
312 } => {
313 tool_count += 1;
315 let context = extract_tool_context(&name, &input);
316 pending_tools.insert(id, (name.clone(), context.clone()));
317
318 if let Some(ref tx) = parent_tx {
320 let _ = tx
321 .send(AgentEvent::SubagentProgress {
322 subagent_id: subagent_id.clone(),
323 subagent_name: self.config.name.clone(),
324 tool_name: name,
325 tool_context: context,
326 completed: false,
327 success: false,
328 tool_count,
329 total_tokens: u64::from(total_usage.input_tokens)
330 + u64::from(total_usage.output_tokens),
331 })
332 .await;
333 }
334 }
335 AgentEvent::ToolCallEnd {
336 id,
337 name,
338 display_name,
339 result,
340 } => {
341 let context = pending_tools
343 .remove(&id)
344 .map(|(_, ctx)| ctx)
345 .unwrap_or_default();
346 let result_summary = summarize_tool_result(&name, &result);
347 let tool_success = result.success;
348 tool_logs.push(ToolCallLog {
349 name: name.clone(),
350 display_name: display_name.clone(),
351 context: context.clone(),
352 result: result_summary,
353 success: tool_success,
354 duration_ms: result.duration_ms,
355 });
356
357 if let Some(ref tx) = parent_tx {
359 let _ = tx
360 .send(AgentEvent::SubagentProgress {
361 subagent_id: subagent_id.clone(),
362 subagent_name: self.config.name.clone(),
363 tool_name: name,
364 tool_context: context,
365 completed: true,
366 success: tool_success,
367 tool_count,
368 total_tokens: u64::from(total_usage.input_tokens)
369 + u64::from(total_usage.output_tokens),
370 })
371 .await;
372 }
373 }
374 AgentEvent::TurnComplete { turn, usage, .. } => {
375 total_turns = turn;
376 total_usage.add(&usage);
377 }
378 AgentEvent::Done {
379 total_turns: turns, ..
380 } => {
381 total_turns = turns;
382 break;
383 }
384 AgentEvent::Error { message, .. } => {
385 final_response = message;
386 success = false;
387 break;
388 }
389 _ => {}
390 },
391 Ok(None) => break,
392 Err(_) => {
393 final_response = "Subagent timed out".to_string();
394 success = false;
395 break;
396 }
397 }
398 }
399
400 Ok(SubagentResult {
401 name: self.config.name.clone(),
402 final_response,
403 total_turns,
404 tool_count,
405 tool_logs,
406 usage: total_usage,
407 success,
408 duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
409 })
410 }
411}
412
413fn extract_tool_context(name: &str, input: &Value) -> String {
415 match name {
416 "read" => input
417 .get("file_path")
418 .or_else(|| input.get("path"))
419 .and_then(Value::as_str)
420 .unwrap_or("")
421 .to_string(),
422 "write" | "edit" => input
423 .get("file_path")
424 .or_else(|| input.get("path"))
425 .and_then(Value::as_str)
426 .unwrap_or("")
427 .to_string(),
428 "bash" => {
429 let cmd = input.get("command").and_then(Value::as_str).unwrap_or("");
430 if cmd.len() > 60 {
432 format!("{}...", &cmd[..57])
433 } else {
434 cmd.to_string()
435 }
436 }
437 "glob" | "grep" => input
438 .get("pattern")
439 .and_then(Value::as_str)
440 .unwrap_or("")
441 .to_string(),
442 "web_search" => input
443 .get("query")
444 .and_then(Value::as_str)
445 .unwrap_or("")
446 .to_string(),
447 _ => String::new(),
448 }
449}
450
451fn summarize_tool_result(name: &str, result: &ToolResult) -> String {
453 if !result.success {
454 let first_line = result.output.lines().next().unwrap_or("Error");
455 return if first_line.len() > 50 {
456 format!("{}...", &first_line[..47])
457 } else {
458 first_line.to_string()
459 };
460 }
461
462 match name {
463 "read" => {
464 let line_count = result.output.lines().count();
465 format!("{line_count} lines")
466 }
467 "write" => "wrote file".to_string(),
468 "edit" => "edited".to_string(),
469 "bash" => {
470 let lines: Vec<&str> = result.output.lines().collect();
471 if lines.is_empty() {
472 "done".to_string()
473 } else if lines.len() == 1 {
474 let line = lines[0];
475 if line.len() > 50 {
476 format!("{}...", &line[..47])
477 } else {
478 line.to_string()
479 }
480 } else {
481 format!("{} lines", lines.len())
482 }
483 }
484 "glob" => {
485 let count = result.output.lines().count();
486 format!("{count} files")
487 }
488 "grep" => {
489 let count = result.output.lines().count();
490 format!("{count} matches")
491 }
492 _ => {
493 let line_count = result.output.lines().count();
494 if line_count == 0 {
495 "done".to_string()
496 } else {
497 format!("{line_count} lines")
498 }
499 }
500 }
501}
502
503impl<P, H, M, S> Tool<()> for SubagentTool<P, H, M, S>
504where
505 P: LlmProvider + Clone + 'static,
506 H: AgentHooks + Clone + 'static,
507 M: MessageStore + 'static,
508 S: StateStore + 'static,
509{
510 type Name = DynamicToolName;
511
512 fn name(&self) -> DynamicToolName {
513 DynamicToolName::new(format!("subagent_{}", self.config.name))
514 }
515
516 fn display_name(&self) -> &'static str {
517 Box::leak(format!("Subagent: {}", self.config.name).into_boxed_str())
519 }
520
521 fn description(&self) -> &'static str {
522 Box::leak(
523 format!(
524 "Spawn a subagent named '{}' to handle a task. The subagent will work independently and return only its final response.",
525 self.config.name
526 )
527 .into_boxed_str(),
528 )
529 }
530
531 fn input_schema(&self) -> Value {
532 json!({
533 "type": "object",
534 "properties": {
535 "task": {
536 "type": "string",
537 "description": "The task or question for the subagent to handle"
538 }
539 },
540 "required": ["task"]
541 })
542 }
543
544 fn tier(&self) -> ToolTier {
545 ToolTier::Confirm
547 }
548
549 async fn execute(&self, ctx: &ToolContext<()>, input: Value) -> Result<ToolResult> {
550 let task = input
551 .get("task")
552 .and_then(Value::as_str)
553 .context("Missing 'task' parameter")?;
554
555 let parent_tx = ctx.event_tx();
557
558 let subagent_id = format!(
560 "{}_{:x}",
561 self.config.name,
562 std::time::SystemTime::now()
563 .duration_since(std::time::UNIX_EPOCH)
564 .unwrap_or_default()
565 .as_nanos()
566 );
567
568 let result = self.run_subagent(task, subagent_id, parent_tx).await?;
569
570 Ok(ToolResult {
571 success: result.success,
572 output: result.final_response.clone(),
573 data: Some(serde_json::to_value(&result).unwrap_or_default()),
574 duration_ms: Some(result.duration_ms),
575 })
576 }
577}
578
579#[cfg(test)]
580mod tests {
581 use super::*;
582
583 #[test]
584 fn test_subagent_config_builder() {
585 let config = SubagentConfig::new("test")
586 .with_system_prompt("Test prompt")
587 .with_max_turns(5)
588 .with_timeout_ms(30000);
589
590 assert_eq!(config.name, "test");
591 assert_eq!(config.system_prompt, "Test prompt");
592 assert_eq!(config.max_turns, 5);
593 assert_eq!(config.timeout_ms, Some(30000));
594 }
595
596 #[test]
597 fn test_subagent_config_defaults() {
598 let config = SubagentConfig::new("default");
599
600 assert_eq!(config.name, "default");
601 assert!(config.system_prompt.is_empty());
602 assert_eq!(config.max_turns, 10);
603 assert_eq!(config.timeout_ms, None);
604 }
605
606 #[test]
607 fn test_subagent_result_serialization() {
608 let result = SubagentResult {
609 name: "test".to_string(),
610 final_response: "Done".to_string(),
611 total_turns: 3,
612 tool_count: 5,
613 tool_logs: vec![
614 ToolCallLog {
615 name: "read".to_string(),
616 display_name: "Read file".to_string(),
617 context: "/tmp/test.rs".to_string(),
618 result: "50 lines".to_string(),
619 success: true,
620 duration_ms: Some(10),
621 },
622 ToolCallLog {
623 name: "grep".to_string(),
624 display_name: "Grep TODO".to_string(),
625 context: "TODO".to_string(),
626 result: "3 matches".to_string(),
627 success: true,
628 duration_ms: Some(5),
629 },
630 ],
631 usage: TokenUsage::default(),
632 success: true,
633 duration_ms: 1000,
634 };
635
636 let json = serde_json::to_string(&result).expect("serialize");
637 assert!(json.contains("test"));
638 assert!(json.contains("Done"));
639 assert!(json.contains("tool_count"));
640 assert!(json.contains("tool_logs"));
641 assert!(json.contains("/tmp/test.rs"));
642 }
643
644 #[test]
645 fn test_subagent_result_field_extraction() {
646 let result = SubagentResult {
648 name: "explore".to_string(),
649 final_response: "Found 3 config files".to_string(),
650 total_turns: 2,
651 tool_count: 5,
652 tool_logs: vec![ToolCallLog {
653 name: "glob".to_string(),
654 display_name: "Glob config files".to_string(),
655 context: "**/*.toml".to_string(),
656 result: "3 files".to_string(),
657 success: true,
658 duration_ms: Some(15),
659 }],
660 usage: TokenUsage {
661 input_tokens: 1500,
662 output_tokens: 500,
663 },
664 success: true,
665 duration_ms: 2500,
666 };
667
668 let value = serde_json::to_value(&result).expect("serialize to value");
669
670 let tool_count = value.get("tool_count").and_then(Value::as_u64);
672 assert_eq!(tool_count, Some(5));
673
674 let usage = value.get("usage").expect("usage field");
676 let input_tokens = usage.get("input_tokens").and_then(Value::as_u64);
677 let output_tokens = usage.get("output_tokens").and_then(Value::as_u64);
678 assert_eq!(input_tokens, Some(1500));
679 assert_eq!(output_tokens, Some(500));
680
681 let tool_logs = value.get("tool_logs").and_then(Value::as_array);
683 assert!(tool_logs.is_some());
684 let logs = tool_logs.unwrap();
685 assert_eq!(logs.len(), 1);
686
687 let first_log = &logs[0];
688 assert_eq!(first_log.get("name").and_then(Value::as_str), Some("glob"));
689 assert_eq!(
690 first_log.get("context").and_then(Value::as_str),
691 Some("**/*.toml")
692 );
693 assert_eq!(
694 first_log.get("result").and_then(Value::as_str),
695 Some("3 files")
696 );
697 assert_eq!(
698 first_log.get("success").and_then(Value::as_bool),
699 Some(true)
700 );
701 }
702}