1use indexmap::IndexMap;
2use serde::{Deserialize, Serialize};
3use std::time::Duration;
4
5use crate::constants::{defaults, tools};
6use crate::core::plugins::PluginRuntimeConfig;
7
8#[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 #[default]
15 #[serde(rename = "vt_code")]
16 #[serde(alias = "codex_default")]
17 #[cfg_attr(feature = "schema", schemars(rename = "vt_code"))]
18 VtCode,
19 #[serde(rename = "advanced_vtcode")]
21 #[cfg_attr(feature = "schema", schemars(rename = "advanced_vtcode"))]
22 AdvancedVtCode,
23}
24
25#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
27#[derive(Debug, Clone, Deserialize, Serialize)]
28pub struct ToolsConfig {
29 #[serde(default)]
31 pub profile: ToolProfile,
32
33 #[serde(default = "default_tool_policy")]
35 pub default_policy: ToolPolicy,
36
37 #[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 #[serde(default = "default_max_repeated_tool_calls")]
48 pub max_repeated_tool_calls: usize,
49
50 #[serde(default = "default_max_consecutive_blocked_tool_calls_per_turn")]
55 pub max_consecutive_blocked_tool_calls_per_turn: usize,
56
57 #[serde(default)]
61 pub max_total_blocked_tool_calls_per_turn: Option<usize>,
62
63 #[serde(default)]
67 #[cfg_attr(feature = "schema", schemars(with = "std::collections::BTreeMap<String, usize>"))]
68 pub blocked_tool_thresholds: IndexMap<String, usize>,
69
70 #[serde(default = "default_max_tool_rate_per_second")]
73 pub max_tool_rate_per_second: Option<usize>,
74
75 #[serde(default = "default_max_sequential_spool_chunk_reads")]
78 pub max_sequential_spool_chunk_reads: usize,
79
80 #[serde(default)]
82 pub web_fetch: WebFetchConfig,
83
84 #[serde(default)]
86 pub web_search: WebSearchConfig,
87
88 #[serde(default)]
90 pub plugins: PluginRuntimeConfig,
91
92 #[serde(default)]
94 pub editor: EditorToolConfig,
95
96 #[serde(default)]
100 pub loop_thresholds: IndexMap<String, usize>,
101
102 #[serde(default = "default_client_tool_search")]
110 pub client_tool_search: bool,
111}
112
113#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
115#[derive(Debug, Clone, Deserialize, Serialize)]
116pub struct EditorToolConfig {
117 #[serde(default = "default_editor_enabled")]
119 pub enabled: bool,
120
121 #[serde(default)]
123 pub preferred_editor: String,
124
125 #[serde(default = "default_editor_suspend_tui")]
127 pub suspend_tui: bool,
128}
129
130#[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 #[default]
137 Restricted,
138 Whitelist,
140}
141
142#[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]
153 Auto,
154 Duckduckgo,
156}
157
158impl WebSearchProvider {
159 #[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#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
192#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
193pub struct WebSearchConfig {
194 #[serde(default)]
198 pub provider: WebSearchProvider,
199
200 #[serde(default = "default_web_search_max_results")]
203 pub max_results: usize,
204
205 #[serde(default = "default_web_search_timeout_secs")]
207 pub timeout_secs: u64,
208
209 #[serde(default = "default_web_search_cooldown_ms")]
212 pub cooldown_ms: u64,
213
214 #[serde(default = "default_web_search_cache_ttl_secs")]
217 pub cache_ttl_secs: u64,
218
219 #[serde(default = "default_web_search_session_max_requests")]
222 pub session_max_requests: u32,
223}
224
225#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
227#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
228pub struct WebFetchConfig {
229 #[serde(default = "default_web_fetch_mode")]
231 pub mode: WebFetchMode,
232
233 #[serde(default)]
235 pub blocked_domains: Vec<String>,
236
237 #[serde(default)]
239 pub allowed_domains: Vec<String>,
240
241 #[serde(default)]
243 pub blocked_patterns: Vec<String>,
244
245 #[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
306fn 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#[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,
357 #[default]
359 Prompt,
360 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 (tools::START_PLANNING, ToolPolicy::Allow),
441 (tools::TASK_TRACKER, ToolPolicy::Allow),
442 (tools::MATRIX, ToolPolicy::Allow),
443 (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 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 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 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 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 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 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 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}