agix-base 0.5.0

Agix — foundation types, traits, and context
Documentation
//! Lifecycle hooks as the engine sees them: the events, the payload a hook is
//! sent, the merged answer of one run, and the trait the session holds. The
//! runner that parses the settings' `hooks` and runs commands, prompts, HTTP
//! and agents is the `hooks` crate's (`hooks::Factory`); [`NoHooks`] is what a
//! session runs on without it. What each event carries and what an answer can
//! do there is documented by `hooks::catalog`.

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;

/// The events a settings file keys hooks by.
#[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 {
    /// Every variant, in declaration order.
    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,
    ];

    /// The name a settings file keys the event by, and the payload's
    /// `hook_event_name`.
    pub fn name(self) -> String {
        format!("{self:?}")
    }
}

/// What a hook is sent. Which optional fields are set depends on the event.
#[derive(Debug, Clone, Serialize, Default)]
pub struct HookInput {
    pub hook_event_name: String,
    pub session_id: String,
    pub cwd: String,
    pub permission_mode: String,
    /// How many delegations deep the session is; `0` for the root.
    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>,
    /// `"turn"` opens a turn, `"steer"` joins the running one.
    #[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>,
    /// The turn a hook that calls a model spends into. Never sent to a hook.
    #[serde(skip)]
    pub spend: Option<Arc<SpendNode>>,
}

/// The fields every payload of a session carries, read when the hook fires:
/// the permission mode changes under a session, so a snapshot would go stale.
pub type HookAmbient = Arc<dyn Fn() -> HookInput + Send + Sync>;

impl HookInput {
    /// The payload of `event`; callers set what their event carries on top.
    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
    }

    /// `ambient`'s session, cwd, permission mode, depth and spend under
    /// `event`.
    pub fn from_ambient(ambient: &HookAmbient, event: impl Into<String>) -> Self {
        Self::lifecycle_of(ambient(), event)
    }

    /// `base`'s session, cwd, permission mode, depth and spend under `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)
    }
}

/// A hook refused the action.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HookBlock {
    pub message: Option<String>,
}

/// What one run of an event's hooks came to, merged.
#[derive(Debug, Clone, Default)]
pub struct HookVerdict {
    pub blocked: Option<HookBlock>,
    /// A hook answered a permission question in advance.
    pub approved: bool,
    /// A hook asked to end the turn.
    pub discontinued: bool,
    pub discontinue_message: Option<String>,
    /// The input the action goes on with, where the event reads a rewrite.
    pub updated_input: Option<serde_json::Value>,
    /// System reminders for the model; empty when blocked or where the event
    /// takes none.
    pub context: Vec<String>,
}

/// A session's hooks; one is shared by a session and its delegates.
#[async_trait]
pub trait Hooks: Send + Sync {
    fn has_hooks_for(&self, event: HookEvent) -> bool;

    /// Run `event`'s hooks on `input`; once `stop` is cancelled those still
    /// running are stopped.
    async fn run(
        &self,
        event: HookEvent,
        input: &HookInput,
        stop: &CancellationToken,
    ) -> HookVerdict;

    /// Start the `FileChanged` watcher on `paths`, payloads from `ambient`.
    /// Called by the root session only.
    fn start_watching(&self, _paths: &[PathBuf], _ambient: HookAmbient) -> Result<(), String> {
        Ok(())
    }

    /// Add `paths` to a watcher already started; nothing when none was.
    fn watch_files(&self, _paths: &[PathBuf]) -> Result<(), String> {
        Ok(())
    }

    /// Re-run the hooks waiting to be woken once their wake signal came, on
    /// payloads from `ambient`.
    async fn check_rewakes(&self, _stop: &CancellationToken, _ambient: HookInput) {}

    /// The host calls of `session_id`, one of the sessions these hooks serve,
    /// for the hooks host connections answer.
    fn route_host_calls(&self, _session_id: &str, _calls: &Arc<dyn super::host_call::HostCalls>) {}
}

/// No hooks: nothing runs, nothing is refused.
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()
    }
}

/// Runs a `"type": "prompt"` hook: the model's answer, as the JSON text of a
/// hook response. Returns soon once `stop` is cancelled.
#[async_trait]
pub trait PromptHookExecutor: Send + Sync {
    async fn execute(
        &self,
        prompt: &str,
        model: Option<&str>,
        payload: &HookInput,
        stop: &CancellationToken,
    ) -> Result<String, String>;
}

/// Runs a `"type": "agent"` hook: the agent's `{"ok": bool, "reason": ...}`
/// as JSON text. The agent stops when `stop` does.
#[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 {
    /// The event is a hook agent's own, or one of its descendants': agent
    /// hooks do not judge those, so the hook does not apply rather than fail.
    NotJudged,
    Failed(String),
}

/// What a session's own hooks are built from.
pub struct HookSession {
    pub session_id: String,
    /// The settings' `hooks`, an untrusted project's already withheld.
    pub config: Option<serde_json::Value>,
    /// Where a command hook's bare script name is looked up, in order.
    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>,
    /// Signalled when background work ends, to re-run waiting rewake hooks.
    pub wake: Option<tokio::sync::mpsc::UnboundedReceiver<()>>,
}

pub trait HooksFactory: Send + Sync {
    fn build(&self, session: HookSession) -> Arc<dyn Hooks>;
}

/// Whether a settings `hooks` section asks for any hook: anything but
/// nothing, `null`, or events each with an empty list.
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,
    }
}