Skip to main content

vtcode_core/subagents/controller_spawn_run/
mod.rs

1#![allow(
2    unused_imports,
3    reason = "Intentional compatibility, platform, or test-only suppression."
4)]
5use anyhow::{Context, Result, anyhow, bail};
6use chrono::Utc;
7use futures::future::{BoxFuture, select_all};
8use std::collections::VecDeque;
9use std::path::PathBuf;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12use tokio::sync::{Notify, RwLock};
13
14use crate::config::VTCodeConfig;
15use crate::config::types::ReasoningEffortLevel;
16use crate::core::agent::runner::{AgentRunner, RunnerSettings};
17use crate::core::agent::task::Task;
18use crate::core::threads::{ThreadBootstrap, ThreadId, ThreadRuntimeHandle, ThreadSnapshot};
19use crate::hooks::{LifecycleHookEngine, SessionStartTrigger};
20use crate::llm::provider::Message;
21use crate::tools::exec_session::ExecSessionManager;
22use crate::tools::pty::{PtyManager, PtySize};
23use crate::utils::session_archive::{SessionArchive, find_session_by_identifier};
24use vtcode_config::SubagentSpec;
25use vtcode_config::auth::OpenAIChatGptAuthHandle;
26
27use self::background::*;
28use self::config::*;
29use self::constants::*;
30use self::discovery::discover_controller_subagents;
31use self::model::*;
32use vtcode_config::subagents::SUBAGENT_HARD_CONCURRENCY_LIMIT;
33
34#[allow(
35    unused_imports,
36    reason = "Intentional compatibility, platform, or test-only suppression."
37)]
38use super::*;
39
40mod background;
41
42/// A dropped blocking launch must not leave its newly created worktree behind.
43struct LaunchWorktree {
44    root: PathBuf,
45    name: String,
46    path: PathBuf,
47    permit: Option<tokio::sync::OwnedSemaphorePermit>,
48    armed: bool,
49}
50
51impl Drop for LaunchWorktree {
52    fn drop(&mut self) {
53        if self.armed
54            && let Err(error) = crate::git::WorktreeManager::new(&self.root).remove(&self.name)
55        {
56            tracing::warn!(%error, worktree = %self.path.display(), "failed to roll back cancelled subagent launch");
57        }
58    }
59}
60
61async fn wait_for_child_stop(handle: &mut JoinHandle<()>, child_id: &str) -> Result<()> {
62    match handle.await {
63        Ok(()) => Ok(()),
64        Err(error) if error.is_cancelled() => Ok(()),
65        Err(error) => Err(error).with_context(|| format!("subagent {child_id} launch failed to stop cleanly")),
66    }
67}
68
69impl SubagentController {
70    /// Spawns a new subagent child process from a [`SpawnAgentRequest`].
71    pub async fn spawn(&self, request: SpawnAgentRequest) -> Result<SubagentStatusEntry> {
72        self.ensure_ordinary_delegation_allowed()?;
73        let mut request = request;
74        let delegation = self
75            .prepare_delegation_context(
76                request.agent_type.clone(),
77                &mut request.items,
78                &mut request.model,
79                "spawn_agent",
80            )
81            .await?;
82        let spec = self.resolve_requested_spec(delegation.requested_agent.as_deref()).await?;
83        let prompt = self.prepare_delegation_prompt(
84            &spec,
85            &delegation,
86            request.message.as_deref(),
87            &request.items,
88            "spawn_agent",
89            "spawning the subagent",
90        )?;
91        self.spawn_with_spec(
92            spec,
93            prompt,
94            request.fork_context,
95            request.background,
96            request.max_turns,
97            request.model,
98            request.reasoning_effort,
99        )
100        .await
101    }
102
103    /// Spawns a background subprocess for a subagent marked `background: true`.
104    pub async fn spawn_background_subprocess(
105        &self,
106        request: SpawnBackgroundSubprocessRequest,
107    ) -> Result<BackgroundSubprocessEntry> {
108        if self.config.managed_background_runtime {
109            bail!("managed background subprocesses cannot launch nested background subprocesses");
110        }
111        if !self.config.vt_cfg.subagents.background.enabled {
112            bail!("Background subagents are disabled by configuration");
113        }
114
115        let mut request = request;
116        let delegation = self
117            .prepare_delegation_context(
118                request.agent_type.clone(),
119                &mut request.items,
120                &mut request.model,
121                "spawn_background_subprocess",
122            )
123            .await?;
124        let spec = self.resolve_requested_spec(delegation.requested_agent.as_deref()).await?;
125        if !spec.background {
126            bail!(
127                "spawn_background_subprocess requires an agent with `background: true`; '{}' is a normal delegated child agent. Use spawn_agent instead.",
128                spec.name
129            );
130        }
131        let prompt = self.prepare_delegation_prompt(
132            &spec,
133            &delegation,
134            request.message.as_deref(),
135            &request.items,
136            "spawn_background_subprocess",
137            "launching the background subprocess",
138        )?;
139        let desired_max_turns = normalize_background_child_max_turns(request.max_turns.or(spec.max_turns), true);
140        let desired_model_override = request.model.clone().or_else(|| spec.model.clone());
141        let desired_reasoning_override = request
142            .reasoning_effort
143            .clone()
144            .or_else(|| spec.reasoning_effort.as_ref().map(|e| e.as_str().to_string()));
145
146        let record_id = background_record_id(spec.name.as_str());
147        let _ = self.refresh_background_processes().await?;
148        {
149            let state = self.state.read().await;
150            if let Some(record) = state.background_children.get(&record_id)
151                && record.desired_enabled
152                && record.status.is_active()
153            {
154                let conflicts = Self::active_background_launch_conflicts(
155                    record,
156                    prompt.as_str(),
157                    desired_max_turns,
158                    desired_model_override.as_deref(),
159                    desired_reasoning_override.as_deref(),
160                );
161                if !conflicts.is_empty() {
162                    bail!(
163                        "spawn_background_subprocess found active background subprocess '{}' with different {}. Stop or restart the existing subprocess before changing its launch settings.",
164                        spec.name,
165                        conflicts.join(", "),
166                    );
167                }
168                return Ok(record.build_status_entry());
169            }
170        }
171
172        self.ensure_background_record_running(
173            spec.name.as_str(),
174            Some(record_id.as_str()),
175            0,
176            Some(BackgroundLaunchOverrides {
177                prompt: Some(prompt),
178                max_turns: request.max_turns,
179                model_override: request.model,
180                reasoning_override: request.reasoning_effort,
181            }),
182        )
183        .await
184    }
185
186    /// Spawns a subagent with a custom [`SubagentSpec`] that must be read-only.
187    pub async fn spawn_custom(&self, spec: SubagentSpec, request: SpawnAgentRequest) -> Result<SubagentStatusEntry> {
188        if !spec.is_subagent() {
189            bail!("custom subagent spawn only supports subagent-capable specs; '{}' is primary-only", spec.name);
190        }
191
192        if !spec.is_read_only() {
193            bail!(
194                "custom subagent spawn only supports read-only specs; '{}' exposes write-capable behavior",
195                spec.name
196            );
197        }
198
199        let mut request = request;
200        sanitize_subagent_input_items(&mut request.items);
201
202        let prompt = request_prompt(request.message.as_deref(), &request.items)
203            .or_else(|| spec.initial_prompt.clone())
204            .filter(|value| !value.trim().is_empty())
205            .ok_or_else(|| anyhow!("custom subagent spawn requires a task message or items"))?;
206        if delegated_task_requires_clarification(&prompt) {
207            bail!(
208                "custom subagent task for '{}' is too vague ('{}'). Provide a specific delegated task before spawning the subagent.",
209                spec.name,
210                prompt.trim()
211            );
212        }
213
214        self.spawn_with_spec(
215            spec,
216            prompt,
217            request.fork_context,
218            request.background,
219            request.max_turns,
220            request.model,
221            request.reasoning_effort,
222        )
223        .await
224    }
225
226    /// Sends additional input to a running or queued subagent.
227    pub async fn send_input(&self, request: SendInputRequest) -> Result<SubagentStatusEntry> {
228        self.ensure_ordinary_delegation_allowed()?;
229        let prompt = request_prompt(request.message.as_deref(), &request.items)
230            .ok_or_else(|| anyhow!("send_input requires a message or items"))?;
231
232        let maybe_restart = {
233            let mut state = self.state.write().await;
234            let record = state
235                .children
236                .get_mut(&request.target)
237                .ok_or_else(|| anyhow!("Unknown subagent id {}", request.target))?;
238
239            if record.status == SubagentStatus::Closed || record.closing {
240                bail!("Subagent {} is closed", request.target);
241            }
242
243            record.updated_at = Utc::now();
244            record.last_prompt = Some(prompt.clone());
245
246            if request.interrupt {
247                if let Some(handle) = record.handle.as_ref() {
248                    handle.abort();
249                }
250                record.status = SubagentStatus::Queued;
251                record.queued_prompts.clear();
252                record.queued_prompts.push_back(prompt.clone());
253                true
254            } else if !record.status.is_terminal() {
255                record.status = SubagentStatus::Waiting;
256                record.queued_prompts.push_back(prompt.clone());
257                false
258            } else {
259                record.status = SubagentStatus::Queued;
260                record.queued_prompts.push_back(prompt.clone());
261                true
262            }
263        };
264
265        if maybe_restart {
266            self.restart_child(&request.target).await?;
267        }
268
269        self.status_for(&request.target).await
270    }
271
272    /// Resumes a closed or errored subagent and its descendants by re-queuing
273    /// their prompts. Cascades recursively through child-scoped controllers so
274    /// grandchildren closed by `close_tree` are resumed too, not merely
275    /// un-gated.
276    pub async fn resume(&self, target: &str) -> Result<SubagentStatusEntry> {
277        self.ensure_ordinary_delegation_allowed()?;
278        self.resume_tree(target).await
279    }
280
281    /// Recursively reopens `target` and every descendant across the whole
282    /// delegation tree (boxed for async recursion, mirroring `close_tree`).
283    fn resume_tree(&self, target: &str) -> BoxFuture<'static, Result<SubagentStatusEntry>> {
284        let self_owned = self.clone();
285        let target_owned = target.to_string();
286        Box::pin(async move {
287            if self_owned.shutdown_requested.load(Ordering::Relaxed) {
288                bail!("Subagent controller is shutting down; cannot resume subagents");
289            }
290            let subtree_ids = self_owned.collect_spawn_subtree_ids(&target_owned).await?;
291            let mut restart_ids = Vec::new();
292            for node_id in subtree_ids.iter() {
293                if self_owned.reopen_single(node_id.as_str()).await? {
294                    restart_ids.push(node_id.clone());
295                }
296            }
297            // Recursively resume each child-scoped controller's descendants,
298            // but only for controllers whose owning record is inside the
299            // resumed subtree (mirroring close_tree's sibling isolation).
300            // Grandchildren live in the child controller's state, so they are
301            // reopened through that controller to keep node ownership correct.
302            let nested = self_owned.nested_controllers_in_subtree(&subtree_ids).await;
303            for (controller, session_id) in nested {
304                let ids = controller.spawn_child_ids_for_parent(&session_id).await;
305                for id in ids {
306                    if let Err(err) = controller.resume_tree(&id).await {
307                        tracing::warn!(node_id = id.as_str(), error = %err, "Failed to resume nested subagent subtree");
308                    }
309                }
310            }
311            // Re-check shutdown before launching: a concurrent signal_shutdown
312            // between reopen and restart would otherwise start a child after
313            // shutdown aborted the subtree.
314            if self_owned.shutdown_requested.load(Ordering::Relaxed) {
315                bail!("Subagent controller is shutting down; cannot resume subagents");
316            }
317            for restart_id in restart_ids {
318                self_owned.restart_child(&restart_id).await?;
319            }
320            self_owned.status_for(&target_owned).await
321        })
322    }
323
324    /// Closes a subagent and all its descendants, aborting any in-flight work.
325    pub async fn close(&self, target: &str) -> Result<SubagentStatusEntry> {
326        // `close_tree` walks the full nesting tree (including grandchildren
327        // spawned through child-scoped controllers) and closes bottom-up.
328        self.close_tree(target).await
329    }
330
331    /// Closes `target` and every descendant across the whole delegation tree.
332    ///
333    /// Unlike [`Self::close`] this is recursive over child-scoped controllers,
334    /// so it works for arbitrary `max_depth`. The recursion is boxed to satisfy
335    /// Rust's async-fn recursion requirement.
336    ///
337    /// Ordering prevents a race where a still-running child spawns a new
338    /// descendant after the descendant snapshot: each child-scoped controller
339    /// is marked as closing (which rejects new spawns via `spawn_with_spec`)
340    /// before the owning child's handle is aborted and its subtree is closed.
341    fn close_tree(&self, target: &str) -> BoxFuture<'static, Result<SubagentStatusEntry>> {
342        let self_owned = self.clone();
343        let target_owned = target.to_string();
344        Box::pin(async move {
345            let subtree_ids = self_owned.collect_spawn_subtree_ids(&target_owned).await?;
346            {
347                let mut state = self_owned.state.write().await;
348                for id in &subtree_ids {
349                    if let Some(record) = state.children.get_mut(id) {
350                        record.closing = true;
351                    }
352                }
353            }
354            let nested = self_owned.nested_controllers_in_subtree(&subtree_ids).await;
355            // Mark every child-scoped controller in the subtree as closing so
356            // it rejects new grandchild spawns before we start aborting.
357            for (controller, _) in &nested {
358                controller.begin_close().await;
359            }
360            // Close the target's own subtree (deepest first) on this
361            // controller. Aborting the owning child's handle first stops it
362            // from spawning further descendants.
363            let subtree_ids_for_rescan = subtree_ids.clone();
364            for node_id in subtree_ids.into_iter().rev() {
365                self_owned.close_single(node_id.as_str()).await?;
366            }
367            let mut nested_errors = Vec::new();
368            // ...then recursively close each child-scoped controller's subtree.
369            // Grandchildren live in the child controller's state, not ours, so
370            // they are closed through that controller to keep node ownership
371            // correct. Only controllers of nodes inside the closed subtree are
372            // cascaded, so closing one subagent never kills a sibling's
373            // descendants.
374            for (controller, session_id) in nested {
375                let ids = controller.spawn_child_ids_for_parent(&session_id).await;
376                for id in ids {
377                    if let Err(err) = controller.close_tree(&id).await {
378                        tracing::warn!(node_id = id.as_str(), error = %err, "Failed to close nested subagent subtree");
379                        nested_errors.push(format!("{id}: {err:#}"));
380                    }
381                }
382            }
383            // A child may have attached a freshly created controller between
384            // the snapshot above and its handle abort. Re-scan and cascade
385            // again so no grandchild outlives the close; the second pass is a
386            // no-op in the common case because close_tree is idempotent.
387            let late = self_owned.nested_controllers_in_subtree(&subtree_ids_for_rescan).await;
388            for (controller, session_id) in late {
389                controller.begin_close().await;
390                let ids = controller.spawn_child_ids_for_parent(&session_id).await;
391                for id in ids {
392                    if let Err(err) = controller.close_tree(&id).await {
393                        tracing::warn!(node_id = id.as_str(), error = %err, "Failed to close late nested subagent subtree");
394                        nested_errors.push(format!("{id}: {err:#}"));
395                    }
396                }
397            }
398            if !nested_errors.is_empty() {
399                bail!("Failed to close nested subagents: {}", nested_errors.join("; "));
400            }
401            {
402                let mut state = self_owned.state.write().await;
403                for id in &subtree_ids_for_rescan {
404                    if let Some(record) = state.children.get_mut(id) {
405                        record.closing = false;
406                    }
407                }
408            }
409            self_owned.status_for(&target_owned).await
410        })
411    }
412
413    /// Blocks until one of the target subagents reaches a terminal state or the timeout expires.
414    pub async fn wait(&self, targets: &[String], timeout_ms: Option<u64>) -> Result<Option<SubagentStatusEntry>> {
415        for target in targets {
416            if let Ok(entry) = self.status_for(target).await
417                && entry.status.is_terminal()
418            {
419                return Ok(Some(entry));
420            }
421        }
422
423        let timeout = std::time::Duration::from_millis(
424            timeout_ms.unwrap_or_else(|| self.config.vt_cfg.subagents.default_timeout_seconds.saturating_mul(1000)),
425        );
426        let deadline = tokio::time::Instant::now() + timeout;
427
428        loop {
429            // Collect notify handles from child records.
430            let notifies = {
431                let state = self.state.read().await;
432                targets
433                    .iter()
434                    .filter_map(|target| state.children.get(target).map(|record| record.notify.clone()))
435                    .collect::<Vec<_>>()
436            };
437            if notifies.is_empty() {
438                return Ok(None);
439            }
440
441            // Register notified() futures BEFORE checking terminal status.
442            // This prevents a Tokio Notify race condition: if apply_result()
443            // calls notify_waiters() between a status check and future
444            // creation, the notification is permanently lost. By registering
445            // futures first, any concurrent notification either:
446            //   (a) arrives before we poll the future → stored as a permit,
447            //       select! returns immediately, loop re-checks status, or
448            //   (b) arrives after we start waiting → wakes the future normally.
449            let wait_any = select_all(
450                notifies
451                    .into_iter()
452                    .map(|notify| Box::pin(async move { notify.notified().await }))
453                    .collect::<Vec<_>>(),
454            );
455            tokio::pin!(wait_any);
456
457            // Now check if any target is already terminal.
458            for target in targets {
459                if let Ok(entry) = self.status_for(target).await
460                    && entry.status.is_terminal()
461                {
462                    return Ok(Some(entry));
463                }
464            }
465
466            let sleep = tokio::time::sleep_until(deadline);
467            tokio::pin!(sleep);
468
469            tokio::select! {
470                _ = &mut sleep => return Ok(None),
471                _ = &mut wait_any => {}
472            }
473        }
474    }
475
476    /// Returns the current status of a tracked subagent by its target id.
477    pub async fn status_for(&self, target: &str) -> Result<SubagentStatusEntry> {
478        let state = self.state.read().await;
479        let record = state
480            .children
481            .get(target)
482            .ok_or_else(|| anyhow!("Unknown subagent id {target}"))?;
483        Ok(record.build_status_entry())
484    }
485
486    pub(super) async fn spawn_child_ids_for_parent(&self, parent_thread_id: &str) -> Vec<String> {
487        let state = self.state.read().await;
488        let mut child_ids = state
489            .children
490            .values()
491            .filter(|record| record.parent_thread_id == parent_thread_id)
492            .map(|record| record.id.clone())
493            .collect::<Vec<_>>();
494        child_ids.sort();
495        child_ids
496    }
497
498    pub(super) async fn collect_spawn_subtree_ids(&self, root_thread_id: &str) -> Result<Vec<String>> {
499        let mut subtree_ids = Vec::new();
500        let mut stack = vec![root_thread_id.to_string()];
501
502        while let Some(thread_id) = stack.pop() {
503            subtree_ids.push(thread_id.clone());
504            let child_ids = self.spawn_child_ids_for_parent(&thread_id).await;
505            for child_id in child_ids.into_iter().rev() {
506                stack.push(child_id);
507            }
508        }
509
510        Ok(subtree_ids)
511    }
512
513    /// Collects the child-scoped controllers owned by records inside `subtree_ids`,
514    /// paired with each owning record's session id. Shared by `resume_tree` and
515    /// `close_tree` so subtree isolation cannot diverge between them.
516    async fn nested_controllers_in_subtree(&self, subtree_ids: &[String]) -> Vec<(Arc<SubagentController>, String)> {
517        let subtree_set = subtree_ids.iter().collect::<std::collections::HashSet<_>>();
518        let state = self.state.read().await;
519        state
520            .children
521            .iter()
522            .filter(|(id, _)| subtree_set.contains(id))
523            .filter_map(|(_, record)| {
524                record
525                    .child_controller
526                    .clone()
527                    .map(|controller| (controller, record.session_id.clone()))
528            })
529            .collect()
530    }
531
532    pub(super) async fn reopen_single(&self, target: &str) -> Result<bool> {
533        let child_controller = {
534            let mut state = self.state.write().await;
535            let record = state
536                .children
537                .get_mut(target)
538                .ok_or_else(|| anyhow!("Unknown subagent id {target}"))?;
539            anyhow::ensure!(!record.closing, "Subagent {target} is closing");
540            if !record.status.is_terminal() {
541                return Ok(false);
542            }
543            let prompt = record
544                .last_prompt
545                .clone()
546                .unwrap_or_else(|| "Continue the delegated task from the existing context.".to_string());
547            record.status = SubagentStatus::Queued;
548            record.closing = false;
549            record.updated_at = Utc::now();
550            record.completed_at = None;
551            record.error = None;
552            record.summary = None;
553            if record.queued_prompts.is_empty() {
554                record.queued_prompts.push_back(prompt);
555            }
556            record.child_controller.clone()
557        };
558        // Reopening a subtree reverses the transient `begin_close` on any
559        // child-scoped controller so a resumed child can delegate again (and
560        // its controller resumes saving background state).
561        if let Some(controller) = child_controller {
562            controller.end_close().await;
563        }
564        Ok(true)
565    }
566
567    async fn close_single(&self, target: &str) -> Result<SubagentStatusEntry> {
568        let mut pending = self.shutdown_handles.lock().await;
569        let mut state = self.state.write().await;
570        let record = state
571            .children
572            .get_mut(target)
573            .ok_or_else(|| anyhow!("Unknown subagent id {target}"))?;
574        if record.status == SubagentStatus::Closed {
575            return Ok(record.build_status_entry());
576        }
577        record.closing = true;
578        if let Some(handle) = record.handle.take() {
579            handle.abort();
580            anyhow::ensure!(pending.insert(target.to_owned(), handle).is_none(), "duplicate subagent handle");
581        }
582        drop(state);
583        if let Some(handle) = pending.get_mut(target) {
584            let result = wait_for_child_stop(handle, target).await;
585            pending.remove(target);
586            result?;
587        }
588        let mut state = self.state.write().await;
589        let record = state
590            .children
591            .get_mut(target)
592            .ok_or_else(|| anyhow!("Unknown subagent id {target}"))?;
593        record.status = SubagentStatus::Closed;
594        record.updated_at = Utc::now();
595        record.completed_at = Some(Utc::now());
596        record.notify.notify_waiters();
597        Ok(record.build_status_entry())
598    }
599
600    pub(super) async fn find_spec(&self, candidate: &str) -> Option<SubagentSpec> {
601        self.state
602            .read()
603            .await
604            .discovered
605            .effective
606            .iter()
607            .find(|spec| spec.is_subagent() && spec.matches_name(candidate))
608            .cloned()
609    }
610
611    pub(super) async fn resolve_requested_spec(&self, requested: Option<&str>) -> Result<SubagentSpec> {
612        let requested = requested.unwrap_or("default");
613        self.find_spec(requested)
614            .await
615            .ok_or_else(|| anyhow!("Unknown subagent type {requested}"))
616    }
617
618    async fn prepare_delegation_context(
619        &self,
620        requested_agent: Option<String>,
621        items: &mut Vec<SubagentInputItem>,
622        model: &mut Option<String>,
623        tool_name: &'static str,
624    ) -> Result<PreparedDelegationContext> {
625        let state = self.state.read().await;
626        sanitize_subagent_input_items(items);
627        *model = normalize_requested_model_override(model.take(), &state.turn_hints.current_input);
628        let requested_agent = if let Some(agent_type) = requested_agent {
629            Some(agent_type)
630        } else {
631            match state.turn_hints.explicit_mentions.as_slice() {
632                [] => None,
633                [single] => Some(single.clone()),
634                mentions => {
635                    bail!(
636                        "{} omitted agent_type, but the user explicitly selected multiple agents: {}. Specify agent_type explicitly.",
637                        tool_name,
638                        mentions.join(", ")
639                    );
640                }
641            }
642        };
643        Ok(PreparedDelegationContext {
644            requested_agent,
645            explicit_mentions: state.turn_hints.explicit_mentions.clone(),
646            explicit_request: state.turn_hints.explicit_request,
647        })
648    }
649
650    fn prepare_delegation_prompt(
651        &self,
652        spec: &SubagentSpec,
653        delegation: &PreparedDelegationContext,
654        message: Option<&str>,
655        items: &[SubagentInputItem],
656        tool_name: &'static str,
657        launch_phrase: &'static str,
658    ) -> Result<String> {
659        if let Some(explicit) = delegation.explicit_mentions.first()
660            && delegation.explicit_mentions.len() == 1
661            && !spec.matches_name(explicit)
662        {
663            bail!(
664                "{} requested agent_type '{}', but the user explicitly selected '{}'. Use the selected agent or ask the user to clarify.",
665                tool_name,
666                spec.name,
667                explicit
668            );
669        }
670        if !spec.is_read_only() && !delegation.explicit_request && delegation.requested_agent.is_none() {
671            bail!(
672                "{} cannot launch write-capable agent '{}' without an explicit delegation signal from the current user turn. Ask the user to mention the agent, say 'delegate'/'spawn', or request parallel work.",
673                tool_name,
674                spec.name
675            );
676        }
677        if spec.is_read_only() && !self.config.vt_cfg.subagents.auto_delegate_read_only && !delegation.explicit_request
678        {
679            bail!(
680                "{} cannot proactively launch read-only agent '{}' because `subagents.auto_delegate_read_only` is disabled and the current user turn did not explicitly request delegation.",
681                tool_name,
682                spec.name
683            );
684        }
685        let prompt = request_prompt(message, items)
686            .or_else(|| spec.initial_prompt.clone())
687            .filter(|value| !value.trim().is_empty())
688            .ok_or_else(|| anyhow!("{tool_name} requires a task message or items"))?;
689        if delegated_task_requires_clarification(&prompt) {
690            bail!(
691                "{} task for '{}' is too vague ('{}'). Ask the user for a specific delegated task before {}.",
692                tool_name,
693                spec.name,
694                prompt.trim(),
695                launch_phrase
696            );
697        }
698        Ok(prompt)
699    }
700
701    fn active_background_launch_conflicts(
702        record: &BackgroundRecord,
703        prompt: &str,
704        max_turns: Option<usize>,
705        model_override: Option<&str>,
706        reasoning_override: Option<&str>,
707    ) -> Vec<&'static str> {
708        let mut conflicts = Vec::new();
709        if record.prompt != prompt {
710            conflicts.push("prompt");
711        }
712        if record.max_turns != max_turns {
713            conflicts.push("max_turns");
714        }
715        if record.model_override.as_deref() != model_override {
716            conflicts.push("model");
717        }
718        if record.reasoning_override.as_deref() != reasoning_override {
719            conflicts.push("reasoning_effort");
720        }
721        conflicts
722    }
723
724    async fn spawn_with_spec(
725        &self,
726        spec: SubagentSpec,
727        prompt: String,
728        fork_context: bool,
729        background: bool,
730        max_turns: Option<usize>,
731        model_override: Option<String>,
732        reasoning_override: Option<String>,
733    ) -> Result<SubagentStatusEntry> {
734        if !self.config.vt_cfg.subagents.enabled {
735            bail!("Subagents are disabled by configuration");
736        }
737        if self.shutdown_requested.load(Ordering::Relaxed) || self.closing.load(Ordering::Relaxed) {
738            bail!("Subagent controller is shutting down; cannot spawn new subagents");
739        }
740        if self.config.depth.saturating_add(1) > self.config.vt_cfg.subagents.max_depth {
741            bail!("Subagent depth limit reached (max_depth={})", self.config.vt_cfg.subagents.max_depth);
742        }
743        if self.config.depth > 0 && spec.isolation == Some(vtcode_config::IsolationMode::Worktree) {
744            bail!(
745                "Subagent '{}' requests isolation=worktree, but nested worktree isolation is not supported \
746                 (child-scoped controllers operate inside the parent's worktree). Use isolation=worktree only \
747                 at the root delegation level.",
748                spec.name
749            );
750        }
751        let is_background_child = background;
752        let child_max_turns = normalize_background_child_max_turns(max_turns.or(spec.max_turns), is_background_child);
753        let (_, _, effective_config) = prepare_child_runtime_config(
754            &self.config.vt_cfg,
755            &spec,
756            self.config.parent_model.as_str(),
757            self.config.parent_provider.as_str(),
758            self.config.parent_reasoning_effort,
759            child_max_turns,
760            model_override.as_deref(),
761            reasoning_override.as_deref(),
762            !spec.is_read_only() && self.config.depth.saturating_add(2) <= self.config.vt_cfg.subagents.max_depth,
763            resolve_effective_subagent_model,
764        )?;
765
766        // Reserve admission before any side effect. The permit is owned by the
767        // launched task and is released on every launch-error/cancellation path.
768        let permit = Arc::clone(&self.admission)
769            .try_acquire_owned()
770            .context("Subagent concurrency limit reached")?;
771        let launch_id = uuid::Uuid::new_v4();
772        {
773            let state = self.state.read().await;
774            let active = state.children.values().filter(|record| !record.status.is_terminal()).count();
775            let cap = self.config.vt_cfg.subagents.max_concurrent.min(SUBAGENT_HARD_CONCURRENCY_LIMIT);
776            if active >= cap {
777                bail!("Subagent concurrency limit reached (max_concurrent={cap})");
778            }
779        }
780        self.ensure_ordinary_delegation_allowed()?;
781        // Create a worktree for isolation if requested.
782        let (mut worktree_guard, permit) = if spec.isolation == Some(vtcode_config::IsolationMode::Worktree) {
783            let workspace_root = self.config.workspace_root.clone();
784            let worktree_name = format!("{}-{launch_id}", sanitize_component(spec.name.as_str()));
785            let worktree_name_for_error = worktree_name.clone();
786            let worktree_result = tokio::task::spawn_blocking(move || {
787                let path = crate::git::WorktreeManager::new(&workspace_root).create(&worktree_name)?;
788                Ok::<_, anyhow::Error>(LaunchWorktree {
789                    root: workspace_root,
790                    name: worktree_name,
791                    path,
792                    permit: Some(permit),
793                    armed: true,
794                })
795            })
796            .await
797            .context("Worktree creation task panicked")?;
798            let mut guard = worktree_result
799                .with_context(|| format!("Failed to create worktree for subagent '{}'", worktree_name_for_error))?;
800            let permit = guard.permit.take().context("worktree launch reservation missing")?;
801            (Some(guard), permit)
802        } else {
803            (None, permit)
804        };
805        let worktree_path = worktree_guard.as_ref().map(|guard| guard.path.clone());
806
807        let id = format!("agent-{}-{launch_id}", sanitize_component(spec.name.as_str()));
808        let parent_session_id = self.parent_session_id.read().await.clone();
809        let session_id =
810            format!("{}-{}", sanitize_component(parent_session_id.as_str()), sanitize_component(id.as_str()));
811        let display_label = subagent_display_label(&spec);
812        let notify = Arc::new(Notify::new());
813        let mut state = self.state.write().await;
814        // Re-check the close gates while the write lock is held. The earlier
815        // check can race with a concurrent `close_tree` that snapshots and
816        // closes the subtree between this spawn's admission and its record
817        // insertion; checking after acquisition closes that window.
818        if self.shutdown_requested.load(Ordering::Relaxed) || self.closing.load(Ordering::Relaxed) {
819            drop(state);
820            self.remove_failed_launch_worktree(worktree_path.as_ref()).await?;
821            if let Some(guard) = worktree_guard.as_mut() {
822                guard.armed = false;
823            }
824            bail!("Subagent controller is shutting down; cannot spawn new subagents");
825        }
826        let initial_messages = if fork_context {
827            state.parent_messages.clone()
828        } else {
829            Vec::new()
830        };
831        let entry = ChildRecord {
832            id: id.clone(),
833            session_id,
834            parent_thread_id: parent_session_id,
835            spec: spec.clone(),
836            display_label,
837            status: SubagentStatus::Queued,
838            background: is_background_child,
839            depth: self.config.depth.saturating_add(1),
840            created_at: Utc::now(),
841            updated_at: Utc::now(),
842            completed_at: None,
843            summary: None,
844            error: None,
845            archive_metadata: None,
846            archive_path: None,
847            transcript_path: None,
848            effective_config: Some(effective_config),
849            stored_messages: initial_messages,
850            last_prompt: Some(prompt.clone()),
851            queued_prompts: VecDeque::from([prompt]),
852            max_turns: child_max_turns,
853            model_override,
854            reasoning_override,
855            thread_handle: None,
856            handle: None,
857            closing: false,
858            notify,
859            worktree_path,
860            child_controller: None,
861        };
862        state.children.insert(id.clone(), entry);
863        drop(state);
864
865        if let Err(error) = self.launch_child_reserved(id.as_str(), permit).await {
866            let worktree = self
867                .state
868                .write()
869                .await
870                .children
871                .remove(&id)
872                .and_then(|record| record.worktree_path);
873            self.remove_failed_launch_worktree(worktree.as_ref())
874                .await
875                .with_context(|| format!("launch failed: {error:#}; worktree rollback failed"))?;
876            if let Some(guard) = worktree_guard.as_mut() {
877                guard.armed = false;
878            }
879            return Err(error);
880        }
881        if let Some(guard) = worktree_guard.as_mut() {
882            guard.armed = false;
883        }
884        self.status_for(&id).await
885    }
886
887    async fn remove_failed_launch_worktree(&self, path: Option<&std::path::PathBuf>) -> Result<()> {
888        if let Some(path) = path {
889            let name = path
890                .file_name()
891                .and_then(|name| name.to_str())
892                .context("invalid owned worktree name")?
893                .to_owned();
894            let root = self.config.workspace_root.clone();
895            tokio::task::spawn_blocking(move || crate::git::WorktreeManager::new(root).remove(&name))
896                .await
897                .context("failed launch worktree cleanup panicked")??;
898        }
899        Ok(())
900    }
901
902    async fn restart_child(&self, target: &str) -> Result<()> {
903        let mut pending = self.shutdown_handles.lock().await;
904        let finishing_handle = {
905            let mut state = self.state.write().await;
906            let record = state
907                .children
908                .get_mut(target)
909                .ok_or_else(|| anyhow!("Unknown subagent id {target}"))?;
910            anyhow::ensure!(!record.closing, "Subagent {target} is closing");
911            if record.queued_prompts.is_empty()
912                && let Some(prompt) = record.last_prompt.clone()
913            {
914                record.queued_prompts.push_back(prompt);
915            }
916            if record.queued_prompts.is_empty() {
917                bail!("Subagent {target} has no queued input");
918            }
919            record.handle.take()
920        };
921        let launch_result = async {
922            // Abort schedules cancellation; await the owned launch before
923            // reserving its replacement's concurrency slot.
924            if let Some(handle) = finishing_handle {
925                anyhow::ensure!(pending.insert(target.to_owned(), handle).is_none(), "duplicate subagent handle");
926            }
927            if let Some(handle) = pending.get_mut(target) {
928                let result = wait_for_child_stop(handle, target).await;
929                pending.remove(target);
930                result?;
931            }
932            self.launch_child(target).await
933        }
934        .await;
935        if let Err(error) = &launch_result {
936            let mut state = self.state.write().await;
937            if let Some(record) = state.children.get_mut(target)
938                && record.status == SubagentStatus::Queued
939                && record.handle.as_ref().is_none_or(|handle| handle.is_finished())
940            {
941                record.status = SubagentStatus::Failed;
942                record.error = Some(format!("{error:#}"));
943                record.summary = None;
944                record.updated_at = Utc::now();
945                record.completed_at = Some(record.updated_at);
946                record.notify.notify_waiters();
947            }
948        }
949        launch_result
950    }
951}
952
953pub(super) fn finalize_background_launch(
954    record: &mut BackgroundRecord,
955    expected_exec_session_id: &str,
956    child_pid: Option<u32>,
957    started_at: Option<chrono::DateTime<Utc>>,
958    updated_at: chrono::DateTime<Utc>,
959) -> bool {
960    if record.exec_session_id != expected_exec_session_id
961        || !matches!(record.status, BackgroundSubprocessStatus::Starting)
962    {
963        return false;
964    }
965    record.pid = child_pid;
966    record.started_at = started_at;
967    record.status = BackgroundSubprocessStatus::Running;
968    record.updated_at = updated_at;
969    record.ended_at = None;
970    record.error = None;
971    record.summary = Some("Background subagent is running".to_string());
972    true
973}