Skip to main content

vtcode_config/core/provider/
mod.rs

1use crate::core::advisor::AdvisorConfig;
2use serde::{Deserialize, Serialize};
3use vtcode_commons::reasoning::ReasoningEffortLevel;
4
5/// Controls how thinking content is returned in Anthropic API responses.
6#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
8#[serde(rename_all = "lowercase")]
9pub enum ThinkingDisplayMode {
10    /// Thinking blocks contain summarized thinking text (default on Claude 4 models).
11    Summarized,
12    /// Thinking blocks are returned with an empty `thinking` field (default on Claude Opus 4.7).
13    Omitted,
14    /// Only the short progress updates written between tool calls come back as
15    /// text; reasoning stays hidden (Claude Sonnet 5.5, Claude Opus 5.5,
16    /// Claude Fable 5.x). Sent with the `thinking-display-updates-2026-08-18`
17    /// beta.
18    Updates,
19    /// Catch-all for unknown display modes added by the Anthropic API.
20    #[serde(other)]
21    Unknown,
22}
23
24impl ThinkingDisplayMode {
25    /// Returns the string representation for the API wire format.
26    pub fn as_str(self) -> &'static str {
27        match self {
28            Self::Summarized => "summarized",
29            Self::Omitted => "omitted",
30            Self::Updates => "updates",
31            Self::Unknown => "unknown",
32        }
33    }
34}
35
36/// Native OpenAI service tier selection.
37#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
39#[serde(rename_all = "lowercase")]
40pub enum OpenAIServiceTier {
41    Flex,
42    Priority,
43    Ultrafast,
44}
45
46impl OpenAIServiceTier {
47    pub const fn as_str(self) -> &'static str {
48        match self {
49            Self::Flex => "flex",
50            Self::Priority => "priority",
51            Self::Ultrafast => "ultrafast",
52        }
53    }
54
55    pub fn parse(value: &str) -> Option<Self> {
56        let normalized = value.trim();
57        if normalized.eq_ignore_ascii_case("flex") {
58            Some(Self::Flex)
59        } else if normalized.eq_ignore_ascii_case("priority") {
60            Some(Self::Priority)
61        } else if normalized.eq_ignore_ascii_case("ultrafast") {
62            Some(Self::Ultrafast)
63        } else {
64            None
65        }
66    }
67}
68
69/// How VT Code should provision OpenAI hosted shell environments.
70#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
72#[serde(rename_all = "snake_case")]
73pub enum OpenAIHostedShellEnvironment {
74    #[default]
75    ContainerAuto,
76    ContainerReference,
77}
78
79impl OpenAIHostedShellEnvironment {
80    pub const fn as_str(self) -> &'static str {
81        match self {
82            Self::ContainerAuto => "container_auto",
83            Self::ContainerReference => "container_reference",
84        }
85    }
86}
87
88impl OpenAIHostedShellEnvironment {
89    const fn uses_container_reference(self) -> bool {
90        matches!(self, Self::ContainerReference)
91    }
92}
93
94/// Hosted shell network access policy.
95#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
97#[serde(rename_all = "snake_case")]
98pub enum OpenAIHostedShellNetworkPolicyType {
99    #[default]
100    Disabled,
101    Allowlist,
102}
103
104impl OpenAIHostedShellNetworkPolicyType {
105    pub const fn as_str(self) -> &'static str {
106        match self {
107            Self::Disabled => "disabled",
108            Self::Allowlist => "allowlist",
109        }
110    }
111}
112
113/// Per-domain secret injected by the OpenAI hosted shell runtime.
114#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
115#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
116pub struct OpenAIHostedShellDomainSecret {
117    pub domain: String,
118    pub name: String,
119    pub value: String,
120}
121
122impl OpenAIHostedShellDomainSecret {
123    fn validation_error(&self, index: usize) -> Option<String> {
124        let base = format!("provider.openai.hosted_shell.network_policy.domain_secrets[{index}]");
125
126        if self.domain.trim().is_empty() {
127            return Some(format!("`{base}.domain` must not be empty when set."));
128        }
129        if self.name.trim().is_empty() {
130            return Some(format!("`{base}.name` must not be empty when set."));
131        }
132        if self.value.trim().is_empty() {
133            return Some(format!("`{base}.value` must not be empty when set."));
134        }
135
136        None
137    }
138}
139
140/// Request-scoped network policy for OpenAI hosted shell environments.
141#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
142#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Default)]
143pub struct OpenAIHostedShellNetworkPolicy {
144    #[serde(rename = "type", default)]
145    pub policy_type: OpenAIHostedShellNetworkPolicyType,
146
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub allowed_domains: Vec<String>,
149
150    #[serde(default, skip_serializing_if = "Vec::is_empty")]
151    pub domain_secrets: Vec<OpenAIHostedShellDomainSecret>,
152}
153
154impl OpenAIHostedShellNetworkPolicy {
155    pub const fn is_allowlist(&self) -> bool {
156        matches!(self.policy_type, OpenAIHostedShellNetworkPolicyType::Allowlist)
157    }
158
159    fn first_invalid_message(&self) -> Option<String> {
160        match self.policy_type {
161            OpenAIHostedShellNetworkPolicyType::Disabled => {
162                if !self.allowed_domains.is_empty() || !self.domain_secrets.is_empty() {
163                    return Some(
164                        "`provider.openai.hosted_shell.network_policy.allowed_domains` and `provider.openai.hosted_shell.network_policy.domain_secrets` require `provider.openai.hosted_shell.network_policy.type = \"allowlist\"`."
165                            .to_string(),
166                    );
167                }
168            }
169            OpenAIHostedShellNetworkPolicyType::Allowlist => {
170                if let Some(index) = self.allowed_domains.iter().position(|value| value.trim().is_empty()) {
171                    return Some(format!(
172                        "`provider.openai.hosted_shell.network_policy.allowed_domains[{index}]` must not be empty when set."
173                    ));
174                }
175
176                if self.allowed_domains.is_empty() {
177                    return Some(
178                        "`provider.openai.hosted_shell.network_policy.allowed_domains` must include at least one domain when `provider.openai.hosted_shell.network_policy.type = \"allowlist\"`."
179                            .to_string(),
180                    );
181                }
182
183                for (index, secret) in self.domain_secrets.iter().enumerate() {
184                    if let Some(message) = secret.validation_error(index) {
185                        return Some(message);
186                    }
187
188                    let secret_domain = secret.domain.trim();
189                    if !self
190                        .allowed_domains
191                        .iter()
192                        .any(|domain| domain.trim().eq_ignore_ascii_case(secret_domain))
193                    {
194                        return Some(format!(
195                            "`provider.openai.hosted_shell.network_policy.domain_secrets[{index}].domain` must also appear in `provider.openai.hosted_shell.network_policy.allowed_domains`."
196                        ));
197                    }
198                }
199            }
200        }
201
202        None
203    }
204}
205
206/// Reserved keyword values for hosted skill version selection.
207#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
209#[serde(rename_all = "lowercase")]
210pub enum OpenAIHostedSkillVersionKeyword {
211    #[default]
212    Latest,
213}
214
215/// Hosted skill version selector for OpenAI Responses hosted shell mounts.
216#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
217#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
218#[serde(untagged)]
219pub enum OpenAIHostedSkillVersion {
220    Latest(OpenAIHostedSkillVersionKeyword),
221    Number(u64),
222    String(String),
223}
224
225impl Default for OpenAIHostedSkillVersion {
226    fn default() -> Self {
227        Self::Latest(OpenAIHostedSkillVersionKeyword::Latest)
228    }
229}
230
231impl OpenAIHostedSkillVersion {
232    fn validation_error(&self, field_path: &str) -> Option<String> {
233        match self {
234            Self::String(value) if value.trim().is_empty() => {
235                Some(format!("`{field_path}` must not be empty when set."))
236            }
237            _ => None,
238        }
239    }
240}
241
242/// Hosted skill reference mounted into an OpenAI hosted shell environment.
243#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
244#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
245#[serde(tag = "type", rename_all = "snake_case")]
246pub enum OpenAIHostedSkill {
247    /// Reference to a pre-registered hosted skill.
248    SkillReference {
249        skill_id: String,
250        #[serde(default)]
251        version: OpenAIHostedSkillVersion,
252    },
253    /// Inline base64 zip bundle.
254    Inline {
255        bundle_b64: String,
256        #[serde(skip_serializing_if = "Option::is_none")]
257        sha256: Option<String>,
258    },
259}
260
261impl OpenAIHostedSkill {
262    fn validation_error(&self, index: usize) -> Option<String> {
263        match self {
264            Self::SkillReference { skill_id, version } => {
265                let skill_id_path = format!("provider.openai.hosted_shell.skills[{index}].skill_id");
266                if skill_id.trim().is_empty() {
267                    return Some(format!("`{skill_id_path}` must not be empty when `type = \"skill_reference\"`."));
268                }
269
270                let version_path = format!("provider.openai.hosted_shell.skills[{index}].version");
271                version.validation_error(&version_path)
272            }
273            Self::Inline { bundle_b64, .. } => {
274                let bundle_path = format!("provider.openai.hosted_shell.skills[{index}].bundle_b64");
275                if bundle_b64.trim().is_empty() {
276                    return Some(format!("`{bundle_path}` must not be empty when `type = \"inline\"`."));
277                }
278                None
279            }
280        }
281    }
282}
283
284/// OpenAI hosted shell configuration.
285#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
286#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Default)]
287pub struct OpenAIHostedShellConfig {
288    /// Enable OpenAI hosted shell instead of VT Code's local shell tool.
289    #[serde(default)]
290    pub enabled: bool,
291
292    /// Environment provisioning mode for hosted shell.
293    #[serde(default)]
294    pub environment: OpenAIHostedShellEnvironment,
295
296    /// Existing OpenAI container ID to reuse when `environment = "container_reference"`.
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub container_id: Option<String>,
299
300    /// File IDs to mount when using `container_auto`.
301    #[serde(default, skip_serializing_if = "Vec::is_empty")]
302    pub file_ids: Vec<String>,
303
304    /// Hosted skills to mount when using `container_auto`.
305    #[serde(default, skip_serializing_if = "Vec::is_empty")]
306    pub skills: Vec<OpenAIHostedSkill>,
307
308    /// Request-scoped network policy for `container_auto` hosted shells.
309    #[serde(default)]
310    pub network_policy: OpenAIHostedShellNetworkPolicy,
311}
312
313impl OpenAIHostedShellConfig {
314    fn container_id_ref(&self) -> Option<&str> {
315        self.container_id.as_deref().map(str::trim).filter(|value| !value.is_empty())
316    }
317
318    pub const fn uses_container_reference(&self) -> bool {
319        self.environment.uses_container_reference()
320    }
321
322    pub fn first_invalid_skill_message(&self) -> Option<String> {
323        if self.uses_container_reference() {
324            return None;
325        }
326
327        self.skills
328            .iter()
329            .enumerate()
330            .find_map(|(index, skill)| skill.validation_error(index))
331    }
332
333    fn has_valid_skill_mounts(&self) -> bool {
334        self.first_invalid_skill_message().is_none()
335    }
336
337    pub fn first_invalid_network_policy_message(&self) -> Option<String> {
338        if self.uses_container_reference() {
339            return None;
340        }
341
342        self.network_policy.first_invalid_message()
343    }
344
345    fn has_valid_network_policy(&self) -> bool {
346        self.first_invalid_network_policy_message().is_none()
347    }
348
349    pub fn has_valid_reference_target(&self) -> bool {
350        !self.uses_container_reference() || self.container_id_ref().is_some()
351    }
352
353    pub fn is_valid_for_runtime(&self) -> bool {
354        self.has_valid_reference_target() && self.has_valid_skill_mounts() && self.has_valid_network_policy()
355    }
356}
357
358/// OpenAI hosted tool search configuration.
359#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
360#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
361pub struct OpenAIToolSearchConfig {
362    /// Enable hosted tool search for OpenAI Responses-compatible models.
363    #[serde(default = "default_tool_search_enabled")]
364    pub enabled: bool,
365
366    /// Automatically defer loading of all tools except the core always-on set.
367    #[serde(default = "default_defer_by_default")]
368    pub defer_by_default: bool,
369
370    /// Tool names that should never be deferred (always available).
371    #[serde(default)]
372    pub always_available_tools: Vec<String>,
373}
374
375impl Default for OpenAIToolSearchConfig {
376    fn default() -> Self {
377        Self {
378            enabled: default_tool_search_enabled(),
379            defer_by_default: default_defer_by_default(),
380            always_available_tools: Vec::new(),
381        }
382    }
383}
384
385/// Manual compaction defaults for the native OpenAI `/responses/compact` flow.
386#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
387#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Default)]
388pub struct OpenAIManualCompactionConfig {
389    /// Optional custom instructions appended to manual `/compact` requests.
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    pub instructions: Option<String>,
392}
393
394/// OpenAI-specific provider configuration
395#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
396#[derive(Debug, Clone, Deserialize, Serialize, Default)]
397pub struct OpenAIConfig {
398    /// Enable persistent Responses API WebSocket generation and streaming on
399    /// native OpenAI and OpenAI-compatible Responses endpoints.
400    /// This is an opt-in path designed for long-running, tool-heavy workflows.
401    /// A persistent connection removes per-request HTTP handshake overhead, so
402    /// pair it with `service_tier = "ultrafast"` on `gpt-6.2-astra`, `gpt-6.2-sol`,
403    /// `gpt-6-astra`, and `gpt-6.1-sol` for agentic tool-call bursts (Ultrafast
404    /// docs strongly recommend WebSockets). Streaming falls back to HTTP only
405    /// before any output event is exposed.
406    #[serde(default)]
407    pub websocket_mode: bool,
408
409    /// Optional Responses API `store` flag.
410    /// Set to `false` to avoid server-side storage when using Responses-compatible models.
411    #[serde(default, skip_serializing_if = "Option::is_none")]
412    pub responses_store: Option<bool>,
413
414    /// Optional Responses API `include` selectors.
415    /// Example: `["reasoning.encrypted_content"]` for encrypted reasoning continuity.
416    #[serde(default, skip_serializing_if = "Vec::is_empty")]
417    pub responses_include: Vec<String>,
418
419    /// Optional native OpenAI `service_tier` request parameter.
420    /// Leave unset to inherit the Project-level default service tier.
421    /// Options: "flex", "priority", "ultrafast".
422    /// "ultrafast" is the fastest tier: supported on `gpt-6.2-astra`, `gpt-6.2-sol`,
423    /// `gpt-6-astra`, and `gpt-6.1-sol`. It costs more and has separate rate limits
424    /// from Standard and Fast modes (check your organization's limits; Astra defaults
425    /// 500k/1M/5M TPM and 6.1-sol 1M/4M/40M TPM). Data residency is US-only on 6.2
426    /// Astra/Sol, US/global on Astra, and US/EU/global on 6.1-sol. Pairs best with
427    /// `websocket_mode = true`.
428    #[serde(default, skip_serializing_if = "Option::is_none")]
429    pub service_tier: Option<OpenAIServiceTier>,
430
431    /// Manual `/compact` defaults for the native OpenAI standalone compaction endpoint.
432    #[serde(default)]
433    pub manual_compaction: OpenAIManualCompactionConfig,
434
435    /// Optional hosted shell configuration for OpenAI native Responses models.
436    #[serde(default)]
437    pub hosted_shell: OpenAIHostedShellConfig,
438
439    /// Hosted tool search configuration for OpenAI Responses-compatible models.
440    #[serde(default)]
441    pub tool_search: OpenAIToolSearchConfig,
442}
443
444/// Anthropic-specific provider configuration
445#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
446#[derive(Debug, Clone, Deserialize, Serialize)]
447pub struct AnthropicConfig {
448    /// Native Claude speed (standard or fast). Fast uses premium pricing; unsupported routes keep this preference dormant.
449    #[serde(default, skip_serializing_if = "Option::is_none")]
450    pub speed: Option<super::AnthropicSpeed>,
451
452    /// Enable adaptive or extended thinking for Anthropic models
453    /// When enabled, Claude uses internal reasoning before responding, providing
454    /// enhanced reasoning capabilities for complex tasks.
455    /// Only supported by Claude 4, Claude 4.5, and Claude 3.7 Sonnet models.
456    /// Claude Opus 4.7 uses adaptive thinking instead of budgeted extended thinking.
457    /// Note: Extended thinking is now auto-enabled by default (31,999 tokens).
458    /// Set MAX_THINKING_TOKENS=63999 environment variable for 2x budget on 64K models.
459    /// See: <https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking>
460    #[serde(default = "default_extended_thinking_enabled")]
461    pub extended_thinking_enabled: bool,
462
463    /// Beta header for interleaved thinking feature
464    #[serde(default = "default_interleaved_thinking_beta")]
465    pub interleaved_thinking_beta: String,
466
467    /// Budget tokens for extended thinking (minimum: 1024, default: 31999)
468    /// On 64K output models (Opus 4.5, Sonnet 4.5, Haiku 4.5): default 31,999, max 63,999
469    /// On 32K output models (Opus 4): max 31,999
470    /// Claude Opus 4.7 ignores this setting and uses adaptive thinking instead.
471    /// Use MAX_THINKING_TOKENS environment variable to override.
472    #[serde(default = "default_interleaved_thinking_budget_tokens")]
473    pub interleaved_thinking_budget_tokens: u32,
474
475    /// Type value for enabling interleaved thinking
476    #[serde(default = "default_interleaved_thinking_type")]
477    pub interleaved_thinking_type_enabled: String,
478
479    /// Tool search configuration for dynamic tool discovery (advanced-tool-use beta)
480    #[serde(default)]
481    pub tool_search: ToolSearchConfig,
482
483    /// Native Anthropic memory tool configuration.
484    #[serde(default)]
485    pub memory: AnthropicMemoryConfig,
486
487    /// Effort level for adaptive thinking/token usage (low, medium, high, xhigh, max)
488    /// Controls how many tokens Claude uses when responding, trading off between
489    /// response thoroughness and token efficiency.
490    /// Unset by default: each model then uses its own default effort (for example
491    /// `medium` on Claude Opus 5.5, `high` on Claude Opus 5). An explicit
492    /// `agent.reasoning_effort` or `/effort` selection takes precedence; a value the
493    /// active model does not support falls back to that model's default.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub effort: Option<ReasoningEffortLevel>,
496
497    /// Optional Anthropic task budget token total for Claude Fable 5/5.1, Opus 5,
498    /// and Opus 5.5 (not sent for other models).
499    /// When set, VT Code sends `output_config.task_budget = { type = "tokens", total = N }`
500    /// and the required beta header.
501    /// Anthropic currently requires a minimum of 20,000 tokens.
502    #[serde(default)]
503    pub task_budget_tokens: Option<u32>,
504
505    /// Beta header for Anthropic task budgets.
506    #[serde(default = "default_task_budget_beta")]
507    pub task_budget_beta: String,
508
509    /// Controls how thinking content is returned in API responses.
510    ///   - "summarized": Thinking blocks contain summarized text (default on Opus 4.6 and earlier).
511    ///   - "omitted": Thinking blocks have an empty `thinking` field (default on Opus 4.7+).
512    ///   - "updates": Only the progress updates between tool calls are returned as text
513    ///     (Claude Sonnet 5.5, Claude Opus 5.5 and Claude Fable 5.x; the VT Code
514    ///     default on Claude Sonnet 5.5 and Claude Opus 5.5).
515    ///     Ignored on models without progress updates.
516    ///
517    /// When set, this overrides the model-specific default.
518    /// See: <https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking#controlling-thinking-display>
519    #[serde(default)]
520    pub thinking_display: Option<ThinkingDisplayMode>,
521
522    /// Enable token counting via the count_tokens endpoint
523    /// When enabled, the agent can estimate input token counts before making API calls
524    /// Useful for proactive management of rate limits and costs
525    #[serde(default = "default_count_tokens_enabled")]
526    pub count_tokens_enabled: bool,
527
528    /// Claude Advisor server-side tool configuration. The advisor pairs a faster
529    /// executor model with a higher-intelligence advisor model for strategic
530    /// guidance mid-generation. Only honored for Anthropic models and providers.
531    #[serde(default)]
532    pub advisor: AdvisorConfig,
533
534    /// Server-side refusal fallbacks (`fallbacks` request parameter).
535    ///   - "default": let Anthropic pick the recommended fallback model when the
536    ///     primary model declines on policy grounds (the VT Code default).
537    ///   - "off": never send `fallbacks`.
538    ///   - a list of 1-3 `{ model, max_tokens }` entries tried in order.
539    ///
540    /// Only sent to the first-party Claude API (`api.anthropic.com`) for models
541    /// whose capability profile supports server-side fallbacks (Claude Opus 5,
542    /// Opus 5.5, Fable 5 and Fable 5.1); other models and endpoints send nothing.
543    #[serde(default)]
544    pub fallbacks: AnthropicFallbacks,
545}
546
547/// Keyword forms of [`AnthropicFallbacks`].
548#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
549#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Default)]
550#[serde(rename_all = "lowercase")]
551pub enum AnthropicFallbackMode {
552    /// Use Anthropic's recommended fallback chain (`fallbacks: "default"`).
553    #[default]
554    Default,
555    /// Do not request server-side fallbacks.
556    Off,
557}
558
559/// One explicit server-side fallback entry.
560#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
561#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
562pub struct AnthropicFallbackTarget {
563    /// Fallback model id, for example `claude-opus-4-8`.
564    pub model: String,
565    /// Optional `max_tokens` override for this fallback attempt.
566    #[serde(default, skip_serializing_if = "Option::is_none")]
567    pub max_tokens: Option<u32>,
568}
569
570/// Server-side refusal fallback selection: `"default"`, `"off"`, or an explicit
571/// list of fallback models.
572#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
573#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
574#[serde(untagged)]
575pub enum AnthropicFallbacks {
576    Mode(AnthropicFallbackMode),
577    Models(Vec<AnthropicFallbackTarget>),
578}
579
580impl Default for AnthropicFallbacks {
581    fn default() -> Self {
582        Self::Mode(AnthropicFallbackMode::Default)
583    }
584}
585
586impl AnthropicFallbacks {
587    /// Maximum number of explicit fallback entries the API accepts.
588    pub const MAX_MODELS: usize = 3;
589
590    /// Returns a validation message when an explicit list is empty, too long,
591    /// has a blank model, or repeats a model.
592    pub fn validation_error(&self, field_path: &str) -> Option<String> {
593        let Self::Models(models) = self else {
594            return None;
595        };
596        Self::entries_validation_error(
597            field_path,
598            models.iter().map(|target| (target.model.as_str(), target.max_tokens)),
599        )
600    }
601
602    /// Validates explicit fallback entries given as `(model, max_tokens)`
603    /// pairs, applying the same rules as the list form of
604    /// `provider.anthropic.fallbacks`. Shared with request-level fallback
605    /// lists so both paths reject the same payloads.
606    pub fn entries_validation_error<'a>(
607        field_path: &str,
608        entries: impl ExactSizeIterator<Item = (&'a str, Option<u32>)>,
609    ) -> Option<String> {
610        let len = entries.len();
611        if len == 0 || len > Self::MAX_MODELS {
612            return Some(format!(
613                "`{field_path}` must list between 1 and {} fallback models, or be \"default\" or \"off\".",
614                Self::MAX_MODELS
615            ));
616        }
617        let mut seen = std::collections::HashSet::with_capacity(len);
618        for (model, max_tokens) in entries {
619            let model = model.trim();
620            if model.is_empty() {
621                return Some(format!("`{field_path}` entries must set a non-empty `model`."));
622            }
623            if !seen.insert(model) {
624                return Some(format!("`{field_path}` lists `{model}` more than once; entries must be distinct."));
625            }
626            if max_tokens == Some(0) {
627                return Some(format!("`{field_path}` entry `{model}` must use a positive `max_tokens`."));
628            }
629        }
630        None
631    }
632}
633
634impl Default for AnthropicConfig {
635    fn default() -> Self {
636        Self {
637            speed: None,
638            extended_thinking_enabled: default_extended_thinking_enabled(),
639            interleaved_thinking_beta: default_interleaved_thinking_beta(),
640            interleaved_thinking_budget_tokens: default_interleaved_thinking_budget_tokens(),
641            interleaved_thinking_type_enabled: default_interleaved_thinking_type(),
642            tool_search: ToolSearchConfig::default(),
643            memory: AnthropicMemoryConfig::default(),
644            effort: None,
645            task_budget_tokens: None,
646            task_budget_beta: default_task_budget_beta(),
647            thinking_display: None,
648            count_tokens_enabled: default_count_tokens_enabled(),
649            advisor: AdvisorConfig::default(),
650            fallbacks: AnthropicFallbacks::default(),
651        }
652    }
653}
654
655#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
656#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
657pub struct AnthropicMemoryConfig {
658    #[serde(default)]
659    pub enabled: bool,
660}
661
662/// OpenRouter app attribution (<https://openrouter.ai/docs/app-attribution>).
663///
664/// Opt-in only. When `enabled` is false no attribution headers are sent.
665/// When true, VT Code sends `HTTP-Referer`, `X-OpenRouter-Title`, and
666/// `X-OpenRouter-Categories: cli-agent`.
667#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
668#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
669pub struct OpenRouterAttributionConfig {
670    /// Master opt-in switch. Default false for privacy.
671    #[serde(default)]
672    pub enabled: bool,
673
674    /// Override app URL used as `HTTP-Referer`. Defaults to the VT Code repo.
675    #[serde(default, skip_serializing_if = "Option::is_none")]
676    pub referer: Option<String>,
677
678    /// Override display name used as `X-OpenRouter-Title`. Defaults to `VT Code`.
679    #[serde(default, skip_serializing_if = "Option::is_none")]
680    pub title: Option<String>,
681}
682
683impl OpenRouterAttributionConfig {
684    /// Default referer sent when attribution is enabled and no override is set.
685    pub const DEFAULT_REFERER: &'static str = "https://github.com/vinhnx/vtcode";
686    /// Default title sent when attribution is enabled and no override is set.
687    pub const DEFAULT_TITLE: &'static str = "VT Code";
688    /// Fixed marketplace category. `cli-agent` is the allowlisted terminal-agent category.
689    pub const CATEGORIES: &'static str = "cli-agent";
690
691    /// Resolve whether attribution headers should be sent.
692    ///
693    /// The environment layer wins when set to a recognized value
694    /// (`ConfigLayerStack` env > file); unrecognized or unset values fall
695    /// through to the file value. Delegates to the canonical tri-state
696    /// parser — do not fork the accepted-value set.
697    pub fn is_enabled(&self) -> bool {
698        vtcode_commons::utils::parse_env_bool(crate::constants::env_vars::VTCODE_OPENROUTER_ATTRIBUTION, self.enabled)
699    }
700
701    /// Header-safe override check: non-empty, bounded, no CTLs (reqwest
702    /// `HeaderValue` rejects `\r`/`\n`/control bytes; fall back to defaults).
703    fn header_safe(value: &str) -> bool {
704        !value.is_empty() && value.len() <= 512 && !value.bytes().any(|b| b < 0x20 || b == 0x7F)
705    }
706
707    /// Resolve effective referer, falling back to the default. Empty or
708    /// header-unsafe overrides are ignored.
709    pub fn resolved_referer(&self) -> &str {
710        self.referer
711            .as_deref()
712            .map(str::trim)
713            .filter(|s| Self::header_safe(s))
714            .unwrap_or(Self::DEFAULT_REFERER)
715    }
716
717    /// Resolve effective title, falling back to the default. Empty or
718    /// header-unsafe overrides are ignored.
719    pub fn resolved_title(&self) -> &str {
720        self.title
721            .as_deref()
722            .map(str::trim)
723            .filter(|s| Self::header_safe(s))
724            .unwrap_or(Self::DEFAULT_TITLE)
725    }
726}
727
728/// OpenRouter-specific provider configuration.
729#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
730#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq, Eq)]
731pub struct OpenRouterConfig {
732    /// App attribution opt-in (`[provider.openrouter.attribution]`).
733    #[serde(default)]
734    pub attribution: OpenRouterAttributionConfig,
735}
736
737#[inline]
738fn default_count_tokens_enabled() -> bool {
739    false
740}
741
742/// Tool search algorithm for Anthropic's advanced-tool-use beta
743#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
744#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
745#[serde(rename_all = "lowercase")]
746pub enum ToolSearchAlgorithm {
747    /// Regex-based search using Python re.search() syntax
748    #[default]
749    Regex,
750    /// BM25-based natural language search
751    Bm25,
752    /// Forward-compatible catch-all for unknown algorithm values
753    #[serde(other)]
754    Unknown,
755}
756
757impl ToolSearchAlgorithm {
758    /// Returns the string representation of this algorithm variant.
759    fn as_str(&self) -> &str {
760        match self {
761            Self::Regex => "regex",
762            Self::Bm25 => "bm25",
763            Self::Unknown => "unknown",
764        }
765    }
766}
767
768impl std::fmt::Display for ToolSearchAlgorithm {
769    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
770        f.write_str(self.as_str())
771    }
772}
773
774/// Configuration for Anthropic's tool search feature (advanced-tool-use beta)
775/// Enables dynamic tool discovery for large tool catalogs (up to 10k tools)
776#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
777#[derive(Debug, Clone, Deserialize, Serialize)]
778pub struct ToolSearchConfig {
779    /// Enable tool search feature (requires advanced-tool-use-2025-11-20 beta)
780    #[serde(default = "default_tool_search_enabled")]
781    pub enabled: bool,
782
783    /// Search algorithm: "regex" (Python regex patterns) or "bm25" (natural language)
784    #[serde(default = "default_tool_search_algorithm")]
785    pub algorithm: ToolSearchAlgorithm,
786
787    /// Automatically defer loading of all tools except core tools
788    #[serde(default = "default_defer_by_default")]
789    pub defer_by_default: bool,
790
791    /// Maximum number of tool search results to return
792    #[serde(default = "default_max_results")]
793    max_results: u32,
794
795    /// Tool names that should never be deferred (always available)
796    #[serde(default)]
797    pub always_available_tools: Vec<String>,
798}
799
800impl Default for ToolSearchConfig {
801    fn default() -> Self {
802        Self {
803            enabled: default_tool_search_enabled(),
804            algorithm: default_tool_search_algorithm(),
805            defer_by_default: default_defer_by_default(),
806            max_results: default_max_results(),
807            always_available_tools: vec![],
808        }
809    }
810}
811
812#[inline]
813fn default_tool_search_enabled() -> bool {
814    true
815}
816
817#[inline]
818fn default_tool_search_algorithm() -> ToolSearchAlgorithm {
819    ToolSearchAlgorithm::Regex
820}
821
822#[inline]
823fn default_defer_by_default() -> bool {
824    true
825}
826
827#[inline]
828fn default_max_results() -> u32 {
829    5
830}
831
832#[inline]
833fn default_extended_thinking_enabled() -> bool {
834    true
835}
836
837#[inline]
838fn default_interleaved_thinking_beta() -> String {
839    "interleaved-thinking-2025-05-14".to_string()
840}
841
842#[inline]
843fn default_interleaved_thinking_budget_tokens() -> u32 {
844    crate::constants::context::DEFAULT_THINKING_BUDGET
845}
846
847#[inline]
848fn default_interleaved_thinking_type() -> String {
849    "enabled".to_string()
850}
851
852#[inline]
853fn default_task_budget_beta() -> String {
854    "task-budgets-2026-03-13".to_string()
855}
856
857#[cfg(test)]
858mod tests;