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, ToolCall { id: String, name: String, args: Value, }, ToolResult { id: String, name: String, args: Value, content: String, is_error: bool, }, TurnEnd, AgentEnd, RunEnd { aborted: bool, }, Stream(StreamEvent), Message(Message), Info(String), Injected(Vec), SubUsage(hx_ai::Usage), } impl Event { 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}), } } 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; fn guard(&self) -> Option { None } } #[derive(Default, Clone)] pub struct Bus { hooks: Arc>>>, } #[derive(Debug, Default, PartialEq)] pub struct Outcome { pub blocked: Option, pub args: Option, pub inject: Vec, } impl Bus { pub fn add_arc(&mut self, h: Arc) -> &mut Self { self.hooks .write() .unwrap_or_else(|e| e.into_inner()) .push(h); self } pub fn add(&mut self, h: impl Hook + 'static) -> &mut Self { self.add_arc(Arc::new(h)) } pub fn guards(&self) -> (usize, bool) { let hooks = self.hooks.read().unwrap_or_else(|e| e.into_inner()); let g: Vec = hooks.iter().filter_map(|h| h.guard()).collect(); (g.len(), g.iter().all(|a| *a)) } pub async fn emit(&self, ev: Event) -> Outcome { let mut ev = ev; let mut o = Outcome::default(); let hooks = self.hooks.read().unwrap_or_else(|e| e.into_inner()).clone(); for h in &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()); } }