skills: skill tool, YAML frontmatter, disable-model-invocation, argument-hint
This commit is contained in:
1 parent
7e29515821
commit
199f337662
12 files changed
+325
-118
No files matched your search
Generated
+20
@@ -1044,6 +1044,7 @@ dependencies = [
|
|||||||
"hx-ai",
|
"hx-ai",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"serde_norway",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
@@ -2449,6 +2450,19 @@ dependencies = [
|
|||||||
"zmij",
|
"zmij",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_norway"
|
||||||
|
version = "0.9.42"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e408f29489b5fd500fab51ff1484fc859bb655f32c671f307dcd733b72e8168c"
|
||||||
|
dependencies = [
|
||||||
|
"indexmap",
|
||||||
|
"itoa",
|
||||||
|
"ryu",
|
||||||
|
"serde",
|
||||||
|
"unsafe-libyaml-norway",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_spanned"
|
name = "serde_spanned"
|
||||||
version = "1.1.1"
|
version = "1.1.1"
|
||||||
@@ -3059,6 +3073,12 @@ version = "0.2.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unsafe-libyaml-norway"
|
||||||
|
version = "0.2.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b39abd59bf32521c7f2301b52d05a6a2c975b6003521cbd0c6dc1582f0a22104"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "untrusted"
|
name = "untrusted"
|
||||||
version = "0.9.0"
|
version = "0.9.0"
|
||||||
|
|||||||
@@ -80,17 +80,22 @@ A child starts with a cold prompt cache and costs tokens of its own: it saves *m
|
|||||||
|
|
||||||
## Skills
|
## Skills
|
||||||
|
|
||||||
Skills are `<dir>/<name>/SKILL.md` files with `name:` / `description:` frontmatter. Only the name and
|
Skills are `<dir>/<name>/SKILL.md` files with YAML frontmatter (`name`, `description`, `load`,
|
||||||
description go into the system prompt; the model reads the file when a task matches. Looked up in
|
`disable-model-invocation`, `argument-hint`; other keys such as `license` are ignored, `>` / `|` block
|
||||||
`~/.agents/skills` (shared with other agents), `~/.hx/skills`, then `.agents/skills` and `.hx/skills` in
|
descriptions work). Name and full description go into the system prompt; the model loads the body with the
|
||||||
the project; a later directory wins when names collide. `/skills` lists what loaded and the searched dirs.
|
`skill` tool (output: `Base directory for this skill: <dir>` + body without frontmatter). Looked up in
|
||||||
|
`~/.claude/skills`, `~/.agents/skills` (shared with other agents), `~/.hx/skills`, then `.agents/skills`,
|
||||||
|
`.claude/skills` and `.hx/skills` in the project; a later directory wins when names collide. `/skills` lists
|
||||||
|
what loaded, the searched dirs, and skills skipped for invalid YAML (quote descriptions that contain `: `).
|
||||||
|
|
||||||
A `load:` frontmatter key sets when a skill reaches the model: `auto` (default, listed by description; the
|
A `load:` frontmatter key sets when a skill reaches the model: `auto` (default, listed by description, so
|
||||||
model reads it when the task matches, so write the description as "use when ..."), `always` (body inlined in
|
write it as "use when ..."), `always` (body inlined in the system prompt every turn) or `manual`.
|
||||||
the system prompt every turn) or `manual` (only via `/<name>`, never mentioned to the model).
|
`disable-model-invocation: true` (alias: `load: manual`) keeps a skill out of the prompt and refuses it in
|
||||||
|
the `skill` tool; only `/<name>` runs it.
|
||||||
|
|
||||||
Each skill is also a command: `/<name> [args]` sends the skill file plus `args` as the prompt. Builtin
|
Each skill is also a command: `/<name> [args]` sends the skill body (frontmatter stripped, base directory
|
||||||
commands win when names collide.
|
line first) plus `args` as the prompt; `argument-hint` shows next to the name in `/` completion and `/help`.
|
||||||
|
Builtin commands win when names collide.
|
||||||
|
|
||||||
## Memory
|
## Memory
|
||||||
|
|
||||||
|
|||||||
@@ -454,7 +454,7 @@ async fn main() -> Result<()> {
|
|||||||
.sum();
|
.sum();
|
||||||
let mut skill_rows: Vec<(String, usize)> = sk
|
let mut skill_rows: Vec<(String, usize)> = sk
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|k| k.load == context::Load::Auto)
|
.filter(|k| k.load == context::Load::Auto && k.model_invocable)
|
||||||
.map(|k| {
|
.map(|k| {
|
||||||
(
|
(
|
||||||
format!("skill: {}", k.name),
|
format!("skill: {}", k.name),
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ futures = "0.3.34"
|
|||||||
hx-ai = { version = "0.1.0", path = "../hx-ai" }
|
hx-ai = { version = "0.1.0", path = "../hx-ai" }
|
||||||
serde = { version = "1.0.229", features = ["derive"] }
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
serde_json = "1.0.151"
|
serde_json = "1.0.151"
|
||||||
|
serde_norway = "0.9.42"
|
||||||
thiserror = "2.0.21"
|
thiserror = "2.0.21"
|
||||||
tokio = { version = "1.53.1", features = ["rt", "sync", "time", "macros", "fs", "process", "io-util"] }
|
tokio = { version = "1.53.1", features = ["rt", "sync", "time", "macros", "fs", "process", "io-util"] }
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ pub struct CmdSpec {
|
|||||||
pub summary: String,
|
pub summary: String,
|
||||||
pub source: Source,
|
pub source: Source,
|
||||||
pub args: ArgKind,
|
pub args: ArgKind,
|
||||||
|
/// `argument-hint:` of a skill, shown as `/name <hint>`.
|
||||||
|
pub hint: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CmdSpec {
|
impl CmdSpec {
|
||||||
@@ -36,6 +38,7 @@ impl CmdSpec {
|
|||||||
summary: summary.into(),
|
summary: summary.into(),
|
||||||
source,
|
source,
|
||||||
args,
|
args,
|
||||||
|
hint: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -108,21 +111,24 @@ pub fn skill_specs(skills: &[Skill], taken: &[CmdSpec]) -> Vec<CmdSpec> {
|
|||||||
summary: s.description.clone(),
|
summary: s.description.clone(),
|
||||||
source: Source::Skill(s.path.clone()),
|
source: Source::Skill(s.path.clone()),
|
||||||
args: ArgKind::Free,
|
args: ArgKind::Free,
|
||||||
|
hint: s.hint.clone(),
|
||||||
})
|
})
|
||||||
.collect()
|
.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> {
|
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() {
|
let ask = if arg.is_empty() {
|
||||||
"Apply this skill."
|
"Apply this skill."
|
||||||
} else {
|
} else {
|
||||||
arg
|
arg
|
||||||
};
|
};
|
||||||
Ok(format!(
|
Ok(format!(
|
||||||
"<skill name=\"{name}\" path=\"{}\">\n{body}\n</skill>\n\n{ask}",
|
"<skill name=\"{name}\">\n{}\n</skill>\n\n{ask}",
|
||||||
path.display()
|
sk.text()
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,10 +137,11 @@ pub fn help(specs: &[CmdSpec]) -> String {
|
|||||||
specs
|
specs
|
||||||
.iter()
|
.iter()
|
||||||
.map(|s| {
|
.map(|s| {
|
||||||
let arg = match &s.args {
|
let arg = match (&s.hint, &s.args) {
|
||||||
ArgKind::None => "",
|
(Some(h), _) => format!(" {h}"),
|
||||||
ArgKind::Path => " <path>",
|
(_, ArgKind::None) => String::new(),
|
||||||
_ => " [args]",
|
(_, ArgKind::Path) => " <path>".into(),
|
||||||
|
_ => " [args]".into(),
|
||||||
};
|
};
|
||||||
format!("/{}{arg} — {}", s.name, s.summary)
|
format!("/{}{arg} — {}", s.name, s.summary)
|
||||||
})
|
})
|
||||||
@@ -217,7 +224,10 @@ fn detail(s: &CmdSpec) -> String {
|
|||||||
Source::Mcp => "mcp · ",
|
Source::Mcp => "mcp · ",
|
||||||
Source::Ext => "ext · ",
|
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 {
|
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();
|
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("REVIEW BODY") && p.ends_with("PR 7"), "{p}");
|
||||||
|
assert!(p.contains("Base directory for this skill:") && !p.contains("description:"));
|
||||||
let h = help(&specs);
|
let h = help(&specs);
|
||||||
assert!(h.contains("/model [args] — show or switch model") && h.contains("/review"));
|
assert!(h.contains("/model [args] — show or switch model") && h.contains("/review"));
|
||||||
}
|
}
|
||||||
|
|||||||
+181
-94
@@ -46,13 +46,34 @@ pub struct Skill {
|
|||||||
pub description: String,
|
pub description: String,
|
||||||
pub path: PathBuf,
|
pub path: PathBuf,
|
||||||
pub load: Load,
|
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.
|
/// Text after the frontmatter.
|
||||||
pub body: String,
|
pub body: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Frontmatter `load:` key. `auto` (default): name + description in the system prompt, the model reads
|
impl Skill {
|
||||||
/// the file when the task matches. `always`: the body is inlined in the system prompt. `manual`: only
|
/// Skill directory (holds `SKILL.md` and its helper files).
|
||||||
/// reachable as a `/<name>` command, never mentioned to the model.
|
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)]
|
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||||
pub enum Load {
|
pub enum Load {
|
||||||
#[default]
|
#[default]
|
||||||
@@ -61,16 +82,30 @@ pub enum Load {
|
|||||||
Manual,
|
Manual,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Skill dirs, lowest priority first: `~/.agents/skills` (shared with other agents), `<hx home>/skills`,
|
/// Known frontmatter keys; everything else (`license`, ...) is ignored.
|
||||||
/// `<project>/.agents/skills`, `<project>/.hx/skills`.
|
#[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> {
|
pub fn skill_dirs(home: &Path, cwd: &Path) -> Vec<PathBuf> {
|
||||||
let mut v: Vec<PathBuf> = std::env::var_os("HOME")
|
let user = std::env::var_os("HOME").map(PathBuf::from);
|
||||||
.map(|h| PathBuf::from(h).join(".agents/skills"))
|
let mut v: Vec<PathBuf> = user
|
||||||
.into_iter()
|
.iter()
|
||||||
|
.flat_map(|h| [h.join(".claude/skills"), h.join(".agents/skills")])
|
||||||
.collect();
|
.collect();
|
||||||
v.extend([
|
v.extend([
|
||||||
home.join("skills"),
|
home.join("skills"),
|
||||||
cwd.join(".agents/skills"),
|
cwd.join(".agents/skills"),
|
||||||
|
cwd.join(".claude/skills"),
|
||||||
cwd.join(".hx/skills"),
|
cwd.join(".hx/skills"),
|
||||||
]);
|
]);
|
||||||
v
|
v
|
||||||
@@ -80,9 +115,56 @@ pub fn skills(home: &Path, cwd: &Path) -> Vec<Skill> {
|
|||||||
skills_in(&skill_dirs(home, cwd))
|
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> {
|
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 out: Vec<Skill> = vec![];
|
||||||
|
let mut warn = vec![];
|
||||||
for dir in dirs {
|
for dir in dirs {
|
||||||
let Ok(rd) = std::fs::read_dir(dir) else {
|
let Ok(rd) = std::fs::read_dir(dir) else {
|
||||||
continue;
|
continue;
|
||||||
@@ -97,68 +179,21 @@ pub fn skills_in(dirs: &[PathBuf]) -> Vec<Skill> {
|
|||||||
let Ok(s) = std::fs::read_to_string(&p) else {
|
let Ok(s) = std::fs::read_to_string(&p) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let (fm, body) = s
|
match parse_skill(&p, &s) {
|
||||||
.strip_prefix("---")
|
Ok(sk) => {
|
||||||
.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.retain(|x| x.name != sk.name);
|
||||||
out.push(sk);
|
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.
|
/// One system-prompt index line for an `auto` skill.
|
||||||
// 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).
|
|
||||||
pub fn skill_index_line(k: &Skill) -> String {
|
pub fn skill_index_line(k: &Skill) -> String {
|
||||||
let d = k.description.trim();
|
format!("- {}: {}\n", k.name, k.description)
|
||||||
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())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> String {
|
pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> String {
|
||||||
@@ -177,22 +212,16 @@ pub fn prompt_tail(home: &Path, cwd: &Path) -> String {
|
|||||||
for k in sk.iter().filter(|k| k.load == Load::Always) {
|
for k in sk.iter().filter(|k| k.load == Load::Always) {
|
||||||
s.push_str(&format!("\n\n# Skill: {}\n{}", k.name, k.body));
|
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() {
|
if !auto.is_empty() {
|
||||||
s.push_str("\n\n# Skills\nRead a skill's file with `read` when the task matches it.\n");
|
s.push_str("\n\n# Skills\nCall the `skill` tool with the name when the task matches.\n");
|
||||||
let mut roots: Vec<&Path> = vec![];
|
for k in auto {
|
||||||
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(&skill_index_line(k));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
for (p, c) in context_files(home, cwd) {
|
for (p, c) in context_files(home, cwd) {
|
||||||
s.push_str(&format!("\n\n# {}\n{}", p.display(), c.trim()));
|
s.push_str(&format!("\n\n# {}\n{}", p.display(), c.trim()));
|
||||||
}
|
}
|
||||||
@@ -242,35 +271,87 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert!(g < p && p < sub);
|
assert!(g < p && p < sub);
|
||||||
assert!(!s.contains("IGNORED"));
|
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!(!s.contains("BODY"), "skill body must load on demand only");
|
||||||
assert!(system_prompt(Some("CUSTOM"), &home, &proj).starts_with("CUSTOM"));
|
assert!(system_prompt(Some("CUSTOM"), &home, &proj).starts_with("CUSTOM"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn index_line_caps_description() {
|
fn index_line_is_full_description() {
|
||||||
let k = Skill {
|
let k = Skill {
|
||||||
name: "n".into(),
|
name: "n".into(),
|
||||||
description: "d".repeat(500),
|
description: "d".repeat(500),
|
||||||
path: "/p/SKILL.md".into(),
|
path: "/p/SKILL.md".into(),
|
||||||
load: Load::Auto,
|
load: Load::Auto,
|
||||||
|
model_invocable: true,
|
||||||
|
hint: None,
|
||||||
body: String::new(),
|
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!(
|
assert!(
|
||||||
l.len() < 150 && l.contains('…') && l.ends_with("(/p/SKILL.md)\n"),
|
!parse_skill(
|
||||||
"{l}"
|
p,
|
||||||
|
"---
|
||||||
|
load: manual
|
||||||
|
---
|
||||||
|
"
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.model_invocable
|
||||||
);
|
);
|
||||||
let short = Skill {
|
}
|
||||||
description: "short".into(),
|
|
||||||
..k
|
#[test]
|
||||||
};
|
fn user_only_and_broken_skills() {
|
||||||
assert_eq!(skill_index_line(&short), "- n: short (/p/SKILL.md)\n");
|
let t = tempfile::tempdir().unwrap();
|
||||||
let short = Skill {
|
for (n, fm) in [
|
||||||
path: "/r/n/SKILL.md".into(),
|
("ok", "description: fine"),
|
||||||
..short
|
("hid", "description: secret\ndisable-model-invocation: true"),
|
||||||
};
|
("bad", "description: [oops"),
|
||||||
assert_eq!(skill_index_line(&short), "- n: short\n");
|
] {
|
||||||
|
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]
|
#[test]
|
||||||
@@ -338,10 +419,16 @@ mod tests {
|
|||||||
.collect();
|
.collect();
|
||||||
assert_eq!(got, [("a", "shared"), ("g", "hx-g")]);
|
assert_eq!(got, [("a", "shared"), ("g", "hx-g")]);
|
||||||
let d = skill_dirs(Path::new("/h"), Path::new("/p"));
|
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!(
|
assert_eq!(
|
||||||
d[1..],
|
d[2..],
|
||||||
["/h/skills", "/p/.agents/skills", "/p/.hx/skills"].map(PathBuf::from)
|
[
|
||||||
|
"/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
|
/// 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.
|
/// `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 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.";
|
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;
|
const MAX_RESULT: usize = 8_000;
|
||||||
|
|||||||
@@ -412,6 +412,9 @@ mod tests {
|
|||||||
d.contains("tools.bash({command: string, timeout?: integer})"),
|
d.contains("tools.bash({command: string, timeout?: integer})"),
|
||||||
"{d}"
|
"{d}"
|
||||||
);
|
);
|
||||||
|
assert!(d.contains("tools.skill({name: string})"), "{d}");
|
||||||
|
assert!(crate::registry().get("skill").is_some());
|
||||||
|
assert!(hx_core::subagent::EXPLORE_TOOLS.contains(&"skill"));
|
||||||
assert_eq!(ident("mcp__dev-radius__search"), "mcp__dev_radius__search");
|
assert_eq!(ident("mcp__dev-radius__search"), "mcp__dev_radius__search");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
//! Built-in tools: read, write, edit, bash.
|
//! Built-in tools: read, write, edit, bash.
|
||||||
|
|
||||||
pub mod codemode;
|
pub mod codemode;
|
||||||
|
pub mod skill;
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use hx_ai::ToolSpec;
|
use hx_ai::ToolSpec;
|
||||||
@@ -14,7 +15,7 @@ const MAX_BYTES: usize = 20_000;
|
|||||||
/// bash keeps this much of the start (command echo, first errors) and the rest from the end.
|
/// bash keeps this much of the start (command echo, first errors) and the rest from the end.
|
||||||
const HEAD_BYTES: usize = 4_000;
|
const HEAD_BYTES: usize = 4_000;
|
||||||
|
|
||||||
fn spec(name: &str, desc: &str, schema: Value) -> ToolSpec {
|
pub(crate) fn spec(name: &str, desc: &str, schema: Value) -> ToolSpec {
|
||||||
ToolSpec {
|
ToolSpec {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
description: desc.into(),
|
description: desc.into(),
|
||||||
@@ -65,7 +66,8 @@ pub fn registry() -> Registry {
|
|||||||
.add(Bash)
|
.add(Bash)
|
||||||
.add(AskUser)
|
.add(AskUser)
|
||||||
.add(MemoryWrite)
|
.add(MemoryWrite)
|
||||||
.add(MemoryForget);
|
.add(MemoryForget)
|
||||||
|
.add(skill::Skill);
|
||||||
r
|
r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
//! `skill` tool: the model loads a skill body by name (no paths, so no traversal).
|
||||||
|
|
||||||
|
use crate::spec;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use hx_ai::ToolSpec;
|
||||||
|
use hx_core::context;
|
||||||
|
use hx_core::tool::{Tool, ToolCtx, ToolResult};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
pub struct Skill;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Tool for Skill {
|
||||||
|
fn spec(&self) -> ToolSpec {
|
||||||
|
spec(
|
||||||
|
"skill",
|
||||||
|
"Load a skill by name from the Skills list in the system prompt. Returns its instructions.",
|
||||||
|
json!({"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||||
|
let name = a["name"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.trim_start_matches('/');
|
||||||
|
let all = context::skills(&context::hx_home(), &cx.cwd);
|
||||||
|
match all.iter().find(|k| k.name == name) {
|
||||||
|
None => ToolResult::err(format!("no skill `{name}`")),
|
||||||
|
Some(k) if !k.model_invocable => {
|
||||||
|
ToolResult::err(format!("skill {name} is user-invoked only"))
|
||||||
|
}
|
||||||
|
Some(k) => ToolResult::ok(k.text()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn loads_by_name_and_refuses_user_only() {
|
||||||
|
let t = tempfile::tempdir().unwrap();
|
||||||
|
let cwd = t.path().join("proj");
|
||||||
|
for (n, extra) in [("a", ""), ("u", "disable-model-invocation: true\n")] {
|
||||||
|
let d = cwd.join(".hx/skills").join(n);
|
||||||
|
std::fs::create_dir_all(&d).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
d.join("SKILL.md"),
|
||||||
|
format!("---\nname: {n}\ndescription: x\n{extra}---\nBODY-{n}\n"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let cx = ToolCtx {
|
||||||
|
cwd: cwd.clone(),
|
||||||
|
state: Default::default(),
|
||||||
|
};
|
||||||
|
let r = Skill.call(json!({"name": "a"}), &cx).await;
|
||||||
|
assert!(!r.is_error, "{}", r.content);
|
||||||
|
let dir = cwd.join(".hx/skills/a");
|
||||||
|
assert!(
|
||||||
|
r.content
|
||||||
|
.starts_with(&format!("Base directory for this skill: {}", dir.display()))
|
||||||
|
);
|
||||||
|
assert!(r.content.contains("BODY-a") && !r.content.contains("description:"));
|
||||||
|
let r = Skill.call(json!({"name": "u"}), &cx).await;
|
||||||
|
assert!(
|
||||||
|
r.is_error && r.content.contains("user-invoked only"),
|
||||||
|
"{}",
|
||||||
|
r.content
|
||||||
|
);
|
||||||
|
let r = Skill.call(json!({"name": "../../etc/passwd"}), &cx).await;
|
||||||
|
assert!(r.is_error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1233,7 +1233,10 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
}
|
}
|
||||||
"skills" => {
|
"skills" => {
|
||||||
let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd);
|
let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd);
|
||||||
let l = skills_list(&app.specs, &dirs);
|
let mut l = skills_list(&app.specs, &dirs);
|
||||||
|
for w in hx_core::context::scan_skills(&dirs).1 {
|
||||||
|
l.push_str(&format!("\nwarning: {w}"));
|
||||||
|
}
|
||||||
show(app, "skills", l);
|
show(app, "skills", l);
|
||||||
}
|
}
|
||||||
"yolo" => {
|
"yolo" => {
|
||||||
|
|||||||
+1
-1
@@ -31,7 +31,7 @@ assert len(log) == 4, len(log)
|
|||||||
parent, child1, child2, parent2 = [r["body"] for r in log]
|
parent, child1, child2, parent2 = [r["body"] for r in log]
|
||||||
assert "haiku" in child1["model"] and "sonnet" in parent["model"], (child1["model"], parent["model"])
|
assert "haiku" in child1["model"] and "sonnet" in parent["model"], (child1["model"], parent["model"])
|
||||||
assert child1["messages"][0]["content"][0]["text"] == "what is in note.txt?"
|
assert child1["messages"][0]["content"][0]["text"] == "what is in note.txt?"
|
||||||
assert {t["name"] for t in child1["tools"]} == {"Read", "Bash"}, [t["name"] for t in child1["tools"]]
|
assert {t["name"] for t in child1["tools"]} == {"Read", "Bash", "skill"}, [t["name"] for t in child1["tools"]]
|
||||||
assert "Task" in {t["name"] for t in parent["tools"]}
|
assert "Task" in {t["name"] for t in parent["tools"]}
|
||||||
# parent got only the child's answer (+ stats line), not the Read result
|
# parent got only the child's answer (+ stats line), not the Read result
|
||||||
res = json.dumps(parent2["messages"][-1])
|
res = json.dumps(parent2["messages"][-1])
|
||||||
|
|||||||
Reference in new issue
Block a user