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, TodoItem, 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 /// Current todo list state.
106 pub todo_items: &'a [TodoItem],
107 /// Hash of the currently exposed tool surface.
108 pub tool_surface_hash: &'a str,
109 /// Whether background work is still active.
110 pub has_background_tasks: bool,
111 /// Structured snapshot of the currently assembled context window.
112 pub window: &'a ContextWindowSnapshot,
113}
114
115/// Reason why the agent stopped.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum StopReason {
118 /// Query completed successfully.
119 Complete,
120 /// No more tool calls in the response.
121 NoToolCalls,
122 /// Maximum iterations reached.
123 MaxIterations,
124 /// Model signaled end of turn.
125 EndTurn,
126}
127
128/// Action to take before a tool is executed.
129#[derive(Debug, Clone)]
130pub enum PreToolAction {
131 /// Allow the tool to execute.
132 Allow,
133 /// Deny the tool execution. The reason is sent to the LLM as an error.
134 Deny(String),
135 /// Abort the agent run entirely with an error.
136 Abort(String),
137}
138
139/// Action to take after a tool is executed.
140#[derive(Debug, Clone)]
141pub enum PostToolAction {
142 /// Keep the original tool result.
143 Keep,
144 /// Replace the tool result with a custom value.
145 Replace(ToolResult),
146 /// Abort the agent run entirely with an error.
147 Abort(String),
148}
149
150/// Action to take at a safe turn boundary.
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub enum TurnBoundaryAction {
153 /// Continue with the next model request.
154 Continue,
155 /// End the current run cleanly after the processed tool batch.
156 EndTurn,
157}
158
159/// Trait for intercepting agent operations.
160///
161/// All methods have default no-op implementations.
162/// Implement only the methods you need.
163///
164/// Hooks are composed using the [`HCons`] type, allowing multiple hooks to be
165/// chained together at compile time with zero runtime overhead.
166pub trait Hook: Send + Sync {
167 /// Called before a tool is executed.
168 ///
169 /// Return `PreToolAction::Deny` to reject the tool call (reason sent to LLM),
170 /// or `PreToolAction::Abort` to stop the agent entirely.
171 fn pre_tool_use(
172 &self,
173 _ctx: &ToolUseContext<'_>,
174 ) -> impl std::future::Future<Output = PreToolAction> + Send {
175 async { PreToolAction::Allow }
176 }
177
178 /// Called after a tool is executed.
179 ///
180 /// Return `PostToolAction::Replace` to override the tool result, or
181 /// `PostToolAction::Abort` to stop the agent.
182 fn post_tool_use(
183 &self,
184 _ctx: &ToolResultContext<'_>,
185 ) -> impl std::future::Future<Output = PostToolAction> + Send {
186 async { PostToolAction::Keep }
187 }
188
189 /// Called when the agent is about to stop.
190 ///
191 /// Return `Some(error)` to convert a successful stop into an error.
192 fn on_stop(
193 &self,
194 _ctx: &StopContext<'_>,
195 ) -> impl std::future::Future<Output = Option<String>> + Send {
196 async { None }
197 }
198
199 /// Called when text is streamed from the LLM.
200 ///
201 /// This is for observation only.
202 fn on_text(&self, _text: &str) -> impl std::future::Future<Output = ()> + Send {
203 async {}
204 }
205
206 /// Called after a full tool/result cycle is committed into agent memory,
207 /// before the next model request begins.
208 fn on_turn_boundary(
209 &self,
210 _ctx: &TurnBoundaryContext<'_>,
211 ) -> impl std::future::Future<Output = TurnBoundaryAction> + Send {
212 async { TurnBoundaryAction::Continue }
213 }
214
215 /// Called when the runtime emits a structured checkpoint.
216 ///
217 /// Return `Some(error)` to fail the run immediately.
218 fn on_checkpoint(
219 &self,
220 _ctx: &CheckpointContext<'_>,
221 ) -> impl std::future::Future<Output = Option<String>> + Send {
222 async { None }
223 }
224}
225
226/// No-op implementation for unit type (base case for `HCons`).
227impl Hook for () {}
228
229/// Heterogeneous list cons cell for composing hooks at compile time.
230///
231/// This allows chaining multiple hooks together without boxing or dynamic dispatch.
232///
233/// # Example
234///
235/// ```rust,ignore
236/// let agent = Agent::builder(llm)
237/// .hook(LoggingHook)
238/// .hook(ConfirmationHook)
239/// .build();
240/// // Creates Agent<LLM, HCons<ConfirmationHook, HCons<LoggingHook, ()>>>
241/// ```
242#[derive(Debug, Clone, Copy, Default)]
243pub struct HCons<Head, Tail> {
244 /// The first hook in the chain.
245 pub head: Head,
246 /// The remaining hooks.
247 pub tail: Tail,
248}
249
250impl<Head, Tail> HCons<Head, Tail> {
251 /// Creates a new hook chain.
252 #[must_use]
253 pub const fn new(head: Head, tail: Tail) -> Self {
254 Self { head, tail }
255 }
256}
257
258impl<Head, Tail> Hook for HCons<Head, Tail>
259where
260 Head: Hook,
261 Tail: Hook,
262{
263 async fn pre_tool_use(&self, ctx: &ToolUseContext<'_>) -> PreToolAction {
264 match self.head.pre_tool_use(ctx).await {
265 PreToolAction::Allow => self.tail.pre_tool_use(ctx).await,
266 other => other,
267 }
268 }
269
270 async fn post_tool_use(&self, ctx: &ToolResultContext<'_>) -> PostToolAction {
271 match self.head.post_tool_use(ctx).await {
272 PostToolAction::Keep => self.tail.post_tool_use(ctx).await,
273 other => other,
274 }
275 }
276
277 async fn on_stop(&self, ctx: &StopContext<'_>) -> Option<String> {
278 if let Some(err) = self.head.on_stop(ctx).await {
279 return Some(err);
280 }
281 self.tail.on_stop(ctx).await
282 }
283
284 async fn on_text(&self, text: &str) {
285 self.head.on_text(text).await;
286 self.tail.on_text(text).await;
287 }
288
289 async fn on_turn_boundary(&self, ctx: &TurnBoundaryContext<'_>) -> TurnBoundaryAction {
290 match self.head.on_turn_boundary(ctx).await {
291 TurnBoundaryAction::Continue => self.tail.on_turn_boundary(ctx).await,
292 other @ TurnBoundaryAction::EndTurn => other,
293 }
294 }
295
296 async fn on_checkpoint(&self, ctx: &CheckpointContext<'_>) -> Option<String> {
297 if let Some(err) = self.head.on_checkpoint(ctx).await {
298 return Some(err);
299 }
300 self.tail.on_checkpoint(ctx).await
301 }
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 struct CountingHook {
309 count: std::sync::atomic::AtomicUsize,
310 }
311
312 impl CountingHook {
313 fn new() -> Self {
314 Self {
315 count: std::sync::atomic::AtomicUsize::new(0),
316 }
317 }
318 }
319
320 impl Hook for CountingHook {
321 fn pre_tool_use(
322 &self,
323 _ctx: &ToolUseContext<'_>,
324 ) -> impl std::future::Future<Output = PreToolAction> + Send {
325 self.count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
326 std::future::ready(PreToolAction::Allow)
327 }
328 }
329
330 #[tokio::test]
331 async fn test_unit_hook() {
332 let hook = ();
333 let ctx = ToolUseContext {
334 tool_name: "test",
335 arguments: "{}",
336 turn: 0,
337 message_count: 1,
338 };
339 let action = hook.pre_tool_use(&ctx).await;
340 assert!(matches!(action, PreToolAction::Allow));
341 }
342
343 #[tokio::test]
344 async fn test_hcons_chain() {
345 let chain = HCons::new(CountingHook::new(), HCons::new(CountingHook::new(), ()));
346
347 let ctx = ToolUseContext {
348 tool_name: "test",
349 arguments: "{}",
350 turn: 0,
351 message_count: 1,
352 };
353
354 let action = chain.pre_tool_use(&ctx).await;
355 assert!(matches!(action, PreToolAction::Allow));
356 }
357}