diff --git a/README.md b/README.md index d690143..69fc20d 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,8 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off ## Subagents +Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt; `read` and read-only `bash` (`ls cat head tail wc grep rg fd pwd echo stat file du df which tree diff`, `git status|log|diff|show|branch|blame|ls-files|rev-parse`) run freely, unless chained/redirected or a path looks secret (`.env*`, `.ssh/`, `.aws/`, `*.pem`, `*.key`, `id_rsa*`, `.netrc`, `.git-credentials`, `auth.json`), which asks first. `--yolo` skips all prompts. + The model can call `task(prompt, kind)` to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `.sub/`; `hx stats` lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet. A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens. diff --git a/crates/hx-core/src/permit.rs b/crates/hx-core/src/permit.rs index 221bcd1..93bc467 100644 --- a/crates/hx-core/src/permit.rs +++ b/crates/hx-core/src/permit.rs @@ -1,4 +1,4 @@ -//! Permission gate for mutating tools (bash, write, edit) and the edits log behind `/review`. +//! Permission gate for mutating tools (bash, write, edit) and secret reads and the edits log behind `/review`. use std::collections::HashSet; use std::path::{Path, PathBuf}; @@ -8,6 +8,61 @@ pub fn gated(tool: &str) -> bool { matches!(tool, "bash" | "write" | "edit") } +/// 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. +const READONLY: &[&str] = &[ + "ls", "cat", "head", "tail", "wc", "grep", "rg", "fd", "pwd", "echo", "stat", "file", "du", + "df", "which", "tree", "diff", +]; +const READONLY_GIT: &[&str] = &[ + "status", + "log", + "diff", + "show", + "branch", + "blame", + "ls-files", + "rev-parse", +]; + +/// Paths that hold credentials: reading them asks first. +// ponytail: name/dir patterns only; add content sniffing if needed. +pub fn secret(path: &str) -> bool { + let p = path.trim_matches(['"', '\'']); + let comps: Vec<&str> = p.split('/').collect(); + let name = comps.last().copied().unwrap_or_default(); + comps + .iter() + .any(|c| matches!(*c, ".ssh" | ".aws" | ".gnupg")) + || name.starts_with(".env") + || name.starts_with("id_rsa") + || name.starts_with("id_ed25519") + || name.starts_with("credentials") + || matches!(name, ".netrc" | ".git-credentials" | "auth.json") + || name.ends_with(".pem") + || name.ends_with(".key") +} + +fn readonly_cmd(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), + }; + ok && !compound(cmd) && !w.iter().any(|a| secret(a)) +} + +/// Does this call need a yes? Writes and unknown commands do; reads of non-secret files do not. +pub fn needs_permit(tool: &str, args: &serde_json::Value) -> bool { + let a = |k: &str| args[k].as_str().unwrap_or_default(); + match tool { + "bash" => !readonly_cmd(a("command").trim()), + "read" => secret(a("path")), + _ => gated(tool), + } +} + /// What the user is asked. #[derive(Debug, Clone, PartialEq)] pub struct Request { @@ -180,6 +235,22 @@ mod tests { assert!(gated("bash") && !gated("read")); } + #[test] + fn reads_are_free_unless_secret() { + let ask = |t: &str, k: &str, v: &str| needs_permit(t, &json!({ k: v })); + assert!(!ask("read", "path", "src/main.rs")); + assert!(ask("read", "path", ".env") && ask("read", "path", "/h/.ssh/config")); + assert!(ask("read", "path", "certs/a.pem")); + assert!(!ask("bash", "command", "ls -l")); + 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", "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", "")); + assert!(ask("write", "path", "a") && ask("edit", "path", "a")); + } + #[test] fn rules_match_narrowly() { let d = tempfile::tempdir().unwrap(); diff --git a/crates/hx-core/src/tool.rs b/crates/hx-core/src/tool.rs index 3805d77..fdb690c 100644 --- a/crates/hx-core/src/tool.rs +++ b/crates/hx-core/src/tool.rs @@ -105,7 +105,7 @@ impl Registry { if let Err(e) = validate(&t.spec().input_schema, &args) { return ToolResult::err(e); } - if crate::permit::gated(name) + if crate::permit::needs_permit(name, &args) && let Some(ask) = cx.state.permit.get() { let req = crate::permit::request(name, &args); @@ -215,14 +215,16 @@ mod tests { }); let _ = c.state.permit.set(p); assert_eq!( - r.call("bash", json!({"command": "ls -l"}), &c) + r.call("bash", json!({"command": "mkdir -p a"}), &c) .await .content, "ran" ); - // rule bash:ls remembered: no second prompt + // rule bash:mkdir remembered: no second prompt assert_eq!( - r.call("bash", json!({"command": "ls"}), &c).await.content, + r.call("bash", json!({"command": "mkdir b"}), &c) + .await + .content, "ran" ); assert_eq!(*asked.lock().unwrap(), 1); diff --git a/tests/fake_anthropic.py b/tests/fake_anthropic.py index 00cbca5..c3412c4 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 cat. Turn 3: final text. +Turn 1: tool_use write hello.txt. Turn 2: tool_use bash sort. 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": "cat hello.txt"}})], + [("tool_use", {"id": "t2", "name": "Bash", "input": {"command": "sort 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 05426cc..876d56f 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", "cat hello"]\n' "$root" >> "$tmp/home/.hx/config.toml" +printf '[[extensions]]\ncommand = ["python3", "%s/examples/ext_guard.py", "sort 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: `cat hello` is not allowed" in log, "no block" +assert "blocked: ext_guard: `sort 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 0c84d4d..4bf1a3d 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 always rule", "allow always: write") send(b"y", 2) -check("second prompt for bash", "allow always: cat *") +check("second prompt for bash", "allow always: sort *") send(b"y", 3) check("tool call shown", "hello.txt") check("tool outcome", "1 lines")