use rig_core::conversation::{Aside, Author, Conversation};
use rig_core::message::{ImageMediaType, Message, UserContent};
use serde_json::json;
use super::*;
use crate::{BLOBS, Files};
pub const SYNTHETIC: &str = "rig-session/synthetic";
pub const SYNTHETIC_BLOBS: &str = "synthetic-blobs/";
pub const UNINSTALLED: &str = "uninstalled.state";
pub const UNINSTALLED_FILE: &str = "plugins/uninstalled/data";
pub const CHAIN: Chain = Chain {
steps: &[Step {
from: SYNTHETIC,
to: FORMAT,
apply: from_synthetic,
#[cfg(test)]
fixture,
}],
};
fn from_synthetic(session: &mut Snapshot) -> Result<(), SessionError> {
rename_format(session, FORMAT)?;
move_files(session, SYNTHETIC_BLOBS, BLOBS);
Ok(())
}
pub fn write_fixture(store: &dyn Store) -> Result<(), SessionError> {
let snapshot = Snapshot::read(&fixture()?)?;
snapshot.write_to(store)
}
fn fixture() -> Result<MemoryStore, SessionError> {
let store = MemoryStore::default();
let mut conversation = Conversation::from_messages([
Message::User {
content: vec![
UserContent::text("a synthetic session"),
UserContent::image_base64("cG5n", Some(ImageMediaType::PNG), None),
],
},
Message::assistant("seen"),
]);
conversation.add_aside(Aside::new(
"uninstalled.aside",
Author::plugin("uninstalled"),
json!({"kept": [1, "as is"]}),
));
crate::save(&store, "agent", &mut conversation)?;
let mut session = Session::read(&store)?;
session
.saved
.insert(UNINSTALLED.to_owned(), json!({"kept": [false, "as is"]}));
session.save(&store)?;
store.write_file(META, br#"{"title":"synthetic"}"#)?;
store.write_file(UNINSTALLED_FILE, b"opaque\0\xff bytes")?;
let mut snapshot = Snapshot::read(&store)?;
rename_format(&mut snapshot, SYNTHETIC)?;
move_files(&mut snapshot, BLOBS, SYNTHETIC_BLOBS);
let synthetic = MemoryStore::default();
snapshot.write_to(&synthetic)?;
Ok(synthetic)
}
fn rename_format(session: &mut Snapshot, to: &str) -> Result<(), SessionError> {
for bytes in session.logs.values_mut() {
let Some((first, rest)) =
memchr::memchr(b'\n', bytes).and_then(|at| bytes.split_at_checked(at))
else {
continue;
};
let mut header: Value = serde_json::from_slice(first).map_err(invalid_json)?;
if let Some(header) = header.as_object_mut() {
header.insert("format".to_owned(), to.into());
}
let mut renamed = serde_json::to_vec(&header).map_err(invalid_json)?;
renamed.extend_from_slice(rest);
*bytes = renamed;
}
Ok(())
}
fn move_files(session: &mut Snapshot, from: &str, to: &str) {
let moved: Vec<String> = session
.files
.keys()
.filter(|name| name.starts_with(from))
.cloned()
.collect();
for name in moved {
if let (Some(bytes), Some(rest)) = (session.files.remove(&name), name.strip_prefix(from)) {
session.files.insert(format!("{to}{rest}"), bytes);
}
}
}