aither_agent/hook.rs
1//! Hooks: where the embedder decides.
2//!
3//! Events observe; hooks are the control points. One [`Hooks`] value holds
4//! the embedder's decisions at every point the loop offers one, and each
5//! method has a default that changes nothing, so an implementation overrides
6//! only what it decides.
7//!
8//! # Example
9//!
10//! ```rust,ignore
11//! struct ReadOnly;
12//!
13//! impl Hooks for ReadOnly {
14//! async fn before_tool(&self, call: &ToolInvocation<'_>) -> ToolDecision {
15//! if call.name == "write" {
16//! ToolDecision::Deny("this agent only reads".into())
17//! } else {
18//! ToolDecision::Allow
19//! }
20//! }
21//! }
22//!
23//! let agent = Agent::builder(llm).hooks(ReadOnly).build();
24//! ```
25
26use std::time::Duration;
27
28use aither_core::llm::tool::ApprovalRequest;
29use aither_core::llm::{CallIdentity, ToolResult};
30
31use crate::context::ContextBlock;
32use crate::event::RunId;
33
34/// What the loop knows as it assembles a request.
35#[derive(Debug)]
36#[non_exhaustive]
37pub struct RequestCx<'a> {
38 /// The run the request belongs to.
39 pub run: &'a RunId,
40 /// The turn the request starts, counting from 1.
41 pub turn: usize,
42 /// Number of recent conversation messages currently in memory.
43 pub message_count: usize,
44}
45
46/// A tool call the model made, before it runs.
47#[derive(Debug)]
48#[non_exhaustive]
49pub struct ToolInvocation<'a> {
50 /// The call and the agent making it.
51 pub call: &'a CallIdentity,
52 /// The tool.
53 pub name: &'a str,
54 /// The arguments as the model made them.
55 pub arguments: &'a serde_json::Value,
56 /// The turn the call belongs to.
57 pub turn: usize,
58 /// Number of recent conversation messages currently in memory.
59 pub message_count: usize,
60}
61
62/// What [`Hooks::before_tool`] decides for a tool call.
63#[derive(Debug, Clone)]
64#[non_exhaustive]
65pub enum ToolDecision {
66 /// Run the call as the model made it.
67 Allow,
68 /// Do not run it; the model reads `reason` as the call's result.
69 Deny(String),
70 /// Run it with these arguments instead.
71 Rewrite(serde_json::Value),
72 /// Run it if the agent's [`Approver`](aither_core::llm::tool::Approver)
73 /// approves `request`; a denial reaches the model like
74 /// [`Deny`](Self::Deny). Without an approver the run fails.
75 Ask(ApprovalRequest),
76 /// End the run with this reason as its error.
77 Abort(String),
78}
79
80/// A tool call after it ran.
81///
82/// The error is the one the tool returned, typed, so a hook can downcast it.
83#[derive(Debug)]
84#[non_exhaustive]
85pub struct ToolOutcome {
86 /// The call and the agent that made it.
87 pub call: CallIdentity,
88 /// The tool.
89 pub name: String,
90 /// The arguments the call ran with.
91 pub arguments: serde_json::Value,
92 /// What the tool returned. A call a hook denied is an `Ok` error result.
93 pub result: Result<ToolResult, aither_core::Error>,
94 /// How long the tool ran.
95 pub duration: Duration,
96}
97
98impl ToolOutcome {
99 /// What the model reads of the call.
100 #[must_use]
101 pub fn for_model(&self) -> ToolResult {
102 match &self.result {
103 Ok(result) => result.clone(),
104 Err(error) => ToolResult::error(format!("Error: {error}")),
105 }
106 }
107}
108
109/// What [`Hooks::after_tool`] decides for a finished tool call.
110#[derive(Debug, Clone)]
111#[non_exhaustive]
112pub enum AfterTool {
113 /// The model reads what the tool returned.
114 Keep,
115 /// The model reads this instead.
116 Replace(ToolResult),
117 /// The model reads what the tool returned, and the conversation gains
118 /// this context as a durable block after the turn's results.
119 Append(String),
120 /// End the run with this reason as its error.
121 Abort(String),
122}
123
124/// The model ended its turn with no tool call.
125#[derive(Debug)]
126#[non_exhaustive]
127pub struct StopCx<'a> {
128 /// The model's reply.
129 pub final_text: &'a str,
130 /// The turn, counting from 1.
131 pub turn: usize,
132 /// Number of recent conversation messages currently in memory.
133 pub message_count: usize,
134}
135
136/// What [`Hooks::on_stop`] decides when the model ends its turn.
137#[derive(Debug, Clone, PartialEq, Eq)]
138#[non_exhaustive]
139pub enum StopDecision {
140 /// The run ends.
141 End,
142 /// The run goes on for another turn; the model reads `reason` as a
143 /// system reminder.
144 Continue {
145 /// Why the run is not over.
146 reason: String,
147 },
148}
149
150/// A turn that called tools has ended.
151#[derive(Debug)]
152#[non_exhaustive]
153pub struct TurnBoundaryContext<'a> {
154 /// The text the model wrote in the turn.
155 pub assistant_text: &'a str,
156 /// The turn, counting from 1.
157 pub turn: usize,
158 /// Number of recent conversation messages currently in memory.
159 pub message_count: usize,
160 /// The turn's tool calls and what became of them, in completion order.
161 pub outcomes: &'a [ToolOutcome],
162}
163
164/// What [`Hooks::on_turn_boundary`] decides at a turn's end.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166#[non_exhaustive]
167pub enum TurnBoundaryAction {
168 /// The run goes on.
169 Continue,
170 /// The run ends here, such as to let a waiting message in.
171 EndTurn,
172}
173
174/// The embedder's decisions at the loop's control points.
175pub trait Hooks: Send + Sync + 'static {
176 /// Blocks to put into the conversation before a request is sent.
177 fn before_request(
178 &self,
179 cx: &RequestCx<'_>,
180 ) -> impl std::future::Future<Output = Vec<ContextBlock>> + Send {
181 let _ = cx;
182 async { Vec::new() }
183 }
184
185 /// Whether a tool call runs, and how.
186 fn before_tool(
187 &self,
188 call: &ToolInvocation<'_>,
189 ) -> impl std::future::Future<Output = ToolDecision> + Send {
190 let _ = call;
191 async { ToolDecision::Allow }
192 }
193
194 /// What the model reads of a finished tool call.
195 fn after_tool(
196 &self,
197 outcome: &ToolOutcome,
198 ) -> impl std::future::Future<Output = AfterTool> + Send {
199 let _ = outcome;
200 async { AfterTool::Keep }
201 }
202
203 /// Whether the run ends when the model ends its turn without a tool
204 /// call.
205 fn on_stop(&self, cx: &StopCx<'_>) -> impl std::future::Future<Output = StopDecision> + Send {
206 let _ = cx;
207 async { StopDecision::End }
208 }
209
210 /// Whether the run goes on after a turn that called tools.
211 fn on_turn_boundary(
212 &self,
213 cx: &TurnBoundaryContext<'_>,
214 ) -> impl std::future::Future<Output = TurnBoundaryAction> + Send {
215 let _ = cx;
216 async { TurnBoundaryAction::Continue }
217 }
218}
219
220impl Hooks for () {}