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#[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#[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
59pub 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#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
76#[derive(Debug, Clone, Deserialize, Serialize)]
77pub struct PromptCachingConfig {
78 #[serde(default = "default_enabled")]
80 pub enabled: bool,
81
82 #[serde(default = "default_cache_dir")]
84 pub cache_dir: String,
85
86 #[serde(default = "default_max_entries")]
88 pub max_entries: usize,
89
90 #[serde(default = "default_max_age_days")]
92 pub max_age_days: u64,
93
94 #[serde(default = "default_auto_cleanup")]
96 pub enable_auto_cleanup: bool,
97
98 #[serde(default = "default_min_quality_threshold")]
100 pub min_quality_threshold: f64,
101
102 #[serde(default = "default_cache_friendly_prompt_shaping")]
105 pub cache_friendly_prompt_shaping: bool,
106
107 #[serde(default = "default_true")]
112 pub stable_tool_catalog_across_modes: bool,
113
114 #[serde(default = "default_true")]
117 pub gap_warning_enabled: bool,
118
119 #[serde(default)]
122 pub gap_warning_threshold_secs: Option<u64>,
123
124 #[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 pub fn resolve_cache_dir(&self, workspace_root: Option<&Path>) -> PathBuf {
155 resolve_path(&self.cache_dir, workspace_root)
156 }
157
158 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 pub fn gap_threshold_secs(&self, provider_name: &str) -> Option<u64> {
183 self.gap_threshold_secs_for_model(provider_name, "")
184 }
185
186 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 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#[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#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
258pub enum PromptCacheRetention {
259 #[serde(rename = "in_memory")]
261 InMemory,
262 #[default]
264 #[serde(rename = "24h")]
265 H24,
266 #[serde(other, rename = "unknown")]
272 Unknown,
273}
274
275impl PromptCacheRetention {
276 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#[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 #[serde(default)]
311 pub auxiliary_explicit_cache: bool,
312
313 #[serde(default = "default_openai_prompt_cache_key_mode")]
316 pub prompt_cache_key_mode: OpenAIPromptCacheKeyMode,
317
318 #[serde(default)]
323 pub prompt_cache_retention: Option<PromptCacheRetention>,
324
325 #[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 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#[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
375fn 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#[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#[must_use]
403pub fn session_affinity_provider(provider_name: &str) -> bool {
404 affinity_namespace(provider_name).is_some()
405}
406
407#[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#[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#[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 Off,
465 #[default]
467 Session,
468}
469
470#[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 #[serde(default = "default_anthropic_tools_ttl")]
482 pub tools_ttl_seconds: u64,
483
484 #[serde(default = "default_anthropic_messages_ttl")]
488 pub messages_ttl_seconds: u64,
489
490 #[serde(default = "default_anthropic_max_breakpoints")]
493 pub max_breakpoints: u8,
494
495 #[serde(default = "default_true")]
497 pub cache_system_messages: bool,
498
499 #[serde(default = "default_true")]
501 pub cache_user_messages: bool,
502
503 #[serde(default = "default_true")]
506 pub cache_tool_definitions: bool,
507
508 #[serde(default = "default_min_message_length")]
512 pub min_message_length_for_cache: usize,
513
514 #[serde(default = "default_anthropic_extended_ttl")]
517 pub extended_ttl_seconds: Option<u64>,
518
519 #[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#[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 #[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#[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#[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 #[serde(default = "default_true")]
593 propagate_provider_capabilities: bool,
594
595 #[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#[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#[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 #[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#[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 pub(crate) fn validate(&self) -> anyhow::Result<()> {
775 self.providers.openai.validate()?;
777 Ok(())
778 }
779}
780
781#[cfg(test)]
782mod tests;
783#[cfg(test)]
784mod ttl_tests;