Skip to main content

vtcode_core/subagents/
mod.rs

1#![allow(
2    unused_imports,
3    reason = "Intentional compatibility, platform, or test-only suppression."
4)]
5// ─── Module Structure ───────────────────────────────────────────────────────
6
7mod background;
8mod config;
9mod constants;
10mod discovery;
11pub mod matrix;
12mod model;
13mod prompt;
14mod types;
15
16// ─── Re-exports ─────────────────────────────────────────────────────────────
17
18pub use background::{
19    background_record_id, build_background_subagent_command, extract_tail_lines, load_archive_preview,
20    subagent_display_label,
21};
22pub(crate) use config::inline_mcp_provider;
23pub use config::{
24    ResolvedAgentRuntimeView, build_child_config, compose_subagent_instructions, filter_child_tools,
25    normalize_background_child_max_turns, normalize_child_max_turns, prepare_child_runtime_config,
26};
27pub use discovery::discover_controller_subagents;
28pub use model::{
29    agent_type_for_spec, load_memory_appendix, load_memory_appendix_async, load_primary_memory_appendix,
30    load_primary_memory_appendix_async,
31};
32pub use prompt::{
33    contains_explicit_delegation_request, contains_explicit_model_request, delegated_task_requires_clarification,
34    extract_explicit_agent_mentions, normalize_requested_model_override, request_prompt, sanitize_subagent_input_items,
35};
36pub use types::{
37    BackgroundCompletionEvent, BackgroundRecord, BackgroundSubprocessEntry, BackgroundSubprocessSnapshot,
38    BackgroundSubprocessStatus, ChildRecord, ChildRunResult, ControllerState, PersistedBackgroundRecord,
39    PersistedBackgroundState, SendInputRequest, SpawnAgentRequest, SpawnBackgroundSubprocessRequest,
40    StatusEntryBuilder, SubagentInputItem, SubagentStatus, SubagentStatusEntry, SubagentThreadSnapshot,
41    TurnDelegationHints,
42};
43
44// VerificationResult is defined in this module (below) and re-exported at the
45// crate root via `pub use subagents::VerificationResult`.
46
47// ─── Public Utilities ───────────────────────────────────────────────────────
48
49/// Returns `true` if `name` is one of the reserved subagent-internal tool names.
50pub fn is_subagent_tool(name: &str) -> bool {
51    SUBAGENT_TOOL_NAMES.contains(&name)
52}
53
54#[derive(Clone, Default)]
55pub(super) struct BackgroundLaunchOverrides {
56    prompt: Option<String>,
57    max_turns: Option<usize>,
58    model_override: Option<String>,
59    reasoning_override: Option<String>,
60}
61
62#[derive(Clone, Default)]
63pub(super) struct PreparedDelegationContext {
64    requested_agent: Option<String>,
65    explicit_mentions: Vec<String>,
66    explicit_request: bool,
67}
68
69/// Result of a propose/verify cycle.
70///
71/// Returned by [`SubagentController::verify_proposed_change`]. The caller
72/// inspects `approved` to decide whether to commit or retry the mutation.
73#[derive(Debug, Clone)]
74pub struct VerificationResult {
75    /// Whether the verifier approved the change.
76    pub approved: bool,
77    /// Concrete issues identified by the verifier (empty if approved).
78    pub issues: Vec<String>,
79    /// Free-text reasoning from the verifier.
80    pub reasoning: String,
81}
82
83// ─── Controller ─────────────────────────────────────────────────────────────
84
85use anyhow::{Context, Result, anyhow, bail};
86use chrono::Utc;
87use futures::future::select_all;
88use parking_lot::Mutex as ParkingMutex;
89use std::collections::VecDeque;
90use std::path::PathBuf;
91use std::sync::Arc;
92use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
93use tokio::sync::{Mutex, Notify, RwLock, broadcast};
94use tokio::task::JoinHandle;
95use tokio_util::sync::CancellationToken;
96
97use crate::config::VTCodeConfig;
98use crate::config::types::ReasoningEffortLevel;
99use crate::core::agent::runner::{AgentRunner, RunnerSettings};
100use crate::core::agent::task::Task;
101use crate::core::threads::{ThreadBootstrap, ThreadId, ThreadRuntimeHandle, ThreadSnapshot};
102use crate::hooks::{LifecycleHookEngine, SessionStartTrigger};
103use crate::llm::provider::Message;
104use crate::tools::exec_session::ExecSessionManager;
105use crate::tools::pty::{PtyManager, PtySize};
106use crate::utils::session_archive::{SessionArchive, find_session_by_identifier};
107use vtcode_config::SubagentSpec;
108use vtcode_config::auth::OpenAIChatGptAuthHandle;
109
110use self::background::*;
111use self::config::*;
112use self::constants::*;
113use self::model::*;
114use vtcode_config::subagents::SUBAGENT_HARD_CONCURRENCY_LIMIT;
115
116const BACKGROUND_COMPLETION_CHANNEL_CAPACITY: usize = 64;
117
118/// Upper bound on remembered background-completion identities.
119///
120/// A session outlives any single completion, so the dedupe memo must not grow
121/// unboundedly. Redelivery can only arrive from the live broadcast channel (a
122/// retained, not-yet-drained copy), so remembering roughly four times that
123/// channel's capacity preserves the whole replay window while keeping memory
124/// flat. Shared by the subagent controller and the run loop's
125/// `PendingBackgroundCompletions`.
126pub const BACKGROUND_COMPLETION_IDENTITY_CAPACITY: usize = 256;
127
128struct BackgroundCompletionChannel {
129    sender: broadcast::Sender<BackgroundCompletionEvent>,
130    parent_sender: broadcast::Sender<BackgroundCompletionEvent>,
131    pending_parent_events: VecDeque<BackgroundCompletionEvent>,
132    parent_subscribed: bool,
133}
134
135impl BackgroundCompletionChannel {
136    fn new() -> Self {
137        let (sender, _) = broadcast::channel(BACKGROUND_COMPLETION_CHANNEL_CAPACITY);
138        let (parent_sender, _) = broadcast::channel(BACKGROUND_COMPLETION_CHANNEL_CAPACITY);
139        Self {
140            sender,
141            parent_sender,
142            pending_parent_events: VecDeque::new(),
143            parent_subscribed: false,
144        }
145    }
146
147    fn subscribe(&self) -> broadcast::Receiver<BackgroundCompletionEvent> {
148        self.sender.subscribe()
149    }
150
151    fn subscribe_parent(&mut self) -> (broadcast::Receiver<BackgroundCompletionEvent>, bool) {
152        let receiver = self.parent_sender.subscribe();
153        self.parent_subscribed = true;
154        let replayed = !self.pending_parent_events.is_empty();
155        while let Some(event) = self.pending_parent_events.pop_front() {
156            let _ = self.parent_sender.send(event);
157        }
158        (receiver, replayed)
159    }
160
161    fn publish(&mut self, event: BackgroundCompletionEvent) {
162        if !self.parent_subscribed {
163            if self.pending_parent_events.len() >= BACKGROUND_COMPLETION_CHANNEL_CAPACITY {
164                self.pending_parent_events.pop_front();
165                tracing::warn!(
166                    capacity = BACKGROUND_COMPLETION_CHANNEL_CAPACITY,
167                    "Dropping oldest undelivered parent background completion"
168                );
169            }
170            self.pending_parent_events.push_back(event.clone());
171        } else {
172            let _ = self.parent_sender.send(event.clone());
173        }
174        let _ = self.sender.send(event);
175    }
176}
177
178// ─── Controller Config ─────────────────────────────────────────────────────
179
180/// Configuration required to construct a [`SubagentController`].
181#[derive(Clone)]
182pub struct SubagentControllerConfig {
183    /// Workspace root directory for the session.
184    pub workspace_root: PathBuf,
185    /// Session identifier of the parent agent.
186    pub parent_session_id: String,
187    /// Model identifier used by the parent agent.
188    pub parent_model: String,
189    /// Provider name used by the parent agent.
190    pub parent_provider: String,
191    /// Reasoning effort level of the parent agent.
192    pub parent_reasoning_effort: ReasoningEffortLevel,
193    /// API key for LLM provider access.
194    pub api_key: String,
195    /// Full VT Code configuration.
196    pub vt_cfg: VTCodeConfig,
197    /// Optional OpenAI ChatGPT authentication handle.
198    pub openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
199    /// Current nesting depth of the subagent hierarchy.
200    pub depth: usize,
201    /// Whether the subagent lifecycle engine must be workspace-gated. Mirrors
202    /// the main-session rule: pass `true` whenever workspace-controlled hook
203    /// content is present (workspace vtcode.toml/.vtcode layers OR a primary
204    /// agent spec contributing workspace-controlled hooks). Failing to gate
205    /// here would let workspace hooks run without user approval in a
206    /// subagent context.
207    pub workspace_gated: bool,
208    /// Manager for exec sessions (PTY and pipe).
209    pub exec_sessions: ExecSessionManager,
210    /// PTY session manager.
211    pub pty_manager: PtyManager,
212    /// Whether this controller manages a background runtime subprocess.
213    pub managed_background_runtime: bool,
214}
215
216/// Central controller that manages spawning, lifecycle, and state of all subagents.
217/// The background completion monitor is cancelled when the final controller
218/// owner is dropped; its task-held clone is intentionally non-owning.
219pub struct SubagentController {
220    admission: Arc<tokio::sync::Semaphore>,
221    matrix: Arc<matrix::MatrixRuntime>,
222    config: Arc<SubagentControllerConfig>,
223    parent_session_id: Arc<RwLock<String>>,
224    lifecycle_hooks: Option<LifecycleHookEngine>,
225    state: Arc<RwLock<ControllerState>>,
226    shutdown_requested: Arc<AtomicBool>,
227    /// Transient close-in-progress flag. Unlike `shutdown_requested` this is
228    /// cleared when a subtree is reopened via `reopen_single`, so a resumed
229    /// child can delegate again and its controller keeps saving background
230    /// state. Set only while `close_tree`/`signal_shutdown` are tearing a
231    /// subtree down.
232    closing: Arc<AtomicBool>,
233    background_completion_channel: Arc<ParkingMutex<BackgroundCompletionChannel>>,
234    background_completion_notify: Arc<Notify>,
235    background_completion_shutdown: CancellationToken,
236    background_completion_monitor: Arc<Mutex<Option<JoinHandle<()>>>>,
237    /// Aborted child tasks remain owned until shutdown has observed their exit.
238    shutdown_handles: Arc<Mutex<std::collections::BTreeMap<String, JoinHandle<()>>>>,
239    /// Counts controller clones that participate in monitor ownership.
240    background_completion_owners: Arc<AtomicUsize>,
241    /// The monitor task retains a clone for processing but must not keep the
242    /// monitor alive after all external controller owners are gone.
243    background_completion_monitor_owner: bool,
244}
245
246impl Clone for SubagentController {
247    fn clone(&self) -> Self {
248        self.background_completion_owners.fetch_add(1, Ordering::Relaxed);
249        Self {
250            admission: Arc::clone(&self.admission),
251            matrix: Arc::clone(&self.matrix),
252            config: Arc::clone(&self.config),
253            parent_session_id: Arc::clone(&self.parent_session_id),
254            lifecycle_hooks: self.lifecycle_hooks.clone(),
255            state: Arc::clone(&self.state),
256            shutdown_requested: Arc::clone(&self.shutdown_requested),
257            closing: Arc::clone(&self.closing),
258            background_completion_channel: Arc::clone(&self.background_completion_channel),
259            background_completion_notify: Arc::clone(&self.background_completion_notify),
260            background_completion_shutdown: self.background_completion_shutdown.clone(),
261            background_completion_monitor: Arc::clone(&self.background_completion_monitor),
262            shutdown_handles: Arc::clone(&self.shutdown_handles),
263            background_completion_owners: Arc::clone(&self.background_completion_owners),
264            background_completion_monitor_owner: true,
265        }
266    }
267}
268
269impl Drop for SubagentController {
270    fn drop(&mut self) {
271        if !self.background_completion_monitor_owner
272            || self.background_completion_owners.fetch_sub(1, Ordering::AcqRel) != 1
273        {
274            return;
275        }
276
277        self.background_completion_shutdown.cancel();
278        if let Ok(mut monitor_slot) = self.background_completion_monitor.try_lock()
279            && let Some(monitor) = monitor_slot.take()
280        {
281            monitor.abort();
282        }
283    }
284}
285
286impl SubagentController {
287    /// Creates a new controller, discovering subagent specs and loading persisted background state.
288    pub async fn new(config: SubagentControllerConfig) -> Result<Self> {
289        let discovered = discover_controller_subagents(&config.workspace_root).await?;
290        // Box the inner constructor: it carries `VTCodeConfig` + spec state
291        // across awaits, which would otherwise bloat every `new` caller's
292        // async frame past the `large_futures` budget (denied in test builds).
293        Box::pin(Self::new_with_discovered(config, discovered)).await
294    }
295
296    /// Creates a new controller reusing an already-discovered spec set.
297    ///
298    /// Interactive startup discovers specs once on the first-paint path;
299    /// hydration passes that result here to skip a second workspace/plugin
300    /// filesystem scan. Behavior matches [`Self::new`] otherwise.
301    pub async fn new_with_discovered(
302        config: SubagentControllerConfig,
303        discovered: vtcode_config::DiscoveredSubagents,
304    ) -> Result<Self> {
305        let workspace_gated = config.workspace_gated;
306        let lifecycle_hooks = LifecycleHookEngine::new_with_session_gated(
307            config.workspace_root.clone(),
308            &config.vt_cfg.hooks,
309            SessionStartTrigger::Startup,
310            config.parent_session_id.clone(),
311            workspace_gated,
312        )?;
313        if let Some(engine) = lifecycle_hooks.as_ref() {
314            crate::hooks::lifecycle::restore_workspace_hook_approval(engine, &config.workspace_root).await;
315        }
316        let background_children = load_background_state(&config.workspace_root)
317            .await?
318            .records
319            .into_iter()
320            .map(|record| (record.id.clone(), BackgroundRecord::from_persisted(record)))
321            .collect();
322        let controller = Self {
323            admission: Arc::new(tokio::sync::Semaphore::new(
324                config.vt_cfg.subagents.max_concurrent.min(SUBAGENT_HARD_CONCURRENCY_LIMIT),
325            )),
326            matrix: Arc::new(matrix::MatrixRuntime::default()),
327            parent_session_id: Arc::new(RwLock::new(config.parent_session_id.clone())),
328            lifecycle_hooks,
329            config: Arc::new(config),
330            state: Arc::new(RwLock::new(ControllerState {
331                discovered,
332                parent_messages: Vec::new(),
333                turn_hints: TurnDelegationHints::default(),
334                children: std::collections::BTreeMap::new(),
335                background_children,
336                background_completion_identities: VecDeque::new(),
337            })),
338            shutdown_requested: Arc::new(AtomicBool::new(false)),
339            closing: Arc::new(AtomicBool::new(false)),
340            background_completion_channel: Arc::new(ParkingMutex::new(BackgroundCompletionChannel::new())),
341            background_completion_notify: Arc::new(Notify::new()),
342            background_completion_shutdown: CancellationToken::new(),
343            background_completion_monitor: Arc::new(Mutex::new(None)),
344            shutdown_handles: Arc::new(Mutex::new(std::collections::BTreeMap::new())),
345            background_completion_owners: Arc::new(AtomicUsize::new(1)),
346            background_completion_monitor_owner: true,
347        };
348        controller.start_background_completion_monitor().await;
349        Ok(controller)
350    }
351
352    /// Subscribes to terminal notifications for managed background subprocesses.
353    pub fn subscribe_background_completions(&self) -> broadcast::Receiver<BackgroundCompletionEvent> {
354        self.background_completion_channel.lock().subscribe()
355    }
356
357    /// Subscribes the parent run loop and replays completions that arrived
358    /// before its receiver was installed.
359    pub fn subscribe_parent_background_completions(&self) -> broadcast::Receiver<BackgroundCompletionEvent> {
360        let (receiver, replayed) = self.background_completion_channel.lock().subscribe_parent();
361        if replayed {
362            self.background_completion_notify.notify_one();
363        }
364        receiver
365    }
366
367    /// Returns the wake signal used by the interactive loop while it is idle.
368    pub fn background_completion_notify(&self) -> Arc<Notify> {
369        Arc::clone(&self.background_completion_notify)
370    }
371
372    /// Re-discovers subagent specs from the workspace.
373    pub async fn reload(&self) -> Result<()> {
374        let discovered = discover_controller_subagents(&self.config.workspace_root).await?;
375        self.state.write().await.discovered = discovered;
376        Ok(())
377    }
378
379    /// Stores the parent conversation messages for context forking into children.
380    pub async fn set_parent_messages(&self, messages: &[Message]) {
381        let cloned = messages.to_vec();
382        self.state.write().await.parent_messages = cloned;
383    }
384
385    /// Parses the current user input to extract explicit agent mentions and delegation signals.
386    pub async fn set_turn_delegation_hints_from_input(&self, input: &str) -> Vec<String> {
387        let mut state = self.state.write().await;
388        let explicit_mentions = extract_explicit_agent_mentions(input, state.discovered.effective.as_slice());
389        let explicit_request = contains_explicit_delegation_request(input, explicit_mentions.as_slice());
390        state.turn_hints = TurnDelegationHints {
391            explicit_mentions: explicit_mentions.clone(),
392            explicit_request,
393            current_input: input.to_string(),
394        };
395        explicit_mentions
396    }
397
398    /// Resets delegation hints at the end of a turn.
399    pub async fn clear_turn_delegation_hints(&self) {
400        self.state.write().await.turn_hints = TurnDelegationHints::default();
401    }
402
403    /// Updates the parent session identifier at runtime.
404    pub async fn set_parent_session_id(&self, session_id: impl Into<String>) {
405        *self.parent_session_id.write().await = session_id.into();
406    }
407
408    /// Returns the currently effective subagent specifications (merged builtin + workspace).
409    pub async fn effective_specs(&self) -> Vec<SubagentSpec> {
410        self.state.read().await.discovered.effective.clone()
411    }
412
413    /// Returns specs that are shadowed by workspace-level overrides.
414    pub async fn shadowed_specs(&self) -> Vec<SubagentSpec> {
415        self.state.read().await.discovered.shadowed.clone()
416    }
417
418    /// Returns status entries for all tracked child subagents.
419    pub async fn status_entries(&self) -> Vec<SubagentStatusEntry> {
420        let state = self.state.read().await;
421        let mut entries = state.children.values().map(ChildRecord::build_status_entry).collect::<Vec<_>>();
422        drop(state);
423        entries.extend(self.matrix_projection_entries().await);
424        entries
425    }
426}
427
428// ─── Controller submodule split ────────────────────────────────────────────
429
430mod controller_background_ops;
431mod controller_child_loop;
432mod controller_helpers;
433mod controller_spawn_run;
434mod controller_verify;
435
436#[allow(
437    unused_imports,
438    reason = "Intentional compatibility, platform, or test-only suppression."
439)]
440pub(super) use controller_helpers::*;
441
442// ─── Tests ──────────────────────────────────────────────────────────────────
443
444#[cfg(test)]
445mod tests;