use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::skill::{Skill, SkillParam};
mod frontmatter;
use frontmatter::split_frontmatter;
pub use frontmatter::{SkillArg, SkillFrontmatter, SkillScope};
#[derive(Debug)]
pub struct PromptSkill {
frontmatter: SkillFrontmatter,
content: String,
body: String,
skill_dir: Option<PathBuf>,
source_path: Option<PathBuf>,
static_name: &'static str,
static_version: &'static str,
static_category: &'static str,
static_author: &'static str,
static_tags: Vec<&'static str>,
static_allowed_tools: Vec<String>,
static_disallowed_tools: Vec<String>,
static_paths: Vec<String>,
}
impl PromptSkill {
pub fn from_markdown(content: &str) -> Result<Self, String> {
let (frontmatter_str, body) = split_frontmatter(content)?;
let frontmatter: SkillFrontmatter = serde_yaml::from_str(frontmatter_str)
.map_err(|e| format!("Frontmatter parse error: {e}"))?;
if frontmatter.name.is_empty() {
return Err("Skill name is empty".to_string());
}
if frontmatter.description.is_empty() {
return Err("Skill description is empty".to_string());
}
if !frontmatter
.name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
return Err(format!(
"Invalid skill name '{}': only alphanumeric, hyphens, and underscores allowed",
frontmatter.name
));
}
let static_name: &'static str = Box::leak(frontmatter.name.clone().into_boxed_str());
let static_version: &'static str = Box::leak(
frontmatter
.version
.clone()
.unwrap_or_else(|| "1.0".to_string())
.into_boxed_str(),
);
let static_category: &'static str =
Box::leak(frontmatter.category.clone().into_boxed_str());
let static_author: &'static str = Box::leak(
frontmatter
.author
.clone()
.unwrap_or_default()
.into_boxed_str(),
);
let static_tags: Vec<&'static str> = frontmatter
.tags
.iter()
.map(|t| Box::leak(t.clone().into_boxed_str()) as &'static str)
.collect();
let static_allowed_tools: Vec<String> = frontmatter.allowed_tools.clone();
let static_disallowed_tools: Vec<String> = frontmatter.disallowed_tools.clone();
let static_paths: Vec<String> = frontmatter.paths.clone();
Ok(Self {
frontmatter,
content: content.to_string(),
body: body.to_string(),
skill_dir: None,
source_path: None,
static_name,
static_version,
static_category,
static_author,
static_tags,
static_allowed_tools,
static_disallowed_tools,
static_paths,
})
}
pub fn frontmatter(&self) -> &SkillFrontmatter {
&self.frontmatter
}
pub fn scope(&self) -> SkillScope {
SkillScope::parse(self.frontmatter.scope.as_deref())
}
pub fn body(&self) -> &str {
&self.body
}
pub fn skill_dir_path(&self) -> Option<&Path> {
self.skill_dir.as_deref()
}
pub fn scripts_dir(&self) -> Option<PathBuf> {
self.skill_dir
.as_ref()
.map(|d| d.join("scripts"))
.filter(|p| p.is_dir())
}
pub fn references_dir(&self) -> Option<PathBuf> {
self.skill_dir
.as_ref()
.map(|d| d.join("references"))
.filter(|p| p.is_dir())
}
pub fn templates_dir(&self) -> Option<PathBuf> {
self.skill_dir
.as_ref()
.map(|d| d.join("templates"))
.filter(|p| p.is_dir())
}
pub fn from_dir(path: impl AsRef<Path>) -> Result<Self, String> {
let path = path.as_ref();
let skill_md = path.join("SKILL.md");
if !skill_md.exists() {
return Err(format!("SKILL.md not found in {}", path.display()));
}
let content = std::fs::read_to_string(&skill_md)
.map_err(|e| format!("Failed to read {}: {}", skill_md.display(), e))?;
let mut skill = Self::from_markdown(&content)?;
if let Some(dir_name) = path.file_name().and_then(|n| n.to_str())
&& dir_name != skill.frontmatter.name
{
return Err(format!(
"Directory name '{}' does not match skill name '{}'",
dir_name, skill.frontmatter.name
));
}
skill.skill_dir = Some(path.to_path_buf());
skill.source_path = Some(path.join("SKILL.md"));
Ok(skill)
}
pub fn scan_dir(path: impl AsRef<Path>) -> Result<Vec<Self>, String> {
let path = path.as_ref();
if !path.is_dir() {
return Ok(Vec::new());
}
let mut skills = Vec::new();
let entries = std::fs::read_dir(path)
.map_err(|e| format!("Failed to read directory {}: {}", path.display(), e))?;
for entry in entries {
let entry = match entry {
Ok(e) => e,
Err(_) => continue,
};
let entry_path = entry.path();
if entry_path
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.starts_with('_'))
{
continue;
}
if entry_path.is_dir() && entry_path.join("SKILL.md").exists() {
match Self::from_dir(&entry_path) {
Ok(skill) => skills.push(skill),
Err(e) => {
tracing::warn!(
dir = %entry_path.display(),
error = %e,
"skipping invalid skill directory"
);
}
}
}
}
skills.sort_by(|a, b| a.frontmatter.name.cmp(&b.frontmatter.name));
Ok(skills)
}
pub fn resolve_body(&self, params: &HashMap<String, String>, raw_arguments: &str) -> String {
let mut result = self.body.clone();
result = result.replace("$ARGUMENTS", raw_arguments);
if let Some(dir) = &self.skill_dir {
result = result.replace("$PHI_SKILL_DIR", &dir.to_string_lossy());
}
let mut sorted_keys: Vec<&String> = params.keys().collect();
sorted_keys.sort_by_key(|b| std::cmp::Reverse(b.len()));
for key in sorted_keys {
let value = ¶ms[key];
let placeholder = format!("${}", key);
result = result.replace(&placeholder, value);
}
result
}
}
impl Skill for PromptSkill {
fn name(&self) -> &'static str {
self.static_name
}
fn brief_description(&self) -> String {
self.frontmatter.description.clone()
}
fn detailed_description(&self) -> String {
self.content.clone()
}
fn tools(&self) -> Vec<Arc<dyn agent_base::Tool>> {
vec![]
}
fn parameters(&self) -> &[SkillParam] {
&[]
}
fn version(&self) -> &'static str {
self.static_version
}
fn tags(&self) -> &[&'static str] {
&self.static_tags
}
fn author(&self) -> &'static str {
self.static_author
}
fn category(&self) -> &'static str {
self.static_category
}
fn allowed_tools(&self) -> &[String] {
&self.static_allowed_tools
}
fn disallowed_tools(&self) -> &[String] {
&self.static_disallowed_tools
}
fn model_override(&self) -> Option<&str> {
self.frontmatter
.model
.as_deref()
.filter(|m| *m != "inherit")
}
fn is_user_invocable(&self) -> bool {
self.frontmatter.user_invocable
}
fn disable_model_invocation(&self) -> bool {
self.frontmatter.disable_model_invocation
}
fn context_mode(&self) -> Option<&str> {
self.frontmatter.context.as_deref()
}
fn path_patterns(&self) -> &[String] {
&self.static_paths
}
fn skill_dir(&self) -> Option<&Path> {
self.skill_dir.as_deref()
}
fn source_path(&self) -> Option<&Path> {
self.source_path.as_deref()
}
fn read_reference(&self, relative_path: &str) -> Result<String, String> {
let ref_dir = self.references_dir().ok_or_else(|| {
format!(
"Skill '{}' has no references/ directory",
self.frontmatter.name
)
})?;
let ref_dir_canon = ref_dir
.canonicalize()
.map_err(|e| format!("Failed to resolve references/ directory: {}", e))?;
let resolved = ref_dir.join(relative_path);
let canonical = resolved.canonicalize().map_err(|e| {
format!(
"Failed to resolve reference path '{}': {}",
relative_path, e
)
})?;
if !canonical.starts_with(&ref_dir_canon) {
return Err(format!(
"Path traversal denied: '{}' is outside references/",
relative_path
));
}
std::fs::read_to_string(&canonical)
.map_err(|e| format!("Failed to read reference '{}': {}", relative_path, e))
}
}
#[cfg(feature = "fuzzing")]
pub mod fuzz_exports {
pub fn split_frontmatter(content: &str) -> Result<(&str, &str), String> {
super::split_frontmatter(content)
}
}
#[cfg(test)]
mod tests;