diff --git a/crates/hx-core/src/context.rs b/crates/hx-core/src/context.rs index 5f6e57e..804a3fb 100644 --- a/crates/hx-core/src/context.rs +++ b/crates/hx-core/src/context.rs @@ -3,7 +3,12 @@ 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."; +Use the tools to read, edit and run code. Read files before editing them. Keep answers short.\n\n\ +# Working rules\n\ +- Inspect with the tools, not scripts: `read` for files, `rg` to search text, `fd` or `find` to list files, `ls`/`tree` for directories.\n\ +- Never use node, python, perl, sed or awk to look at files or data; they need user approval every time. Read-only commands (ls cat head tail rg fd find grep wc jq sort, git status/log/diff/show) run without a prompt, also piped into each other.\n\ +- One simple command per call: no `;`, `&&`, redirects, `$()`. Those need approval too.\n\ +- Script only when the task needs it (build, test, edit), not to explore."; const CONTEXT_FILES: &[&str] = &["AGENTS.md", "CLAUDE.md"]; @@ -190,6 +195,14 @@ pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> String { mod tests { use super::*; + #[test] + fn default_prompt_has_working_rules() { + assert!( + DEFAULT_PROMPT.contains("never use node") || DEFAULT_PROMPT.contains("Never use node") + ); + assert!(DEFAULT_PROMPT.contains("`rg`")); + } + #[test] fn prompt_assembly() { let t = tempfile::tempdir().unwrap(); diff --git a/crates/hx-core/src/permit.rs b/crates/hx-core/src/permit.rs index e15fcb8..526226e 100644 --- a/crates/hx-core/src/permit.rs +++ b/crates/hx-core/src/permit.rs @@ -9,10 +9,15 @@ pub fn gated(tool: &str) -> bool { } /// Read-only commands that run without a prompt (when not compound and no argument is a secret). -/// Not listed on purpose: find (-exec/-delete), env, xargs, sed, cargo, curl. +/// Pipes are fine when every segment is read-only. Not listed on purpose: env, xargs, sed, cargo, curl. const READONLY: &[&str] = &[ "ls", "cat", "head", "tail", "wc", "grep", "rg", "fd", "pwd", "echo", "stat", "file", "du", - "df", "which", "tree", "diff", + "df", "which", "tree", "diff", "sort", "cut", "nl", "tr", "jq", "find", +]; +/// `find` actions that run or write; `sort -o` writes a file. +const WRITING_FLAGS: &[&str] = &[ + "-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls", + "-o", "--output", ]; const READONLY_GIT: &[&str] = &[ "status", @@ -44,13 +49,18 @@ pub fn secret(path: &str) -> bool { } fn readonly_cmd(cmd: &str) -> bool { + // `||` yields an empty segment, which is rejected + !cmd.is_empty() && cmd.split('|').all(|seg| readonly_simple(seg.trim())) +} + +fn readonly_simple(cmd: &str) -> bool { let w: Vec<&str> = cmd.split_whitespace().collect(); let ok = match w.as_slice() { [] => false, ["git", sub, ..] => READONLY_GIT.contains(sub), - [c, ..] => READONLY.contains(c), + [c, args @ ..] => READONLY.contains(c) && !args.iter().any(|a| WRITING_FLAGS.contains(a)), }; - ok && !compound(cmd) && !w.iter().any(|a| secret(a)) + ok && !compound(&cmd.replace('|', "")) && !w.iter().any(|a| secret(a)) } /// Does this call need a yes? Writes and unknown commands do; reads of non-secret files do not. @@ -265,6 +275,14 @@ mod tests { assert!(!ask("bash", "command", "git status")); assert!(!ask("bash", "command", "grep -rn foo src")); assert!(ask("bash", "command", "cat .env") && ask("bash", "command", "cat ~/.ssh/id_rsa")); + assert!(!ask("bash", "command", "rg foo src | head -5")); + assert!(!ask("bash", "command", "find . -name '*.rs' | sort | head")); + assert!(!ask("bash", "command", "cat a.json | jq .x")); + assert!( + ask("bash", "command", "find . -exec rm {} +") && ask("bash", "command", "sort -o f f") + ); + assert!(ask("bash", "command", "ls || rm x") && ask("bash", "command", "ls | sh")); + assert!(ask("bash", "command", "node -e 1") && ask("bash", "command", "python3 -c 1")); assert!(ask("bash", "command", "cat a | rm x") && ask("bash", "command", "ls > f")); assert!(ask("bash", "command", "git push") && ask("bash", "command", "find . -delete")); assert!(ask("bash", "command", "cargo test") && ask("bash", "command", "")); diff --git a/crates/hx-core/src/stats.rs b/crates/hx-core/src/stats.rs index f234a81..d4a97bd 100644 --- a/crates/hx-core/src/stats.rs +++ b/crates/hx-core/src/stats.rs @@ -135,6 +135,34 @@ pub fn report(s: &Session) -> String { call_b / 4 ); + // bash calls that ask for approval, by first word: shows which habits break the read-only flow + let mut asks: HashMap = HashMap::new(); + for m in msgs.iter().filter(|m| m.role == Role::Assistant) { + for b in &m.content { + if let ContentBlock::ToolUse { name, input, .. } = b + && name == "bash" + && crate::permit::needs_permit(name, input) + { + { + let c = input["command"].as_str().unwrap_or_default(); + *asks + .entry(c.split_whitespace().next().unwrap_or("").into()) + .or_default() += 1; + } + } + } + } + if !asks.is_empty() { + let mut v: Vec<_> = asks.into_iter().collect(); + v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + let list: Vec = v.iter().take(8).map(|(c, n)| format!("{c} {n}")).collect(); + let _ = writeln!( + o, + "approval prompts from bash, by command: {}", + list.join(", ") + ); + } + // carried cost of tool results on the current path let mut names: HashMap<&str, &str> = HashMap::new(); for m in &msgs { diff --git a/crates/hx-tools/src/lib.rs b/crates/hx-tools/src/lib.rs index 197bcf0..16375e0 100644 --- a/crates/hx-tools/src/lib.rs +++ b/crates/hx-tools/src/lib.rs @@ -316,7 +316,7 @@ impl Tool for Bash { fn spec(&self) -> ToolSpec { spec( "bash", - "Run a shell command in the working directory. stdout and stderr are merged. Long output keeps the start and the end; the middle is cut and the full output saved to a file.", + "Run a shell command in the working directory. Read-only commands (ls cat head tail rg fd find grep wc jq sort, git status/log/diff/show, piped together) run at once; everything else, e.g. node, python, sed, cargo, asks the user first. To inspect files prefer read/rg/fd. stdout and stderr are merged. Long output keeps the start and the end; the middle is cut and the full output saved to a file.", json!({"type":"object","properties":{ "command":{"type":"string"}, "timeout":{"type":"integer","description":"seconds, default 120"}}, diff --git a/tests/fake_anthropic.py b/tests/fake_anthropic.py index c3412c4..f97b1fe 100644 --- a/tests/fake_anthropic.py +++ b/tests/fake_anthropic.py @@ -1,13 +1,13 @@ """Scripted fake of the Anthropic SSE API for end-to-end tests of `hx -p`. -Turn 1: tool_use write hello.txt. Turn 2: tool_use bash sort. Turn 3: final text. +Turn 1: tool_use write hello.txt. Turn 2: tool_use bash sed. Turn 3: final text. Usage: python3 tests/fake_anthropic.py PORT [TURNS.json] """ import http.server, json, sys TURNS = [ [("tool_use", {"id": "t1", "name": "Write", "input": {"path": "hello.txt", "content": "hi from hx\n"}})], - [("tool_use", {"id": "t2", "name": "Bash", "input": {"command": "sort hello.txt"}})], + [("tool_use", {"id": "t2", "name": "Bash", "input": {"command": "sed -n p hello.txt"}})], [("text", "Done: file says hi from hx.")], ] if len(sys.argv) > 2: # optional scripted turns: JSON [[["tool_use", {...}] | ["text", "..."], ...], ...] diff --git a/tests/m7_e2e.sh b/tests/m7_e2e.sh index 876d56f..ad7cc43 100644 --- a/tests/m7_e2e.sh +++ b/tests/m7_e2e.sh @@ -52,13 +52,13 @@ kill $srv; rm -f hello.txt # 3) extension blocks the bash call (cat) and registers its tool start 3 -printf '[[extensions]]\ncommand = ["python3", "%s/examples/ext_guard.py", "sort hello"]\n' "$root" >> "$tmp/home/.hx/config.toml" +printf '[[extensions]]\ncommand = ["python3", "%s/examples/ext_guard.py", "sed -n p hello"]\n' "$root" >> "$tmp/home/.hx/config.toml" "$root/target/debug/hx" -p "go" --mode json > "$tmp/ext" 2> "$tmp/err" || fail "ext run" "$tmp/err" python3 - "$tmp/ext" <<'PY' || fail "ext block" "$tmp/ext" import json, sys ev = [json.loads(l) for l in open(sys.argv[1])] log = json.dumps(ev) -assert "blocked: ext_guard: `sort hello` is not allowed" in log, "no block" +assert "blocked: ext_guard: `sed -n p hello` is not allowed" in log, "no block" bash = [e for e in ev if e["type"] == "tool_result" and e["name"] == "bash"] assert len(bash) == 1 and bash[0]["is_error"] and bash[0]["content"].startswith("blocked:"), bash PY diff --git a/tests/tui_smoke.py b/tests/tui_smoke.py index 14b3947..d65ce5e 100644 --- a/tests/tui_smoke.py +++ b/tests/tui_smoke.py @@ -69,7 +69,7 @@ send(b"make hello.txt"); send(b"\r", 2) check("permission prompt", "permission") check("allow all edits option", "allow all edits this session") send(b"y", 2) -check("second prompt for bash", "allow always: sort *") +check("second prompt for bash", "allow always: sed *") send(b"y", 3) check("tool call shown", "hello.txt") check("tool outcome", "1 lines")