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

+1
View File
@@ -20,6 +20,7 @@ hx-mcp = { version = "0.1.0", path = "../hx-mcp" }
hx-tui = { version = "0.1.0", path = "../hx-tui" }
serde = { version = "1.0.229", features = ["derive"] }
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal", "io-std", "io-util"] }
serde_json = "1.0.151"
toml = "1.1.6"
[lints]
+43 -1
View File
@@ -8,6 +8,8 @@ use hx_core::hook::{Event, Hook, HookAction};
use hx_core::session::Session;
use hx_core::tool::ToolCtx;
use std::io::Write;
mod rpc;
use std::sync::Arc;
#[derive(Parser)]
@@ -29,6 +31,16 @@ struct Cli {
/// Continue the most recent session in this directory.
#[arg(short, long)]
r#continue: bool,
/// Output mode: text (default for -p), json (NDJSON events on stdout; needs -p), rpc (JSON-RPC on stdio).
#[arg(long, value_enum, default_value_t = Mode::Text)]
mode: Mode,
}
#[derive(Clone, Copy, PartialEq, clap::ValueEnum)]
enum Mode {
Text,
Json,
Rpc,
}
#[derive(Subcommand)]
@@ -57,6 +69,8 @@ struct Config {
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
system_prompt: Option<String>,
lsp: Option<LspCfg>,
/// subprocess extensions (JSON-RPC over stdio); global and project lists are concatenated
extensions: Vec<hx_core::ext::ExtCfg>,
}
#[derive(Default, Clone, serde::Deserialize)]
@@ -97,6 +111,7 @@ impl Config {
max_tokens: o.max_tokens.or(c.max_tokens),
system_prompt: o.system_prompt.or(c.system_prompt),
lsp: o.lsp.or(c.lsp),
extensions: [c.extensions, o.extensions].concat(),
};
}
Ok(c)
@@ -301,6 +316,15 @@ async fn main() -> Result<()> {
if let Some(n) = cfg.max_tokens {
agent.max_tokens = n;
}
for e in &cfg.extensions {
let x = hx_core::ext::Extension::start(e, &cwd)
.await
.map_err(|err| anyhow::anyhow!("extension {:?}: {err}", e.command))?;
for t in x.tools() {
agent.tools.add(t);
}
agent.bus.add_arc(x);
}
let lcfg = cfg.lsp.clone().unwrap_or_default();
let mut servers = hx_lens::manager::default_servers();
servers.retain(|s| !lcfg.disable.contains(&s.id) && !lcfg.servers.iter().any(|o| o.id == s.id));
@@ -353,6 +377,14 @@ async fn main() -> Result<()> {
.collect();
mgr.warm(probe).await;
}
if cli.mode == Mode::Rpc {
let r = rpc::serve(agent, abort).await;
mgr.shutdown().await;
return r;
}
if cli.mode == Mode::Json && cli.print.is_none() {
anyhow::bail!("--mode json needs -p <prompt>");
}
let Some(prompt) = cli.print else {
hx_tui::run(hx_tui::Setup {
agent,
@@ -423,13 +455,23 @@ async fn main() -> Result<()> {
mgr.shutdown().await;
return Ok(());
};
agent.bus.add(Printer);
if cli.mode == Mode::Json {
agent.bus.add(rpc::Ndjson);
} else {
agent.bus.add(Printer);
}
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
abort.abort();
}
});
let r = agent.run(prompt).await;
if cli.mode == Mode::Json {
rpc::emit(
&serde_json::json!({"type": "done", "error": r.as_ref().err().map(|e| e.to_string()),
"usage": agent.usage, "session": path}),
);
}
let u = &agent.usage;
let cost = pricing(&agent.model)
.map(|p| format!(" ~${:.4}", u.cost(&p)))
+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(())
}