Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(hooks): reorganise hook module into separate files

Steven Enamakelf0b3836721d3
diff --git a/crates/openhuman-core/src/hooks/config.rs b/crates/openhuman-core/src/hooks/config.rs
deleted file mode 100644
index 11812227c8..0000000000
--- a/crates/openhuman-core/src/hooks/config.rs
+++ /dev/null
@@ -1,364 +0,0 @@
-//! `hooks.json` — schema, discovery, and layering.
-//!
-//! The file format is Cursor's, version 1:
-//!
-//! ```json
-//! {
-//! "version": 1,
-//! "hooks": {
-//! "beforeShellExecution": [
-//! { "command": "./scripts/audit.sh", "matcher": "^rm ", "timeout": 10 }
-//! ]
-//! }
-//! }
-//! ```
-//!
-//! ## Layering
-//!
-//! Four layers are read, lowest trust last so that a more specific file cannot
-//! *remove* a broader policy — the lists concatenate, they do not override. That
-//! is the opposite of how config.toml merges, and it is deliberate: an operator
-//! who installs a system-wide deny hook must not be overridden by a repository
-//! that ships its own `hooks.json`. Since [`HookOutput::merge`] takes the
-//! strictest verdict, concatenation is the safe composition.
-//!
-//! [`HookOutput::merge`]: super::types::HookOutput::merge
-
-use serde::{Deserialize, Serialize};
-use std::collections::BTreeMap;
-use std::path::{Path, PathBuf};
-
-use super::types::{normalize_key, HookEvent};
-
-/// The only schema version this loader accepts.
-pub const HOOKS_SCHEMA_VERSION: u32 = 1;
-
-/// Filename looked for in every layer directory.
-pub const HOOKS_FILE_NAME: &str = "hooks.json";
-
-/// Where a hook definition came from. Surfaced in diagnostics and in the RPC
-/// listing so "why is this hook running" has an answer that names a file.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
-#[serde(rename_all = "lowercase")]
-pub enum HookLayer {
- /// Machine-wide, operator-managed.
- System,
- /// The user's own `~/.openhuman/hooks.json`.
- User,
- /// The core's workspace directory.
- Workspace,
- /// `<project>/.openhuman/hooks.json` inside the action dir.
- Project,
-}
-
-impl HookLayer {
- /// Human-readable label for logs and the RPC listing.
- pub fn as_str(self) -> &'static str {
- match self {
- HookLayer::System => "system",
- HookLayer::User => "user",
- HookLayer::Workspace => "workspace",
- HookLayer::Project => "project",
- }
- }
-}
-
-/// How a hook is executed.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
-#[serde(rename_all = "lowercase")]
-pub enum HookKind {
- /// Spawn a program, hand it the event JSON on stdin, read a decision from
- /// stdout.
- #[default]
- Command,
- /// Evaluate a natural-language condition with a model, which answers
- /// `{ "ok": bool, "reason": string }`.
- Prompt,
-}
-
-/// One configured hook.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct HookDefinition {
- /// The program to run, or the prompt text for a `prompt` hook.
- pub command: String,
- /// Execution strategy.
- #[serde(default, rename = "type")]
- pub kind: HookKind,
- /// Seconds before the hook is killed. Falls back to the engine default.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub timeout: Option<u64>,
- /// Restricts which occurrences of the event reach this hook. See
- /// [`super::matcher`] for the per-event semantics.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub matcher: Option<String>,
- /// Follow-ups this hook may inject before the engine stops honouring them.
- /// `None` in the file means "engine default"; explicit JSON `null` means
- /// unlimited, matching Cursor.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub loop_limit: Option<u32>,
- /// Treat a crashed, missing, or timed-out hook as a denial rather than
- /// letting the action through. Off by default: a broken audit script must
- /// not brick the agent, but a security hook can opt into the other trade.
- #[serde(default, alias = "failClosed")]
- pub fail_closed: bool,
- /// Model override for a `prompt` hook.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub model: Option<String>,
- /// Skip this definition without deleting it.
- #[serde(default = "default_true")]
- pub enabled: bool,
- /// Resolved at load time from the file's own location — never read from
- /// the file, so a `hooks.json` cannot claim to be a more trusted layer.
- #[serde(skip_deserializing)]
- pub layer: Option<HookLayer>,
- /// Directory the hook process runs in: the directory holding its
- /// `hooks.json`. Resolved at load time, never read from the file.
- #[serde(skip_deserializing)]
- pub source_dir: Option<PathBuf>,
-}
-
-fn default_true() -> bool {
- true
-}
-
-impl HookDefinition {
- /// A short identifier for logs: layer plus the head of the command.
- pub fn label(&self) -> String {
- let layer = self.layer.map(HookLayer::as_str).unwrap_or("unknown");
- let head = self.command.split_whitespace().next().unwrap_or("<empty>");
- format!("{layer}:{head}")
- }
-}
-
-/// One parsed `hooks.json`.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct HooksFile {
- /// Schema version. Anything other than [`HOOKS_SCHEMA_VERSION`] is rejected.
- #[serde(default)]
- pub version: u32,
- /// Event name → definitions, in run order.
- #[serde(default)]
- pub hooks: BTreeMap<String, Vec<HookDefinition>>,
-}
-
-/// The merged, ready-to-run hook set.
-#[derive(Debug, Clone, Default)]
-pub struct HookConfig {
- /// Definitions grouped by resolved event, in layer order.
- pub by_event: BTreeMap<HookEvent, Vec<HookDefinition>>,
- /// Files that contributed, for diagnostics.
- pub sources: Vec<PathBuf>,
- /// Non-fatal problems found while loading: unreadable files, unknown event
- /// names, wrong versions. Surfaced rather than swallowed — a hook that
- /// silently never runs is worse than one that reports why.
- pub warnings: Vec<String>,
-}
-
-impl HookConfig {
- /// Definitions registered for an event, in run order.
- pub fn for_event(&self, event: HookEvent) -> &[HookDefinition] {
- self.by_event
- .get(&event)
- .map(Vec::as_slice)
- .unwrap_or_default()
- }
-
- /// Whether anything at all is configured.
- pub fn is_empty(&self) -> bool {
- self.by_event.values().all(Vec::is_empty)
- }
-
- /// Total number of configured definitions.
- pub fn len(&self) -> usize {
- self.by_event.values().map(Vec::len).sum()
- }
-
- /// Parse one file's contents into this config, tagging every definition
- /// with its layer and source directory.
- fn absorb(&mut self, path: &Path, layer: HookLayer, contents: &str) {
- let file: HooksFile = match serde_json::from_str(contents) {
- Ok(file) => file,
- Err(error) => {
- self.warnings
- .push(format!("{}: invalid JSON: {error}", path.display()));
- return;
- }
- };
- if file.version != HOOKS_SCHEMA_VERSION {
- self.warnings.push(format!(
- "{}: unsupported version {} (expected {HOOKS_SCHEMA_VERSION}); ignored",
- path.display(),
- file.version
- ));
- return;
- }
- let source_dir = path.parent().map(Path::to_path_buf);
- for (key, definitions) in file.hooks {
- let Some(event) = HookEvent::parse(&key) else {
- self.warnings.push(format!(
- "{}: unknown hook event '{key}'; known events: {}",
- path.display(),
- known_events_hint(&key)
- ));
- continue;
- };
- if !event.is_wired() {
- self.warnings.push(format!(
- "{}: '{event}' is defined but not yet fired by this build; its hooks will never run",
- path.display()
- ));
- }
- let slot = self.by_event.entry(event).or_default();
- for mut definition in definitions {
- if definition.command.trim().is_empty() {
- self.warnings.push(format!(
- "{}: hook for '{event}' has an empty command; ignored",
- path.display()
- ));
- continue;
- }
- definition.layer = Some(layer);
- definition.source_dir.clone_from(&source_dir);
- if let Some(problem) = unrunnable_reason(&definition) {
- self.warnings
- .push(format!("{}: hook for '{event}' {problem}", path.display()));
- }
- slot.push(definition);
- }
- }
- self.sources.push(path.to_path_buf());
- }
-}
-
-/// Report a command-hook script that cannot run, or `None` when it looks fine.
-///
-/// Only *relative* paths are checked. An absolute path may legitimately be
-/// resolved on a machine this config was not loaded on, and a bare name is a
-/// `PATH` lookup or a shell built-in — guessing at either would produce a
-/// warning for a working hook, which is worse than no warning at all.
-fn unrunnable_reason(definition: &HookDefinition) -> Option<String> {
- if definition.kind != HookKind::Command {
- return None;
- }
- let program = definition.command.split_whitespace().next()?;
- if !program.starts_with("./") && !program.starts_with("../") {
- return None;
- }
- let resolved = definition.source_dir.as_ref()?.join(program);
- if !resolved.exists() {
- return Some(format!(
- "points at a missing script: {}",
- resolved.display()
- ));
- }
- if !super::exec::is_executable(&resolved) {
- return Some(format!(
- "points at a script that is not executable (chmod +x): {}",
- resolved.display()
- ));
- }
- None
-}
-
-/// Suggest the closest known event name, so a typo reports something useful
-/// rather than the full list of eighteen.
-fn known_events_hint(key: &str) -> String {
- let normalized = normalize_key(key);
- let closest = HookEvent::ALL.iter().copied().find(|event| {
- let candidate = normalize_key(event.as_str());
- candidate.starts_with(&normalized) || normalized.starts_with(&candidate)
- });
- match closest {
- Some(event) => format!("did you mean '{event}'?"),
- None => HookEvent::ALL
- .iter()
- .map(|event| event.as_str())
- .collect::<Vec<_>>()
- .join(", "),
- }
-}
-
-/// The directories searched for a `hooks.json`, lowest trust last.
-///
-/// `project_dir` is the agent's action root; `workspace_dir` is the core's
-/// internal state directory. Both are passed in rather than resolved here so
-/// the loader stays testable without touching process globals.
-pub fn layer_paths(
- project_dir: Option<&Path>,
- workspace_dir: Option<&Path>,
-) -> Vec<(HookLayer, PathBuf)> {
- let mut paths = Vec::new();
- if let Some(system) = system_hooks_dir() {
- paths.push((HookLayer::System, system.join(HOOKS_FILE_NAME)));
- }
- if let Some(home) = dirs::home_dir() {
- paths.push((
- HookLayer::User,
- home.join(".openhuman").join(HOOKS_FILE_NAME),
- ));
- }
- if let Some(workspace) = workspace_dir {
- paths.push((HookLayer::Workspace, workspace.join(HOOKS_FILE_NAME)));
- }
- if let Some(project) = project_dir {
- paths.push((
- HookLayer::Project,
- project.join(".openhuman").join(HOOKS_FILE_NAME),
- ));
- }
- paths
-}
-
-#[cfg(target_os = "windows")]
-fn system_hooks_dir() -> Option<PathBuf> {
- std::env::var_os("ProgramData").map(|dir| PathBuf::from(dir).join("OpenHuman"))
-}
-
-#[cfg(target_os = "macos")]
-fn system_hooks_dir() -> Option<PathBuf> {
- Some(PathBuf::from("/Library/Application Support/OpenHuman"))
-}
-
-#[cfg(not(any(target_os = "windows", target_os = "macos")))]
-fn system_hooks_dir() -> Option<PathBuf> {
- Some(PathBuf::from("/etc/openhuman"))
-}
-
-/// Read every layer and merge it into one config.
-///
-/// A missing file is not a warning — most hosts have none. An unreadable or
-/// malformed one is, because that is a hook the author believes is running.
-pub fn load(project_dir: Option<&Path>, workspace_dir: Option<&Path>) -> HookConfig {
- let mut config = HookConfig::default();
- for (layer, path) in layer_paths(project_dir, workspace_dir) {
- match std::fs::read_to_string(&path) {
- Ok(contents) => {
- log::debug!(
- "[hooks] loading {} layer from {}",
- layer.as_str(),
- path.display()
- );
- config.absorb(&path, layer, &contents);
- }
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
- Err(error) => config
- .warnings
- .push(format!("{}: unreadable: {error}", path.display())),
- }
- }
- log::debug!(
- "[hooks] loaded {} definition(s) from {} file(s), {} warning(s)",
- config.len(),
- config.sources.len(),
- config.warnings.len()
- );
- config
-}
-
-/// Parse a single file's contents. Exposed for the RPC validate endpoint and
-/// for tests, which must not depend on the host's real layer directories.
-pub fn parse_one(path: &Path, layer: HookLayer, contents: &str) -> HookConfig {
- let mut config = HookConfig::default();
- config.absorb(path, layer, contents);
- config
-}
diff --git a/crates/openhuman-core/src/hooks/context.rs b/crates/openhuman-core/src/hooks/context.rs
deleted file mode 100644
index 5a67ad7ca4..0000000000
--- a/crates/openhuman-core/src/hooks/context.rs
+++ /dev/null
@@ -1,88 +0,0 @@
-//! Building the stdin envelope.
-//!
-//! Every hook event shares a common header — version, workspace roots, session
-//! and model identity — and the pieces of it that do not change during a run
-//! are resolved once at startup rather than per event. A hook firing on every
-//! tool call must not cost a config load.
-
-use std::path::PathBuf;
-use std::sync::RwLock;
-
-use super::types::{HookEvent, HookInput, HookPayload};
-
-/// Host facts shared by every hook envelope, resolved once at startup.
-#[derive(Debug, Clone, Default)]
-pub struct HostContext {
- /// Filesystem roots the agent may act in. First entry is the primary root
- /// and becomes `OPENHUMAN_PROJECT_DIR` for hook processes.
- pub workspace_roots: Vec<PathBuf>,
- /// Core version string.
- pub version: String,
-}
-
-static HOST: RwLock<Option<HostContext>> = RwLock::new(None);
-
-/// Install the host facts. Called once during core bootstrap, and again by the
-/// RPC reload endpoint when the action dir changes.
-pub fn set_host_context(context: HostContext) {
- log::debug!(
- "[hooks] host context: version={} roots={:?}",
- context.version,
- context.workspace_roots
- );
- *HOST.write().expect("hook host context poisoned") = Some(context);
-}
-
-/// The installed host facts, or an empty default before bootstrap has run.
-pub fn host_context() -> HostContext {
- HOST.read()
- .expect("hook host context poisoned")
- .clone()
- .unwrap_or_default()
-}
-
-/// Per-turn identity attached to each envelope.
-///
-/// All fields are optional because the moments hooks fire at do not all belong
-/// to a session — a `sessionStart` has no generation, a CLI turn has no
-/// conversation.
-#[derive(Debug, Clone, Default)]
-pub struct TurnIdentity {
- /// Conversation/thread identifier.
- pub conversation_id: Option<String>,
- /// Per-turn generation identifier.
- pub generation_id: Option<String>,
- /// Agent session identifier.
- pub session_id: Option<String>,
- /// Model driving the turn.
- pub model: Option<String>,
- /// Canonical agent definition id.
- pub agent_id: Option<String>,
- /// Working directory the action is scoped to.
- pub cwd: Option<String>,
-}
-
-/// Assemble the envelope handed to a hook on stdin.
-pub fn build_input(event: HookEvent, identity: TurnIdentity, payload: HookPayload) -> HookInput {
- let host = host_context();
- HookInput {
- hook_event_name: event.as_str().to_string(),
- conversation_id: identity.conversation_id,
- generation_id: identity.generation_id,
- session_id: identity.session_id,
- model: identity.model,
- agent_id: identity.agent_id,
- openhuman_version: if host.version.is_empty() {
- env!("CARGO_PKG_VERSION").to_string()
- } else {
- host.version
- },
- workspace_roots: host
- .workspace_roots
- .iter()
- .map(|root| root.display().to_string())
- .collect(),
- cwd: identity.cwd,
- payload,
- }
-}
diff --git a/crates/openhuman-core/src/hooks/engine.rs b/crates/openhuman-core/src/hooks/engine.rs
deleted file mode 100644
index ad69d9b8c4..0000000000
--- a/crates/openhuman-core/src/hooks/engine.rs
+++ /dev/null
@@ -1,343 +0,0 @@
-//! The hook engine — matching, ordering, and aggregating.
-//!
-//! One process-global engine holds the merged [`HookConfig`], the session-scoped
-//! environment contributed by `sessionStart` hooks, and the per-session
-//! follow-up counters that stop a `stop` hook from looping forever.
-//!
-//! ## Gating versus observing
-//!
-//! [`HookEvent::is_gating`] splits the events in two, and the split decides the
-//! execution strategy:
-//!
-//! * **Gating** events run their hooks **sequentially, in layer order**, and the
-//! turn waits. A denial short-circuits the rest — once the action is refused
-//! there is nothing later hooks can add, and running them would pay latency
-//! for an outcome that cannot change.
-//! * **Observing** events are dispatched onto a background task and the turn
-//! never waits. An audit hook that hangs must not hang the agent.
-//!
-//! That asymmetry is the whole reason the engine exists rather than each call
-//! site spawning processes itself: it is the one place the latency budget of a
-//! turn is spent deliberately.
-
-use std::collections::{BTreeMap, HashMap};
-use std::path::PathBuf;
-use std::sync::Arc;
-use std::time::Duration;
-
-use tokio::sync::RwLock;
-
-use super::config::{self, HookConfig, HookDefinition};
-use super::exec::{self, HookRun, DEFAULT_TIMEOUT};
-use super::matcher;
-use super::types::{HookEvent, HookInput, HookOutput};
-
-/// Follow-ups a single hook may inject per session before the engine stops
-/// honouring it. Matches Cursor's default; a definition may raise it, and an
-/// explicit `null` in the file lifts the cap entirely.
-pub const DEFAULT_LOOP_LIMIT: u32 = 5;
-
-/// The result of dispatching one event.
-#[derive(Debug, Clone, Default)]
-pub struct HookOutcome {
- /// The merged decision across every hook that ran.
- pub output: HookOutput,
- /// Per-hook detail, in run order. Empty for a fire-and-forget dispatch.
- pub runs: Vec<HookRun>,
-}
-
-impl HookOutcome {
- /// Whether the action was refused.
- pub fn is_deny(&self) -> bool {
- self.output.is_deny()
- }
-
- /// Whether the action needs human approval.
- pub fn is_ask(&self) -> bool {
- self.output.is_ask()
- }
-
- /// The reason to hand the model, when the action was refused.
- pub fn denial_reason(&self) -> Option<&str> {
- if !self.is_deny() {
- return None;
- }
- self.output
- .agent_message
- .as_deref()
- .or(self.output.user_message.as_deref())
- }
-}
-
-/// Matching, execution, and aggregation of configured hooks.
-pub struct HookEngine {
- config: RwLock<Arc<HookConfig>>,
- /// Environment contributed by `sessionStart` hooks, keyed by session id.
- /// Cursor scopes these to the session; so do we, rather than mutating the
- /// process environment, which would leak one session's variables into
- /// every concurrent one.
- session_env: RwLock<HashMap<String, BTreeMap<String, String>>>,
- /// Follow-ups already granted, keyed by session and hook label.
- loop_counts: RwLock<HashMap<(String, String), u32>>,
- default_timeout: RwLock<Duration>,
-}
-
-impl Default for HookEngine {
- fn default() -> Self {
- Self {
- config: RwLock::new(Arc::new(HookConfig::default())),
- session_env: RwLock::new(HashMap::new()),
- loop_counts: RwLock::new(HashMap::new()),
- default_timeout: RwLock::new(DEFAULT_TIMEOUT),
- }
- }
-}
-
-static ENGINE: std::sync::LazyLock<HookEngine> = std::sync::LazyLock::new(HookEngine::default);
-
-/// The process-global engine.
-pub fn global() -> &'static HookEngine {
- &ENGINE
-}
-
-impl HookEngine {
- /// Re-read every layer and swap the config in.
- ///
- /// Reloading is a whole-config swap rather than an incremental patch: a
- /// half-applied hook set is a policy nobody wrote.
- pub async fn reload(
- &self,
- project_dir: Option<PathBuf>,
- workspace_dir: Option<PathBuf>,
- ) -> Arc<HookConfig> {
- let loaded = tokio::task::spawn_blocking(move || {
- config::load(project_dir.as_deref(), workspace_dir.as_deref())
- })
- .await
- .unwrap_or_default();
- for warning in &loaded.warnings {
- log::warn!("[hooks] {warning}");
- }
- let loaded = Arc::new(loaded);
- *self.config.write().await = Arc::clone(&loaded);
- log::info!(
- "[hooks] active configuration: {} hook(s) across {} file(s)",
- loaded.len(),
- loaded.sources.len()
- );
- loaded
- }
-
- /// Install a config directly. Used by tests and by the RPC surface, which
- /// validates a candidate file before letting it become live.
- pub async fn install(&self, config: HookConfig) {
- *self.config.write().await = Arc::new(config);
- }
-
- /// The currently active config.
- pub async fn snapshot(&self) -> Arc<HookConfig> {
- Arc::clone(&*self.config.read().await)
- }
-
- /// Override the timeout applied to hooks that name none.
- pub async fn set_default_timeout(&self, timeout: Duration) {
- *self.default_timeout.write().await = timeout;
- }
-
- /// Whether any hook is registered for an event. Call sites use this to skip
- /// building an input envelope for an event nobody is listening to — the
- /// common case, and the reason hooks cost nothing when unconfigured.
- pub async fn has_hooks(&self, event: HookEvent) -> bool {
- !self.snapshot().await.for_event(event).is_empty()
- }
-
- /// Run an event's hooks and return the merged decision.
- ///
- /// Observing events are dispatched in the background and return an empty
- /// outcome immediately; see the module docs.
- pub async fn dispatch(&self, event: HookEvent, input: HookInput) -> HookOutcome {
- let config = self.snapshot().await;
- let selected: Vec<HookDefinition> = config
- .for_event(event)
- .iter()
- .filter(|definition| definition.enabled)
- .filter(|definition| {
- matcher::matches(
- definition.matcher.as_deref(),
- matcher::subject(event, &input.payload),
- )
- })
- .cloned()
- .collect();
- if selected.is_empty() {
- return HookOutcome::default();
- }
- log::debug!(
- "[hooks] {event}: {} hook(s) selected ({} configured)",
- selected.len(),
- config.for_event(event).len()
- );
-
- if !event.is_gating() {
- self.dispatch_detached(event, input, selected).await;
- return HookOutcome::default();
- }
- self.dispatch_blocking(event, input, selected).await
- }
-
- /// Run an event's hooks in the foreground regardless of whether the event
- /// is gating, and report every run.
- ///
- /// Only the `hooks.test` RPC uses this. A detached dispatch would report
- /// nothing, which is precisely the opposite of what an author debugging a
- /// hook needs — so the test path trades the latency guarantee for
- /// observability, and nothing on a turn's path may call it.
- pub async fn dispatch_for_test(&self, event: HookEvent, input: HookInput) -> HookOutcome {
- let config = self.snapshot().await;
- let selected: Vec<HookDefinition> = config
- .for_event(event)
- .iter()
- .filter(|definition| definition.enabled)
- .filter(|definition| {
- matcher::matches(
- definition.matcher.as_deref(),
- matcher::subject(event, &input.payload),
- )
- })
- .cloned()
- .collect();
- if selected.is_empty() {
- return HookOutcome::default();
- }
- self.dispatch_blocking(event, input, selected).await
- }
-
- /// Run hooks in order, stopping at the first denial.
- async fn dispatch_blocking(
- &self,
- event: HookEvent,
- input: HookInput,
- selected: Vec<HookDefinition>,
- ) -> HookOutcome {
- let env = self.env_for(&input).await;
- let default_timeout = *self.default_timeout.read().await;
- let mut outcome = HookOutcome::default();
- for definition in selected {
- let run = exec::run(&definition, &input, &env, default_timeout).await;
- log::debug!(
- "[hooks] {event}: {} finished in {}ms (deny={}, error={:?})",
- run.label,
- run.duration.as_millis(),
- run.output.is_deny(),
- run.error
- );
- let denied = run.output.is_deny();
- let followup = run.output.followup_message.clone();
- let mut run = run;
- if followup.is_some() && !self.grant_followup(&input, &definition, &run.label).await {
- log::debug!(
- "[hooks] {event}: {} exhausted its follow-up budget; dropping the message",
- run.label
- );
- run.output.followup_message = None;
- }
- outcome.output.merge(run.output.clone());
- outcome.runs.push(run);
- if denied {
- break;
- }
- }
- if let Some(env) = outcome.output.env.clone() {
- self.absorb_session_env(&input, env).await;
- }
- outcome
- }
-
- /// Fire hooks on a background task, so the turn never waits on them.
- async fn dispatch_detached(
- &self,
- event: HookEvent,
- input: HookInput,
- selected: Vec<HookDefinition>,
- ) {
- let env = self.env_for(&input).await;
- let default_timeout = *self.default_timeout.read().await;
- tokio::spawn(async move {
- for definition in selected {
- let run = exec::run(&definition, &input, &env, default_timeout).await;
- if let Some(error) = &run.error {
- log::warn!("[hooks] {event}: {} failed: {error}", run.label);
- } else {
- log::trace!(
- "[hooks] {event}: {} finished in {}ms",
- run.label,
- run.duration.as_millis()
- );
- }
- }
- });
- }
-
- /// Ambient variables plus anything a `sessionStart` hook contributed.
- async fn env_for(&self, input: &HookInput) -> BTreeMap<String, String> {
- let mut env = exec::ambient_env(input);
- if let Some(session) = &input.session_id {
- if let Some(extra) = self.session_env.read().await.get(session) {
- env.extend(extra.clone());
- }
- }
- env
- }
-
- async fn absorb_session_env(&self, input: &HookInput, env: BTreeMap<String, String>) {
- let Some(session) = input.session_id.clone() else {
- log::debug!("[hooks] ignoring session env from a hook fired outside a session");
- return;
- };
- self.session_env
- .write()
- .await
- .entry(session)
- .or_default()
- .extend(env);
- }
-
- /// Charge one follow-up against a hook's budget, returning whether it may
- /// be honoured. A hook with no session id gets exactly one, since there is
- /// nowhere to keep a counter and an unbounded loop is the worse failure.
- async fn grant_followup(
- &self,
- input: &HookInput,
- definition: &HookDefinition,
- label: &str,
- ) -> bool {
- // Cursor's `loop_limit: null` means unlimited. serde cannot distinguish
- // an explicit null from an absent key in an `Option<u32>`, so the file
- // convention here is: absent → engine default, `0` → unlimited.
- let limit = match definition.loop_limit {
- Some(0) => return true,
- Some(limit) => limit,
- None => DEFAULT_LOOP_LIMIT,
- };
- let Some(session) = input.session_id.clone() else {
- return true;
- };
- let key = (session, label.to_string());
- let mut counts = self.loop_counts.write().await;
- let count = counts.entry(key).or_insert(0);
- if *count >= limit {
- return false;
- }
- *count += 1;
- true
- }
-
- /// Drop everything scoped to a finished session.
- pub async fn forget_session(&self, session_id: &str) {
- self.session_env.write().await.remove(session_id);
- self.loop_counts
- .write()
- .await
- .retain(|(session, _), _| session != session_id);
- }
-}
diff --git a/crates/openhuman-core/src/hooks/exec.rs b/crates/openhuman-core/src/hooks/exec.rs
deleted file mode 100644
index 2bffb733db..0000000000
--- a/crates/openhuman-core/src/hooks/exec.rs
+++ /dev/null
@@ -1,324 +0,0 @@
-//! Running one hook.
-//!
-//! ## The contract
-//!
-//! A command hook receives the event JSON on stdin, and answers on stdout. Its
-//! exit code decides how the answer is read:
-//!
-//! | Exit | Meaning |
-//! | ---- | ------- |
-//! | `0` | Success. stdout is parsed as a [`HookOutput`]; empty stdout is a no-op. |
-//! | `2` | Deny, regardless of stdout. stderr becomes the reason the agent sees. |
-//! | else | Failure. Fails open — unless the definition sets `fail_closed`. |
-//!
-//! A timeout, a missing interpreter, and unparseable stdout are all *failures*
-//! and take the same path as a non-zero exit: open by default, closed on
-//! request. That symmetry matters — a hook that denies only when it manages to
-//! run is not a security control, so `fail_closed` has to cover every way the
-//! script can fail to answer, not just the tidy one.
-//!
-//! ## Why stdout is parsed leniently
-//!
-//! Scripts print. A hook that echoes a progress line and *then* prints its JSON
-//! is the common case, not an error, so the parser takes the last complete JSON
-//! object on stdout rather than demanding the whole stream be JSON.
-
-use std::collections::BTreeMap;
-use std::path::Path;
-use std::process::Stdio;
-use std::time::{Duration, Instant};
-
-use tokio::io::AsyncWriteExt;
-
-use super::config::{HookDefinition, HookKind};
-use super::types::{HookInput, HookOutput, HookPermission};
-
-/// Exit code a hook uses to refuse an action.
-pub const EXIT_DENY: i32 = 2;
-
-/// Timeout applied when neither the definition nor the engine names one.
-pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
-
-/// What running one hook produced, with enough detail for diagnostics.
-#[derive(Debug, Clone)]
-pub struct HookRun {
- /// The hook's own label, for logs.
- pub label: String,
- /// The decision, after exit-code and fail-closed handling.
- pub output: HookOutput,
- /// Wall-clock runtime.
- pub duration: Duration,
- /// Set when the hook did not answer cleanly. Present even when the engine
- /// failed open, so "nothing happened" and "it broke and we continued" stay
- /// distinguishable in the logs and in the RPC test endpoint.
- pub error: Option<String>,
-}
-
-impl HookRun {
- fn noop(label: String, duration: Duration, error: Option<String>) -> Self {
- Self {
- label,
- output: HookOutput::default(),
- duration,
- error,
- }
- }
-}
-
-/// Run one hook against one event.
-///
-/// `env` carries session-scoped variables contributed by an earlier
-/// `sessionStart` hook, plus the ambient `OPENHUMAN_*` variables the engine
-/// adds. Never returns `Err`: a hook that cannot run is a [`HookRun`] with an
-/// `error` and either an empty output (fail-open) or a denial (fail-closed).
-pub async fn run(
- definition: &HookDefinition,
- input: &HookInput,
- env: &BTreeMap<String, String>,
- default_timeout: Duration,
-) -> HookRun {
- let label = definition.label();
- let started = Instant::now();
- match definition.kind {
- HookKind::Command => {
- let timeout = definition
- .timeout
- .map(Duration::from_secs)
- .unwrap_or(default_timeout);
- let result = run_command(definition, input, env, timeout).await;
- finish(definition, label, started.elapsed(), result)
- }
- HookKind::Prompt => {
- let result = run_prompt(definition, input).await;
- finish(definition, label, started.elapsed(), result)
- }
- }
-}
-
-/// Apply the fail-open / fail-closed policy to a raw outcome.
-fn finish(
- definition: &HookDefinition,
- label: String,
- duration: Duration,
- result: Result<HookOutput, String>,
-) -> HookRun {
- match result {
- Ok(output) => HookRun {
- label,
- output,
- duration,
- error: None,
- },
- Err(error) if definition.fail_closed => {
- log::warn!("[hooks] {label} failed and is fail-closed; denying: {error}");
- HookRun {
- output: HookOutput::deny(format!("hook '{label}' could not run: {error}")),
- label,
- duration,
- error: Some(error),
- }
- }
- Err(error) => {
- log::warn!("[hooks] {label} failed; continuing (fail-open): {error}");
- HookRun::noop(label, duration, Some(error))
- }
- }
-}
-
-async fn run_command(
- definition: &HookDefinition,
- input: &HookInput,
- env: &BTreeMap<String, String>,
- timeout: Duration,
-) -> Result<HookOutput, String> {
- let payload =
- serde_json::to_vec(input).map_err(|error| format!("serializing input: {error}"))?;
-
- let mut command = crate::agent::platform_shell::build_tokio_command(&definition.command);
- if let Some(dir) = definition.source_dir.as_deref().filter(|dir| dir.is_dir()) {
- command.current_dir(dir);
- }
- for (key, value) in env {
- command.env(key, value);
- }
- command
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .kill_on_drop(true);
-
- let mut child = command
- .spawn()
- .map_err(|error| format!("spawning {:?}: {error}", definition.command))?;
-
- if let Some(mut stdin) = child.stdin.take() {
- // A hook that ignores stdin closes the pipe early; that is a broken pipe
- // on our side, not a hook failure, so the write error is only logged.
- if let Err(error) = stdin.write_all(&payload).await {
- log::debug!("[hooks] {} closed stdin early: {error}", definition.label());
- }
- drop(stdin);
- }
-
- let output = match tokio::time::timeout(timeout, child.wait_with_output()).await {
- Ok(Ok(output)) => output,
- Ok(Err(error)) => return Err(format!("waiting on hook: {error}")),
- Err(_) => return Err(format!("timed out after {}s", timeout.as_secs())),
- };
-
- let stdout = String::from_utf8_lossy(&output.stdout);
- let stderr = String::from_utf8_lossy(&output.stderr);
- let code = output.status.code();
-
- if code == Some(EXIT_DENY) {
- let reason = first_non_empty(&[&stderr, &stdout])
- .unwrap_or_else(|| format!("hook {} denied the action", definition.label()));
- return Ok(HookOutput::deny(reason));
- }
- if !output.status.success() {
- let detail = first_non_empty(&[&stderr, &stdout]).unwrap_or_default();
- return Err(match code {
- Some(code) => format!("exited with status {code}: {detail}"),
- None => format!("terminated by signal: {detail}"),
- });
- }
- parse_stdout(&stdout)
-}
-
-/// Extract the hook's decision from stdout, ignoring anything printed around it.
-fn parse_stdout(stdout: &str) -> Result<HookOutput, String> {
- let trimmed = stdout.trim();
- if trimmed.is_empty() {
- return Ok(HookOutput::default());
- }
- if let Ok(output) = serde_json::from_str::<HookOutput>(trimmed) {
- return Ok(output);
- }
- // Fall back to the last line that parses on its own — the "script logged
- // first, then answered" case.
- let recovered = trimmed
- .lines()
- .rev()
- .map(str::trim)
- .filter(|line| line.starts_with('{'))
- .find_map(|line| serde_json::from_str::<HookOutput>(line).ok());
- recovered.ok_or_else(|| {
- format!(
- "stdout was not a hook decision object: {}",
- truncate(trimmed, 200)
- )
- })
-}
-
-/// Answer shape for a `prompt` hook, mirroring Cursor's `{ ok, reason }`.
-#[derive(serde::Deserialize)]
-struct PromptVerdict {
- ok: bool,
- #[serde(default)]
- reason: Option<String>,
-}
-
-/// Evaluate a natural-language condition with a model.
-///
-/// The prompt text may contain `$ARGUMENTS`, replaced by the event JSON — the
-/// same placeholder Cursor uses, so a prompt hook ports across unchanged.
-async fn run_prompt(definition: &HookDefinition, input: &HookInput) -> Result<HookOutput, String> {
- let arguments =
- serde_json::to_string(input).map_err(|error| format!("serializing input: {error}"))?;
- let prompt = if definition.command.contains("$ARGUMENTS") {
- definition.command.replace("$ARGUMENTS", &arguments)
- } else {
- format!("{}\n\nEvent:\n{arguments}", definition.command)
- };
- let instruction = format!(
- "{prompt}\n\nAnswer with JSON only: {{\"ok\": true}} to allow, or \
- {{\"ok\": false, \"reason\": \"...\"}} to deny."
- );
-
- let answer = super::prompt_eval::evaluate(&instruction, definition.model.as_deref()).await?;
- let verdict: PromptVerdict = serde_json::from_str(answer.trim())
- .or_else(|_| {
- answer
- .lines()
- .rev()
- .map(str::trim)
- .filter(|line| line.starts_with('{'))
- .find_map(|line| serde_json::from_str::<PromptVerdict>(line).ok())
- .ok_or_else(|| {
- format!("model answer was not a verdict: {}", truncate(&answer, 200))
- })
- })
- .map_err(|error| error.to_string())?;
-
- if verdict.ok {
- return Ok(HookOutput {
- permission: Some(HookPermission::Allow),
- ..HookOutput::default()
- });
- }
- Ok(HookOutput::deny(verdict.reason.unwrap_or_else(|| {
- format!("hook '{}' denied the action", definition.label())
- })))
-}
-
-fn first_non_empty(candidates: &[&str]) -> Option<String> {
- candidates
- .iter()
- .map(|text| text.trim())
- .find(|text| !text.is_empty())
- .map(|text| truncate(text, 2000))
-}
-
-fn truncate(text: &str, max_chars: usize) -> String {
- if text.chars().count() <= max_chars {
- return text.to_string();
- }
- let head: String = text.chars().take(max_chars).collect();
- format!("{head}…")
-}
-
-/// Ambient environment every hook receives, on top of the process environment.
-///
-/// `CLAUDE_PROJECT_DIR` and `CURSOR_PROJECT_DIR` are set alongside the
-/// OpenHuman names so a script written for either host finds its project root
-/// without an OpenHuman-specific branch.
-pub fn ambient_env(input: &HookInput) -> BTreeMap<String, String> {
- let mut env = BTreeMap::new();
- if let Some(root) = input.workspace_roots.first() {
- env.insert("OPENHUMAN_PROJECT_DIR".into(), root.clone());
- env.insert("CLAUDE_PROJECT_DIR".into(), root.clone());
- env.insert("CURSOR_PROJECT_DIR".into(), root.clone());
- }
- env.insert("OPENHUMAN_VERSION".into(), input.openhuman_version.clone());
- env.insert("OPENHUMAN_HOOK_EVENT".into(), input.hook_event_name.clone());
- if let Some(session) = &input.session_id {
- env.insert("OPENHUMAN_SESSION_ID".into(), session.clone());
- }
- if let Some(agent) = &input.agent_id {
- env.insert("OPENHUMAN_AGENT_ID".into(), agent.clone());
- }
- env
-}
-
-/// True when a path exists and is executable by this process.
-///
-/// Read at **load** time so a hook whose script is missing or was committed
-/// without the executable bit is reported when the file is read, not when the
-/// moment it was meant to guard finally arrives.
-pub fn is_executable(path: &Path) -> bool {
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::metadata(path)
- .map(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
- .unwrap_or(false)
- }
- #[cfg(not(unix))]
- {
- path.is_file()
- }
-}
-
-#[cfg(test)]
-#[path = "exec_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/hooks/exec_tests.rs b/crates/openhuman-core/src/hooks/exec_tests.rs
deleted file mode 100644
index 4c04e1af58..0000000000
--- a/crates/openhuman-core/src/hooks/exec_tests.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-use super::*;
-
-#[test]
-fn empty_stdout_is_a_noop() {
- let output = parse_stdout(" \n").expect("empty stdout is allowed");
- assert!(output.permission.is_none());
-}
-
-#[test]
-fn plain_json_is_parsed() {
- let output = parse_stdout(r#"{"permission":"deny","agent_message":"no"}"#).unwrap();
- assert!(output.is_deny());
- assert_eq!(output.agent_message.as_deref(), Some("no"));
-}
-
-#[test]
-fn json_after_log_lines_is_recovered() {
- let stdout = "checking policy...\nstill checking\n{\"permission\":\"allow\"}\n";
- let output = parse_stdout(stdout).unwrap();
- assert_eq!(output.permission, Some(HookPermission::Allow));
-}
-
-#[test]
-fn unparseable_stdout_is_an_error() {
- let error = parse_stdout("not json at all").unwrap_err();
- assert!(error.contains("not a hook decision object"), "{error}");
-}
-
-#[test]
-fn truncate_marks_elision() {
- assert_eq!(truncate("abcdef", 3), "abc…");
- assert_eq!(truncate("abc", 3), "abc");
-}
diff --git a/crates/openhuman-core/src/hooks/followup.rs b/crates/openhuman-core/src/hooks/followup.rs
deleted file mode 100644
index 7e3b7620e3..0000000000
--- a/crates/openhuman-core/src/hooks/followup.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-//! Follow-up messages injected by `stop` hooks.
-//!
-//! A `stop` hook can answer with `followup_message`, asking for one more turn —
-//! "you did not run the tests, run them". The hook fires *after* the turn has
-//! already returned to its caller, so the message cannot re-enter the turn that
-//! produced it. It is queued here instead, and the entrypoint that owns the
-//! conversation decides whether to spend another turn on it.
-//!
-//! That indirection is not an implementation shortcut. Only the entrypoint
-//! knows whether there is still a user attached: a chat turn can be extended,
-//! a cron run that has already reported its result cannot, and a channel turn
-//! that has flushed its reply would surprise the recipient. A queue lets each
-//! answer for itself, and lets a host that answers "no" simply never drain it.
-//!
-//! [`HookEngine`](super::engine::HookEngine)'s `loop_limit` accounting has
-//! already been charged by the time a message lands here, so a drain loop
-//! cannot spin: a hook that keeps asking runs out of budget.
-
-use std::collections::HashMap;
-use tokio::sync::{broadcast, RwLock};
-
-/// A queued follow-up.
-#[derive(Debug, Clone)]
-pub struct Followup {
- /// Session the message belongs to, when the hook fired inside one.
- pub session_id: Option<String>,
- /// The message to send as the next user turn.
- pub message: String,
-}
-
-/// Messages queued per session, plus one bucket for sessionless turns.
-static PENDING: std::sync::LazyLock<RwLock<HashMap<String, Vec<String>>>> =
- std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
-
-/// Key used for follow-ups that arrived without a session id.
-const SESSIONLESS: &str = "";
-
-static CHANNEL: std::sync::LazyLock<broadcast::Sender<Followup>> = std::sync::LazyLock::new(|| {
- // A small buffer: a listener that falls this far behind has stopped caring,
- // and dropping old follow-ups is better than holding a turn's worth of
- // stale instructions.
- broadcast::channel(64).0
-});
-
-/// Queue a follow-up and notify any live listener.
-pub async fn publish(session_id: Option<String>, message: String) {
- let key = session_id
- .clone()
- .unwrap_or_else(|| SESSIONLESS.to_string());
- log::info!(
- "[hooks] stop hook queued a follow-up for session {:?} ({} chars)",
- session_id,
- message.chars().count()
- );
- PENDING
- .write()
- .await
- .entry(key)
- .or_default()
- .push(message.clone());
- // A send with no subscribers is not an error here — the queue is the
- // durable half, the channel only wakes a listener that already exists.
- let _ = CHANNEL.send(Followup {
- session_id,
- message,
- });
-}
-
-/// Listen for follow-ups as they are queued.
-pub fn subscribe() -> broadcast::Receiver<Followup> {
- CHANNEL.subscribe()
-}
-
-/// Take everything queued for a session, clearing it.
-pub async fn take(session_id: Option<&str>) -> Vec<String> {
- let key = session_id.unwrap_or(SESSIONLESS);
- PENDING.write().await.remove(key).unwrap_or_default()
-}
-
-/// Drop anything still queued for a finished session.
-pub async fn forget(session_id: &str) {
- PENDING.write().await.remove(session_id);
-}
-
-#[cfg(test)]
-#[path = "followup_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/hooks/followup_tests.rs b/crates/openhuman-core/src/hooks/followup_tests.rs
deleted file mode 100644
index 6511bdc3b8..0000000000
--- a/crates/openhuman-core/src/hooks/followup_tests.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use super::*;
-
-#[tokio::test]
-async fn queued_messages_are_taken_once() {
- publish(Some("s1".into()), "run the tests".into()).await;
- assert_eq!(take(Some("s1")).await, vec!["run the tests".to_string()]);
- assert!(take(Some("s1")).await.is_empty());
-}
-
-#[tokio::test]
-async fn sessionless_followups_land_in_their_own_bucket() {
- publish(None, "no session".into()).await;
- assert!(take(Some("s2")).await.is_empty());
- assert_eq!(take(None).await, vec!["no session".to_string()]);
-}
-
-#[tokio::test]
-async fn forget_drops_the_queue() {
- publish(Some("s3".into()), "gone".into()).await;
- forget("s3").await;
- assert!(take(Some("s3")).await.is_empty());
-}
diff --git a/crates/openhuman-core/src/hooks/hooks_tests.rs b/crates/openhuman-core/src/hooks/hooks_tests.rs
deleted file mode 100644
index ac32267498..0000000000
--- a/crates/openhuman-core/src/hooks/hooks_tests.rs
+++ /dev/null
@@ -1,520 +0,0 @@
-//! Domain tests: config layering, selection, and the execution contract.
-//!
-//! The execution tests shell out to real scripts on purpose. The whole feature
-//! is "spawn a process and read what it says", and a mocked runner would test
-//! the mock's idea of exit codes rather than the operating system's.
-
-use std::collections::BTreeMap;
-use std::path::PathBuf;
-use std::time::Duration;
-
-use super::config::{self, HookDefinition, HookKind, HookLayer};
-use super::engine::HookEngine;
-use super::exec;
-use super::types::{
- HookEvent, HookInput, HookOutput, HookPayload, HookPermission, ShellPayload, ToolPayload,
-};
-
-fn input(event: HookEvent, payload: HookPayload) -> HookInput {
- HookInput {
- hook_event_name: event.as_str().to_string(),
- conversation_id: None,
- generation_id: None,
- session_id: Some("sess-test".into()),
- model: None,
- agent_id: None,
- openhuman_version: "test".into(),
- workspace_roots: vec!["/tmp".into()],
- cwd: None,
- payload,
- }
-}
-
-fn tool_payload(tool: &str) -> HookPayload {
- HookPayload::Tool(ToolPayload {
- tool_name: tool.into(),
- tool_input: serde_json::json!({}),
- tool_use_id: "call-1".into(),
- ..ToolPayload::default()
- })
-}
-
-/// Write a `hooks.json` and an executable script into a fresh temp dir.
-fn scratch(file: &str, script: Option<(&str, &str)>) -> tempfile::TempDir {
- let dir = tempfile::tempdir().expect("temp dir");
- std::fs::write(dir.path().join(config::HOOKS_FILE_NAME), file).expect("write hooks.json");
- if let Some((name, body)) = script {
- let path = dir.path().join(name);
- std::fs::write(&path, body).expect("write script");
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
- .expect("chmod script");
- }
- }
- dir
-}
-
-fn definition(command: &str, dir: &std::path::Path) -> HookDefinition {
- HookDefinition {
- command: command.to_string(),
- kind: HookKind::Command,
- timeout: Some(20),
- matcher: None,
- loop_limit: None,
- fail_closed: false,
- model: None,
- enabled: true,
- layer: Some(HookLayer::Project),
- source_dir: Some(dir.to_path_buf()),
- }
-}
-
-#[test]
-fn event_names_resolve_across_dialects() {
- assert_eq!(HookEvent::parse("preToolUse"), Some(HookEvent::PreToolUse));
- assert_eq!(HookEvent::parse("PreToolUse"), Some(HookEvent::PreToolUse));
- assert_eq!(
- HookEvent::parse("pre_tool_use"),
- Some(HookEvent::PreToolUse)
- );
- assert_eq!(
- HookEvent::parse("UserPromptSubmit"),
- Some(HookEvent::BeforeSubmitPrompt)
- );
- assert_eq!(HookEvent::parse("notAnEvent"), None);
-}
-
-#[test]
-fn every_event_round_trips_through_its_wire_name() {
- for event in HookEvent::ALL {
- assert_eq!(HookEvent::parse(event.as_str()), Some(event), "{event}");
- }
-}
-
-#[test]
-fn unsupported_version_is_a_warning_not_a_silent_drop() {
- let parsed = config::parse_one(
- &PathBuf::from("/tmp/hooks.json"),
- HookLayer::Project,
- r#"{"version": 2, "hooks": {"preToolUse": [{"command": "x"}]}}"#,
- );
- assert!(parsed.is_empty());
- assert_eq!(parsed.warnings.len(), 1);
- assert!(parsed.warnings[0].contains("unsupported version 2"));
-}
-
-#[test]
-fn unknown_event_names_suggest_the_closest_match() {
- let parsed = config::parse_one(
- &PathBuf::from("/tmp/hooks.json"),
- HookLayer::Project,
- r#"{"version": 1, "hooks": {"preTool": [{"command": "x"}]}}"#,
- );
- assert!(parsed.is_empty());
- assert!(
- parsed.warnings[0].contains("did you mean 'preToolUse'"),
- "{:?}",
- parsed.warnings
- );
-}
-
-#[test]
-fn definitions_are_tagged_with_their_layer_not_the_files_claim() {
- let parsed = config::parse_one(
- &PathBuf::from("/etc/openhuman/hooks.json"),
- HookLayer::System,
- r#"{"version": 1, "hooks": {"preToolUse": [{"command": "x", "layer": "project"}]}}"#,
- );
- let definitions = parsed.for_event(HookEvent::PreToolUse);
- assert_eq!(definitions.len(), 1);
- assert_eq!(definitions[0].layer, Some(HookLayer::System));
-}
-
-#[test]
-fn strictest_verdict_wins_when_outputs_merge() {
- let mut allow = HookOutput {
- permission: Some(HookPermission::Allow),
- ..HookOutput::default()
- };
- allow.merge(HookOutput {
- permission: Some(HookPermission::Ask),
- ..HookOutput::default()
- });
- assert_eq!(allow.permission, Some(HookPermission::Ask));
- allow.merge(HookOutput::deny("no"));
- assert_eq!(allow.permission, Some(HookPermission::Deny));
- // A later allow cannot undo the denial.
- allow.merge(HookOutput {
- permission: Some(HookPermission::Allow),
- ..HookOutput::default()
- });
- assert_eq!(allow.permission, Some(HookPermission::Deny));
-}
-
-#[test]
-fn merged_messages_concatenate_and_rewrites_take_the_last() {
- let mut first = HookOutput {
- agent_message: Some("one".into()),
- updated_input: Some(serde_json::json!({"a": 1})),
- ..HookOutput::default()
- };
- first.merge(HookOutput {
- agent_message: Some("two".into()),
- updated_input: Some(serde_json::json!({"a": 2})),
- ..HookOutput::default()
- });
- assert_eq!(first.agent_message.as_deref(), Some("one\ntwo"));
- assert_eq!(first.updated_input.unwrap()["a"], 2);
-}
-
-#[cfg(unix)]
-#[tokio::test]
-async fn a_hook_that_prints_a_decision_is_honoured() {
- let dir = scratch(
- "{}",
- Some((
- "deny.sh",
- "#!/bin/sh\necho '{\"permission\":\"deny\",\"agent_message\":\"nope\"}'\n",
- )),
- );
- let run = exec::run(
- &definition("./deny.sh", dir.path()),
- &input(HookEvent::PreToolUse, tool_payload("shell")),
- &BTreeMap::new(),
- Duration::from_secs(10),
- )
- .await;
- assert!(run.error.is_none(), "{:?}", run.error);
- assert!(run.output.is_deny());
- assert_eq!(run.output.agent_message.as_deref(), Some("nope"));
-}
-
-#[cfg(unix)]
-#[tokio::test]
-async fn exit_code_two_denies_with_stderr_as_the_reason() {
- let dir = scratch(
- "{}",
- Some((
- "deny.sh",
- "#!/bin/sh\necho 'blocked by policy' 1>&2\nexit 2\n",
- )),
- );
- let run = exec::run(
- &definition("./deny.sh", dir.path()),
- &input(HookEvent::PreToolUse, tool_payload("shell")),
- &BTreeMap::new(),
- Duration::from_secs(10),
- )
- .await;
- assert!(run.output.is_deny());
- assert_eq!(
- run.output.agent_message.as_deref(),
- Some("blocked by policy")
- );
-}
-
-#[cfg(unix)]
-#[tokio::test]
-async fn a_crashing_hook_fails_open_by_default_and_closed_on_request() {
- let dir = scratch("{}", Some(("boom.sh", "#!/bin/sh\nexit 9\n")));
- let open = exec::run(
- &definition("./boom.sh", dir.path()),
- &input(HookEvent::PreToolUse, tool_payload("shell")),
- &BTreeMap::new(),
- Duration::from_secs(10),
- )
- .await;
- assert!(!open.output.is_deny());
- assert!(open.error.is_some(), "the failure is still reported");
-
- let mut closed = definition("./boom.sh", dir.path());
- closed.fail_closed = true;
- let closed = exec::run(
- &closed,
- &input(HookEvent::PreToolUse, tool_payload("shell")),
- &BTreeMap::new(),
- Duration::from_secs(10),
- )
- .await;
- assert!(closed.output.is_deny());
-}
-
-#[cfg(unix)]
-#[tokio::test]
-async fn a_hook_that_hangs_times_out_rather_than_stalling_the_turn() {
- let dir = scratch("{}", Some(("hang.sh", "#!/bin/sh\nsleep 30\n")));
- let mut hook = definition("./hang.sh", dir.path());
- hook.timeout = Some(1);
- let run = exec::run(
- &hook,
- &input(HookEvent::PreToolUse, tool_payload("shell")),
- &BTreeMap::new(),
- Duration::from_secs(1),
- )
- .await;
- assert!(run
- .error
- .as_deref()
- .unwrap_or_default()
- .contains("timed out"));
- assert!(
- !run.output.is_deny(),
- "a timeout fails open unless asked otherwise"
- );
-}
-
-#[cfg(unix)]
-#[tokio::test]
-async fn the_event_reaches_the_hook_on_stdin() {
- let dir = scratch(
- "{}",
- Some((
- "echo.sh",
- "#!/bin/sh\nbody=$(cat)\ncase \"$body\" in *beforeShellExecution*) \
- echo '{\"permission\":\"deny\",\"agent_message\":\"saw the event\"}';; \
- *) echo '{}';; esac\n",
- )),
- );
- let run = exec::run(
- &definition("./echo.sh", dir.path()),
- &input(
- HookEvent::BeforeShellExecution,
- HookPayload::Shell(ShellPayload {
- command: "rm -rf /".into(),
- sandbox: false,
- ..ShellPayload::default()
- }),
- ),
- &BTreeMap::new(),
- Duration::from_secs(10),
- )
- .await;
- assert_eq!(run.output.agent_message.as_deref(), Some("saw the event"));
-}
-
-#[cfg(unix)]
-#[tokio::test]
-async fn matchers_decide_which_hook_runs() {
- let engine = HookEngine::default();
- let dir = scratch(
- r#"{"version": 1, "hooks": {"preToolUse": [
- {"command": "./deny.sh", "matcher": "shell"}
- ]}}"#,
- Some(("deny.sh", "#!/bin/sh\necho '{\"permission\":\"deny\"}'\n")),
- );
- let loaded = config::load(None, Some(dir.path()));
- // The workspace layer reads `<dir>/hooks.json` directly.
- assert_eq!(loaded.len(), 1, "{:?}", loaded.warnings);
- engine.install(loaded).await;
-
- let denied = engine
- .dispatch(
- HookEvent::PreToolUse,
- input(HookEvent::PreToolUse, tool_payload("shell")),
- )
- .await;
- assert!(denied.is_deny());
-
- let allowed = engine
- .dispatch(
- HookEvent::PreToolUse,
- input(HookEvent::PreToolUse, tool_payload("memory_store")),
- )
- .await;
- assert!(!allowed.is_deny(), "a non-matching tool is untouched");
-}
-
-#[cfg(unix)]
-#[tokio::test]
-async fn a_denial_short_circuits_the_remaining_hooks() {
- let engine = HookEngine::default();
- let dir = scratch(
- r#"{"version": 1, "hooks": {"preToolUse": [
- {"command": "./deny.sh"},
- {"command": "./second.sh"}
- ]}}"#,
- Some((
- "deny.sh",
- "#!/bin/sh\necho '{\"permission\":\"deny\",\"agent_message\":\"first\"}'\n",
- )),
- );
- std::fs::write(
- dir.path().join("second.sh"),
- "#!/bin/sh\necho '{\"agent_message\":\"second\"}'\n",
- )
- .unwrap();
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(
- dir.path().join("second.sh"),
- std::fs::Permissions::from_mode(0o755),
- )
- .unwrap();
- }
- engine.install(config::load(None, Some(dir.path()))).await;
-
- let outcome = engine
- .dispatch(
- HookEvent::PreToolUse,
- input(HookEvent::PreToolUse, tool_payload("shell")),
- )
- .await;
- assert!(outcome.is_deny());
- assert_eq!(outcome.runs.len(), 1, "the second hook never ran");
- assert_eq!(outcome.denial_reason(), Some("first"));
-}
-
-#[cfg(unix)]
-#[tokio::test]
-async fn followups_stop_once_a_hook_exhausts_its_budget() {
- let engine = HookEngine::default();
- let dir = scratch(
- r#"{"version": 1, "hooks": {"stop": [
- {"command": "./again.sh", "loop_limit": 2}
- ]}}"#,
- Some((
- "again.sh",
- "#!/bin/sh\necho '{\"followup_message\":\"keep going\"}'\n",
- )),
- );
- engine.install(config::load(None, Some(dir.path()))).await;
-
- let mut granted = 0;
- for _ in 0..4 {
- let outcome = engine
- .dispatch(
- HookEvent::Stop,
- input(
- HookEvent::Stop,
- HookPayload::Stop(super::types::StopPayload {
- status: "completed".into(),
- loop_count: 0,
- iteration_count: None,
- }),
- ),
- )
- .await;
- if outcome.output.followup_message.is_some() {
- granted += 1;
- }
- }
- assert_eq!(granted, 2, "the loop limit caps the follow-ups");
-}
-
-#[tokio::test]
-async fn an_unconfigured_engine_reports_no_hooks_for_any_event() {
- let engine = HookEngine::default();
- for event in HookEvent::ALL {
- assert!(!engine.has_hooks(event).await, "{event}");
- }
-}
-
-#[test]
-fn configuring_an_unwired_event_warns_rather_than_failing_silently() {
- let parsed = config::parse_one(
- &PathBuf::from("/tmp/hooks.json"),
- HookLayer::Project,
- r#"{"version": 1, "hooks": {"sessionStart": [{"command": "x"}]}}"#,
- );
- assert_eq!(parsed.for_event(HookEvent::SessionStart).len(), 1);
- assert!(
- parsed.warnings.iter().any(|w| w.contains("never run")),
- "{:?}",
- parsed.warnings
- );
-}
-
-#[test]
-fn wired_events_do_not_warn() {
- let parsed = config::parse_one(
- &PathBuf::from("/tmp/hooks.json"),
- HookLayer::Project,
- r#"{"version": 1, "hooks": {"preToolUse": [{"command": "x"}]}}"#,
- );
- assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings);
-}
-
-#[test]
-fn a_payload_is_parsed_for_its_event_not_by_untagged_guessing() {
- // `{"trigger": "auto"}` also satisfies `SessionPayload` (every field
- // optional), which is declared earlier in the untagged enum — so untagged
- // dispatch would silently drop the trigger.
- let payload = HookPayload::from_value_for(
- HookEvent::PreCompact,
- serde_json::json!({"trigger": "auto", "message_count": 12}),
- )
- .expect("a compact payload parses");
- match payload {
- HookPayload::Compact(compact) => {
- assert_eq!(compact.trigger, "auto");
- assert_eq!(compact.message_count, Some(12));
- }
- other => panic!("expected a compact payload, got {other:?}"),
- }
-}
-
-#[test]
-fn a_payload_that_does_not_fit_its_event_is_rejected() {
- let error = HookPayload::from_value_for(HookEvent::BeforeShellExecution, serde_json::json!({}))
- .expect_err("a shell payload needs a command");
- assert!(error.contains("command"), "{error}");
-}
-
-#[test]
-fn a_relative_script_that_is_missing_is_reported_at_load_time() {
- let dir = tempfile::tempdir().expect("temp dir");
- std::fs::write(
- dir.path().join(config::HOOKS_FILE_NAME),
- r#"{"version": 1, "hooks": {"preToolUse": [{"command": "./nope.sh"}]}}"#,
- )
- .unwrap();
- let loaded = config::load(None, Some(dir.path()));
- assert!(
- loaded.warnings.iter().any(|w| w.contains("missing script")),
- "{:?}",
- loaded.warnings
- );
-}
-
-#[test]
-fn a_bare_command_name_is_not_second_guessed() {
- let dir = tempfile::tempdir().expect("temp dir");
- std::fs::write(
- dir.path().join(config::HOOKS_FILE_NAME),
- r#"{"version": 1, "hooks": {"preToolUse": [{"command": "audit-tool --strict"}]}}"#,
- )
- .unwrap();
- let loaded = config::load(None, Some(dir.path()));
- assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
-}
-
-/// `subagentStart` has a call site in `subagent_host`; `subagentStop` does
-/// not — `ops::subagent_stopped` is never called. Reporting it as wired is the
-/// one outcome `is_wired`'s own documentation calls the worst this system can
-/// produce: the author believes a policy is enforced and nothing says otherwise.
-#[test]
-fn subagent_stop_is_reported_as_not_yet_fired() {
- assert!(
- HookEvent::SubagentStart.is_wired(),
- "subagentStart is fired from subagent_host"
- );
- assert!(
- !HookEvent::SubagentStop.is_wired(),
- "nothing calls ops::subagent_stopped yet"
- );
-
- let parsed = config::parse_one(
- &PathBuf::from("/tmp/hooks.json"),
- HookLayer::Project,
- r#"{"version": 1, "hooks": {"subagentStop": [{"command": "x"}]}}"#,
- );
- assert_eq!(parsed.for_event(HookEvent::SubagentStop).len(), 1);
- assert!(
- parsed.warnings.iter().any(|w| w.contains("never run")),
- "{:?}",
- parsed.warnings
- );
-}
diff --git a/crates/openhuman-core/src/hooks/matcher.rs b/crates/openhuman-core/src/hooks/matcher.rs
deleted file mode 100644
index eebeaefec2..0000000000
--- a/crates/openhuman-core/src/hooks/matcher.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-//! Matcher semantics — which occurrences of an event reach a given hook.
-//!
-//! A matcher is one string, and what it is matched *against* depends on the
-//! event, exactly as in Cursor: tool events match the tool name, shell events
-//! match the command line, file events match the path. The syntax is uniform:
-//!
-//! * `*` or an absent matcher — everything.
-//! * `Shell|Read|Write` — alternation of exact, case-insensitive names.
-//! * `MCP:<tool>` — an MCP tool, by its registered name.
-//! * anything else — a regular expression, anchored nowhere (so `^rm ` and
-//! `secrets` both work as written).
-//!
-//! An invalid regular expression does **not** silently match everything. It
-//! matches nothing and logs, because a matcher that fails open turns a typo in
-//! a deny rule into a rule that fires on every call — the loudest possible
-//! failure mode is the safe one here only for allow rules, and the engine
-//! cannot tell which kind it is holding.
-
-use super::types::{HookEvent, HookPayload, ToolPayload};
-
-/// The string a matcher is compared against for a given event, or `None` when
-/// the event has no meaningful subject (session lifecycle, compaction).
-pub fn subject(event: HookEvent, payload: &HookPayload) -> Option<&str> {
- match (event, payload) {
- (
- HookEvent::PreToolUse
- | HookEvent::PostToolUse
- | HookEvent::PostToolUseFailure
- | HookEvent::BeforeMcpExecution
- | HookEvent::AfterMcpExecution,
- HookPayload::Tool(ToolPayload { tool_name, .. }),
- ) => Some(tool_name.as_str()),
- (
- HookEvent::BeforeShellExecution | HookEvent::AfterShellExecution,
- HookPayload::Shell(shell),
- ) => Some(shell.command.as_str()),
- (HookEvent::BeforeReadFile | HookEvent::AfterFileEdit, HookPayload::File(file)) => {
- Some(file.file_path.as_str())
- }
- (HookEvent::BeforeSubmitPrompt, HookPayload::Prompt(prompt)) => {
- Some(prompt.prompt.as_str())
- }
- (HookEvent::SubagentStart | HookEvent::SubagentStop, HookPayload::Subagent(subagent)) => {
- Some(subagent.subagent_type.as_str())
- }
- (HookEvent::AfterAgentResponse | HookEvent::AfterAgentThought, HookPayload::Text(text)) => {
- Some(text.text.as_str())
- }
- _ => None,
- }
-}
-
-/// Whether `matcher` selects `subject`.
-///
-/// An absent matcher selects everything. An event with no subject is selected
-/// by an absent or wildcard matcher only — a hook that asks to match `Shell`
-/// should not fire on `sessionStart`.
-pub fn matches(matcher: Option<&str>, subject: Option<&str>) -> bool {
- let Some(matcher) = matcher.map(str::trim).filter(|m| !m.is_empty()) else {
- return true;
- };
- if matcher == "*" {
- return true;
- }
- let Some(subject) = subject else {
- return false;
- };
- if matcher.contains('|') && !is_regex_syntax(matcher) {
- return matcher
- .split('|')
- .any(|alternative| name_matches(alternative.trim(), subject));
- }
- if !is_regex_syntax(matcher) {
- return name_matches(matcher, subject);
- }
- match regex::Regex::new(matcher) {
- Ok(regex) => regex.is_match(subject),
- Err(error) => {
- log::warn!("[hooks] invalid matcher regex {matcher:?}: {error}; matching nothing");
- false
- }
- }
-}
-
-/// Case-insensitive exact comparison, with `MCP:<tool>` reduced to `<tool>`.
-fn name_matches(matcher: &str, subject: &str) -> bool {
- let matcher = matcher.strip_prefix("MCP:").unwrap_or(matcher);
- matcher.eq_ignore_ascii_case(subject)
-}
-
-/// A matcher made only of identifier characters is treated as a literal name,
-/// not a regex — so `Shell` means the tool called `Shell` and nothing else.
-fn is_regex_syntax(matcher: &str) -> bool {
- matcher
- .chars()
- .any(|c| !(c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == ':' || c == '|'))
-}
-
-#[cfg(test)]
-#[path = "matcher_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/hooks/matcher_tests.rs b/crates/openhuman-core/src/hooks/matcher_tests.rs
deleted file mode 100644
index 0f0c69359b..0000000000
--- a/crates/openhuman-core/src/hooks/matcher_tests.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-use super::*;
-
-#[test]
-fn absent_matcher_selects_everything() {
- assert!(matches(None, Some("anything")));
- assert!(matches(None, None));
- assert!(matches(Some(" "), Some("anything")));
-}
-
-#[test]
-fn wildcard_selects_subjectless_events() {
- assert!(matches(Some("*"), None));
-}
-
-#[test]
-fn named_matcher_skips_subjectless_events() {
- assert!(!matches(Some("shell"), None));
-}
-
-#[test]
-fn literal_name_is_case_insensitive_and_exact() {
- assert!(matches(Some("Shell"), Some("shell")));
- assert!(!matches(Some("Shell"), Some("shell_extra")));
-}
-
-#[test]
-fn alternation_matches_any_branch() {
- assert!(matches(Some("Read|Write|Shell"), Some("write")));
- assert!(!matches(Some("Read|Write"), Some("shell")));
-}
-
-#[test]
-fn mcp_prefix_is_stripped() {
- assert!(matches(Some("MCP:search_docs"), Some("search_docs")));
-}
-
-#[test]
-fn regex_matcher_applies_to_command_lines() {
- assert!(matches(Some("^rm "), Some("rm -rf /tmp/x")));
- assert!(!matches(Some("^rm "), Some("echo rm ")));
-}
-
-#[test]
-fn invalid_regex_matches_nothing() {
- assert!(!matches(Some("["), Some("anything")));
-}
diff --git a/crates/openhuman-core/src/hooks/types.rs b/crates/openhuman-core/src/hooks/types.rs
deleted file mode 100644
index 986b88d28e..0000000000
--- a/crates/openhuman-core/src/hooks/types.rs
+++ /dev/null
@@ -1,591 +0,0 @@
-//! Wire types for the configurable hook system.
-//!
-//! The vocabulary is deliberately close to Cursor's `hooks.json` contract
-//! (<https://cursor.com/docs/hooks>) so a hook script written for one host runs
-//! unchanged on the other: same event names, same stdin envelope, same stdout
-//! decision object, same exit-code semantics.
-//!
-//! Two things are *not* copied verbatim, and both are widenings rather than
-//! divergences:
-//!
-//! * **Event names are matched loosely.** [`HookEvent::parse`] normalizes by
-//! lowercasing and dropping separators, so `preToolUse`, `PreToolUse` and
-//! `pre_tool_use` are the same event. A `hooks.json` authored for Cursor,
-//! for Claude Code, or by hand all resolve.
-//! * **One output struct serves every event.** A hook may return any subset of
-//! fields; the engine honours only the ones its event defines. That keeps a
-//! generic "deny everything from this script" hook usable across events
-//! without the author tracking which schema each one wants.
-
-use serde::{Deserialize, Serialize};
-use std::collections::BTreeMap;
-
-/// A lifecycle moment a configured hook can observe or gate.
-///
-/// Ordering of the variants follows the lifecycle, not the alphabet: session →
-/// prompt → tool → shell/file specialisations → subagent → wrap-up.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
-pub enum HookEvent {
- /// A new agent session was created.
- #[serde(rename = "sessionStart")]
- SessionStart,
- /// A session finished, was aborted, or errored.
- #[serde(rename = "sessionEnd")]
- SessionEnd,
- /// The user submitted a prompt, before it reaches the model.
- #[serde(rename = "beforeSubmitPrompt")]
- BeforeSubmitPrompt,
- /// Immediately before a tool executes. Can deny or rewrite the arguments.
- #[serde(rename = "preToolUse")]
- PreToolUse,
- /// After a tool returned successfully. Can append context for the model.
- #[serde(rename = "postToolUse")]
- PostToolUse,
- /// After a tool failed, timed out, or was denied.
- #[serde(rename = "postToolUseFailure")]
- PostToolUseFailure,
- /// Before a shell command runs — the shell-tool specialisation of
- /// [`Self::PreToolUse`], carrying the command line rather than raw args.
- #[serde(rename = "beforeShellExecution")]
- BeforeShellExecution,
- /// After a shell command completed.
- #[serde(rename = "afterShellExecution")]
- AfterShellExecution,
- /// Before an MCP tool call leaves the process.
- #[serde(rename = "beforeMCPExecution")]
- BeforeMcpExecution,
- /// After an MCP tool call returned.
- #[serde(rename = "afterMCPExecution")]
- AfterMcpExecution,
- /// Before a file is read into the model's context.
- #[serde(rename = "beforeReadFile")]
- BeforeReadFile,
- /// After a file was written or edited on disk.
- #[serde(rename = "afterFileEdit")]
- AfterFileEdit,
- /// A subagent is about to start.
- #[serde(rename = "subagentStart")]
- SubagentStart,
- /// A subagent finished.
- #[serde(rename = "subagentStop")]
- SubagentStop,
- /// The transcript is about to be compacted.
- #[serde(rename = "preCompact")]
- PreCompact,
- /// The assistant produced a message.
- #[serde(rename = "afterAgentResponse")]
- AfterAgentResponse,
- /// The assistant produced a reasoning block.
- #[serde(rename = "afterAgentThought")]
- AfterAgentThought,
- /// The agent loop finished a turn. Can inject a follow-up message.
- #[serde(rename = "stop")]
- Stop,
-}
-
-impl HookEvent {
- /// Every event, in lifecycle order. Used by the RPC surface and by the
- /// config validator to report unknown event keys with a usable suggestion.
- pub const ALL: [HookEvent; 18] = [
- HookEvent::SessionStart,
- HookEvent::SessionEnd,
- HookEvent::BeforeSubmitPrompt,
- HookEvent::PreToolUse,
- HookEvent::PostToolUse,
- HookEvent::PostToolUseFailure,
- HookEvent::BeforeShellExecution,
- HookEvent::AfterShellExecution,
- HookEvent::BeforeMcpExecution,
- HookEvent::AfterMcpExecution,
- HookEvent::BeforeReadFile,
- HookEvent::AfterFileEdit,
- HookEvent::SubagentStart,
- HookEvent::SubagentStop,
- HookEvent::PreCompact,
- HookEvent::AfterAgentResponse,
- HookEvent::AfterAgentThought,
- HookEvent::Stop,
- ];
-
- /// The canonical wire name, as it appears in `hooks.json` and in the
- /// `hook_event_name` field of the stdin envelope.
- pub fn as_str(self) -> &'static str {
- match self {
- HookEvent::SessionStart => "sessionStart",
- HookEvent::SessionEnd => "sessionEnd",
- HookEvent::BeforeSubmitPrompt => "beforeSubmitPrompt",
- HookEvent::PreToolUse => "preToolUse",
- HookEvent::PostToolUse => "postToolUse",
- HookEvent::PostToolUseFailure => "postToolUseFailure",
- HookEvent::BeforeShellExecution => "beforeShellExecution",
- HookEvent::AfterShellExecution => "afterShellExecution",
- HookEvent::BeforeMcpExecution => "beforeMCPExecution",
- HookEvent::AfterMcpExecution => "afterMCPExecution",
- HookEvent::BeforeReadFile => "beforeReadFile",
- HookEvent::AfterFileEdit => "afterFileEdit",
- HookEvent::SubagentStart => "subagentStart",
- HookEvent::SubagentStop => "subagentStop",
- HookEvent::PreCompact => "preCompact",
- HookEvent::AfterAgentResponse => "afterAgentResponse",
- HookEvent::AfterAgentThought => "afterAgentThought",
- HookEvent::Stop => "stop",
- }
- }
-
- /// Resolve a config key to an event, tolerating casing and separators.
- ///
- /// `preToolUse`, `PreToolUse`, `pre_tool_use` and `pre-tool-use` are the
- /// same event; so are Claude Code's `UserPromptSubmit` /
- /// `SubagentStop` spellings, which alias onto the closest OpenHuman moment.
- pub fn parse(key: &str) -> Option<HookEvent> {
- let normalized = normalize_key(key);
- if let Some(event) = HookEvent::ALL
- .iter()
- .copied()
- .find(|event| normalize_key(event.as_str()) == normalized)
- {
- return Some(event);
- }
- // Aliases from neighbouring hook dialects.
- match normalized.as_str() {
- "userpromptsubmit" => Some(HookEvent::BeforeSubmitPrompt),
- "notification" | "agentresponse" => Some(HookEvent::AfterAgentResponse),
- "agentthought" => Some(HookEvent::AfterAgentThought),
- "precompaction" | "compact" => Some(HookEvent::PreCompact),
- "sessionstop" => Some(HookEvent::SessionEnd),
- "toolusefailure" | "tooluseerror" => Some(HookEvent::PostToolUseFailure),
- _ => None,
- }
- }
-
- /// Whether the core currently fires this event.
- ///
- /// Every event in [`Self::ALL`] is a complete contract — it parses, it
- /// matches, it executes, and `hooks.test` fires it — but a few have no call
- /// site in the harness yet. Those return `false`, and the loader warns when
- /// a `hooks.json` registers one, because a hook that silently never runs is
- /// the worst outcome this system can produce: the author believes a policy
- /// is enforced and nothing says otherwise.
- ///
- /// Move an event here as its call site lands; do not flip one optimistically.
- pub fn is_wired(self) -> bool {
- !matches!(
- self,
- // No async seam at session construction yet — `AgentBuilder::build`
- // is synchronous, and `sessionStart` has to be able to return
- // context that reaches the system prompt.
- HookEvent::SessionStart
- | HookEvent::SessionEnd
- // Compaction runs inside the tinyagents middleware, which owns
- // its own trigger; surfacing it needs a seam upstream.
- | HookEvent::PreCompact
- // Reasoning blocks are not projected onto the post-turn seam
- // the bridge rides.
- | HookEvent::AfterAgentThought
- // `ops::subagent_stopped` exists and is complete, but nothing
- // calls it: `subagent_host` fires the start side and returns
- // from a dozen places without a stop. Until one lands, a
- // configured `subagentStop` hook never runs.
- | HookEvent::SubagentStop
- )
- }
-
- /// Whether a decision from this event can change what the core does.
- ///
- /// Gating events are run **sequentially** and their output is honoured;
- /// observational events are fire-and-forget, so the engine never blocks a
- /// turn on one. This is the single place that distinction is encoded.
- pub fn is_gating(self) -> bool {
- matches!(
- self,
- HookEvent::PreToolUse
- | HookEvent::BeforeShellExecution
- | HookEvent::BeforeMcpExecution
- | HookEvent::BeforeReadFile
- | HookEvent::BeforeSubmitPrompt
- | HookEvent::SubagentStart
- | HookEvent::SessionStart
- | HookEvent::PostToolUse
- | HookEvent::Stop
- | HookEvent::SubagentStop
- | HookEvent::PreCompact
- )
- }
-}
-
-impl std::fmt::Display for HookEvent {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.write_str(self.as_str())
- }
-}
-
-/// Lowercase and drop every separator, so hook-name dialects converge.
-pub(crate) fn normalize_key(key: &str) -> String {
- key.chars()
- .filter(|c| c.is_ascii_alphanumeric())
- .map(|c| c.to_ascii_lowercase())
- .collect()
-}
-
-/// The permission verdict a gating hook may return.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
-#[serde(rename_all = "lowercase")]
-pub enum HookPermission {
- /// Proceed. The absence of a verdict means the same thing.
- #[default]
- Allow,
- /// Refuse the action. The agent is told why.
- Deny,
- /// Escalate to the human through the existing approval gate.
- Ask,
-}
-
-/// The envelope handed to every hook on stdin.
-///
-/// Fields common to all events sit at the top level; the event-specific body is
-/// flattened in from [`HookPayload`], matching Cursor's shape where one JSON
-/// object carries both.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct HookInput {
- /// The event that fired, as its canonical wire name.
- pub hook_event_name: String,
- /// Conversation/thread identifier, when the moment belongs to one.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub conversation_id: Option<String>,
- /// Per-turn generation identifier, when known.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub generation_id: Option<String>,
- /// Agent session identifier, when the moment belongs to a session.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub session_id: Option<String>,
- /// Model driving the turn, when known.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub model: Option<String>,
- /// Canonical agent definition id, when known.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub agent_id: Option<String>,
- /// Core version string, so a hook can gate on host capability.
- pub openhuman_version: String,
- /// Filesystem roots the agent may act in — `action_dir` plus any turn
- /// workspace. First entry is the primary root.
- pub workspace_roots: Vec<String>,
- /// Working directory the action is scoped to, when the event has one.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub cwd: Option<String>,
- /// The event body.
- #[serde(flatten)]
- pub payload: HookPayload,
-}
-
-/// Event-specific fields, flattened into [`HookInput`].
-///
-/// Untagged on purpose: the discriminator a hook script reads is
-/// `hook_event_name`, exactly as in Cursor, so the body must not add a second
-/// tag key of its own.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-#[serde(untagged)]
-pub enum HookPayload {
- /// Events that carry no body beyond the common envelope.
- #[default]
- Empty,
- /// Tool lifecycle: pre, post, and failure.
- Tool(ToolPayload),
- /// Shell command execution.
- Shell(ShellPayload),
- /// File read or edit.
- File(FilePayload),
- /// Prompt submission.
- Prompt(PromptPayload),
- /// Subagent start/stop.
- Subagent(SubagentPayload),
- /// Session start/end.
- Session(SessionPayload),
- /// Transcript compaction.
- Compact(CompactPayload),
- /// Assistant text or reasoning.
- Text(TextPayload),
- /// Turn completion.
- Stop(StopPayload),
-}
-
-impl HookPayload {
- /// Parse a body **for a known event**.
- ///
- /// Never rely on `serde`'s untagged dispatch for this. Several bodies have
- /// only optional fields, so untagged matching picks whichever variant is
- /// declared first and happens to accept the object — `{"trigger":"auto"}`
- /// deserializes as a [`SessionPayload`] with everything `None`, silently
- /// throwing away the field the caller sent. The event already says which
- /// body this is; use it.
- pub fn from_value_for(event: HookEvent, value: serde_json::Value) -> Result<Self, String> {
- fn parse<T: serde::de::DeserializeOwned>(value: serde_json::Value) -> Result<T, String> {
- serde_json::from_value(value).map_err(|error| error.to_string())
- }
- if value.is_null() {
- return Ok(HookPayload::Empty);
- }
- Ok(match event {
- HookEvent::PreToolUse
- | HookEvent::PostToolUse
- | HookEvent::PostToolUseFailure
- | HookEvent::BeforeMcpExecution
- | HookEvent::AfterMcpExecution => HookPayload::Tool(parse(value)?),
- HookEvent::BeforeShellExecution | HookEvent::AfterShellExecution => {
- HookPayload::Shell(parse(value)?)
- }
- HookEvent::BeforeReadFile | HookEvent::AfterFileEdit => {
- HookPayload::File(parse(value)?)
- }
- HookEvent::BeforeSubmitPrompt => HookPayload::Prompt(parse(value)?),
- HookEvent::SubagentStart | HookEvent::SubagentStop => {
- HookPayload::Subagent(parse(value)?)
- }
- HookEvent::SessionStart | HookEvent::SessionEnd => HookPayload::Session(parse(value)?),
- HookEvent::PreCompact => HookPayload::Compact(parse(value)?),
- HookEvent::AfterAgentResponse | HookEvent::AfterAgentThought => {
- HookPayload::Text(parse(value)?)
- }
- HookEvent::Stop => HookPayload::Stop(parse(value)?),
- })
- }
-}
-
-/// Body for `preToolUse`, `postToolUse`, `postToolUseFailure`, and the MCP
-/// specialisations.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct ToolPayload {
- /// Registered tool name.
- pub tool_name: String,
- /// Arguments after argument-recovery normalization.
- pub tool_input: serde_json::Value,
- /// Provider call id, correlating the pre and post events.
- pub tool_use_id: String,
- /// Tool output, JSON-stringified. Absent before execution.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub tool_output: Option<String>,
- /// Wall-clock tool runtime in milliseconds. Absent before execution.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub duration_ms: Option<u64>,
- /// Failure text, on `postToolUseFailure`.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub error_message: Option<String>,
- /// Failure class: `timeout`, `error`, or `permission_denied`.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub failure_type: Option<String>,
-}
-
-/// Body for `beforeShellExecution` / `afterShellExecution`.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct ShellPayload {
- /// The full command line as it will be handed to the shell.
- pub command: String,
- /// Whether the command runs inside a sandbox backend.
- pub sandbox: bool,
- /// Combined output. Absent before execution.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub output: Option<String>,
- /// Wall-clock runtime in milliseconds. Absent before execution.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub duration_ms: Option<u64>,
-}
-
-/// Body for `beforeReadFile` / `afterFileEdit`.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct FilePayload {
- /// Absolute path of the file.
- pub file_path: String,
- /// Applied edits, on `afterFileEdit`.
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub edits: Vec<FileEdit>,
-}
-
-/// A single string replacement within a file.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct FileEdit {
- /// Text that was replaced. Empty for a whole-file write.
- pub old_string: String,
- /// Text that replaced it.
- pub new_string: String,
-}
-
-/// Body for `beforeSubmitPrompt`.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct PromptPayload {
- /// The user's message.
- pub prompt: String,
- /// Attachment paths riding along with the prompt.
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub attachments: Vec<String>,
-}
-
-/// Body for `subagentStart` / `subagentStop`.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct SubagentPayload {
- /// Agent definition id of the child.
- pub subagent_type: String,
- /// The task handed to the child.
- pub task: String,
- /// Parent conversation identifier.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub parent_conversation_id: Option<String>,
- /// Terminal status on stop: `completed`, `error`, or `aborted`.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub status: Option<String>,
- /// Child runtime in milliseconds, on stop.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub duration_ms: Option<u64>,
-}
-
-/// Body for `sessionStart` / `sessionEnd`.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct SessionPayload {
- /// Entrypoint that created the session (`cli`, `web_chat`, `cron`, …).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub entrypoint: Option<String>,
- /// Why the session ended, on `sessionEnd`.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub reason: Option<String>,
- /// Session lifetime in milliseconds, on `sessionEnd`.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub duration_ms: Option<u64>,
-}
-
-/// Body for `preCompact`.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct CompactPayload {
- /// `auto` or `manual`.
- pub trigger: String,
- /// Context occupancy as a percentage of the window.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub context_usage_percent: Option<f64>,
- /// Messages in the transcript at the moment of compaction.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub message_count: Option<usize>,
-}
-
-/// Body for `afterAgentResponse` / `afterAgentThought`.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct TextPayload {
- /// The assistant text or reasoning block.
- pub text: String,
- /// Reasoning duration in milliseconds, for thoughts.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub duration_ms: Option<u64>,
-}
-
-/// Body for `stop`.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct StopPayload {
- /// `completed`, `aborted`, or `error`.
- pub status: String,
- /// How many times this turn has already been extended by a follow-up.
- pub loop_count: u32,
- /// Model calls made during the turn.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub iteration_count: Option<usize>,
-}
-
-/// What a hook may return on stdout.
-///
-/// Every field is optional and every event honours only the subset it defines,
-/// so one script can serve several events without branching on the schema.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct HookOutput {
- /// Verdict for a gating event.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub permission: Option<HookPermission>,
- /// Shown to the human. Never enters the model transcript.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub user_message: Option<String>,
- /// Shown to the model — the reason a denial happened, or a nudge.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub agent_message: Option<String>,
- /// Replacement tool arguments, honoured on `preToolUse`.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub updated_input: Option<serde_json::Value>,
- /// Text appended to a tool result or to the session's system context.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub additional_context: Option<String>,
- /// `false` aborts prompt submission on `beforeSubmitPrompt`.
- #[serde(default, rename = "continue", skip_serializing_if = "Option::is_none")]
- pub continue_: Option<bool>,
- /// Injects another user turn on `stop` / `subagentStop`.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub followup_message: Option<String>,
- /// Environment variables added to every later hook in the session,
- /// honoured on `sessionStart`.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub env: Option<BTreeMap<String, String>>,
-}
-
-impl HookOutput {
- /// A denial carrying the reason the model should see.
- pub fn deny(agent_message: impl Into<String>) -> Self {
- Self {
- permission: Some(HookPermission::Deny),
- agent_message: Some(agent_message.into()),
- ..Self::default()
- }
- }
-
- /// Whether this output refuses the action.
- pub fn is_deny(&self) -> bool {
- self.permission == Some(HookPermission::Deny)
- }
-
- /// Whether this output escalates to the human.
- pub fn is_ask(&self) -> bool {
- self.permission == Some(HookPermission::Ask)
- }
-
- /// Fold a later hook's output into this one.
- ///
- /// Denial is sticky and beats `ask`, which beats `allow` — the strictest
- /// verdict from any hook wins, so adding a hook can never loosen a policy
- /// another one set. Text fields concatenate; `updated_input` and `env`
- /// are last-writer-wins because merging two rewrites of the same arguments
- /// has no defensible semantics.
- pub fn merge(&mut self, other: HookOutput) {
- self.permission = match (self.permission, other.permission) {
- (Some(HookPermission::Deny), _) | (_, Some(HookPermission::Deny)) => {
- Some(HookPermission::Deny)
- }
- (Some(HookPermission::Ask), _) | (_, Some(HookPermission::Ask)) => {
- Some(HookPermission::Ask)
- }
- (Some(HookPermission::Allow), _) | (_, Some(HookPermission::Allow)) => {
- Some(HookPermission::Allow)
- }
- (None, None) => None,
- };
- append_message(&mut self.user_message, other.user_message);
- append_message(&mut self.agent_message, other.agent_message);
- append_message(&mut self.additional_context, other.additional_context);
- append_message(&mut self.followup_message, other.followup_message);
- if other.updated_input.is_some() {
- self.updated_input = other.updated_input;
- }
- if let Some(env) = other.env {
- self.env.get_or_insert_with(BTreeMap::new).extend(env);
- }
- // `continue: false` is sticky for the same reason denial is.
- if other.continue_ == Some(false) || self.continue_ == Some(false) {
- self.continue_ = Some(false);
- } else if other.continue_.is_some() {
- self.continue_ = other.continue_;
- }
- }
-}
-
-fn append_message(slot: &mut Option<String>, addition: Option<String>) {
- let Some(addition) = addition.filter(|text| !text.is_empty()) else {
- return;
- };
- match slot {
- Some(existing) => {
- existing.push('\n');
- existing.push_str(&addition);
- }
- None => *slot = Some(addition),
- }
-}