| 1 | use std::collections::HashMap; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | |
| 4 | use crate::frontmatter::{ |
| 5 | SkillValidationMode, parse_frontmatter, parse_frontmatter_bool, validate_skill_frontmatter, |
| 6 | }; |
| 7 | |
| 8 | pub const MAX_SKILL_NAME_CHARS: usize = 64; |
| 9 | |
| 10 | /// Maximum directory-traversal depth when discovering skills. |
| 11 | /// |
| 12 | /// Defends against pathological configurations (e.g. a user pointing |
| 13 | /// `skills_dir` at `~`) without artificially limiting realistic |
| 14 | /// vendored layouts like `<root>/<org>/<repo>/<skill>/SKILL.md`. |
| 15 | pub const MAX_DISCOVERY_DEPTH: usize = 8; |
| 16 | |
| 17 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 18 | pub enum SkillInvocation { |
| 19 | ModelAndUser, |
| 20 | ExplicitOnly, |
| 21 | ModelOnly, |
| 22 | Disabled, |
| 23 | } |
| 24 | |
| 25 | impl SkillInvocation { |
| 26 | pub fn model_invocable(self) -> bool { |
| 27 | matches!(self, Self::ModelAndUser | Self::ModelOnly) |
| 28 | } |
| 29 | |
| 30 | pub fn user_invocable(self) -> bool { |
| 31 | matches!(self, Self::ModelAndUser | Self::ExplicitOnly) |
| 32 | } |
| 33 | |
| 34 | pub fn restrict_implicit(self) -> Self { |
| 35 | if self.user_invocable() { |
| 36 | Self::ExplicitOnly |
| 37 | } else { |
| 38 | Self::Disabled |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | pub fn from_frontmatter(value: Option<&str>) -> Self { |
| 43 | match value.map(str::trim).map(|value| value.to_ascii_lowercase()) { |
| 44 | Some(value) if value == "explicit-only" || value == "explicit_only" => { |
| 45 | Self::ExplicitOnly |
| 46 | } |
| 47 | _ => Self::ModelAndUser, |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | #[derive(Debug, Clone)] |
| 53 | pub struct ParsedSkill { |
| 54 | pub name: String, |
| 55 | pub legacy_activation_name: Option<String>, |
| 56 | pub description: String, |
| 57 | pub localized_descriptions: HashMap<String, String>, |
| 58 | pub invocation: SkillInvocation, |
| 59 | pub aliases: Vec<String>, |
| 60 | pub argument_hint: Option<String>, |
| 61 | pub body: String, |
| 62 | pub path: PathBuf, |
| 63 | } |
| 64 | |
| 65 | #[derive(Debug, Clone)] |
| 66 | pub struct NormalizedSkillName { |
| 67 | pub name: String, |
| 68 | pub legacy_activation_name: Option<String>, |
| 69 | pub warning: Option<String>, |
| 70 | } |
| 71 | |
| 72 | pub fn normalize_skill_name(name: &str, skill_path: &Path) -> NormalizedSkillName { |
| 73 | let legacy = legacy_skill_name_for_lookup(name); |
| 74 | let normalized = normalize_skill_name_for_lookup(name); |
| 75 | let supported_unicode_name = |
| 76 | !name.is_ascii() && !name.chars().any(char::is_control) && is_valid_skill_name(&normalized); |
| 77 | let legacy_activation_name = (legacy != normalized).then_some(legacy); |
| 78 | let mut resolved = name.to_string(); |
| 79 | let mut warning = None; |
| 80 | if normalized != name || !is_valid_skill_name(name) { |
| 81 | let original = std::mem::replace(&mut resolved, normalized); |
| 82 | if !supported_unicode_name { |
| 83 | warning = Some(format!( |
| 84 | "Skill name `{original}` in {} is not a safe command name; using `{resolved}` instead.", |
| 85 | skill_path.display(), |
| 86 | )); |
| 87 | } |
| 88 | } |
| 89 | NormalizedSkillName { |
| 90 | name: resolved, |
| 91 | legacy_activation_name, |
| 92 | warning, |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | pub fn parse_verified_content( |
| 97 | path: &Path, |
| 98 | content: &str, |
| 99 | ) -> std::result::Result<(ParsedSkill, Vec<String>), String> { |
| 100 | let (mut skill, mut warnings) = parse_skill_and_warnings(path, content)?; |
| 101 | skill.path = path.to_path_buf(); |
| 102 | let normalized = normalize_skill_name(&skill.name, path); |
| 103 | skill.legacy_activation_name = normalized.legacy_activation_name; |
| 104 | skill.name = normalized.name; |
| 105 | warnings.extend(normalized.warning); |
| 106 | Ok((skill, warnings)) |
| 107 | } |
| 108 | |
| 109 | pub fn parse_skill_and_warnings( |
| 110 | path: &Path, |
| 111 | content: &str, |
| 112 | ) -> std::result::Result<(ParsedSkill, Vec<String>), String> { |
| 113 | // Try to parse frontmatter block first. If absent, fall back to |
| 114 | // extracting the first `# Heading` as the skill name so that plain |
| 115 | // Markdown files (no `---` fence) are accepted instead of rejected. |
| 116 | let parsed = parse_frontmatter(content)?; |
| 117 | let warnings = validate_skill_frontmatter( |
| 118 | parsed.as_ref().map(|(metadata, _)| metadata), |
| 119 | Some(path), |
| 120 | SkillValidationMode::Lenient, |
| 121 | )?; |
| 122 | if let Some((metadata, body)) = parsed { |
| 123 | let name = metadata |
| 124 | .get("name") |
| 125 | .filter(|name| !name.is_empty()) |
| 126 | .cloned() |
| 127 | .ok_or_else(|| "missing required frontmatter field: name".to_string())?; |
| 128 | |
| 129 | let mut description = metadata.get("description").cloned().unwrap_or_default(); |
| 130 | if let Some(trigger) = metadata |
| 131 | .get("when_to_use") |
| 132 | .filter(|value| !value.trim().is_empty()) |
| 133 | { |
| 134 | if !description.is_empty() { |
| 135 | description.push(' '); |
| 136 | } |
| 137 | description.push_str("Use when: "); |
| 138 | description.push_str(trigger.trim()); |
| 139 | } |
| 140 | |
| 141 | let explicit = |
| 142 | SkillInvocation::from_frontmatter(metadata.get("invocation").map(String::as_str)) |
| 143 | == SkillInvocation::ExplicitOnly; |
| 144 | let model_allowed = !explicit |
| 145 | && metadata |
| 146 | .get("allow_implicit_invocation") |
| 147 | .is_none_or(|value| parse_frontmatter_bool(value) == Some(true)) |
| 148 | && metadata |
| 149 | .get("explicit_only") |
| 150 | .is_none_or(|value| parse_frontmatter_bool(value) == Some(false)) |
| 151 | && metadata |
| 152 | .get("disable-model-invocation") |
| 153 | .is_none_or(|value| parse_frontmatter_bool(value) == Some(false)); |
| 154 | let user_allowed = metadata |
| 155 | .get("user-invocable") |
| 156 | .is_none_or(|value| parse_frontmatter_bool(value) == Some(true)); |
| 157 | let invocation = match (model_allowed, user_allowed) { |
| 158 | (true, true) => SkillInvocation::ModelAndUser, |
| 159 | (false, true) => SkillInvocation::ExplicitOnly, |
| 160 | (true, false) => SkillInvocation::ModelOnly, |
| 161 | (false, false) => SkillInvocation::Disabled, |
| 162 | }; |
| 163 | let aliases = metadata |
| 164 | .get("aliases-for") |
| 165 | .into_iter() |
| 166 | .flat_map(|value| value.split([',', ' ', '\t'])) |
| 167 | .map(str::trim) |
| 168 | .filter(|alias| !alias.is_empty()) |
| 169 | .map(normalize_skill_name_for_lookup) |
| 170 | .filter(|alias| is_valid_skill_name(alias)) |
| 171 | .collect(); |
| 172 | |
| 173 | // Collect `description_<tag>:` frontmatter keys (already lowercased |
| 174 | // above) into locale-specific descriptions, e.g. `description_zh`. |
| 175 | let localized_descriptions = metadata |
| 176 | .iter() |
| 177 | .filter_map(|(key, value)| { |
| 178 | key.strip_prefix("description_") |
| 179 | .filter(|tag| !tag.is_empty()) |
| 180 | .map(|tag| (tag.to_string(), value.clone())) |
| 181 | }) |
| 182 | .collect(); |
| 183 | |
| 184 | return Ok(( |
| 185 | ParsedSkill { |
| 186 | name, |
| 187 | legacy_activation_name: None, |
| 188 | description, |
| 189 | localized_descriptions, |
| 190 | invocation, |
| 191 | aliases, |
| 192 | argument_hint: metadata |
| 193 | .get("argument-hint") |
| 194 | .filter(|value| !value.trim().is_empty()) |
| 195 | .cloned(), |
| 196 | body: body.trim().to_string(), |
| 197 | // Filled in by `discover` after parse succeeds; default to an |
| 198 | // empty path so direct constructors (e.g. tests) compile. |
| 199 | path: PathBuf::new(), |
| 200 | }, |
| 201 | warnings, |
| 202 | )); |
| 203 | } |
| 204 | |
| 205 | // Graceful degradation: no frontmatter fence found. |
| 206 | // Extract the first `# Heading` as the skill name. |
| 207 | let heading_re = regex::Regex::new(r"(?m)^#\s+(.+)$").expect("static regex is valid"); |
| 208 | let name = heading_re |
| 209 | .captures(content) |
| 210 | .and_then(|c| c.get(1)) |
| 211 | .map(|m| m.as_str().trim().to_string()) |
| 212 | .filter(|s| !s.is_empty()) |
| 213 | .ok_or_else(|| { |
| 214 | "no frontmatter and no `# Heading` found to use as skill name".to_string() |
| 215 | })?; |
| 216 | |
| 217 | Ok(( |
| 218 | ParsedSkill { |
| 219 | name, |
| 220 | legacy_activation_name: None, |
| 221 | description: String::new(), |
| 222 | localized_descriptions: HashMap::new(), |
| 223 | invocation: SkillInvocation::ModelAndUser, |
| 224 | aliases: Vec::new(), |
| 225 | argument_hint: None, |
| 226 | body: content.trim().to_string(), |
| 227 | path: PathBuf::new(), |
| 228 | }, |
| 229 | warnings, |
| 230 | )) |
| 231 | } |
| 232 | |
| 233 | pub fn is_valid_skill_name(name: &str) -> bool { |
| 234 | let char_count = name.chars().count(); |
| 235 | char_count > 0 |
| 236 | && char_count <= MAX_SKILL_NAME_CHARS |
| 237 | && name |
| 238 | .chars() |
| 239 | .next() |
| 240 | .is_some_and(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit()) |
| 241 | && name |
| 242 | .chars() |
| 243 | .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-') |
| 244 | } |
| 245 | |
| 246 | pub fn normalize_skill_name_for_lookup(name: &str) -> String { |
| 247 | normalize_qualified_skill_name(name, normalize_skill_name_segment) |
| 248 | } |
| 249 | |
| 250 | fn legacy_skill_name_for_lookup(name: &str) -> String { |
| 251 | normalize_qualified_skill_name(name, legacy_skill_name_segment) |
| 252 | } |
| 253 | |
| 254 | fn normalize_qualified_skill_name(name: &str, segment: fn(&str) -> String) -> String { |
| 255 | if let Some((plugin, skill)) = name.trim().split_once(':') |
| 256 | && !plugin.is_empty() |
| 257 | && !skill.is_empty() |
| 258 | && !skill.contains(':') |
| 259 | { |
| 260 | return format!("{}:{}", segment(plugin), segment(skill)); |
| 261 | } |
| 262 | segment(name) |
| 263 | } |
| 264 | |
| 265 | pub fn normalize_skill_name_segment(name: &str) -> String { |
| 266 | let name = name.trim(); |
| 267 | let legacy = legacy_skill_name_segment(name); |
| 268 | if name.is_ascii() { |
| 269 | return legacy; |
| 270 | } |
| 271 | // Preserve ASCII identities, but distinguish UTF-8 source names the old |
| 272 | // slug folded together. No transliteration or Unicode normalization. |
| 273 | let digest = crate::install::sha256_hex(name.to_ascii_lowercase().as_bytes()); |
| 274 | let prefix = legacy[..legacy.len().min(31)].trim_end_matches('-'); |
| 275 | format!("{prefix}-{}", &digest[..32]) |
| 276 | } |
| 277 | |
| 278 | fn legacy_skill_name_segment(name: &str) -> String { |
| 279 | let mut out = String::new(); |
| 280 | let mut pending_dash = false; |
| 281 | |
| 282 | for ch in name.trim().chars() { |
| 283 | if ch.is_ascii_alphanumeric() { |
| 284 | if pending_dash && !out.is_empty() && out.len() < MAX_SKILL_NAME_CHARS { |
| 285 | out.push('-'); |
| 286 | } |
| 287 | pending_dash = false; |
| 288 | if out.len() < MAX_SKILL_NAME_CHARS { |
| 289 | out.push(ch.to_ascii_lowercase()); |
| 290 | } |
| 291 | } else { |
| 292 | pending_dash = true; |
| 293 | } |
| 294 | |
| 295 | if out.len() >= MAX_SKILL_NAME_CHARS { |
| 296 | break; |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | while out.ends_with('-') { |
| 301 | out.pop(); |
| 302 | } |
| 303 | |
| 304 | if out.is_empty() { |
| 305 | "skill".to_string() |
| 306 | } else { |
| 307 | out |
| 308 | } |
| 309 | } |
| 310 |