vtcode-core 0.169.5

Core library for VT Code - a Rust-based terminal coding agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! ToolRegistry construction helpers.

use std::future::Future;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::RwLock;

use parking_lot::Mutex;

use crate::config::{PersistentMemoryConfig, PtyConfig};
use crate::core::memory_pool::MemoryPool;
use crate::tool_policy::ToolPolicyManager;
use crate::tools::handlers::PlanningWorkflowState;
use crate::tools::output_spooler::{SpoolerConfig, ToolOutputSpooler};
use crate::tools::safety_gateway::SafetyGateway;
use vtcode_config::DynamicContextConfig;
use vtcode_config::loader::ConfigManager;

use super::ToolRegistry;
use super::assembly::ToolAssembly;
use super::circuit_breaker;
use super::distributed::ToolConfigSnapshot;
use super::execution_history::ToolExecutionHistory;
use super::harness::HarnessContext;
use super::inventory::ToolInventory;
use super::pack::register_builtin_packs;
use super::policy::ToolPolicyGateway;
use super::pty;
use super::resiliency::ResiliencyContext;
use super::shell_policy::ShellPolicyChecker;
use super::timeout::ToolTimeoutPolicy;

fn spooler_config_from_dynamic_context(config: &DynamicContextConfig) -> SpoolerConfig {
    SpoolerConfig {
        enabled: config.enabled,
        threshold_bytes: config.tool_output_threshold,
        max_files: config.max_spooled_files,
        max_age_secs: config.spool_max_age_secs,
        include_file_reference: true,
    }
}

#[derive(Debug, Default)]
struct WorkspaceToolConfig {
    tool: ToolConfigSnapshot,
    spooler: SpoolerConfig,
    persistent_memory: PersistentMemoryConfig,
    persistent_memory_enabled: bool,
}

/// Load the config needed by tool registration in one parse. Falls back to
/// defaults on any load/parse error so a malformed config never blocks tool
/// registration.
fn load_workspace_tool_config(workspace_root: &Path) -> WorkspaceToolConfig {
    match ConfigManager::load_from_workspace(workspace_root) {
        Ok(manager) => workspace_tool_config_from_loaded(manager.config()),
        Err(err) => {
            tracing::warn!(
                workspace = %workspace_root.display(),
                error = %err,
                "Failed to load workspace config for tool registry; using defaults"
            );
            WorkspaceToolConfig::default()
        }
    }
}

fn workspace_tool_config_from_loaded(config: &vtcode_config::loader::VTCodeConfig) -> WorkspaceToolConfig {
    let persistent_memory_enabled = config.persistent_memory_enabled();
    let mut persistent_memory = config.agent.persistent_memory.clone();
    persistent_memory.enabled = persistent_memory_enabled;
    WorkspaceToolConfig {
        tool: ToolConfigSnapshot {
            web_search: config.tools.web_search.clone(),
            web_fetch: config.tools.web_fetch.clone(),
        },
        spooler: spooler_config_from_dynamic_context(&config.context.dynamic),
        persistent_memory,
        persistent_memory_enabled,
    }
}

impl ToolRegistry {
    pub fn new(workspace_root: PathBuf) -> impl Future<Output = Self> {
        Self::build(workspace_root, PtyConfig::default())
    }

    /// Build a registry reusing an already-loaded session config snapshot.
    ///
    /// Interactive startup already owns the merged `VTCodeConfig`; passing it
    /// here avoids a second `ConfigManager::load_from_workspace` file read +
    /// TOML parse on the first-paint path. Falls back to defaults for any
    /// field the snapshot does not carry, matching `load_workspace_tool_config`
    /// behavior on parse failure.
    pub fn new_with_loaded_config(
        workspace_root: PathBuf,
        config: &vtcode_config::loader::VTCodeConfig,
    ) -> impl Future<Output = Self> {
        let snapshot = workspace_tool_config_from_loaded(config);
        Self::build_with_snapshot(workspace_root, PtyConfig::default(), None, true, snapshot)
    }

    /// Build a first-paint registry: reuses the loaded session config snapshot
    /// and skips workspace policy file I/O.
    ///
    /// Policy evaluation fails open to tool metadata defaults until hydration
    /// attaches the manager via `ensure_workspace_policy_manager`, which runs
    /// before any tool executes.
    pub fn new_for_first_paint_with_loaded_config(
        workspace_root: PathBuf,
        config: &vtcode_config::loader::VTCodeConfig,
    ) -> impl Future<Output = Self> {
        let snapshot = workspace_tool_config_from_loaded(config);
        Self::build_with_snapshot(workspace_root, PtyConfig::default(), None, false, snapshot)
    }

    pub fn new_with_config(workspace_root: PathBuf, pty_config: PtyConfig) -> impl Future<Output = Self> {
        Self::build(workspace_root, pty_config)
    }

    /// Build a registry for offline metadata without creating a workspace policy file.
    pub fn new_for_schema(workspace_root: PathBuf) -> impl Future<Output = Self> {
        Self::build_with_policy(workspace_root, PtyConfig::default(), None, false)
    }

    pub fn new_with_custom_policy(
        workspace_root: PathBuf,
        policy_manager: ToolPolicyManager,
    ) -> impl Future<Output = Self> {
        Self::build_with_policy(workspace_root, PtyConfig::default(), Some(policy_manager), true)
    }

    pub fn new_with_custom_policy_and_config(
        workspace_root: PathBuf,
        pty_config: PtyConfig,
        policy_manager: ToolPolicyManager,
    ) -> impl Future<Output = Self> {
        Self::build_with_policy(workspace_root, pty_config, Some(policy_manager), true)
    }

    async fn build(workspace_root: PathBuf, pty_config: PtyConfig) -> Self {
        Self::build_with_policy(workspace_root, pty_config, None, true).await
    }

    async fn build_with_policy(
        workspace_root: PathBuf,
        pty_config: PtyConfig,
        policy_manager: Option<ToolPolicyManager>,
        initialize_policy: bool,
    ) -> Self {
        // Load the user-config snapshot *before* constructing the inventory so
        // `WebFetchTool`/`WebSearchTool` are built with the user's allow/block
        // lists, cooldown, and session cap rather than defaulting out. The
        // snapshot is passed explicitly to active packs; parse the workspace
        // config once because both the web tools and output spooler consume it.
        let config_workspace = workspace_root.clone();
        let workspace_config =
            match tokio::task::spawn_blocking(move || load_workspace_tool_config(&config_workspace)).await {
                Ok(config) => config,
                Err(error) => {
                    tracing::warn!(%error, "Workspace tool config task panicked; using defaults");
                    WorkspaceToolConfig::default()
                }
            };
        Self::build_with_snapshot(workspace_root, pty_config, policy_manager, initialize_policy, workspace_config).await
    }

    async fn build_with_snapshot(
        workspace_root: PathBuf,
        pty_config: PtyConfig,
        policy_manager: Option<ToolPolicyManager>,
        initialize_policy: bool,
        workspace_config: WorkspaceToolConfig,
    ) -> Self {
        let WorkspaceToolConfig {
            tool: tool_config,
            spooler: spooler_config,
            persistent_memory: persistent_memory_config,
            persistent_memory_enabled,
        } = workspace_config;
        let edited_file_monitor = Arc::new(crate::tools::edited_file_monitor::EditedFileMonitor::new());
        let inventory = ToolInventory::new(workspace_root.clone(), Arc::clone(&edited_file_monitor));
        let planning_workflow_state = PlanningWorkflowState::new(workspace_root.clone());

        register_builtin_packs(&inventory, &planning_workflow_state, &tool_config).await;

        let pty_sessions = pty::PtySessionManager::new(workspace_root.clone(), pty_config);
        let exec_sessions =
            crate::tools::exec_session::ExecSessionManager::new(workspace_root.clone(), pty_sessions.clone());

        let policy_gateway = match (policy_manager, initialize_policy) {
            (Some(pm), _) => ToolPolicyGateway::with_policy_manager(pm),
            (None, true) => ToolPolicyGateway::new(&workspace_root).await,
            (None, false) => ToolPolicyGateway::without_persistence(),
        };

        let optimization_config = vtcode_config::OptimizationConfig::default();
        let metrics = Arc::new(crate::metrics::MetricsCollector::new());
        let hot_cache_size = std::num::NonZeroUsize::new(optimization_config.tool_registry.hot_cache_size)
            .unwrap_or(std::num::NonZeroUsize::MIN);
        let output_spooler = Arc::new(ToolOutputSpooler::with_config(&workspace_root, spooler_config));
        // Age-expired leftovers from prior sessions are pruned immediately;
        // periodic cleanup only fires every N spools inside one session, so
        // short sessions never reached the threshold and stale spools piled up
        // across runs. The count budget stays on the in-session periodic path:
        // pinning is per-process, so a startup count prune in this session
        // could delete young spools a concurrent session still reads.
        if let Err(error) = output_spooler.cleanup_expired_files().await {
            tracing::debug!(%error, "startup spool prune failed");
        }

        // Pre-allocate FxHashMaps with expected capacity for typical MCP tool sets.
        // Most sessions register 10-50 MCP tools; start with room for 32 to
        // avoid rehashing during initial discovery without wasting memory.
        let mcp_tool_index = rustc_hash::FxHashMap::with_capacity_and_hasher(32, rustc_hash::FxBuildHasher);
        let mcp_reverse_index = rustc_hash::FxHashMap::with_capacity_and_hasher(32, rustc_hash::FxBuildHasher);

        let registry = Self {
            inventory,
            persistent_memory_config: Arc::new(persistent_memory_config),
            persistent_memory_enabled,
            edited_file_monitor,
            policy_gateway: Arc::new(policy_gateway),
            pty_sessions,
            exec_sessions,
            mcp_client: Arc::new(parking_lot::RwLock::new(None)),
            mcp_tool_index: Arc::new(tokio::sync::RwLock::new(mcp_tool_index)),
            mcp_reverse_index: Arc::new(tokio::sync::RwLock::new(mcp_reverse_index)),
            timeout_policy: Arc::new(parking_lot::RwLock::new(ToolTimeoutPolicy::default())),
            execution_history: ToolExecutionHistory::with_workspace_root(100, workspace_root.clone()),
            harness_context: HarnessContext::default(),
            resiliency: Arc::new(Mutex::new(ResiliencyContext::default())),
            mcp_circuit_breaker: Arc::new(circuit_breaker::McpCircuitBreaker::with_metrics(metrics.clone())),
            shared_circuit_breaker: Arc::new(RwLock::new(None)),
            initialized: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            tool_call_counter: Arc::new(std::sync::atomic::AtomicU64::new(0)),
            pty_poll_counter: Arc::new(std::sync::atomic::AtomicU64::new(0)),
            turn_preview_bytes: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            turn_tiny_preview_bytes: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            canonical_plans_dir: Arc::new(std::sync::OnceLock::new()),
            metrics,
            shell_policy: Arc::new(RwLock::new(ShellPolicyChecker::new())),
            runtime_sandbox_config: Arc::new(RwLock::new(super::sandbox_facade::runtime_sandbox_config_default())),
            agent_type: Arc::new(RwLock::new("unknown".to_owned())),
            cached_available_tools: Arc::new(parking_lot::RwLock::new(None)),
            active_tool_profile: Arc::new(RwLock::new(crate::config::ToolProfile::default())),
            progress_callback: Arc::new(RwLock::new(None)),
            active_pty_sessions: Arc::new(RwLock::new(None)),

            memory_pool: Arc::new(MemoryPool::from_config(&optimization_config.memory_pool)),
            hot_tool_cache: Arc::new(parking_lot::RwLock::new(lru::LruCache::new(hot_cache_size))),
            optimization_config,
            middleware: crate::tools::tool_middleware::MiddlewareChain::new(),

            output_spooler,

            planning_workflow_state,
            planning_mode_policy_overrides: Arc::new(parking_lot::RwLock::new(None)),
            safety_gateway: Arc::new(SafetyGateway::default()),
            cgp_runtime_mode: Arc::new(RwLock::new(None)),
            tool_assembly: Arc::new(RwLock::new(ToolAssembly::empty())),
            tool_catalog_state: Arc::new(super::tool_catalog_facade::SessionToolCatalogState::new()),
            subagent_controller: Arc::new(RwLock::new(None)),
            session_scheduler: Arc::new(tokio::sync::Mutex::new(crate::scheduler::SessionScheduler::new())),
            session_model_tools: Arc::new(RwLock::new(None)),
            self_ref: Arc::new(RwLock::new(None)),
        };

        registry.rebuild_tool_assembly().await;
        registry.sync_policy_catalog().await;
        registry.initialize_resiliency_trackers();
        registry
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[tokio::test]
    async fn tool_registry_uses_workspace_dynamic_context_for_output_spooler() {
        let temp = tempdir().unwrap();
        std::fs::write(
            temp.path().join("vtcode.toml"),
            r#"[context.dynamic]
enabled = true
tool_output_threshold = 4096
max_spooled_files = 7
spool_max_age_secs = 12

[workspace]
use_root_config = true
"#,
        )
        .unwrap();

        let registry = ToolRegistry::new(temp.path().to_path_buf()).await;
        let config = registry.output_spooler().config();

        assert!(config.enabled);
        assert_eq!(config.threshold_bytes, 4096);
        assert_eq!(config.max_files, 7);
        assert_eq!(config.max_age_secs, 12);
    }

    #[tokio::test]
    async fn tool_registry_falls_back_to_default_spooler_config_on_invalid_workspace_config() {
        let temp = tempdir().unwrap();
        std::fs::write(
            temp.path().join("vtcode.toml"),
            r#"[context.dynamic]
tool_output_threshold = "oops"
"#,
        )
        .unwrap();

        let registry = ToolRegistry::new(temp.path().to_path_buf()).await;
        let config = registry.output_spooler().config();

        assert!(config.enabled);
        assert_eq!(config.threshold_bytes, DynamicContextConfig::default().tool_output_threshold);
        assert_eq!(config.max_files, SpoolerConfig::default().max_files);
        assert_eq!(config.max_age_secs, SpoolerConfig::default().max_age_secs);
    }

    #[tokio::test]
    async fn tool_registry_captures_effective_memory_config() {
        let temp = tempdir().expect("workspace");
        std::fs::write(
            temp.path().join("vtcode.toml"),
            "[features]\nmemories = true\n\n[agent.persistent_memory]\nenabled = true\n\n[workspace]\nuse_root_config = true\n",
        )
        .expect("workspace config");

        let snapshot = load_workspace_tool_config(temp.path());
        assert!(snapshot.persistent_memory_enabled);
        assert!(snapshot.persistent_memory.enabled);

        let registry = ToolRegistry::new(temp.path().to_path_buf()).await;
        assert!(registry.persistent_memory_enabled);
        assert!(registry.persistent_memory_config.enabled);
    }

    #[tokio::test]
    async fn schema_registry_does_not_create_workspace_policy() {
        let temp = tempdir().expect("workspace");

        let _registry = ToolRegistry::new_for_schema(temp.path().to_path_buf()).await;

        assert!(!temp.path().join(".vtcode").exists());
    }

    #[tokio::test]
    async fn loaded_config_registry_reuses_snapshot_without_workspace_parse() {
        // Asymmetric: workspace file says 4096/7/12, loaded snapshot says
        // 8192/3/99. The registry must reflect the snapshot, proving the
        // first-paint path does not pay a second workspace TOML parse.
        let temp = tempdir().expect("workspace");
        std::fs::write(
            temp.path().join("vtcode.toml"),
            r#"[context.dynamic]
enabled = true
tool_output_threshold = 4096
max_spooled_files = 7
spool_max_age_secs = 12

[workspace]
use_root_config = true
"#,
        )
        .expect("workspace config");

        let mut loaded = vtcode_config::loader::VTCodeConfig::default();
        loaded.context.dynamic.enabled = true;
        loaded.context.dynamic.tool_output_threshold = 8192;
        loaded.context.dynamic.max_spooled_files = 3;
        loaded.context.dynamic.spool_max_age_secs = 99;

        let registry = ToolRegistry::new_with_loaded_config(temp.path().to_path_buf(), &loaded).await;
        let config = registry.output_spooler().config();

        assert!(config.enabled);
        assert_eq!(config.threshold_bytes, 8192);
        assert_eq!(config.max_files, 3);
        assert_eq!(config.max_age_secs, 99);
    }

    #[tokio::test]
    async fn first_paint_registry_defers_policy_manager_until_ensure() {
        let temp = tempdir().expect("workspace");
        let loaded = vtcode_config::loader::VTCodeConfig::default();

        let registry = ToolRegistry::new_for_first_paint_with_loaded_config(temp.path().to_path_buf(), &loaded).await;
        assert!(!registry.has_policy_manager().await, "first-paint registry must skip policy file I/O");

        registry.ensure_workspace_policy_manager(temp.path()).await;
        assert!(
            registry.has_policy_manager().await,
            "hydration must attach the workspace policy manager before any tool runs"
        );
    }
}