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 #[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 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#[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
384fn 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#[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#[must_use]
412pub fn session_affinity_provider(provider_name: &str) -> bool {
413 affinity_namespace(provider_name).is_some()
414}
415
416#[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#[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#[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 Off,
474 #[default]
476 Session,
477}
478
479#[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 #[serde(default = "default_anthropic_tools_ttl")]
491 pub tools_ttl_seconds: u64,
492
493 #[serde(default = "default_anthropic_messages_ttl")]
497 pub messages_ttl_seconds: u64,
498
499 #[serde(default = "default_anthropic_max_breakpoints")]
502 pub max_breakpoints: u8,
503
504 #[serde(default = "default_true")]
506 pub cache_system_messages: bool,
507
508 #[serde(default = "default_true")]
510 pub cache_user_messages: bool,
511
512 #[serde(default = "default_true")]
515 pub cache_tool_definitions: bool,
516
517 #[serde(default = "default_min_message_length")]
521 pub min_message_length_for_cache: usize,
522
523 #[serde(default = "default_anthropic_extended_ttl")]
526 pub extended_ttl_seconds: Option<u64>,
527
528 #[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#[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 #[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#[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#[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 #[serde(default = "default_true")]
602 propagate_provider_capabilities: bool,
603
604 #[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#[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#[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 #[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#[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 pub(crate) fn validate(&self) -> anyhow::Result<()> {
784 self.providers.openai.validate()?;
786 Ok(())
787 }
788}
789
790#[cfg(test)]
791mod tests;
792#[cfg(test)]
793mod ttl_tests;