1#![allow(
2 unused_imports,
3 reason = "Intentional compatibility, platform, or test-only suppression."
4)]
5mod background;
8mod config;
9mod constants;
10mod discovery;
11pub mod matrix;
12mod model;
13mod prompt;
14mod types;
15
16pub 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
44pub 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#[derive(Debug, Clone)]
74pub struct VerificationResult {
75 pub approved: bool,
77 pub issues: Vec<String>,
79 pub reasoning: String,
81}
82
83use 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
118pub 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#[derive(Clone)]
182pub struct SubagentControllerConfig {
183 pub workspace_root: PathBuf,
185 pub parent_session_id: String,
187 pub parent_model: String,
189 pub parent_provider: String,
191 pub parent_reasoning_effort: ReasoningEffortLevel,
193 pub api_key: String,
195 pub vt_cfg: VTCodeConfig,
197 pub openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
199 pub depth: usize,
201 pub workspace_gated: bool,
208 pub exec_sessions: ExecSessionManager,
210 pub pty_manager: PtyManager,
212 pub managed_background_runtime: bool,
214}
215
216pub 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 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 shutdown_handles: Arc<Mutex<std::collections::BTreeMap<String, JoinHandle<()>>>>,
239 background_completion_owners: Arc<AtomicUsize>,
241 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 pub async fn new(config: SubagentControllerConfig) -> Result<Self> {
289 let discovered = discover_controller_subagents(&config.workspace_root).await?;
290 Box::pin(Self::new_with_discovered(config, discovered)).await
294 }
295
296 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 pub fn subscribe_background_completions(&self) -> broadcast::Receiver<BackgroundCompletionEvent> {
354 self.background_completion_channel.lock().subscribe()
355 }
356
357 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 pub fn background_completion_notify(&self) -> Arc<Notify> {
369 Arc::clone(&self.background_completion_notify)
370 }
371
372 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 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 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 pub async fn clear_turn_delegation_hints(&self) {
400 self.state.write().await.turn_hints = TurnDelegationHints::default();
401 }
402
403 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 pub async fn effective_specs(&self) -> Vec<SubagentSpec> {
410 self.state.read().await.discovered.effective.clone()
411 }
412
413 pub async fn shadowed_specs(&self) -> Vec<SubagentSpec> {
415 self.state.read().await.discovered.shadowed.clone()
416 }
417
418 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
428mod 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#[cfg(test)]
445mod tests;