use std::time::Duration;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::approval::{EffectKey, InterruptKind};
use crate::authority::Authority;
use crate::limits::LimitKind;
use crate::message::{Message, ToolCall};
use crate::outcome::RunOutcome;
use crate::provider::{ModelRequest, ModelResponse, ProviderError, Usage};
use crate::receipt::Receipt;
use crate::safeguard::Safeguard;
use crate::state::RunId;
use crate::stuck::StuckSignal;
use crate::tool::{ToolInfo, ToolOutput};
#[derive(Debug, Clone, Copy)]
pub struct HookContext<'a> {
pub run_id: RunId,
pub agent_id: &'a str,
pub session_id: &'a str,
pub turn: u32,
pub messages: &'a [Message],
pub receipts: &'a [Receipt],
pub usage: Usage,
pub run_usage: Usage,
pub untrusted_seen: bool,
pub declined: &'a [EffectKey],
}
impl HookContext<'_> {
pub fn run_receipts(&self) -> impl Iterator<Item = &Receipt> {
let run_id = self.run_id;
self.receipts.iter().filter(move |r| r.run_id == run_id)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ToolDecision {
Allow,
Deny {
reason: String,
},
Rewrite {
arguments: Value,
},
Interrupt {
reason: String,
kind: InterruptKind,
},
Answer {
output: ToolOutput,
},
}
impl ToolDecision {
pub fn ask(request: crate::OwnerApprovalRequest) -> Self {
ToolDecision::Interrupt {
reason: format!("approval required: {}", request.summary),
kind: InterruptKind::OwnerApproval(request),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum StopDecision {
Accept,
Continue { message: String },
Halt { reason: String },
AcceptUnmet { unmet: Vec<String> },
}
impl StopDecision {
pub fn permits_stop(&self) -> bool {
!matches!(self, Self::Continue { .. })
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum StuckDecision {
Nudge { message: String },
Stop,
Ignore,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ModelDecision {
Accept,
Reject { message: String },
Stop { reason: String },
}
#[derive(Debug, Clone, PartialEq)]
pub enum ModelErrorDecision {
Fail,
Retry { after: Duration },
Recover { response: ModelResponse },
Abort,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LimitDecision {
Stop,
Extend { amount: u64 },
Forbid,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HookPoint {
OnRunStart,
EditTranscript,
BeforeModel,
AfterModel,
AnswerModel,
OnModelError,
OnLimit,
BeforeTool,
AfterTool,
OnStop,
OnStuck,
OnRunEnd,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum HookFailure {
Panicked {
message: String,
},
TimedOut {
after_ms: u64,
},
Cancelled,
}
#[async_trait]
pub trait Hook: Send + Sync {
fn safeguards(&self) -> &'static [Safeguard] {
&[]
}
fn name(&self) -> &'static str {
std::any::type_name::<Self>()
}
fn redactor(&self) -> Option<&dyn crate::redaction::Redact> {
None
}
fn timeout(&self) -> Option<Duration> {
None
}
fn authority(&self) -> Option<Authority> {
None
}
async fn on_run_start(&self, _ctx: &HookContext<'_>) {}
async fn edit_transcript(&self, _ctx: &HookContext<'_>) -> Option<Vec<Message>> {
None
}
async fn before_model(&self, _ctx: &HookContext<'_>, _request: &mut ModelRequest) {}
async fn answer_model(
&self,
_ctx: &HookContext<'_>,
_request: &ModelRequest,
) -> Option<ModelResponse> {
None
}
async fn after_model(
&self,
_ctx: &HookContext<'_>,
_response: &mut ModelResponse,
) -> ModelDecision {
ModelDecision::Accept
}
async fn on_model_error(
&self,
_ctx: &HookContext<'_>,
_error: &ProviderError,
) -> ModelErrorDecision {
ModelErrorDecision::Fail
}
async fn on_limit(&self, _ctx: &HookContext<'_>, _limit: LimitKind) -> LimitDecision {
LimitDecision::Stop
}
async fn before_tool(
&self,
_ctx: &HookContext<'_>,
_call: &ToolCall,
_tool: &ToolInfo,
) -> ToolDecision {
ToolDecision::Allow
}
async fn after_tool(
&self,
_ctx: &HookContext<'_>,
_receipt: &Receipt,
_output: &mut ToolOutput,
) {
}
async fn on_stop(&self, _ctx: &HookContext<'_>, _final_text: &str) -> StopDecision {
StopDecision::Accept
}
async fn on_run_end(&self, _ctx: &HookContext<'_>, _outcome: &RunOutcome) {}
async fn on_stuck(
&self,
_ctx: &HookContext<'_>,
_signal: &StuckSignal,
) -> Option<StuckDecision> {
None
}
}