1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::fs;
4use std::path::Path;
5
6use crate::acp::AgentClientProtocolConfig;
7use crate::context::ContextFeaturesConfig;
8use crate::core::{
9 AgentConfig, AnthropicConfig, AuthConfig, AutomationConfig, CommandsConfig,
10 DotfileProtectionConfig, ModelConfig, OpenAIConfig, PermissionsConfig, PromptCachingConfig,
11 SandboxConfig, SecurityConfig, SkillsConfig, ToolsConfig,
12};
13use crate::debug::DebugConfig;
14use crate::defaults::{self, ConfigDefaultsProvider};
15use crate::hooks::HooksConfig;
16use crate::mcp::McpClientConfig;
17use crate::optimization::OptimizationConfig;
18use crate::output_styles::OutputStyleConfig;
19use crate::root::{ChatConfig, PtyConfig, UiConfig};
20use crate::telemetry::TelemetryConfig;
21use crate::timeouts::TimeoutsConfig;
22
23use crate::loader::syntax_highlighting::SyntaxHighlightingConfig;
24
25#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
27#[derive(Debug, Clone, Deserialize, Serialize, Default)]
28pub struct ProviderConfig {
29 #[serde(default)]
31 pub openai: OpenAIConfig,
32
33 #[serde(default)]
35 pub anthropic: AnthropicConfig,
36}
37
38#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
40#[derive(Debug, Clone, Deserialize, Serialize, Default)]
41pub struct VTCodeConfig {
42 #[serde(default)]
44 pub agent: AgentConfig,
45
46 #[serde(default)]
48 pub auth: AuthConfig,
49
50 #[serde(default)]
52 pub tools: ToolsConfig,
53
54 #[serde(default)]
56 pub commands: CommandsConfig,
57
58 #[serde(default)]
60 pub permissions: PermissionsConfig,
61
62 #[serde(default)]
64 pub security: SecurityConfig,
65
66 #[serde(default)]
68 pub sandbox: SandboxConfig,
69
70 #[serde(default)]
72 pub ui: UiConfig,
73
74 #[serde(default)]
76 pub chat: ChatConfig,
77
78 #[serde(default)]
80 pub pty: PtyConfig,
81
82 #[serde(default)]
84 pub debug: DebugConfig,
85
86 #[serde(default)]
88 pub context: ContextFeaturesConfig,
89
90 #[serde(default)]
92 pub telemetry: TelemetryConfig,
93
94 #[serde(default)]
96 pub optimization: OptimizationConfig,
97
98 #[serde(default)]
100 pub syntax_highlighting: SyntaxHighlightingConfig,
101
102 #[serde(default)]
104 pub timeouts: TimeoutsConfig,
105
106 #[serde(default)]
108 pub automation: AutomationConfig,
109
110 #[serde(default)]
112 pub prompt_cache: PromptCachingConfig,
113
114 #[serde(default)]
116 pub mcp: McpClientConfig,
117
118 #[serde(default)]
120 pub acp: AgentClientProtocolConfig,
121
122 #[serde(default)]
124 pub hooks: HooksConfig,
125
126 #[serde(default)]
128 pub model: ModelConfig,
129
130 #[serde(default)]
132 pub provider: ProviderConfig,
133
134 #[serde(default)]
136 pub skills: SkillsConfig,
137
138 #[serde(default)]
140 pub output_style: OutputStyleConfig,
141
142 #[serde(default)]
144 pub dotfile_protection: DotfileProtectionConfig,
145}
146
147impl VTCodeConfig {
148 pub fn validate(&self) -> Result<()> {
149 self.syntax_highlighting
150 .validate()
151 .context("Invalid syntax_highlighting configuration")?;
152
153 self.context
154 .validate()
155 .context("Invalid context configuration")?;
156
157 self.hooks
158 .validate()
159 .context("Invalid hooks configuration")?;
160
161 self.timeouts
162 .validate()
163 .context("Invalid timeouts configuration")?;
164
165 self.prompt_cache
166 .validate()
167 .context("Invalid prompt_cache configuration")?;
168
169 self.ui
170 .keyboard_protocol
171 .validate()
172 .context("Invalid keyboard_protocol configuration")?;
173
174 self.pty.validate().context("Invalid pty configuration")?;
175
176 Ok(())
177 }
178
179 #[cfg(feature = "bootstrap")]
180 pub fn bootstrap_project<P: AsRef<Path>>(workspace: P, force: bool) -> Result<Vec<String>> {
182 Self::bootstrap_project_with_options(workspace, force, false)
183 }
184
185 #[cfg(feature = "bootstrap")]
186 pub fn bootstrap_project_with_options<P: AsRef<Path>>(
188 workspace: P,
189 force: bool,
190 use_home_dir: bool,
191 ) -> Result<Vec<String>> {
192 let workspace = workspace.as_ref().to_path_buf();
193 defaults::with_config_defaults(|provider| {
194 Self::bootstrap_project_with_provider(&workspace, force, use_home_dir, provider)
195 })
196 }
197
198 #[cfg(feature = "bootstrap")]
199 pub fn bootstrap_project_with_provider<P: AsRef<Path>>(
201 workspace: P,
202 force: bool,
203 use_home_dir: bool,
204 defaults_provider: &dyn ConfigDefaultsProvider,
205 ) -> Result<Vec<String>> {
206 let workspace = workspace.as_ref();
207 let config_file_name = defaults_provider.config_file_name().to_string();
208 let (config_path, gitignore_path) = crate::loader::bootstrap::determine_bootstrap_targets(
209 workspace,
210 use_home_dir,
211 &config_file_name,
212 defaults_provider,
213 )?;
214
215 crate::loader::bootstrap::ensure_parent_dir(&config_path)?;
216 crate::loader::bootstrap::ensure_parent_dir(&gitignore_path)?;
217
218 let mut created_files = Vec::new();
219
220 if !config_path.exists() || force {
221 let config_content = Self::default_vtcode_toml_template();
222
223 fs::write(&config_path, config_content).with_context(|| {
224 format!("Failed to write config file: {}", config_path.display())
225 })?;
226
227 if let Some(file_name) = config_path.file_name().and_then(|name| name.to_str()) {
228 created_files.push(file_name.to_string());
229 }
230 }
231
232 if !gitignore_path.exists() || force {
233 let gitignore_content = Self::default_vtcode_gitignore();
234 fs::write(&gitignore_path, gitignore_content).with_context(|| {
235 format!(
236 "Failed to write gitignore file: {}",
237 gitignore_path.display()
238 )
239 })?;
240
241 if let Some(file_name) = gitignore_path.file_name().and_then(|name| name.to_str()) {
242 created_files.push(file_name.to_string());
243 }
244 }
245
246 Ok(created_files)
247 }
248
249 #[cfg(feature = "bootstrap")]
250 fn default_vtcode_toml_template() -> String {
252 r#"# VT Code Configuration File (Example)
253# Getting-started reference; see docs/config/CONFIGURATION_PRECEDENCE.md for override order.
254# Copy this file to vtcode.toml and customize as needed.
255
256# Core agent behavior; see docs/config/CONFIGURATION_PRECEDENCE.md.
257[agent]
258# Primary LLM provider to use (e.g., "openai", "gemini", "anthropic", "openrouter")
259provider = "openai"
260
261# Environment variable containing the API key for the provider
262api_key_env = "OPENAI_API_KEY"
263
264# Default model to use when no specific model is specified
265default_model = "gpt-5.4"
266
267# Visual theme for the terminal interface
268theme = "ciapre-dark"
269
270# Enable TODO planning helper mode for structured task management
271todo_planning_mode = true
272
273# UI surface to use ("auto", "alternate", "inline")
274ui_surface = "auto"
275
276# Maximum number of conversation turns before rotating context (affects memory usage)
277# Lower values reduce memory footprint but may lose context; higher values preserve context but use more memory
278max_conversation_turns = 150
279
280# Reasoning effort level ("none", "minimal", "low", "medium", "high", "xhigh") - affects model usage and response speed
281reasoning_effort = "none"
282
283# Temperature for main model responses (0.0-1.0)
284temperature = 0.7
285
286# Enable self-review loop to check and improve responses (increases API calls)
287enable_self_review = false
288
289# Maximum number of review passes when self-review is enabled
290max_review_passes = 1
291
292# Enable prompt refinement loop for improved prompt quality (increases processing time)
293refine_prompts_enabled = false
294
295# Maximum passes for prompt refinement when enabled
296refine_prompts_max_passes = 1
297
298# Optional alternate model for refinement (leave empty to use default)
299refine_prompts_model = ""
300
301# Maximum size of project documentation to include in context (in bytes)
302project_doc_max_bytes = 16384
303
304# Maximum size of instruction files to process (in bytes)
305instruction_max_bytes = 16384
306
307# List of additional instruction files to include in context
308instruction_files = []
309
310# Default editing mode on startup: "edit" or "plan"
311# "edit" - Full tool access for file modifications and command execution (default)
312# "plan" - Read-only mode that produces implementation plans without making changes
313# Toggle during session with Shift+Tab or /plan command
314default_editing_mode = "edit"
315
316# Onboarding configuration - Customize the startup experience
317[agent.onboarding]
318# Enable the onboarding welcome message on startup
319enabled = true
320
321# Custom introduction text shown on startup
322intro_text = "Let's get oriented. I preloaded workspace context so we can move fast."
323
324# Include project overview information in welcome
325include_project_overview = true
326
327# Include language summary information in welcome
328include_language_summary = false
329
330# Include key guideline highlights from AGENTS.md
331include_guideline_highlights = true
332
333# Include usage tips in the welcome message
334include_usage_tips_in_welcome = false
335
336# Include recommended actions in the welcome message
337include_recommended_actions_in_welcome = false
338
339# Maximum number of guideline highlights to show
340guideline_highlight_limit = 3
341
342# List of usage tips shown during onboarding
343usage_tips = [
344 "Describe your current coding goal or ask for a quick status overview.",
345 "Reference AGENTS.md guidelines when proposing changes.",
346 "Prefer asking for targeted file reads or diffs before editing.",
347]
348
349# List of recommended actions shown during onboarding
350recommended_actions = [
351 "Review the highlighted guidelines and share the task you want to tackle.",
352 "Ask for a workspace tour if you need more context.",
353]
354
355# Checkpointing configuration for session persistence
356[agent.checkpointing]
357# Enable automatic session checkpointing
358enabled = false
359
360# Maximum number of checkpoints to keep on disk
361max_snapshots = 50
362
363# Maximum age of checkpoints to keep (in days)
364max_age_days = 30
365
366# Tool security configuration
367[tools]
368# Default policy when no specific policy is defined ("allow", "prompt", "deny")
369# "allow" - Execute without confirmation
370# "prompt" - Ask for confirmation
371# "deny" - Block the tool
372default_policy = "prompt"
373
374# Maximum number of tool loops allowed per turn
375# Set to 0 to disable the limit and let other turn safeguards govern termination.
376max_tool_loops = 0
377
378# Maximum number of repeated identical tool calls (prevents stuck loops)
379max_repeated_tool_calls = 2
380
381# Maximum consecutive blocked tool calls before force-breaking the turn
382# Helps prevent high-CPU churn when calls are repeatedly denied/blocked
383max_consecutive_blocked_tool_calls_per_turn = 8
384
385# Maximum sequential spool-chunk reads per turn before nudging targeted extraction/summarization
386max_sequential_spool_chunk_reads = 6
387
388# Specific tool policies - Override default policy for individual tools
389[tools.policies]
390apply_patch = "prompt" # Apply code patches (requires confirmation)
391request_user_input = "allow" # Ask focused user questions when the task requires it
392task_tracker = "prompt" # Create or update explicit task plans
393unified_exec = "prompt" # Run commands; pipe-first by default, set tty=true for PTY/interactive sessions
394unified_file = "allow" # Canonical file read/write/edit/move/copy/delete surface
395unified_search = "allow" # Canonical search/list/intelligence/error surface
396
397# Command security - Define safe and dangerous command patterns
398[commands]
399# Commands that are always allowed without confirmation
400allow_list = [
401 "ls", # List directory contents
402 "pwd", # Print working directory
403 "git status", # Show git status
404 "git diff", # Show git differences
405 "cargo check", # Check Rust code
406 "echo", # Print text
407]
408
409# Commands that are never allowed
410deny_list = [
411 "rm -rf /", # Delete root directory (dangerous)
412 "rm -rf ~", # Delete home directory (dangerous)
413 "shutdown", # Shut down system (dangerous)
414 "reboot", # Reboot system (dangerous)
415 "sudo *", # Any sudo command (dangerous)
416 ":(){ :|:& };:", # Fork bomb (dangerous)
417]
418
419# Command patterns that are allowed (supports glob patterns)
420allow_glob = [
421 "git *", # All git commands
422 "cargo *", # All cargo commands
423 "python -m *", # Python module commands
424]
425
426# Command patterns that are denied (supports glob patterns)
427deny_glob = [
428 "rm *", # All rm commands
429 "sudo *", # All sudo commands
430 "chmod *", # All chmod commands
431 "chown *", # All chown commands
432 "kubectl *", # All kubectl commands (admin access)
433]
434
435# Regular expression patterns for allowed commands (if needed)
436allow_regex = []
437
438# Regular expression patterns for denied commands (if needed)
439deny_regex = []
440
441# Security configuration - Safety settings for automated operations
442[security]
443# Require human confirmation for potentially dangerous actions
444human_in_the_loop = true
445
446# Require explicit write tool usage for claims about file modifications
447require_write_tool_for_claims = true
448
449# Auto-apply patches without prompting (DANGEROUS - disable for safety)
450auto_apply_detected_patches = false
451
452# UI configuration - Terminal and display settings
453[ui]
454# Tool output display mode
455# "compact" - Concise tool output
456# "full" - Detailed tool output
457tool_output_mode = "compact"
458
459# Maximum number of lines to display in tool output (prevents transcript flooding)
460# Lines beyond this limit are truncated to a tail preview
461tool_output_max_lines = 600
462
463# Maximum bytes threshold for spooling tool output to disk
464# Output exceeding this size is written to .vtcode/tool-output/*.log
465tool_output_spool_bytes = 200000
466
467# Optional custom directory for spooled tool output logs
468# If not set, defaults to .vtcode/tool-output/
469# tool_output_spool_dir = "/path/to/custom/spool/dir"
470
471# Allow ANSI escape sequences in tool output (enables colors but may cause layout issues)
472allow_tool_ansi = false
473
474# Number of rows to allocate for inline UI viewport
475inline_viewport_rows = 16
476
477# Show elapsed time divider after each completed turn
478show_turn_timer = false
479
480# Show warning/error/fatal diagnostic lines directly in transcript
481# Effective in debug/development builds only
482show_diagnostics_in_transcript = false
483
484# Show timeline navigation panel
485show_timeline_pane = false
486
487# Runtime notification preferences
488[ui.notifications]
489# Master toggle for terminal/desktop notifications
490enabled = true
491
492# Delivery mode: "terminal", "hybrid", or "desktop"
493delivery_mode = "hybrid"
494
495# Suppress notifications while terminal is focused
496suppress_when_focused = true
497
498# Failure/error notifications
499command_failure = false
500tool_failure = false
501error = true
502
503# Completion notifications
504# Legacy master toggle (fallback for split settings when unset)
505completion = true
506completion_success = false
507completion_failure = true
508
509# Human approval/interaction notifications
510hitl = true
511policy_approval = true
512request = false
513
514# Success notifications for tool call results
515tool_success = false
516
517# Repeated notification suppression
518repeat_window_seconds = 30
519max_identical_in_window = 1
520
521# Status line configuration
522[ui.status_line]
523# Status line mode ("auto", "command", "hidden")
524mode = "auto"
525
526# How often to refresh status line (milliseconds)
527refresh_interval_ms = 2000
528
529# Timeout for command execution in status line (milliseconds)
530command_timeout_ms = 200
531
532# PTY (Pseudo Terminal) configuration - For interactive command execution
533[pty]
534# Enable PTY support for interactive commands
535enabled = true
536
537# Default number of terminal rows for PTY sessions
538default_rows = 24
539
540# Default number of terminal columns for PTY sessions
541default_cols = 80
542
543# Maximum number of concurrent PTY sessions
544max_sessions = 10
545
546# Command timeout in seconds (prevents hanging commands)
547command_timeout_seconds = 300
548
549# Number of recent lines to show in PTY output
550stdout_tail_lines = 20
551
552# Total lines to keep in PTY scrollback buffer
553scrollback_lines = 400
554
555# Optional preferred shell for PTY sessions (falls back to $SHELL when unset)
556# preferred_shell = "/bin/zsh"
557
558# Route shell execution through zsh EXEC_WRAPPER intercept hooks (feature-gated)
559shell_zsh_fork = false
560
561# Absolute path to patched zsh used when shell_zsh_fork is enabled
562# zsh_path = "/usr/local/bin/zsh"
563
564# Context management configuration - Controls conversation memory
565[context]
566# Maximum number of tokens to keep in context (affects model cost and performance)
567# Higher values preserve more context but cost more and may hit token limits
568max_context_tokens = 90000
569
570# Percentage to trim context to when it gets too large
571trim_to_percent = 60
572
573# Number of recent conversation turns to always preserve
574preserve_recent_turns = 6
575
576# Decision ledger configuration - Track important decisions
577[context.ledger]
578# Enable decision tracking and persistence
579enabled = true
580
581# Maximum number of decisions to keep in ledger
582max_entries = 12
583
584# Include ledger summary in model prompts
585include_in_prompt = true
586
587# Preserve ledger during context compression
588preserve_in_compression = true
589
590# AI model routing - Intelligent model selection
591# Telemetry and analytics
592[telemetry]
593# Enable trajectory logging for usage analysis
594trajectory_enabled = true
595
596# Syntax highlighting configuration
597[syntax_highlighting]
598# Enable syntax highlighting for code in tool output
599enabled = true
600
601# Theme for syntax highlighting
602theme = "base16-ocean.dark"
603
604# Cache syntax highlighting themes for performance
605cache_themes = true
606
607# Maximum file size for syntax highlighting (in MB)
608max_file_size_mb = 10
609
610# Programming languages to enable syntax highlighting for
611enabled_languages = [
612 "rust",
613 "python",
614 "javascript",
615 "typescript",
616 "go",
617 "java",
618 "bash",
619 "sh",
620 "shell",
621 "zsh",
622 "markdown",
623 "md",
624]
625
626# Timeout for syntax highlighting operations (milliseconds)
627highlight_timeout_ms = 1000
628
629# Automation features - Full-auto mode settings
630[automation.full_auto]
631# Enable full automation mode (DANGEROUS - requires careful oversight)
632enabled = false
633
634# Maximum number of turns before asking for human input
635max_turns = 30
636
637# Tools allowed in full automation mode
638allowed_tools = [
639 "write_file",
640 "read_file",
641 "list_files",
642 "grep_file",
643]
644
645# Require profile acknowledgment before using full auto
646require_profile_ack = true
647
648# Path to full auto profile configuration
649profile_path = "automation/full_auto_profile.toml"
650
651# Prompt caching - Cache model responses for efficiency
652[prompt_cache]
653# Enable prompt caching (reduces API calls for repeated prompts)
654enabled = false
655
656# Directory for cache storage
657cache_dir = "~/.vtcode/cache/prompts"
658
659# Maximum number of cache entries to keep
660max_entries = 1000
661
662# Maximum age of cache entries (in days)
663max_age_days = 30
664
665# Enable automatic cache cleanup
666enable_auto_cleanup = true
667
668# Minimum quality threshold to keep cache entries
669min_quality_threshold = 0.7
670
671# Keep volatile runtime counters at the end of system prompts to improve provider-side prefix cache reuse
672# (disabled by default; opt in per workspace)
673cache_friendly_prompt_shaping = false
674
675# Prompt cache configuration for OpenAI
676 [prompt_cache.providers.openai]
677 enabled = true
678 min_prefix_tokens = 1024
679 idle_expiration_seconds = 3600
680 surface_metrics = true
681 # Routing key strategy for OpenAI prompt cache locality.
682 # "session" creates one stable key per VT Code conversation.
683 prompt_cache_key_mode = "session"
684 # Optional: server-side prompt cache retention for OpenAI Responses API
685 # Example: "24h" (leave commented out for default behavior)
686 # prompt_cache_retention = "24h"
687
688# Prompt cache configuration for Anthropic
689[prompt_cache.providers.anthropic]
690enabled = true
691default_ttl_seconds = 300
692extended_ttl_seconds = 3600
693max_breakpoints = 4
694cache_system_messages = true
695cache_user_messages = true
696
697# Prompt cache configuration for Gemini
698[prompt_cache.providers.gemini]
699enabled = true
700mode = "implicit"
701min_prefix_tokens = 1024
702explicit_ttl_seconds = 3600
703
704# Prompt cache configuration for OpenRouter
705[prompt_cache.providers.openrouter]
706enabled = true
707propagate_provider_capabilities = true
708report_savings = true
709
710# Prompt cache configuration for Moonshot
711[prompt_cache.providers.moonshot]
712enabled = true
713
714# Prompt cache configuration for DeepSeek
715[prompt_cache.providers.deepseek]
716enabled = true
717surface_metrics = true
718
719# Prompt cache configuration for Z.AI
720[prompt_cache.providers.zai]
721enabled = false
722
723# Model Context Protocol (MCP) - Connect external tools and services
724[mcp]
725# Enable Model Context Protocol (may impact startup time if services unavailable)
726enabled = true
727max_concurrent_connections = 5
728request_timeout_seconds = 30
729retry_attempts = 3
730
731# MCP UI configuration
732[mcp.ui]
733mode = "compact"
734max_events = 50
735show_provider_names = true
736
737# MCP renderer profiles for different services
738[mcp.ui.renderers]
739sequential-thinking = "sequential-thinking"
740context7 = "context7"
741
742# MCP provider configuration - External services that connect via MCP
743[[mcp.providers]]
744name = "time"
745command = "uvx"
746args = ["mcp-server-time"]
747enabled = true
748max_concurrent_requests = 3
749[mcp.providers.env]
750
751# Agent Client Protocol (ACP) - IDE integration
752[acp]
753enabled = true
754
755[acp.zed]
756enabled = true
757transport = "stdio"
758# workspace_trust controls ACP trust mode: "tools_policy" (prompts) or "full_auto" (no prompts)
759workspace_trust = "full_auto"
760
761[acp.zed.tools]
762read_file = true
763list_files = true"#.to_string()
764 }
765
766 #[cfg(feature = "bootstrap")]
767 fn default_vtcode_gitignore() -> String {
768 r#"# Security-focused exclusions
769.env, .env.local, secrets/, .aws/, .ssh/
770
771# Development artifacts
772target/, build/, dist/, node_modules/, vendor/
773
774# Database files
775*.db, *.sqlite, *.sqlite3
776
777# Binary files
778*.exe, *.dll, *.so, *.dylib, *.bin
779
780# IDE files (comprehensive)
781.vscode/, .idea/, *.swp, *.swo
782"#
783 .to_string()
784 }
785
786 #[cfg(feature = "bootstrap")]
787 pub fn create_sample_config<P: AsRef<Path>>(output: P) -> Result<()> {
789 let output = output.as_ref();
790 let config_content = Self::default_vtcode_toml_template();
791
792 fs::write(output, config_content)
793 .with_context(|| format!("Failed to write config file: {}", output.display()))?;
794
795 Ok(())
796 }
797}