471 lines
15 KiB
Rust
471 lines
15 KiB
Rust
//! Slash-command registry and the completion engine shared by the TUI and RPC mode.
|
|
|
|
use crate::context::Skill;
|
|
use std::path::PathBuf;
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum Source {
|
|
Builtin,
|
|
/// `SKILL.md` path; running the command sends its body as a prompt.
|
|
Skill(PathBuf),
|
|
Mcp,
|
|
Ext,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum ArgKind {
|
|
None,
|
|
Free,
|
|
Enum(Vec<String>),
|
|
Path,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct CmdSpec {
|
|
/// Without the leading `/`.
|
|
pub name: String,
|
|
pub summary: String,
|
|
pub source: Source,
|
|
pub args: ArgKind,
|
|
/// `argument-hint:` of a skill, shown as `/name <hint>`.
|
|
pub hint: Option<String>,
|
|
}
|
|
|
|
impl CmdSpec {
|
|
pub fn new(name: &str, summary: &str, source: Source, args: ArgKind) -> Self {
|
|
Self {
|
|
name: name.into(),
|
|
summary: summary.into(),
|
|
source,
|
|
args,
|
|
hint: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Commands handled by the TUI itself. `models` feeds `/model` completion.
|
|
pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
|
use ArgKind::*;
|
|
let b = |n, s, a| CmdSpec::new(n, s, Source::Builtin, a);
|
|
vec![
|
|
b("help", "list commands and keys", None),
|
|
b(
|
|
"model",
|
|
"show or switch model",
|
|
Enum(
|
|
std::iter::once("auto".to_string())
|
|
.chain(models.iter().map(|m| m.to_string()))
|
|
.collect(),
|
|
),
|
|
),
|
|
b(
|
|
"provider",
|
|
"switch provider",
|
|
Enum(vec!["claude".into(), "codex".into()]),
|
|
),
|
|
b(
|
|
"effort",
|
|
"thinking level (tab on an empty line cycles)",
|
|
Enum(["off", "low", "medium", "high"].map(String::from).into()),
|
|
),
|
|
b("compact", "summarize old context", None),
|
|
b("new", "start a new session (old one stays resumable)", None),
|
|
b("clear", "alias of /new", None),
|
|
b("sessions", "browse, resume, delete sessions", None),
|
|
b("yolo", "toggle: run every tool without asking", None),
|
|
b(
|
|
"sandbox",
|
|
"sandbox on/off; `claude` toggles it for claude; no arg: status",
|
|
Enum(["on", "off", "claude"].map(String::from).into()),
|
|
),
|
|
b("lsp", "language server status", None),
|
|
b("copy", "copy the last answer to the clipboard", None),
|
|
b("usage", "subscription limits, resets, credits", None),
|
|
b(
|
|
"keys",
|
|
"show keys as hx receives them (debug shift-enter)",
|
|
None,
|
|
),
|
|
b(
|
|
"stats",
|
|
"token dashboard: cache hit, per-request usage",
|
|
None,
|
|
),
|
|
b(
|
|
"diff",
|
|
"diff of this session's edits; reject reverts a file",
|
|
None,
|
|
),
|
|
b("btw", "side question; no tools, not saved", Free),
|
|
b("skills", "list skills and where they load from", None),
|
|
b(
|
|
"reload",
|
|
"re-read AGENTS.md, skills, config, MCP prompt index",
|
|
None,
|
|
),
|
|
b(
|
|
"resume",
|
|
"resume a session file; no arg opens /sessions",
|
|
Path,
|
|
),
|
|
b("quit", "exit hx", None),
|
|
b("exit", "exit hx", None),
|
|
]
|
|
}
|
|
|
|
/// One `/<name>` per skill; names taken by `taken` (builtins) are skipped, so builtins win.
|
|
pub fn skill_specs(skills: &[Skill], taken: &[CmdSpec]) -> Vec<CmdSpec> {
|
|
skills
|
|
.iter()
|
|
.filter(|s| {
|
|
!s.name.contains(char::is_whitespace) && !taken.iter().any(|t| t.name == s.name)
|
|
})
|
|
.map(|s| CmdSpec {
|
|
name: s.name.clone(),
|
|
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: 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 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}\">\n{}\n</skill>\n\n{ask}",
|
|
sk.text()
|
|
))
|
|
}
|
|
|
|
/// `/help` text generated from the registry.
|
|
pub fn help(specs: &[CmdSpec]) -> String {
|
|
specs
|
|
.iter()
|
|
.map(|s| {
|
|
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)
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join("\n")
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Candidate {
|
|
/// Replaces `line[start..cursor]`.
|
|
pub label: String,
|
|
pub detail: String,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Default)]
|
|
pub struct Completion {
|
|
/// Byte offset where the completed token starts.
|
|
pub start: usize,
|
|
pub items: Vec<Candidate>,
|
|
}
|
|
|
|
pub const MAX_ITEMS: usize = 8;
|
|
/// Enum args (model ids) show every match; the popup scrolls.
|
|
pub const MAX_ENUM_ITEMS: usize = 100;
|
|
|
|
/// Complete the token ending at byte `cur` of `line`:
|
|
/// `/cmd` at line start → commands; `/cmd partial` → the command's args; `@partial` → files.
|
|
pub fn complete(line: &str, cur: usize, specs: &[CmdSpec], files: &[String]) -> Completion {
|
|
let cur = floor_boundary(line, cur.min(line.len()));
|
|
let before = &line[..cur];
|
|
let start = before
|
|
.char_indices()
|
|
.rev()
|
|
.find(|(_, c)| c.is_whitespace())
|
|
.map_or(0, |(i, c)| i + c.len_utf8());
|
|
let tok = &before[start..];
|
|
let cand = |label: String, detail: &str| Candidate {
|
|
label,
|
|
detail: detail.into(),
|
|
};
|
|
let raw = tok.strip_prefix('@').unwrap_or(tok);
|
|
let items = if is_fs_path(raw) && (start > 0 || tok.starts_with('@') || raw[1..].contains('/'))
|
|
{
|
|
let at = if tok.starts_with('@') { "@" } else { "" };
|
|
complete_path(raw)
|
|
.into_iter()
|
|
.map(|f| cand(format!("{at}{f}"), ""))
|
|
.collect()
|
|
} else if let Some(q) = tok.strip_prefix('@') {
|
|
rank(files.iter().map(String::as_str), q, MAX_ITEMS)
|
|
.into_iter()
|
|
.map(|f| cand(format!("@{f}"), ""))
|
|
.collect()
|
|
} else if start == 0
|
|
&& let Some(q) = tok.strip_prefix('/')
|
|
{
|
|
let names: Vec<&str> = specs.iter().map(|s| s.name.as_str()).collect();
|
|
rank(names.iter().copied(), q, MAX_ITEMS)
|
|
.into_iter()
|
|
.filter_map(|n| specs.iter().find(|s| s.name == n))
|
|
.map(|s| cand(format!("/{}", s.name), &detail(s)))
|
|
.collect()
|
|
} else if let Some(cmd) = before[..start].strip_prefix('/')
|
|
&& let [name] = cmd.split_whitespace().collect::<Vec<_>>()[..]
|
|
&& let Some(spec) = specs.iter().find(|s| s.name == name)
|
|
{
|
|
match &spec.args {
|
|
ArgKind::Enum(v) => rank(v.iter().map(String::as_str), tok, MAX_ENUM_ITEMS)
|
|
.into_iter()
|
|
.map(|x| cand(x.into(), ""))
|
|
.collect(),
|
|
ArgKind::Path => rank(files.iter().map(String::as_str), tok, MAX_ITEMS)
|
|
.into_iter()
|
|
.map(|x| cand(x.into(), ""))
|
|
.collect(),
|
|
ArgKind::None | ArgKind::Free => vec![],
|
|
}
|
|
} else {
|
|
vec![]
|
|
};
|
|
Completion { start, items }
|
|
}
|
|
|
|
pub fn is_fs_path(t: &str) -> bool {
|
|
t == "~"
|
|
|| t.starts_with(['/', '~']) && t.contains('/')
|
|
|| t.starts_with("./")
|
|
|| t.starts_with("../")
|
|
}
|
|
|
|
/// Expand a leading `~/` to `$HOME`.
|
|
pub fn expand_home(p: &str) -> PathBuf {
|
|
match (p.strip_prefix("~/"), std::env::var_os("HOME")) {
|
|
(Some(rest), Some(h)) => PathBuf::from(h).join(rest),
|
|
_ => PathBuf::from(p),
|
|
}
|
|
}
|
|
|
|
/// Live directory listing for a `~/`, `/`, `./` or `../` token; the typed form is kept in labels.
|
|
/// Directories first and suffixed `/`; dotfiles only when the prefix starts with `.`.
|
|
fn complete_path(tok: &str) -> Vec<String> {
|
|
if tok == "~" {
|
|
return vec!["~/".into()];
|
|
}
|
|
let (dir, pre) = tok.rsplit_once('/').map_or(("", tok), |(d, p)| (d, p));
|
|
let shown = format!("{dir}/");
|
|
let real = if dir.is_empty() {
|
|
PathBuf::from("/")
|
|
} else {
|
|
expand_home(&shown)
|
|
};
|
|
let Ok(rd) = std::fs::read_dir(real) else {
|
|
return vec![];
|
|
};
|
|
let pre_l = pre.to_lowercase();
|
|
let mut v: Vec<(bool, String)> = rd
|
|
.flatten()
|
|
.filter_map(|e| {
|
|
let n = e.file_name().to_string_lossy().into_owned();
|
|
if (n.starts_with('.') && !pre.starts_with('.'))
|
|
|| !n.to_lowercase().starts_with(&pre_l)
|
|
{
|
|
return None;
|
|
}
|
|
let d = e.path().is_dir();
|
|
Some((d, if d { format!("{n}/") } else { n }))
|
|
})
|
|
.collect();
|
|
v.sort_by(|a, b| {
|
|
b.0.cmp(&a.0)
|
|
.then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase()))
|
|
});
|
|
v.into_iter()
|
|
.take(MAX_ENUM_ITEMS)
|
|
.map(|(_, n)| format!("{shown}{n}"))
|
|
.collect()
|
|
}
|
|
|
|
fn detail(s: &CmdSpec) -> String {
|
|
let tag = match s.source {
|
|
Source::Builtin => "",
|
|
Source::Skill(_) => "skill · ",
|
|
Source::Mcp => "mcp · ",
|
|
Source::Ext => "ext · ",
|
|
};
|
|
match &s.hint {
|
|
Some(h) => format!("{tag}{h} {}", s.summary),
|
|
None => format!("{tag}{}", s.summary),
|
|
}
|
|
}
|
|
|
|
fn floor_boundary(s: &str, mut i: usize) -> usize {
|
|
while !s.is_char_boundary(i) {
|
|
i -= 1;
|
|
}
|
|
i
|
|
}
|
|
|
|
/// Case-insensitive subsequence match. Order: basename prefix, basename substring, substring,
|
|
/// subsequence; shorter first within a tier.
|
|
pub fn rank<'a>(xs: impl Iterator<Item = &'a str>, q: &str, n: usize) -> Vec<&'a str> {
|
|
let q = q.to_lowercase();
|
|
let mut hits: Vec<(usize, usize, &str)> = xs
|
|
.filter_map(|x| {
|
|
let l = x.to_lowercase();
|
|
let mut it = l.chars();
|
|
if !q.chars().all(|c| it.any(|y| y == c)) {
|
|
return None;
|
|
}
|
|
let base = l.rsplit('/').next().unwrap_or(&l);
|
|
let tier = if base.starts_with(&q) {
|
|
0
|
|
} else if base.contains(&q) {
|
|
1
|
|
} else if l.contains(&q) {
|
|
2
|
|
} else {
|
|
3
|
|
};
|
|
Some((tier, x.len(), x))
|
|
})
|
|
.collect();
|
|
hits.sort();
|
|
hits.into_iter().take(n).map(|(_, _, x)| x).collect()
|
|
}
|
|
|
|
/// Longest common prefix of all candidates (char-boundary safe).
|
|
pub fn common_prefix<S: AsRef<str>>(xs: &[S]) -> String {
|
|
let Some(first) = xs.first().map(AsRef::as_ref) else {
|
|
return String::new();
|
|
};
|
|
let mut end = first.len();
|
|
for x in &xs[1..] {
|
|
end = end.min(
|
|
first
|
|
.bytes()
|
|
.zip(x.as_ref().bytes())
|
|
.take_while(|(a, b)| a == b)
|
|
.count(),
|
|
);
|
|
}
|
|
first[..floor_boundary(first, end)].to_string()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
#[test]
|
|
fn fs_paths_complete() {
|
|
let d = tempfile::tempdir().unwrap();
|
|
let r = d.path();
|
|
std::fs::create_dir_all(r.join("Docs/sub")).unwrap();
|
|
std::fs::write(r.join("doc.txt"), "").unwrap();
|
|
std::fs::write(r.join(".hid"), "").unwrap();
|
|
let t = |l: &str| -> Vec<String> {
|
|
super::complete(l, l.len(), &[], &[])
|
|
.items
|
|
.into_iter()
|
|
.map(|c| c.label)
|
|
.collect()
|
|
};
|
|
let b = r.display();
|
|
assert_eq!(
|
|
t(&format!("see {b}/do")),
|
|
[format!("{b}/Docs/"), format!("{b}/doc.txt")]
|
|
);
|
|
assert_eq!(t(&format!("@{b}/Docs/")), [format!("@{b}/Docs/sub/")]);
|
|
assert_eq!(t(&format!("{b}/.")), [format!("{b}/.hid")]);
|
|
assert!(t(&format!("{b}/nope/x")).is_empty());
|
|
assert_eq!(t("x ~"), ["~/"]);
|
|
// slash command stays a command
|
|
assert!(t("/etc").is_empty());
|
|
}
|
|
|
|
use super::*;
|
|
|
|
fn labels(c: &Completion) -> Vec<&str> {
|
|
c.items.iter().map(|i| i.label.as_str()).collect()
|
|
}
|
|
|
|
#[test]
|
|
fn completion_table() {
|
|
let t = tempfile::tempdir().unwrap();
|
|
std::fs::create_dir_all(t.path().join("review")).unwrap();
|
|
std::fs::write(
|
|
t.path().join("review/SKILL.md"),
|
|
"---\nname: review\ndescription: code review\n---\nREVIEW BODY",
|
|
)
|
|
.unwrap();
|
|
std::fs::create_dir_all(t.path().join("help")).unwrap();
|
|
std::fs::write(t.path().join("help/SKILL.md"), "---\nname: help\n---\nx").unwrap();
|
|
let skills = crate::context::skills_in(&[t.path().to_path_buf()]);
|
|
let mut specs = builtins(&["claude-sonnet-5-5", "claude-opus-5-5", "gpt-5.6-sol"]);
|
|
let sk = skill_specs(&skills, &specs);
|
|
assert_eq!(sk.len(), 1, "builtin /help wins over the skill");
|
|
specs.extend(sk);
|
|
specs.push(CmdSpec::new(
|
|
"fs:grep",
|
|
"mcp prompt",
|
|
Source::Mcp,
|
|
ArgKind::Path,
|
|
));
|
|
let files: Vec<String> = [
|
|
"src/main.rs",
|
|
"src/lib.rs",
|
|
"crates/x/src/main.rs",
|
|
"docs/ü.md",
|
|
]
|
|
.map(String::from)
|
|
.into();
|
|
let c = |l: &str| complete(l, l.len(), &specs, &files);
|
|
|
|
assert_eq!(c("/").items.len(), MAX_ITEMS);
|
|
assert_eq!(labels(&c("/mo")), ["/model"]);
|
|
assert_eq!(labels(&c("/co")), ["/copy", "/compact"]);
|
|
let r = c("/rev");
|
|
assert_eq!(labels(&r), ["/review"]);
|
|
assert_eq!(r.items[0].detail, "skill · code review");
|
|
let m = c("/model op");
|
|
assert_eq!((m.start, labels(&m)), (7, vec!["claude-opus-5-5"]));
|
|
assert_eq!(c("/model ").items.len(), 4, "auto + 3 models");
|
|
assert_eq!(labels(&c("/provider c")), ["codex", "claude"]);
|
|
assert_eq!(labels(&c("/fs:grep lib")), ["src/lib.rs"]);
|
|
assert!(
|
|
c("/review foo").items.is_empty(),
|
|
"free args: nothing to offer"
|
|
);
|
|
assert!(c("/model a b").items.is_empty());
|
|
assert!(c("say /mo").items.is_empty(), "commands only at line start");
|
|
let a = c("look at @src/ma");
|
|
assert_eq!(
|
|
(a.start, labels(&a)),
|
|
(8, vec!["@src/main.rs", "@crates/x/src/main.rs"])
|
|
);
|
|
// cursor mid-line, non-ASCII before and inside the token
|
|
let l = "héllo @ü rest";
|
|
let u = complete(l, "héllo @ü".len(), &specs, &files);
|
|
assert_eq!((u.start, labels(&u)), (7, vec!["@docs/ü.md"]));
|
|
assert_eq!(
|
|
complete(l, 2, &specs, &files).items.len(),
|
|
0,
|
|
"mid-char cursor is safe"
|
|
);
|
|
assert_eq!(common_prefix(&["src/a", "src/b"]), "src/");
|
|
assert_eq!(common_prefix(&["ü1", "ü2"]), "ü");
|
|
|
|
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"));
|
|
}
|
|
}
|