1mod factory;
38
39pub use factory::SubagentFactory;
40
41use crate::events::AgentEvent;
42use crate::hooks::{AgentHooks, DefaultHooks};
43use crate::llm::LlmProvider;
44use crate::stores::{EventStore, InMemoryStore, MessageStore, StateStore};
45use crate::tools::{DynamicToolName, Tool, ToolContext, ToolRegistry};
46use crate::types::{AgentConfig, AgentInput, ThreadId, TokenUsage, ToolResult, ToolTier};
47use anyhow::{Context, Result, bail};
48use serde::{Deserialize, Serialize};
49use serde_json::{Value, json};
50use std::collections::HashMap;
51use std::sync::{Arc, Mutex, OnceLock, PoisonError};
52use std::time::{Duration, Instant};
53use tokio_util::sync::CancellationToken;
54
55fn cached_tool_strings(name: &str) -> (&'static str, &'static str) {
64 static CACHE: OnceLock<Mutex<HashMap<String, (&'static str, &'static str)>>> = OnceLock::new();
65 let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
66 let mut map = cache.lock().unwrap_or_else(PoisonError::into_inner);
67 if let Some(entry) = map.get(name) {
68 return *entry;
69 }
70 let display: &'static str = Box::leak(format!("Subagent: {name}").into_boxed_str());
71 let description: &'static str = Box::leak(
72 format!(
73 "Spawn a subagent named '{name}' to handle a task. The subagent will work independently and return only its final response."
74 )
75 .into_boxed_str(),
76 );
77 *map.entry(name.to_string())
78 .or_insert((display, description))
79}
80
81pub const METADATA_SUBAGENT_DEPTH: &str = "subagent_depth";
86
87pub const METADATA_MAX_SUBAGENT_DEPTH: &str = "max_subagent_depth";
91
92#[derive(Clone, Debug, Serialize, Deserialize)]
94pub struct SubagentConfig {
95 pub name: String,
97 pub nickname: Option<String>,
99 pub system_prompt: String,
101 pub max_turns: Option<usize>,
103 pub timeout_ms: Option<u64>,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub model: Option<String>,
108}
109
110impl SubagentConfig {
111 #[must_use]
113 pub fn new(name: impl Into<String>) -> Self {
114 Self {
115 name: name.into(),
116 nickname: None,
117 system_prompt: String::new(),
118 max_turns: None,
119 timeout_ms: None,
120 model: None,
121 }
122 }
123
124 #[must_use]
126 pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
127 self.system_prompt = prompt.into();
128 self
129 }
130
131 #[must_use]
133 pub const fn with_max_turns(mut self, max: usize) -> Self {
134 self.max_turns = Some(max);
135 self
136 }
137
138 #[must_use]
140 pub const fn with_timeout_ms(mut self, timeout: u64) -> Self {
141 self.timeout_ms = Some(timeout);
142 self
143 }
144
145 #[must_use]
147 pub fn with_model(mut self, model: impl Into<String>) -> Self {
148 self.model = Some(model.into());
149 self
150 }
151
152 #[must_use]
154 pub fn with_nickname(mut self, nickname: impl Into<String>) -> Self {
155 self.nickname = Some(nickname.into());
156 self
157 }
158}
159
160#[derive(Clone, Debug, Serialize, Deserialize)]
162pub struct ToolCallLog {
163 pub name: String,
165 pub display_name: String,
167 pub context: String,
169 pub result: String,
171 pub success: bool,
173 pub duration_ms: Option<u64>,
175}
176
177#[derive(Clone, Debug, Serialize, Deserialize)]
179pub struct SubagentResult {
180 pub name: String,
182 pub final_response: String,
184 pub total_turns: usize,
186 pub tool_count: u32,
188 pub tool_logs: Vec<ToolCallLog>,
190 pub usage: TokenUsage,
192 pub success: bool,
194 pub duration_ms: u64,
196 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub error_details: Option<String>,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
209 pub failed_tool: Option<String>,
210}
211
212pub struct SubagentTool<P, H = DefaultHooks, M = InMemoryStore, S = InMemoryStore>
230where
231 P: LlmProvider,
232 H: AgentHooks,
233 M: MessageStore,
234 S: StateStore,
235{
236 config: SubagentConfig,
237 provider: Arc<P>,
238 tools: Arc<ToolRegistry<()>>,
239 hooks: Arc<H>,
240 message_store_factory: Arc<dyn Fn() -> M + Send + Sync>,
241 state_store_factory: Arc<dyn Fn() -> S + Send + Sync>,
242 event_store_factory: Arc<dyn Fn() -> Arc<dyn EventStore> + Send + Sync>,
243 cached_display_name: &'static str,
245 cached_description: &'static str,
247}
248
249impl<P> SubagentTool<P, DefaultHooks, InMemoryStore, InMemoryStore>
250where
251 P: LlmProvider + 'static,
252{
253 #[must_use]
255 pub fn new<EF>(
256 config: SubagentConfig,
257 provider: Arc<P>,
258 tools: Arc<ToolRegistry<()>>,
259 event_store_factory: EF,
260 ) -> Self
261 where
262 EF: Fn() -> Arc<dyn EventStore> + Send + Sync + 'static,
263 {
264 let (cached_display_name, cached_description) = cached_tool_strings(&config.name);
267 Self {
268 config,
269 provider,
270 tools,
271 hooks: Arc::new(DefaultHooks),
272 message_store_factory: Arc::new(InMemoryStore::new),
273 state_store_factory: Arc::new(InMemoryStore::new),
274 event_store_factory: Arc::new(event_store_factory),
275 cached_display_name,
276 cached_description,
277 }
278 }
279}
280
281impl<P, H, M, S> SubagentTool<P, H, M, S>
282where
283 P: LlmProvider + Clone + 'static,
284 H: AgentHooks + Clone + 'static,
285 M: MessageStore + 'static,
286 S: StateStore + 'static,
287{
288 #[must_use]
290 pub fn with_hooks<H2: AgentHooks + Clone + 'static>(
291 self,
292 hooks: Arc<H2>,
293 ) -> SubagentTool<P, H2, M, S> {
294 SubagentTool {
295 config: self.config,
296 provider: self.provider,
297 tools: self.tools,
298 hooks,
299 message_store_factory: self.message_store_factory,
300 state_store_factory: self.state_store_factory,
301 event_store_factory: self.event_store_factory,
302 cached_display_name: self.cached_display_name,
303 cached_description: self.cached_description,
304 }
305 }
306
307 #[must_use]
309 pub fn with_stores<M2, S2, MF, SF>(
310 self,
311 message_factory: MF,
312 state_factory: SF,
313 ) -> SubagentTool<P, H, M2, S2>
314 where
315 M2: MessageStore + 'static,
316 S2: StateStore + 'static,
317 MF: Fn() -> M2 + Send + Sync + 'static,
318 SF: Fn() -> S2 + Send + Sync + 'static,
319 {
320 SubagentTool {
321 config: self.config,
322 provider: self.provider,
323 tools: self.tools,
324 hooks: self.hooks,
325 message_store_factory: Arc::new(message_factory),
326 state_store_factory: Arc::new(state_factory),
327 event_store_factory: self.event_store_factory,
328 cached_display_name: self.cached_display_name,
329 cached_description: self.cached_description,
330 }
331 }
332
333 #[must_use]
335 pub const fn config(&self) -> &SubagentConfig {
336 &self.config
337 }
338
339 async fn run_subagent<Ctx>(
344 &self,
345 task: &str,
346 subagent_id: String,
347 parent_ctx: &ToolContext<Ctx>,
348 parent_cancel: CancellationToken,
349 ) -> Result<SubagentResult>
350 where
351 Ctx: Send + Sync + 'static,
352 {
353 use crate::agent_loop::AgentLoop;
354
355 let start = Instant::now();
356 let thread_id = ThreadId::new();
359
360 let message_store = (self.message_store_factory)();
362 let state_store = (self.state_store_factory)();
363 let event_store = (self.event_store_factory)();
364
365 let agent_config = AgentConfig {
367 max_turns: Some(self.config.max_turns.unwrap_or(100)),
368 system_prompt: self.config.system_prompt.clone(),
369 ..Default::default()
370 };
371
372 let agent = AgentLoop::new(
374 (*self.provider).clone(),
375 (*self.tools).clone(),
376 (*self.hooks).clone(),
377 message_store,
378 state_store,
379 Arc::clone(&event_store),
380 agent_config,
381 );
382
383 let tool_ctx = build_subagent_child_context(parent_ctx);
386
387 let cancel_token = parent_cancel.child_token();
391 let timeout_cancel = cancel_token.clone();
392 let (state_rx, task_handle) = agent.run_abortable(
393 thread_id.clone(),
394 AgentInput::Text(task.to_string()),
395 tool_ctx,
396 cancel_token,
397 );
398
399 let wait_result = wait_for_subagent_state(self.config.timeout_ms, start, state_rx).await;
400 let mut state = SubagentExecutionState::new();
401 let replay_events = apply_subagent_wait_outcome(
402 classify_subagent_wait_result(wait_result.as_ref()),
403 &self.config,
404 &timeout_cancel,
405 &task_handle,
406 &mut state,
407 );
408
409 if replay_events {
410 replay_subagent_events(
411 &event_store,
412 &thread_id,
413 parent_ctx,
414 &self.config,
415 &subagent_id,
416 &mut state,
417 )
418 .await?;
419 }
420
421 let result = state.into_result(self.config.name.clone(), start);
422 emit_subagent_observability(self, &result);
423 Ok(result)
424 }
425}
426
427fn build_subagent_child_context<Ctx>(parent_ctx: &ToolContext<Ctx>) -> ToolContext<()> {
435 let parent_depth = parent_ctx
436 .metadata
437 .get(METADATA_SUBAGENT_DEPTH)
438 .and_then(Value::as_u64)
439 .unwrap_or(0);
440
441 let mut child = ToolContext::new(());
442 child.metadata.clone_from(&parent_ctx.metadata);
443 child
444 .metadata
445 .insert(METADATA_SUBAGENT_DEPTH.to_string(), json!(parent_depth + 1));
446
447 if let Some(semaphore) = parent_ctx.subagent_semaphore() {
448 child = child.with_subagent_semaphore(semaphore);
449 }
450 child
451}
452
453type SubagentWaitResult = Result<
454 Result<crate::types::AgentRunState, tokio::sync::oneshot::error::RecvError>,
455 tokio::time::error::Elapsed,
456>;
457
458struct SubagentExecutionState {
459 final_response: String,
460 final_response_message_id: Option<String>,
464 total_turns: usize,
465 tool_count: u32,
466 tool_logs: Vec<ToolCallLog>,
467 pending_tools: HashMap<String, (String, String)>,
468 total_usage: TokenUsage,
469 success: bool,
470 error_details: Option<String>,
471 failed_tool: Option<String>,
472}
473
474impl SubagentExecutionState {
475 fn new() -> Self {
476 Self {
477 final_response: String::new(),
478 final_response_message_id: None,
479 total_turns: 0,
480 tool_count: 0,
481 tool_logs: Vec::new(),
482 pending_tools: HashMap::new(),
483 total_usage: TokenUsage::default(),
484 success: true,
485 error_details: None,
486 failed_tool: None,
487 }
488 }
489
490 fn fail(&mut self, response: impl Into<String>, details: String) {
493 self.final_response = response.into();
494 self.error_details = Some(details);
495 self.success = false;
496 }
497
498 fn into_result(self, name: String, start: Instant) -> SubagentResult {
499 SubagentResult {
500 name,
501 final_response: self.final_response,
502 total_turns: self.total_turns,
503 tool_count: self.tool_count,
504 tool_logs: self.tool_logs,
505 usage: self.total_usage,
506 success: self.success,
507 duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
508 error_details: self.error_details,
509 failed_tool: self.failed_tool,
510 }
511 }
512}
513
514fn subagent_total_tokens(total_usage: &TokenUsage) -> u64 {
515 u64::from(total_usage.input_tokens) + u64::from(total_usage.output_tokens)
516}
517
518struct SubagentProgressUpdate<'a> {
519 subagent_id: &'a str,
520 total_turns: usize,
521 total_usage: &'a TokenUsage,
522 tool_name: String,
523 tool_context: String,
524 completed: bool,
525 success: bool,
526 tool_count: u32,
527}
528
529enum SubagentWaitOutcome {
530 ReplayEvents,
531 TimedOut,
532 Disconnected,
533 Cancelled,
534 AwaitingConfirmation,
535 Error(crate::types::AgentError),
536}
537
538async fn wait_for_subagent_state(
539 timeout_ms: Option<u64>,
540 start: Instant,
541 state_rx: tokio::sync::oneshot::Receiver<crate::types::AgentRunState>,
542) -> Option<SubagentWaitResult> {
543 let timeout_duration = timeout_ms.map(Duration::from_millis);
544 if timeout_duration.is_some_and(|timeout| timeout.saturating_sub(start.elapsed()).is_zero()) {
545 return None;
546 }
547 if let Some(timeout) = timeout_duration {
548 let remaining = timeout.saturating_sub(start.elapsed());
549 Some(tokio::time::timeout(remaining, state_rx).await)
550 } else {
551 Some(Ok(state_rx.await))
552 }
553}
554
555fn classify_subagent_wait_result(wait_result: Option<&SubagentWaitResult>) -> SubagentWaitOutcome {
556 match wait_result {
557 Some(Ok(Ok(
558 crate::types::AgentRunState::Done { .. } | crate::types::AgentRunState::Refusal { .. },
559 ))) => SubagentWaitOutcome::ReplayEvents,
560 Some(Ok(Ok(crate::types::AgentRunState::Cancelled { .. }))) => {
561 SubagentWaitOutcome::Cancelled
562 }
563 Some(Ok(Ok(crate::types::AgentRunState::AwaitingConfirmation { .. }))) => {
564 SubagentWaitOutcome::AwaitingConfirmation
565 }
566 Some(Ok(Ok(crate::types::AgentRunState::Error(error)))) => {
567 SubagentWaitOutcome::Error(error.clone())
568 }
569 Some(Ok(Ok(_))) => SubagentWaitOutcome::Error(crate::types::AgentError::new(
573 "subagent returned an unrecognized run state".to_string(),
574 false,
575 )),
576 Some(Ok(Err(_))) => SubagentWaitOutcome::Disconnected,
577 None | Some(Err(_)) => SubagentWaitOutcome::TimedOut,
578 }
579}
580
581fn apply_subagent_wait_outcome(
582 outcome: SubagentWaitOutcome,
583 config: &SubagentConfig,
584 timeout_cancel: &CancellationToken,
585 task_handle: &tokio::task::JoinHandle<()>,
586 state: &mut SubagentExecutionState,
587) -> bool {
588 let (response, details) = match outcome {
591 SubagentWaitOutcome::ReplayEvents => return true,
592 SubagentWaitOutcome::TimedOut => (
593 "Subagent timed out".to_string(),
594 format!(
595 "Subagent '{}' timed out after {}ms",
596 config.name,
597 config.timeout_ms.unwrap_or(0)
598 ),
599 ),
600 SubagentWaitOutcome::Disconnected => (
601 "Subagent ended unexpectedly".to_string(),
602 format!(
603 "Subagent '{}' ended before returning a final state",
604 config.name
605 ),
606 ),
607 SubagentWaitOutcome::Cancelled => (
608 "Subagent cancelled".to_string(),
609 format!("Subagent '{}' was cancelled", config.name),
610 ),
611 SubagentWaitOutcome::AwaitingConfirmation => (
612 "Subagent requires confirmation".to_string(),
613 format!(
614 "Subagent '{}' requested confirmation, which is not supported in nested runs",
615 config.name
616 ),
617 ),
618 SubagentWaitOutcome::Error(error) => (error.message.clone(), error.message),
619 };
620
621 timeout_cancel.cancel();
623 task_handle.abort();
624 state.fail(response, details);
625 false
626}
627
628async fn replay_subagent_events<Ctx: Send + Sync + 'static>(
629 event_store: &Arc<dyn EventStore>,
630 thread_id: &ThreadId,
631 parent_ctx: &ToolContext<Ctx>,
632 config: &SubagentConfig,
633 subagent_id: &str,
634 state: &mut SubagentExecutionState,
635) -> Result<()> {
636 for envelope in event_store.get_events(thread_id).await? {
637 match envelope.event {
638 AgentEvent::Text { message_id, text } => {
639 if state.final_response_message_id.as_deref() != Some(message_id.as_str()) {
645 state.final_response.clear();
646 state.final_response_message_id = Some(message_id);
647 }
648 state.final_response.push_str(&text);
649 }
650 AgentEvent::ToolCallStart {
651 id, name, input, ..
652 } => {
653 state.tool_count += 1;
654 let context = extract_tool_context(&name, &input);
655 state
656 .pending_tools
657 .insert(id, (name.clone(), context.clone()));
658
659 emit_subagent_progress_if_possible(
660 parent_ctx,
661 config,
662 SubagentProgressUpdate {
663 subagent_id,
664 total_turns: state.total_turns,
665 total_usage: &state.total_usage,
666 tool_name: name,
667 tool_context: context,
668 completed: false,
669 success: false,
670 tool_count: state.tool_count,
671 },
672 )
673 .await;
674 }
675 AgentEvent::ToolCallEnd {
676 id,
677 name,
678 display_name,
679 result,
680 } => {
681 let context = state
682 .pending_tools
683 .remove(&id)
684 .map(|(_, ctx)| ctx)
685 .unwrap_or_default();
686 let tool_success = result.success;
687 state.tool_logs.push(ToolCallLog {
688 name: name.clone(),
689 display_name: display_name.clone(),
690 context: context.clone(),
691 result: summarize_tool_result(&name, &result),
692 success: tool_success,
693 duration_ms: result.duration_ms,
694 });
695
696 emit_subagent_progress_if_possible(
697 parent_ctx,
698 config,
699 SubagentProgressUpdate {
700 subagent_id,
701 total_turns: state.total_turns,
702 total_usage: &state.total_usage,
703 tool_name: name,
704 tool_context: context,
705 completed: true,
706 success: tool_success,
707 tool_count: state.tool_count,
708 },
709 )
710 .await;
711 }
712 AgentEvent::TurnComplete { turn, usage, .. } => {
713 state.total_turns = turn;
714 state.total_usage.add(&usage);
715 }
716 AgentEvent::Done {
717 total_turns: turns, ..
718 } => {
719 state.total_turns = turns;
720 break;
721 }
722 AgentEvent::Refusal { text, .. } => {
723 let refusal_message =
724 text.unwrap_or_else(|| "Subagent refused the request".to_string());
725 state.error_details = Some(refusal_message.clone());
726 state.final_response = refusal_message;
727 state.success = false;
728 break;
729 }
730 AgentEvent::Error { message, .. } => {
731 state.error_details = Some(message.clone());
732 state.final_response = message;
733 state.success = false;
734 break;
735 }
736 _ => {}
737 }
738 }
739 Ok(())
740}
741
742async fn emit_subagent_progress_if_possible<Ctx: Send + Sync + 'static>(
743 parent_ctx: &ToolContext<Ctx>,
744 config: &SubagentConfig,
745 update: SubagentProgressUpdate<'_>,
746) {
747 if let Err(error) = emit_subagent_progress(parent_ctx, config, update).await {
748 log::warn!("Failed to emit subagent progress event: {error}");
749 }
750}
751
752async fn emit_subagent_progress<Ctx: Send + Sync + 'static>(
753 parent_ctx: &ToolContext<Ctx>,
754 config: &SubagentConfig,
755 SubagentProgressUpdate {
756 subagent_id,
757 total_turns,
758 total_usage,
759 tool_name,
760 tool_context,
761 completed,
762 success,
763 tool_count,
764 }: SubagentProgressUpdate<'_>,
765) -> Result<()> {
766 let max_turns = config.max_turns.map(usize_to_u32_saturating);
767 let current_turn = Some(usize_to_u32_saturating(total_turns));
768
769 parent_ctx
770 .emit_event(AgentEvent::SubagentProgress {
771 subagent_id: subagent_id.to_string(),
772 subagent_name: config.name.clone(),
773 nickname: config.nickname.clone(),
774 child_thread_id: None,
775 child_root_task_id: None,
776 subagent_task_id: None,
777 max_turns,
778 current_turn,
779 model: config.model.clone(),
780 tool_name,
781 tool_context,
782 completed,
783 success,
784 tool_count,
785 total_tokens: subagent_total_tokens(total_usage),
786 input_tokens: u64::from(total_usage.input_tokens),
787 output_tokens: u64::from(total_usage.output_tokens),
788 cache_read_input_tokens: u64::from(total_usage.cached_input_tokens),
789 cache_creation_input_tokens: u64::from(total_usage.cache_creation_input_tokens),
790 })
791 .await
792}
793
794fn usize_to_u32_saturating(value: usize) -> u32 {
795 u32::try_from(value).unwrap_or(u32::MAX)
796}
797
798#[cfg(feature = "otel")]
799fn emit_subagent_observability<P, H, M, S>(tool: &SubagentTool<P, H, M, S>, result: &SubagentResult)
800where
801 P: LlmProvider + Clone + 'static,
802 H: AgentHooks + Clone + 'static,
803 M: MessageStore + 'static,
804 S: StateStore + 'static,
805{
806 use crate::observability::{attrs, baggage, langfuse, metrics, provider_name, spans};
807 use opentelemetry::Context;
808 use opentelemetry::KeyValue;
809 use opentelemetry::trace::{Span, TraceContextExt};
810
811 let parent_ctx = Context::current();
817 let parent_span_context = parent_ctx.span().span_context().clone();
818
819 let normalized_provider_name = provider_name::normalize(tool.provider.provider());
820 let request_model = tool.provider.model().to_string();
821 let agent_name = tool.config.name.clone();
822
823 let mut span = spans::start_internal_span(
824 "invoke_agent",
825 vec![
826 KeyValue::new(attrs::GEN_AI_OPERATION_NAME, "invoke_agent"),
827 KeyValue::new(attrs::GEN_AI_AGENT_NAME, agent_name.clone()),
828 KeyValue::new(attrs::GEN_AI_PROVIDER_NAME, normalized_provider_name),
829 KeyValue::new(attrs::GEN_AI_REQUEST_MODEL, request_model.clone()),
830 KeyValue::new(attrs::SDK_RUN_MODE, "loop"),
831 ],
832 );
833 baggage::copy_baggage_to_active_span(&mut span);
834 langfuse::tag_observation(&mut span, langfuse::ObservationType::Agent);
835 if parent_span_context.is_valid() {
836 spans::link_to_parent_turn(
837 &mut span,
838 &parent_span_context.trace_id().to_string(),
839 &parent_span_context.span_id().to_string(),
840 );
841 }
842 let outcome = if result.success { "done" } else { "error" };
843 span.set_attribute(KeyValue::new(attrs::SDK_OUTCOME, outcome));
844 span.set_attribute(attrs::kv_i64(
845 attrs::SDK_TOTAL_TURNS,
846 i64::try_from(result.total_turns).unwrap_or(0),
847 ));
848 span.set_attribute(attrs::kv_i64(
849 attrs::GEN_AI_USAGE_INPUT_TOKENS,
850 i64::from(result.usage.input_tokens),
851 ));
852 span.set_attribute(attrs::kv_i64(
853 attrs::GEN_AI_USAGE_OUTPUT_TOKENS,
854 i64::from(result.usage.output_tokens),
855 ));
856 if outcome == "error" {
857 spans::set_span_error(&mut span, "agent_error", "subagent invocation failed");
858 }
859 span.end();
860
861 let metrics_handle = metrics::Metrics::global();
870 metrics_handle.subagent_invocations.add(
871 1,
872 &[
873 KeyValue::new(attrs::GEN_AI_AGENT_NAME, agent_name),
874 KeyValue::new(attrs::SDK_OUTCOME, outcome),
875 ],
876 );
877 record_subagent_token_usage(
878 &metrics_handle,
879 result,
880 normalized_provider_name,
881 &request_model,
882 );
883}
884
885#[cfg(feature = "otel")]
886fn record_subagent_token_usage(
887 metrics: &crate::observability::metrics::Metrics,
888 result: &SubagentResult,
889 provider_name: &'static str,
890 request_model: &str,
891) {
892 use crate::observability::attrs;
893 use opentelemetry::KeyValue;
894
895 let entries: [(u32, &'static str); 2] = [
896 (result.usage.input_tokens, "input"),
897 (result.usage.output_tokens, "output"),
898 ];
899
900 for (count, token_type) in entries {
901 if count == 0 {
902 continue;
903 }
904 metrics.token_usage.record(
905 u64::from(count),
906 &[
907 KeyValue::new(attrs::GEN_AI_OPERATION_NAME, "invoke_agent"),
908 KeyValue::new(attrs::GEN_AI_PROVIDER_NAME, provider_name),
909 KeyValue::new("gen_ai.token.type", token_type),
910 KeyValue::new(attrs::GEN_AI_REQUEST_MODEL, request_model.to_string()),
911 ],
912 );
913 }
914}
915
916#[cfg(not(feature = "otel"))]
917const fn emit_subagent_observability<P, H, M, S>(
918 _tool: &SubagentTool<P, H, M, S>,
919 _result: &SubagentResult,
920) where
921 P: LlmProvider + Clone + 'static,
922 H: AgentHooks + Clone + 'static,
923 M: MessageStore + 'static,
924 S: StateStore + 'static,
925{
926}
927
928fn extract_tool_context(name: &str, input: &Value) -> String {
930 match name {
931 "read" => input
932 .get("file_path")
933 .or_else(|| input.get("path"))
934 .and_then(Value::as_str)
935 .unwrap_or("")
936 .to_string(),
937 "write" | "edit" => input
938 .get("file_path")
939 .or_else(|| input.get("path"))
940 .and_then(Value::as_str)
941 .unwrap_or("")
942 .to_string(),
943 "bash" => {
944 let cmd = input.get("command").and_then(Value::as_str).unwrap_or("");
945 if cmd.len() > 60 {
947 format!("{}...", crate::primitive_tools::truncate_str(cmd, 57))
948 } else {
949 cmd.to_string()
950 }
951 }
952 "glob" | "grep" => input
953 .get("pattern")
954 .and_then(Value::as_str)
955 .unwrap_or("")
956 .to_string(),
957 "web_search" => input
958 .get("query")
959 .and_then(Value::as_str)
960 .unwrap_or("")
961 .to_string(),
962 _ => String::new(),
963 }
964}
965
966fn summarize_tool_result(name: &str, result: &ToolResult) -> String {
968 if !result.success {
969 let first_line = result.output.lines().next().unwrap_or("Error");
970 return if first_line.len() > 50 {
971 format!(
972 "{}...",
973 crate::primitive_tools::truncate_str(first_line, 47)
974 )
975 } else {
976 first_line.to_string()
977 };
978 }
979
980 match name {
981 "read" => {
982 let line_count = result.output.lines().count();
983 format!("{line_count} lines")
984 }
985 "write" => "wrote file".to_string(),
986 "edit" => "edited".to_string(),
987 "bash" => {
988 let lines: Vec<&str> = result.output.lines().collect();
989 if lines.is_empty() {
990 "done".to_string()
991 } else if lines.len() == 1 {
992 let line = lines[0];
993 if line.len() > 50 {
994 format!("{}...", crate::primitive_tools::truncate_str(line, 47))
995 } else {
996 line.to_string()
997 }
998 } else {
999 format!("{} lines", lines.len())
1000 }
1001 }
1002 "glob" => {
1003 let count = result.output.lines().count();
1004 format!("{count} files")
1005 }
1006 "grep" => {
1007 let count = result.output.lines().count();
1008 format!("{count} matches")
1009 }
1010 _ => {
1011 let line_count = result.output.lines().count();
1012 if line_count == 0 {
1013 "done".to_string()
1014 } else {
1015 format!("{line_count} lines")
1016 }
1017 }
1018 }
1019}
1020
1021impl<P, H, M, S, Ctx> Tool<Ctx> for SubagentTool<P, H, M, S>
1022where
1023 P: LlmProvider + Clone + 'static,
1024 H: AgentHooks + Clone + 'static,
1025 M: MessageStore + 'static,
1026 S: StateStore + 'static,
1027 Ctx: Send + Sync + 'static,
1028{
1029 type Name = DynamicToolName;
1030
1031 fn name(&self) -> DynamicToolName {
1032 DynamicToolName::new(format!("subagent_{}", self.config.name))
1033 }
1034
1035 fn display_name(&self) -> &'static str {
1036 self.cached_display_name
1037 }
1038
1039 fn description(&self) -> &'static str {
1040 self.cached_description
1041 }
1042
1043 fn input_schema(&self) -> Value {
1044 json!({
1045 "type": "object",
1046 "properties": {
1047 "task": {
1048 "type": "string",
1049 "description": "The task or question for the subagent to handle"
1050 }
1051 },
1052 "required": ["task"]
1053 })
1054 }
1055
1056 fn tier(&self) -> ToolTier {
1057 ToolTier::Confirm
1059 }
1060
1061 async fn execute(&self, ctx: &ToolContext<Ctx>, input: Value) -> Result<ToolResult> {
1062 let task = input
1063 .get("task")
1064 .and_then(Value::as_str)
1065 .context("Missing 'task' parameter")?;
1066
1067 let current_depth = ctx
1069 .metadata
1070 .get(METADATA_SUBAGENT_DEPTH)
1071 .and_then(Value::as_u64)
1072 .unwrap_or(0);
1073 let max_depth = ctx
1074 .metadata
1075 .get(METADATA_MAX_SUBAGENT_DEPTH)
1076 .and_then(Value::as_u64)
1077 .unwrap_or(3); if current_depth >= max_depth {
1080 bail!(
1081 "Subagent depth limit exceeded ({current_depth}/{max_depth}). \
1082 Cannot spawn nested subagent '{}' — maximum nesting depth reached.",
1083 self.config.name
1084 );
1085 }
1086
1087 let _permit = if let Some(ref sem) = ctx.subagent_semaphore() {
1089 match sem.clone().try_acquire_owned() {
1090 Ok(permit) => Some(permit),
1091 Err(_) => {
1092 return Ok(ToolResult {
1093 success: false,
1094 output: format!(
1095 "Cannot spawn subagent '{}': maximum concurrent subagent limit reached. \
1096 Try again when another subagent completes.",
1097 self.config.name
1098 ),
1099 data: None,
1100 documents: Vec::new(),
1101 duration_ms: Some(0),
1102 });
1103 }
1104 }
1105 } else {
1106 None
1107 };
1108
1109 let subagent_id = format!(
1111 "{}_{:x}",
1112 self.config.name,
1113 std::time::SystemTime::now()
1114 .duration_since(std::time::UNIX_EPOCH)
1115 .unwrap_or_default()
1116 .as_nanos()
1117 );
1118
1119 let cancel_token = ctx.cancel_token().unwrap_or_default();
1122
1123 let result = self
1124 .run_subagent(task, subagent_id, ctx, cancel_token)
1125 .await?;
1126
1127 Ok(ToolResult {
1128 success: result.success,
1129 output: result.final_response.clone(),
1130 data: Some(serde_json::to_value(&result).unwrap_or_default()),
1131 documents: Vec::new(),
1132 duration_ms: Some(result.duration_ms),
1133 })
1134 }
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139 use super::*;
1140 use crate::authority::{EventAuthority, LocalEventAuthority};
1141 use crate::events::{AgentEvent, AgentEventEnvelope};
1142 use crate::llm::{ChatOutcome, ChatRequest, ChatResponse, ContentBlock, StopReason, Usage};
1143 use crate::stores::{EventStore, InMemoryEventStore, StoredTurnEvents};
1144 use anyhow::{Context, Result, bail};
1145 use async_trait::async_trait;
1146 use tokio::sync::Mutex;
1147
1148 #[derive(Clone)]
1149 struct TestProvider {
1150 responses: Arc<Mutex<Vec<ChatOutcome>>>,
1151 delay: Option<Duration>,
1152 }
1153
1154 impl TestProvider {
1155 fn new(responses: Vec<ChatOutcome>) -> Self {
1156 Self {
1157 responses: Arc::new(Mutex::new(responses)),
1158 delay: None,
1159 }
1160 }
1161
1162 fn with_delay(mut self, delay: Duration) -> Self {
1163 self.delay = Some(delay);
1164 self
1165 }
1166
1167 fn text_response(text: &str) -> ChatOutcome {
1168 ChatOutcome::Success(ChatResponse {
1169 id: "resp_text".to_string(),
1170 content: vec![ContentBlock::Text {
1171 text: text.to_string(),
1172 }],
1173 model: "test-model".to_string(),
1174 stop_reason: Some(StopReason::EndTurn),
1175 usage: Usage {
1176 served_speed: None,
1177 input_tokens: 10,
1178 output_tokens: 20,
1179 cached_input_tokens: 0,
1180 cache_creation_input_tokens: 0,
1181 },
1182 })
1183 }
1184
1185 fn tool_use_response(tool_id: &str, tool_name: &str, input: Value) -> ChatOutcome {
1186 ChatOutcome::Success(ChatResponse {
1187 id: "resp_tool".to_string(),
1188 content: vec![ContentBlock::ToolUse {
1189 id: tool_id.to_string(),
1190 name: tool_name.to_string(),
1191 input,
1192 thought_signature: None,
1193 }],
1194 model: "test-model".to_string(),
1195 stop_reason: Some(StopReason::ToolUse),
1196 usage: Usage {
1197 served_speed: None,
1198 input_tokens: 15,
1199 output_tokens: 25,
1200 cached_input_tokens: 0,
1201 cache_creation_input_tokens: 0,
1202 },
1203 })
1204 }
1205
1206 fn refusal_response(text: Option<&str>) -> ChatOutcome {
1207 let content = text.map_or_else(Vec::new, |text| {
1208 vec![ContentBlock::Text {
1209 text: text.to_string(),
1210 }]
1211 });
1212 ChatOutcome::Success(ChatResponse {
1213 id: "resp_refusal".to_string(),
1214 content,
1215 model: "test-model".to_string(),
1216 stop_reason: Some(StopReason::Refusal),
1217 usage: Usage {
1218 served_speed: None,
1219 input_tokens: 12,
1220 output_tokens: 0,
1221 cached_input_tokens: 0,
1222 cache_creation_input_tokens: 0,
1223 },
1224 })
1225 }
1226 }
1227
1228 #[async_trait]
1229 impl LlmProvider for TestProvider {
1230 async fn chat(&self, _request: ChatRequest) -> Result<ChatOutcome> {
1231 if let Some(delay) = self.delay {
1232 tokio::time::sleep(delay).await;
1233 }
1234
1235 let mut responses = self.responses.lock().await;
1236 if responses.is_empty() {
1237 Ok(Self::text_response("default"))
1238 } else {
1239 Ok(responses.remove(0))
1240 }
1241 }
1242
1243 fn model(&self) -> &'static str {
1244 "test-model"
1245 }
1246
1247 fn provider(&self) -> &'static str {
1248 "mock"
1249 }
1250 }
1251
1252 struct TestEchoTool;
1253
1254 impl Tool<()> for TestEchoTool {
1255 type Name = DynamicToolName;
1256
1257 fn name(&self) -> DynamicToolName {
1258 DynamicToolName::new("echo")
1259 }
1260
1261 fn display_name(&self) -> &'static str {
1262 "Echo"
1263 }
1264
1265 fn description(&self) -> &'static str {
1266 "Echo the input"
1267 }
1268
1269 fn input_schema(&self) -> Value {
1270 json!({
1271 "type": "object",
1272 "properties": {
1273 "message": { "type": "string" }
1274 },
1275 "required": ["message"]
1276 })
1277 }
1278
1279 fn tier(&self) -> ToolTier {
1280 ToolTier::Observe
1281 }
1282
1283 async fn execute(&self, _ctx: &ToolContext<()>, input: Value) -> Result<ToolResult> {
1284 let message = input
1285 .get("message")
1286 .and_then(Value::as_str)
1287 .context("missing echo message")?;
1288 Ok(ToolResult::success(format!("Echo: {message}")))
1289 }
1290 }
1291
1292 #[derive(Clone, Default)]
1293 struct RecordingEventStore {
1294 inner: Arc<InMemoryEventStore>,
1295 appended: Arc<Mutex<Vec<(ThreadId, usize, AgentEventEnvelope)>>>,
1296 }
1297
1298 impl RecordingEventStore {
1299 async fn appended_events(&self) -> Vec<(ThreadId, usize, AgentEventEnvelope)> {
1300 self.appended.lock().await.clone()
1301 }
1302 }
1303
1304 #[async_trait]
1305 impl EventStore for RecordingEventStore {
1306 async fn append(
1307 &self,
1308 thread_id: &ThreadId,
1309 turn: usize,
1310 envelope: AgentEventEnvelope,
1311 ) -> Result<()> {
1312 self.appended
1313 .lock()
1314 .await
1315 .push((thread_id.clone(), turn, envelope.clone()));
1316 self.inner.append(thread_id, turn, envelope).await
1317 }
1318
1319 async fn finish_turn(&self, thread_id: &ThreadId, turn: usize) -> Result<()> {
1320 self.inner.finish_turn(thread_id, turn).await
1321 }
1322
1323 async fn get_turn(
1324 &self,
1325 thread_id: &ThreadId,
1326 turn: usize,
1327 ) -> Result<Option<StoredTurnEvents>> {
1328 self.inner.get_turn(thread_id, turn).await
1329 }
1330
1331 async fn get_turns(&self, thread_id: &ThreadId) -> Result<Vec<StoredTurnEvents>> {
1332 self.inner.get_turns(thread_id).await
1333 }
1334
1335 async fn clear(&self, thread_id: &ThreadId) -> Result<()> {
1336 self.inner.clear(thread_id).await
1337 }
1338 }
1339
1340 #[derive(Clone, Default)]
1341 struct AlwaysFailAppendEventStore;
1342
1343 #[async_trait]
1344 impl EventStore for AlwaysFailAppendEventStore {
1345 async fn append(
1346 &self,
1347 _thread_id: &ThreadId,
1348 _turn: usize,
1349 _envelope: AgentEventEnvelope,
1350 ) -> Result<()> {
1351 bail!("append failed")
1352 }
1353
1354 async fn finish_turn(&self, _thread_id: &ThreadId, _turn: usize) -> Result<()> {
1355 Ok(())
1356 }
1357
1358 async fn get_turn(
1359 &self,
1360 _thread_id: &ThreadId,
1361 _turn: usize,
1362 ) -> Result<Option<StoredTurnEvents>> {
1363 Ok(None)
1364 }
1365
1366 async fn get_turns(&self, _thread_id: &ThreadId) -> Result<Vec<StoredTurnEvents>> {
1367 Ok(Vec::new())
1368 }
1369
1370 async fn clear(&self, _thread_id: &ThreadId) -> Result<()> {
1371 Ok(())
1372 }
1373 }
1374
1375 #[derive(Clone, Default)]
1376 struct NoReadAfterFailureEventStore {
1377 inner: Arc<InMemoryEventStore>,
1378 }
1379
1380 #[async_trait]
1381 impl EventStore for NoReadAfterFailureEventStore {
1382 async fn append(
1383 &self,
1384 thread_id: &ThreadId,
1385 turn: usize,
1386 envelope: AgentEventEnvelope,
1387 ) -> Result<()> {
1388 self.inner.append(thread_id, turn, envelope).await
1389 }
1390
1391 async fn finish_turn(&self, thread_id: &ThreadId, turn: usize) -> Result<()> {
1392 self.inner.finish_turn(thread_id, turn).await
1393 }
1394
1395 async fn get_turn(
1396 &self,
1397 thread_id: &ThreadId,
1398 turn: usize,
1399 ) -> Result<Option<StoredTurnEvents>> {
1400 self.inner.get_turn(thread_id, turn).await
1401 }
1402
1403 async fn get_turns(&self, _thread_id: &ThreadId) -> Result<Vec<StoredTurnEvents>> {
1404 bail!("get_events should not be called after subagent failure")
1405 }
1406
1407 async fn clear(&self, thread_id: &ThreadId) -> Result<()> {
1408 self.inner.clear(thread_id).await
1409 }
1410 }
1411
1412 #[derive(Clone, Default)]
1413 struct PanicProvider;
1414
1415 #[async_trait]
1416 impl LlmProvider for PanicProvider {
1417 async fn chat(&self, _request: ChatRequest) -> Result<ChatOutcome> {
1418 panic!("panic provider should disconnect subagent");
1424 }
1425
1426 fn model(&self) -> &'static str {
1427 "panic-model"
1428 }
1429
1430 fn provider(&self) -> &'static str {
1431 "panic"
1432 }
1433 }
1434
1435 #[test]
1436 fn test_subagent_config_builder() {
1437 let config = SubagentConfig::new("test")
1438 .with_system_prompt("Test prompt")
1439 .with_max_turns(5)
1440 .with_timeout_ms(30000);
1441
1442 assert_eq!(config.name, "test");
1443 assert_eq!(config.system_prompt, "Test prompt");
1444 assert_eq!(config.max_turns, Some(5));
1445 assert_eq!(config.timeout_ms, Some(30000));
1446 }
1447
1448 #[test]
1449 fn test_subagent_config_defaults() {
1450 let config = SubagentConfig::new("default");
1451
1452 assert_eq!(config.name, "default");
1453 assert!(config.system_prompt.is_empty());
1454 assert_eq!(config.max_turns, None);
1455 assert_eq!(config.timeout_ms, None);
1456 }
1457
1458 #[test]
1459 fn test_subagent_result_serialization() -> Result<()> {
1460 let result = SubagentResult {
1461 name: "test".to_string(),
1462 final_response: "Done".to_string(),
1463 total_turns: 3,
1464 tool_count: 5,
1465 tool_logs: vec![
1466 ToolCallLog {
1467 name: "read".to_string(),
1468 display_name: "Read file".to_string(),
1469 context: "/tmp/test.rs".to_string(),
1470 result: "50 lines".to_string(),
1471 success: true,
1472 duration_ms: Some(10),
1473 },
1474 ToolCallLog {
1475 name: "grep".to_string(),
1476 display_name: "Grep TODO".to_string(),
1477 context: "TODO".to_string(),
1478 result: "3 matches".to_string(),
1479 success: true,
1480 duration_ms: Some(5),
1481 },
1482 ],
1483 usage: TokenUsage::default(),
1484 success: true,
1485 duration_ms: 1000,
1486 error_details: None,
1487 failed_tool: None,
1488 };
1489
1490 let json = serde_json::to_string(&result).context("failed to serialize subagent result")?;
1491 assert!(json.contains("test"));
1492 assert!(json.contains("Done"));
1493 assert!(json.contains("tool_count"));
1494 assert!(json.contains("tool_logs"));
1495 assert!(json.contains("/tmp/test.rs"));
1496
1497 Ok(())
1498 }
1499
1500 #[test]
1501 fn test_subagent_result_field_extraction() -> Result<()> {
1502 let result = SubagentResult {
1503 name: "explore".to_string(),
1504 final_response: "Found 3 config files".to_string(),
1505 total_turns: 2,
1506 tool_count: 5,
1507 tool_logs: vec![ToolCallLog {
1508 name: "glob".to_string(),
1509 display_name: "Glob config files".to_string(),
1510 context: "**/*.toml".to_string(),
1511 result: "3 files".to_string(),
1512 success: true,
1513 duration_ms: Some(15),
1514 }],
1515 usage: TokenUsage {
1516 input_tokens: 1500,
1517 output_tokens: 500,
1518 ..Default::default()
1519 },
1520 success: true,
1521 duration_ms: 2500,
1522 error_details: None,
1523 failed_tool: None,
1524 };
1525
1526 let value =
1527 serde_json::to_value(&result).context("failed to convert subagent result to json")?;
1528
1529 let tool_count = value.get("tool_count").and_then(Value::as_u64);
1530 assert_eq!(tool_count, Some(5));
1531
1532 let usage = value.get("usage").context("missing usage field")?;
1533 let input_tokens = usage.get("input_tokens").and_then(Value::as_u64);
1534 let output_tokens = usage.get("output_tokens").and_then(Value::as_u64);
1535 assert_eq!(input_tokens, Some(1500));
1536 assert_eq!(output_tokens, Some(500));
1537
1538 let logs = value
1539 .get("tool_logs")
1540 .and_then(Value::as_array)
1541 .context("missing tool_logs array")?;
1542 assert_eq!(logs.len(), 1);
1543
1544 let first_log = &logs[0];
1545 assert_eq!(first_log.get("name").and_then(Value::as_str), Some("glob"));
1546 assert_eq!(
1547 first_log.get("context").and_then(Value::as_str),
1548 Some("**/*.toml")
1549 );
1550 assert_eq!(
1551 first_log.get("result").and_then(Value::as_str),
1552 Some("3 files")
1553 );
1554 assert_eq!(
1555 first_log.get("success").and_then(Value::as_bool),
1556 Some(true)
1557 );
1558
1559 Ok(())
1560 }
1561
1562 #[tokio::test]
1563 async fn test_run_subagent_uses_isolated_child_thread() -> Result<()> {
1564 let event_store = Arc::new(RecordingEventStore::default());
1565 let provider = Arc::new(TestProvider::new(vec![
1566 TestProvider::tool_use_response("tool_1", "echo", json!({ "message": "child" })),
1567 TestProvider::text_response("Subagent complete"),
1568 ]));
1569 let mut tools = ToolRegistry::new();
1570 tools.register(TestEchoTool);
1571
1572 let tool = SubagentTool::new(SubagentConfig::new("worker"), provider, Arc::new(tools), {
1573 let store = Arc::clone(&event_store);
1574 move || -> Arc<dyn EventStore> { store.clone() }
1575 });
1576 let parent_thread = ThreadId::new();
1577 let parent_ctx = ToolContext::new(()).with_event_store(
1578 event_store.clone(),
1579 parent_thread.clone(),
1580 1,
1581 Arc::new(LocalEventAuthority::new()),
1582 );
1583
1584 let result = tool
1585 .run_subagent(
1586 "Inspect the repo",
1587 "subagent_1".to_string(),
1588 &parent_ctx,
1589 CancellationToken::new(),
1590 )
1591 .await?;
1592
1593 assert!(result.success);
1594 assert_eq!(result.tool_count, 1);
1595 assert_eq!(result.tool_logs.len(), 1);
1596
1597 let parent_turn = event_store
1598 .get_turn(&parent_thread, 1)
1599 .await?
1600 .context("missing parent turn")?;
1601 assert!(!parent_turn.events.is_empty());
1602 assert!(
1603 parent_turn
1604 .events
1605 .iter()
1606 .all(|envelope| { matches!(envelope.event, AgentEvent::SubagentProgress { .. }) })
1607 );
1608
1609 let appended = event_store.appended_events().await;
1610 let child_thread = appended
1611 .iter()
1612 .map(|(thread_id, _, _)| thread_id.clone())
1613 .find(|thread_id| thread_id != &parent_thread)
1614 .context("missing child thread events")?;
1615 let child_turn = event_store
1616 .get_turn(&child_thread, 1)
1617 .await?
1618 .context("missing child turn")?;
1619 let child_events = event_store.get_events(&child_thread).await?;
1620
1621 assert!(
1622 child_turn
1623 .events
1624 .iter()
1625 .any(|envelope| { matches!(envelope.event, AgentEvent::ToolCallStart { .. }) })
1626 );
1627 assert!(
1628 child_events
1629 .iter()
1630 .any(|envelope| { matches!(envelope.event, AgentEvent::Done { .. }) })
1631 );
1632
1633 Ok(())
1634 }
1635
1636 #[tokio::test]
1637 async fn test_run_subagent_timeout_marks_result_as_failed() -> Result<()> {
1638 let event_store = Arc::new(NoReadAfterFailureEventStore::default());
1639 let provider = Arc::new(
1640 TestProvider::new(vec![TestProvider::text_response("Too late")])
1641 .with_delay(Duration::from_millis(50)),
1642 );
1643 let tool = SubagentTool::new(
1644 SubagentConfig::new("worker").with_timeout_ms(10),
1645 provider,
1646 Arc::new(ToolRegistry::<()>::new()),
1647 {
1648 let store = Arc::clone(&event_store);
1649 move || -> Arc<dyn EventStore> { store.clone() }
1650 },
1651 );
1652
1653 let result = tool
1654 .run_subagent(
1655 "Take too long",
1656 "subagent_timeout".to_string(),
1657 &ToolContext::new(()),
1658 CancellationToken::new(),
1659 )
1660 .await?;
1661
1662 assert!(!result.success);
1663 assert_eq!(result.final_response, "Subagent timed out");
1664 assert!(
1665 result
1666 .error_details
1667 .context("missing timeout details")?
1668 .contains("timed out")
1669 );
1670
1671 Ok(())
1672 }
1673
1674 #[tokio::test]
1675 async fn test_run_subagent_progress_failures_do_not_abort_successful_runs() -> Result<()> {
1676 let provider = Arc::new(TestProvider::new(vec![
1677 TestProvider::tool_use_response("tool_1", "echo", json!({ "message": "child" })),
1678 TestProvider::text_response("Subagent complete"),
1679 ]));
1680 let mut tools = ToolRegistry::new();
1681 tools.register(TestEchoTool);
1682
1683 let tool = SubagentTool::new(SubagentConfig::new("worker"), provider, Arc::new(tools), {
1684 move || -> Arc<dyn EventStore> { Arc::new(InMemoryEventStore::new()) }
1685 });
1686 let parent_ctx = ToolContext::new(()).with_event_store(
1687 Arc::new(AlwaysFailAppendEventStore),
1688 ThreadId::new(),
1689 1,
1690 Arc::new(LocalEventAuthority::new()),
1691 );
1692
1693 let result = tool
1694 .run_subagent(
1695 "Inspect the repo",
1696 "subagent_progress".to_string(),
1697 &parent_ctx,
1698 CancellationToken::new(),
1699 )
1700 .await?;
1701
1702 assert!(result.success);
1703 assert_eq!(result.final_response, "Subagent complete");
1704 assert_eq!(result.tool_count, 1);
1705
1706 Ok(())
1707 }
1708
1709 #[tokio::test]
1710 async fn test_run_subagent_panic_classified_as_error_not_disconnected() -> Result<()> {
1711 let tool = SubagentTool::new(
1720 SubagentConfig::new("worker"),
1721 Arc::new(PanicProvider),
1722 Arc::new(ToolRegistry::<()>::new()),
1723 move || -> Arc<dyn EventStore> { Arc::new(InMemoryEventStore::new()) },
1724 );
1725
1726 let result = tool
1727 .run_subagent(
1728 "Crash",
1729 "subagent_panic".to_string(),
1730 &ToolContext::new(()),
1731 CancellationToken::new(),
1732 )
1733 .await?;
1734
1735 assert!(!result.success);
1736 assert_ne!(result.final_response, "Subagent ended unexpectedly");
1739 let details = result
1740 .error_details
1741 .context("panicking subagent must carry structured error details")?;
1742 assert!(
1743 !details.contains("ended before returning a final state"),
1744 "panic must not be classified as Disconnected; got {details:?}",
1745 );
1746 assert!(
1747 details.contains("panicked"),
1748 "structured error should reflect the panic; got {details:?}",
1749 );
1750 assert!(
1751 details.contains("panic provider should disconnect subagent"),
1752 "structured error should carry the original panic message; got {details:?}",
1753 );
1754
1755 Ok(())
1756 }
1757
1758 #[tokio::test]
1759 async fn test_run_subagent_refusal_marks_result_as_failed() -> Result<()> {
1760 let tool = SubagentTool::new(
1761 SubagentConfig::new("worker"),
1762 Arc::new(TestProvider::new(vec![TestProvider::refusal_response(
1763 Some("Refused for policy reasons"),
1764 )])),
1765 Arc::new(ToolRegistry::<()>::new()),
1766 || Arc::new(InMemoryEventStore::new()),
1767 );
1768
1769 let result = tool
1770 .run_subagent(
1771 "Refuse",
1772 "subagent_refusal".to_string(),
1773 &ToolContext::new(()),
1774 CancellationToken::new(),
1775 )
1776 .await?;
1777
1778 assert!(!result.success);
1779 assert_eq!(result.final_response, "Refused for policy reasons");
1780 assert_eq!(
1781 result.error_details.as_deref(),
1782 Some("Refused for policy reasons")
1783 );
1784
1785 Ok(())
1786 }
1787
1788 #[tokio::test]
1789 async fn test_run_subagent_cancelled_marks_result_as_failed() -> Result<()> {
1790 let tool = SubagentTool::new(
1791 SubagentConfig::new("worker"),
1792 Arc::new(
1793 TestProvider::new(vec![TestProvider::text_response("Too late")])
1794 .with_delay(Duration::from_millis(50)),
1795 ),
1796 Arc::new(ToolRegistry::<()>::new()),
1797 || Arc::new(InMemoryEventStore::new()),
1798 );
1799 let cancel_token = CancellationToken::new();
1800 cancel_token.cancel();
1801
1802 let result = tool
1803 .run_subagent(
1804 "Cancel",
1805 "subagent_cancelled".to_string(),
1806 &ToolContext::new(()),
1807 cancel_token,
1808 )
1809 .await?;
1810
1811 assert!(!result.success);
1812 assert_eq!(result.final_response, "Subagent cancelled");
1813 assert!(
1814 result
1815 .error_details
1816 .context("missing cancellation details")?
1817 .contains("cancelled")
1818 );
1819
1820 Ok(())
1821 }
1822
1823 #[tokio::test]
1824 async fn test_run_subagent_llm_error_does_not_infer_failed_tool() -> Result<()> {
1825 let provider = Arc::new(TestProvider::new(vec![
1826 ChatOutcome::ServerError("llm transport failed".to_string()),
1827 ChatOutcome::ServerError("llm transport failed".to_string()),
1828 ChatOutcome::ServerError("llm transport failed".to_string()),
1829 ChatOutcome::ServerError("llm transport failed".to_string()),
1830 ChatOutcome::ServerError("llm transport failed".to_string()),
1831 ChatOutcome::ServerError("llm transport failed".to_string()),
1832 ]));
1833 let mut tools = ToolRegistry::new();
1834 tools.register(TestEchoTool);
1835
1836 let tool = SubagentTool::new(
1837 SubagentConfig::new("worker"),
1838 provider,
1839 Arc::new(tools),
1840 || Arc::new(InMemoryEventStore::new()),
1841 );
1842
1843 let result = tool
1844 .run_subagent(
1845 "Trigger an llm failure",
1846 "subagent_llm_error".to_string(),
1847 &ToolContext::new(()),
1848 CancellationToken::new(),
1849 )
1850 .await?;
1851
1852 assert!(!result.success);
1853 assert!(result.failed_tool.is_none());
1854 assert!(
1855 result
1856 .error_details
1857 .as_deref()
1858 .unwrap_or_default()
1859 .contains("Server error")
1860 );
1861
1862 Ok(())
1863 }
1864
1865 #[tokio::test]
1866 async fn test_replay_subagent_events_stops_after_error() -> Result<()> {
1867 let event_store: Arc<dyn EventStore> = Arc::new(InMemoryEventStore::new());
1868 let thread_id = ThreadId::new();
1869 let authority = LocalEventAuthority::new();
1870 event_store
1871 .append(
1872 &thread_id,
1873 1,
1874 authority.wrap(AgentEvent::error("subagent boom", false)),
1875 )
1876 .await?;
1877 event_store
1878 .append(
1879 &thread_id,
1880 1,
1881 authority.wrap(AgentEvent::Text {
1882 message_id: "msg_after_error".to_string(),
1883 text: "should not be appended".to_string(),
1884 }),
1885 )
1886 .await?;
1887
1888 let mut state = SubagentExecutionState::new();
1889 replay_subagent_events(
1890 &event_store,
1891 &thread_id,
1892 &ToolContext::new(()),
1893 &SubagentConfig::new("worker"),
1894 "subagent_error",
1895 &mut state,
1896 )
1897 .await?;
1898
1899 assert!(!state.success);
1900 assert_eq!(state.final_response, "subagent boom");
1901 assert_eq!(state.error_details.as_deref(), Some("subagent boom"));
1902
1903 Ok(())
1904 }
1905
1906 #[tokio::test]
1907 async fn test_replay_keeps_only_final_message_text() -> Result<()> {
1908 let event_store: Arc<dyn EventStore> = Arc::new(InMemoryEventStore::new());
1909 let thread_id = ThreadId::new();
1910 let authority = LocalEventAuthority::new();
1911
1912 event_store
1914 .append(
1915 &thread_id,
1916 1,
1917 authority.wrap(AgentEvent::Text {
1918 message_id: "m1".to_string(),
1919 text: "Let me check the repo...".to_string(),
1920 }),
1921 )
1922 .await?;
1923 event_store
1925 .append(
1926 &thread_id,
1927 2,
1928 authority.wrap(AgentEvent::Text {
1929 message_id: "m2".to_string(),
1930 text: "Final answer ".to_string(),
1931 }),
1932 )
1933 .await?;
1934 event_store
1935 .append(
1936 &thread_id,
1937 2,
1938 authority.wrap(AgentEvent::Text {
1939 message_id: "m2".to_string(),
1940 text: "part two".to_string(),
1941 }),
1942 )
1943 .await?;
1944 event_store
1945 .append(
1946 &thread_id,
1947 2,
1948 authority.wrap(AgentEvent::done(
1949 thread_id.clone(),
1950 2,
1951 TokenUsage::default(),
1952 Duration::from_millis(1),
1953 )),
1954 )
1955 .await?;
1956
1957 let mut state = SubagentExecutionState::new();
1958 replay_subagent_events(
1959 &event_store,
1960 &thread_id,
1961 &ToolContext::new(()),
1962 &SubagentConfig::new("worker"),
1963 "subagent_final",
1964 &mut state,
1965 )
1966 .await?;
1967
1968 assert_eq!(state.final_response, "Final answer part two");
1971
1972 Ok(())
1973 }
1974
1975 #[test]
1976 fn build_subagent_child_context_increments_depth_and_propagates_semaphore() {
1977 let semaphore = Arc::new(tokio::sync::Semaphore::new(2));
1978 let parent = ToolContext::new(())
1979 .with_metadata(METADATA_SUBAGENT_DEPTH, json!(2))
1980 .with_metadata(METADATA_MAX_SUBAGENT_DEPTH, json!(5))
1981 .with_subagent_semaphore(Arc::clone(&semaphore));
1982
1983 let child = build_subagent_child_context(&parent);
1984
1985 assert_eq!(
1986 child
1987 .metadata
1988 .get(METADATA_SUBAGENT_DEPTH)
1989 .and_then(Value::as_u64),
1990 Some(3)
1991 );
1992 assert_eq!(
1994 child
1995 .metadata
1996 .get(METADATA_MAX_SUBAGENT_DEPTH)
1997 .and_then(Value::as_u64),
1998 Some(5)
1999 );
2000 assert!(child.subagent_semaphore().is_some());
2002 }
2003
2004 #[test]
2005 fn cached_tool_strings_are_interned_per_name() {
2006 let a = cached_tool_strings("worker");
2007 let b = cached_tool_strings("worker");
2008 assert!(std::ptr::eq(a.0, b.0));
2011 assert!(std::ptr::eq(a.1, b.1));
2012 assert_eq!(a.0, "Subagent: worker");
2013
2014 let c = cached_tool_strings("a-different-name");
2015 assert!(!std::ptr::eq(a.0, c.0));
2016 }
2017
2018 #[tokio::test]
2019 async fn test_nested_subagent_depth_limit_propagates() -> Result<()> {
2020 use crate::hooks::AllowAllHooks;
2021
2022 let inner = SubagentTool::new(
2024 SubagentConfig::new("inner"),
2025 Arc::new(TestProvider::new(vec![TestProvider::text_response(
2026 "inner ran (should not happen)",
2027 )])),
2028 Arc::new(ToolRegistry::<()>::new()),
2029 || -> Arc<dyn EventStore> { Arc::new(InMemoryEventStore::new()) },
2030 );
2031 let mut middle_tools = ToolRegistry::new();
2032 middle_tools.register(inner);
2033
2034 let outer = SubagentTool::new(
2038 SubagentConfig::new("outer"),
2039 Arc::new(TestProvider::new(vec![
2040 TestProvider::tool_use_response(
2041 "call_inner",
2042 "subagent_inner",
2043 json!({ "task": "go deeper" }),
2044 ),
2045 TestProvider::text_response("outer done"),
2046 ])),
2047 Arc::new(middle_tools),
2048 || -> Arc<dyn EventStore> { Arc::new(InMemoryEventStore::new()) },
2049 )
2050 .with_hooks(Arc::new(AllowAllHooks));
2051
2052 let parent_ctx = ToolContext::new(()).with_metadata(METADATA_MAX_SUBAGENT_DEPTH, json!(1));
2055
2056 let result = outer
2057 .execute(&parent_ctx, json!({ "task": "start" }))
2058 .await?;
2059
2060 assert!(result.success, "outer subagent should still complete");
2061 assert_eq!(result.output, "outer done");
2062
2063 let subresult: SubagentResult =
2064 serde_json::from_value(result.data.context("missing subagent result data")?)
2065 .context("subagent result should deserialize")?;
2066 let nested = subresult
2067 .tool_logs
2068 .iter()
2069 .find(|log| log.name == "subagent_inner")
2070 .context("missing nested subagent tool log")?;
2071 assert!(!nested.success, "nested spawn must be rejected");
2072 assert!(
2073 nested.result.contains("depth limit"),
2074 "nested failure should be the depth-limit error; got: {}",
2075 nested.result
2076 );
2077
2078 Ok(())
2079 }
2080}