Skip to main content

Hook

Trait Hook 

Source
pub trait Hook<E: Send>:
    Send
    + Sync
    + 'static {
    // Required method
    fn handle<'life0, 'life1, 'async_trait>(
        &'life0 self,
        event: &'life1 mut E,
    ) -> Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait,
             'life1: 'async_trait;
}
Expand description

A reusable or stateful hook (HookCallback as an object).

Return Ok(()), or an error to fail the invocation (see HookOutput). Implementations for events that borrow the agent name the lifetime: impl<'a> Hook<BeforeInvocationEvent<'a>> with event: &mut BeforeInvocationEvent<'a>; eliding it (Hook<BeforeInvocationEvent<'_>>) implements the trait for one lifetime only, and registration then fails to compile.

use strands::BoxError;
use strands::hooks::{BeforeInvocationEvent, BeforeToolCallEvent, Hook, HookRegistry};

struct Audit;

#[strands::async_trait]
impl<'a> Hook<BeforeInvocationEvent<'a>> for Audit {
    async fn handle(&self, event: &mut BeforeInvocationEvent<'a>) -> Result<(), BoxError> {
        event.set_cancel("closed for maintenance");
        Ok(())
    }
}

#[strands::async_trait]
impl Hook<BeforeToolCallEvent> for Audit {
    async fn handle(&self, event: &mut BeforeToolCallEvent) -> Result<(), BoxError> {
        if event.tool_use().name == "shell" {
            return Err("shell is disabled".into());
        }
        Ok(())
    }
}

let hooks = HookRegistry::new();
hooks.add_hook_impl::<BeforeInvocationEvent<'_>>(Audit);
hooks.add_hook_impl::<BeforeToolCallEvent>(Audit);

Required Methods§

Source

fn handle<'life0, 'life1, 'async_trait>( &'life0 self, event: &'life1 mut E, ) -> Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Handles the event.

§Errors

Any error fails the invocation; an InterruptError stops it for human input.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§