use std::time::Duration;
use aither_core::llm::{CallIdentity, ToolResult};
use crate::external_hook::{InjectedContext, LifecyclePayload};
use crate::{ContextCheckpoint, context_window::ContextWindowSnapshot};
#[derive(Debug)]
pub struct ToolUseContext<'a> {
pub call: &'a CallIdentity,
pub tool_name: &'a str,
pub arguments: &'a str,
pub turn: usize,
pub message_count: usize,
}
#[derive(Debug)]
pub struct ToolResultContext<'a> {
pub tool_name: &'a str,
pub arguments: &'a str,
pub result: &'a ToolResult,
pub duration: Duration,
}
#[derive(Debug)]
pub struct StopContext<'a> {
pub final_text: &'a str,
pub turns: usize,
pub reason: StopReason,
}
#[derive(Debug)]
pub struct TurnBoundaryContext<'a> {
pub assistant_text: &'a str,
pub turn: usize,
pub message_count: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckpointReason {
TurnBoundary,
Stop,
}
#[derive(Debug)]
pub struct CheckpointContext<'a> {
pub reason: CheckpointReason,
pub assistant_text: &'a str,
pub turn: usize,
pub message_count: usize,
pub context: &'a ContextCheckpoint,
pub tool_surface_hash: &'a str,
pub has_background_tasks: bool,
pub window: &'a ContextWindowSnapshot,
pub tasks: Option<&'a crate::tasks::TasksCheckpoint>,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
Complete,
NoToolCalls,
MaxIterations,
EndTurn,
AwaitingBackground,
}
#[derive(Debug, Clone)]
pub enum PreToolAction {
Allow,
Deny(String),
Abort(String),
}
#[derive(Debug, Clone)]
pub enum PostToolAction {
Keep,
Replace(ToolResult),
Abort(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TurnBoundaryAction {
Continue,
EndTurn,
}
pub trait Hook: Send + Sync {
fn pre_tool_use(
&self,
_ctx: &ToolUseContext<'_>,
) -> impl std::future::Future<Output = PreToolAction> + Send {
async { PreToolAction::Allow }
}
fn post_tool_use(
&self,
_ctx: &ToolResultContext<'_>,
) -> impl std::future::Future<Output = PostToolAction> + Send {
async { PostToolAction::Keep }
}
fn on_stop(
&self,
_ctx: &StopContext<'_>,
) -> impl std::future::Future<Output = Option<String>> + Send {
async { None }
}
fn on_text(&self, _text: &str) -> impl std::future::Future<Output = ()> + Send {
async {}
}
fn on_turn_boundary(
&self,
_ctx: &TurnBoundaryContext<'_>,
) -> impl std::future::Future<Output = TurnBoundaryAction> + Send {
async { TurnBoundaryAction::Continue }
}
fn on_checkpoint(
&self,
_ctx: &CheckpointContext<'_>,
) -> impl std::future::Future<Output = Option<String>> + Send {
async { None }
}
fn on_lifecycle<P: LifecyclePayload>(
&self,
_payload: &P,
) -> impl std::future::Future<Output = ()> + Send {
async {}
}
fn take_injected_context(&self) -> Vec<InjectedContext> {
Vec::new()
}
}
impl Hook for () {}
#[derive(Debug, Clone, Copy, Default)]
pub struct HCons<Head, Tail> {
pub head: Head,
pub tail: Tail,
}
impl<Head, Tail> HCons<Head, Tail> {
#[must_use]
pub const fn new(head: Head, tail: Tail) -> Self {
Self { head, tail }
}
}
impl<Head, Tail> Hook for HCons<Head, Tail>
where
Head: Hook,
Tail: Hook,
{
async fn pre_tool_use(&self, ctx: &ToolUseContext<'_>) -> PreToolAction {
match self.head.pre_tool_use(ctx).await {
PreToolAction::Allow => self.tail.pre_tool_use(ctx).await,
other => other,
}
}
async fn post_tool_use(&self, ctx: &ToolResultContext<'_>) -> PostToolAction {
match self.head.post_tool_use(ctx).await {
PostToolAction::Keep => self.tail.post_tool_use(ctx).await,
other => other,
}
}
async fn on_stop(&self, ctx: &StopContext<'_>) -> Option<String> {
if let Some(err) = self.head.on_stop(ctx).await {
return Some(err);
}
self.tail.on_stop(ctx).await
}
async fn on_text(&self, text: &str) {
self.head.on_text(text).await;
self.tail.on_text(text).await;
}
async fn on_turn_boundary(&self, ctx: &TurnBoundaryContext<'_>) -> TurnBoundaryAction {
match self.head.on_turn_boundary(ctx).await {
TurnBoundaryAction::Continue => self.tail.on_turn_boundary(ctx).await,
other @ TurnBoundaryAction::EndTurn => other,
}
}
async fn on_checkpoint(&self, ctx: &CheckpointContext<'_>) -> Option<String> {
if let Some(err) = self.head.on_checkpoint(ctx).await {
return Some(err);
}
self.tail.on_checkpoint(ctx).await
}
async fn on_lifecycle<P: LifecyclePayload>(&self, payload: &P) {
futures::join!(
self.head.on_lifecycle(payload),
self.tail.on_lifecycle(payload)
);
}
fn take_injected_context(&self) -> Vec<InjectedContext> {
let mut context = self.head.take_injected_context();
context.extend(self.tail.take_injected_context());
context
}
}
#[cfg(test)]
mod tests {
use super::*;
struct CountingHook {
count: std::sync::atomic::AtomicUsize,
}
impl CountingHook {
fn new() -> Self {
Self {
count: std::sync::atomic::AtomicUsize::new(0),
}
}
}
impl Hook for CountingHook {
fn pre_tool_use(
&self,
_ctx: &ToolUseContext<'_>,
) -> impl std::future::Future<Output = PreToolAction> + Send {
self.count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
std::future::ready(PreToolAction::Allow)
}
}
fn test_call() -> CallIdentity {
CallIdentity::new(
aither_core::llm::ToolCallId::new("call_1"),
aither_core::llm::AgentIdentity::Main,
)
}
#[tokio::test]
async fn test_unit_hook() {
let hook = ();
let call = test_call();
let ctx = ToolUseContext {
call: &call,
tool_name: "test",
arguments: "{}",
turn: 0,
message_count: 1,
};
let action = hook.pre_tool_use(&ctx).await;
assert!(matches!(action, PreToolAction::Allow));
}
#[tokio::test]
async fn test_hcons_chain() {
let chain = HCons::new(CountingHook::new(), HCons::new(CountingHook::new(), ()));
let call = test_call();
let ctx = ToolUseContext {
call: &call,
tool_name: "test",
arguments: "{}",
turn: 0,
message_count: 1,
};
let action = chain.pre_tool_use(&ctx).await;
assert!(matches!(action, PreToolAction::Allow));
}
}