Skip to main content

tea_coding/resources/
skills.rs

1use std::collections::BTreeMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4use std::str::FromStr;
5
6use tea_context::{SkillId, SkillMetadata};
7
8use crate::resources::frontmatter::{field, parse};
9use crate::{CodingError, CodingErrorCode};
10
11const MAX_SKILLS: usize = 128;
12const MAX_SKILL_CONTENT_BYTES: usize = 128 * 1024;
13
14/// One validated declarative skill whose body is loaded only on invocation.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct DiscoveredSkill {
17    metadata: SkillMetadata,
18    path: PathBuf,
19}
20
21impl DiscoveredSkill {
22    /// Returns prompt-safe skill metadata.
23    #[must_use]
24    pub const fn metadata(&self) -> &SkillMetadata {
25        &self.metadata
26    }
27
28    /// Loads the body after explicit `/skill:name [args]` invocation.
29    ///
30    /// # Errors
31    ///
32    /// Rejects invalid syntax, changed metadata, oversized content, and unsafe referenced paths.
33    pub fn invoke(&self, invocation: &str) -> Result<LoadedSkill, CodingError> {
34        let prefix = format!("/skill:{}", self.metadata.id());
35        let args = invocation
36            .strip_prefix(&prefix)
37            .filter(|remaining| remaining.is_empty() || remaining.starts_with(' '))
38            .ok_or_else(invalid)?
39            .trim_start()
40            .to_owned();
41        if args.len() > 16 * 1024 || args.contains('\0') {
42            return Err(invalid());
43        }
44        let source = fs::read_to_string(&self.path).map_err(|_| not_found())?;
45        let document = parse(&source)?;
46        if field(&document, "name")? != self.metadata.id().as_str() {
47            return Err(invalid());
48        }
49        Ok(LoadedSkill {
50            content: document.body,
51            arguments: args,
52            directory: self.path.parent().ok_or_else(invalid)?.to_path_buf(),
53        })
54    }
55}
56
57/// Explicitly loaded skill body and its safe reference base.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct LoadedSkill {
60    content: String,
61    arguments: String,
62    directory: PathBuf,
63}
64
65impl LoadedSkill {
66    /// Returns skill instructions.
67    #[must_use]
68    pub fn content(&self) -> &str {
69        &self.content
70    }
71    /// Returns uninterpreted invocation arguments.
72    #[must_use]
73    pub fn arguments(&self) -> &str {
74        &self.arguments
75    }
76    /// Resolves one relative existing reference beneath the skill directory.
77    ///
78    /// # Errors
79    ///
80    /// Rejects absolute/traversing/missing references and symlink escape.
81    pub fn resolve_reference(&self, relative: &str) -> Result<PathBuf, CodingError> {
82        let path = Path::new(relative);
83        if relative.is_empty()
84            || path.is_absolute()
85            || path.components().any(|component| {
86                matches!(
87                    component,
88                    std::path::Component::ParentDir
89                        | std::path::Component::RootDir
90                        | std::path::Component::Prefix(_)
91                )
92            })
93        {
94            return Err(invalid());
95        }
96        let directory = fs::canonicalize(&self.directory).map_err(|_| not_found())?;
97        let target = fs::canonicalize(directory.join(path)).map_err(|_| not_found())?;
98        if !target.starts_with(&directory) {
99            return Err(invalid());
100        }
101        Ok(target)
102    }
103}
104
105pub(crate) fn discover(roots: &[PathBuf]) -> Result<Vec<DiscoveredSkill>, CodingError> {
106    let mut candidates = Vec::new();
107    for root in roots {
108        let canonical_root = match fs::canonicalize(root) {
109            Ok(root) => root,
110            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
111            Err(_) => return Err(not_found()),
112        };
113        let entries = match fs::read_dir(&canonical_root) {
114            Ok(entries) => entries,
115            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
116            Err(_) => return Err(not_found()),
117        };
118        let mut directories = entries
119            .filter_map(Result::ok)
120            .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))
121            .map(|entry| entry.path())
122            .collect::<Vec<_>>();
123        directories.sort();
124        for directory in directories {
125            let path = directory.join("SKILL.md");
126            match fs::canonicalize(path) {
127                Ok(path) if path.starts_with(&canonical_root) && path.is_file() => {
128                    candidates.push(path);
129                }
130                Ok(_) => return Err(invalid()),
131                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
132                Err(_) => return Err(not_found()),
133            }
134        }
135    }
136    if candidates.len() > MAX_SKILLS {
137        return Err(invalid());
138    }
139    let mut skills = BTreeMap::new();
140    for path in candidates {
141        let source = fs::read_to_string(&path).map_err(|_| not_found())?;
142        if source.len() > MAX_SKILL_CONTENT_BYTES {
143            return Err(invalid());
144        }
145        let document = parse(&source)?;
146        let name = field(&document, "name")?;
147        let description = field(&document, "description")?;
148        let metadata =
149            SkillMetadata::new(SkillId::from_str(name).map_err(|_| invalid())?, description)
150                .map_err(|_| invalid())?;
151        if skills
152            .insert(name.to_owned(), DiscoveredSkill { metadata, path })
153            .is_some()
154        {
155            return Err(CodingError::new(
156                CodingErrorCode::InvalidInput,
157                "duplicate skill name",
158            ));
159        }
160    }
161    Ok(skills.into_values().collect())
162}
163
164fn invalid() -> CodingError {
165    CodingError::new(CodingErrorCode::InvalidInput, "skill resource is invalid")
166}
167fn not_found() -> CodingError {
168    CodingError::new(CodingErrorCode::NotFound, "skill resource is missing")
169}