agent-works 0.13.0

Batteries-included Agent toolbox built on agent-base
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! Core compression logic — hybrid retention + stable-prefix cache.
//!
//! [`ContextCompactor`] takes a full message history and produces a compressed
//! copy that preserves:
//!
//! 1. The system prompt (verbatim).
//! 2. The most recent N messages (verbatim, including tool results).
//! 3. A handoff summary of the older history (generated by LLM, cached).
//!
//! The compactor is **stateful** — it caches summaries keyed on a stable prefix
//! hash so repeated calls with the same old block skip the LLM round-trip.

use std::sync::{Arc, Mutex};

use agent_base::llm_trait::LlmProvider;
use agent_base::{AgentResult, AgentRuntime, ChatMessage, SessionId};

use crate::compression::config::CompressionConfig;
use crate::compression::events::{CompressionEvent, CompressionTrigger};
use crate::compression::filter::{SUMMARY_PREFIX, is_summary_message, split_system_prompt};
use crate::compression::summarizer::summarize;

mod fit;
pub(crate) use fit::estimate_message_tokens;
use fit::{hash_str, message_content_len, truncate_to_chars, truncate_user_messages};
pub use fit::{safe_cut_index, serialize_block, truncate_str};

// ── Public API ───────────────────────────────────────────────────────────────

/// Cached summary entry: `(transcript_len, summary_text)`.
///
/// `transcript_len` guards against reusing a stale summary when the old block
/// has grown significantly since the cache was populated.
type CompactionCache = std::collections::HashMap<(u64, u64), (usize, String)>;

/// Core compressor implementing the hybrid retention strategy.
///
/// Holds an [`LlmProvider`] for LLM summarisation and a thread-safe cache to
/// avoid redundant calls.  Designed to be shared via `Arc` across middleware
/// invocations.
///
/// Use `clone()` to create a second handle that shares the same
/// underlying cache — useful when the compactor is registered as middleware *and*
/// stored separately for manual `/compact` access.
pub struct ContextCompactor {
    client: Arc<dyn LlmProvider>,
    config: CompressionConfig,
    /// `(session_id, prefix_hash) → (transcript_len, summary)` cache.
    /// Wrapped in `Arc` so that `clone()` shares the same cache.
    cache: Arc<Mutex<CompactionCache>>,
}

#[allow(missing_docs)]
impl ContextCompactor {
    pub fn new(client: Arc<dyn LlmProvider>, config: CompressionConfig) -> Self {
        Self {
            client,
            config,
            cache: Arc::new(Mutex::new(std::collections::HashMap::new())),
        }
    }

    /// Create a second handle to the same compactor.
    ///
    /// The clone shares the same LLM client and summary cache — clearing the
    /// cache through either handle affects both.
    pub fn clone_handle(&self) -> Self {
        Self {
            client: self.client.clone(),
            config: self.config.clone(),
            cache: self.cache.clone(),
        }
    }

    pub fn config(&self) -> &CompressionConfig {
        &self.config
    }

    // ── Core compression ─────────────────────────────────────────────────

    /// Maximum tokens for user messages preserved verbatim from the old block.
    ///
    /// Matches codex's `COMPACT_USER_MESSAGE_MAX_TOKENS`.  User messages are
    /// typically short instructions, so 20k tokens is generous enough to never
    /// truncate in practice while preventing pathological cases (e.g., user
    /// pasting a huge code block).
    const MAX_PRESERVED_USER_TOKENS: usize = 20_000;

    /// Produce a compressed copy of `messages` for a single LLM call.
    ///
    /// Returns `None` when compression is skipped (disabled, below threshold,
    /// or too few messages).  The caller should use the original `messages`
    /// unchanged in that case.
    ///
    /// `session_id` is used as part of the cache key so different sessions
    /// never share summaries.
    ///
    /// # Compression strategy
    ///
    /// User messages from the old block are preserved verbatim (truncated to
    /// `MAX_PRESERVED_USER_TOKENS`).
    /// Only assistant and tool responses are summarised by the LLM.  This
    /// mirrors codex's compaction strategy and avoids the common pitfall of
    /// the summarizer reproducing assistant-generated content (poems, code,
    /// articles) verbatim, which can make the compressed output *larger* than
    /// the original.
    pub async fn compact(
        &self,
        session_id: u64,
        messages: &[ChatMessage],
        trigger: CompressionTrigger,
        emit_fn: Option<&(dyn Fn(CompressionEvent) + Sync)>,
    ) -> AgentResult<Option<Vec<ChatMessage>>> {
        let t0 = std::time::Instant::now();
        if !self.config.enabled {
            return Ok(None);
        }

        let total_tokens: usize = messages.iter().map(estimate_message_tokens).sum();
        tracing::info!(
            total_tokens,
            trigger = self.config.trigger_tokens,
            "[compact-timing] enter compact()"
        );
        if total_tokens <= self.config.trigger_tokens {
            return Ok(None);
        }

        // 1. Split off system prompt.
        let (system_msgs, conversation) = split_system_prompt(messages);
        tracing::info!(
            elapsed_ms = t0.elapsed().as_millis() as u64,
            conv_len = conversation.len(),
            keep = self.config.keep_recent_messages,
            "[compact-timing] after split_system_prompt"
        );
        if conversation.len() <= self.config.keep_recent_messages + 1 {
            return Ok(None);
        }

        // 2. Split conversation into old / recent.
        let mut recent_start = conversation.len() - self.config.keep_recent_messages;
        recent_start = safe_cut_index(conversation, 0, recent_start);
        tracing::info!(
            elapsed_ms = t0.elapsed().as_millis() as u64,
            recent_start,
            "[compact-timing] after split old/recent"
        );
        if recent_start == 0 {
            return Ok(None);
        }

        // All checks passed — compression will proceed. Notify caller.

        let old = &conversation[..recent_start];
        let recent = &conversation[recent_start..];

        // Defensive: never start the old block on an orphaned tool result.
        if matches!(old.first(), Some(ChatMessage::Tool { .. })) {
            tracing::warn!("context compression skipped: old block starts with a tool result");
            return Ok(None);
        }

        // 3. Filter old summaries from both blocks.
        let old: Vec<&ChatMessage> = old.iter().filter(|m| !is_summary_message(m)).collect();
        let recent: Vec<&ChatMessage> = recent.iter().filter(|m| !is_summary_message(m)).collect();

        // 4. Extract original goal (first user message in old block).
        let original_goal = old
            .iter()
            .find_map(|m| match m {
                ChatMessage::User { content, .. } if !content.starts_with(SUMMARY_PREFIX) => {
                    Some(content.as_str())
                }
                _ => None,
            })
            .unwrap_or("(unknown goal)");
        let original_goal = truncate_str(original_goal, 400);

        // 5. Separate user messages (preserved verbatim) from assistant/tool
        //    messages (sent to summarizer).
        let preserved_user_msgs: Vec<&ChatMessage> = old
            .iter()
            .filter(|m| matches!(m, ChatMessage::User { .. }))
            .copied()
            .collect();
        let assistant_tool_msgs: Vec<&ChatMessage> = old
            .iter()
            .filter(|m| !matches!(m, ChatMessage::User { .. }))
            .copied()
            .collect();

        // Serialize only assistant/tool messages for the summarizer.
        let transcript = truncate_to_chars(&assistant_tool_msgs, self.config.max_transcript_chars);
        if transcript.trim().is_empty() && preserved_user_msgs.is_empty() {
            return Ok(None);
        }

        // All early-exit checks passed — compression will proceed.
        let msg_count = messages.len();
        if let Some(emit) = emit_fn {
            emit(CompressionEvent::Preparing {
                session_id,
                tokens_before: total_tokens,
                msg_count,
                trigger: trigger.clone(),
            });
            emit(CompressionEvent::Started {
                session_id,
                tokens_before: total_tokens,
                msg_count,
                trigger: trigger.clone(),
            });
        }

        const CACHE_PREFIX_CHARS: usize = 4096;
        let prefix: String = transcript.chars().take(CACHE_PREFIX_CHARS).collect();
        let key = (session_id, hash_str(&prefix));

        let cached = self.cache.lock().ok().and_then(|c| c.get(&key).cloned());

        // Reuse cached summary when the transcript hasn't changed, OR when it
        // has hit the max_transcript_chars cap (content is frozen at that point,
        // further growth only affects the tail which is truncated away).
        let cache_effective = matches!(cached, Some((cl, _)) if cl == transcript.len() || transcript.len() >= self.config.max_transcript_chars);

        let summary = if transcript.trim().is_empty() {
            // No assistant/tool content to summarize — skip LLM call.
            String::new()
        } else {
            match cached {
                Some((_, ref s)) if cache_effective => s.clone(),
                _ => {
                    // Notify caller that we're about to call the LLM.
                    if let Some(emit) = emit_fn {
                        emit(CompressionEvent::Progress {
                            session_id,
                            chars: 0,
                        });
                    }
                    tracing::info!(
                        elapsed_ms = t0.elapsed().as_millis() as u64,
                        "[compact-timing] before summarize() LLM call"
                    );
                    // summarize() reports cumulative char count via on_progress.
                    // Wrap it to emit CompressionEvent::Progress.
                    let s = if let Some(emit) = emit_fn {
                        let progress_fn = |chars: usize| {
                            emit(CompressionEvent::Progress { session_id, chars });
                        };
                        summarize(
                            self.client.as_ref(),
                            &transcript,
                            &original_goal,
                            self.config.max_summary_chars,
                            Some(&progress_fn),
                        )
                        .await
                    } else {
                        summarize(
                            self.client.as_ref(),
                            &transcript,
                            &original_goal,
                            self.config.max_summary_chars,
                            None,
                        )
                        .await
                    };
                    let s = match s {
                        Ok(s) => {
                            tracing::info!(
                                elapsed_ms = t0.elapsed().as_millis() as u64,
                                "[compact-timing] summarize() returned Ok"
                            );
                            s
                        }
                        Err(e) => {
                            tracing::warn!(
                                session_id,
                                "summarisation failed, falling back to dropping old block: {e}"
                            );
                            String::new()
                        }
                    };
                    if !s.is_empty()
                        && let Ok(mut cache) = self.cache.lock()
                    {
                        cache.insert(key, (transcript.len(), s.clone()));
                    }
                    s
                }
            }
        };

        // 6. Assemble: [system prompt] + [preserved user messages] + [summary] + [recent N].
        //    User messages are preserved verbatim (truncated to MAX_PRESERVED_USER_TOKENS)
        //    so the LLM always sees exact user instructions.
        let mut new_messages: Vec<ChatMessage> = system_msgs.to_vec();

        // Add preserved user messages, truncated from the start to fit.
        let truncated_user =
            truncate_user_messages(&preserved_user_msgs, Self::MAX_PRESERVED_USER_TOKENS);

        let trimmed = summary.trim();

        // 7. Guard: if the replacement (preserved users + summary) is larger
        //    than the original old block, discard the compression and keep the
        //    original messages.  This prevents negative compression on short
        //    conversations where the summary overhead exceeds the original
        //    assistant content.
        let old_block_chars: usize = old.iter().map(|m| message_content_len(m)).sum();
        let replacement_chars: usize = truncated_user
            .iter()
            .map(|m| message_content_len(m))
            .sum::<usize>()
            + if trimmed.is_empty() {
                0
            } else {
                SUMMARY_PREFIX.len() + 1 + trimmed.len()
            };
        if replacement_chars >= old_block_chars {
            tracing::info!(
                session_id,
                old_block_chars,
                replacement_chars,
                "[compact-timing] replacement larger than original, skipping compression"
            );
            return Ok(None);
        }

        new_messages.extend(truncated_user.into_iter().cloned());

        if !trimmed.is_empty() {
            new_messages.push(ChatMessage::user(format!("{SUMMARY_PREFIX}\n{trimmed}")));
        }
        new_messages.extend(recent.into_iter().cloned());

        // Record what happened.
        let compressed_tokens: usize = new_messages.iter().map(estimate_message_tokens).sum();
        tracing::info!(
            session_id,
            tokens_before = total_tokens,
            tokens_after = compressed_tokens,
            kept_recent = self.config.keep_recent_messages,
            summary_len = trimmed.len(),
            preserved_user_count = preserved_user_msgs.len(),
            old_block_chars,
            replacement_chars,
            cache_hit = cache_effective,
            elapsed_ms = t0.elapsed().as_millis() as u64,
            "[compact-timing] compression complete"
        );

        Ok(Some(new_messages))
    }

    // ── Cache management ─────────────────────────────────────────────────

    /// Clear all cached summaries.
    pub fn clear_cache(&self) {
        if let Ok(mut cache) = self.cache.lock() {
            cache.clear();
        }
    }

    // ── Session-level compression ──────────────────────────────────────────

    /// Read-compress-write-back: compress a session's messages in place.
    ///
    /// Returns `Ok(true)` if compression was applied (session was above the
    /// threshold), `Ok(false)` if the session was already below the threshold.
    ///
    /// Returns `Err` if the write-back validation fails (unexpected) or if
    /// the session was modified concurrently between read and write-back
    /// (TOCTOU guard).
    pub async fn compact_session(
        &self,
        runtime: &AgentRuntime,
        session_id: &SessionId,
        emit_fn: Option<std::sync::Arc<dyn Fn(agent_base::UserEvent) + Send + Sync>>,
    ) -> AgentResult<bool> {
        let sid = session_id.id;
        let trigger = CompressionTrigger::Manual;

        // Phase 1: read messages from the session (lock held briefly).
        let messages = runtime
            .with_session_mut(session_id, |session| session.chat_messages().to_vec())
            .await?;
        let msg_count_before = messages.len();
        let tokens_before: usize = messages.iter().map(estimate_message_tokens).sum();

        // Phase 2: compress (async LLM call, no session lock held).
        // Filter out old summary messages before compressing (same as middleware).
        let filtered: Vec<ChatMessage> = messages
            .iter()
            .filter(|m| !is_summary_message(m))
            .cloned()
            .collect();

        // Build emit_fn wrapper: CompressionEvent → into_user_event() → caller's emit_fn.
        let compressed = if let Some(ref ef) = emit_fn {
            let ef = ef.clone();
            self.compact(
                sid,
                &filtered,
                trigger.clone(),
                Some(&move |ev: CompressionEvent| {
                    ef(ev.into_user_event());
                }),
            )
            .await?
        } else {
            self.compact(sid, &filtered, trigger.clone(), None).await?
        };

        let compressed = match compressed {
            Some(msgs) => msgs,
            None => {
                // Below threshold — no-op, no events needed.
                return Ok(false);
            }
        };

        let tokens_after: usize = compressed.iter().map(estimate_message_tokens).sum();
        let msg_count_after = compressed.len();

        // Phase 3: write back (lock held briefly for set_chat_messages + validation).
        // TOCTOU guard: verify message count hasn't changed since Phase 1.
        runtime
            .with_session_mut(session_id, |session| {
                let msg_count_now = session.chat_messages().len();
                if msg_count_now != msg_count_before {
                    return Err(agent_base::AgentError::internal(format!(
                        "session modified concurrently ({} → {} messages), aborting write-back",
                        msg_count_before, msg_count_now
                    )));
                }
                session.set_chat_messages(compressed).map_err(|e| {
                    agent_base::AgentError::internal(format!(
                        "set_chat_messages validation failed: {e}"
                    ))
                })
            })
            .await??;

        // Emit Completed event.
        let reduction_pct = if tokens_before > 0 {
            ((tokens_before as f64 - tokens_after as f64) / tokens_before as f64 * 100.0).round()
                as i32
        } else {
            0
        };
        if let Some(ref f) = emit_fn {
            f(CompressionEvent::Completed {
                session_id: sid,
                tokens_before,
                tokens_after,
                reduction_pct,
                msg_count_before,
                msg_count_after,
                trigger,
            }
            .into_user_event());
        }

        Ok(true)
    }
}

// ── Helpers ──────────────────────────────────────────────────────────────────

/// Implement the agent-base `ContextCompaction` trait so the react loop
/// can trigger inline compaction without depending on agent-works directly.
#[async_trait::async_trait]
impl agent_base::ContextCompaction for ContextCompactor {
    async fn compact(
        &self,
        session_id: &SessionId,
        messages: &[ChatMessage],
    ) -> Option<agent_base::CompactionOutcome> {
        // Delegate to the existing compact() method with InlineCompaction trigger
        match self
            .compact(
                session_id.id,
                messages,
                CompressionTrigger::InlineCompaction,
                None,
            )
            .await
        {
            Ok(Some(result)) => {
                // This compactor always replaces the history wholesale, which
                // is the Reset kind for logging — the react loop must say
                // "compaction" here (issue #33).
                Some(agent_base::CompactionOutcome {
                    kind: agent_base::CompactionKind::Reset,
                    messages: result,
                })
            }
            Ok(None) => None,
            Err(e) => {
                tracing::warn!(
                    session_id = session_id.id,
                    error = %e,
                    "inline compaction failed"
                );
                None
            }
        }
    }

    fn token_count_hint(&self, _session_id: &SessionId) -> Option<usize> {
        // The react loop uses ContextWindowManager for estimation
        None
    }
}

#[cfg(test)]
mod tests;