Skip to main content

vtcode_config/loader/
config.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::fs;
4use std::path::Path;
5
6use crate::acp::AgentClientProtocolConfig;
7use crate::codex::{FileOpener, HistoryConfig, TuiConfig};
8use crate::context::ContextFeaturesConfig;
9use crate::core::{
10    AgentConfig, AnthropicConfig, AuthConfig, AutomationConfig, CommandsConfig,
11    CustomProviderConfig, DotfileProtectionConfig, ModelConfig, OpenAIConfig, PermissionsConfig,
12    PromptCachingConfig, SandboxConfig, SecurityConfig, SkillsConfig, ToolsConfig,
13};
14use crate::debug::DebugConfig;
15use crate::defaults::{self, ConfigDefaultsProvider};
16use crate::hooks::HooksConfig;
17use crate::ide_context::IdeContextConfig;
18use crate::mcp::McpClientConfig;
19use crate::optimization::OptimizationConfig;
20use crate::output_styles::OutputStyleConfig;
21use crate::root::{ChatConfig, PtyConfig, UiConfig};
22use crate::subagents::SubagentRuntimeLimits;
23use crate::telemetry::TelemetryConfig;
24use crate::timeouts::TimeoutsConfig;
25
26use crate::loader::syntax_highlighting::SyntaxHighlightingConfig;
27
28/// Provider-specific configuration
29#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
30#[derive(Debug, Clone, Deserialize, Serialize, Default)]
31pub struct ProviderConfig {
32    /// OpenAI provider configuration
33    #[serde(default)]
34    pub openai: OpenAIConfig,
35
36    /// Anthropic provider configuration
37    #[serde(default)]
38    pub anthropic: AnthropicConfig,
39}
40
41/// Codex-compatible top-level feature flags.
42///
43/// Maps to `[features]` in `vtcode.toml`.
44/// When `memories` is true, VT Code can carry useful context from earlier
45/// threads into future work via the persistent memory subsystem.
46#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
47#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
48pub struct FeaturesConfig {
49    /// Master toggle for the memories subsystem.
50    /// When true, VT Code extracts durable context from completed threads
51    /// and injects it into future sessions.
52    #[serde(default)]
53    pub memories: bool,
54}
55
56/// Main configuration structure for VT Code
57#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
58#[derive(Debug, Clone, Deserialize, Serialize, Default)]
59pub struct VTCodeConfig {
60    /// Codex-compatible top-level feature flags (`[features]` table).
61    #[serde(default)]
62    pub features: FeaturesConfig,
63
64    /// Codex-compatible clickable citation URI scheme.
65    #[serde(default)]
66    pub file_opener: FileOpener,
67
68    /// External notification command invoked for supported events.
69    #[serde(default)]
70    pub notify: Vec<String>,
71
72    /// Codex-compatible local history persistence controls.
73    #[serde(default)]
74    pub history: HistoryConfig,
75
76    /// Codex-compatible TUI settings.
77    #[serde(default)]
78    pub tui: TuiConfig,
79
80    /// Agent-wide settings
81    #[serde(default)]
82    pub agent: AgentConfig,
83
84    /// Authentication configuration for OAuth flows
85    #[serde(default)]
86    pub auth: AuthConfig,
87
88    /// Tool execution policies
89    #[serde(default)]
90    pub tools: ToolsConfig,
91
92    /// Unix command permissions
93    #[serde(default)]
94    pub commands: CommandsConfig,
95
96    /// Permission system settings (resolution, audit logging, caching)
97    #[serde(default)]
98    pub permissions: PermissionsConfig,
99
100    /// Security settings
101    #[serde(default)]
102    pub security: SecurityConfig,
103
104    /// Sandbox settings for command execution isolation
105    #[serde(default)]
106    pub sandbox: SandboxConfig,
107
108    /// UI settings
109    #[serde(default)]
110    pub ui: UiConfig,
111
112    /// Chat settings
113    #[serde(default)]
114    pub chat: ChatConfig,
115
116    /// PTY settings
117    #[serde(default)]
118    pub pty: PtyConfig,
119
120    /// Debug and tracing settings
121    #[serde(default)]
122    pub debug: DebugConfig,
123
124    /// Context features (e.g., Decision Ledger)
125    #[serde(default)]
126    pub context: ContextFeaturesConfig,
127
128    /// Telemetry configuration (logging, trajectory)
129    #[serde(default)]
130    pub telemetry: TelemetryConfig,
131
132    /// Performance optimization settings
133    #[serde(default)]
134    pub optimization: OptimizationConfig,
135
136    /// Syntax highlighting configuration
137    #[serde(default)]
138    pub syntax_highlighting: SyntaxHighlightingConfig,
139
140    /// Timeout ceilings and UI warning thresholds
141    #[serde(default)]
142    pub timeouts: TimeoutsConfig,
143
144    /// Automation configuration
145    #[serde(default)]
146    pub automation: AutomationConfig,
147
148    /// Subagent runtime configuration
149    #[serde(default)]
150    pub subagents: SubagentRuntimeLimits,
151
152    /// Prompt cache configuration (local + provider integration)
153    #[serde(default)]
154    pub prompt_cache: PromptCachingConfig,
155
156    /// Model Context Protocol configuration
157    #[serde(default)]
158    pub mcp: McpClientConfig,
159
160    /// Agent Client Protocol configuration
161    #[serde(default)]
162    pub acp: AgentClientProtocolConfig,
163
164    /// IDE context configuration
165    #[serde(default)]
166    pub ide_context: IdeContextConfig,
167
168    /// Lifecycle hooks configuration
169    #[serde(default)]
170    pub hooks: HooksConfig,
171
172    /// Model-specific behavior configuration
173    #[serde(default)]
174    pub model: ModelConfig,
175
176    /// Provider-specific configuration
177    #[serde(default)]
178    pub provider: ProviderConfig,
179
180    /// Skills system configuration (Agent Skills spec)
181    #[serde(default)]
182    pub skills: SkillsConfig,
183
184    /// User-defined OpenAI-compatible provider endpoints.
185    /// These entries are editable in `/config` and appear in the model picker
186    /// using each entry's `display_name`.
187    #[serde(default)]
188    pub custom_providers: Vec<CustomProviderConfig>,
189
190    /// Output style configuration
191    #[serde(default)]
192    pub output_style: OutputStyleConfig,
193
194    /// Dotfile protection configuration
195    #[serde(default)]
196    pub dotfile_protection: DotfileProtectionConfig,
197}
198
199impl VTCodeConfig {
200    pub fn validate(&self) -> Result<()> {
201        self.syntax_highlighting
202            .validate()
203            .context("Invalid syntax_highlighting configuration")?;
204
205        self.context
206            .validate()
207            .context("Invalid context configuration")?;
208
209        self.hooks
210            .validate()
211            .context("Invalid hooks configuration")?;
212
213        self.timeouts
214            .validate()
215            .context("Invalid timeouts configuration")?;
216
217        self.prompt_cache
218            .validate()
219            .context("Invalid prompt_cache configuration")?;
220
221        self.agent
222            .validate_llm_params()
223            .map_err(anyhow::Error::msg)
224            .context("Invalid agent configuration")?;
225
226        self.ui
227            .keyboard_protocol
228            .validate()
229            .context("Invalid keyboard_protocol configuration")?;
230
231        self.pty.validate().context("Invalid pty configuration")?;
232
233        // Validate custom providers
234        let mut seen_names = std::collections::HashSet::new();
235        for cp in &self.custom_providers {
236            cp.validate()
237                .map_err(|msg| anyhow::anyhow!(msg))
238                .context("Invalid custom_providers configuration")?;
239            if !seen_names.insert(cp.name.to_lowercase()) {
240                anyhow::bail!("custom_providers: duplicate name `{}`", cp.name);
241            }
242        }
243
244        Ok(())
245    }
246
247    /// Returns true when the persistent memory subsystem is enabled.
248    ///
249    /// The top-level `features.memories` flag is the global master switch.
250    /// `agent.persistent_memory.enabled` then enables repository-scoped storage.
251    #[must_use]
252    pub fn persistent_memory_enabled(&self) -> bool {
253        self.features.memories && self.agent.persistent_memory.enabled
254    }
255
256    /// Returns true when the memories subsystem is enabled for injection.
257    ///
258    /// Memories are active when the subsystem is enabled and `memories.use_memories`
259    /// is true.
260    #[must_use]
261    pub fn memories_enabled(&self) -> bool {
262        self.persistent_memory_enabled() && self.agent.persistent_memory.memories.use_memories
263    }
264
265    /// Returns true when completed threads should be stored as memory inputs.
266    #[must_use]
267    pub fn should_generate_memories(&self) -> bool {
268        self.persistent_memory_enabled() && self.agent.persistent_memory.memories.generate_memories
269    }
270
271    /// Look up a custom provider by its stable key.
272    pub fn custom_provider(&self, name: &str) -> Option<&CustomProviderConfig> {
273        let lower = name.to_lowercase();
274        self.custom_providers
275            .iter()
276            .find(|cp| cp.name.to_lowercase() == lower)
277    }
278
279    /// Get the display name for any provider key, falling back to the raw key
280    /// if no custom provider matches.
281    pub fn provider_display_name(&self, provider_key: &str) -> String {
282        if let Some(cp) = self.custom_provider(provider_key) {
283            cp.display_name.clone()
284        } else if provider_key.eq_ignore_ascii_case("codex") {
285            "Codex".to_string()
286        } else if let Ok(p) = std::str::FromStr::from_str(provider_key) {
287            let p: crate::models::Provider = p;
288            p.label().to_string()
289        } else {
290            provider_key.to_string()
291        }
292    }
293
294    #[cfg(feature = "bootstrap")]
295    /// Bootstrap project with config + gitignore
296    pub fn bootstrap_project<P: AsRef<Path>>(workspace: P, force: bool) -> Result<Vec<String>> {
297        Self::bootstrap_project_with_options(workspace, force, false)
298    }
299
300    #[cfg(feature = "bootstrap")]
301    /// Bootstrap project with config + gitignore, with option to create in home directory
302    pub fn bootstrap_project_with_options<P: AsRef<Path>>(
303        workspace: P,
304        force: bool,
305        use_home_dir: bool,
306    ) -> Result<Vec<String>> {
307        let workspace = workspace.as_ref().to_path_buf();
308        defaults::with_config_defaults(|provider| {
309            Self::bootstrap_project_with_provider(&workspace, force, use_home_dir, provider)
310        })
311    }
312
313    #[cfg(feature = "bootstrap")]
314    /// Bootstrap project files using the supplied [`ConfigDefaultsProvider`].
315    pub fn bootstrap_project_with_provider<P: AsRef<Path>>(
316        workspace: P,
317        force: bool,
318        use_home_dir: bool,
319        defaults_provider: &dyn ConfigDefaultsProvider,
320    ) -> Result<Vec<String>> {
321        let workspace = workspace.as_ref();
322        let config_file_name = defaults_provider.config_file_name().to_string();
323        let (config_path, gitignore_path) = crate::loader::bootstrap::determine_bootstrap_targets(
324            workspace,
325            use_home_dir,
326            &config_file_name,
327            defaults_provider,
328        )?;
329        let vtcode_readme_path = workspace.join(".vtcode").join("README.md");
330        let ast_grep_config_path = workspace.join("sgconfig.yml");
331        let ast_grep_rule_path = workspace
332            .join("rules")
333            .join("examples")
334            .join("no-console-log.yml");
335        let ast_grep_test_path = workspace
336            .join("rule-tests")
337            .join("examples")
338            .join("no-console-log-test.yml");
339        let ast_grep_snapshot_path = workspace
340            .join("rule-tests")
341            .join("__snapshots__")
342            .join("no-console-log-snapshot.yml");
343
344        crate::loader::bootstrap::ensure_parent_dir(&config_path)?;
345        crate::loader::bootstrap::ensure_parent_dir(&gitignore_path)?;
346        crate::loader::bootstrap::ensure_parent_dir(&vtcode_readme_path)?;
347        crate::loader::bootstrap::ensure_parent_dir(&ast_grep_config_path)?;
348        crate::loader::bootstrap::ensure_parent_dir(&ast_grep_rule_path)?;
349        crate::loader::bootstrap::ensure_parent_dir(&ast_grep_test_path)?;
350        crate::loader::bootstrap::ensure_parent_dir(&ast_grep_snapshot_path)?;
351
352        let mut created_files = Vec::new();
353
354        if !config_path.exists() || force {
355            let config_content = Self::default_vtcode_toml_template();
356
357            fs::write(&config_path, config_content).with_context(|| {
358                format!("Failed to write config file: {}", config_path.display())
359            })?;
360
361            if let Some(file_name) = config_path.file_name().and_then(|name| name.to_str()) {
362                created_files.push(file_name.to_string());
363            }
364        }
365
366        if !gitignore_path.exists() || force {
367            let gitignore_content = Self::default_vtcode_gitignore();
368            fs::write(&gitignore_path, gitignore_content).with_context(|| {
369                format!(
370                    "Failed to write gitignore file: {}",
371                    gitignore_path.display()
372                )
373            })?;
374
375            if let Some(file_name) = gitignore_path.file_name().and_then(|name| name.to_str()) {
376                created_files.push(file_name.to_string());
377            }
378        }
379
380        if !vtcode_readme_path.exists() || force {
381            let vtcode_readme = Self::default_vtcode_readme_template();
382            fs::write(&vtcode_readme_path, vtcode_readme).with_context(|| {
383                format!(
384                    "Failed to write VT Code README: {}",
385                    vtcode_readme_path.display()
386                )
387            })?;
388            created_files.push(".vtcode/README.md".to_string());
389        }
390
391        let ast_grep_files = [
392            (
393                &ast_grep_config_path,
394                Self::default_ast_grep_config_template(),
395                "sgconfig.yml",
396            ),
397            (
398                &ast_grep_rule_path,
399                Self::default_ast_grep_example_rule_template(),
400                "rules/examples/no-console-log.yml",
401            ),
402            (
403                &ast_grep_test_path,
404                Self::default_ast_grep_example_test_template(),
405                "rule-tests/examples/no-console-log-test.yml",
406            ),
407            (
408                &ast_grep_snapshot_path,
409                Self::default_ast_grep_example_snapshot_template(),
410                "rule-tests/__snapshots__/no-console-log-snapshot.yml",
411            ),
412        ];
413
414        for (path, contents, label) in ast_grep_files {
415            if !path.exists() || force {
416                fs::write(path, contents).with_context(|| {
417                    format!("Failed to write ast-grep scaffold file: {}", path.display())
418                })?;
419                created_files.push(label.to_string());
420            }
421        }
422
423        Ok(created_files)
424    }
425
426    #[cfg(feature = "bootstrap")]
427    /// Generate the default `vtcode.toml` template used by bootstrap helpers.
428    fn default_vtcode_toml_template() -> String {
429        r#"# VT Code Configuration File (Example)
430# Getting-started reference; see docs/config/CONFIGURATION_PRECEDENCE.md for override order.
431# Copy this file to vtcode.toml and customize as needed.
432
433# Clickable file citation URI scheme ("vscode", "cursor", "windsurf", "vscode-insiders", "none")
434file_opener = "none"
435
436# Optional external command invoked after each completed agent turn
437notify = []
438
439# User-defined OpenAI-compatible providers
440custom_providers = []
441
442# [[custom_providers]]
443# name = "mycorp"
444# display_name = "MyCorporateName"
445# base_url = "https://llm.corp.example/v1"
446# api_key_env = "MYCORP_API_KEY"
447# model = "gpt-5-mini"
448
449[history]
450# Persist local session transcripts to disk
451persistence = "file"
452
453# Optional max size budget for each persisted session snapshot
454# max_bytes = 104857600
455
456[tui]
457# Enable all built-in TUI notifications, disable them, or restrict to specific event types.
458# notifications = true
459# notifications = ["agent-turn-complete", "approval-requested"]
460
461# Notification transport: "auto", "osc9", or "bel"
462# notification_method = "auto"
463
464# Set to false to reduce shimmer/animation effects
465# animations = true
466
467# Alternate-screen override: "always" or "never"
468# alternate_screen = "never"
469
470# Show onboarding hints on the welcome screen
471# show_tooltips = true
472
473# Core agent behavior; see docs/config/CONFIGURATION_PRECEDENCE.md.
474[agent]
475# Primary LLM provider to use (e.g., "openai", "gemini", "anthropic", "openrouter")
476provider = "openai"
477
478# Environment variable containing the API key for the provider
479api_key_env = "OPENAI_API_KEY"
480
481# Default model to use when no specific model is specified
482default_model = "gpt-5.4"
483
484# Visual theme for the terminal interface
485theme = "ciapre-dark"
486
487# Enable TODO planning helper mode for structured task management
488todo_planning_mode = true
489
490# UI surface to use ("auto", "alternate", "inline")
491ui_surface = "auto"
492
493# Maximum number of conversation turns before rotating context (affects memory usage)
494# Lower values reduce memory footprint but may lose context; higher values preserve context but use more memory
495max_conversation_turns = 150
496
497# Reasoning effort level ("none", "minimal", "low", "medium", "high", "xhigh", "max") - affects model usage and response speed
498reasoning_effort = "none"
499
500# Temperature for main model responses (0.0-1.0)
501temperature = 0.7
502
503# Enable self-review loop to check and improve responses (increases API calls)
504enable_self_review = false
505
506# Maximum number of review passes when self-review is enabled
507max_review_passes = 1
508
509# Enable prompt refinement loop for improved prompt quality (increases processing time)
510refine_prompts_enabled = false
511
512# Maximum passes for prompt refinement when enabled
513refine_prompts_max_passes = 1
514
515# Optional alternate model for refinement (leave empty to use default)
516refine_prompts_model = ""
517
518# Maximum size of project documentation to include in context (in bytes)
519project_doc_max_bytes = 16384
520
521# Maximum size of instruction files to process (in bytes)
522instruction_max_bytes = 16384
523
524# List of additional instruction files to include in context
525instruction_files = []
526
527# Instruction files or globs to exclude from AGENTS/rules discovery
528instruction_excludes = []
529
530# Maximum recursive @import depth for instruction and rule files
531instruction_import_max_depth = 5
532
533# Durable per-repository memory for main sessions
534[agent.persistent_memory]
535enabled = false
536auto_write = true
537# directory_override = "/absolute/user-local/path"
538# Startup scan budget for the compact memory summary
539startup_line_limit = 200
540startup_byte_limit = 25600
541
542# Lightweight model helpers for lower-cost side tasks
543[agent.small_model]
544enabled = true
545model = ""
546temperature = 0.3
547use_for_large_reads = true
548use_for_web_summary = true
549use_for_git_history = true
550use_for_memory = true
551
552# Inline prompt suggestions for the chat composer
553[agent.prompt_suggestions]
554# Enable Alt+P ghost-text suggestions in the composer
555enabled = true
556
557# Lightweight model for prompt suggestions (leave empty to auto-pick)
558model = ""
559
560# Lower values keep suggestions stable and completion-like
561temperature = 0.3
562
563# Show a one-time note that LLM-backed suggestions can consume tokens
564show_cost_notice = true
565
566# Onboarding configuration - Customize the startup experience
567[agent.onboarding]
568# Enable the onboarding welcome message on startup
569enabled = true
570
571# Custom introduction text shown on startup
572intro_text = "Let's get oriented. I preloaded workspace context so we can move fast."
573
574# Include project overview information in welcome
575include_project_overview = true
576
577# Include language summary information in welcome
578include_language_summary = false
579
580# Include key guideline highlights from AGENTS.md
581include_guideline_highlights = true
582
583# Include usage tips in the welcome message
584include_usage_tips_in_welcome = false
585
586# Include recommended actions in the welcome message
587include_recommended_actions_in_welcome = false
588
589# Maximum number of guideline highlights to show
590guideline_highlight_limit = 3
591
592# List of usage tips shown during onboarding
593usage_tips = [
594    "Describe your current coding goal or ask for a quick status overview.",
595    "Reference AGENTS.md guidelines when proposing changes.",
596    "Prefer asking for targeted file reads or diffs before editing.",
597]
598
599# List of recommended actions shown during onboarding
600recommended_actions = [
601    "Review the highlighted guidelines and share the task you want to tackle.",
602    "Ask for a workspace tour if you need more context.",
603]
604
605# Checkpointing configuration for session persistence
606[agent.checkpointing]
607# Enable automatic session checkpointing
608enabled = true
609
610# Maximum number of checkpoints to keep on disk
611max_snapshots = 50
612
613# Maximum age of checkpoints to keep (in days)
614max_age_days = 30
615
616# Tool security configuration
617[tools]
618# Default policy when no specific policy is defined ("allow", "prompt", "deny")
619# "allow" - Execute without confirmation
620# "prompt" - Ask for confirmation
621# "deny" - Block the tool
622default_policy = "prompt"
623
624# Maximum number of tool loops allowed per turn
625# Set to 0 to disable the limit and let other turn safeguards govern termination.
626max_tool_loops = 0
627
628# Maximum number of repeated identical tool calls (prevents stuck loops)
629max_repeated_tool_calls = 2
630
631# Maximum consecutive blocked tool calls before force-breaking the turn
632# Helps prevent high-CPU churn when calls are repeatedly denied/blocked
633max_consecutive_blocked_tool_calls_per_turn = 8
634
635# Maximum sequential spool-chunk reads per turn before nudging targeted extraction/summarization
636max_sequential_spool_chunk_reads = 6
637
638# Specific tool policies - Override default policy for individual tools
639[tools.policies]
640apply_patch = "prompt"            # Apply code patches (requires confirmation)
641request_user_input = "allow"      # Ask focused user questions when the task requires it
642task_tracker = "prompt"           # Create or update explicit task plans
643unified_exec = "prompt"           # Run commands; pipe-first by default, set tty=true for PTY/interactive sessions
644unified_file = "allow"            # Canonical file read/write/edit/move/copy/delete surface
645unified_search = "allow"          # Canonical search/list/intelligence/error surface
646
647# Command security - Define safe and dangerous command patterns
648[commands]
649# Commands that are always allowed without confirmation
650allow_list = [
651    "ls",           # List directory contents
652    "pwd",          # Print working directory
653    "git status",   # Show git status
654    "git diff",     # Show git differences
655    "cargo check",  # Check Rust code
656    "echo",         # Print text
657]
658
659# Commands that are never allowed
660deny_list = [
661    "rm -rf /",        # Delete root directory (dangerous)
662    "rm -rf ~",        # Delete home directory (dangerous)
663    "shutdown",        # Shut down system (dangerous)
664    "reboot",          # Reboot system (dangerous)
665    "sudo *",          # Any sudo command (dangerous)
666    ":(){ :|:& };:",   # Fork bomb (dangerous)
667]
668
669# Command patterns that are allowed (supports glob patterns)
670allow_glob = [
671    "git *",        # All git commands
672    "cargo *",      # All cargo commands
673    "python -m *",  # Python module commands
674]
675
676# Command patterns that are denied (supports glob patterns)
677deny_glob = [
678    "rm *",         # All rm commands
679    "sudo *",       # All sudo commands
680    "chmod *",      # All chmod commands
681    "chown *",      # All chown commands
682    "kubectl *",    # All kubectl commands (admin access)
683]
684
685# Regular expression patterns for allowed commands (if needed)
686allow_regex = []
687
688# Regular expression patterns for denied commands (if needed)
689deny_regex = []
690
691# Security configuration - Safety settings for automated operations
692[security]
693# Require human confirmation for potentially dangerous actions
694human_in_the_loop = true
695
696# Require explicit write tool usage for claims about file modifications
697require_write_tool_for_claims = true
698
699# Auto-apply patches without prompting (DANGEROUS - disable for safety)
700auto_apply_detected_patches = false
701
702# UI configuration - Terminal and display settings
703[ui]
704# Tool output display mode
705# "compact" - Concise tool output
706# "full" - Detailed tool output
707tool_output_mode = "compact"
708
709# Maximum number of lines to display in tool output (prevents transcript flooding)
710# Lines beyond this limit are truncated to a tail preview
711tool_output_max_lines = 600
712
713# Maximum bytes threshold for spooling tool output to disk
714# Output exceeding this size is written to .vtcode/tool-output/*.log
715tool_output_spool_bytes = 200000
716
717# Optional custom directory for spooled tool output logs
718# If not set, defaults to .vtcode/tool-output/
719# tool_output_spool_dir = "/path/to/custom/spool/dir"
720
721# Allow ANSI escape sequences in tool output (enables colors but may cause layout issues)
722allow_tool_ansi = false
723
724# Number of rows to allocate for inline UI viewport
725inline_viewport_rows = 16
726
727# Show elapsed time divider after each completed turn
728show_turn_timer = false
729
730# Show warning/error/fatal diagnostic lines directly in transcript
731# Effective in debug/development builds only
732show_diagnostics_in_transcript = false
733
734# Show timeline navigation panel
735show_timeline_pane = false
736
737# Runtime notification preferences
738[ui.notifications]
739# Master toggle for terminal/desktop notifications
740enabled = true
741
742# Delivery mode: "terminal", "hybrid", or "desktop"
743delivery_mode = "desktop"
744
745# Preferred desktop backend: "auto", "osascript", "notify_rust", or "terminal"
746backend = "auto"
747
748# Suppress notifications while terminal is focused
749suppress_when_focused = true
750
751# Failure/error notifications
752command_failure = false
753tool_failure = false
754error = true
755
756# Completion notifications
757# Legacy master toggle (fallback for split settings when unset)
758completion = true
759completion_success = false
760completion_failure = true
761
762# Human approval/interaction notifications
763hitl = true
764policy_approval = true
765request = false
766
767# Success notifications for tool call results
768tool_success = false
769
770# Repeated notification suppression
771repeat_window_seconds = 30
772max_identical_in_window = 1
773
774# Status line configuration
775[ui.status_line]
776# Status line mode ("auto", "command", "hidden")
777mode = "auto"
778
779# How often to refresh status line (milliseconds)
780refresh_interval_ms = 2000
781
782# Timeout for command execution in status line (milliseconds)
783command_timeout_ms = 200
784
785# Terminal title configuration
786[ui.terminal_title]
787# Ordered terminal title items (empty list disables VT Code-managed titles)
788items = ["spinner", "project"]
789
790# Enable Vim-style prompt editing in interactive mode
791vim_mode = false
792
793# PTY (Pseudo Terminal) configuration - For interactive command execution
794[pty]
795# Enable PTY support for interactive commands
796enabled = true
797
798# Default number of terminal rows for PTY sessions
799default_rows = 24
800
801# Default number of terminal columns for PTY sessions
802default_cols = 80
803
804# Maximum number of concurrent PTY sessions
805max_sessions = 10
806
807# Command timeout in seconds (prevents hanging commands)
808command_timeout_seconds = 300
809
810# Number of recent lines to show in PTY output
811stdout_tail_lines = 20
812
813# Total lines to keep in PTY scrollback buffer
814scrollback_lines = 400
815
816# Terminal emulation backend for PTY snapshots
817emulation_backend = "ghostty"
818
819# Optional preferred shell for PTY sessions (falls back to $SHELL when unset)
820# preferred_shell = "/bin/zsh"
821
822# Route shell execution through zsh EXEC_WRAPPER intercept hooks (feature-gated)
823shell_zsh_fork = false
824
825# Absolute path to patched zsh used when shell_zsh_fork is enabled
826# zsh_path = "/usr/local/bin/zsh"
827
828# Context management configuration - Controls conversation memory
829[context]
830# Maximum number of tokens to keep in context (affects model cost and performance)
831# Higher values preserve more context but cost more and may hit token limits
832max_context_tokens = 90000
833
834# Percentage to trim context to when it gets too large
835trim_to_percent = 60
836
837# Number of recent conversation turns to always preserve
838preserve_recent_turns = 6
839
840# Decision ledger configuration - Track important decisions
841[context.ledger]
842# Enable decision tracking and persistence
843enabled = true
844
845# Maximum number of decisions to keep in ledger
846max_entries = 12
847
848# Include ledger summary in model prompts
849include_in_prompt = true
850
851# Preserve ledger during context compression
852preserve_in_compression = true
853
854# AI model routing - Intelligent model selection
855# Telemetry and analytics
856[telemetry]
857# Enable trajectory logging for usage analysis
858trajectory_enabled = true
859
860# Syntax highlighting configuration
861[syntax_highlighting]
862# Enable syntax highlighting for code in tool output
863enabled = true
864
865# Theme for syntax highlighting
866theme = "base16-ocean.dark"
867
868# Cache syntax highlighting themes for performance
869cache_themes = true
870
871# Maximum file size for syntax highlighting (in MB)
872max_file_size_mb = 10
873
874# Programming languages to enable syntax highlighting for
875enabled_languages = [
876    "rust",
877    "python",
878    "javascript",
879    "typescript",
880    "go",
881    "java",
882    "bash",
883    "sh",
884    "shell",
885    "zsh",
886    "markdown",
887    "md",
888]
889
890# Timeout for syntax highlighting operations (milliseconds)
891highlight_timeout_ms = 1000
892
893# Automation features - Full-auto mode settings
894[automation.full_auto]
895# Enable full automation mode (DANGEROUS - requires careful oversight)
896enabled = false
897
898# Maximum number of turns before asking for human input
899max_turns = 30
900
901# Tools allowed in full automation mode
902allowed_tools = [
903    "write_file",
904    "read_file",
905    "list_files",
906    "grep_file",
907]
908
909# Require profile acknowledgment before using full auto
910require_profile_ack = true
911
912# Path to full auto profile configuration
913profile_path = "automation/full_auto_profile.toml"
914
915[automation.scheduled_tasks]
916# Enable /loop, cron tools, and durable `vtcode schedule` jobs
917enabled = false
918
919# Prompt caching - Cache model responses for efficiency
920[prompt_cache]
921# Enable prompt caching (reduces API calls for repeated prompts)
922enabled = true
923
924# Directory for cache storage
925cache_dir = "~/.vtcode/cache/prompts"
926
927# Maximum number of cache entries to keep
928max_entries = 1000
929
930# Maximum age of cache entries (in days)
931max_age_days = 30
932
933# Enable automatic cache cleanup
934enable_auto_cleanup = true
935
936# Minimum quality threshold to keep cache entries
937min_quality_threshold = 0.7
938
939# Keep volatile runtime counters at the end of system prompts to improve provider-side prefix cache reuse
940# (enabled by default; disable only if you need legacy prompt layout)
941cache_friendly_prompt_shaping = true
942
943# Prompt cache configuration for OpenAI
944    [prompt_cache.providers.openai]
945    enabled = true
946    min_prefix_tokens = 1024
947    idle_expiration_seconds = 3600
948    surface_metrics = true
949    # Routing key strategy for OpenAI prompt cache locality.
950    # "session" creates one stable key per VT Code conversation.
951    prompt_cache_key_mode = "session"
952    # Optional: server-side prompt cache retention for OpenAI Responses API
953    # Supported values: "in_memory" or "24h" (leave commented out for default behavior)
954    # prompt_cache_retention = "24h"
955
956# Prompt cache configuration for Anthropic
957[prompt_cache.providers.anthropic]
958enabled = true
959default_ttl_seconds = 300
960extended_ttl_seconds = 3600
961max_breakpoints = 4
962cache_system_messages = true
963cache_user_messages = true
964
965# Prompt cache configuration for Gemini
966[prompt_cache.providers.gemini]
967enabled = true
968mode = "implicit"
969min_prefix_tokens = 1024
970explicit_ttl_seconds = 3600
971
972# Prompt cache configuration for OpenRouter
973[prompt_cache.providers.openrouter]
974enabled = true
975propagate_provider_capabilities = true
976report_savings = true
977
978# Prompt cache configuration for Moonshot
979[prompt_cache.providers.moonshot]
980enabled = true
981
982# Prompt cache configuration for DeepSeek
983[prompt_cache.providers.deepseek]
984enabled = true
985surface_metrics = true
986
987# Prompt cache configuration for Z.AI
988[prompt_cache.providers.zai]
989enabled = false
990
991# Model Context Protocol (MCP) - Connect external tools and services
992[mcp]
993# Enable Model Context Protocol (may impact startup time if services unavailable)
994enabled = true
995max_concurrent_connections = 5
996request_timeout_seconds = 30
997retry_attempts = 3
998
999# MCP UI configuration
1000[mcp.ui]
1001mode = "compact"
1002max_events = 50
1003show_provider_names = true
1004
1005# MCP renderer profiles for different services
1006[mcp.ui.renderers]
1007sequential-thinking = "sequential-thinking"
1008context7 = "context7"
1009
1010# MCP provider configuration - External services that connect via MCP
1011[[mcp.providers]]
1012name = "time"
1013command = "uvx"
1014args = ["mcp-server-time"]
1015enabled = true
1016max_concurrent_requests = 3
1017[mcp.providers.env]
1018
1019# Agent Client Protocol (ACP) - IDE integration
1020[acp]
1021enabled = true
1022
1023[acp.zed]
1024enabled = true
1025transport = "stdio"
1026# workspace_trust controls ACP trust mode: "tools_policy" (prompts) or "full_auto" (no prompts)
1027workspace_trust = "full_auto"
1028
1029[acp.zed.tools]
1030read_file = true
1031list_files = true
1032
1033# Cross-IDE editor context bridge
1034[ide_context]
1035enabled = true
1036inject_into_prompt = true
1037show_in_tui = true
1038include_selection_text = true
1039provider_mode = "auto"
1040
1041[ide_context.providers.vscode_compatible]
1042enabled = true
1043
1044[ide_context.providers.zed]
1045enabled = true
1046
1047[ide_context.providers.generic]
1048enabled = true"#.to_string()
1049    }
1050
1051    #[cfg(feature = "bootstrap")]
1052    fn default_vtcode_gitignore() -> String {
1053        r#"# Security-focused exclusions
1054.env, .env.local, secrets/, .aws/, .ssh/
1055
1056# Development artifacts
1057target/, build/, dist/, node_modules/, vendor/
1058
1059# Database files
1060*.db, *.sqlite, *.sqlite3
1061
1062# Binary files
1063*.exe, *.dll, *.so, *.dylib, *.bin
1064
1065# IDE files (comprehensive)
1066.vscode/, .idea/, *.swp, *.swo
1067"#
1068        .to_string()
1069    }
1070
1071    #[cfg(feature = "bootstrap")]
1072    fn default_vtcode_readme_template() -> &'static str {
1073        "# VT Code Workspace Files\n\n- Put always-on repository guidance in `AGENTS.md`.\n- Put path-scoped prompt rules in `.vtcode/rules/*.md` using YAML frontmatter.\n- Keep authoring notes and other workspace docs outside `.vtcode/rules/` so they are not loaded into prompt memory.\n"
1074    }
1075
1076    #[cfg(feature = "bootstrap")]
1077    fn default_ast_grep_config_template() -> &'static str {
1078        "ruleDirs:\n  - rules\ntestConfigs:\n  - testDir: rule-tests\n    snapshotDir: __snapshots__\n"
1079    }
1080
1081    #[cfg(feature = "bootstrap")]
1082    fn default_ast_grep_example_rule_template() -> &'static str {
1083        "id: no-console-log\nlanguage: JavaScript\nseverity: error\nmessage: Avoid `console.log` in checked JavaScript files.\nnote: |\n  This starter rule is scoped to `__ast_grep_examples__/` so fresh repositories can\n  validate the scaffold without scanning unrelated project files.\nrule:\n  pattern: console.log($$$ARGS)\nfiles:\n  - __ast_grep_examples__/**/*.js\n"
1084    }
1085
1086    #[cfg(feature = "bootstrap")]
1087    fn default_ast_grep_example_test_template() -> &'static str {
1088        "id: no-console-log\nvalid:\n  - |\n    const logger = {\n      info(message) {\n        return message;\n      },\n    };\ninvalid:\n  - |\n    function greet(name) {\n      console.log(name);\n    }\n"
1089    }
1090
1091    #[cfg(feature = "bootstrap")]
1092    fn default_ast_grep_example_snapshot_template() -> &'static str {
1093        "id: no-console-log\nsnapshots:\n  ? |\n    function greet(name) {\n      console.log(name);\n    }\n  : labels:\n    - source: console.log(name)\n      style: primary\n      start: 25\n      end: 42\n"
1094    }
1095
1096    #[cfg(feature = "bootstrap")]
1097    /// Create sample configuration file
1098    pub fn create_sample_config<P: AsRef<Path>>(output: P) -> Result<()> {
1099        let output = output.as_ref();
1100        let config_content = Self::default_vtcode_toml_template();
1101
1102        fs::write(output, config_content)
1103            .with_context(|| format!("Failed to write config file: {}", output.display()))?;
1104
1105        Ok(())
1106    }
1107}
1108
1109#[cfg(test)]
1110mod tests {
1111    use super::VTCodeConfig;
1112    use tempfile::tempdir;
1113
1114    #[cfg(feature = "bootstrap")]
1115    #[test]
1116    fn bootstrap_project_creates_vtcode_readme() {
1117        let workspace = tempdir().expect("workspace");
1118        let created = VTCodeConfig::bootstrap_project(workspace.path(), false)
1119            .expect("bootstrap project should succeed");
1120
1121        assert!(
1122            created.iter().any(|entry| entry == ".vtcode/README.md"),
1123            "created files: {:?}",
1124            created
1125        );
1126        assert!(workspace.path().join(".vtcode/README.md").exists());
1127    }
1128
1129    #[cfg(feature = "bootstrap")]
1130    #[test]
1131    fn bootstrap_project_creates_ast_grep_scaffold() {
1132        let workspace = tempdir().expect("workspace");
1133        let created = VTCodeConfig::bootstrap_project(workspace.path(), false)
1134            .expect("bootstrap project should succeed");
1135
1136        assert!(created.iter().any(|entry| entry == "sgconfig.yml"));
1137        assert!(
1138            created
1139                .iter()
1140                .any(|entry| entry == "rules/examples/no-console-log.yml")
1141        );
1142        assert!(
1143            created
1144                .iter()
1145                .any(|entry| entry == "rule-tests/examples/no-console-log-test.yml")
1146        );
1147        assert!(
1148            created
1149                .iter()
1150                .any(|entry| entry == "rule-tests/__snapshots__/no-console-log-snapshot.yml")
1151        );
1152
1153        assert!(workspace.path().join("sgconfig.yml").exists());
1154        assert!(
1155            workspace
1156                .path()
1157                .join("rules/examples/no-console-log.yml")
1158                .exists()
1159        );
1160        assert!(
1161            workspace
1162                .path()
1163                .join("rule-tests/examples/no-console-log-test.yml")
1164                .exists()
1165        );
1166        assert!(
1167            workspace
1168                .path()
1169                .join("rule-tests/__snapshots__/no-console-log-snapshot.yml")
1170                .exists()
1171        );
1172    }
1173
1174    #[cfg(feature = "bootstrap")]
1175    #[test]
1176    fn bootstrap_project_preserves_existing_ast_grep_files_without_force() {
1177        let workspace = tempdir().expect("workspace");
1178        let sgconfig_path = workspace.path().join("sgconfig.yml");
1179        let rule_path = workspace.path().join("rules/examples/no-console-log.yml");
1180
1181        std::fs::create_dir_all(workspace.path().join("rules/examples")).expect("create rules dir");
1182        std::fs::write(&sgconfig_path, "ruleDirs:\n  - custom-rules\n").expect("write sgconfig");
1183        std::fs::write(&rule_path, "id: custom-rule\n").expect("write rule");
1184
1185        let created = VTCodeConfig::bootstrap_project(workspace.path(), false)
1186            .expect("bootstrap project should succeed");
1187
1188        assert!(
1189            !created.iter().any(|entry| entry == "sgconfig.yml"),
1190            "created files: {created:?}"
1191        );
1192        assert!(
1193            !created
1194                .iter()
1195                .any(|entry| entry == "rules/examples/no-console-log.yml"),
1196            "created files: {created:?}"
1197        );
1198        assert_eq!(
1199            std::fs::read_to_string(&sgconfig_path).expect("read sgconfig"),
1200            "ruleDirs:\n  - custom-rules\n"
1201        );
1202        assert_eq!(
1203            std::fs::read_to_string(&rule_path).expect("read rule"),
1204            "id: custom-rule\n"
1205        );
1206    }
1207}