fix(maestro): resolve command wrappers with a shell-aware tokenizer (#199)
command_program/command_tool whitespace-split and only skipped whole wrapper words, so quoted paths broke, sudo -u/env -i/nohup/time/npx --yes/pnpm|yarn --silent dlx/bun x were rejected, and pnpm claude / yarn claude (a package.json script, not `dlx claude`) resolved as a Claude launch. Replace it with a tokenizer that honours quoting and escaping without evaluating any expansion, and per-wrapper option tables (env, sudo, command, nohup, time, npx, pnpm, yarn, bun) that require dlx/x before looking through a package-manager wrapper. Ambiguous shell grammar (pipelines, list operators, redirections, substitution, unterminated quotes) is rejected outright rather than guessed through; command_program still degrades to the naive first word for display, but command_tool returns None. Mirror the same resolver in web/src/toolIcon.ts and add fixtures/command-resolution.json as a parity fixture both test suites assert against.
This commit is contained in:
@@ -166,45 +166,32 @@ pub fn merge_linear<T>(folder: TreeFolder<T>) -> TreeFolder<T> {
|
||||
cur
|
||||
}
|
||||
|
||||
/// Command wrappers that run another program: the program is what follows.
|
||||
const WRAPPERS: [&str; 8] = [
|
||||
"sudo", "env", "npx", "bunx", "uvx", "pnpm", "yarn", "command",
|
||||
];
|
||||
|
||||
/// The program a command line runs, basenamed and stripped of its arguments —
|
||||
/// what a session card shows per `docs/SIDEBAR.md`, which names the program
|
||||
/// and never its flags. Leading `FOO=bar` assignments and wrappers (`sudo`,
|
||||
/// `npx`, `pnpm dlx`, …) are looked through. Mirrors the web's `splitCommand`.
|
||||
/// `npx`, `pnpm dlx`, …) are looked through, and quoting/escaping is honoured
|
||||
/// (never evaluated — no `$var`/`` `cmd` ``/`$(cmd)` expansion). A command a
|
||||
/// shell would need real grammar for (pipelines, `&&`/`;`, redirections,
|
||||
/// substitution, an unterminated quote) falls back to the naive first word
|
||||
/// rather than guessing through it (#199). Mirrors the web's `splitCommand`.
|
||||
pub fn command_program(command: &str) -> String {
|
||||
let words: Vec<&str> = command.split_whitespace().collect();
|
||||
let mut i = 0;
|
||||
while i < words.len() {
|
||||
let word = words[i];
|
||||
if is_env_assignment(word) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let wrapper = basename(word).to_lowercase();
|
||||
if WRAPPERS.contains(&wrapper.as_str()) {
|
||||
i += 1;
|
||||
if (wrapper == "pnpm" || wrapper == "yarn") && words.get(i) == Some(&"dlx") {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
match words.get(i) {
|
||||
Some(word) => basename(word).to_string(),
|
||||
// Nothing but wrappers and assignments: say what was there rather than
|
||||
// rendering an empty fragment.
|
||||
None => command.trim().to_string(),
|
||||
match resolve(command) {
|
||||
Some(r) => match r.words.get(r.program_index) {
|
||||
Some(word) => basename(word).to_string(),
|
||||
// Nothing but wrappers and assignments: say what was there
|
||||
// rather than rendering an empty fragment.
|
||||
None => command.trim().to_string(),
|
||||
},
|
||||
None => legacy_first_word(command),
|
||||
}
|
||||
}
|
||||
|
||||
/// Program name (already basenamed and lowercased) -> the tool id its mark
|
||||
/// stands for. Mirrors the web's `BY_PROGRAM` in `web/src/toolIcon.ts`;
|
||||
/// recognition is deliberately narrow, so an unrecognised program has no tool.
|
||||
/// `claude-code-acp` — the daemon's actual structured-session child — is
|
||||
/// deliberately absent: the daemon launches it directly and ignores
|
||||
/// `req.command`, so it is never itself a valid user-facing launch form.
|
||||
const BY_PROGRAM: [(&str, &str); 17] = [
|
||||
("claude", "claude"),
|
||||
("claude-code", "claude"),
|
||||
@@ -226,17 +213,292 @@ const BY_PROGRAM: [(&str, &str); 17] = [
|
||||
];
|
||||
|
||||
/// The tool id a command line's icon stands for (`claude`, `codex`,
|
||||
/// `opencode`, ...), or `None` when the program is not one we have a mark for.
|
||||
/// The command bar matches this field (`docs/COMMAND-BAR.md`), so it must name
|
||||
/// the same tools the web's `splitCommand().tool` does.
|
||||
/// `opencode`, ...), or `None` when the program is not one we have a mark for
|
||||
/// — including a command line [`resolve`] would only guess at. The command
|
||||
/// bar matches this field (`docs/COMMAND-BAR.md`), so it must name the same
|
||||
/// tools the web's `splitCommand().tool` does.
|
||||
pub fn command_tool(command: &str) -> Option<&'static str> {
|
||||
let program = command_program(command).to_lowercase();
|
||||
let r = resolve(command)?;
|
||||
let program = basename(r.words.get(r.program_index)?).to_lowercase();
|
||||
BY_PROGRAM
|
||||
.iter()
|
||||
.find(|(name, _)| *name == program)
|
||||
.map(|(_, tool)| *tool)
|
||||
}
|
||||
|
||||
/// [`resolve`]'s outcome: the tokenized command line, and the index within it
|
||||
/// of the word that is the actual program (past every assignment/wrapper it
|
||||
/// resolved through).
|
||||
struct Resolution {
|
||||
words: Vec<String>,
|
||||
program_index: usize,
|
||||
}
|
||||
|
||||
/// Tokenize `command` and walk past leading `FOO=bar` assignments and known
|
||||
/// wrapper forms (interleaved in any order/count) to find the program. `None`
|
||||
/// when [`tokenize`] can't safely make sense of the line at all.
|
||||
fn resolve(command: &str) -> Option<Resolution> {
|
||||
let words = tokenize(command)?;
|
||||
let refs: Vec<&str> = words.iter().map(String::as_str).collect();
|
||||
let mut i = 0;
|
||||
while let Some(&word) = refs.get(i) {
|
||||
if is_env_assignment(word) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let wrapper = basename(word).to_lowercase();
|
||||
let Some(resolver) = wrapper_resolver(&wrapper) else {
|
||||
break;
|
||||
};
|
||||
match resolver(&refs, i) {
|
||||
Some(next) if next > i => i = next,
|
||||
// Not a form of the wrapper we recognise (an unknown option, or
|
||||
// — for `pnpm`/`yarn`/`bun` — no `dlx`/`x` subcommand behind it):
|
||||
// the wrapper word itself is the program, not a launcher.
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
Some(Resolution {
|
||||
words,
|
||||
program_index: i,
|
||||
})
|
||||
}
|
||||
|
||||
/// The naive "first whitespace word, basenamed" reading used only when
|
||||
/// [`tokenize`] rejects the line outright — still something sane to show,
|
||||
/// never a wrapper/tool match to act on.
|
||||
fn legacy_first_word(command: &str) -> String {
|
||||
match command.split_whitespace().next() {
|
||||
Some(word) => basename(word).to_string(),
|
||||
None => command.trim().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Word-split `command` the way a shell would (honouring `'…'`, `"…"` and
|
||||
/// `\` quoting/escaping — POSIX quote *removal*, not evaluation) and return
|
||||
/// `None` the moment it needs real shell grammar this resolver doesn't
|
||||
/// attempt: a pipeline/list operator (`|`, `&`, `;`, `<`, `>`), a subshell or
|
||||
/// substitution (`(`, `)`, `` ` ``, `$(`), or an unterminated quote/escape.
|
||||
/// Never expands `$var`/`` `cmd` ``/`$(cmd)` — a bare `$` is kept literal.
|
||||
fn tokenize(command: &str) -> Option<Vec<String>> {
|
||||
let mut words = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut has_current = false;
|
||||
let mut chars = command.chars().peekable();
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
' ' | '\t' | '\n' | '\r' => {
|
||||
if has_current {
|
||||
words.push(std::mem::take(&mut current));
|
||||
has_current = false;
|
||||
}
|
||||
}
|
||||
'|' | '&' | ';' | '<' | '>' | '(' | ')' | '`' => return None,
|
||||
'$' if chars.peek() == Some(&'(') => return None,
|
||||
'\'' => {
|
||||
has_current = true;
|
||||
loop {
|
||||
match chars.next() {
|
||||
Some('\'') => break,
|
||||
Some(c2) => current.push(c2),
|
||||
None => return None, // unterminated single quote
|
||||
}
|
||||
}
|
||||
}
|
||||
'"' => {
|
||||
has_current = true;
|
||||
loop {
|
||||
match chars.next() {
|
||||
Some('"') => break,
|
||||
Some('\\') => match chars.next() {
|
||||
Some(c2 @ ('"' | '\\' | '$' | '`')) => current.push(c2),
|
||||
Some(c2) => {
|
||||
current.push('\\');
|
||||
current.push(c2);
|
||||
}
|
||||
None => return None, // trailing backslash
|
||||
},
|
||||
Some(c2) => current.push(c2),
|
||||
None => return None, // unterminated double quote
|
||||
}
|
||||
}
|
||||
}
|
||||
'\\' => {
|
||||
has_current = true;
|
||||
current.push(chars.next()?); // None: trailing backslash
|
||||
}
|
||||
other => {
|
||||
has_current = true;
|
||||
current.push(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
if has_current {
|
||||
words.push(current);
|
||||
}
|
||||
Some(words)
|
||||
}
|
||||
|
||||
/// A wrapper's known `-`/`--` options: which take no value, and which
|
||||
/// consume either a following word or a `--flag=value` as theirs. A
|
||||
/// `-`-prefixed word this table doesn't know halts resolution rather than
|
||||
/// guessing past it (#199) — callers read that as [`OptionTable::consume`]
|
||||
/// returning `None`.
|
||||
struct OptionTable {
|
||||
flags: &'static [&'static str],
|
||||
valued: &'static [&'static str],
|
||||
}
|
||||
|
||||
impl OptionTable {
|
||||
/// Consume this table's options starting at `words[i]`, returning the
|
||||
/// index just past them (which may equal `i` if there are none) — or
|
||||
/// `None` on an option this table doesn't recognise, or a valued option
|
||||
/// missing its operand.
|
||||
fn consume(&self, words: &[&str], mut i: usize) -> Option<usize> {
|
||||
loop {
|
||||
let Some(&word) = words.get(i) else {
|
||||
return Some(i);
|
||||
};
|
||||
if word == "--" {
|
||||
return Some(i + 1);
|
||||
}
|
||||
if word == "-" || !word.starts_with('-') {
|
||||
return Some(i);
|
||||
}
|
||||
if let Some((flag, _)) = word.split_once('=') {
|
||||
return if self.valued.contains(&flag) {
|
||||
i += 1;
|
||||
continue;
|
||||
} else {
|
||||
None
|
||||
};
|
||||
}
|
||||
if self.flags.contains(&word) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if self.valued.contains(&word) {
|
||||
words.get(i + 1)?;
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const NO_OPTIONS: OptionTable = OptionTable {
|
||||
flags: &[],
|
||||
valued: &[],
|
||||
};
|
||||
|
||||
const ENV_OPTS: OptionTable = OptionTable {
|
||||
flags: &["-i", "--ignore-environment", "-0", "--null"],
|
||||
valued: &["-u", "--unset", "-C", "--chdir", "-S", "--split-string"],
|
||||
};
|
||||
|
||||
const SUDO_OPTS: OptionTable = OptionTable {
|
||||
flags: &[
|
||||
"-i",
|
||||
"--login",
|
||||
"-n",
|
||||
"--non-interactive",
|
||||
"-E",
|
||||
"--preserve-env",
|
||||
"-H",
|
||||
"--set-home",
|
||||
"-A",
|
||||
"--askpass",
|
||||
"-b",
|
||||
"--background",
|
||||
"-k",
|
||||
"--reset-timestamp",
|
||||
"-K",
|
||||
"--remove-timestamp",
|
||||
"-S",
|
||||
"--stdin",
|
||||
],
|
||||
valued: &["-u", "--user", "-g", "--group"],
|
||||
};
|
||||
|
||||
const COMMAND_BUILTIN_OPTS: OptionTable = OptionTable {
|
||||
flags: &["-p", "-v", "-V"],
|
||||
valued: &[],
|
||||
};
|
||||
|
||||
const TIME_OPTS: OptionTable = OptionTable {
|
||||
flags: &[
|
||||
"-p",
|
||||
"--portability",
|
||||
"-v",
|
||||
"--verbose",
|
||||
"-a",
|
||||
"--append",
|
||||
"-q",
|
||||
"--quiet",
|
||||
],
|
||||
valued: &["-o", "--output", "-f", "--format"],
|
||||
};
|
||||
|
||||
const NPX_OPTS: OptionTable = OptionTable {
|
||||
flags: &["-y", "--yes", "--no", "-q", "--quiet", "--ignore-existing"],
|
||||
valued: &["-p", "--package", "-c", "--call", "--shell"],
|
||||
};
|
||||
|
||||
const PNPM_OPTS: OptionTable = OptionTable {
|
||||
flags: &[
|
||||
"--silent",
|
||||
"-s",
|
||||
"--stream",
|
||||
"--aggregate-output",
|
||||
"--no-progress",
|
||||
],
|
||||
valued: &["-C", "--dir", "--filter"],
|
||||
};
|
||||
|
||||
const YARN_OPTS: OptionTable = OptionTable {
|
||||
flags: &["--silent", "-s", "--no-progress", "--non-interactive"],
|
||||
valued: &["--cwd"],
|
||||
};
|
||||
|
||||
/// A resolver for one wrapper form: given the tokenized command and the
|
||||
/// index of the wrapper word itself, the index of the word after it (past
|
||||
/// its options and any subcommand it requires), or `None` if this occurrence
|
||||
/// isn't a form we resolve through.
|
||||
type WrapperResolver = fn(&[&str], usize) -> Option<usize>;
|
||||
|
||||
fn wrapper_resolver(name: &str) -> Option<WrapperResolver> {
|
||||
match name {
|
||||
"env" => Some(|words, i| ENV_OPTS.consume(words, i + 1)),
|
||||
"sudo" => Some(|words, i| SUDO_OPTS.consume(words, i + 1)),
|
||||
"command" => Some(|words, i| COMMAND_BUILTIN_OPTS.consume(words, i + 1)),
|
||||
"nohup" => Some(|words, i| NO_OPTIONS.consume(words, i + 1)),
|
||||
"time" => Some(|words, i| TIME_OPTS.consume(words, i + 1)),
|
||||
"npx" => Some(|words, i| NPX_OPTS.consume(words, i + 1)),
|
||||
"pnpm" => Some(|words, i| resolve_dlx(&PNPM_OPTS, words, i)),
|
||||
"yarn" => Some(|words, i| resolve_dlx(&YARN_OPTS, words, i)),
|
||||
"bun" => Some(resolve_bun),
|
||||
"bunx" | "uvx" => Some(|_words, i| Some(i + 1)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `pnpm`/`yarn` only look through to the package behind an explicit `dlx`
|
||||
/// — without it, the next word is a `package.json` script name, not a
|
||||
/// package to run (#199: `pnpm claude` is not `pnpm dlx claude`).
|
||||
fn resolve_dlx(opts: &OptionTable, words: &[&str], i: usize) -> Option<usize> {
|
||||
let j = opts.consume(words, i + 1)?;
|
||||
(words.get(j) == Some(&"dlx")).then_some(j + 1)
|
||||
}
|
||||
|
||||
/// `bun x <pkg>` is bun's `dlx`/`npx` equivalent; `bun run <script>` is not
|
||||
/// (the same package-script ambiguity as bare `pnpm`/`yarn`), so only an `x`
|
||||
/// subcommand is looked through.
|
||||
fn resolve_bun(words: &[&str], i: usize) -> Option<usize> {
|
||||
(words.get(i + 1) == Some(&"x")).then_some(i + 2)
|
||||
}
|
||||
|
||||
/// `FOO=bar`, the shell's own prefix for one command's environment.
|
||||
fn is_env_assignment(word: &str) -> bool {
|
||||
let mut chars = word.chars();
|
||||
@@ -497,38 +759,80 @@ mod tests {
|
||||
"claude"
|
||||
);
|
||||
assert_eq!(command_program(" zsh -l "), "zsh");
|
||||
assert_eq!(command_program("hx src/main.rs"), "hx");
|
||||
}
|
||||
|
||||
/// The #199 resolver contract: every case in the shared parity fixture,
|
||||
/// asserted identically here and by `web/src/toolIcon.test.ts`, so a
|
||||
/// resolver regression in either language fails its own suite.
|
||||
#[test]
|
||||
fn command_program_looks_through_paths_env_and_wrappers() {
|
||||
assert_eq!(command_program("/usr/local/bin/claude -p hi"), "claude");
|
||||
assert_eq!(command_program("FOO=1 BAR=2 claude"), "claude");
|
||||
assert_eq!(command_program("npx opencode"), "opencode");
|
||||
assert_eq!(command_program("pnpm dlx opencode run"), "opencode");
|
||||
fn resolves_the_shared_command_resolution_fixture() {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Case {
|
||||
command: String,
|
||||
program: String,
|
||||
tool: Option<String>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Fixture {
|
||||
cases: Vec<Case>,
|
||||
}
|
||||
let raw = include_str!("../../../fixtures/command-resolution.json");
|
||||
let fixture: Fixture = serde_json::from_str(raw).expect("valid fixture JSON");
|
||||
assert!(!fixture.cases.is_empty());
|
||||
for case in &fixture.cases {
|
||||
assert_eq!(
|
||||
command_program(&case.command),
|
||||
case.program,
|
||||
"program for {:?}",
|
||||
case.command
|
||||
);
|
||||
assert_eq!(
|
||||
command_tool(&case.command),
|
||||
case.tool.as_deref(),
|
||||
"tool for {:?}",
|
||||
case.command
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shell-aware tokenization (#199): quoting/escaping is honoured, never
|
||||
/// evaluated — no `$var`/`` `cmd` ``/`$(cmd)` expansion is attempted.
|
||||
#[test]
|
||||
fn command_program_keeps_a_line_that_is_only_wrappers() {
|
||||
assert_eq!(command_program("sudo"), "sudo");
|
||||
assert_eq!(command_program(""), "");
|
||||
fn tokenize_handles_quotes_and_escapes_without_expanding_anything() {
|
||||
assert_eq!(
|
||||
tokenize("claude --resume"),
|
||||
Some(vec!["claude".into(), "--resume".into()])
|
||||
);
|
||||
assert_eq!(
|
||||
tokenize("\"/opt/my agent/claude\" --resume"),
|
||||
Some(vec!["/opt/my agent/claude".into(), "--resume".into()])
|
||||
);
|
||||
assert_eq!(
|
||||
tokenize("FOO=\"bar baz\" claude"),
|
||||
Some(vec!["FOO=bar baz".into(), "claude".into()])
|
||||
);
|
||||
assert_eq!(
|
||||
tokenize("claude --name=$HOME"),
|
||||
Some(vec!["claude".into(), "--name=$HOME".into()]),
|
||||
"a bare $ is kept literal, never expanded"
|
||||
);
|
||||
}
|
||||
|
||||
/// The command bar's `tool` field (docs/COMMAND-BAR.md) names the same
|
||||
/// tools the web's `splitCommand().tool` does.
|
||||
/// Real shell grammar this resolver doesn't attempt — pipelines, list
|
||||
/// operators, subshells/substitution, an unterminated quote — is
|
||||
/// rejected outright rather than guessed through (#199).
|
||||
#[test]
|
||||
fn command_tool_names_the_mark_the_card_shows() {
|
||||
assert_eq!(command_tool("claude --resume"), Some("claude"));
|
||||
assert_eq!(command_tool("npx opencode"), Some("opencode"));
|
||||
assert_eq!(command_tool("/bin/zsh -l"), Some("shell"));
|
||||
assert_eq!(command_tool("CLAUDE"), Some("claude"));
|
||||
}
|
||||
|
||||
/// Narrow on purpose: an unrecognised program has no mark, so the
|
||||
/// candidate has no `tool` field to match rather than a wrong one.
|
||||
#[test]
|
||||
fn command_tool_is_absent_for_an_unrecognised_program() {
|
||||
assert_eq!(command_tool("hx src/main.rs"), None);
|
||||
assert_eq!(command_tool(""), None);
|
||||
fn tokenize_rejects_ambiguous_shell_grammar() {
|
||||
for command in [
|
||||
"claude | tee log.txt",
|
||||
"claude; echo done",
|
||||
"claude && echo done",
|
||||
"echo hi $(claude)",
|
||||
"claude \"unterminated",
|
||||
"claude 'unterminated",
|
||||
"claude \\",
|
||||
] {
|
||||
assert_eq!(tokenize(command), None, "{command:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1941,10 +1941,28 @@ mod tests {
|
||||
("./bin/claude", true),
|
||||
("FOO=1 BAR=2 claude", true),
|
||||
("npx claude-code", true),
|
||||
("npx --yes claude-code", true),
|
||||
("sudo claude", true),
|
||||
("sudo -u root claude", true),
|
||||
("env -i claude", true),
|
||||
("nohup claude", true),
|
||||
("time claude", true),
|
||||
("command claude", true),
|
||||
("pnpm --silent dlx claude-code", true),
|
||||
("yarn --silent dlx claude-code", true),
|
||||
("bun x claude-code", true),
|
||||
("\"/opt/my agent/claude\" --resume", true),
|
||||
("bash", false),
|
||||
("opencode", false),
|
||||
("/usr/local/bin/bash -l", false),
|
||||
// A package-manager wrapper without `dlx`/`x` runs a
|
||||
// `package.json` script, not the package (#199) — must not be
|
||||
// mistaken for a Claude launch.
|
||||
("pnpm claude", false),
|
||||
("yarn claude", false),
|
||||
// The daemon's structured-session child, never a valid
|
||||
// user-facing launch form (#199).
|
||||
("claude-code-acp", false),
|
||||
];
|
||||
for &(command, supported) in cases {
|
||||
let mut draft = DraftPane {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"_description": "the parity fixture for #199's command resolver — every case here is asserted identically by crates/maestro-protocol/src/display.rs (command_program/command_tool) and web/src/toolIcon.ts (splitCommand). `program` is the resolved, basenamed program; `tool` is the icon id it maps to, or null when unrecognised/ambiguous.",
|
||||
"cases": [
|
||||
{ "command": "claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "claude --resume", "program": "claude", "tool": "claude" },
|
||||
{ "command": "CLAUDE", "program": "CLAUDE", "tool": "claude" },
|
||||
{ "command": "/usr/local/bin/claude -p hi", "program": "claude", "tool": "claude" },
|
||||
{ "command": "./bin/claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "FOO=1 BAR=2 claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "FOO=\"bar baz\" claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "'/usr/local/bin/claude'", "program": "claude", "tool": "claude" },
|
||||
{ "command": "\"/opt/my agent/claude\" --resume", "program": "claude", "tool": "claude" },
|
||||
{ "command": "env -i claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "env --ignore-environment claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "sudo -u root claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "sudo --user=root claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "sudo -- claude --resume", "program": "claude", "tool": "claude" },
|
||||
{ "command": "nohup claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "time claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "time -o /tmp/t.log claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "command claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "npx --yes claude-code", "program": "claude-code", "tool": "claude" },
|
||||
{ "command": "npx claude-code", "program": "claude-code", "tool": "claude" },
|
||||
{ "command": "pnpm --silent dlx claude-code", "program": "claude-code", "tool": "claude" },
|
||||
{ "command": "pnpm -C ./pkg dlx claude-code", "program": "claude-code", "tool": "claude" },
|
||||
{ "command": "pnpm dlx claude-code", "program": "claude-code", "tool": "claude" },
|
||||
{ "command": "yarn --silent dlx claude-code", "program": "claude-code", "tool": "claude" },
|
||||
{ "command": "bun x claude-code", "program": "claude-code", "tool": "claude" },
|
||||
{ "command": "bunx claude-code", "program": "claude-code", "tool": "claude" },
|
||||
{ "command": "uvx claude-code", "program": "claude-code", "tool": "claude" },
|
||||
{ "command": "sudo env -i claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "FOO=1 sudo BAR=2 claude", "program": "claude", "tool": "claude" },
|
||||
{ "command": "npx opencode", "program": "opencode", "tool": "opencode" },
|
||||
{ "command": "pnpm dlx opencode run", "program": "opencode", "tool": "opencode" },
|
||||
{ "command": "pnpm claude", "program": "pnpm", "tool": null },
|
||||
{ "command": "yarn claude", "program": "yarn", "tool": null },
|
||||
{ "command": "claude-code-acp", "program": "claude-code-acp", "tool": null },
|
||||
{ "command": "hx src/main.rs", "program": "hx", "tool": null },
|
||||
{ "command": "bash", "program": "bash", "tool": "shell" },
|
||||
{ "command": "opencode", "program": "opencode", "tool": "opencode" },
|
||||
{ "command": "sudo", "program": "sudo", "tool": null },
|
||||
{ "command": "", "program": "", "tool": null },
|
||||
{ "command": "npx --unknown-flag claude-code", "program": "npx", "tool": null },
|
||||
{ "command": "claude | tee log.txt", "program": "claude", "tool": null },
|
||||
{ "command": "claude; echo done", "program": "claude;", "tool": null },
|
||||
{ "command": "claude && echo done", "program": "claude", "tool": null },
|
||||
{ "command": "echo hi $(claude)", "program": "echo", "tool": null },
|
||||
{ "command": "claude \"unterminated", "program": "claude", "tool": null }
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { splitCommand, toolIconSvg } from "./toolIcon.js";
|
||||
import commandResolutionFixture from "../../fixtures/command-resolution.json";
|
||||
|
||||
interface CommandResolutionCase {
|
||||
command: string;
|
||||
program: string;
|
||||
tool: string | null;
|
||||
}
|
||||
|
||||
describe("tool icons on the command fragment (docs/SIDEBAR.md)", () => {
|
||||
it("recognises the agents and shells sessions are spawned with", () => {
|
||||
@@ -46,6 +53,14 @@ describe("tool icons on the command fragment (docs/SIDEBAR.md)", () => {
|
||||
expect(splitCommand("").tool).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves every case in the shared command-resolution fixture (#199)", () => {
|
||||
const cases = commandResolutionFixture.cases as CommandResolutionCase[];
|
||||
expect(cases.length).toBeGreaterThan(0);
|
||||
for (const { command, program, tool } of cases) {
|
||||
expect(splitCommand(command), command).toEqual({ tool, program });
|
||||
}
|
||||
});
|
||||
|
||||
it("gives every recognised tool a labelled mark", () => {
|
||||
for (const tool of ["claude", "codex", "opencode", "gemini", "aider", "cursor", "pi", "shell"]) {
|
||||
const svg = toolIconSvg(tool);
|
||||
|
||||
+247
-17
@@ -9,10 +9,11 @@
|
||||
* as text, so the fragment never renders a mark that stands for the wrong tool.
|
||||
*/
|
||||
|
||||
/** Command wrappers that run another program: the tool is what follows. */
|
||||
const WRAPPERS = new Set(["sudo", "env", "npx", "bunx", "uvx", "pnpm", "yarn", "command"]);
|
||||
|
||||
/** Program name (already basenamed and lowercased) → icon id. */
|
||||
/** Program name (already basenamed and lowercased) → icon id.
|
||||
*
|
||||
* `claude-code-acp` — the daemon's actual structured-session child — is
|
||||
* deliberately absent: the daemon launches it directly and ignores the
|
||||
* session's command, so it is never itself a valid user-facing launch form. */
|
||||
const BY_PROGRAM: Record<string, string> = {
|
||||
claude: "claude",
|
||||
"claude-code": "claude",
|
||||
@@ -53,15 +54,42 @@ export interface CommandParts {
|
||||
program: string;
|
||||
}
|
||||
|
||||
/** Split a command line into the tool its icon stands for and the program name.
|
||||
/** Split a command line into the tool its icon stands for and the program
|
||||
* name — basenamed and stripped of its arguments. Leading `FOO=bar`
|
||||
* assignments and wrapper forms (`sudo`, `env -i`, `npx`, `pnpm dlx`, …) are
|
||||
* looked through, and quoting/escaping is honoured (never evaluated — no
|
||||
* `$var`/`` `cmd` ``/`$(cmd)` expansion). A command a shell would need real
|
||||
* grammar for (pipelines, `&&`/`;`, redirections, substitution, an
|
||||
* unterminated quote) falls back to the naive first word rather than
|
||||
* guessing through it (#199). Mirrors the Rust `command_program`/
|
||||
* `command_tool` in `crates/maestro-protocol/src/display.rs`.
|
||||
*
|
||||
* `claude --resume` → `{tool: "claude", program: "claude"}`; an unrecognised
|
||||
* `hx src/` keeps `hx` as the program with no tool. */
|
||||
export function splitCommand(command: string): CommandParts {
|
||||
const words = command.trim().split(/\s+/).filter(Boolean);
|
||||
const words = tokenize(command);
|
||||
if (words === null) {
|
||||
const program = legacyFirstWord(command);
|
||||
return { tool: null, program };
|
||||
}
|
||||
const i = programIndex(words);
|
||||
if (i >= words.length) return { tool: null, program: command.trim() };
|
||||
const program = basename(words[i]);
|
||||
return { tool: BY_PROGRAM[program.toLowerCase()] ?? null, program };
|
||||
}
|
||||
|
||||
/** The naive "first whitespace word, basenamed" reading used only when
|
||||
* {@link tokenize} rejects the line outright — still something sane to
|
||||
* show, never a wrapper/tool match to act on. */
|
||||
function legacyFirstWord(command: string): string {
|
||||
const first = command.trim().split(/\s+/).filter(Boolean)[0];
|
||||
return first === undefined ? command.trim() : basename(first);
|
||||
}
|
||||
|
||||
/** Walk `words` past leading `FOO=bar` assignments and known wrapper forms
|
||||
* (interleaved in any order/count) to the index of the actual program. */
|
||||
function programIndex(words: string[]): number {
|
||||
let i = 0;
|
||||
// Leading `FOO=bar` assignments and wrappers stand in front of the real
|
||||
// program; `pnpm dlx x` / `yarn dlx x` need one more word skipped.
|
||||
while (i < words.length) {
|
||||
const word = words[i];
|
||||
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) {
|
||||
@@ -69,16 +97,16 @@ export function splitCommand(command: string): CommandParts {
|
||||
continue;
|
||||
}
|
||||
const wrapper = basename(word).toLowerCase();
|
||||
if (WRAPPERS.has(wrapper)) {
|
||||
i += 1;
|
||||
if ((wrapper === "pnpm" || wrapper === "yarn") && words[i] === "dlx") i += 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
const resolver = WRAPPER_RESOLVERS[wrapper];
|
||||
if (!resolver) break;
|
||||
const next = resolver(words, i);
|
||||
// Not a form of the wrapper we recognise (an unknown option, or — for
|
||||
// `pnpm`/`yarn`/`bun` — no `dlx`/`x` subcommand behind it): the wrapper
|
||||
// word itself is the program, not a launcher.
|
||||
if (next === null || next <= i) break;
|
||||
i = next;
|
||||
}
|
||||
if (i >= words.length) return { tool: null, program: command.trim() };
|
||||
const program = basename(words[i]);
|
||||
return { tool: BY_PROGRAM[program.toLowerCase()] ?? null, program };
|
||||
return i;
|
||||
}
|
||||
|
||||
function basename(word: string): string {
|
||||
@@ -86,6 +114,208 @@ function basename(word: string): string {
|
||||
return cut >= 0 ? word.slice(cut + 1) : word;
|
||||
}
|
||||
|
||||
/** Word-split `command` the way a shell would (honouring `'…'`, `"…"` and
|
||||
* `\` quoting/escaping — POSIX quote *removal*, not evaluation) and return
|
||||
* `null` the moment it needs real shell grammar this resolver doesn't
|
||||
* attempt: a pipeline/list operator (`|`, `&`, `;`, `<`, `>`), a subshell or
|
||||
* substitution (`(`, `)`, `` ` ``, `$(`), or an unterminated quote/escape.
|
||||
* Never expands `$var`/`` `cmd` ``/`$(cmd)` — a bare `$` is kept literal. */
|
||||
function tokenize(command: string): string[] | null {
|
||||
const words: string[] = [];
|
||||
let current = "";
|
||||
let hasCurrent = false;
|
||||
let i = 0;
|
||||
const n = command.length;
|
||||
|
||||
while (i < n) {
|
||||
const c = command[i];
|
||||
if (c === " " || c === "\t" || c === "\n" || c === "\r") {
|
||||
if (hasCurrent) {
|
||||
words.push(current);
|
||||
current = "";
|
||||
hasCurrent = false;
|
||||
}
|
||||
i += 1;
|
||||
} else if ("|&;<>()`".includes(c)) {
|
||||
return null;
|
||||
} else if (c === "$" && command[i + 1] === "(") {
|
||||
return null;
|
||||
} else if (c === "'") {
|
||||
hasCurrent = true;
|
||||
i += 1;
|
||||
const close = command.indexOf("'", i);
|
||||
if (close === -1) return null; // unterminated single quote
|
||||
current += command.slice(i, close);
|
||||
i = close + 1;
|
||||
} else if (c === '"') {
|
||||
hasCurrent = true;
|
||||
i += 1;
|
||||
for (;;) {
|
||||
if (i >= n) return null; // unterminated double quote
|
||||
const c2 = command[i];
|
||||
if (c2 === '"') {
|
||||
i += 1;
|
||||
break;
|
||||
}
|
||||
if (c2 === "\\") {
|
||||
const escaped = command[i + 1];
|
||||
if (escaped === undefined) return null; // trailing backslash
|
||||
current += '"\\$`'.includes(escaped) ? escaped : "\\" + escaped;
|
||||
i += 2;
|
||||
} else {
|
||||
current += c2;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
} else if (c === "\\") {
|
||||
const escaped = command[i + 1];
|
||||
if (escaped === undefined) return null; // trailing backslash
|
||||
hasCurrent = true;
|
||||
current += escaped;
|
||||
i += 2;
|
||||
} else {
|
||||
hasCurrent = true;
|
||||
current += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
if (hasCurrent) words.push(current);
|
||||
return words;
|
||||
}
|
||||
|
||||
/** A wrapper's known `-`/`--` options: which take no value, and which
|
||||
* consume either a following word or a `--flag=value` as theirs. A
|
||||
* `-`-prefixed word this table doesn't know halts resolution rather than
|
||||
* guessing past it (#199) — callers read that as {@link consumeOptions}
|
||||
* returning `null`. */
|
||||
interface OptionTable {
|
||||
flags: Set<string>;
|
||||
valued: Set<string>;
|
||||
}
|
||||
|
||||
/** Consume `opts`'s options starting at `words[i]`, returning the index just
|
||||
* past them (which may equal `i` if there are none) — or `null` on an
|
||||
* option this table doesn't recognise, or a valued option missing its
|
||||
* operand. */
|
||||
function consumeOptions(opts: OptionTable, words: string[], i: number): number | null {
|
||||
for (;;) {
|
||||
const word = words[i];
|
||||
if (word === undefined) return i;
|
||||
if (word === "--") return i + 1;
|
||||
if (word === "-" || !word.startsWith("-")) return i;
|
||||
const eq = word.indexOf("=");
|
||||
if (eq >= 0) {
|
||||
if (opts.valued.has(word.slice(0, eq))) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (opts.flags.has(word)) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (opts.valued.has(word)) {
|
||||
if (words[i + 1] === undefined) return null;
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const NO_OPTIONS: OptionTable = { flags: new Set(), valued: new Set() };
|
||||
|
||||
const ENV_OPTS: OptionTable = {
|
||||
flags: new Set(["-i", "--ignore-environment", "-0", "--null"]),
|
||||
valued: new Set(["-u", "--unset", "-C", "--chdir", "-S", "--split-string"]),
|
||||
};
|
||||
|
||||
const SUDO_OPTS: OptionTable = {
|
||||
flags: new Set([
|
||||
"-i",
|
||||
"--login",
|
||||
"-n",
|
||||
"--non-interactive",
|
||||
"-E",
|
||||
"--preserve-env",
|
||||
"-H",
|
||||
"--set-home",
|
||||
"-A",
|
||||
"--askpass",
|
||||
"-b",
|
||||
"--background",
|
||||
"-k",
|
||||
"--reset-timestamp",
|
||||
"-K",
|
||||
"--remove-timestamp",
|
||||
"-S",
|
||||
"--stdin",
|
||||
]),
|
||||
valued: new Set(["-u", "--user", "-g", "--group"]),
|
||||
};
|
||||
|
||||
const COMMAND_BUILTIN_OPTS: OptionTable = {
|
||||
flags: new Set(["-p", "-v", "-V"]),
|
||||
valued: new Set(),
|
||||
};
|
||||
|
||||
const TIME_OPTS: OptionTable = {
|
||||
flags: new Set(["-p", "--portability", "-v", "--verbose", "-a", "--append", "-q", "--quiet"]),
|
||||
valued: new Set(["-o", "--output", "-f", "--format"]),
|
||||
};
|
||||
|
||||
const NPX_OPTS: OptionTable = {
|
||||
flags: new Set(["-y", "--yes", "--no", "-q", "--quiet", "--ignore-existing"]),
|
||||
valued: new Set(["-p", "--package", "-c", "--call", "--shell"]),
|
||||
};
|
||||
|
||||
const PNPM_OPTS: OptionTable = {
|
||||
flags: new Set(["--silent", "-s", "--stream", "--aggregate-output", "--no-progress"]),
|
||||
valued: new Set(["-C", "--dir", "--filter"]),
|
||||
};
|
||||
|
||||
const YARN_OPTS: OptionTable = {
|
||||
flags: new Set(["--silent", "-s", "--no-progress", "--non-interactive"]),
|
||||
valued: new Set(["--cwd"]),
|
||||
};
|
||||
|
||||
/** `pnpm`/`yarn` only look through to the package behind an explicit `dlx`
|
||||
* — without it, the next word is a `package.json` script name, not a
|
||||
* package to run (#199: `pnpm claude` is not `pnpm dlx claude`). */
|
||||
function resolveDlx(opts: OptionTable, words: string[], i: number): number | null {
|
||||
const j = consumeOptions(opts, words, i + 1);
|
||||
if (j === null) return null;
|
||||
return words[j] === "dlx" ? j + 1 : null;
|
||||
}
|
||||
|
||||
/** `bun x <pkg>` is bun's `dlx`/`npx` equivalent; `bun run <script>` is not
|
||||
* (the same package-script ambiguity as bare `pnpm`/`yarn`), so only an `x`
|
||||
* subcommand is looked through. */
|
||||
function resolveBun(words: string[], i: number): number | null {
|
||||
return words[i + 1] === "x" ? i + 2 : null;
|
||||
}
|
||||
|
||||
/** A resolver for one wrapper form: given the tokenized command and the
|
||||
* index of the wrapper word itself, the index of the word after it (past
|
||||
* its options and any subcommand it requires), or `null` if this occurrence
|
||||
* isn't a form we resolve through. */
|
||||
type WrapperResolver = (words: string[], i: number) => number | null;
|
||||
|
||||
const WRAPPER_RESOLVERS: Record<string, WrapperResolver> = {
|
||||
env: (words, i) => consumeOptions(ENV_OPTS, words, i + 1),
|
||||
sudo: (words, i) => consumeOptions(SUDO_OPTS, words, i + 1),
|
||||
command: (words, i) => consumeOptions(COMMAND_BUILTIN_OPTS, words, i + 1),
|
||||
nohup: (words, i) => consumeOptions(NO_OPTIONS, words, i + 1),
|
||||
time: (words, i) => consumeOptions(TIME_OPTS, words, i + 1),
|
||||
npx: (words, i) => consumeOptions(NPX_OPTS, words, i + 1),
|
||||
pnpm: (words, i) => resolveDlx(PNPM_OPTS, words, i),
|
||||
yarn: (words, i) => resolveDlx(YARN_OPTS, words, i),
|
||||
bun: resolveBun,
|
||||
bunx: (_words, i) => i + 1,
|
||||
uvx: (_words, i) => i + 1,
|
||||
};
|
||||
|
||||
/** Anthropic's burst: tapered rays around a centre, long ones on the axes. */
|
||||
function burst(): string {
|
||||
const rays = Array.from({ length: 8 }, (_, k) => {
|
||||
|
||||
Reference in New Issue
Block a user