aither_agent/hook.rs
1//! Hook system for intercepting agent operations.
2//!
3//! Hooks allow customizing agent behavior at key points:
4//! - Before/after tool calls
5//! - When the agent stops
6//! - When text is streamed
7//!
8//! # Example
9//!
10//! ```rust,ignore
11//! struct LoggingHook;
12//!
13//! impl Hook for LoggingHook {
14//! async fn pre_tool_use(&self, ctx: &ToolUseContext<'_>) -> PreToolAction {
15//! println!("Calling: {}", ctx.tool_name);
16//! PreToolAction::Allow
17//! }
18//! }
19//!
20//! let agent = Agent::builder(llm)
21//! .hook(LoggingHook)
22//! .build();
23//! ```
24
25use std::time::Duration;
26
27use aither_core::llm::ToolResult;
28
29use crate::{ContextCheckpoint, context_window::ContextWindowSnapshot};
30
31/// Context provided to hooks before a tool is called.
32#[derive(Debug)]
33pub struct ToolUseContext<'a> {
34 /// Name of the tool being called.
35 pub tool_name: &'a str,
36 /// JSON-encoded arguments.
37 pub arguments: &'a str,
38 /// Current turn number (0-indexed).
39 pub turn: usize,
40 /// Number of messages in the conversation.
41 pub message_count: usize,
42}
43
44/// Context provided to hooks after a tool is executed.
45#[derive(Debug)]
46pub struct ToolResultContext<'a> {
47 /// Name of the tool that was called.
48 pub tool_name: &'a str,
49 /// JSON-encoded arguments that were passed.
50 pub arguments: &'a str,
51 /// Structured result of the tool execution.
52 pub result: &'a ToolResult,
53 /// Time taken to execute the tool.
54 pub duration: Duration,
55}
56
57/// Context provided to hooks when the agent is about to stop.
58#[derive(Debug)]
59pub struct StopContext<'a> {
60 /// The final response text.
61 pub final_text: &'a str,
62 /// Total number of turns taken.
63 pub turns: usize,
64 /// Reason for stopping.
65 pub reason: StopReason,
66}
67
68/// Context provided to hooks at a safe iteration boundary.
69///
70/// This boundary happens after the agent has fully processed the last batch of
71/// tool results and updated its internal context, but before it starts the next
72/// model request.
73#[derive(Debug)]
74pub struct TurnBoundaryContext<'a> {
75 /// Assistant text produced before the last tool batch.
76 pub assistant_text: &'a str,
77 /// Current turn number (1-indexed within the agent loop).
78 pub turn: usize,
79 /// Number of recent conversation messages after processing the tool batch.
80 pub message_count: usize,
81}
82
83/// Reason why a checkpoint is being emitted.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum CheckpointReason {
86 /// A full tool/result cycle was committed and the next model request has not started yet.
87 TurnBoundary,
88 /// The run is about to stop with the current context state.
89 Stop,
90}
91
92/// Structured checkpoint payload emitted from the runtime.
93#[derive(Debug)]
94pub struct CheckpointContext<'a> {
95 /// Why this checkpoint was emitted.
96 pub reason: CheckpointReason,
97 /// Assistant text produced in the current turn before this checkpoint.
98 pub assistant_text: &'a str,
99 /// Current turn number (1-indexed within the agent loop).
100 pub turn: usize,
101 /// Number of recent conversation messages currently in memory.
102 pub message_count: usize,
103 /// Structured runtime context after the latest turn mutations.
104 pub context: &'a ContextCheckpoint,
105 /// Hash of the currently exposed tool surface.
106 pub tool_surface_hash: &'a str,
107 /// Whether background work is still active.
108 pub has_background_tasks: bool,
109 /// Structured snapshot of the currently assembled context window.
110 pub window: &'a ContextWindowSnapshot,
111}
112
113/// Reason why the agent stopped.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub enum StopReason {
116 /// Query completed successfully.
117 Complete,
118 /// No more tool calls in the response.
119 NoToolCalls,
120 /// Maximum iterations reached.
121 MaxIterations,
122 /// Model signaled end of turn.
123 EndTurn,
124}
125
126/// Action to take before a tool is executed.
127#[derive(Debug, Clone)]
128pub enum PreToolAction {
129 /// Allow the tool to execute.
130 Allow,
131 /// Deny the tool execution. The reason is sent to the LLM as an error.
132 Deny(String),
133 /// Abort the agent run entirely with an error.
134 Abort(String),
135}
136
137/// Action to take after a tool is executed.
138#[derive(Debug, Clone)]
139pub enum PostToolAction {
140 /// Keep the original tool result.
141 Keep,
142 /// Replace the tool result with a custom value.
143 Replace(ToolResult),
144 /// Abort the agent run entirely with an error.
145 Abort(String),
146}
147
148/// Action to take at a safe turn boundary.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub enum TurnBoundaryAction {
151 /// Continue with the next model request.
152 Continue,
153 /// End the current run cleanly after the processed tool batch.
154 EndTurn,
155}
156
157/// Trait for intercepting agent operations.
158///
159/// All methods have default no-op implementations.
160/// Implement only the methods you need.
161///
162/// Hooks are composed using the [`HCons`] type, allowing multiple hooks to be
163/// chained together at compile time with zero runtime overhead.
164pub trait Hook: Send + Sync {
165 /// Called before a tool is executed.
166 ///
167 /// Return `PreToolAction::Deny` to reject the tool call (reason sent to LLM),
168 /// or `PreToolAction::Abort` to stop the agent entirely.
169 fn pre_tool_use(
170 &self,
171 _ctx: &ToolUseContext<'_>,
172 ) -> impl std::future::Future<Output = PreToolAction> + Send {
173 async { PreToolAction::Allow }
174 }
175
176 /// Called after a tool is executed.
177 ///
178 /// Return `PostToolAction::Replace` to override the tool result, or
179 /// `PostToolAction::Abort` to stop the agent.
180 fn post_tool_use(
181 &self,
182 _ctx: &ToolResultContext<'_>,
183 ) -> impl std::future::Future<Output = PostToolAction> + Send {
184 async { PostToolAction::Keep }
185 }
186
187 /// Called when the agent is about to stop.
188 ///
189 /// Return `Some(error)` to convert a successful stop into an error.
190 fn on_stop(
191 &self,
192 _ctx: &StopContext<'_>,
193 ) -> impl std::future::Future<Output = Option<String>> + Send {
194 async { None }
195 }
196
197 /// Called when text is streamed from the LLM.
198 ///
199 /// This is for observation only.
200 fn on_text(&self, _text: &str) -> impl std::future::Future<Output = ()> + Send {
201 async {}
202 }
203
204 /// Called after a full tool/result cycle is committed into agent memory,
205 /// before the next model request begins.
206 fn on_turn_boundary(
207 &self,
208 _ctx: &TurnBoundaryContext<'_>,
209 ) -> impl std::future::Future<Output = TurnBoundaryAction> + Send {
210 async { TurnBoundaryAction::Continue }
211 }
212
213 /// Called when the runtime emits a structured checkpoint.
214 ///
215 /// Return `Some(error)` to fail the run immediately.
216 fn on_checkpoint(
217 &self,
218 _ctx: &CheckpointContext<'_>,
219 ) -> impl std::future::Future<Output = Option<String>> + Send {
220 async { None }
221 }
222}
223
224/// No-op implementation for unit type (base case for `HCons`).
225impl Hook for () {}
226
227/// Heterogeneous list cons cell for composing hooks at compile time.
228///
229/// This allows chaining multiple hooks together without boxing or dynamic dispatch.
230///
231/// # Example
232///
233/// ```rust,ignore
234/// let agent = Agent::builder(llm)
235/// .hook(LoggingHook)
236/// .hook(ConfirmationHook)
237/// .build();
238/// // Creates Agent<LLM, HCons<ConfirmationHook, HCons<LoggingHook, ()>>>
239/// ```
240#[derive(Debug, Clone, Copy, Default)]
241pub struct HCons<Head, Tail> {
242 /// The first hook in the chain.
243 pub head: Head,
244 /// The remaining hooks.
245 pub tail: Tail,
246}
247
248impl<Head, Tail> HCons<Head, Tail> {
249 /// Creates a new hook chain.
250 #[must_use]
251 pub const fn new(head: Head, tail: Tail) -> Self {
252 Self { head, tail }
253 }
254}
255
256impl<Head, Tail> Hook for HCons<Head, Tail>
257where
258 Head: Hook,
259 Tail: Hook,
260{
261 async fn pre_tool_use(&self, ctx: &ToolUseContext<'_>) -> PreToolAction {
262 match self.head.pre_tool_use(ctx).await {
263 PreToolAction::Allow => self.tail.pre_tool_use(ctx).await,
264 other => other,
265 }
266 }
267
268 async fn post_tool_use(&self, ctx: &ToolResultContext<'_>) -> PostToolAction {
269 match self.head.post_tool_use(ctx).await {
270 PostToolAction::Keep => self.tail.post_tool_use(ctx).await,
271 other => other,
272 }
273 }
274
275 async fn on_stop(&self, ctx: &StopContext<'_>) -> Option<String> {
276 if let Some(err) = self.head.on_stop(ctx).await {
277 return Some(err);
278 }
279 self.tail.on_stop(ctx).await
280 }
281
282 async fn on_text(&self, text: &str) {
283 self.head.on_text(text).await;
284 self.tail.on_text(text).await;
285 }
286
287 async fn on_turn_boundary(&self, ctx: &TurnBoundaryContext<'_>) -> TurnBoundaryAction {
288 match self.head.on_turn_boundary(ctx).await {
289 TurnBoundaryAction::Continue => self.tail.on_turn_boundary(ctx).await,
290 other @ TurnBoundaryAction::EndTurn => other,
291 }
292 }
293
294 async fn on_checkpoint(&self, ctx: &CheckpointContext<'_>) -> Option<String> {
295 if let Some(err) = self.head.on_checkpoint(ctx).await {
296 return Some(err);
297 }
298 self.tail.on_checkpoint(ctx).await
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 struct CountingHook {
307 count: std::sync::atomic::AtomicUsize,
308 }
309
310 impl CountingHook {
311 fn new() -> Self {
312 Self {
313 count: std::sync::atomic::AtomicUsize::new(0),
314 }
315 }
316 }
317
318 impl Hook for CountingHook {
319 fn pre_tool_use(
320 &self,
321 _ctx: &ToolUseContext<'_>,
322 ) -> impl std::future::Future<Output = PreToolAction> + Send {
323 self.count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
324 std::future::ready(PreToolAction::Allow)
325 }
326 }
327
328 #[tokio::test]
329 async fn test_unit_hook() {
330 let hook = ();
331 let ctx = ToolUseContext {
332 tool_name: "test",
333 arguments: "{}",
334 turn: 0,
335 message_count: 1,
336 };
337 let action = hook.pre_tool_use(&ctx).await;
338 assert!(matches!(action, PreToolAction::Allow));
339 }
340
341 #[tokio::test]
342 async fn test_hcons_chain() {
343 let chain = HCons::new(CountingHook::new(), HCons::new(CountingHook::new(), ()));
344
345 let ctx = ToolUseContext {
346 tool_name: "test",
347 arguments: "{}",
348 turn: 0,
349 message_count: 1,
350 };
351
352 let action = chain.pre_tool_use(&ctx).await;
353 assert!(matches!(action, PreToolAction::Allow));
354 }
355}