Guide models to read-only inspection: prompt rules, pipes and find in the read-only gate, approval stats
This commit is contained in:
1 parent
8345d0f504
commit
37dfbc3102
7 files changed
+70
-11
No files matched your search
@@ -3,7 +3,12 @@
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
pub const DEFAULT_PROMPT: &str = "You are hx, a coding agent working in the user's repository. \
|
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"];
|
const CONTEXT_FILES: &[&str] = &["AGENTS.md", "CLAUDE.md"];
|
||||||
|
|
||||||
@@ -189,6 +194,14 @@ pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> String {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn prompt_assembly() {
|
fn prompt_assembly() {
|
||||||
let t = tempfile::tempdir().unwrap();
|
let t = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -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).
|
/// 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] = &[
|
const READONLY: &[&str] = &[
|
||||||
"ls", "cat", "head", "tail", "wc", "grep", "rg", "fd", "pwd", "echo", "stat", "file", "du",
|
"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] = &[
|
const READONLY_GIT: &[&str] = &[
|
||||||
"status",
|
"status",
|
||||||
@@ -44,13 +49,18 @@ pub fn secret(path: &str) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn readonly_cmd(cmd: &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 w: Vec<&str> = cmd.split_whitespace().collect();
|
||||||
let ok = match w.as_slice() {
|
let ok = match w.as_slice() {
|
||||||
[] => false,
|
[] => false,
|
||||||
["git", sub, ..] => READONLY_GIT.contains(sub),
|
["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.
|
/// Does this call need a yes? Writes and unknown commands do; reads of non-secret files do not.
|
||||||
@@ -257,6 +267,14 @@ mod tests {
|
|||||||
assert!(!ask("bash", "command", "git status"));
|
assert!(!ask("bash", "command", "git status"));
|
||||||
assert!(!ask("bash", "command", "grep -rn foo src"));
|
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", "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", "cat a | rm x") && ask("bash", "command", "ls > f"));
|
||||||
assert!(ask("bash", "command", "git push") && ask("bash", "command", "find . -delete"));
|
assert!(ask("bash", "command", "git push") && ask("bash", "command", "find . -delete"));
|
||||||
assert!(ask("bash", "command", "cargo test") && ask("bash", "command", ""));
|
assert!(ask("bash", "command", "cargo test") && ask("bash", "command", ""));
|
||||||
|
|||||||
@@ -135,6 +135,34 @@ pub fn report(s: &Session) -> String {
|
|||||||
call_b / 4
|
call_b / 4
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// bash calls that ask for approval, by first word: shows which habits break the read-only flow
|
||||||
|
let mut asks: HashMap<String, u32> = 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<String> = 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
|
// carried cost of tool results on the current path
|
||||||
let mut names: HashMap<&str, &str> = HashMap::new();
|
let mut names: HashMap<&str, &str> = HashMap::new();
|
||||||
for m in &msgs {
|
for m in &msgs {
|
||||||
|
|||||||
@@ -310,7 +310,7 @@ impl Tool for Bash {
|
|||||||
fn spec(&self) -> ToolSpec {
|
fn spec(&self) -> ToolSpec {
|
||||||
spec(
|
spec(
|
||||||
"bash",
|
"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":{
|
json!({"type":"object","properties":{
|
||||||
"command":{"type":"string"},
|
"command":{"type":"string"},
|
||||||
"timeout":{"type":"integer","description":"seconds, default 120"}},
|
"timeout":{"type":"integer","description":"seconds, default 120"}},
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
"""Scripted fake of the Anthropic SSE API for end-to-end tests of `hx -p`.
|
"""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]
|
Usage: python3 tests/fake_anthropic.py PORT [TURNS.json]
|
||||||
"""
|
"""
|
||||||
import http.server, json, sys
|
import http.server, json, sys
|
||||||
|
|
||||||
TURNS = [
|
TURNS = [
|
||||||
[("tool_use", {"id": "t1", "name": "Write", "input": {"path": "hello.txt", "content": "hi from hx\n"}})],
|
[("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.")],
|
[("text", "Done: file says hi from hx.")],
|
||||||
]
|
]
|
||||||
if len(sys.argv) > 2: # optional scripted turns: JSON [[["tool_use", {...}] | ["text", "..."], ...], ...]
|
if len(sys.argv) > 2: # optional scripted turns: JSON [[["tool_use", {...}] | ["text", "..."], ...], ...]
|
||||||
|
|||||||
+2
-2
@@ -52,13 +52,13 @@ kill $srv; rm -f hello.txt
|
|||||||
|
|
||||||
# 3) extension blocks the bash call (cat) and registers its tool
|
# 3) extension blocks the bash call (cat) and registers its tool
|
||||||
start 3
|
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"
|
"$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"
|
python3 - "$tmp/ext" <<'PY' || fail "ext block" "$tmp/ext"
|
||||||
import json, sys
|
import json, sys
|
||||||
ev = [json.loads(l) for l in open(sys.argv[1])]
|
ev = [json.loads(l) for l in open(sys.argv[1])]
|
||||||
log = json.dumps(ev)
|
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"]
|
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
|
assert len(bash) == 1 and bash[0]["is_error"] and bash[0]["content"].startswith("blocked:"), bash
|
||||||
PY
|
PY
|
||||||
|
|||||||
+1
-1
@@ -69,7 +69,7 @@ send(b"make hello.txt"); send(b"\r", 2)
|
|||||||
check("permission prompt", "permission")
|
check("permission prompt", "permission")
|
||||||
check("allow always rule", "allow always: write")
|
check("allow always rule", "allow always: write")
|
||||||
send(b"y", 2)
|
send(b"y", 2)
|
||||||
check("second prompt for bash", "allow always: sort *")
|
check("second prompt for bash", "allow always: sed *")
|
||||||
send(b"y", 3)
|
send(b"y", 3)
|
||||||
check("tool call shown", "hello.txt")
|
check("tool call shown", "hello.txt")
|
||||||
check("tool outcome", "1 lines")
|
check("tool outcome", "1 lines")
|
||||||
|
|||||||
Reference in new issue
Block a user