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