1use crate::llm::{Completion, CompletionResponse, LLMClientDyn, TokenUsage, throttled_completion};
2use eyre::Result;
3use rig_core::completion::message::{ToolChoice, ToolResultContent, UserContent};
4use rig_core::completion::{AssistantContent, Message};
5use std::sync::Arc;
6use tokio::sync::Semaphore;
7use tracing::{info, warn};
8
9const COMPACTION_MAX_OUTPUT_TOKENS: u64 = 8_192;
10const COMPACTION_MAX_CORRECTIONS: usize = 2;
11const CONTINUE_MESSAGE: &str = "Continue from where you left off.";
12const SUMMARY_TAG: &str = "summary";
13const COMPACTION_SUMMARY_INSTRUCTIONS: &str = "Focus strictly on information vital for code analysis. Omit conversational filler, raw search/tool outputs, and large blocks of code.\n\
14When constructing the summary, you MUST use the following exact markdown structure inside the tags:\n\
15<summary>\n\
16## Review Goal\n\
17[1-2 sentences on the core objective of this code exploration/review. What are we looking for?]\n\
18## Key Findings & Discoveries\n\
19- [List major architectural insights, design patterns discovered, or critical issues/bugs identified so far.]\n\
20- [Keep these concise but highly technical.]\n\
21## Codebase Map (Relevant Files)\n\
22- [List the critical files and directories that have been identified as relevant to the goal.]\n\
23- [Briefly note why they are relevant (e.g., `src/auth/token.rs`: handles JWT validation and is where the bug likely resides).]\n\
24## Explored Territory\n\
25- [Briefly list what areas, files, or concepts have already been thoroughly investigated so we do not repeat work.]\n\
26## Last Action & Immediate Context\n\
27- [Describe the most recent tool calls and their results. What was the agent trying to find or verify? What did it just learn?]\n\
28## Open Questions & Next Steps\n\
29- [List any unresolved anomalies, pending review items, constraints to remember, or specific files that still need to be examined.]\n\
30</summary>\n\
31Return EXACTLY ONE tagged block starting with <summary> and ending with </summary>. Do not include any text, pleasantries, or explanations outside of these tags.";
32const MISSING_SUMMARY_CORRECTION: &str = "Your response is missing the required <summary>...</summary> block. Reply with ONLY the tagged summary block and nothing else outside the tags.";
33const WRAP_SUMMARY_CORRECTION: &str = "Wrap your entire response in <summary>...</summary> tags and output nothing outside them.";
34
35pub struct CompactionOutcome {
36 pub usage: TokenUsage,
37 pub summary: String,
38 pub trigger_usage: TokenUsage,
39}
40
41enum CompactionInput<'a> {
42 Messages(&'a [Message]),
43 Transcript(&'a str),
44}
45
46enum CorrectionMode {
47 MissingSummary,
48 WrapSummary,
49}
50
51#[allow(clippy::too_many_arguments)]
53pub async fn compact_history(
54 semaphore: &Semaphore,
55 client: Arc<dyn LLMClientDyn>,
56 model: &str,
57 system_prompt: &str,
58 history: &mut Vec<Message>,
59 prompt: &mut Message,
60 turn: usize,
61 usage: TokenUsage,
62) -> Result<Option<CompactionOutcome>> {
63 if history.is_empty() {
64 return Ok(None);
65 }
66
67 let outcome =
68 summarize_history(semaphore, client, model, system_prompt, history, turn, usage).await?;
69 let continue_msg = Message::user(CONTINUE_MESSAGE.to_string());
70 *history = vec![
71 Message::user(format!(
72 "compacted conversation summary before turn {turn}:\n\n{}",
73 outcome.summary
74 )),
75 continue_msg.clone(),
76 ];
77 *prompt = continue_msg;
78 info!(
79 turn,
80 trigger_input_tokens = outcome.trigger_usage.input_tokens,
81 trigger_output_tokens = outcome.trigger_usage.output_tokens,
82 trigger_total_tokens = outcome.trigger_usage.total_tokens,
83 input_tokens = outcome.usage.input_tokens,
84 output_tokens = outcome.usage.output_tokens,
85 total_tokens = outcome.usage.total_tokens,
86 "compaction complete"
87 );
88 Ok(Some(outcome))
89}
90
91async fn summarize_history(
92 semaphore: &Semaphore,
93 client: Arc<dyn LLMClientDyn>,
94 model: &str,
95 system_prompt: &str,
96 thread: &[Message],
97 turn: usize,
98 usage: TokenUsage,
99) -> Result<CompactionOutcome> {
100 match run_compaction(
101 semaphore,
102 &client,
103 model,
104 system_prompt,
105 CompactionInput::Messages(thread),
106 turn,
107 usage,
108 )
109 .await
110 {
111 Ok(outcome) => Ok(outcome),
112 Err(err) => {
113 warn!("in-context compaction failed ({err}), retrying with rendered transcript");
114 let transcript = render_history_as_text(thread);
115 let outcome = run_compaction(
116 semaphore,
117 &client,
118 model,
119 system_prompt,
120 CompactionInput::Transcript(&transcript),
121 turn,
122 usage,
123 )
124 .await?;
125 info!("rendered transcript compaction succeeded");
126 Ok(outcome)
127 }
128 }
129}
130
131async fn run_compaction(
132 semaphore: &Semaphore,
133 client: &Arc<dyn LLMClientDyn>,
134 model: &str,
135 system_prompt: &str,
136 input: CompactionInput<'_>,
137 turn: usize,
138 usage: TokenUsage,
139) -> Result<CompactionOutcome> {
140 let prompt = build_compaction_prompt(&input, turn, usage);
141 let response = throttled_completion(
142 semaphore,
143 client,
144 compaction_completion(
145 model,
146 system_prompt,
147 history_for_initial_request(&input),
148 Message::user(prompt.clone()),
149 ),
150 )
151 .await?;
152
153 match extract_summary(&response) {
154 Some(summary) => Ok(CompactionOutcome {
155 usage: response.usage,
156 summary,
157 trigger_usage: usage,
158 }),
159 None => {
160 let attempt = InitialAttempt {
161 prompt,
162 response,
163 correction_mode: correction_mode(&input),
164 };
165 run_corrections(semaphore, client, model, system_prompt, &input, usage, attempt).await
166 }
167 }
168}
169
170struct InitialAttempt {
171 prompt: String,
172 response: CompletionResponse,
173 correction_mode: CorrectionMode,
174}
175
176async fn run_corrections(
177 semaphore: &Semaphore,
178 client: &Arc<dyn LLMClientDyn>,
179 model: &str,
180 system_prompt: &str,
181 input: &CompactionInput<'_>,
182 trigger_usage: TokenUsage,
183 attempt: InitialAttempt,
184) -> Result<CompactionOutcome> {
185 let InitialAttempt {
186 prompt: original_prompt,
187 response: initial_response,
188 correction_mode,
189 } = attempt;
190 let correction = correction_prompt(&correction_mode);
191 let mut history = correction_history(input, original_prompt, initial_response.message());
192 let mut previous = initial_response;
193
194 for _ in 0..COMPACTION_MAX_CORRECTIONS {
195 let next = throttled_completion(
196 semaphore,
197 client,
198 compaction_completion(
199 model,
200 system_prompt,
201 history.clone(),
202 Message::user(correction.to_string()),
203 ),
204 )
205 .await?;
206 match extract_summary(&next) {
207 Some(summary) => {
208 return Ok(CompactionOutcome {
209 usage: next.usage,
210 summary,
211 trigger_usage,
212 });
213 }
214 None => {
215 history.push(next.message());
216 history.push(Message::user(correction.to_string()));
217 previous = next;
218 }
219 }
220 }
221
222 match correction_mode {
223 CorrectionMode::MissingSummary => Err(eyre::eyre!(
224 "compaction output missing <summary> block after {COMPACTION_MAX_CORRECTIONS} corrections: {}",
225 previous.text()
226 )),
227 CorrectionMode::WrapSummary => Err(eyre::eyre!(
228 "rendered compaction also failed to produce <summary> block: {}",
229 previous.text()
230 )),
231 }
232}
233
234fn compaction_completion(
235 model: &str,
236 system_prompt: &str,
237 history: Vec<Message>,
238 prompt: Message,
239) -> Completion {
240 Completion {
241 model: model.to_string(),
242 prompt,
243 preamble: Some(system_prompt.to_string()),
244 history,
245 tools: Vec::new(),
246 tool_choice: Some(ToolChoice::None),
247 max_tokens: Some(COMPACTION_MAX_OUTPUT_TOKENS),
248 additional_params: None,
249 }
250}
251
252fn history_for_initial_request(input: &CompactionInput<'_>) -> Vec<Message> {
253 match input {
254 CompactionInput::Messages(thread) => thread.to_vec(),
255 CompactionInput::Transcript(_) => Vec::new(),
256 }
257}
258
259fn correction_history(
260 input: &CompactionInput<'_>,
261 original_prompt: String,
262 assistant_message: Message,
263) -> Vec<Message> {
264 let mut history = history_for_initial_request(input);
265 history.push(Message::user(original_prompt));
266 history.push(assistant_message);
267 history
268}
269
270fn correction_mode(input: &CompactionInput<'_>) -> CorrectionMode {
271 match input {
272 CompactionInput::Messages(_) => CorrectionMode::MissingSummary,
273 CompactionInput::Transcript(_) => CorrectionMode::WrapSummary,
274 }
275}
276
277fn correction_prompt(mode: &CorrectionMode) -> &'static str {
278 match mode {
279 CorrectionMode::MissingSummary => MISSING_SUMMARY_CORRECTION,
280 CorrectionMode::WrapSummary => WRAP_SUMMARY_CORRECTION,
281 }
282}
283
284fn build_compaction_prompt(input: &CompactionInput<'_>, turn: usize, usage: TokenUsage) -> String {
285 let intro = match input {
286 CompactionInput::Messages(_) => {
287 "This thread is getting out of hand and needs to be compacted. Stop previous work and summarize the conversation so far.".to_string()
288 }
289 CompactionInput::Transcript(transcript) => format!(
290 "Summarize the following code exploration and review session transcript so the agent can continue seamlessly from where it left off.\n\n<transcript>\n{transcript}\n</transcript>"
291 ),
292 };
293
294 format!(
295 "{intro}\n\n{COMPACTION_SUMMARY_INSTRUCTIONS}\n\
296This compaction is happening before turn {turn}. Context size at compaction: {} input, {} output, {} total tokens.",
297 usage.input_tokens, usage.output_tokens, usage.total_tokens
298 )
299}
300
301fn extract_summary(response: &CompletionResponse) -> Option<String> {
302 extract_tag(&response.text(), SUMMARY_TAG)
303}
304
305fn render_history_as_text(history: &[Message]) -> String {
306 let mut parts = Vec::new();
307 for msg in history {
308 match msg {
309 Message::User { content } => {
310 for item in content.iter() {
311 match item {
312 UserContent::Text(t) if !t.text.is_empty() => {
313 parts.push(format!("[user]: {}", t.text));
314 }
315 UserContent::ToolResult(tr) => {
316 let result = tr
317 .content
318 .iter()
319 .filter_map(|content| match content {
320 ToolResultContent::Text(t) => Some(t.text.as_str()),
321 _ => None,
322 })
323 .collect::<Vec<_>>()
324 .join("");
325 parts.push(format!("[tool result {}]: {}", tr.id, result));
326 }
327 _ => {}
328 }
329 }
330 }
331 Message::Assistant { content, .. } => {
332 for item in content.iter() {
333 match item {
334 AssistantContent::Text(t) if !t.text().is_empty() => {
335 parts.push(format!("[assistant]: {}", t.text()));
336 }
337 AssistantContent::ToolCall(tc) => {
338 parts.push(format!(
339 "[called: {}({})]",
340 tc.function.name, tc.function.arguments
341 ));
342 }
343 _ => {}
344 }
345 }
346 }
347 Message::System { .. } => {}
348 }
349 }
350 parts.join("\n\n")
351}
352
353fn extract_tag(text: &str, tag: &str) -> Option<String> {
354 let start_tag = format!("<{tag}>");
355 let end_tag = format!("</{tag}>");
356 let start = text.find(&start_tag)? + start_tag.len();
357 let end = start + text[start..].find(&end_tag)?;
358 if end < start {
359 return None;
360 }
361 let content = text[start..end].trim();
362 if content.is_empty() {
363 None
364 } else {
365 Some(content.to_string())
366 }
367}