325 lines
11 KiB
Rust
325 lines
11 KiB
Rust
//! System prompt, AGENTS.md discovery, skills.
|
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
pub const DEFAULT_PROMPT: &str = "You are hx, a coding agent working in the user's repository. \
|
|
Use the tools to read, edit and run code. Read files before editing them. Keep answers short.";
|
|
|
|
const CONTEXT_FILES: &[&str] = &["AGENTS.md", "CLAUDE.md"];
|
|
|
|
pub fn hx_home() -> PathBuf {
|
|
std::env::var_os("HX_HOME")
|
|
.map(PathBuf::from)
|
|
.unwrap_or_else(|| {
|
|
std::env::var_os("HOME")
|
|
.map(PathBuf::from)
|
|
.unwrap_or_default()
|
|
.join(".hx")
|
|
})
|
|
}
|
|
|
|
/// Context files from global (`~/.hx`) then root-most to `cwd`. First match per dir.
|
|
pub fn context_files(home: &Path, cwd: &Path) -> Vec<(PathBuf, String)> {
|
|
let mut dirs: Vec<&Path> = cwd.ancestors().collect();
|
|
dirs.reverse();
|
|
let mut out = vec![];
|
|
for d in std::iter::once(home).chain(dirs) {
|
|
for n in CONTEXT_FILES {
|
|
let p = d.join(n);
|
|
if let Ok(s) = std::fs::read_to_string(&p) {
|
|
out.push((p, s));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Skill {
|
|
pub name: String,
|
|
pub description: String,
|
|
pub path: PathBuf,
|
|
pub load: Load,
|
|
/// 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.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
|
pub enum Load {
|
|
#[default]
|
|
Auto,
|
|
Always,
|
|
Manual,
|
|
}
|
|
|
|
/// Skill dirs, lowest priority first: `~/.agents/skills` (shared with other agents), `<hx home>/skills`,
|
|
/// `<project>/.agents/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()
|
|
.collect();
|
|
v.extend([
|
|
home.join("skills"),
|
|
cwd.join(".agents/skills"),
|
|
cwd.join(".hx/skills"),
|
|
]);
|
|
v
|
|
}
|
|
|
|
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> {
|
|
let mut out: Vec<Skill> = vec![];
|
|
for dir in dirs {
|
|
let Ok(rd) = std::fs::read_dir(dir) else {
|
|
continue;
|
|
};
|
|
let mut paths: Vec<_> = rd
|
|
.flatten()
|
|
.map(|e| e.path().join("SKILL.md"))
|
|
.filter(|p| p.is_file())
|
|
.collect();
|
|
paths.sort();
|
|
for p in paths {
|
|
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);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// 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).
|
|
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())
|
|
}
|
|
}
|
|
|
|
pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> String {
|
|
let mut s = base.unwrap_or(DEFAULT_PROMPT).to_string();
|
|
s.push_str(&format!("\n\nWorking directory: {}", cwd.display()));
|
|
let sk = skills(home, cwd);
|
|
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();
|
|
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));
|
|
}
|
|
}
|
|
}
|
|
for (p, c) in context_files(home, cwd) {
|
|
s.push_str(&format!("\n\n# {}\n{}", p.display(), c.trim()));
|
|
}
|
|
s
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn prompt_assembly() {
|
|
let t = tempfile::tempdir().unwrap();
|
|
let home = t.path().join("home");
|
|
let proj = t.path().join("proj/sub");
|
|
std::fs::create_dir_all(home.join("skills/g")).unwrap();
|
|
std::fs::create_dir_all(proj.join(".hx/skills/g")).unwrap();
|
|
std::fs::write(home.join("AGENTS.md"), "GLOBAL").unwrap();
|
|
std::fs::write(t.path().join("proj/AGENTS.md"), "PROJ").unwrap();
|
|
std::fs::write(t.path().join("proj/CLAUDE.md"), "IGNORED").unwrap();
|
|
std::fs::write(proj.join("CLAUDE.md"), "SUB").unwrap();
|
|
std::fs::write(
|
|
home.join("skills/g/SKILL.md"),
|
|
"---\nname: g\ndescription: global\n---\nbody",
|
|
)
|
|
.unwrap();
|
|
std::fs::write(
|
|
proj.join(".hx/skills/g/SKILL.md"),
|
|
"---\nname: g\ndescription: \"local\"\n---\nBODY",
|
|
)
|
|
.unwrap();
|
|
|
|
let s = system_prompt(None, &home, &proj);
|
|
let (g, p, sub) = (
|
|
s.find("GLOBAL").unwrap(),
|
|
s.find("PROJ").unwrap(),
|
|
s.find("SUB").unwrap(),
|
|
);
|
|
assert!(g < p && p < sub);
|
|
assert!(!s.contains("IGNORED"));
|
|
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() {
|
|
let k = Skill {
|
|
name: "n".into(),
|
|
description: "d".repeat(500),
|
|
path: "/p/SKILL.md".into(),
|
|
load: Load::Auto,
|
|
body: String::new(),
|
|
};
|
|
let l = skill_index_line(&k);
|
|
assert!(
|
|
l.len() < 150 && l.contains('…') && l.ends_with("(/p/SKILL.md)\n"),
|
|
"{l}"
|
|
);
|
|
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 skill_load_modes() {
|
|
let t = tempfile::tempdir().unwrap();
|
|
for (n, l) in [("a", "always"), ("m", "manual"), ("d", "")] {
|
|
let d = t.path().join(n);
|
|
std::fs::create_dir_all(&d).unwrap();
|
|
let load = if l.is_empty() {
|
|
String::new()
|
|
} else {
|
|
format!("load: {l}\n")
|
|
};
|
|
std::fs::write(
|
|
d.join("SKILL.md"),
|
|
format!("---\nname: {n}\ndescription: use when {n}\n{load}---\nBODY-{n}\n"),
|
|
)
|
|
.unwrap();
|
|
}
|
|
let sk = skills_in(&[t.path().to_path_buf()]);
|
|
let loads: Vec<_> = sk.iter().map(|s| (s.name.as_str(), s.load)).collect();
|
|
assert_eq!(
|
|
loads,
|
|
[("a", Load::Always), ("d", Load::Auto), ("m", Load::Manual)]
|
|
);
|
|
assert_eq!(sk[0].body, "BODY-a");
|
|
// prompt: always inlined, auto listed only, manual absent
|
|
let home = t.path().join("h");
|
|
std::fs::create_dir_all(home.join("skills")).unwrap();
|
|
for n in ["a", "d", "m"] {
|
|
std::fs::create_dir_all(home.join("skills").join(n)).unwrap();
|
|
std::fs::copy(
|
|
t.path().join(n).join("SKILL.md"),
|
|
home.join("skills").join(n).join("SKILL.md"),
|
|
)
|
|
.unwrap();
|
|
}
|
|
let p = system_prompt(None, &home, &t.path().join("proj"));
|
|
assert!(p.contains("BODY-a") && !p.contains("- a:"));
|
|
assert!(p.contains("- d: use when d") && !p.contains("BODY-d"));
|
|
assert!(!p.contains("BODY-m") && !p.contains("- m:"));
|
|
}
|
|
|
|
#[test]
|
|
fn agent_skills_dir() {
|
|
let t = tempfile::tempdir().unwrap();
|
|
let w = |p: &str, s: &str| {
|
|
let p = t.path().join(p);
|
|
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
|
std::fs::write(p, s).unwrap();
|
|
};
|
|
w(
|
|
"agent/a/SKILL.md",
|
|
"---\nname: a\ndescription: shared\n---\n",
|
|
);
|
|
w(
|
|
"agent/g/SKILL.md",
|
|
"---\nname: g\ndescription: shared-g\n---\n",
|
|
);
|
|
w("hx/g/SKILL.md", "---\nname: g\ndescription: hx-g\n---\n");
|
|
let sk = skills_in(&[t.path().join("agent"), t.path().join("hx")]);
|
|
let got: Vec<(&str, &str)> = sk
|
|
.iter()
|
|
.map(|s| (s.name.as_str(), s.description.as_str()))
|
|
.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_eq!(
|
|
d[1..],
|
|
["/h/skills", "/p/.agents/skills", "/p/.hx/skills"].map(PathBuf::from)
|
|
);
|
|
}
|
|
}
|