Skip to main content

vtcode_config/core/prompt_cache/
mod.rs

1use crate::constants::prompt_cache;
2use crate::env_helpers::default_true;
3use serde::{Deserialize, Serialize};
4use std::path::{Path, PathBuf};
5use vtcode_commons::VtCodePaths;
6
7/// Known native models supporting explicit breakpoints and configurable cache lifetimes.
8/// Reject migration-only aliases: parsing an older model as a newer replacement
9/// does not establish support for the older model's wire request.
10#[must_use]
11pub fn supports_openai_explicit_prompt_cache(model: &str) -> bool {
12    use crate::models::ModelId;
13    let Ok(model_id) = model.parse::<ModelId>() else {
14        return false;
15    };
16    (model_id.as_str() == model || model == crate::constants::models::openai::GPT_5_6)
17        && matches!(
18            model_id,
19            ModelId::GPT56Sol
20                | ModelId::GPT56Terra
21                | ModelId::GPT56Luna
22                | ModelId::GPT62Astra
23                | ModelId::GPT62Sol
24                | ModelId::GPT6Astra
25                | ModelId::GPT6Sol
26                | ModelId::GPT61Sol
27                | ModelId::GPT61Terra
28                | ModelId::GPT6Luna
29        )
30}
31
32/// Requested minimum lifetime for Responses prompt-cache writes.
33#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
34#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
35pub enum PromptCacheTtl {
36    #[default]
37    #[serde(rename = "30m")]
38    M30,
39    #[serde(rename = "12h")]
40    H12,
41}
42
43impl PromptCacheTtl {
44    pub const fn as_str(self) -> &'static str {
45        match self {
46            Self::M30 => "30m",
47            Self::H12 => "12h",
48        }
49    }
50
51    pub const fn seconds(self) -> u64 {
52        match self {
53            Self::M30 => 1_800,
54            Self::H12 => 43_200,
55        }
56    }
57}
58
59/// Resolve explicit configuration, then catalog policy, then the default lifetime.
60pub fn resolved_openai_prompt_cache_ttl(configured: Option<PromptCacheTtl>, model: &str) -> PromptCacheTtl {
61    configured
62        .or_else(|| {
63            crate::models::model_catalog_entry("openai", model)
64                .and_then(|entry| entry.prompt_cache_ttl)
65                .and_then(|ttl| match ttl {
66                    "30m" => Some(PromptCacheTtl::M30),
67                    "12h" => Some(PromptCacheTtl::H12),
68                    _ => None,
69                })
70        })
71        .unwrap_or_default()
72}
73
74/// Global prompt caching configuration loaded from vtcode.toml
75#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
76#[derive(Debug, Clone, Deserialize, Serialize)]
77pub struct PromptCachingConfig {
78    /// Enable prompt caching features globally
79    #[serde(default = "default_enabled")]
80    pub enabled: bool,
81
82    /// Base directory for local prompt cache storage (supports `~` expansion)
83    #[serde(default = "default_cache_dir")]
84    pub cache_dir: String,
85
86    /// Maximum number of cached prompt entries to retain on disk
87    #[serde(default = "default_max_entries")]
88    pub max_entries: usize,
89
90    /// Maximum age (in days) before cached entries are purged
91    #[serde(default = "default_max_age_days")]
92    pub max_age_days: u64,
93
94    /// Automatically evict stale entries on startup/shutdown
95    #[serde(default = "default_auto_cleanup")]
96    pub enable_auto_cleanup: bool,
97
98    /// Minimum quality score required before persisting an entry
99    #[serde(default = "default_min_quality_threshold")]
100    pub min_quality_threshold: f64,
101
102    /// Enable prompt-shaping optimizations that improve provider-side cache locality.
103    /// When enabled, VT Code keeps volatile runtime context at the end of prompt text.
104    #[serde(default = "default_cache_friendly_prompt_shaping")]
105    pub cache_friendly_prompt_shaping: bool,
106
107    /// Keep the wire tool catalog identical across planning and execution
108    /// turns (union of both modes' tools). Planning toggles then do not
109    /// rewrite the tool prefix. The fail-closed execution gate still blocks
110    /// mutations during planning.
111    #[serde(default = "default_true")]
112    pub stable_tool_catalog_across_modes: bool,
113
114    /// Warn before a request when the pause since the previous request likely
115    /// exceeded the provider prompt cache lifetime (advisory only).
116    #[serde(default = "default_true")]
117    pub gap_warning_enabled: bool,
118
119    /// Override for the cache-gap warning threshold in seconds. When unset,
120    /// a provider-specific default is used (Anthropic 300s, OpenAI 600s).
121    #[serde(default)]
122    pub gap_warning_threshold_secs: Option<u64>,
123
124    /// Provider specific overrides
125    #[serde(default)]
126    pub providers: ProviderPromptCachingConfig,
127}
128
129impl Default for PromptCachingConfig {
130    fn default() -> Self {
131        let cache_dir = default_cache_dir();
132        Self {
133            enabled: default_enabled() && !cache_dir.is_empty(),
134            cache_dir,
135            max_entries: default_max_entries(),
136            max_age_days: default_max_age_days(),
137            enable_auto_cleanup: default_auto_cleanup(),
138            min_quality_threshold: default_min_quality_threshold(),
139            cache_friendly_prompt_shaping: default_cache_friendly_prompt_shaping(),
140            stable_tool_catalog_across_modes: true,
141            gap_warning_enabled: default_true(),
142            gap_warning_threshold_secs: None,
143            providers: ProviderPromptCachingConfig::default(),
144        }
145    }
146}
147
148impl PromptCachingConfig {
149    /// Resolve the configured cache directory to an absolute path
150    ///
151    /// - `~` is expanded to the user's home directory when available
152    /// - Relative paths are resolved against the provided workspace root when supplied
153    /// - Falls back to the configured string when neither applies
154    pub fn resolve_cache_dir(&self, workspace_root: Option<&Path>) -> PathBuf {
155        resolve_path(&self.cache_dir, workspace_root)
156    }
157
158    /// Returns true when prompt caching is active for the given provider runtime name.
159    pub fn is_provider_enabled(&self, provider_name: &str) -> bool {
160        if !self.enabled {
161            return false;
162        }
163
164        match provider_name.to_ascii_lowercase().as_str() {
165            "openai" | "merge-gateway" => self.providers.openai.enabled,
166            "anthropic" | "minimax" => self.providers.anthropic.enabled,
167            "gemini" => {
168                self.providers.gemini.enabled && !matches!(self.providers.gemini.mode, GeminiPromptCacheMode::Off)
169            }
170            "openrouter" => self.providers.openrouter.enabled,
171            "moonshot" => self.providers.moonshot.enabled,
172            "deepseek" => self.providers.deepseek.enabled,
173            "zai" => self.providers.zai.enabled,
174            _ => false,
175        }
176    }
177
178    /// Resolve the cache-gap warning threshold in seconds for a provider.
179    ///
180    /// Returns `None` when gap warnings or provider caching are disabled.
181    /// Call the model-aware resolver when the active model is known.
182    pub fn gap_threshold_secs(&self, provider_name: &str) -> Option<u64> {
183        self.gap_threshold_secs_for_model(provider_name, "")
184    }
185
186    /// Prefer the lifetime emitted by the route; otherwise preserve model-aware baseline advisories.
187    pub fn gap_threshold_secs_for_route(
188        &self,
189        provider: &str,
190        model: &str,
191        ttl: Option<PromptCacheTtl>,
192    ) -> Option<u64> {
193        if !self.gap_warning_enabled
194            || !self.enabled
195            || !(self.is_provider_enabled(provider) || (ttl.is_some() && self.providers.openai.enabled))
196        {
197            return None;
198        }
199        if let Some(threshold) = self.gap_warning_threshold_secs {
200            return Some(threshold);
201        }
202        if let Some(ttl) = ttl {
203            return Some(ttl.seconds());
204        }
205
206        Some(match provider.to_ascii_lowercase().as_str() {
207            "anthropic" | "minimax" => prompt_cache::ANTHROPIC_CACHE_GAP_WARNING_SECONDS,
208            "openai"
209                if supports_openai_explicit_prompt_cache(model)
210                    || self.providers.openai.prompt_cache_retention == Some(PromptCacheRetention::H24) =>
211            {
212                30 * 60
213            }
214            "openai" => prompt_cache::OPENAI_CACHE_GAP_WARNING_SECONDS,
215            _ => prompt_cache::DEFAULT_CACHE_GAP_WARNING_SECONDS,
216        })
217    }
218
219    /// Model-aware advisory threshold for callers without resolved route capabilities.
220    /// Runtime callers should pass the effective lifetime to the route-aware resolver.
221    pub fn gap_threshold_secs_for_model(&self, provider_name: &str, model: &str) -> Option<u64> {
222        let ttl = (provider_name.eq_ignore_ascii_case("openai") && supports_openai_explicit_prompt_cache(model))
223            .then(|| resolved_openai_prompt_cache_ttl(self.providers.openai.prompt_cache_ttl, model));
224        self.gap_threshold_secs_for_route(provider_name, model, ttl)
225    }
226}
227
228/// Per-provider configuration overrides
229#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
230#[derive(Debug, Clone, Deserialize, Serialize, Default)]
231pub struct ProviderPromptCachingConfig {
232    #[serde(default = "OpenAIPromptCacheSettings::default")]
233    pub openai: OpenAIPromptCacheSettings,
234
235    #[serde(default = "AnthropicPromptCacheSettings::default")]
236    pub anthropic: AnthropicPromptCacheSettings,
237
238    #[serde(default = "GeminiPromptCacheSettings::default")]
239    pub gemini: GeminiPromptCacheSettings,
240
241    #[serde(default = "OpenRouterPromptCacheSettings::default")]
242    pub openrouter: OpenRouterPromptCacheSettings,
243
244    #[serde(default = "MoonshotPromptCacheSettings::default")]
245    moonshot: MoonshotPromptCacheSettings,
246
247    #[serde(default = "DeepSeekPromptCacheSettings::default")]
248    pub deepseek: DeepSeekPromptCacheSettings,
249
250    #[serde(default = "ZaiPromptCacheSettings::default")]
251    zai: ZaiPromptCacheSettings,
252}
253
254/// OpenAI prompt cache retention policy.
255/// Controls the model-side prompt caching window.
256#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
258pub enum PromptCacheRetention {
259    /// In-memory caching (short-lived, free)
260    #[serde(rename = "in_memory")]
261    InMemory,
262    /// 24-hour persistent caching
263    #[default]
264    #[serde(rename = "24h")]
265    H24,
266    /// Forward-compatible catch-all for unknown retention values.
267    ///
268    /// The explicit `rename` keeps the serialized form (`"unknown"`) aligned
269    /// with [`PromptCacheRetention::as_str`]; bare `#[serde(other)]` would
270    /// serialize the variant name as `"Unknown"`.
271    #[serde(other, rename = "unknown")]
272    Unknown,
273}
274
275impl PromptCacheRetention {
276    /// Returns the string representation for the OpenAI API wire format.
277    pub fn as_str(&self) -> &str {
278        match self {
279            Self::InMemory => "in_memory",
280            Self::H24 => "24h",
281            Self::Unknown => "unknown",
282        }
283    }
284}
285
286impl std::fmt::Display for PromptCacheRetention {
287    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288        f.write_str(self.as_str())
289    }
290}
291
292/// OpenAI prompt caching controls (automatic with metrics)
293#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
294#[derive(Debug, Clone, Deserialize, Serialize)]
295pub struct OpenAIPromptCacheSettings {
296    #[serde(default = "default_true")]
297    pub enabled: bool,
298
299    #[serde(default = "default_openai_min_prefix_tokens")]
300    min_prefix_tokens: u32,
301
302    #[serde(default = "default_openai_idle_expiration")]
303    idle_expiration_seconds: u64,
304
305    #[serde(default = "default_true")]
306    pub surface_metrics: bool,
307
308    /// Opt in to stable-instruction-only cache writes for independent native
309    /// GPT-5.6+ auxiliary requests. Interactive requests keep implicit caching.
310    #[serde(default)]
311    pub auxiliary_explicit_cache: bool,
312
313    /// Strategy for generating OpenAI `prompt_cache_key`.
314    /// Session-scoped keys derive one stable key per VT Code conversation.
315    #[serde(default = "default_openai_prompt_cache_key_mode")]
316    pub prompt_cache_key_mode: OpenAIPromptCacheKeyMode,
317
318    /// Optional prompt cache retention policy to pass directly into OpenAI Responses API.
319    /// Supported values are "in_memory" and "24h". If set, VT Code will include
320    /// `prompt_cache_retention` in the request body to extend the model-side prompt
321    /// caching window or request the explicit in-memory policy.
322    #[serde(default)]
323    pub prompt_cache_retention: Option<PromptCacheRetention>,
324
325    /// Optional Responses minimum write lifetime; defaults to catalog policy or 30m.
326    #[serde(default)]
327    pub prompt_cache_ttl: Option<PromptCacheTtl>,
328}
329
330impl Default for OpenAIPromptCacheSettings {
331    fn default() -> Self {
332        Self {
333            enabled: default_true(),
334            min_prefix_tokens: default_openai_min_prefix_tokens(),
335            idle_expiration_seconds: default_openai_idle_expiration(),
336            surface_metrics: default_true(),
337            auxiliary_explicit_cache: false,
338            prompt_cache_key_mode: default_openai_prompt_cache_key_mode(),
339            prompt_cache_retention: None,
340            prompt_cache_ttl: None,
341        }
342    }
343}
344
345impl OpenAIPromptCacheSettings {
346    /// Validate OpenAI provider prompt cache settings.
347    /// With the typed enum, invalid values are caught at deserialization time.
348    fn validate(&self) -> anyhow::Result<()> {
349        if let Some(PromptCacheRetention::Unknown) = self.prompt_cache_retention {
350            anyhow::bail!("prompt_cache_retention must be one of: in_memory, 24h");
351        }
352        Ok(())
353    }
354}
355
356/// Build a stable OpenAI `prompt_cache_key` for requests that should share
357/// provider-side cache routing.
358#[must_use]
359pub fn build_openai_prompt_cache_key(
360    prompt_cache_enabled: bool,
361    prompt_cache_key_mode: &OpenAIPromptCacheKeyMode,
362    lineage_id: Option<&str>,
363) -> Option<String> {
364    if !prompt_cache_enabled {
365        return None;
366    }
367
368    let lineage_id = lineage_id.map(str::trim).filter(|value| !value.is_empty());
369    match prompt_cache_key_mode {
370        OpenAIPromptCacheKeyMode::Session => lineage_id.map(|lineage_id| format!("vtcode:openai:{lineage_id}")),
371        OpenAIPromptCacheKeyMode::Off => None,
372    }
373}
374
375/// Wire namespace for a provider's session-affinity key (`vtcode:{namespace}:{lineage}`).
376/// `None` means the provider carries no session lineage. Single source of truth
377/// for the affinity provider set: the gate and key builders below derive
378/// membership from this instead of repeating provider lists.
379fn affinity_namespace(provider_name: &str) -> Option<&'static str> {
380    match provider_name.trim().to_ascii_lowercase().as_str() {
381        "openai" => Some("openai"),
382        "merge-gateway" => Some("merge"),
383        "openrouter" => Some("openrouter"),
384        "xai" => Some("xai"),
385        "opencode-go" => Some("opencode-go"),
386        _ => None,
387    }
388}
389
390/// Rewrite an OpenAI-style cache key for routes that share the wire shape but
391/// need distinct routing stickiness. Keeps the stable session identifier while
392/// namespacing gateway/session-affinity traffic apart from native OpenAI.
393#[must_use]
394pub fn map_prompt_cache_key_for_provider(provider_name: &str, key: String) -> String {
395    match affinity_namespace(provider_name) {
396        Some(namespace) => key.replacen("vtcode:openai:", &format!("vtcode:{namespace}:"), 1),
397        None => key,
398    }
399}
400
401/// Providers that send lineage-stable session/cache identity on the wire.
402#[must_use]
403pub fn session_affinity_provider(provider_name: &str) -> bool {
404    affinity_namespace(provider_name).is_some()
405}
406
407/// Whether `LLMRequest.prompt_cache_key` should carry session lineage for this provider.
408///
409/// OpenAI/Merge keep the OpenAI prompt-cache enablement gate.
410/// OpenRouter/xAI/OpenCode Go need lineage for documented session affinity even
411/// when the OpenAI-specific cache block is off (global prompt-cache master
412/// switch still applies). OpenCode Go rejects requests without its session
413/// header, so its lineage must not depend on the OpenAI cache flag.
414#[must_use]
415pub fn session_affinity_key_enabled(
416    provider_name: &str,
417    global_prompt_cache_enabled: bool,
418    openai_prompt_cache_enabled: bool,
419) -> bool {
420    if !global_prompt_cache_enabled {
421        return false;
422    }
423    let provider = provider_name.trim().to_ascii_lowercase();
424    match provider.as_str() {
425        "openai" | "merge-gateway" => openai_prompt_cache_enabled,
426        _ => affinity_namespace(&provider).is_some(),
427    }
428}
429
430/// Build the namespaced session-affinity / prompt-cache key for a request.
431///
432/// OpenAI/Merge honor [`OpenAIPromptCacheKeyMode`]. OpenRouter/xAI/OpenCode Go
433/// always use a stable session namespace when the affinity gate is on: sticky
434/// routing is independent of the OpenAI prompt-cache key mode.
435#[must_use]
436pub fn build_session_affinity_prompt_cache_key(
437    provider_name: &str,
438    session_affinity_enabled: bool,
439    prompt_cache_key_mode: &OpenAIPromptCacheKeyMode,
440    lineage_id: Option<&str>,
441) -> Option<String> {
442    if !session_affinity_enabled {
443        return None;
444    }
445    let provider = provider_name.trim().to_ascii_lowercase();
446    let lineage = lineage_id.map(str::trim).filter(|value| !value.is_empty())?;
447    match provider.as_str() {
448        "openai" | "merge-gateway" => match prompt_cache_key_mode {
449            OpenAIPromptCacheKeyMode::Session => {
450                Some(map_prompt_cache_key_for_provider(&provider, format!("vtcode:openai:{lineage}")))
451            }
452            OpenAIPromptCacheKeyMode::Off => None,
453        },
454        _ => affinity_namespace(&provider).map(|namespace| format!("vtcode:{namespace}:{lineage}")),
455    }
456}
457
458/// OpenAI prompt cache key derivation mode.
459#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
460#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Default)]
461#[serde(rename_all = "snake_case")]
462pub enum OpenAIPromptCacheKeyMode {
463    /// Do not send `prompt_cache_key` in OpenAI requests.
464    Off,
465    /// Send one stable `prompt_cache_key` per VT Code session.
466    #[default]
467    Session,
468}
469
470/// Anthropic Claude cache control settings
471#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
472#[derive(Debug, Clone, Deserialize, Serialize)]
473pub struct AnthropicPromptCacheSettings {
474    #[serde(default = "default_true")]
475    pub enabled: bool,
476
477    /// Default TTL in seconds for the first cache breakpoint (tools/system).
478    /// Anthropic only supports "5m" (300s) or "1h" (3600s) TTL formats.
479    /// Set to >= 3600 for 1-hour cache on tools and system prompts.
480    /// Default: 3600 (1 hour) - recommended for stable tool definitions
481    #[serde(default = "default_anthropic_tools_ttl")]
482    pub tools_ttl_seconds: u64,
483
484    /// TTL for subsequent cache breakpoints (messages).
485    /// Set to >= 3600 for 1-hour cache on messages.
486    /// Default: 300 (5 minutes) - recommended for frequently changing messages
487    #[serde(default = "default_anthropic_messages_ttl")]
488    pub messages_ttl_seconds: u64,
489
490    /// Maximum number of cache breakpoints to use (max 4 per Anthropic spec).
491    /// Default: 4
492    #[serde(default = "default_anthropic_max_breakpoints")]
493    pub max_breakpoints: u8,
494
495    /// Apply cache control to system prompts by default
496    #[serde(default = "default_true")]
497    pub cache_system_messages: bool,
498
499    /// Apply cache control to user messages exceeding threshold
500    #[serde(default = "default_true")]
501    pub cache_user_messages: bool,
502
503    /// Apply cache control to tool definitions by default
504    /// Default: true (tools are typically stable and benefit from longer caching)
505    #[serde(default = "default_true")]
506    pub cache_tool_definitions: bool,
507
508    /// Minimum message length (in characters) before applying cache control
509    /// to avoid caching very short messages that don't benefit from caching.
510    /// Default: 256 characters (~64 tokens)
511    #[serde(default = "default_min_message_length")]
512    pub min_message_length_for_cache: usize,
513
514    /// Extended TTL for Anthropic prompt caching (in seconds)
515    /// Set to >= 3600 for 1-hour cache on messages
516    #[serde(default = "default_anthropic_extended_ttl")]
517    pub extended_ttl_seconds: Option<u64>,
518
519    /// Prefer the 1h extended TTL for tools/system/messages even when the
520    /// per-breakpoint TTLs are 5m. Use when sessions idle past the 5m cache
521    /// window. Opt-in; 1h writes cost 2x base input.
522    #[serde(default)]
523    pub prefer_extended_ttl: bool,
524}
525
526impl Default for AnthropicPromptCacheSettings {
527    fn default() -> Self {
528        Self {
529            enabled: default_true(),
530            tools_ttl_seconds: default_anthropic_tools_ttl(),
531            messages_ttl_seconds: default_anthropic_messages_ttl(),
532            max_breakpoints: default_anthropic_max_breakpoints(),
533            cache_system_messages: default_true(),
534            cache_user_messages: default_true(),
535            cache_tool_definitions: default_true(),
536            min_message_length_for_cache: default_min_message_length(),
537            extended_ttl_seconds: default_anthropic_extended_ttl(),
538            prefer_extended_ttl: false,
539        }
540    }
541}
542
543/// Gemini API caching preferences
544#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
545#[derive(Debug, Clone, Deserialize, Serialize)]
546pub struct GeminiPromptCacheSettings {
547    #[serde(default = "default_true")]
548    pub enabled: bool,
549
550    #[serde(default = "default_gemini_mode")]
551    pub mode: GeminiPromptCacheMode,
552
553    #[serde(default = "default_gemini_min_prefix_tokens")]
554    min_prefix_tokens: u32,
555
556    /// TTL for explicit caches (ignored in implicit mode)
557    #[serde(default = "default_gemini_explicit_ttl")]
558    pub explicit_ttl_seconds: Option<u64>,
559}
560
561impl Default for GeminiPromptCacheSettings {
562    fn default() -> Self {
563        Self {
564            enabled: default_true(),
565            mode: GeminiPromptCacheMode::default(),
566            min_prefix_tokens: default_gemini_min_prefix_tokens(),
567            explicit_ttl_seconds: default_gemini_explicit_ttl(),
568        }
569    }
570}
571
572/// Gemini prompt caching mode selection
573#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
574#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
575#[serde(rename_all = "snake_case")]
576#[derive(Default)]
577pub enum GeminiPromptCacheMode {
578    #[default]
579    Implicit,
580    Explicit,
581    Off,
582}
583
584/// OpenRouter passthrough caching controls
585#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
586#[derive(Debug, Clone, Deserialize, Serialize)]
587pub struct OpenRouterPromptCacheSettings {
588    #[serde(default = "default_true")]
589    pub enabled: bool,
590
591    /// Propagate provider cache instructions automatically
592    #[serde(default = "default_true")]
593    propagate_provider_capabilities: bool,
594
595    /// Surface cache savings reported by OpenRouter
596    #[serde(default = "default_true")]
597    pub report_savings: bool,
598}
599
600impl Default for OpenRouterPromptCacheSettings {
601    fn default() -> Self {
602        Self {
603            enabled: default_true(),
604            propagate_provider_capabilities: default_true(),
605            report_savings: default_true(),
606        }
607    }
608}
609
610/// Moonshot prompt caching configuration (leverages server-side reuse)
611#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
612#[derive(Debug, Clone, Deserialize, Serialize)]
613pub struct MoonshotPromptCacheSettings {
614    #[serde(default = "default_moonshot_enabled")]
615    enabled: bool,
616}
617
618impl Default for MoonshotPromptCacheSettings {
619    fn default() -> Self {
620        Self { enabled: default_moonshot_enabled() }
621    }
622}
623
624/// DeepSeek prompt caching configuration (automatic KV cache reuse)
625#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
626#[derive(Debug, Clone, Deserialize, Serialize)]
627pub struct DeepSeekPromptCacheSettings {
628    #[serde(default = "default_true")]
629    pub enabled: bool,
630
631    /// Emit cache hit/miss metrics from responses when available
632    #[serde(default = "default_true")]
633    pub surface_metrics: bool,
634}
635
636impl Default for DeepSeekPromptCacheSettings {
637    fn default() -> Self {
638        Self {
639            enabled: default_true(),
640            surface_metrics: default_true(),
641        }
642    }
643}
644
645/// Z.AI prompt caching configuration (disabled until platform exposes metrics)
646#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
647#[derive(Debug, Clone, Deserialize, Serialize)]
648pub struct ZaiPromptCacheSettings {
649    #[serde(default = "default_zai_enabled")]
650    enabled: bool,
651}
652
653impl Default for ZaiPromptCacheSettings {
654    fn default() -> Self {
655        Self { enabled: default_zai_enabled() }
656    }
657}
658
659fn default_enabled() -> bool {
660    prompt_cache::DEFAULT_ENABLED
661}
662
663fn default_cache_dir() -> String {
664    VtCodePaths::resolve()
665        .map(|paths| paths.cache_dir().join("prompts").display().to_string())
666        .unwrap_or_default()
667}
668
669fn default_max_entries() -> usize {
670    prompt_cache::DEFAULT_MAX_ENTRIES
671}
672
673fn default_max_age_days() -> u64 {
674    prompt_cache::DEFAULT_MAX_AGE_DAYS
675}
676
677fn default_auto_cleanup() -> bool {
678    prompt_cache::DEFAULT_AUTO_CLEANUP
679}
680
681fn default_min_quality_threshold() -> f64 {
682    prompt_cache::DEFAULT_MIN_QUALITY_THRESHOLD
683}
684
685fn default_cache_friendly_prompt_shaping() -> bool {
686    prompt_cache::DEFAULT_CACHE_FRIENDLY_PROMPT_SHAPING
687}
688
689fn default_openai_min_prefix_tokens() -> u32 {
690    prompt_cache::OPENAI_MIN_PREFIX_TOKENS
691}
692
693fn default_openai_idle_expiration() -> u64 {
694    prompt_cache::OPENAI_IDLE_EXPIRATION_SECONDS
695}
696
697fn default_openai_prompt_cache_key_mode() -> OpenAIPromptCacheKeyMode {
698    OpenAIPromptCacheKeyMode::Session
699}
700
701fn default_anthropic_extended_ttl() -> Option<u64> {
702    Some(prompt_cache::ANTHROPIC_EXTENDED_TTL_SECONDS)
703}
704
705fn default_anthropic_tools_ttl() -> u64 {
706    prompt_cache::ANTHROPIC_TOOLS_TTL_SECONDS
707}
708
709fn default_anthropic_messages_ttl() -> u64 {
710    prompt_cache::ANTHROPIC_MESSAGES_TTL_SECONDS
711}
712
713fn default_anthropic_max_breakpoints() -> u8 {
714    prompt_cache::ANTHROPIC_MAX_BREAKPOINTS
715}
716
717fn default_min_message_length() -> usize {
718    prompt_cache::ANTHROPIC_MIN_MESSAGE_LENGTH_FOR_CACHE
719}
720
721fn default_gemini_min_prefix_tokens() -> u32 {
722    prompt_cache::GEMINI_MIN_PREFIX_TOKENS
723}
724
725fn default_gemini_explicit_ttl() -> Option<u64> {
726    Some(prompt_cache::GEMINI_EXPLICIT_DEFAULT_TTL_SECONDS)
727}
728
729fn default_gemini_mode() -> GeminiPromptCacheMode {
730    GeminiPromptCacheMode::Implicit
731}
732
733fn default_zai_enabled() -> bool {
734    prompt_cache::ZAI_CACHE_ENABLED
735}
736
737fn default_moonshot_enabled() -> bool {
738    prompt_cache::MOONSHOT_CACHE_ENABLED
739}
740
741fn resolve_path(input: &str, workspace_root: Option<&Path>) -> PathBuf {
742    let trimmed = input.trim();
743    if trimmed.is_empty() {
744        return resolve_default_cache_dir();
745    }
746
747    if let Some(stripped) = trimmed.strip_prefix("~/").or_else(|| trimmed.strip_prefix("~\\")) {
748        if let Some(home) = dirs::home_dir() {
749            return home.join(stripped);
750        }
751        return PathBuf::from(stripped);
752    }
753
754    let candidate = Path::new(trimmed);
755    if candidate.is_absolute() {
756        return candidate.to_path_buf();
757    }
758
759    if let Some(root) = workspace_root {
760        return root.join(candidate);
761    }
762
763    candidate.to_path_buf()
764}
765
766fn resolve_default_cache_dir() -> PathBuf {
767    VtCodePaths::resolve()
768        .map(|paths| paths.cache_dir().join("prompts"))
769        .unwrap_or_default()
770}
771
772impl PromptCachingConfig {
773    /// Validate prompt cache config and provider overrides
774    pub(crate) fn validate(&self) -> anyhow::Result<()> {
775        // Validate OpenAI provider settings
776        self.providers.openai.validate()?;
777        Ok(())
778    }
779}
780
781#[cfg(test)]
782mod tests;
783#[cfg(test)]
784mod ttl_tests;