strands/memory/extraction/
triggers.rs1use 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
10const LAST: HookCallbackOptions = HookCallbackOptions {
13 order: HookOrder::SDK_LAST,
14};
15
16#[derive(Debug, Clone, Copy, Default)]
19#[non_exhaustive]
20pub struct InvocationTrigger;
21
22impl InvocationTrigger {
23 #[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bon::Builder)]
46pub struct IntervalTriggerOptions {
47 pub turns: u64,
49}
50
51#[derive(Debug, Clone, Copy)]
54pub struct IntervalTrigger {
55 turns: u64,
56}
57
58impl IntervalTrigger {
59 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 #[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 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}