Skip to main content

services/
validation.rs

1//! `ultron/refinement-validation.ts`: the content checks the worker's refinement service runs when a refinement is
2//! activated (A32). A skill must be a loadable SKILL.md: YAML frontmatter with a kebab-case name and a description,
3//! then a nonempty body. An instruction is bounded plain text. Capability requests are refused separately by the
4//! refinement service itself.
5
6use crate::local::{Validator, frontmatter};
7use serde_json::Value;
8use std::sync::Arc;
9
10const MAX_SKILL_BYTES: usize = 64 * 1024;
11const MAX_INSTRUCTION_BYTES: usize = 16 * 1024;
12
13fn line_terminator(ch: char) -> bool {
14    matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
15}
16
17/// `new RegExp(`^${key}:\\s*(.+)$`, "m").exec(frontmatter)?.[1]?.trim()`.
18fn field<'a>(frontmatter: &'a str, key: &str) -> Option<&'a str> {
19    let prefix = format!("{key}:");
20    let starts = std::iter::once(0).chain(
21        frontmatter
22            .char_indices()
23            .filter(|(_, ch)| line_terminator(*ch))
24            .map(|(at, ch)| at + ch.len_utf8()),
25    );
26    for start in starts {
27        let Some(rest) = frontmatter[start..].strip_prefix(&prefix) else {
28            continue;
29        };
30        // `\s*` is greedy and crosses lines; `(.+)` then takes the rest of a line.
31        let skipped = rest.trim_start_matches(jsrt::string::is_space);
32        let line_end = skipped.find(line_terminator).unwrap_or(skipped.len());
33        if line_end > 0 {
34            return Some(jsrt::string::trim(&skipped[..line_end]));
35        }
36        // Nothing after the spaces: backtracking leaves `(.+)` a run of spaces when one exists on a line.
37        let spaces = &rest[..rest.len() - skipped.len()];
38        if spaces.chars().any(|ch| !line_terminator(ch)) {
39            return Some("");
40        }
41    }
42    None
43}
44
45/// `/^[a-z0-9]+(?:-[a-z0-9]+)*$/`.
46fn kebab(name: &str) -> bool {
47    name.split('-')
48        .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()))
49}
50
51/// `validateRefinementContent(kind, content)`: `Ok(true)` for a valid skill or instruction, `Ok(true)` for the
52/// kinds it does not check (TS `undefined`), an error naming the problem otherwise.
53pub fn validate_refinement_content(kind: &str, content: &Value) -> Result<bool, String> {
54    match kind {
55        "skill" => {
56            let text = content.as_str().ok_or("A skill refinement must be SKILL.md text")?;
57            if text.len() > MAX_SKILL_BYTES {
58                return Err("Skill content exceeds 64 KiB".into());
59            }
60            let (front, body) = frontmatter(text.trim_start_matches(jsrt::string::is_space), true)
61                .ok_or("Skill content needs YAML frontmatter")?;
62            if !field(front, "name").is_some_and(|name| !name.is_empty() && kebab(name)) {
63                return Err("Skill frontmatter needs a kebab-case name".into());
64            }
65            if !field(front, "description").is_some_and(|description| !description.is_empty()) {
66                return Err("Skill frontmatter needs a description".into());
67            }
68            if jsrt::string::trim(body).is_empty() {
69                return Err("Skill body is empty".into());
70            }
71            Ok(true)
72        }
73        "instruction" => {
74            let text = content
75                .as_str()
76                .filter(|text| !jsrt::string::trim(text).is_empty())
77                .ok_or("An instruction refinement must be text")?;
78            if text.len() > MAX_INSTRUCTION_BYTES {
79                return Err("Instruction exceeds 16 KiB".into());
80            }
81            Ok(true)
82        }
83        _ => Ok(true),
84    }
85}
86
87pub fn worker_validator() -> Validator {
88    Arc::new(validate_refinement_content)
89}