agent_works/compression/middleware/mod.rs
1//! Middleware integration for context compression.
2//!
3//! [`CompressionMiddleware`] implements the [`agent_base::Middleware`] trait,
4//! compressing the per-LLM-call message list on every `on_pre_llm` invocation.
5//!
6//! The middleware delegates to [`ContextCompactor`] which handles the hybrid
7//! retention strategy (system prompt + summary + recent N messages) and the
8//! stable-prefix cache. The session's stored history is **never** modified;
9//! only the mutable message copy in [`PreLlmCtx`] is replaced.
10//!
11//! A [`CompressionPolicy`] controls whether compression proceeds once the token
12//! threshold is crossed. The default [`AutoCompressionPolicy`] always proceeds;
13//! custom policies can add user confirmation, rate limiting, etc.
14
15use std::sync::Arc;
16use std::sync::atomic::{AtomicUsize, Ordering};
17
18use agent_base::{AgentResult, ChatMessage, Middleware, PreLlmCtx};
19
20use crate::compression::compactor::{ContextCompactor, estimate_message_tokens};
21use std::sync::Once;
22
23use crate::compression::config::CompressionConfig;
24use crate::compression::events::{CompressionEvent, CompressionTrigger};
25use crate::compression::filter::is_summary_message;
26use crate::compression::policy::{AutoCompressionPolicy, CompressionPolicy};
27
28/// Write compression before/after log to `/tmp/phi-agent-compression/`.
29fn write_compression_log(
30 session_id: u64,
31 before: &[ChatMessage],
32 after: &[ChatMessage],
33 tokens_before: usize,
34 tokens_after: usize,
35 reduction_pct: i32,
36) {
37 use std::io::Write;
38
39 let dir = std::path::Path::new("/tmp/phi-agent-compression");
40 if let Err(e) = std::fs::create_dir_all(dir) {
41 tracing::warn!("Failed to create compression log dir: {e}");
42 return;
43 }
44
45 let ts = std::time::SystemTime::now()
46 .duration_since(std::time::UNIX_EPOCH)
47 .unwrap_or_default()
48 .as_secs();
49 let filename = dir.join(format!("session_{session_id}_{ts}.json"));
50
51 let log = serde_json::json!({
52 "session_id": session_id,
53 "timestamp": ts,
54 "evaluation": {
55 "tokens_before": tokens_before,
56 "tokens_after": tokens_after,
57 "reduction_pct": reduction_pct,
58 "msg_count_before": before.len(),
59 "msg_count_after": after.len(),
60 },
61 "before": before.iter().map(format_message).collect::<Vec<_>>(),
62 "after": after.iter().map(format_message).collect::<Vec<_>>(),
63 });
64
65 match std::fs::File::create(&filename) {
66 Ok(mut f) => {
67 if let Err(e) = f.write_all(serde_json::to_string_pretty(&log).unwrap().as_bytes()) {
68 tracing::warn!("Failed to write compression log: {e}");
69 } else {
70 tracing::info!("Compression log written to {}", filename.display());
71 }
72 }
73 Err(e) => tracing::warn!("Failed to create compression log file: {e}"),
74 }
75}
76
77/// Format a ChatMessage into a readable JSON value for logging.
78fn format_message(msg: &ChatMessage) -> serde_json::Value {
79 match msg {
80 ChatMessage::System { content, .. } => serde_json::json!({
81 "role": "system",
82 "content": content,
83 }),
84 ChatMessage::User { content, .. } => serde_json::json!({
85 "role": "user",
86 "content": content,
87 }),
88 ChatMessage::Assistant {
89 content,
90 tool_calls,
91 ..
92 } => {
93 let mut m = serde_json::json!({
94 "role": "assistant",
95 "content": content,
96 });
97 if let Some(tc) = tool_calls {
98 m["tool_calls"] = serde_json::to_value(tc).unwrap_or_default();
99 }
100 m
101 }
102 ChatMessage::Tool {
103 content,
104 tool_call_id,
105 ..
106 } => serde_json::json!({
107 "role": "tool",
108 "tool_call_id": tool_call_id,
109 "content": content,
110 }),
111 ChatMessage::Custom { role, data } => serde_json::json!({
112 "role": role,
113 "data": data,
114 }),
115 }
116}
117
118/// Middleware that compresses conversation history before each LLM call.
119///
120/// Wraps a [`ContextCompactor`] and forwards `on_pre_llm` to its [`compact`]
121/// method. When the estimated token count is below [`CompressionConfig::trigger_tokens`],
122/// the middleware is a no-op and the original messages pass through unchanged.
123///
124/// A [`CompressionPolicy`] controls whether compression actually proceeds once
125/// the threshold is crossed. Use [`with_policy`](Self::with_policy) to supply
126/// a custom policy (e.g. user confirmation, rate limiting).
127///
128/// # Usage
129///
130/// ```ignore
131/// use agent_works::compression::{CompressionConfig, CompressionMiddleware};
132///
133/// let mw = CompressionMiddleware::new(config, client);
134/// builder.middleware(mw);
135/// ```
136///
137/// [`compact`]: ContextCompactor::compact
138pub struct CompressionMiddleware {
139 compactor: ContextCompactor,
140 policy: Box<dyn CompressionPolicy>,
141 /// Message count after the last successful compression.
142 /// Used to calculate only the *new* old-block tokens for threshold checks,
143 /// preventing re-triggering caused by recent messages rolling into the old block.
144 last_compressed_msg_count: AtomicUsize,
145}
146
147#[allow(missing_docs)]
148impl CompressionMiddleware {
149 /// Create a new middleware with the given config and LLM client.
150 ///
151 /// Uses [`AutoCompressionPolicy`] (always compress when threshold is hit).
152 pub fn new(
153 config: CompressionConfig,
154 client: Arc<dyn agent_base::llm_trait::LlmProvider>,
155 ) -> Self {
156 Self {
157 compactor: ContextCompactor::new(client, config),
158 policy: Box::new(AutoCompressionPolicy),
159 last_compressed_msg_count: AtomicUsize::new(0),
160 }
161 }
162
163 /// Create a new middleware from an existing [`ContextCompactor`].
164 ///
165 /// Uses [`AutoCompressionPolicy`].
166 pub fn from_compactor(compactor: ContextCompactor) -> Self {
167 Self {
168 compactor,
169 policy: Box::new(AutoCompressionPolicy),
170 last_compressed_msg_count: AtomicUsize::new(0),
171 }
172 }
173
174 /// Create a new middleware with a custom [`CompressionPolicy`].
175 pub fn with_policy(
176 config: CompressionConfig,
177 client: Arc<dyn agent_base::llm_trait::LlmProvider>,
178 policy: Box<dyn CompressionPolicy>,
179 ) -> Self {
180 Self {
181 compactor: ContextCompactor::new(client, config),
182 policy,
183 last_compressed_msg_count: AtomicUsize::new(0),
184 }
185 }
186
187 /// Access the inner compactor (e.g. for `/compact` or cache clearing).
188 pub fn compactor(&self) -> &ContextCompactor {
189 &self.compactor
190 }
191
192 /// Create a cloned handle of the inner compactor.
193 ///
194 /// The clone shares the same cache — clearing it through either handle
195 /// affects both. Useful for storing a separate handle outside the
196 /// middleware (e.g. in `PhiAgent` for `/compact` access).
197 pub fn clone_compactor(&self) -> ContextCompactor {
198 self.compactor.clone_handle()
199 }
200
201 /// Access the compression config.
202 pub fn config(&self) -> &CompressionConfig {
203 self.compactor.config()
204 }
205}
206
207#[async_trait::async_trait]
208impl Middleware for CompressionMiddleware {
209 async fn on_pre_llm(&self, ctx: &mut PreLlmCtx) -> AgentResult<()> {
210 let t0 = std::time::Instant::now();
211 let msg_count = ctx.messages.len();
212
213 // Quick check — below minimum message count, skip entirely.
214 // Need at least system + keep_recent + 1 to have anything to compress.
215 let keep = self.config().keep_recent_messages;
216 if msg_count <= keep + 1 {
217 return Ok(());
218 }
219
220 // Only count tokens added SINCE the last compression (new old-block
221 // content). This prevents re-triggering caused by recent messages
222 // rolling into the old block after compression.
223 //
224 // Also skip system and existing summary messages.
225 let last_compressed = self.last_compressed_msg_count.load(Ordering::Relaxed);
226 let tokens_before: usize = ctx
227 .messages
228 .iter()
229 .skip(last_compressed)
230 .filter(|m| !matches!(m, ChatMessage::System { .. }))
231 .filter(|m| !is_summary_message(m))
232 .map(estimate_message_tokens)
233 .sum();
234 tracing::info!(
235 tokens_before,
236 msg_count,
237 trigger = self.config().trigger_tokens,
238 "[compression-timing] threshold check"
239 );
240
241 // Quick check — below threshold, skip entirely.
242 if tokens_before <= self.config().trigger_tokens {
243 return Ok(());
244 }
245
246 // Defensive: warn once if trigger_tokens >= 1M.
247 // The caller should ensure trigger_tokens < context_window.
248 static TRIGGER_WARN: Once = Once::new();
249 if self.config().trigger_tokens >= 1_000_000 {
250 TRIGGER_WARN.call_once(|| {
251 tracing::warn!(
252 trigger_tokens = self.config().trigger_tokens,
253 "trigger_tokens >= 1M — likely exceeds context_window; compression may never fire efficiently"
254 );
255 });
256 }
257
258 tracing::info!(
259 elapsed_ms = t0.elapsed().as_millis() as u64,
260 "[compression-timing] threshold passed"
261 );
262
263 // Policy check — ask policy whether to proceed.
264 if !self.policy.should_compress(tokens_before, msg_count).await {
265 return Ok(());
266 }
267
268 tracing::info!(
269 elapsed_ms = t0.elapsed().as_millis() as u64,
270 "[compression-timing] policy passed, entering compact"
271 );
272
273 // Determine trigger type (manual if /compact, auto otherwise).
274 // For now, middleware is always auto; /compact goes through a different path.
275 let trigger = CompressionTrigger::Auto;
276 let sid = ctx.session_id.id;
277
278 // Discard old summary before re-compressing.
279 // compact() handles preserving user messages and summarizing assistant/tool.
280 // We only need to remove the old summary so it doesn't get re-summarized.
281 let filtered: Vec<ChatMessage> = ctx
282 .messages
283 .iter()
284 .filter(|m| !is_summary_message(m))
285 .cloned()
286 .collect();
287
288 // After filtering, check if there's enough content to compress.
289 // Need more than keep_recent messages to have an old block at all.
290 let keep = self.config().keep_recent_messages;
291 if filtered.len() <= keep + 1 {
292 self.last_compressed_msg_count
293 .store(msg_count, Ordering::Relaxed);
294 return Ok(());
295 }
296
297 // Save messages before compression for logging.
298 let messages_before = ctx.messages.clone();
299 let t_compact = std::time::Instant::now();
300
301 match self
302 .compactor
303 .compact(
304 sid,
305 &filtered,
306 trigger.clone(),
307 Some(&|ev| ctx.emit(ev.into_user_event())),
308 )
309 .await?
310 {
311 Some(compressed) => {
312 tracing::info!(
313 elapsed_ms = t_compact.elapsed().as_millis() as u64,
314 "[compression-timing] compact() returned Some"
315 );
316 ctx.messages = compressed;
317 // Record the pre-compression message count so the next threshold
318 // check only counts new content added since this compression.
319 // Using pre-compression count (not compressed length) because
320 // skip() operates on the full message array structure.
321 self.last_compressed_msg_count
322 .store(msg_count, Ordering::Relaxed);
323 // Count tokens after compression (same scope as tokens_before).
324 // tokens_before counts all non-system, non-summary messages from last_compressed.
325 // tokens_after should count the same scope after compression.
326 // Since compression replaces the old block with a summary, we count
327 // all non-system messages in the compressed result (including the new summary).
328 let tokens_after: usize = ctx
329 .messages
330 .iter()
331 .filter(|m| !matches!(m, ChatMessage::System { .. }))
332 .map(estimate_message_tokens)
333 .sum();
334 let reduction_pct = if tokens_before > 0 {
335 ((tokens_before as f64 - tokens_after as f64) / tokens_before as f64 * 100.0)
336 .round() as i32
337 } else {
338 0
339 };
340
341 // Send Completed event.
342 ctx.emit(
343 CompressionEvent::Completed {
344 session_id: sid,
345 tokens_before,
346 tokens_after,
347 reduction_pct,
348 msg_count_before: msg_count,
349 msg_count_after: ctx.messages.len(),
350 trigger,
351 }
352 .into_user_event(),
353 );
354
355 // Write before/after log to /tmp/phi-agent-compression/.
356 write_compression_log(
357 ctx.session_id.id,
358 &messages_before,
359 &ctx.messages,
360 tokens_before,
361 tokens_after,
362 reduction_pct,
363 );
364 }
365 None => {
366 // Compression skipped (threshold not reached, disabled, or too few messages).
367 // This is a normal no-op — do NOT send Failed event.
368 // compact() is pure and never modified ctx.messages, so no restore needed.
369 //
370 // Still update the checkpoint so the next threshold check only
371 // counts truly new content, preventing a re-trigger loop.
372 self.last_compressed_msg_count
373 .store(msg_count, Ordering::Relaxed);
374 }
375 }
376 Ok(())
377 }
378}
379
380#[cfg(test)]
381mod tests;