Skip to main content

strands/memory/extraction/
triggers.rs

1//! Extraction triggers.
2
3use std::sync::Arc;
4use std::sync::atomic::{AtomicU64, Ordering};
5
6use super::{ExtractionTrigger, ExtractionTriggerContext};
7use crate::error::{Error, Result};
8use crate::hooks::{AfterInvocationEvent, HookCallbackOptions, HookOrder};
9
10/// Runs after the SDK's own after-invocation hooks (such as session persistence), so extraction
11/// sees the settled turn.
12const LAST: HookCallbackOptions = HookCallbackOptions {
13    order: HookOrder::SDK_LAST,
14};
15
16/// Runs extraction after every agent invocation (`InvocationTrigger`): nothing said in a turn is
17/// missed, and with an extractor it costs a model call per turn.
18#[derive(Debug, Clone, Copy, Default)]
19#[non_exhaustive]
20pub struct InvocationTrigger;
21
22impl InvocationTrigger {
23    /// Creates the trigger.
24    #[must_use]
25    pub fn new() -> Self {
26        Self
27    }
28}
29
30impl ExtractionTrigger for InvocationTrigger {
31    fn name(&self) -> &str {
32        "invocation"
33    }
34
35    fn attach(&self, context: ExtractionTriggerContext<'_>) {
36        let fire = context.fire;
37        context.agent.add_hook_with(
38            move |event: &mut AfterInvocationEvent<'_>| fire.fire(event.invocation_context().cloned()),
39            LAST,
40        );
41    }
42}
43
44/// Options for [`IntervalTrigger`] (`IntervalTriggerOptions`).
45#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bon::Builder)]
46pub struct IntervalTriggerOptions {
47    /// Run extraction once every this many invocations; at least 1.
48    pub turns: u64,
49}
50
51/// Runs extraction every N agent invocations (`IntervalTrigger`); the messages of the skipped
52/// turns are saved when it fires.
53#[derive(Debug, Clone, Copy)]
54pub struct IntervalTrigger {
55    turns: u64,
56}
57
58impl IntervalTrigger {
59    /// Creates the trigger.
60    ///
61    /// # Errors
62    ///
63    /// `IntervalTrigger: turns must be a positive integer, got <turns>` when `turns` is 0.
64    pub fn new(options: IntervalTriggerOptions) -> Result<Self> {
65        if options.turns < 1 {
66            return Err(Error::other(format!(
67                "IntervalTrigger: turns must be a positive integer, got {}",
68                options.turns
69            )));
70        }
71        Ok(Self { turns: options.turns })
72    }
73
74    /// The interval.
75    #[must_use]
76    pub fn turns(&self) -> u64 {
77        self.turns
78    }
79}
80
81impl ExtractionTrigger for IntervalTrigger {
82    fn name(&self) -> &str {
83        "interval"
84    }
85
86    fn attach(&self, context: ExtractionTriggerContext<'_>) {
87        // Each attach counts on its own, so two stores sharing one trigger fire independently.
88        let count = Arc::new(AtomicU64::new(0));
89        let turns = self.turns;
90        let fire = context.fire;
91        context.agent.add_hook_with(
92            move |event: &mut AfterInvocationEvent<'_>| {
93                let count = count.fetch_add(1, Ordering::SeqCst) + 1;
94                if count.is_multiple_of(turns) {
95                    fire.fire(event.invocation_context().cloned());
96                }
97            },
98            LAST,
99        );
100    }
101}