Skip to main content

vtcode_config/loader/
config.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4use std::str::FromStr;
5
6use crate::acp::AgentClientProtocolConfig;
7use crate::codex::{FileOpener, HistoryConfig, TuiConfig};
8use crate::computer_use::ComputerUseConfig;
9use crate::constants::defaults::DEFAULT_PRIMARY_AGENT_NAME;
10use crate::context::ContextFeaturesConfig;
11use crate::core::{
12    AgentConfig, AgentPermissionsConfig, AnthropicConfig, AuthConfig, AutomationConfig, CommandsConfig,
13    CustomProviderConfig, DesktopConfig, DotfileProtectionConfig, ModelConfig, OpenAIConfig, OpenRouterConfig,
14    PermissionsConfig, PromptCachingConfig, ProviderOverrideConfig, SandboxConfig, SecurityConfig, SkillsConfig,
15    ToolsConfig,
16};
17use crate::debug::DebugConfig;
18use crate::env_helpers::default_true;
19use crate::hooks::HooksConfig;
20use crate::mcp::McpClientConfig;
21use crate::models::{MiMoAuthMethod, Provider};
22use crate::optimization::OptimizationConfig;
23use crate::output_styles::OutputStyleConfig;
24use crate::root::{ChatConfig, PtyConfig, UiConfig};
25use crate::subagents::SubagentRuntimeLimits;
26use crate::telemetry::TelemetryConfig;
27use crate::timeouts::TimeoutsConfig;
28use crate::webmcp::WebmcpConfig;
29
30use crate::loader::syntax_highlighting::SyntaxHighlightingConfig;
31
32/// Provider-specific configuration
33#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
34#[derive(Debug, Clone, Deserialize, Serialize, Default)]
35pub struct ProviderConfig {
36    /// OpenAI provider configuration
37    #[serde(default)]
38    pub openai: OpenAIConfig,
39
40    /// Anthropic provider configuration
41    #[serde(default)]
42    pub anthropic: AnthropicConfig,
43
44    /// OpenRouter provider configuration
45    #[serde(default)]
46    pub openrouter: OpenRouterConfig,
47
48    /// Xiaomi MiMo auth method: "payg" or "token-plan"
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub mimo_auth_method: Option<MiMoAuthMethod>,
51}
52
53/// Codex-compatible top-level feature flags.
54///
55/// Maps to `[features]` in `vtcode.toml`.
56/// When `memories` is true, VT Code can carry useful context from earlier
57/// threads into future work via the persistent memory subsystem.
58#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
59#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
60pub struct FeaturesConfig {
61    /// Master toggle for the memories subsystem.
62    /// When true, VT Code extracts durable context from completed threads
63    /// and injects it into future sessions.
64    #[serde(default)]
65    pub memories: bool,
66}
67
68/// Workspace-level configuration controls.
69///
70/// Maps to `[workspace]` in `vtcode.toml`.
71/// When `use_root_config` is true, only the workspace root `vtcode.toml`
72/// is used as the active config layer (system, user, project, and
73/// dot-dir layers are discarded).
74#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
75#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
76pub struct WorkspaceConfig {
77    /// When true, force the workspace root `vtcode.toml` as the sole
78    /// active config layer, discarding system, user, project, and
79    /// dot-dir layers.
80    #[serde(default)]
81    pub(crate) use_root_config: bool,
82
83    /// Include workspace context in messages.
84    #[serde(default = "default_true")]
85    pub(crate) include_context: bool,
86
87    /// Maximum size of workspace context to include (in bytes).
88    #[serde(default)]
89    pub(crate) max_context_size: Option<usize>,
90}
91
92impl Default for WorkspaceConfig {
93    fn default() -> Self {
94        Self {
95            use_root_config: false,
96            include_context: true,
97            max_context_size: None,
98        }
99    }
100}
101
102/// Main configuration structure for VT Code
103#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
104#[derive(Debug, Clone, Deserialize, Serialize)]
105pub struct VTCodeConfig {
106    /// Primary agent selected at startup when no session override is active.
107    #[serde(default = "default_primary_agent")]
108    pub default_primary_agent: String,
109
110    /// Codex-compatible top-level feature flags (`[features]` table).
111    #[serde(default)]
112    pub features: FeaturesConfig,
113
114    /// Codex-compatible clickable citation URI scheme.
115    #[serde(default)]
116    pub file_opener: FileOpener,
117
118    /// External notification command invoked for supported events.
119    #[serde(default)]
120    pub notify: Vec<String>,
121
122    /// Codex-compatible local history persistence controls.
123    #[serde(default)]
124    pub history: HistoryConfig,
125
126    /// Codex-compatible TUI settings.
127    #[serde(default)]
128    pub tui: TuiConfig,
129
130    /// Native macOS desktop app settings.
131    #[serde(default)]
132    pub desktop: DesktopConfig,
133
134    /// Agent-wide settings
135    #[serde(default)]
136    pub agent: AgentConfig,
137
138    /// Authentication configuration for OAuth flows
139    #[serde(default)]
140    pub auth: AuthConfig,
141
142    /// Tool execution policies
143    #[serde(default)]
144    pub tools: ToolsConfig,
145
146    /// Unix command permissions
147    #[serde(default)]
148    pub commands: CommandsConfig,
149
150    /// Permission system settings (resolution, audit logging, caching)
151    #[serde(default)]
152    pub permissions: PermissionsConfig,
153
154    /// Runtime-only agent permission policy supplied by derived child agents.
155    #[serde(skip)]
156    #[cfg_attr(feature = "schema", schemars(skip))]
157    pub runtime_agent_permissions: Option<AgentPermissionsConfig>,
158
159    /// Runtime-only snapshot of lifecycle hook commands sourced from
160    /// workspace-controlled configuration layers, populated by `ConfigManager`
161    /// at load time. Workspace-controlled hooks require explicit user approval
162    /// before execution; see [`WorkspaceLifecycleHooks`](crate::hooks::WorkspaceLifecycleHooks).
163    #[serde(skip)]
164    #[cfg_attr(feature = "schema", schemars(skip))]
165    pub workspace_lifecycle_hooks: Option<crate::hooks::WorkspaceLifecycleHooks>,
166
167    /// Security settings
168    #[serde(default)]
169    pub security: SecurityConfig,
170
171    /// Sandbox settings for command execution isolation
172    #[serde(default)]
173    pub sandbox: SandboxConfig,
174
175    /// UI settings
176    #[serde(default)]
177    pub ui: UiConfig,
178
179    /// Chat settings
180    #[serde(default)]
181    pub chat: ChatConfig,
182
183    /// PTY settings
184    #[serde(default)]
185    pub pty: PtyConfig,
186
187    /// Debug and tracing settings
188    #[serde(default)]
189    pub debug: DebugConfig,
190
191    /// Context features (e.g., Decision Ledger)
192    #[serde(default)]
193    pub context: ContextFeaturesConfig,
194
195    /// Telemetry configuration (logging, trajectory)
196    #[serde(default)]
197    pub telemetry: TelemetryConfig,
198
199    /// Performance optimization settings
200    #[serde(default)]
201    pub optimization: OptimizationConfig,
202
203    /// Syntax highlighting configuration
204    #[serde(default)]
205    pub syntax_highlighting: SyntaxHighlightingConfig,
206
207    /// Timeout ceilings and UI warning thresholds
208    #[serde(default)]
209    pub timeouts: TimeoutsConfig,
210
211    /// Automation configuration
212    #[serde(default)]
213    pub automation: AutomationConfig,
214
215    /// Subagent runtime configuration
216    #[serde(default)]
217    pub subagents: SubagentRuntimeLimits,
218
219    /// Prompt cache configuration (local + provider integration)
220    #[serde(default)]
221    pub prompt_cache: PromptCachingConfig,
222
223    /// Model Context Protocol configuration
224    #[serde(default)]
225    pub mcp: McpClientConfig,
226
227    /// Authenticated browser editor bridge configuration
228    #[serde(default)]
229    pub webmcp: WebmcpConfig,
230
231    /// Opt-in computer-use runtime configuration
232    #[serde(default)]
233    pub computer_use: ComputerUseConfig,
234
235    /// Agent Client Protocol configuration
236    #[serde(default)]
237    pub acp: AgentClientProtocolConfig,
238
239    /// Lifecycle hooks configuration
240    #[serde(default)]
241    pub hooks: HooksConfig,
242
243    /// Model-specific behavior configuration
244    #[serde(default)]
245    pub model: ModelConfig,
246
247    /// Provider-specific configuration
248    #[serde(default)]
249    pub provider: ProviderConfig,
250
251    /// Skills system configuration (Agent Skills spec)
252    #[serde(default)]
253    pub skills: SkillsConfig,
254
255    /// Extra OpenAI-compatible endpoints for the model picker.
256    /// Define in user or system config only.
257    #[serde(default)]
258    pub custom_providers: Vec<CustomProviderConfig>,
259
260    /// Built-in provider overrides for model lists and endpoint configuration.
261    ///
262    /// Maps provider key (e.g., "opencode-zen", "opencode-go") to override
263    /// config that extends the provider's hardcoded model list with custom
264    /// models, and optionally overrides the base URL or API key env var.
265    #[serde(default)]
266    pub provider_overrides: BTreeMap<String, ProviderOverrideConfig>,
267
268    /// Restrict which providers may be used.
269    ///
270    /// When non-empty, only providers listed here are visible in the model
271    /// picker, selectable at first-run, and instantiable at runtime.  Empty
272    /// (the default) means all built-in and custom providers are available.
273    #[serde(default)]
274    pub providers_whitelist: Vec<String>,
275
276    /// Output style configuration
277    #[serde(default)]
278    pub output_style: OutputStyleConfig,
279
280    /// Dotfile protection configuration
281    #[serde(default)]
282    pub dotfile_protection: DotfileProtectionConfig,
283
284    /// Workspace-level configuration controls
285    #[serde(default)]
286    pub workspace: WorkspaceConfig,
287}
288
289impl Default for VTCodeConfig {
290    fn default() -> Self {
291        Self {
292            default_primary_agent: default_primary_agent(),
293            features: FeaturesConfig::default(),
294            file_opener: FileOpener::default(),
295            notify: Vec::new(),
296            history: HistoryConfig::default(),
297            tui: TuiConfig::default(),
298            desktop: DesktopConfig::default(),
299            agent: AgentConfig::default(),
300            auth: AuthConfig::default(),
301            tools: ToolsConfig::default(),
302            commands: CommandsConfig::default(),
303            permissions: PermissionsConfig::default(),
304            runtime_agent_permissions: None,
305            workspace_lifecycle_hooks: None,
306            security: SecurityConfig::default(),
307            sandbox: SandboxConfig::default(),
308            ui: UiConfig::default(),
309            chat: ChatConfig::default(),
310            pty: PtyConfig::default(),
311            debug: DebugConfig::default(),
312            context: ContextFeaturesConfig::default(),
313            telemetry: TelemetryConfig::default(),
314            optimization: OptimizationConfig::default(),
315            syntax_highlighting: SyntaxHighlightingConfig::default(),
316            timeouts: TimeoutsConfig::default(),
317            automation: AutomationConfig::default(),
318            subagents: SubagentRuntimeLimits::default(),
319            prompt_cache: PromptCachingConfig::default(),
320            mcp: McpClientConfig::default(),
321            webmcp: WebmcpConfig::default(),
322            computer_use: ComputerUseConfig::default(),
323            acp: AgentClientProtocolConfig::default(),
324            hooks: HooksConfig::default(),
325            model: ModelConfig::default(),
326            provider: ProviderConfig::default(),
327            skills: SkillsConfig::default(),
328            custom_providers: Vec::new(),
329            provider_overrides: BTreeMap::new(),
330            providers_whitelist: Vec::new(),
331            output_style: OutputStyleConfig::default(),
332            dotfile_protection: DotfileProtectionConfig::default(),
333            workspace: WorkspaceConfig::default(),
334        }
335    }
336}
337
338impl VTCodeConfig {
339    pub fn validate(&self) -> Result<()> {
340        self.syntax_highlighting
341            .validate()
342            .context("Invalid syntax_highlighting configuration")?;
343
344        self.context.validate().context("Invalid context configuration")?;
345
346        self.hooks.validate().context("Invalid hooks configuration")?;
347
348        self.timeouts.validate().context("Invalid timeouts configuration")?;
349
350        self.prompt_cache.validate().context("Invalid prompt_cache configuration")?;
351
352        self.webmcp.validate().context("Invalid webmcp configuration")?;
353
354        self.computer_use.validate().context("Invalid computer_use configuration")?;
355
356        self.permissions.validate().context("Invalid permissions configuration")?;
357
358        if let Some(agent_permissions) = &self.runtime_agent_permissions {
359            agent_permissions
360                .validate()
361                .context("Invalid runtime_agent_permissions configuration")?;
362        }
363
364        self.agent
365            .validate_llm_params()
366            .map_err(anyhow::Error::msg)
367            .context("Invalid agent configuration")?;
368
369        self.ui
370            .keyboard_protocol
371            .validate()
372            .context("Invalid keyboard_protocol configuration")?;
373
374        self.pty.validate().context("Invalid pty configuration")?;
375
376        // Validate custom providers
377        let mut seen_names = std::collections::HashSet::new();
378        for cp in &self.custom_providers {
379            cp.validate()
380                .map_err(|msg| anyhow::anyhow!(msg))
381                .context("Invalid custom_providers configuration")?;
382            if !seen_names.insert(cp.name.to_lowercase()) {
383                anyhow::bail!("custom_providers: duplicate name `{}`", cp.name);
384            }
385        }
386
387        // Validate provider overrides
388        for (provider_name, override_config) in &self.provider_overrides {
389            override_config
390                .validate(provider_name)
391                .map_err(|msg| anyhow::anyhow!(msg))
392                .context("Invalid provider_overrides configuration")?;
393            // Validate that the provider key matches a known provider
394            if Provider::from_str(provider_name).is_err() {
395                anyhow::bail!(
396                    "provider_overrides: unknown provider `{provider_name}`; \
397                     must be one of: gemini, openai, anthropic, copilot, deepseek, meta, \
398                     openrouter, ollama, lmstudio, llamacpp, moonshot, zai, minimax, \
399                     mimo, mistral, huggingface, opencodezen, opencodego, qwen, \
400                     stepfun, evolink, poolside, nvidia, merge-gateway, vercel"
401                );
402            }
403        }
404
405        // Validate providers_whitelist entries
406        for entry in &self.providers_whitelist {
407            let known = Provider::from_str(entry).is_ok() || self.custom_providers.iter().any(|cp| cp.name == *entry);
408            if !known {
409                anyhow::bail!(
410                    "providers_whitelist: unknown provider `{entry}`; \
411                     must be a built-in provider or a name from custom_providers"
412                );
413            }
414        }
415
416        Ok(())
417    }
418
419    /// Returns true when the persistent memory subsystem is enabled.
420    ///
421    /// The top-level `features.memories` flag is the global master switch.
422    /// `agent.persistent_memory.enabled` then enables repository-scoped storage.
423    #[must_use]
424    pub fn persistent_memory_enabled(&self) -> bool {
425        self.features.memories && self.agent.persistent_memory.enabled
426    }
427
428    /// Returns true when the memories subsystem is enabled for injection.
429    ///
430    /// Memories are active when the subsystem is enabled and `memories.use_memories`
431    /// is true.
432    #[must_use]
433    pub fn memories_enabled(&self) -> bool {
434        self.persistent_memory_enabled() && self.agent.persistent_memory.memories.use_memories
435    }
436
437    /// Returns true when completed threads should be stored as memory inputs.
438    #[must_use]
439    pub fn should_generate_memories(&self) -> bool {
440        self.persistent_memory_enabled() && self.agent.persistent_memory.memories.generate_memories
441    }
442
443    /// Look up a custom provider by its stable key.
444    pub fn custom_provider(&self, name: &str) -> Option<&CustomProviderConfig> {
445        let lower = name.to_lowercase();
446        self.custom_providers.iter().find(|cp| cp.name.to_lowercase() == lower)
447    }
448
449    /// Return the explicitly configured credential key for a provider.
450    ///
451    /// Custom-provider identities take precedence over built-in provider
452    /// overrides. A missing result means callers should use the provider's
453    /// built-in default or the agent-wide fallback.
454    pub fn configured_api_key_env(&self, name: &str) -> Option<String> {
455        if let Some(custom_provider) = self.custom_provider(name) {
456            return Some(custom_provider.resolved_api_key_env());
457        }
458
459        self.provider_overrides
460            .iter()
461            .find(|(provider, _)| provider.eq_ignore_ascii_case(name))
462            .and_then(|(_, provider_override)| provider_override.api_key_env.clone())
463            .filter(|api_key_env| !api_key_env.trim().is_empty())
464    }
465
466    /// Get the display name for any provider key, falling back to the raw key
467    /// if no custom provider matches.
468    pub fn provider_display_name(&self, provider_key: &str) -> String {
469        if let Some(cp) = self.custom_provider(provider_key) {
470            cp.display_name.clone()
471        } else if provider_key.eq_ignore_ascii_case("codex") {
472            "Codex".to_string()
473        } else if let Ok(p) = FromStr::from_str(provider_key) {
474            let p: Provider = p;
475            p.label().to_string()
476        } else {
477            provider_key.to_string()
478        }
479    }
480}
481
482fn default_primary_agent() -> String {
483    DEFAULT_PRIMARY_AGENT_NAME.to_string()
484}