1use std::path::{Component, Path, PathBuf};
4use std::sync::{Arc, LazyLock};
5
6use futures::future::BoxFuture;
7use regex::Regex;
8use yaml_rust2::{Yaml, YamlLoader};
9
10use crate::error::{Error, Result};
11use crate::models::is_js_whitespace;
12use crate::types::{JsonObject, JsonValue};
13
14static SKILL_NAME_PATTERN: LazyLock<Option<Regex>> =
15 LazyLock::new(|| Regex::new(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$").ok());
16static YAML_KEY_VALUE_LINE: LazyLock<Option<Regex>> =
17 LazyLock::new(|| Regex::new(r"^(\s*[A-Za-z0-9_][A-Za-z0-9_-]*):\s+([^\n\r\u{2028}\u{2029}]+)$").ok());
18
19const MAX_SKILL_NAME_LENGTH: usize = 64;
20const SKILL_MD_NAMES: [&str; 2] = ["SKILL.md", "skill.md"];
21
22#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
36pub struct SkillConfig {
37 #[builder(into)]
39 pub name: String,
40 #[builder(into)]
42 pub description: String,
43 #[builder(into)]
45 pub instructions: Option<String>,
46 #[builder(into)]
48 pub path: Option<String>,
49 pub allowed_tools: Option<Vec<String>>,
51 pub metadata: Option<JsonObject>,
53 #[builder(into)]
55 pub license: Option<String>,
56 #[builder(into)]
58 pub compatibility: Option<String>,
59}
60
61#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bon::Builder)]
63pub struct SkillLoadOptions {
64 #[builder(default)]
66 pub strict: bool,
67}
68
69impl SkillLoadOptions {
70 #[must_use]
72 pub fn strict() -> Self {
73 Self { strict: true }
74 }
75}
76
77#[derive(Debug, Clone, PartialEq)]
96pub struct Skill {
97 name: String,
98 description: String,
99 instructions: String,
100 path: Option<String>,
101 allowed_tools: Option<Vec<String>>,
102 metadata: JsonObject,
103 license: Option<String>,
104 compatibility: Option<String>,
105}
106
107impl From<SkillConfig> for Skill {
108 fn from(config: SkillConfig) -> Self {
109 Self::new(config)
110 }
111}
112
113impl Skill {
114 #[must_use]
116 pub fn new(config: SkillConfig) -> Self {
117 Self {
118 name: config.name,
119 description: config.description,
120 instructions: config.instructions.unwrap_or_default(),
121 path: config.path,
122 allowed_tools: config.allowed_tools,
123 metadata: config.metadata.unwrap_or_default(),
124 license: config.license,
125 compatibility: config.compatibility,
126 }
127 }
128
129 #[must_use]
131 pub fn name(&self) -> &str {
132 &self.name
133 }
134
135 #[must_use]
137 pub fn description(&self) -> &str {
138 &self.description
139 }
140
141 #[must_use]
143 pub fn instructions(&self) -> &str {
144 &self.instructions
145 }
146
147 #[must_use]
149 pub fn path(&self) -> Option<&str> {
150 self.path.as_deref()
151 }
152
153 #[must_use]
155 pub fn allowed_tools(&self) -> Option<&[String]> {
156 self.allowed_tools.as_deref()
157 }
158
159 #[must_use]
161 pub fn metadata(&self) -> &JsonObject {
162 &self.metadata
163 }
164
165 #[must_use]
167 pub fn license(&self) -> Option<&str> {
168 self.license.as_deref()
169 }
170
171 #[must_use]
173 pub fn compatibility(&self) -> Option<&str> {
174 self.compatibility.as_deref()
175 }
176
177 pub fn from_file(skill_path: impl AsRef<Path>, options: SkillLoadOptions) -> Result<Self> {
186 let resolved = resolve_path(skill_path.as_ref());
187 let is_skill_md = resolved
188 .file_name()
189 .is_some_and(|name| name.to_string_lossy().to_lowercase() == "skill.md");
190 let (skill_md, skill_dir) = if resolved.is_file() && is_skill_md {
191 let dir = resolved.parent().map(Path::to_path_buf).unwrap_or_default();
192 (resolved, dir)
193 } else if resolved.is_dir() {
194 (find_skill_md(&resolved)?, resolved)
195 } else {
196 return Err(Error::other(format!(
197 "path=<{}> | skill path does not exist or is not a valid skill directory",
198 resolved.display()
199 )));
200 };
201
202 tracing::debug!("path=<{}> | loading skill", skill_md.display());
203 let content = std::fs::read_to_string(&skill_md)?;
204 let skill = Self::from_content_at(&content, options, Some(skill_dir.to_string_lossy().into_owned()))?;
205 tracing::debug!(
206 "name=<{}>, path=<{}> | skill loaded successfully",
207 skill.name,
208 skill.path.as_deref().unwrap_or_default()
209 );
210 Ok(skill)
211 }
212
213 pub fn from_content(content: &str, options: SkillLoadOptions) -> Result<Self> {
223 Self::from_content_at(content, options, None)
224 }
225
226 pub(crate) fn from_content_at(content: &str, options: SkillLoadOptions, path: Option<String>) -> Result<Self> {
229 let (frontmatter, body) = parse_frontmatter(content)?;
230 let Some(name) = non_empty_string(frontmatter.get("name")) else {
231 return Err(Error::other("SKILL.md content must have a 'name' field in frontmatter"));
232 };
233 if non_empty_string(frontmatter.get("description")).is_none() {
234 return Err(Error::other(
235 "SKILL.md content must have a 'description' field in frontmatter",
236 ));
237 }
238 validate_skill_name(name, path.as_deref(), options.strict)?;
239 Ok(build_skill_from_frontmatter(&frontmatter, body, path))
240 }
241
242 pub async fn from_url(url: &str, options: SkillLoadOptions) -> Result<Self> {
252 Self::from_url_with(url, options, &UrlFetcher::default()).await
253 }
254
255 pub(crate) async fn from_url_with(url: &str, options: SkillLoadOptions, fetcher: &UrlFetcher) -> Result<Self> {
256 if !url.starts_with("https://") {
257 return Err(Error::other(format!("url=<{url}> | not a valid HTTPS URL")));
258 }
259 tracing::info!("url=<{url}> | fetching skill content");
260 let content = match fetcher.fetch(url.to_owned()).await {
261 Ok(content) => content,
262 Err(FetchError::Status { status, status_text }) => {
263 return Err(Error::other(format!("url=<{url}> | HTTP {status}: {status_text}")));
264 }
265 Err(FetchError::Failed(message)) => {
266 return Err(Error::other(format!("url=<{url}> | failed to fetch skill: {message}")));
267 }
268 };
269 Self::from_content(&content, options)
270 }
271
272 pub fn from_directory(skills_dir: impl AsRef<Path>, options: SkillLoadOptions) -> Result<Vec<Self>> {
281 let resolved = resolve_path(skills_dir.as_ref());
282 if !resolved.is_dir() {
283 return Err(Error::other(format!(
284 "path=<{}> | skills directory does not exist",
285 resolved.display()
286 )));
287 }
288 let mut children = std::fs::read_dir(&resolved)?
289 .filter_map(|entry| entry.ok().map(|entry| entry.file_name().to_string_lossy().into_owned()))
290 .collect::<Vec<_>>();
291 crate::storage::sort_keys(&mut children);
292
293 let mut skills = Vec::new();
294 for child in children {
295 let child_path = resolved.join(&child);
296 if !child_path.is_dir() {
297 continue;
298 }
299 if find_skill_md(&child_path).is_err() {
300 tracing::debug!("path=<{}> | skipping directory without SKILL.md", child_path.display());
301 continue;
302 }
303 match Self::from_file(&child_path, options) {
304 Ok(skill) => skills.push(skill),
305 Err(error) => tracing::warn!(
306 "path=<{}> | skipping skill due to error: Error: {error}",
307 child_path.display()
308 ),
309 }
310 }
311 tracing::debug!(
312 "path=<{}>, count=<{}> | loaded skills from directory",
313 resolved.display(),
314 skills.len()
315 );
316 Ok(skills)
317 }
318}
319
320#[derive(Debug, Clone, PartialEq, Eq)]
322pub(crate) enum FetchError {
323 Status { status: u16, status_text: String },
325 Failed(String),
327}
328
329type FetchFn = dyn Fn(String) -> BoxFuture<'static, std::result::Result<String, FetchError>> + Send + Sync;
330
331#[derive(Clone)]
333pub(crate) struct UrlFetcher(Arc<FetchFn>);
334
335impl UrlFetcher {
336 #[cfg(test)]
337 pub(crate) fn new(
338 fetch: impl Fn(String) -> BoxFuture<'static, std::result::Result<String, FetchError>> + Send + Sync + 'static,
339 ) -> Self {
340 Self(Arc::new(fetch))
341 }
342
343 pub(crate) fn fetch(&self, url: String) -> BoxFuture<'static, std::result::Result<String, FetchError>> {
344 (self.0)(url)
345 }
346}
347
348impl Default for UrlFetcher {
349 fn default() -> Self {
350 Self(Arc::new(|url| Box::pin(http_get_text(url))))
351 }
352}
353
354impl std::fmt::Debug for UrlFetcher {
355 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
356 f.write_str("UrlFetcher")
357 }
358}
359
360async fn http_get_text(url: String) -> std::result::Result<String, FetchError> {
361 const SKILL_HTTPS_FETCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
362 let client = reqwest::Client::builder()
363 .timeout(SKILL_HTTPS_FETCH_TIMEOUT)
364 .build()
365 .map_err(|error| FetchError::Failed(error.to_string()))?;
366 let response = client
367 .get(&url)
368 .header(reqwest::header::USER_AGENT, "strands-agents-sdk")
369 .send()
370 .await
371 .map_err(|error| FetchError::Failed(error.to_string()))?;
372 let status = response.status();
373 if !status.is_success() {
374 return Err(FetchError::Status {
375 status: status.as_u16(),
376 status_text: status.canonical_reason().unwrap_or_default().to_owned(),
377 });
378 }
379 response
380 .text()
381 .await
382 .map_err(|error| FetchError::Failed(error.to_string()))
383}
384
385fn resolve_path(path: &Path) -> PathBuf {
387 let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
388 let mut resolved = PathBuf::new();
389 for component in absolute.components() {
390 match component {
391 Component::CurDir => {}
392 Component::ParentDir => {
393 resolved.pop();
394 }
395 other => resolved.push(other),
396 }
397 }
398 resolved
399}
400
401fn find_skill_md(skill_dir: &Path) -> Result<PathBuf> {
403 SKILL_MD_NAMES
404 .iter()
405 .map(|name| skill_dir.join(name))
406 .find(|candidate| candidate.is_file())
407 .ok_or_else(|| {
408 Error::other(format!(
409 "path=<{}> | no SKILL.md found in skill directory",
410 skill_dir.display()
411 ))
412 })
413}
414
415fn js_trim(text: &str) -> &str {
416 text.trim_matches(is_js_whitespace)
417}
418
419fn is_line_terminator(c: char) -> bool {
420 matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}')
421}
422
423fn find_closing_delimiter(rest: &str) -> Option<(usize, usize)> {
426 rest.match_indices("\n---").find_map(|(start, _)| {
427 let after = start + "\n---".len();
428 let line_end = rest[after..]
429 .find(is_line_terminator)
430 .map_or(rest.len(), |offset| after + offset);
431 rest[after..line_end]
432 .chars()
433 .all(is_js_whitespace)
434 .then_some((start, after))
435 })
436}
437
438fn parse_frontmatter(content: &str) -> Result<(JsonObject, String)> {
440 let stripped = js_trim(content);
441 let Some(rest) = stripped.strip_prefix("---") else {
442 return Err(Error::other("SKILL.md must start with --- frontmatter delimiter"));
443 };
444 let Some((start, after)) = find_closing_delimiter(rest) else {
445 return Err(Error::other("SKILL.md frontmatter missing closing --- delimiter"));
446 };
447 let frontmatter_text = js_trim(&rest[..start]);
448 let body = js_trim(&rest[after..]).to_owned();
449
450 let parsed = match parse_yaml(frontmatter_text) {
451 Ok(parsed) => parsed,
452 Err(_) => {
453 tracing::warn!("YAML parse failed, retrying with colon-quoting fallback");
454 parse_yaml(&fix_yaml_colons(frontmatter_text))?
455 }
456 };
457 let frontmatter = match parsed {
458 JsonValue::Object(map) => map,
459 _ => JsonObject::new(),
460 };
461 Ok((frontmatter, body))
462}
463
464fn parse_yaml(text: &str) -> Result<JsonValue> {
467 let mut documents = YamlLoader::load_from_str(text).map_err(|error| Error::other(error.to_string()))?;
468 if documents.len() > 1 {
469 return Err(Error::other(
470 "Source contains multiple documents; please use YAML.parseAllDocuments()",
471 ));
472 }
473 Ok(documents.pop().map_or(JsonValue::Null, yaml_to_json))
474}
475
476fn yaml_to_json(yaml: Yaml) -> JsonValue {
477 match yaml {
478 Yaml::String(text) => JsonValue::String(text),
479 Yaml::Integer(number) => JsonValue::from(number),
480 Yaml::Real(text) => yaml_real(&text),
481 Yaml::Boolean(flag) => JsonValue::Bool(flag),
482 Yaml::Array(items) => JsonValue::Array(items.into_iter().map(yaml_to_json).collect()),
483 Yaml::Hash(entries) => JsonValue::Object(
484 entries
485 .into_iter()
486 .map(|(key, value)| (yaml_key(key), yaml_to_json(value)))
487 .collect(),
488 ),
489 Yaml::Null | Yaml::Alias(_) | Yaml::BadValue => JsonValue::Null,
490 }
491}
492
493fn yaml_real(text: &str) -> JsonValue {
495 Yaml::Real(text.to_owned())
496 .as_f64()
497 .and_then(serde_json::Number::from_f64)
498 .map_or(JsonValue::Null, JsonValue::Number)
499}
500
501fn yaml_key(key: Yaml) -> String {
504 match yaml_to_json(key) {
505 JsonValue::String(text) => text,
506 JsonValue::Null => String::new(),
507 other => js_string(&other),
508 }
509}
510
511fn fix_yaml_colons(yaml: &str) -> String {
514 let Some(pattern) = YAML_KEY_VALUE_LINE.as_ref() else {
515 return yaml.to_owned();
516 };
517 yaml.split('\n')
518 .map(|line| {
519 let Some(captures) = pattern.captures(line) else {
520 return line.to_owned();
521 };
522 let (key, value) = (&captures[1], &captures[2]);
523 if !value.contains(':') || value.starts_with('"') || value.starts_with('\'') {
524 return line.to_owned();
525 }
526 let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
527 format!("{key}: \"{escaped}\"")
528 })
529 .collect::<Vec<_>>()
530 .join("\n")
531}
532
533fn js_string(value: &JsonValue) -> String {
536 const MAX_PLAIN_INTEGER: f64 = 1e21;
537 match value {
538 JsonValue::String(text) => text.clone(),
539 JsonValue::Null => "null".to_owned(),
540 JsonValue::Bool(flag) => flag.to_string(),
541 JsonValue::Number(number) => match number.as_f64() {
542 Some(float) if number.is_f64() && float.fract() == 0.0 && float.abs() < MAX_PLAIN_INTEGER => {
543 format!("{float:.0}")
544 }
545 _ => number.to_string(),
546 },
547 JsonValue::Array(items) => items
548 .iter()
549 .map(|item| if item.is_null() { String::new() } else { js_string(item) })
550 .collect::<Vec<_>>()
551 .join(","),
552 JsonValue::Object(_) => "[object Object]".to_owned(),
553 }
554}
555
556fn non_empty_string(value: Option<&JsonValue>) -> Option<&str> {
557 value.and_then(JsonValue::as_str).filter(|text| !text.is_empty())
558}
559
560fn basename(path: &str) -> &str {
562 let is_separator = |c: char| c == '/' || (cfg!(windows) && c == '\\');
563 let trimmed = path.trim_end_matches(is_separator);
564 trimmed.rsplit(is_separator).next().unwrap_or(trimmed)
565}
566
567fn validate_skill_name(name: &str, dir_path: Option<&str>, strict: bool) -> Result<()> {
570 if name.is_empty() {
571 return Err(Error::other("Skill name cannot be empty"));
572 }
573 let report = |message: String| -> Result<()> {
574 if strict {
575 return Err(Error::other(message));
576 }
577 tracing::warn!("{message}");
578 Ok(())
579 };
580 if name.encode_utf16().count() > MAX_SKILL_NAME_LENGTH {
581 report(format!(
582 "name=<{name}> | skill name exceeds {MAX_SKILL_NAME_LENGTH} character limit"
583 ))?;
584 }
585 let matches_pattern = SKILL_NAME_PATTERN
586 .as_ref()
587 .is_some_and(|pattern| pattern.is_match(name));
588 if !matches_pattern {
589 report(format!(
590 "name=<{name}> | skill name should be 1-64 lowercase alphanumeric characters or hyphens, should not start/end with hyphen"
591 ))?;
592 }
593 if name.contains("--") {
594 report(format!("name=<{name}> | skill name contains consecutive hyphens"))?;
595 }
596 if let Some(dir_path) = dir_path {
597 let directory = basename(dir_path);
598 if directory != name {
599 report(format!(
600 "name=<{name}>, directory=<{directory}> | skill name does not match parent directory name"
601 ))?;
602 }
603 }
604 Ok(())
605}
606
607fn build_skill_from_frontmatter(frontmatter: &JsonObject, body: String, path: Option<String>) -> Skill {
609 let allowed_tools = match frontmatter
610 .get("allowed-tools")
611 .or_else(|| frontmatter.get("allowed_tools"))
612 {
613 Some(JsonValue::String(text)) if !js_trim(text).is_empty() => Some(
614 js_trim(text)
615 .split(is_js_whitespace)
616 .filter(|item| !item.is_empty())
617 .map(str::to_owned)
618 .collect(),
619 ),
620 Some(JsonValue::Array(items)) => Some(items.iter().filter(|item| !item.is_null()).map(js_string).collect()),
621 _ => None,
622 };
623 let metadata = match frontmatter.get("metadata") {
624 Some(JsonValue::Object(map)) => map.clone(),
625 _ => JsonObject::new(),
626 };
627 let optional_string = |key: &str| frontmatter.get(key).filter(|value| !value.is_null()).map(js_string);
628 Skill {
629 name: frontmatter
630 .get("name")
631 .and_then(JsonValue::as_str)
632 .unwrap_or_default()
633 .to_owned(),
634 description: frontmatter
635 .get("description")
636 .and_then(JsonValue::as_str)
637 .unwrap_or_default()
638 .to_owned(),
639 instructions: body,
640 path,
641 allowed_tools,
642 metadata,
643 license: optional_string("license"),
644 compatibility: optional_string("compatibility"),
645 }
646}
647
648#[cfg(test)]
649mod tests;