Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

On the Claude engine, the CLI's own tools stop repeating a call that keeps failing (21d) (#693)

Oleksandr Ivanchenko10f0805a5842
diff --git a/.github/workflows/mac-local.yml b/.github/workflows/mac-local.yml
index 8486a9ae..e7961b35 100644
--- a/.github/workflows/mac-local.yml
+++ b/.github/workflows/mac-local.yml
@@ -3,7 +3,7 @@ name: mac-local
# 0.8.0 079-mac-local-hardening: Claude on this computer, on a Mac (src/drivers/mac_local.rs).
# ci.yml's rust job runs on Linux and mac.yml only builds apps/mac, so kwnt's macOS code path
# (cfg!(target_os = "macos") in drivers/cli.rs) would otherwise never run in CI. This job:
-# - runs the hardening's unit tests on macOS (exactly 12, so a rename can't skip them), and
+# - runs the hardening's unit tests on macOS (exactly 13, so a rename can't skip them), and
# - runs scripts/mac_local_probe.sh: the real Claude Code accepts kwnt's settings, Seatbelt
# (sandbox-runtime, what Claude's Bash sandbox is built on) enforces the denied places, and
# whether the Keychain is reachable through the security service (reported, not enforced).
@@ -74,7 +74,7 @@ jobs:
run: |
set -o pipefail
cargo test --locked --lib -- mac_local:: no_tools::a_mac_claude_turn no_tools::the_hardening_reaches 2>&1 | tee unit.log
- grep -q "test result: ok. 12 passed; 0 failed; 1 ignored" unit.log || { echo "::error::expected exactly 12 hardening tests to pass"; exit 1; }
+ grep -q "test result: ok. 13 passed; 0 failed; 1 ignored" unit.log || { echo "::error::expected exactly 13 hardening tests to pass"; exit 1; }
- name: Probe the real Claude and Seatbelt
run: |
set -o pipefail
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 52f2c4e4..20456e0b 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -1580,6 +1580,10 @@ impl Driver for CliDriver {
let mut codex_out_file: Option<String> = None;
// Lives until the CLI exits; dropping it deletes the per-turn MCP config file.
let mut _mcp_config: Option<crate::mcp::cli_config::ConfigFile> = None;
+ // 21d: the curl config claude's repeat-guard hooks post through; lives as long as the CLI
+ let mut repeat_hook: Option<crate::mcp::cli_config::ConfigFile> = None;
+ // Whether this computer's `--settings` already went in (claude: before its prompt)
+ let mut settings_added = false;
let effort = input.effort_level.as_deref().unwrap_or("medium");
@@ -1823,6 +1827,16 @@ impl Driver for CliDriver {
// timeout (300 s) always ends a waiting card first (QA F-2)
cmd.env("CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT", tool_timeout_ms.to_string());
cmd.env("MCP_TIMEOUT", "30000");
+ // 21d: claude's own tools (Bash, Read…) report each result to the turn's
+ // repeat guard, which refuses the 4th identical failing call. Only on this
+ // computer: a VM turn's claude gets none of these settings
+ let builtins = !input.no_tools && !ctx.kwnt_only;
+ if let (true, true, Some(url)) = (file.is_some(), builtins, ctx.permission_url.as_deref()) {
+ match crate::mcp::cli_hooks::write_curl_config(&ctx.config_dir, url) {
+ Ok(f) => repeat_hook = Some(f),
+ Err(e) => tracing::warn!(error = %e, "couldn't write the repeat guard's hook config; claude's own tools run unguarded"),
+ }
+ }
_mcp_config = file;
}
Err(e) => {
@@ -1842,6 +1856,17 @@ impl Driver for CliDriver {
// JSON lines as claude works, ending in one result that tells a usage limit or
// sign-out apart from a reply; partial messages keep a long answer from looking stalled
cmd.arg("--output-format").arg("stream-json").arg("--verbose").arg("--include-partial-messages");
+ // This computer's settings (Mac hardening, 21d's repeat-guard hooks) go before the
+ // prompt, so the prompt stays the last argument (QA 21d round 3)
+ if isolated.is_none() {
+ let mut settings = self.local_settings_args(cfg!(target_os = "macos"));
+ if let Some(hook) = &repeat_hook {
+ // 21d: in the same one `--settings`, joined with any hooks already there
+ super::mac_local::merge_settings_arg(&mut settings, crate::mcp::cli_hooks::settings(&hook.path));
+ }
+ cmd.args(settings);
+ settings_added = true;
+ }
cmd.arg("-p").arg(&effective_prompt);
}
}
@@ -1853,8 +1878,11 @@ impl Driver for CliDriver {
if let Some(env) = &self.profile_env {
env.apply(&mut cmd);
}
- // claude -p has no subcommand, so its overrides can follow the other options
- cmd.args(self.local_settings_args(cfg!(target_os = "macos")));
+ // claude's own settings were added before its prompt; the other CLIs' overrides
+ // follow their other options
+ if !settings_added {
+ cmd.args(self.local_settings_args(cfg!(target_os = "macos")));
+ }
}
// codex's reply comes from its -o file; its stdout carries the `--json` steps
@@ -2795,6 +2823,49 @@ endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\n
}
}
+ /// 21d: a claude turn with kwnt's tools gets the repeat guard's three hooks in its one
+ /// `--settings`; their curl config holds the turn's hook URL while claude runs, never argv,
+ /// and is gone after. A turn without claude's own tools (customer, no tools) gets none.
+ #[tokio::test]
+ async fn claudes_own_tools_get_the_repeat_guard_hooks() {
+ let cfg = tempfile::tempdir().unwrap();
+ let body = format!("{RECORD}\ncat {}/claude-hook-*.curl > {{dir}}/curl 2>/dev/null\necho '{CLAUDE_RESULT}'", cfg.path().display());
+ let url = "http://127.0.0.1:8790/api/mcp/permission/tokTOK123";
+ let with = |kwnt_only: bool| TurnInput {
+ mcp: Some(crate::mcp::McpTurnContext { permission_url: Some(url.into()), kwnt_only, ..mcp_context(cfg.path()) }),
+ ..turn(false)
+ };
+ let fake = Fake::new("claude", &body);
+ fake.run(with(false)).await.unwrap();
+ let argv = fake.argv();
+ let settings: Vec<&String> = argv.windows(2).filter(|w| w[0] == "--settings").map(|w| &w[1]).collect();
+ assert_eq!(settings.len(), 1, "{argv:?}");
+ let v: serde_json::Value = serde_json::from_str(settings[0]).unwrap();
+ for event in crate::mcp::cli_hooks::HOOK_EVENTS {
+ let cmd = v["hooks"][event][0]["hooks"][0]["command"].as_str().unwrap_or_else(|| panic!("{event}: {v}"));
+ assert!(cmd.starts_with("curl -sf -m 2 ") && cmd.ends_with(" || true"), "{cmd}");
+ assert!(cmd.contains(&cfg.path().display().to_string()), "{cmd}");
+ }
+ if cfg!(target_os = "macos") {
+ assert_eq!(v["sandbox"]["enabled"], true, "with the Mac hardening, in the same object");
+ }
+ assert!(argv.iter().all(|a| !a.contains("tokTOK123")), "the token stays out of argv: {argv:?}");
+ // The prompt stays the last argument, after the settings (QA 21d round 3: the hooks
+ // after it hid an ask_user call from a CLI that reads its prompt last)
+ assert_eq!(argv[argv.len() - 2], "-p", "{argv:?}");
+ assert!(argv.iter().position(|a| a == "--settings").unwrap() < argv.len() - 2, "{argv:?}");
+ assert_eq!(std::fs::read_to_string(fake.path("curl")).unwrap(), format!("url = \"{url}/hook\"\n"));
+ let left: Vec<_> = std::fs::read_dir(cfg.path()).unwrap().flatten().map(|e| e.file_name()).collect();
+ assert!(left.is_empty(), "the turn's config files go with it: {left:?}");
+
+ // A customer's turn has no built-in tools: no hooks
+ let fake = Fake::new("claude", &body);
+ fake.run(with(true)).await.unwrap();
+ let argv = fake.argv();
+ assert!(argv.iter().all(|a| !a.contains("PreToolUse")), "{argv:?}");
+ assert_eq!(std::fs::read_to_string(fake.path("curl")).unwrap_or_default(), "", "no hook config");
+ }
+
const CLAUDE_INIT_EMPTY: &str = r#"{"type":"system","subtype":"init","tools":[],"mcp_servers":[],"skills":[],"slash_commands":[]}"#;
const CLAUDE_RESULT: &str = r#"{"type":"result","subtype":"success","is_error":false,"num_turns":1,"result":"The card."}"#;
diff --git a/src/drivers/mac_local.rs b/src/drivers/mac_local.rs
index 7207831c..b1ad96da 100644
--- a/src/drivers/mac_local.rs
+++ b/src/drivers/mac_local.rs
@@ -260,11 +260,23 @@ pub fn settings(places: &Places, seatbelt: bool, ssh_auth_sock: Option<&str>) ->
/// Merges `extra` into the `--settings` JSON already in `args` (a profile's env overrides), or
/// appends `--settings extra`. Claude reads one `--settings`, so they must be one object.
+/// 21d: `hooks` merge per event (both lists of matchers run); any other key is replaced.
pub fn merge_settings_arg(args: &mut Vec<String>, extra: Value) {
if let Some(i) = args.iter().position(|a| a == "--settings") {
if let Some(Ok(Value::Object(mut have))) = args.get(i + 1).map(|v| serde_json::from_str::<Value>(v)) {
if let Value::Object(add) = extra {
for (k, v) in add {
+ if let (true, Some(Value::Object(old)), Value::Object(new)) = (k == "hooks", have.get_mut("hooks"), &v) {
+ for (event, matchers) in new {
+ match (old.get_mut(event), matchers) {
+ (Some(Value::Array(list)), Value::Array(more)) => list.extend(more.iter().cloned()),
+ _ => {
+ old.insert(event.clone(), matchers.clone());
+ }
+ }
+ }
+ continue;
+ }
have.insert(k, v);
}
}
@@ -388,6 +400,31 @@ mod tests {
assert_eq!(args[2], "--settings");
}
+ /// 21d: the repeat guard's hooks join hooks already in the one `--settings`, per event
+ #[test]
+ fn hooks_merge_per_event_into_the_one_settings() {
+ let mine = json!({"matcher": "Bash", "hooks": [{"type": "command", "command": "mine"}]});
+ let mut args = vec!["--settings".to_string(), json!({ "env": { "A": "1" }, "hooks": { "PreToolUse": [mine], "Stop": [] } }).to_string()];
+ let guard = crate::mcp::cli_hooks::settings(std::path::Path::new("/d/claude-hook-1.curl"));
+ merge_settings_arg(&mut args, guard.clone());
+ merge_settings_arg(&mut args, settings(&places(), true, None));
+ assert_eq!(args.iter().filter(|a| *a == "--settings").count(), 1, "{args:?}");
+ let v: Value = serde_json::from_str(&args[1]).unwrap();
+ assert_eq!(v["env"]["A"], "1");
+ assert_eq!(v["sandbox"]["enabled"], true);
+ let pre = v["hooks"]["PreToolUse"].as_array().unwrap();
+ assert_eq!(pre.len(), 2, "the existing PreToolUse hook stays: {pre:?}");
+ assert_eq!(pre[0]["hooks"][0]["command"], "mine");
+ assert_eq!(pre[1], guard["hooks"]["PreToolUse"][0]);
+ assert_eq!(v["hooks"]["PostToolUse"], guard["hooks"]["PostToolUse"]);
+ assert_eq!(v["hooks"]["PostToolUseFailure"], guard["hooks"]["PostToolUseFailure"]);
+ assert_eq!(v["hooks"]["Stop"], json!([]));
+ // No --settings yet: the hooks alone become it
+ let mut args = vec!["-p".to_string(), "hi".to_string()];
+ merge_settings_arg(&mut args, guard.clone());
+ assert_eq!(args[3], guard.to_string());
+ }
+
#[test]
fn paths_become_absolute_rules() {
assert_eq!(rule_path("/Users/o/.claude/", true), "//Users/o/.claude/**");
diff --git a/src/mcp/cli_config.rs b/src/mcp/cli_config.rs
index aadc4269..104e6b89 100644
--- a/src/mcp/cli_config.rs
+++ b/src/mcp/cli_config.rs
@@ -35,7 +35,7 @@ impl Drop for ConfigFile {
}
}
-fn create_private_dir(dir: &Path) -> std::io::Result<()> {
+pub(crate) fn create_private_dir(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
#[cfg(unix)]
{
diff --git a/src/mcp/cli_hooks.rs b/src/mcp/cli_hooks.rs
new file mode 100644
index 00000000..ff44be88
--- /dev/null
+++ b/src/mcp/cli_hooks.rs
@@ -0,0 +1,283 @@
+//! 21d: on the claude engine, the CLI's own tools (Bash, Read, WebFetch…) stop repeating a call
+//! that keeps failing.
+//!
+//! kwnt only sees a built-in call's permission prompt, never its result, and claude allows some
+//! calls (Read, Grep…) without asking at all. So the turn's one `--settings` gets three command
+//! hooks that post claude's hook payload to [`hook_url`] for this turn's token:
+//! - `PreToolUse`: kwnt checks the turn's [`RepeatGuard`]; on a stop it answers
+//! `permissionDecision: "deny"` with the same [`stop_text`](super::repeat_guard::stop_text) as
+//! kwnt's own tools (18a), so the model reads the same words. Claude runs PreToolUse before its
+//! permission check, so a stopped call never shows a card.
+//! - `PostToolUse` (claude 2.1.325: a call that worked) clears the call.
+//! - `PostToolUseFailure` (a call that failed, with its `error` text, e.g. `"Exit code 1\n…"`)
+//! counts one more identical failure. A call claude or the person denied fires neither event.
+//!
+//! The hook never blocks a turn on its own error: `curl -sf -m 2 … || true` exits 0 with no output
+//! when kwnt is unreachable, slow, or answers with an error, and claude then runs the call as usual.
+//! The URL (it carries the turn's token) sits in a 0600 curl config file, never in argv.
+
+use super::cli_config::{create_private_dir, ConfigFile};
+use super::repeat_guard::{is_stop_text, RepeatGuard};
+use serde_json::{json, Value};
+use std::io::Write;
+use std::path::Path;
+
+/// The hook events kwnt asks claude to post.
+pub const HOOK_EVENTS: [&str; 3] = ["PreToolUse", "PostToolUse", "PostToolUseFailure"];
+
+/// Only claude's own tools: MCP tools (`mcp__…`) are left to their own guards (kwnt's own tools
+/// have 18a's). claude's matcher is a JavaScript regular expression.
+pub const BUILTIN_MATCHER: &str = "^(?!mcp__)";
+
+/// Seconds claude waits for the hook before it runs the call anyway (curl itself gives up after 2).
+const HOOK_TIMEOUT_SECS: u64 = 5;
+
+/// Where the hooks post for the turn whose permission endpoint is `permission_url`.
+pub fn hook_url(permission_url: &str) -> String {
+ format!("{}/hook", permission_url.trim_end_matches('/'))
+}
+
+fn sh_quote(s: &str) -> String {
+ format!("'{}'", s.replace('\'', "'\\''"))
+}
+
+/// The hook command: posts claude's payload (stdin) to the URL in `curl_config`. Silent and
+/// exit 0 whatever happens, so a failure never blocks the call (exit 2 would).
+pub fn hook_command(curl_config: &Path) -> String {
+ format!(
+ "curl -sf -m 2 -H 'Content-Type: application/json' --data-binary @- -K {} || true",
+ sh_quote(&curl_config.to_string_lossy())
+ )
+}
+
+/// The `hooks` object merged into the turn's one `--settings`.
+pub fn settings(curl_config: &Path) -> Value {
+ let entry = json!([{
+ "matcher": BUILTIN_MATCHER,
+ "hooks": [{"type": "command", "command": hook_command(curl_config), "timeout": HOOK_TIMEOUT_SECS}],
+ }]);
+ let mut hooks = serde_json::Map::new();
+ for event in HOOK_EVENTS {
+ hooks.insert(event.to_string(), entry.clone());
+ }
+ json!({ "hooks": hooks })
+}
+
+/// Writes the curl config (`url = "…"`, mode 0600) for this turn's hooks next to its MCP config.
+/// Removed when the returned guard drops.
+pub fn write_curl_config(config_dir: &Path, permission_url: &str) -> std::io::Result<ConfigFile> {
+ create_private_dir(config_dir)?;
+ let path = config_dir.join(format!("claude-hook-{}.curl", uuid::Uuid::new_v4().simple()));
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options.open(&path)?;
+ let guard = ConfigFile { path };
+ let url = hook_url(permission_url).replace('\\', "\\\\").replace('"', "\\\"");
+ file.write_all(format!("url = \"{url}\"\n").as_bytes())?;
+ file.sync_all()?;
+ Ok(guard)
+}
+
+/// The same call is the same key as 18a's (tool name plus arguments), except Bash's
+/// `description`: the model writes a new one for the same command, and it changes nothing.
+pub fn key(tool: &str, input: &Value) -> [u8; 32] {
+ match input {
+ Value::Object(map) if tool == "Bash" && map.contains_key("description") => {
+ let mut map = map.clone();
+ map.remove("description");
+ RepeatGuard::key(tool, &Value::Object(map))
+ }
+ _ => RepeatGuard::key(tool, input),
+ }
+}
+
+/// What kwnt does with one hook payload. `Some` is the hook's stdout (a PreToolUse deny);
+/// `None` means no output, and claude goes on as usual.
+pub fn on_event(guard: &RepeatGuard, msg: &Value) -> Option<Value> {
+ let tool = msg["tool_name"].as_str().unwrap_or("");
+ if tool.is_empty() || tool.starts_with("mcp__") {
+ return None;
+ }
+ let input = msg.get("tool_input").cloned().unwrap_or_else(|| json!({}));
+ let k = key(tool, &input);
+ match msg["hook_event_name"].as_str().unwrap_or("") {
+ "PreToolUse" => {
+ let stopped = guard.check(&k)?;
+ tracing::info!(tool = %tool, count = stopped.count, "repeat guard: didn't run a claude tool call that kept failing the same way");
+ Some(json!({
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": stopped.text,
+ }
+ }))
+ }
+ "PostToolUse" => {
+ guard.after(&k, "ok", "");
+ None
+ }
+ "PostToolUseFailure" => {
+ let error = msg["error"].as_str().unwrap_or("");
+ // The person pressing stop isn't a failure; a stop text is the guard's own words
+ if msg["is_interrupt"] != json!(true) && !is_stop_text(error) {
+ guard.after(&k, "error", error);
+ }
+ None
+ }
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::mcp::repeat_guard::{STOP_PREFIX, REPEAT_LIMIT};
+
+ // Shapes recorded from claude 2.1.325 (Nov 15), see autonomy/cli-tools-repeat-guard/impl.md
+ fn pre(tool: &str, input: Value) -> Value {
+ json!({"session_id": "s", "hook_event_name": "PreToolUse", "tool_name": tool, "tool_input": input, "tool_use_id": "toolu_1"})
+ }
+ fn failed(tool: &str, input: Value, error: &str) -> Value {
+ json!({"hook_event_name": "PostToolUseFailure", "tool_name": tool, "tool_input": input, "tool_use_id": "toolu_1",
+ "error": error, "is_interrupt": false, "duration_ms": 19})
+ }
+ fn worked(tool: &str, input: Value) -> Value {
+ json!({"hook_event_name": "PostToolUse", "tool_name": tool, "tool_input": input, "tool_use_id": "toolu_1",
+ "tool_response": {"stdout": "x", "stderr": "", "interrupted": false}})
+ }
+ const CAT_ERR: &str = "Exit code 1\ncat: /tmp/missing-a.txt: No such file or directory";
+
+ fn bash(description: &str) -> Value {
+ json!({"command": "cat /tmp/missing-a.txt", "description": description})
+ }
+
+ #[test]
+ fn three_failures_deny_the_fourth_with_the_same_stop_text() {
+ let g = RepeatGuard::default();
+ for i in 0..REPEAT_LIMIT {
+ assert_eq!(on_event(&g, &pre("Bash", bash(&format!("try {i}")))), None, "call {} runs", i + 1);
+ assert_eq!(on_event(&g, &failed("Bash", bash(&format!("try {i}")), CAT_ERR)), None);
+ }
+ let out = on_event(&g, &pre("Bash", bash("one more"))).expect("4th call denied");
+ let o = &out["hookSpecificOutput"];
+ assert_eq!(o["hookEventName"], "PreToolUse");
+ assert_eq!(o["permissionDecision"], "deny");
+ let reason = o["permissionDecisionReason"].as_str().unwrap();
+ assert!(reason.starts_with(STOP_PREFIX), "{reason}");
+ assert!(reason.contains("already failed 3 times in this turn"), "{reason}");
+ assert!(reason.contains("cat: /tmp/missing-a.txt: No such file or directory"), "{reason}");
+ assert_eq!(
+ reason,
+ crate::mcp::repeat_guard::stop_text(3, CAT_ERR),
+ "the same words as kwant's own tools (18a)"
+ );
+ // A different command isn't stopped
+ assert_eq!(on_event(&g, &pre("Bash", json!({"command": "cat /tmp/other"}))), None);
+ }
+
+ #[test]
+ fn a_different_error_starts_again_and_ok_clears() {
+ let g = RepeatGuard::default();
+ let input = json!({"file_path": "/tmp/nope.txt"});
+ for _ in 0..2 {
+ on_event(&g, &failed("Read", input.clone(), "File does not exist."));
+ }
+ on_event(&g, &failed("Read", input.clone(), "EACCES: permission denied"));
+ on_event(&g, &failed("Read", input.clone(), "EACCES: permission denied"));
+ assert_eq!(on_event(&g, &pre("Read", input.clone())), None, "2 of the new error so far");
+ on_event(&g, &failed("Read", input.clone(), "EACCES: permission denied"));
+ assert!(on_event(&g, &pre("Read", input.clone())).is_some(), "3 of the new error");
+ // The file appears: an ok clears the call
+ on_event(&g, &worked("Read", input.clone()));
+ assert_eq!(on_event(&g, &pre("Read", input.clone())), None);
+ for _ in 0..2 {
+ on_event(&g, &failed("Read", input.clone(), "EACCES: permission denied"));
+ }
+ assert_eq!(on_event(&g, &pre("Read", input)), None, "counting starts again after an ok");
+ }
+
+ #[test]
+ fn interrupts_stop_texts_and_mcp_tools_are_not_counted() {
+ let g = RepeatGuard::default();
+ let input = json!({"url": "https://x.test"});
+ for _ in 0..5 {
+ let mut m = failed("WebFetch", input.clone(), "Request aborted");
+ m["is_interrupt"] = json!(true);
+ on_event(&g, &m);
+ let stop = crate::mcp::repeat_guard::stop_text(3, "boom");
+ on_event(&g, &failed("WebFetch", input.clone(), &format!("PreToolUse:WebFetch hook error: {stop}")));
+ }
+ assert_eq!(on_event(&g, &pre("WebFetch", input)), None);
+ let mcp = json!({"q": 1});
+ for _ in 0..5 {
+ on_event(&g, &failed("mcp__github__create_issue", mcp.clone(), "422"));
+ }
+ assert_eq!(on_event(&g, &pre("mcp__github__create_issue", mcp)), None, "left to the MCP guards");
+ // kwnt's own ask_user (and its question tool) never pass through these hooks: a question
+ // that "fails" (dismissed, timed out) any number of times is never denied or counted
+ for tool in ["mcp__kwnt_tools__ask_user", "mcp__kwnt__ask_user", "mcp__kwnt_tools__question"] {
+ let ask = json!({"question": "Ship it?", "choices": ["yes", "no"]});
+ for _ in 0..5 {
+ assert_eq!(on_event(&g, &pre(tool, ask.clone())), None, "{tool}");
+ assert_eq!(on_event(&g, &failed(tool, ask.clone(), "The person dismissed the question.")), None, "{tool}");
+ }
+ assert_eq!(on_event(&g, &pre(tool, ask)), None, "{tool} is never denied");
+ }
+ // Junk never panics and never denies
+ for junk in [json!(null), json!({}), json!({"hook_event_name": "PreToolUse"}), json!({"tool_name": "Bash"})] {
+ assert_eq!(on_event(&g, &junk), None);
+ }
+ }
+
+ #[test]
+ fn the_bash_description_is_not_part_of_the_call() {
+ assert_eq!(key("Bash", &bash("a")), key("Bash", &bash("b")));
+ assert_eq!(key("Bash", &bash("a")), key("Bash", &json!({"command": "cat /tmp/missing-a.txt"})));
+ assert_ne!(key("Bash", &bash("a")), key("Bash", &json!({"command": "cat /tmp/missing-b.txt", "description": "a"})));
+ // Other tools keep every argument
+ assert_ne!(key("Task", &json!({"description": "a"})), key("Task", &json!({"description": "b"})));
+ }
+
+ #[test]
+ fn settings_post_three_events_for_builtin_tools_and_fail_open() {
+ let path = Path::new("/Users/o/Library/Application Support/kwnt/mcp/claude-hook-1.curl");
+ let v = settings(path);
+ let hooks = v["hooks"].as_object().unwrap();
+ assert_eq!(hooks.len(), 3);
+ for event in HOOK_EVENTS {
+ let e = &hooks[event][0];
+ assert_eq!(e["matcher"], BUILTIN_MATCHER);
+ let h = &e["hooks"][0];
+ assert_eq!(h["type"], "command");
+ assert_eq!(h["timeout"], 5);
+ let cmd = h["command"].as_str().unwrap();
+ assert!(cmd.starts_with("curl -sf -m 2 "), "{cmd}");
+ assert!(cmd.ends_with(" || true"), "never exits 2: {cmd}");
+ assert!(cmd.contains("-K '/Users/o/Library/Application Support/kwnt/mcp/claude-hook-1.curl'"), "{cmd}");
+ assert!(!cmd.contains("/api/mcp/permission"), "the token stays out of argv: {cmd}");
+ }
+ assert_eq!(hook_command(Path::new("/a/it's")), "curl -sf -m 2 -H 'Content-Type: application/json' --data-binary @- -K '/a/it'\\''s' || true");
+ }
+
+ #[test]
+ fn the_curl_config_holds_the_url_privately_and_goes_with_its_guard() {
+ let dir = tempfile::tempdir().unwrap();
+ let mcp = dir.path().join("mcp");
+ let f = write_curl_config(&mcp, "http://127.0.0.1:8790/api/mcp/permission/tok_A-1").unwrap();
+ let text = std::fs::read_to_string(&f.path).unwrap();
+ assert_eq!(text, "url = \"http://127.0.0.1:8790/api/mcp/permission/tok_A-1/hook\"\n");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(std::fs::metadata(&f.path).unwrap().permissions().mode() & 0o777, 0o600);
+ }
+ let path = f.path.clone();
+ drop(f);
+ assert!(!path.exists());
+ }
+}
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index 6753eed0..b86753e5 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -3,6 +3,7 @@
pub mod builtin_tools;
pub mod cli_config;
+pub mod cli_hooks;
pub mod client;
pub mod composio;
pub mod echo_server;
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index def9a791..d1774775 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -49,11 +49,24 @@ pub struct PermissionSession {
gateway: Arc<Mutex<Option<Arc<McpToolSession>>>>,
/// Cancelled when the turn ends: calls still waiting (for a card) give up.
ended: CancellationToken,
+ /// 21d: the turn's repeat guard for claude's own tools (Bash, Read…), fed by its hooks
+ /// ([`permission_hook_endpoint`]). Separate from 18a's guard for kwnt's own tools; it goes
+ /// when `finish_turn` drops the session.
+ pub repeats: Arc<crate::mcp::repeat_guard::RepeatGuard>,
}
impl PermissionSession {
pub fn new(kwant_id: String, kwant_name: String, turn_id: String, ctx: McpTurnContext, cwd: Option<PathBuf>) -> Self {
- Self { kwant_id, kwant_name, turn_id, ctx, cwd, gateway: Default::default(), ended: CancellationToken::new() }
+ Self {
+ kwant_id,
+ kwant_name,
+ turn_id,
+ ctx,
+ cwd,
+ gateway: Default::default(),
+ ended: CancellationToken::new(),
+ repeats: Default::default(),
+ }
}
fn caller(&self) -> Caller {
@@ -1343,6 +1356,24 @@ pub async fn permission_endpoint(
}
}
+/// `POST /api/mcp/permission/:token/hook`: claude's PreToolUse, PostToolUse and
+/// PostToolUseFailure hooks for this turn's built-in tools ([`mcp::cli_hooks`]). Answers a
+/// PreToolUse deny when the same call already failed 3 times the same way, and nothing otherwise
+/// (204). An unknown token is a 404, which the hook's `curl -f` turns into no output: the call runs.
+pub async fn permission_hook_endpoint(State(state): State<AppState>, Path(token): Path<String>, Json(msg): Json<Value>) -> Response {
+ let session = state.mcp_sessions.lock().await.get(&token).cloned();
+ let Some(session) = session else {
+ return StatusCode::NOT_FOUND.into_response();
+ };
+ match mcp::cli_hooks::on_event(&session.repeats, &msg) {
+ Some(out) => {
+ tracing::info!(kwant = %session.kwant_id, turn = %session.turn_id, "repeat guard: a claude tool call was denied");
+ Json(out).into_response()
+ }
+ None => StatusCode::NO_CONTENT.into_response(),
+ }
+}
+
fn bearer_token(headers: &HeaderMap) -> Option<&str> {
let value = headers.get(AUTHORIZATION)?.to_str().ok()?;
let (scheme, token) = value.split_once(' ')?;
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 829c7d82..47522135 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -456,6 +456,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/mcp/oauth/client.json", get(mcp_oauth::client_document))
.route("/api/kwants/:id/mcp-servers", get(mcp_routes::get_kwant_servers).put(mcp_routes::set_kwant_servers))
.route("/api/mcp/permission/:token", post(mcp_runtime::permission_endpoint))
+ .route("/api/mcp/permission/:token/hook", post(mcp_runtime::permission_hook_endpoint))
.route("/api/mcp/gateway", post(mcp_runtime::gateway_endpoint))
.route("/api/mcp/gateway/grok", post(mcp_runtime::gateway_grok_endpoint))
.route("/api/mcp/self", post(continuity::self_endpoint))
diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rs
index dcc5dae7..adbe4e42 100644
--- a/tests/mcp_runtime_test.rs
+++ b/tests/mcp_runtime_test.rs
@@ -279,6 +279,79 @@ async fn permission_endpoint_answers_claude_prompts_over_http() {
assert!(McpClient::connect(&http_server(format!("{base}/api/mcp/permission/gone")), None).await.is_err());
}
+/// 21d: claude's hooks for its own tools, through the real route and the real hook command
+/// (`sh -c "curl … || true"` with the payload on stdin, as claude runs it): 3 identical failures
+/// deny the 4th call with the stop text, a different error starts again, an ok clears the call,
+/// and an unreachable kwnt or a finished turn lets every call through (no output, exit 0).
+#[cfg(unix)]
+#[tokio::test]
+async fn claude_hooks_stop_the_fourth_identical_failing_call() {
+ let (state, tmp) = state().await;
+ let base = serve(state.clone()).await;
+ let c = ctx(tmp.path(), Arc::new(FixedApprover(true)));
+ state.mcp_sessions.lock().await.insert("hook-tok".into(), PermissionSession::new("k1".into(), "Ada".into(), "t1".into(), c, None));
+ let curl = kwnt::mcp::cli_hooks::write_curl_config(&tmp.path().join("mcp"), &format!("{base}/api/mcp/permission/hook-tok")).unwrap();
+ let cmd = kwnt::mcp::cli_hooks::hook_command(&curl.path);
+ let hook = |payload: Value| {
+ let cmd = cmd.clone();
+ async move {
+ tokio::task::spawn_blocking(move || {
+ use std::io::Write;
+ let mut child = std::process::Command::new("sh")
+ .arg("-c")
+ .arg(&cmd)
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .spawn()
+ .unwrap();
+ child.stdin.take().unwrap().write_all(payload.to_string().as_bytes()).unwrap();
+ let out = child.wait_with_output().unwrap();
+ assert_eq!(out.status.code(), Some(0), "the hook never blocks a call on its own: {cmd}");
+ String::from_utf8(out.stdout).unwrap()
+ })
+ .await
+ .unwrap()
+ }
+ };
+ let input = json!({"command": "cat /tmp/missing-a.txt", "description": "Print missing-a.txt"});
+ let pre = |input: &Value| json!({"hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": input, "tool_use_id": "toolu_1"});
+ let failed = |input: &Value, error: &str| {
+ json!({"hook_event_name": "PostToolUseFailure", "tool_name": "Bash", "tool_input": input, "tool_use_id": "toolu_1", "error": error, "is_interrupt": false})
+ };
+ let worked = |input: &Value| json!({"hook_event_name": "PostToolUse", "tool_name": "Bash", "tool_input": input, "tool_response": {"stdout": "x"}});
+ let err = "Exit code 1\ncat: /tmp/missing-a.txt: No such file or directory";
+
+ for _ in 0..3 {
+ assert_eq!(hook(pre(&input)).await, "", "runs");
+ assert_eq!(hook(failed(&input, err)).await, "");
+ }
+ let out: Value = serde_json::from_str(&hook(pre(&input)).await).expect("a deny on the 4th call");
+ assert_eq!(out["hookSpecificOutput"]["permissionDecision"], "deny");
+ assert_eq!(out["hookSpecificOutput"]["permissionDecisionReason"], kwnt::mcp::repeat_guard::stop_text(3, err));
+ // A new description for the same command is the same call
+ let mut again = input.clone();
+ again["description"] = json!("Try once more");
+ assert!(hook(pre(&again)).await.contains("\"deny\""));
+
+ // A different error starts again at 1
+ hook(failed(&input, "Exit code 1\ncat: /tmp/missing-a.txt: Permission denied")).await;
+ assert_eq!(hook(pre(&input)).await, "");
+ hook(failed(&input, "Exit code 1\ncat: /tmp/missing-a.txt: Permission denied")).await;
+ hook(failed(&input, "Exit code 1\ncat: /tmp/missing-a.txt: Permission denied")).await;
+ assert!(hook(pre(&input)).await.contains("\"deny\""), "3 of the new error");
+ // An ok clears it
+ hook(worked(&input)).await;
+ assert_eq!(hook(pre(&input)).await, "");
+
+ // A finished turn (404) and an unreachable kwnt let the call through
+ state.mcp_sessions.lock().await.remove("hook-tok");
+ assert_eq!(hook(pre(&input)).await, "");
+ let gone = kwnt::mcp::cli_hooks::write_curl_config(&tmp.path().join("mcp2"), "http://127.0.0.1:1/api/mcp/permission/x").unwrap();
+ let down = kwnt::mcp::cli_hooks::hook_command(&gone.path);
+ let out = std::process::Command::new("sh").arg("-c").arg(format!("echo '{{}}' | {down}")).output().unwrap();
+ assert_eq!((out.status.code(), out.stdout.len()), (Some(0), 0));
+}
+
fn turn(mcp: Option<McpTurnContext>) -> TurnInput {
TurnInput {
fresh_eyes: false,