1use std::collections::HashSet;
5use std::fmt;
6use std::sync::Arc;
7
8use super::placeholder::{is_offloaded, is_offloaded_content};
9use super::strategies::offload::target::is_protocol_block;
10use crate::error::Result;
11use crate::storage::{NamespacedStorage, Storage};
12use crate::types::{ContentBlock, JsonObject, JsonValue, Message, ToolResultBlock};
13
14pub(crate) const ARCHIVE_PREFIX: &str = "context";
16
17#[derive(Debug, Clone, PartialEq, Eq)]
20pub(crate) struct ArchiveKey {
21 pub(crate) id: String,
23 pub(crate) index: usize,
25}
26
27pub(crate) fn format_archive_key(id: &str, index: usize) -> String {
29 format!("{id}_{index}")
30}
31
32pub(crate) fn parse_archive_key(key: &str) -> Option<ArchiveKey> {
35 let separator = key.rfind('_').filter(|&separator| separator > 0)?;
36 let index = &key[separator + 1..];
37 if index.is_empty() || !index.bytes().all(|byte| byte.is_ascii_digit()) {
38 return None;
39 }
40 Some(ArchiveKey {
41 id: key[..separator].to_owned(),
42 index: index.parse().ok()?,
43 })
44}
45
46fn encode(value: &impl serde::Serialize) -> Result<Vec<u8>> {
47 Ok(serde_json::to_vec(value)?)
48}
49
50fn decode(bytes: &[u8]) -> Result<JsonValue> {
51 Ok(serde_json::from_slice(bytes)?)
52}
53
54struct Inner {
55 storage: Arc<dyn Storage>,
56 base_storage: Arc<dyn Storage>,
57 caller_scoped: bool,
58 session_id: String,
59 storage_type_name: String,
60}
61
62#[derive(Clone)]
70pub struct Archive {
71 inner: Arc<Inner>,
72}
73
74impl Archive {
75 pub fn new(storage: Arc<dyn Storage>, session_id: &str, agent_id: &str) -> Result<Self> {
82 Self::with_namespace(storage, session_id, agent_id, false)
83 }
84
85 pub(crate) fn with_namespace(
88 storage: Arc<dyn Storage>,
89 session_id: &str,
90 agent_id: &str,
91 custom_archive_namespace: bool,
92 ) -> Result<Self> {
93 let caller_scoped = custom_archive_namespace && storage.is_namespaced();
94 let scoped: Arc<dyn Storage> = if caller_scoped {
95 storage.clone()
96 } else {
97 Arc::new(NamespacedStorage::new(
98 storage.clone(),
99 &format!("{ARCHIVE_PREFIX}/{session_id}/scopes/agent/{agent_id}"),
100 )?)
101 };
102 let storage_type_name = storage.storage_type().to_owned();
103 Ok(Self {
104 inner: Arc::new(Inner {
105 storage: scoped,
106 base_storage: storage,
107 caller_scoped,
108 session_id: session_id.to_owned(),
109 storage_type_name,
110 }),
111 })
112 }
113
114 #[must_use]
116 pub fn storage_type_name(&self) -> &str {
117 &self.inner.storage_type_name
118 }
119
120 pub async fn store(&self, id: &str, block_index: usize, data: &[u8]) -> Result<String> {
126 let key = format_archive_key(id, block_index);
127 self.inner.storage.write(&key, data).await?;
128 Ok(key)
129 }
130
131 pub(crate) async fn ensure_archived(
144 &self,
145 block: &ContentBlock,
146 message: &Message,
147 block_index: usize,
148 ) -> Result<String> {
149 if let ContentBlock::ToolResult(result) = block {
150 if result.content.iter().any(is_offloaded_content) {
153 return Ok(result.tool_use_id.clone());
154 }
155 if self.keys_of(&result.tool_use_id).await?.len() < result.content.len() {
156 self.store_tool_result(result).await;
157 }
158 return Ok(result.tool_use_id.clone());
159 }
160 let key = format_archive_key(message.tracking_id(), block_index);
161 if !self.list(&key).await?.contains(&key) {
162 self.store(message.tracking_id(), block_index, &encode(block)?).await?;
163 }
164 Ok(key)
165 }
166
167 pub(crate) async fn store_removed(&self, removed: &[Message]) -> Result<String> {
174 let first = removed.first().map_or("", Message::tracking_id);
175 let id = format!("removed-{first}");
176 self.store(&id, 0, &encode(&removed)?).await?;
177 Ok(id)
178 }
179
180 pub async fn store_message(
185 &self,
186 message: &Message,
187 skip_tool_use_ids: Option<&HashSet<String>>,
188 stored_keys: Option<&HashSet<String>>,
189 ) {
190 for (block_index, block) in message.content.iter().enumerate() {
191 if is_skipped(block, message, block_index, skip_tool_use_ids, stored_keys) {
192 continue;
193 }
194 if let ContentBlock::ToolResult(result) = block {
195 self.store_tool_result(result).await;
196 continue;
197 }
198 let stored = match encode(block) {
199 Ok(bytes) => self.store(message.tracking_id(), block_index, &bytes).await.map(drop),
200 Err(error) => Err(error),
201 };
202 if let Err(error) = stored {
203 tracing::warn!(
204 "tracking_id=<{}>, error=<{error}> | failed to archive block",
205 message.tracking_id()
206 );
207 }
208 }
209 }
210
211 async fn store_tool_result(&self, block: &ToolResultBlock) {
212 for (block_index, item) in block.content.iter().enumerate() {
213 let stored = match encode(item) {
214 Ok(bytes) => self.store(&block.tool_use_id, block_index, &bytes).await.map(drop),
215 Err(error) => Err(error),
216 };
217 if let Err(error) = stored {
218 tracing::warn!(
219 "tool_use_id=<{}>, block_index=<{block_index}>, error=<{error}> | failed to archive sub-block",
220 block.tool_use_id
221 );
222 }
223 }
224 }
225
226 pub async fn retrieve(&self, reference: &str) -> Result<Option<JsonValue>> {
232 let Some(bytes) = self.inner.storage.read(reference).await? else {
233 return Ok(None);
234 };
235 decode(&bytes).map(Some)
236 }
237
238 pub async fn list(&self, prefix: &str) -> Result<Vec<String>> {
244 self.inner.storage.list(prefix).await
245 }
246
247 pub(crate) async fn keys_of(&self, id: &str) -> Result<Vec<String>> {
254 let mut keys: Vec<(usize, String)> = self
255 .list(&format!("{id}_"))
256 .await?
257 .into_iter()
258 .filter_map(|key| {
259 let parsed = parse_archive_key(&key)?;
260 (parsed.id == id).then_some((parsed.index, key))
261 })
262 .collect();
263 keys.sort_by_key(|(index, _)| *index);
264 Ok(keys.into_iter().map(|(_, key)| key).collect())
265 }
266
267 pub async fn delete(&self, reference: &str) -> Result<()> {
273 self.inner.storage.delete(reference).await?;
274 tracing::debug!("reference=<{reference}> | archive entry deleted");
275 Ok(())
276 }
277
278 pub async fn clear(&self) -> Result<()> {
285 for key in self.list("").await? {
286 self.delete(&key).await?;
287 }
288 Ok(())
289 }
290
291 pub async fn clear_session(&self) -> Result<()> {
299 if self.inner.caller_scoped {
300 tracing::debug!(
301 "session_id=<{}> | skipping archive deletion, archive is caller-scoped",
302 self.inner.session_id
303 );
304 return Ok(());
305 }
306 let prefix = format!("{ARCHIVE_PREFIX}/{}/", self.inner.session_id);
307 for key in self.inner.base_storage.list(&prefix).await? {
308 self.inner.base_storage.delete(&key).await?;
309 }
310 Ok(())
311 }
312
313 pub async fn take_snapshot(&self) -> Result<JsonObject> {
319 let mut entries = JsonObject::new();
320 for key in self.list("").await? {
321 if let Some(data) = self.retrieve(&key).await? {
322 entries.insert(key, data);
323 }
324 }
325 Ok(entries)
326 }
327
328 pub async fn load_snapshot(&self, entries: &JsonObject) -> Result<()> {
334 for (key, data) in entries {
335 self.inner.storage.write(key, &encode(data)?).await?;
336 }
337 Ok(())
338 }
339}
340
341fn is_skipped(
343 block: &ContentBlock,
344 message: &Message,
345 block_index: usize,
346 skip_tool_use_ids: Option<&HashSet<String>>,
347 stored_keys: Option<&HashSet<String>>,
348) -> bool {
349 if is_protocol_block(block) {
350 return true;
351 }
352 if let ContentBlock::ToolResult(result) = block {
353 if skip_tool_use_ids.is_some_and(|skip| skip.contains(&result.tool_use_id))
354 || result.content.iter().any(is_offloaded_content)
355 {
356 return true;
357 }
358 return stored_keys.is_some_and(|keys| {
359 keys.iter()
360 .any(|key| parse_archive_key(key).is_some_and(|parsed| parsed.id == result.tool_use_id))
361 });
362 }
363 if is_offloaded(block) {
364 return true;
365 }
366 stored_keys.is_some_and(|keys| keys.contains(&format_archive_key(message.tracking_id(), block_index)))
367}
368
369impl fmt::Debug for Archive {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 f.debug_struct("Archive")
372 .field("session_id", &self.inner.session_id)
373 .field("storage_type_name", &self.inner.storage_type_name)
374 .field("caller_scoped", &self.inner.caller_scoped)
375 .finish_non_exhaustive()
376 }
377}
378
379#[cfg(test)]
380#[path = "archive/tests.rs"]
381mod tests;