claude_cli: tool calls on the event bus, extensions can block, permissions deny/extensions-only (#182)
This commit is contained in:
1 parent
6ebf1c3180
commit
6978aad27a
12 files changed
+297
-12
No files matched your search
@@ -106,7 +106,7 @@ fable = false # same as /fable on|off
|
|||||||
|
|
||||||
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; `/yolo` toggles it live (also while a turn runs), `!` on a permission prompt allows it and turns yolo on.
|
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; `/yolo` toggles it live (also while a turn runs), `!` on a permission prompt allows it and turns yolo on.
|
||||||
|
|
||||||
Auto permissions (`--auto`, `permissions = "auto"`, `/auto [on|off|log]`): nothing prompts for the usual work, and dangerous calls are refused without asking. A refused call returns `blocked by auto mode: <reason>` to the model (also over a stored "always" rule); `/auto log` lists the last 20. Per call, in order: (1) rules block `rm -rf` of home/root/project root/outside the project, `sudo`, raw disk writes and filesystem creation, download piped to a shell, force push, push to main/master, sending `.env`/keys over the network, `npm|cargo publish`, `docker push`, `kubectl delete`, `terraform destroy`, SQL `DROP`, writes to `/etc`, `~/.ssh`, shell rc files, `.git/hooks`; (2) rules allow routine work inside the project (build/test/format, local git, `mkdir`/`mv`/`cp`/`rm` in the project, `write`/`edit` of project files); (3) everything else (unknown binaries, `curl`, `python -c`, `$(..)`, redirects, paths outside the project) goes to one cheap-model request (Haiku/Luna, ~300 input tokens, 20 s timeout) that answers ALLOW or BLOCK; if that fails or is unavailable the normal prompt appears. `--yolo` / `/yolo` still skip everything. With the `claude_cli` provider the same rules apply to claude's tool calls, but no model judge runs (unclear ones ask). Pattern rules are not a sandbox: combine with `[sandbox]` for confinement.
|
Auto permissions (`--auto`, `permissions = "auto"`, `/auto [on|off|log]`): nothing prompts for the usual work, and dangerous calls are refused without asking. A refused call returns `blocked by auto mode: <reason>` to the model (also over a stored "always" rule); `/auto log` lists the last 20. Per call, in order: (1) rules block `rm -rf` of home/root/project root/outside the project, `sudo`, raw disk writes and filesystem creation, download piped to a shell, force push, push to main/master, sending `.env`/keys over the network, `npm|cargo publish`, `docker push`, `kubectl delete`, `terraform destroy`, SQL `DROP`, writes to `/etc`, `~/.ssh`, shell rc files, `.git/hooks`; (2) rules allow routine work inside the project (build/test/format, local git, `mkdir`/`mv`/`cp`/`rm` in the project, `write`/`edit` of project files); (3) everything else (unknown binaries, `curl`, `python -c`, `$(..)`, redirects, paths outside the project) goes to one cheap-model request (Haiku/Luna, ~300 input tokens, 20 s timeout) that answers ALLOW or BLOCK; if that fails or is unavailable the normal prompt appears. `--yolo` / `/yolo` still skip everything. With the `claude_cli` provider claude's tools appear on the event bus (`tool_call` / `tool_result`; hx names `bash{command}`, `write|edit|read{path}`, other tools under claude's name), so extensions can block them (a `block` denies the call with its reason) and NDJSON / `hx stats` see them. Reads are asked too (`--settings` `permissions.ask`). In `-p` there is no prompt and everything is allowed, unless `permissions = "deny"` (every unanswered call is denied) or `permissions = "extensions-only"` (allowed only while a live `tool_call` extension exists). The same rules apply to claude's tool calls, but no model judge runs (unclear ones ask). Pattern rules are not a sandbox: combine with `[sandbox]` for confinement.
|
||||||
|
|
||||||
The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) 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 `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and 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.
|
The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) 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 `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and 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.
|
||||||
|
|
||||||
|
|||||||
@@ -115,6 +115,18 @@ fn tool_line(b: &Value) -> String {
|
|||||||
format!("{name}: {d}")
|
format!("{name}: {d}")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Tool result content: a string or a list of `{type: "text", text}` blocks.
|
||||||
|
fn result_text(c: &Value) -> String {
|
||||||
|
match c.as_array() {
|
||||||
|
Some(a) => a
|
||||||
|
.iter()
|
||||||
|
.filter_map(|b| b["text"].as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n"),
|
||||||
|
None => c.as_str().unwrap_or_default().to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn usage(u: &Value) -> Usage {
|
fn usage(u: &Value) -> Usage {
|
||||||
let n = |k: &str| u[k].as_u64().unwrap_or(0);
|
let n = |k: &str| u[k].as_u64().unwrap_or(0);
|
||||||
Usage {
|
Usage {
|
||||||
@@ -184,7 +196,13 @@ impl Provider for ClaudeCli {
|
|||||||
let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a, "env": env}}});
|
let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a, "env": env}}});
|
||||||
cmd.args(["--mcp-config", &cfg.to_string()]);
|
cmd.args(["--mcp-config", &cfg.to_string()]);
|
||||||
if !env.is_null() {
|
if !env.is_null() {
|
||||||
|
// reads in the project run without a prompt by default; "ask" sends them to hx too
|
||||||
|
// ponytail: unverified against a real claude (not installed on the dev box)
|
||||||
cmd.args(["--permission-prompt-tool", "mcp__hx__approve"]);
|
cmd.args(["--permission-prompt-tool", "mcp__hx__approve"]);
|
||||||
|
cmd.args([
|
||||||
|
"--settings",
|
||||||
|
r#"{"permissions":{"ask":["Read","Grep","Glob","LS"]}}"#,
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
cmd.args(&self.args)
|
cmd.args(&self.args)
|
||||||
@@ -212,6 +230,8 @@ impl Provider for ClaudeCli {
|
|||||||
// usage of the last API request: the real context size (`result` sums all requests)
|
// usage of the last API request: the real context size (`result` sums all requests)
|
||||||
let mut last: Option<Value> = None;
|
let mut last: Option<Value> = None;
|
||||||
let mut quota = Quota::default();
|
let mut quota = Quota::default();
|
||||||
|
// tool_use blocks by id, completed by the `user` message carrying the result
|
||||||
|
let mut uses: std::collections::HashMap<String, (String, Value)> = Default::default();
|
||||||
while let Ok(Some(l)) = lines.next_line().await {
|
while let Ok(Some(l)) = lines.next_line().await {
|
||||||
let Ok(v) = serde_json::from_str::<Value>(&l) else {
|
let Ok(v) = serde_json::from_str::<Value>(&l) else {
|
||||||
continue;
|
continue;
|
||||||
@@ -250,12 +270,37 @@ impl Provider for ClaudeCli {
|
|||||||
}
|
}
|
||||||
for b in v["message"]["content"].as_array().into_iter().flatten() {
|
for b in v["message"]["content"].as_array().into_iter().flatten() {
|
||||||
if b["type"] == "tool_use" {
|
if b["type"] == "tool_use" {
|
||||||
|
uses.insert(
|
||||||
|
b["id"].as_str().unwrap_or_default().into(),
|
||||||
|
(
|
||||||
|
b["name"].as_str().unwrap_or("tool").into(),
|
||||||
|
b["input"].clone(),
|
||||||
|
),
|
||||||
|
);
|
||||||
let _ = tx.send(Ok(StreamEvent::TextDelta {
|
let _ = tx.send(Ok(StreamEvent::TextDelta {
|
||||||
text: format!("\n[claude {}]\n", tool_line(b)),
|
text: format!("\n[claude {}]\n", tool_line(b)),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Some("user") => {
|
||||||
|
for b in v["message"]["content"].as_array().into_iter().flatten() {
|
||||||
|
let id = b["tool_use_id"].as_str().unwrap_or_default();
|
||||||
|
if b["type"] != "tool_result" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some((name, input)) = uses.remove(id) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let _ = tx.send(Ok(StreamEvent::ToolRun {
|
||||||
|
id: id.into(),
|
||||||
|
name,
|
||||||
|
input,
|
||||||
|
content: result_text(&b["content"]),
|
||||||
|
is_error: b["is_error"].as_bool().unwrap_or(false),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
Some("rate_limit_event") => {
|
Some("rate_limit_event") => {
|
||||||
if let Some(w) = window(&v) {
|
if let Some(w) = window(&v) {
|
||||||
quota.windows.retain(|x| x.label != w.label);
|
quota.windows.retain(|x| x.label != w.label);
|
||||||
|
|||||||
@@ -258,6 +258,15 @@ pub enum StreamEvent {
|
|||||||
id: String,
|
id: String,
|
||||||
name: String,
|
name: String,
|
||||||
},
|
},
|
||||||
|
/// A tool the provider ran itself (`claude_cli`): raw tool name and input plus its result.
|
||||||
|
/// The agent turns it into `ToolCall` / `ToolResult` events; it is not part of the message.
|
||||||
|
ToolRun {
|
||||||
|
id: String,
|
||||||
|
name: String,
|
||||||
|
input: serde_json::Value,
|
||||||
|
content: String,
|
||||||
|
is_error: bool,
|
||||||
|
},
|
||||||
/// Rate-limit / credit snapshot from the response headers (sent first, when present).
|
/// Rate-limit / credit snapshot from the response headers (sent first, when present).
|
||||||
Quota(Quota),
|
Quota(Quota),
|
||||||
Done {
|
Done {
|
||||||
|
|||||||
@@ -1096,8 +1096,11 @@ async fn main() -> Result<()> {
|
|||||||
// claude asks here (via `hx mcp-serve`) before running its tools
|
// claude asks here (via `hx mcp-serve`) before running its tools
|
||||||
let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone());
|
let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone());
|
||||||
let _ = CLAUDE_CX.set(cx.clone());
|
let _ = CLAUDE_CX.set(cx.clone());
|
||||||
|
let bus = agent.bus.clone();
|
||||||
|
// only -p has no prompt; `permissions = "deny" | "extensions-only"` closes it
|
||||||
|
let mode = hx_core::approve::Unanswered::from_config(cfg.permissions.as_deref());
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let _ = hx_core::approve::serve(&p, cx).await;
|
let _ = hx_core::approve::serve(&p, cx, bus, mode).await;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let Some(prompt) = cli.print else {
|
let Some(prompt) = cli.print else {
|
||||||
|
|||||||
@@ -378,6 +378,42 @@ impl Agent {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A tool `claude_cli` ran itself: `ToolCall` (unless the permission bridge sent it before the
|
||||||
|
/// run) and `ToolResult`, in hx' vocabulary. Informational: the tool already ran.
|
||||||
|
async fn claude_tool(
|
||||||
|
&self,
|
||||||
|
id: String,
|
||||||
|
name: &str,
|
||||||
|
input: &serde_json::Value,
|
||||||
|
content: String,
|
||||||
|
is_error: bool,
|
||||||
|
) {
|
||||||
|
let (name, args) = crate::approve::hx_call(name, input);
|
||||||
|
let seen = self
|
||||||
|
.cx
|
||||||
|
.state
|
||||||
|
.claude_seen
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.remove(&id);
|
||||||
|
if !seen {
|
||||||
|
self.emit(Event::ToolCall {
|
||||||
|
id: id.clone(),
|
||||||
|
name: name.clone(),
|
||||||
|
args: args.clone(),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
self.emit(Event::ToolResult {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
args,
|
||||||
|
content,
|
||||||
|
is_error,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
async fn emit(&self, ev: Event) -> crate::hook::Outcome {
|
async fn emit(&self, ev: Event) -> crate::hook::Outcome {
|
||||||
self.bus.emit(ev).await
|
self.bus.emit(ev).await
|
||||||
}
|
}
|
||||||
@@ -460,6 +496,10 @@ impl Agent {
|
|||||||
if let StreamEvent::Done { message, stop, usage } = &ev {
|
if let StreamEvent::Done { message, stop, usage } = &ev {
|
||||||
done = Some((message.clone(), *stop, usage.clone()));
|
done = Some((message.clone(), *stop, usage.clone()));
|
||||||
}
|
}
|
||||||
|
if let StreamEvent::ToolRun { id, name, input, content, is_error } = ev {
|
||||||
|
self.claude_tool(id, &name, &input, content, is_error).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
self.emit(Event::Stream(ev)).await;
|
self.emit(Event::Stream(ev)).await;
|
||||||
}
|
}
|
||||||
None => break,
|
None => break,
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
//! calls the `approve` tool of `hx mcp-serve`, which forwards the question over a Unix socket to the
|
//! 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.
|
//! hx process that owns the TUI; that one shows the usual permission prompt.
|
||||||
|
|
||||||
|
use crate::hook::{Bus, Event};
|
||||||
use crate::permit::Request;
|
use crate::permit::Request;
|
||||||
use crate::tool::{Tool, ToolCtx, ToolResult, gate_why};
|
use crate::tool::{Tool, ToolCtx, ToolResult, gate_why};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
@@ -58,8 +59,62 @@ pub fn question(tool: &str, input: &Value) -> Option<Request> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Answer permission questions on `path` until the process ends.
|
/// `claude_cli` tool call in hx' vocabulary (`Bash` -> `bash {command}`); other tools keep claude's name.
|
||||||
pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
pub fn hx_call(tool: &str, input: &Value) -> (String, Value) {
|
||||||
|
let s = |k: &str| input[k].as_str().unwrap_or_default().to_string();
|
||||||
|
let path = || {
|
||||||
|
s(if input["file_path"].is_string() {
|
||||||
|
"file_path"
|
||||||
|
} else {
|
||||||
|
"notebook_path"
|
||||||
|
})
|
||||||
|
};
|
||||||
|
match tool {
|
||||||
|
"Bash" => ("bash".into(), json!({"command": s("command")})),
|
||||||
|
"Write" => ("write".into(), json!({"path": path()})),
|
||||||
|
"Edit" | "MultiEdit" | "NotebookEdit" => ("edit".into(), json!({"path": path()})),
|
||||||
|
"Read" => ("read".into(), json!({"path": path()})),
|
||||||
|
t => (t.into(), input.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the bridge does with a call nobody answered (no permission prompt, `-p`).
|
||||||
|
/// `permissions` in config.toml: absent = allow (compatible), "deny", "extensions-only".
|
||||||
|
#[derive(Clone, Copy, Default, PartialEq, Debug)]
|
||||||
|
pub enum Unanswered {
|
||||||
|
#[default]
|
||||||
|
Allow,
|
||||||
|
Deny,
|
||||||
|
/// allow only while a live extension guards `tool_call`
|
||||||
|
ExtensionsOnly,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Unanswered {
|
||||||
|
pub fn from_config(s: Option<&str>) -> Self {
|
||||||
|
match s {
|
||||||
|
Some("deny") => Self::Deny,
|
||||||
|
Some("extensions-only") => Self::ExtensionsOnly,
|
||||||
|
_ => Self::Allow,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(self, bus: &Bus) -> Result<(), String> {
|
||||||
|
match self {
|
||||||
|
Self::Allow => Ok(()),
|
||||||
|
Self::Deny => Err("no permission prompt available (permissions = \"deny\")".into()),
|
||||||
|
Self::ExtensionsOnly => match bus.guards() {
|
||||||
|
(n, true) if n > 0 => Ok(()),
|
||||||
|
_ => Err(
|
||||||
|
"no live extension guards tool_call (permissions = \"extensions-only\")".into(),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answer permission questions on `path` until the process ends. Every question is first sent to
|
||||||
|
/// `bus` as a `ToolCall` (extensions can block it), then goes through the usual prompt.
|
||||||
|
pub async fn serve(path: &Path, cx: ToolCtx, bus: Bus, mode: Unanswered) -> std::io::Result<()> {
|
||||||
let _ = std::fs::remove_file(path);
|
let _ = std::fs::remove_file(path);
|
||||||
let l = UnixListener::bind(path)?;
|
let l = UnixListener::bind(path)?;
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
@@ -69,7 +124,7 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
|||||||
}
|
}
|
||||||
loop {
|
loop {
|
||||||
let (c, _) = l.accept().await?;
|
let (c, _) = l.accept().await?;
|
||||||
let cx = cx.clone();
|
let (cx, bus) = (cx.clone(), bus.clone());
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let (r, mut w) = c.into_split();
|
let (r, mut w) = c.into_split();
|
||||||
let mut line = String::new();
|
let mut line = String::new();
|
||||||
@@ -79,7 +134,39 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
|||||||
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
||||||
// hx tools run by `codemode` inside mcp-serve ask for their own permission
|
// hx tools run by `codemode` inside mcp-serve ask for their own permission
|
||||||
let mut input = None;
|
let mut input = None;
|
||||||
let ok = if v["tool_name"] == "AskUserQuestion" {
|
let tool = v["tool_name"].as_str().unwrap_or_default();
|
||||||
|
let unprompted = |cx: &ToolCtx| {
|
||||||
|
if cx.state.permit.get().is_none() {
|
||||||
|
mode.check(&bus)
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut blocked = None;
|
||||||
|
if tool != "AskUserQuestion" && v.get("permit").is_none() {
|
||||||
|
let (name, args) = hx_call(tool, &v["input"]);
|
||||||
|
let id = v["tool_use_id"].as_str().unwrap_or_default();
|
||||||
|
if !id.is_empty() {
|
||||||
|
cx.state
|
||||||
|
.claude_seen
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.insert(id.into());
|
||||||
|
}
|
||||||
|
let o = bus
|
||||||
|
.emit(Event::ToolCall {
|
||||||
|
id: id.into(),
|
||||||
|
name,
|
||||||
|
args,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
blocked = o.blocked.map(|r| format!("blocked: {r}"));
|
||||||
|
}
|
||||||
|
let ok = if let Some(r) = blocked {
|
||||||
|
Err(r)
|
||||||
|
} else if let Err(r) = unprompted(&cx) {
|
||||||
|
Err(r)
|
||||||
|
} else if v["tool_name"] == "AskUserQuestion" {
|
||||||
// claude's own question tool: show hx's popup, hand the answers back as input
|
// claude's own question tool: show hx's popup, hand the answers back as input
|
||||||
input = ask(&cx, &v["input"]).await;
|
input = ask(&cx, &v["input"]).await;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -235,6 +322,25 @@ mod tests {
|
|||||||
assert_eq!(question("Foo", &json!({})).unwrap().rule, "claude:Foo");
|
assert_eq!(question("Foo", &json!({})).unwrap().rule, "claude:Foo");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn claude_calls_use_hx_names() {
|
||||||
|
assert_eq!(
|
||||||
|
hx_call("Bash", &json!({"command": "ls", "x": 1})),
|
||||||
|
("bash".into(), json!({"command": "ls"}))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
hx_call("MultiEdit", &json!({"file_path": "a"})),
|
||||||
|
("edit".into(), json!({"path": "a"}))
|
||||||
|
);
|
||||||
|
assert_eq!(hx_call("Read", &json!({"file_path": "a"})).0, "read");
|
||||||
|
assert_eq!(
|
||||||
|
hx_call("WebFetch", &json!({"url": "u"})),
|
||||||
|
("WebFetch".into(), json!({"url": "u"}))
|
||||||
|
);
|
||||||
|
assert_eq!(Unanswered::from_config(Some("deny")), Unanswered::Deny);
|
||||||
|
assert_eq!(Unanswered::from_config(None), Unanswered::Allow);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn ask_user_question_uses_popup() {
|
async fn ask_user_question_uses_popup() {
|
||||||
let cx = ToolCtx {
|
let cx = ToolCtx {
|
||||||
@@ -268,7 +374,7 @@ mod tests {
|
|||||||
let path =
|
let path =
|
||||||
std::env::temp_dir().join(format!("hx-approve-test-{}.sock", std::process::id()));
|
std::env::temp_dir().join(format!("hx-approve-test-{}.sock", std::process::id()));
|
||||||
let (p, c) = (path.clone(), cx.clone());
|
let (p, c) = (path.clone(), cx.clone());
|
||||||
tokio::spawn(async move { serve(&p, c).await });
|
tokio::spawn(async move { serve(&p, c, Bus::default(), Unanswered::Allow).await });
|
||||||
while !path.exists() {
|
while !path.exists() {
|
||||||
tokio::task::yield_now().await;
|
tokio::task::yield_now().await;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -161,6 +161,12 @@ impl Extension {
|
|||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Hook for Extension {
|
impl Hook for Extension {
|
||||||
|
fn guard(&self) -> Option<bool> {
|
||||||
|
self.subscribe
|
||||||
|
.iter()
|
||||||
|
.any(|s| s == "tool_call" || s == "*")
|
||||||
|
.then(|| self.alive.load(Ordering::SeqCst))
|
||||||
|
}
|
||||||
async fn on(&self, ev: &Event) -> HookAction {
|
async fn on(&self, ev: &Event) -> HookAction {
|
||||||
if !self.subscribe.iter().any(|s| s == ev.kind() || s == "*") {
|
if !self.subscribe.iter().any(|s| s == ev.kind() || s == "*") {
|
||||||
return HookAction::Continue;
|
return HookAction::Continue;
|
||||||
|
|||||||
@@ -100,11 +100,16 @@ pub enum HookAction {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait Hook: Send + Sync {
|
pub trait Hook: Send + Sync {
|
||||||
async fn on(&self, ev: &Event) -> HookAction;
|
async fn on(&self, ev: &Event) -> HookAction;
|
||||||
|
/// `Some(alive)` if this hook guards `tool_call` (extensions subscribed to it).
|
||||||
|
fn guard(&self) -> Option<bool> {
|
||||||
|
None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Clones share the hook list (the permission bridge emits on the agent's bus).
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct Bus {
|
pub struct Bus {
|
||||||
hooks: Vec<Arc<dyn Hook>>,
|
hooks: Arc<std::sync::RwLock<Vec<Arc<dyn Hook>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Aggregate outcome of dispatching one event to all hooks.
|
/// Aggregate outcome of dispatching one event to all hooks.
|
||||||
@@ -117,19 +122,29 @@ pub struct Outcome {
|
|||||||
|
|
||||||
impl Bus {
|
impl Bus {
|
||||||
pub fn add_arc(&mut self, h: Arc<dyn Hook>) -> &mut Self {
|
pub fn add_arc(&mut self, h: Arc<dyn Hook>) -> &mut Self {
|
||||||
self.hooks.push(h);
|
self.hooks
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.push(h);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
pub fn add(&mut self, h: impl Hook + 'static) -> &mut Self {
|
pub fn add(&mut self, h: impl Hook + 'static) -> &mut Self {
|
||||||
self.hooks.push(Arc::new(h));
|
self.add_arc(Arc::new(h))
|
||||||
self
|
}
|
||||||
|
|
||||||
|
/// (number of `tool_call` guards, all of them alive).
|
||||||
|
pub fn guards(&self) -> (usize, bool) {
|
||||||
|
let hooks = self.hooks.read().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let g: Vec<bool> = hooks.iter().filter_map(|h| h.guard()).collect();
|
||||||
|
(g.len(), g.iter().all(|a| *a))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Hooks run in registration order. First `Block` wins; `Mutate` is visible to later hooks.
|
/// Hooks run in registration order. First `Block` wins; `Mutate` is visible to later hooks.
|
||||||
pub async fn emit(&self, ev: Event) -> Outcome {
|
pub async fn emit(&self, ev: Event) -> Outcome {
|
||||||
let mut ev = ev;
|
let mut ev = ev;
|
||||||
let mut o = Outcome::default();
|
let mut o = Outcome::default();
|
||||||
for h in &self.hooks {
|
let hooks = self.hooks.read().unwrap_or_else(|e| e.into_inner()).clone();
|
||||||
|
for h in &hooks {
|
||||||
match h.on(&ev).await {
|
match h.on(&ev).await {
|
||||||
HookAction::Continue => {}
|
HookAction::Continue => {}
|
||||||
HookAction::Block(r) => {
|
HookAction::Block(r) => {
|
||||||
|
|||||||
@@ -84,6 +84,8 @@ pub struct State {
|
|||||||
/// ponytail: keyed by command text, so two identical commands running at once share a tail;
|
/// ponytail: keyed by command text, so two identical commands running at once share a tail;
|
||||||
/// key by call id once ToolCtx carries it.
|
/// key by call id once ToolCtx carries it.
|
||||||
pub live: Mutex<HashMap<String, String>>,
|
pub live: Mutex<HashMap<String, String>>,
|
||||||
|
/// `claude_cli` tool_use ids the permission bridge already put on the bus.
|
||||||
|
pub claude_seen: Mutex<std::collections::HashSet<String>>,
|
||||||
/// Structured last lens report for side panels.
|
/// Structured last lens report for side panels.
|
||||||
pub lens: Mutex<LensView>,
|
pub lens: Mutex<LensView>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,4 +13,28 @@ export HOME="$tmp/home" HX_CLAUDE_BIN="$root/tests/fake_claude.py" FAKE_CLAUDE_L
|
|||||||
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 "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 '"--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; }
|
grep -q "cm-ok" "$tmp/out" || { echo "FAIL codemode"; cat "$tmp/out" "$tmp/err"; exit 1; }
|
||||||
|
# bridge goes through the bus: an extension blocks a secret Read and `curl`; tool events reach NDJSON
|
||||||
|
cd "$tmp/repo"
|
||||||
|
export FAKE_ASK=1
|
||||||
|
timeout 20 "$root/target/debug/hx" -p "go" --mode json -s "$tmp/s2.jsonl" > "$tmp/o2" 2> "$tmp/e2" || { echo "FAIL ask run"; cat "$tmp/e2"; exit 1; }
|
||||||
|
python3 - "$tmp/o2" allow <<'PY' || { echo "FAIL events (no extension)"; exit 1; }
|
||||||
|
import json, sys
|
||||||
|
ev = [json.loads(l) for l in open(sys.argv[1]) if l.startswith("{")]
|
||||||
|
calls = [(e["name"], e["id"]) for e in ev if e["type"] == "tool_call"]
|
||||||
|
res = [e for e in ev if e["type"] == "tool_result"]
|
||||||
|
assert calls == [("read", "t1"), ("bash", "t2")], calls
|
||||||
|
assert [r["is_error"] for r in res] == [False, False] and "allow" in res[1]["content"], res
|
||||||
|
PY
|
||||||
|
printf 'claude_cli = []\n[lsp]\nmode = "off"\ntests = "off"\n[[extensions]]\ncommand = ["python3", "%s/tests/ext_block_all.py"]\n' "$root" > "$tmp/home/.hx/config.toml"
|
||||||
|
timeout 20 "$root/target/debug/hx" -p "go" --mode json -s "$tmp/s3.jsonl" > "$tmp/o3" 2> "$tmp/e3" || { echo "FAIL ext run"; cat "$tmp/e3"; exit 1; }
|
||||||
|
python3 - "$tmp/o3" <<'PY' || { echo "FAIL events (extension)"; cat "$tmp/e3"; exit 1; }
|
||||||
|
import json, sys
|
||||||
|
ev = [json.loads(l) for l in open(sys.argv[1]) if l.startswith("{")]
|
||||||
|
res = [e for e in ev if e["type"] == "tool_result"]
|
||||||
|
assert len(res) == 2 and all(r["is_error"] and "blocked: guard: " in r["content"] for r in res), res
|
||||||
|
PY
|
||||||
|
# a dead guard must not leave the run open under permissions = "extensions-only"
|
||||||
|
printf 'claude_cli = []\npermissions = "extensions-only"\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml"
|
||||||
|
timeout 20 "$root/target/debug/hx" -p "go" --mode json -s "$tmp/s4.jsonl" > "$tmp/o4" 2> "$tmp/e4" || { echo "FAIL deny run"; cat "$tmp/e4"; exit 1; }
|
||||||
|
grep -q 'extensions-only' "$tmp/o4" && ! grep -q '"content":"allow' "$tmp/o4" || { echo "FAIL extensions-only"; cat "$tmp/o4"; exit 1; }
|
||||||
echo "claude cli e2e ok"
|
echo "claude cli e2e ok"
|
||||||
Executable
+12
@@ -0,0 +1,12 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Test extension: subscribes to tool_call, blocks `read` of secrets and `bash` curl."""
|
||||||
|
import json, sys
|
||||||
|
for line in sys.stdin:
|
||||||
|
m = json.loads(line)
|
||||||
|
if m["method"] == "initialize":
|
||||||
|
r = {"subscribe": ["tool_call"], "tools": []}
|
||||||
|
else:
|
||||||
|
e = m["params"]["event"]
|
||||||
|
bad = (e["name"] == "read" and ".ssh" in e["args"]["path"]) or (e["name"] == "bash" and "curl" in e["args"]["command"])
|
||||||
|
r = {"action": "block", "reason": "guard: " + e["name"]} if bad else {"action": "continue"}
|
||||||
|
print(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}), flush=True)
|
||||||
@@ -6,6 +6,29 @@ if "--version" in sys.argv:
|
|||||||
print("fake"); sys.exit(0)
|
print("fake"); sys.exit(0)
|
||||||
def out(o): print(json.dumps(o), flush=True)
|
def out(o): print(json.dumps(o), flush=True)
|
||||||
reply = "hello from claude"
|
reply = "hello from claude"
|
||||||
|
if os.environ.get("FAKE_ASK"): # ask hx about a secret Read and `curl x` (ids t1/t2); report the answers
|
||||||
|
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"]})
|
||||||
|
asks = [("t1", "Read", {"file_path": "/home/u/.ssh/id_rsa"}), ("t2", "Bash", {"command": "curl x"})]
|
||||||
|
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n")
|
||||||
|
p.stdin.flush()
|
||||||
|
p.stdout.readline()
|
||||||
|
ans = []
|
||||||
|
for i, (tid, n, inp) in enumerate(asks): # one at a time: deterministic order
|
||||||
|
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 10 + i, "method": "tools/call", "params": {"name": "approve",
|
||||||
|
"arguments": {"tool_name": n, "input": inp, "tool_use_id": tid}}}) + "\n")
|
||||||
|
p.stdin.flush()
|
||||||
|
ans.append(json.loads(json.loads(p.stdout.readline())["result"]["content"][0]["text"]))
|
||||||
|
p.stdin.close()
|
||||||
|
out({"type": "system", "subtype": "init", "session_id": "S1"})
|
||||||
|
for (tid, n, inp), a in zip(asks, ans):
|
||||||
|
out({"type": "assistant", "session_id": "S1", "message": {"content": [{"type": "tool_use", "id": tid, "name": n, "input": inp}]}})
|
||||||
|
out({"type": "user", "session_id": "S1", "message": {"content": [{"type": "tool_result", "tool_use_id": tid,
|
||||||
|
"content": a["behavior"] + ": " + a.get("message", ""), "is_error": a["behavior"] == "deny"}]}})
|
||||||
|
out({"type": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 1, "output_tokens": 1}})
|
||||||
|
sys.exit(0)
|
||||||
if "--permission-prompt-tool" in sys.argv: # act like claude: ask hx whether `rm -rf x` may run
|
if "--permission-prompt-tool" in sys.argv: # act like claude: ask hx whether `rm -rf x` may run
|
||||||
import subprocess
|
import subprocess
|
||||||
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
|
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
|
||||||
|
|||||||
Reference in new issue
Block a user