use hx_ai::{ContentBlock, Message, Role}; use std::collections::HashMap; const KEEP: usize = 8; const STEP: usize = 8; const MIN_BYTES: usize = 4_000; pub fn target_boundary(msgs: &[Message]) -> usize { let total = msgs.iter().filter(|m| m.role == Role::Assistant).count(); total.saturating_sub(KEEP) / STEP * STEP } pub fn mask_old_results(msgs: Vec, boundary: usize) -> Vec { if boundary == 0 { return msgs; } let mut calls: HashMap = HashMap::new(); let mut turn = 0; msgs.into_iter() .map(|mut m| { if m.role == Role::Assistant { turn += 1; for b in &m.content { if let ContentBlock::ToolUse { id, name, input } = b { let a: String = input.to_string().chars().take(80).collect(); calls.insert(id.clone(), format!("{name} {a}")); } } } else if turn <= boundary { for b in &mut m.content { if let ContentBlock::ToolResult { tool_use_id, content, .. } = b && content.len() >= MIN_BYTES { let what = calls.get(tool_use_id).map_or("tool", |s| s.as_str()); *content = format!( "[elided old tool result: {what} ({} bytes); run the tool again if you need it]", content.len() ); } } } m }) .collect() } #[cfg(test)] mod tests { use super::*; fn pair(i: usize, size: usize) -> [Message; 2] { [ Message { role: Role::Assistant, content: vec![ContentBlock::ToolUse { id: format!("t{i}"), name: "bash".into(), input: serde_json::json!({"command": format!("c{i}")}), }], }, Message { role: Role::User, content: vec![ContentBlock::ToolResult { tool_use_id: format!("t{i}"), content: "x".repeat(size), is_error: false, }], }, ] } fn result(m: &Message) -> &str { match &m.content[0] { ContentBlock::ToolResult { content, .. } => content, _ => panic!(), } } #[test] fn masks_old_big_only_in_steps() { let build = |n: usize| -> Vec { let mut v = vec![Message::user("go")]; for i in 0..n { v.extend(pair(i, if i == 1 { 100 } else { 5000 })); } v }; let m = build(15); let v = mask_old_results(m.clone(), target_boundary(&m)); assert!(v.iter().all(|m| m.text().is_empty() || m.text() == "go")); assert_eq!(result(&v[2]).len(), 5000); let m = build(16); let v = mask_old_results(m.clone(), target_boundary(&m)); assert!( result(&v[2]).starts_with("[elided old tool result: bash"), "{}", result(&v[2]) ); assert!(result(&v[2]).contains("c0")); assert_eq!(result(&v[4]).len(), 100); assert_eq!(result(&v[2 * 8 + 2]).len(), 5000); assert_eq!(mask_old_results(m, target_boundary(&build(16))), v); let m = build(17); let w = mask_old_results(m.clone(), target_boundary(&m)); assert_eq!(&w[..17], &v[..17]); } }