//! Machine interfaces: NDJSON event stream (`--mode json`) and JSON-RPC over stdio (`--mode rpc`). use anyhow::Result; use hx_core::agent::{AbortHandle, Agent}; use hx_core::hook::{Event, Hook, HookAction}; use serde_json::{Value, json}; use std::io::Write; use std::sync::Arc; use tokio::io::AsyncBufReadExt; use tokio::sync::Mutex; /// One JSON line on stdout. pub fn emit(v: &Value) { let mut o = std::io::stdout().lock(); let _ = writeln!(o, "{v}"); let _ = o.flush(); } /// `--mode json`: every bus event as one NDJSON line. pub struct Ndjson; #[async_trait::async_trait] impl Hook for Ndjson { async fn on(&self, ev: &Event) -> HookAction { emit(&ev.to_json()); HookAction::Continue } } /// RPC mode forwards events as `event` notifications. struct Notify; #[async_trait::async_trait] impl Hook for Notify { async fn on(&self, ev: &Event) -> HookAction { emit(&json!({"jsonrpc": "2.0", "method": "event", "params": ev.to_json()})); HookAction::Continue } } fn reply(id: &Value, r: Result) { 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}}), }); } /// Methods: `prompt {text}` (replies when the run ends; events stream meanwhile), `abort`, /// `state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`, /// `complete {line, cursor?}` (cursor = byte offset, default end), `sessions {scope?: project|all}`, /// `new`, `resume {path}`. One prompt at a time. pub struct Ctx { pub specs: Vec, pub files: Vec, pub session_dir: std::path::PathBuf, pub switcher: hx_core::switch::Switcher, } pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()> { let Ctx { specs, files, session_dir, mut switcher, } = cx; agent.bus.add(Notify); let agent = Arc::new(Mutex::new(agent)); let busy = Arc::new(std::sync::atomic::AtomicBool::new(false)); let mut lines = tokio::io::BufReader::new(tokio::io::stdin()).lines(); let mut running = vec![]; while let Some(l) = lines.next_line().await? { let m: Value = match serde_json::from_str(&l) { Ok(m) => m, Err(e) => { reply(&Value::Null, Err(format!("parse error: {e}"))); continue; } }; let id = m["id"].clone(); let p = &m["params"]; let method = m["method"].as_str().unwrap_or_default(); // abort and complete must work while a prompt holds the agent lock if method == "complete" { let Some(line) = p["line"].as_str() else { reply(&id, Err("params.line required".into())); continue; }; let cur = p["cursor"].as_u64().map_or(line.len(), |c| c as usize); let c = hx_core::command::complete(line, cur, &specs, &files); let items: Vec<_> = c .items .iter() .map(|i| json!({"label": i.label, "detail": i.detail})) .collect(); reply(&id, Ok(json!({"start": c.start, "items": items}))); continue; } if method == "abort" { abort.abort(); reply(&id, Ok(json!({}))); continue; } if method == "prompt" { let Some(text) = p["text"].as_str().map(String::from) else { reply(&id, Err("params.text required".into())); continue; }; if busy.swap(true, std::sync::atomic::Ordering::SeqCst) { reply(&id, Err("busy: a prompt is running; abort it first".into())); continue; } let (agent, busy) = (agent.clone(), busy.clone()); running.push(tokio::spawn(async move { let mut a = agent.lock().await; let r = a.run(text).await; busy.store(false, std::sync::atomic::Ordering::SeqCst); reply( &id, r.map(|m| json!({"message": m, "usage": a.usage()})) .map_err(|e| e.to_string()), ); })); continue; } if busy.load(std::sync::atomic::Ordering::SeqCst) { reply(&id, Err("busy: a prompt is running".into())); continue; } let mut a = agent.lock().await; let r = match method { "state" => Ok(json!({ "model": a.model(), "session": a.session().path(), "head": a.session().head(), "title": hx_core::session::title(&a.session().messages()), "messages": a.session().messages().len(), "usage": a.usage(), "tools": a.tools.specs().into_iter().map(|t| t.name).collect::>(), })), "messages" => Ok(json!(a.session().messages())), "fork" => match p["id"].as_u64() { Some(n) if a.fork(n) => Ok(json!({"head": a.session().head()})), _ => Err("unknown entry id".into()), }, "clear" | "new" => a.new_session_here() .map(|_| json!({"session": a.session().path()})) .map_err(|e| e.to_string()), "set_model" => match p["model"].as_str() { // switches provider too when the model belongs to another one Some(m) => switcher .set_model(&mut a, m) .map(|sw| { let mut r = json!({"model": sw.model}); if sw.provider_changed { r["provider"] = json!(format!("{:?}", sw.kind).to_lowercase()); } r }), None => Err("params.model required".into()), }, "compact" => a .compact_now() .await .map(|c| json!({"compacted": c})) .map_err(|e| e.to_string()), "sessions" => { use hx_core::session::{list, list_all}; let v = match p["scope"].as_str() { Some("all") => list_all(session_dir.parent().unwrap_or(&session_dir)), _ => list(&session_dir), }; Ok(json!(v.iter().map(|m| json!({ "path": m.path, "title": m.title, "messages": m.messages, "model": m.model, "branches": m.branches, "project": m.project, "modified": m.modified.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()), })).collect::>())) } "resume" => match p["path"].as_str() { Some(path) => a .resume(std::path::Path::new(path)) .map(|_| { json!({"session": a.session().path(), "messages": a.session().messages().len()}) }) .map_err(|e| e.to_string()), None => Err("params.path required".into()), }, other => Err(format!("method not found: {other}")), }; if !id.is_null() { reply(&id, r); } } // stdin closed: let a running prompt finish for h in running { let _ = h.await; } Ok(()) }