From 769effc8b060a755adc90beb9ac3d843ee5534ec Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 16 Oct 2026 20:09:32 +0000 Subject: [PATCH 1/3] ai: claude_cli provider (official claude binary, subscription billing) --- crates/hx-ai/Cargo.toml | 2 +- crates/hx-ai/src/claude_cli.rs | 244 +++++++++++++++++++++++++++++++++ crates/hx-ai/src/lib.rs | 1 + crates/hx-cli/src/main.rs | 17 +++ tests/all.sh | 1 + tests/claude_cli_e2e.sh | 15 ++ tests/fake_claude.py | 14 ++ 7 files changed, 293 insertions(+), 1 deletion(-) create mode 100644 crates/hx-ai/src/claude_cli.rs create mode 100644 tests/claude_cli_e2e.sh create mode 100755 tests/fake_claude.py diff --git a/crates/hx-ai/Cargo.toml b/crates/hx-ai/Cargo.toml index 2da20c2..2ed4858 100644 --- a/crates/hx-ai/Cargo.toml +++ b/crates/hx-ai/Cargo.toml @@ -15,7 +15,7 @@ serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" sha2 = "0.11.0" thiserror = "2.0.21" -tokio = { version = "1.53.1", features = ["rt", "rt-multi-thread", "macros", "time", "net", "io-util", "sync"] } +tokio = { version = "1.53.1", features = ["rt", "rt-multi-thread", "macros", "time", "net", "io-util", "sync", "process"] } [lints] workspace = true diff --git a/crates/hx-ai/src/claude_cli.rs b/crates/hx-ai/src/claude_cli.rs new file mode 100644 index 0000000..b3f9a88 --- /dev/null +++ b/crates/hx-ai/src/claude_cli.rs @@ -0,0 +1,244 @@ +//! Claude via the real `claude` CLI (`claude -p --output-format stream-json`). +//! +//! Anthropic bills OAuth traffic from third-party apps as "extra usage"; the official binary keeps +//! using the subscription. `claude` runs its own agent loop (tools included), hx only displays the +//! stream. ponytail: one `claude` process per hx turn, continued with `--resume`; add a long-lived +//! `--input-format stream-json` process if startup latency hurts. + +use crate::{ + ContentBlock, Error, Message, Provider, Request, Result, Role, StopReason, StreamEvent, Usage, +}; +use futures::StreamExt; +use futures::stream::BoxStream; +use serde_json::{Value, json}; +use std::sync::{Arc, Mutex}; +use tokio::io::{AsyncBufReadExt, BufReader}; + +pub struct ClaudeCli { + bin: String, + /// extra args, e.g. `["--permission-mode", "acceptEdits"]` + args: Vec, + /// `hx mcp-serve` entry (command, args) offered to claude as MCP server "hx" + mcp: Option<(String, Vec)>, + session: Arc>>, +} + +impl ClaudeCli { + pub fn new(args: Vec) -> Self { + Self { + bin: std::env::var("HX_CLAUDE_BIN").unwrap_or_else(|_| "claude".into()), + args, + mcp: None, + session: Default::default(), + } + } + + pub fn with_mcp(mut self, command: String, args: Vec) -> Self { + self.mcp = Some((command, args)); + self + } + + /// Whether the binary can be started at all. + pub fn available() -> bool { + let bin = std::env::var("HX_CLAUDE_BIN").unwrap_or_else(|_| "claude".into()); + std::process::Command::new(bin) + .arg("--version") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + } +} + +/// Prompt for this turn. Fresh `claude` session: replay earlier text so a resumed hx session keeps context. +fn prompt(msgs: &[Message], resumed: bool) -> String { + let last = msgs + .iter() + .rposition(|m| m.role == Role::User && !m.text().is_empty()); + let Some(last) = last else { + return String::new(); + }; + if resumed || last == 0 { + return msgs[last].text(); + } + let mut s = String::from("Conversation so far:\n"); + for m in &msgs[..last] { + let t = m.text(); + if !t.is_empty() { + let who = if m.role == Role::User { + "User" + } else { + "Assistant" + }; + s += &format!("{who}: {t}\n"); + } + } + s + "\nCurrent request:\n" + &msgs[last].text() +} + +fn usage(u: &Value) -> Usage { + let n = |k: &str| u[k].as_u64().unwrap_or(0); + Usage { + input_tokens: n("input_tokens"), + output_tokens: n("output_tokens"), + cache_read_tokens: n("cache_read_input_tokens"), + cache_write_tokens: n("cache_creation_input_tokens"), + } +} + +#[async_trait::async_trait] +impl Provider for ClaudeCli { + async fn models(&self) -> Result> { + Ok(crate::models::fallback(crate::auth::Kind::Claude)) + } + + async fn stream(&self, req: Request) -> Result>> { + let sid = self.session.lock().ok().and_then(|s| s.clone()); + let mut cmd = tokio::process::Command::new(&self.bin); + cmd.args([ + "-p", + "--output-format", + "stream-json", + "--verbose", + "--include-partial-messages", + "--model", + &req.model, + ]); + if let Some(s) = &sid { + cmd.args(["--resume", s]); + } + if !req.system.is_empty() { + cmd.args(["--append-system-prompt", &req.system]); + } + if let Some((c, a)) = &self.mcp { + let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a}}}); + cmd.args(["--mcp-config", &cfg.to_string()]); + } + cmd.args(&self.args) + .arg("--") + .arg(prompt(&req.messages, sid.is_some())) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .kill_on_drop(true); + let mut child = cmd.spawn().map_err(|e| { + Error::Http(format!( + "cannot start {:?}: {e} (is claude installed?)", + self.bin + )) + })?; + let out = child.stdout.take().expect("piped"); + let mut err = child.stderr.take().expect("piped"); + let session = self.session.clone(); + let (tx, rx) = tokio::sync::mpsc::unbounded_channel::>(); + tokio::spawn(async move { + let _child = child; // dropped (killed) when the consumer goes away + let mut lines = BufReader::new(out).lines(); + let (mut text, mut think) = (String::new(), String::new()); + let mut done = false; + while let Ok(Some(l)) = lines.next_line().await { + let Ok(v) = serde_json::from_str::(&l) else { + continue; + }; + if let (Some(s), Ok(mut g)) = (v["session_id"].as_str(), session.lock()) { + *g = Some(s.into()); + } + match v["type"].as_str() { + Some("stream_event") => { + let e = &v["event"]; + match e["type"].as_str() { + Some("content_block_delta") => match e["delta"]["type"].as_str() { + Some("text_delta") => { + let t = e["delta"]["text"].as_str().unwrap_or_default(); + text += t; + let _ = tx.send(Ok(StreamEvent::TextDelta { text: t.into() })); + } + Some("thinking_delta") => { + let t = e["delta"]["thinking"].as_str().unwrap_or_default(); + think += t; + let _ = + tx.send(Ok(StreamEvent::ThinkingDelta { text: t.into() })); + } + _ => {} + }, + // claude runs its tools itself; show them, don't hand them to hx + Some("content_block_start") + if e["content_block"]["type"] == "tool_use" => + { + let n = e["content_block"]["name"].as_str().unwrap_or("tool"); + let _ = tx.send(Ok(StreamEvent::TextDelta { + text: format!("\n[claude tool: {n}]\n"), + })); + } + _ => {} + } + } + Some("result") => { + done = true; + if v["is_error"].as_bool().unwrap_or(false) { + let body = v["result"].as_str().unwrap_or("claude failed").to_string(); + let _ = tx.send(Err(Error::Api { status: 0, body })); + break; + } + if text.is_empty() && think.is_empty() { + text = v["result"].as_str().unwrap_or_default().into(); + } + let mut content = vec![]; + if !think.is_empty() { + content.push(ContentBlock::Thinking { + thinking: std::mem::take(&mut think), + signature: None, + }); + } + content.push(ContentBlock::Text { + text: std::mem::take(&mut text), + }); + let _ = tx.send(Ok(StreamEvent::Done { + message: Message { + role: Role::Assistant, + content, + }, + stop: StopReason::EndTurn, + usage: usage(&v["usage"]), + })); + break; + } + _ => {} + } + } + if !done { + let mut e = String::new(); + let _ = tokio::io::AsyncReadExt::read_to_string(&mut err, &mut e).await; + let _ = tx.send(Err(Error::Http(format!( + "claude exited without result: {}", + e.trim() + )))); + } + }); + Ok( + futures::stream::unfold(rx, |mut rx| async move { rx.recv().await.map(|x| (x, rx)) }) + .boxed(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prompt_replays_history_only_on_fresh_session() { + let m = vec![ + Message::user("a"), + Message { + role: Role::Assistant, + content: vec![ContentBlock::Text { text: "b".into() }], + }, + Message::user("c"), + ]; + assert_eq!(prompt(&m, true), "c"); + let p = prompt(&m, false); + assert!(p.contains("User: a") && p.contains("Assistant: b") && p.ends_with("c")); + assert_eq!(prompt(&m[..1], false), "a"); + } +} diff --git a/crates/hx-ai/src/lib.rs b/crates/hx-ai/src/lib.rs index 2802f71..4672828 100644 --- a/crates/hx-ai/src/lib.rs +++ b/crates/hx-ai/src/lib.rs @@ -2,6 +2,7 @@ pub mod anthropic; pub mod auth; +pub mod claude_cli; pub mod codex; pub mod models; pub mod openai_compat; diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 328021f..b7fd7fa 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -117,6 +117,8 @@ struct Config { provider: Option, model: Option, claude_model: Option, + /// Run Claude through the official `claude` CLI (subscription billing). Value = extra `claude` args, `[]` for none. + claude_cli: Option>, /// OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter, ...), provider "custom". openai_compat: Option, codex_model: Option, @@ -193,6 +195,7 @@ impl Config { provider: o.provider.or(c.provider), model: o.model.or(c.model), claude_model: o.claude_model.or(c.claude_model), + claude_cli: o.claude_cli.or(c.claude_cli), openai_compat: o.openai_compat.or(c.openai_compat), codex_model: o.codex_model.or(c.codex_model), compact_at: o.compact_at.or(c.compact_at), @@ -258,6 +261,7 @@ fn logged_in() -> Vec { .into_iter() .filter(|k| match k { Kind::Custom => COMPAT.get().is_some(), + Kind::Claude if CLAUDE_CLI.get().is_some() => true, k => hx_ai::auth::Auth::load(*k).is_ok(), }) .collect() @@ -346,9 +350,19 @@ fn pricing(model: &str) -> Option { /// `[openai_compat]` from config, set once at startup. static COMPAT: 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(); fn provider(k: Kind) -> hx_ai::Result> { Ok(match k { + Kind::Claude if CLAUDE_CLI.get().is_some() => { + let c = + hx_ai::claude_cli::ClaudeCli::new(CLAUDE_CLI.get().cloned().unwrap_or_default()); + Arc::new(match std::env::current_exe() { + Ok(e) => c.with_mcp(e.to_string_lossy().into(), vec!["mcp-serve".into()]), + Err(_) => c, + }) + } Kind::Claude => { let a = Anthropic::login_default()?; Arc::new(match std::env::var("HX_BASE_URL") { @@ -615,6 +629,9 @@ async fn main() -> Result<()> { if let Some(oc) = cfg.openai_compat.clone() { let _ = COMPAT.set(oc); } + if let Some(a) = cfg.claude_cli.clone() { + let _ = CLAUDE_CLI.set(a); + } // MCP servers connect while the model catalog loads let mcp_cfg = hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?; let mcp = hx_mcp::Hub::spawn(mcp_cfg); diff --git a/tests/all.sh b/tests/all.sh index b7b7fb9..0f8889a 100755 --- a/tests/all.sh +++ b/tests/all.sh @@ -21,3 +21,4 @@ python3 tests/tui_lspinstall.py | grep -q FAIL && { echo "tui lsp install FAIL"; sh tests/m7_e2e.sh sh tests/m8_e2e.sh sh tests/sandbox_e2e.sh +sh tests/claude_cli_e2e.sh diff --git a/tests/claude_cli_e2e.sh b/tests/claude_cli_e2e.sh new file mode 100644 index 0000000..11686b5 --- /dev/null +++ b/tests/claude_cli_e2e.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# claude_cli = [] routes Claude through the `claude` binary (fake here): streamed text arrives, argv is right. +set -eu +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" +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 "hello from claude" "$tmp/out" || { echo "FAIL text"; cat "$tmp/out" "$tmp/err"; exit 1; } +grep -q '"--mcp-config"' "$tmp/argv" && grep -q '"stream-json"' "$tmp/argv" || { echo "FAIL argv"; cat "$tmp/argv"; exit 1; } +echo "claude cli e2e ok" diff --git a/tests/fake_claude.py b/tests/fake_claude.py new file mode 100755 index 0000000..1bdf853 --- /dev/null +++ b/tests/fake_claude.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 +"""Fake `claude -p --output-format stream-json`: logs argv to $FAKE_CLAUDE_LOG, streams one reply.""" +import json, os, sys +open(os.environ["FAKE_CLAUDE_LOG"], "a").write(json.dumps(sys.argv[1:]) + "\n") +if "--version" in sys.argv: + print("fake"); sys.exit(0) +def out(o): print(json.dumps(o), flush=True) +out({"type": "system", "subtype": "init", "session_id": "S1"}) +ev = lambda e: out({"type": "stream_event", "session_id": "S1", "event": e}) +ev({"type": "content_block_start", "content_block": {"type": "tool_use", "name": "Read"}}) +ev({"type": "content_block_delta", "delta": {"type": "text_delta", "text": "hello "}}) +ev({"type": "content_block_delta", "delta": {"type": "text_delta", "text": "from claude"}}) +out({"type": "result", "session_id": "S1", "is_error": False, "result": "hello from claude", + "usage": {"input_tokens": 3, "output_tokens": 4}}) -- 2.54.1 From b06c06ad80004de879d73d6d61ea6e43cd0604e4 Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 16 Oct 2026 20:13:46 +0000 Subject: [PATCH 2/3] cli: claude_cli auto-on when claude is in PATH; false disables --- crates/hx-cli/src/main.rs | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index b7fd7fa..0283f84 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -111,14 +111,22 @@ enum McpAction { } /// `~/.hx/config.toml`, overridden by `.hx/config.toml` in the project. +#[derive(Clone, serde::Deserialize)] +#[serde(untagged)] +enum CliCfg { + Switch(bool), + Args(Vec), +} + #[derive(Default, serde::Deserialize)] #[serde(default, deny_unknown_fields)] struct Config { provider: Option, model: Option, claude_model: Option, - /// Run Claude through the official `claude` CLI (subscription billing). Value = extra `claude` args, `[]` for none. - claude_cli: Option>, + /// Run Claude through the official `claude` CLI (subscription billing). Default: on when `claude` is in PATH. + /// `false` = own OAuth calls (billed as extra usage); `true` / `[]` = on; a list = on with extra `claude` args. + claude_cli: Option, /// OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter, ...), provider "custom". openai_compat: Option, codex_model: Option, @@ -629,7 +637,15 @@ async fn main() -> Result<()> { if let Some(oc) = cfg.openai_compat.clone() { let _ = COMPAT.set(oc); } - if let Some(a) = cfg.claude_cli.clone() { + // auto-detect, except against a test server (HX_BASE_URL) + let cli_args = match cfg.claude_cli.clone() { + Some(CliCfg::Args(a)) => Some(a), + Some(CliCfg::Switch(on)) => on.then(Vec::new), + None => (std::env::var_os("HX_BASE_URL").is_none() + && hx_ai::claude_cli::ClaudeCli::available()) + .then(Vec::new), + }; + if let Some(a) = cli_args { let _ = CLAUDE_CLI.set(a); } // MCP servers connect while the model catalog loads @@ -1020,6 +1036,19 @@ mod tests { #[cfg(test)] mod config_tests { + #[test] + fn claude_cli_switch_or_args() { + use super::{CliCfg, Config}; + let p = |t: &str| toml::from_str::(t).unwrap().claude_cli; + assert!(matches!( + p("claude_cli = false"), + Some(CliCfg::Switch(false)) + )); + assert!(matches!(p("claude_cli = true"), Some(CliCfg::Switch(true)))); + assert!(matches!(p("claude_cli = [\"-x\"]"), Some(CliCfg::Args(a)) if a == ["-x"])); + assert!(p("").is_none()); + } + #[test] fn sample_config_parses() { let s = super::SAMPLE_CONFIG; -- 2.54.1 From 0032a5a952f79376703d2cf7e47bf32bace4c1ab Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 16 Oct 2026 20:23:35 +0000 Subject: [PATCH 3/3] claude_cli: permission prompts via --permission-prompt-tool, bridged to the hx TUI --- crates/hx-ai/src/claude_cli.rs | 16 +-- crates/hx-cli/src/main.rs | 16 ++- crates/hx-core/Cargo.toml | 2 +- crates/hx-core/src/approve.rs | 180 +++++++++++++++++++++++++++++++++ crates/hx-core/src/lib.rs | 1 + crates/hx-core/src/tool.rs | 58 +++++------ tests/claude_cli_e2e.sh | 6 +- tests/fake_claude.py | 15 ++- 8 files changed, 248 insertions(+), 46 deletions(-) create mode 100644 crates/hx-core/src/approve.rs diff --git a/crates/hx-ai/src/claude_cli.rs b/crates/hx-ai/src/claude_cli.rs index b3f9a88..bc83c61 100644 --- a/crates/hx-ai/src/claude_cli.rs +++ b/crates/hx-ai/src/claude_cli.rs @@ -18,8 +18,8 @@ pub struct ClaudeCli { bin: String, /// extra args, e.g. `["--permission-mode", "acceptEdits"]` args: Vec, - /// `hx mcp-serve` entry (command, args) offered to claude as MCP server "hx" - mcp: Option<(String, Vec)>, + /// `hx mcp-serve` entry (command, args, env) offered to claude as MCP server "hx" + mcp: Option<(String, Vec, Value)>, session: Arc>>, } @@ -33,8 +33,9 @@ impl ClaudeCli { } } - pub fn with_mcp(mut self, command: String, args: Vec) -> Self { - self.mcp = Some((command, args)); + /// `env` also carries the permission socket: claude then asks hx (`mcp__hx__approve`) before tools run. + pub fn with_mcp(mut self, command: String, args: Vec, env: Value) -> Self { + self.mcp = Some((command, args, env)); self } @@ -110,9 +111,12 @@ impl Provider for ClaudeCli { if !req.system.is_empty() { cmd.args(["--append-system-prompt", &req.system]); } - if let Some((c, a)) = &self.mcp { - let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a}}}); + if let Some((c, a, env)) = &self.mcp { + let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a, "env": env}}}); cmd.args(["--mcp-config", &cfg.to_string()]); + if !env.is_null() { + cmd.args(["--permission-prompt-tool", "mcp__hx__approve"]); + } } cmd.args(&self.args) .arg("--") diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 0283f84..573707b 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -367,7 +367,11 @@ fn provider(k: Kind) -> hx_ai::Result> { let c = hx_ai::claude_cli::ClaudeCli::new(CLAUDE_CLI.get().cloned().unwrap_or_default()); Arc::new(match std::env::current_exe() { - Ok(e) => c.with_mcp(e.to_string_lossy().into(), vec!["mcp-serve".into()]), + 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() }), + ), Err(_) => c, }) } @@ -607,6 +611,9 @@ 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, state: Default::default(), @@ -891,6 +898,13 @@ async fn main() -> Result<()> { if cli.mode == Mode::Json && cli.print.is_none() { anyhow::bail!("--mode json needs -p "); } + if CLAUDE_CLI.get().is_some() { + // claude asks here (via `hx mcp-serve`) before running its tools + let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone()); + tokio::spawn(async move { + let _ = hx_core::approve::serve(&p, cx).await; + }); + } let Some(prompt) = cli.print else { hx_tui::run(hx_tui::Setup { agent, diff --git a/crates/hx-core/Cargo.toml b/crates/hx-core/Cargo.toml index a068dde..40c2714 100644 --- a/crates/hx-core/Cargo.toml +++ b/crates/hx-core/Cargo.toml @@ -12,7 +12,7 @@ serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" serde_norway = "0.9.42" thiserror = "2.0.21" -tokio = { version = "1.53.1", features = ["rt", "sync", "time", "macros", "fs", "process", "io-util"] } +tokio = { version = "1.53.1", features = ["rt", "sync", "time", "macros", "fs", "process", "io-util", "net"] } [lints] workspace = true diff --git a/crates/hx-core/src/approve.rs b/crates/hx-core/src/approve.rs new file mode 100644 index 0000000..13ff96c --- /dev/null +++ b/crates/hx-core/src/approve.rs @@ -0,0 +1,180 @@ +//! Permission bridge for the `claude` CLI provider: `claude --permission-prompt-tool mcp__hx__approve` +//! calls the `approve` tool of `hx mcp-serve`, which forwards the question over a Unix socket to the +//! hx process that owns the TUI; that one shows the usual permission prompt. + +use crate::permit::Request; +use crate::tool::{Tool, ToolCtx, ToolResult, gate}; +use async_trait::async_trait; +use hx_ai::ToolSpec; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::net::{UnixListener, UnixStream}; + +pub const ENV: &str = "HX_PERMIT_SOCK"; + +/// New per-process socket path. +pub fn sock_path() -> PathBuf { + std::env::temp_dir().join(format!("hx-permit-{}.sock", std::process::id())) +} + +/// Map a `claude` tool call to a permission question; `None` = no prompt needed. +// ponytail: reads and searches are never asked (claude already confines them to the project); add rules when needed. +pub fn question(tool: &str, input: &Value) -> Option { + let s = |k: &str| input[k].as_str().unwrap_or_default().to_string(); + match tool { + "Bash" => { + let a = json!({"command": s("command")}); + crate::permit::needs_permit("bash", &a).then(|| crate::permit::request("bash", &a)) + } + "Write" | "Edit" | "MultiEdit" | "NotebookEdit" => Some(Request { + tool: if tool == "Write" { "write" } else { "edit" }.into(), + detail: if input["file_path"].is_string() { + s("file_path") + } else { + s("notebook_path") + }, + rule: String::new(), + }), + "Read" => crate::permit::secret(&s("file_path")).then(|| Request { + tool: "read".into(), + detail: s("file_path"), + rule: String::new(), + }), + "Grep" | "Glob" | "LS" | "TodoWrite" | "NotebookRead" | "Task" | "Agent" => None, + t if t.starts_with("mcp__hx__") => None, + "WebFetch" => Some(crate::permit::request( + "web_fetch", + &json!({"url": s("url")}), + )), + t => { + let d: String = input.to_string().chars().take(200).collect(); + Some(Request { + tool: t.into(), + detail: d, + rule: format!("claude:{t}"), + }) + } + } +} + +/// Answer permission questions on `path` until the process ends. +pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> { + let _ = std::fs::remove_file(path); + let l = UnixListener::bind(path)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + } + loop { + let (c, _) = l.accept().await?; + let cx = cx.clone(); + tokio::spawn(async move { + let (r, mut w) = c.into_split(); + let mut line = String::new(); + if BufReader::new(r).read_line(&mut line).await.is_err() { + 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, + }; + let _ = w + .write_all(format!("{}\n", json!({"allow": ok})).as_bytes()) + .await; + }); + } +} + +/// MCP tool `approve` for `--permission-prompt-tool`. +pub struct Approve(pub PathBuf); + +#[async_trait] +impl Tool for Approve { + fn spec(&self) -> ToolSpec { + ToolSpec { + name: "approve".into(), + description: "Permission prompt bridge for claude (internal).".into(), + input_schema: json!({"type": "object", "properties": { + "tool_name": {"type": "string"}, "input": {"type": "object"}, "tool_use_id": {"type": "string"} + }, "required": ["tool_name", "input"]}), + } + } + 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); + ToolResult::ok(if ok { + json!({"behavior": "allow", "updatedInput": args["input"]}) + } else { + json!({"behavior": "deny", "message": "denied by the user; do not retry, ask what to do instead"}) + } + .to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn questions() { + assert!(question("Bash", &json!({"command": "ls -la"})).is_none()); + let q = question("Bash", &json!({"command": "cargo test"})).unwrap(); + assert_eq!( + (q.tool.as_str(), q.rule.as_str()), + ("bash", "bash:cargo test *") + ); + let q = question("Edit", &json!({"file_path": "a.rs"})).unwrap(); + assert_eq!((q.tool.as_str(), q.detail.as_str()), ("edit", "a.rs")); + assert!(question("Read", &json!({"file_path": "src/a.rs"})).is_none()); + assert!(question("Read", &json!({"file_path": "/h/.ssh/id_rsa"})).is_some()); + assert!(question("mcp__hx__lsp", &json!({})).is_none()); + assert_eq!(question("Foo", &json!({})).unwrap().rule, "claude:Foo"); + } + + #[tokio::test] + async fn socket_round_trip_allows_and_denies() { + use crate::permit::Decision; + let cx = ToolCtx { + cwd: ".".into(), + state: Default::default(), + }; + let _ = cx.state.permit.set(std::sync::Arc::new(|r| { + Box::pin(async move { + if r.detail.contains("rm") { + Decision::Deny + } else { + Decision::Once + } + }) + })); + let path = + std::env::temp_dir().join(format!("hx-approve-test-{}.sock", std::process::id())); + let (p, c) = (path.clone(), cx.clone()); + tokio::spawn(async move { serve(&p, c).await }); + while !path.exists() { + tokio::task::yield_now().await; + } + let t = Approve(path.clone()); + let ask = |cmd: &str| { + let a = json!({"tool_name": "Bash", "input": {"command": cmd}}); + let (t, cx) = (&t, &cx); + async move { t.call(a, cx).await.content } + }; + assert!(ask("cargo test").await.contains("\"allow\"")); + assert!(ask("rm -rf x").await.contains("\"deny\"")); + let _ = std::fs::remove_file(path); + } +} diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index 0fd8c7a..997eab3 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -1,6 +1,7 @@ //! hx core: tools, hooks, agent loop, sessions, context. pub mod agent; +pub mod approve; pub mod command; pub mod compact; pub mod context; diff --git a/crates/hx-core/src/tool.rs b/crates/hx-core/src/tool.rs index 0157472..ed3aa84 100644 --- a/crates/hx-core/src/tool.rs +++ b/crates/hx-core/src/tool.rs @@ -82,6 +82,28 @@ pub struct Registry { tools: BTreeMap>, } +/// Ask the user (unless a stored rule covers `req`); false = denied. No prompt hook = allowed. +pub async fn gate(cx: &ToolCtx, req: crate::permit::Request) -> bool { + use crate::permit::Decision; + let Some(ask) = cx.state.permit.get() else { + return true; + }; + let allow = || cx.state.allow.lock().unwrap_or_else(|e| e.into_inner()); + // One prompt at a time; re-check after waiting, an earlier answer may cover this call. + let _turn = cx.state.asking.lock().await; + if allow().allows(&req) { + return true; + } + let rule = req.rule.clone(); + match ask(req).await { + Decision::Once => {} + Decision::Always => allow().add(&rule), + Decision::Edits => allow().allow_edits(), + Decision::Deny => return false, + } + true +} + impl Registry { pub fn add(&mut self, t: impl Tool + 'static) -> &mut Self { self.tools.insert(t.spec().name, Arc::new(t)); @@ -106,41 +128,9 @@ impl Registry { return ToolResult::err(e); } if crate::permit::needs_permit(name, &args) - && let Some(ask) = cx.state.permit.get() + && !gate(cx, crate::permit::request(name, &args)).await { - let req = crate::permit::request(name, &args); - let allowed = || { - cx.state - .allow - .lock() - .unwrap_or_else(|e| e.into_inner()) - .allows(&req) - }; - // One prompt at a time; re-check after waiting, an earlier answer may cover this call. - let _turn = cx.state.asking.lock().await; - if !allowed() { - let rule = req.rule.clone(); - match ask(req.clone()).await { - crate::permit::Decision::Once => {} - crate::permit::Decision::Always => cx - .state - .allow - .lock() - .unwrap_or_else(|e| e.into_inner()) - .add(&rule), - crate::permit::Decision::Edits => cx - .state - .allow - .lock() - .unwrap_or_else(|e| e.into_inner()) - .allow_edits(), - crate::permit::Decision::Deny => { - return ToolResult::err( - "denied by the user; do not retry, ask what to do instead", - ); - } - } - } + return ToolResult::err("denied by the user; do not retry, ask what to do instead"); } t.call(args, cx).await } diff --git a/tests/claude_cli_e2e.sh b/tests/claude_cli_e2e.sh index 11686b5..e858e1b 100644 --- a/tests/claude_cli_e2e.sh +++ b/tests/claude_cli_e2e.sh @@ -1,5 +1,5 @@ #!/bin/sh -# claude_cli = [] routes Claude through the `claude` binary (fake here): streamed text arrives, argv is right. +# (print mode has no prompt, so the permission bridge allows) claude_cli = [] routes Claude through the `claude` binary (fake here): streamed text arrives, argv is right. set -eu root=$(cd "$(dirname "$0")/.." && pwd) tmp=$(mktemp -d) @@ -10,6 +10,6 @@ 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 "hello from claude" "$tmp/out" || { echo "FAIL text"; cat "$tmp/out" "$tmp/err"; exit 1; } -grep -q '"--mcp-config"' "$tmp/argv" && grep -q '"stream-json"' "$tmp/argv" || { echo "FAIL argv"; cat "$tmp/argv"; exit 1; } +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; } echo "claude cli e2e ok" diff --git a/tests/fake_claude.py b/tests/fake_claude.py index 1bdf853..6c78459 100755 --- a/tests/fake_claude.py +++ b/tests/fake_claude.py @@ -5,10 +5,23 @@ open(os.environ["FAKE_CLAUDE_LOG"], "a").write(json.dumps(sys.argv[1:]) + "\n") if "--version" in sys.argv: print("fake"); sys.exit(0) def out(o): print(json.dumps(o), flush=True) +reply = "hello from claude" +if "--permission-prompt-tool" in sys.argv: # act like claude: ask hx whether `rm -rf x` may run + import subprocess + cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"] + p = subprocess.Popen([cfg["command"], *cfg["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + text=True, env={**os.environ, **cfg["env"]}) + call = {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "approve", "arguments": + {"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)] + p.stdin.close() + reply = "approve: " + json.loads(lines[1]["result"]["content"][0]["text"])["behavior"] out({"type": "system", "subtype": "init", "session_id": "S1"}) ev = lambda e: out({"type": "stream_event", "session_id": "S1", "event": e}) ev({"type": "content_block_start", "content_block": {"type": "tool_use", "name": "Read"}}) -ev({"type": "content_block_delta", "delta": {"type": "text_delta", "text": "hello "}}) +ev({"type": "content_block_delta", "delta": {"type": "text_delta", "text": reply + " "}}) ev({"type": "content_block_delta", "delta": {"type": "text_delta", "text": "from claude"}}) out({"type": "result", "session_id": "S1", "is_error": False, "result": "hello from claude", "usage": {"input_tokens": 3, "output_tokens": 4}}) -- 2.54.1