//! ACP client (ORCHESTRATOR.md section 5): JSON-RPC 2.0, one JSON object per line, over the stdio of //! `hx serve --acp`. Standard ACP messages (`initialize`, `session/new`, `session/update`, //! `session/request_permission`) plus the custom `hx/*` messages. `hx/step` is acknowledged at once; the //! outcome arrives later as the `hx/step_result` notification. use crate::profile::Profile; use crate::run::hx_env; use anyhow::{Context, Result, anyhow, bail}; use serde_json::{Value, json}; use std::io::{BufRead, Write}; use std::os::unix::process::CommandExt; use std::path::Path; use std::process::{Child, ChildStdin, Command, Stdio}; use std::sync::mpsc; use std::time::{Duration, Instant}; /// Receives what hx reports while a step runs. pub trait Sink { /// Notifications: `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`, `session/update`. fn notify(&mut self, method: &str, params: &Value) -> Result<()>; /// `session/request_permission`: returns the chosen `optionId`, or None to cancel the request. fn permission(&mut self, params: &Value) -> Option; /// Called about every 100 ms while a step runs: what the user or the budgets want hx to be told. fn poll(&mut self) -> Poll { Poll::default() } } /// What to send to a running step. #[derive(Default, Debug, PartialEq)] pub struct Poll { /// User hints, sent as `hx/message`. pub messages: Vec, /// `hx/interrupt`: finish the current tool call, then stop (the step result still arrives). pub interrupt: bool, /// `hx/compact`: compact the context now. pub compact: bool, } const POLL_EVERY: Duration = Duration::from_millis(100); #[derive(Debug, PartialEq)] pub struct StepResult { /// done | blocked | needs_input pub status: String, pub catch: Option, /// Why a step is `blocked` without a catch; `"limit"` means hx hit a limit passed in `hx/step`. pub reason: Option, pub question: Option, pub summary: String, } pub struct Acp { child: Child, stdin: ChildStdin, rx: mpsc::Receiver, next_id: u64, session: String, } impl Acp { /// Starts `hx serve --acp --cwd --session ` and opens an ACP session. pub fn spawn(p: &Profile, worktree: &Path, id: &str) -> Result { let mut parts = p.hx.split_whitespace(); let mut cmd = Command::new(parts.next().context("empty hx command")?); // sandbox and permission flags are options of the root command, so they go before `serve` cmd.args(parts).args(p.acp_flags()); cmd.args(["serve", "--acp", "--cwd"]) .arg(worktree) .args(["--session", id]); // same cleared environment as the batch runner: orch's secrets never reach the agent cmd.env_clear().envs(hx_env(std::env::vars(), p)); if let Some(h) = &p.home { cmd.env("HOME", h); } let log = std::fs::File::create(format!("{}.agent.log", worktree.display()))?; let mut child = cmd .current_dir(worktree) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::from(log)) .process_group(0) // own group: kill takes hx and its tool children together .spawn() .with_context(|| format!("spawn {}", p.hx))?; let stdin = child.stdin.take().expect("piped"); let out = child.stdout.take().expect("piped"); let (tx, rx) = mpsc::channel(); std::thread::spawn(move || { for l in std::io::BufReader::new(out).lines().map_while(Result::ok) { if let Ok(v) = serde_json::from_str::(&l) && tx.send(v).is_err() { break; } } }); let mut a = Self { child, stdin, rx, next_id: 1, session: String::new(), }; a.request( "initialize", json!({"protocolVersion": 1, "clientCapabilities": {}}), )?; let new = a.request("session/new", json!({"cwd": worktree, "mcpServers": []}))?; a.session = new["sessionId"].as_str().unwrap_or(id).to_string(); Ok(a) } fn send(&mut self, v: Value) -> Result<()> { let mut line = v.to_string(); line.push('\n'); self.stdin .write_all(line.as_bytes()) .and_then(|()| self.stdin.flush()) .context("write to hx (did it exit?)") } /// Sends a request and returns its result. Only used for the handshake, before any step runs, so /// nothing hx sends in between has a sink to go to and is dropped. fn request(&mut self, method: &str, params: Value) -> Result { let id = self.next_id; self.next_id += 1; self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))?; loop { let m = self.recv()?; if m.get("method").is_none() && m["id"] == json!(id) { if let Some(e) = m.get("error") { bail!("hx {method}: {}", e["message"].as_str().unwrap_or("error")); } return Ok(m["result"].clone()); } self.dispatch(&m, None)?; } } fn recv(&mut self) -> Result { self.rx .recv() .map_err(|_| anyhow!("hx closed its output (exited or crashed)")) } /// Handles one message that is not the response we wait for. Returns a step result if it was one. fn dispatch(&mut self, m: &Value, sink: Option<&mut dyn Sink>) -> Result> { let Some(method) = m["method"].as_str() else { return Ok(None); // a late response (e.g. the ack of hx/step) }; // ACP reserves a leading `_` for custom methods: `_hx/intent` is the same as `hx/intent` let method = method .strip_prefix('_') .filter(|r| r.starts_with("hx/")) .unwrap_or(method); let params = &m["params"]; if m.get("id").is_some() { // a request from hx let reply = if method == "session/request_permission" { let chosen = sink.and_then(|s| s.permission(params)); let outcome = match chosen { Some(o) => json!({"outcome": "selected", "optionId": o}), None => json!({"outcome": "cancelled"}), }; json!({"jsonrpc": "2.0", "id": m["id"], "result": {"outcome": outcome}}) } else { json!({"jsonrpc": "2.0", "id": m["id"], "error": {"code": -32601, "message": format!("unsupported: {method}")}}) }; self.send(reply)?; return Ok(None); } if method == "hx/step_result" { let s = |k: &str| params[k].as_str().map(String::from); return Ok(Some(StepResult { status: s("status").unwrap_or_default(), catch: s("catch"), reason: s("reason"), question: s("question"), summary: s("summary").unwrap_or_default(), })); } if let Some(s) = sink { s.notify(method, params)?; } Ok(None) } /// Runs one agent step and waits for its `hx/step_result`. pub fn step( &mut self, prompt: &str, instruction: &str, context: Value, limits: Value, sink: &mut dyn Sink, ) -> Result { let id = self.next_id; self.next_id += 1; self.send( json!({"jsonrpc": "2.0", "id": id, "method": "hx/step", "params": { "sessionId": self.session, "prompt": prompt, "instruction": instruction, "context": context, "limits": limits, }}), )?; let mut last_poll = Instant::now(); let mut interrupted = false; loop { // poll on a timer, also while hx streams without a pause (a recv timeout alone would starve it) if last_poll.elapsed() >= POLL_EVERY { last_poll = Instant::now(); let p = sink.poll(); for text in p.messages { self.notify( "hx/message", json!({"sessionId": self.session, "text": text}), )?; } if p.interrupt && !interrupted { interrupted = true; self.notify("hx/interrupt", json!({"sessionId": self.session}))?; } if p.compact { self.notify("hx/compact", json!({"sessionId": self.session}))?; } } let m = match self.rx.recv_timeout(POLL_EVERY) { Ok(m) => m, Err(mpsc::RecvTimeoutError::Timeout) => continue, Err(mpsc::RecvTimeoutError::Disconnected) => { bail!("hx closed its output (exited or crashed)") } }; if m.get("method").is_none() && m["id"] == json!(id) { if let Some(e) = m.get("error") { bail!( "hx/step rejected: {}", e["message"].as_str().unwrap_or("error") ); } continue; // the ack } if let Some(r) = self.dispatch(&m, Some(&mut *sink))? { return Ok(r); } } } fn notify(&mut self, method: &str, params: Value) -> Result<()> { self.send(json!({"jsonrpc": "2.0", "method": method, "params": params})) } } impl Drop for Acp { fn drop(&mut self) { crate::state::kill_group(self.child.id()); let _ = self.child.wait(); } }