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. Omitted or `false` sends `store: false`,
410    /// avoiding server-side application-state retention on Responses-compatible models.
411    /// Set to `true` to opt into server-side storage on native and compatible OpenAI
412    /// HTTP Responses routes; ChatGPT subscription routes and `websocket_mode = true`
413    /// always send `store: false`.
414    /// Organizations with Zero Data Retention treat `true` as `false` server-side, so
415    /// this setting cannot override an org-level data-controls policy.
416    #[serde(default, skip_serializing_if = "Option::is_none")]
417    pub responses_store: Option<bool>,
418
419    /// Optional Responses API `include` selectors.
420    /// Example: `["reasoning.encrypted_content"]` for encrypted reasoning continuity.
421    #[serde(default, skip_serializing_if = "Vec::is_empty")]
422    pub responses_include: Vec<String>,
423
424    /// Optional native OpenAI `service_tier` request parameter.
425    /// Leave unset to inherit the Project-level default service tier.
426    /// Options: "flex", "priority", "ultrafast".
427    /// "ultrafast" is the fastest tier: supported on `gpt-6.2-astra`, `gpt-6.2-sol`,
428    /// `gpt-6-astra`, and `gpt-6.1-sol`. It costs more and has separate rate limits
429    /// from Standard and Fast modes (check your organization's limits; Astra defaults
430    /// 500k/1M/5M TPM and 6.1-sol 1M/4M/40M TPM). Data residency is US-only on 6.2
431    /// Astra/Sol, US/global on Astra, and US/EU/global on 6.1-sol. Pairs best with
432    /// `websocket_mode = true`.
433    #[serde(default, skip_serializing_if = "Option::is_none")]
434    pub service_tier: Option<OpenAIServiceTier>,
435
436    /// Manual `/compact` defaults for the native OpenAI standalone compaction endpoint.
437    #[serde(default)]
438    pub manual_compaction: OpenAIManualCompactionConfig,
439
440    /// Optional hosted shell configuration for OpenAI native Responses models.
441    #[serde(default)]
442    pub hosted_shell: OpenAIHostedShellConfig,
443
444    /// Hosted tool search configuration for OpenAI Responses-compatible models.
445    #[serde(default)]
446    pub tool_search: OpenAIToolSearchConfig,
447}
448
449/// Anthropic-specific provider configuration
450#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
451#[derive(Debug, Clone, Deserialize, Serialize)]
452pub struct AnthropicConfig {
453    /// Native Claude speed (standard or fast). Fast uses premium pricing; unsupported routes keep this preference dormant.
454    #[serde(default, skip_serializing_if = "Option::is_none")]
455    pub speed: Option<super::AnthropicSpeed>,
456
457    /// Enable adaptive or extended thinking for Anthropic models
458    /// When enabled, Claude uses internal reasoning before responding, providing
459    /// enhanced reasoning capabilities for complex tasks.
460    /// Only supported by Claude 4, Claude 4.5, and Claude 3.7 Sonnet models.
461    /// Claude Opus 4.7 uses adaptive thinking instead of budgeted extended thinking.
462    /// Note: Extended thinking is now auto-enabled by default (31,999 tokens).
463    /// Set MAX_THINKING_TOKENS=63999 environment variable for 2x budget on 64K models.
464    /// See: <https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking>
465    #[serde(default = "default_extended_thinking_enabled")]
466    pub extended_thinking_enabled: bool,
467
468    /// Beta header for interleaved thinking feature
469    #[serde(default = "default_interleaved_thinking_beta")]
470    pub interleaved_thinking_beta: String,
471
472    /// Budget tokens for extended thinking (minimum: 1024, default: 31999)
473    /// On 64K output models (Opus 4.5, Sonnet 4.5, Haiku 4.5): default 31,999, max 63,999
474    /// On 32K output models (Opus 4): max 31,999
475    /// Claude Opus 4.7 ignores this setting and uses adaptive thinking instead.
476    /// Use MAX_THINKING_TOKENS environment variable to override.
477    #[serde(default = "default_interleaved_thinking_budget_tokens")]
478    pub interleaved_thinking_budget_tokens: u32,
479
480    /// Type value for enabling interleaved thinking
481    #[serde(default = "default_interleaved_thinking_type")]
482    pub interleaved_thinking_type_enabled: String,
483
484    /// Tool search configuration for dynamic tool discovery (advanced-tool-use beta)
485    #[serde(default)]
486    pub tool_search: ToolSearchConfig,
487
488    /// Native Anthropic memory tool configuration.
489    #[serde(default)]
490    pub memory: AnthropicMemoryConfig,
491
492    /// Effort level for adaptive thinking/token usage (low, medium, high, xhigh, max)
493    /// Controls how many tokens Claude uses when responding, trading off between
494    /// response thoroughness and token efficiency.
495    /// Unset by default: each model then uses its own default effort (for example
496    /// `medium` on Claude Opus 5.5, `high` on Claude Opus 5). An explicit
497    /// `agent.reasoning_effort` or `/effort` selection takes precedence; a value the
498    /// active model does not support falls back to that model's default.
499    #[serde(default, skip_serializing_if = "Option::is_none")]
500    pub effort: Option<ReasoningEffortLevel>,
501
502    /// Optional Anthropic task budget token total for Claude Fable 5/5.1, Opus 5,
503    /// and Opus 5.5 (not sent for other models).
504    /// When set, VT Code sends `output_config.task_budget = { type = "tokens", total = N }`
505    /// and the required beta header.
506    /// Anthropic currently requires a minimum of 20,000 tokens.
507    #[serde(default)]
508    pub task_budget_tokens: Option<u32>,
509
510    /// Beta header for Anthropic task budgets.
511    #[serde(default = "default_task_budget_beta")]
512    pub task_budget_beta: String,
513
514    /// Controls how thinking content is returned in API responses.
515    ///   - "summarized": Thinking blocks contain summarized text (default on Opus 4.6 and earlier).
516    ///   - "omitted": Thinking blocks have an empty `thinking` field (default on Opus 4.7+).
517    ///   - "updates": Only the progress updates between tool calls are returned as text
518    ///     (Claude Sonnet 5.5, Claude Opus 5.5 and Claude Fable 5.x; the VT Code
519    ///     default on Claude Sonnet 5.5 and Claude Opus 5.5).
520    ///     Ignored on models without progress updates.
521    ///
522    /// When set, this overrides the model-specific default.
523    /// See: <https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking#controlling-thinking-display>
524    #[serde(default)]
525    pub thinking_display: Option<ThinkingDisplayMode>,
526
527    /// Enable token counting via the count_tokens endpoint
528    /// When enabled, the agent can estimate input token counts before making API calls
529    /// Useful for proactive management of rate limits and costs
530    #[serde(default = "default_count_tokens_enabled")]
531    pub count_tokens_enabled: bool,
532
533    /// Claude Advisor server-side tool configuration. The advisor pairs a faster
534    /// executor model with a higher-intelligence advisor model for strategic
535    /// guidance mid-generation. Only honored for Anthropic models and providers.
536    #[serde(default)]
537    pub advisor: AdvisorConfig,
538
539    /// Server-side refusal fallbacks (`fallbacks` request parameter).
540    ///   - "default": let Anthropic pick the recommended fallback model when the
541    ///     primary model declines on policy grounds (the VT Code default).
542    ///   - "off": never send `fallbacks`.
543    ///   - a list of 1-3 `{ model, max_tokens }` entries tried in order.
544    ///
545    /// Only sent to the first-party Claude API (`api.anthropic.com`) for models
546    /// whose capability profile supports server-side fallbacks (Claude Opus 5,
547    /// Opus 5.5, Fable 5 and Fable 5.1); other models and endpoints send nothing.
548    #[serde(default)]
549    pub fallbacks: AnthropicFallbacks,
550}
551
552/// Keyword forms of [`AnthropicFallbacks`].
553#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
554#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Default)]
555#[serde(rename_all = "lowercase")]
556pub enum AnthropicFallbackMode {
557    /// Use Anthropic's recommended fallback chain (`fallbacks: "default"`).
558    #[default]
559    Default,
560    /// Do not request server-side fallbacks.
561    Off,
562}
563
564/// One explicit server-side fallback entry.
565#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
566#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
567pub struct AnthropicFallbackTarget {
568    /// Fallback model id, for example `claude-opus-4-8`.
569    pub model: String,
570    /// Optional `max_tokens` override for this fallback attempt.
571    #[serde(default, skip_serializing_if = "Option::is_none")]
572    pub max_tokens: Option<u32>,
573}
574
575/// Server-side refusal fallback selection: `"default"`, `"off"`, or an explicit
576/// list of fallback models.
577#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
578#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
579#[serde(untagged)]
580pub enum AnthropicFallbacks {
581    Mode(AnthropicFallbackMode),
582    Models(Vec<AnthropicFallbackTarget>),
583}
584
585impl Default for AnthropicFallbacks {
586    fn default() -> Self {
587        Self::Mode(AnthropicFallbackMode::Default)
588    }
589}
590
591impl AnthropicFallbacks {
592    /// Maximum number of explicit fallback entries the API accepts.
593    pub const MAX_MODELS: usize = 3;
594
595    /// Returns a validation message when an explicit list is empty, too long,
596    /// has a blank model, or repeats a model.
597    pub fn validation_error(&self, field_path: &str) -> Option<String> {
598        let Self::Models(models) = self else {
599            return None;
600        };
601        Self::entries_validation_error(
602            field_path,
603            models.iter().map(|target| (target.model.as_str(), target.max_tokens)),
604        )
605    }
606
607    /// Validates explicit fallback entries given as `(model, max_tokens)`
608    /// pairs, applying the same rules as the list form of
609    /// `provider.anthropic.fallbacks`. Shared with request-level fallback
610    /// lists so both paths reject the same payloads.
611    pub fn entries_validation_error<'a>(
612        field_path: &str,
613        entries: impl ExactSizeIterator<Item = (&'a str, Option<u32>)>,
614    ) -> Option<String> {
615        let len = entries.len();
616        if len == 0 || len > Self::MAX_MODELS {
617            return Some(format!(
618                "`{field_path}` must list between 1 and {} fallback models, or be \"default\" or \"off\".",
619                Self::MAX_MODELS
620            ));
621        }
622        let mut seen = std::collections::HashSet::with_capacity(len);
623        for (model, max_tokens) in entries {
624            let model = model.trim();
625            if model.is_empty() {
626                return Some(format!("`{field_path}` entries must set a non-empty `model`."));
627            }
628            if !seen.insert(model) {
629                return Some(format!("`{field_path}` lists `{model}` more than once; entries must be distinct."));
630            }
631            if max_tokens == Some(0) {
632                return Some(format!("`{field_path}` entry `{model}` must use a positive `max_tokens`."));
633            }
634        }
635        None
636    }
637}
638
639impl Default for AnthropicConfig {
640    fn default() -> Self {
641        Self {
642            speed: None,
643            extended_thinking_enabled: default_extended_thinking_enabled(),
644            interleaved_thinking_beta: default_interleaved_thinking_beta(),
645            interleaved_thinking_budget_tokens: default_interleaved_thinking_budget_tokens(),
646            interleaved_thinking_type_enabled: default_interleaved_thinking_type(),
647            tool_search: ToolSearchConfig::default(),
648            memory: AnthropicMemoryConfig::default(),
649            effort: None,
650            task_budget_tokens: None,
651            task_budget_beta: default_task_budget_beta(),
652            thinking_display: None,
653            count_tokens_enabled: default_count_tokens_enabled(),
654            advisor: AdvisorConfig::default(),
655            fallbacks: AnthropicFallbacks::default(),
656        }
657    }
658}
659
660#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
661#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
662pub struct AnthropicMemoryConfig {
663    #[serde(default)]
664    pub enabled: bool,
665}
666
667/// OpenRouter app attribution (<https://openrouter.ai/docs/app-attribution>).
668///
669/// Opt-in only. When `enabled` is false no attribution headers are sent.
670/// When true, VT Code sends `HTTP-Referer`, `X-OpenRouter-Title`, and
671/// `X-OpenRouter-Categories: cli-agent`.
672#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
673#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
674pub struct OpenRouterAttributionConfig {
675    /// Master opt-in switch. Default false for privacy.
676    #[serde(default)]
677    pub enabled: bool,
678
679    /// Override app URL used as `HTTP-Referer`. Defaults to the VT Code repo.
680    #[serde(default, skip_serializing_if = "Option::is_none")]
681    pub referer: Option<String>,
682
683    /// Override display name used as `X-OpenRouter-Title`. Defaults to `VT Code`.
684    #[serde(default, skip_serializing_if = "Option::is_none")]
685    pub title: Option<String>,
686}
687
688impl OpenRouterAttributionConfig {
689    /// Default referer sent when attribution is enabled and no override is set.
690    pub const DEFAULT_REFERER: &'static str = "https://github.com/vinhnx/vtcode";
691    /// Default title sent when attribution is enabled and no override is set.
692    pub const DEFAULT_TITLE: &'static str = "VT Code";
693    /// Fixed marketplace category. `cli-agent` is the allowlisted terminal-agent category.
694    pub const CATEGORIES: &'static str = "cli-agent";
695
696    /// Resolve whether attribution headers should be sent.
697    ///
698    /// The environment layer wins when set to a recognized value
699    /// (`ConfigLayerStack` env > file); unrecognized or unset values fall
700    /// through to the file value. Delegates to the canonical tri-state
701    /// parser — do not fork the accepted-value set.
702    pub fn is_enabled(&self) -> bool {
703        vtcode_commons::utils::parse_env_bool(crate::constants::env_vars::VTCODE_OPENROUTER_ATTRIBUTION, self.enabled)
704    }
705
706    /// Header-safe override check: non-empty, bounded, no CTLs (reqwest
707    /// `HeaderValue` rejects `\r`/`\n`/control bytes; fall back to defaults).
708    fn header_safe(value: &str) -> bool {
709        !value.is_empty() && value.len() <= 512 && !value.bytes().any(|b| b < 0x20 || b == 0x7F)
710    }
711
712    /// Resolve effective referer, falling back to the default. Empty or
713    /// header-unsafe overrides are ignored.
714    pub fn resolved_referer(&self) -> &str {
715        self.referer
716            .as_deref()
717            .map(str::trim)
718            .filter(|s| Self::header_safe(s))
719            .unwrap_or(Self::DEFAULT_REFERER)
720    }
721
722    /// Resolve effective title, falling back to the default. Empty or
723    /// header-unsafe overrides are ignored.
724    pub fn resolved_title(&self) -> &str {
725        self.title
726            .as_deref()
727            .map(str::trim)
728            .filter(|s| Self::header_safe(s))
729            .unwrap_or(Self::DEFAULT_TITLE)
730    }
731}
732
733/// OpenRouter-specific provider configuration.
734#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
735#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq, Eq)]
736pub struct OpenRouterConfig {
737    /// App attribution opt-in (`[provider.openrouter.attribution]`).
738    #[serde(default)]
739    pub attribution: OpenRouterAttributionConfig,
740}
741
742#[inline]
743fn default_count_tokens_enabled() -> bool {
744    false
745}
746
747/// Tool search algorithm for Anthropic's advanced-tool-use beta
748#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
749#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
750#[serde(rename_all = "lowercase")]
751pub enum ToolSearchAlgorithm {
752    /// Regex-based search using Python re.search() syntax
753    #[default]
754    Regex,
755    /// BM25-based natural language search
756    Bm25,
757    /// Forward-compatible catch-all for unknown algorithm values
758    #[serde(other)]
759    Unknown,
760}
761
762impl ToolSearchAlgorithm {
763    /// Returns the string representation of this algorithm variant.
764    fn as_str(&self) -> &str {
765        match self {
766            Self::Regex => "regex",
767            Self::Bm25 => "bm25",
768            Self::Unknown => "unknown",
769        }
770    }
771}
772
773impl std::fmt::Display for ToolSearchAlgorithm {
774    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
775        f.write_str(self.as_str())
776    }
777}
778
779/// Configuration for Anthropic's tool search feature (advanced-tool-use beta)
780/// Enables dynamic tool discovery for large tool catalogs (up to 10k tools)
781#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
782#[derive(Debug, Clone, Deserialize, Serialize)]
783pub struct ToolSearchConfig {
784    /// Enable tool search feature (requires advanced-tool-use-2025-11-20 beta)
785    #[serde(default = "default_tool_search_enabled")]
786    pub enabled: bool,
787
788    /// Search algorithm: "regex" (Python regex patterns) or "bm25" (natural language)
789    #[serde(default = "default_tool_search_algorithm")]
790    pub algorithm: ToolSearchAlgorithm,
791
792    /// Automatically defer loading of all tools except core tools
793    #[serde(default = "default_defer_by_default")]
794    pub defer_by_default: bool,
795
796    /// Maximum number of tool search results to return
797    #[serde(default = "default_max_results")]
798    max_results: u32,
799
800    /// Tool names that should never be deferred (always available)
801    #[serde(default)]
802    pub always_available_tools: Vec<String>,
803}
804
805impl Default for ToolSearchConfig {
806    fn default() -> Self {
807        Self {
808            enabled: default_tool_search_enabled(),
809            algorithm: default_tool_search_algorithm(),
810            defer_by_default: default_defer_by_default(),
811            max_results: default_max_results(),
812            always_available_tools: vec![],
813        }
814    }
815}
816
817#[inline]
818fn default_tool_search_enabled() -> bool {
819    true
820}
821
822#[inline]
823fn default_tool_search_algorithm() -> ToolSearchAlgorithm {
824    ToolSearchAlgorithm::Regex
825}
826
827#[inline]
828fn default_defer_by_default() -> bool {
829    true
830}
831
832#[inline]
833fn default_max_results() -> u32 {
834    5
835}
836
837#[inline]
838fn default_extended_thinking_enabled() -> bool {
839    true
840}
841
842mod serde_defaults;
843use serde_defaults::{
844    default_interleaved_thinking_beta, default_interleaved_thinking_budget_tokens, default_interleaved_thinking_type,
845    default_task_budget_beta,
846};
847
848#[cfg(test)]
849mod tests;