Skip to main content

vtcode_config/types/
mod.rs

1//! Common types and interfaces used throughout the application
2
3use crate::core::PromptCachingConfig;
4use serde::{Deserialize, Deserializer, Serialize};
5use std::collections::BTreeMap;
6use std::env;
7use std::fmt;
8use std::path::PathBuf;
9
10// Re-export from vtcode-commons so downstream code can use `vtcode_config::types::ReasoningEffortLevel`.
11pub use vtcode_commons::reasoning::ReasoningEffortLevel;
12
13/// System prompt mode (inspired by pi-coding-agent philosophy)
14/// Controls verbosity and complexity of system prompts sent to models
15#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
17#[serde(rename_all = "lowercase")]
18#[derive(Default)]
19pub enum SystemPromptMode {
20    /// Minimal prompt (~500 tokens base) - Pi-inspired, modern models need less guidance
21    /// Best for: Power users, token-constrained contexts, fast responses
22    #[default]
23    Minimal,
24    /// Lightweight prompt (~750 tokens base) - Essential guidance only
25    /// Best for: Resource-constrained operations, simple tasks
26    Lightweight,
27    /// Default prompt (~900 tokens base) - Full guidance with all features
28    /// Best for: General usage, comprehensive error handling
29    Default,
30    /// Specialized prompt (~900 tokens base) - Complex refactoring and analysis
31    /// Best for: Multi-file changes, sophisticated code analysis
32    Specialized,
33}
34
35impl SystemPromptMode {
36    /// Return the textual representation for configuration
37    fn as_str(self) -> &'static str {
38        match self {
39            Self::Minimal => "minimal",
40            Self::Lightweight => "lightweight",
41            Self::Default => "default",
42            Self::Specialized => "specialized",
43        }
44    }
45
46    /// Parse system prompt mode from user configuration
47    pub fn parse(value: &str) -> Option<Self> {
48        let normalized = value.trim();
49        if normalized.eq_ignore_ascii_case("minimal") {
50            Some(Self::Minimal)
51        } else if normalized.eq_ignore_ascii_case("lightweight") {
52            Some(Self::Lightweight)
53        } else if normalized.eq_ignore_ascii_case("default") {
54            Some(Self::Default)
55        } else if normalized.eq_ignore_ascii_case("specialized") {
56            Some(Self::Specialized)
57        } else {
58            None
59        }
60    }
61
62    /// Allowed configuration values for validation
63    pub fn allowed_values() -> &'static [&'static str] {
64        &["minimal", "lightweight", "default", "specialized"]
65    }
66}
67
68impl fmt::Display for SystemPromptMode {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.write_str(self.as_str())
71    }
72}
73
74impl<'de> Deserialize<'de> for SystemPromptMode {
75    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
76    where
77        D: Deserializer<'de>,
78    {
79        let raw = String::deserialize(deserializer)?;
80        if let Some(parsed) = Self::parse(&raw) {
81            Ok(parsed)
82        } else {
83            Ok(Self::default())
84        }
85    }
86}
87
88/// Tool documentation mode (inspired by pi-coding-agent progressive disclosure)
89/// Controls how much tool documentation is loaded upfront vs on-demand
90#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
92#[serde(rename_all = "lowercase")]
93#[derive(Default)]
94pub enum ToolDocumentationMode {
95    /// First sentence of each tool description (at most 64 chars) and no
96    /// parameter descriptions - Pi-style, power users
97    /// Best for: Maximum efficiency, experienced users, token-constrained contexts
98    Minimal,
99    /// Complete tool and parameter descriptions; only unusually long tails are
100    /// trimmed at a sentence boundary. Schema size depends on the exposed
101    /// catalog; `emitted_model_tool_schema_fits_within_first_request_budget`
102    /// guards the representative interactive catalog.
103    /// Best for: General usage (recommended)
104    #[default]
105    Progressive,
106    /// Every tool and parameter description sent unmodified
107    /// Best for: Debugging tool definitions, comprehensive documentation
108    Full,
109}
110
111impl ToolDocumentationMode {
112    /// Return the textual representation for configuration
113    fn as_str(self) -> &'static str {
114        match self {
115            Self::Minimal => "minimal",
116            Self::Progressive => "progressive",
117            Self::Full => "full",
118        }
119    }
120
121    /// Parse tool documentation mode from user configuration
122    fn parse(value: &str) -> Option<Self> {
123        let normalized = value.trim();
124        if normalized.eq_ignore_ascii_case("minimal") {
125            Some(Self::Minimal)
126        } else if normalized.eq_ignore_ascii_case("progressive") {
127            Some(Self::Progressive)
128        } else if normalized.eq_ignore_ascii_case("full") {
129            Some(Self::Full)
130        } else {
131            None
132        }
133    }
134
135    /// Allowed configuration values for validation
136    pub fn allowed_values() -> &'static [&'static str] {
137        &["minimal", "progressive", "full"]
138    }
139}
140
141impl fmt::Display for ToolDocumentationMode {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.write_str(self.as_str())
144    }
145}
146
147impl<'de> Deserialize<'de> for ToolDocumentationMode {
148    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
149    where
150        D: Deserializer<'de>,
151    {
152        let raw = String::deserialize(deserializer)?;
153        if let Some(parsed) = Self::parse(&raw) {
154            Ok(parsed)
155        } else {
156            Ok(Self::default())
157        }
158    }
159}
160
161/// Configured shell syntax profile used for model-facing command examples.
162///
163/// This is prompt guidance only. Command approval, sandboxing, and allow-list
164/// policy are enforced elsewhere in the runtime.
165#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
167#[serde(rename_all = "snake_case")]
168#[derive(Default)]
169pub enum ShellPromptProfile {
170    /// Detect from the current platform. Unix-like shells are used for Linux,
171    /// macOS, and WSL. Native Windows uses PowerShell.
172    #[default]
173    Auto,
174    /// Use Unix-like shell syntax in prompt examples.
175    UnixLike,
176    /// Use native PowerShell syntax in prompt examples.
177    ///
178    /// The canonical wire value is `powershell` (matching `Self::as_str`,
179    /// [`Self::allowed_values`], and the docs); `snake_case` would otherwise
180    /// render it as the drifting `power_shell`.
181    #[serde(rename = "powershell")]
182    PowerShell,
183}
184
185impl ShellPromptProfile {
186    /// Return the textual representation for configuration.
187    fn as_str(self) -> &'static str {
188        match self {
189            Self::Auto => "auto",
190            Self::UnixLike => "unix_like",
191            Self::PowerShell => "powershell",
192        }
193    }
194
195    /// Parse a shell prompt profile from user configuration.
196    fn parse(value: &str) -> Option<Self> {
197        let normalized = value.trim();
198        if normalized.eq_ignore_ascii_case("auto") {
199            Some(Self::Auto)
200        } else if normalized.eq_ignore_ascii_case("unix_like")
201            || normalized.eq_ignore_ascii_case("unix-like")
202            || normalized.eq_ignore_ascii_case("unix")
203            || normalized.eq_ignore_ascii_case("posix")
204        {
205            Some(Self::UnixLike)
206        } else if normalized.eq_ignore_ascii_case("powershell")
207            || normalized.eq_ignore_ascii_case("power_shell")
208            || normalized.eq_ignore_ascii_case("windows")
209        {
210            Some(Self::PowerShell)
211        } else {
212            None
213        }
214    }
215
216    /// Allowed configuration values for validation.
217    pub fn allowed_values() -> &'static [&'static str] {
218        &["auto", "unix_like", "powershell"]
219    }
220
221    /// Resolve this configured value against the current runtime platform.
222    pub fn resolve_for_current_platform(self) -> ResolvedShellPromptProfile {
223        self.resolve_for_platform(ShellProfilePlatform::current())
224    }
225
226    /// Resolve this configured value against an explicit platform.
227    fn resolve_for_platform(self, platform: ShellProfilePlatform) -> ResolvedShellPromptProfile {
228        match self {
229            Self::Auto => match platform {
230                ShellProfilePlatform::NativeWindows => ResolvedShellPromptProfile::PowerShell,
231                ShellProfilePlatform::UnixLike | ShellProfilePlatform::Wsl => ResolvedShellPromptProfile::UnixLike,
232            },
233            Self::UnixLike => ResolvedShellPromptProfile::UnixLike,
234            Self::PowerShell => ResolvedShellPromptProfile::PowerShell,
235        }
236    }
237}
238
239impl fmt::Display for ShellPromptProfile {
240    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241        f.write_str(self.as_str())
242    }
243}
244
245impl<'de> Deserialize<'de> for ShellPromptProfile {
246    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
247    where
248        D: Deserializer<'de>,
249    {
250        let raw = String::deserialize(deserializer)?;
251        if let Some(parsed) = Self::parse(&raw) {
252            Ok(parsed)
253        } else {
254            Ok(Self::default())
255        }
256    }
257}
258
259/// Platform category used to resolve [`ShellPromptProfile::Auto`].
260#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
262#[serde(rename_all = "snake_case")]
263pub enum ShellProfilePlatform {
264    UnixLike,
265    Wsl,
266    NativeWindows,
267}
268
269impl ShellProfilePlatform {
270    fn current() -> Self {
271        if cfg!(windows) {
272            Self::NativeWindows
273        } else if is_wsl_environment() {
274            Self::Wsl
275        } else {
276            Self::UnixLike
277        }
278    }
279}
280
281/// Prompt profile after automatic platform resolution.
282#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
283#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
284#[serde(rename_all = "snake_case")]
285pub enum ResolvedShellPromptProfile {
286    UnixLike,
287    /// Canonical wire value is `powershell` (matching `Self::as_str`); the
288    /// derived `snake_case` form would otherwise be the drifting `power_shell`.
289    #[serde(rename = "powershell")]
290    PowerShell,
291}
292
293impl ResolvedShellPromptProfile {
294    fn as_str(self) -> &'static str {
295        match self {
296            Self::UnixLike => "unix_like",
297            Self::PowerShell => "powershell",
298        }
299    }
300}
301
302impl fmt::Display for ResolvedShellPromptProfile {
303    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304        f.write_str(self.as_str())
305    }
306}
307
308fn is_wsl_environment() -> bool {
309    if env::var_os("WSL_DISTRO_NAME").is_some() || env::var_os("WSL_INTEROP").is_some() {
310        return true;
311    }
312
313    for path in ["/proc/sys/kernel/osrelease", "/proc/version"] {
314        if let Ok(contents) = std::fs::read_to_string(path)
315            && contents.to_ascii_lowercase().contains("microsoft")
316        {
317            return true;
318        }
319    }
320
321    false
322}
323
324/// Verbosity level for model output (GPT-5.4-family and compatible models)
325#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
327#[serde(rename_all = "lowercase")]
328#[derive(Default)]
329pub enum VerbosityLevel {
330    Low,
331    #[default]
332    Medium,
333    High,
334}
335
336impl VerbosityLevel {
337    /// Return the textual representation expected by downstream APIs
338    pub fn as_str(self) -> &'static str {
339        match self {
340            Self::Low => "low",
341            Self::Medium => "medium",
342            Self::High => "high",
343        }
344    }
345
346    /// Attempt to parse a verbosity level from user configuration input
347    pub fn parse(value: &str) -> Option<Self> {
348        let normalized = value.trim();
349        if normalized.eq_ignore_ascii_case("low") {
350            Some(Self::Low)
351        } else if normalized.eq_ignore_ascii_case("medium") {
352            Some(Self::Medium)
353        } else if normalized.eq_ignore_ascii_case("high") {
354            Some(Self::High)
355        } else {
356            None
357        }
358    }
359
360    /// Enumerate the allowed configuration values
361    pub fn allowed_values() -> &'static [&'static str] {
362        &["low", "medium", "high"]
363    }
364}
365
366impl fmt::Display for VerbosityLevel {
367    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368        f.write_str(self.as_str())
369    }
370}
371
372impl<'de> Deserialize<'de> for VerbosityLevel {
373    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
374    where
375        D: Deserializer<'de>,
376    {
377        let raw = String::deserialize(deserializer)?;
378        if let Some(parsed) = Self::parse(&raw) {
379            Ok(parsed)
380        } else {
381            Ok(Self::default())
382        }
383    }
384}
385
386/// Preferred rendering surface for the interactive chat UI
387#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
388#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
389#[serde(rename_all = "lowercase")]
390#[derive(Default)]
391pub enum UiSurfacePreference {
392    Auto,
393    Alternate,
394    #[default]
395    Inline,
396}
397
398impl UiSurfacePreference {
399    /// String representation used in configuration and logging
400    fn as_str(self) -> &'static str {
401        match self {
402            Self::Auto => "auto",
403            Self::Alternate => "alternate",
404            Self::Inline => "inline",
405        }
406    }
407
408    /// Parse a surface preference from configuration input
409    fn parse(value: &str) -> Option<Self> {
410        let normalized = value.trim();
411        if normalized.eq_ignore_ascii_case("auto") {
412            Some(Self::Auto)
413        } else if normalized.eq_ignore_ascii_case("alternate") || normalized.eq_ignore_ascii_case("alt") {
414            Some(Self::Alternate)
415        } else if normalized.eq_ignore_ascii_case("inline") {
416            Some(Self::Inline)
417        } else {
418            None
419        }
420    }
421
422    /// Enumerate the accepted configuration values for validation messaging
423    pub fn allowed_values() -> &'static [&'static str] {
424        &["auto", "alternate", "inline"]
425    }
426}
427
428impl fmt::Display for UiSurfacePreference {
429    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430        f.write_str(self.as_str())
431    }
432}
433
434impl<'de> Deserialize<'de> for UiSurfacePreference {
435    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
436    where
437        D: Deserializer<'de>,
438    {
439        let raw = String::deserialize(deserializer)?;
440        if let Some(parsed) = Self::parse(&raw) {
441            Ok(parsed)
442        } else {
443            Ok(Self::default())
444        }
445    }
446}
447
448/// Source describing how the active model was selected
449#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
450pub enum ModelSelectionSource {
451    /// Model provided by workspace configuration
452    #[default]
453    WorkspaceConfig,
454    /// Model provided by CLI override
455    CliOverride,
456}
457
458/// Configuration for the agent
459#[derive(Debug, Clone)]
460pub struct AgentConfig {
461    pub model: String,
462    pub api_key: String,
463    pub provider: String,
464    pub openai_chatgpt_auth: Option<crate::auth::OpenAIChatGptAuthHandle>,
465    pub api_key_env: String,
466    pub workspace: PathBuf,
467    pub verbose: bool,
468    pub quiet: bool,
469    pub theme: String,
470    pub reasoning_effort: ReasoningEffortLevel,
471    pub ui_surface: UiSurfacePreference,
472    pub prompt_cache: PromptCachingConfig,
473    pub model_source: ModelSelectionSource,
474    pub custom_api_keys: BTreeMap<String, String>,
475    pub checkpointing_enabled: bool,
476    pub checkpointing_storage_dir: Option<PathBuf>,
477    pub checkpointing_max_snapshots: usize,
478    pub checkpointing_max_age_days: Option<u64>,
479    pub max_conversation_turns: usize,
480    pub model_behavior: Option<crate::core::ModelConfig>,
481}
482
483/// Workshop agent capability levels
484#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
485pub enum CapabilityLevel {
486    /// Basic chat only
487    Basic,
488    /// Can read files
489    FileReading,
490    /// Can read files and list directories
491    FileListing,
492    /// Can read files, list directories, and run bash commands
493    Bash,
494    /// Can read files, list directories, run bash commands, and edit files
495    Editing,
496    /// Full capabilities including code search
497    CodeSearch,
498}
499
500/// Session information
501#[derive(Debug, Clone, Serialize, Deserialize)]
502pub struct SessionInfo {
503    pub session_id: String,
504    pub start_time: u64,
505    pub total_turns: usize,
506    pub total_decisions: usize,
507    pub error_count: usize,
508}
509
510/// Error information for tracking
511#[derive(Debug, Clone, Serialize, Deserialize)]
512pub struct ErrorInfo {
513    error_type: String,
514    message: String,
515    turn_number: usize,
516    recoverable: bool,
517    timestamp: u64,
518}
519
520/// Performance metrics
521#[derive(Debug, Clone, Serialize, Deserialize)]
522pub struct PerformanceMetrics {
523    pub session_duration_seconds: u64,
524    pub total_api_calls: usize,
525    pub total_tokens_used: Option<usize>,
526    pub average_response_time_ms: f64,
527    pub tool_execution_count: usize,
528    pub error_count: usize,
529    pub recovery_success_rate: f64,
530}
531
532/// Analysis depth for workspace analysis
533#[derive(Debug, Clone, Serialize, Deserialize)]
534pub enum AnalysisDepth {
535    Basic,
536    Standard,
537    Deep,
538}
539
540/// Output format for commands
541#[derive(Debug, Clone, Serialize, Deserialize)]
542pub enum OutputFormat {
543    Text,
544    Json,
545    Html,
546}
547
548#[cfg(test)]
549mod tests {
550    use super::*;
551
552    #[test]
553    fn test_reasoning_effort_parse_and_allowed_values_include_max() {
554        assert_eq!(ReasoningEffortLevel::parse("max"), Some(ReasoningEffortLevel::Max));
555        assert_eq!(ReasoningEffortLevel::Max.as_str(), "max");
556        assert!(ReasoningEffortLevel::allowed_values().contains(&"max"));
557    }
558
559    #[test]
560    fn shell_prompt_profile_parses_aliases() {
561        assert_eq!(ShellPromptProfile::parse("auto"), Some(ShellPromptProfile::Auto));
562        assert_eq!(ShellPromptProfile::parse("unix-like"), Some(ShellPromptProfile::UnixLike));
563        assert_eq!(ShellPromptProfile::parse("posix"), Some(ShellPromptProfile::UnixLike));
564        assert_eq!(ShellPromptProfile::parse("PowerShell"), Some(ShellPromptProfile::PowerShell));
565        assert_eq!(ShellPromptProfile::parse("unknown"), None);
566    }
567
568    #[test]
569    fn ui_surface_defaults_to_inline() {
570        assert_eq!(UiSurfacePreference::default(), UiSurfacePreference::Inline);
571    }
572
573    #[test]
574    fn auto_shell_prompt_profile_selects_platform_defaults() {
575        let profile = ShellPromptProfile::Auto;
576
577        assert_eq!(profile.resolve_for_platform(ShellProfilePlatform::UnixLike), ResolvedShellPromptProfile::UnixLike);
578        assert_eq!(profile.resolve_for_platform(ShellProfilePlatform::Wsl), ResolvedShellPromptProfile::UnixLike);
579        assert_eq!(
580            profile.resolve_for_platform(ShellProfilePlatform::NativeWindows),
581            ResolvedShellPromptProfile::PowerShell
582        );
583    }
584
585    #[test]
586    fn explicit_shell_prompt_profiles_override_platform_defaults() {
587        assert_eq!(
588            ShellPromptProfile::UnixLike.resolve_for_platform(ShellProfilePlatform::NativeWindows),
589            ResolvedShellPromptProfile::UnixLike
590        );
591        assert_eq!(
592            ShellPromptProfile::PowerShell.resolve_for_platform(ShellProfilePlatform::Wsl),
593            ResolvedShellPromptProfile::PowerShell
594        );
595    }
596
597    /// Every `as_str()`/`parse()`/serde triangle in this module stays in
598    /// lockstep; see [`crate::test_support::assert_string_enum_lockstep`].
599    #[test]
600    fn string_enums_keep_as_str_and_serde_in_lockstep() {
601        use crate::test_support::assert_string_enum_lockstep;
602
603        assert_string_enum_lockstep!(
604            SystemPromptMode,
605            [
606                SystemPromptMode::Minimal,
607                SystemPromptMode::Lightweight,
608                SystemPromptMode::Default,
609                SystemPromptMode::Specialized,
610            ]
611        );
612        assert_string_enum_lockstep!(
613            ToolDocumentationMode,
614            [
615                ToolDocumentationMode::Minimal,
616                ToolDocumentationMode::Progressive,
617                ToolDocumentationMode::Full,
618            ]
619        );
620        assert_string_enum_lockstep!(
621            ShellPromptProfile,
622            [
623                ShellPromptProfile::Auto,
624                ShellPromptProfile::UnixLike,
625                ShellPromptProfile::PowerShell,
626            ]
627        );
628        assert_string_enum_lockstep!(
629            VerbosityLevel,
630            [VerbosityLevel::Low, VerbosityLevel::Medium, VerbosityLevel::High]
631        );
632        assert_string_enum_lockstep!(
633            UiSurfacePreference,
634            [
635                UiSurfacePreference::Auto,
636                UiSurfacePreference::Alternate,
637                UiSurfacePreference::Inline,
638            ]
639        );
640
641        // The shared `allowed_values()` lists are the model-facing validation
642        // surface; pin them against `parse()` so a rename cannot silently drop
643        // a value from the accepted set.
644        for value in SystemPromptMode::allowed_values() {
645            assert!(SystemPromptMode::parse(value).is_some(), "allowed value {value:?} must parse");
646        }
647        for value in ToolDocumentationMode::allowed_values() {
648            assert!(ToolDocumentationMode::parse(value).is_some(), "allowed value {value:?} must parse");
649        }
650        for value in ShellPromptProfile::allowed_values() {
651            assert!(ShellPromptProfile::parse(value).is_some(), "allowed value {value:?} must parse");
652        }
653        for value in VerbosityLevel::allowed_values() {
654            assert!(VerbosityLevel::parse(value).is_some(), "allowed value {value:?} must parse");
655        }
656        for value in UiSurfacePreference::allowed_values() {
657            assert!(UiSurfacePreference::parse(value).is_some(), "allowed value {value:?} must parse");
658        }
659    }
660
661    /// `ResolvedShellPromptProfile` has no `parse()`, so it is not covered by
662    /// [`crate::test_support::assert_string_enum_lockstep`]. It still exposes the
663    /// same value through `Display`/`as_str()` and the derived `snake_case`
664    /// serde form — and it carries a schema derive — so pin those together.
665    #[test]
666    fn resolved_shell_prompt_profile_matches_display_and_serde() {
667        for profile in [
668            ResolvedShellPromptProfile::UnixLike,
669            ResolvedShellPromptProfile::PowerShell,
670        ] {
671            let expected = profile.to_string();
672            assert_eq!(
673                serde_json::to_value(profile).expect("resolved profile serializes"),
674                serde_json::json!(expected),
675                "serde wire form drifted from Display for {profile:?}"
676            );
677        }
678    }
679}