M7: json + rpc modes, subprocess extensions (closes #52 #53 #54)
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s

This commit is contained in:
hermes committed 2026-09-30 21:40:20 +00:00
1 parent cf8268d17b
commit a01d0cbb5b
15 files changed
+723 -3

No files matched your search

+137
View File
@@ -0,0 +1,137 @@
//! 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<Value, String>) {
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`. One prompt at a time.
pub async fn serve(mut agent: Agent, abort: AbortHandle) -> Result<()> {
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 must work while a prompt holds the agent lock
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(),
"messages": a.session.messages().len(), "usage": a.usage,
"tools": a.tools.specs().into_iter().map(|t| t.name).collect::<Vec<_>>(),
})),
"messages" => Ok(json!(a.session.messages())),
"fork" => match p["id"].as_u64() {
Some(n) if a.session.fork(n) => Ok(json!({"head": a.session.head()})),
_ => Err("unknown entry id".into()),
},
"clear" => a
.session
.rebase(vec![])
.map(|_| json!({}))
.map_err(|e| e.to_string()),
"set_model" => match p["model"].as_str() {
Some(m) => {
a.model = m.into();
Ok(json!({"model": m}))
}
None => Err("params.model required".into()),
},
"compact" => a
.compact(4)
.await
.map(|c| json!({"compacted": c}))
.map_err(|e| e.to_string()),
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(())
}