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_runtime
Steven Enamakele6475c3a24cc
diff --git a/Cargo.lock b/Cargo.lockindex f2bea04cad..558415035c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6269,6 +6269,8 @@ version = "2.1.2"dependencies = ["async-trait","chrono",+ "regex",+ "serde","serde_json","thiserror 2.0.20","tinyagents-harness",diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rsindex 3714253817..b7d7c775f1 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs@@ -517,7 +517,7 @@ pub(crate) async fn run_subagent_direct(// forbids never reaches a user script, and before config load so a// denied spawn has no side effects at all.if let Err(reason) = crate::hooks::ops::subagent_starting(- crate::hooks::context::TurnIdentity {+ tinyagents_runtime::command_hooks::context::TurnIdentity {conversation_id: Some(parent.session_id.clone()),session_id: Some(parent.session_id.clone()),agent_id: Some(parent.agent_definition_id.clone()),diff --git a/crates/openhuman-core/src/hooks/bridge.rs b/crates/openhuman-core/src/hooks/bridge.rsindex d9e276be8d..fea902625b 100644--- a/crates/openhuman-core/src/hooks/bridge.rs+++ b/crates/openhuman-core/src/hooks/bridge.rs@@ -29,9 +29,9 @@ use serde_json::Value;use crate::agent::hooks::{PostTurnHook, ToolHook, ToolHookContext, ToolHookDecision, TurnContext};-use super::context::{build_input, TurnIdentity};-use super::engine::{self, HookOutcome};-use super::types::{+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,};@@ -220,7 +220,7 @@ async fn dispatch_pair(context: &ToolHookContext,identity: TurnIdentity,) -> HookOutcome {- let engine = engine::global();+ let engine = super::host::engine();let mut merged = HookOutcome::default();if engine.has_hooks(generic).await {@@ -317,7 +317,7 @@ impl PostTurnHook for ConfiguredHookBridge {}async fn on_turn_complete(&self, ctx: &TurnContext) -> anyhow::Result<()> {- let engine = engine::global();+ let engine = super::host::engine();let identity = TurnIdentity {session_id: ctx.session_id.clone(),agent_id: ctx.agent_id.clone(),@@ -354,7 +354,7 @@ impl PostTurnHook for ConfiguredHookBridge {// 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.- super::followup::publish(ctx.session_id.clone(), followup).await;+ tinyagents_runtime::command_hooks::followup::publish(ctx.session_id.clone(), followup).await;}}Ok(())diff --git a/crates/openhuman-core/src/hooks/host.rs b/crates/openhuman-core/src/hooks/host.rsnew file mode 100644index 0000000000..a88ff35429--- /dev/null+++ b/crates/openhuman-core/src/hooks/host.rs@@ -0,0 +1,39 @@+//! 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+//! 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.++use std::sync::{Arc, LazyLock};++use async_trait::async_trait;+use tinyagents_runtime::command_hooks::{HookEngine, HookEnvironment, PromptEvaluator};++/// Product name handed to the engine: `ProgramData\OpenHuman`,+/// `/Library/Application Support/OpenHuman`, `/etc/openhuman`, `.openhuman`,+/// and the `OPENHUMAN_*` hook variables all derive from it.+pub const PRODUCT_NAME: &str = "OpenHuman";++struct HostPromptEvaluator;++#[async_trait]+impl PromptEvaluator for HostPromptEvaluator {+ async fn evaluate(&self, instruction: &str, model: Option<&str>) -> Result<String, String> {+ super::prompt_eval::evaluate(instruction, model).await+ }+}++fn environment() -> HookEnvironment {+ HookEnvironment::new(PRODUCT_NAME, dirs::home_dir())+ .with_shell(crate::agent::platform_shell::build_tokio_command)+ .with_prompt_evaluator(Arc::new(HostPromptEvaluator))+}++static ENGINE: LazyLock<HookEngine> = LazyLock::new(|| HookEngine::new(environment()));++/// The process-global engine.+pub fn engine() -> &'static HookEngine {+ &ENGINE+}diff --git a/crates/openhuman-core/src/hooks/mod.rs b/crates/openhuman-core/src/hooks/mod.rsindex bb89b743f0..0cfbc8d6f4 100644--- a/crates/openhuman-core/src/hooks/mod.rs+++ b/crates/openhuman-core/src/hooks/mod.rs@@ -16,50 +16,23 @@//!//! | Module | Owns |//! | ------ | ---- |-//! | [`types`] | the wire contract: events, the stdin envelope, the decision object |-//! | [`config`] | `hooks.json` parsing and the four-layer merge |-//! | [`matcher`] | which occurrences of an event reach a given hook |-//! | [`exec`] | running one hook: stdin, timeout, exit codes, fail-open/closed |-//! | [`engine`] | selection, ordering, aggregation, session state |-//! | [`context`] | assembling the envelope from ambient host facts |+//! | `tinyagents_runtime::command_hooks` | the engine and the whole `hooks.json` contract: types, config, matcher, exec, engine, context, follow-ups |+//! | [`host`] | the process-global engine and its OpenHuman seams (product name, home, shell, prompt model) |//! | [`bridge`] | mounting the engine on the harness's existing tool/turn seams |//! | [`ops`] | the lifecycle moments that have no existing seam |-//! | [`followup`] | queueing what a `stop` hook asks for next |//!-//! ## Two rules worth knowing before changing anything here-//!-//! **The strictest verdict wins.** Layers concatenate rather than override, and-//! [`types::HookOutput::merge`] folds denial over ask over allow. Adding a hook-//! can therefore never loosen a policy another one set — which is what makes it-//! safe for a repository to ship its own `hooks.json` on a machine that already-//! has an operator-managed one.-//!-//! **Gating costs a turn's latency; observing does not.** [`types::HookEvent::is_gating`]-//! is the single place that split is encoded, and [`engine`] reads it to decide-//! between running hooks sequentially in the turn's path and spawning them onto-//! a background task. An audit hook that hangs must not hang the agent.+//! The two rules that govern the engine (strictest verdict wins; gating costs a+//! turn's latency, observing does not) are documented with it in+//! `tinyagents_runtime::command_hooks`.pub mod bridge;-pub mod config;-pub mod context;-pub mod engine;-pub mod exec;-pub mod followup;-pub mod matcher;+pub mod host;pub mod ops;pub mod prompt_eval;pub mod schemas;-pub mod types;--#[cfg(test)]-#[path = "hooks_tests.rs"]-mod tests;-pub use config::{HookConfig, HookDefinition, HookKind, HookLayer, HooksFile};-pub use engine::{global as engine_global, HookEngine, HookOutcome};pub use ops::{init, PromptVerdict};pub use schemas::{all_controller_schemas as all_hooks_controller_schemas,all_registered_controllers as all_hooks_registered_controllers,};-pub use types::{HookEvent, HookInput, HookOutput, HookPayload, HookPermission};diff --git a/crates/openhuman-core/src/hooks/ops.rs b/crates/openhuman-core/src/hooks/ops.rsindex 3407fc84ef..b67441bcda 100644--- a/crates/openhuman-core/src/hooks/ops.rs+++ b/crates/openhuman-core/src/hooks/ops.rs@@ -10,9 +10,8 @@use std::path::PathBuf;use std::time::Duration;-use super::context::{build_input, set_host_context, HostContext, TurnIdentity};-use super::engine;-use super::types::{+use tinyagents_runtime::command_hooks::context::{build_input, set_host_context, HostContext, TurnIdentity};+use tinyagents_runtime::command_hooks::types::{CompactPayload, HookEvent, HookPayload, PromptPayload, SessionPayload, SubagentPayload,TextPayload,};@@ -31,17 +30,17 @@ pub async fn init(config: &crate::config::schema::Config) {if !settings.enabled {super::bridge::ConfiguredHookBridge::uninstall();- engine::global()- .install(super::config::HookConfig::default())+ super::host::engine()+ .install(tinyagents_runtime::command_hooks::HookConfig::default()).await;log::info!("[hooks] disabled by configuration");return;}- engine::global()+ super::host::engine().set_default_timeout(Duration::from_secs(settings.default_timeout_secs)).await;- let loaded = engine::global()+ let loaded = super::host::engine().reload(Some(config.action_dir.clone()),Some(config.workspace_dir.clone()),@@ -69,7 +68,7 @@ fn workspace_roots(config: &crate::config::schema::Config) -> Vec<PathBuf> {/// Fire `sessionStart`, returning context the caller should append to the/// session's system prompt.pub async fn session_started(identity: TurnIdentity, entrypoint: Option<String>) -> Option<String> {- let engine = engine::global();+ let engine = super::host::engine();if !engine.has_hooks(HookEvent::SessionStart).await {return None;}@@ -91,7 +90,7 @@ pub async fn session_started(identity: TurnIdentity, entrypoint: Option<String>)/// Fire `sessionEnd` and release everything scoped to the session.pub async fn session_ended(identity: TurnIdentity, reason: &str, duration_ms: Option<u64>) {- let engine = engine::global();+ let engine = super::host::engine();let session_id = identity.session_id.clone();if engine.has_hooks(HookEvent::SessionEnd).await {let input = build_input(@@ -107,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;- super::followup::forget(&session_id).await;+ tinyagents_runtime::command_hooks::followup::forget(&session_id).await;}}@@ -134,7 +133,7 @@ pub async fn prompt_submitted(prompt: &str,attachments: Vec<String>,) -> PromptVerdict {- let engine = engine::global();+ let engine = super::host::engine();if !engine.has_hooks(HookEvent::BeforeSubmitPrompt).await {return PromptVerdict::Submit {additional_context: None,@@ -170,7 +169,7 @@ pub async fn pre_compact(context_usage_percent: Option<f64>,message_count: Option<usize>,) -> Option<String> {- let engine = engine::global();+ let engine = super::host::engine();if !engine.has_hooks(HookEvent::PreCompact).await {return None;}@@ -196,7 +195,7 @@ pub async fn subagent_starting(subagent_type: &str,task: &str,) -> Result<(), String> {- let engine = engine::global();+ let engine = super::host::engine();if !engine.has_hooks(HookEvent::SubagentStart).await {return Ok(());}@@ -226,7 +225,7 @@ pub async fn subagent_stopped(status: &str,duration_ms: Option<u64>,) -> Option<String> {- let engine = engine::global();+ let engine = super::host::engine();if !engine.has_hooks(HookEvent::SubagentStop).await {return None;}@@ -251,7 +250,7 @@ pub async fn subagent_stopped(/// Fire `afterAgentThought`. Observational, so this returns as soon as the/// hooks are scheduled.pub async fn agent_thought(identity: TurnIdentity, text: &str, duration_ms: Option<u64>) {- let engine = engine::global();+ let engine = super::host::engine();if !engine.has_hooks(HookEvent::AfterAgentThought).await {return;}diff --git a/crates/openhuman-core/src/hooks/schemas.rs b/crates/openhuman-core/src/hooks/schemas.rsindex 7e422a4c47..286ee9ff0b 100644--- a/crates/openhuman-core/src/hooks/schemas.rs+++ b/crates/openhuman-core/src/hooks/schemas.rs@@ -14,8 +14,8 @@ use crate::config::rpc as config_rpc;use crate::core::all::{ControllerFuture, RegisteredController};use crate::core::{ControllerSchema, FieldSchema, TypeSchema};-use super::context::TurnIdentity;-use super::types::{HookEvent, HookPayload};+use tinyagents_runtime::command_hooks::context::TurnIdentity;+use tinyagents_runtime::command_hooks::types::{HookEvent, HookPayload};pub fn all_controller_schemas() -> Vec<ControllerSchema> {vec![schemas("list"), schemas("reload"), schemas("test")]@@ -105,14 +105,14 @@ pub fn schemas(function: &str) -> ControllerSchema {}fn handle_list(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { Ok(describe(super::engine::global().snapshot().await.as_ref())) })+ Box::pin(async move { Ok(describe(super::host::engine().snapshot().await.as_ref())) })}fn handle_reload(_params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let config = config_rpc::load_config_with_timeout().await?;super::ops::init(&config).await;- Ok(describe(super::engine::global().snapshot().await.as_ref()))+ Ok(describe(super::host::engine().snapshot().await.as_ref()))})}@@ -135,11 +135,11 @@ fn handle_test(params: Map<String, Value>) -> ControllerFuture {).map_err(|error| format!("invalid payload for '{event}': {error}"))?;- let input = super::context::build_input(event, TurnIdentity::default(), payload);+ let input = tinyagents_runtime::command_hooks::context::build_input(event, TurnIdentity::default(), payload);// A test fire is always run in the foreground, even for an// observational event: the point of the endpoint is to show the author// what happened, and a detached dispatch would report nothing.- let outcome = super::engine::global()+ let outcome = super::host::engine().dispatch_for_test(event, input).await;Ok(json!({@@ -158,7 +158,7 @@ fn handle_test(params: Map<String, Value>) -> ControllerFuture {}/// Render a config for the wire, naming the source file of every definition.-fn describe(config: &super::config::HookConfig) -> Value {+fn describe(config: &tinyagents_runtime::command_hooks::config::HookConfig) -> Value {let by_event: Map<String, Value> = config.by_event.iter()@@ -173,7 +173,7 @@ fn describe(config: &super::config::HookConfig) -> Value {"timeout": definition.timeout,"fail_closed": definition.fail_closed,"enabled": definition.enabled,- "layer": definition.layer.map(super::config::HookLayer::as_str),+ "layer": definition.layer.map(tinyagents_runtime::command_hooks::config::HookLayer::as_str),"source_dir": definition.source_dir.as_ref().map(|dir| dir.display().to_string()),})})diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rsindex 41cc9fb6cb..2eed06f33b 100644--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs@@ -312,7 +312,7 @@ pub async fn start_chat(// The message here is post-attachment-processing, so a hook sees extracted// text and placeholders rather than a multi-megabyte data URI on stdin.match crate::hooks::ops::prompt_submitted(- crate::hooks::context::TurnIdentity {+ tinyagents_runtime::command_hooks::context::TurnIdentity {conversation_id: Some(thread_id.clone()),..Default::default()},