//! Herdr integration (https://herdr.dev/docs/add-herdr-support/): reports idle/working/blocked, the //! resume command and release to the herdr that owns this pane. No-op outside herdr. //! Reports go through a single worker that only sends the latest state and never blocks the agent. use crate::hook::{Event, HookAction}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::sync::watch; #[derive(Debug, Clone, PartialEq)] pub enum State { Idle, Working, Blocked(String), } struct Reporter { bin: String, pane: String, } static TX: OnceLock> = OnceLock::new(); static REP: OnceLock = OnceLock::new(); static SEQ: AtomicU64 = AtomicU64::new(0); /// Session file the pane resumes (None until the session has a turn: empty files are not worth resuming). static SESSION: Mutex> = Mutex::new(None); static PATH: Mutex> = Mutex::new(None); /// Current session file; call on start and whenever the session is replaced (/resume, /new). pub fn set_session(p: &std::path::Path) { let s = p.to_string_lossy().into_owned(); // herdr rejects apostrophes and control characters in resume args let ok = !s.chars().any(|c| c == '\'' || c.is_control()); *PATH.lock().unwrap_or_else(|e| e.into_inner()) = ok.then_some(s.clone()); let live = ok && p.metadata().is_ok_and(|m| m.len() > 0); *SESSION.lock().unwrap_or_else(|e| e.into_inner()) = live.then_some(s); } fn resume_path() -> Option { SESSION.lock().unwrap_or_else(|e| e.into_inner()).clone() } /// Strictly increasing across processes: wall-clock millis, bumped within this one. fn next_seq() -> u64 { let now = SystemTime::now() .duration_since(UNIX_EPOCH) .map_or(0, |d| d.as_millis() as u64); let mut last = SEQ.load(Ordering::Relaxed); loop { let n = now.max(last + 1); match SEQ.compare_exchange(last, n, Ordering::Relaxed, Ordering::Relaxed) { Ok(_) => return n, Err(l) => last = l, } } } fn state_args(pane: &str, s: &State, seq: u64, resume: Option<&str>) -> Vec { let mut a: Vec = [ "pane", "report-agent", pane, "--source", "hx", "--agent", "hx", ] .map(String::from) .into(); let (st, msg) = match s { State::Idle => ("idle", None), State::Working => ("working", None), State::Blocked(m) => ("blocked", Some(m)), }; a.extend(["--state".into(), st.into(), "--seq".into(), seq.to_string()]); if let Some(m) = msg { a.extend(["--message".into(), m.clone()]); } if let Some(p) = resume { a.extend(["--".into(), "hx".into(), "--session".into(), p.into()]); } a } fn release_args(pane: &str, seq: u64) -> Vec { [ "pane", "release-agent", pane, "--source", "hx", "--agent", "hx", "--seq", ] .map(String::from) .into_iter() .chain([seq.to_string()]) .collect() } impl Reporter { /// Runs the herdr CLI with a short timeout; failures are ignored. async fn run(&self, args: Vec) { let mut c = tokio::process::Command::new(&self.bin); c.args(args) .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .kill_on_drop(true); if let Ok(mut ch) = c.spawn() { let _ = tokio::time::timeout(Duration::from_secs(2), ch.wait()).await; } } } /// Starts reporting when running inside herdr. Call once, inside the tokio runtime. pub fn init() -> bool { let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); if var("HERDR_ENV").as_deref() != Some("1") { return false; } let (Some(bin), Some(pane)) = (var("HERDR_BIN_PATH"), var("HERDR_PANE_ID")) else { return false; }; let (tx, mut rx) = watch::channel(State::Idle); if TX.set(tx).is_err() || REP.set(Reporter { bin, pane }).is_err() { return false; } tokio::spawn(async move { // The first report claims the pane; `report` marks it changed again on every update. loop { let s = rx.borrow_and_update().clone(); if let Some(r) = REP.get() { let p = resume_path(); r.run(state_args(&r.pane, &s, next_seq(), p.as_deref())) .await; } if rx.changed().await.is_err() { break; } } }); true } /// Reports a state (no-op outside herdr or when unchanged). pub fn report(s: State) { if let Some(tx) = TX.get() { tx.send_if_modified(|c| { let ch = *c != s; *c = s; ch }); } } /// Permission/choice prompt waits for the user. pub fn blocked(msg: impl Into) { report(State::Blocked(msg.into())); } /// The user answered; the agent runs again. pub fn working() { report(State::Working); } /// Clears this pane's agent. Call when the user quits. pub async fn release() { if let Some(r) = REP.get() { r.run(release_args(&r.pane, next_seq())).await; } } /// Maps agent events to herdr states. pub struct Hook; #[async_trait::async_trait] impl crate::hook::Hook for Hook { async fn on(&self, ev: &Event) -> HookAction { match ev { Event::TurnStart => { let p = PATH.lock().unwrap_or_else(|e| e.into_inner()).clone(); *SESSION.lock().unwrap_or_else(|e| e.into_inner()) = p; report(State::Working); } Event::ToolCall { .. } | Event::ToolResult { .. } => report(State::Working), Event::AgentEnd => report(State::Idle), _ => {} } HookAction::Continue } } #[cfg(test)] mod tests { use super::*; #[test] fn args() { let a = state_args( "p1", &State::Blocked("bash: ls".into()), 7, Some("/s/a.jsonl"), ); let j = a.join(" "); assert!( j.starts_with("pane report-agent p1 --source hx --agent hx --state blocked --seq 7") ); assert!(j.contains("--message bash: ls") && j.ends_with("-- hx --session /s/a.jsonl")); assert!(!state_args("p1", &State::Idle, 1, None).contains(&"--".to_string())); assert_eq!(release_args("p1", 9).last().unwrap(), "9"); } #[test] fn seq_increases() { let (a, b) = (next_seq(), next_seq()); assert!(b > a); } #[tokio::test] async fn runs_binary() { let d = tempfile::tempdir().unwrap(); let out = d.path().join("argv"); let bin = d.path().join("herdr"); std::fs::write( &bin, format!("#!/bin/sh\necho \"$@\" > {}\n", out.display()), ) .unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); let r = Reporter { bin: bin.to_string_lossy().into(), pane: "p9".into(), }; r.run(release_args(&r.pane, 3)).await; assert!( std::fs::read_to_string(out) .unwrap() .starts_with("pane release-agent p9") ); } }