Skip to main content

vtcode_core/core/agent/
bootstrap.rs

1//! Component builder and bootstrap utilities for the core agent.
2//!
3//! This module extracts the initialization logic from [`Agent`](super::core::Agent)
4//! so it can be reused by downstream consumers. The builder pattern makes it easy
5//! to override default components (for example when embedding VT Code in other
6//! applications or exposing a reduced open-source surface area) without relying
7//! on the binary crate's internal setup.
8
9use std::fs;
10use std::path::Path;
11use std::sync::Arc;
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14use anyhow::{Context, Result};
15
16use crate::config::models::Provider;
17use crate::config::types::{AgentConfig, SessionInfo};
18use crate::models_manager::ModelsManager;
19use crate::utils::error_messages::{ERR_CREATE_DIR, ERR_GET_METADATA};
20
21use crate::core::decision_tracker::DecisionTracker;
22use crate::core::error_recovery::ErrorRecoveryManager;
23use crate::ctx_err;
24use crate::llm::client::{AnyClient, ProviderClientAdapter};
25use crate::llm::factory::{ProviderConfig, create_provider_with_config, infer_provider_from_model};
26use crate::tools::ToolRegistry;
27use tracing::warn;
28
29/// Collection of dependencies required by the [`Agent`](super::core::Agent).
30///
31/// Consumers that want to reuse the agent loop can either construct this bundle
32/// directly with [`AgentComponentBuilder`] or provide their own specialized
33/// implementation when embedding VT Code.
34pub struct AgentComponentSet {
35    pub client: AnyClient,
36    pub tool_registry: Arc<ToolRegistry>,
37    pub decision_tracker: DecisionTracker,
38    pub error_recovery: ErrorRecoveryManager,
39    pub models_manager: Arc<ModelsManager>,
40
41    pub session_info: SessionInfo,
42}
43
44/// Builder for [`AgentComponentSet`].
45///
46/// The builder exposes hooks for overriding individual components which makes
47/// the agent easier to adapt for open-source scenarios or bespoke deployments.
48#[must_use = "build the agent components before discarding the builder"]
49pub struct AgentComponentBuilder<'config> {
50    config: &'config AgentConfig,
51    client: Option<AnyClient>,
52    tool_registry: Option<Arc<ToolRegistry>>,
53    decision_tracker: Option<DecisionTracker>,
54    error_recovery: Option<ErrorRecoveryManager>,
55    models_manager: Option<Arc<ModelsManager>>,
56
57    session_info: Option<SessionInfo>,
58}
59
60impl<'config> AgentComponentBuilder<'config> {
61    /// Create a new builder scoped to the provided configuration.
62    pub fn new(config: &'config AgentConfig) -> Self {
63        Self {
64            config,
65            client: None,
66            tool_registry: None,
67            decision_tracker: None,
68            error_recovery: None,
69            models_manager: None,
70            session_info: None,
71        }
72    }
73
74    /// Override the LLM client instance.
75    pub fn with_client(mut self, client: AnyClient) -> Self {
76        self.client = Some(client);
77        self
78    }
79
80    /// Override the tool registry instance.
81    pub fn with_tool_registry(mut self, registry: Arc<ToolRegistry>) -> Self {
82        self.tool_registry = Some(registry);
83        self
84    }
85
86    /// Override the decision tracker instance.
87    pub fn with_decision_tracker(mut self, tracker: DecisionTracker) -> Self {
88        self.decision_tracker = Some(tracker);
89        self
90    }
91
92    /// Override the error recovery manager instance.
93    pub fn with_error_recovery(mut self, manager: ErrorRecoveryManager) -> Self {
94        self.error_recovery = Some(manager);
95        self
96    }
97
98    /// Override the models manager instance.
99    pub fn with_models_manager(mut self, manager: Arc<ModelsManager>) -> Self {
100        self.models_manager = Some(manager);
101        self
102    }
103
104    /// Override the session metadata.
105    pub fn with_session_info(mut self, session_info: SessionInfo) -> Self {
106        self.session_info = Some(session_info);
107        self
108    }
109
110    /// Build the component set, lazily constructing any missing dependencies.
111    pub async fn build(mut self) -> Result<AgentComponentSet> {
112        ensure_workspace_ready(&self.config.workspace)?;
113
114        let client = match self.client.take() {
115            Some(client) => client,
116            None => create_llm_client(self.config)?,
117        };
118
119        let session_info = match self.session_info.take() {
120            Some(info) => info,
121            None => create_session_info().context("Failed to initialize agent session metadata for bootstrap")?,
122        };
123
124        let tool_registry = match self.tool_registry {
125            Some(registry) => registry,
126            None => {
127                let registry = ToolRegistry::new(self.config.workspace.clone()).await;
128                registry.set_harness_session(session_info.session_id.clone());
129                Arc::new(registry)
130            }
131        };
132
133        // Prefer custom manager if provided, otherwise reuse global singleton.
134        // The global singleton is provider-agnostic; provider filtering happens at query time.
135        let models_manager = self.models_manager.take().unwrap_or_else(|| {
136            // Clone Arc from global - this is cheap since ModelsManager is behind LazyLock
137            Arc::new(ModelsManager::with_provider(self.config.provider.parse::<Provider>().ok().unwrap_or_default()))
138        });
139
140        let decision_tracker = self.decision_tracker.unwrap_or_default();
141
142        let error_recovery = self.error_recovery.unwrap_or_default();
143
144        Ok(AgentComponentSet {
145            client,
146            tool_registry,
147            decision_tracker,
148            error_recovery,
149            models_manager,
150
151            session_info,
152        })
153    }
154}
155
156fn create_llm_client(config: &AgentConfig) -> Result<AnyClient> {
157    let provider_name = if config.provider.trim().is_empty() {
158        infer_provider_from_model(&config.model)
159            .map(|provider| provider.to_string())
160            .ok_or_else(|| anyhow::anyhow!("Cannot determine provider for model: {}", config.model))?
161    } else {
162        config.provider.to_lowercase()
163    };
164
165    let provider = create_provider_with_config(
166        &provider_name,
167        ProviderConfig {
168            api_key: Some(config.api_key.clone()),
169            openai_chatgpt_auth: config.openai_chatgpt_auth.clone(),
170            copilot_auth: None,
171            base_url: None,
172            model: Some(config.model.clone()),
173            prompt_cache: Some(config.prompt_cache.clone()),
174            timeouts: None,
175            openai: None,
176            anthropic: None,
177            openrouter: None,
178            model_behavior: config.model_behavior.clone(),
179            workspace_root: Some(config.workspace.clone()),
180        },
181    )
182    .with_context(|| format!("Failed to initialize provider '{provider_name}'"))?;
183
184    Ok(Box::new(ProviderClientAdapter::new(provider, config.model.clone())))
185}
186
187fn create_session_info() -> Result<SessionInfo> {
188    let now = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|err| err.duration());
189
190    Ok(build_session_info(now))
191}
192
193fn build_session_info(duration: Result<Duration, Duration>) -> SessionInfo {
194    let (start_time, session_id) = match duration {
195        Ok(duration) => {
196            let secs = duration.as_secs();
197            (secs, format!("session_{secs}"))
198        }
199        Err(delta) => {
200            let fallback = delta.as_secs();
201            warn!(fallback_seconds = fallback, "System time is before UNIX epoch; using fallback session id");
202            (fallback, format!("session_fallback_{fallback}"))
203        }
204    };
205
206    SessionInfo {
207        session_id,
208        start_time,
209        total_turns: 0,
210        total_decisions: 0,
211        error_count: 0,
212    }
213}
214
215fn ensure_workspace_ready(workspace_root: &Path) -> Result<()> {
216    if workspace_root.exists() {
217        let metadata =
218            fs::metadata(workspace_root).with_context(|| ctx_err!(ERR_GET_METADATA, workspace_root.display()))?;
219
220        anyhow::ensure!(metadata.is_dir(), "Workspace path is not a directory: {}", workspace_root.display());
221    } else {
222        fs::create_dir_all(workspace_root).with_context(|| ctx_err!(ERR_CREATE_DIR, workspace_root.display()))?;
223    }
224
225    Ok(())
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use crate::config::constants::models;
232    use crate::config::core::PromptCachingConfig;
233    use crate::config::models::Provider;
234    use crate::config::types::{ModelSelectionSource, ReasoningEffortLevel, UiSurfacePreference};
235    use crate::core::agent::snapshots::{DEFAULT_CHECKPOINTS_ENABLED, DEFAULT_MAX_AGE_DAYS, DEFAULT_MAX_SNAPSHOTS};
236    use std::collections::BTreeMap;
237
238    #[tokio::test]
239    async fn builds_default_component_set() {
240        let temp_dir = tempfile::tempdir().expect("temp dir");
241        let agent_config = AgentConfig {
242            model: models::google::GEMINI_3_FLASH_PREVIEW.to_string(),
243            api_key: "test-api-key".to_owned(),
244            provider: Provider::Gemini.to_string(),
245            api_key_env: Provider::Gemini.default_api_key_env().to_string(),
246            workspace: temp_dir.path().to_path_buf(),
247            verbose: false,
248            theme: "default".to_owned(),
249            reasoning_effort: ReasoningEffortLevel::default(),
250            ui_surface: UiSurfacePreference::Inline,
251            prompt_cache: PromptCachingConfig::default(),
252            model_source: ModelSelectionSource::WorkspaceConfig,
253            custom_api_keys: BTreeMap::new(),
254            checkpointing_enabled: DEFAULT_CHECKPOINTS_ENABLED,
255            checkpointing_storage_dir: None,
256            checkpointing_max_snapshots: DEFAULT_MAX_SNAPSHOTS,
257            checkpointing_max_age_days: Some(DEFAULT_MAX_AGE_DAYS),
258            quiet: false,
259            max_conversation_turns: 1000,
260            model_behavior: None,
261            openai_chatgpt_auth: None,
262        };
263
264        let components = AgentComponentBuilder::new(&agent_config)
265            .build()
266            .await
267            .expect("component build succeeds");
268
269        assert!(components.session_info.session_id.starts_with("session_"));
270        assert_eq!(components.session_info.total_turns, 0);
271        assert!(!components.tool_registry.available_tools().await.is_empty());
272    }
273
274    #[tokio::test]
275    async fn allows_overriding_components() {
276        let temp_dir = tempfile::tempdir().expect("temp dir");
277        let agent_config = AgentConfig {
278            model: models::google::GEMINI_3_FLASH_PREVIEW.to_string(),
279            api_key: "test-api-key".to_owned(),
280            provider: Provider::Gemini.to_string(),
281            api_key_env: Provider::Gemini.default_api_key_env().to_string(),
282            workspace: temp_dir.path().to_path_buf(),
283            verbose: true,
284            theme: "custom".to_owned(),
285            reasoning_effort: ReasoningEffortLevel::High,
286            ui_surface: UiSurfacePreference::Alternate,
287            prompt_cache: PromptCachingConfig::default(),
288            model_source: ModelSelectionSource::WorkspaceConfig,
289            custom_api_keys: BTreeMap::new(),
290            checkpointing_enabled: DEFAULT_CHECKPOINTS_ENABLED,
291            checkpointing_storage_dir: None,
292            checkpointing_max_snapshots: DEFAULT_MAX_SNAPSHOTS,
293            checkpointing_max_age_days: Some(DEFAULT_MAX_AGE_DAYS),
294            quiet: false,
295            max_conversation_turns: 1000,
296            model_behavior: None,
297            openai_chatgpt_auth: None,
298        };
299
300        let custom_session = SessionInfo {
301            session_id: "session_custom".to_owned(),
302            start_time: 42,
303            total_turns: 1,
304            total_decisions: 2,
305            error_count: 3,
306        };
307
308        let registry = Arc::new(ToolRegistry::new(agent_config.workspace.clone()).await);
309        // Install a self-reference so built-in tools are exposed to
310        // `unified_exec` code snippets as callable library functions.
311        registry.set_self_ref(Arc::clone(&registry));
312
313        let components = AgentComponentBuilder::new(&agent_config)
314            .with_session_info(custom_session.clone())
315            .with_tool_registry(Arc::clone(&registry))
316            .build()
317            .await
318            .expect("component build succeeds with overrides");
319
320        assert_eq!(components.session_info.session_id, custom_session.session_id);
321        assert_eq!(components.session_info.start_time, custom_session.start_time);
322        assert_eq!(Arc::as_ptr(&components.tool_registry), Arc::as_ptr(&registry));
323    }
324
325    #[test]
326    fn session_info_uses_fallback_when_clock_is_before_epoch() {
327        let info = build_session_info(Err(Duration::from_secs(42)));
328        assert_eq!(info.session_id, "session_fallback_42");
329        assert_eq!(info.start_time, 42);
330        assert_eq!(info.total_turns, 0);
331    }
332
333    #[tokio::test]
334    async fn rejects_non_directory_workspace() {
335        let temp_dir = tempfile::tempdir().expect("temp dir");
336        let file_path = temp_dir.path().join("not_dir");
337        fs::write(&file_path, "not a dir").expect("write file");
338
339        let agent_config = AgentConfig {
340            workspace: file_path.clone(),
341            ..sample_config(temp_dir.path())
342        };
343
344        let result = AgentComponentBuilder::new(&agent_config).build().await;
345        assert!(result.is_err(), "expected workspace validation to fail");
346    }
347
348    fn sample_config(workspace: &Path) -> AgentConfig {
349        AgentConfig {
350            model: models::google::GEMINI_3_FLASH_PREVIEW.to_string(),
351            api_key: "test-api-key".to_owned(),
352            provider: Provider::Gemini.to_string(),
353            api_key_env: Provider::Gemini.default_api_key_env().to_string(),
354            workspace: workspace.to_path_buf(),
355            verbose: false,
356            theme: "default".to_owned(),
357            reasoning_effort: ReasoningEffortLevel::default(),
358            ui_surface: UiSurfacePreference::Inline,
359            prompt_cache: PromptCachingConfig::default(),
360            model_source: ModelSelectionSource::WorkspaceConfig,
361            custom_api_keys: BTreeMap::new(),
362            checkpointing_enabled: DEFAULT_CHECKPOINTS_ENABLED,
363            checkpointing_storage_dir: None,
364            checkpointing_max_snapshots: DEFAULT_MAX_SNAPSHOTS,
365            checkpointing_max_age_days: Some(DEFAULT_MAX_AGE_DAYS),
366            quiet: false,
367            max_conversation_turns: 1000,
368            model_behavior: None,
369            openai_chatgpt_auth: None,
370        }
371    }
372}