Merge pull request 'claude_cli: tool calls on the event bus (#182)' (#183) from feat/claude-cli-bus into main
This commit was merged in pull request #183.
This commit is contained in:
commit
f1b3ee0607
13 files changed
+380
-12
No files matched your search
@@ -115,6 +115,18 @@ fn tool_line(b: &Value) -> String {
|
||||
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 {
|
||||
let n = |k: &str| u[k].as_u64().unwrap_or(0);
|
||||
Usage {
|
||||
@@ -184,7 +196,13 @@ impl Provider for ClaudeCli {
|
||||
let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a, "env": env}}});
|
||||
cmd.args(["--mcp-config", &cfg.to_string()]);
|
||||
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([
|
||||
"--settings",
|
||||
r#"{"permissions":{"ask":["Bash","Read","Grep","Glob","LS"]}}"#,
|
||||
]);
|
||||
}
|
||||
}
|
||||
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)
|
||||
let mut last: Option<Value> = None;
|
||||
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 {
|
||||
let Ok(v) = serde_json::from_str::<Value>(&l) else {
|
||||
continue;
|
||||
@@ -250,12 +270,37 @@ impl Provider for ClaudeCli {
|
||||
}
|
||||
for b in v["message"]["content"].as_array().into_iter().flatten() {
|
||||
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 {
|
||||
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") => {
|
||||
if let Some(w) = window(&v) {
|
||||
quota.windows.retain(|x| x.label != w.label);
|
||||
|
||||
@@ -258,6 +258,15 @@ pub enum StreamEvent {
|
||||
id: 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).
|
||||
Quota(Quota),
|
||||
Done {
|
||||
|
||||
@@ -595,6 +595,7 @@ async fn main() -> Result<()> {
|
||||
);
|
||||
print!("{}", hx_core::stats::task_report(&Session::open(&session)?));
|
||||
print!("{}", hx_core::stats::route_report(&session));
|
||||
print!("{}", hx_core::stats::claude_report(&session));
|
||||
print!("{}", hx_core::stats::sub_report(&session));
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1096,8 +1097,11 @@ async fn main() -> Result<()> {
|
||||
// claude asks here (via `hx mcp-serve`) before running its tools
|
||||
let (p, cx) = (hx_core::approve::sock_path(), agent.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 {
|
||||
let _ = hx_core::approve::serve(&p, cx).await;
|
||||
let _ = hx_core::approve::serve(&p, cx, bus, mode).await;
|
||||
});
|
||||
}
|
||||
let Some(prompt) = cli.print else {
|
||||
|
||||
@@ -378,6 +378,49 @@ impl Agent {
|
||||
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;
|
||||
}
|
||||
crate::stats::log_claude_tool(
|
||||
self.session.path(),
|
||||
&name,
|
||||
args.to_string().len(),
|
||||
content.len(),
|
||||
is_error,
|
||||
);
|
||||
self.emit(Event::ToolResult {
|
||||
id,
|
||||
name,
|
||||
args,
|
||||
content,
|
||||
is_error,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn emit(&self, ev: Event) -> crate::hook::Outcome {
|
||||
self.bus.emit(ev).await
|
||||
}
|
||||
@@ -460,6 +503,10 @@ impl Agent {
|
||||
if let StreamEvent::Done { message, stop, usage } = &ev {
|
||||
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;
|
||||
}
|
||||
None => break,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! 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::hook::{Bus, Event};
|
||||
use crate::permit::Request;
|
||||
use crate::tool::{Tool, ToolCtx, ToolResult, gate_why};
|
||||
use async_trait::async_trait;
|
||||
@@ -58,8 +59,64 @@ pub fn question(tool: &str, input: &Value) -> Option<Request> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer permission questions on `path` until the process ends.
|
||||
pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
||||
/// `claude_cli` tool call in hx' vocabulary (`Bash` -> `bash {command}`); other tools keep claude's name.
|
||||
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 {
|
||||
/// Unknown values (typos) deny: this is a safety setting, failing open would hide the mistake.
|
||||
/// `ask`, `auto` and `yolo` are the interactive modes and leave `-p` as it was.
|
||||
pub fn from_config(s: Option<&str>) -> Self {
|
||||
match s {
|
||||
None | Some("ask" | "auto" | "yolo") => Self::Allow,
|
||||
Some("extensions-only") => Self::ExtensionsOnly,
|
||||
Some(_) => Self::Deny,
|
||||
}
|
||||
}
|
||||
|
||||
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 l = UnixListener::bind(path)?;
|
||||
#[cfg(unix)]
|
||||
@@ -69,7 +126,7 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
||||
}
|
||||
loop {
|
||||
let (c, _) = l.accept().await?;
|
||||
let cx = cx.clone();
|
||||
let (cx, bus) = (cx.clone(), bus.clone());
|
||||
tokio::spawn(async move {
|
||||
let (r, mut w) = c.into_split();
|
||||
let mut line = String::new();
|
||||
@@ -79,7 +136,39 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
||||
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
||||
// hx tools run by `codemode` inside mcp-serve ask for their own permission
|
||||
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
|
||||
input = ask(&cx, &v["input"]).await;
|
||||
Ok(())
|
||||
@@ -235,6 +324,30 @@ mod tests {
|
||||
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);
|
||||
assert_eq!(Unanswered::from_config(Some("auto")), Unanswered::Allow);
|
||||
assert_eq!(
|
||||
Unanswered::from_config(Some("extrensions-only")),
|
||||
Unanswered::Deny
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ask_user_question_uses_popup() {
|
||||
let cx = ToolCtx {
|
||||
@@ -268,7 +381,7 @@ mod tests {
|
||||
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 });
|
||||
tokio::spawn(async move { serve(&p, c, Bus::default(), Unanswered::Allow).await });
|
||||
while !path.exists() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
|
||||
@@ -161,6 +161,12 @@ impl Extension {
|
||||
|
||||
#[async_trait]
|
||||
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 {
|
||||
if !self.subscribe.iter().any(|s| s == ev.kind() || s == "*") {
|
||||
return HookAction::Continue;
|
||||
|
||||
@@ -100,11 +100,16 @@ pub enum HookAction {
|
||||
#[async_trait]
|
||||
pub trait Hook: Send + Sync {
|
||||
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)]
|
||||
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.
|
||||
@@ -117,19 +122,29 @@ pub struct Outcome {
|
||||
|
||||
impl Bus {
|
||||
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
|
||||
}
|
||||
pub fn add(&mut self, h: impl Hook + 'static) -> &mut Self {
|
||||
self.hooks.push(Arc::new(h));
|
||||
self
|
||||
self.add_arc(Arc::new(h))
|
||||
}
|
||||
|
||||
/// (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.
|
||||
pub async fn emit(&self, ev: Event) -> Outcome {
|
||||
let mut ev = ev;
|
||||
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 {
|
||||
HookAction::Continue => {}
|
||||
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;
|
||||
/// key by call id once ToolCtx carries it.
|
||||
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.
|
||||
pub lens: Mutex<LensView>,
|
||||
}
|
||||
|
||||
@@ -46,6 +46,57 @@ pub fn task_report(s: &Session) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Append one `claude_cli` tool run to `<session>.claude` (claude runs the tools itself, so they
|
||||
/// are not session messages). Best effort.
|
||||
pub fn log_claude_tool(
|
||||
session: &std::path::Path,
|
||||
name: &str,
|
||||
args: usize,
|
||||
result: usize,
|
||||
err: bool,
|
||||
) {
|
||||
use std::io::Write;
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(session.with_extension("claude"))
|
||||
{
|
||||
let _ = writeln!(
|
||||
f,
|
||||
"{}",
|
||||
serde_json::json!({"name": name, "args": args, "result": result, "error": err})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tools claude ran itself (`<session>.claude`): calls, errors/blocks, argument and result bytes per tool.
|
||||
pub fn claude_report(session: &std::path::Path) -> String {
|
||||
let Ok(t) = std::fs::read_to_string(session.with_extension("claude")) else {
|
||||
return String::new();
|
||||
};
|
||||
let mut by: std::collections::BTreeMap<String, [u64; 4]> = Default::default();
|
||||
for v in t
|
||||
.lines()
|
||||
.filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
|
||||
{
|
||||
let e = by
|
||||
.entry(v["name"].as_str().unwrap_or("?").into())
|
||||
.or_default();
|
||||
e[0] += 1;
|
||||
e[1] += u64::from(v["error"] == true);
|
||||
e[2] += v["args"].as_u64().unwrap_or(0);
|
||||
e[3] += v["result"].as_u64().unwrap_or(0);
|
||||
}
|
||||
let mut s = String::from("claude tool calls (run by claude, not in the message history):\n");
|
||||
for (n, [c, e, a, r]) in by {
|
||||
let _ = writeln!(
|
||||
s,
|
||||
" {n}: {c} calls, {e} errors/blocked, args {a} B, results {r} B"
|
||||
);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// One line per subagent log in `<session>.sub/` (empty when there are none).
|
||||
/// Auto-mode choices from `<session>.route`: turns per tier, how often the tier was held back
|
||||
/// or forced, and how often the next prompt had to go up again (a pick that was too low).
|
||||
@@ -406,6 +457,22 @@ pub fn report(s: &Session) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn claude_tools_are_counted() {
|
||||
let p = std::env::temp_dir().join(format!("hx-claude-stats-{}.jsonl", std::process::id()));
|
||||
let c = p.with_extension("claude");
|
||||
let _ = std::fs::remove_file(&c);
|
||||
assert_eq!(super::claude_report(&p), "");
|
||||
super::log_claude_tool(&p, "bash", 10, 100, false);
|
||||
super::log_claude_tool(&p, "bash", 10, 20, true);
|
||||
let r = super::claude_report(&p);
|
||||
let _ = std::fs::remove_file(&c);
|
||||
assert!(
|
||||
r.contains("bash: 2 calls, 1 errors/blocked, args 20 B, results 120 B"),
|
||||
"{r}"
|
||||
);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
use hx_ai::{Message, Usage};
|
||||
|
||||
|
||||
Reference in new issue
Block a user