Skip to main content

tea_coding/resources/
prompts.rs

1use std::collections::BTreeMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use crate::resources::frontmatter::{field, parse};
6use crate::{CodingError, CodingErrorCode};
7
8const MAX_TEMPLATES: usize = 128;
9
10/// Validated non-executable Markdown prompt template.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct PromptTemplate {
13    name: String,
14    description: String,
15    body: String,
16    defaults: BTreeMap<String, String>,
17}
18
19impl PromptTemplate {
20    /// Returns the canonical template name.
21    #[must_use]
22    pub fn name(&self) -> &str {
23        &self.name
24    }
25    /// Returns metadata shown by command discovery.
26    #[must_use]
27    pub fn description(&self) -> &str {
28        &self.description
29    }
30    /// Expands `$1`..`$9` and `${name}` once without recursion or evaluation.
31    #[must_use]
32    pub fn expand(&self, positional: &[String], named: &BTreeMap<String, String>) -> String {
33        let mut output = String::with_capacity(self.body.len());
34        let mut remaining = self.body.as_str();
35        while let Some(marker) = remaining.find('$') {
36            output.push_str(&remaining[..marker]);
37            remaining = &remaining[marker..];
38            if let Some(index) = remaining
39                .as_bytes()
40                .get(1)
41                .copied()
42                .filter(u8::is_ascii_digit)
43                .map(|digit| usize::from(digit - b'0'))
44                .filter(|index| (1..=9).contains(index))
45            {
46                output.push_str(positional.get(index - 1).map_or("", String::as_str));
47                remaining = &remaining[2..];
48            } else if let Some(after_open) = remaining.strip_prefix("${") {
49                if let Some(end) = after_open.find('}') {
50                    let name = &after_open[..end];
51                    if let Some(default) = self.defaults.get(name) {
52                        output.push_str(named.get(name).map_or(default, String::as_ref));
53                        remaining = &after_open[end + 1..];
54                    } else {
55                        output.push('$');
56                        remaining = &remaining[1..];
57                    }
58                } else {
59                    output.push('$');
60                    remaining = &remaining[1..];
61                }
62            } else {
63                output.push('$');
64                remaining = &remaining[1..];
65            }
66        }
67        output.push_str(remaining);
68        output
69    }
70}
71
72pub(crate) fn discover(
73    global: Option<&Path>,
74    trusted_project: Option<&Path>,
75) -> Result<Vec<PromptTemplate>, CodingError> {
76    let mut templates = BTreeMap::new();
77    for root in [global, trusted_project].into_iter().flatten() {
78        for template in load_layer(root)? {
79            templates.insert(template.name.clone(), template);
80        }
81    }
82    if templates.len() > MAX_TEMPLATES {
83        return Err(invalid());
84    }
85    Ok(templates.into_values().collect())
86}
87
88fn load_layer(root: &Path) -> Result<Vec<PromptTemplate>, CodingError> {
89    let entries = match fs::read_dir(root) {
90        Ok(entries) => entries,
91        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
92        Err(_) => return Err(not_found()),
93    };
94    let mut paths = entries
95        .filter_map(Result::ok)
96        .filter(|entry| {
97            entry.file_type().is_ok_and(|kind| kind.is_file())
98                && entry
99                    .path()
100                    .extension()
101                    .is_some_and(|extension| extension == "md")
102        })
103        .map(|entry| entry.path())
104        .collect::<Vec<PathBuf>>();
105    paths.sort();
106    let mut layer = BTreeMap::new();
107    for path in paths {
108        let document = parse(&fs::read_to_string(path).map_err(|_| not_found())?)?;
109        let name = field(&document, "name")?.to_owned();
110        let description = field(&document, "description")?.to_owned();
111        if !valid_name(&name) {
112            return Err(invalid());
113        }
114        let defaults = document
115            .fields
116            .iter()
117            .filter_map(|(key, value)| {
118                key.strip_prefix("default_")
119                    .map(|name| (name.to_owned(), value.clone()))
120            })
121            .collect();
122        let template = PromptTemplate {
123            name: name.clone(),
124            description,
125            body: document.body,
126            defaults,
127        };
128        if layer.insert(name, template).is_some() {
129            return Err(CodingError::new(
130                CodingErrorCode::InvalidInput,
131                "duplicate prompt template name in one layer",
132            ));
133        }
134    }
135    Ok(layer.into_values().collect())
136}
137
138fn valid_name(value: &str) -> bool {
139    !value.is_empty()
140        && value.len() <= 128
141        && value.bytes().all(|byte| {
142            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_')
143        })
144}
145fn invalid() -> CodingError {
146    CodingError::new(CodingErrorCode::InvalidInput, "prompt template is invalid")
147}
148fn not_found() -> CodingError {
149    CodingError::new(
150        CodingErrorCode::NotFound,
151        "prompt template directory is missing",
152    )
153}