Skip to main content

vtcode_core/tools/registry/
builder.rs

1//! ToolRegistry construction helpers.
2
3use std::future::Future;
4use std::path::Path;
5use std::path::PathBuf;
6use std::sync::Arc;
7use std::sync::RwLock;
8
9use parking_lot::Mutex;
10
11use crate::config::{PersistentMemoryConfig, PtyConfig};
12use crate::core::memory_pool::MemoryPool;
13use crate::tool_policy::ToolPolicyManager;
14use crate::tools::handlers::PlanningWorkflowState;
15use crate::tools::output_spooler::{SpoolerConfig, ToolOutputSpooler};
16use crate::tools::safety_gateway::SafetyGateway;
17use vtcode_config::DynamicContextConfig;
18use vtcode_config::loader::ConfigManager;
19
20use super::ToolRegistry;
21use super::assembly::ToolAssembly;
22use super::circuit_breaker;
23use super::distributed::ToolConfigSnapshot;
24use super::execution_history::ToolExecutionHistory;
25use super::harness::HarnessContext;
26use super::inventory::ToolInventory;
27use super::pack::register_builtin_packs;
28use super::policy::ToolPolicyGateway;
29use super::pty;
30use super::resiliency::ResiliencyContext;
31use super::shell_policy::ShellPolicyChecker;
32use super::timeout::ToolTimeoutPolicy;
33
34fn spooler_config_from_dynamic_context(config: &DynamicContextConfig) -> SpoolerConfig {
35    SpoolerConfig {
36        enabled: config.enabled,
37        threshold_bytes: config.tool_output_threshold,
38        max_files: config.max_spooled_files,
39        max_age_secs: config.spool_max_age_secs,
40        include_file_reference: true,
41    }
42}
43
44#[derive(Debug, Default)]
45struct WorkspaceToolConfig {
46    tool: ToolConfigSnapshot,
47    spooler: SpoolerConfig,
48    persistent_memory: PersistentMemoryConfig,
49    persistent_memory_enabled: bool,
50    inspection_mode: vtcode_config::core::agent::InspectionMode,
51}
52
53/// Load the config needed by tool registration in one parse. Falls back to
54/// defaults for non-web settings on load/parse errors. Web tools stay registered
55/// for discovery but fail closed rather than using default network permissions.
56fn load_workspace_tool_config(workspace_root: &Path) -> WorkspaceToolConfig {
57    match ConfigManager::load_from_workspace(workspace_root) {
58        Ok(manager) => workspace_tool_config_from_loaded(manager.config()),
59        Err(err) => {
60            tracing::warn!(
61                workspace = %workspace_root.display(),
62                error = %err,
63                "Failed to load workspace config for tool registry; disabling web tools"
64            );
65            unavailable_web_config()
66        }
67    }
68}
69
70fn unavailable_web_config() -> WorkspaceToolConfig {
71    WorkspaceToolConfig {
72        tool: ToolConfigSnapshot { web_config_load_failed: true, ..Default::default() },
73        ..Default::default()
74    }
75}
76
77fn workspace_tool_config_from_loaded(config: &vtcode_config::loader::VTCodeConfig) -> WorkspaceToolConfig {
78    let persistent_memory_enabled = config.persistent_memory_enabled();
79    let mut persistent_memory = config.agent.persistent_memory.clone();
80    persistent_memory.enabled = persistent_memory_enabled;
81    WorkspaceToolConfig {
82        tool: ToolConfigSnapshot {
83            web_search: config.tools.web_search.clone(),
84            web_config_load_failed: false,
85            web_fetch: config.tools.web_fetch.clone(),
86        },
87        spooler: spooler_config_from_dynamic_context(&config.context.dynamic),
88        persistent_memory,
89        persistent_memory_enabled,
90        inspection_mode: config.agent.harness.inspection.mode,
91    }
92}
93
94impl ToolRegistry {
95    pub fn new(workspace_root: PathBuf) -> impl Future<Output = Self> {
96        Self::build(workspace_root, PtyConfig::default())
97    }
98
99    /// Build a registry reusing an already-loaded session config snapshot.
100    ///
101    /// Interactive startup already owns the merged `VTCodeConfig`; passing it
102    /// here avoids a second `ConfigManager::load_from_workspace` file read +
103    /// TOML parse on the first-paint path. Falls back to defaults for any
104    /// field the snapshot does not carry, matching `load_workspace_tool_config`
105    /// behavior on parse failure.
106    pub fn new_with_loaded_config(
107        workspace_root: PathBuf,
108        config: &vtcode_config::loader::VTCodeConfig,
109    ) -> impl Future<Output = Self> {
110        let snapshot = workspace_tool_config_from_loaded(config);
111        Self::build_with_snapshot(workspace_root, PtyConfig::default(), None, true, snapshot)
112    }
113
114    /// Build a first-paint registry: reuses the loaded session config snapshot
115    /// and skips workspace policy file I/O.
116    ///
117    /// Policy evaluation fails open to tool metadata defaults until hydration
118    /// attaches the manager via `ensure_workspace_policy_manager`, which runs
119    /// before any tool executes.
120    pub fn new_for_first_paint_with_loaded_config(
121        workspace_root: PathBuf,
122        config: &vtcode_config::loader::VTCodeConfig,
123    ) -> impl Future<Output = Self> {
124        let snapshot = workspace_tool_config_from_loaded(config);
125        Self::build_with_snapshot(workspace_root, PtyConfig::default(), None, false, snapshot)
126    }
127
128    pub fn new_with_config(workspace_root: PathBuf, pty_config: PtyConfig) -> impl Future<Output = Self> {
129        Self::build(workspace_root, pty_config)
130    }
131
132    /// Build a registry for offline metadata without creating a workspace policy file.
133    pub fn new_for_schema(workspace_root: PathBuf) -> impl Future<Output = Self> {
134        Self::build_with_policy(workspace_root, PtyConfig::default(), None, false)
135    }
136
137    pub fn new_with_custom_policy(
138        workspace_root: PathBuf,
139        policy_manager: ToolPolicyManager,
140    ) -> impl Future<Output = Self> {
141        Self::build_with_policy(workspace_root, PtyConfig::default(), Some(policy_manager), true)
142    }
143
144    pub fn new_with_custom_policy_and_config(
145        workspace_root: PathBuf,
146        pty_config: PtyConfig,
147        policy_manager: ToolPolicyManager,
148    ) -> impl Future<Output = Self> {
149        Self::build_with_policy(workspace_root, pty_config, Some(policy_manager), true)
150    }
151
152    async fn build(workspace_root: PathBuf, pty_config: PtyConfig) -> Self {
153        Self::build_with_policy(workspace_root, pty_config, None, true).await
154    }
155
156    async fn build_with_policy(
157        workspace_root: PathBuf,
158        pty_config: PtyConfig,
159        policy_manager: Option<ToolPolicyManager>,
160        initialize_policy: bool,
161    ) -> Self {
162        // Load the user-config snapshot *before* constructing the inventory so
163        // `WebFetchTool`/`WebSearchTool` are built with the user's allow/block
164        // lists, cooldown, and session cap rather than defaulting out. The
165        // snapshot is passed explicitly to active packs; parse the workspace
166        // config once because both the web tools and output spooler consume it.
167        let config_workspace = workspace_root.clone();
168        let workspace_config =
169            match tokio::task::spawn_blocking(move || load_workspace_tool_config(&config_workspace)).await {
170                Ok(config) => config,
171                Err(error) => {
172                    tracing::warn!(%error, "Workspace tool config task panicked; disabling web tools");
173                    unavailable_web_config()
174                }
175            };
176        Self::build_with_snapshot(workspace_root, pty_config, policy_manager, initialize_policy, workspace_config).await
177    }
178
179    async fn build_with_snapshot(
180        workspace_root: PathBuf,
181        pty_config: PtyConfig,
182        policy_manager: Option<ToolPolicyManager>,
183        initialize_policy: bool,
184        workspace_config: WorkspaceToolConfig,
185    ) -> Self {
186        let WorkspaceToolConfig {
187            tool: tool_config,
188            spooler: spooler_config,
189            persistent_memory: persistent_memory_config,
190            persistent_memory_enabled,
191            inspection_mode,
192        } = workspace_config;
193        let edited_file_monitor = Arc::new(crate::tools::edited_file_monitor::EditedFileMonitor::new());
194        edited_file_monitor.source_inspection().set_mode(inspection_mode);
195        let inventory = ToolInventory::new(workspace_root.clone(), Arc::clone(&edited_file_monitor));
196        let planning_workflow_state = PlanningWorkflowState::new(workspace_root.clone());
197
198        register_builtin_packs(&inventory, &planning_workflow_state, &tool_config).await;
199
200        let pty_sessions = pty::PtySessionManager::new(workspace_root.clone(), pty_config);
201        let exec_sessions =
202            crate::tools::exec_session::ExecSessionManager::new(workspace_root.clone(), pty_sessions.clone());
203
204        let policy_gateway = match (policy_manager, initialize_policy) {
205            (Some(pm), _) => ToolPolicyGateway::with_policy_manager(pm),
206            (None, true) => ToolPolicyGateway::new(&workspace_root).await,
207            (None, false) => ToolPolicyGateway::without_persistence(),
208        };
209
210        let optimization_config = vtcode_config::OptimizationConfig::default();
211        let metrics = Arc::new(crate::metrics::MetricsCollector::new());
212        let hot_cache_size = std::num::NonZeroUsize::new(optimization_config.tool_registry.hot_cache_size)
213            .unwrap_or(std::num::NonZeroUsize::MIN);
214        let output_spooler = Arc::new(ToolOutputSpooler::with_config(&workspace_root, spooler_config));
215        // Age-expired leftovers from prior sessions are pruned immediately;
216        // periodic cleanup only fires every N spools inside one session, so
217        // short sessions never reached the threshold and stale spools piled up
218        // across runs. The count budget stays on the in-session periodic path:
219        // pinning is per-process, so a startup count prune in this session
220        // could delete young spools a concurrent session still reads.
221        if let Err(error) = output_spooler.cleanup_expired_files().await {
222            tracing::debug!(%error, "startup spool prune failed");
223        }
224
225        // Pre-allocate FxHashMaps with expected capacity for typical MCP tool sets.
226        // Most sessions register 10-50 MCP tools; start with room for 32 to
227        // avoid rehashing during initial discovery without wasting memory.
228        let mcp_tool_index = rustc_hash::FxHashMap::with_capacity_and_hasher(32, rustc_hash::FxBuildHasher);
229        let mcp_reverse_index = rustc_hash::FxHashMap::with_capacity_and_hasher(32, rustc_hash::FxBuildHasher);
230
231        let registry = Self {
232            inventory,
233            persistent_memory_config: Arc::new(persistent_memory_config),
234            persistent_memory_enabled,
235            edited_file_monitor,
236            policy_gateway: Arc::new(policy_gateway),
237            pty_sessions,
238            exec_sessions,
239            mcp_client: Arc::new(parking_lot::RwLock::new(None)),
240            mcp_tool_index: Arc::new(tokio::sync::RwLock::new(mcp_tool_index)),
241            mcp_reverse_index: Arc::new(tokio::sync::RwLock::new(mcp_reverse_index)),
242            timeout_policy: Arc::new(parking_lot::RwLock::new(ToolTimeoutPolicy::default())),
243            execution_history: ToolExecutionHistory::with_workspace_root(100, workspace_root.clone()),
244            patch_recovery_reads: Arc::new(Mutex::new(super::patch_recovery::PatchRecoveryReads::default())),
245            harness_context: HarnessContext::default(),
246            resiliency: Arc::new(Mutex::new(ResiliencyContext::default())),
247            mcp_circuit_breaker: Arc::new(circuit_breaker::McpCircuitBreaker::with_metrics(metrics.clone())),
248            shared_circuit_breaker: Arc::new(RwLock::new(None)),
249            initialized: Arc::new(std::sync::atomic::AtomicBool::new(false)),
250            tool_call_counter: Arc::new(std::sync::atomic::AtomicU64::new(0)),
251            pty_poll_counter: Arc::new(std::sync::atomic::AtomicU64::new(0)),
252            canonical_plans_dir: Arc::new(std::sync::OnceLock::new()),
253            metrics,
254            shell_policy: Arc::new(RwLock::new(ShellPolicyChecker::new())),
255            runtime_sandbox_config: Arc::new(RwLock::new(super::sandbox_facade::runtime_sandbox_config_default())),
256            agent_type: Arc::new(RwLock::new("unknown".to_owned())),
257            cached_available_tools: Arc::new(parking_lot::RwLock::new(None)),
258            active_tool_profile: Arc::new(RwLock::new(crate::config::ToolProfile::default())),
259            progress_callback: Arc::new(RwLock::new(None)),
260            active_pty_sessions: Arc::new(RwLock::new(None)),
261
262            memory_pool: Arc::new(MemoryPool::from_config(&optimization_config.memory_pool)),
263            hot_tool_cache: Arc::new(parking_lot::RwLock::new(lru::LruCache::new(hot_cache_size))),
264            optimization_config,
265            middleware: crate::tools::tool_middleware::MiddlewareChain::new(),
266
267            output_spooler,
268
269            planning_workflow_state,
270            planning_mode_policy_overrides: Arc::new(parking_lot::RwLock::new(None)),
271            safety_gateway: Arc::new(SafetyGateway::default()),
272            cgp_runtime_mode: Arc::new(RwLock::new(None)),
273            tool_assembly: Arc::new(RwLock::new(ToolAssembly::empty())),
274            tool_catalog_state: Arc::new(super::tool_catalog_facade::SessionToolCatalogState::new()),
275            subagent_controller: Arc::new(RwLock::new(None)),
276            matrix_worker: Arc::new(parking_lot::RwLock::new(None)),
277            matrix_coordinator: Arc::new(std::sync::atomic::AtomicBool::new(false)),
278            session_scheduler: Arc::new(tokio::sync::Mutex::new(crate::scheduler::SessionScheduler::new())),
279            session_model_tools: Arc::new(RwLock::new(None)),
280            self_ref: Arc::new(RwLock::new(None)),
281        };
282
283        registry.rebuild_tool_assembly().await;
284        registry.sync_policy_catalog().await;
285        registry.initialize_resiliency_trackers();
286        registry
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293    use tempfile::tempdir;
294
295    #[tokio::test]
296    async fn unsupported_search_provider_disables_web_tools_even_when_approved() {
297        for provider in ["unsupported-provider"] {
298            let temp = tempdir().unwrap();
299            std::fs::write(
300                temp.path().join("vtcode.toml"),
301                format!(
302                    r#"
303[workspace]
304use_root_config = true
305[tools.web_search]
306provider = "{provider}"
307[tools.web_fetch]
308mode = "whitelist"
309allowed_domains = ["only.example.com"]
310"#
311                ),
312            )
313            .unwrap();
314            let snapshot = load_workspace_tool_config(temp.path());
315            assert!(snapshot.tool.web_config_load_failed);
316            let registry = ToolRegistry::new(temp.path().to_path_buf()).await;
317            registry.allow_all_tools().await.unwrap();
318            for name in ["web_search", "web_fetch"] {
319                let registration = registry.inventory.get_registration(name).unwrap();
320                let super::super::ToolHandler::TraitObject(tool) = registration.handler() else {
321                    panic!("native web tool")
322                };
323                // Empty args are safe even if the guard regresses: each underlying
324                // web tool rejects them before credential resolution or network I/O.
325                let error = tool.execute(serde_json::json!({})).await.unwrap_err();
326                assert!(error.to_string().contains("workspace configuration could not be loaded"), "{name}: {error}");
327                let expected_provider =
328                    format!("provider = \"{}\"", vtcode_config::WebSearchProvider::Auto.backend_id());
329                assert!(error.to_string().contains(&expected_provider));
330            }
331            let registration = registry.inventory.get_registration("web_fetch").unwrap();
332            let factory = registration.native_cgp_factory().unwrap();
333            let native =
334                factory(&registration, temp.path().to_path_buf(), super::super::cgp_facade::CgpRuntimeMode::Ci);
335            let result = native
336                .execute(serde_json::json!({"url":"http://127.0.0.1:1", "prompt":"read"}))
337                .await;
338            let message = match result {
339                Ok(output) => output.to_string(),
340                Err(error) => format!("{error:#}"),
341            };
342            assert!(message.contains("workspace configuration could not be loaded"), "{message}");
343            let output = registry
344                .execute_tool(
345                    "fetch_url",
346                    serde_json::json!({
347                        "url":"http://127.0.0.1:1", "prompt":"read"
348                    }),
349                )
350                .await
351                .unwrap();
352            let error = super::super::ToolExecutionError::from_tool_output(&output).unwrap();
353            assert!(error.message.contains("workspace configuration could not be loaded"));
354            assert!(!error.retryable);
355        }
356    }
357
358    #[tokio::test]
359    async fn tool_registry_uses_workspace_dynamic_context_for_output_spooler() {
360        let temp = tempdir().unwrap();
361        std::fs::write(
362            temp.path().join("vtcode.toml"),
363            r#"[context.dynamic]
364enabled = true
365tool_output_threshold = 4096
366max_spooled_files = 7
367spool_max_age_secs = 12
368
369[workspace]
370use_root_config = true
371"#,
372        )
373        .unwrap();
374
375        let registry = ToolRegistry::new(temp.path().to_path_buf()).await;
376        let config = registry.output_spooler().config();
377
378        assert!(config.enabled);
379        assert_eq!(config.threshold_bytes, 4096);
380        assert_eq!(config.max_files, 7);
381        assert_eq!(config.max_age_secs, 12);
382    }
383
384    #[tokio::test]
385    async fn tool_registry_falls_back_to_default_spooler_config_on_invalid_workspace_config() {
386        let temp = tempdir().unwrap();
387        std::fs::write(
388            temp.path().join("vtcode.toml"),
389            r#"[context.dynamic]
390tool_output_threshold = "oops"
391"#,
392        )
393        .unwrap();
394
395        let registry = ToolRegistry::new(temp.path().to_path_buf()).await;
396        let config = registry.output_spooler().config();
397
398        assert!(config.enabled);
399        assert_eq!(config.threshold_bytes, DynamicContextConfig::default().tool_output_threshold);
400        assert_eq!(config.max_files, SpoolerConfig::default().max_files);
401        assert_eq!(config.max_age_secs, SpoolerConfig::default().max_age_secs);
402    }
403
404    #[tokio::test]
405    async fn tool_registry_captures_effective_memory_config() {
406        let temp = tempdir().expect("workspace");
407        std::fs::write(
408            temp.path().join("vtcode.toml"),
409            "[features]\nmemories = true\n\n[agent.persistent_memory]\nenabled = true\n\n[workspace]\nuse_root_config = true\n",
410        )
411        .expect("workspace config");
412
413        let snapshot = load_workspace_tool_config(temp.path());
414        assert!(snapshot.persistent_memory_enabled);
415        assert!(snapshot.persistent_memory.enabled);
416
417        let registry = ToolRegistry::new(temp.path().to_path_buf()).await;
418        assert!(registry.persistent_memory_enabled);
419        assert!(registry.persistent_memory_config.enabled);
420    }
421
422    #[tokio::test]
423    async fn schema_registry_does_not_create_workspace_policy() {
424        let temp = tempdir().expect("workspace");
425
426        let _registry = ToolRegistry::new_for_schema(temp.path().to_path_buf()).await;
427
428        assert!(!temp.path().join(".vtcode").exists());
429    }
430
431    #[tokio::test]
432    async fn loaded_config_registry_reuses_snapshot_without_workspace_parse() {
433        // Asymmetric: workspace file says 4096/7/12, loaded snapshot says
434        // 8192/3/99. The registry must reflect the snapshot, proving the
435        // first-paint path does not pay a second workspace TOML parse.
436        let temp = tempdir().expect("workspace");
437        std::fs::write(
438            temp.path().join("vtcode.toml"),
439            r#"[context.dynamic]
440enabled = true
441tool_output_threshold = 4096
442max_spooled_files = 7
443spool_max_age_secs = 12
444
445[workspace]
446use_root_config = true
447"#,
448        )
449        .expect("workspace config");
450
451        let mut loaded = vtcode_config::loader::VTCodeConfig::default();
452        loaded.context.dynamic.enabled = true;
453        loaded.context.dynamic.tool_output_threshold = 8192;
454        loaded.context.dynamic.max_spooled_files = 3;
455        loaded.context.dynamic.spool_max_age_secs = 99;
456
457        let registry = ToolRegistry::new_with_loaded_config(temp.path().to_path_buf(), &loaded).await;
458        let config = registry.output_spooler().config();
459
460        assert!(config.enabled);
461        assert_eq!(config.threshold_bytes, 8192);
462        assert_eq!(config.max_files, 3);
463        assert_eq!(config.max_age_secs, 99);
464    }
465
466    #[tokio::test]
467    async fn first_paint_registry_defers_policy_manager_until_ensure() {
468        let temp = tempdir().expect("workspace");
469        let loaded = vtcode_config::loader::VTCodeConfig::default();
470
471        let registry = ToolRegistry::new_for_first_paint_with_loaded_config(temp.path().to_path_buf(), &loaded).await;
472        assert!(!registry.has_policy_manager().await, "first-paint registry must skip policy file I/O");
473
474        registry.ensure_workspace_policy_manager(temp.path()).await;
475        assert!(
476            registry.has_policy_manager().await,
477            "hydration must attach the workspace policy manager before any tool runs"
478        );
479    }
480}