agent_works/compression/compactor/mod.rs
1//! Core compression logic — hybrid retention + stable-prefix cache.
2//!
3//! [`ContextCompactor`] takes a full message history and produces a compressed
4//! copy that preserves:
5//!
6//! 1. The system prompt (verbatim).
7//! 2. The most recent N messages (verbatim, including tool results).
8//! 3. A handoff summary of the older history (generated by LLM, cached).
9//!
10//! The compactor is **stateful** — it caches summaries keyed on a stable prefix
11//! hash so repeated calls with the same old block skip the LLM round-trip.
12
13use std::sync::{Arc, Mutex};
14
15use agent_base::llm_trait::LlmProvider;
16use agent_base::{AgentResult, AgentRuntime, ChatMessage, SessionId};
17
18use crate::compression::config::CompressionConfig;
19use crate::compression::events::{CompressionEvent, CompressionTrigger};
20use crate::compression::filter::{SUMMARY_PREFIX, is_summary_message, split_system_prompt};
21use crate::compression::summarizer::summarize;
22
23mod fit;
24pub(crate) use fit::estimate_message_tokens;
25use fit::{hash_str, message_content_len, truncate_to_chars, truncate_user_messages};
26pub use fit::{safe_cut_index, serialize_block, truncate_str};
27
28// ── Public API ───────────────────────────────────────────────────────────────
29
30/// Cached summary entry: `(transcript_len, summary_text)`.
31///
32/// `transcript_len` guards against reusing a stale summary when the old block
33/// has grown significantly since the cache was populated.
34type CompactionCache = std::collections::HashMap<(u64, u64), (usize, String)>;
35
36/// Core compressor implementing the hybrid retention strategy.
37///
38/// Holds an [`LlmProvider`] for LLM summarisation and a thread-safe cache to
39/// avoid redundant calls. Designed to be shared via `Arc` across middleware
40/// invocations.
41///
42/// Use `clone()` to create a second handle that shares the same
43/// underlying cache — useful when the compactor is registered as middleware *and*
44/// stored separately for manual `/compact` access.
45pub struct ContextCompactor {
46 client: Arc<dyn LlmProvider>,
47 config: CompressionConfig,
48 /// `(session_id, prefix_hash) → (transcript_len, summary)` cache.
49 /// Wrapped in `Arc` so that `clone()` shares the same cache.
50 cache: Arc<Mutex<CompactionCache>>,
51}
52
53#[allow(missing_docs)]
54impl ContextCompactor {
55 pub fn new(client: Arc<dyn LlmProvider>, config: CompressionConfig) -> Self {
56 Self {
57 client,
58 config,
59 cache: Arc::new(Mutex::new(std::collections::HashMap::new())),
60 }
61 }
62
63 /// Create a second handle to the same compactor.
64 ///
65 /// The clone shares the same LLM client and summary cache — clearing the
66 /// cache through either handle affects both.
67 pub fn clone_handle(&self) -> Self {
68 Self {
69 client: self.client.clone(),
70 config: self.config.clone(),
71 cache: self.cache.clone(),
72 }
73 }
74
75 pub fn config(&self) -> &CompressionConfig {
76 &self.config
77 }
78
79 // ── Core compression ─────────────────────────────────────────────────
80
81 /// Maximum tokens for user messages preserved verbatim from the old block.
82 ///
83 /// Matches codex's `COMPACT_USER_MESSAGE_MAX_TOKENS`. User messages are
84 /// typically short instructions, so 20k tokens is generous enough to never
85 /// truncate in practice while preventing pathological cases (e.g., user
86 /// pasting a huge code block).
87 const MAX_PRESERVED_USER_TOKENS: usize = 20_000;
88
89 /// Produce a compressed copy of `messages` for a single LLM call.
90 ///
91 /// Returns `None` when compression is skipped (disabled, below threshold,
92 /// or too few messages). The caller should use the original `messages`
93 /// unchanged in that case.
94 ///
95 /// `session_id` is used as part of the cache key so different sessions
96 /// never share summaries.
97 ///
98 /// # Compression strategy
99 ///
100 /// User messages from the old block are preserved verbatim (truncated to
101 /// `MAX_PRESERVED_USER_TOKENS`).
102 /// Only assistant and tool responses are summarised by the LLM. This
103 /// mirrors codex's compaction strategy and avoids the common pitfall of
104 /// the summarizer reproducing assistant-generated content (poems, code,
105 /// articles) verbatim, which can make the compressed output *larger* than
106 /// the original.
107 pub async fn compact(
108 &self,
109 session_id: u64,
110 messages: &[ChatMessage],
111 trigger: CompressionTrigger,
112 emit_fn: Option<&(dyn Fn(CompressionEvent) + Sync)>,
113 ) -> AgentResult<Option<Vec<ChatMessage>>> {
114 let t0 = std::time::Instant::now();
115 if !self.config.enabled {
116 return Ok(None);
117 }
118
119 let total_tokens: usize = messages.iter().map(estimate_message_tokens).sum();
120 tracing::info!(
121 total_tokens,
122 trigger = self.config.trigger_tokens,
123 "[compact-timing] enter compact()"
124 );
125 if total_tokens <= self.config.trigger_tokens {
126 return Ok(None);
127 }
128
129 // 1. Split off system prompt.
130 let (system_msgs, conversation) = split_system_prompt(messages);
131 tracing::info!(
132 elapsed_ms = t0.elapsed().as_millis() as u64,
133 conv_len = conversation.len(),
134 keep = self.config.keep_recent_messages,
135 "[compact-timing] after split_system_prompt"
136 );
137 if conversation.len() <= self.config.keep_recent_messages + 1 {
138 return Ok(None);
139 }
140
141 // 2. Split conversation into old / recent.
142 let mut recent_start = conversation.len() - self.config.keep_recent_messages;
143 recent_start = safe_cut_index(conversation, 0, recent_start);
144 tracing::info!(
145 elapsed_ms = t0.elapsed().as_millis() as u64,
146 recent_start,
147 "[compact-timing] after split old/recent"
148 );
149 if recent_start == 0 {
150 return Ok(None);
151 }
152
153 // All checks passed — compression will proceed. Notify caller.
154
155 let old = &conversation[..recent_start];
156 let recent = &conversation[recent_start..];
157
158 // Defensive: never start the old block on an orphaned tool result.
159 if matches!(old.first(), Some(ChatMessage::Tool { .. })) {
160 tracing::warn!("context compression skipped: old block starts with a tool result");
161 return Ok(None);
162 }
163
164 // 3. Filter old summaries from both blocks.
165 let old: Vec<&ChatMessage> = old.iter().filter(|m| !is_summary_message(m)).collect();
166 let recent: Vec<&ChatMessage> = recent.iter().filter(|m| !is_summary_message(m)).collect();
167
168 // 4. Extract original goal (first user message in old block).
169 let original_goal = old
170 .iter()
171 .find_map(|m| match m {
172 ChatMessage::User { content, .. } if !content.starts_with(SUMMARY_PREFIX) => {
173 Some(content.as_str())
174 }
175 _ => None,
176 })
177 .unwrap_or("(unknown goal)");
178 let original_goal = truncate_str(original_goal, 400);
179
180 // 5. Separate user messages (preserved verbatim) from assistant/tool
181 // messages (sent to summarizer).
182 let preserved_user_msgs: Vec<&ChatMessage> = old
183 .iter()
184 .filter(|m| matches!(m, ChatMessage::User { .. }))
185 .copied()
186 .collect();
187 let assistant_tool_msgs: Vec<&ChatMessage> = old
188 .iter()
189 .filter(|m| !matches!(m, ChatMessage::User { .. }))
190 .copied()
191 .collect();
192
193 // Serialize only assistant/tool messages for the summarizer.
194 let transcript = truncate_to_chars(&assistant_tool_msgs, self.config.max_transcript_chars);
195 if transcript.trim().is_empty() && preserved_user_msgs.is_empty() {
196 return Ok(None);
197 }
198
199 // All early-exit checks passed — compression will proceed.
200 let msg_count = messages.len();
201 if let Some(emit) = emit_fn {
202 emit(CompressionEvent::Preparing {
203 session_id,
204 tokens_before: total_tokens,
205 msg_count,
206 trigger: trigger.clone(),
207 });
208 emit(CompressionEvent::Started {
209 session_id,
210 tokens_before: total_tokens,
211 msg_count,
212 trigger: trigger.clone(),
213 });
214 }
215
216 const CACHE_PREFIX_CHARS: usize = 4096;
217 let prefix: String = transcript.chars().take(CACHE_PREFIX_CHARS).collect();
218 let key = (session_id, hash_str(&prefix));
219
220 let cached = self.cache.lock().ok().and_then(|c| c.get(&key).cloned());
221
222 // Reuse cached summary when the transcript hasn't changed, OR when it
223 // has hit the max_transcript_chars cap (content is frozen at that point,
224 // further growth only affects the tail which is truncated away).
225 let cache_effective = matches!(cached, Some((cl, _)) if cl == transcript.len() || transcript.len() >= self.config.max_transcript_chars);
226
227 let summary = if transcript.trim().is_empty() {
228 // No assistant/tool content to summarize — skip LLM call.
229 String::new()
230 } else {
231 match cached {
232 Some((_, ref s)) if cache_effective => s.clone(),
233 _ => {
234 // Notify caller that we're about to call the LLM.
235 if let Some(emit) = emit_fn {
236 emit(CompressionEvent::Progress {
237 session_id,
238 chars: 0,
239 });
240 }
241 tracing::info!(
242 elapsed_ms = t0.elapsed().as_millis() as u64,
243 "[compact-timing] before summarize() LLM call"
244 );
245 // summarize() reports cumulative char count via on_progress.
246 // Wrap it to emit CompressionEvent::Progress.
247 let s = if let Some(emit) = emit_fn {
248 let progress_fn = |chars: usize| {
249 emit(CompressionEvent::Progress { session_id, chars });
250 };
251 summarize(
252 self.client.as_ref(),
253 &transcript,
254 &original_goal,
255 self.config.max_summary_chars,
256 Some(&progress_fn),
257 )
258 .await
259 } else {
260 summarize(
261 self.client.as_ref(),
262 &transcript,
263 &original_goal,
264 self.config.max_summary_chars,
265 None,
266 )
267 .await
268 };
269 let s = match s {
270 Ok(s) => {
271 tracing::info!(
272 elapsed_ms = t0.elapsed().as_millis() as u64,
273 "[compact-timing] summarize() returned Ok"
274 );
275 s
276 }
277 Err(e) => {
278 tracing::warn!(
279 session_id,
280 "summarisation failed, falling back to dropping old block: {e}"
281 );
282 String::new()
283 }
284 };
285 if !s.is_empty()
286 && let Ok(mut cache) = self.cache.lock()
287 {
288 cache.insert(key, (transcript.len(), s.clone()));
289 }
290 s
291 }
292 }
293 };
294
295 // 6. Assemble: [system prompt] + [preserved user messages] + [summary] + [recent N].
296 // User messages are preserved verbatim (truncated to MAX_PRESERVED_USER_TOKENS)
297 // so the LLM always sees exact user instructions.
298 let mut new_messages: Vec<ChatMessage> = system_msgs.to_vec();
299
300 // Add preserved user messages, truncated from the start to fit.
301 let truncated_user =
302 truncate_user_messages(&preserved_user_msgs, Self::MAX_PRESERVED_USER_TOKENS);
303
304 let trimmed = summary.trim();
305
306 // 7. Guard: if the replacement (preserved users + summary) is larger
307 // than the original old block, discard the compression and keep the
308 // original messages. This prevents negative compression on short
309 // conversations where the summary overhead exceeds the original
310 // assistant content.
311 let old_block_chars: usize = old.iter().map(|m| message_content_len(m)).sum();
312 let replacement_chars: usize = truncated_user
313 .iter()
314 .map(|m| message_content_len(m))
315 .sum::<usize>()
316 + if trimmed.is_empty() {
317 0
318 } else {
319 SUMMARY_PREFIX.len() + 1 + trimmed.len()
320 };
321 if replacement_chars >= old_block_chars {
322 tracing::info!(
323 session_id,
324 old_block_chars,
325 replacement_chars,
326 "[compact-timing] replacement larger than original, skipping compression"
327 );
328 return Ok(None);
329 }
330
331 new_messages.extend(truncated_user.into_iter().cloned());
332
333 if !trimmed.is_empty() {
334 new_messages.push(ChatMessage::user(format!("{SUMMARY_PREFIX}\n{trimmed}")));
335 }
336 new_messages.extend(recent.into_iter().cloned());
337
338 // Record what happened.
339 let compressed_tokens: usize = new_messages.iter().map(estimate_message_tokens).sum();
340 tracing::info!(
341 session_id,
342 tokens_before = total_tokens,
343 tokens_after = compressed_tokens,
344 kept_recent = self.config.keep_recent_messages,
345 summary_len = trimmed.len(),
346 preserved_user_count = preserved_user_msgs.len(),
347 old_block_chars,
348 replacement_chars,
349 cache_hit = cache_effective,
350 elapsed_ms = t0.elapsed().as_millis() as u64,
351 "[compact-timing] compression complete"
352 );
353
354 Ok(Some(new_messages))
355 }
356
357 // ── Cache management ─────────────────────────────────────────────────
358
359 /// Clear all cached summaries.
360 pub fn clear_cache(&self) {
361 if let Ok(mut cache) = self.cache.lock() {
362 cache.clear();
363 }
364 }
365
366 // ── Session-level compression ──────────────────────────────────────────
367
368 /// Read-compress-write-back: compress a session's messages in place.
369 ///
370 /// Returns `Ok(true)` if compression was applied (session was above the
371 /// threshold), `Ok(false)` if the session was already below the threshold.
372 ///
373 /// Returns `Err` if the write-back validation fails (unexpected) or if
374 /// the session was modified concurrently between read and write-back
375 /// (TOCTOU guard).
376 pub async fn compact_session(
377 &self,
378 runtime: &AgentRuntime,
379 session_id: &SessionId,
380 emit_fn: Option<std::sync::Arc<dyn Fn(agent_base::UserEvent) + Send + Sync>>,
381 ) -> AgentResult<bool> {
382 let sid = session_id.id;
383 let trigger = CompressionTrigger::Manual;
384
385 // Phase 1: read messages from the session (lock held briefly).
386 let messages = runtime
387 .with_session_mut(session_id, |session| session.chat_messages().to_vec())
388 .await?;
389 let msg_count_before = messages.len();
390 let tokens_before: usize = messages.iter().map(estimate_message_tokens).sum();
391
392 // Phase 2: compress (async LLM call, no session lock held).
393 // Filter out old summary messages before compressing (same as middleware).
394 let filtered: Vec<ChatMessage> = messages
395 .iter()
396 .filter(|m| !is_summary_message(m))
397 .cloned()
398 .collect();
399
400 // Build emit_fn wrapper: CompressionEvent → into_user_event() → caller's emit_fn.
401 let compressed = if let Some(ref ef) = emit_fn {
402 let ef = ef.clone();
403 self.compact(
404 sid,
405 &filtered,
406 trigger.clone(),
407 Some(&move |ev: CompressionEvent| {
408 ef(ev.into_user_event());
409 }),
410 )
411 .await?
412 } else {
413 self.compact(sid, &filtered, trigger.clone(), None).await?
414 };
415
416 let compressed = match compressed {
417 Some(msgs) => msgs,
418 None => {
419 // Below threshold — no-op, no events needed.
420 return Ok(false);
421 }
422 };
423
424 let tokens_after: usize = compressed.iter().map(estimate_message_tokens).sum();
425 let msg_count_after = compressed.len();
426
427 // Phase 3: write back (lock held briefly for set_chat_messages + validation).
428 // TOCTOU guard: verify message count hasn't changed since Phase 1.
429 runtime
430 .with_session_mut(session_id, |session| {
431 let msg_count_now = session.chat_messages().len();
432 if msg_count_now != msg_count_before {
433 return Err(agent_base::AgentError::internal(format!(
434 "session modified concurrently ({} → {} messages), aborting write-back",
435 msg_count_before, msg_count_now
436 )));
437 }
438 session.set_chat_messages(compressed).map_err(|e| {
439 agent_base::AgentError::internal(format!(
440 "set_chat_messages validation failed: {e}"
441 ))
442 })
443 })
444 .await??;
445
446 // Emit Completed event.
447 let reduction_pct = if tokens_before > 0 {
448 ((tokens_before as f64 - tokens_after as f64) / tokens_before as f64 * 100.0).round()
449 as i32
450 } else {
451 0
452 };
453 if let Some(ref f) = emit_fn {
454 f(CompressionEvent::Completed {
455 session_id: sid,
456 tokens_before,
457 tokens_after,
458 reduction_pct,
459 msg_count_before,
460 msg_count_after,
461 trigger,
462 }
463 .into_user_event());
464 }
465
466 Ok(true)
467 }
468}
469
470// ── Helpers ──────────────────────────────────────────────────────────────────
471
472/// Implement the agent-base `ContextCompaction` trait so the react loop
473/// can trigger inline compaction without depending on agent-works directly.
474#[async_trait::async_trait]
475impl agent_base::ContextCompaction for ContextCompactor {
476 async fn compact(
477 &self,
478 session_id: &SessionId,
479 messages: &[ChatMessage],
480 ) -> Option<agent_base::CompactionOutcome> {
481 // Delegate to the existing compact() method with InlineCompaction trigger
482 match self
483 .compact(
484 session_id.id,
485 messages,
486 CompressionTrigger::InlineCompaction,
487 None,
488 )
489 .await
490 {
491 Ok(Some(result)) => {
492 // This compactor always replaces the history wholesale, which
493 // is the Reset kind for logging — the react loop must say
494 // "compaction" here (issue #33).
495 Some(agent_base::CompactionOutcome {
496 kind: agent_base::CompactionKind::Reset,
497 messages: result,
498 })
499 }
500 Ok(None) => None,
501 Err(e) => {
502 tracing::warn!(
503 session_id = session_id.id,
504 error = %e,
505 "inline compaction failed"
506 );
507 None
508 }
509 }
510 }
511
512 fn token_count_hint(&self, _session_id: &SessionId) -> Option<usize> {
513 // The react loop uses ContextWindowManager for estimation
514 None
515 }
516}
517
518#[cfg(test)]
519mod tests;