diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 8b19860..8008aaf 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -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(()); } diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 823bcc7..bef76c1 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -404,6 +404,13 @@ impl Agent { }) .await; } + crate::stats::log_claude_tool( + self.session.path(), + &name, + args.to_string().len(), + content.len(), + is_error, + ); self.emit(Event::ToolResult { id, name, diff --git a/crates/hx-core/src/approve.rs b/crates/hx-core/src/approve.rs index 8de9ed7..509fb3e 100644 --- a/crates/hx-core/src/approve.rs +++ b/crates/hx-core/src/approve.rs @@ -90,11 +90,13 @@ pub enum Unanswered { } 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 { - Some("deny") => Self::Deny, + None | Some("ask" | "auto" | "yolo") => Self::Allow, Some("extensions-only") => Self::ExtensionsOnly, - _ => Self::Allow, + Some(_) => Self::Deny, } } @@ -339,6 +341,11 @@ mod tests { ); 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] diff --git a/crates/hx-core/src/stats.rs b/crates/hx-core/src/stats.rs index e2f6c4c..dc7c7b7 100644 --- a/crates/hx-core/src/stats.rs +++ b/crates/hx-core/src/stats.rs @@ -46,6 +46,57 @@ pub fn task_report(s: &Session) -> String { ) } +/// Append one `claude_cli` tool run to `.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 (`.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 = Default::default(); + for v in t + .lines() + .filter_map(|l| serde_json::from_str::(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 `.sub/` (empty when there are none). /// Auto-mode choices from `.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}; diff --git a/tests/claude_cli_e2e.sh b/tests/claude_cli_e2e.sh index 40a5ab0..97f7eb8 100644 --- a/tests/claude_cli_e2e.sh +++ b/tests/claude_cli_e2e.sh @@ -25,6 +25,7 @@ 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 +"$root/target/debug/hx" stats "$tmp/s2.jsonl" | grep -q "bash: 1 calls, 0 errors" || { echo "FAIL stats"; "$root/target/debug/hx" stats "$tmp/s2.jsonl"; exit 1; } 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; }