1 parent
cf8268d17b
commit
a01d0cbb5b
15 files changed
+723
-3
No files matched your search
@@ -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
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
pub mod agent;
|
||||
pub mod context;
|
||||
pub mod ext;
|
||||
pub mod hook;
|
||||
pub mod session;
|
||||
pub mod tool;
|
||||
|
||||
Reference in new issue
Block a user