diff --git a/README.md b/README.md index ecb740e..3c0bfbd 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,13 @@ poor proxy (context7: 2 tools, 1.1k tokens), the eager rule is schema size, not `hx mcp-serve` runs hx as a stdio MCP server exposing the `lsp` tool (diagnostics, definition, references, hover, symbols) to other clients. +## Herdr + +Inside a [herdr](https://herdr.dev) pane (`HERDR_ENV=1`) hx reports `idle` / `working` / `blocked` (permission, +ask and choose prompts) to the sidebar, `herdr agent list` and `herdr agent wait`. It also reports +`hx --session ` as resume command, so a herdr server restart reopens the same session, and releases +the pane on quit. Outside herdr nothing happens. + ## Machine interfaces ### Event stream (`hx -p "..." --mode json`) diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 7c26067..03d5bc5 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -555,6 +555,10 @@ async fn main() -> Result<()> { model: model.clone(), effort: Some(effort), }; + if hx_core::herdr::init() { + hx_core::herdr::set_session(&path); + agent.bus.add(hx_core::herdr::Hook); + } agent.set_model(model); agent.set_effort(effort); agent.set_system(context::system_prompt( @@ -698,6 +702,7 @@ async fn main() -> Result<()> { }, ) .await; + hx_core::herdr::release().await; mgr.shutdown().await; return r; } @@ -785,6 +790,7 @@ async fn main() -> Result<()> { }, }) .await?; + hx_core::herdr::release().await; mgr.shutdown().await; return Ok(()); }; @@ -823,6 +829,7 @@ async fn main() -> Result<()> { { eprintln!("[lsp] {n}"); } + hx_core::herdr::release().await; mgr.shutdown().await; r?; Ok(()) diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 22b6b70..53b2cab 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -162,6 +162,7 @@ impl Agent { /// Continue in another session (resume or new). Drops token usage measured on the old history. pub fn replace_session(&mut self, session: Session) { + crate::herdr::set_session(session.path()); self.session = session; self.window.reset(); } diff --git a/crates/hx-core/src/herdr.rs b/crates/hx-core/src/herdr.rs new file mode 100644 index 0000000..363bf6a --- /dev/null +++ b/crates/hx-core/src/herdr.rs @@ -0,0 +1,246 @@ +//! 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") + ); + } +} diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index dbf38e4..6d2b9c7 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -5,6 +5,7 @@ pub mod command; pub mod compact; pub mod context; pub mod ext; +pub mod herdr; pub mod hook; mod mask; pub mod memory; diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index b66c386..2dafc90 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -267,24 +267,39 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { .ask .set(std::sync::Arc::new(move |q: String| { let (otx, orx) = tokio::sync::oneshot::channel(); + hx_core::herdr::blocked(q.clone()); let _ = tx.send(Ui::Ask(q, otx)); - Box::pin(async move { orx.await.unwrap_or(false) }) + Box::pin(async move { + let r = orx.await.unwrap_or(false); + hx_core::herdr::working(); + r + }) })); } if !yolo { let tx = tx.clone(); let _ = agent.cx.state.permit.set(std::sync::Arc::new(move |r| { let (otx, orx) = tokio::sync::oneshot::channel(); + hx_core::herdr::blocked(format!("{}: {}", r.tool, r.detail)); let _ = tx.send(Ui::Permit(r, otx)); - Box::pin(async move { orx.await.unwrap_or(hx_core::permit::Decision::Deny) }) + Box::pin(async move { + let d = orx.await.unwrap_or(hx_core::permit::Decision::Deny); + hx_core::herdr::working(); + d + }) })); } { let tx = tx.clone(); let _ = agent.cx.state.choose.set(std::sync::Arc::new(move |q| { let (otx, orx) = tokio::sync::oneshot::channel(); + hx_core::herdr::blocked("choose an option"); let _ = tx.send(Ui::Choose(q, otx)); - Box::pin(async move { orx.await.unwrap_or(None) }) + Box::pin(async move { + let c = orx.await.unwrap_or(None); + hx_core::herdr::working(); + c + }) })); } let (stx, mut srx) = mpsc::unbounded_channel(); diff --git a/tests/e2e.sh b/tests/e2e.sh index a5a2285..284ab8c 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -26,4 +26,11 @@ import json, sys last = json.load(sys.stdin)[-1] assert last["path"].endswith("/responses") and last["body"]["model"] == "gpt-5.6-terra" and last["auth"] == "Bearer cx-token", last ' || { echo "FAIL: gpt model not routed to codex"; cat "$tmp/err"; exit 1; } +# inside herdr: working, idle and release reach the herdr binary; resume command carries the session +printf '#!/bin/sh\necho "$@" >> "%s/herdr.log"\n' "$tmp" > "$tmp/herdr"; chmod +x "$tmp/herdr" +echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json" +HERDR_ENV=1 HERDR_PANE_ID=p7 HERDR_BIN_PATH="$tmp/herdr" HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port" "$root/target/debug/hx" -p "make hello.txt" > /dev/null 2>&1 +grep -q 'report-agent p7 --source hx --agent hx --state working' "$tmp/herdr.log" || { echo "FAIL: herdr working"; exit 1; } +grep -q -- '-- hx --session .*jsonl' "$tmp/herdr.log" || { echo "FAIL: herdr resume"; exit 1; } +grep -q 'release-agent p7' "$tmp/herdr.log" || { echo "FAIL: herdr release"; exit 1; } echo "e2e ok"