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