diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 9e903d8..6ef6631 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -454,6 +454,8 @@ fn pricing(model: &str) -> Option { /// `[openai_compat]` from config, set once at startup. static COMPAT: std::sync::OnceLock = std::sync::OnceLock::new(); +/// `codemode` from config: also offer the codemode tool to claude. +static CODEMODE: std::sync::OnceLock = std::sync::OnceLock::new(); /// `claude_cli` from config: extra args for the `claude` binary. static CLAUDE_CLI: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -464,11 +466,14 @@ fn provider(k: Kind) -> hx_ai::Result> { hx_ai::claude_cli::ClaudeCli::new(CLAUDE_CLI.get().cloned().unwrap_or_default()); let c = c.with_spawner(Arc::new(|bin| Box::pin(claude_command(bin)))); Arc::new(match std::env::current_exe() { - Ok(e) => c.with_mcp( - e.to_string_lossy().into(), - vec!["mcp-serve".into()], - serde_json::json!({ hx_core::approve::ENV: hx_core::approve::sock_path() }), - ), + Ok(e) => c.with_mcp(e.to_string_lossy().into(), vec!["mcp-serve".into()], { + let mut env = + serde_json::json!({ hx_core::approve::ENV: hx_core::approve::sock_path() }); + if CODEMODE.get().copied().unwrap_or(false) { + env["HX_CODEMODE"] = "1".into(); + } + env + }), Err(_) => c, }) } @@ -708,13 +713,35 @@ async fn main() -> Result<()> { )); let mut reg = hx_core::tool::Registry::default(); reg.add(hx_lens::LspTool::new(mgr.clone())); - if let Some(p) = std::env::var_os(hx_core::approve::ENV) { - reg.add(hx_core::approve::Approve(p.into())); - } let cx = ToolCtx { - cwd, + cwd: cwd.clone(), state: Default::default(), }; + let sock = std::env::var_os(hx_core::approve::ENV); + if let Some(p) = &sock { + reg.add(hx_core::approve::Approve(p.into())); + // tools run by codemode ask hx for permission like any other + let _ = cx + .state + .permit + .set(hx_core::approve::remote_permit(p.into())); + } + if std::env::var_os("HX_CODEMODE").is_some() { + // claude keeps its own tools; only `codemode` is added, and scripts may call the hx tools + let cfg = Config::load(&cwd)?; + let hub = Arc::new( + hx_mcp::Hub::start( + hx_mcp::config::load(&context::hx_home(), &cwd) + .map_err(anyhow::Error::msg)?, + ) + .await, + ); + let mut all = hx_tools::registry(); + hx_tools::web::register(&mut all, web_search(&cfg)); + hub.register(&mut all); + all.add(hx_lens::LspTool::new(mgr.clone())); + reg.add(hx_tools::codemode::Codemode::new(&all)); + } hx_mcp::serve::serve( reg, cx, @@ -749,6 +776,7 @@ async fn main() -> Result<()> { && hx_ai::claude_cli::ClaudeCli::available()) .then(Vec::new), }; + let _ = CODEMODE.set(cfg.codemode.unwrap_or(false)); if let Some(a) = cli_args { let _ = CLAUDE_CLI.set(a); } diff --git a/crates/hx-core/src/approve.rs b/crates/hx-core/src/approve.rs index 13ff96c..fbf3adc 100644 --- a/crates/hx-core/src/approve.rs +++ b/crates/hx-core/src/approve.rs @@ -77,9 +77,23 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> { return; } let v: Value = serde_json::from_str(&line).unwrap_or_default(); - let ok = match question(v["tool_name"].as_str().unwrap_or_default(), &v["input"]) { - None => true, - Some(q) => gate(&cx, q).await, + // hx tools run by `codemode` inside mcp-serve ask for their own permission + let ok = if let Some(q) = v.get("permit") { + let s = |k: &str| q[k].as_str().unwrap_or_default().to_string(); + gate( + &cx, + Request { + tool: s("tool"), + detail: s("detail"), + rule: s("rule"), + }, + ) + .await + } else { + match question(v["tool_name"].as_str().unwrap_or_default(), &v["input"]) { + None => true, + Some(q) => gate(&cx, q).await, + } }; let _ = w .write_all(format!("{}\n", json!({"allow": ok})).as_bytes()) @@ -88,6 +102,38 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> { } } +async fn roundtrip(path: &Path, msg: Value) -> bool { + let ask = async { + let mut c = UnixStream::connect(path).await?; + c.write_all(format!("{msg}\n").as_bytes()).await?; + let mut l = String::new(); + BufReader::new(c).read_line(&mut l).await?; + std::io::Result::Ok(l) + }; + ask.await + .ok() + .and_then(|l| serde_json::from_str::(&l).ok()) + .is_some_and(|v| v["allow"] == true) +} + +/// Permission hook for tools that run in another process (`hx mcp-serve`): ask the owner of the socket. +/// Unreachable socket = deny. +pub fn remote_permit(path: PathBuf) -> crate::permit::Permit { + use crate::permit::Decision; + std::sync::Arc::new(move |r| { + let path = path.clone(); + Box::pin(async move { + let m = json!({"permit": {"tool": r.tool, "detail": r.detail, "rule": r.rule}}); + // the owner stores "always" itself; here a yes is a plain yes + if roundtrip(&path, m).await { + Decision::Once + } else { + Decision::Deny + } + }) + }) +} + /// MCP tool `approve` for `--permission-prompt-tool`. pub struct Approve(pub PathBuf); @@ -103,18 +149,7 @@ impl Tool for Approve { } } async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult { - let ask = async { - let mut c = UnixStream::connect(&self.0).await?; - c.write_all(format!("{args}\n").as_bytes()).await?; - let mut l = String::new(); - BufReader::new(c).read_line(&mut l).await?; - std::io::Result::Ok(l) - }; - let ok = ask - .await - .ok() - .and_then(|l| serde_json::from_str::(&l).ok()) - .is_some_and(|v| v["allow"] == true); + let ok = roundtrip(&self.0, args.clone()).await; ToolResult::ok(if ok { json!({"behavior": "allow", "updatedInput": args["input"]}) } else { @@ -175,6 +210,20 @@ mod tests { }; assert!(ask("cargo test").await.contains("\"allow\"")); assert!(ask("rm -rf x").await.contains("\"deny\"")); - let _ = std::fs::remove_file(path); + // tools run in another process ask through the same socket + let remote = remote_permit(path.clone()); + let req = |d: &str| crate::permit::Request { + tool: "bash".into(), + detail: d.into(), + rule: String::new(), + }; + assert_eq!(remote(req("cargo test")).await, Decision::Once); + assert_eq!(remote(req("rm -rf x")).await, Decision::Deny); + let _ = std::fs::remove_file(&path); + assert_eq!( + remote(req("cargo test")).await, + Decision::Deny, + "no socket = deny" + ); } } diff --git a/tests/claude_cli_e2e.sh b/tests/claude_cli_e2e.sh index 45fe500..cb6661e 100644 --- a/tests/claude_cli_e2e.sh +++ b/tests/claude_cli_e2e.sh @@ -5,11 +5,12 @@ root=$(cd "$(dirname "$0")/.." && pwd) tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT mkdir -p "$tmp/home/.hx" "$tmp/repo" -printf 'claude_cli = []\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml" +printf 'claude_cli = []\ncodemode = true\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml" chmod +x "$root/tests/fake_claude.py" cd "$tmp/repo" export HOME="$tmp/home" HX_CLAUDE_BIN="$root/tests/fake_claude.py" FAKE_CLAUDE_LOG="$tmp/argv" "$root/target/debug/hx" -p "hi" -s "$tmp/s.jsonl" > "$tmp/out" 2> "$tmp/err" || { echo "FAIL run"; cat "$tmp/err"; exit 1; } grep -q "claude Bash: echo hi-from-tool" "$tmp/out" && grep -q "approve: allow" "$tmp/out" || { echo "FAIL text"; cat "$tmp/out" "$tmp/err"; exit 1; } grep -q '"--permission-prompt-tool"' "$tmp/argv" && grep -q '"--mcp-config"' "$tmp/argv" && grep -q '"stream-json"' "$tmp/argv" || { echo "FAIL argv"; cat "$tmp/argv"; exit 1; } +grep -q "cm-ok" "$tmp/out" || { echo "FAIL codemode"; cat "$tmp/out" "$tmp/err"; exit 1; } echo "claude cli e2e ok" diff --git a/tests/fake_claude.py b/tests/fake_claude.py index d36f780..1c40dde 100755 --- a/tests/fake_claude.py +++ b/tests/fake_claude.py @@ -15,9 +15,15 @@ if "--permission-prompt-tool" in sys.argv: # act like claude: ask hx whether `r {"tool_name": "Bash", "input": {"command": "rm -rf x"}}}} p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n" + json.dumps(call) + "\n") p.stdin.flush() - lines = [json.loads(p.stdout.readline()) for _ in range(2)] + cm = {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "codemode", "arguments": + {"script": "return await tools.bash({command: 'echo cm-' + 'ok > cm.txt; cat cm.txt'})"}}} + if "HX_CODEMODE" in cfg["env"]: + p.stdin.write(json.dumps(cm) + "\n"); p.stdin.flush() + lines = [json.loads(p.stdout.readline()) for _ in range(2 + ("HX_CODEMODE" in cfg["env"]))] p.stdin.close() reply = "approve: " + json.loads(lines[1]["result"]["content"][0]["text"])["behavior"] + if len(lines) == 3: + reply += " " + lines[2]["result"]["content"][0]["text"] out({"type": "system", "subtype": "init", "session_id": "S1"}) ev = lambda e: out({"type": "stream_event", "session_id": "S1", "event": e}) out({"type": "assistant", "session_id": "S1", "message": {"content": [