use crate::rpc::emit; use anyhow::Result; use async_trait::async_trait; use hx_ai::{Pricing, StreamEvent, Usage}; use hx_core::agent::{AbortHandle, Agent, Error}; use hx_core::hook::{Event, Hook, HookAction}; use hx_core::permit::Decision; use serde_json::{Value, json}; use std::collections::HashMap; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::SeqCst}; use std::sync::{Arc, Mutex as StdMutex}; use std::time::Duration; use tokio::io::AsyncBufReadExt; use tokio::sync::{Mutex, oneshot}; const PROMPT: &str = r#" # Headless step You run as one step of an automated pipeline. Nobody answers questions while you work: decide yourself and state assumptions. If you cannot go on without a human answer, stop and ask it. Lines starting with "Messages since your last step" are hints from the orchestrator; follow them. End every step with exactly one fenced block, last in your reply: ```hx-step {"status": "done" | "blocked" | "needs_input", "summary": "what you did, 1-3 sentences", "catch": "blocked only: one name from the catch list of the step, else omit", "question": "the one question you need answered (needs_input only)", "decisions": ["choices worth recording, e.g. token bucket over sliding window"], "plan": {"steps": ["..."], "files": ["paths you will touch"]}} ``` `decisions` and `plan` are optional; give `plan` in planning steps. Put free text in `summary`, never in `catch`."#; pub struct Opts { pub session: String, pub cwd: PathBuf, pub pricing: Option, } struct Link { sid: String, next: AtomicU64, pending: StdMutex>>, } impl Link { fn notify(&self, method: &str, params: Value) { emit(&json!({"jsonrpc": "2.0", "method": method, "params": params})); } fn update(&self, u: Value) { self.notify( "session/update", json!({"sessionId": self.sid, "update": u}), ); } async fn request(&self, method: &str, params: Value) -> Option { let id = self.next.fetch_add(1, SeqCst); let (tx, rx) = oneshot::channel(); self.pending .lock() .unwrap_or_else(|e| e.into_inner()) .insert(id, tx); emit(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})); rx.await.ok() } fn resolve(&self, id: &Value, msg: Value) { let tx = id.as_u64().and_then(|n| { self.pending .lock() .unwrap_or_else(|e| e.into_inner()) .remove(&n) }); if let Some(tx) = tx { let _ = tx.send(msg); } } fn close(&self) { self.pending .lock() .unwrap_or_else(|e| e.into_inner()) .clear(); } } fn respond(id: &Value, r: Result) { if id.is_null() { return; } emit(&match r { Ok(v) => json!({"jsonrpc": "2.0", "id": id, "result": v}), Err(e) => json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32000, "message": e}}), }); } #[derive(Default)] struct M { step: Usage, total: Usage, ctx: u64, ctx_limit: Option, cost_limit: Option, stop: Option, pending: Vec, question: Option, intent: String, before: HashMap>, } struct Meter { link: Arc, abort: AbortHandle, cwd: PathBuf, pricing: Option, window: u64, st: StdMutex, } fn kind(tool: &str) -> &'static str { match tool { "bash" => "execute", "write" | "edit" => "edit", "read" => "read", "grep" | "find" | "ls" | "lsp" => "search", "web_fetch" | "web_search" => "fetch", _ => "other", } } fn intent_of(name: &str, args: &Value) -> String { let s = |k: &str| args[k].as_str().unwrap_or_default(); let short = |t: &str| { t.lines() .next() .unwrap_or_default() .chars() .take(80) .collect::() }; match name { "bash" => format!("Running `{}`", short(s("command"))), "edit" => format!("Editing {}", s("path")), "write" => format!("Writing {}", s("path")), "read" => format!("Reading {}", s("path")), _ => format!("Using {name}"), } } fn line_diff(old: &str, new: &str) -> (usize, usize) { use similar::{ChangeTag, TextDiff}; TextDiff::from_lines(old, new) .iter_all_changes() .fold((0, 0), |(a, r), c| match c.tag() { ChangeTag::Insert => (a + 1, r), ChangeTag::Delete => (a, r + 1), ChangeTag::Equal => (a, r), }) } impl Meter { fn m(&self) -> std::sync::MutexGuard<'_, M> { self.st.lock().unwrap_or_else(|e| e.into_inner()) } fn cost(&self, u: &Usage) -> f64 { self.pricing.map_or(0.0, |p| u.cost(&p)) } fn usage_note(&self, m: &M) { self.link.notify( "hx/usage", json!({"used": m.ctx, "limit": m.ctx_limit.unwrap_or(self.window), "cost": self.cost(&m.total)}), ); } fn path(&self, args: &Value) -> PathBuf { self.cwd.join(args["path"].as_str().unwrap_or_default()) } fn begin(&self, ctx: Option, cost: Option) { let mut m = self.m(); m.step = Usage::default(); m.ctx_limit = ctx; m.cost_limit = cost; m.stop = None; m.question = None; } fn stop(&self, why: impl Into) { let mut m = self.m(); m.stop.get_or_insert(why.into()); } fn take(&self) -> (Option, Option) { let mut m = self.m(); (m.stop.take(), m.question.take()) } fn sync(&self, total: &Usage, ctx: Option) { let mut m = self.m(); m.total = total.clone(); if let Some(c) = ctx { m.ctx = c; } self.usage_note(&m); } fn say(&self, m: &mut M, text: String) { if m.intent != text { self.link.notify("hx/intent", json!(text)); m.intent = text; } } } #[async_trait] impl Hook for Meter { async fn on(&self, ev: &Event) -> HookAction { match ev { Event::Stream(StreamEvent::TextDelta { text }) => { self.link.update(json!({ "sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}})) } Event::Stream(StreamEvent::ThinkingDelta { text }) => { self.link.update(json!({ "sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": text}})) } Event::Stream(StreamEvent::Done { usage, .. }) => { let mut m = self.m(); m.step.add(usage); m.total.add(usage); m.ctx = usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens; if let Some(l) = m.ctx_limit.filter(|l| m.ctx >= *l) { let why = format!( "context limit reached ({}/{l} tokens); send hx/compact", m.ctx ); m.stop.get_or_insert(why); } if let Some(l) = m.cost_limit.filter(|l| self.cost(&m.step) >= *l) { m.stop.get_or_insert(format!("cost limit ${l:.2} reached")); } self.usage_note(&m); } Event::SubUsage(u) => { let mut m = self.m(); m.step.add(u); m.total.add(u); self.usage_note(&m); } Event::ToolCall { id, name, args } => { let text = intent_of(name, args); let mut m = self.m(); self.say(&mut m, text.clone()); if matches!(name.as_str(), "write" | "edit") { m.before .insert(id.clone(), std::fs::read_to_string(self.path(args)).ok()); } drop(m); self.link .update(json!({"sessionUpdate": "tool_call", "toolCallId": id, "title": text, "kind": kind(name), "status": "in_progress", "rawInput": args})); } Event::ToolResult { id, args, content, is_error, .. } => { let shown: String = content.chars().take(4000).collect(); self.link.update( json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "status": if *is_error { "failed" } else { "completed" }, "content": [{"type": "content", "content": {"type": "text", "text": shown}}]}), ); let old = self.m().before.remove(id); if let (false, Some(old)) = (*is_error, old) { let p = self.path(args); if let Ok(new) = std::fs::read_to_string(&p) { let (added, removed) = line_diff(old.as_deref().unwrap_or_default(), &new); let rel = p.strip_prefix(&self.cwd).unwrap_or(&p); self.link.notify( "hx/edit", json!({"path": rel, "added": added, "removed": removed}), ); } } } Event::TurnEnd | Event::AgentEnd => { let mut m = self.m(); if m.stop.is_some() { if matches!(ev, Event::TurnEnd) { self.abort.abort(); } } else if !m.pending.is_empty() { return HookAction::Inject(format!( "Messages since your last step:\n{}", std::mem::take(&mut m.pending) .iter() .map(|h| format!("- {h}")) .collect::>() .join("\n") )); } } _ => {} } HookAction::Continue } } fn options(always: bool) -> Value { let mut o = vec![json!({"optionId": "allow_once", "name": "Allow", "kind": "allow_once"})]; if always { o.push(json!({"optionId": "allow_always", "name": "Allow always", "kind": "allow_always"})); } o.push(json!({"optionId": "reject_once", "name": "Deny", "kind": "reject_once"})); json!(o) } async fn permission( link: &Link, mut abort: tokio::sync::watch::Receiver, call: Value, always: bool, ) -> Option { let params = json!({"sessionId": link.sid, "toolCall": call, "options": options(always)}); let reply = tokio::select! { r = link.request("session/request_permission", params) => r?, _ = async { abort.wait_for(|a| *a).await.is_ok() } => return None, }; let o = &reply["result"]["outcome"]; (o["outcome"] == "selected") .then(|| o["optionId"].as_str().map(String::from)) .flatten() } fn install(agent: &Agent, link: &Arc, meter: &Arc) { let state = &agent.cx.state; let abort = state.abort.get().cloned(); let calls = Arc::new(AtomicU64::new(0)); let rx = move || { abort .clone() .unwrap_or_else(|| tokio::sync::watch::channel(false).1) }; { let (link, rx, calls) = (link.clone(), rx.clone(), calls.clone()); let _ = state.permit.set(Arc::new(move |r| { let (link, rx) = (link.clone(), rx.clone()); let n = calls.fetch_add(1, SeqCst); Box::pin(async move { let call = json!({"toolCallId": format!("perm-{n}"), "title": format!("{}: {}", r.tool, r.detail), "kind": kind(&r.tool), "status": "pending", "rawInput": {"tool": r.tool, "detail": r.detail}}); let always = !r.rule.is_empty() || matches!(r.tool.as_str(), "write" | "edit"); match permission(&link, rx(), call, always).await.as_deref() { Some("allow_once") => Decision::Once, Some("allow_always") if matches!(r.tool.as_str(), "write" | "edit") => { Decision::Edits } Some("allow_always") => Decision::Always, _ => Decision::Deny, } }) })); } { let (link, rx) = (link.clone(), rx.clone()); let _ = state.ask.set(Arc::new(move |q| { let (link, rx) = (link.clone(), rx.clone()); let n = calls.fetch_add(1, SeqCst); Box::pin(async move { let call = json!({"toolCallId": format!("perm-{n}"), "title": q, "kind": "other", "status": "pending"}); permission(&link, rx(), call, false).await.as_deref() == Some("allow_once") }) })); } { let meter = meter.clone(); let _ = state.choose.set(Arc::new(move |q| { meter.m().question.get_or_insert(q.text); Box::pin(async { None }) })); } } fn text_of(v: &Value) -> Option { match v { Value::Null => None, Value::String(s) => (!s.trim().is_empty()).then(|| s.clone()), Value::Array(a) if a.iter().all(|b| b["text"].is_string()) => { let t: Vec<_> = a.iter().filter_map(|b| b["text"].as_str()).collect(); Some(t.join("\n")) } o => serde_json::to_string_pretty(o).ok(), } } fn compose(p: &Value) -> String { let mut parts = vec![]; parts.extend(text_of(&p["instruction"])); parts.extend(text_of(&p["context"]).map(|c| format!("Context:\n{c}"))); parts.extend(text_of(&p["prompt"])); parts.join("\n\n") } fn num(v: &Value, keys: &[&str]) -> Option { keys.iter().find_map(|k| v[k].as_f64()).filter(|n| *n > 0.0) } fn report(text: &str) -> Option<(Value, &str)> { let i = text.rfind("```hx-step")?; let rest = &text[i + "```hx-step".len()..]; let end = rest.find("```")?; Some(( serde_json::from_str(rest[..end].trim()).ok()?, text[..i].trim(), )) } fn now() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()) } fn outcome(link: &Link, reply: &str, question: Option, catches: &[String]) -> Value { let (rep, body) = report(reply).unwrap_or((Value::Null, reply.trim())); for d in rep["decisions"].as_array().into_iter().flatten() { let (text, state) = match d { Value::String(s) => (s.as_str(), "made"), o => ( o["text"].as_str().unwrap_or_default(), o["state"].as_str().unwrap_or("made"), ), }; if !text.is_empty() { link.notify( "hx/decision", json!({"text": text, "state": state, "at": now()}), ); } } if rep["plan"].is_object() { link.notify( "hx/plan", json!({"steps": rep["plan"]["steps"], "files": rep["plan"]["files"]}), ); } let mut status = rep["status"] .as_str() .filter(|s| matches!(*s, "done" | "blocked" | "needs_input")) .unwrap_or(if question.is_some() { "needs_input" } else { "done" }); let q = rep["question"].as_str().map(String::from).or(question); if status == "needs_input" && q.is_none() { status = "blocked"; } let mut summary: String = rep["summary"] .as_str() .map_or_else(|| body.chars().take(1500).collect(), String::from); let mut catch = Value::Null; if let (true, Some(c)) = (status == "blocked", rep["catch"].as_str()) { if catches.iter().any(|n| n == c) { catch = json!(c); } else if !c.is_empty() { summary = format!("{summary} ({c})"); } } json!({"status": status, "summary": summary, "catch": catch, "question": q}) } fn catch_names(p: &Value) -> Vec { [&p["catches"], &p["context"]["catches"]] .iter() .find_map(|v| v.as_array()) .into_iter() .flatten() .filter_map(|c| c.as_str().map(String::from)) .collect() } struct Srv { link: Arc, meter: Arc, agent: Arc>, } async fn step(s: &Srv, p: &Value) -> Value { let blocked = |reason: &str, why: String| { json!({"status": "blocked", "summary": why, "catch": null, "reason": reason, "question": null}) }; let mut prompt = compose(p); if prompt.is_empty() { return blocked("error", "empty step: no prompt".into()); } let catches = catch_names(p); if !catches.is_empty() { prompt.push_str(&format!( "\n\nValid `catch` names when status is blocked: {}. Use one only if it fits.", catches.join(", ") )); } let lim = &p["limits"]; let wall = num(lim, &["wall_time_secs", "wall_time", "wall_secs"]); s.meter.begin( num(lim, &["context_tokens", "context"]).map(|n| n as u64), num(lim, &["cost_usd", "cost"]), ); let mut a = s.agent.lock().await; let r = { let run = a.run(prompt); tokio::pin!(run); let deadline = async { match wall { Some(w) => tokio::time::sleep(Duration::from_secs_f64(w)).await, None => std::future::pending().await, } }; tokio::select! { r = &mut run => r, _ = deadline => { s.meter.stop(format!("wall time limit {}s reached", wall.unwrap_or_default())); tokio::select! { r = &mut run => r, _ = tokio::time::sleep(Duration::from_secs(30)) => { s.meter.abort.abort(); run.await } } } } }; let (stop, question) = s.meter.take(); s.meter.sync(a.usage(), None); match r { Ok(m) => outcome(&s.link, &m.text(), question, &catches), Err(Error::Aborted) => match stop { Some(s) if s == "interrupted" => blocked("interrupted", s), Some(s) => blocked("limit", s), None => blocked("cancelled", "cancelled".into()), }, Err(e) => blocked("error", e.to_string()), } } pub async fn serve(mut agent: Agent, abort: AbortHandle, o: Opts) -> Result<()> { let link = Arc::new(Link { sid: o.session, next: AtomicU64::new(1), pending: Default::default(), }); let meter = Arc::new(Meter { link: link.clone(), abort: abort.clone(), cwd: o.cwd, pricing: o.pricing, window: agent.compact_at() as u64, st: Default::default(), }); agent.tools.retain(|n| n != "exit_plan"); agent.append_system(PROMPT); install(&agent, &link, &meter); agent.bus.add_arc(meter.clone()); let srv = Arc::new(Srv { link: link.clone(), meter: meter.clone(), agent: Arc::new(Mutex::new(agent)), }); let busy = Arc::new(AtomicBool::new(false)); let mut tasks = vec![]; let mut lines = tokio::io::BufReader::new(tokio::io::stdin()).lines(); while let Some(l) = lines.next_line().await? { let Ok(m) = serde_json::from_str::(&l) else { emit(&json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": "parse error"}})); continue; }; let (id, p) = (m["id"].clone(), m["params"].clone()); let Some(method) = m["method"].as_str() else { link.resolve(&id, m); continue; }; match method { "initialize" => respond( &id, Ok(json!({"protocolVersion": 1, "authMethods": [], "agentCapabilities": {"loadSession": true, "promptCapabilities": {}}, "agentInfo": {"name": "hx", "version": env!("CARGO_PKG_VERSION")}})), ), "session/new" | "session/load" => respond(&id, Ok(json!({"sessionId": link.sid}))), "session/cancel" => abort.abort(), "hx/interrupt" => { if busy.load(SeqCst) { meter.stop("interrupted"); } respond(&id, Ok(json!({}))); } "hx/message" => { match text_of(&p) .or_else(|| text_of(&p["text"])) .or_else(|| text_of(&p["message"])) { Some(t) => { meter.m().pending.push(t); respond(&id, Ok(json!({}))); } None => respond(&id, Err("message text required".into())), } } "hx/compact" => { if busy.swap(true, SeqCst) { respond(&id, Err("busy: a step is running".into())); continue; } let (srv, busy) = (srv.clone(), busy.clone()); tasks.push(tokio::spawn(async move { let mut a = srv.agent.lock().await; let r = a.compact_now().await; srv.meter.sync(a.usage(), Some(a.context_tokens() as u64)); busy.store(false, SeqCst); respond( &id, r.map(|c| json!({"compacted": c})) .map_err(|e| e.to_string()), ); })); } "hx/step" | "session/prompt" => { if busy.swap(true, SeqCst) { respond(&id, Err("busy: a step is running".into())); continue; } let (srv, busy) = (srv.clone(), busy.clone()); let acp = method == "session/prompt"; tasks.push(tokio::spawn(async move { let hints = std::mem::take(&mut srv.meter.m().pending); let mut p = p; if !hints.is_empty() { let h = hints.iter().map(|h| format!("- {h}")).collect::>(); p["instruction"] = json!(format!( "Messages since your last step:\n{}\n\n{}", h.join("\n"), text_of(&p["instruction"]).unwrap_or_default() )); } let out = step(&srv, &p).await; busy.store(false, SeqCst); srv.link.notify("hx/step_result", out.clone()); respond( &id, Ok(if acp { let cancelled = out["reason"] == "cancelled"; json!({"stopReason": if cancelled { "cancelled" } else { "end_turn" }}) } else { out }), ); })); } other => respond(&id, Err(format!("method not found: {other}"))), } } abort.abort(); link.close(); for t in tasks { let _ = t.await; } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn report_block_is_parsed() { let t = "did it\n```hx-step\n{\"status\":\"blocked\",\"catch\":\"x\"}\n```"; let (v, body) = report(t).unwrap(); assert_eq!((v["status"].as_str(), body), (Some("blocked"), "did it")); assert!(report("no block").is_none()); assert!(report("```hx-step\nnot json\n```").is_none()); } #[test] fn step_prompt_and_limits() { let p = json!({"instruction": "implement", "context": {"goal": "x"}, "prompt": "go"}); let c = compose(&p); assert!(c.starts_with("implement\n\nContext:\n{"), "{c}"); assert!(c.ends_with("\n\ngo")); assert_eq!( num(&json!({"cost_usd": 2.5}), &["cost_usd", "cost"]), Some(2.5) ); assert_eq!(num(&json!({"cost_usd": 0}), &["cost_usd"]), None); assert_eq!( text_of(&json!([{"type": "text", "text": "a"}])), Some("a".into()) ); } #[test] fn diff_counts_lines() { assert_eq!(line_diff("a\nb\n", "a\nc\nd\n"), (2, 1)); assert_eq!(line_diff("", "x\n"), (1, 0)); } #[test] fn outcome_defaults() { let l = Link { sid: "s".into(), next: AtomicU64::new(1), pending: Default::default(), }; assert_eq!(outcome(&l, "all good", None, &[])["status"], "done"); let o = outcome(&l, "hmm", Some("which db?".into()), &[]); assert_eq!( (o["status"].as_str(), o["question"].as_str()), (Some("needs_input"), Some("which db?")) ); let r = "```hx-step\n{\"status\":\"needs_input\"}\n```"; assert_eq!(outcome(&l, r, None, &[])["status"], "blocked"); } #[test] fn catch_must_be_a_listed_name() { let l = Link { sid: "s".into(), next: AtomicU64::new(1), pending: Default::default(), }; let names = catch_names(&json!({"context": {"catches": ["PlanInvalid", "ToolDenied"]}})); let blocked = |c: &str| { let r = format!( "```hx-step\n{{\"status\":\"blocked\",\"summary\":\"s\",\"catch\":\"{c}\"}}\n```" ); outcome(&l, &r, None, &names) }; assert_eq!(blocked("ToolDenied")["catch"], "ToolDenied"); let o = blocked("made up"); assert_eq!( (o["catch"].is_null(), o["summary"].as_str()), (true, Some("s (made up)")) ); let r = "```hx-step\n{\"status\":\"done\",\"catch\":\"ToolDenied\"}\n```"; assert!(outcome(&l, r, None, &names)["catch"].is_null()); } }