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(())
}
+1 -1
View File
@@ -11,7 +11,7 @@ hx-ai = { version = "0.1.0", path = "../hx-ai" }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
thiserror = "2.0.21"
tokio = { version = "1.53.1", features = ["rt", "sync", "time", "macros", "fs"] }
tokio = { version = "1.53.1", features = ["rt", "sync", "time", "macros", "fs", "process", "io-util"] }
[lints]
workspace = true
+10 -1
View File
@@ -266,9 +266,18 @@ impl Agent {
.await;
match o.blocked {
Some(r) => {
let content = format!("blocked: {r}");
self.emit(Event::ToolResult {
id: id.clone(),
name: name.clone(),
args: args.clone(),
content: content.clone(),
is_error: true,
})
.await;
results[i] = Some(ContentBlock::ToolResult {
tool_use_id: id.clone(),
content: format!("blocked: {r}"),
content,
is_error: true,
})
}
+285
View File
@@ -0,0 +1,285 @@
//! Subprocess extensions: an external program speaks newline-delimited JSON-RPC 2.0 over stdio.
//!
//! Handshake: hx sends `initialize {protocolVersion, cwd}`; the extension replies
//! `{subscribe: [event types], tools: [{name, description, inputSchema}]}`.
//! Per subscribed event hx sends `event {event}` (request, `id`); reply `{action: "continue" | "block" |
//! "mutate" | "inject", reason?, args?, text?}`. Tool calls: `tool/call {name, args}` -> `{content, is_error}`.
//! A dead or slow extension never blocks the agent: errors and timeouts count as `continue`.
use crate::hook::{Event, Hook, HookAction};
use crate::tool::{Tool, ToolCtx, ToolResult};
use async_trait::async_trait;
use hx_ai::ToolSpec;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::{Mutex, oneshot};
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
pub struct ExtCfg {
pub command: Vec<String>,
/// per-request timeout in seconds (default 10; tool calls get 10x)
#[serde(default)]
pub timeout_secs: Option<u64>,
}
type Pending = Arc<Mutex<HashMap<i64, oneshot::Sender<Value>>>>;
pub struct Extension {
pub name: String,
stdin: Mutex<tokio::process::ChildStdin>,
pending: Pending,
next: AtomicI64,
alive: Arc<AtomicBool>,
timeout: Duration,
pub subscribe: Vec<String>,
pub tools: Vec<ToolSpec>,
_child: tokio::process::Child,
}
impl Extension {
pub async fn start(cfg: &ExtCfg, cwd: &std::path::Path) -> Result<Arc<Self>, String> {
let (bin, args) = cfg.command.split_first().ok_or("empty extension command")?;
let mut child = tokio::process::Command::new(bin)
.args(args)
.current_dir(cwd)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.kill_on_drop(true)
.spawn()
.map_err(|e| format!("spawn {bin}: {e}"))?;
let stdin = child.stdin.take().ok_or("no stdin")?;
let stdout = child.stdout.take().ok_or("no stdout")?;
let pending: Pending = Default::default();
let alive = Arc::new(AtomicBool::new(true));
let (p, a) = (pending.clone(), alive.clone());
tokio::spawn(async move {
let mut lines = BufReader::new(stdout).lines();
while let Ok(Some(l)) = lines.next_line().await {
let Ok(m) = serde_json::from_str::<Value>(&l) else {
continue;
};
if let Some(id) = m["id"].as_i64()
&& let Some(tx) = p.lock().await.remove(&id)
{
let _ = tx.send(m);
}
}
a.store(false, Ordering::SeqCst);
p.lock().await.clear();
});
let mut ext = Self {
name: std::path::Path::new(bin)
.file_name()
.map_or(bin.clone(), |n| n.to_string_lossy().into_owned()),
stdin: Mutex::new(stdin),
pending,
next: AtomicI64::new(1),
alive,
timeout: Duration::from_secs(cfg.timeout_secs.unwrap_or(10)),
subscribe: vec![],
tools: vec![],
_child: child,
};
let r = ext
.request(
"initialize",
json!({"protocolVersion": 1, "cwd": cwd}),
ext.timeout,
)
.await?;
ext.subscribe = r["subscribe"]
.as_array()
.into_iter()
.flatten()
.filter_map(|v| v.as_str().map(String::from))
.collect();
ext.tools = r["tools"]
.as_array()
.into_iter()
.flatten()
.map(|t| ToolSpec {
name: t["name"].as_str().unwrap_or_default().into(),
description: t["description"].as_str().unwrap_or_default().into(),
input_schema: t["inputSchema"].clone(),
})
.filter(|t| !t.name.is_empty())
.collect();
Ok(Arc::new(ext))
}
async fn request(
&self,
method: &str,
params: Value,
timeout: Duration,
) -> Result<Value, String> {
if !self.alive.load(Ordering::SeqCst) {
return Err(format!("extension {} exited", self.name));
}
let id = self.next.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = oneshot::channel();
self.pending.lock().await.insert(id, tx);
let mut b =
serde_json::to_vec(&json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}))
.map_err(|e| e.to_string())?;
b.push(b'\n');
{
let mut w = self.stdin.lock().await;
w.write_all(&b).await.map_err(|e| e.to_string())?;
w.flush().await.map_err(|e| e.to_string())?;
}
let m = match tokio::time::timeout(timeout, rx).await {
Ok(Ok(m)) => m,
Ok(Err(_)) => return Err(format!("extension {} exited", self.name)),
Err(_) => {
self.pending.lock().await.remove(&id);
return Err(format!("extension {}: {method} timed out", self.name));
}
};
match m.get("error") {
Some(e) => Err(format!("extension {}: {}", self.name, e["message"])),
None => Ok(m["result"].clone()),
}
}
/// Proxy tools for registration; the extension itself goes on the bus via `Bus::add_arc`.
pub fn tools(self: &Arc<Self>) -> Vec<ExtTool> {
self.tools
.iter()
.map(|t| ExtTool {
ext: self.clone(),
spec: t.clone(),
})
.collect()
}
}
#[async_trait]
impl Hook for Extension {
async fn on(&self, ev: &Event) -> HookAction {
if !self.subscribe.iter().any(|s| s == ev.kind() || s == "*") {
return HookAction::Continue;
}
let r = match self
.request("event", json!({"event": ev.to_json()}), self.timeout)
.await
{
Ok(r) => r,
Err(e) => {
eprintln!("[ext] {e}");
return HookAction::Continue;
}
};
match r["action"].as_str() {
Some("block") => HookAction::Block(
r["reason"]
.as_str()
.map_or_else(|| format!("blocked by {}", self.name), String::from),
),
Some("mutate") if r["args"].is_object() => HookAction::Mutate(r["args"].clone()),
Some("inject") => r["text"]
.as_str()
.map_or(HookAction::Continue, |t| HookAction::Inject(t.into())),
_ => HookAction::Continue,
}
}
}
pub struct ExtTool {
ext: Arc<Extension>,
spec: ToolSpec,
}
#[async_trait]
impl Tool for ExtTool {
fn spec(&self) -> ToolSpec {
self.spec.clone()
}
async fn call(&self, args: Value, _: &ToolCtx) -> ToolResult {
match self
.ext
.request(
"tool/call",
json!({"name": self.spec.name, "args": args}),
self.ext.timeout * 10,
)
.await
{
Ok(r) => ToolResult {
content: r["content"].as_str().unwrap_or_default().into(),
is_error: r["is_error"].as_bool().unwrap_or(false),
},
Err(e) => ToolResult::err(e),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const EXT: &str = r#"
import json, sys
for line in sys.stdin:
m = json.loads(line); p = m.get("params") or {}
if m["method"] == "initialize":
r = {"subscribe": ["tool_call"], "tools": [{"name": "shout", "description": "upper-case",
"inputSchema": {"type": "object", "properties": {"s": {"type": "string"}}, "required": ["s"]}}]}
elif m["method"] == "event":
e = p["event"]
if e["name"] == "bash" and "rm -rf" in e["args"].get("cmd", ""):
r = {"action": "block", "reason": "no rm -rf"}
elif e["name"] == "bash":
r = {"action": "mutate", "args": {"cmd": e["args"]["cmd"] + " # ext"}}
else:
r = {"action": "continue"}
elif m["method"] == "tool/call":
r = {"content": p["args"]["s"].upper(), "is_error": False}
print(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}), flush=True)
"#;
#[tokio::test]
async fn blocks_mutates_and_serves_tools() {
let d = tempfile::tempdir().unwrap();
let f = d.path().join("ext.py");
std::fs::write(&f, EXT).unwrap();
let cfg = ExtCfg {
command: vec!["python3".into(), f.to_string_lossy().into()],
timeout_secs: None,
};
let e = Extension::start(&cfg, d.path()).await.unwrap();
assert_eq!(e.subscribe, ["tool_call"]);
let call = |cmd: &str| Event::ToolCall {
id: "1".into(),
name: "bash".into(),
args: json!({"cmd": cmd}),
};
assert_eq!(
e.on(&call("rm -rf /")).await,
HookAction::Block("no rm -rf".into())
);
assert_eq!(
e.on(&call("ls")).await,
HookAction::Mutate(json!({"cmd": "ls # ext"}))
);
assert_eq!(
e.on(&Event::TurnEnd).await,
HookAction::Continue,
"not subscribed"
);
let t = &e.tools()[0];
let cx = ToolCtx {
cwd: d.path().into(),
state: Default::default(),
};
assert_eq!(t.call(json!({"s": "hi"}), &cx).await, ToolResult::ok("HI"));
// dead extension: continue, tool errors
std::fs::write(&f, "import sys; sys.stdin.readline()").unwrap();
assert!(Extension::start(&cfg, d.path()).await.is_err());
}
}
+74
View File
@@ -33,6 +33,48 @@ pub enum Event {
Info(String),
}
impl Event {
/// Stable JSON form (NDJSON mode, RPC notifications, extensions). Schema: README "Event stream".
pub fn to_json(&self) -> Value {
use serde_json::json;
match self {
Event::SessionStart => json!({"type": "session_start"}),
Event::TurnStart => json!({"type": "turn_start"}),
Event::ToolCall { id, name, args } => {
json!({"type": "tool_call", "id": id, "name": name, "args": args})
}
Event::ToolResult {
id,
name,
args,
content,
is_error,
} => json!({"type": "tool_result", "id": id, "name": name, "args": args,
"content": content, "is_error": is_error}),
Event::TurnEnd => json!({"type": "turn_end"}),
Event::AgentEnd => json!({"type": "agent_end"}),
Event::Stream(e) => json!({"type": "stream", "event": e}),
Event::Message(m) => json!({"type": "message", "message": m}),
Event::Info(t) => json!({"type": "info", "text": t}),
}
}
/// `type` of `to_json`, for subscriptions.
pub fn kind(&self) -> &'static str {
match self {
Event::SessionStart => "session_start",
Event::TurnStart => "turn_start",
Event::ToolCall { .. } => "tool_call",
Event::ToolResult { .. } => "tool_result",
Event::TurnEnd => "turn_end",
Event::AgentEnd => "agent_end",
Event::Stream(_) => "stream",
Event::Message(_) => "message",
Event::Info(_) => "info",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum HookAction {
Continue,
@@ -60,6 +102,10 @@ pub struct Outcome {
}
impl Bus {
pub fn add_arc(&mut self, h: Arc<dyn Hook>) -> &mut Self {
self.hooks.push(h);
self
}
pub fn add(&mut self, h: impl Hook + 'static) -> &mut Self {
self.hooks.push(Arc::new(h));
self
@@ -94,6 +140,34 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn event_json_schema() {
let e = Event::ToolCall {
id: "1".into(),
name: "bash".into(),
args: json!({"cmd": "ls"}),
};
assert_eq!(
e.to_json(),
json!({"type": "tool_call", "id": "1", "name": "bash", "args": {"cmd": "ls"}})
);
assert_eq!(e.kind(), "tool_call");
let s = Event::Stream(StreamEvent::TextDelta { text: "hi".into() });
assert_eq!(
s.to_json(),
json!({"type": "stream", "event": {"type": "text_delta", "text": "hi"}})
);
for ev in [
Event::SessionStart,
Event::TurnStart,
Event::TurnEnd,
Event::AgentEnd,
Event::Info("x".into()),
] {
assert_eq!(ev.to_json()["type"], ev.kind());
}
}
struct NoRm;
#[async_trait]
impl Hook for NoRm {
+1
View File
@@ -2,6 +2,7 @@
pub mod agent;
pub mod context;
pub mod ext;
pub mod hook;
pub mod session;
pub mod tool;