claude_cli: permission prompts via --permission-prompt-tool, bridged to the hx TUI

This commit is contained in:
hermes committed 2026-10-16 20:23:35 +00:00
1 parent b06c06ad80
commit 0032a5a952
8 files changed
+248 -46

No files matched your search

+1 -1
View File
@@ -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
+180
View File
@@ -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<Request> {
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::<Value>(&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);
}
}
+1
View File
@@ -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;
+24 -34
View File
@@ -82,6 +82,28 @@ pub struct Registry {
tools: BTreeMap<String, Arc<dyn Tool>>,
}
/// 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
}