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    /// Optional lifetime for the stable developer-instruction cache breakpoint on native
330    /// GPT-5.6+ Responses routes. When unset, the breakpoint inherits `prompt_cache_ttl`.
331    /// Set to `"12h"` to keep the stable prefix reusable across longer gaps while session
332    /// history stays at the shorter request lifetime. 12-hour writes cost 2.5x ordinary
333    /// input versus 1.25x for 30-minute writes. Options: "30m", "12h".
334    #[serde(default)]
335    pub stable_prefix_ttl: Option<PromptCacheTtl>,
336}
337
338impl Default for OpenAIPromptCacheSettings {
339    fn default() -> Self {
340        Self {
341            enabled: default_true(),
342            min_prefix_tokens: default_openai_min_prefix_tokens(),
343            idle_expiration_seconds: default_openai_idle_expiration(),
344            surface_metrics: default_true(),
345            auxiliary_explicit_cache: false,
346            prompt_cache_key_mode: default_openai_prompt_cache_key_mode(),
347            prompt_cache_retention: None,
348            prompt_cache_ttl: None,
349            stable_prefix_ttl: None,
350        }
351    }
352}
353
354impl OpenAIPromptCacheSettings {
355    /// Validate OpenAI provider prompt cache settings.
356    /// With the typed enum, invalid values are caught at deserialization time.
357    fn validate(&self) -> anyhow::Result<()> {
358        if let Some(PromptCacheRetention::Unknown) = self.prompt_cache_retention {
359            anyhow::bail!("prompt_cache_retention must be one of: in_memory, 24h");
360        }
361        Ok(())
362    }
363}
364
365/// Build a stable OpenAI `prompt_cache_key` for requests that should share
366/// provider-side cache routing.
367#[must_use]
368pub fn build_openai_prompt_cache_key(
369    prompt_cache_enabled: bool,
370    prompt_cache_key_mode: &OpenAIPromptCacheKeyMode,
371    lineage_id: Option<&str>,
372) -> Option<String> {
373    if !prompt_cache_enabled {
374        return None;
375    }
376
377    let lineage_id = lineage_id.map(str::trim).filter(|value| !value.is_empty());
378    match prompt_cache_key_mode {
379        OpenAIPromptCacheKeyMode::Session => lineage_id.map(|lineage_id| format!("vtcode:openai:{lineage_id}")),
380        OpenAIPromptCacheKeyMode::Off => None,
381    }
382}
383
384/// Wire namespace for a provider's session-affinity key (`vtcode:{namespace}:{lineage}`).
385/// `None` means the provider carries no session lineage. Single source of truth
386/// for the affinity provider set: the gate and key builders below derive
387/// membership from this instead of repeating provider lists.
388fn affinity_namespace(provider_name: &str) -> Option<&'static str> {
389    match provider_name.trim().to_ascii_lowercase().as_str() {
390        "openai" => Some("openai"),
391        "merge-gateway" => Some("merge"),
392        "openrouter" => Some("openrouter"),
393        "xai" => Some("xai"),
394        "opencode-go" => Some("opencode-go"),
395        _ => None,
396    }
397}
398
399/// Rewrite an OpenAI-style cache key for routes that share the wire shape but
400/// need distinct routing stickiness. Keeps the stable session identifier while
401/// namespacing gateway/session-affinity traffic apart from native OpenAI.
402#[must_use]
403pub fn map_prompt_cache_key_for_provider(provider_name: &str, key: String) -> String {
404    match affinity_namespace(provider_name) {
405        Some(namespace) => key.replacen("vtcode:openai:", &format!("vtcode:{namespace}:"), 1),
406        None => key,
407    }
408}
409
410/// Providers that send lineage-stable session/cache identity on the wire.
411#[must_use]
412pub fn session_affinity_provider(provider_name: &str) -> bool {
413    affinity_namespace(provider_name).is_some()
414}
415
416/// Whether `LLMRequest.prompt_cache_key` should carry session lineage for this provider.
417///
418/// OpenAI/Merge keep the OpenAI prompt-cache enablement gate.
419/// OpenRouter/xAI/OpenCode Go need lineage for documented session affinity even
420/// when the OpenAI-specific cache block is off (global prompt-cache master
421/// switch still applies). OpenCode Go rejects requests without its session
422/// header, so its lineage must not depend on the OpenAI cache flag.
423#[must_use]
424pub fn session_affinity_key_enabled(
425    provider_name: &str,
426    global_prompt_cache_enabled: bool,
427    openai_prompt_cache_enabled: bool,
428) -> bool {
429    if !global_prompt_cache_enabled {
430        return false;
431    }
432    let provider = provider_name.trim().to_ascii_lowercase();
433    match provider.as_str() {
434        "openai" | "merge-gateway" => openai_prompt_cache_enabled,
435        _ => affinity_namespace(&provider).is_some(),
436    }
437}
438
439/// Build the namespaced session-affinity / prompt-cache key for a request.
440///
441/// OpenAI/Merge honor [`OpenAIPromptCacheKeyMode`]. OpenRouter/xAI/OpenCode Go
442/// always use a stable session namespace when the affinity gate is on: sticky
443/// routing is independent of the OpenAI prompt-cache key mode.
444#[must_use]
445pub fn build_session_affinity_prompt_cache_key(
446    provider_name: &str,
447    session_affinity_enabled: bool,
448    prompt_cache_key_mode: &OpenAIPromptCacheKeyMode,
449    lineage_id: Option<&str>,
450) -> Option<String> {
451    if !session_affinity_enabled {
452        return None;
453    }
454    let provider = provider_name.trim().to_ascii_lowercase();
455    let lineage = lineage_id.map(str::trim).filter(|value| !value.is_empty())?;
456    match provider.as_str() {
457        "openai" | "merge-gateway" => match prompt_cache_key_mode {
458            OpenAIPromptCacheKeyMode::Session => {
459                Some(map_prompt_cache_key_for_provider(&provider, format!("vtcode:openai:{lineage}")))
460            }
461            OpenAIPromptCacheKeyMode::Off => None,
462        },
463        _ => affinity_namespace(&provider).map(|namespace| format!("vtcode:{namespace}:{lineage}")),
464    }
465}
466
467/// OpenAI prompt cache key derivation mode.
468#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
469#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Default)]
470#[serde(rename_all = "snake_case")]
471pub enum OpenAIPromptCacheKeyMode {
472    /// Do not send `prompt_cache_key` in OpenAI requests.
473    Off,
474    /// Send one stable `prompt_cache_key` per VT Code session.
475    #[default]
476    Session,
477}
478
479/// Anthropic Claude cache control settings
480#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
481#[derive(Debug, Clone, Deserialize, Serialize)]
482pub struct AnthropicPromptCacheSettings {
483    #[serde(default = "default_true")]
484    pub enabled: bool,
485
486    /// Default TTL in seconds for the first cache breakpoint (tools/system).
487    /// Anthropic only supports "5m" (300s) or "1h" (3600s) TTL formats.
488    /// Set to >= 3600 for 1-hour cache on tools and system prompts.
489    /// Default: 3600 (1 hour) - recommended for stable tool definitions
490    #[serde(default = "default_anthropic_tools_ttl")]
491    pub tools_ttl_seconds: u64,
492
493    /// TTL for subsequent cache breakpoints (messages).
494    /// Set to >= 3600 for 1-hour cache on messages.
495    /// Default: 300 (5 minutes) - recommended for frequently changing messages
496    #[serde(default = "default_anthropic_messages_ttl")]
497    pub messages_ttl_seconds: u64,
498
499    /// Maximum number of cache breakpoints to use (max 4 per Anthropic spec).
500    /// Default: 4
501    #[serde(default = "default_anthropic_max_breakpoints")]
502    pub max_breakpoints: u8,
503
504    /// Apply cache control to system prompts by default
505    #[serde(default = "default_true")]
506    pub cache_system_messages: bool,
507
508    /// Apply cache control to user messages exceeding threshold
509    #[serde(default = "default_true")]
510    pub cache_user_messages: bool,
511
512    /// Apply cache control to tool definitions by default
513    /// Default: true (tools are typically stable and benefit from longer caching)
514    #[serde(default = "default_true")]
515    pub cache_tool_definitions: bool,
516
517    /// Minimum message length (in characters) before applying cache control
518    /// to avoid caching very short messages that don't benefit from caching.
519    /// Default: 256 characters (~64 tokens)
520    #[serde(default = "default_min_message_length")]
521    pub min_message_length_for_cache: usize,
522
523    /// Extended TTL for Anthropic prompt caching (in seconds)
524    /// Set to >= 3600 for 1-hour cache on messages
525    #[serde(default = "default_anthropic_extended_ttl")]
526    pub extended_ttl_seconds: Option<u64>,
527
528    /// Prefer the 1h extended TTL for tools/system/messages even when the
529    /// per-breakpoint TTLs are 5m. Use when sessions idle past the 5m cache
530    /// window. Opt-in; 1h writes cost 2x base input.
531    #[serde(default)]
532    pub prefer_extended_ttl: bool,
533}
534
535impl Default for AnthropicPromptCacheSettings {
536    fn default() -> Self {
537        Self {
538            enabled: default_true(),
539            tools_ttl_seconds: default_anthropic_tools_ttl(),
540            messages_ttl_seconds: default_anthropic_messages_ttl(),
541            max_breakpoints: default_anthropic_max_breakpoints(),
542            cache_system_messages: default_true(),
543            cache_user_messages: default_true(),
544            cache_tool_definitions: default_true(),
545            min_message_length_for_cache: default_min_message_length(),
546            extended_ttl_seconds: default_anthropic_extended_ttl(),
547            prefer_extended_ttl: false,
548        }
549    }
550}
551
552/// Gemini API caching preferences
553#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
554#[derive(Debug, Clone, Deserialize, Serialize)]
555pub struct GeminiPromptCacheSettings {
556    #[serde(default = "default_true")]
557    pub enabled: bool,
558
559    #[serde(default = "default_gemini_mode")]
560    pub mode: GeminiPromptCacheMode,
561
562    #[serde(default = "default_gemini_min_prefix_tokens")]
563    min_prefix_tokens: u32,
564
565    /// TTL for explicit caches (ignored in implicit mode)
566    #[serde(default = "default_gemini_explicit_ttl")]
567    pub explicit_ttl_seconds: Option<u64>,
568}
569
570impl Default for GeminiPromptCacheSettings {
571    fn default() -> Self {
572        Self {
573            enabled: default_true(),
574            mode: GeminiPromptCacheMode::default(),
575            min_prefix_tokens: default_gemini_min_prefix_tokens(),
576            explicit_ttl_seconds: default_gemini_explicit_ttl(),
577        }
578    }
579}
580
581/// Gemini prompt caching mode selection
582#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
583#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
584#[serde(rename_all = "snake_case")]
585#[derive(Default)]
586pub enum GeminiPromptCacheMode {
587    #[default]
588    Implicit,
589    Explicit,
590    Off,
591}
592
593/// OpenRouter passthrough caching controls
594#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
595#[derive(Debug, Clone, Deserialize, Serialize)]
596pub struct OpenRouterPromptCacheSettings {
597    #[serde(default = "default_true")]
598    pub enabled: bool,
599
600    /// Propagate provider cache instructions automatically
601    #[serde(default = "default_true")]
602    propagate_provider_capabilities: bool,
603
604    /// Surface cache savings reported by OpenRouter
605    #[serde(default = "default_true")]
606    pub report_savings: bool,
607}
608
609impl Default for OpenRouterPromptCacheSettings {
610    fn default() -> Self {
611        Self {
612            enabled: default_true(),
613            propagate_provider_capabilities: default_true(),
614            report_savings: default_true(),
615        }
616    }
617}
618
619/// Moonshot prompt caching configuration (leverages server-side reuse)
620#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
621#[derive(Debug, Clone, Deserialize, Serialize)]
622pub struct MoonshotPromptCacheSettings {
623    #[serde(default = "default_moonshot_enabled")]
624    enabled: bool,
625}
626
627impl Default for MoonshotPromptCacheSettings {
628    fn default() -> Self {
629        Self { enabled: default_moonshot_enabled() }
630    }
631}
632
633/// DeepSeek prompt caching configuration (automatic KV cache reuse)
634#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
635#[derive(Debug, Clone, Deserialize, Serialize)]
636pub struct DeepSeekPromptCacheSettings {
637    #[serde(default = "default_true")]
638    pub enabled: bool,
639
640    /// Emit cache hit/miss metrics from responses when available
641    #[serde(default = "default_true")]
642    pub surface_metrics: bool,
643}
644
645impl Default for DeepSeekPromptCacheSettings {
646    fn default() -> Self {
647        Self {
648            enabled: default_true(),
649            surface_metrics: default_true(),
650        }
651    }
652}
653
654/// Z.AI prompt caching configuration (disabled until platform exposes metrics)
655#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
656#[derive(Debug, Clone, Deserialize, Serialize)]
657pub struct ZaiPromptCacheSettings {
658    #[serde(default = "default_zai_enabled")]
659    enabled: bool,
660}
661
662impl Default for ZaiPromptCacheSettings {
663    fn default() -> Self {
664        Self { enabled: default_zai_enabled() }
665    }
666}
667
668fn default_enabled() -> bool {
669    prompt_cache::DEFAULT_ENABLED
670}
671
672fn default_cache_dir() -> String {
673    VtCodePaths::resolve()
674        .map(|paths| paths.cache_dir().join("prompts").display().to_string())
675        .unwrap_or_default()
676}
677
678fn default_max_entries() -> usize {
679    prompt_cache::DEFAULT_MAX_ENTRIES
680}
681
682fn default_max_age_days() -> u64 {
683    prompt_cache::DEFAULT_MAX_AGE_DAYS
684}
685
686fn default_auto_cleanup() -> bool {
687    prompt_cache::DEFAULT_AUTO_CLEANUP
688}
689
690fn default_min_quality_threshold() -> f64 {
691    prompt_cache::DEFAULT_MIN_QUALITY_THRESHOLD
692}
693
694fn default_cache_friendly_prompt_shaping() -> bool {
695    prompt_cache::DEFAULT_CACHE_FRIENDLY_PROMPT_SHAPING
696}
697
698fn default_openai_min_prefix_tokens() -> u32 {
699    prompt_cache::OPENAI_MIN_PREFIX_TOKENS
700}
701
702fn default_openai_idle_expiration() -> u64 {
703    prompt_cache::OPENAI_IDLE_EXPIRATION_SECONDS
704}
705
706fn default_openai_prompt_cache_key_mode() -> OpenAIPromptCacheKeyMode {
707    OpenAIPromptCacheKeyMode::Session
708}
709
710fn default_anthropic_extended_ttl() -> Option<u64> {
711    Some(prompt_cache::ANTHROPIC_EXTENDED_TTL_SECONDS)
712}
713
714fn default_anthropic_tools_ttl() -> u64 {
715    prompt_cache::ANTHROPIC_TOOLS_TTL_SECONDS
716}
717
718fn default_anthropic_messages_ttl() -> u64 {
719    prompt_cache::ANTHROPIC_MESSAGES_TTL_SECONDS
720}
721
722fn default_anthropic_max_breakpoints() -> u8 {
723    prompt_cache::ANTHROPIC_MAX_BREAKPOINTS
724}
725
726fn default_min_message_length() -> usize {
727    prompt_cache::ANTHROPIC_MIN_MESSAGE_LENGTH_FOR_CACHE
728}
729
730fn default_gemini_min_prefix_tokens() -> u32 {
731    prompt_cache::GEMINI_MIN_PREFIX_TOKENS
732}
733
734fn default_gemini_explicit_ttl() -> Option<u64> {
735    Some(prompt_cache::GEMINI_EXPLICIT_DEFAULT_TTL_SECONDS)
736}
737
738fn default_gemini_mode() -> GeminiPromptCacheMode {
739    GeminiPromptCacheMode::Implicit
740}
741
742fn default_zai_enabled() -> bool {
743    prompt_cache::ZAI_CACHE_ENABLED
744}
745
746fn default_moonshot_enabled() -> bool {
747    prompt_cache::MOONSHOT_CACHE_ENABLED
748}
749
750fn resolve_path(input: &str, workspace_root: Option<&Path>) -> PathBuf {
751    let trimmed = input.trim();
752    if trimmed.is_empty() {
753        return resolve_default_cache_dir();
754    }
755
756    if let Some(stripped) = trimmed.strip_prefix("~/").or_else(|| trimmed.strip_prefix("~\\")) {
757        if let Some(home) = dirs::home_dir() {
758            return home.join(stripped);
759        }
760        return PathBuf::from(stripped);
761    }
762
763    let candidate = Path::new(trimmed);
764    if candidate.is_absolute() {
765        return candidate.to_path_buf();
766    }
767
768    if let Some(root) = workspace_root {
769        return root.join(candidate);
770    }
771
772    candidate.to_path_buf()
773}
774
775fn resolve_default_cache_dir() -> PathBuf {
776    VtCodePaths::resolve()
777        .map(|paths| paths.cache_dir().join("prompts"))
778        .unwrap_or_default()
779}
780
781impl PromptCachingConfig {
782    /// Validate prompt cache config and provider overrides
783    pub(crate) fn validate(&self) -> anyhow::Result<()> {
784        // Validate OpenAI provider settings
785        self.providers.openai.validate()?;
786        Ok(())
787    }
788}
789
790#[cfg(test)]
791mod tests;
792#[cfg(test)]
793mod ttl_tests;