Skip to main content

strands/hooks/
events.rs

1//! The 17 hook events.
2//!
3//! Sequential events run on the agent loop and lend callbacks the mutable [`LocalAgent`]
4//! (`BeforeInvocationEvent<'a>`). Per-tool events ([`BeforeToolCallEvent`],
5//! [`AfterToolCallEvent`], [`ToolStreamUpdateEvent`], [`ToolResultEvent`]) run inside tool tasks
6//! and hold a [`ToolAgent`].
7//!
8//! Fields are private; every field has a getter, and only the fields hooks may write have
9//! setters. The serializable records of these events are in [`AgentStreamEvent`].
10//!
11//! [`AgentStreamEvent`]: super::AgentStreamEvent
12
13use std::fmt;
14use std::sync::Arc;
15
16use crate::agent::continuation::ContinuationInput;
17use crate::agent::{AgentResult, InvocationContext, InvocationState, InvokeArgs, LocalAgent, ToolAgent};
18use crate::error::Error;
19use crate::interrupt::{Interrupt, InterruptError, InterruptSource};
20use crate::models::streaming::ModelStreamEvent;
21use crate::models::{Model, Redaction};
22use crate::tools::{Tool, ToolStreamEvent};
23use crate::types::{
24    ContentBlock, InterruptParams, JsonValue, Message, StopReason, ToolResultBlock, ToolResultError, ToolUse,
25};
26
27/// The tool-use descriptor on tool-call events (`ToolUseData`): the shape of the model's tool use.
28pub type ToolUseData = ToolUse;
29
30/// A hook's request to cancel an operation.
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum Cancel {
34    /// Not cancelled (`false`).
35    #[default]
36    NotCancelled,
37    /// Cancelled with the default message (`true`).
38    Cancelled,
39    /// Cancelled with this message (a string).
40    Message(String),
41}
42
43impl Cancel {
44    /// Whether cancellation was requested.
45    #[must_use]
46    pub fn is_cancelled(&self) -> bool {
47        !matches!(self, Self::NotCancelled)
48    }
49
50    /// The cancel message, or `default` for a plain cancel; `None` when not cancelled.
51    #[must_use]
52    pub fn message_or<'a>(&'a self, default: &'a str) -> Option<&'a str> {
53        match self {
54            Self::NotCancelled => None,
55            Self::Cancelled => Some(default),
56            Self::Message(message) => Some(message),
57        }
58    }
59}
60
61impl From<bool> for Cancel {
62    fn from(cancel: bool) -> Self {
63        if cancel { Self::Cancelled } else { Self::NotCancelled }
64    }
65}
66
67impl From<&str> for Cancel {
68    fn from(message: &str) -> Self {
69        Self::Message(message.to_owned())
70    }
71}
72
73impl From<String> for Cancel {
74    fn from(message: String) -> Self {
75        Self::Message(message)
76    }
77}
78
79/// A hook's request to end the turn after a tool batch.
80#[derive(Debug, Clone, Default, PartialEq)]
81#[non_exhaustive]
82pub enum EndTurn {
83    /// Keep going (`false`).
84    #[default]
85    Continue,
86    /// End with the default message `Turn ended early by hook after tool execution` (`true`).
87    End,
88    /// End with this text as the final assistant message (a string).
89    Message(String),
90    /// End with these blocks as the final assistant message (`ContentBlock[]`).
91    Content(Vec<ContentBlock>),
92}
93
94impl EndTurn {
95    /// Whether ending the turn was requested.
96    #[must_use]
97    pub fn is_end(&self) -> bool {
98        !matches!(self, Self::Continue)
99    }
100}
101
102impl From<bool> for EndTurn {
103    fn from(end: bool) -> Self {
104        if end { Self::End } else { Self::Continue }
105    }
106}
107
108impl From<&str> for EndTurn {
109    fn from(message: &str) -> Self {
110        Self::Message(message.to_owned())
111    }
112}
113
114impl From<String> for EndTurn {
115    fn from(message: String) -> Self {
116        Self::Message(message)
117    }
118}
119
120impl From<Vec<ContentBlock>> for EndTurn {
121    fn from(content: Vec<ContentBlock>) -> Self {
122        Self::Content(content)
123    }
124}
125
126/// What a model call returned (`ModelStopResponse`).
127#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
128#[serde(rename_all = "camelCase")]
129#[non_exhaustive]
130pub struct ModelStopResponse {
131    /// The message the model returned.
132    pub message: Message,
133    /// Why the model stopped.
134    pub stop_reason: StopReason,
135    /// Set when guardrails redacted the last user message; the redacted message is the last one
136    /// in the agent's history.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub redaction: Option<Redaction>,
139}
140
141impl ModelStopResponse {
142    /// Creates the response.
143    pub fn new(message: Message, stop_reason: StopReason) -> Self {
144        Self {
145            message,
146            stop_reason,
147            redaction: None,
148        }
149    }
150
151    /// Sets the redaction.
152    #[must_use]
153    pub fn with_redaction(mut self, redaction: Redaction) -> Self {
154        self.redaction = Some(redaction);
155        self
156    }
157}
158
159/// Fields every sequential event carries.
160struct Sequential<'a> {
161    agent: &'a mut LocalAgent,
162    invocation_state: InvocationState,
163    invocation_context: Option<InvocationContext>,
164}
165
166impl<'a> Sequential<'a> {
167    fn new(agent: &'a mut LocalAgent, invocation_state: InvocationState) -> Self {
168        Self {
169            agent,
170            invocation_state,
171            invocation_context: None,
172        }
173    }
174}
175
176/// Fields every per-tool event carries.
177#[derive(Clone)]
178struct PerTool {
179    agent: ToolAgent,
180    invocation_state: InvocationState,
181    invocation_context: Option<InvocationContext>,
182}
183
184impl PerTool {
185    fn new(agent: ToolAgent, invocation_state: InvocationState) -> Self {
186        let invocation_context = agent.invocation_context().cloned();
187        Self {
188            agent,
189            invocation_state,
190            invocation_context,
191        }
192    }
193}
194
195macro_rules! sequential_accessors {
196    ($event:ident) => {
197        impl<'a> $event<'a> {
198            /// The agent.
199            #[must_use]
200            pub fn agent(&self) -> &LocalAgent {
201                self.base.agent
202            }
203
204            /// The agent, mutably: hooks may change its messages, system prompt, tools and state.
205            pub fn agent_mut(&mut self) -> &mut LocalAgent {
206                self.base.agent
207            }
208
209            /// The caller's per-invocation state.
210            #[must_use]
211            pub fn invocation_state(&self) -> &InvocationState {
212                &self.base.invocation_state
213            }
214
215            /// The request this event belongs to.
216            #[must_use]
217            pub fn invocation_context(&self) -> Option<&InvocationContext> {
218                self.base.invocation_context.as_ref()
219            }
220
221            pub(crate) fn with_invocation_context(mut self, context: Option<InvocationContext>) -> Self {
222                self.base.invocation_context = context;
223                self
224            }
225        }
226
227        impl fmt::Debug for $event<'_> {
228            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229                f.debug_struct(stringify!($event)).finish_non_exhaustive()
230            }
231        }
232    };
233}
234
235macro_rules! per_tool_accessors {
236    ($event:ident) => {
237        impl $event {
238            /// The agent running the tool.
239            #[must_use]
240            pub fn agent(&self) -> &ToolAgent {
241                &self.base.agent
242            }
243
244            /// The caller's per-invocation state.
245            #[must_use]
246            pub fn invocation_state(&self) -> &InvocationState {
247                &self.base.invocation_state
248            }
249
250            /// The request this event belongs to.
251            #[must_use]
252            pub fn invocation_context(&self) -> Option<&InvocationContext> {
253                self.base.invocation_context.as_ref()
254            }
255        }
256
257        impl fmt::Debug for $event {
258            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259                f.debug_struct(stringify!($event)).finish_non_exhaustive()
260            }
261        }
262    };
263}
264
265/// The agent finished construction and initialized its built-in components (`InitializedEvent`).
266///
267/// It fires outside any invocation, so it carries no invocation state.
268#[non_exhaustive]
269pub struct InitializedEvent<'a> {
270    agent: &'a mut LocalAgent,
271}
272
273impl<'a> InitializedEvent<'a> {
274    pub(crate) fn new(agent: &'a mut LocalAgent) -> Self {
275        Self { agent }
276    }
277
278    /// The agent.
279    #[must_use]
280    pub fn agent(&self) -> &LocalAgent {
281        self.agent
282    }
283
284    /// The agent, mutably.
285    pub fn agent_mut(&mut self) -> &mut LocalAgent {
286        self.agent
287    }
288}
289
290impl fmt::Debug for InitializedEvent<'_> {
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        f.debug_struct("InitializedEvent").finish_non_exhaustive()
293    }
294}
295
296/// A new request is starting, before any model call or tool runs (`BeforeInvocationEvent`).
297#[non_exhaustive]
298pub struct BeforeInvocationEvent<'a> {
299    base: Sequential<'a>,
300    messages: Vec<Message>,
301    cancel: Cancel,
302}
303
304sequential_accessors!(BeforeInvocationEvent);
305
306impl<'a> BeforeInvocationEvent<'a> {
307    pub(crate) fn new(agent: &'a mut LocalAgent, invocation_state: InvocationState, messages: Vec<Message>) -> Self {
308        Self {
309            base: Sequential::new(agent, invocation_state),
310            messages,
311            cancel: Cancel::NotCancelled,
312        }
313    }
314
315    /// The input messages of this invocation.
316    #[must_use]
317    pub fn messages(&self) -> &[Message] {
318        &self.messages
319    }
320
321    /// The input messages, to edit before processing.
322    pub fn messages_mut(&mut self) -> &mut Vec<Message> {
323        &mut self.messages
324    }
325
326    /// Replaces the input messages.
327    pub fn set_messages(&mut self, messages: Vec<Message>) {
328        self.messages = messages;
329    }
330
331    /// The cancel request.
332    #[must_use]
333    pub fn cancel(&self) -> &Cancel {
334        &self.cancel
335    }
336
337    /// Cancels the invocation: `true` uses the default message, a string becomes the assistant
338    /// response.
339    pub fn set_cancel(&mut self, cancel: impl Into<Cancel>) {
340        self.cancel = cancel.into();
341    }
342
343    pub(crate) fn take_messages(&mut self) -> Vec<Message> {
344        std::mem::take(&mut self.messages)
345    }
346}
347
348/// The request ended, successfully or not (`AfterInvocationEvent`). Callbacks with the same order
349/// run in reverse registration order.
350#[non_exhaustive]
351pub struct AfterInvocationEvent<'a> {
352    base: Sequential<'a>,
353    resume: Option<InvokeArgs>,
354    continuation_inputs: Vec<ContinuationInput>,
355}
356
357sequential_accessors!(AfterInvocationEvent);
358
359impl<'a> AfterInvocationEvent<'a> {
360    pub(crate) fn new(agent: &'a mut LocalAgent, invocation_state: InvocationState) -> Self {
361        Self {
362            base: Sequential::new(agent, invocation_state),
363            resume: None,
364            continuation_inputs: Vec::new(),
365        }
366    }
367
368    /// The input of the follow-up invocation, if a hook requested one.
369    #[must_use]
370    pub fn resume(&self) -> Option<&InvokeArgs> {
371        self.resume.as_ref()
372    }
373
374    /// Re-enters the loop with `args` once the callbacks finish, with a fresh pair of invocation
375    /// events. Ignored when the invocation failed or a limit was reached; the last callback to set
376    /// it wins.
377    pub fn set_resume(&mut self, args: impl Into<InvokeArgs>) {
378        self.resume = Some(args.into());
379    }
380
381    /// Clears a requested follow-up invocation.
382    pub fn clear_resume(&mut self) {
383        self.resume = None;
384    }
385
386    pub(crate) fn take_resume(&mut self) -> Option<InvokeArgs> {
387        self.resume.take()
388    }
389
390    /// Contributes input to a follow-up pass (`continuations.addInput`).
391    pub(crate) fn add_continuation_input(&mut self, input: ContinuationInput) {
392        self.continuation_inputs.push(input);
393    }
394
395    pub(crate) fn take_continuation_inputs(&mut self) -> Vec<ContinuationInput> {
396        std::mem::take(&mut self.continuation_inputs)
397    }
398}
399
400/// The framework added a message to the history (`MessageAddedEvent`).
401#[non_exhaustive]
402pub struct MessageAddedEvent<'a> {
403    base: Sequential<'a>,
404    message: Message,
405}
406
407sequential_accessors!(MessageAddedEvent);
408
409impl<'a> MessageAddedEvent<'a> {
410    pub(crate) fn new(agent: &'a mut LocalAgent, invocation_state: InvocationState, message: Message) -> Self {
411        Self {
412            base: Sequential::new(agent, invocation_state),
413            message,
414        }
415    }
416
417    /// The added message.
418    #[must_use]
419    pub fn message(&self) -> &Message {
420        &self.message
421    }
422}
423
424/// A model call is about to start (`BeforeModelCallEvent`).
425#[non_exhaustive]
426pub struct BeforeModelCallEvent<'a> {
427    base: Sequential<'a>,
428    model: Arc<dyn Model>,
429    projected_input_tokens: Option<u64>,
430    cancel: Cancel,
431    continuation_inputs: Vec<ContinuationInput>,
432    raised_interrupts: Vec<Interrupt>,
433}
434
435sequential_accessors!(BeforeModelCallEvent);
436
437impl<'a> BeforeModelCallEvent<'a> {
438    pub(crate) fn new(agent: &'a mut LocalAgent, invocation_state: InvocationState, model: Arc<dyn Model>) -> Self {
439        Self {
440            base: Sequential::new(agent, invocation_state),
441            model,
442            projected_input_tokens: None,
443            cancel: Cancel::NotCancelled,
444            continuation_inputs: Vec::new(),
445            raised_interrupts: Vec::new(),
446        }
447    }
448
449    /// Contributes input appended before this model call (`continuations.addInput`).
450    pub(crate) fn add_continuation_input(&mut self, input: ContinuationInput) {
451        self.continuation_inputs.push(input);
452    }
453
454    /// Stops the invocation for interrupts raised elsewhere, such as by background tasks that
455    /// need input.
456    pub(crate) fn raise_interrupts(&mut self, interrupts: Vec<Interrupt>) {
457        self.raised_interrupts.extend(interrupts);
458    }
459
460    pub(crate) fn take_raised_interrupts(&mut self) -> Vec<Interrupt> {
461        std::mem::take(&mut self.raised_interrupts)
462    }
463
464    pub(crate) fn take_continuation_inputs(&mut self) -> Vec<ContinuationInput> {
465        std::mem::take(&mut self.continuation_inputs)
466    }
467
468    #[must_use]
469    pub(crate) fn with_projected_input_tokens(mut self, tokens: u64) -> Self {
470        self.projected_input_tokens = Some(tokens);
471        self
472    }
473
474    /// The model about to be called.
475    #[must_use]
476    pub fn model(&self) -> &Arc<dyn Model> {
477        &self.model
478    }
479
480    /// The projected input tokens of the call, from message metadata and token estimation.
481    #[must_use]
482    pub fn projected_input_tokens(&self) -> Option<u64> {
483        self.projected_input_tokens
484    }
485
486    /// The cancel request.
487    #[must_use]
488    pub fn cancel(&self) -> &Cancel {
489        &self.cancel
490    }
491
492    /// Cancels the model call: `true` uses the default message, a string becomes the assistant
493    /// response.
494    pub fn set_cancel(&mut self, cancel: impl Into<Cancel>) {
495        self.cancel = cancel.into();
496    }
497}
498
499/// A model call finished, successfully or not (`AfterModelCallEvent`). Callbacks with the same
500/// order run in reverse registration order.
501#[non_exhaustive]
502pub struct AfterModelCallEvent<'a> {
503    base: Sequential<'a>,
504    model: Arc<dyn Model>,
505    attempt_count: u32,
506    stop_data: Option<ModelStopResponse>,
507    error: Option<Error>,
508    retry: bool,
509}
510
511sequential_accessors!(AfterModelCallEvent);
512
513impl<'a> AfterModelCallEvent<'a> {
514    pub(crate) fn new(
515        agent: &'a mut LocalAgent,
516        invocation_state: InvocationState,
517        model: Arc<dyn Model>,
518        attempt_count: u32,
519    ) -> Self {
520        Self {
521            base: Sequential::new(agent, invocation_state),
522            model,
523            attempt_count,
524            stop_data: None,
525            error: None,
526            retry: false,
527        }
528    }
529
530    #[must_use]
531    pub(crate) fn with_stop_data(mut self, stop_data: ModelStopResponse) -> Self {
532        self.stop_data = Some(stop_data);
533        self
534    }
535
536    #[must_use]
537    pub(crate) fn with_error(mut self, error: Error) -> Self {
538        self.error = Some(error);
539        self
540    }
541
542    /// The model that was called.
543    #[must_use]
544    pub fn model(&self) -> &Arc<dyn Model> {
545        &self.model
546    }
547
548    /// The 1-based model attempt within this turn, counting the one that just finished. A fresh
549    /// turn always starts at 1.
550    #[must_use]
551    pub fn attempt_count(&self) -> u32 {
552        self.attempt_count
553    }
554
555    /// The model's response; `None` when the call failed.
556    #[must_use]
557    pub fn stop_data(&self) -> Option<&ModelStopResponse> {
558        self.stop_data.as_ref()
559    }
560
561    /// The error the call failed with.
562    #[must_use]
563    pub fn error(&self) -> Option<&Error> {
564        self.error.as_ref()
565    }
566
567    /// Whether a hook requested a retry of the model call.
568    #[must_use]
569    pub fn retry(&self) -> bool {
570        self.retry
571    }
572
573    /// Requests (or withdraws) a retry of the model call.
574    pub fn set_retry(&mut self, retry: bool) {
575        self.retry = retry;
576    }
577
578    pub(crate) fn take_error(&mut self) -> Option<Error> {
579        self.error.take()
580    }
581}
582
583/// One streaming event from the model (`ModelStreamUpdateEvent`).
584#[non_exhaustive]
585pub struct ModelStreamUpdateEvent<'a> {
586    base: Sequential<'a>,
587    event: ModelStreamEvent,
588}
589
590sequential_accessors!(ModelStreamUpdateEvent);
591
592impl<'a> ModelStreamUpdateEvent<'a> {
593    pub(crate) fn new(agent: &'a mut LocalAgent, invocation_state: InvocationState, event: ModelStreamEvent) -> Self {
594        Self {
595            base: Sequential::new(agent, invocation_state),
596            event,
597        }
598    }
599
600    /// The model stream event.
601    #[must_use]
602    pub fn event(&self) -> &ModelStreamEvent {
603        &self.event
604    }
605}
606
607/// A content block the model finished (`ContentBlockEvent`).
608#[non_exhaustive]
609pub struct ContentBlockEvent<'a> {
610    base: Sequential<'a>,
611    content_block: ContentBlock,
612}
613
614sequential_accessors!(ContentBlockEvent);
615
616impl<'a> ContentBlockEvent<'a> {
617    pub(crate) fn new(
618        agent: &'a mut LocalAgent,
619        invocation_state: InvocationState,
620        content_block: ContentBlock,
621    ) -> Self {
622        Self {
623            base: Sequential::new(agent, invocation_state),
624            content_block,
625        }
626    }
627
628    /// The finished block.
629    #[must_use]
630    pub fn content_block(&self) -> &ContentBlock {
631        &self.content_block
632    }
633}
634
635/// The model finished a message (`ModelMessageEvent`).
636#[non_exhaustive]
637pub struct ModelMessageEvent<'a> {
638    base: Sequential<'a>,
639    message: Message,
640    stop_reason: StopReason,
641}
642
643sequential_accessors!(ModelMessageEvent);
644
645impl<'a> ModelMessageEvent<'a> {
646    pub(crate) fn new(
647        agent: &'a mut LocalAgent,
648        invocation_state: InvocationState,
649        message: Message,
650        stop_reason: StopReason,
651    ) -> Self {
652        Self {
653            base: Sequential::new(agent, invocation_state),
654            message,
655            stop_reason,
656        }
657    }
658
659    /// The assembled message.
660    #[must_use]
661    pub fn message(&self) -> &Message {
662        &self.message
663    }
664
665    /// Why the model stopped.
666    #[must_use]
667    pub fn stop_reason(&self) -> StopReason {
668        self.stop_reason.clone()
669    }
670}
671
672/// The model asked for tools, before any of them runs (`BeforeToolsEvent`).
673#[non_exhaustive]
674pub struct BeforeToolsEvent<'a> {
675    base: Sequential<'a>,
676    message: Message,
677    cancel: Cancel,
678    interrupts: Vec<Interrupt>,
679}
680
681sequential_accessors!(BeforeToolsEvent);
682
683impl<'a> BeforeToolsEvent<'a> {
684    pub(crate) fn new(agent: &'a mut LocalAgent, invocation_state: InvocationState, message: Message) -> Self {
685        Self {
686            base: Sequential::new(agent, invocation_state),
687            message,
688            cancel: Cancel::NotCancelled,
689            interrupts: Vec::new(),
690        }
691    }
692
693    /// The assistant message with the tool uses.
694    #[must_use]
695    pub fn message(&self) -> &Message {
696        &self.message
697    }
698
699    /// The cancel request.
700    #[must_use]
701    pub fn cancel(&self) -> &Cancel {
702        &self.cancel
703    }
704
705    /// Cancels every tool call of the batch: `true` uses the default message, a string becomes the
706    /// error text of each tool result.
707    pub fn set_cancel(&mut self, cancel: impl Into<Cancel>) {
708        self.cancel = cancel.into();
709    }
710
711    /// Raises an interrupt for human input (`interrupt`), with the id `hook:beforeTools:<name>`.
712    ///
713    /// Returns the response when the agent resumed with one (or `params` carries a preemptive
714    /// response). Otherwise the interrupt is recorded on the event and the agent stops with it
715    /// once every callback has run; return the [`InterruptError`] with `?` (it does not fail the
716    /// invocation) or simply return from the callback.
717    ///
718    /// # Errors
719    ///
720    /// The unanswered interrupt.
721    pub fn interrupt(&mut self, params: impl Into<InterruptParams>) -> Result<JsonValue, InterruptError> {
722        let params = params.into();
723        let id = format!("hook:beforeTools:{}", params.name);
724        let raised = self
725            .base
726            .agent
727            .interrupt_state()
728            .raise(&id, &params, InterruptSource::Hook);
729        raised.inspect_err(|error| self.interrupts.extend(error.interrupts.iter().cloned()))
730    }
731
732    pub(crate) fn take_interrupts(&mut self) -> Vec<Interrupt> {
733        std::mem::take(&mut self.interrupts)
734    }
735}
736
737/// Every tool of the batch finished (`AfterToolsEvent`). Callbacks with the same order run in
738/// reverse registration order.
739#[non_exhaustive]
740pub struct AfterToolsEvent<'a> {
741    base: Sequential<'a>,
742    message: Message,
743    end_turn: EndTurn,
744}
745
746sequential_accessors!(AfterToolsEvent);
747
748impl<'a> AfterToolsEvent<'a> {
749    pub(crate) fn new(agent: &'a mut LocalAgent, invocation_state: InvocationState, message: Message) -> Self {
750        Self {
751            base: Sequential::new(agent, invocation_state),
752            message,
753            end_turn: EndTurn::Continue,
754        }
755    }
756
757    /// The user message with the tool results.
758    #[must_use]
759    pub fn message(&self) -> &Message {
760        &self.message
761    }
762
763    /// The end-turn request.
764    #[must_use]
765    pub fn end_turn(&self) -> &EndTurn {
766        &self.end_turn
767    }
768
769    /// Ends the turn after this batch without calling the model again; the stop reason is
770    /// `EndTurn`. `true` appends the default message, a string or blocks become the final
771    /// assistant message.
772    pub fn set_end_turn(&mut self, end_turn: impl Into<EndTurn>) {
773        self.end_turn = end_turn.into();
774    }
775}
776
777/// The final event of an invocation, with its result (`AgentResultEvent`).
778#[non_exhaustive]
779pub struct AgentResultEvent<'a> {
780    base: Sequential<'a>,
781    result: AgentResult,
782}
783
784sequential_accessors!(AgentResultEvent);
785
786impl<'a> AgentResultEvent<'a> {
787    pub(crate) fn new(agent: &'a mut LocalAgent, invocation_state: InvocationState, result: AgentResult) -> Self {
788        Self {
789            base: Sequential::new(agent, invocation_state),
790            result,
791        }
792    }
793
794    /// The result.
795    #[must_use]
796    pub fn result(&self) -> &AgentResult {
797        &self.result
798    }
799}
800
801/// The agent stopped for an unanswered interrupt; one event fires per interrupt
802/// (`InterruptEvent`).
803#[non_exhaustive]
804pub struct InterruptEvent<'a> {
805    base: Sequential<'a>,
806    interrupt: Interrupt,
807}
808
809sequential_accessors!(InterruptEvent);
810
811impl<'a> InterruptEvent<'a> {
812    pub(crate) fn new(agent: &'a mut LocalAgent, invocation_state: InvocationState, interrupt: Interrupt) -> Self {
813        Self {
814            base: Sequential::new(agent, invocation_state),
815            interrupt,
816        }
817    }
818
819    /// The interrupt; its source tells a tool interrupt from a hook interrupt.
820    #[must_use]
821    pub fn interrupt(&self) -> &Interrupt {
822        &self.interrupt
823    }
824}
825
826/// A tool is about to run, after its lookup (`BeforeToolCallEvent`).
827///
828/// Hooks can cancel the call, run a different tool with
829/// [`set_selected_tool`](Self::set_selected_tool), or rewrite the tool use; a changed name
830/// re-resolves the tool unless one is selected. The tool use id stays the model's.
831#[non_exhaustive]
832pub struct BeforeToolCallEvent {
833    base: PerTool,
834    tool_use: ToolUse,
835    tool: Option<Arc<dyn Tool>>,
836    cancel: Cancel,
837    selected_tool: Option<Arc<dyn Tool>>,
838    interrupts: Vec<Interrupt>,
839}
840
841per_tool_accessors!(BeforeToolCallEvent);
842
843impl BeforeToolCallEvent {
844    pub(crate) fn new(
845        agent: ToolAgent,
846        invocation_state: InvocationState,
847        tool_use: ToolUse,
848        tool: Option<Arc<dyn Tool>>,
849    ) -> Self {
850        Self {
851            base: PerTool::new(agent, invocation_state),
852            tool_use,
853            tool,
854            cancel: Cancel::NotCancelled,
855            selected_tool: None,
856            interrupts: Vec::new(),
857        }
858    }
859
860    /// The tool use about to run.
861    #[must_use]
862    pub fn tool_use(&self) -> &ToolUse {
863        &self.tool_use
864    }
865
866    /// The tool use, to edit its name or input in place.
867    pub fn tool_use_mut(&mut self) -> &mut ToolUse {
868        &mut self.tool_use
869    }
870
871    /// Replaces the tool use.
872    pub fn set_tool_use(&mut self, tool_use: ToolUse) {
873        self.tool_use = tool_use;
874    }
875
876    /// The registry's tool for the name, if any.
877    #[must_use]
878    pub fn tool(&self) -> Option<&Arc<dyn Tool>> {
879        self.tool.as_ref()
880    }
881
882    /// The cancel request.
883    #[must_use]
884    pub fn cancel(&self) -> &Cancel {
885        &self.cancel
886    }
887
888    /// Cancels the tool call: `true` uses the default message, a string becomes the error text of
889    /// the tool result.
890    pub fn set_cancel(&mut self, cancel: impl Into<Cancel>) {
891        self.cancel = cancel.into();
892    }
893
894    /// The replacement tool a hook selected.
895    #[must_use]
896    pub fn selected_tool(&self) -> Option<&Arc<dyn Tool>> {
897        self.selected_tool.as_ref()
898    }
899
900    /// Runs `tool` instead of the registry's match. The last callback to set it wins.
901    pub fn set_selected_tool(&mut self, tool: Arc<dyn Tool>) {
902        self.selected_tool = Some(tool);
903    }
904
905    /// Raises an interrupt for human input (`interrupt`), with the id
906    /// `hook:beforeToolCall:<toolUseId>:<name>`.
907    ///
908    /// Returns the response when the agent resumed with one (or `params` carries a preemptive
909    /// response). Otherwise the interrupt is recorded on the event and the agent stops with it
910    /// once every callback has run; return the [`InterruptError`] with `?` (it does not fail the
911    /// invocation) or simply return from the callback.
912    ///
913    /// # Errors
914    ///
915    /// The unanswered interrupt.
916    pub fn interrupt(&mut self, params: impl Into<InterruptParams>) -> Result<JsonValue, InterruptError> {
917        let params = params.into();
918        let id = format!("hook:beforeToolCall:{}:{}", self.tool_use.tool_use_id, params.name);
919        let raised = self.base.agent.raise_interrupt(&id, &params);
920        raised.inspect_err(|error| self.interrupts.extend(error.interrupts.iter().cloned()))
921    }
922
923    pub(crate) fn take_interrupts(&mut self) -> Vec<Interrupt> {
924        std::mem::take(&mut self.interrupts)
925    }
926
927    pub(crate) fn take_selected_tool(&mut self) -> Option<Arc<dyn Tool>> {
928        self.selected_tool.take()
929    }
930}
931
932/// A tool call finished, successfully or not (`AfterToolCallEvent`). Callbacks with the same
933/// order run in reverse registration order.
934#[non_exhaustive]
935pub struct AfterToolCallEvent {
936    base: PerTool,
937    tool_use: ToolUse,
938    tool: Option<Arc<dyn Tool>>,
939    result: ToolResultBlock,
940    error: Option<ToolResultError>,
941    retry: bool,
942}
943
944per_tool_accessors!(AfterToolCallEvent);
945
946impl AfterToolCallEvent {
947    pub(crate) fn new(
948        agent: ToolAgent,
949        invocation_state: InvocationState,
950        tool_use: ToolUse,
951        tool: Option<Arc<dyn Tool>>,
952        result: ToolResultBlock,
953    ) -> Self {
954        let error = result.error.clone();
955        Self {
956            base: PerTool::new(agent, invocation_state),
957            tool_use,
958            tool,
959            result,
960            error,
961            retry: false,
962        }
963    }
964
965    /// The tool use that ran.
966    #[must_use]
967    pub fn tool_use(&self) -> &ToolUse {
968        &self.tool_use
969    }
970
971    /// The tool that ran, if one was found.
972    #[must_use]
973    pub fn tool(&self) -> Option<&Arc<dyn Tool>> {
974        self.tool.as_ref()
975    }
976
977    /// The tool result.
978    #[must_use]
979    pub fn result(&self) -> &ToolResultBlock {
980        &self.result
981    }
982
983    /// The tool result, to edit before it reaches the model (redact, truncate).
984    pub fn result_mut(&mut self) -> &mut ToolResultBlock {
985        &mut self.result
986    }
987
988    /// Replaces the tool result.
989    pub fn set_result(&mut self, result: ToolResultBlock) {
990        self.result = result;
991    }
992
993    /// The error the tool failed with; it stays the original when a hook replaces the result.
994    #[must_use]
995    pub fn error(&self) -> Option<&ToolResultError> {
996        self.error.as_ref()
997    }
998
999    /// Whether a hook requested a retry of the tool call.
1000    #[must_use]
1001    pub fn retry(&self) -> bool {
1002        self.retry
1003    }
1004
1005    /// Requests (or withdraws) a retry of the tool call.
1006    pub fn set_retry(&mut self, retry: bool) {
1007        self.retry = retry;
1008    }
1009
1010    pub(crate) fn into_result(self) -> ToolResultBlock {
1011        self.result
1012    }
1013}
1014
1015/// A tool yielded a progress event (`ToolStreamUpdateEvent`).
1016#[non_exhaustive]
1017pub struct ToolStreamUpdateEvent {
1018    base: PerTool,
1019    event: ToolStreamEvent,
1020}
1021
1022per_tool_accessors!(ToolStreamUpdateEvent);
1023
1024impl ToolStreamUpdateEvent {
1025    pub(crate) fn new(agent: ToolAgent, invocation_state: InvocationState, event: ToolStreamEvent) -> Self {
1026        Self {
1027            base: PerTool::new(agent, invocation_state),
1028            event,
1029        }
1030    }
1031
1032    /// The tool's progress event.
1033    #[must_use]
1034    pub fn event(&self) -> &ToolStreamEvent {
1035        &self.event
1036    }
1037}
1038
1039/// A tool call's final result is ready (`ToolResultEvent`).
1040#[non_exhaustive]
1041pub struct ToolResultEvent {
1042    base: PerTool,
1043    result: ToolResultBlock,
1044}
1045
1046per_tool_accessors!(ToolResultEvent);
1047
1048impl ToolResultEvent {
1049    pub(crate) fn new(agent: ToolAgent, invocation_state: InvocationState, result: ToolResultBlock) -> Self {
1050        Self {
1051            base: PerTool::new(agent, invocation_state),
1052            result,
1053        }
1054    }
1055
1056    /// The result.
1057    #[must_use]
1058    pub fn result(&self) -> &ToolResultBlock {
1059        &self.result
1060    }
1061}
1062
1063#[cfg(test)]
1064mod tests;