Files
hx/crates/hx-core/src/compact.rs
T

194 lines
6.5 KiB
Rust

//! Context compaction: turn the old part of the conversation into a summary.
//!
//! Pure data in, data out. The agent owns the provider call and the session; this module decides
//! *what* to summarize and *what history remains* afterwards. *When* to compact is
//! [`ContextWindow`](crate::window::ContextWindow)'s call.
use hx_ai::{ContentBlock, Message, Request, Role};
const SUMMARY_PROMPT: &str = "Summarize the conversation below for a coding agent that will continue the work. \
Keep: the user's goals and constraints, decisions made, files touched and why, current state, open problems, next steps. \
Be concise and factual. Output only the summary.";
/// A decided compaction: which part of the history gets summarized and which stays verbatim.
pub struct Plan {
transcript: String,
kept: Vec<Message>,
/// Kept history starts at a user prompt, so the summary can be folded into it.
folds_into_prompt: bool,
}
/// Plan the compaction of `msgs`, keeping at least `keep` trailing messages verbatim.
/// `None` when there is nothing old enough to cut.
///
/// Cuts at the latest user prompt; inside one long tool loop (no prompt to cut at) it cuts before an
/// assistant message and the summary becomes its own leading user message.
pub fn plan(msgs: &[Message], keep: usize) -> Option<Plan> {
let range = 1..=msgs.len().saturating_sub(keep);
let prompt_cut = range.clone().rev().find(|&i| is_prompt(&msgs[i]));
let cut = prompt_cut.or_else(|| range.rev().find(|&i| msgs[i].role == Role::Assistant))?;
Some(Plan {
transcript: transcript(&msgs[..cut]),
kept: msgs[cut..].to_vec(),
folds_into_prompt: prompt_cut.is_some(),
})
}
impl Plan {
/// The summarization request to send to the model.
pub fn request(&self, model: &str) -> Request {
Request {
model: model.into(),
system: SUMMARY_PROMPT.into(),
messages: vec![Message::user(self.transcript.clone())],
tools: vec![],
max_tokens: 4096,
effort: hx_ai::Effort::Off,
}
}
/// The new history once the model has produced `summary`.
pub fn apply(self, summary: &str) -> Vec<Message> {
let note = format!("[Summary of earlier conversation]\n{summary}\n[End of summary]");
let mut kept = self.kept;
if self.folds_into_prompt {
kept[0].content.insert(0, ContentBlock::Text { text: note });
} else {
kept.insert(0, Message::user(note));
}
kept
}
}
fn is_prompt(m: &Message) -> bool {
m.role == Role::User
&& !m
.content
.iter()
.any(|b| matches!(b, ContentBlock::ToolResult { .. }))
}
fn transcript(msgs: &[Message]) -> String {
let cut = |s: &str| -> String {
if s.len() > 800 {
format!("{}…", s.chars().take(800).collect::<String>())
} else {
s.to_string()
}
};
let mut t = String::new();
for m in msgs {
let who = if m.role == Role::User {
"USER"
} else {
"ASSISTANT"
};
for b in &m.content {
match b {
ContentBlock::Text { text } => t.push_str(&format!("{who}: {text}\n")),
ContentBlock::ToolUse { name, input, .. } => {
t.push_str(&format!("TOOL CALL {name}: {}\n", cut(&input.to_string())))
}
ContentBlock::ToolResult {
content, is_error, ..
} => t.push_str(&format!(
"TOOL RESULT{}: {}\n",
if *is_error { " (error)" } else { "" },
cut(content)
)),
_ => {}
}
}
}
t
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn text(role: Role, t: &str) -> Message {
Message {
role,
content: vec![ContentBlock::Text { text: t.into() }],
}
}
fn call(id: &str) -> Message {
Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolUse {
id: id.into(),
name: "echo".into(),
input: json!({}),
}],
}
}
fn result(id: &str) -> Message {
Message {
role: Role::User,
content: vec![ContentBlock::ToolResult {
tool_use_id: id.into(),
content: "ok".into(),
is_error: false,
}],
}
}
#[test]
fn nothing_old_enough_to_cut() {
let m = vec![text(Role::User, "p1"), text(Role::Assistant, "r1")];
assert!(plan(&m, 10).is_none());
assert!(plan(&m, 2).is_none(), "the first message is never cut");
}
#[test]
fn cuts_at_latest_prompt_and_folds_summary_into_it() {
let m = vec![
text(Role::User, "p1"),
text(Role::Assistant, "r1"),
text(Role::User, "p2"),
text(Role::Assistant, "r2"),
];
let p = plan(&m, 2).unwrap();
let req = p.request("m");
let t = req.messages[0].text();
assert!(t.contains("USER: p1") && t.contains("ASSISTANT: r1") && !t.contains("p2"));
assert_eq!(req.model, "m");
let h = p.apply("SUM");
assert_eq!(h.len(), 2);
assert!(h[0].text().contains("SUM") && h[0].text().ends_with("p2"));
}
#[test]
fn inside_a_tool_loop_the_summary_is_its_own_message() {
// p, a1, r1, a2, r2, fin: no prompt in the cuttable range
let m = vec![
text(Role::User, "go"),
call("1"),
result("1"),
call("2"),
result("2"),
text(Role::Assistant, "fin"),
];
let h = plan(&m, 3).unwrap().apply("SUM");
// summary(user), a2, r2, fin: roles alternate and the tool_use still has its result
assert_eq!(h.len(), 4);
assert_eq!(h[0].role, Role::User);
assert!(h[0].text().contains("SUM"));
assert_eq!(h[1].role, Role::Assistant);
assert!(matches!(h[2].content[0], ContentBlock::ToolResult { .. }));
}
#[test]
fn transcript_truncates_long_tool_output() {
let mut r = result("1");
if let ContentBlock::ToolResult { content, .. } = &mut r.content[0] {
*content = "z".repeat(2000);
}
let t = transcript(&[call("1"), r]);
assert!(t.contains("TOOL CALL echo") && t.contains("TOOL RESULT"));
assert!(t.len() < 1000 && t.contains('…'));
}
}