Skip to main content

fallow_api/
released_skills.rs

1//! The released fallow skills (`npm/fallow/skills/<name>/`), embedded at
2//! build time. `fallow agent install` writes them to disk, and the MCP server
3//! serves them through the skills extension.
4
5use std::io::{self, Read as _};
6
7include!(concat!(env!("OUT_DIR"), "/embedded_skill.rs"));
8
9impl EmbeddedSkillFile {
10    /// The uncompressed bytes of the file.
11    ///
12    /// # Errors
13    ///
14    /// Returns an error when the embedded gzip payload is corrupt.
15    pub fn bytes(&self) -> io::Result<Vec<u8>> {
16        let mut decoder = flate2::read::GzDecoder::new(self.gzip);
17        let mut bytes = Vec::with_capacity(self.raw_len);
18        decoder.read_to_end(&mut bytes)?;
19        Ok(bytes)
20    }
21}
22
23/// The frontmatter of a `SKILL.md`: every field, in source order.
24pub type Frontmatter = serde_json::Map<String, serde_json::Value>;
25
26/// Parse the YAML frontmatter at the start of a `SKILL.md`.
27///
28/// Each value keeps its YAML type: a string, a boolean, a number, a null, a
29/// sequence or a mapping. A plain scalar that is not a valid JSON number,
30/// such as `.inf`, keeps its source text as a string.
31///
32/// # Errors
33///
34/// Returns an error when the text has no frontmatter block, the block is not
35/// valid YAML, or a mapping key is not a scalar. CRLF line ends are accepted.
36pub fn parse_frontmatter(skill_md: &str) -> Result<Frontmatter, String> {
37    let skill_md = skill_md.replace("\r\n", "\n");
38    let block = skill_md
39        .strip_prefix("---\n")
40        .and_then(|rest| rest.split_once("\n---\n").map(|(block, _)| block))
41        .ok_or("SKILL.md has no frontmatter block")?;
42    let document = fallow_config::yaml::parse(block).map_err(|e| e.to_string())?;
43    match yaml_to_json(document.root())? {
44        serde_json::Value::Object(fields) => Ok(fields),
45        _ => Err("SKILL.md frontmatter is not a mapping".to_string()),
46    }
47}
48
49fn yaml_to_json(node: fallow_config::yaml::YamlNode<'_>) -> Result<serde_json::Value, String> {
50    use serde_json::Value;
51    if node.is_null() {
52        return Ok(Value::Null);
53    }
54    if let Some(flag) = node.as_bool() {
55        return Ok(Value::Bool(flag));
56    }
57    if let Some(text) = node.as_str() {
58        return Ok(Value::String(text.to_string()));
59    }
60    if let Some(mapping) = node.as_mapping() {
61        let mut fields = Frontmatter::new();
62        for (key, value) in mapping.iter() {
63            let key = key.scalar_text().ok_or("frontmatter key is not a scalar")?;
64            fields.insert(key.to_string(), yaml_to_json(value)?);
65        }
66        return Ok(Value::Object(fields));
67    }
68    if let Some(items) = node.as_sequence() {
69        return items
70            .map(yaml_to_json)
71            .collect::<Result<_, _>>()
72            .map(Value::Array);
73    }
74    let text = node.scalar_text().ok_or("unsupported frontmatter value")?;
75    Ok(serde_json::from_str::<serde_json::Number>(text)
76        .map_or_else(|_| Value::String(text.to_string()), Value::Number))
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[test]
84    fn frontmatter_keeps_every_field() {
85        let fields = parse_frontmatter(
86            "---\nname: demo\ndescription: \"Use: when asked\"\nlicense: MIT\nbeta: true\n---\n# Demo\n",
87        )
88        .expect("valid frontmatter");
89        assert_eq!(
90            serde_json::Value::Object(fields),
91            serde_json::json!({
92                "name": "demo",
93                "description": "Use: when asked",
94                "license": "MIT",
95                "beta": true,
96            })
97        );
98    }
99
100    #[test]
101    fn frontmatter_keeps_value_types() {
102        let fields = parse_frontmatter(
103            "---\nname: demo\nversion: 1.10\ncount: 3\nempty: ~\nquoted: \"42\"\n\
104             allowed-tools: [Read, Grep]\nmetadata:\n  owner: fallow\n---\n",
105        )
106        .expect("valid frontmatter");
107        assert_eq!(
108            serde_json::Value::Object(fields),
109            serde_json::json!({
110                "name": "demo",
111                "version": 1.10,
112                "count": 3,
113                "empty": null,
114                "quoted": "42",
115                "allowed-tools": ["Read", "Grep"],
116                "metadata": { "owner": "fallow" },
117            })
118        );
119    }
120
121    #[test]
122    fn frontmatter_rejects_a_missing_block() {
123        assert!(parse_frontmatter("# No frontmatter\n").is_err());
124        assert!(parse_frontmatter("---\n- a\n- b\n---\n").is_err());
125    }
126
127    #[test]
128    fn every_embedded_skill_has_name_and_description() {
129        for skill in EMBEDDED_SKILLS {
130            let skill_md = skill
131                .files
132                .iter()
133                .find(|f| f.path == "SKILL.md")
134                .expect("every skill ships SKILL.md");
135            let text = String::from_utf8(skill_md.bytes().expect("decompress SKILL.md"))
136                .expect("SKILL.md is UTF-8");
137            let fields = parse_frontmatter(&text).expect("valid frontmatter");
138            assert_eq!(fields["name"], skill.name);
139            assert!(
140                fields["description"]
141                    .as_str()
142                    .is_some_and(|d| !d.is_empty())
143            );
144            for file in skill.files {
145                let bytes = file.bytes().expect("decompress skill file");
146                assert_eq!(bytes.len(), file.raw_len, "{}", file.path);
147            }
148        }
149    }
150}