Skip to main content

strands/agent/
snapshot.rs

1//! Agent snapshots: point-in-time captures of an agent's messages, state, system prompt, model
2//! state and interrupts, in the persisted layout shared with the other Strands SDKs.
3
4use std::fmt;
5use std::str::FromStr;
6
7use super::local_agent::LocalAgent;
8use crate::clock::iso_timestamp;
9use crate::error::{Error, Result};
10use crate::interrupt::InterruptStateData;
11use crate::types::{JsonObject, JsonValue, Message, SNAPSHOT_SCHEMA_VERSION, Scope, Snapshot, SystemPrompt};
12
13/// A field an agent snapshot can capture (`SnapshotField`).
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15#[non_exhaustive]
16pub enum SnapshotField {
17    /// The conversation history, `"messages"`.
18    Messages,
19    /// The app state, `"state"`.
20    State,
21    /// The system prompt, `"systemPrompt"`.
22    SystemPrompt,
23    /// The model provider's state, `"modelState"`.
24    ModelState,
25    /// The interrupt state, `"interrupts"`.
26    Interrupts,
27}
28
29/// Every snapshot field, in the order a snapshot writes them (`ALL_SNAPSHOT_FIELDS`).
30pub(crate) const ALL_SNAPSHOT_FIELDS: [SnapshotField; 5] = [
31    SnapshotField::Messages,
32    SnapshotField::State,
33    SnapshotField::SystemPrompt,
34    SnapshotField::ModelState,
35    SnapshotField::Interrupts,
36];
37
38impl SnapshotField {
39    /// The field's key in `Snapshot::data`.
40    #[must_use]
41    pub fn as_str(self) -> &'static str {
42        match self {
43            Self::Messages => "messages",
44            Self::State => "state",
45            Self::SystemPrompt => "systemPrompt",
46            Self::ModelState => "modelState",
47            Self::Interrupts => "interrupts",
48        }
49    }
50}
51
52impl fmt::Display for SnapshotField {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        f.write_str(self.as_str())
55    }
56}
57
58impl FromStr for SnapshotField {
59    type Err = Error;
60
61    /// Parses a field key, failing on an unknown one.
62    fn from_str(name: &str) -> Result<Self> {
63        ALL_SNAPSHOT_FIELDS
64            .into_iter()
65            .find(|field| field.as_str() == name)
66            .ok_or_else(|| {
67                let valid: Vec<&str> = ALL_SNAPSHOT_FIELDS.iter().map(|field| field.as_str()).collect();
68                Error::other(format!(
69                    "Invalid snapshot field: {name}. Valid fields are: {}",
70                    valid.join(", ")
71                ))
72            })
73    }
74}
75
76/// A named set of snapshot fields (`SnapshotPreset`).
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
78#[non_exhaustive]
79pub enum SnapshotPreset {
80    /// Everything a session needs to resume the agent, `"session"`: all five fields.
81    Session,
82}
83
84impl SnapshotPreset {
85    /// The preset's name.
86    #[must_use]
87    pub fn as_str(self) -> &'static str {
88        match self {
89            Self::Session => "session",
90        }
91    }
92
93    /// The fields the preset captures (`SNAPSHOT_PRESETS`).
94    #[must_use]
95    pub fn fields(self) -> &'static [SnapshotField] {
96        match self {
97            Self::Session => &ALL_SNAPSHOT_FIELDS,
98        }
99    }
100}
101
102impl FromStr for SnapshotPreset {
103    type Err = Error;
104
105    /// Parses a preset name, failing on an unknown one.
106    fn from_str(name: &str) -> Result<Self> {
107        match name {
108            "session" => Ok(Self::Session),
109            _ => Err(Error::other(format!(
110                "Invalid preset: {name}. Valid presets are: session"
111            ))),
112        }
113    }
114}
115
116/// Which fields [`Agent::take_snapshot`](crate::Agent::take_snapshot) captures
117/// (`TakeSnapshotOptions`): the preset's fields, plus `include`, minus `exclude`.
118///
119/// ```
120/// use strands::agent::{SnapshotField, SnapshotPreset, TakeSnapshotOptions};
121///
122/// let options = TakeSnapshotOptions {
123///     preset: Some(SnapshotPreset::Session),
124///     exclude: vec![SnapshotField::Interrupts],
125///     ..Default::default()
126/// };
127/// # let _ = options;
128/// ```
129#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
130pub struct TakeSnapshotOptions {
131    /// The starting set of fields; none when unset.
132    pub preset: Option<SnapshotPreset>,
133    /// Fields added to the preset's.
134    #[builder(default)]
135    pub include: Vec<SnapshotField>,
136    /// Fields removed after the preset and `include` are applied.
137    #[builder(default)]
138    pub exclude: Vec<SnapshotField>,
139    /// Application-owned data stored in the snapshot; Strands never reads it (`appData`).
140    pub app_data: Option<JsonObject>,
141}
142
143impl TakeSnapshotOptions {
144    /// The `session` preset (`{ preset: 'session' }`).
145    #[must_use]
146    pub fn session() -> Self {
147        Self {
148            preset: Some(SnapshotPreset::Session),
149            ..Self::default()
150        }
151    }
152}
153
154impl From<SnapshotPreset> for TakeSnapshotOptions {
155    fn from(preset: SnapshotPreset) -> Self {
156        Self {
157            preset: Some(preset),
158            ..Self::default()
159        }
160    }
161}
162
163impl LocalAgent {
164    /// Captures a point-in-time snapshot of the agent's state.
165    ///
166    /// # Errors
167    ///
168    /// When the options select no field, or a value fails to serialize.
169    pub fn take_snapshot(&self, options: impl Into<TakeSnapshotOptions>) -> Result<Snapshot> {
170        take_snapshot(self, &options.into())
171    }
172
173    /// Restores the agent's state from a snapshot. Only the fields present in
174    /// `snapshot.data` are restored; the others stay as they are. Once the agent is initialized,
175    /// its background tasks refuse the load while they track tasks, and reload theirs from a
176    /// restored `state`, as [`Agent::load_snapshot`](crate::Agent::load_snapshot) does.
177    ///
178    /// # Errors
179    ///
180    /// A snapshot of another scope or schema version, data that does not decode, or background
181    /// tasks still tracked. Nothing is restored when an error is returned.
182    pub fn load_snapshot(&mut self, snapshot: &Snapshot) -> Result<()> {
183        let background_tasks = self.background_tasks().cloned();
184        if let Some(background_tasks) = &background_tasks {
185            background_tasks.assert_can_load_snapshot()?;
186        }
187        load_snapshot(self, snapshot)?;
188        if let Some(background_tasks) = background_tasks
189            && snapshot.data.contains_key("state")
190        {
191            background_tasks.load_app_state(self);
192        }
193        Ok(())
194    }
195}
196
197/// Resolves the fields a snapshot captures, in [`ALL_SNAPSHOT_FIELDS`] order.
198///
199/// # Errors
200///
201/// When no field is left: `No fields to include in snapshot. Specify a preset or include fields.`
202pub(crate) fn resolve_snapshot_fields(options: &TakeSnapshotOptions) -> Result<Vec<SnapshotField>> {
203    let preset = options.preset.map(SnapshotPreset::fields).unwrap_or_default();
204    let fields: Vec<SnapshotField> = ALL_SNAPSHOT_FIELDS
205        .into_iter()
206        .filter(|field| preset.contains(field) || options.include.contains(field))
207        .filter(|field| !options.exclude.contains(field))
208        .collect();
209    if fields.is_empty() {
210        return Err(Error::other(
211            "No fields to include in snapshot. Specify a preset or include fields.",
212        ));
213    }
214    Ok(fields)
215}
216
217/// Captures the agent's state.
218pub(crate) fn take_snapshot(agent: &LocalAgent, options: &TakeSnapshotOptions) -> Result<Snapshot> {
219    let mut data = JsonObject::new();
220    for field in resolve_snapshot_fields(options)? {
221        let value = match field {
222            SnapshotField::Messages => serde_json::to_value(agent.messages())?,
223            SnapshotField::State => agent.app_state().to_json(),
224            SnapshotField::SystemPrompt => match agent.system_prompt() {
225                Some(system_prompt) => serde_json::to_value(system_prompt)?,
226                None => JsonValue::Null,
227            },
228            SnapshotField::ModelState => agent.model_state().to_json(),
229            SnapshotField::Interrupts => serde_json::to_value(agent.interrupt_state().to_data())?,
230        };
231        data.insert(field.as_str().to_owned(), value);
232    }
233    Ok(Snapshot::new(Scope::Agent, iso_timestamp(), data).with_app_data(options.app_data.clone().unwrap_or_default()))
234}
235
236/// The `session` snapshot agents as tools use to reset a sub-agent and to persist its interrupted
237/// turn.
238pub(crate) fn take_session_snapshot(agent: &LocalAgent) -> Result<Snapshot> {
239    take_snapshot(agent, &TakeSnapshotOptions::session())
240}
241
242/// Restores the fields present in a snapshot; absent fields stay as they are.
243/// A `null` system prompt clears it; `null` interrupts leave the interrupt state alone.
244pub(crate) fn load_snapshot(agent: &mut LocalAgent, snapshot: &Snapshot) -> Result<()> {
245    if snapshot.scope != Scope::Agent {
246        return Err(Error::other(format!(
247            "Expected snapshot scope 'agent', got '{}'",
248            serde_json::to_value(snapshot.scope)?.as_str().unwrap_or_default()
249        )));
250    }
251    if snapshot.schema_version != SNAPSHOT_SCHEMA_VERSION {
252        return Err(Error::other(format!(
253            "Unsupported snapshot schema version: {}. Current version: {SNAPSHOT_SCHEMA_VERSION}",
254            snapshot.schema_version
255        )));
256    }
257    let data = &snapshot.data;
258    let messages = data
259        .get("messages")
260        .map(|messages| serde_json::from_value::<Vec<Message>>(messages.clone()))
261        .transpose()?;
262    let system_prompt = data
263        .get("systemPrompt")
264        .map(|system_prompt| match system_prompt {
265            JsonValue::Null => Ok(None),
266            value => serde_json::from_value::<SystemPrompt>(value.clone()).map(Some),
267        })
268        .transpose()?;
269    let interrupts = data
270        .get("interrupts")
271        .filter(|value| !value.is_null())
272        .map(|value| InterruptStateData::from_json(value.clone()))
273        .transpose()?;
274
275    if let Some(messages) = messages {
276        *agent.messages_mut() = messages;
277    }
278    if let Some(state) = data.get("state") {
279        agent.app_state().load_json(state.clone());
280    }
281    if let Some(system_prompt) = system_prompt {
282        agent.set_system_prompt(system_prompt);
283    }
284    if let Some(model_state) = data.get("modelState") {
285        agent.model_state().load_json(model_state.clone());
286    }
287    if let Some(interrupts) = interrupts {
288        agent.interrupt_state().load_data(interrupts);
289    }
290    Ok(())
291}
292
293#[cfg(test)]
294mod tests;