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
817# Options: "ghostty_core" (pure Rust, default), "legacy_vt100" (vt100 crate, lowest fidelity)
818emulation_backend = "ghostty_core"
819
820# Optional preferred shell for PTY sessions (falls back to $SHELL when unset)
821# preferred_shell = "/bin/zsh"
822
823# Route shell execution through zsh EXEC_WRAPPER intercept hooks (feature-gated)
824shell_zsh_fork = false
825
826# Absolute path to patched zsh used when shell_zsh_fork is enabled
827# zsh_path = "/usr/local/bin/zsh"
828
829# Context management configuration - Controls conversation memory
830[context]
831# Maximum number of tokens to keep in context (affects model cost and performance)
832# Higher values preserve more context but cost more and may hit token limits
833max_context_tokens = 90000
834
835# Percentage to trim context to when it gets too large
836trim_to_percent = 60
837
838# Number of recent conversation turns to always preserve
839preserve_recent_turns = 6
840
841# Decision ledger configuration - Track important decisions
842[context.ledger]
843# Enable decision tracking and persistence
844enabled = true
845
846# Maximum number of decisions to keep in ledger
847max_entries = 12
848
849# Include ledger summary in model prompts
850include_in_prompt = true
851
852# Preserve ledger during context compression
853preserve_in_compression = true
854
855# AI model routing - Intelligent model selection
856# Telemetry and analytics
857[telemetry]
858# Enable trajectory logging for usage analysis
859trajectory_enabled = true
860
861# Syntax highlighting configuration
862[syntax_highlighting]
863# Enable syntax highlighting for code in tool output
864enabled = true
865
866# Theme for syntax highlighting
867theme = "base16-ocean.dark"
868
869# Cache syntax highlighting themes for performance
870cache_themes = true
871
872# Maximum file size for syntax highlighting (in MB)
873max_file_size_mb = 10
874
875# Programming languages to enable syntax highlighting for
876enabled_languages = [
877    "rust",
878    "python",
879    "javascript",
880    "typescript",
881    "go",
882    "java",
883    "bash",
884    "sh",
885    "shell",
886    "zsh",
887    "markdown",
888    "md",
889]
890
891# Timeout for syntax highlighting operations (milliseconds)
892highlight_timeout_ms = 1000
893
894# Automation features - Full-auto mode settings
895[automation.full_auto]
896# Enable full automation mode (DANGEROUS - requires careful oversight)
897enabled = false
898
899# Maximum number of turns before asking for human input
900max_turns = 30
901
902# Tools allowed in full automation mode
903allowed_tools = [
904    "write_file",
905    "read_file",
906    "list_files",
907    "grep_file",
908]
909
910# Require profile acknowledgment before using full auto
911require_profile_ack = true
912
913# Path to full auto profile configuration
914profile_path = "automation/full_auto_profile.toml"
915
916[automation.scheduled_tasks]
917# Enable /loop, cron tools, and durable `vtcode schedule` jobs
918enabled = false
919
920# Prompt caching - Cache model responses for efficiency
921[prompt_cache]
922# Enable prompt caching (reduces API calls for repeated prompts)
923enabled = true
924
925# Directory for cache storage
926cache_dir = "~/.vtcode/cache/prompts"
927
928# Maximum number of cache entries to keep
929max_entries = 1000
930
931# Maximum age of cache entries (in days)
932max_age_days = 30
933
934# Enable automatic cache cleanup
935enable_auto_cleanup = true
936
937# Minimum quality threshold to keep cache entries
938min_quality_threshold = 0.7
939
940# Keep volatile runtime counters at the end of system prompts to improve provider-side prefix cache reuse
941# (enabled by default; disable only if you need legacy prompt layout)
942cache_friendly_prompt_shaping = true
943
944# Prompt cache configuration for OpenAI
945    [prompt_cache.providers.openai]
946    enabled = true
947    min_prefix_tokens = 1024
948    idle_expiration_seconds = 3600
949    surface_metrics = true
950    # Routing key strategy for OpenAI prompt cache locality.
951    # "session" creates one stable key per VT Code conversation.
952    prompt_cache_key_mode = "session"
953    # Optional: server-side prompt cache retention for OpenAI Responses API
954    # Supported values: "in_memory" or "24h" (leave commented out for default behavior)
955    # prompt_cache_retention = "24h"
956
957# Prompt cache configuration for Anthropic
958[prompt_cache.providers.anthropic]
959enabled = true
960default_ttl_seconds = 300
961extended_ttl_seconds = 3600
962max_breakpoints = 4
963cache_system_messages = true
964cache_user_messages = true
965
966# Prompt cache configuration for Gemini
967[prompt_cache.providers.gemini]
968enabled = true
969mode = "implicit"
970min_prefix_tokens = 1024
971explicit_ttl_seconds = 3600
972
973# Prompt cache configuration for OpenRouter
974[prompt_cache.providers.openrouter]
975enabled = true
976propagate_provider_capabilities = true
977report_savings = true
978
979# Prompt cache configuration for Moonshot
980[prompt_cache.providers.moonshot]
981enabled = true
982
983# Prompt cache configuration for DeepSeek
984[prompt_cache.providers.deepseek]
985enabled = true
986surface_metrics = true
987
988# Prompt cache configuration for Z.AI
989[prompt_cache.providers.zai]
990enabled = false
991
992# Model Context Protocol (MCP) - Connect external tools and services
993[mcp]
994# Enable Model Context Protocol (may impact startup time if services unavailable)
995enabled = true
996max_concurrent_connections = 5
997request_timeout_seconds = 30
998retry_attempts = 3
999
1000# MCP UI configuration
1001[mcp.ui]
1002mode = "compact"
1003max_events = 50
1004show_provider_names = true
1005
1006# MCP renderer profiles for different services
1007[mcp.ui.renderers]
1008sequential-thinking = "sequential-thinking"
1009context7 = "context7"
1010
1011# MCP provider configuration - External services that connect via MCP
1012[[mcp.providers]]
1013name = "time"
1014command = "uvx"
1015args = ["mcp-server-time"]
1016enabled = true
1017max_concurrent_requests = 3
1018[mcp.providers.env]
1019
1020# Agent Client Protocol (ACP) - IDE integration
1021[acp]
1022enabled = true
1023
1024[acp.zed]
1025enabled = true
1026transport = "stdio"
1027# workspace_trust controls ACP trust mode: "tools_policy" (prompts) or "full_auto" (no prompts)
1028workspace_trust = "full_auto"
1029
1030[acp.zed.tools]
1031read_file = true
1032list_files = true
1033
1034# Cross-IDE editor context bridge
1035[ide_context]
1036enabled = true
1037inject_into_prompt = true
1038show_in_tui = true
1039include_selection_text = true
1040provider_mode = "auto"
1041
1042[ide_context.providers.vscode_compatible]
1043enabled = true
1044
1045[ide_context.providers.zed]
1046enabled = true
1047
1048[ide_context.providers.generic]
1049enabled = true"#.to_string()
1050    }
1051
1052    #[cfg(feature = "bootstrap")]
1053    fn default_vtcode_gitignore() -> String {
1054        r#"# Security-focused exclusions
1055.env, .env.local, secrets/, .aws/, .ssh/
1056
1057# Development artifacts
1058target/, build/, dist/, node_modules/, vendor/
1059
1060# Database files
1061*.db, *.sqlite, *.sqlite3
1062
1063# Binary files
1064*.exe, *.dll, *.so, *.dylib, *.bin
1065
1066# IDE files (comprehensive)
1067.vscode/, .idea/, *.swp, *.swo
1068"#
1069        .to_string()
1070    }
1071
1072    #[cfg(feature = "bootstrap")]
1073    fn default_vtcode_readme_template() -> &'static str {
1074        "# 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"
1075    }
1076
1077    #[cfg(feature = "bootstrap")]
1078    fn default_ast_grep_config_template() -> &'static str {
1079        "ruleDirs:\n  - rules\ntestConfigs:\n  - testDir: rule-tests\n    snapshotDir: __snapshots__\n"
1080    }
1081
1082    #[cfg(feature = "bootstrap")]
1083    fn default_ast_grep_example_rule_template() -> &'static str {
1084        "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"
1085    }
1086
1087    #[cfg(feature = "bootstrap")]
1088    fn default_ast_grep_example_test_template() -> &'static str {
1089        "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"
1090    }
1091
1092    #[cfg(feature = "bootstrap")]
1093    fn default_ast_grep_example_snapshot_template() -> &'static str {
1094        "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"
1095    }
1096
1097    #[cfg(feature = "bootstrap")]
1098    /// Create sample configuration file
1099    pub fn create_sample_config<P: AsRef<Path>>(output: P) -> Result<()> {
1100        let output = output.as_ref();
1101        let config_content = Self::default_vtcode_toml_template();
1102
1103        fs::write(output, config_content)
1104            .with_context(|| format!("Failed to write config file: {}", output.display()))?;
1105
1106        Ok(())
1107    }
1108}
1109
1110#[cfg(test)]
1111mod tests {
1112    use super::VTCodeConfig;
1113    use tempfile::tempdir;
1114
1115    #[cfg(feature = "bootstrap")]
1116    #[test]
1117    fn bootstrap_project_creates_vtcode_readme() {
1118        let workspace = tempdir().expect("workspace");
1119        let created = VTCodeConfig::bootstrap_project(workspace.path(), false)
1120            .expect("bootstrap project should succeed");
1121
1122        assert!(
1123            created.iter().any(|entry| entry == ".vtcode/README.md"),
1124            "created files: {:?}",
1125            created
1126        );
1127        assert!(workspace.path().join(".vtcode/README.md").exists());
1128    }
1129
1130    #[cfg(feature = "bootstrap")]
1131    #[test]
1132    fn bootstrap_project_creates_ast_grep_scaffold() {
1133        let workspace = tempdir().expect("workspace");
1134        let created = VTCodeConfig::bootstrap_project(workspace.path(), false)
1135            .expect("bootstrap project should succeed");
1136
1137        assert!(created.iter().any(|entry| entry == "sgconfig.yml"));
1138        assert!(
1139            created
1140                .iter()
1141                .any(|entry| entry == "rules/examples/no-console-log.yml")
1142        );
1143        assert!(
1144            created
1145                .iter()
1146                .any(|entry| entry == "rule-tests/examples/no-console-log-test.yml")
1147        );
1148        assert!(
1149            created
1150                .iter()
1151                .any(|entry| entry == "rule-tests/__snapshots__/no-console-log-snapshot.yml")
1152        );
1153
1154        assert!(workspace.path().join("sgconfig.yml").exists());
1155        assert!(
1156            workspace
1157                .path()
1158                .join("rules/examples/no-console-log.yml")
1159                .exists()
1160        );
1161        assert!(
1162            workspace
1163                .path()
1164                .join("rule-tests/examples/no-console-log-test.yml")
1165                .exists()
1166        );
1167        assert!(
1168            workspace
1169                .path()
1170                .join("rule-tests/__snapshots__/no-console-log-snapshot.yml")
1171                .exists()
1172        );
1173    }
1174
1175    #[cfg(feature = "bootstrap")]
1176    #[test]
1177    fn bootstrap_project_preserves_existing_ast_grep_files_without_force() {
1178        let workspace = tempdir().expect("workspace");
1179        let sgconfig_path = workspace.path().join("sgconfig.yml");
1180        let rule_path = workspace.path().join("rules/examples/no-console-log.yml");
1181
1182        std::fs::create_dir_all(workspace.path().join("rules/examples")).expect("create rules dir");
1183        std::fs::write(&sgconfig_path, "ruleDirs:\n  - custom-rules\n").expect("write sgconfig");
1184        std::fs::write(&rule_path, "id: custom-rule\n").expect("write rule");
1185
1186        let created = VTCodeConfig::bootstrap_project(workspace.path(), false)
1187            .expect("bootstrap project should succeed");
1188
1189        assert!(
1190            !created.iter().any(|entry| entry == "sgconfig.yml"),
1191            "created files: {created:?}"
1192        );
1193        assert!(
1194            !created
1195                .iter()
1196                .any(|entry| entry == "rules/examples/no-console-log.yml"),
1197            "created files: {created:?}"
1198        );
1199        assert_eq!(
1200            std::fs::read_to_string(&sgconfig_path).expect("read sgconfig"),
1201            "ruleDirs:\n  - custom-rules\n"
1202        );
1203        assert_eq!(
1204            std::fs::read_to_string(&rule_path).expect("read rule"),
1205            "id: custom-rule\n"
1206        );
1207    }
1208}