Skip to main content

vtcode_config/core/
tools.rs

1use indexmap::IndexMap;
2use serde::{Deserialize, Serialize};
3use std::time::Duration;
4
5use crate::constants::{defaults, tools};
6use crate::core::plugins::PluginRuntimeConfig;
7
8/// Model-facing tool profile for a session.
9#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
10#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
11#[serde(rename_all = "snake_case")]
12pub enum ToolProfile {
13    /// VT Code standard baseline: exec_command, write_stdin, and apply_patch.
14    #[default]
15    #[serde(rename = "vt_code")]
16    #[serde(alias = "codex_default")]
17    #[cfg_attr(feature = "schema", schemars(rename = "vt_code"))]
18    VtCode,
19    /// VTCode specialised tools, including code_search and eligible dynamic tools.
20    #[serde(rename = "advanced_vtcode")]
21    #[cfg_attr(feature = "schema", schemars(rename = "advanced_vtcode"))]
22    AdvancedVtCode,
23}
24
25/// Tools configuration
26#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
27#[derive(Debug, Clone, Deserialize, Serialize)]
28pub struct ToolsConfig {
29    /// Model-facing tool profile.
30    #[serde(default)]
31    pub profile: ToolProfile,
32
33    /// Default policy for tools not explicitly listed
34    #[serde(default = "default_tool_policy")]
35    pub default_policy: ToolPolicy,
36
37    /// Specific tool policies
38    #[serde(default)]
39    #[cfg_attr(
40        feature = "schema",
41        schemars(with = "std::collections::BTreeMap<String, ToolPolicy>")
42    )]
43    pub policies: IndexMap<String, ToolPolicy>,
44
45    /// Maximum number of times the same tool invocation can be retried with the
46    /// identical arguments within a single turn.
47    #[serde(default = "default_max_repeated_tool_calls")]
48    pub max_repeated_tool_calls: usize,
49
50    /// Maximum consecutive blocked tool calls allowed per turn before forcing a
51    /// turn break. The total fuse is 2x this value in normal mode, 4x in Plan
52    /// Mode, and this value in recovery mode, unless overridden by
53    /// `max_total_blocked_tool_calls_per_turn`.
54    #[serde(default = "default_max_consecutive_blocked_tool_calls_per_turn")]
55    pub max_consecutive_blocked_tool_calls_per_turn: usize,
56
57    /// Optional explicit cap for total blocked tool calls per turn. When unset,
58    /// the runtime derives it from the consecutive cap (2x normal, 4x plan,
59    /// 1x recovery) so existing configs keep their behavior.
60    #[serde(default)]
61    pub max_total_blocked_tool_calls_per_turn: Option<usize>,
62
63    /// Per-tool consecutive blocked-call cap overrides keyed by tool name.
64    /// Allows read-only tools (e.g. `code_search`) to tolerate more denies
65    /// than mutating tools (e.g. `exec_command`) before tripping the fuse.
66    #[serde(default)]
67    #[cfg_attr(feature = "schema", schemars(with = "std::collections::BTreeMap<String, usize>"))]
68    pub blocked_tool_thresholds: IndexMap<String, usize>,
69
70    /// Optional per-second rate limit for tool calls to smooth bursty retries.
71    /// When unset, the runtime defaults apply.
72    #[serde(default = "default_max_tool_rate_per_second")]
73    pub max_tool_rate_per_second: Option<usize>,
74
75    /// Maximum sequential spool-chunk `read_file` calls allowed per turn before
76    /// nudging the agent to switch to targeted extraction/summarization.
77    #[serde(default = "default_max_sequential_spool_chunk_reads")]
78    pub max_sequential_spool_chunk_reads: usize,
79
80    /// Web Fetch tool security configuration
81    #[serde(default)]
82    pub web_fetch: WebFetchConfig,
83
84    /// Web Search tool configuration (provider selection, result caps, timeouts).
85    #[serde(default)]
86    pub web_search: WebSearchConfig,
87
88    /// Dynamic plugin runtime configuration
89    #[serde(default)]
90    pub plugins: PluginRuntimeConfig,
91
92    /// External editor integration settings used by `/edit` and keyboard shortcuts
93    #[serde(default)]
94    pub editor: EditorToolConfig,
95
96    /// Tool-specific loop thresholds (Adaptive Loop Detection)
97    /// Allows setting higher loop limits for read-only tools (e.g., ls, grep)
98    /// and lower limits for mutating tools.
99    #[serde(default)]
100    pub loop_thresholds: IndexMap<String, usize>,
101
102    /// Enables client-local deferred tool loading for providers without a
103    /// hosted tool search (e.g. Gemini). When enabled, tools flagged
104    /// `defer_loading: true` are omitted from the request payload instead
105    /// of being sent eagerly, and a compact summary of what is discoverable
106    /// is appended to the system prompt; the model loads them via the
107    /// local MCP discovery tools. Enabled by default because
108    /// eager MCP schemas are the dominant source of token inflation.
109    #[serde(default = "default_client_tool_search")]
110    pub client_tool_search: bool,
111
112    /// Code Mode pilot configuration (agent-written snippet execution).
113    ///
114    /// Off by default. `enabled = true` in config opts the workspace in;
115    /// the `VTCODE_EXPERIMENTAL_CODE_MODE` environment variable fills the
116    /// default when the key is absent (so CI and containers can flip the
117    /// pilot without editing config files). The final override — env wins
118    /// over an explicit config value — is resolved once per session in
119    /// `ToolRegistry::apply_config_policies` (`config OR env`), because
120    /// serde `default` only fills missing keys and cannot express
121    /// env-over-explicit at parse time.
122    #[serde(default)]
123    pub code_mode: CodeModeConfig,
124}
125
126/// Code Mode pilot configuration.
127///
128/// Experimental: lets the agent compose many tool calls inside one
129/// sandboxed Python 3 / Node.js snippet instead of one model round trip
130/// per call. Direct tool calls remain the default path.
131#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
132#[derive(Debug, Clone, Deserialize, Serialize)]
133pub struct CodeModeConfig {
134    /// Opt the workspace in to experimental agent-written snippet
135    /// execution. Default `false` (or the env var when the config key is
136    /// absent). The session-effective flag additionally ORs the env var at
137    /// `ToolRegistry::apply_config_policies`, so env wins over explicit
138    /// config at runtime.
139    #[serde(default = "default_code_mode_enabled")]
140    pub enabled: bool,
141}
142
143impl Default for CodeModeConfig {
144    fn default() -> Self {
145        Self { enabled: default_code_mode_enabled() }
146    }
147}
148
149fn default_code_mode_enabled() -> bool {
150    crate::env_helpers::read_env_var(crate::constants::env_vars::VTCODE_EXPERIMENTAL_CODE_MODE)
151        .and_then(|v| vtcode_commons::utils::parse_bool_env_value(&v))
152        .unwrap_or(false)
153}
154
155/// External editor integration configuration
156#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
157#[derive(Debug, Clone, Deserialize, Serialize)]
158pub struct EditorToolConfig {
159    /// Enable external editor support for `/edit` and keyboard shortcuts
160    #[serde(default = "default_editor_enabled")]
161    pub enabled: bool,
162
163    /// Preferred editor command override (supports arguments, e.g. "code --wait")
164    #[serde(default)]
165    pub preferred_editor: String,
166
167    /// Suspend the TUI event loop while editor is running
168    #[serde(default = "default_editor_suspend_tui")]
169    pub suspend_tui: bool,
170}
171
172/// Web fetch security mode
173#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
174#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
175#[serde(rename_all = "snake_case")]
176pub enum WebFetchMode {
177    /// Blocklist mode: allow by default, block listed domains (default)
178    #[default]
179    Restricted,
180    /// Allowlist mode: block by default, allow only listed domains
181    Whitelist,
182}
183
184/// Web search provider identifier.
185///
186/// VT Code only targets the keyless DuckDuckGo HTML endpoint for web
187/// search, so the provider enum is intentionally minimal. `Auto` defers to
188/// the DDG default and is the recommended choice.
189#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
190#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq, Hash)]
191#[serde(rename_all = "snake_case")]
192pub enum WebSearchProvider {
193    /// Default; same as `Duckduckgo` for now (kept for back-compat).
194    #[default]
195    Auto,
196    /// Keyless DuckDuckGo HTML scraping (`https://html.duckduckgo.com/html/`).
197    Duckduckgo,
198}
199
200impl WebSearchProvider {
201    /// Return the canonical runtime backend identifier.
202    #[must_use]
203    pub const fn backend_id(self) -> &'static str {
204        match self {
205            Self::Auto | Self::Duckduckgo => "duckduckgo",
206        }
207    }
208}
209
210impl<'de> Deserialize<'de> for WebSearchProvider {
211    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
212        let value = String::deserialize(deserializer)?;
213        match value.as_str() {
214            "auto" => Ok(Self::Auto),
215            "duckduckgo" => Ok(Self::Duckduckgo),
216            _ => Err(serde::de::Error::unknown_variant(&value, &["auto", "duckduckgo"])),
217        }
218    }
219}
220
221/// Web Search tool configuration.
222///
223/// VT Code only uses the keyless DuckDuckGo HTML endpoint. The defaults
224/// below are tuned to be polite to that endpoint and to keep the agent
225/// responsive under constrained network conditions:
226/// - `cooldown_ms`: minimum gap between consecutive live requests on the
227///   same tool instance (avoids bursty hammering that triggers the DDG
228///   anti-bot challenge).
229/// - `cache_ttl_secs`: how long successful results are served from memory
230///   before a fresh request is made.
231/// - `session_max_requests`: hard cap on outbound requests per tool
232///   instance (defends against runaway loops).
233#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
234#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
235pub struct WebSearchConfig {
236    /// Provider selection. The built-in backend is the keyless DuckDuckGo
237    /// HTML endpoint; `auto` is retained as a compatibility alias.
238    /// Options: "auto", "duckduckgo".
239    #[serde(default)]
240    pub provider: WebSearchProvider,
241
242    /// Default cap on the number of results returned per call. Hard-capped
243    /// at 20 by the runtime to keep responses inline-friendly.
244    #[serde(default = "default_web_search_max_results")]
245    pub max_results: usize,
246
247    /// Per-request timeout in seconds. Capped at 60s by the runtime.
248    #[serde(default = "default_web_search_timeout_secs")]
249    pub timeout_secs: u64,
250
251    /// Minimum gap between consecutive live requests, in milliseconds.
252    /// Defaults to 3000ms (3s).
253    #[serde(default = "default_web_search_cooldown_ms")]
254    pub cooldown_ms: u64,
255
256    /// How long successful search results are cached before a fresh
257    /// request is made, in seconds. Defaults to 300s (5 min).
258    #[serde(default = "default_web_search_cache_ttl_secs")]
259    pub cache_ttl_secs: u64,
260
261    /// Hard cap on outbound network requests per tool instance. Defaults
262    /// to 12 as a conservative VTCode budget; this is not a DuckDuckGo quota.
263    #[serde(default = "default_web_search_session_max_requests")]
264    pub session_max_requests: u32,
265}
266
267/// Web Fetch tool security configuration
268#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
269#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
270pub struct WebFetchConfig {
271    /// Security mode: restricted (blocklist) or whitelist (allowlist)
272    #[serde(default = "default_web_fetch_mode")]
273    pub mode: WebFetchMode,
274
275    /// Inline blocklist - Additional domains to block
276    #[serde(default)]
277    pub blocked_domains: Vec<String>,
278
279    /// Inline whitelist - Domains to allow in restricted mode
280    #[serde(default)]
281    pub allowed_domains: Vec<String>,
282
283    /// Additional blocked patterns
284    #[serde(default)]
285    pub blocked_patterns: Vec<String>,
286
287    /// Strict HTTPS-only mode
288    #[serde(default = "default_strict_https")]
289    pub strict_https_only: bool,
290}
291
292impl Default for ToolsConfig {
293    fn default() -> Self {
294        let policies = DEFAULT_TOOL_POLICIES
295            .iter()
296            .map(|(tool, policy)| ((*tool).into(), policy.clone()))
297            .collect::<IndexMap<_, _>>();
298        Self {
299            profile: ToolProfile::default(),
300            default_policy: default_tool_policy(),
301            policies,
302            max_repeated_tool_calls: default_max_repeated_tool_calls(),
303            max_consecutive_blocked_tool_calls_per_turn: default_max_consecutive_blocked_tool_calls_per_turn(),
304            max_total_blocked_tool_calls_per_turn: None,
305            blocked_tool_thresholds: IndexMap::new(),
306            max_tool_rate_per_second: default_max_tool_rate_per_second(),
307            max_sequential_spool_chunk_reads: default_max_sequential_spool_chunk_reads(),
308            web_fetch: WebFetchConfig::default(),
309            web_search: WebSearchConfig::default(),
310            plugins: PluginRuntimeConfig::default(),
311            editor: EditorToolConfig::default(),
312            loop_thresholds: IndexMap::new(),
313            client_tool_search: default_client_tool_search(),
314            code_mode: CodeModeConfig::default(),
315        }
316    }
317}
318
319impl ToolsConfig {
320    #[inline]
321    pub fn tool_call_delay(&self) -> Option<Duration> {
322        tool_call_delay_for_rate(self.max_tool_rate_per_second)
323    }
324}
325
326#[inline]
327pub fn tool_call_delay_for_rate(max_per_second: Option<usize>) -> Option<Duration> {
328    let rate = max_per_second?;
329    if rate == 0 {
330        return None;
331    }
332
333    let nanos = 1_000_000_000u64.saturating_div(rate as u64).max(1);
334    Some(Duration::from_nanos(nanos))
335}
336
337impl Default for WebFetchConfig {
338    fn default() -> Self {
339        Self {
340            mode: default_web_fetch_mode(),
341            blocked_domains: Vec::new(),
342            allowed_domains: default_web_fetch_allowed_domains(),
343            blocked_patterns: Vec::new(),
344            strict_https_only: true,
345        }
346    }
347}
348
349/// Default `WebFetchConfig::allowed_domains` value.
350///
351/// Sourced from the curated TOML allowlist (shipped with the crate at
352/// `data/network_allowlist.toml`) and filtered down to the categories
353/// that make sense as `web_fetch` targets: search engines, specialized
354/// knowledge bases, package registries, code-hosting platforms, and
355/// web-crawl relays other than `defuddle.md`. AI provider endpoints,
356/// OAuth flows, dev infrastructure, and OS-update mirrors are excluded
357/// (those need auth or aren't useful as fetch targets).
358///
359/// The result is cached in a process-global `OnceLock` so the TOML parse
360/// happens exactly once per process even though `WebFetchConfig::default`
361/// is called from serde paths, the tool registry, and tests.
362fn default_web_fetch_allowed_domains() -> Vec<String> {
363    use std::sync::OnceLock;
364    static CACHE: OnceLock<Vec<String>> = OnceLock::new();
365    CACHE
366        .get_or_init(|| crate::network_allowlist::NetworkAllowlist::load_default().web_fetch_relevant_domains())
367        .clone()
368}
369
370impl Default for WebSearchConfig {
371    fn default() -> Self {
372        Self {
373            provider: WebSearchProvider::default(),
374            max_results: default_web_search_max_results(),
375            timeout_secs: default_web_search_timeout_secs(),
376            cooldown_ms: default_web_search_cooldown_ms(),
377            cache_ttl_secs: default_web_search_cache_ttl_secs(),
378            session_max_requests: default_web_search_session_max_requests(),
379        }
380    }
381}
382
383impl Default for EditorToolConfig {
384    fn default() -> Self {
385        Self {
386            enabled: default_editor_enabled(),
387            preferred_editor: String::new(),
388            suspend_tui: default_editor_suspend_tui(),
389        }
390    }
391}
392
393/// Tool execution policy
394#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
395#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
396#[serde(rename_all = "lowercase")]
397pub enum ToolPolicy {
398    /// Allow execution without confirmation
399    Allow,
400    /// Prompt user for confirmation
401    #[default]
402    Prompt,
403    /// Deny execution
404    Deny,
405}
406
407#[inline]
408const fn default_tool_policy() -> ToolPolicy {
409    ToolPolicy::Prompt
410}
411
412#[inline]
413const fn default_max_repeated_tool_calls() -> usize {
414    defaults::DEFAULT_MAX_REPEATED_TOOL_CALLS
415}
416
417#[inline]
418const fn default_max_consecutive_blocked_tool_calls_per_turn() -> usize {
419    defaults::DEFAULT_MAX_CONSECUTIVE_BLOCKED_TOOL_CALLS_PER_TURN
420}
421
422#[inline]
423const fn default_max_tool_rate_per_second() -> Option<usize> {
424    None
425}
426
427#[inline]
428const fn default_max_sequential_spool_chunk_reads() -> usize {
429    defaults::DEFAULT_MAX_SEQUENTIAL_SPOOL_CHUNK_READS_PER_TURN
430}
431
432#[inline]
433fn default_web_fetch_mode() -> WebFetchMode {
434    WebFetchMode::Restricted
435}
436
437fn default_strict_https() -> bool {
438    true
439}
440
441#[inline]
442const fn default_web_search_max_results() -> usize {
443    8
444}
445
446#[inline]
447const fn default_web_search_timeout_secs() -> u64 {
448    20
449}
450
451#[inline]
452const fn default_web_search_cooldown_ms() -> u64 {
453    3_000
454}
455
456#[inline]
457const fn default_web_search_cache_ttl_secs() -> u64 {
458    300
459}
460
461#[inline]
462const fn default_web_search_session_max_requests() -> u32 {
463    12
464}
465
466#[inline]
467const fn default_editor_enabled() -> bool {
468    true
469}
470
471#[inline]
472const fn default_editor_suspend_tui() -> bool {
473    true
474}
475
476#[inline]
477const fn default_client_tool_search() -> bool {
478    true
479}
480
481const DEFAULT_TOOL_POLICIES: &[(&str, ToolPolicy)] = &[
482    // Core workflow tools (non-destructive)
483    (tools::START_PLANNING, ToolPolicy::Allow),
484    (tools::TASK_TRACKER, ToolPolicy::Allow),
485    (tools::MATRIX, ToolPolicy::Allow),
486    // Public model-facing tools.
487    (tools::CODE_SEARCH, ToolPolicy::Allow),
488    (tools::EXEC_COMMAND, ToolPolicy::Allow),
489    (tools::WRITE_STDIN, ToolPolicy::Allow),
490    (tools::APPLY_PATCH, ToolPolicy::Prompt),
491];
492
493#[cfg(test)]
494mod tests;