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
113/// External editor integration configuration
114#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
115#[derive(Debug, Clone, Deserialize, Serialize)]
116pub struct EditorToolConfig {
117    /// Enable external editor support for `/edit` and keyboard shortcuts
118    #[serde(default = "default_editor_enabled")]
119    pub enabled: bool,
120
121    /// Preferred editor command override (supports arguments, e.g. "code --wait")
122    #[serde(default)]
123    pub preferred_editor: String,
124
125    /// Suspend the TUI event loop while editor is running
126    #[serde(default = "default_editor_suspend_tui")]
127    pub suspend_tui: bool,
128}
129
130/// Web fetch security mode
131#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
132#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
133#[serde(rename_all = "snake_case")]
134pub enum WebFetchMode {
135    /// Blocklist mode: allow by default, block listed domains (default)
136    #[default]
137    Restricted,
138    /// Allowlist mode: block by default, allow only listed domains
139    Whitelist,
140}
141
142/// Web search provider identifier.
143///
144/// VT Code only targets the keyless DuckDuckGo HTML endpoint for web
145/// search, so the provider enum is intentionally minimal. `Auto` defers to
146/// the DDG default and is the recommended choice.
147#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
148#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq, Hash)]
149#[serde(rename_all = "snake_case")]
150pub enum WebSearchProvider {
151    /// Default; same as `Duckduckgo` for now (kept for back-compat).
152    #[default]
153    Auto,
154    /// Keyless DuckDuckGo HTML scraping (`https://html.duckduckgo.com/html/`).
155    Duckduckgo,
156}
157
158impl WebSearchProvider {
159    /// Return the canonical runtime backend identifier.
160    #[must_use]
161    pub const fn backend_id(self) -> &'static str {
162        match self {
163            Self::Auto | Self::Duckduckgo => "duckduckgo",
164        }
165    }
166}
167
168impl<'de> Deserialize<'de> for WebSearchProvider {
169    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
170        let value = String::deserialize(deserializer)?;
171        match value.as_str() {
172            "auto" => Ok(Self::Auto),
173            "duckduckgo" => Ok(Self::Duckduckgo),
174            _ => Err(serde::de::Error::unknown_variant(&value, &["auto", "duckduckgo"])),
175        }
176    }
177}
178
179/// Web Search tool configuration.
180///
181/// VT Code only uses the keyless DuckDuckGo HTML endpoint. The defaults
182/// below are tuned to be polite to that endpoint and to keep the agent
183/// responsive under constrained network conditions:
184/// - `cooldown_ms`: minimum gap between consecutive live requests on the
185///   same tool instance (avoids bursty hammering that triggers the DDG
186///   anti-bot challenge).
187/// - `cache_ttl_secs`: how long successful results are served from memory
188///   before a fresh request is made.
189/// - `session_max_requests`: hard cap on outbound requests per tool
190///   instance (defends against runaway loops).
191#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
192#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
193pub struct WebSearchConfig {
194    /// Provider selection. The built-in backend is the keyless DuckDuckGo
195    /// HTML endpoint; `auto` is retained as a compatibility alias.
196    /// Options: "auto", "duckduckgo".
197    #[serde(default)]
198    pub provider: WebSearchProvider,
199
200    /// Default cap on the number of results returned per call. Hard-capped
201    /// at 20 by the runtime to keep responses inline-friendly.
202    #[serde(default = "default_web_search_max_results")]
203    pub max_results: usize,
204
205    /// Per-request timeout in seconds. Capped at 60s by the runtime.
206    #[serde(default = "default_web_search_timeout_secs")]
207    pub timeout_secs: u64,
208
209    /// Minimum gap between consecutive live requests, in milliseconds.
210    /// Defaults to 3000ms (3s).
211    #[serde(default = "default_web_search_cooldown_ms")]
212    pub cooldown_ms: u64,
213
214    /// How long successful search results are cached before a fresh
215    /// request is made, in seconds. Defaults to 300s (5 min).
216    #[serde(default = "default_web_search_cache_ttl_secs")]
217    pub cache_ttl_secs: u64,
218
219    /// Hard cap on outbound network requests per tool instance. Defaults
220    /// to 12 as a conservative VTCode budget; this is not a DuckDuckGo quota.
221    #[serde(default = "default_web_search_session_max_requests")]
222    pub session_max_requests: u32,
223}
224
225/// Web Fetch tool security configuration
226#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
227#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
228pub struct WebFetchConfig {
229    /// Security mode: restricted (blocklist) or whitelist (allowlist)
230    #[serde(default = "default_web_fetch_mode")]
231    pub mode: WebFetchMode,
232
233    /// Inline blocklist - Additional domains to block
234    #[serde(default)]
235    pub blocked_domains: Vec<String>,
236
237    /// Inline whitelist - Domains to allow in restricted mode
238    #[serde(default)]
239    pub allowed_domains: Vec<String>,
240
241    /// Additional blocked patterns
242    #[serde(default)]
243    pub blocked_patterns: Vec<String>,
244
245    /// Strict HTTPS-only mode
246    #[serde(default = "default_strict_https")]
247    pub strict_https_only: bool,
248}
249
250impl Default for ToolsConfig {
251    fn default() -> Self {
252        let policies = DEFAULT_TOOL_POLICIES
253            .iter()
254            .map(|(tool, policy)| ((*tool).into(), policy.clone()))
255            .collect::<IndexMap<_, _>>();
256        Self {
257            profile: ToolProfile::default(),
258            default_policy: default_tool_policy(),
259            policies,
260            max_repeated_tool_calls: default_max_repeated_tool_calls(),
261            max_consecutive_blocked_tool_calls_per_turn: default_max_consecutive_blocked_tool_calls_per_turn(),
262            max_total_blocked_tool_calls_per_turn: None,
263            blocked_tool_thresholds: IndexMap::new(),
264            max_tool_rate_per_second: default_max_tool_rate_per_second(),
265            max_sequential_spool_chunk_reads: default_max_sequential_spool_chunk_reads(),
266            web_fetch: WebFetchConfig::default(),
267            web_search: WebSearchConfig::default(),
268            plugins: PluginRuntimeConfig::default(),
269            editor: EditorToolConfig::default(),
270            loop_thresholds: IndexMap::new(),
271            client_tool_search: default_client_tool_search(),
272        }
273    }
274}
275
276impl ToolsConfig {
277    #[inline]
278    pub fn tool_call_delay(&self) -> Option<Duration> {
279        tool_call_delay_for_rate(self.max_tool_rate_per_second)
280    }
281}
282
283#[inline]
284pub fn tool_call_delay_for_rate(max_per_second: Option<usize>) -> Option<Duration> {
285    let rate = max_per_second?;
286    if rate == 0 {
287        return None;
288    }
289
290    let nanos = 1_000_000_000u64.saturating_div(rate as u64).max(1);
291    Some(Duration::from_nanos(nanos))
292}
293
294impl Default for WebFetchConfig {
295    fn default() -> Self {
296        Self {
297            mode: default_web_fetch_mode(),
298            blocked_domains: Vec::new(),
299            allowed_domains: default_web_fetch_allowed_domains(),
300            blocked_patterns: Vec::new(),
301            strict_https_only: true,
302        }
303    }
304}
305
306/// Default `WebFetchConfig::allowed_domains` value.
307///
308/// Sourced from the curated TOML allowlist (shipped with the crate at
309/// `data/network_allowlist.toml`) and filtered down to the categories
310/// that make sense as `web_fetch` targets: search engines, specialized
311/// knowledge bases, package registries, code-hosting platforms, and
312/// web-crawl relays other than `defuddle.md`. AI provider endpoints,
313/// OAuth flows, dev infrastructure, and OS-update mirrors are excluded
314/// (those need auth or aren't useful as fetch targets).
315///
316/// The result is cached in a process-global `OnceLock` so the TOML parse
317/// happens exactly once per process even though `WebFetchConfig::default`
318/// is called from serde paths, the tool registry, and tests.
319fn default_web_fetch_allowed_domains() -> Vec<String> {
320    use std::sync::OnceLock;
321    static CACHE: OnceLock<Vec<String>> = OnceLock::new();
322    CACHE
323        .get_or_init(|| crate::network_allowlist::NetworkAllowlist::load_default().web_fetch_relevant_domains())
324        .clone()
325}
326
327impl Default for WebSearchConfig {
328    fn default() -> Self {
329        Self {
330            provider: WebSearchProvider::default(),
331            max_results: default_web_search_max_results(),
332            timeout_secs: default_web_search_timeout_secs(),
333            cooldown_ms: default_web_search_cooldown_ms(),
334            cache_ttl_secs: default_web_search_cache_ttl_secs(),
335            session_max_requests: default_web_search_session_max_requests(),
336        }
337    }
338}
339
340impl Default for EditorToolConfig {
341    fn default() -> Self {
342        Self {
343            enabled: default_editor_enabled(),
344            preferred_editor: String::new(),
345            suspend_tui: default_editor_suspend_tui(),
346        }
347    }
348}
349
350/// Tool execution policy
351#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
352#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
353#[serde(rename_all = "lowercase")]
354pub enum ToolPolicy {
355    /// Allow execution without confirmation
356    Allow,
357    /// Prompt user for confirmation
358    #[default]
359    Prompt,
360    /// Deny execution
361    Deny,
362}
363
364#[inline]
365const fn default_tool_policy() -> ToolPolicy {
366    ToolPolicy::Prompt
367}
368
369#[inline]
370const fn default_max_repeated_tool_calls() -> usize {
371    defaults::DEFAULT_MAX_REPEATED_TOOL_CALLS
372}
373
374#[inline]
375const fn default_max_consecutive_blocked_tool_calls_per_turn() -> usize {
376    defaults::DEFAULT_MAX_CONSECUTIVE_BLOCKED_TOOL_CALLS_PER_TURN
377}
378
379#[inline]
380const fn default_max_tool_rate_per_second() -> Option<usize> {
381    None
382}
383
384#[inline]
385const fn default_max_sequential_spool_chunk_reads() -> usize {
386    defaults::DEFAULT_MAX_SEQUENTIAL_SPOOL_CHUNK_READS_PER_TURN
387}
388
389#[inline]
390fn default_web_fetch_mode() -> WebFetchMode {
391    WebFetchMode::Restricted
392}
393
394fn default_strict_https() -> bool {
395    true
396}
397
398#[inline]
399const fn default_web_search_max_results() -> usize {
400    8
401}
402
403#[inline]
404const fn default_web_search_timeout_secs() -> u64 {
405    20
406}
407
408#[inline]
409const fn default_web_search_cooldown_ms() -> u64 {
410    3_000
411}
412
413#[inline]
414const fn default_web_search_cache_ttl_secs() -> u64 {
415    300
416}
417
418#[inline]
419const fn default_web_search_session_max_requests() -> u32 {
420    12
421}
422
423#[inline]
424const fn default_editor_enabled() -> bool {
425    true
426}
427
428#[inline]
429const fn default_editor_suspend_tui() -> bool {
430    true
431}
432
433#[inline]
434const fn default_client_tool_search() -> bool {
435    true
436}
437
438const DEFAULT_TOOL_POLICIES: &[(&str, ToolPolicy)] = &[
439    // Core workflow tools (non-destructive)
440    (tools::START_PLANNING, ToolPolicy::Allow),
441    (tools::TASK_TRACKER, ToolPolicy::Allow),
442    (tools::MATRIX, ToolPolicy::Allow),
443    // Public model-facing tools.
444    (tools::CODE_SEARCH, ToolPolicy::Allow),
445    (tools::EXEC_COMMAND, ToolPolicy::Allow),
446    (tools::WRITE_STDIN, ToolPolicy::Allow),
447    (tools::APPLY_PATCH, ToolPolicy::Prompt),
448];
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    #[test]
455    fn tools_config_defaults_to_vt_code_profile() {
456        assert_eq!(ToolsConfig::default().profile, ToolProfile::VtCode);
457    }
458
459    #[test]
460    fn vt_code_profile_round_trips_through_toml() {
461        let config: ToolsConfig = toml::from_str("profile = \"vt_code\"").expect("vt_code tool profile should parse");
462        assert_eq!(config.profile, ToolProfile::VtCode);
463
464        let serialised = toml::to_string(&config).expect("tools config should serialise");
465        assert!(serialised.contains("profile = \"vt_code\""));
466
467        let round_tripped: ToolsConfig = toml::from_str(&serialised).expect("serialised tools config should parse");
468        assert_eq!(round_tripped.profile, ToolProfile::VtCode);
469    }
470
471    #[test]
472    fn tool_profile_round_trips_through_toml() {
473        let config: ToolsConfig =
474            toml::from_str("profile = \"advanced_vtcode\"").expect("advanced tool profile should parse");
475        assert_eq!(config.profile, ToolProfile::AdvancedVtCode);
476
477        let serialised = toml::to_string(&config).expect("tools config should serialise");
478        assert!(serialised.contains("profile = \"advanced_vtcode\""));
479
480        let round_tripped: ToolsConfig = toml::from_str(&serialised).expect("serialised tools config should parse");
481        assert_eq!(round_tripped.profile, ToolProfile::AdvancedVtCode);
482    }
483
484    #[test]
485    fn tool_profile_rejects_unintended_derived_spelling() {
486        let error = toml::from_str::<ToolsConfig>("profile = \"advanced_vt_code\"")
487            .expect_err("unintended spelling should fail")
488            .to_string();
489
490        assert!(error.contains("unknown variant `advanced_vt_code`"), "{error}");
491        assert!(error.contains("`advanced_vtcode`"), "{error}");
492    }
493
494    #[test]
495    fn invalid_tool_profile_reports_allowed_values() {
496        let error = toml::from_str::<ToolsConfig>("profile = \"experimental\"")
497            .expect_err("unknown tool profile should fail")
498            .to_string();
499
500        assert!(error.contains("unknown variant `experimental`"), "{error}");
501        assert!(error.contains("`vt_code`"), "{error}");
502        assert!(error.contains("`advanced_vtcode`"), "{error}");
503    }
504
505    #[cfg(feature = "schema")]
506    #[test]
507    fn tools_config_schema_includes_profile_values() {
508        let schema = schemars::schema_for!(ToolsConfig);
509        let schema_json = serde_json::to_value(schema).expect("schema should serialise");
510        let schema_text = serde_json::to_string(&schema_json).expect("schema should stringify");
511
512        assert!(schema_json["properties"].get("profile").is_some());
513        assert!(schema_text.contains("vt_code"));
514        assert!(schema_text.contains("advanced_vtcode"));
515    }
516
517    #[test]
518    fn editor_config_defaults_are_enabled() {
519        let config = ToolsConfig::default();
520        assert!(config.editor.enabled);
521        assert!(config.editor.preferred_editor.is_empty());
522        assert!(config.editor.suspend_tui);
523    }
524
525    #[test]
526    fn tools_config_ignores_removed_tool_loop_budget_key() {
527        // `max_tool_loops` was removed; stale configs carrying it must still
528        // parse (the key is pruned on the next save with a warning).
529        let parsed: ToolsConfig = toml::from_str("max_tool_loops = 20").expect("stale loop-budget key must parse");
530        assert_eq!(parsed.max_repeated_tool_calls, defaults::DEFAULT_MAX_REPEATED_TOOL_CALLS);
531    }
532
533    #[test]
534    fn tool_call_delay_for_rate_ignores_unset_or_zero_limits() {
535        assert_eq!(tool_call_delay_for_rate(None), None);
536        assert_eq!(tool_call_delay_for_rate(Some(0)), None);
537    }
538
539    #[test]
540    fn tool_call_delay_for_rate_uses_per_second_interval() {
541        assert_eq!(tool_call_delay_for_rate(Some(4)), Some(Duration::from_millis(250)));
542    }
543
544    #[test]
545    fn default_tool_policies_only_seed_current_public_surface() {
546        let config = ToolsConfig::default();
547
548        assert_eq!(config.policies.get(tools::EXEC_COMMAND), Some(&ToolPolicy::Allow));
549        assert_eq!(config.policies.get(tools::WRITE_STDIN), Some(&ToolPolicy::Allow));
550        assert_eq!(config.policies.get(tools::CODE_SEARCH), Some(&ToolPolicy::Allow));
551        assert_eq!(config.policies.get(tools::APPLY_PATCH), Some(&ToolPolicy::Prompt));
552        for legacy_tool in [
553            tools::UNIFIED_EXEC,
554            tools::UNIFIED_SEARCH,
555            tools::UNIFIED_FILE,
556            tools::READ_FILE,
557            tools::WRITE_FILE,
558            tools::EDIT_FILE,
559            tools::RUN_PTY_CMD,
560            tools::READ_PTY_SESSION,
561            tools::LIST_PTY_SESSIONS,
562            tools::SEND_PTY_INPUT,
563            tools::CLOSE_PTY_SESSION,
564            tools::EXECUTE_CODE,
565        ] {
566            assert!(!config.policies.contains_key(legacy_tool));
567        }
568    }
569
570    #[test]
571    fn client_tool_search_defaults_to_enabled() {
572        let config = ToolsConfig::default();
573        assert!(config.client_tool_search);
574
575        let deserialized: ToolsConfig = toml::from_str("default_policy = \"prompt\"\n")
576            .expect("tools config should parse without client_tool_search");
577        assert!(deserialized.client_tool_search);
578
579        let disabled: ToolsConfig = toml::from_str(
580            r#"
581default_policy = "prompt"
582client_tool_search = false
583"#,
584        )
585        .expect("tools config should parse with client_tool_search disabled");
586        assert!(!disabled.client_tool_search);
587    }
588
589    #[test]
590    fn editor_config_deserializes_from_toml() {
591        let config: ToolsConfig = toml::from_str(
592            r#"
593default_policy = "prompt"
594
595[editor]
596enabled = false
597preferred_editor = "code --wait"
598suspend_tui = false
599"#,
600        )
601        .expect("tools config should parse");
602
603        assert!(!config.editor.enabled);
604        assert_eq!(config.editor.preferred_editor, "code --wait");
605        assert!(!config.editor.suspend_tui);
606    }
607
608    #[test]
609    fn web_search_config_deserializes_from_toml() {
610        let config: ToolsConfig = toml::from_str(
611            r#"
612default_policy = "prompt"
613
614[web_search]
615provider = "duckduckgo"
616max_results = 12
617timeout_secs = 25
618cooldown_ms = 1500
619cache_ttl_secs = 120
620session_max_requests = 5
621"#,
622        )
623        .expect("tools config should parse");
624
625        assert_eq!(config.web_search.provider, WebSearchProvider::Duckduckgo);
626        assert_eq!(config.web_search.max_results, 12);
627        assert_eq!(config.web_search.timeout_secs, 25);
628        assert_eq!(config.web_search.cooldown_ms, 1500);
629        assert_eq!(config.web_search.cache_ttl_secs, 120);
630        assert_eq!(config.web_search.session_max_requests, 5);
631    }
632
633    #[test]
634    fn web_search_config_defaults_are_polite() {
635        let config = WebSearchConfig::default();
636        assert_eq!(config.provider, WebSearchProvider::Auto);
637        assert_eq!(config.max_results, 8);
638        assert_eq!(config.timeout_secs, 20);
639        assert!(config.cooldown_ms >= 1_000);
640        assert!(config.cache_ttl_secs >= 60);
641        assert!(config.session_max_requests > 0);
642    }
643
644    #[test]
645    fn web_search_provider_serializes_lowercase() {
646        // Serde rename_all = "snake_case" means enum variants serialize
647        // lowercase, matching the LLM-facing schema strings.
648        let json = serde_json::to_value(WebSearchProvider::Duckduckgo).unwrap();
649        assert_eq!(json, serde_json::json!("duckduckgo"));
650    }
651
652    #[test]
653    fn web_search_provider_backend_id_is_canonical() {
654        assert_eq!(WebSearchProvider::Auto.backend_id(), "duckduckgo");
655        assert_eq!(WebSearchProvider::Auto.backend_id(), WebSearchProvider::Duckduckgo.backend_id());
656    }
657
658    #[test]
659    fn web_search_unsupported_provider_uses_generic_error() {
660        let error = serde_json::from_value::<WebSearchProvider>(serde_json::json!("unsupported-provider"))
661            .unwrap_err()
662            .to_string();
663        assert!(error.contains("unknown variant"));
664        assert!(error.contains("auto"));
665        assert!(error.contains("duckduckgo"));
666    }
667
668    #[test]
669    fn web_fetch_default_allowed_domains_seed_common_dev_sites() {
670        // The defaults should include the sites the agent most commonly
671        // needs (looking up a user, fetching a crate's README, etc.).
672        // This is a regression test for the "who is vinhnx?" case where
673        // the default `Restricted` mode blocked github.com / npmjs.com /
674        // crates.io even though none of them are on the blocklist.
675        //
676        // After H1: the inline list was removed in favour of the TOML
677        // allowlist, filtered to web-fetch-relevant categories. Hosts
678        // that aren't in the TOML (`npmjs.com`, `www.npmjs.com`,
679        // `docs.rs`, etc.) are no longer in the defaults — that's
680        // intentional, see the allowlist policy in
681        // `NetworkAllowlist::web_fetch_relevant_domains`.
682        let allowed = WebFetchConfig::default().allowed_domains;
683        for host in [
684            "github.com",
685            "api.github.com",
686            "raw.githubusercontent.com",
687            "crates.io",
688            "index.crates.io",
689            "registry.npmjs.org",
690            "pypi.org",
691        ] {
692            assert!(
693                allowed.iter().any(|d| d == host),
694                "default allowed_domains should include {host}; got {allowed:?}"
695            );
696        }
697    }
698
699    #[test]
700    fn web_fetch_default_allowed_domains_include_relevant_categories() {
701        // The TOML allowlist is filtered to web-friendly categories for the
702        // web_fetch defaults: search engines, package registries, code
703        // hosting, web-crawl relays (minus defuddle.md), MCP servers, and
704        // specialized knowledge bases. AI provider endpoints and dev
705        // infrastructure are explicitly excluded (those need auth or
706        // aren't useful as fetch targets).
707        let allowed = WebFetchConfig::default().allowed_domains;
708        for host in [
709            "github.com",
710            "crates.io",
711            "registry.npmjs.org",
712            "pypi.org",
713            "en.wikipedia.org",
714            "r.jina.ai",
715            "api.tavily.com",
716        ] {
717            assert!(
718                allowed.iter().any(|d| d == host),
719                "default allowed_domains should include {host}; got {allowed:?}"
720            );
721        }
722    }
723
724    #[test]
725    fn web_fetch_default_allowed_domains_exclude_ai_and_dev_infra() {
726        // H1 (review): the old default merged every category. The new
727        // default must not include AI provider endpoints (LLM inference
728        // APIs that need auth), OAuth flows, dev infrastructure, OS-update
729        // mirrors, or `defuddle.md` (which is a relay, not a fetch
730        // target).
731        //
732        // Search APIs like `api.tavily.com` ARE allowed — those are
733        // legitimate fetch targets the agent might query directly.
734        let allowed = WebFetchConfig::default().allowed_domains;
735        for host in [
736            "api.anthropic.com",
737            "api.openai.com",
738            "api.fireworks.ai",
739            "api.deepseek.com",
740            "defuddle.md",
741            "*.auth0.com",
742            "*.workers.dev",
743            "*.vercel.app",
744            "us.i.posthog.com",
745            "security.ubuntu.com",
746            "archive.ubuntu.com",
747        ] {
748            assert!(
749                !allowed.iter().any(|d| d == host),
750                "default allowed_domains must NOT include {host}; got {allowed:?}"
751            );
752        }
753    }
754
755    #[test]
756    fn web_fetch_default_allowed_domains_preserves_wildcards_in_relevant_categories() {
757        // The TOML has `*.vercel.app` in dev_infra and `*.clerk.accounts.dev`
758        // in auth. After filtering for web_fetch, neither should remain.
759        // A future TOML change that moves a wildcard into a web-relevant
760        // category will be picked up here.
761        let allowed = WebFetchConfig::default().allowed_domains;
762        let wildcards: Vec<&str> = allowed.iter().map(|s| s.as_str()).filter(|s| s.starts_with("*.")).collect();
763        assert!(
764            wildcards.is_empty(),
765            "expected no wildcards in web_fetch defaults (dev_infra/auth are excluded); got {wildcards:?}"
766        );
767    }
768
769    #[test]
770    fn web_fetch_default_allowed_domains_returns_fresh_vec() {
771        // `default_web_fetch_allowed_domains` is cached in a OnceLock, but
772        // each call must return a fresh `Vec` so callers can mutate the
773        // returned value without affecting the cached snapshot.
774        let mut a = WebFetchConfig::default().allowed_domains;
775        a.push("evil.example".to_string());
776        let b = WebFetchConfig::default().allowed_domains;
777        assert!(!b.iter().any(|d| d == "evil.example"));
778    }
779
780    #[test]
781    fn blocked_tool_caps_default_to_derived_total() {
782        let config = ToolsConfig::default();
783        assert!(config.max_total_blocked_tool_calls_per_turn.is_none());
784        assert!(config.blocked_tool_thresholds.is_empty());
785    }
786
787    #[test]
788    fn blocked_tool_caps_deserialize_from_toml() {
789        let config: ToolsConfig = toml::from_str(
790            r#"
791max_consecutive_blocked_tool_calls_per_turn = 3
792max_total_blocked_tool_calls_per_turn = 10
793
794[blocked_tool_thresholds]
795exec_command = 3
796code_search = 6
797"#,
798        )
799        .expect("blocked tool caps should parse");
800        assert_eq!(config.max_consecutive_blocked_tool_calls_per_turn, 3);
801        assert_eq!(config.max_total_blocked_tool_calls_per_turn, Some(10));
802        assert_eq!(config.blocked_tool_thresholds.get("exec_command"), Some(&3));
803        assert_eq!(config.blocked_tool_thresholds.get("code_search"), Some(&6));
804    }
805}