skills: skill tool, YAML frontmatter, disable-model-invocation, argument-hint
This commit is contained in:
1 parent
7e29515821
commit
199f337662
12 files changed
+328
-121
No files matched your search
@@ -27,6 +27,8 @@ pub struct CmdSpec {
|
||||
pub summary: String,
|
||||
pub source: Source,
|
||||
pub args: ArgKind,
|
||||
/// `argument-hint:` of a skill, shown as `/name <hint>`.
|
||||
pub hint: Option<String>,
|
||||
}
|
||||
|
||||
impl CmdSpec {
|
||||
@@ -36,6 +38,7 @@ impl CmdSpec {
|
||||
summary: summary.into(),
|
||||
source,
|
||||
args,
|
||||
hint: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,21 +111,24 @@ pub fn skill_specs(skills: &[Skill], taken: &[CmdSpec]) -> Vec<CmdSpec> {
|
||||
summary: s.description.clone(),
|
||||
source: Source::Skill(s.path.clone()),
|
||||
args: ArgKind::Free,
|
||||
hint: s.hint.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The prompt a `/<skill> args` command sends.
|
||||
/// The prompt a `/<skill> args` command sends: base dir line + body (no frontmatter), then the args.
|
||||
pub fn skill_prompt(name: &str, path: &std::path::Path, arg: &str) -> std::io::Result<String> {
|
||||
let body = std::fs::read_to_string(path)?;
|
||||
let raw = std::fs::read_to_string(path)?;
|
||||
let sk = crate::context::parse_skill(path, &raw)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||
let ask = if arg.is_empty() {
|
||||
"Apply this skill."
|
||||
} else {
|
||||
arg
|
||||
};
|
||||
Ok(format!(
|
||||
"<skill name=\"{name}\" path=\"{}\">\n{body}\n</skill>\n\n{ask}",
|
||||
path.display()
|
||||
"<skill name=\"{name}\">\n{}\n</skill>\n\n{ask}",
|
||||
sk.text()
|
||||
))
|
||||
}
|
||||
|
||||
@@ -131,10 +137,11 @@ pub fn help(specs: &[CmdSpec]) -> String {
|
||||
specs
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let arg = match &s.args {
|
||||
ArgKind::None => "",
|
||||
ArgKind::Path => " <path>",
|
||||
_ => " [args]",
|
||||
let arg = match (&s.hint, &s.args) {
|
||||
(Some(h), _) => format!(" {h}"),
|
||||
(_, ArgKind::None) => String::new(),
|
||||
(_, ArgKind::Path) => " <path>".into(),
|
||||
_ => " [args]".into(),
|
||||
};
|
||||
format!("/{}{arg} — {}", s.name, s.summary)
|
||||
})
|
||||
@@ -217,7 +224,10 @@ fn detail(s: &CmdSpec) -> String {
|
||||
Source::Mcp => "mcp · ",
|
||||
Source::Ext => "ext · ",
|
||||
};
|
||||
format!("{tag}{}", s.summary)
|
||||
match &s.hint {
|
||||
Some(h) => format!("{tag}{h} {}", s.summary),
|
||||
None => format!("{tag}{}", s.summary),
|
||||
}
|
||||
}
|
||||
|
||||
fn floor_boundary(s: &str, mut i: usize) -> usize {
|
||||
@@ -349,6 +359,7 @@ mod tests {
|
||||
|
||||
let p = skill_prompt("review", &skills[1].path, "PR 7").unwrap();
|
||||
assert!(p.contains("REVIEW BODY") && p.ends_with("PR 7"), "{p}");
|
||||
assert!(p.contains("Base directory for this skill:") && !p.contains("description:"));
|
||||
let h = help(&specs);
|
||||
assert!(h.contains("/model [args] — show or switch model") && h.contains("/review"));
|
||||
}
|
||||
|
||||
+184
-97
@@ -46,13 +46,34 @@ pub struct Skill {
|
||||
pub description: String,
|
||||
pub path: PathBuf,
|
||||
pub load: Load,
|
||||
/// False (`disable-model-invocation: true` or `load: manual`): not in the prompt index, the
|
||||
/// `skill` tool refuses it; only the user's `/<name>` reaches it.
|
||||
pub model_invocable: bool,
|
||||
/// `argument-hint:` shown next to `/<name>`.
|
||||
pub hint: Option<String>,
|
||||
/// Text after the frontmatter.
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
/// Frontmatter `load:` key. `auto` (default): name + description in the system prompt, the model reads
|
||||
/// the file when the task matches. `always`: the body is inlined in the system prompt. `manual`: only
|
||||
/// reachable as a `/<name>` command, never mentioned to the model.
|
||||
impl Skill {
|
||||
/// Skill directory (holds `SKILL.md` and its helper files).
|
||||
pub fn dir(&self) -> &Path {
|
||||
self.path.parent().unwrap_or(Path::new(""))
|
||||
}
|
||||
|
||||
/// What the model or a `/<name>` command receives: base dir line + body, no frontmatter.
|
||||
pub fn text(&self) -> String {
|
||||
format!(
|
||||
"Base directory for this skill: {}\n\n{}",
|
||||
self.dir().display(),
|
||||
self.body
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Frontmatter `load:` key. `auto` (default): name + description in the system prompt, the model calls
|
||||
/// the `skill` tool when the task matches. `always`: the body is inlined in the system prompt. `manual`:
|
||||
/// alias for `disable-model-invocation: true`, only reachable as a `/<name>` command.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub enum Load {
|
||||
#[default]
|
||||
@@ -61,16 +82,30 @@ pub enum Load {
|
||||
Manual,
|
||||
}
|
||||
|
||||
/// Skill dirs, lowest priority first: `~/.agents/skills` (shared with other agents), `<hx home>/skills`,
|
||||
/// `<project>/.agents/skills`, `<project>/.hx/skills`.
|
||||
/// Known frontmatter keys; everything else (`license`, ...) is ignored.
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
struct Front {
|
||||
name: Option<String>,
|
||||
description: Option<String>,
|
||||
load: Option<String>,
|
||||
#[serde(rename = "disable-model-invocation")]
|
||||
disable_model_invocation: Option<bool>,
|
||||
#[serde(rename = "argument-hint")]
|
||||
argument_hint: Option<String>,
|
||||
}
|
||||
|
||||
/// Skill dirs, lowest priority first: `~/.claude/skills`, `~/.agents/skills` (shared with other agents),
|
||||
/// `<hx home>/skills`, `<project>/.agents/skills`, `<project>/.claude/skills`, `<project>/.hx/skills`.
|
||||
pub fn skill_dirs(home: &Path, cwd: &Path) -> Vec<PathBuf> {
|
||||
let mut v: Vec<PathBuf> = std::env::var_os("HOME")
|
||||
.map(|h| PathBuf::from(h).join(".agents/skills"))
|
||||
.into_iter()
|
||||
let user = std::env::var_os("HOME").map(PathBuf::from);
|
||||
let mut v: Vec<PathBuf> = user
|
||||
.iter()
|
||||
.flat_map(|h| [h.join(".claude/skills"), h.join(".agents/skills")])
|
||||
.collect();
|
||||
v.extend([
|
||||
home.join("skills"),
|
||||
cwd.join(".agents/skills"),
|
||||
cwd.join(".claude/skills"),
|
||||
cwd.join(".hx/skills"),
|
||||
]);
|
||||
v
|
||||
@@ -80,9 +115,56 @@ pub fn skills(home: &Path, cwd: &Path) -> Vec<Skill> {
|
||||
skills_in(&skill_dirs(home, cwd))
|
||||
}
|
||||
|
||||
/// `<dir>/<name>/SKILL.md` with `name:` / `description:` frontmatter. Later dirs override earlier ones by name.
|
||||
pub fn skills_in(dirs: &[PathBuf]) -> Vec<Skill> {
|
||||
scan_skills(dirs).0
|
||||
}
|
||||
|
||||
/// Parse one `SKILL.md`. Err: the frontmatter is not valid YAML.
|
||||
pub fn parse_skill(p: &Path, s: &str) -> Result<Skill, String> {
|
||||
let (fm, body) = s
|
||||
.strip_prefix("---")
|
||||
.and_then(|r| r.split_once("\n---"))
|
||||
.map_or(("", s), |(f, b)| {
|
||||
(f, b.split_once('\n').map_or("", |x| x.1))
|
||||
});
|
||||
let f: Front = if fm.trim().is_empty() {
|
||||
Front::default()
|
||||
} else {
|
||||
serde_norway::from_str(fm).map_err(|e| e.to_string())?
|
||||
};
|
||||
let load = match f.load.as_deref() {
|
||||
Some("always") => Load::Always,
|
||||
Some("manual") => Load::Manual,
|
||||
_ => Load::Auto,
|
||||
};
|
||||
Ok(Skill {
|
||||
name: f.name.unwrap_or_else(|| {
|
||||
p.parent()
|
||||
.and_then(|d| d.file_name())
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.into()
|
||||
}),
|
||||
// folded (`>`) and literal (`|`) blocks become one line
|
||||
description: f
|
||||
.description
|
||||
.unwrap_or_default()
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
load,
|
||||
model_invocable: !f.disable_model_invocation.unwrap_or(false) && load != Load::Manual,
|
||||
hint: f.argument_hint.filter(|h| !h.trim().is_empty()),
|
||||
body: body.trim().to_string(),
|
||||
path: p.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `<dir>/<name>/SKILL.md`. Later dirs override earlier ones by name. Skills whose frontmatter does not
|
||||
/// parse are skipped and reported in the second value (shown by `/skills`).
|
||||
pub fn scan_skills(dirs: &[PathBuf]) -> (Vec<Skill>, Vec<String>) {
|
||||
let mut out: Vec<Skill> = vec![];
|
||||
let mut warn = vec![];
|
||||
for dir in dirs {
|
||||
let Ok(rd) = std::fs::read_dir(dir) else {
|
||||
continue;
|
||||
@@ -97,68 +179,21 @@ pub fn skills_in(dirs: &[PathBuf]) -> Vec<Skill> {
|
||||
let Ok(s) = std::fs::read_to_string(&p) else {
|
||||
continue;
|
||||
};
|
||||
let (fm, body) = s
|
||||
.strip_prefix("---")
|
||||
.and_then(|r| r.split_once("\n---"))
|
||||
.map_or(("", s.as_str()), |(f, b)| {
|
||||
(f, b.split_once('\n').map_or("", |x| x.1))
|
||||
});
|
||||
let get = |k: &str| {
|
||||
fm.lines().find_map(|l| {
|
||||
l.strip_prefix(k)?
|
||||
.strip_prefix(':')
|
||||
.map(|v| v.trim().trim_matches('"').to_string())
|
||||
})
|
||||
};
|
||||
let name = get("name").unwrap_or_else(|| {
|
||||
p.parent()
|
||||
.and_then(|d| d.file_name())
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.into()
|
||||
});
|
||||
let load = match get("load").as_deref() {
|
||||
Some("always") => Load::Always,
|
||||
Some("manual") => Load::Manual,
|
||||
_ => Load::Auto,
|
||||
};
|
||||
let sk = Skill {
|
||||
description: get("description").unwrap_or_default(),
|
||||
load,
|
||||
body: body.trim().to_string(),
|
||||
name,
|
||||
path: p,
|
||||
};
|
||||
out.retain(|x| x.name != sk.name);
|
||||
out.push(sk);
|
||||
match parse_skill(&p, &s) {
|
||||
Ok(sk) => {
|
||||
out.retain(|x| x.name != sk.name);
|
||||
out.push(sk);
|
||||
}
|
||||
Err(e) => warn.push(format!("{}: skipped, bad frontmatter: {e}", p.display())),
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
(out, warn)
|
||||
}
|
||||
|
||||
/// Index descriptions are cut here; the full text stays in the skill file the model reads on demand.
|
||||
// ponytail: fixed cap, not configurable; add a config key if someone needs longer index lines.
|
||||
const INDEX_DESC_CHARS: usize = 100;
|
||||
|
||||
/// Skill root directory: `<root>/<dir>/SKILL.md`.
|
||||
fn skill_root(k: &Skill) -> Option<&Path> {
|
||||
k.path.parent()?.parent()
|
||||
}
|
||||
|
||||
/// One system-prompt index line for an `auto` skill. The path is omitted when it is
|
||||
/// `<root>/<name>/SKILL.md` (the root is stated once in the group header).
|
||||
/// One system-prompt index line for an `auto` skill.
|
||||
pub fn skill_index_line(k: &Skill) -> String {
|
||||
let d = k.description.trim();
|
||||
let d = match d.char_indices().nth(INDEX_DESC_CHARS) {
|
||||
Some((i, _)) => format!("{}…", d[..i].trim_end()),
|
||||
None => d.to_string(),
|
||||
};
|
||||
let regular = skill_root(k).is_some_and(|r| k.path == r.join(&k.name).join("SKILL.md"));
|
||||
if regular {
|
||||
format!("- {}: {d}\n", k.name)
|
||||
} else {
|
||||
format!("- {}: {d} ({})\n", k.name, k.path.display())
|
||||
}
|
||||
format!("- {}: {}\n", k.name, k.description)
|
||||
}
|
||||
|
||||
pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> String {
|
||||
@@ -177,20 +212,14 @@ pub fn prompt_tail(home: &Path, cwd: &Path) -> String {
|
||||
for k in sk.iter().filter(|k| k.load == Load::Always) {
|
||||
s.push_str(&format!("\n\n# Skill: {}\n{}", k.name, k.body));
|
||||
}
|
||||
let auto: Vec<_> = sk.iter().filter(|k| k.load == Load::Auto).collect();
|
||||
let auto: Vec<_> = sk
|
||||
.iter()
|
||||
.filter(|k| k.load == Load::Auto && k.model_invocable)
|
||||
.collect();
|
||||
if !auto.is_empty() {
|
||||
s.push_str("\n\n# Skills\nRead a skill's file with `read` when the task matches it.\n");
|
||||
let mut roots: Vec<&Path> = vec![];
|
||||
for r in auto.iter().filter_map(|k| skill_root(k)) {
|
||||
if !roots.contains(&r) {
|
||||
roots.push(r);
|
||||
}
|
||||
}
|
||||
for r in roots {
|
||||
s.push_str(&format!("Skill file: {}/<name>/SKILL.md\n", r.display()));
|
||||
for k in auto.iter().filter(|k| skill_root(k) == Some(r)) {
|
||||
s.push_str(&skill_index_line(k));
|
||||
}
|
||||
s.push_str("\n\n# Skills\nCall the `skill` tool with the name when the task matches.\n");
|
||||
for k in auto {
|
||||
s.push_str(&skill_index_line(k));
|
||||
}
|
||||
}
|
||||
for (p, c) in context_files(home, cwd) {
|
||||
@@ -242,35 +271,87 @@ mod tests {
|
||||
);
|
||||
assert!(g < p && p < sub);
|
||||
assert!(!s.contains("IGNORED"));
|
||||
assert!(s.contains("- g: local") && !s.contains("global ("));
|
||||
assert!(s.contains("- g: local") && !s.contains("global"));
|
||||
assert!(!s.contains("BODY"), "skill body must load on demand only");
|
||||
assert!(system_prompt(Some("CUSTOM"), &home, &proj).starts_with("CUSTOM"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_line_caps_description() {
|
||||
fn index_line_is_full_description() {
|
||||
let k = Skill {
|
||||
name: "n".into(),
|
||||
description: "d".repeat(500),
|
||||
path: "/p/SKILL.md".into(),
|
||||
load: Load::Auto,
|
||||
model_invocable: true,
|
||||
hint: None,
|
||||
body: String::new(),
|
||||
};
|
||||
let l = skill_index_line(&k);
|
||||
assert_eq!(skill_index_line(&k), format!("- n: {}\n", "d".repeat(500)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frontmatter_yaml() {
|
||||
let p = Path::new("/r/n/SKILL.md");
|
||||
let k = parse_skill(
|
||||
p,
|
||||
"---\nname: n\ndescription: >\n line one\n line two\nlicense: MIT\noutput: x\nargument-hint: <pr>\ndisable-model-invocation: true\n---\nB\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(k.description, "line one line two");
|
||||
assert_eq!(k.hint.as_deref(), Some("<pr>"));
|
||||
assert!(!k.model_invocable && k.load == Load::Auto);
|
||||
let k = parse_skill(p, "---\nname: n\ndescription: |\n a\n b\n---\n").unwrap();
|
||||
assert_eq!(k.description, "a b");
|
||||
assert!(parse_skill(p, "---\ndescription: [oops\n---\nB").is_err());
|
||||
let k = parse_skill(p, "no frontmatter").unwrap();
|
||||
assert_eq!((k.name.as_str(), k.body.as_str()), ("n", "no frontmatter"));
|
||||
assert!(
|
||||
l.len() < 150 && l.contains('…') && l.ends_with("(/p/SKILL.md)\n"),
|
||||
"{l}"
|
||||
!parse_skill(
|
||||
p,
|
||||
"---
|
||||
load: manual
|
||||
---
|
||||
"
|
||||
)
|
||||
.unwrap()
|
||||
.model_invocable
|
||||
);
|
||||
let short = Skill {
|
||||
description: "short".into(),
|
||||
..k
|
||||
};
|
||||
assert_eq!(skill_index_line(&short), "- n: short (/p/SKILL.md)\n");
|
||||
let short = Skill {
|
||||
path: "/r/n/SKILL.md".into(),
|
||||
..short
|
||||
};
|
||||
assert_eq!(skill_index_line(&short), "- n: short\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_only_and_broken_skills() {
|
||||
let t = tempfile::tempdir().unwrap();
|
||||
for (n, fm) in [
|
||||
("ok", "description: fine"),
|
||||
("hid", "description: secret\ndisable-model-invocation: true"),
|
||||
("bad", "description: [oops"),
|
||||
] {
|
||||
let d = t.path().join("s").join(n);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
std::fs::write(d.join("SKILL.md"), format!("---\n{fm}\n---\nBODY-{n}\n")).unwrap();
|
||||
}
|
||||
let (sk, warn) = scan_skills(&[t.path().join("s")]);
|
||||
let names: Vec<_> = sk.iter().map(|k| k.name.as_str()).collect();
|
||||
assert_eq!(names, ["hid", "ok"]);
|
||||
assert!(
|
||||
warn.len() == 1 && warn[0].contains("bad/SKILL.md"),
|
||||
"{warn:?}"
|
||||
);
|
||||
let home = t.path().join("h");
|
||||
std::fs::create_dir_all(home.join("skills")).unwrap();
|
||||
for n in ["ok", "hid"] {
|
||||
let d = home.join("skills").join(n);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
std::fs::copy(
|
||||
t.path().join("s").join(n).join("SKILL.md"),
|
||||
d.join("SKILL.md"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let p = system_prompt(None, &home, &t.path().join("proj"));
|
||||
assert!(p.contains("- ok: fine") && !p.contains("secret"), "{p}");
|
||||
assert!(p.contains("Call the `skill` tool"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -338,10 +419,16 @@ mod tests {
|
||||
.collect();
|
||||
assert_eq!(got, [("a", "shared"), ("g", "hx-g")]);
|
||||
let d = skill_dirs(Path::new("/h"), Path::new("/p"));
|
||||
assert!(d[0].ends_with(".agents/skills"));
|
||||
assert!(d[0].ends_with(".claude/skills") && d[1].ends_with(".agents/skills"));
|
||||
assert_eq!(
|
||||
d[1..],
|
||||
["/h/skills", "/p/.agents/skills", "/p/.hx/skills"].map(PathBuf::from)
|
||||
d[2..],
|
||||
[
|
||||
"/h/skills",
|
||||
"/p/.agents/skills",
|
||||
"/p/.claude/skills",
|
||||
"/p/.hx/skills"
|
||||
]
|
||||
.map(PathBuf::from)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -228,7 +228,7 @@ impl Sub {
|
||||
|
||||
/// Tools of a read-only child. ponytail: `bash` can still write; the prompt forbids it. Drop
|
||||
/// `bash` for a search/grep tool if models ignore that.
|
||||
pub const EXPLORE_TOOLS: &[&str] = &["read", "lsp", "bash"];
|
||||
pub const EXPLORE_TOOLS: &[&str] = &["read", "lsp", "bash", "skill"];
|
||||
pub const EXPLORE_PROMPT: &str = "You are a research subagent of hx. Answer the task by reading code; do not modify anything (no writes, no redirects, no installs). Your final message is the only thing the caller sees: give the answer with file:line references, short, no preamble.";
|
||||
pub const GENERAL_PROMPT: &str = "You are a subagent of hx working in the user's repository. Do the task fully with the tools; read files before editing them. Your final message is the only thing the caller sees: say what you changed or found, short, with file paths.";
|
||||
const MAX_RESULT: usize = 8_000;
|
||||
|
||||
Reference in new issue
Block a user