1use std::collections::{BTreeMap, HashMap};
4use std::path::{Path, PathBuf};
5use std::sync::{OnceLock, RwLock};
6use std::time::{Duration, SystemTime};
7
8use serde::Deserialize;
9use tokio::fs;
10use tracing::warn;
11use vtcode_commons::VtCodePaths;
12
13const PROMPTS_DIR: &str = ".vtcode/prompts";
14const TEMPLATES_DIR: &str = "templates";
15const SYSTEM_PROMPT_FILENAME: &str = "system.md";
16const APPEND_SYSTEM_PROMPT_FILENAME: &str = "append-system.md";
17const PROMPT_RESOURCE_CACHE_TTL: Duration = Duration::from_secs(5 * 60);
18const PROMPT_RESOURCE_CACHE_MAX_ENTRIES: usize = 32;
19
20static SYSTEM_PROMPT_LAYERS_CACHE: OnceLock<RwLock<HashMap<PromptResourceCacheKey, CachedSystemPromptLayers>>> =
21 OnceLock::new();
22static PROMPT_TEMPLATES_CACHE: OnceLock<RwLock<HashMap<PromptResourceCacheKey, CachedPromptTemplates>>> =
23 OnceLock::new();
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct PromptTemplate {
27 pub name: String,
28 pub description: String,
29 pub body: String,
30 pub path: PathBuf,
31}
32
33#[derive(Debug, Clone, Default, PartialEq, Eq)]
34pub struct SystemPromptLayers {
35 pub override_body: Option<String>,
36 pub append_bodies: Vec<String>,
37}
38
39#[derive(Debug, Clone, Copy)]
40enum PromptResourceScope {
41 User,
42 Workspace,
43}
44
45#[derive(Debug, Clone)]
46struct PromptResourceOptions<'a> {
47 workspace_root: &'a Path,
48 home_dir: Option<PathBuf>,
49}
50
51#[derive(Debug, Clone, Default, Deserialize)]
52struct PromptTemplateFrontmatter {
53 description: Option<String>,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Hash)]
57struct PromptResourceCacheKey {
58 workspace_root: PathBuf,
59 home_dir: Option<PathBuf>,
60}
61
62impl PromptResourceCacheKey {
63 fn new(options: &PromptResourceOptions<'_>) -> Self {
64 Self {
65 workspace_root: normalize_cache_path(options.workspace_root),
66 home_dir: options.home_dir.as_deref().map(normalize_cache_path),
67 }
68 }
69}
70
71#[derive(Clone)]
72struct CachedPromptTemplates {
73 templates: Vec<PromptTemplate>,
74 timestamp: SystemTime,
75 source_mtime: SystemTime,
76 source_paths: (PathBuf, Option<PathBuf>),
77}
78
79impl CachedPromptTemplates {
80 fn is_expired(&self) -> bool {
81 self.timestamp.elapsed().unwrap_or(PROMPT_RESOURCE_CACHE_TTL) > PROMPT_RESOURCE_CACHE_TTL
82 }
83
84 fn is_source_stale(&self) -> bool {
85 let mut check: Vec<&Path> = vec![self.source_paths.0.as_path()];
86 if let Some(ref h) = self.source_paths.1 {
87 check.push(h.as_path());
88 }
89 newest_mtime(check) > self.source_mtime
90 }
91}
92
93#[derive(Clone)]
94struct CachedSystemPromptLayers {
95 layers: SystemPromptLayers,
96 timestamp: SystemTime,
97 source_mtime: SystemTime,
98}
99
100impl CachedSystemPromptLayers {
101 fn is_expired(&self) -> bool {
102 self.timestamp.elapsed().unwrap_or(PROMPT_RESOURCE_CACHE_TTL) > PROMPT_RESOURCE_CACHE_TTL
103 }
104
105 fn is_source_stale(&self, check_paths: &[&Path]) -> bool {
106 newest_mtime(check_paths.iter().copied()) > self.source_mtime
107 }
108}
109
110fn normalize_cache_path(path: &Path) -> PathBuf {
111 dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
112}
113
114pub(crate) fn user_prompts_dir(home: &Path) -> PathBuf {
115 if dirs::home_dir().as_deref() == Some(home)
116 && let Ok(paths) = VtCodePaths::resolve()
117 && let Ok(prompt_dir) = paths.config_path("prompts")
118 {
119 return prompt_dir;
120 }
121 home.join(PROMPTS_DIR)
122}
123
124fn newest_mtime<'a>(paths: impl IntoIterator<Item = &'a Path>) -> SystemTime {
127 let mut newest = SystemTime::UNIX_EPOCH;
128 for path in paths {
129 if let Ok(metadata) = std::fs::metadata(path) {
130 if let Ok(mtime) = metadata.modified() {
131 newest = newest.max(mtime);
132 }
133 }
134 }
135 newest
136}
137
138fn system_prompt_layers_cache() -> &'static RwLock<HashMap<PromptResourceCacheKey, CachedSystemPromptLayers>> {
139 SYSTEM_PROMPT_LAYERS_CACHE.get_or_init(|| RwLock::new(HashMap::new()))
140}
141
142fn prompt_templates_cache() -> &'static RwLock<HashMap<PromptResourceCacheKey, CachedPromptTemplates>> {
143 PROMPT_TEMPLATES_CACHE.get_or_init(|| RwLock::new(HashMap::new()))
144}
145
146trait ExpirableCacheEntry {
149 fn is_expired(&self) -> bool;
150 fn timestamp(&self) -> SystemTime;
151}
152
153impl ExpirableCacheEntry for CachedSystemPromptLayers {
154 fn is_expired(&self) -> bool {
155 self.is_expired()
156 }
157
158 fn timestamp(&self) -> SystemTime {
159 self.timestamp
160 }
161}
162
163impl ExpirableCacheEntry for CachedPromptTemplates {
164 fn is_expired(&self) -> bool {
165 self.is_expired()
166 }
167
168 fn timestamp(&self) -> SystemTime {
169 self.timestamp
170 }
171}
172
173fn get_cached<K, V>(cache: &RwLock<HashMap<K, V>>, key: &K, what: &str) -> Option<V>
175where
176 K: Eq + std::hash::Hash,
177 V: ExpirableCacheEntry + Clone,
178{
179 match cache.read() {
180 Ok(cache) => cache.get(key).filter(|cached| !cached.is_expired()).cloned(),
181 Err(_) => {
182 warn!("{what} cache lock poisoned while reading cache");
183 None
184 }
185 }
186}
187
188fn evict_if_full<K, V>(cache: &mut HashMap<K, V>, key: &K)
191where
192 K: Eq + std::hash::Hash + Clone,
193 V: ExpirableCacheEntry,
194{
195 if cache.len() < PROMPT_RESOURCE_CACHE_MAX_ENTRIES || cache.contains_key(key) {
196 return;
197 }
198 let expired: Vec<K> = cache
199 .iter()
200 .filter(|(_, value)| value.is_expired())
201 .map(|(cache_key, _)| cache_key.clone())
202 .collect();
203 for cache_key in expired {
204 cache.remove(&cache_key);
205 }
206
207 if cache.len() >= PROMPT_RESOURCE_CACHE_MAX_ENTRIES {
208 let oldest_key = cache
209 .iter()
210 .min_by_key(|(_, value)| value.timestamp())
211 .map(|(cache_key, _)| cache_key.clone());
212 if let Some(oldest_key) = oldest_key {
213 cache.remove(&oldest_key);
214 }
215 }
216}
217
218fn get_cached_system_prompt_layers(key: &PromptResourceCacheKey) -> Option<CachedSystemPromptLayers> {
219 get_cached(system_prompt_layers_cache(), key, "system prompt layers")
220}
221
222fn cache_system_prompt_layers(key: PromptResourceCacheKey, layers: &SystemPromptLayers) {
223 match system_prompt_layers_cache().write() {
224 Ok(mut cache) => {
225 evict_if_full(&mut cache, &key);
226
227 let mut source_paths = vec![
228 key.workspace_root.join(PROMPTS_DIR).join(SYSTEM_PROMPT_FILENAME),
229 key.workspace_root.join(PROMPTS_DIR).join(APPEND_SYSTEM_PROMPT_FILENAME),
230 ];
231 if let Some(ref home) = key.home_dir {
232 let prompt_dir = user_prompts_dir(home);
233 source_paths.push(prompt_dir.join(SYSTEM_PROMPT_FILENAME));
234 source_paths.push(prompt_dir.join(APPEND_SYSTEM_PROMPT_FILENAME));
235 }
236 let source_mtime = newest_mtime(source_paths.iter().map(PathBuf::as_path));
237
238 cache.insert(
239 key,
240 CachedSystemPromptLayers {
241 layers: layers.clone(),
242 timestamp: SystemTime::now(),
243 source_mtime,
244 },
245 );
246 }
247 Err(_) => warn!("system prompt layers cache lock poisoned while writing cache"),
248 }
249}
250
251fn get_cached_prompt_templates(key: &PromptResourceCacheKey) -> Option<CachedPromptTemplates> {
252 get_cached(prompt_templates_cache(), key, "prompt templates")
253}
254
255fn cache_prompt_templates(key: PromptResourceCacheKey, templates: &[PromptTemplate]) {
256 match prompt_templates_cache().write() {
257 Ok(mut cache) => {
258 evict_if_full(&mut cache, &key);
259
260 let source_paths = (
261 key.workspace_root.join(PROMPTS_DIR).join(TEMPLATES_DIR),
262 key.home_dir.as_ref().map(|h| user_prompts_dir(h).join(TEMPLATES_DIR)),
263 );
264 let mut mtime_paths = vec![source_paths.0.clone()];
265 if let Some(ref p) = source_paths.1 {
266 mtime_paths.push(p.clone());
267 }
268 let source_mtime = newest_mtime(mtime_paths.iter().map(PathBuf::as_path));
269
270 cache.insert(
271 key,
272 CachedPromptTemplates {
273 templates: templates.to_vec(),
274 timestamp: SystemTime::now(),
275 source_mtime,
276 source_paths,
277 },
278 );
279 }
280 Err(_) => warn!("prompt templates cache lock poisoned while writing cache"),
281 }
282}
283
284#[cfg(test)]
285fn clear_prompt_resource_caches() {
286 if let Ok(mut cache) = system_prompt_layers_cache().write() {
287 cache.clear();
288 }
289 if let Ok(mut cache) = prompt_templates_cache().write() {
290 cache.clear();
291 }
292}
293
294pub async fn resolve_system_prompt_layers(workspace_root: &Path) -> SystemPromptLayers {
295 resolve_system_prompt_layers_with_options(PromptResourceOptions::new(workspace_root)).await
296}
297
298pub async fn discover_prompt_templates(workspace_root: &Path) -> Vec<PromptTemplate> {
299 discover_prompt_templates_with_options(PromptResourceOptions::new(workspace_root)).await
300}
301
302pub async fn find_prompt_template(workspace_root: &Path, name: &str) -> Option<PromptTemplate> {
303 let normalized = name.trim();
304 if normalized.is_empty() {
305 return None;
306 }
307
308 find_prompt_template_with_options(PromptResourceOptions::new(workspace_root), normalized).await
309}
310
311impl SystemPromptLayers {
312 fn effective_override_body(&self) -> Option<&str> {
314 self.override_body.as_deref().map(str::trim).filter(|body| !body.is_empty())
315 }
316
317 fn effective_append_bodies(&self) -> impl Iterator<Item = &str> {
319 self.append_bodies
320 .iter()
321 .map(|body| body.trim())
322 .filter(|body| !body.is_empty())
323 }
324
325 pub fn applied_text(&self) -> String {
331 let mut text = String::new();
332 let bodies = self.effective_override_body().into_iter().chain(self.effective_append_bodies());
333 for body in bodies {
334 if !text.is_empty() {
335 text.push_str("\n\n");
336 }
337 text.push_str(body);
338 }
339 text
340 }
341}
342
343pub fn apply_system_prompt_layers(base_prompt: &str, layers: &SystemPromptLayers) -> String {
344 let mut prompt = String::new();
345
346 if let Some(override_body) = layers.effective_override_body() {
347 prompt.push_str(override_body);
348 } else {
349 prompt.push_str(base_prompt);
350 }
351
352 for append_body in layers.effective_append_bodies() {
353 if !prompt.is_empty() {
354 prompt.push_str("\n\n");
355 }
356 prompt.push_str(append_body);
357 }
358
359 prompt
360}
361
362pub fn expand_prompt_template(body: &str, args: &[String]) -> String {
363 let joined_args = args.join(" ");
364 let mut expanded = String::with_capacity(body.len() + joined_args.len());
365 let chars: Vec<char> = body.chars().collect();
366 let mut index = 0;
367
368 while index < chars.len() {
369 if chars[index] != '$' {
370 expanded.push(chars[index]);
371 index += 1;
372 continue;
373 }
374
375 if index + 1 >= chars.len() {
376 expanded.push('$');
377 index += 1;
378 continue;
379 }
380
381 match chars[index + 1] {
382 '@' => {
383 expanded.push_str(&joined_args);
384 index += 2;
385 }
386 'A' => {
387 const ARGUMENTS_TOKEN: &str = "ARGUMENTS";
388 let remaining: String = chars[index + 1..].iter().collect();
389 if remaining.starts_with(ARGUMENTS_TOKEN) {
390 expanded.push_str(&joined_args);
391 index += ARGUMENTS_TOKEN.chars().count() + 1;
392 } else {
393 expanded.push('$');
394 index += 1;
395 }
396 }
397 digit if digit.is_ascii_digit() => {
398 let mut cursor = index + 1;
399 while cursor < chars.len() && chars[cursor].is_ascii_digit() {
400 cursor += 1;
401 }
402 let ordinal: String = chars[index + 1..cursor].iter().collect();
403 let replacement = ordinal
404 .parse::<usize>()
405 .ok()
406 .and_then(|value| value.checked_sub(1))
407 .and_then(|position| args.get(position))
408 .map(String::as_str)
409 .unwrap_or("");
410 expanded.push_str(replacement);
411 index = cursor;
412 }
413 _ => {
414 expanded.push('$');
415 index += 1;
416 }
417 }
418 }
419
420 expanded
421}
422
423impl<'a> PromptResourceOptions<'a> {
424 fn new(workspace_root: &'a Path) -> Self {
425 #[cfg(test)]
426 let home_dir = None;
427
428 #[cfg(not(test))]
429 let home_dir = dirs::home_dir();
430
431 Self { workspace_root, home_dir }
432 }
433}
434
435async fn resolve_system_prompt_layers_with_options(options: PromptResourceOptions<'_>) -> SystemPromptLayers {
436 let cache_key = PromptResourceCacheKey::new(&options);
437 if let Some(cached) = get_cached_system_prompt_layers(&cache_key) {
438 let check_paths = [
439 options.workspace_root.join(PROMPTS_DIR).join(SYSTEM_PROMPT_FILENAME),
440 options
441 .home_dir
442 .as_ref()
443 .map(|h| user_prompts_dir(h).join(SYSTEM_PROMPT_FILENAME))
444 .unwrap_or_default(),
445 options.workspace_root.join(PROMPTS_DIR).join(APPEND_SYSTEM_PROMPT_FILENAME),
446 options
447 .home_dir
448 .as_ref()
449 .map(|h| user_prompts_dir(h).join(APPEND_SYSTEM_PROMPT_FILENAME))
450 .unwrap_or_default(),
451 ];
452 let check_refs: Vec<_> = check_paths.iter().map(|p| p.as_path()).collect();
453 if !cached.is_source_stale(&check_refs) {
454 return cached.layers;
455 }
456 }
457
458 let layers = resolve_system_prompt_layers_uncached(&options).await;
459 cache_system_prompt_layers(cache_key, &layers);
460 layers
461}
462
463async fn resolve_system_prompt_layers_uncached(options: &PromptResourceOptions<'_>) -> SystemPromptLayers {
464 let mut layers = SystemPromptLayers::default();
465
466 let user_system_path = options
467 .home_dir
468 .as_ref()
469 .map(|home| user_prompts_dir(home).join(SYSTEM_PROMPT_FILENAME));
470 let workspace_system_path = options.workspace_root.join(PROMPTS_DIR).join(SYSTEM_PROMPT_FILENAME);
471
472 if let Some(path) = user_system_path.as_ref() {
473 layers.override_body = read_optional_markdown(path).await;
474 }
475
476 if let Some(workspace_override) = read_optional_markdown(&workspace_system_path).await {
477 layers.override_body = Some(workspace_override);
478 }
479
480 if let Some(path) = options
481 .home_dir
482 .as_ref()
483 .map(|home| user_prompts_dir(home).join(APPEND_SYSTEM_PROMPT_FILENAME))
484 && let Some(contents) = read_optional_markdown(&path).await
485 {
486 layers.append_bodies.push(contents);
487 }
488
489 let workspace_append = options.workspace_root.join(PROMPTS_DIR).join(APPEND_SYSTEM_PROMPT_FILENAME);
490 if let Some(contents) = read_optional_markdown(&workspace_append).await {
491 layers.append_bodies.push(contents);
492 }
493
494 layers
495}
496
497async fn discover_prompt_templates_with_options(options: PromptResourceOptions<'_>) -> Vec<PromptTemplate> {
498 let cache_key = PromptResourceCacheKey::new(&options);
499 if let Some(cached) = get_cached_prompt_templates(&cache_key) {
500 if !cached.is_source_stale() {
501 return cached.templates;
502 }
503 }
504
505 let templates = discover_prompt_templates_uncached(&options).await;
506 cache_prompt_templates(cache_key, &templates);
507 templates
508}
509
510async fn discover_prompt_templates_uncached(options: &PromptResourceOptions<'_>) -> Vec<PromptTemplate> {
511 let mut discovered = BTreeMap::new();
512
513 if let Some(home) = options.home_dir.as_deref() {
514 let user_templates = user_prompts_dir(home).join(TEMPLATES_DIR);
515 merge_prompt_templates(&mut discovered, &user_templates, PromptResourceScope::User).await;
516 }
517
518 let workspace_templates = options.workspace_root.join(PROMPTS_DIR).join(TEMPLATES_DIR);
519 merge_prompt_templates(&mut discovered, &workspace_templates, PromptResourceScope::Workspace).await;
520
521 discovered.into_values().collect()
522}
523
524async fn find_prompt_template_with_options(options: PromptResourceOptions<'_>, name: &str) -> Option<PromptTemplate> {
525 if !is_safe_template_name(name) {
526 return None;
527 }
528
529 discover_prompt_templates_with_options(options)
530 .await
531 .into_iter()
532 .find(|template| template.name == name)
533}
534
535async fn merge_prompt_templates(
536 discovered: &mut BTreeMap<String, PromptTemplate>,
537 directory: &Path,
538 scope: PromptResourceScope,
539) {
540 let Ok(mut entries) = fs::read_dir(directory).await else {
541 return;
542 };
543
544 let mut markdown_files = Vec::new();
545 loop {
546 match entries.next_entry().await {
547 Ok(Some(entry)) => {
548 let path = entry.path();
549 if path.extension().and_then(|ext| ext.to_str()) == Some("md") {
550 markdown_files.push(path);
551 }
552 }
553 Ok(None) => break,
554 Err(err) => {
555 warn!("failed to read prompt templates directory {}: {}", directory.display(), err);
556 break;
557 }
558 }
559 }
560
561 markdown_files.sort();
562
563 for path in markdown_files {
564 let Some(name) = path
565 .file_stem()
566 .and_then(|stem| stem.to_str())
567 .map(str::trim)
568 .filter(|stem| !stem.is_empty())
569 .map(str::to_string)
570 else {
571 continue;
572 };
573
574 match load_prompt_template(&path, name.clone()).await {
575 Some(template) => {
576 if matches!(scope, PromptResourceScope::Workspace) {
577 discovered.insert(name, template);
578 } else {
579 discovered.entry(name).or_insert(template);
580 }
581 }
582 None => continue,
583 }
584 }
585}
586
587async fn load_prompt_template(path: &Path, name: String) -> Option<PromptTemplate> {
588 let raw = read_optional_markdown(path).await?;
589 let normalized = normalize_newlines(&raw);
590 let (frontmatter, body) = parse_frontmatter(&normalized);
591 let description = frontmatter
592 .description
593 .filter(|value| !value.trim().is_empty())
594 .unwrap_or_else(|| derive_template_description(&body, &name));
595
596 Some(PromptTemplate {
597 name,
598 description,
599 body: body.trim().to_string(),
600 path: path.to_path_buf(),
601 })
602}
603
604async fn read_optional_markdown(path: &Path) -> Option<String> {
605 match fs::read_to_string(path).await {
606 Ok(contents) => Some(contents),
607 Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
608 Err(err) => {
609 warn!("failed to read prompt resource {}: {}", path.display(), err);
610 None
611 }
612 }
613}
614
615fn parse_frontmatter(content: &str) -> (PromptTemplateFrontmatter, String) {
616 if !content.starts_with("---\n") {
617 return (PromptTemplateFrontmatter::default(), content.to_string());
618 }
619
620 let Some(frontmatter_end) = content[4..].find("\n---\n").map(|idx| idx + 4) else {
621 return (PromptTemplateFrontmatter::default(), content.to_string());
622 };
623
624 let yaml = &content[4..frontmatter_end];
625 let body_start = frontmatter_end + 5;
626 let body = if body_start < content.len() {
627 content[body_start..].to_string()
628 } else {
629 String::new()
630 };
631
632 let metadata = match serde_saphyr::from_str::<PromptTemplateFrontmatter>(yaml.trim()) {
633 Ok(value) => value,
634 Err(err) => {
635 warn!("failed to parse prompt template frontmatter: {}", err);
636 PromptTemplateFrontmatter::default()
637 }
638 };
639
640 (metadata, body)
641}
642
643fn derive_template_description(body: &str, name: &str) -> String {
644 for line in body.lines().map(str::trim) {
645 if line.is_empty() {
646 continue;
647 }
648 if let Some(heading) = line.strip_prefix('#') {
649 let trimmed = heading.trim_start_matches('#').trim();
650 if !trimmed.is_empty() {
651 return trimmed.to_string();
652 }
653 }
654 return line.to_string();
655 }
656
657 format!("Prompt template `{name}`")
658}
659
660fn normalize_newlines(content: &str) -> String {
661 content.replace("\r\n", "\n")
662}
663
664fn is_safe_template_name(name: &str) -> bool {
665 !name.is_empty() && !name.contains('/') && !name.contains('\\') && !name.contains("..")
666}
667
668#[cfg(test)]
669mod tests;