use std::path::PathBuf;
use std::sync::Arc;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio_util::sync::CancellationToken;
use super::budget_policy::SpendNode;
use super::exec::{Network, Process};
use crate::telemetry::TelemetrySink;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HookEvent {
PreToolUse,
PostToolUse,
PostToolUseFailure,
TurnStart,
TurnComplete,
SessionStart,
SessionEnd,
Stop,
StopFailure,
UserPromptSubmit,
PreCompact,
PostCompact,
PermissionRequested,
PermissionDenied,
Setup,
Notification,
SubagentStop,
SubagentStart,
TeammateIdle,
TaskCreated,
TaskCompleted,
Elicitation,
ElicitationResult,
WorktreeCreate,
WorktreeRemove,
InstructionsLoaded,
CwdChanged,
FileChanged,
PostSampling,
}
impl HookEvent {
pub const ALL: [HookEvent; 29] = [
HookEvent::PreToolUse,
HookEvent::PostToolUse,
HookEvent::PostToolUseFailure,
HookEvent::TurnStart,
HookEvent::TurnComplete,
HookEvent::SessionStart,
HookEvent::SessionEnd,
HookEvent::Stop,
HookEvent::StopFailure,
HookEvent::UserPromptSubmit,
HookEvent::PreCompact,
HookEvent::PostCompact,
HookEvent::PermissionRequested,
HookEvent::PermissionDenied,
HookEvent::Setup,
HookEvent::Notification,
HookEvent::SubagentStop,
HookEvent::SubagentStart,
HookEvent::TeammateIdle,
HookEvent::TaskCreated,
HookEvent::TaskCompleted,
HookEvent::Elicitation,
HookEvent::ElicitationResult,
HookEvent::WorktreeCreate,
HookEvent::WorktreeRemove,
HookEvent::InstructionsLoaded,
HookEvent::CwdChanged,
HookEvent::FileChanged,
HookEvent::PostSampling,
];
pub fn name(self) -> String {
format!("{self:?}")
}
}
#[derive(Debug, Clone, Serialize, Default)]
pub struct HookInput {
pub hook_event_name: String,
pub session_id: String,
pub cwd: String,
pub permission_mode: String,
pub depth: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_input: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_use_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_result: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_error: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub user_prompt: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub delivery: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub turn_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub stop_reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub agent_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub stop_hook_active: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub team_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub teammate_name: Option<String>,
#[serde(skip)]
pub spend: Option<Arc<SpendNode>>,
}
pub type HookAmbient = Arc<dyn Fn() -> HookInput + Send + Sync>;
impl HookInput {
pub fn lifecycle(
event: impl Into<String>,
session_id: impl Into<String>,
cwd: impl Into<String>,
permission_mode: impl Into<String>,
) -> Self {
Self {
hook_event_name: event.into(),
session_id: session_id.into(),
cwd: cwd.into(),
permission_mode: permission_mode.into(),
..Default::default()
}
}
pub fn with_depth(mut self, depth: u32) -> Self {
self.depth = depth;
self
}
pub fn with_turn_id(mut self, turn_id: impl Into<String>) -> Self {
self.turn_id = Some(turn_id.into());
self
}
pub fn with_stop_reason(mut self, reason: impl Into<String>) -> Self {
self.stop_reason = Some(reason.into());
self
}
pub fn with_agent_type(mut self, agent_type: Option<String>) -> Self {
self.agent_type = agent_type;
self
}
pub fn with_tool(mut self, name: impl Into<String>, input: serde_json::Value) -> Self {
self.tool_name = Some(name.into());
self.tool_input = Some(input);
self
}
pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
pub fn with_source(mut self, source: impl Into<String>) -> Self {
self.source = Some(source.into());
self
}
pub fn spending_into(mut self, spend: Option<Arc<SpendNode>>) -> Self {
self.spend = spend;
self
}
pub fn with_team(
mut self,
team_name: impl Into<String>,
teammate_name: impl Into<String>,
) -> Self {
self.team_name = Some(team_name.into());
self.teammate_name = Some(teammate_name.into());
self
}
pub fn from_ambient(ambient: &HookAmbient, event: impl Into<String>) -> Self {
Self::lifecycle_of(ambient(), event)
}
pub fn lifecycle_of(base: HookInput, event: impl Into<String>) -> Self {
Self::lifecycle(event, base.session_id, base.cwd, base.permission_mode)
.with_depth(base.depth)
.spending_into(base.spend)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HookBlock {
pub message: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct HookVerdict {
pub blocked: Option<HookBlock>,
pub approved: bool,
pub discontinued: bool,
pub discontinue_message: Option<String>,
pub updated_input: Option<serde_json::Value>,
pub context: Vec<String>,
}
#[async_trait]
pub trait Hooks: Send + Sync {
fn has_hooks_for(&self, event: HookEvent) -> bool;
async fn run(
&self,
event: HookEvent,
input: &HookInput,
stop: &CancellationToken,
) -> HookVerdict;
fn start_watching(&self, _paths: &[PathBuf], _ambient: HookAmbient) -> Result<(), String> {
Ok(())
}
fn watch_files(&self, _paths: &[PathBuf]) -> Result<(), String> {
Ok(())
}
async fn check_rewakes(&self, _stop: &CancellationToken, _ambient: HookInput) {}
fn route_host_calls(&self, _session_id: &str, _calls: &Arc<dyn super::host_call::HostCalls>) {}
}
pub struct NoHooks;
#[async_trait]
impl Hooks for NoHooks {
fn has_hooks_for(&self, _: HookEvent) -> bool {
false
}
async fn run(&self, _: HookEvent, _: &HookInput, _: &CancellationToken) -> HookVerdict {
HookVerdict::default()
}
}
#[async_trait]
pub trait PromptHookExecutor: Send + Sync {
async fn execute(
&self,
prompt: &str,
model: Option<&str>,
payload: &HookInput,
stop: &CancellationToken,
) -> Result<String, String>;
}
#[async_trait]
pub trait AgentHookExecutor: Send + Sync {
async fn execute(
&self,
prompt: &str,
model: Option<&str>,
payload: &HookInput,
stop: &CancellationToken,
) -> Result<String, AgentHookError>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentHookError {
NotJudged,
Failed(String),
}
pub struct HookSession {
pub session_id: String,
pub config: Option<serde_json::Value>,
pub search_dirs: Vec<PathBuf>,
pub project_untrusted: bool,
pub process: Arc<dyn Process>,
pub network: Arc<dyn Network>,
pub prompts: Arc<dyn PromptHookExecutor>,
pub agents: Arc<dyn AgentHookExecutor>,
pub telemetry: Arc<dyn TelemetrySink>,
pub wake: Option<tokio::sync::mpsc::UnboundedReceiver<()>>,
}
pub trait HooksFactory: Send + Sync {
fn build(&self, session: HookSession) -> Arc<dyn Hooks>;
}
pub fn configures_hooks(config: Option<&serde_json::Value>) -> bool {
use serde_json::Value;
match config {
None | Some(Value::Null) => false,
Some(Value::Object(events)) => events
.values()
.any(|hooks| !matches!(hooks, Value::Array(list) if list.is_empty())),
Some(_) => true,
}
}