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."; pub struct Plan { transcript: String, kept: Vec, folds_into_prompt: bool, } pub fn plan(msgs: &[Message], keep: usize) -> Option { 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 { 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, } } pub fn apply(self, summary: &str) -> Vec { 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::()) } 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() { 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"); 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('…')); } }