//! `cotton-session-host hook <event>` — the command every hook the adapters//! register invokes.//!//! It reads the agent's hook JSON on stdin, hands it to the daemon as//! `{event, session_id, payload}`, and for `PermissionRequest` BLOCKS until the//! daemon answers a decision or the wait runs out.//!//! **What it prints, and when it prints nothing.** On a decision it prints the//! exact JSON the daemon's adapter encoded — this command knows neither//! agent's decision dialect, which is why an agent's format can change without//! a line here changing. On a timeout, on a daemon that is not listening, and//! on an event that is not a permission request, it prints NOTHING and exits 0://! both agents read an empty answer as "the hook had no opinion", so the//! session falls back to its own prompt in the TUI. A session waiting on a//! person in front of the terminal is the correct failure; a hook that crashed//! the turn is not.use std::path::Path;use std::time::Duration;use tokio::io::{AsyncBufReadExtas _, AsyncWriteExtas _, BufReader};use tokio::net::UnixStream;usecrate::protocol::{line, parse, Event, Request};/// The event whose hook blocks on an answer.pubconst BLOCKING_EVENT: &str = "PermissionRequest";/// What a hook run produced.#[derive(Debug, Clone, PartialEq, Eq)]pubstructHookOutcome {/// What to print on stdout. Empty means print nothing.pub stdout: String,}implHookOutcome {/// Print nothing.pubfn silent() -> Self {Self { stdout: String::new(), } }}/// The message this command sends for `event` and the JSON it was given.////// Pure, so the wire shape is a test rather than a socket.pubfn request(event: &str, stdin: &str) -> Request {let payload: serde_json::Value = serde_json::from_str(stdin.trim()).unwrap_or_else(|_| {// An agent that handed us something that is not JSON is still an agent// waiting on this hook. The text is forwarded AS TEXT rather than// dropped, so the daemon's log shows what arrived. serde_json::Value::String(stdin.trim().to_string()) });let session_id = payload .get("session_id") .and_then(serde_json::Value::as_str) .map(str::to_string);Request::Hook { event: event.to_string(), session_id, payload, }}/// Run one hook against the daemon's socket.pubasyncfn run(event: &str, socket: &Path, stdin: &str, wait: Duration) -> HookOutcome {letOk(stream) = UnixStream::connect(socket).awaitelse {// No daemon. The agent gets no opinion and prompts in its own TUI.returnHookOutcome::silent(); };let (read, mut write) = stream.into_split();letOk(text) = line(&request(event, stdin)) else {returnHookOutcome::silent(); };if write.write_all(text.as_bytes()).await.is_err() {returnHookOutcome::silent(); }let _ = write.flush().await;if event != BLOCKING_EVENT {returnHookOutcome::silent(); }letmut lines = BufReader::new(read).lines();let answered = tokio::time::timeout(wait, async {whileletOk(Some(line)) = lines.next_line().await {ifletOk(Event::Decision { stdout, .. }) = parse::<Event>(&line) {returnSome(stdout); }// Any other answer — `ok` on a timeout at the daemon's end, an// error — means there is no decision to print.if parse::<Event>(&line).is_ok() {returnNone; } }None }) .await;match answered {Ok(Some(stdout)) => HookOutcome { stdout: format!("{stdout}\n"), }, _ => HookOutcome::silent(), }}#[cfg(test)]#[path = "hook_tests.rs"]mod hook_tests;