From 199f337662255ce2abd96e8ef2c46b060ea755d6 Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 9 Oct 2026 14:49:38 +0000 Subject: [PATCH] skills: skill tool, YAML frontmatter, disable-model-invocation, argument-hint --- Cargo.lock | 20 +++ README.md | 23 ++- crates/hx-cli/src/main.rs | 2 +- crates/hx-core/Cargo.toml | 1 + crates/hx-core/src/command.rs | 29 +++- crates/hx-core/src/context.rs | 281 +++++++++++++++++++++----------- crates/hx-core/src/subagent.rs | 2 +- crates/hx-tools/src/codemode.rs | 3 + crates/hx-tools/src/lib.rs | 6 +- crates/hx-tools/src/skill.rs | 75 +++++++++ crates/hx-tui/src/lib.rs | 5 +- tests/m8_e2e.sh | 2 +- 12 files changed, 328 insertions(+), 121 deletions(-) create mode 100644 crates/hx-tools/src/skill.rs diff --git a/Cargo.lock b/Cargo.lock index ab1550d..c691d77 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1044,6 +1044,7 @@ dependencies = [ "hx-ai", "serde", "serde_json", + "serde_norway", "tempfile", "thiserror 2.0.21", "tokio", @@ -2449,6 +2450,19 @@ dependencies = [ "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]] name = "serde_spanned" version = "1.1.1" @@ -3059,6 +3073,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "unsafe-libyaml-norway" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39abd59bf32521c7f2301b52d05a6a2c975b6003521cbd0c6dc1582f0a22104" + [[package]] name = "untrusted" version = "0.9.0" diff --git a/README.md b/README.md index 547f4e0..dcdeeec 100644 --- a/README.md +++ b/README.md @@ -80,17 +80,22 @@ A child starts with a cold prompt cache and costs tokens of its own: it saves *m ## Skills -Skills are `//SKILL.md` files with `name:` / `description:` frontmatter. Only the name and -description go into the system prompt; the model reads the file when a task matches. Looked up in -`~/.agents/skills` (shared with other agents), `~/.hx/skills`, then `.agents/skills` and `.hx/skills` in -the project; a later directory wins when names collide. `/skills` lists what loaded and the searched dirs. +Skills are `//SKILL.md` files with YAML frontmatter (`name`, `description`, `load`, +`disable-model-invocation`, `argument-hint`; other keys such as `license` are ignored, `>` / `|` block +descriptions work). Name and full description go into the system prompt; the model loads the body with the +`skill` tool (output: `Base directory for this skill: ` + 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 -model reads it when the task matches, so write the description as "use when ..."), `always` (body inlined in -the system prompt every turn) or `manual` (only via `/`, never mentioned to the model). +A `load:` frontmatter key sets when a skill reaches the model: `auto` (default, listed by description, so +write it as "use when ..."), `always` (body inlined in the system prompt every turn) or `manual`. +`disable-model-invocation: true` (alias: `load: manual`) keeps a skill out of the prompt and refuses it in +the `skill` tool; only `/` runs it. -Each skill is also a command: `/ [args]` sends the skill file plus `args` as the prompt. Builtin -commands win when names collide. +Each skill is also a command: `/ [args]` sends the skill body (frontmatter stripped, base directory +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 diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 4c5a363..ef54886 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -454,7 +454,7 @@ async fn main() -> Result<()> { .sum(); let mut skill_rows: Vec<(String, usize)> = sk .iter() - .filter(|k| k.load == context::Load::Auto) + .filter(|k| k.load == context::Load::Auto && k.model_invocable) .map(|k| { ( format!("skill: {}", k.name), diff --git a/crates/hx-core/Cargo.toml b/crates/hx-core/Cargo.toml index 089563c..a068dde 100644 --- a/crates/hx-core/Cargo.toml +++ b/crates/hx-core/Cargo.toml @@ -10,6 +10,7 @@ futures = "0.3.34" hx-ai = { version = "0.1.0", path = "../hx-ai" } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" +serde_norway = "0.9.42" thiserror = "2.0.21" tokio = { version = "1.53.1", features = ["rt", "sync", "time", "macros", "fs", "process", "io-util"] } diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs index 8017dd5..5c6a407 100644 --- a/crates/hx-core/src/command.rs +++ b/crates/hx-core/src/command.rs @@ -27,6 +27,8 @@ pub struct CmdSpec { pub summary: String, pub source: Source, pub args: ArgKind, + /// `argument-hint:` of a skill, shown as `/name `. + pub hint: Option, } 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 { summary: s.description.clone(), source: Source::Skill(s.path.clone()), args: ArgKind::Free, + hint: s.hint.clone(), }) .collect() } -/// The prompt a `/ args` command sends. +/// The prompt a `/ 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 { - 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!( - "\n{body}\n\n\n{ask}", - path.display() + "\n{}\n\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 => " ", - _ => " [args]", + let arg = match (&s.hint, &s.args) { + (Some(h), _) => format!(" {h}"), + (_, ArgKind::None) => String::new(), + (_, ArgKind::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")); } diff --git a/crates/hx-core/src/context.rs b/crates/hx-core/src/context.rs index 67793c0..0f4dd2f 100644 --- a/crates/hx-core/src/context.rs +++ b/crates/hx-core/src/context.rs @@ -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 `/` reaches it. + pub model_invocable: bool, + /// `argument-hint:` shown next to `/`. + pub hint: Option, /// 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 `/` 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 `/` 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 `/` 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), `/skills`, -/// `/.agents/skills`, `/.hx/skills`. +/// Known frontmatter keys; everything else (`license`, ...) is ignored. +#[derive(serde::Deserialize, Default)] +struct Front { + name: Option, + description: Option, + load: Option, + #[serde(rename = "disable-model-invocation")] + disable_model_invocation: Option, + #[serde(rename = "argument-hint")] + argument_hint: Option, +} + +/// Skill dirs, lowest priority first: `~/.claude/skills`, `~/.agents/skills` (shared with other agents), +/// `/skills`, `/.agents/skills`, `/.claude/skills`, `/.hx/skills`. pub fn skill_dirs(home: &Path, cwd: &Path) -> Vec { - let mut v: Vec = 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 = 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 { skills_in(&skill_dirs(home, cwd)) } -/// `//SKILL.md` with `name:` / `description:` frontmatter. Later dirs override earlier ones by name. pub fn skills_in(dirs: &[PathBuf]) -> Vec { + scan_skills(dirs).0 +} + +/// Parse one `SKILL.md`. Err: the frontmatter is not valid YAML. +pub fn parse_skill(p: &Path, s: &str) -> Result { + 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::>() + .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(), + }) +} + +/// `//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, Vec) { let mut out: Vec = 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 { 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: `//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 -/// `//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: {}//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: \ndisable-model-invocation: true\n---\nB\n", + ) + .unwrap(); + assert_eq!(k.description, "line one line two"); + assert_eq!(k.hint.as_deref(), Some("")); + 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) ); } } diff --git a/crates/hx-core/src/subagent.rs b/crates/hx-core/src/subagent.rs index ab33f9b..bd3d8ad 100644 --- a/crates/hx-core/src/subagent.rs +++ b/crates/hx-core/src/subagent.rs @@ -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; diff --git a/crates/hx-tools/src/codemode.rs b/crates/hx-tools/src/codemode.rs index aa98b9b..747c360 100644 --- a/crates/hx-tools/src/codemode.rs +++ b/crates/hx-tools/src/codemode.rs @@ -412,6 +412,9 @@ mod tests { d.contains("tools.bash({command: string, timeout?: integer})"), "{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"); } } diff --git a/crates/hx-tools/src/lib.rs b/crates/hx-tools/src/lib.rs index 0abe780..a4667e0 100644 --- a/crates/hx-tools/src/lib.rs +++ b/crates/hx-tools/src/lib.rs @@ -1,6 +1,7 @@ //! Built-in tools: read, write, edit, bash. pub mod codemode; +pub mod skill; use async_trait::async_trait; 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. 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 { name: name.into(), description: desc.into(), @@ -65,7 +66,8 @@ pub fn registry() -> Registry { .add(Bash) .add(AskUser) .add(MemoryWrite) - .add(MemoryForget); + .add(MemoryForget) + .add(skill::Skill); r } diff --git a/crates/hx-tools/src/skill.rs b/crates/hx-tools/src/skill.rs new file mode 100644 index 0000000..fe75272 --- /dev/null +++ b/crates/hx-tools/src/skill.rs @@ -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); + } +} diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index cee9157..2e6af89 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -1233,7 +1233,10 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { } "skills" => { 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); } "yolo" => { diff --git a/tests/m8_e2e.sh b/tests/m8_e2e.sh index fea91a2..da73c17 100644 --- a/tests/m8_e2e.sh +++ b/tests/m8_e2e.sh @@ -31,7 +31,7 @@ assert len(log) == 4, len(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 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"]} # parent got only the child's answer (+ stats line), not the Read result res = json.dumps(parent2["messages"][-1])