vtcode-config 0.185.4

Config loader components shared across VT Code and downstream adopters
Documentation
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::time::Duration;

use crate::constants::{defaults, tools};
use crate::core::plugins::PluginRuntimeConfig;

/// Model-facing tool profile for a session.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolProfile {
    /// VT Code standard baseline: exec_command, write_stdin, and apply_patch.
    #[default]
    #[serde(rename = "vt_code")]
    #[serde(alias = "codex_default")]
    #[cfg_attr(feature = "schema", schemars(rename = "vt_code"))]
    VtCode,
    /// VTCode specialised tools, including code_search and eligible dynamic tools.
    #[serde(rename = "advanced_vtcode")]
    #[cfg_attr(feature = "schema", schemars(rename = "advanced_vtcode"))]
    AdvancedVtCode,
}

/// Tools configuration
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ToolsConfig {
    /// Model-facing tool profile.
    #[serde(default)]
    pub profile: ToolProfile,

    /// Default policy for tools not explicitly listed
    #[serde(default = "default_tool_policy")]
    pub default_policy: ToolPolicy,

    /// Specific tool policies
    #[serde(default)]
    #[cfg_attr(
        feature = "schema",
        schemars(with = "std::collections::BTreeMap<String, ToolPolicy>")
    )]
    pub policies: IndexMap<String, ToolPolicy>,

    /// Maximum number of times the same tool invocation can be retried with the
    /// identical arguments within a single turn.
    #[serde(default = "default_max_repeated_tool_calls")]
    pub max_repeated_tool_calls: usize,

    /// Maximum consecutive blocked tool calls allowed per turn before forcing a
    /// turn break. The total fuse is 2x this value in normal mode, 4x in Plan
    /// Mode, and this value in recovery mode, unless overridden by
    /// `max_total_blocked_tool_calls_per_turn`.
    #[serde(default = "default_max_consecutive_blocked_tool_calls_per_turn")]
    pub max_consecutive_blocked_tool_calls_per_turn: usize,

    /// Optional explicit cap for total blocked tool calls per turn. When unset,
    /// the runtime derives it from the consecutive cap (2x normal, 4x plan,
    /// 1x recovery) so existing configs keep their behavior.
    #[serde(default)]
    pub max_total_blocked_tool_calls_per_turn: Option<usize>,

    /// Per-tool consecutive blocked-call cap overrides keyed by tool name.
    /// Allows read-only tools (e.g. `code_search`) to tolerate more denies
    /// than mutating tools (e.g. `exec_command`) before tripping the fuse.
    #[serde(default)]
    #[cfg_attr(feature = "schema", schemars(with = "std::collections::BTreeMap<String, usize>"))]
    pub blocked_tool_thresholds: IndexMap<String, usize>,

    /// Optional per-second rate limit for tool calls to smooth bursty retries.
    /// When unset, the runtime defaults apply.
    #[serde(default = "default_max_tool_rate_per_second")]
    pub max_tool_rate_per_second: Option<usize>,

    /// Maximum sequential spool-chunk `read_file` calls allowed per turn before
    /// nudging the agent to switch to targeted extraction/summarization.
    #[serde(default = "default_max_sequential_spool_chunk_reads")]
    pub max_sequential_spool_chunk_reads: usize,

    /// Web Fetch tool security configuration
    #[serde(default)]
    pub web_fetch: WebFetchConfig,

    /// Web Search tool configuration (provider selection, result caps, timeouts).
    #[serde(default)]
    pub web_search: WebSearchConfig,

    /// Dynamic plugin runtime configuration
    #[serde(default)]
    pub plugins: PluginRuntimeConfig,

    /// External editor integration settings used by `/edit` and keyboard shortcuts
    #[serde(default)]
    pub editor: EditorToolConfig,

    /// Tool-specific loop thresholds (Adaptive Loop Detection)
    /// Allows setting higher loop limits for read-only tools (e.g., ls, grep)
    /// and lower limits for mutating tools.
    #[serde(default)]
    pub loop_thresholds: IndexMap<String, usize>,

    /// Enables client-local deferred tool loading for providers without a
    /// hosted tool search (e.g. Gemini). When enabled, tools flagged
    /// `defer_loading: true` are omitted from the request payload instead
    /// of being sent eagerly, and a compact summary of what is discoverable
    /// is appended to the system prompt; the model loads them via the
    /// local MCP discovery tools. Enabled by default because
    /// eager MCP schemas are the dominant source of token inflation.
    #[serde(default = "default_client_tool_search")]
    pub client_tool_search: bool,

    /// Code Mode pilot configuration (agent-written snippet execution).
    ///
    /// Off by default. `enabled = true` in config opts the workspace in;
    /// the `VTCODE_EXPERIMENTAL_CODE_MODE` environment variable fills the
    /// default when the key is absent (so CI and containers can flip the
    /// pilot without editing config files). The final override — env wins
    /// over an explicit config value — is resolved once per session in
    /// `ToolRegistry::apply_config_policies` (`config OR env`), because
    /// serde `default` only fills missing keys and cannot express
    /// env-over-explicit at parse time.
    #[serde(default)]
    pub code_mode: CodeModeConfig,
}

/// Code Mode pilot configuration.
///
/// Experimental: lets the agent compose many tool calls inside one
/// sandboxed Python 3 / Node.js snippet instead of one model round trip
/// per call. Direct tool calls remain the default path.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CodeModeConfig {
    /// Opt the workspace in to experimental agent-written snippet
    /// execution. Default `false` (or the env var when the config key is
    /// absent). The session-effective flag additionally ORs the env var at
    /// `ToolRegistry::apply_config_policies`, so env wins over explicit
    /// config at runtime.
    #[serde(default = "default_code_mode_enabled")]
    pub enabled: bool,
}

impl Default for CodeModeConfig {
    fn default() -> Self {
        Self { enabled: default_code_mode_enabled() }
    }
}

fn default_code_mode_enabled() -> bool {
    crate::env_helpers::read_env_var(crate::constants::env_vars::VTCODE_EXPERIMENTAL_CODE_MODE)
        .and_then(|v| vtcode_commons::utils::parse_bool_env_value(&v))
        .unwrap_or(false)
}

/// External editor integration configuration
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct EditorToolConfig {
    /// Enable external editor support for `/edit` and keyboard shortcuts
    #[serde(default = "default_editor_enabled")]
    pub enabled: bool,

    /// Preferred editor command override (supports arguments, e.g. "code --wait")
    #[serde(default)]
    pub preferred_editor: String,

    /// Suspend the TUI event loop while editor is running
    #[serde(default = "default_editor_suspend_tui")]
    pub suspend_tui: bool,
}

/// Web fetch security mode
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum WebFetchMode {
    /// Blocklist mode: allow by default, block listed domains (default)
    #[default]
    Restricted,
    /// Allowlist mode: block by default, allow only listed domains
    Whitelist,
}

/// Web search provider identifier.
///
/// VT Code only targets the keyless DuckDuckGo HTML endpoint for web
/// search, so the provider enum is intentionally minimal. `Auto` defers to
/// the DDG default and is the recommended choice.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum WebSearchProvider {
    /// Default; same as `Duckduckgo` for now (kept for back-compat).
    #[default]
    Auto,
    /// Keyless DuckDuckGo HTML scraping (`https://html.duckduckgo.com/html/`).
    Duckduckgo,
}

impl WebSearchProvider {
    /// Return the canonical runtime backend identifier.
    #[must_use]
    pub const fn backend_id(self) -> &'static str {
        match self {
            Self::Auto | Self::Duckduckgo => "duckduckgo",
        }
    }
}

impl<'de> Deserialize<'de> for WebSearchProvider {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = String::deserialize(deserializer)?;
        match value.as_str() {
            "auto" => Ok(Self::Auto),
            "duckduckgo" => Ok(Self::Duckduckgo),
            _ => Err(serde::de::Error::unknown_variant(&value, &["auto", "duckduckgo"])),
        }
    }
}

/// Web Search tool configuration.
///
/// VT Code only uses the keyless DuckDuckGo HTML endpoint. The defaults
/// below are tuned to be polite to that endpoint and to keep the agent
/// responsive under constrained network conditions:
/// - `cooldown_ms`: minimum gap between consecutive live requests on the
///   same tool instance (avoids bursty hammering that triggers the DDG
///   anti-bot challenge).
/// - `cache_ttl_secs`: how long successful results are served from memory
///   before a fresh request is made.
/// - `session_max_requests`: hard cap on outbound requests per tool
///   instance (defends against runaway loops).
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct WebSearchConfig {
    /// Provider selection. The built-in backend is the keyless DuckDuckGo
    /// HTML endpoint; `auto` is retained as a compatibility alias.
    /// Options: "auto", "duckduckgo".
    #[serde(default)]
    pub provider: WebSearchProvider,

    /// Default cap on the number of results returned per call. Hard-capped
    /// at 20 by the runtime to keep responses inline-friendly.
    #[serde(default = "default_web_search_max_results")]
    pub max_results: usize,

    /// Per-request timeout in seconds. Capped at 60s by the runtime.
    #[serde(default = "default_web_search_timeout_secs")]
    pub timeout_secs: u64,

    /// Minimum gap between consecutive live requests, in milliseconds.
    /// Defaults to 3000ms (3s).
    #[serde(default = "default_web_search_cooldown_ms")]
    pub cooldown_ms: u64,

    /// How long successful search results are cached before a fresh
    /// request is made, in seconds. Defaults to 300s (5 min).
    #[serde(default = "default_web_search_cache_ttl_secs")]
    pub cache_ttl_secs: u64,

    /// Hard cap on outbound network requests per tool instance. Defaults
    /// to 12 as a conservative VTCode budget; this is not a DuckDuckGo quota.
    #[serde(default = "default_web_search_session_max_requests")]
    pub session_max_requests: u32,
}

/// Web Fetch tool security configuration
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct WebFetchConfig {
    /// Security mode: restricted (blocklist) or whitelist (allowlist)
    #[serde(default = "default_web_fetch_mode")]
    pub mode: WebFetchMode,

    /// Inline blocklist - Additional domains to block
    #[serde(default)]
    pub blocked_domains: Vec<String>,

    /// Inline whitelist - Domains to allow in restricted mode
    #[serde(default)]
    pub allowed_domains: Vec<String>,

    /// Additional blocked patterns
    #[serde(default)]
    pub blocked_patterns: Vec<String>,

    /// Strict HTTPS-only mode
    #[serde(default = "default_strict_https")]
    pub strict_https_only: bool,
}

impl Default for ToolsConfig {
    fn default() -> Self {
        let policies = DEFAULT_TOOL_POLICIES
            .iter()
            .map(|(tool, policy)| ((*tool).into(), policy.clone()))
            .collect::<IndexMap<_, _>>();
        Self {
            profile: ToolProfile::default(),
            default_policy: default_tool_policy(),
            policies,
            max_repeated_tool_calls: default_max_repeated_tool_calls(),
            max_consecutive_blocked_tool_calls_per_turn: default_max_consecutive_blocked_tool_calls_per_turn(),
            max_total_blocked_tool_calls_per_turn: None,
            blocked_tool_thresholds: IndexMap::new(),
            max_tool_rate_per_second: default_max_tool_rate_per_second(),
            max_sequential_spool_chunk_reads: default_max_sequential_spool_chunk_reads(),
            web_fetch: WebFetchConfig::default(),
            web_search: WebSearchConfig::default(),
            plugins: PluginRuntimeConfig::default(),
            editor: EditorToolConfig::default(),
            loop_thresholds: IndexMap::new(),
            client_tool_search: default_client_tool_search(),
            code_mode: CodeModeConfig::default(),
        }
    }
}

impl ToolsConfig {
    #[inline]
    pub fn tool_call_delay(&self) -> Option<Duration> {
        tool_call_delay_for_rate(self.max_tool_rate_per_second)
    }
}

#[inline]
pub fn tool_call_delay_for_rate(max_per_second: Option<usize>) -> Option<Duration> {
    let rate = max_per_second?;
    if rate == 0 {
        return None;
    }

    let nanos = 1_000_000_000u64.saturating_div(rate as u64).max(1);
    Some(Duration::from_nanos(nanos))
}

impl Default for WebFetchConfig {
    fn default() -> Self {
        Self {
            mode: default_web_fetch_mode(),
            blocked_domains: Vec::new(),
            allowed_domains: default_web_fetch_allowed_domains(),
            blocked_patterns: Vec::new(),
            strict_https_only: true,
        }
    }
}

/// Default `WebFetchConfig::allowed_domains` value.
///
/// Sourced from the curated TOML allowlist (shipped with the crate at
/// `data/network_allowlist.toml`) and filtered down to the categories
/// that make sense as `web_fetch` targets: search engines, specialized
/// knowledge bases, package registries, code-hosting platforms, and
/// web-crawl relays other than `defuddle.md`. AI provider endpoints,
/// OAuth flows, dev infrastructure, and OS-update mirrors are excluded
/// (those need auth or aren't useful as fetch targets).
///
/// The result is cached in a process-global `OnceLock` so the TOML parse
/// happens exactly once per process even though `WebFetchConfig::default`
/// is called from serde paths, the tool registry, and tests.
fn default_web_fetch_allowed_domains() -> Vec<String> {
    use std::sync::OnceLock;
    static CACHE: OnceLock<Vec<String>> = OnceLock::new();
    CACHE
        .get_or_init(|| crate::network_allowlist::NetworkAllowlist::load_default().web_fetch_relevant_domains())
        .clone()
}

impl Default for WebSearchConfig {
    fn default() -> Self {
        Self {
            provider: WebSearchProvider::default(),
            max_results: default_web_search_max_results(),
            timeout_secs: default_web_search_timeout_secs(),
            cooldown_ms: default_web_search_cooldown_ms(),
            cache_ttl_secs: default_web_search_cache_ttl_secs(),
            session_max_requests: default_web_search_session_max_requests(),
        }
    }
}

impl Default for EditorToolConfig {
    fn default() -> Self {
        Self {
            enabled: default_editor_enabled(),
            preferred_editor: String::new(),
            suspend_tui: default_editor_suspend_tui(),
        }
    }
}

/// Tool execution policy
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ToolPolicy {
    /// Allow execution without confirmation
    Allow,
    /// Prompt user for confirmation
    #[default]
    Prompt,
    /// Deny execution
    Deny,
}

#[inline]
const fn default_tool_policy() -> ToolPolicy {
    ToolPolicy::Prompt
}

#[inline]
const fn default_max_repeated_tool_calls() -> usize {
    defaults::DEFAULT_MAX_REPEATED_TOOL_CALLS
}

#[inline]
const fn default_max_consecutive_blocked_tool_calls_per_turn() -> usize {
    defaults::DEFAULT_MAX_CONSECUTIVE_BLOCKED_TOOL_CALLS_PER_TURN
}

#[inline]
const fn default_max_tool_rate_per_second() -> Option<usize> {
    None
}

#[inline]
const fn default_max_sequential_spool_chunk_reads() -> usize {
    defaults::DEFAULT_MAX_SEQUENTIAL_SPOOL_CHUNK_READS_PER_TURN
}

#[inline]
fn default_web_fetch_mode() -> WebFetchMode {
    WebFetchMode::Restricted
}

fn default_strict_https() -> bool {
    true
}

#[inline]
const fn default_web_search_max_results() -> usize {
    8
}

#[inline]
const fn default_web_search_timeout_secs() -> u64 {
    20
}

#[inline]
const fn default_web_search_cooldown_ms() -> u64 {
    3_000
}

#[inline]
const fn default_web_search_cache_ttl_secs() -> u64 {
    300
}

#[inline]
const fn default_web_search_session_max_requests() -> u32 {
    12
}

#[inline]
const fn default_editor_enabled() -> bool {
    true
}

#[inline]
const fn default_editor_suspend_tui() -> bool {
    true
}

#[inline]
const fn default_client_tool_search() -> bool {
    true
}

const DEFAULT_TOOL_POLICIES: &[(&str, ToolPolicy)] = &[
    // Core workflow tools (non-destructive)
    (tools::START_PLANNING, ToolPolicy::Allow),
    (tools::TASK_TRACKER, ToolPolicy::Allow),
    (tools::MATRIX, ToolPolicy::Allow),
    // Public model-facing tools.
    (tools::CODE_SEARCH, ToolPolicy::Allow),
    (tools::EXEC_COMMAND, ToolPolicy::Allow),
    (tools::WRITE_STDIN, ToolPolicy::Allow),
    (tools::APPLY_PATCH, ToolPolicy::Prompt),
];

#[cfg(test)]
mod tests;