Files
hx/crates/hx-core/src/hook.rs
T

225 lines
6.9 KiB
Rust

//! Event bus and hooks. Lens, MCP and extensions all plug in here.
use async_trait::async_trait;
use hx_ai::{Message, StreamEvent};
use serde_json::Value;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub enum Event {
SessionStart,
TurnStart,
/// Before a tool runs. `Block` or `Mutate` apply.
ToolCall {
id: String,
name: String,
args: Value,
},
ToolResult {
id: String,
name: String,
args: Value,
content: String,
is_error: bool,
},
/// After all tools of a turn ran. `Inject` adds a user message before the next request.
TurnEnd,
/// Model finished without tool calls. `Inject` makes the agent continue.
AgentEnd,
/// A run ended for any reason (done, error, abort). Fires after the last turn.
RunEnd {
aborted: bool,
},
/// Streaming output from the model (UI).
Stream(StreamEvent),
Message(Message),
/// Human-readable notice for the UI (compaction etc).
Info(String),
/// Text hooks injected at turn/agent end (lens reports etc), for display.
Injected(Vec<String>),
/// Tokens spent by subagents (`task` tool) in the tools just run; already added to `Agent::usage`.
SubUsage(hx_ai::Usage),
}
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::RunEnd { aborted } => json!({"type": "run_end", "aborted": aborted}),
Event::Stream(e) => json!({"type": "stream", "event": e}),
Event::Message(m) => json!({"type": "message", "message": m}),
Event::Info(t) => json!({"type": "info", "text": t}),
Event::Injected(t) => json!({"type": "injected", "texts": t}),
Event::SubUsage(u) => json!({"type": "sub_usage", "usage": u}),
}
}
/// `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::RunEnd { .. } => "run_end",
Event::Stream(_) => "stream",
Event::Message(_) => "message",
Event::Info(_) => "info",
Event::Injected(_) => "injected",
Event::SubUsage(_) => "sub_usage",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum HookAction {
Continue,
Block(String),
Mutate(Value),
Inject(String),
}
#[async_trait]
pub trait Hook: Send + Sync {
async fn on(&self, ev: &Event) -> HookAction;
}
#[derive(Default, Clone)]
pub struct Bus {
hooks: Vec<Arc<dyn Hook>>,
}
/// Aggregate outcome of dispatching one event to all hooks.
#[derive(Debug, Default, PartialEq)]
pub struct Outcome {
pub blocked: Option<String>,
pub args: Option<Value>,
pub inject: Vec<String>,
}
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
}
/// Hooks run in registration order. First `Block` wins; `Mutate` is visible to later hooks.
pub async fn emit(&self, ev: Event) -> Outcome {
let mut ev = ev;
let mut o = Outcome::default();
for h in &self.hooks {
match h.on(&ev).await {
HookAction::Continue => {}
HookAction::Block(r) => {
o.blocked = Some(r);
break;
}
HookAction::Mutate(v) => {
if let Event::ToolCall { args, .. } = &mut ev {
*args = v.clone();
o.args = Some(v);
}
}
HookAction::Inject(m) => o.inject.push(m),
}
}
o
}
}
#[cfg(test)]
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 {
async fn on(&self, ev: &Event) -> HookAction {
match ev {
Event::ToolCall { args, .. }
if args["cmd"].as_str().is_some_and(|c| c.contains("rm -rf")) =>
{
HookAction::Block("no".into())
}
Event::ToolCall { args, .. } if args["cmd"] == "ls" => {
HookAction::Mutate(json!({"cmd": "ls -la"}))
}
Event::TurnEnd => HookAction::Inject("diag".into()),
_ => HookAction::Continue,
}
}
}
#[tokio::test]
async fn block_mutate_inject() {
let mut b = Bus::default();
b.add(NoRm);
let call = |c: &str| Event::ToolCall {
id: "1".into(),
name: "bash".into(),
args: json!({"cmd": c}),
};
assert_eq!(
b.emit(call("rm -rf /")).await.blocked.as_deref(),
Some("no")
);
assert_eq!(
b.emit(call("ls")).await.args,
Some(json!({"cmd": "ls -la"}))
);
assert_eq!(b.emit(Event::TurnEnd).await.inject, ["diag"]);
assert_eq!(b.emit(Event::SessionStart).await, Outcome::default());
}
}