Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Relay: every agent's events onto one set, and each agent's own reply

Claudeea861d5d05fd
diff --git a/windows/hook/src/main.rs b/windows/hook/src/main.rs
index 59099c3f..e02f4803 100644
--- a/windows/hook/src/main.rs
+++ b/windows/hook/src/main.rs
@@ -1,26 +1,35 @@
-//! coucou-hook — the relay Claude Code runs on every hook event.
+//! coucou-hook — the relay Claude Code (and every other agent) runs on each hook
+//! event.
//!
-//! Reads the hook JSON on stdin, adds a little terminal context, and hands it to
+//! Reads the hook JSON on stdin, maps the agent's event and field names onto
+//! Claude Code's (normalize.rs), adds a little terminal context, and hands it to
//! Coucou over the named pipe `\\.\pipe\coucou-<sid>` (Windows) or the Unix
//! socket `$XDG_RUNTIME_DIR/coucou.sock` (Linux).
//!
-//! Hard rule (docs/CLAUDE.md): **never block Claude Code.**
-//! * If the pipe does not exist — Coucou is closed — we exit 0 immediately with
-//! nothing on stdout, and the session carries on untouched.
+//! Hard rule (docs/CLAUDE.md): **never block the agent.**
+//! * If the pipe does not exist — Coucou is closed — we exit 0 immediately, with
+//! only the "no opinion" reply the agent expects (reply.rs), and the session
+//! carries on untouched.
//! * Every step runs under a deadline enforced by the main thread, so a pipe that
//! accepts the connection and then stops reading cannot wedge the session
//! either: we abandon the worker and exit.
//! * Only `PermissionRequest` waits for an answer, because approving from the
-//! island is the whole point. No answer means empty stdout, and Claude Code
-//! asks in the terminal exactly as if Coucou were not installed.
+//! island is the whole point. No answer means no decision, and the agent asks
+//! in its terminal exactly as if Coucou were not installed.
//!
-//! Usage: `coucou-hook <EventName>` (the name is also read from the JSON).
+//! Usage: `coucou-hook [--agent <name>] [<EventName>]` (the event name is also
+//! read from the JSON; `--agent` is absent for Claude Code).
use std::io::{Read, Write};
use std::sync::mpsc;
use std::time::Duration;
-/// Budget for getting a pipe connection. Beyond this Claude Code wins, always.
+use serde_json::{Map, Value};
+
+mod normalize;
+mod reply;
+
+/// Budget for getting a pipe connection. Beyond this the agent wins, always.
const CONNECT_TIMEOUT: Duration = Duration::from_millis(300);
/// Whole-run budget for an event nobody waits on: connect and write, no more.
const FIRE_AND_FORGET_BUDGET: Duration = Duration::from_secs(2);
@@ -29,7 +38,7 @@ const DECISION_BUDGET: Duration = Duration::from_secs(110);
/// Fields that are pointless to forward and can be enormous (a whole file read,
/// a full command output). The island never shows them.
-const DROPPED_FIELDS: &[&str] = &["tool_response", "transcript_path"];
+const DROPPED_FIELDS: &[&str] = &["tool_response", "tool_output", "transcript_path"];
/// Longest string forwarded for any single field; the island truncates to far
/// less than this anyway.
const MAX_FIELD_LEN: usize = 2_000;
@@ -44,84 +53,52 @@ mod unix;
#[cfg(target_os = "linux")]
use unix::connect;
-/// Normalize event names across agents (Claude Code, Gemini CLI, Antigravity)
-fn normalize_event(name: &str) -> String {
- match name {
- "BeforeTool" | "BeforeToolSelection" => "PreToolUse".to_string(),
- "AfterTool" | "AfterModel" | "PostInvocation" => "PostToolUse".to_string(),
- "BeforeAgent" | "PreInvocation" => "UserPromptSubmit".to_string(),
- "AfterAgent" => "Stop".to_string(),
- "startup" => "SessionStart".to_string(),
- "exit" => "SessionEnd".to_string(),
- other => other.to_string(),
- }
+/// What the command line says: `--agent <name>` and the event name.
+struct Args {
+ agent: String,
+ event: String,
}
-/// Normalize tool fields from Gemini CLI format (`toolCall: {name, args: {...}}`)
-/// into canonical `tool_name` and `tool_input`.
-fn normalize_tool_fields(map: &mut serde_json::Map<String, serde_json::Value>) {
- if !map.contains_key("tool_name") {
- let (extracted_name, extracted_input) = if let Some(tool) = map.get("toolCall").and_then(|t| t.as_object()) {
- let name = tool.get("name").and_then(|n| n.as_str()).map(|n| n.to_string());
- let input = if let Some(args) = tool.get("args").and_then(|a| a.as_object()) {
- let mut input_map = serde_json::Map::new();
- for (k, v) in args {
- let target_key = match k.as_str() {
- "CommandLine" => "command",
- "FilePath" => "file_path",
- "Path" => "path",
- "Url" => "url",
- "Query" => "query",
- "Pattern" => "pattern",
- other => other,
- };
- input_map.insert(target_key.into(), v.clone());
- }
- Some(input_map)
- } else {
- None
- };
- (name, input)
- } else if let Some(name) = map.get("tool").and_then(|t| t.as_str()) {
- (Some(name.to_string()), None)
- } else {
- (None, None)
- };
-
- if let Some(name) = extracted_name {
- map.insert("tool_name".into(), serde_json::Value::String(name));
- }
- if let Some(input) = extracted_input {
- if !map.contains_key("tool_input") {
- map.insert("tool_input".into(), serde_json::Value::Object(input));
- }
+fn args() -> Args {
+ let mut agent = String::new();
+ let mut event = String::new();
+ let mut it = std::env::args().skip(1);
+ while let Some(arg) = it.next() {
+ if arg == "--agent" {
+ agent = it.next().unwrap_or_default();
+ } else if event.is_empty() {
+ event = arg;
}
}
+ Args { agent, event }
+}
- if !map.contains_key("session_id") {
- let mut found_sid = None;
- for key in &["conversationId", "conversation_id", "sessionId", "GEMINI_SESSION_ID"] {
- if let Some(val) = map.get(*key).and_then(|v| v.as_str()) {
- if !val.is_empty() {
- found_sid = Some(val.to_string());
- break;
- }
- }
- }
- if let Some(sid) = found_sid {
- map.insert("session_id".into(), serde_json::Value::String(sid));
- } else if let Ok(sid) = std::env::var("GEMINI_SESSION_ID") {
- if !sid.is_empty() {
- map.insert("session_id".into(), serde_json::Value::String(sid));
- }
- }
- }
+/// One event, ready to forward.
+struct Event {
+ /// The payload as one line of JSON.
+ line: String,
+ /// The canonical event name.
+ name: String,
+ /// For Claude Code's AskUserQuestion, the question as it was asked.
+ question: Option<Value>,
}
fn main() {
- let Some((payload, event, question, agent)) = read_event() else { std::process::exit(0) };
+ let args = args();
+ let mut raw = Vec::new();
+ let _ = std::io::stdin().read_to_end(&mut raw);
+ let env = |key: &str| std::env::var(key).ok();
+ let cwd = std::env::current_dir().map(|p| p.to_string_lossy().to_string()).unwrap_or_default();
+
+ let Some(event) = prepare(&raw, &args, &env, &cwd) else {
+ // Nothing we could forward. An agent that needs JSON still gets its
+ // "no opinion" — Copilot is fail-closed and would deny without it.
+ let name = normalize::event(&args.event);
+ print(reply::stdout(&args.agent, name, None, None));
+ std::process::exit(0);
+ };
- let waits_for_answer = event == "PermissionRequest";
+ let waits_for_answer = event.name == "PermissionRequest";
let budget = if waits_for_answer { DECISION_BUDGET } else { FIRE_AND_FORGET_BUDGET };
// The worker owns every blocking call. If it overruns the budget we simply
@@ -129,196 +106,62 @@ fn main() {
// (No catch_unwind here — the release profile is panic = "abort", so it would
// be dead code. `talk` is written to have nothing to panic on instead.)
let (tx, rx) = mpsc::channel::<Option<String>>();
+ let line = event.line.clone();
std::thread::spawn(move || {
- let _ = tx.send(talk(&payload, waits_for_answer));
+ let _ = tx.send(talk(&line, waits_for_answer));
});
- if let Ok(Some(decision)) = rx.recv_timeout(budget) {
- if let Some(json) = decision_json(&decision, question.as_ref()) {
- let mut out = std::io::stdout();
- let _ = writeln!(out, "{json}");
- let _ = out.flush();
- }
- } else if !waits_for_answer && (agent == "gemini" || agent == "antigravity") {
- // Gemini CLI and Antigravity expect a JSON response on stdout ({})
- let mut out = std::io::stdout();
- let _ = writeln!(out, "{{}}");
- let _ = out.flush();
- }
- // Nothing printed: Claude Code asks in the terminal, as if we were not here.
+ let decision = rx.recv_timeout(budget).ok().flatten();
+ print(reply::stdout(&args.agent, &event.name, decision.as_deref(), event.question.as_ref()));
std::process::exit(0);
}
-/// The documented PermissionRequest output. Anything we do not recognise prints
-/// nothing at all rather than guessing — silence is the safe answer.
-/// See https://code.claude.com/docs/en/hooks
-///
-/// `question` is the AskUserQuestion input, when that is what is being asked:
-/// the island may then answer it, which Claude Code takes as the same input
-/// with an `answers` map added. Nothing else of the input can be changed from
-/// the island, and no other tool's input can be changed at all.
-fn decision_json(decision: &str, question: Option<&serde_json::Value>) -> Option<String> {
- if decision.trim_start().starts_with('{') {
- let reply = serde_json::from_str::<serde_json::Value>(decision).ok()?;
- let answers = reply.get("answers")?.as_object()?;
- let question = question?;
- if !answers_fit(question, answers) {
- return None;
- }
- let mut input = question.as_object()?.clone();
- input.insert("answers".into(), serde_json::Value::Object(answers.clone()));
- return Some(
- serde_json::json!({
- "hookSpecificOutput": {
- "hookEventName": "PermissionRequest",
- "decision": { "behavior": "allow", "updatedInput": input },
- }
- })
- .to_string(),
- );
+fn print(line: Option<String>) {
+ if let Some(line) = line {
+ let mut out = std::io::stdout();
+ let _ = writeln!(out, "{line}");
+ let _ = out.flush();
}
- let behavior = match decision.trim() {
- // "always" still answers a plain allow; remembering it is the island's
- // business, not Claude Code's.
- "allow" | "always" => r#"{"behavior":"allow"}"#.to_string(),
- "deny" => r#"{"behavior":"deny","message":"Denied from Coucou"}"#.to_string(),
- _ => return None,
- };
- Some(format!(
- r#"{{"hookSpecificOutput":{{"hookEventName":"PermissionRequest","decision":{behavior}}}}}"#
- ))
}
-/// True when `answers` answers exactly the questions Claude Code asked: one entry
-/// per question, keyed by its text; a single-select answer is one of its option
-/// labels (a string), a multi-select answer a non-empty list of distinct labels
-/// (Claude Code 2.1.136+ takes the list, as the Mac sends it). Same rule as
-/// `QuestionPayload.accepts` on macOS.
-fn answers_fit(question: &serde_json::Value, answers: &serde_json::Map<String, serde_json::Value>) -> bool {
- let Some(items) = question.get("questions").and_then(|q| q.as_array()) else { return false };
- if items.is_empty() || items.len() != answers.len() {
- return false;
- }
- items.iter().all(|item| {
- let Some(text) = item.get("question").and_then(|q| q.as_str()) else { return false };
- let labels: Vec<&str> = item
- .get("options")
- .and_then(|o| o.as_array())
- .map(|opts| opts.iter().filter_map(|o| o.get("label").and_then(|l| l.as_str())).collect())
- .unwrap_or_default();
- let multi = item.get("multiSelect").and_then(|m| m.as_bool()).unwrap_or(false);
- match answers.get(text) {
- Some(serde_json::Value::String(pick)) if !multi => labels.contains(&pick.as_str()),
- Some(serde_json::Value::Array(picks)) if multi => {
- let picks: Vec<&str> = picks.iter().filter_map(|p| p.as_str()).collect();
- let mut seen = picks.clone();
- seen.sort_unstable();
- seen.dedup();
- !picks.is_empty() && seen.len() == picks.len() && picks.iter().all(|p| labels.contains(p))
- }
- _ => false,
- }
- })
-}
-
-/// Reads stdin and returns the payload to forward, the event name, — for an
-/// AskUserQuestion permission request — the question as Claude Code sent it,
-/// and the agent the hook was installed for.
-fn read_event() -> Option<(String, String, Option<serde_json::Value>, String)> {
- let mut raw = Vec::new();
- if std::io::stdin().read_to_end(&mut raw).is_err() || raw.is_empty() {
- return None;
- }
+/// The payload to forward, from the raw stdin bytes. `env` reads an environment
+/// variable and `cwd` is the working directory, so tests stay pure.
+fn prepare(raw: &[u8], args: &Args, env: &dyn Fn(&str) -> Option<String>, cwd: &str) -> Option<Event> {
// Some shells hand us a UTF-8 BOM; serde_json would choke on it.
- if raw.starts_with(&[0xEF, 0xBB, 0xBF]) {
- raw.drain(..3);
- }
-
- let mut payload = serde_json::from_slice::<serde_json::Value>(&raw).ok()?;
+ let raw = raw.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(raw);
+ let mut payload = serde_json::from_slice::<Value>(raw).ok()?;
let map = payload.as_object_mut()?;
- // Parse argv: "coucou-hook.exe [--agent <name>] [<EventName>]"
- // --agent tags the payload with coucou_agent so the app routes to the right pill.
- // Absent or invalid names are validated and discarded by the app, not here.
- let mut agent = String::new();
- let mut arg_event = String::new();
- {
- let mut it = std::env::args().skip(1);
- while let Some(arg) = it.next() {
- if arg == "--agent" {
- agent = it.next().unwrap_or_default();
- } else if arg_event.is_empty() {
- arg_event = arg;
- }
- }
- }
- // Which agent this hook was installed for. Absent means Claude Code,
- // so existing hook commands keep working unchanged.
- if !agent.is_empty() {
- map.insert("coucou_agent".into(), serde_json::Value::String(agent.clone()));
+ // Which agent this hook was installed for, so the app routes it to the right
+ // pill. Absent means Claude Code, so existing hook commands keep working
+ // unchanged; invalid names are discarded by the app, not here.
+ if !args.agent.is_empty() {
+ map.insert("coucou_agent".into(), Value::String(args.agent.clone()));
}
- normalize_tool_fields(map);
-
let raw_event = map
.get("hook_event_name")
- .and_then(|v| v.as_str())
- .map(str::to_string)
+ .and_then(Value::as_str)
.filter(|s| !s.is_empty())
- .unwrap_or(arg_event);
- let event = normalize_event(&raw_event);
- map.insert("hook_event_name".into(), serde_json::Value::String(event.clone()));
+ .map(str::to_string)
+ .unwrap_or_else(|| args.event.clone());
+ normalize::fields(map, env);
+ let name = normalize::refine(normalize::event(&raw_event), map);
+ map.insert("hook_event_name".into(), Value::String(name.clone()));
for field in DROPPED_FIELDS {
map.remove(*field);
}
- let cwd_missing = map
- .get("cwd")
- .and_then(|v| v.as_str())
- .map(str::is_empty)
- .unwrap_or(true);
- if cwd_missing {
- // Also check workspacePaths or workspace_roots (Gemini CLI)
- let mut found_path = None;
- for key in &["workspacePaths", "workspace_roots"] {
- if let Some(arr) = map.get(*key).and_then(|v| v.as_array()) {
- if let Some(first) = arr.first().and_then(|v| v.as_str()) {
- if !first.is_empty() {
- found_path = Some(first.to_string());
- break;
- }
- }
- }
- }
- if let Some(p) = found_path {
- map.insert("cwd".into(), serde_json::Value::String(p));
- } else if let Ok(cwd) = std::env::current_dir() {
- map.insert(
- "cwd".into(),
- serde_json::Value::String(cwd.to_string_lossy().to_string()),
- );
- }
+ if map.get("cwd").and_then(Value::as_str).map(str::is_empty).unwrap_or(true) && !cwd.is_empty() {
+ map.insert("cwd".into(), Value::String(cwd.to_string()));
}
- // Which terminal the session runs in. Unlike macOS, Coucou here accepts
- // events from every terminal, so this is context only — never a filter.
- for (key, var) in [
- ("term_program", "TERM_PROGRAM"),
- ("wt_session", "WT_SESSION"),
- ("term_session_id", "TERM_SESSION_ID"),
- ("vscode_pid", "VSCODE_PID"),
- ("session_pid", "CLAUDE_CODE_SSE_PORT"),
- ] {
- if !map.contains_key(key) {
- let value = std::env::var(var).unwrap_or_default();
- map.insert(key.into(), serde_json::Value::String(value));
- }
- }
+ add_terminal_context(map, env);
// Kept whole: what goes back to Claude Code must be its own input, not the
// shortened copy the island is shown.
- let question = (map.get("tool_name").and_then(|v| v.as_str()) == Some("AskUserQuestion"))
+ let question = (map.get("tool_name").and_then(Value::as_str) == Some("AskUserQuestion"))
.then(|| map.get("tool_input").cloned())
.flatten();
@@ -326,13 +169,29 @@ fn read_event() -> Option<(String, String, Option<serde_json::Value>, String)> {
let mut line = payload.to_string();
line.push('\n');
- Some((line, event, question, agent))
+ Some(Event { line, name, question })
+}
+
+/// Which terminal the session runs in. Unlike macOS, Coucou here accepts events
+/// from every terminal, so this is context only — never a filter.
+fn add_terminal_context(map: &mut Map<String, Value>, env: &dyn Fn(&str) -> Option<String>) {
+ for (key, var) in [
+ ("term_program", "TERM_PROGRAM"),
+ ("wt_session", "WT_SESSION"),
+ ("term_session_id", "TERM_SESSION_ID"),
+ ("vscode_pid", "VSCODE_PID"),
+ ("session_pid", "CLAUDE_CODE_SSE_PORT"),
+ ] {
+ if !map.contains_key(key) {
+ map.insert(key.into(), Value::String(env(var).unwrap_or_default()));
+ }
+ }
}
/// Caps every string in the payload. A single Write can carry a whole file.
-fn truncate_strings(value: &mut serde_json::Value) {
+fn truncate_strings(value: &mut Value) {
match value {
- serde_json::Value::String(s) => {
+ Value::String(s) => {
if s.len() > MAX_FIELD_LEN {
// Cut on a char boundary; a lone byte index can split UTF-8.
let mut end = MAX_FIELD_LEN;
@@ -343,8 +202,8 @@ fn truncate_strings(value: &mut serde_json::Value) {
s.push('…');
}
}
- serde_json::Value::Array(items) => items.iter_mut().for_each(truncate_strings),
- serde_json::Value::Object(map) => map.values_mut().for_each(truncate_strings),
+ Value::Array(items) => items.iter_mut().for_each(truncate_strings),
+ Value::Object(map) => map.values_mut().for_each(truncate_strings),
_ => {}
}
}
@@ -384,70 +243,11 @@ fn talk(payload: &str, waits_for_answer: bool) -> Option<String> {
mod tests {
use super::*;
- #[test]
- fn decision_json_matches_the_documented_shape() {
- assert_eq!(
- decision_json("allow", None).unwrap(),
- r#"{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}"#
- );
- assert_eq!(
- decision_json("deny", None).unwrap(),
- r#"{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"deny","message":"Denied from Coucou"}}}"#
- );
- // "always" is an island concept; Claude Code just gets an allow.
- assert!(decision_json("always", None).unwrap().contains(r#""behavior":"allow""#));
- }
-
- #[test]
- fn anything_unrecognised_prints_nothing() {
- assert!(decision_json("", None).is_none());
- assert!(decision_json("maybe", None).is_none());
- // The shape the app used to send must not be mistaken for a decision.
- assert!(decision_json(r#"{"permissionDecision":"allow"}"#, None).is_none());
- }
-
- #[test]
- fn an_answered_question_goes_back_as_the_same_input_plus_answers() {
- let question = serde_json::json!({
- "questions": [{ "question": "Which one?", "options": [{ "label": "A" }, { "label": "B" }] }]
- });
- let out = decision_json(r#"{"answers":{"Which one?":"B"}}"#, Some(&question)).unwrap();
- let v: serde_json::Value = serde_json::from_str(&out).unwrap();
- let decision = &v["hookSpecificOutput"]["decision"];
- assert_eq!(decision["behavior"], "allow");
- assert_eq!(decision["updatedInput"]["questions"], question["questions"]);
- assert_eq!(decision["updatedInput"]["answers"]["Which one?"], "B");
- }
-
- #[test]
- fn answers_are_only_accepted_for_a_question() {
- // Any other tool: the island cannot rewrite its input.
- assert!(decision_json(r#"{"answers":{"q":"a"}}"#, None).is_none());
- let question = serde_json::json!({ "questions": [] });
- assert!(decision_json(r#"{"answers":{}}"#, Some(&question)).is_none());
- assert!(decision_json(r#"{"answers":{"q":1}}"#, Some(&question)).is_none());
- assert!(decision_json(r#"{"command":"rm -rf /"}"#, Some(&question)).is_none());
- }
-
- #[test]
- fn answers_must_match_the_questions_asked() {
- let q = serde_json::json!({ "questions": [
- { "question": "Which one?", "options": [{ "label": "A" }, { "label": "B" }] },
- { "question": "Extras?", "multiSelect": true,
- "options": [{ "label": "Tests" }, { "label": "Docs" }, { "label": "Lint" }] }
- ]});
- let ok = |a: &str| decision_json(a, Some(&q)).is_some();
- assert!(ok(r#"{"answers":{"Which one?":"A","Extras?":["Tests","Docs"]}}"#));
- // Not one of the labels, or an answer to a question nobody asked.
- assert!(!ok(r#"{"answers":{"Which one?":"C","Extras?":["Tests"]}}"#));
- assert!(!ok(r#"{"answers":{"Which one?":"A","Extras?":["Tests"],"Other?":"x"}}"#));
- // A question left out.
- assert!(!ok(r#"{"answers":{"Which one?":"A"}}"#));
- // Shapes: single-select is one string, multi-select a non-empty list.
- assert!(!ok(r#"{"answers":{"Which one?":["A"],"Extras?":["Tests"]}}"#));
- assert!(!ok(r#"{"answers":{"Which one?":"A","Extras?":"Tests"}}"#));
- assert!(!ok(r#"{"answers":{"Which one?":"A","Extras?":[]}}"#));
- assert!(!ok(r#"{"answers":{"Which one?":"A","Extras?":["Tests","Tests"]}}"#));
+ fn run(raw: &str, agent: &str, event: &str) -> (Value, Event) {
+ let args = Args { agent: agent.into(), event: event.into() };
+ let ev = prepare(raw.as_bytes(), &args, &|_| None, "/home/me/here").expect("forwarded");
+ let v = serde_json::from_str(ev.line.trim_end()).unwrap();
+ (v, ev)
}
#[test]
@@ -460,33 +260,54 @@ mod tests {
}
#[test]
- fn normalize_event_maps_gemini_events_to_canonical() {
- assert_eq!(normalize_event("BeforeTool"), "PreToolUse");
- assert_eq!(normalize_event("AfterTool"), "PostToolUse");
- assert_eq!(normalize_event("BeforeAgent"), "UserPromptSubmit");
- assert_eq!(normalize_event("AfterAgent"), "Stop");
- assert_eq!(normalize_event("startup"), "SessionStart");
- assert_eq!(normalize_event("exit"), "SessionEnd");
- assert_eq!(normalize_event("PreToolUse"), "PreToolUse");
+ fn claude_code_payloads_are_forwarded_as_they_are() {
+ let (v, ev) = run(r#"{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"/p"}"#, "", "PreToolUse");
+ assert_eq!(ev.name, "PreToolUse");
+ assert!(v.get("coucou_agent").is_none());
+ assert_eq!(v["cwd"], "/p");
+ assert_eq!(v["tool_name"], "Bash");
}
#[test]
- fn normalize_tool_fields_extracts_gemini_tool_call() {
- let mut map = serde_json::Map::new();
- map.insert(
- "toolCall".into(),
- serde_json::json!({
- "name": "Bash",
- "args": {
- "CommandLine": "ls -la"
- }
- }),
- );
- map.insert("conversationId".into(), serde_json::json!("gemini-conv-123"));
- normalize_tool_fields(&mut map);
-
- assert_eq!(map.get("tool_name").unwrap(), "Bash");
- assert_eq!(map.get("tool_input").unwrap()["command"], "ls -la");
- assert_eq!(map.get("session_id").unwrap(), "gemini-conv-123");
+ fn an_agents_event_is_tagged_and_renamed() {
+ // Gemini CLI: its own name in the payload, ours on the command line.
+ let (v, ev) = run(r#"{"hook_event_name":"BeforeTool","toolCall":{"name":"shell","args":{"CommandLine":"ls"}}}"#, "gemini", "PreToolUse");
+ assert_eq!(ev.name, "PreToolUse");
+ assert_eq!(v["hook_event_name"], "PreToolUse");
+ assert_eq!(v["coucou_agent"], "gemini");
+ assert_eq!(v["tool_input"]["command"], "ls");
+ assert_eq!(v["cwd"], "/home/me/here");
+
+ // Copilot CLI sends no event name: the command line's camelCase one is used.
+ let (_, ev) = run(r#"{"toolName":"bash"}"#, "copilot", "permissionRequest");
+ assert_eq!(ev.name, "PermissionRequest");
+
+ // Cursor: a stop that failed, and its tool output left behind.
+ let (v, ev) = run(r#"{"hook_event_name":"stop","status":"error","tool_output":"huge"}"#, "cursor", "");
+ assert_eq!(ev.name, "StopFailure");
+ assert!(v.get("tool_output").is_none());
+ }
+
+ #[test]
+ fn a_question_is_kept_whole_and_only_for_ask_user_question() {
+ let long = "x".repeat(3000);
+ let raw = format!(r#"{{"hook_event_name":"PermissionRequest","tool_name":"AskUserQuestion","tool_input":{{"questions":[{{"question":"{long}"}}]}}}}"#);
+ let (v, ev) = run(&raw, "", "");
+ assert_eq!(ev.question.unwrap()["questions"][0]["question"].as_str().unwrap().len(), 3000);
+ assert!(v["tool_input"]["questions"][0]["question"].as_str().unwrap().ends_with('…'));
+ let (_, ev) = run(r#"{"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":"ls"}}"#, "", "");
+ assert!(ev.question.is_none());
+ }
+
+ #[test]
+ fn what_cannot_be_read_is_not_forwarded() {
+ let args = Args { agent: "copilot".into(), event: "preToolUse".into() };
+ for raw in ["", "not json", "[1,2]"] {
+ assert!(prepare(raw.as_bytes(), &args, &|_| None, "/").is_none());
+ }
+ // A BOM is not a reason to drop the event.
+ let mut bom = vec![0xEF, 0xBB, 0xBF];
+ bom.extend_from_slice(br#"{"hook_event_name":"Stop"}"#);
+ assert!(prepare(&bom, &args, &|_| None, "/").is_some());
}
}
diff --git a/windows/hook/src/normalize.rs b/windows/hook/src/normalize.rs
new file mode 100644
index 00000000..7d0c3052
--- /dev/null
+++ b/windows/hook/src/normalize.rs
@@ -0,0 +1,267 @@
+//! Every agent's hook payload, mapped onto the events and fields the island
+//! knows (Claude Code's). Same table as `normalize_event` /
+//! `normalize_tool_fields` in the Mac relay (HookServer.swift), plus Cursor's
+//! events.
+
+use serde_json::{Map, Value};
+
+/// The canonical name of an agent's event. Unknown names pass through.
+pub fn event(name: &str) -> &str {
+ match name {
+ // Gemini CLI
+ "BeforeTool" | "BeforeToolSelection" => "PreToolUse",
+ "AfterTool" | "AfterModel" => "PostToolUse",
+ "BeforeAgent" => "UserPromptSubmit",
+ "AfterAgent" => "Stop",
+ "startup" => "SessionStart",
+ "exit" => "SessionEnd",
+ // Antigravity
+ "PreInvocation" => "UserPromptSubmit",
+ "PostInvocation" => "PostToolUse",
+ // snake_case relays
+ "pre_tool_use" => "PreToolUse",
+ "post_tool_use" => "PostToolUse",
+ "user_prompt_submit" => "UserPromptSubmit",
+ "session_start" => "SessionStart",
+ "session_end" => "SessionEnd",
+ "stop" => "Stop",
+ // Copilot CLI (camelCase) — Cursor shares most of these
+ "sessionStart" => "SessionStart",
+ "userPromptSubmitted" => "UserPromptSubmit",
+ "agentStop" => "Stop",
+ "notification" => "Notification",
+ "preToolUse" => "PreToolUse",
+ "postToolUse" => "PostToolUse",
+ "permissionRequest" => "PermissionRequest",
+ "sessionEnd" => "SessionEnd",
+ // Cursor
+ "beforeSubmitPrompt" => "UserPromptSubmit",
+ "postToolUseFailure" => "PostToolUseFailure",
+ "subagentStart" => "SubagentStart",
+ "subagentStop" => "SubagentStop",
+ other => other,
+ }
+}
+
+/// Keys of Antigravity's `toolCall.args` the island reads under another name.
+const ARG_ALIASES: &[(&str, &str)] = &[
+ ("CommandLine", "command"),
+ ("FilePath", "file_path"),
+ ("Path", "path"),
+ ("Url", "url"),
+ ("Query", "query"),
+ ("Pattern", "pattern"),
+];
+
+fn non_empty_str<'a>(map: &'a Map<String, Value>, key: &str) -> Option<&'a str> {
+ map.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
+}
+
+/// Fills `tool_name`, `tool_input`, `session_id` and `cwd` from wherever the
+/// agent put them. A field the payload already has is never overwritten.
+/// `env` reads an environment variable (a parameter so tests stay pure).
+pub fn fields(map: &mut Map<String, Value>, env: &dyn Fn(&str) -> Option<String>) {
+ let tool_call = map.get("toolCall").and_then(Value::as_object).cloned();
+
+ if !map.contains_key("tool_name") {
+ // Copilot: toolName. Gemini CLI / Antigravity: toolCall.name. Others: tool.
+ let name = non_empty_str(map, "toolName")
+ .or_else(|| tool_call.as_ref().and_then(|t| non_empty_str(t, "name")))
+ .or_else(|| non_empty_str(map, "tool"))
+ .map(str::to_string);
+ if let Some(name) = name {
+ map.insert("tool_name".into(), Value::String(name));
+ }
+ }
+
+ if !map.contains_key("tool_input") {
+ // Copilot sends toolArgs as an object, or as the JSON text of one.
+ let args = match map.get("toolArgs") {
+ Some(Value::Object(o)) => Some(o.clone()),
+ Some(Value::String(s)) => serde_json::from_str::<Value>(s)
+ .ok()
+ .and_then(|v| v.as_object().cloned()),
+ _ => None,
+ };
+ let input = args.or_else(|| {
+ let mut flat = tool_call.as_ref()?.get("args")?.as_object()?.clone();
+ for (from, to) in ARG_ALIASES {
+ if let Some(v) = flat.get(*from).cloned() {
+ flat.insert((*to).to_string(), v);
+ }
+ }
+ Some(flat)
+ });
+ if let Some(input) = input {
+ map.insert("tool_input".into(), Value::Object(input));
+ }
+ }
+
+ if non_empty_str(map, "session_id").is_none() {
+ let sid = ["conversationId", "conversation_id", "sessionId", "GEMINI_SESSION_ID"]
+ .iter()
+ .find_map(|k| non_empty_str(map, k))
+ .map(str::to_string)
+ .or_else(|| env("GEMINI_SESSION_ID").filter(|s| !s.is_empty()));
+ if let Some(sid) = sid {
+ map.insert("session_id".into(), Value::String(sid));
+ }
+ }
+
+ if non_empty_str(map, "cwd").is_none() {
+ // Copilot: workdir. Gemini CLI / Antigravity: workspacePaths. Cursor: workspace_roots.
+ let cwd = non_empty_str(map, "workdir").map(str::to_string).or_else(|| {
+ ["workspacePaths", "workspace_roots"].iter().find_map(|k| {
+ map.get(*k)?.as_array()?.first()?.as_str().filter(|s| !s.is_empty()).map(str::to_string)
+ })
+ });
+ if let Some(cwd) = cwd {
+ map.insert("cwd".into(), Value::String(cwd));
+ }
+ }
+}
+
+/// The event once the payload is known: a stop that reports an error (Cursor's
+/// `status: "error"`) is a StopFailure.
+pub fn refine(event: &str, map: &Map<String, Value>) -> String {
+ if event == "Stop" && map.get("status").and_then(Value::as_str) == Some("error") {
+ return "StopFailure".into();
+ }
+ event.to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn obj(v: Value) -> Map<String, Value> {
+ v.as_object().unwrap().clone()
+ }
+
+ fn no_env(_: &str) -> Option<String> {
+ None
+ }
+
+ #[test]
+ fn every_agents_event_names_map_onto_claude_codes() {
+ for (raw, canonical) in [
+ ("BeforeTool", "PreToolUse"),
+ ("BeforeToolSelection", "PreToolUse"),
+ ("AfterTool", "PostToolUse"),
+ ("AfterModel", "PostToolUse"),
+ ("BeforeAgent", "UserPromptSubmit"),
+ ("AfterAgent", "Stop"),
+ ("startup", "SessionStart"),
+ ("exit", "SessionEnd"),
+ ("PreInvocation", "UserPromptSubmit"),
+ ("PostInvocation", "PostToolUse"),
+ ("pre_tool_use", "PreToolUse"),
+ ("post_tool_use", "PostToolUse"),
+ ("user_prompt_submit", "UserPromptSubmit"),
+ ("session_start", "SessionStart"),
+ ("session_end", "SessionEnd"),
+ ("stop", "Stop"),
+ ("sessionStart", "SessionStart"),
+ ("userPromptSubmitted", "UserPromptSubmit"),
+ ("agentStop", "Stop"),
+ ("notification", "Notification"),
+ ("preToolUse", "PreToolUse"),
+ ("postToolUse", "PostToolUse"),
+ ("permissionRequest", "PermissionRequest"),
+ ("sessionEnd", "SessionEnd"),
+ ("beforeSubmitPrompt", "UserPromptSubmit"),
+ ("postToolUseFailure", "PostToolUseFailure"),
+ ("subagentStart", "SubagentStart"),
+ ("subagentStop", "SubagentStop"),
+ ] {
+ assert_eq!(event(raw), canonical, "{raw}");
+ }
+ // Claude Code's own names, and anything unknown, pass through.
+ for same in ["PreToolUse", "PermissionRequest", "Stop", "Interrupt", "somethingNew"] {
+ assert_eq!(event(same), same);
+ }
+ }
+
+ #[test]
+ fn antigravity_and_gemini_tool_calls_become_tool_name_and_input() {
+ let mut m = obj(json!({
+ "conversationId": "conv-1",
+ "workspacePaths": ["C:\\Projects\\test"],
+ "toolCall": { "name": "run_command", "args": { "CommandLine": "cargo check" } }
+ }));
+ fields(&mut m, &no_env);
+ assert_eq!(m["tool_name"], "run_command");
+ assert_eq!(m["tool_input"]["command"], "cargo check");
+ assert_eq!(m["tool_input"]["CommandLine"], "cargo check");
+ assert_eq!(m["session_id"], "conv-1");
+ assert_eq!(m["cwd"], "C:\\Projects\\test");
+ }
+
+ #[test]
+ fn copilot_tool_name_args_and_workdir_are_read() {
+ let mut m = obj(json!({
+ "toolName": "bash",
+ "toolArgs": "{\"command\":\"npm test\"}",
+ "sessionId": "s-9",
+ "workdir": "/home/me/app"
+ }));
+ fields(&mut m, &no_env);
+ assert_eq!(m["tool_name"], "bash");
+ assert_eq!(m["tool_input"]["command"], "npm test");
+ assert_eq!(m["session_id"], "s-9");
+ assert_eq!(m["cwd"], "/home/me/app");
+
+ let mut m = obj(json!({ "toolName": "edit", "toolArgs": { "path": "a.rs" } }));
+ fields(&mut m, &no_env);
+ assert_eq!(m["tool_input"]["path"], "a.rs");
+ }
+
+ #[test]
+ fn cursor_conversation_and_workspace_become_session_and_cwd() {
+ let mut m = obj(json!({ "conversation_id": "c-1", "workspace_roots": ["/w/proj"] }));
+ fields(&mut m, &no_env);
+ assert_eq!(m["session_id"], "c-1");
+ assert_eq!(m["cwd"], "/w/proj");
+ }
+
+ #[test]
+ fn what_the_payload_already_says_is_never_overwritten() {
+ let mut m = obj(json!({
+ "tool_name": "Bash", "tool_input": { "command": "ls" },
+ "session_id": "keep", "cwd": "/keep",
+ "toolName": "other", "toolArgs": { "command": "rm" },
+ "conversationId": "no", "workdir": "/no"
+ }));
+ fields(&mut m, &|_| Some("env".into()));
+ assert_eq!(m["tool_name"], "Bash");
+ assert_eq!(m["tool_input"]["command"], "ls");
+ assert_eq!(m["session_id"], "keep");
+ assert_eq!(m["cwd"], "/keep");
+ }
+
+ #[test]
+ fn gemini_session_comes_from_the_environment_last() {
+ let mut m = obj(json!({}));
+ fields(&mut m, &|k| (k == "GEMINI_SESSION_ID").then(|| "g-7".to_string()));
+ assert_eq!(m["session_id"], "g-7");
+ }
+
+ #[test]
+ fn odd_shapes_are_ignored_not_trusted() {
+ let mut m = obj(json!({ "toolCall": "nope", "toolArgs": "not json", "workspacePaths": "x", "tool": 3 }));
+ fields(&mut m, &no_env);
+ assert!(!m.contains_key("tool_name"));
+ assert!(!m.contains_key("tool_input"));
+ assert!(!m.contains_key("cwd"));
+ }
+
+ #[test]
+ fn a_stop_with_an_error_status_is_a_failure() {
+ assert_eq!(refine("Stop", &obj(json!({ "status": "error" }))), "StopFailure");
+ for status in ["completed", "aborted"] {
+ assert_eq!(refine("Stop", &obj(json!({ "status": status }))), "Stop");
+ }
+ assert_eq!(refine("PreToolUse", &obj(json!({ "status": "error" }))), "PreToolUse");
+ }
+}
diff --git a/windows/hook/src/reply.rs b/windows/hook/src/reply.rs
new file mode 100644
index 00000000..9da86a71
--- /dev/null
+++ b/windows/hook/src/reply.rs
@@ -0,0 +1,269 @@
+//! What the relay prints back to the agent — the only place that knows each
+//! agent's stdout contract. Same replies as the Mac relay (HookServer.swift).
+//!
+//! The one rule that matters: **nothing that allows anything is ever printed
+//! without a decision a human clicked.** With no decision the reply is silence,
+//! an empty `{}`, or Copilot's explicit "ask", and every agent then asks in its
+//! own terminal exactly as if Coucou were not installed.
+
+use serde_json::{json, Map, Value};
+
+/// The agents whose permission requests the island can answer: Claude Code
+/// (no `--agent`), Codex, Copilot CLI and Muse Code. Any decision for another
+/// agent is ignored here too, whatever the app sent.
+pub fn takes_decisions(agent: &str) -> bool {
+ matches!(agent, "" | "codex" | "copilot" | "muse")
+}
+
+/// Agents that read a JSON object on stdout after every hook and get `{}` —
+/// "no opinion" — when there is nothing to say.
+fn wants_json(agent: &str) -> bool {
+ matches!(agent, "gemini" | "antigravity" | "copilot" | "muse")
+}
+
+/// The line to print for `event` from `agent`, given the island's `decision`
+/// (`None`: nobody clicked) and, for Claude Code's AskUserQuestion, the
+/// question as it was asked.
+pub fn stdout(agent: &str, event: &str, decision: Option<&str>, question: Option<&Value>) -> Option<String> {
+ if event != "PermissionRequest" {
+ return wants_json(agent).then(|| "{}".to_string());
+ }
+ let decision = decision.filter(|_| takes_decisions(agent));
+ match agent {
+ // Copilot CLI and Muse Code read a bare permissionDecision. Copilot is
+ // fail-closed: it must always get valid JSON, so silence is an "ask".
+ "copilot" | "muse" => {
+ let word = match decision.map(str::trim) {
+ Some("allow" | "always") => Some("allow"),
+ Some("deny") => Some("deny"),
+ _ => None,
+ };
+ match word {
+ Some(word) => Some(json!({ "permissionDecision": word }).to_string()),
+ None if agent == "copilot" => Some(json!({ "permissionDecision": "ask" }).to_string()),
+ None => None,
+ }
+ }
+ // Claude Code and Codex share the documented hookSpecificOutput. Only
+ // Claude Code asks questions.
+ "" => decision.and_then(|d| decision_json(d, question)),
+ _ => decision.and_then(|d| decision_json(d, None)),
+ }
+}
+
+/// The documented PermissionRequest output. Anything we do not recognise prints
+/// nothing at all rather than guessing — silence is the safe answer.
+/// See https://code.claude.com/docs/en/hooks
+///
+/// `question` is the AskUserQuestion input, when that is what is being asked:
+/// the island may then answer it, which Claude Code takes as the same input
+/// with an `answers` map added. Nothing else of the input can be changed from
+/// the island, and no other tool's input can be changed at all.
+pub fn decision_json(decision: &str, question: Option<&Value>) -> Option<String> {
+ if decision.trim_start().starts_with('{') {
+ let reply = serde_json::from_str::<Value>(decision).ok()?;
+ let answers = reply.get("answers")?.as_object()?;
+ let question = question?;
+ if !answers_fit(question, answers) {
+ return None;
+ }
+ let mut input = question.as_object()?.clone();
+ input.insert("answers".into(), Value::Object(answers.clone()));
+ return Some(
+ json!({
+ "hookSpecificOutput": {
+ "hookEventName": "PermissionRequest",
+ "decision": { "behavior": "allow", "updatedInput": input },
+ }
+ })
+ .to_string(),
+ );
+ }
+ let behavior = match decision.trim() {
+ // "always" still answers a plain allow; remembering it is the island's
+ // business, not the agent's.
+ "allow" | "always" => r#"{"behavior":"allow"}"#.to_string(),
+ "deny" => r#"{"behavior":"deny","message":"Denied from Coucou"}"#.to_string(),
+ _ => return None,
+ };
+ Some(format!(
+ r#"{{"hookSpecificOutput":{{"hookEventName":"PermissionRequest","decision":{behavior}}}}}"#
+ ))
+}
+
+/// True when `answers` answers exactly the questions Claude Code asked: one entry
+/// per question, keyed by its text; a single-select answer is one of its option
+/// labels (a string), a multi-select answer a non-empty list of distinct labels
+/// (Claude Code 2.1.136+ takes the list, as the Mac sends it). Same rule as
+/// `QuestionPayload.accepts` on macOS.
+fn answers_fit(question: &Value, answers: &Map<String, Value>) -> bool {
+ let Some(items) = question.get("questions").and_then(|q| q.as_array()) else { return false };
+ if items.is_empty() || items.len() != answers.len() {
+ return false;
+ }
+ items.iter().all(|item| {
+ let Some(text) = item.get("question").and_then(|q| q.as_str()) else { return false };
+ let labels: Vec<&str> = item
+ .get("options")
+ .and_then(|o| o.as_array())
+ .map(|opts| opts.iter().filter_map(|o| o.get("label").and_then(|l| l.as_str())).collect())
+ .unwrap_or_default();
+ let multi = item.get("multiSelect").and_then(|m| m.as_bool()).unwrap_or(false);
+ match answers.get(text) {
+ Some(Value::String(pick)) if !multi => labels.contains(&pick.as_str()),
+ Some(Value::Array(picks)) if multi => {
+ let picks: Vec<&str> = picks.iter().filter_map(|p| p.as_str()).collect();
+ let mut seen = picks.clone();
+ seen.sort_unstable();
+ seen.dedup();
+ !picks.is_empty() && seen.len() == picks.len() && picks.iter().all(|p| labels.contains(p))
+ }
+ _ => false,
+ }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const AGENTS: &[&str] = &[
+ "", "gemini", "antigravity", "cursor", "codex", "copilot", "muse", "opencode", "amp",
+ "hermes", "claude-desktop", "my-tool",
+ ];
+ const EVENTS: &[&str] = &[
+ "SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure",
+ "PermissionRequest", "Notification", "Stop", "StopFailure", "SessionEnd", "Interrupt",
+ "SubagentStart", "SubagentStop", "",
+ ];
+
+ /// Whatever a reply says, does it let anything through?
+ fn allows(out: &str) -> bool {
+ let v: Value = serde_json::from_str(out).expect("every reply is JSON");
+ let text = v.to_string();
+ text.contains("allow") || v.get("decision").is_some() || v.get("permission").is_some() || v.get("continue").is_some()
+ }
+
+ #[test]
+ fn nothing_is_ever_allowed_without_a_decision() {
+ for agent in AGENTS {
+ for event in EVENTS {
+ if let Some(out) = stdout(agent, event, None, None) {
+ assert!(!allows(&out), "{agent:?} {event} printed {out} with nobody clicking");
+ }
+ // A decline, a timeout or garbage from the app is no decision either.
+ for not_a_decision in ["", "ask", "maybe", "{\"permissionDecision\":\"allow\"}"] {
+ if let Some(out) = stdout(agent, event, Some(not_a_decision), None) {
+ assert!(!allows(&out), "{agent:?} {event} {not_a_decision:?} printed {out}");
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn a_decision_only_counts_on_a_permission_request_from_an_agent_that_takes_one() {
+ for agent in AGENTS {
+ for event in EVENTS.iter().filter(|e| **e != "PermissionRequest") {
+ if let Some(out) = stdout(agent, event, Some("allow"), None) {
+ assert!(!allows(&out), "{agent:?} {event}: {out}");
+ }
+ }
+ let out = stdout(agent, "PermissionRequest", Some("allow"), None);
+ assert_eq!(out.as_deref().is_some_and(allows), takes_decisions(agent), "{agent:?}: {out:?}");
+ }
+ }
+
+ #[test]
+ fn each_agent_gets_its_own_reply_shape() {
+ let allow = r#"{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}"#;
+ let deny = r#"{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"deny","message":"Denied from Coucou"}}}"#;
+ for agent in ["", "codex"] {
+ assert_eq!(stdout(agent, "PermissionRequest", Some("allow"), None).unwrap(), allow);
+ assert_eq!(stdout(agent, "PermissionRequest", Some("always"), None).unwrap(), allow);
+ assert_eq!(stdout(agent, "PermissionRequest", Some("deny"), None).unwrap(), deny);
+ assert_eq!(stdout(agent, "PermissionRequest", None, None), None);
+ assert_eq!(stdout(agent, "PreToolUse", None, None), None);
+ }
+ for agent in ["copilot", "muse"] {
+ assert_eq!(stdout(agent, "PermissionRequest", Some("allow"), None).unwrap(), r#"{"permissionDecision":"allow"}"#);
+ assert_eq!(stdout(agent, "PermissionRequest", Some("deny"), None).unwrap(), r#"{"permissionDecision":"deny"}"#);
+ assert_eq!(stdout(agent, "PreToolUse", None, None).unwrap(), "{}");
+ }
+ // Copilot is fail-closed: no decision is an explicit "ask", never silence.
+ assert_eq!(stdout("copilot", "PermissionRequest", None, None).unwrap(), r#"{"permissionDecision":"ask"}"#);
+ assert_eq!(stdout("muse", "PermissionRequest", None, None), None);
+ // Gemini CLI and Antigravity read "{}" as "no opinion" — Antigravity's
+ // PreToolUse included: the tool is never allowed on Coucou's say-so.
+ for agent in ["gemini", "antigravity"] {
+ for event in ["PreToolUse", "PostToolUse", "UserPromptSubmit", "Stop"] {
+ assert_eq!(stdout(agent, event, None, None).unwrap(), "{}");
+ }
+ }
+ // Cursor: silence, which Cursor reads as "carry on as usual".
+ for event in ["PreToolUse", "UserPromptSubmit", "Stop"] {
+ assert_eq!(stdout("cursor", event, None, None), None);
+ }
+ // Hermes approvals are not supported: its decisions are never relayed.
+ assert_eq!(stdout("hermes", "PermissionRequest", Some("allow"), None), None);
+ }
+
+ #[test]
+ fn decision_json_matches_the_documented_shape() {
+ assert_eq!(
+ decision_json("allow", None).unwrap(),
+ r#"{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}"#
+ );
+ assert!(decision_json("always", None).unwrap().contains(r#""behavior":"allow""#));
+ }
+
+ #[test]
+ fn anything_unrecognised_prints_nothing() {
+ assert!(decision_json("", None).is_none());
+ assert!(decision_json("maybe", None).is_none());
+ // The shape the app used to send must not be mistaken for a decision.
+ assert!(decision_json(r#"{"permissionDecision":"allow"}"#, None).is_none());
+ }
+
+ #[test]
+ fn an_answered_question_goes_back_as_the_same_input_plus_answers() {
+ let question = json!({
+ "questions": [{ "question": "Which one?", "options": [{ "label": "A" }, { "label": "B" }] }]
+ });
+ let out = stdout("", "PermissionRequest", Some(r#"{"answers":{"Which one?":"B"}}"#), Some(&question)).unwrap();
+ let v: Value = serde_json::from_str(&out).unwrap();
+ let decision = &v["hookSpecificOutput"]["decision"];
+ assert_eq!(decision["behavior"], "allow");
+ assert_eq!(decision["updatedInput"]["questions"], question["questions"]);
+ assert_eq!(decision["updatedInput"]["answers"]["Which one?"], "B");
+ // Only Claude Code asks questions: an answer for anyone else is nothing.
+ assert!(stdout("codex", "PermissionRequest", Some(r#"{"answers":{"Which one?":"B"}}"#), Some(&question)).is_none());
+ }
+
+ #[test]
+ fn answers_are_only_accepted_for_a_question() {
+ assert!(decision_json(r#"{"answers":{"q":"a"}}"#, None).is_none());
+ let question = json!({ "questions": [] });
+ assert!(decision_json(r#"{"answers":{}}"#, Some(&question)).is_none());
+ assert!(decision_json(r#"{"answers":{"q":1}}"#, Some(&question)).is_none());
+ assert!(decision_json(r#"{"command":"rm -rf /"}"#, Some(&question)).is_none());
+ }
+
+ #[test]
+ fn answers_must_match_the_questions_asked() {
+ let q = json!({ "questions": [
+ { "question": "Which one?", "options": [{ "label": "A" }, { "label": "B" }] },
+ { "question": "Extras?", "multiSelect": true,
+ "options": [{ "label": "Tests" }, { "label": "Docs" }, { "label": "Lint" }] }
+ ]});
+ let ok = |a: &str| decision_json(a, Some(&q)).is_some();
+ assert!(ok(r#"{"answers":{"Which one?":"A","Extras?":["Tests","Docs"]}}"#));
+ assert!(!ok(r#"{"answers":{"Which one?":"C","Extras?":["Tests"]}}"#));
+ assert!(!ok(r#"{"answers":{"Which one?":"A","Extras?":["Tests"],"Other?":"x"}}"#));
+ assert!(!ok(r#"{"answers":{"Which one?":"A"}}"#));
+ assert!(!ok(r#"{"answers":{"Which one?":["A"],"Extras?":["Tests"]}}"#));
+ assert!(!ok(r#"{"answers":{"Which one?":"A","Extras?":"Tests"}}"#));
+ assert!(!ok(r#"{"answers":{"Which one?":"A","Extras?":[]}}"#));
+ assert!(!ok(r#"{"answers":{"Which one?":"A","Extras?":["Tests","Tests"]}}"#));
+ }
+}