Skip to main content

vtcode_core/core/agent/
runner.rs

1//! Agent runner for executing individual agent instances
2
3use crate::config::VTCodeConfig;
4use crate::config::constants::tools;
5use crate::config::models::{ModelId, Provider};
6use crate::config::types::{ReasoningEffortLevel, VerbosityLevel};
7use crate::core::agent::events::EventSink;
8use crate::core::agent::features::FeatureSet;
9use crate::core::agent::session_config::ResolvedSessionConfig;
10use crate::core::agent::steering::SteeringMessage;
11use crate::core::threads::{ThreadBootstrap, ThreadRuntimeHandle, build_thread_archive_metadata};
12use std::path::Path;
13
14/// Settings for the agent runner
15#[derive(Clone, Default)]
16pub struct RunnerSettings {
17    /// Reasoning effort level for the agent
18    pub reasoning_effort: Option<ReasoningEffortLevel>,
19    /// Verbosity level for output text
20    pub verbosity: Option<VerbosityLevel>,
21}
22
23use crate::core::agent::types::AgentType;
24use crate::core::loop_detector::LoopDetector;
25use crate::exec::events::ThreadEvent;
26use crate::llm::AnyClient;
27use crate::llm::client::ProviderClientAdapter;
28use crate::llm::factory::{ProviderConfig, create_provider_with_config, infer_provider_from_model};
29use crate::llm::provider as uni_provider;
30use crate::primary_agent::ActivePrimaryAgent;
31use crate::prompts::PromptContext;
32use crate::tools::ToolRegistry;
33
34use anyhow::{Context, Result, anyhow};
35use parking_lot::{Mutex, RwLock};
36use std::path::PathBuf;
37use std::str::FromStr;
38use std::sync::Arc;
39use tracing::{info, warn};
40use vtcode_config::auth::OpenAIChatGptAuthHandle;
41
42mod config_helpers;
43mod constants;
44mod continuation;
45mod contract_render;
46mod escalation;
47mod evaluator_types;
48mod execute;
49mod execute_checks;
50mod execute_helpers;
51mod helpers;
52mod orchestration;
53mod output;
54mod planner_helpers;
55mod planner_types;
56pub mod prompt_alignment;
57mod replan_helpers;
58mod retry;
59mod summarize;
60mod summary;
61mod task_setup;
62mod telemetry;
63mod tool_access;
64mod tool_args;
65mod tool_dispatch_common;
66mod tool_exec;
67mod tool_execution_guard;
68mod tool_rejection;
69mod tool_types;
70mod types;
71mod validation;
72mod verification;
73mod workspace_detection;
74
75/// Attach an eagerly initialized MCP client to the runner's tool registry.
76///
77/// Exec and other non-interactive runner sessions do not drive the async MCP
78/// manager, so MCP tools would otherwise remain invisible for the whole run.
79async fn attach_mcp_client(
80    tool_registry: &ToolRegistry,
81    session_config: &ResolvedSessionConfig,
82    workspace: &Path,
83) -> Result<()> {
84    let config = session_config.effective();
85    let sandbox_context = if config.sandbox.enabled
86        && !matches!(config.sandbox.default_policy, vtcode_config::SandboxPolicy::DangerFullAccess)
87    {
88        let policy = crate::tools::registry::sandbox_policy_from_runtime_config(&config.sandbox, workspace)?;
89        Some(crate::mcp::McpSandboxContext::new(policy, workspace))
90    } else {
91        None
92    };
93
94    let mut client = crate::mcp::McpClient::with_sandbox_context(config.mcp.clone(), sandbox_context);
95    let startup_timeout = std::time::Duration::from_secs(config.mcp.startup_timeout_seconds.unwrap_or(30));
96    let result = tokio::time::timeout(startup_timeout, client.initialize()).await;
97    match result {
98        Ok(Ok(())) => {}
99        Ok(Err(err)) => return Err(err).context("MCP client initialization failed"),
100        Err(_) => anyhow::bail!("MCP client initialization timed out after {} seconds", startup_timeout.as_secs()),
101    }
102
103    let client = Arc::new(client);
104    tool_registry.set_mcp_client(client).await;
105    if let Err(err) = tool_registry.refresh_mcp_tools().await {
106        warn!("Failed to refresh MCP tools after attach: {err:#}");
107    }
108    info!("MCP client attached to runner tool registry");
109    Ok(())
110}
111
112#[cfg(test)]
113mod tests;
114
115type ToolArgTransform = Arc<dyn Fn(&str, serde_json::Value) -> serde_json::Value + Send + Sync>;
116
117/// Individual agent runner for executing specialized agent tasks
118pub struct AgentRunner {
119    /// Agent type and configuration
120    agent_type: AgentType,
121    /// LLM client for this agent
122    client: AnyClient,
123    /// Unified provider client (OpenAI/Anthropic/Gemini) for tool-calling
124    provider_client: Box<dyn uni_provider::LLMProvider>,
125    /// Tool registry with restricted access
126    tool_registry: ToolRegistry,
127    /// System prompt content
128    system_prompt: String,
129    /// Token-budget report for `system_prompt`, computed at session
130    /// construction time (or recomputed by `set_system_prompt`). Reused by
131    /// `compose_task_system_prompt` for non-simple tasks so the budget
132    /// warning and preflight check stay accurate without recomposing the
133    /// prompt on every turn.
134    system_prompt_report: crate::prompts::system::SystemPromptReport,
135    /// Session information
136    session_id: String,
137    /// Initial archived history used to seed the first task on this runner.
138    bootstrap_messages: Vec<crate::llm::provider::Message>,
139    /// Workspace path
140    _workspace: PathBuf,
141    /// Frozen session-scoped configuration snapshot
142    session_config: Arc<ResolvedSessionConfig>,
143    /// Tool catalogue configuration used for this runner's model surface.
144    session_tools_config: crate::tools::handlers::SessionToolsConfig,
145    /// Model identifier
146    model: String,
147    /// API key (for provider client construction in future flows)
148    _api_key: String,
149    /// Reasoning effort level for models that support it
150    reasoning_effort: Option<ReasoningEffortLevel>,
151    /// Verbosity level for output text
152    verbosity: Option<VerbosityLevel>,
153    /// Suppress stdout output when emitting structured events
154    quiet: bool,
155    /// Optional sink for streaming structured events
156    event_sink: Option<EventSink>,
157    /// Shared thread runtime state for history/event ownership
158    thread_handle: ThreadRuntimeHandle,
159    /// Maximum number of autonomous turns before halting
160    max_turns: usize,
161    /// Loop detector to prevent infinite exploration
162    loop_detector: Mutex<LoopDetector>,
163    /// Cached shell policy patterns to avoid recompilation
164
165    /// Receiver for steering messages (e.g., stop, pause)
166    steering_receiver: Mutex<Option<tokio::sync::mpsc::UnboundedReceiver<SteeringMessage>>>,
167    /// Optional restricted tool definitions used instead of the default registry projection.
168    tool_definitions_override: RwLock<Option<Vec<uni_provider::ToolDefinition>>>,
169    /// Optional argument transformer applied before tool validation/execution.
170    tool_arg_transform: Option<ToolArgTransform>,
171    local_tools_only: bool,
172    /// Active primary-agent policy to intersect with runner tools.
173    active_primary_agent: Option<ActivePrimaryAgent>,
174}
175
176impl AgentRunner {
177    /// Get the selected model for the current turn.
178    fn get_selected_model(&self) -> String {
179        self.model.clone()
180    }
181
182    fn runner_println(&self, args: std::fmt::Arguments) {
183        if !self.quiet {
184            println!("{args}");
185        }
186    }
187
188    /// Create a new agent runner.
189    pub async fn new(
190        agent_type: AgentType,
191        model: ModelId,
192        api_key: String,
193        workspace: PathBuf,
194        session_id: String,
195        settings: RunnerSettings,
196        steering_receiver: Option<tokio::sync::mpsc::UnboundedReceiver<SteeringMessage>>,
197    ) -> Result<Self> {
198        Box::pin(Self::new_internal(
199            agent_type,
200            model,
201            api_key,
202            workspace,
203            session_id,
204            settings,
205            steering_receiver,
206            ThreadBootstrap::new(None),
207            None,
208            None,
209        ))
210        .await
211    }
212
213    /// Create an agent runner with prebuilt thread bootstrap, config, and auth.
214    #[allow(
215        clippy::too_many_arguments,
216        reason = "Intentional compatibility, platform, or test-only suppression."
217    )]
218    pub async fn new_with_bootstrap(
219        agent_type: AgentType,
220        model: ModelId,
221        api_key: String,
222        workspace: PathBuf,
223        session_id: String,
224        settings: RunnerSettings,
225        steering_receiver: Option<tokio::sync::mpsc::UnboundedReceiver<SteeringMessage>>,
226        bootstrap: ThreadBootstrap,
227        vt_cfg: Option<VTCodeConfig>,
228        openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
229    ) -> Result<Self> {
230        Box::pin(Self::new_internal(
231            agent_type,
232            model,
233            api_key,
234            workspace,
235            session_id,
236            settings,
237            steering_receiver,
238            bootstrap,
239            vt_cfg,
240            openai_chatgpt_auth,
241        ))
242        .await
243    }
244
245    #[expect(
246        clippy::too_many_arguments,
247        reason = "Intentional compatibility, platform, test, or API-shape suppression."
248    )]
249    async fn new_internal(
250        agent_type: AgentType,
251        model: ModelId,
252        api_key: String,
253        workspace: PathBuf,
254        session_id: String,
255        settings: RunnerSettings,
256        steering_receiver: Option<tokio::sync::mpsc::UnboundedReceiver<SteeringMessage>>,
257        bootstrap: ThreadBootstrap,
258        vt_cfg: Option<VTCodeConfig>,
259        openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
260    ) -> Result<Self> {
261        // Load configuration once to seed system prompt and runtime policies
262        let session_config = if let Some(vt_cfg) = vt_cfg {
263            ResolvedSessionConfig::from_config(vt_cfg)
264        } else {
265            match ResolvedSessionConfig::load_from_workspace(&workspace) {
266                Ok(session_config) => session_config,
267                Err(err) => {
268                    warn!("Failed to load vtcode configuration for system prompt composition: {err:#}");
269                    ResolvedSessionConfig::from_config(VTCodeConfig::default())
270                }
271            }
272        };
273        let session_config = Arc::new(session_config);
274        let provider_name = {
275            let configured = session_config.effective().agent.provider.trim();
276            if configured.is_empty() {
277                infer_provider_from_model(&model.as_str())
278                    .map(|provider| provider.to_string())
279                    .ok_or_else(|| anyhow!("Failed to determine provider for model {model}"))?
280            } else {
281                configured.to_lowercase()
282            }
283        };
284        let provider_config = ProviderConfig {
285            api_key: Some(api_key.clone()),
286            openai_chatgpt_auth: openai_chatgpt_auth.clone(),
287            copilot_auth: Some(session_config.effective().auth.copilot.clone()),
288            base_url: None,
289            model: Some(model.to_string()),
290            prompt_cache: Some(session_config.effective().prompt_cache.clone()),
291            timeouts: None,
292            openai: Some(session_config.effective().provider.openai.clone()),
293            anthropic: Some(session_config.effective().provider.anthropic.clone()),
294            model_behavior: Some(session_config.effective().model.clone()),
295            workspace_root: Some(workspace.clone()),
296        };
297
298        let client: AnyClient = Box::new(ProviderClientAdapter::new(
299            create_provider_with_config(&provider_name, provider_config.clone())
300                .with_context(|| "Failed to create client provider")?,
301            model.to_string(),
302        ));
303        let provider_client = create_provider_with_config(&provider_name, provider_config)
304            .with_context(|| "Failed to create provider client")?;
305        if std::env::var_os("VTCODE_DEBUG_PROVIDER").is_some() {
306            eprintln!(
307                "vtcode-debug: runner provider={} client_provider={} model={}",
308                provider_name,
309                provider_client.name(),
310                model
311            );
312        }
313        let max_repeated_tool_calls = session_config.effective().tools.max_repeated_tool_calls.max(1);
314        let deferred_tool_policy = crate::tools::handlers::deferred_tool_policy_for_runtime(
315            crate::llm::factory::infer_provider(Some(&session_config.effective().agent.provider), &model.as_str()),
316            provider_client.supports_responses_compaction(&model.as_str()),
317            Some(session_config.effective()),
318        );
319        let anthropic_native_memory_enabled = crate::tools::handlers::anthropic_native_memory_enabled_for_runtime(
320            Provider::from_str(provider_client.name()).ok(),
321            &model.as_str(),
322            Some(session_config.effective()),
323        );
324        let tool_registry = ToolRegistry::new(workspace.clone()).await;
325        tool_registry.set_inspection_mode(session_config.effective().agent.harness.inspection.mode);
326        tool_registry.set_harness_session(session_id.clone());
327        tool_registry.set_matrix_coordinator(session_config.effective().default_primary_agent == "coordinator");
328        tool_registry.set_agent_type(agent_type.to_string());
329        tool_registry.initialize_async().await?;
330        if let Err(err) = tool_registry
331            .apply_session_runtime_config(
332                &session_config.effective().commands,
333                &session_config.effective().permissions,
334                &session_config.effective().sandbox,
335                &session_config.effective().timeouts,
336                &session_config.effective().tools,
337            )
338            .await
339        {
340            warn!("Failed to apply tool policies from config: {}", err);
341        }
342        if session_config.effective().mcp.enabled {
343            if let Err(err) = crate::mcp::validate_mcp_config(&session_config.effective().mcp) {
344                warn!("MCP configuration validation error: {err}");
345            }
346            if let Err(err) = attach_mcp_client(&tool_registry, &session_config, &workspace).await {
347                warn!("Failed to attach MCP client: {err:#}");
348            }
349        }
350        if session_config.effective().context.dynamic.enabled
351            && let Err(err) =
352                crate::context::initialize_dynamic_context(&workspace, &session_config.effective().context.dynamic)
353                    .await
354        {
355            warn!("Failed to initialize dynamic context directories: {}", err);
356        }
357        let session_tools_config = crate::tools::handlers::SessionToolsConfig {
358            surface: crate::tools::handlers::SessionSurface::AgentRunner,
359            capability_level: crate::config::types::CapabilityLevel::CodeSearch,
360            documentation_mode: session_config.effective().agent.tool_documentation_mode,
361            planning_active: tool_registry.is_planning_active(),
362            request_user_input_enabled: false,
363            model_capabilities: crate::tools::handlers::ToolModelCapabilities::for_model_name(&model.as_str()),
364            deferred_tool_policy,
365            anthropic_native_memory_enabled,
366            tool_profile: session_config.effective().tools.profile,
367        };
368        let available_tools = tool_registry
369            .model_tools(session_tools_config.clone())
370            .await
371            .into_iter()
372            .map(|tool| tool.function_name().to_string())
373            .collect::<Vec<_>>();
374        let mut prompt_context = PromptContext::from_workspace_tools(&workspace, available_tools);
375        prompt_context.set_current_directory(workspace.clone());
376        prompt_context.load_available_skills_async().await;
377        let (system_prompt, system_prompt_report) = helpers::compose_system_prompt_with_appendix(
378            workspace.as_path(),
379            session_config.effective(),
380            &prompt_context,
381        )
382        .await?;
383        let loop_detector = LoopDetector::with_max_repeated_calls(max_repeated_tool_calls);
384        let bootstrap_messages = bootstrap.messages.clone();
385        let mut bootstrap = bootstrap;
386        if bootstrap.metadata.is_none() {
387            bootstrap.metadata = Some(build_thread_archive_metadata(
388                workspace.as_path(),
389                &model.as_str(),
390                &session_config.effective().agent.provider,
391                &session_config.effective().agent.theme,
392                settings
393                    .reasoning_effort
394                    .unwrap_or(session_config.effective().agent.reasoning_effort)
395                    .as_str(),
396            ));
397        }
398        let thread_handle =
399            crate::core::threads::ThreadManager::new().start_thread_with_identifier(session_id.clone(), bootstrap);
400        let max_turns = session_config.effective().automation.full_auto.max_turns.max(1);
401        if session_config.effective().default_primary_agent == "coordinator" {
402            let controller =
403                Box::pin(crate::subagents::SubagentController::new(crate::subagents::SubagentControllerConfig {
404                    workspace_root: workspace.clone(),
405                    parent_session_id: session_id.clone(),
406                    parent_model: model.to_string(),
407                    parent_provider: provider_name,
408                    parent_reasoning_effort: settings
409                        .reasoning_effort
410                        .unwrap_or(session_config.effective().agent.reasoning_effort),
411                    api_key: api_key.clone(),
412                    vt_cfg: session_config.effective().clone(),
413                    openai_chatgpt_auth,
414                    depth: 0,
415                    workspace_gated: session_config
416                        .effective()
417                        .workspace_lifecycle_hooks
418                        .as_ref()
419                        .is_some_and(|hooks| !hooks.is_empty()),
420                    exec_sessions: tool_registry.exec_session_manager(),
421                    pty_manager: tool_registry.pty_manager().clone(),
422                    managed_background_runtime: false,
423                }))
424                .await?;
425            tool_registry.set_subagent_controller(Arc::new(controller));
426        }
427
428        Ok(Self {
429            agent_type,
430            client,
431            provider_client,
432            tool_registry,
433            system_prompt,
434            system_prompt_report,
435            session_id,
436            bootstrap_messages,
437            _workspace: workspace,
438            session_config,
439            session_tools_config,
440            model: model.to_string(),
441            _api_key: api_key,
442            reasoning_effort: settings.reasoning_effort,
443            verbosity: settings.verbosity,
444            quiet: false,
445            event_sink: None,
446            thread_handle,
447            max_turns,
448            loop_detector: Mutex::new(loop_detector),
449            steering_receiver: Mutex::new(steering_receiver),
450            tool_definitions_override: RwLock::new(None),
451            tool_arg_transform: None,
452            local_tools_only: false,
453            active_primary_agent: None,
454        })
455    }
456
457    /// Enable or disable console output for this runner.
458    pub fn set_quiet(&mut self, quiet: bool) {
459        self.quiet = quiet;
460    }
461
462    /// Configure the loop detector for subagent mode with tighter read-only
463    /// budgets and earlier navigation streak intervention.
464    pub fn set_subagent_mode(&self, is_subagent: bool) {
465        self.loop_detector.lock().set_subagent_mode(is_subagent);
466    }
467
468    /// Attach a subagent controller to this runner's tool registry so the
469    /// subagent-lifecycle tools (`agent` and its aliases) become available to
470    /// the model. Used to enable nested delegation: the attached controller
471    /// carries the child-scoped depth so the depth check in `spawn_with_spec`
472    /// still governs grandchild spawns.
473    pub fn set_subagent_controller(&self, controller: Arc<crate::subagents::SubagentController>) {
474        self.tool_registry.set_subagent_controller(controller);
475    }
476
477    /// Snapshot the runner-owned conversation messages for archive persistence.
478    pub fn session_messages(&self) -> Vec<crate::llm::provider::Message> {
479        self.thread_handle.messages()
480    }
481
482    /// Clone the underlying thread handle so callers can capture snapshots.
483    pub fn thread_handle(&self) -> ThreadRuntimeHandle {
484        self.thread_handle.clone()
485    }
486
487    /// Workspace root this runner operates within.
488    pub fn workspace(&self) -> &Path {
489        &self._workspace
490    }
491
492    /// Enable read-only planning workflow for the underlying tool registry.
493    pub fn enable_planning(&self) {
494        self.tool_registry.enable_planning();
495    }
496
497    /// Disable read-only planning workflow for the underlying tool registry.
498    pub fn disable_planning(&self) {
499        self.tool_registry.disable_planning();
500    }
501
502    /// Attach a callback that will be invoked for each structured event as it is recorded.
503    pub fn set_event_handler<F>(&mut self, handler: F)
504    where
505        F: FnMut(&ThreadEvent) + Send + 'static,
506    {
507        self.event_sink = Some(Arc::new(Mutex::new(Box::new(handler))));
508    }
509
510    /// Remove any previously registered structured event callback.
511    pub fn clear_event_handler(&mut self) {
512        self.event_sink = None;
513    }
514
515    /// Override the composed system prompt for downstream embedders.
516    ///
517    /// Recomputes `system_prompt_report` against the overridden text so the
518    /// budget warning and preflight check stay accurate even when the prompt
519    /// bypasses the normal section-based composition pipeline.
520    pub fn set_system_prompt(&mut self, system_prompt: impl Into<String>) {
521        self.system_prompt = system_prompt.into();
522        self.system_prompt_report = crate::prompts::system::SystemPromptReport::measure(
523            &self.system_prompt,
524            self.config().agent.max_system_prompt_tokens,
525        );
526    }
527
528    /// Clone the underlying tool registry so embedders can register custom tools.
529    pub fn tool_registry(&self) -> ToolRegistry {
530        self.tool_registry.clone()
531    }
532
533    /// Override the tool definitions used for LLM requests instead of the default registry projection.
534    pub fn set_tool_definitions_override(&mut self, definitions: Vec<uni_provider::ToolDefinition>) {
535        *self.tool_definitions_override.write() = Some(definitions);
536    }
537
538    /// Clear any previously set tool definition override, restoring the default registry projection.
539    pub fn clear_tool_definitions_override(&mut self) {
540        *self.tool_definitions_override.write() = None;
541    }
542
543    /// Set an argument transformer applied to tool calls before validation and execution.
544    pub fn set_tool_arg_transform(&mut self, transform: ToolArgTransform) {
545        self.tool_arg_transform = Some(transform);
546    }
547
548    /// Restrict skill child execution using live trusted registration metadata.
549    pub fn restrict_to_local_tools(&mut self) {
550        self.local_tools_only = true;
551    }
552
553    /// Clear any previously set tool argument transformer.
554    pub fn clear_tool_arg_transform(&mut self) {
555        self.tool_arg_transform = None;
556    }
557
558    /// Apply active primary-agent tool and permission policy to this runner.
559    pub fn set_active_primary_agent(&mut self, active_primary_agent: ActivePrimaryAgent) {
560        self.tool_registry
561            .set_matrix_coordinator(active_primary_agent.identity.name == "coordinator");
562        self.active_primary_agent = Some(active_primary_agent);
563    }
564
565    /// Enable full-auto execution with the provided allow-list.
566    pub async fn enable_full_auto(&mut self, allowed_tools: &[String]) {
567        let mut permission_catalog_config = self.session_tools_config.clone();
568        permission_catalog_config.planning_active = allowed_tools
569            .iter()
570            .any(|tool_name| crate::tools::names::canonical_tool_name(tool_name) == tools::CODE_SEARCH);
571        self.tool_registry
572            .enable_full_auto_permission_for_session(allowed_tools, permission_catalog_config)
573            .await;
574    }
575
576    /// Restrict an allow-list to tools suitable for strict review-only runs.
577    pub async fn review_tool_allowlist(&self, allowed_tools: &[String]) -> Vec<String> {
578        let review_candidates = if allowed_tools.iter().any(|tool| tool.trim() == tools::WILDCARD_ALL) {
579            let mut candidates = self.tool_registry.available_tools().await;
580            if !candidates.iter().any(|tool| tool == tools::CODE_SEARCH) {
581                candidates.push(tools::CODE_SEARCH.to_string());
582            }
583            candidates
584        } else {
585            allowed_tools.to_vec()
586        };
587
588        review_candidates
589            .iter()
590            .filter(|tool_name| {
591                let canonical = crate::tools::names::canonical_tool_name(tool_name);
592
593                !matches!(canonical, tools::REQUEST_USER_INPUT | tools::TASK_TRACKER | tools::START_PLANNING)
594                    && !self.tool_registry.is_mutating_tool(tool_name)
595            })
596            .cloned()
597            .collect()
598    }
599
600    fn features(&self) -> FeatureSet {
601        self.session_config.features().clone()
602    }
603}