Skip to main content

aidaemon_core/
hook.rs

1use std::time::Duration;
2
3use async_trait::async_trait;
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7use crate::approval::{EffectKey, InterruptKind};
8use crate::authority::Authority;
9use crate::limits::LimitKind;
10use crate::message::{Message, ToolCall};
11use crate::outcome::RunOutcome;
12use crate::provider::{ModelRequest, ModelResponse, ProviderError, Usage};
13use crate::receipt::Receipt;
14use crate::safeguard::Safeguard;
15use crate::state::RunId;
16use crate::stuck::StuckSignal;
17use crate::tool::{ToolInfo, ToolOutput};
18
19/// Read-only view of the run handed to every hook.
20#[derive(Debug, Clone, Copy)]
21pub struct HookContext<'a> {
22    pub run_id: RunId,
23    pub agent_id: &'a str,
24    pub session_id: &'a str,
25    pub turn: u32,
26    pub messages: &'a [Message],
27    /// Receipts of the whole session; see [`HookContext::run_receipts`].
28    pub receipts: &'a [Receipt],
29    /// Usage of the whole session.
30    pub usage: Usage,
31    /// Usage of the current run.
32    pub run_usage: Usage,
33    /// The run has read untrusted content so far (see
34    /// [`crate::RunState::untrusted_seen`]).
35    pub untrusted_seen: bool,
36    /// Effects the owner declined earlier in this run (see
37    /// [`crate::RunState::declined`]).
38    pub declined: &'a [EffectKey],
39}
40
41impl HookContext<'_> {
42    /// Receipts produced by the current run only. Completion checks should
43    /// use this so work from an earlier run in the session is not credited.
44    pub fn run_receipts(&self) -> impl Iterator<Item = &Receipt> {
45        let run_id = self.run_id;
46        self.receipts.iter().filter(move |r| r.run_id == run_id)
47    }
48}
49
50/// What a `before_tool` hook decides about one call.
51#[derive(Debug, Clone, PartialEq)]
52pub enum ToolDecision {
53    Allow,
54    /// Refuse. The reason goes back to the model as the tool result, and a
55    /// `Denied` receipt is recorded.
56    Deny {
57        reason: String,
58    },
59    /// Replace the arguments and restart all hooks so earlier judgments
60    /// cannot authorize different effects. Identical arguments are a no-op;
61    /// more than 16 changes refuses the call. Rewriters should be idempotent.
62    Rewrite {
63        arguments: Value,
64    },
65    /// Pause the run before this call (for example, to ask a human). The run
66    /// returns [`crate::RunStatus::Interrupted`] with serializable state that
67    /// [`crate::Agent::resume`] continues later, in this or another process.
68    Interrupt {
69        reason: String,
70        /// Who the interruption waits for; resolvers settle the kinds they
71        /// own.
72        kind: InterruptKind,
73    },
74    /// Answer in the tool's place: the tool does not run and the model sees
75    /// `output`. For results the host already holds (a replayed receipt, a
76    /// suppressed duplicate) or a call deferred on purpose. The receipt is
77    /// [`crate::ReceiptStatus::Answered`]; an answer never ends the run (its
78    /// `finish` is dropped) and never counts as work done.
79    Answer {
80        output: ToolOutput,
81    },
82}
83
84impl ToolDecision {
85    /// Pause the run for the owner to answer `request`
86    /// ([`InterruptKind::OwnerApproval`]), with the summary as the reason.
87    /// Build the request with [`crate::OwnerApprovalRequest::for_call`] to
88    /// carry the call's declared effects, so a decline binds the rest of
89    /// the run.
90    pub fn ask(request: crate::OwnerApprovalRequest) -> Self {
91        ToolDecision::Interrupt {
92            reason: format!("approval required: {}", request.summary),
93            kind: InterruptKind::OwnerApproval(request),
94        }
95    }
96}
97
98/// What an `on_stop` hook decides when the model replies without tool calls.
99///
100/// Stopping and succeeding are separate decisions. A hook can let the run
101/// stop (more turns would not help: the work is blocked, deferred or its
102/// budget for asking is spent) while recording that the objective was not
103/// met. Such a run ends [`crate::RunStatus::Completed`] with
104/// [`crate::RunState::unmet`] filled, and
105/// [`crate::RunOutcome::is_succeeded`] is false.
106#[derive(Debug, Clone, PartialEq)]
107pub enum StopDecision {
108    /// Stop, and this hook has nothing against calling the run a success.
109    Accept,
110    /// Do not finish yet; append this message and run another turn.
111    Continue { message: String },
112    /// Stop now, whatever any other hook asked for, and record `reason` as
113    /// unmet: for a hook that knows more turns must not happen.
114    Halt { reason: String },
115    /// Stop, but the objective is not met. Each line names one unmet
116    /// requirement in words a person can read. The run ends `Completed`
117    /// (the model may not keep going) and never counts as succeeded.
118    AcceptUnmet { unmet: Vec<String> },
119}
120
121impl StopDecision {
122    /// Whether the run may stop (anything but [`StopDecision::Continue`]).
123    pub fn permits_stop(&self) -> bool {
124        !matches!(self, Self::Continue { .. })
125    }
126}
127
128/// What to do when the stuck detector fires.
129#[derive(Debug, Clone, PartialEq)]
130pub enum StuckDecision {
131    /// Tell the model it is repeating itself and keep going.
132    Nudge { message: String },
133    /// End the run with [`crate::RunStatus::Stuck`].
134    Stop,
135    /// Not stuck (for example, deliberate polling). Keep going silently.
136    Ignore,
137}
138
139/// What an `after_model` hook decides about a response.
140#[derive(Debug, Clone, PartialEq)]
141pub enum ModelDecision {
142    /// Carry on with the response as the hooks left it.
143    Accept,
144    /// Do not act on this response: none of its tool calls run and it is
145    /// not a final answer. Its text stays in the transcript, so the model
146    /// can see what it is correcting, followed by `message`, and another
147    /// turn runs. To keep the text from the model, clear it first.
148    Reject { message: String },
149    /// End the run now with [`crate::RunStatus::Stopped`]: none of the
150    /// response's tool calls run and it is not recorded. For a hook that
151    /// knows nothing more may happen, such as a spent budget.
152    Stop { reason: String },
153}
154
155/// What an `on_model_error` hook decides about a failed model call.
156#[derive(Debug, Clone, PartialEq)]
157pub enum ModelErrorDecision {
158    /// End the run with [`crate::RunStatus::ProviderFailed`].
159    Fail,
160    /// Wait, then run another turn. The transcript is untouched and
161    /// `before_model` runs again, so a hook can shrink the request or change
162    /// the model first. The wait stops on cancel and at the wall-clock
163    /// budget, and the retry counts as a turn: budgets bound the retries.
164    Retry { after: Duration },
165    /// Carry on with this response as if the model had given it.
166    Recover { response: ModelResponse },
167    /// End the run, whatever any other hook asked for.
168    Abort,
169}
170
171/// What an `on_limit` hook decides about a limit the run has reached.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum LimitDecision {
174    /// End the run with [`crate::RunStatus::LimitReached`].
175    Stop,
176    /// Raise this limit for the rest of the run. `amount` is in the limit's
177    /// own unit: turns, billable tokens, tool calls, or milliseconds. An
178    /// amount of zero is a [`LimitDecision::Stop`].
179    Extend { amount: u64 },
180    /// End the run, whatever any other hook granted.
181    Forbid,
182}
183
184/// A moment of the loop at which hooks run.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "snake_case")]
187pub enum HookPoint {
188    OnRunStart,
189    EditTranscript,
190    BeforeModel,
191    AfterModel,
192    AnswerModel,
193    OnModelError,
194    OnLimit,
195    BeforeTool,
196    AfterTool,
197    OnStop,
198    OnStuck,
199    OnRunEnd,
200}
201
202/// How a hook failed to give an answer.
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204#[serde(rename_all = "snake_case", tag = "kind")]
205pub enum HookFailure {
206    Panicked {
207        message: String,
208    },
209    TimedOut {
210        after_ms: u64,
211    },
212    /// The run was cancelled while the hook was working.
213    Cancelled,
214}
215
216/// Extension point for every policy. All methods have no-op defaults, so a
217/// hook implements only what it needs. Hooks run in registration order and
218/// outside the model's context window: they cost no tokens and the model
219/// cannot argue its way past them.
220///
221/// The kernel contains every call: a hook that panics, outlasts its time or
222/// is overtaken by a cancel has given no answer, an
223/// [`crate::Event::HookFailed`] is recorded, and the run goes on as that
224/// moment requires. A check that guards something fails closed; anything
225/// else fails open, because the run can go on without it:
226///
227/// | Point | With no answer |
228/// |---|---|
229/// | `before_tool` | the call is refused |
230/// | `after_tool` | the model does not see the result |
231/// | `after_model` | the response is not acted on and the run stops |
232/// | `on_stop` | the run ends with an unmet requirement, never as a success |
233/// | `on_limit`, `on_model_error` | the limit stands, the failure stands |
234/// | `edit_transcript` | the transcript stays as it was |
235/// | `on_run_start`, `before_model`, `on_stuck`, `on_run_end` | the run goes on |
236///
237/// `on_run_start`, `edit_transcript`, `answer_model` and `on_limit` are
238/// unstable: tests cover them
239/// but no shipped policy depends on them yet, so they may still change.
240///
241/// Timeouts and cancels stop a hook at its next `.await`, so a hook that
242/// blocks a thread is not interrupted: keep blocking work off the executor.
243#[async_trait]
244pub trait Hook: Send + Sync {
245    /// The safeguards this hook enforces. [`crate::AgentBuilder::build`]
246    /// requires every [`Safeguard::REQUIRED`] one to be covered by a hook
247    /// or an attestation.
248    fn safeguards(&self) -> &'static [Safeguard] {
249        &[]
250    }
251
252    /// How this hook is named in events and in a saved interruption. Stable
253    /// across restarts of the same build; override it to keep a hook's
254    /// identity across a rename.
255    fn name(&self) -> &'static str {
256        std::any::type_name::<Self>()
257    }
258
259    /// What this hook hides from everything that leaves the kernel. The
260    /// kernel applies it, with the secrets registered in
261    /// [`crate::redaction`], to model requests, events, receipts, the
262    /// question put to the owner and the saved state. Default: nothing.
263    fn redactor(&self) -> Option<&dyn crate::redaction::Redact> {
264        None
265    }
266
267    /// How long one call of this hook may take, in place of
268    /// [`crate::Limits::hook_timeout`]. The wall-clock budget still applies.
269    fn timeout(&self) -> Option<Duration> {
270        None
271    }
272
273    /// The authority this hook enforces, if it enforces one. Passed to
274    /// tools so a tool that starts another run can hold it to the same.
275    fn authority(&self) -> Option<Authority> {
276        None
277    }
278
279    /// A new run is about to take its first turn: load what the other hooks
280    /// will need. Resuming a paused run is not a start. A process that dies
281    /// before the first turn starts the run again, so make this repeatable.
282    async fn on_run_start(&self, _ctx: &HookContext<'_>) {}
283
284    /// Replace the stored transcript at the start of a turn, for example
285    /// with a summary. Prefer a `before_model` edit, which changes one
286    /// request and loses nothing; use this when the shortened history should
287    /// be what later turns and resumes start from.
288    ///
289    /// Hooks run in order and each sees the last one's edit. The kernel
290    /// refuses an empty edit, one with no user message, and one that splits
291    /// a tool call from its result (providers reject those requests), and
292    /// keeps the transcript it had. Receipts and the run's trust state do
293    /// not change: they are the record of what happened, whatever the
294    /// transcript says now.
295    async fn edit_transcript(&self, _ctx: &HookContext<'_>) -> Option<Vec<Message>> {
296        None
297    }
298
299    /// Edit the request before it is sent: trim context, inject memory,
300    /// change the model or tool choice.
301    async fn before_model(&self, _ctx: &HookContext<'_>, _request: &mut ModelRequest) {}
302
303    /// Answer in the model's place, for example from a cache. It runs after
304    /// every `before_model` hook, so it sees the final request. The first
305    /// answer wins; the response is treated as the model's, `after_model`
306    /// included, and the turn counts.
307    async fn answer_model(
308        &self,
309        _ctx: &HookContext<'_>,
310        _request: &ModelRequest,
311    ) -> Option<ModelResponse> {
312        None
313    }
314
315    /// The model replied. Check or rewrite the response before it is
316    /// recorded or acted on; the first `Reject` or `Stop` wins. Calls a hook adds or
317    /// changes face the same validation and `before_tool` hooks as any
318    /// other. Streamed text has already gone out as events, and the tokens
319    /// are already counted.
320    async fn after_model(
321        &self,
322        _ctx: &HookContext<'_>,
323        _response: &mut ModelResponse,
324    ) -> ModelDecision {
325        ModelDecision::Accept
326    }
327
328    /// A model call failed after whatever retries its provider does itself.
329    /// Every hook is asked: an `Abort` beats everything, then the first
330    /// `Recover` or `Retry` wins. With none, the run ends.
331    async fn on_model_error(
332        &self,
333        _ctx: &HookContext<'_>,
334        _error: &ProviderError,
335    ) -> ModelErrorDecision {
336        ModelErrorDecision::Fail
337    }
338
339    /// The run reached a limit in [`crate::Limits`]. Every hook is asked: a
340    /// `Forbid` beats any grant, then the first `Extend` wins, is recorded in [`crate::RunState::limit_grants`], and lasts for
341    /// this run. [`crate::HARD_TURN_CAP`] cannot be extended and is never
342    /// put to a hook. A model call cut off by the wall clock is lost and
343    /// runs again if the limit is extended.
344    async fn on_limit(&self, _ctx: &HookContext<'_>, _limit: LimitKind) -> LimitDecision {
345        LimitDecision::Stop
346    }
347
348    /// Decide whether a call may run. The first `Deny`, `Interrupt` or
349    /// `Answer` wins;
350    /// `Rewrite` changes the arguments seen by later hooks and the tool.
351    async fn before_tool(
352        &self,
353        _ctx: &HookContext<'_>,
354        _call: &ToolCall,
355        _tool: &ToolInfo,
356    ) -> ToolDecision {
357        ToolDecision::Allow
358    }
359
360    /// Inspect or reshape a result before the model sees it (redaction,
361    /// injection screening). The receipt is already final.
362    async fn after_tool(
363        &self,
364        _ctx: &HookContext<'_>,
365        _receipt: &Receipt,
366        _output: &mut ToolOutput,
367    ) {
368    }
369
370    /// The model produced a final answer. Check it against receipts, a
371    /// checklist, tests, anything. Every hook is asked: a `Halt` beats
372    /// everything, then the first `Continue` wins. More than
373    /// [`crate::Limits::max_idle_continuations`] in a row with no new
374    /// successful call ends the run unmet.
375    async fn on_stop(&self, _ctx: &HookContext<'_>, _final_text: &str) -> StopDecision {
376        StopDecision::Accept
377    }
378
379    /// The run ended, with any status: fires once per `run` or `resume` that
380    /// returns (a pause returns too), after the
381    /// outcome is final and every `on_stop` check has had its say, so it is
382    /// the place for after-the-fact work such as writing memory. It cannot
383    /// change the outcome. A `run_resolving` call is one run: the
384    /// interruptions it settles are not run ends.
385    async fn on_run_end(&self, _ctx: &HookContext<'_>, _outcome: &RunOutcome) {}
386
387    /// The stuck detector fired. `None` means "no opinion"; if every hook
388    /// abstains, the default policy nudges and then stops.
389    async fn on_stuck(
390        &self,
391        _ctx: &HookContext<'_>,
392        _signal: &StuckSignal,
393    ) -> Option<StuckDecision> {
394        None
395    }
396}