//! Observation masking: old, large tool results are replaced by a one-line stub in the request //! (the session file keeps the original). Pure function of the message list and a boundary, so the //! request prefix is byte-stable while the boundary stays put. Every move of the boundary rewrites the //! prompt cache from the first changed result on, so the agent moves it rarely (see `Agent`). use hx_ai::{ContentBlock, Message, Role}; use std::collections::HashMap; /// Results from the last `KEEP` assistant turns are never masked. const KEEP: usize = 8; /// The target boundary is a multiple of this many assistant turns. const STEP: usize = 8; /// Results smaller than this stay (a stub would not save much). const MIN_BYTES: usize = 4_000; /// Boundary (in assistant turns) the history would be masked up to right now. pub fn target_boundary(msgs: &[Message]) -> usize { let total = msgs.iter().filter(|m| m.role == Role::Assistant).count(); total.saturating_sub(KEEP) / STEP * STEP } /// Mask results of the first `boundary` assistant turns. 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; // assistant messages seen up to and including this one 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 }; // 15 turns: boundary = (15-8)/8*8 = 0 -> untouched 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); // 16 turns: boundary 8 -> first 8 big results masked, small one (i=1) kept, later ones kept 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); // turn 9 untouched // stable: same input -> same output (prefix bytes identical between calls) assert_eq!(mask_old_results(m, target_boundary(&build(16))), v); // one more turn inside the same step does not change the masked prefix let m = build(17); let w = mask_old_results(m.clone(), target_boundary(&m)); assert_eq!(&w[..17], &v[..17]); } }