Skip to main content

nitpicker_agent/
compact.rs

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