1use std::path::Path;
11
12use anyhow::Result;
13
14use crate::compaction::memory_envelope::{
15 MemoryEnvelopePersistence, MemoryEnvelopePlacement, SessionMemoryEnvelopeUpdate,
16 dedup_repeated_file_reads_for_local_compaction, effective_compaction_threshold_with_reserve,
17 effective_context_budget, persist_memory_envelope_async_with_update, strip_existing_memory_envelope,
18};
19use crate::compaction::two_pass::fingerprint_prefix;
20use crate::compaction::{
21 CompactionConfig, CompactionParentContext, CompactionStrategy, ManualCompactionOptions, SUPPRESS_NONE,
22 build_local_compacted_history, build_summary_prompt, classify_suppress_reason,
23 compact_history_manual_with_parent_context, compacted_history_shrinks, manual_compaction_strategy,
24};
25use crate::exec::events::CompactionMode;
26use crate::llm::{
27 collect_single_response,
28 provider::{LLMProvider, LLMRequest, Message, ToolChoice},
29};
30use vtcode_config::loader::VTCodeConfig;
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct AutoCompactionOutcome {
35 pub original_len: usize,
36 pub compacted_len: usize,
37 pub mode: CompactionMode,
38 pub history_artifact_path: Option<String>,
39 pub envelope: Option<crate::compaction::memory_envelope::SessionMemoryEnvelope>,
42}
43
44pub struct AutoCompactionInput<'a> {
46 pub provider: &'a dyn LLMProvider,
47 pub model: &'a str,
48 pub session_id: &'a str,
49 pub workspace_root: &'a Path,
50 pub vt_cfg: Option<&'a VTCodeConfig>,
51 pub current_token_usage: usize,
53 pub reserved_output_tokens: usize,
55 pub touched_files: &'a [String],
57 pub engine_cfg: CompactionConfig,
59 pub manual_options: ManualCompactionOptions,
61 pub placement: MemoryEnvelopePlacement,
63 pub prefire: Option<&'a crate::compaction::PrefireState>,
65 pub auto_compact_suppressed: &'a mut u8,
69 pub force_compaction: bool,
73 pub steering_update: Option<&'a SessionMemoryEnvelopeUpdate>,
75 pub parent_context: Option<CompactionParentContext>,
80}
81
82impl AutoCompactionInput<'_> {
83 pub(crate) fn should_compact(&self) -> bool {
85 if !self.vt_cfg.is_some_and(|cfg| cfg.agent.harness.auto_compaction_enabled)
86 || *self.auto_compact_suppressed != SUPPRESS_NONE
87 {
88 return false;
89 }
90 let Some(threshold) = effective_compaction_threshold_with_reserve(
91 self.vt_cfg,
92 self.provider,
93 self.model,
94 self.reserved_output_tokens,
95 ) else {
96 return false;
97 };
98 let window = effective_context_budget(self.vt_cfg, self.provider, self.model);
99 let threshold = crate::compaction::CompactionRoutePolicy::resolve(self.provider.name(), self.model)
100 .apply_threshold_cap(threshold, window);
101 self.force_compaction || self.current_token_usage >= threshold
102 }
103}
104
105pub async fn auto_compact_messages(
113 input: AutoCompactionInput<'_>,
114 history: &mut Vec<Message>,
115) -> Result<Option<AutoCompactionOutcome>> {
116 if !input.should_compact() {
117 return Ok(None);
118 }
119 let AutoCompactionInput {
120 provider,
121 model,
122 session_id,
123 workspace_root,
124 vt_cfg,
125 touched_files,
126 engine_cfg,
127 manual_options,
128 placement,
129 prefire,
130 auto_compact_suppressed,
131 force_compaction,
132 steering_update,
133 parent_context,
134 ..
135 } = input;
136
137 let context_budget = match effective_context_budget(vt_cfg, provider, model) {
141 0 => None,
142 budget => Some(budget),
143 };
144 let mut compaction_input = history.clone();
145 strip_existing_memory_envelope(&mut compaction_input);
146 let original_history = compaction_input.clone();
147
148 let compaction_result: Result<Option<AutoCompactionOutcome>> = async {
149 if let Some(prefire_state) = prefire {
151 if let Some(mut compacted) = try_two_pass_with_prefire(
152 prefire_state,
153 provider,
154 model,
155 &original_history,
156 &engine_cfg,
157 context_budget,
158 parent_context.as_ref(),
159 )
160 .await?
161 {
162 let original_len = original_history.len();
163 let envelope = persist_memory_envelope_async_with_update(
164 workspace_root,
165 session_id,
166 vt_cfg,
167 &original_history,
168 touched_files,
169 &mut compacted,
170 MemoryEnvelopePersistence::PersistToDisk,
171 placement,
172 None,
173 steering_update,
174 )
175 .await?;
176 compacted =
177 crate::compaction::bound_compacted_history_to_context(compacted, provider, model, context_budget);
178 let history_artifact_path = envelope.as_ref().and_then(|item| item.history_artifact_path.clone());
179 let compacted_len = compacted.len();
180 *history = compacted;
181 return Ok(Some(AutoCompactionOutcome {
182 original_len,
183 compacted_len,
184 mode: CompactionMode::Local,
185 history_artifact_path,
186 envelope,
187 }));
188 }
189 }
190
191 let strategy = manual_compaction_strategy(provider, model);
196 let compaction_history = if matches!(strategy, CompactionStrategy::Local) {
197 dedup_repeated_file_reads_for_local_compaction(&compaction_input)
198 } else {
199 compaction_input.clone()
200 };
201
202 if !force_compaction
204 && !engine_cfg.always_summarize
205 && compaction_history.len() <= engine_cfg.keep_last_messages
206 {
207 return Ok(None);
208 }
209
210 let (mut compacted, mode) = compact_history_manual_with_parent_context(
211 provider,
212 model,
213 &compaction_history,
214 &engine_cfg,
215 &manual_options,
216 context_budget,
217 parent_context.as_ref(),
218 )
219 .await?;
220
221 if compacted == compaction_history {
222 return Ok(None);
223 }
224
225 if !compacted_history_shrinks(original_history.len(), compacted.len(), mode) {
229 return Ok(None);
230 }
231
232 let original_len = original_history.len();
233 let mut envelope_history = if mode == CompactionMode::Provider {
238 compacted.clone()
239 } else {
240 std::mem::take(&mut compacted)
241 };
242 let envelope = persist_memory_envelope_async_with_update(
243 workspace_root,
244 session_id,
245 vt_cfg,
246 &original_history,
247 touched_files,
248 &mut envelope_history,
249 MemoryEnvelopePersistence::PersistToDisk,
250 placement,
251 None,
252 steering_update,
253 )
254 .await?;
255 if mode == CompactionMode::Local {
256 compacted = envelope_history;
257 compacted =
258 crate::compaction::bound_compacted_history_to_context(compacted, provider, model, context_budget);
259 }
260 let history_artifact_path = envelope.as_ref().and_then(|item| item.history_artifact_path.clone());
261 let compacted_len = compacted.len();
262 *history = compacted;
263 Ok(Some(AutoCompactionOutcome {
264 original_len,
265 compacted_len,
266 mode,
267 history_artifact_path,
268 envelope,
269 }))
270 }
271 .await;
272
273 match &compaction_result {
274 Ok(Some(_)) => {
275 *auto_compact_suppressed = SUPPRESS_NONE;
276 }
277 Ok(None) => {}
278 Err(error) => {
279 let reason = classify_suppress_reason(&error.root_cause().to_string());
280 let new_state = reason.suppress_state();
281 if *auto_compact_suppressed == SUPPRESS_NONE {
284 *auto_compact_suppressed = new_state;
285 }
286 }
287 }
288
289 compaction_result
290}
291
292async fn try_two_pass_with_prefire(
302 prefire: &crate::compaction::PrefireState,
303 provider: &dyn LLMProvider,
304 model: &str,
305 history: &[Message],
306 config: &CompactionConfig,
307 context_budget: Option<usize>,
308 parent: Option<&CompactionParentContext>,
309) -> Result<Option<Vec<Message>>> {
310 let cache = match prefire.take() {
311 Some(cache) => cache,
312 None => return Ok(None),
313 };
314
315 if cache.prefix_len == 0 || cache.prefix_len > history.len() {
316 return Ok(None);
317 }
318
319 if cache.model_slug != model {
320 return Ok(None);
321 }
322
323 let prefix = &history[..cache.prefix_len];
324 if fingerprint_prefix(prefix) != cache.fingerprint {
325 return Ok(None);
326 }
327
328 let tail = &history[cache.prefix_len..];
329 let prompt = build_summary_prompt(tail, &config.summary_prompt);
330 let pass2_history = crate::compaction::two_pass::build_two_pass_pass2_history(prefix, tail, &cache.note1, &prompt);
331
332 let request = LLMRequest {
333 messages: std::sync::Arc::new(pass2_history),
334 model: model.to_string(),
335 system_prompt: parent.and_then(|parent| parent.system_prompt.clone()),
336 tools: parent.and_then(|parent| parent.tools.clone()).filter(|tools| !tools.is_empty()),
337 tool_choice: Some(ToolChoice::none()),
338 ..Default::default()
339 };
340
341 let response = collect_single_response(provider, request).await?;
342 let note2 = response.content.unwrap_or_default().trim().to_string();
343
344 if note2.trim().is_empty() {
345 return Ok(None);
346 }
347
348 let effective_config =
349 crate::compaction::context_bounded_compaction_config(provider, model, history, config, context_budget);
350 let tail_target = crate::compaction::route_tail_target_tokens(provider, model, context_budget);
351 let compacted = build_local_compacted_history(
352 history,
353 ¬e2,
354 effective_config.retained_user_message_tokens,
355 effective_config.retained_user_messages,
356 true,
357 tail_target,
358 );
359
360 let compacted = crate::compaction::bound_compacted_history_to_context(compacted, provider, model, context_budget);
361 if !compacted_history_shrinks(history.len(), compacted.len(), CompactionMode::Local) {
365 return Ok(None);
366 }
367
368 Ok(Some(compacted))
369}
370
371#[cfg(test)]
372mod tests;