//! `cotton-session-host hook ` — 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::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader}; use tokio::net::UnixStream; use crate::protocol::{line, parse, Event, Request}; /// The event whose hook blocks on an answer. pub const BLOCKING_EVENT: &str = "PermissionRequest"; /// What a hook run produced. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HookOutcome { /// What to print on stdout. Empty means print nothing. pub stdout: String, } impl HookOutcome { /// Print nothing. pub fn 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. pub fn 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. pub async fn run(event: &str, socket: &Path, stdin: &str, wait: Duration) -> HookOutcome { let Ok(stream) = UnixStream::connect(socket).await else { // No daemon. The agent gets no opinion and prompts in its own TUI. return HookOutcome::silent(); }; let (read, mut write) = stream.into_split(); let Ok(text) = line(&request(event, stdin)) else { return HookOutcome::silent(); }; if write.write_all(text.as_bytes()).await.is_err() { return HookOutcome::silent(); } let _ = write.flush().await; if event != BLOCKING_EVENT { return HookOutcome::silent(); } let mut lines = BufReader::new(read).lines(); let answered = tokio::time::timeout(wait, async { while let Ok(Some(line)) = lines.next_line().await { if let Ok(Event::Decision { stdout, .. }) = parse::(&line) { return Some(stdout); } // Any other answer — `ok` on a timeout at the daemon's end, an // error — means there is no decision to print. if parse::(&line).is_ok() { return None; } } None }) .await; match answered { Ok(Some(stdout)) => HookOutcome { stdout: format!("{stdout}\n"), }, _ => HookOutcome::silent(), } } #[cfg(test)] #[path = "hook_tests.rs"] mod hook_tests;