The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(hooks): move hook engine to tinyagents_hooks crate
Steven Enamakel797132dfdb71
diff --git a/crates/openhuman-core/src/hooks/bridge.rs b/crates/openhuman-core/src/hooks/bridge.rsdeleted file mode 100644index 9f72f2dbf3..0000000000--- a/crates/openhuman-core/src/hooks/bridge.rs+++ /dev/null@@ -1,373 +0,0 @@-//! Wiring the configured hooks into the agent harness.-//!-//! The harness already carries in-process hook seams —-//! [`ToolHook`](crate::agent::hooks::ToolHook) around every tool and-//! [`PostTurnHook`](crate::agent::hooks::PostTurnHook) after every-//! turn. Rather than adding a second set of call sites, the configurable engine-//! registers itself *through* those seams. One bridge object, registered once-//! at bootstrap, turns every configured `hooks.json` entry into behaviour.-//!-//! ## Derived events-//!-//! Cursor exposes `beforeShellExecution`, `beforeReadFile` and `afterFileEdit`-//! as first-class events. In OpenHuman those moments are not separate call-//! sites — they are the `shell`, `file_read` and `file_write`/`edit` tools-//! going through the ordinary tool seam. So the bridge *derives* them: when a-//! tool call matches one of those families it fires both the generic-//! `preToolUse` event and the specialised one, with a payload shaped the way a-//! Cursor hook expects (a command line, a file path) rather than raw tool-//! arguments.-//!-//! This is what makes a Cursor hook script portable here. The alternative —-//! only exposing `preToolUse` and telling authors to parse `tool_input` — would-//! have been less code and a worse contract: every author would reimplement the-//! same mapping, and each would get the sandbox flag and the path resolution-//! subtly differently.--use async_trait::async_trait;-use serde_json::Value;--use crate::agent::hooks::{PostTurnHook, ToolHook, ToolHookContext, ToolHookDecision, TurnContext};--use tinyagents_runtime::command_hooks::context::{build_input, TurnIdentity};-use tinyagents_runtime::command_hooks::engine::HookOutcome;-use tinyagents_runtime::command_hooks::types::{- FileEdit, FilePayload, HookEvent, HookOutput, HookPayload, ShellPayload, StopPayload,- TextPayload, ToolPayload,-};--/// Name the bridge registers itself under, so a host that rebuilds its core can-/// replace rather than duplicate it.-pub const BRIDGE_HOOK_NAME: &str = "configured_hooks";--/// Tools whose calls are also reported as shell execution.-const SHELL_TOOLS: &[&str] = &["shell", "run_command", "bash"];--/// Tools whose calls are also reported as a file read.-const READ_TOOLS: &[&str] = &["file_read", "read_diff"];--/// Tools whose calls are also reported as a file edit.-const WRITE_TOOLS: &[&str] = &["file_write", "edit", "apply_patch", "update_memory_md"];--/// Bridges the configured hook engine onto the harness hook seams.-#[derive(Debug, Default, Clone, Copy)]-pub struct ConfiguredHookBridge;--impl ConfiguredHookBridge {- /// Register the bridge for every subsequently-created session.- ///- /// Replaces any previously registered bridge rather than appending, so a- /// host that rebuilds its core does not end up firing every hook twice.- pub fn install() {- crate::agent::hooks::replace_embedder_tool_hook(- BRIDGE_HOOK_NAME,- Some(std::sync::Arc::new(ConfiguredHookBridge)),- );- crate::agent::hooks::replace_embedder_post_turn_hook(- BRIDGE_HOOK_NAME,- Some(std::sync::Arc::new(ConfiguredHookBridge)),- );- log::debug!("[hooks] configured-hook bridge installed");- }-- /// Remove the bridge. Used when hooks are disabled by config.- pub fn uninstall() {- crate::agent::hooks::replace_embedder_tool_hook(BRIDGE_HOOK_NAME, None);- crate::agent::hooks::replace_embedder_post_turn_hook(BRIDGE_HOOK_NAME, None);- log::debug!("[hooks] configured-hook bridge removed");- }-}--fn identity_from_tool(context: &ToolHookContext) -> TurnIdentity {- TurnIdentity {- session_id: context.session_id.clone(),- agent_id: context.agent_id.clone(),- cwd: context- .cwd- .as_ref()- .map(|cwd| cwd.to_string_lossy().into_owned()),- ..TurnIdentity::default()- }-}--fn string_field(value: &Value, key: &str) -> Option<String> {- value- .get(key)- .and_then(Value::as_str)- .map(str::to_string)- .filter(|text| !text.is_empty())-}--fn tool_payload(context: &ToolHookContext) -> ToolPayload {- ToolPayload {- tool_name: context.tool_name.clone(),- tool_input: context.arguments.clone(),- tool_use_id: context.call_id.clone(),- tool_output: context.output.clone(),- duration_ms: context.duration_ms,- error_message: context.error.clone(),- failure_type: context.error.as_deref().map(classify_failure),- }-}--/// Map a raw failure string onto Cursor's three failure classes.-fn classify_failure(error: &str) -> String {- let lower = error.to_lowercase();- if lower.contains("timed out") || lower.contains("timeout") {- "timeout".to_string()- } else if lower.contains("policy-blocked")- || lower.contains("permission")- || lower.contains("denied")- {- "permission_denied".to_string()- } else {- "error".to_string()- }-}--/// Which specialised event, if any, this tool also represents.-fn derived_event(tool_name: &str, pre: bool) -> Option<HookEvent> {- let name = tool_name.to_ascii_lowercase();- if SHELL_TOOLS.contains(&name.as_str()) {- return Some(if pre {- HookEvent::BeforeShellExecution- } else {- HookEvent::AfterShellExecution- });- }- if READ_TOOLS.contains(&name.as_str()) {- // There is no `afterReadFile`; a read only has a gating moment.- return pre.then_some(HookEvent::BeforeReadFile);- }- if WRITE_TOOLS.contains(&name.as_str()) {- // A write is only reported once it happened — denying it belongs to- // `preToolUse`, which already fired with the same arguments.- return (!pre).then_some(HookEvent::AfterFileEdit);- }- if is_mcp_tool(&name) {- return Some(if pre {- HookEvent::BeforeMcpExecution- } else {- HookEvent::AfterMcpExecution- });- }- None-}--/// MCP tools reach the registry through the `mcp_*` families; a dynamically-/// installed server's tools are namespaced with `mcp:`.-fn is_mcp_tool(name: &str) -> bool {- name.starts_with("mcp_") || name.starts_with("mcp:") || name.starts_with("mcp__")-}--/// Build the payload the specialised event expects from raw tool arguments.-fn derived_payload(event: HookEvent, context: &ToolHookContext) -> HookPayload {- match event {- HookEvent::BeforeShellExecution | HookEvent::AfterShellExecution => {- HookPayload::Shell(ShellPayload {- command: string_field(&context.arguments, "command").unwrap_or_default(),- sandbox: context- .arguments- .get("sandbox")- .and_then(Value::as_bool)- .unwrap_or(false),- output: context.output.clone(),- duration_ms: context.duration_ms,- })- }- HookEvent::BeforeReadFile => HookPayload::File(FilePayload {- file_path: file_path_argument(&context.arguments),- edits: Vec::new(),- }),- HookEvent::AfterFileEdit => HookPayload::File(FilePayload {- file_path: file_path_argument(&context.arguments),- edits: file_edits(&context.arguments),- }),- _ => HookPayload::Tool(tool_payload(context)),- }-}--/// The file tools spell their path argument three different ways; a hook author-/// should not have to know which tool used which.-fn file_path_argument(arguments: &Value) -> String {- ["path", "file_path", "filename", "file"]- .iter()- .find_map(|key| string_field(arguments, key))- .unwrap_or_default()-}--/// Recover the before/after strings an edit applied, where the tool exposes-/// them. A whole-file write reports one edit whose `old_string` is empty.-fn file_edits(arguments: &Value) -> Vec<FileEdit> {- if let (Some(old), Some(new)) = (- string_field(arguments, "old_string"),- string_field(arguments, "new_string"),- ) {- return vec![FileEdit {- old_string: old,- new_string: new,- }];- }- match string_field(arguments, "content") {- Some(content) => vec![FileEdit {- old_string: String::new(),- new_string: content,- }],- None => Vec::new(),- }-}--/// Fire the generic event and, when the tool has one, its specialisation.-async fn dispatch_pair(- generic: HookEvent,- context: &ToolHookContext,- identity: TurnIdentity,-) -> HookOutcome {- let engine = super::host::engine();- let mut merged = HookOutcome::default();-- if engine.has_hooks(generic).await {- let input = build_input(- generic,- identity.clone(),- HookPayload::Tool(tool_payload(context)),- );- let outcome = engine.dispatch(generic, input).await;- merged.output.merge(outcome.output);- merged.runs.extend(outcome.runs);- }- if merged.output.is_deny() {- return merged;- }-- let pre = matches!(- generic,- HookEvent::PreToolUse | HookEvent::BeforeMcpExecution | HookEvent::BeforeReadFile- );- if let Some(event) = derived_event(&context.tool_name, pre) {- if engine.has_hooks(event).await {- let input = build_input(event, identity, derived_payload(event, context));- let outcome = engine.dispatch(event, input).await;- merged.output.merge(outcome.output);- merged.runs.extend(outcome.runs);- }- }- merged-}--#[async_trait]-impl ToolHook for ConfiguredHookBridge {- fn name(&self) -> &str {- BRIDGE_HOOK_NAME- }-- async fn before_tool(&self, context: &ToolHookContext) -> anyhow::Result<()> {- match self.before_tool_decision(context).await {- ToolHookDecision::Deny(reason) => Err(anyhow::anyhow!(reason)),- _ => Ok(()),- }- }-- async fn after_tool(&self, context: &ToolHookContext) -> anyhow::Result<()> {- self.after_tool_context(context).await;- Ok(())- }-- async fn before_tool_decision(&self, context: &ToolHookContext) -> ToolHookDecision {- let identity = identity_from_tool(context);- let outcome = dispatch_pair(HookEvent::PreToolUse, context, identity).await;- decision_from(outcome.output, &context.tool_name)- }-- async fn after_tool_context(&self, context: &ToolHookContext) -> Option<String> {- let identity = identity_from_tool(context);- let generic = if context.success == Some(false) {- HookEvent::PostToolUseFailure- } else {- HookEvent::PostToolUse- };- let outcome = dispatch_pair(generic, context, identity).await;- outcome.output.additional_context- }-}--/// Translate a merged hook decision into the harness's tool verdict.-fn decision_from(output: HookOutput, tool_name: &str) -> ToolHookDecision {- if output.is_deny() {- let reason = output- .agent_message- .or(output.user_message)- .unwrap_or_else(|| format!("a configured hook denied {tool_name}"));- return ToolHookDecision::Deny(reason);- }- if output.is_ask() {- let reason = output- .user_message- .or(output.agent_message)- .unwrap_or_else(|| format!("a configured hook wants approval for {tool_name}"));- return ToolHookDecision::Ask(reason);- }- match output.updated_input {- Some(arguments) => ToolHookDecision::ProceedWith(arguments),- None => ToolHookDecision::Proceed,- }-}--#[async_trait]-impl PostTurnHook for ConfiguredHookBridge {- fn name(&self) -> &str {- BRIDGE_HOOK_NAME- }-- async fn on_turn_complete(&self, ctx: &TurnContext) -> anyhow::Result<()> {- let engine = super::host::engine();- let identity = TurnIdentity {- session_id: ctx.session_id.clone(),- agent_id: ctx.agent_id.clone(),- conversation_id: ctx.session_id.clone(),- ..TurnIdentity::default()- };-- if engine.has_hooks(HookEvent::AfterAgentResponse).await {- let input = build_input(- HookEvent::AfterAgentResponse,- identity.clone(),- HookPayload::Text(TextPayload {- text: ctx.assistant_response.clone(),- duration_ms: Some(ctx.turn_duration_ms),- }),- );- engine.dispatch(HookEvent::AfterAgentResponse, input).await;- }-- if engine.has_hooks(HookEvent::Stop).await {- let input = build_input(- HookEvent::Stop,- identity,- HookPayload::Stop(StopPayload {- status: "completed".to_string(),- loop_count: 0,- iteration_count: Some(ctx.iteration_count),- }),- );- let outcome = engine.dispatch(HookEvent::Stop, input).await;- if let Some(followup) = outcome.output.followup_message {- // The turn has already returned by the time a post-turn hook- // runs, so a follow-up cannot re-enter this turn. Publishing it- // lets the entrypoint that owns the conversation decide whether- // to start another one — the only layer that knows if there is- // still a user attached.- tinyagents_runtime::command_hooks::followup::publish(- ctx.session_id.clone(),- followup,- )- .await;- }- }- Ok(())- }-}--#[cfg(test)]-#[path = "bridge_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/hooks/bridge_tests.rs b/crates/openhuman-core/src/hooks/bridge_tests.rsdeleted file mode 100644index caf2a0ab86..0000000000--- a/crates/openhuman-core/src/hooks/bridge_tests.rs+++ /dev/null@@ -1,130 +0,0 @@-use super::*;--fn context(tool: &str, arguments: Value) -> ToolHookContext {- ToolHookContext {- event: crate::agent::hooks::ToolHookEvent::PreToolUse,- call_id: "call-1".into(),- tool_name: tool.into(),- arguments,- success: None,- duration_ms: None,- output: None,- error: None,- session_id: Some("sess-1".into()),- cwd: None,- agent_id: None,- }-}--#[test]-fn shell_tools_derive_shell_events() {- assert_eq!(- derived_event("shell", true),- Some(HookEvent::BeforeShellExecution)- );- assert_eq!(- derived_event("shell", false),- Some(HookEvent::AfterShellExecution)- );-}--#[test]-fn reads_have_no_after_event_and_writes_have_no_before_event() {- assert_eq!(- derived_event("file_read", true),- Some(HookEvent::BeforeReadFile)- );- assert_eq!(derived_event("file_read", false), None);- assert_eq!(derived_event("file_write", true), None);- assert_eq!(- derived_event("file_write", false),- Some(HookEvent::AfterFileEdit)- );-}--#[test]-fn mcp_tools_derive_mcp_events() {- assert_eq!(- derived_event("mcp_call_tool", true),- Some(HookEvent::BeforeMcpExecution)- );- assert_eq!(derived_event("memory_store", true), None);-}--#[test]-fn shell_payload_carries_the_command_line() {- let ctx = context("shell", serde_json::json!({"command": "rm -rf /tmp/x"}));- match derived_payload(HookEvent::BeforeShellExecution, &ctx) {- HookPayload::Shell(shell) => {- assert_eq!(shell.command, "rm -rf /tmp/x");- assert!(!shell.sandbox);- }- other => panic!("expected a shell payload, got {other:?}"),- }-}--#[test]-fn file_path_is_read_from_any_of_the_spellings() {- assert_eq!(- file_path_argument(&serde_json::json!({"file_path": "/a"})),- "/a"- );- assert_eq!(file_path_argument(&serde_json::json!({"path": "/b"})), "/b");- assert_eq!(file_path_argument(&serde_json::json!({})), "");-}--#[test]-fn whole_file_write_reports_one_edit_with_empty_old_string() {- let edits = file_edits(&serde_json::json!({"content": "hello"}));- assert_eq!(edits.len(), 1);- assert!(edits[0].old_string.is_empty());- assert_eq!(edits[0].new_string, "hello");-}--#[test]-fn denial_carries_the_agent_message() {- let decision = decision_from(HookOutput::deny("policy says no"), "shell");- match decision {- ToolHookDecision::Deny(reason) => assert_eq!(reason, "policy says no"),- other => panic!("expected a denial, got {other:?}"),- }-}--#[test]-fn updated_input_becomes_a_rewrite() {- let output = HookOutput {- updated_input: Some(serde_json::json!({"command": "ls"})),- ..HookOutput::default()- };- match decision_from(output, "shell") {- ToolHookDecision::ProceedWith(arguments) => {- assert_eq!(arguments["command"], "ls");- }- other => panic!("expected a rewrite, got {other:?}"),- }-}--#[test]-fn timeout_text_classifies_as_a_timeout_failure() {- assert_eq!(classify_failure("tool timed out after 30s"), "timeout");- assert_eq!(- classify_failure("[policy-blocked] nope"),- "permission_denied"- );- assert_eq!(classify_failure("something else"), "error");-}--#[test]-fn configured_hook_identity_uses_the_resolved_working_directory() {- let mut ctx = context("shell", serde_json::json!({"command": "pwd"}));- ctx.cwd = Some(std::path::PathBuf::from("/resolved/workspace"));- assert_eq!(- identity_from_tool(&ctx).cwd.as_deref(),- Some("/resolved/workspace")- );- ctx.arguments["cwd"] = serde_json::json!("relative/argument");- assert_eq!(- identity_from_tool(&ctx).cwd.as_deref(),- Some("/resolved/workspace")- );-}diff --git a/crates/openhuman-core/src/hooks/host.rs b/crates/openhuman-core/src/hooks/host.rsindex 8f9888595c..7a0797d347 100644--- a/crates/openhuman-core/src/hooks/host.rs+++ b/crates/openhuman-core/src/hooks/host.rs@@ -1,7 +1,7 @@//! The process-global hook engine and the OpenHuman seams it is built with.//!//! The engine, `hooks.json` contract and process runner live in-//! `tinyagents_runtime::command_hooks`. This module supplies what is specific+//! `tinyagents_hooks::command`. This module supplies what is specific//! to this host: the product name that decides discovery paths and the//! `OPENHUMAN_*` hook environment, the user's home directory, the platform//! shell, and the model behind `prompt` hooks.diff --git a/crates/openhuman-core/src/hooks/ops.rs b/crates/openhuman-core/src/hooks/ops.rsindex eb57246565..ac6ad45e8d 100644--- a/crates/openhuman-core/src/hooks/ops.rs+++ b/crates/openhuman-core/src/hooks/ops.rs@@ -34,7 +34,7 @@ pub async fn init(ctx: &DispatchCtx, config: &crate::config::schema::Config) {if !settings.enabled {crate::agent::hooks::replace_embedder_tool_hook("configured_hooks", None);super::host::engine()- .install(tinyagents_runtime::command_hooks::HookConfig::default())+ .install(tinyagents_hooks::command::tinyagents_hooks::command::HookConfig::default()).await;log::info!("[hooks] disabled by configuration");return;@@ -106,7 +106,7 @@ pub async fn session_ended(identity: TurnIdentity, reason: &str, duration_ms: Op}if let Some(session_id) = session_id {engine.forget_session(&session_id).await;- tinyagents_runtime::command_hooks::followup::forget(&session_id).await;+ tinyagents_hooks::command::followup::forget(&session_id).await;}}diff --git a/crates/openhuman-core/src/hooks/schemas.rs b/crates/openhuman-core/src/hooks/schemas.rsindex 287b558343..e8a5e7a987 100644--- a/crates/openhuman-core/src/hooks/schemas.rs+++ b/crates/openhuman-core/src/hooks/schemas.rs@@ -14,8 +14,8 @@ use serde_json::{json, Map, Value};use crate::core::all::{ControllerFuture, RegisteredController};use crate::core::{ControllerSchema, FieldSchema, TypeSchema};-use tinyagents_runtime::command_hooks::context::TurnIdentity;-use tinyagents_runtime::command_hooks::types::{HookEvent, HookPayload};+use tinyagents_hooks::command::context::TurnIdentity;+use tinyagents_hooks::command::types::{HookEvent, HookPayload};pub fn all_controller_schemas() -> Vec<ControllerSchema> {vec![schemas("list"), schemas("reload"), schemas("test")]@@ -135,7 +135,7 @@ fn handle_test(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutur).map_err(|error| format!("invalid payload for '{event}': {error}"))?;- let input = tinyagents_runtime::command_hooks::context::build_input(+ let input = tinyagents_hooks::command::context::build_input(event,TurnIdentity::default(),payload,@@ -160,7 +160,7 @@ fn handle_test(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutur}/// Render a config for the wire, naming the source file of every definition.-fn describe(config: &tinyagents_runtime::command_hooks::config::HookConfig) -> Value {+fn describe(config: &tinyagents_hooks::command::config::HookConfig) -> Value {let by_event: Map<String, Value> = config.by_event.iter()@@ -175,7 +175,7 @@ fn describe(config: &tinyagents_runtime::command_hooks::config::HookConfig) -> V"timeout": definition.timeout,"fail_closed": definition.fail_closed,"enabled": definition.enabled,- "layer": definition.layer.map(tinyagents_runtime::command_hooks::config::HookLayer::as_str),+ "layer": definition.layer.map(tinyagents_hooks::command::config::HookLayer::as_str),"source_dir": definition.source_dir.as_ref().map(|dir| dir.display().to_string()),})})diff --git a/crates/openhuman-core/src/hooks/shell.rs b/crates/openhuman-core/src/hooks/shell.rsindex 7fd8761a31..8b33c9e760 100644--- a/crates/openhuman-core/src/hooks/shell.rs+++ b/crates/openhuman-core/src/hooks/shell.rs@@ -1,6 +1,6 @@//! The shell that runs `command` hooks, as selected by TinyBox.//!-//! The hook engine (`tinyagents_runtime::command_hooks`) spawns the hook process+//! The hook engine (`tinyagents_hooks::command`) spawns the hook process//! itself and asks its host for a synchronous `fn(&str) -> Command`. The host//! does not choose the shell: it asks TinyBox's `SelectShell` once, at the async//! boundary where hooks are (re)loaded, and the factory only fills the hook's