strands/agent/
snapshot.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15#[non_exhaustive]
16pub enum SnapshotField {
17 Messages,
19 State,
21 SystemPrompt,
23 ModelState,
25 Interrupts,
27}
28
29pub(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 #[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
78#[non_exhaustive]
79pub enum SnapshotPreset {
80 Session,
82}
83
84impl SnapshotPreset {
85 #[must_use]
87 pub fn as_str(self) -> &'static str {
88 match self {
89 Self::Session => "session",
90 }
91 }
92
93 #[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 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#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
130pub struct TakeSnapshotOptions {
131 pub preset: Option<SnapshotPreset>,
133 #[builder(default)]
135 pub include: Vec<SnapshotField>,
136 #[builder(default)]
138 pub exclude: Vec<SnapshotField>,
139 pub app_data: Option<JsonObject>,
141}
142
143impl TakeSnapshotOptions {
144 #[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 pub fn take_snapshot(&self, options: impl Into<TakeSnapshotOptions>) -> Result<Snapshot> {
170 take_snapshot(self, &options.into())
171 }
172
173 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
197pub(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
217pub(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
236pub(crate) fn take_session_snapshot(agent: &LocalAgent) -> Result<Snapshot> {
239 take_snapshot(agent, &TakeSnapshotOptions::session())
240}
241
242pub(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;