Skip to main content

agent_sdk/
subagent.rs

1//! Subagent support for spawning child agents.
2//!
3//! This module provides the ability to spawn subagents from within an agent.
4//! Subagents are isolated agent instances that run to completion and return
5//! only their final response to the parent agent.
6//!
7//! # Overview
8//!
9//! Subagents are useful for:
10//! - Delegating complex subtasks to specialized agents
11//! - Running parallel investigations
12//! - Isolating context for specific operations
13//!
14//! # Example
15//!
16//! ```ignore
17//! use agent_sdk::subagent::{SubagentTool, SubagentConfig};
18//!
19//! let config = SubagentConfig::new("researcher")
20//!     .with_system_prompt("You are a research specialist...")
21//!     .with_max_turns(10);
22//!
23//! let tool = SubagentTool::new(config, provider, tools, || {
24//!     std::sync::Arc::new(agent_sdk::InMemoryEventStore::new())
25//! });
26//! registry.register(tool);
27//! ```
28//!
29//! # Behavior
30//!
31//! When a subagent runs:
32//! 1. A new isolated thread is created
33//! 2. The subagent runs until completion or max turns
34//! 3. Only the final text response is returned to the parent
35//! 4. The parent does not see the subagent's intermediate tool calls
36
37mod 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
55/// Return the (display name, description) pair for a subagent of the given
56/// name, interning the leaked `&'static str`s so repeated construction with the
57/// same name reuses one allocation.
58///
59/// `SubagentFactory` builds a fresh `SubagentTool` per request, so leaking on
60/// every construction (the previous approach) grew memory without bound in
61/// long-running hosts. Interning bounds the leak to the number of distinct
62/// subagent names.
63fn 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
81/// Metadata key for tracking the current subagent nesting depth.
82///
83/// When a subagent spawns another subagent, the depth is incremented.
84/// Tools check this value against the configured maximum depth.
85pub const METADATA_SUBAGENT_DEPTH: &str = "subagent_depth";
86
87/// Metadata key for the maximum allowed subagent nesting depth.
88///
89/// Set by the host application (e.g. bip) to prevent unbounded recursion.
90pub const METADATA_MAX_SUBAGENT_DEPTH: &str = "max_subagent_depth";
91
92/// Configuration for a subagent.
93#[derive(Clone, Debug, Serialize, Deserialize)]
94pub struct SubagentConfig {
95    /// Name of the subagent (for identification).
96    pub name: String,
97    /// Human-friendly nickname assigned by the parent (e.g., "Zara").
98    pub nickname: Option<String>,
99    /// System prompt for the subagent.
100    pub system_prompt: String,
101    /// Maximum number of turns before stopping.
102    pub max_turns: Option<usize>,
103    /// Optional timeout in milliseconds.
104    pub timeout_ms: Option<u64>,
105    /// Optional model override for this subagent.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub model: Option<String>,
108}
109
110impl SubagentConfig {
111    /// Create a new subagent configuration.
112    #[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    /// Set the system prompt.
125    #[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    /// Set the maximum number of turns.
132    #[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    /// Set the timeout in milliseconds.
139    #[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    /// Set the model override for this subagent.
146    #[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    /// Set a human-friendly nickname for this subagent.
153    #[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/// Log entry for a single tool call within a subagent.
161#[derive(Clone, Debug, Serialize, Deserialize)]
162pub struct ToolCallLog {
163    /// Tool name.
164    pub name: String,
165    /// Tool display name.
166    pub display_name: String,
167    /// Brief context/args (e.g., file path, command).
168    pub context: String,
169    /// Brief result summary.
170    pub result: String,
171    /// Whether the tool call succeeded.
172    pub success: bool,
173    /// Duration in milliseconds.
174    pub duration_ms: Option<u64>,
175}
176
177/// Result from a subagent execution.
178#[derive(Clone, Debug, Serialize, Deserialize)]
179pub struct SubagentResult {
180    /// Name of the subagent.
181    pub name: String,
182    /// The final text response (only visible part to parent).
183    pub final_response: String,
184    /// Total number of turns taken.
185    pub total_turns: usize,
186    /// Number of tool calls made by the subagent.
187    pub tool_count: u32,
188    /// Log of tool calls made by the subagent.
189    pub tool_logs: Vec<ToolCallLog>,
190    /// Token usage statistics.
191    pub usage: TokenUsage,
192    /// Whether the subagent completed successfully.
193    pub success: bool,
194    /// Duration in milliseconds.
195    pub duration_ms: u64,
196    /// Detailed error information when `success` is false.
197    ///
198    /// Contains the raw error message from the agent event, which may include
199    /// stack trace information or structured error context.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub error_details: Option<String>,
202    /// Retained for serialization compatibility with older clients.
203    ///
204    /// The previous implementation inferred this from the "last pending tool"
205    /// when any generic error occurred, which was incorrect for LLM or
206    /// transport failures. The field is currently never populated until the
207    /// SDK has deterministic error provenance.
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub failed_tool: Option<String>,
210}
211
212/// Tool for spawning subagents.
213///
214/// This tool allows an agent to spawn a child agent that runs independently
215/// and returns only its final response.
216///
217/// # Example
218///
219/// ```ignore
220/// use agent_sdk::subagent::{SubagentTool, SubagentConfig};
221///
222/// let config = SubagentConfig::new("analyzer")
223///     .with_system_prompt("You analyze code...");
224///
225/// let tool = SubagentTool::new(config, provider.clone(), tools.clone(), || {
226///     std::sync::Arc::new(agent_sdk::InMemoryEventStore::new())
227/// });
228/// ```
229pub 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 to avoid `Box::leak` on every call.
244    cached_display_name: &'static str,
245    /// Cached description to avoid `Box::leak` on every call.
246    cached_description: &'static str,
247}
248
249impl<P> SubagentTool<P, DefaultHooks, InMemoryStore, InMemoryStore>
250where
251    P: LlmProvider + 'static,
252{
253    /// Create a new subagent tool with default hooks and in-memory message/state stores.
254    #[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        // Intern the leaked strings so repeated construction with the same
265        // name reuses one allocation (factories build a tool per request).
266        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    /// Create with custom hooks.
289    #[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    /// Create with custom store factories.
308    #[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    /// Get the subagent configuration.
334    #[must_use]
335    pub const fn config(&self) -> &SubagentConfig {
336        &self.config
337    }
338
339    /// Run the subagent with a task.
340    ///
341    /// The `parent_cancel` token links the subagent's lifecycle to its parent.
342    /// Cancelling the parent token will also cancel the subagent.
343    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        // Each subagent run gets its own thread id, so a shared event store
357        // only returns this subagent's events when queried with `thread_id`.
358        let thread_id = ThreadId::new();
359
360        // Create stores for this subagent run
361        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        // Create agent config with a default max_turns to prevent unbounded execution
366        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        // Build the subagent
373        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        // Derive the child context from the parent so the subagent-depth guard
384        // and the concurrency semaphore actually propagate into nested runs.
385        let tool_ctx = build_subagent_child_context(parent_ctx);
386
387        // Run with a child cancellation token so parent cancellation propagates.
388        // Use `run_abortable` so we can abort the spawned task on timeout
389        // instead of leaving a detached task that continues making API calls.
390        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
427/// Derive the tool context for a subagent run from its parent.
428///
429/// Copies the parent metadata (so host-set policy such as
430/// [`METADATA_MAX_SUBAGENT_DEPTH`] carries through), increments
431/// [`METADATA_SUBAGENT_DEPTH`] by one, and propagates the shared subagent
432/// concurrency semaphore. Without this the depth guard is dead code and nested
433/// spawning is unbounded.
434fn 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    /// Message id whose text currently populates `final_response`. Used to keep
461    /// only the **last** assistant message's text (the documented contract),
462    /// rather than concatenating every interim turn's commentary.
463    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    /// Record a failure: set the parent-visible response, the detailed error,
491    /// and clear the success flag.
492    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        // `AgentRunState` is `#[non_exhaustive]`; an unrecognized future run
570        // state is surfaced as an error so the subagent failure is not
571        // silently treated as a successful replay.
572        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    // Compute the (parent-visible response, detailed error) for the failure
589    // arms; a successful replay returns early and leaves the finished task be.
590    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    // Every failure path reclaims the spawned run before reporting.
622    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                // Keep only the last assistant message's text. A new message id
640                // means a new assistant message, so reset the accumulator;
641                // multiple text blocks within one message still concatenate.
642                // This honors the documented contract that the parent receives
643                // "only the final text response", not interim commentary.
644                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    // Capture the parent turn's SpanContext **before** starting the
812    // synthetic subagent span so the link points at the caller, not at
813    // ourselves.  When the agent runs without an active parent span
814    // (e.g. running a subagent from a top-level test) the captured
815    // context is invalid and `link_to_parent_turn` becomes a no-op.
816    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    // ── Metrics ─────────────────────────────────────────────────────
862    //
863    // Subagent invocations get a dedicated counter so dashboards can
864    // tell parent-turn LLM activity apart from delegated subagent
865    // work. We also fold the subagent's token usage into the shared
866    // `gen_ai.client.token.usage` histogram so global token-spend
867    // accounting stays accurate; the `gen_ai.operation.name` label
868    // discriminates `invoke_agent` from regular `chat` calls.
869    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
928/// Extracts context information from tool input for display.
929fn 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            // Truncate long commands (UTF-8 safe)
946            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
966/// Summarizes tool result for logging.
967fn 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        // Subagent spawning requires confirmation
1058        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        // ── Depth limit enforcement ───────────────────────────────────
1068        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); // default: 3 levels deep
1078
1079        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        // ── Thread limit enforcement (semaphore) ──────────────────────
1088        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        // Generate a unique ID for this subagent execution
1110        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        // Use the context's cancellation token if available, otherwise create a standalone one.
1120        // This ensures that when a parent agent is cancelled, subagents are also cancelled.
1121        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                    input_tokens: 10,
1177                    output_tokens: 20,
1178                    cached_input_tokens: 0,
1179                    cache_creation_input_tokens: 0,
1180                },
1181            })
1182        }
1183
1184        fn tool_use_response(tool_id: &str, tool_name: &str, input: Value) -> ChatOutcome {
1185            ChatOutcome::Success(ChatResponse {
1186                id: "resp_tool".to_string(),
1187                content: vec![ContentBlock::ToolUse {
1188                    id: tool_id.to_string(),
1189                    name: tool_name.to_string(),
1190                    input,
1191                    thought_signature: None,
1192                }],
1193                model: "test-model".to_string(),
1194                stop_reason: Some(StopReason::ToolUse),
1195                usage: Usage {
1196                    input_tokens: 15,
1197                    output_tokens: 25,
1198                    cached_input_tokens: 0,
1199                    cache_creation_input_tokens: 0,
1200                },
1201            })
1202        }
1203
1204        fn refusal_response(text: Option<&str>) -> ChatOutcome {
1205            let content = text.map_or_else(Vec::new, |text| {
1206                vec![ContentBlock::Text {
1207                    text: text.to_string(),
1208                }]
1209            });
1210            ChatOutcome::Success(ChatResponse {
1211                id: "resp_refusal".to_string(),
1212                content,
1213                model: "test-model".to_string(),
1214                stop_reason: Some(StopReason::Refusal),
1215                usage: Usage {
1216                    input_tokens: 12,
1217                    output_tokens: 0,
1218                    cached_input_tokens: 0,
1219                    cache_creation_input_tokens: 0,
1220                },
1221            })
1222        }
1223    }
1224
1225    #[async_trait]
1226    impl LlmProvider for TestProvider {
1227        async fn chat(&self, _request: ChatRequest) -> Result<ChatOutcome> {
1228            if let Some(delay) = self.delay {
1229                tokio::time::sleep(delay).await;
1230            }
1231
1232            let mut responses = self.responses.lock().await;
1233            if responses.is_empty() {
1234                Ok(Self::text_response("default"))
1235            } else {
1236                Ok(responses.remove(0))
1237            }
1238        }
1239
1240        fn model(&self) -> &'static str {
1241            "test-model"
1242        }
1243
1244        fn provider(&self) -> &'static str {
1245            "mock"
1246        }
1247    }
1248
1249    struct TestEchoTool;
1250
1251    impl Tool<()> for TestEchoTool {
1252        type Name = DynamicToolName;
1253
1254        fn name(&self) -> DynamicToolName {
1255            DynamicToolName::new("echo")
1256        }
1257
1258        fn display_name(&self) -> &'static str {
1259            "Echo"
1260        }
1261
1262        fn description(&self) -> &'static str {
1263            "Echo the input"
1264        }
1265
1266        fn input_schema(&self) -> Value {
1267            json!({
1268                "type": "object",
1269                "properties": {
1270                    "message": { "type": "string" }
1271                },
1272                "required": ["message"]
1273            })
1274        }
1275
1276        fn tier(&self) -> ToolTier {
1277            ToolTier::Observe
1278        }
1279
1280        async fn execute(&self, _ctx: &ToolContext<()>, input: Value) -> Result<ToolResult> {
1281            let message = input
1282                .get("message")
1283                .and_then(Value::as_str)
1284                .context("missing echo message")?;
1285            Ok(ToolResult::success(format!("Echo: {message}")))
1286        }
1287    }
1288
1289    #[derive(Clone, Default)]
1290    struct RecordingEventStore {
1291        inner: Arc<InMemoryEventStore>,
1292        appended: Arc<Mutex<Vec<(ThreadId, usize, AgentEventEnvelope)>>>,
1293    }
1294
1295    impl RecordingEventStore {
1296        async fn appended_events(&self) -> Vec<(ThreadId, usize, AgentEventEnvelope)> {
1297            self.appended.lock().await.clone()
1298        }
1299    }
1300
1301    #[async_trait]
1302    impl EventStore for RecordingEventStore {
1303        async fn append(
1304            &self,
1305            thread_id: &ThreadId,
1306            turn: usize,
1307            envelope: AgentEventEnvelope,
1308        ) -> Result<()> {
1309            self.appended
1310                .lock()
1311                .await
1312                .push((thread_id.clone(), turn, envelope.clone()));
1313            self.inner.append(thread_id, turn, envelope).await
1314        }
1315
1316        async fn finish_turn(&self, thread_id: &ThreadId, turn: usize) -> Result<()> {
1317            self.inner.finish_turn(thread_id, turn).await
1318        }
1319
1320        async fn get_turn(
1321            &self,
1322            thread_id: &ThreadId,
1323            turn: usize,
1324        ) -> Result<Option<StoredTurnEvents>> {
1325            self.inner.get_turn(thread_id, turn).await
1326        }
1327
1328        async fn get_turns(&self, thread_id: &ThreadId) -> Result<Vec<StoredTurnEvents>> {
1329            self.inner.get_turns(thread_id).await
1330        }
1331
1332        async fn clear(&self, thread_id: &ThreadId) -> Result<()> {
1333            self.inner.clear(thread_id).await
1334        }
1335    }
1336
1337    #[derive(Clone, Default)]
1338    struct AlwaysFailAppendEventStore;
1339
1340    #[async_trait]
1341    impl EventStore for AlwaysFailAppendEventStore {
1342        async fn append(
1343            &self,
1344            _thread_id: &ThreadId,
1345            _turn: usize,
1346            _envelope: AgentEventEnvelope,
1347        ) -> Result<()> {
1348            bail!("append failed")
1349        }
1350
1351        async fn finish_turn(&self, _thread_id: &ThreadId, _turn: usize) -> Result<()> {
1352            Ok(())
1353        }
1354
1355        async fn get_turn(
1356            &self,
1357            _thread_id: &ThreadId,
1358            _turn: usize,
1359        ) -> Result<Option<StoredTurnEvents>> {
1360            Ok(None)
1361        }
1362
1363        async fn get_turns(&self, _thread_id: &ThreadId) -> Result<Vec<StoredTurnEvents>> {
1364            Ok(Vec::new())
1365        }
1366
1367        async fn clear(&self, _thread_id: &ThreadId) -> Result<()> {
1368            Ok(())
1369        }
1370    }
1371
1372    #[derive(Clone, Default)]
1373    struct NoReadAfterFailureEventStore {
1374        inner: Arc<InMemoryEventStore>,
1375    }
1376
1377    #[async_trait]
1378    impl EventStore for NoReadAfterFailureEventStore {
1379        async fn append(
1380            &self,
1381            thread_id: &ThreadId,
1382            turn: usize,
1383            envelope: AgentEventEnvelope,
1384        ) -> Result<()> {
1385            self.inner.append(thread_id, turn, envelope).await
1386        }
1387
1388        async fn finish_turn(&self, thread_id: &ThreadId, turn: usize) -> Result<()> {
1389            self.inner.finish_turn(thread_id, turn).await
1390        }
1391
1392        async fn get_turn(
1393            &self,
1394            thread_id: &ThreadId,
1395            turn: usize,
1396        ) -> Result<Option<StoredTurnEvents>> {
1397            self.inner.get_turn(thread_id, turn).await
1398        }
1399
1400        async fn get_turns(&self, _thread_id: &ThreadId) -> Result<Vec<StoredTurnEvents>> {
1401            bail!("get_events should not be called after subagent failure")
1402        }
1403
1404        async fn clear(&self, thread_id: &ThreadId) -> Result<()> {
1405            self.inner.clear(thread_id).await
1406        }
1407    }
1408
1409    #[derive(Clone, Default)]
1410    struct PanicProvider;
1411
1412    #[async_trait]
1413    impl LlmProvider for PanicProvider {
1414        async fn chat(&self, _request: ChatRequest) -> Result<ChatOutcome> {
1415            // Panic isolation catches this at the run-loop
1416            // boundary and turns it into a structured `Error`, so the
1417            // parent classifies it as an agent error rather than a
1418            // dropped channel. The literal text is asserted on by
1419            // `test_run_subagent_panic_classified_as_error_not_disconnected`.
1420            panic!("panic provider should disconnect subagent");
1421        }
1422
1423        fn model(&self) -> &'static str {
1424            "panic-model"
1425        }
1426
1427        fn provider(&self) -> &'static str {
1428            "panic"
1429        }
1430    }
1431
1432    #[test]
1433    fn test_subagent_config_builder() {
1434        let config = SubagentConfig::new("test")
1435            .with_system_prompt("Test prompt")
1436            .with_max_turns(5)
1437            .with_timeout_ms(30000);
1438
1439        assert_eq!(config.name, "test");
1440        assert_eq!(config.system_prompt, "Test prompt");
1441        assert_eq!(config.max_turns, Some(5));
1442        assert_eq!(config.timeout_ms, Some(30000));
1443    }
1444
1445    #[test]
1446    fn test_subagent_config_defaults() {
1447        let config = SubagentConfig::new("default");
1448
1449        assert_eq!(config.name, "default");
1450        assert!(config.system_prompt.is_empty());
1451        assert_eq!(config.max_turns, None);
1452        assert_eq!(config.timeout_ms, None);
1453    }
1454
1455    #[test]
1456    fn test_subagent_result_serialization() -> Result<()> {
1457        let result = SubagentResult {
1458            name: "test".to_string(),
1459            final_response: "Done".to_string(),
1460            total_turns: 3,
1461            tool_count: 5,
1462            tool_logs: vec![
1463                ToolCallLog {
1464                    name: "read".to_string(),
1465                    display_name: "Read file".to_string(),
1466                    context: "/tmp/test.rs".to_string(),
1467                    result: "50 lines".to_string(),
1468                    success: true,
1469                    duration_ms: Some(10),
1470                },
1471                ToolCallLog {
1472                    name: "grep".to_string(),
1473                    display_name: "Grep TODO".to_string(),
1474                    context: "TODO".to_string(),
1475                    result: "3 matches".to_string(),
1476                    success: true,
1477                    duration_ms: Some(5),
1478                },
1479            ],
1480            usage: TokenUsage::default(),
1481            success: true,
1482            duration_ms: 1000,
1483            error_details: None,
1484            failed_tool: None,
1485        };
1486
1487        let json = serde_json::to_string(&result).context("failed to serialize subagent result")?;
1488        assert!(json.contains("test"));
1489        assert!(json.contains("Done"));
1490        assert!(json.contains("tool_count"));
1491        assert!(json.contains("tool_logs"));
1492        assert!(json.contains("/tmp/test.rs"));
1493
1494        Ok(())
1495    }
1496
1497    #[test]
1498    fn test_subagent_result_field_extraction() -> Result<()> {
1499        let result = SubagentResult {
1500            name: "explore".to_string(),
1501            final_response: "Found 3 config files".to_string(),
1502            total_turns: 2,
1503            tool_count: 5,
1504            tool_logs: vec![ToolCallLog {
1505                name: "glob".to_string(),
1506                display_name: "Glob config files".to_string(),
1507                context: "**/*.toml".to_string(),
1508                result: "3 files".to_string(),
1509                success: true,
1510                duration_ms: Some(15),
1511            }],
1512            usage: TokenUsage {
1513                input_tokens: 1500,
1514                output_tokens: 500,
1515                ..Default::default()
1516            },
1517            success: true,
1518            duration_ms: 2500,
1519            error_details: None,
1520            failed_tool: None,
1521        };
1522
1523        let value =
1524            serde_json::to_value(&result).context("failed to convert subagent result to json")?;
1525
1526        let tool_count = value.get("tool_count").and_then(Value::as_u64);
1527        assert_eq!(tool_count, Some(5));
1528
1529        let usage = value.get("usage").context("missing usage field")?;
1530        let input_tokens = usage.get("input_tokens").and_then(Value::as_u64);
1531        let output_tokens = usage.get("output_tokens").and_then(Value::as_u64);
1532        assert_eq!(input_tokens, Some(1500));
1533        assert_eq!(output_tokens, Some(500));
1534
1535        let logs = value
1536            .get("tool_logs")
1537            .and_then(Value::as_array)
1538            .context("missing tool_logs array")?;
1539        assert_eq!(logs.len(), 1);
1540
1541        let first_log = &logs[0];
1542        assert_eq!(first_log.get("name").and_then(Value::as_str), Some("glob"));
1543        assert_eq!(
1544            first_log.get("context").and_then(Value::as_str),
1545            Some("**/*.toml")
1546        );
1547        assert_eq!(
1548            first_log.get("result").and_then(Value::as_str),
1549            Some("3 files")
1550        );
1551        assert_eq!(
1552            first_log.get("success").and_then(Value::as_bool),
1553            Some(true)
1554        );
1555
1556        Ok(())
1557    }
1558
1559    #[tokio::test]
1560    async fn test_run_subagent_uses_isolated_child_thread() -> Result<()> {
1561        let event_store = Arc::new(RecordingEventStore::default());
1562        let provider = Arc::new(TestProvider::new(vec![
1563            TestProvider::tool_use_response("tool_1", "echo", json!({ "message": "child" })),
1564            TestProvider::text_response("Subagent complete"),
1565        ]));
1566        let mut tools = ToolRegistry::new();
1567        tools.register(TestEchoTool);
1568
1569        let tool = SubagentTool::new(SubagentConfig::new("worker"), provider, Arc::new(tools), {
1570            let store = Arc::clone(&event_store);
1571            move || -> Arc<dyn EventStore> { store.clone() }
1572        });
1573        let parent_thread = ThreadId::new();
1574        let parent_ctx = ToolContext::new(()).with_event_store(
1575            event_store.clone(),
1576            parent_thread.clone(),
1577            1,
1578            Arc::new(LocalEventAuthority::new()),
1579        );
1580
1581        let result = tool
1582            .run_subagent(
1583                "Inspect the repo",
1584                "subagent_1".to_string(),
1585                &parent_ctx,
1586                CancellationToken::new(),
1587            )
1588            .await?;
1589
1590        assert!(result.success);
1591        assert_eq!(result.tool_count, 1);
1592        assert_eq!(result.tool_logs.len(), 1);
1593
1594        let parent_turn = event_store
1595            .get_turn(&parent_thread, 1)
1596            .await?
1597            .context("missing parent turn")?;
1598        assert!(!parent_turn.events.is_empty());
1599        assert!(
1600            parent_turn
1601                .events
1602                .iter()
1603                .all(|envelope| { matches!(envelope.event, AgentEvent::SubagentProgress { .. }) })
1604        );
1605
1606        let appended = event_store.appended_events().await;
1607        let child_thread = appended
1608            .iter()
1609            .map(|(thread_id, _, _)| thread_id.clone())
1610            .find(|thread_id| thread_id != &parent_thread)
1611            .context("missing child thread events")?;
1612        let child_turn = event_store
1613            .get_turn(&child_thread, 1)
1614            .await?
1615            .context("missing child turn")?;
1616        let child_events = event_store.get_events(&child_thread).await?;
1617
1618        assert!(
1619            child_turn
1620                .events
1621                .iter()
1622                .any(|envelope| { matches!(envelope.event, AgentEvent::ToolCallStart { .. }) })
1623        );
1624        assert!(
1625            child_events
1626                .iter()
1627                .any(|envelope| { matches!(envelope.event, AgentEvent::Done { .. }) })
1628        );
1629
1630        Ok(())
1631    }
1632
1633    #[tokio::test]
1634    async fn test_run_subagent_timeout_marks_result_as_failed() -> Result<()> {
1635        let event_store = Arc::new(NoReadAfterFailureEventStore::default());
1636        let provider = Arc::new(
1637            TestProvider::new(vec![TestProvider::text_response("Too late")])
1638                .with_delay(Duration::from_millis(50)),
1639        );
1640        let tool = SubagentTool::new(
1641            SubagentConfig::new("worker").with_timeout_ms(10),
1642            provider,
1643            Arc::new(ToolRegistry::<()>::new()),
1644            {
1645                let store = Arc::clone(&event_store);
1646                move || -> Arc<dyn EventStore> { store.clone() }
1647            },
1648        );
1649
1650        let result = tool
1651            .run_subagent(
1652                "Take too long",
1653                "subagent_timeout".to_string(),
1654                &ToolContext::new(()),
1655                CancellationToken::new(),
1656            )
1657            .await?;
1658
1659        assert!(!result.success);
1660        assert_eq!(result.final_response, "Subagent timed out");
1661        assert!(
1662            result
1663                .error_details
1664                .context("missing timeout details")?
1665                .contains("timed out")
1666        );
1667
1668        Ok(())
1669    }
1670
1671    #[tokio::test]
1672    async fn test_run_subagent_progress_failures_do_not_abort_successful_runs() -> Result<()> {
1673        let provider = Arc::new(TestProvider::new(vec![
1674            TestProvider::tool_use_response("tool_1", "echo", json!({ "message": "child" })),
1675            TestProvider::text_response("Subagent complete"),
1676        ]));
1677        let mut tools = ToolRegistry::new();
1678        tools.register(TestEchoTool);
1679
1680        let tool = SubagentTool::new(SubagentConfig::new("worker"), provider, Arc::new(tools), {
1681            move || -> Arc<dyn EventStore> { Arc::new(InMemoryEventStore::new()) }
1682        });
1683        let parent_ctx = ToolContext::new(()).with_event_store(
1684            Arc::new(AlwaysFailAppendEventStore),
1685            ThreadId::new(),
1686            1,
1687            Arc::new(LocalEventAuthority::new()),
1688        );
1689
1690        let result = tool
1691            .run_subagent(
1692                "Inspect the repo",
1693                "subagent_progress".to_string(),
1694                &parent_ctx,
1695                CancellationToken::new(),
1696            )
1697            .await?;
1698
1699        assert!(result.success);
1700        assert_eq!(result.final_response, "Subagent complete");
1701        assert_eq!(result.tool_count, 1);
1702
1703        Ok(())
1704    }
1705
1706    #[tokio::test]
1707    async fn test_run_subagent_panic_classified_as_error_not_disconnected() -> Result<()> {
1708        // A subagent whose LLM provider panics must surface as a
1709        // structured `Error` — NOT the `Disconnected` ("ended
1710        // unexpectedly") path. Before panic isolation the
1711        // panic unwound the spawned run task, dropped `state_tx`, and
1712        // the parent saw a `RecvError` it misclassified as
1713        // `Disconnected`. The run-loop catch_unwind boundary now turns
1714        // the panic into `AgentRunState::Error`, which the subagent
1715        // classifies correctly.
1716        let tool = SubagentTool::new(
1717            SubagentConfig::new("worker"),
1718            Arc::new(PanicProvider),
1719            Arc::new(ToolRegistry::<()>::new()),
1720            move || -> Arc<dyn EventStore> { Arc::new(InMemoryEventStore::new()) },
1721        );
1722
1723        let result = tool
1724            .run_subagent(
1725                "Crash",
1726                "subagent_panic".to_string(),
1727                &ToolContext::new(()),
1728                CancellationToken::new(),
1729            )
1730            .await?;
1731
1732        assert!(!result.success);
1733        // The disconnect path must NOT be taken: a caught panic is a
1734        // structured agent error, not an opaque dropped channel.
1735        assert_ne!(result.final_response, "Subagent ended unexpectedly");
1736        let details = result
1737            .error_details
1738            .context("panicking subagent must carry structured error details")?;
1739        assert!(
1740            !details.contains("ended before returning a final state"),
1741            "panic must not be classified as Disconnected; got {details:?}",
1742        );
1743        assert!(
1744            details.contains("panicked"),
1745            "structured error should reflect the panic; got {details:?}",
1746        );
1747        assert!(
1748            details.contains("panic provider should disconnect subagent"),
1749            "structured error should carry the original panic message; got {details:?}",
1750        );
1751
1752        Ok(())
1753    }
1754
1755    #[tokio::test]
1756    async fn test_run_subagent_refusal_marks_result_as_failed() -> Result<()> {
1757        let tool = SubagentTool::new(
1758            SubagentConfig::new("worker"),
1759            Arc::new(TestProvider::new(vec![TestProvider::refusal_response(
1760                Some("Refused for policy reasons"),
1761            )])),
1762            Arc::new(ToolRegistry::<()>::new()),
1763            || Arc::new(InMemoryEventStore::new()),
1764        );
1765
1766        let result = tool
1767            .run_subagent(
1768                "Refuse",
1769                "subagent_refusal".to_string(),
1770                &ToolContext::new(()),
1771                CancellationToken::new(),
1772            )
1773            .await?;
1774
1775        assert!(!result.success);
1776        assert_eq!(result.final_response, "Refused for policy reasons");
1777        assert_eq!(
1778            result.error_details.as_deref(),
1779            Some("Refused for policy reasons")
1780        );
1781
1782        Ok(())
1783    }
1784
1785    #[tokio::test]
1786    async fn test_run_subagent_cancelled_marks_result_as_failed() -> Result<()> {
1787        let tool = SubagentTool::new(
1788            SubagentConfig::new("worker"),
1789            Arc::new(
1790                TestProvider::new(vec![TestProvider::text_response("Too late")])
1791                    .with_delay(Duration::from_millis(50)),
1792            ),
1793            Arc::new(ToolRegistry::<()>::new()),
1794            || Arc::new(InMemoryEventStore::new()),
1795        );
1796        let cancel_token = CancellationToken::new();
1797        cancel_token.cancel();
1798
1799        let result = tool
1800            .run_subagent(
1801                "Cancel",
1802                "subagent_cancelled".to_string(),
1803                &ToolContext::new(()),
1804                cancel_token,
1805            )
1806            .await?;
1807
1808        assert!(!result.success);
1809        assert_eq!(result.final_response, "Subagent cancelled");
1810        assert!(
1811            result
1812                .error_details
1813                .context("missing cancellation details")?
1814                .contains("cancelled")
1815        );
1816
1817        Ok(())
1818    }
1819
1820    #[tokio::test]
1821    async fn test_run_subagent_llm_error_does_not_infer_failed_tool() -> Result<()> {
1822        let provider = Arc::new(TestProvider::new(vec![
1823            ChatOutcome::ServerError("llm transport failed".to_string()),
1824            ChatOutcome::ServerError("llm transport failed".to_string()),
1825            ChatOutcome::ServerError("llm transport failed".to_string()),
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        ]));
1830        let mut tools = ToolRegistry::new();
1831        tools.register(TestEchoTool);
1832
1833        let tool = SubagentTool::new(
1834            SubagentConfig::new("worker"),
1835            provider,
1836            Arc::new(tools),
1837            || Arc::new(InMemoryEventStore::new()),
1838        );
1839
1840        let result = tool
1841            .run_subagent(
1842                "Trigger an llm failure",
1843                "subagent_llm_error".to_string(),
1844                &ToolContext::new(()),
1845                CancellationToken::new(),
1846            )
1847            .await?;
1848
1849        assert!(!result.success);
1850        assert!(result.failed_tool.is_none());
1851        assert!(
1852            result
1853                .error_details
1854                .as_deref()
1855                .unwrap_or_default()
1856                .contains("Server error")
1857        );
1858
1859        Ok(())
1860    }
1861
1862    #[tokio::test]
1863    async fn test_replay_subagent_events_stops_after_error() -> Result<()> {
1864        let event_store: Arc<dyn EventStore> = Arc::new(InMemoryEventStore::new());
1865        let thread_id = ThreadId::new();
1866        let authority = LocalEventAuthority::new();
1867        event_store
1868            .append(
1869                &thread_id,
1870                1,
1871                authority.wrap(AgentEvent::error("subagent boom", false)),
1872            )
1873            .await?;
1874        event_store
1875            .append(
1876                &thread_id,
1877                1,
1878                authority.wrap(AgentEvent::Text {
1879                    message_id: "msg_after_error".to_string(),
1880                    text: "should not be appended".to_string(),
1881                }),
1882            )
1883            .await?;
1884
1885        let mut state = SubagentExecutionState::new();
1886        replay_subagent_events(
1887            &event_store,
1888            &thread_id,
1889            &ToolContext::new(()),
1890            &SubagentConfig::new("worker"),
1891            "subagent_error",
1892            &mut state,
1893        )
1894        .await?;
1895
1896        assert!(!state.success);
1897        assert_eq!(state.final_response, "subagent boom");
1898        assert_eq!(state.error_details.as_deref(), Some("subagent boom"));
1899
1900        Ok(())
1901    }
1902
1903    #[tokio::test]
1904    async fn test_replay_keeps_only_final_message_text() -> Result<()> {
1905        let event_store: Arc<dyn EventStore> = Arc::new(InMemoryEventStore::new());
1906        let thread_id = ThreadId::new();
1907        let authority = LocalEventAuthority::new();
1908
1909        // Interim commentary in an early assistant message.
1910        event_store
1911            .append(
1912                &thread_id,
1913                1,
1914                authority.wrap(AgentEvent::Text {
1915                    message_id: "m1".to_string(),
1916                    text: "Let me check the repo...".to_string(),
1917                }),
1918            )
1919            .await?;
1920        // The final answer in a later message, split across two text blocks.
1921        event_store
1922            .append(
1923                &thread_id,
1924                2,
1925                authority.wrap(AgentEvent::Text {
1926                    message_id: "m2".to_string(),
1927                    text: "Final answer ".to_string(),
1928                }),
1929            )
1930            .await?;
1931        event_store
1932            .append(
1933                &thread_id,
1934                2,
1935                authority.wrap(AgentEvent::Text {
1936                    message_id: "m2".to_string(),
1937                    text: "part two".to_string(),
1938                }),
1939            )
1940            .await?;
1941        event_store
1942            .append(
1943                &thread_id,
1944                2,
1945                authority.wrap(AgentEvent::done(
1946                    thread_id.clone(),
1947                    2,
1948                    TokenUsage::default(),
1949                    Duration::from_millis(1),
1950                )),
1951            )
1952            .await?;
1953
1954        let mut state = SubagentExecutionState::new();
1955        replay_subagent_events(
1956            &event_store,
1957            &thread_id,
1958            &ToolContext::new(()),
1959            &SubagentConfig::new("worker"),
1960            "subagent_final",
1961            &mut state,
1962        )
1963        .await?;
1964
1965        // Interim commentary must not be glued onto the final answer; only the
1966        // last assistant message's text is returned.
1967        assert_eq!(state.final_response, "Final answer part two");
1968
1969        Ok(())
1970    }
1971
1972    #[test]
1973    fn build_subagent_child_context_increments_depth_and_propagates_semaphore() {
1974        let semaphore = Arc::new(tokio::sync::Semaphore::new(2));
1975        let parent = ToolContext::new(())
1976            .with_metadata(METADATA_SUBAGENT_DEPTH, json!(2))
1977            .with_metadata(METADATA_MAX_SUBAGENT_DEPTH, json!(5))
1978            .with_subagent_semaphore(Arc::clone(&semaphore));
1979
1980        let child = build_subagent_child_context(&parent);
1981
1982        assert_eq!(
1983            child
1984                .metadata
1985                .get(METADATA_SUBAGENT_DEPTH)
1986                .and_then(Value::as_u64),
1987            Some(3)
1988        );
1989        // Host-set max-depth carries through unchanged.
1990        assert_eq!(
1991            child
1992                .metadata
1993                .get(METADATA_MAX_SUBAGENT_DEPTH)
1994                .and_then(Value::as_u64),
1995            Some(5)
1996        );
1997        // The shared concurrency semaphore propagates into the child run.
1998        assert!(child.subagent_semaphore().is_some());
1999    }
2000
2001    #[test]
2002    fn cached_tool_strings_are_interned_per_name() {
2003        let a = cached_tool_strings("worker");
2004        let b = cached_tool_strings("worker");
2005        // The same name reuses a single leaked allocation rather than leaking
2006        // afresh on every construction.
2007        assert!(std::ptr::eq(a.0, b.0));
2008        assert!(std::ptr::eq(a.1, b.1));
2009        assert_eq!(a.0, "Subagent: worker");
2010
2011        let c = cached_tool_strings("a-different-name");
2012        assert!(!std::ptr::eq(a.0, c.0));
2013    }
2014
2015    #[tokio::test]
2016    async fn test_nested_subagent_depth_limit_propagates() -> Result<()> {
2017        use crate::hooks::AllowAllHooks;
2018
2019        // The inner subagent must never run: the depth guard fires first.
2020        let inner = SubagentTool::new(
2021            SubagentConfig::new("inner"),
2022            Arc::new(TestProvider::new(vec![TestProvider::text_response(
2023                "inner ran (should not happen)",
2024            )])),
2025            Arc::new(ToolRegistry::<()>::new()),
2026            || -> Arc<dyn EventStore> { Arc::new(InMemoryEventStore::new()) },
2027        );
2028        let mut middle_tools = ToolRegistry::new();
2029        middle_tools.register(inner);
2030
2031        // The outer subagent tries to spawn the nested subagent, then finishes.
2032        // `AllowAllHooks` auto-approves the Confirm-tier nested spawn so it
2033        // actually reaches the depth guard.
2034        let outer = SubagentTool::new(
2035            SubagentConfig::new("outer"),
2036            Arc::new(TestProvider::new(vec![
2037                TestProvider::tool_use_response(
2038                    "call_inner",
2039                    "subagent_inner",
2040                    json!({ "task": "go deeper" }),
2041                ),
2042                TestProvider::text_response("outer done"),
2043            ])),
2044            Arc::new(middle_tools),
2045            || -> Arc<dyn EventStore> { Arc::new(InMemoryEventStore::new()) },
2046        )
2047        .with_hooks(Arc::new(AllowAllHooks));
2048
2049        // Cap nesting at depth 1: the outer runs at depth 1, so its nested
2050        // spawn (which would be depth 1 >= max 1) must be rejected.
2051        let parent_ctx = ToolContext::new(()).with_metadata(METADATA_MAX_SUBAGENT_DEPTH, json!(1));
2052
2053        let result = outer
2054            .execute(&parent_ctx, json!({ "task": "start" }))
2055            .await?;
2056
2057        assert!(result.success, "outer subagent should still complete");
2058        assert_eq!(result.output, "outer done");
2059
2060        let subresult: SubagentResult =
2061            serde_json::from_value(result.data.context("missing subagent result data")?)
2062                .context("subagent result should deserialize")?;
2063        let nested = subresult
2064            .tool_logs
2065            .iter()
2066            .find(|log| log.name == "subagent_inner")
2067            .context("missing nested subagent tool log")?;
2068        assert!(!nested.success, "nested spawn must be rejected");
2069        assert!(
2070            nested.result.contains("depth limit"),
2071            "nested failure should be the depth-limit error; got: {}",
2072            nested.result
2073        );
2074
2075        Ok(())
2076    }
2077}