Skip to main content

strands/agent/
invocation_state.rs

1//! Per-invocation state shared by hooks and tools (`InvocationState`).
2
3use std::fmt;
4use std::sync::{Arc, PoisonError, RwLock};
5
6/// Per-invocation state threaded through hooks and tools for one agent invocation
7/// (`InvocationState`).
8///
9/// A typed map that holds one value per type, following `http::Extensions`, so callers can pass
10/// live values (clients, pools, request ids) without serializing or downcasting them. Clones share
11/// the same map: a value one hook inserts is visible to later hooks, tools and
12/// [`AgentResult::invocation_state`](crate::AgentResult::invocation_state).
13///
14/// The state belongs to the caller; the SDK never stores its own data in it. It is never
15/// serialized.
16///
17/// ```
18/// use strands::InvocationState;
19///
20/// #[derive(Clone, Debug, PartialEq)]
21/// struct RequestId(String);
22///
23/// let state = InvocationState::new();
24/// let shared = state.clone();
25/// shared.insert(RequestId("req-1".into()));
26/// assert_eq!(state.get::<RequestId>(), Some(RequestId("req-1".into())));
27/// ```
28#[derive(Clone, Default)]
29pub struct InvocationState {
30    values: Arc<RwLock<http::Extensions>>,
31}
32
33impl InvocationState {
34    /// Creates empty state.
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    /// A separate map holding the same values: later inserts on either side do not show on the
40    /// other.
41    pub(crate) fn copy(&self) -> Self {
42        let values = self.values.read().unwrap_or_else(PoisonError::into_inner).clone();
43        Self {
44            values: Arc::new(RwLock::new(values)),
45        }
46    }
47
48    /// Stores `value`, returning the previous value of the same type.
49    pub fn insert<T: Clone + Send + Sync + 'static>(&self, value: T) -> Option<T> {
50        self.values
51            .write()
52            .unwrap_or_else(PoisonError::into_inner)
53            .insert(value)
54    }
55
56    /// Returns a clone of the value of type `T`.
57    #[must_use]
58    pub fn get<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
59        self.values
60            .read()
61            .unwrap_or_else(PoisonError::into_inner)
62            .get::<T>()
63            .cloned()
64    }
65
66    /// Whether a value of type `T` is stored.
67    #[must_use]
68    pub fn contains<T: Clone + Send + Sync + 'static>(&self) -> bool {
69        self.values
70            .read()
71            .unwrap_or_else(PoisonError::into_inner)
72            .get::<T>()
73            .is_some()
74    }
75
76    /// Updates the value of type `T` in place, inserting `T::default()` first when it is absent,
77    /// and returns what `update` returns. The map stays locked while `update` runs, so concurrent
78    /// tools see each other's updates.
79    pub fn update<T, R>(&self, update: impl FnOnce(&mut T) -> R) -> R
80    where
81        T: Clone + Default + Send + Sync + 'static,
82    {
83        let mut values = self.values.write().unwrap_or_else(PoisonError::into_inner);
84        update(values.get_or_insert_default::<T>())
85    }
86
87    /// Removes and returns the value of type `T`.
88    pub fn remove<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
89        self.values
90            .write()
91            .unwrap_or_else(PoisonError::into_inner)
92            .remove::<T>()
93    }
94
95    /// Whether no values are stored.
96    #[must_use]
97    pub fn is_empty(&self) -> bool {
98        self.values.read().unwrap_or_else(PoisonError::into_inner).is_empty()
99    }
100
101    /// The number of stored values.
102    #[must_use]
103    pub fn len(&self) -> usize {
104        self.values.read().unwrap_or_else(PoisonError::into_inner).len()
105    }
106
107    /// Removes every value.
108    pub fn clear(&self) {
109        self.values.write().unwrap_or_else(PoisonError::into_inner).clear();
110    }
111}
112
113impl fmt::Debug for InvocationState {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.debug_struct("InvocationState").field("len", &self.len()).finish()
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[derive(Clone, Debug, Default, PartialEq)]
124    struct Counter(u32);
125
126    #[test]
127    fn clones_share_values() {
128        let state = InvocationState::new();
129        let clone = state.clone();
130        assert_eq!(clone.insert(Counter(1)), None);
131        assert_eq!(state.get::<Counter>(), Some(Counter(1)));
132        assert_eq!(state.insert(Counter(2)), Some(Counter(1)));
133        assert!(clone.contains::<Counter>());
134        assert_eq!(clone.len(), 1);
135        assert_eq!(clone.remove::<Counter>(), Some(Counter(2)));
136        assert!(state.is_empty());
137    }
138
139    #[test]
140    fn update_inserts_a_default_and_mutates_in_place() {
141        let state = InvocationState::new();
142        state.update(|counter: &mut Counter| counter.0 += 1);
143        let total = state.update(|counter: &mut Counter| {
144            counter.0 += 1;
145            counter.0
146        });
147        assert_eq!(total, 2);
148        state.clear();
149        assert_eq!(state.get::<Counter>(), None);
150    }
151}