//! 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()); } }