From 80c0f83a68fa6e4c703aee51739f96bb545dd309 Mon Sep 17 00:00:00 2001 From: hermes Date: Thu, 1 Oct 2026 21:45:17 +0000 Subject: [PATCH] tokens: mask old large tool results in requests; compact inside a single long tool loop --- crates/hx-core/src/agent.rs | 61 +++++++++++++++---- crates/hx-core/src/lib.rs | 1 + crates/hx-core/src/mask.rs | 116 ++++++++++++++++++++++++++++++++++++ 3 files changed, 167 insertions(+), 11 deletions(-) create mode 100644 crates/hx-core/src/mask.rs diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index b71808f..60b2879 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -150,12 +150,14 @@ impl Agent { /// Summarize everything before the most recent user prompts, keeping at least `keep` messages verbatim. /// The session file keeps full history; the head moves to a new root. Returns false if nothing to cut. - /// ponytail: cuts only at user prompts, so one very long tool loop from a single prompt can't be compacted. + /// 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 async fn compact(&mut self, keep: usize) -> Result { let msgs = self.session.messages(); - let Some(cut) = (1..=msgs.len().saturating_sub(keep)) - .rev() - .find(|&i| is_prompt(&msgs[i])) + let range = 1..=msgs.len().saturating_sub(keep); + let prompt_cut = range.clone().rev().find(|&i| is_prompt(&msgs[i])); + let Some(cut) = + prompt_cut.or_else(|| range.rev().find(|&i| msgs[i].role == Role::Assistant)) else { return Ok(false); }; @@ -175,13 +177,13 @@ impl Agent { } } let summary = summary.ok_or(Error::Truncated)?; + let note = format!("[Summary of earlier conversation]\n{summary}\n[End of summary]"); let mut kept = msgs[cut..].to_vec(); - kept[0].content.insert( - 0, - ContentBlock::Text { - text: format!("[Summary of earlier conversation]\n{summary}\n[End of summary]"), - }, - ); + if prompt_cut.is_some() { + kept[0].content.insert(0, ContentBlock::Text { text: note }); + } else { + kept.insert(0, Message::user(note)); + } self.session.rebase(kept)?; self.last_ctx = None; Ok(true) @@ -229,7 +231,7 @@ impl Agent { let req = Request { model: self.model.clone(), system: self.system.clone(), - messages: self.session.messages(), + messages: crate::mask::mask_old_results(self.session.messages()), tools: self.tools.specs(), max_tokens: self.max_tokens, }; @@ -548,6 +550,43 @@ mod tests { assert_eq!(context_tokens(Some((1000, 5)), &m), estimate_tokens(&m)); } + #[tokio::test] + async fn compaction_inside_tool_loop() { + let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]); + let script = Arc::new(Script( + Mutex::new(vec![ + asst(vec![tu("1", "a")]), + asst(vec![tu("2", "b")]), + text("fin"), + text("SUMMARY"), + text("next"), + ]), + Mutex::new(vec![]), + )); + let dir = tempfile::tempdir().unwrap(); + let mut tools = Registry::default(); + tools.add(Echo); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let (mut a, _h) = Agent::new( + script.clone(), + tools, + Session::open(dir.path().join("s.jsonl")).unwrap(), + cx, + ); + a.run("go").await.unwrap(); // p, a1, r1, a2, r2, fin + assert!(a.compact(3).await.unwrap()); + let m = a.session.messages(); + // summary(user), a2, r2, fin -> alternates, tool_use still has its result + assert_eq!(m.len(), 4); + assert_eq!(m[0].role, Role::User); + assert!(m[0].text().contains("SUMMARY")); + assert_eq!(m[1].role, Role::Assistant); + assert!(matches!(m[2].content[0], ContentBlock::ToolResult { .. })); + } + #[tokio::test] async fn compaction() { let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]); diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index 16ab9b5..eb29ab5 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -5,6 +5,7 @@ pub mod command; pub mod context; pub mod ext; pub mod hook; +pub mod mask; pub mod session; pub mod stats; pub mod tool; diff --git a/crates/hx-core/src/mask.rs b/crates/hx-core/src/mask.rs new file mode 100644 index 0000000..8daf8e4 --- /dev/null +++ b/crates/hx-core/src/mask.rs @@ -0,0 +1,116 @@ +//! 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, so the request prefix +//! is byte-stable between steps and the prompt cache only breaks once per `STEP` assistant turns. + +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 masking boundary moves in jumps of this many assistant turns (one cache break per jump). +const STEP: usize = 8; +/// Results smaller than this stay (a stub would not save much). +const MIN_BYTES: usize = 4_000; + +pub fn mask_old_results(msgs: Vec) -> Vec { + let total = msgs.iter().filter(|m| m.role == Role::Assistant).count(); + let boundary = total.saturating_sub(KEEP) / STEP * STEP; + 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 v = mask_old_results(build(15)); + 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 v = mask_old_results(build(16)); + 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(build(16)), v); + // one more turn inside the same step does not change the masked prefix + let w = mask_old_results(build(17)); + assert_eq!(&w[..17], &v[..17]); + } +}