M8: command registry, skills as slash commands, completion engine + popup, rpc complete
Closes #68, closes #69, closes #70, closes #71, closes #72
This commit is contained in:
1 parent
6f0addcd47
commit
65765ce2b3
10 files changed
+651
-125
No files matched your search
@@ -0,0 +1,321 @@
|
||||
//! 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,
|
||||
}
|
||||
|
||||
impl CmdSpec {
|
||||
pub fn new(name: &str, summary: &str, source: Source, args: ArgKind) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
summary: summary.into(),
|
||||
source,
|
||||
args,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(models.iter().map(|m| m.to_string()).collect()),
|
||||
),
|
||||
b(
|
||||
"provider",
|
||||
"switch provider",
|
||||
Enum(vec!["claude".into(), "codex".into()]),
|
||||
),
|
||||
b("compact", "summarize old context", None),
|
||||
b("clear", "start an empty session", None),
|
||||
b("lsp", "language server status", None),
|
||||
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,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The prompt a `/<skill> args` command sends.
|
||||
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 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()
|
||||
))
|
||||
}
|
||||
|
||||
/// `/help` text generated from the registry.
|
||||
pub fn help(specs: &[CmdSpec]) -> String {
|
||||
specs
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let arg = match &s.args {
|
||||
ArgKind::None => "",
|
||||
ArgKind::Path => " <path>",
|
||||
_ => " [args]",
|
||||
};
|
||||
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;
|
||||
|
||||
/// 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 items = 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_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 }
|
||||
}
|
||||
|
||||
fn detail(s: &CmdSpec) -> String {
|
||||
let tag = match s.source {
|
||||
Source::Builtin => "",
|
||||
Source::Skill(_) => "skill · ",
|
||||
Source::Mcp => "mcp · ",
|
||||
Source::Ext => "ext · ",
|
||||
};
|
||||
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 {
|
||||
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-4-5", "claude-opus-4-1", "gpt-5-codex"]);
|
||||
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")), ["/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-4-1"]));
|
||||
assert_eq!(c("/model ").items.len(), 3);
|
||||
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}");
|
||||
let h = help(&specs);
|
||||
assert!(h.contains("/model [args] — show or switch model") && h.contains("/review"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user