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: 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 {
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            let nested = self_owned.nested_controllers_in_subtree(&subtree_ids).await;
347            // Mark every child-scoped controller in the subtree as closing so
348            // it rejects new grandchild spawns before we start aborting.
349            for (controller, _) in &nested {
350                controller.begin_close().await;
351            }
352            // Close the target's own subtree (deepest first) on this
353            // controller. Aborting the owning child's handle first stops it
354            // from spawning further descendants.
355            let subtree_ids_for_rescan = subtree_ids.clone();
356            for node_id in subtree_ids.into_iter().rev() {
357                self_owned.close_single(node_id.as_str()).await?;
358            }
359            // ...then recursively close each child-scoped controller's subtree.
360            // Grandchildren live in the child controller's state, not ours, so
361            // they are closed through that controller to keep node ownership
362            // correct. Only controllers of nodes inside the closed subtree are
363            // cascaded, so closing one subagent never kills a sibling's
364            // descendants.
365            for (controller, session_id) in nested {
366                let ids = controller.spawn_child_ids_for_parent(&session_id).await;
367                for id in ids {
368                    if let Err(err) = controller.close_tree(&id).await {
369                        tracing::warn!(node_id = id.as_str(), error = %err, "Failed to close nested subagent subtree");
370                    }
371                }
372            }
373            // A child may have attached a freshly created controller between
374            // the snapshot above and its handle abort. Re-scan and cascade
375            // again so no grandchild outlives the close; the second pass is a
376            // no-op in the common case because close_tree is idempotent.
377            let late = self_owned.nested_controllers_in_subtree(&subtree_ids_for_rescan).await;
378            for (controller, session_id) in late {
379                controller.begin_close().await;
380                let ids = controller.spawn_child_ids_for_parent(&session_id).await;
381                for id in ids {
382                    if let Err(err) = controller.close_tree(&id).await {
383                        tracing::warn!(node_id = id.as_str(), error = %err, "Failed to close late nested subagent subtree");
384                    }
385                }
386            }
387            self_owned.status_for(&target_owned).await
388        })
389    }
390
391    /// Blocks until one of the target subagents reaches a terminal state or the timeout expires.
392    pub async fn wait(&self, targets: &[String], timeout_ms: Option<u64>) -> Result<Option<SubagentStatusEntry>> {
393        for target in targets {
394            if let Ok(entry) = self.status_for(target).await
395                && entry.status.is_terminal()
396            {
397                return Ok(Some(entry));
398            }
399        }
400
401        let timeout = std::time::Duration::from_millis(
402            timeout_ms.unwrap_or_else(|| self.config.vt_cfg.subagents.default_timeout_seconds.saturating_mul(1000)),
403        );
404        let deadline = tokio::time::Instant::now() + timeout;
405
406        loop {
407            // Collect notify handles from child records.
408            let notifies = {
409                let state = self.state.read().await;
410                targets
411                    .iter()
412                    .filter_map(|target| state.children.get(target).map(|record| record.notify.clone()))
413                    .collect::<Vec<_>>()
414            };
415            if notifies.is_empty() {
416                return Ok(None);
417            }
418
419            // Register notified() futures BEFORE checking terminal status.
420            // This prevents a Tokio Notify race condition: if apply_result()
421            // calls notify_waiters() between a status check and future
422            // creation, the notification is permanently lost. By registering
423            // futures first, any concurrent notification either:
424            //   (a) arrives before we poll the future → stored as a permit,
425            //       select! returns immediately, loop re-checks status, or
426            //   (b) arrives after we start waiting → wakes the future normally.
427            let wait_any = select_all(
428                notifies
429                    .into_iter()
430                    .map(|notify| Box::pin(async move { notify.notified().await }))
431                    .collect::<Vec<_>>(),
432            );
433            tokio::pin!(wait_any);
434
435            // Now check if any target is already terminal.
436            for target in targets {
437                if let Ok(entry) = self.status_for(target).await
438                    && entry.status.is_terminal()
439                {
440                    return Ok(Some(entry));
441                }
442            }
443
444            let sleep = tokio::time::sleep_until(deadline);
445            tokio::pin!(sleep);
446
447            tokio::select! {
448                _ = &mut sleep => return Ok(None),
449                _ = &mut wait_any => {}
450            }
451        }
452    }
453
454    /// Returns the current status of a tracked subagent by its target id.
455    pub async fn status_for(&self, target: &str) -> Result<SubagentStatusEntry> {
456        let state = self.state.read().await;
457        let record = state
458            .children
459            .get(target)
460            .ok_or_else(|| anyhow!("Unknown subagent id {target}"))?;
461        Ok(record.build_status_entry())
462    }
463
464    pub(super) async fn spawn_child_ids_for_parent(&self, parent_thread_id: &str) -> Vec<String> {
465        let state = self.state.read().await;
466        let mut child_ids = state
467            .children
468            .values()
469            .filter(|record| record.parent_thread_id == parent_thread_id)
470            .map(|record| record.id.clone())
471            .collect::<Vec<_>>();
472        child_ids.sort();
473        child_ids
474    }
475
476    pub(super) async fn collect_spawn_subtree_ids(&self, root_thread_id: &str) -> Result<Vec<String>> {
477        let mut subtree_ids = Vec::new();
478        let mut stack = vec![root_thread_id.to_string()];
479
480        while let Some(thread_id) = stack.pop() {
481            subtree_ids.push(thread_id.clone());
482            let child_ids = self.spawn_child_ids_for_parent(&thread_id).await;
483            for child_id in child_ids.into_iter().rev() {
484                stack.push(child_id);
485            }
486        }
487
488        Ok(subtree_ids)
489    }
490
491    /// Collects the child-scoped controllers owned by records inside `subtree_ids`,
492    /// paired with each owning record's session id. Shared by `resume_tree` and
493    /// `close_tree` so subtree isolation cannot diverge between them.
494    async fn nested_controllers_in_subtree(&self, subtree_ids: &[String]) -> Vec<(Arc<SubagentController>, String)> {
495        let subtree_set = subtree_ids.iter().collect::<std::collections::HashSet<_>>();
496        let state = self.state.read().await;
497        state
498            .children
499            .iter()
500            .filter(|(id, _)| subtree_set.contains(id))
501            .filter_map(|(_, record)| {
502                record
503                    .child_controller
504                    .clone()
505                    .map(|controller| (controller, record.session_id.clone()))
506            })
507            .collect()
508    }
509
510    pub(super) async fn reopen_single(&self, target: &str) -> Result<bool> {
511        let child_controller = {
512            let mut state = self.state.write().await;
513            let record = state
514                .children
515                .get_mut(target)
516                .ok_or_else(|| anyhow!("Unknown subagent id {target}"))?;
517            if !record.status.is_terminal() {
518                return Ok(false);
519            }
520            let prompt = record
521                .last_prompt
522                .clone()
523                .unwrap_or_else(|| "Continue the delegated task from the existing context.".to_string());
524            record.status = SubagentStatus::Queued;
525            record.updated_at = Utc::now();
526            record.completed_at = None;
527            record.error = None;
528            record.summary = None;
529            if record.queued_prompts.is_empty() {
530                record.queued_prompts.push_back(prompt);
531            }
532            record.child_controller.clone()
533        };
534        // Reopening a subtree reverses the transient `begin_close` on any
535        // child-scoped controller so a resumed child can delegate again (and
536        // its controller resumes saving background state).
537        if let Some(controller) = child_controller {
538            controller.end_close().await;
539        }
540        Ok(true)
541    }
542
543    async fn close_single(&self, target: &str) -> Result<SubagentStatusEntry> {
544        let mut state = self.state.write().await;
545        let record = state
546            .children
547            .get_mut(target)
548            .ok_or_else(|| anyhow!("Unknown subagent id {target}"))?;
549        if record.status == SubagentStatus::Closed {
550            return Ok(record.build_status_entry());
551        }
552        let handle = record.handle.take();
553        if let Some(handle) = handle.as_ref() {
554            handle.abort();
555        }
556        record.status = SubagentStatus::Closed;
557        record.updated_at = Utc::now();
558        record.completed_at = Some(Utc::now());
559        record.notify.notify_waiters();
560        let entry = record.build_status_entry();
561        drop(state);
562        if let Some(handle) = handle {
563            wait_for_child_stop(handle, target).await?;
564        }
565        Ok(entry)
566    }
567
568    pub(super) async fn find_spec(&self, candidate: &str) -> Option<SubagentSpec> {
569        self.state
570            .read()
571            .await
572            .discovered
573            .effective
574            .iter()
575            .find(|spec| spec.is_subagent() && spec.matches_name(candidate))
576            .cloned()
577    }
578
579    pub(super) async fn resolve_requested_spec(&self, requested: Option<&str>) -> Result<SubagentSpec> {
580        let requested = requested.unwrap_or("default");
581        self.find_spec(requested)
582            .await
583            .ok_or_else(|| anyhow!("Unknown subagent type {requested}"))
584    }
585
586    async fn prepare_delegation_context(
587        &self,
588        requested_agent: Option<String>,
589        items: &mut Vec<SubagentInputItem>,
590        model: &mut Option<String>,
591        tool_name: &'static str,
592    ) -> Result<PreparedDelegationContext> {
593        let state = self.state.read().await;
594        sanitize_subagent_input_items(items);
595        *model = normalize_requested_model_override(model.take(), &state.turn_hints.current_input);
596        let requested_agent = if let Some(agent_type) = requested_agent {
597            Some(agent_type)
598        } else {
599            match state.turn_hints.explicit_mentions.as_slice() {
600                [] => None,
601                [single] => Some(single.clone()),
602                mentions => {
603                    bail!(
604                        "{} omitted agent_type, but the user explicitly selected multiple agents: {}. Specify agent_type explicitly.",
605                        tool_name,
606                        mentions.join(", ")
607                    );
608                }
609            }
610        };
611        Ok(PreparedDelegationContext {
612            requested_agent,
613            explicit_mentions: state.turn_hints.explicit_mentions.clone(),
614            explicit_request: state.turn_hints.explicit_request,
615        })
616    }
617
618    fn prepare_delegation_prompt(
619        &self,
620        spec: &SubagentSpec,
621        delegation: &PreparedDelegationContext,
622        message: Option<&str>,
623        items: &[SubagentInputItem],
624        tool_name: &'static str,
625        launch_phrase: &'static str,
626    ) -> Result<String> {
627        if let Some(explicit) = delegation.explicit_mentions.first()
628            && delegation.explicit_mentions.len() == 1
629            && !spec.matches_name(explicit)
630        {
631            bail!(
632                "{} requested agent_type '{}', but the user explicitly selected '{}'. Use the selected agent or ask the user to clarify.",
633                tool_name,
634                spec.name,
635                explicit
636            );
637        }
638        if !spec.is_read_only() && !delegation.explicit_request && delegation.requested_agent.is_none() {
639            bail!(
640                "{} 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.",
641                tool_name,
642                spec.name
643            );
644        }
645        if spec.is_read_only() && !self.config.vt_cfg.subagents.auto_delegate_read_only && !delegation.explicit_request
646        {
647            bail!(
648                "{} cannot proactively launch read-only agent '{}' because `subagents.auto_delegate_read_only` is disabled and the current user turn did not explicitly request delegation.",
649                tool_name,
650                spec.name
651            );
652        }
653        let prompt = request_prompt(message, items)
654            .or_else(|| spec.initial_prompt.clone())
655            .filter(|value| !value.trim().is_empty())
656            .ok_or_else(|| anyhow!("{tool_name} requires a task message or items"))?;
657        if delegated_task_requires_clarification(&prompt) {
658            bail!(
659                "{} task for '{}' is too vague ('{}'). Ask the user for a specific delegated task before {}.",
660                tool_name,
661                spec.name,
662                prompt.trim(),
663                launch_phrase
664            );
665        }
666        Ok(prompt)
667    }
668
669    fn active_background_launch_conflicts(
670        record: &BackgroundRecord,
671        prompt: &str,
672        max_turns: Option<usize>,
673        model_override: Option<&str>,
674        reasoning_override: Option<&str>,
675    ) -> Vec<&'static str> {
676        let mut conflicts = Vec::new();
677        if record.prompt != prompt {
678            conflicts.push("prompt");
679        }
680        if record.max_turns != max_turns {
681            conflicts.push("max_turns");
682        }
683        if record.model_override.as_deref() != model_override {
684            conflicts.push("model");
685        }
686        if record.reasoning_override.as_deref() != reasoning_override {
687            conflicts.push("reasoning_effort");
688        }
689        conflicts
690    }
691
692    async fn spawn_with_spec(
693        &self,
694        spec: SubagentSpec,
695        prompt: String,
696        fork_context: bool,
697        background: bool,
698        max_turns: Option<usize>,
699        model_override: Option<String>,
700        reasoning_override: Option<String>,
701    ) -> Result<SubagentStatusEntry> {
702        if !self.config.vt_cfg.subagents.enabled {
703            bail!("Subagents are disabled by configuration");
704        }
705        if self.shutdown_requested.load(Ordering::Relaxed) || self.closing.load(Ordering::Relaxed) {
706            bail!("Subagent controller is shutting down; cannot spawn new subagents");
707        }
708        if self.config.depth.saturating_add(1) > self.config.vt_cfg.subagents.max_depth {
709            bail!("Subagent depth limit reached (max_depth={})", self.config.vt_cfg.subagents.max_depth);
710        }
711        if self.config.depth > 0 && spec.isolation == Some(vtcode_config::IsolationMode::Worktree) {
712            bail!(
713                "Subagent '{}' requests isolation=worktree, but nested worktree isolation is not supported \
714                 (child-scoped controllers operate inside the parent's worktree). Use isolation=worktree only \
715                 at the root delegation level.",
716                spec.name
717            );
718        }
719        let is_background_child = background;
720        let child_max_turns = normalize_background_child_max_turns(max_turns.or(spec.max_turns), is_background_child);
721        let (_, _, effective_config) = prepare_child_runtime_config(
722            &self.config.vt_cfg,
723            &spec,
724            self.config.parent_model.as_str(),
725            self.config.parent_provider.as_str(),
726            self.config.parent_reasoning_effort,
727            child_max_turns,
728            model_override.as_deref(),
729            reasoning_override.as_deref(),
730            !spec.is_read_only() && self.config.depth.saturating_add(2) <= self.config.vt_cfg.subagents.max_depth,
731            resolve_effective_subagent_model,
732        )?;
733
734        // Reserve admission before any side effect. The permit is owned by the
735        // launched task and is released on every launch-error/cancellation path.
736        let permit = Arc::clone(&self.admission)
737            .try_acquire_owned()
738            .context("Subagent concurrency limit reached")?;
739        let launch_id = uuid::Uuid::new_v4();
740        {
741            let state = self.state.read().await;
742            let active = state.children.values().filter(|record| !record.status.is_terminal()).count();
743            let cap = self.config.vt_cfg.subagents.max_concurrent.min(SUBAGENT_HARD_CONCURRENCY_LIMIT);
744            if active >= cap {
745                bail!("Subagent concurrency limit reached (max_concurrent={cap})");
746            }
747        }
748        self.ensure_ordinary_delegation_allowed()?;
749        // Create a worktree for isolation if requested.
750        let (mut worktree_guard, permit) = if spec.isolation == Some(vtcode_config::IsolationMode::Worktree) {
751            let workspace_root = self.config.workspace_root.clone();
752            let worktree_name = format!("{}-{launch_id}", sanitize_component(spec.name.as_str()));
753            let worktree_name_for_error = worktree_name.clone();
754            let worktree_result = tokio::task::spawn_blocking(move || {
755                let path = crate::git::WorktreeManager::new(&workspace_root).create(&worktree_name)?;
756                Ok::<_, anyhow::Error>(LaunchWorktree {
757                    root: workspace_root,
758                    name: worktree_name,
759                    path,
760                    permit: Some(permit),
761                    armed: true,
762                })
763            })
764            .await
765            .context("Worktree creation task panicked")?;
766            let mut guard = worktree_result
767                .with_context(|| format!("Failed to create worktree for subagent '{}'", worktree_name_for_error))?;
768            let permit = guard.permit.take().context("worktree launch reservation missing")?;
769            (Some(guard), permit)
770        } else {
771            (None, permit)
772        };
773        let worktree_path = worktree_guard.as_ref().map(|guard| guard.path.clone());
774
775        let id = format!("agent-{}-{launch_id}", sanitize_component(spec.name.as_str()));
776        let parent_session_id = self.parent_session_id.read().await.clone();
777        let session_id =
778            format!("{}-{}", sanitize_component(parent_session_id.as_str()), sanitize_component(id.as_str()));
779        let display_label = subagent_display_label(&spec);
780        let notify = Arc::new(Notify::new());
781        let mut state = self.state.write().await;
782        // Re-check the close gates while the write lock is held. The earlier
783        // check can race with a concurrent `close_tree` that snapshots and
784        // closes the subtree between this spawn's admission and its record
785        // insertion; checking after acquisition closes that window.
786        if self.shutdown_requested.load(Ordering::Relaxed) || self.closing.load(Ordering::Relaxed) {
787            drop(state);
788            self.remove_failed_launch_worktree(worktree_path.as_ref()).await?;
789            if let Some(guard) = worktree_guard.as_mut() {
790                guard.armed = false;
791            }
792            bail!("Subagent controller is shutting down; cannot spawn new subagents");
793        }
794        let initial_messages = if fork_context {
795            state.parent_messages.clone()
796        } else {
797            Vec::new()
798        };
799        let entry = ChildRecord {
800            id: id.clone(),
801            session_id,
802            parent_thread_id: parent_session_id,
803            spec: spec.clone(),
804            display_label,
805            status: SubagentStatus::Queued,
806            background: is_background_child,
807            depth: self.config.depth.saturating_add(1),
808            created_at: Utc::now(),
809            updated_at: Utc::now(),
810            completed_at: None,
811            summary: None,
812            error: None,
813            archive_metadata: None,
814            archive_path: None,
815            transcript_path: None,
816            effective_config: Some(effective_config),
817            stored_messages: initial_messages,
818            last_prompt: Some(prompt.clone()),
819            queued_prompts: VecDeque::from([prompt]),
820            max_turns: child_max_turns,
821            model_override,
822            reasoning_override,
823            thread_handle: None,
824            handle: None,
825            notify,
826            worktree_path,
827            child_controller: None,
828        };
829        state.children.insert(id.clone(), entry);
830        drop(state);
831
832        if let Err(error) = self.launch_child_reserved(id.as_str(), permit).await {
833            let worktree = self
834                .state
835                .write()
836                .await
837                .children
838                .remove(&id)
839                .and_then(|record| record.worktree_path);
840            self.remove_failed_launch_worktree(worktree.as_ref())
841                .await
842                .with_context(|| format!("launch failed: {error:#}; worktree rollback failed"))?;
843            if let Some(guard) = worktree_guard.as_mut() {
844                guard.armed = false;
845            }
846            return Err(error);
847        }
848        if let Some(guard) = worktree_guard.as_mut() {
849            guard.armed = false;
850        }
851        self.status_for(&id).await
852    }
853
854    async fn remove_failed_launch_worktree(&self, path: Option<&std::path::PathBuf>) -> Result<()> {
855        if let Some(path) = path {
856            let name = path
857                .file_name()
858                .and_then(|name| name.to_str())
859                .context("invalid owned worktree name")?
860                .to_owned();
861            let root = self.config.workspace_root.clone();
862            tokio::task::spawn_blocking(move || crate::git::WorktreeManager::new(root).remove(&name))
863                .await
864                .context("failed launch worktree cleanup panicked")??;
865        }
866        Ok(())
867    }
868
869    async fn restart_child(&self, target: &str) -> Result<()> {
870        let finishing_handle = {
871            let mut state = self.state.write().await;
872            let record = state
873                .children
874                .get_mut(target)
875                .ok_or_else(|| anyhow!("Unknown subagent id {target}"))?;
876            if record.queued_prompts.is_empty()
877                && let Some(prompt) = record.last_prompt.clone()
878            {
879                record.queued_prompts.push_back(prompt);
880            }
881            if record.queued_prompts.is_empty() {
882                bail!("Subagent {target} has no queued input");
883            }
884            record.handle.take()
885        };
886        let launch_result = async {
887            // Abort schedules cancellation; await the owned launch before
888            // reserving its replacement's concurrency slot.
889            if let Some(handle) = finishing_handle {
890                wait_for_child_stop(handle, target).await?;
891            }
892            self.launch_child(target).await
893        }
894        .await;
895        if let Err(error) = &launch_result {
896            let mut state = self.state.write().await;
897            if let Some(record) = state.children.get_mut(target)
898                && record.status == SubagentStatus::Queued
899                && record.handle.as_ref().is_none_or(|handle| handle.is_finished())
900            {
901                record.status = SubagentStatus::Failed;
902                record.error = Some(format!("{error:#}"));
903                record.summary = None;
904                record.updated_at = Utc::now();
905                record.completed_at = Some(record.updated_at);
906                record.notify.notify_waiters();
907            }
908        }
909        launch_result
910    }
911}
912
913pub(super) fn finalize_background_launch(
914    record: &mut BackgroundRecord,
915    expected_exec_session_id: &str,
916    child_pid: Option<u32>,
917    started_at: Option<chrono::DateTime<Utc>>,
918    updated_at: chrono::DateTime<Utc>,
919) -> bool {
920    if record.exec_session_id != expected_exec_session_id
921        || !matches!(record.status, BackgroundSubprocessStatus::Starting)
922    {
923        return false;
924    }
925    record.pid = child_pid;
926    record.started_at = started_at;
927    record.status = BackgroundSubprocessStatus::Running;
928    record.updated_at = updated_at;
929    record.ended_at = None;
930    record.error = None;
931    record.summary = Some("Background subagent is running".to_string());
932    true
933}