From a01d0cbb5baffe3a123ea2a41ead54308f96d434 Mon Sep 17 00:00:00 2001 From: hermes Date: Wed, 30 Sep 2026 21:40:20 +0000 Subject: [PATCH] M7: json + rpc modes, subprocess extensions (closes #52 #53 #54) --- .gitea/workflows/ci.yml | 1 + Cargo.lock | 1 + README.md | 40 +++++ crates/hx-cli/Cargo.toml | 1 + crates/hx-cli/src/main.rs | 44 +++++- crates/hx-cli/src/rpc.rs | 137 +++++++++++++++++ crates/hx-core/Cargo.toml | 2 +- crates/hx-core/src/agent.rs | 11 +- crates/hx-core/src/ext.rs | 285 ++++++++++++++++++++++++++++++++++++ crates/hx-core/src/hook.rs | 74 ++++++++++ crates/hx-core/src/lib.rs | 1 + examples/ext_guard.py | 32 ++++ examples/rpc_client.py | 38 +++++ tests/all.sh | 1 + tests/m7_e2e.sh | 58 ++++++++ 15 files changed, 723 insertions(+), 3 deletions(-) create mode 100644 crates/hx-cli/src/rpc.rs create mode 100644 crates/hx-core/src/ext.rs create mode 100644 examples/ext_guard.py create mode 100644 examples/rpc_client.py create mode 100644 tests/m7_e2e.sh diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 3767ee6..22f3451 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -18,3 +18,4 @@ jobs: - run: sh tests/m5_e2e.sh - run: sh tests/m6_e2e.sh - run: python3 tests/tui_lspinstall.py + - run: sh tests/m7_e2e.sh diff --git a/Cargo.lock b/Cargo.lock index e4762b1..536f165 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -990,6 +990,7 @@ dependencies = [ "hx-tools", "hx-tui", "serde", + "serde_json", "tokio", "toml", ] diff --git a/README.md b/README.md index ea3061b..ddb532a 100644 --- a/README.md +++ b/README.md @@ -116,3 +116,43 @@ poor proxy (context7: 2 tools, 1.1k tokens), the eager rule is schema size, not `hx mcp-serve` runs hx as a stdio MCP server exposing the `lsp` tool (diagnostics, definition, references, hover, symbols) to other clients. + +## Machine interfaces + +### Event stream (`hx -p "..." --mode json`) + +One JSON object per line on stdout. `type` is one of: + +| type | fields | +|---|---| +| `session_start`, `turn_start`, `turn_end`, `agent_end` | none | +| `stream` | `event`: `{type: "text_delta", text}` · `{type: "thinking_delta", text}` · `{type: "tool_use_start", id, name}` · `{type: "done", message, stop, usage}` | +| `message` | `message`: `{role, content: [{type: "text", text} \| {type: "tool_use", id, name, input} \| {type: "tool_result", tool_use_id, content, is_error}]}` | +| `tool_call` | `id`, `name`, `args` | +| `tool_result` | `id`, `name`, `args`, `content`, `is_error` (blocked calls: `is_error: true`, content `blocked: `) | +| `info` | `text` | +| `done` (last line) | `error` (null on success), `usage`, `session` | + +### RPC (`hx --mode rpc`) + +JSON-RPC 2.0, one message per line on stdin/stdout. Events arrive as `event` notifications (params = the +event object above). Methods: `prompt {text}` (replies `{message, usage}` when the run ends), `abort`, +`state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`. One prompt at a time; other +methods are rejected while it runs (except `abort`). Example client: `examples/rpc_client.py`. + +### Extensions + +```toml +# ~/.hx/config.toml or .hx/config.toml (lists are concatenated) +[[extensions]] +command = ["python3", "/path/to/ext_guard.py", "rm -rf"] +timeout_secs = 10 +``` + +An extension is a process speaking JSON-RPC over stdio. hx sends `initialize {protocolVersion, cwd}`; the +reply `{subscribe: ["tool_call", ...] | ["*"], tools: [{name, description, inputSchema}]}` picks events and +registers tools. Each subscribed event is sent as `event {event}`; reply `{action: "continue"}`, +`{action: "block", reason}` (tool_call), `{action: "mutate", args}` (tool_call) or +`{action: "inject", text}` (turn_end / agent_end). Tools are called as `tool/call {name, args}` -> +`{content, is_error}`. Errors and timeouts count as `continue`; extensions run before the lens. +Sample: `examples/ext_guard.py`. diff --git a/crates/hx-cli/Cargo.toml b/crates/hx-cli/Cargo.toml index 78f2980..543f40e 100644 --- a/crates/hx-cli/Cargo.toml +++ b/crates/hx-cli/Cargo.toml @@ -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] diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 64aac14..ee482c8 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -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, lsp: Option, + /// subprocess extensions (JSON-RPC over stdio); global and project lists are concatenated + extensions: Vec, } #[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 "); + } 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))) diff --git a/crates/hx-cli/src/rpc.rs b/crates/hx-cli/src/rpc.rs new file mode 100644 index 0000000..563dc65 --- /dev/null +++ b/crates/hx-cli/src/rpc.rs @@ -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) { + 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::>(), + })), + "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(()) +} diff --git a/crates/hx-core/Cargo.toml b/crates/hx-core/Cargo.toml index e8bc561..089563c 100644 --- a/crates/hx-core/Cargo.toml +++ b/crates/hx-core/Cargo.toml @@ -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 diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 8fa7e1d..a3bb18e 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -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, }) } diff --git a/crates/hx-core/src/ext.rs b/crates/hx-core/src/ext.rs new file mode 100644 index 0000000..9e9b257 --- /dev/null +++ b/crates/hx-core/src/ext.rs @@ -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, + /// per-request timeout in seconds (default 10; tool calls get 10x) + #[serde(default)] + pub timeout_secs: Option, +} + +type Pending = Arc>>>; + +pub struct Extension { + pub name: String, + stdin: Mutex, + pending: Pending, + next: AtomicI64, + alive: Arc, + timeout: Duration, + pub subscribe: Vec, + pub tools: Vec, + _child: tokio::process::Child, +} + +impl Extension { + pub async fn start(cfg: &ExtCfg, cwd: &std::path::Path) -> Result, 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::(&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 { + 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) -> Vec { + 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, + 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()); + } +} diff --git a/crates/hx-core/src/hook.rs b/crates/hx-core/src/hook.rs index a94c4ff..21998c7 100644 --- a/crates/hx-core/src/hook.rs +++ b/crates/hx-core/src/hook.rs @@ -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) -> &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 { diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index 42cd3d3..c915307 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -2,6 +2,7 @@ pub mod agent; pub mod context; +pub mod ext; pub mod hook; pub mod session; pub mod tool; diff --git a/examples/ext_guard.py b/examples/ext_guard.py new file mode 100644 index 0000000..72cb511 --- /dev/null +++ b/examples/ext_guard.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Sample hx extension (stdio JSON-RPC). Blocks bash commands matching a pattern and adds a `now` tool. + +~/.hx/config.toml: + [[extensions]] + command = ["python3", "/path/to/ext_guard.py", "rm -rf"] +""" +import json, sys, time + +deny = sys.argv[1] if len(sys.argv) > 1 else "rm -rf" + +for line in sys.stdin: + m = json.loads(line) + p = m.get("params") or {} + meth = m.get("method") + if meth == "initialize": + r = {"subscribe": ["tool_call"], + "tools": [{"name": "now", "description": "Current unix time", + "inputSchema": {"type": "object", "properties": {}}}]} + elif meth == "event": + e = p["event"] + cmd = e["args"].get("command") or e["args"].get("cmd") or "" + if e["name"].lower() == "bash" and deny in cmd: + r = {"action": "block", "reason": f"ext_guard: `{deny}` is not allowed"} + else: + r = {"action": "continue"} + elif meth == "tool/call": + r = {"content": str(int(time.time())), "is_error": False} + else: + print(json.dumps({"jsonrpc": "2.0", "id": m.get("id"), "error": {"code": -32601, "message": "unknown"}}), flush=True) + continue + print(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}), flush=True) diff --git a/examples/rpc_client.py b/examples/rpc_client.py new file mode 100644 index 0000000..ad05165 --- /dev/null +++ b/examples/rpc_client.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Minimal client for `hx --mode rpc`: sends a prompt, prints streamed text, then session state. +Usage: python3 examples/rpc_client.py [hx-binary] "prompt" +""" +import json, subprocess, sys + +hx = sys.argv[1] if len(sys.argv) > 2 else "hx" +p = subprocess.Popen([hx, "--mode", "rpc"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) +nid = 0 + + +def call(method, params=None): + global nid + nid += 1 + p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": nid, "method": method, "params": params or {}}) + "\n") + p.stdin.flush() + while True: + m = json.loads(p.stdout.readline()) + if m.get("method") == "event": + e = m["params"] + if e["type"] == "stream" and e["event"]["type"] == "text_delta": + print(e["event"]["text"], end="", flush=True) + elif e["type"] == "tool_call": + print(f"\n> {e['name']} {json.dumps(e['args'])[:80]}", flush=True) + continue + if m.get("id") == nid: + if "error" in m: + raise SystemExit(f"{method}: {m['error']['message']}") + return m["result"] + + +r = call("prompt", {"text": sys.argv[-1]}) +print() +s = call("state") +print(f"STATE messages={s['messages']} model={s['model']} tools={len(s['tools'])}") +print(f"BUSY_CHECK {call('set_model', {'model': 'claude-x'})['model']}") +p.stdin.close() +p.wait(timeout=30) diff --git a/tests/all.sh b/tests/all.sh index a314af0..a72230d 100755 --- a/tests/all.sh +++ b/tests/all.sh @@ -18,3 +18,4 @@ sh tests/m4_e2e.sh sh tests/m5_e2e.sh sh tests/m6_e2e.sh python3 tests/tui_lspinstall.py | grep -q FAIL && { echo "tui lsp install FAIL"; exit 1; } || echo "tui lsp install ok" +sh tests/m7_e2e.sh diff --git a/tests/m7_e2e.sh b/tests/m7_e2e.sh new file mode 100644 index 0000000..90619cc --- /dev/null +++ b/tests/m7_e2e.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# M7 e2e: --mode json emits NDJSON events; examples/rpc_client.py drives a session over --mode rpc; +# examples/ext_guard.py (extension) blocks a bash call and provides a tool. +set -eu +root=$(cd "$(dirname "$0")/.." && pwd) +tmp=$(mktemp -d) +trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT +mkdir -p "$tmp/home/.hx" "$tmp/repo" +echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json" +printf '[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml" +cd "$tmp/repo" +export HOME="$tmp/home" +start() { + port=$((20000 + ($$ + $1) % 20000)) + python3 "$root/tests/fake_anthropic.py" $port & srv=$! + export HX_BASE_URL="http://127.0.0.1:$port" + sleep 0.5 +} +fail() { echo "FAIL: $1"; cat "$2"; exit 1; } + +# 1) json mode: every line parses; tool_call, tool_result, text and done are present +start 1 +"$root/target/debug/hx" -p "go" --mode json > "$tmp/json" 2> "$tmp/err" || fail "json run" "$tmp/err" +python3 - "$tmp/json" <<'PY' || fail "ndjson schema" "$tmp/json" +import json, sys +ev = [json.loads(l) for l in open(sys.argv[1])] +types = [e["type"] for e in ev] +assert types[-1] == "done" and ev[-1]["error"] is None, ev[-1] +for t in ["turn_start", "stream", "message", "tool_call", "tool_result", "turn_end"]: + assert t in types, t +assert any(e["type"] == "stream" and e["event"]["type"] == "text_delta" for e in ev) +assert any(e["type"] == "tool_result" and "hi from hx" in e["content"] for e in ev) +PY +kill $srv; rm -f hello.txt + +# 2) rpc mode driven by the example client +start 2 +python3 "$root/examples/rpc_client.py" "$root/target/debug/hx" "go" > "$tmp/rpc" 2> "$tmp/err" || fail "rpc" "$tmp/err" +grep -q "Done: file says hi from hx." "$tmp/rpc" || fail "rpc text" "$tmp/rpc" +grep -q "> bash" "$tmp/rpc" || fail "rpc events" "$tmp/rpc" +grep -q "STATE messages=6 " "$tmp/rpc" || fail "rpc state" "$tmp/rpc" +grep -q "BUSY_CHECK claude-x" "$tmp/rpc" || fail "rpc set_model" "$tmp/rpc" +kill $srv; rm -f hello.txt + +# 3) extension blocks the bash call (cat) and registers its tool +start 3 +printf '[[extensions]]\ncommand = ["python3", "%s/examples/ext_guard.py", "cat hello"]\n' "$root" >> "$tmp/home/.hx/config.toml" +"$root/target/debug/hx" -p "go" --mode json > "$tmp/ext" 2> "$tmp/err" || fail "ext run" "$tmp/err" +python3 - "$tmp/ext" <<'PY' || fail "ext block" "$tmp/ext" +import json, sys +ev = [json.loads(l) for l in open(sys.argv[1])] +log = json.dumps(ev) +assert "blocked: ext_guard: `cat hello` is not allowed" in log, "no block" +bash = [e for e in ev if e["type"] == "tool_result" and e["name"] == "bash"] +assert len(bash) == 1 and bash[0]["is_error"] and bash[0]["content"].startswith("blocked:"), bash +PY +curl -s "$HX_BASE_URL/" | grep -q '"name": "now"' || { echo "FAIL: ext tool not offered"; exit 1; } +echo "m7 e2e ok"