Deepen context-window management into ContextWindow #116

Merged
hermes merged 3 commits from context-window into main 2026-10-02 15:06:19 +00:00
6 changed files with 269 additions and 130 deletions

No files matched your search

+30 -71
View File
@@ -1,9 +1,10 @@
//! Agent loop: stream -> tool calls -> hooks -> results -> repeat.
use crate::compact::{self, ContextMeter};
use crate::compact;
use crate::hook::{Bus, Event};
use crate::session::Session;
use crate::tool::{Registry, ToolCtx};
use crate::window::ContextWindow;
use futures::StreamExt;
use hx_ai::{ContentBlock, Message, Provider, Request, Role, StopReason, StreamEvent, Usage};
use std::sync::Arc;
@@ -23,9 +24,6 @@ pub enum Error {
MaxTurns(u32),
}
/// Context size above which old tool results start to be masked, at most.
const MASK_FROM_MAX: usize = 60_000;
pub struct Agent {
provider: Arc<dyn Provider>,
pub tools: Registry,
@@ -37,12 +35,7 @@ pub struct Agent {
max_turns: u32,
usage: Usage,
session: Session,
/// Auto-compact when the estimated context exceeds this many tokens.
compact_at: usize,
ctx: ContextMeter,
/// Assistant turns whose big tool results are masked in requests. Only moves forward, and only
/// once the context is big enough that the saving beats rewriting the prompt cache.
mask_boundary: usize,
window: ContextWindow,
abort: watch::Receiver<bool>,
abort_tx: Arc<watch::Sender<bool>>,
}
@@ -81,9 +74,7 @@ impl Agent {
max_turns: 200,
usage: Usage::default(),
session,
compact_at: 150_000,
ctx: ContextMeter::default(),
mask_boundary: 0,
window: ContextWindow::new(150_000),
abort: rx,
abort_tx: tx.clone(),
};
@@ -132,17 +123,24 @@ impl Agent {
}
pub fn compact_at(&self) -> usize {
self.compact_at
self.window.compact_at()
}
/// Size of the current context in tokens: the provider's last reading plus an estimate of
/// what came after. The number that triggers auto-compaction.
pub fn context_tokens(&self) -> usize {
self.window.tokens(&self.session.messages())
}
/// Auto-compact once the context exceeds `n` tokens.
pub fn set_compact_at(&mut self, n: usize) {
self.compact_at = n;
self.window.set_compact_at(n);
}
/// Derive the compaction threshold from the model's context window (leaving room for a reply).
pub fn fit_window(&mut self, window: u64) {
self.compact_at = hx_ai::models::compact_threshold(window, self.max_tokens);
self.window
.set_compact_at(hx_ai::models::compact_threshold(window, self.max_tokens));
}
/// Switch provider and model together; a model id is only meaningful to its provider.
@@ -154,14 +152,14 @@ impl Agent {
/// Continue in another session (resume or new). Drops token usage measured on the old history.
pub fn replace_session(&mut self, session: Session) {
self.session = session;
self.reset_ctx();
self.window.reset();
}
/// Move the session head to entry `id`. False (and no change) if there is no such entry.
pub fn fork(&mut self, id: u64) -> bool {
let ok = self.session.fork(id);
if ok {
self.reset_ctx();
self.window.reset();
}
ok
}
@@ -169,7 +167,7 @@ impl Agent {
/// Start over: empty the conversation, keeping the session file's history.
pub fn clear(&mut self) -> Result<(), Error> {
self.session.rebase(vec![])?;
self.reset_ctx();
self.window.reset();
Ok(())
}
@@ -191,33 +189,19 @@ impl Agent {
}
let summary = summary.ok_or(Error::Truncated)?;
self.session.rebase(plan.apply(&summary))?;
self.reset_ctx();
self.window.reset();
Ok(true)
}
/// The history was replaced or rewritten: readings and the masking boundary no longer apply.
fn reset_ctx(&mut self) {
self.ctx.reset();
self.mask_boundary = 0;
}
/// Masking starts once the context passes a third of the compaction threshold, but never later
/// than `MASK_FROM_MAX` tokens: with a 1M window a third is ~300k, far beyond where old results
/// already cost more to resend than one cache rewrite.
// ponytail: 60k comes from two real sessions (contexts of 72k and 105k); tune with `hx stats`.
fn mask_from(&self) -> usize {
(self.compact_at / 3).min(MASK_FROM_MAX)
}
fn push(&mut self, m: Message) -> Result<(), Error> {
self.push_with(m, None)
self.session.append(m)?;
Ok(())
}
fn push_with(&mut self, m: Message, usage: Option<Usage>) -> Result<(), Error> {
let assistant = m.role == Role::Assistant;
let by = assistant.then(|| self.model.clone());
let mask = assistant.then_some(self.mask_boundary);
self.session.append_masked(m, by, usage, mask)?;
/// Append the assistant reply with the model, usage and masking boundary of its request.
fn push_reply(&mut self, m: Message, usage: Usage, mask: usize) -> Result<(), Error> {
let by = Some(self.model.clone());
self.session.append_masked(m, by, Some(usage), Some(mask))?;
Ok(())
}
@@ -244,21 +228,15 @@ impl Agent {
if self.aborted() {
return Err(Error::Aborted);
}
if self.ctx.tokens(&self.session.messages()) > self.compact_at
&& self.compact(6).await?
{
if self.window.should_compact(&self.session.messages()) && self.compact(6).await? {
self.emit(Event::Info("context compacted".into())).await;
}
self.emit(Event::TurnStart).await;
let msgs = self.session.messages();
let target = crate::mask::target_boundary(&msgs);
if target > self.mask_boundary && self.ctx.tokens(&msgs) > self.mask_from() {
self.mask_boundary = target;
}
let view = self.window.view(self.session.messages());
let req = Request {
model: self.model.clone(),
system: self.system.clone(),
messages: crate::mask::mask_old_results(msgs, self.mask_boundary),
messages: view.messages,
tools: self.tools.specs(),
max_tokens: self.max_tokens,
};
@@ -286,8 +264,8 @@ impl Agent {
+ usage.cache_read_tokens
+ usage.cache_write_tokens
+ usage.output_tokens) as usize;
self.push_with(msg.clone(), Some(usage))?;
self.ctx.record(total, self.session.messages().len());
self.push_reply(msg.clone(), usage, view.mask)?;
self.window.record(total, self.session.messages().len());
self.emit(Event::Message(msg.clone())).await;
let calls: Vec<(String, String, serde_json::Value)> = msg
@@ -639,25 +617,6 @@ mod tests {
);
}
#[test]
fn mask_threshold_is_capped() {
let dir = tempfile::tempdir().unwrap();
let cx = ToolCtx {
cwd: dir.path().into(),
state: Default::default(),
};
let (mut a, _h) = Agent::new(
Arc::new(Script(Mutex::new(vec![]), Mutex::new(vec![]))),
Registry::default(),
Session::open(dir.path().join("s.jsonl")).unwrap(),
cx,
);
a.set_compact_at(900_000);
assert_eq!(a.mask_from(), MASK_FROM_MAX);
a.set_compact_at(90_000);
assert_eq!(a.mask_from(), 30_000);
}
#[tokio::test]
async fn compaction_inside_tool_loop() {
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
@@ -748,7 +707,7 @@ mod tests {
Session::open(dir.path().join("a.jsonl")).unwrap(),
cx,
);
a.compact_at = 5_000;
a.set_compact_at(5_000);
a.run("hi").await.unwrap(); // real usage now covers 2 messages
// another session whose first two messages are huge and the rest tiny
let mut other = Session::open(dir.path().join("b.jsonl")).unwrap();
+3 -53
View File
@@ -1,7 +1,8 @@
//! Context compaction: measure how big the conversation is, and turn its old part into a summary.
//! 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
//! *when* to compact, *what* to summarize, and *what history remains* afterwards.
//! *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};
@@ -9,39 +10,6 @@ const SUMMARY_PROMPT: &str = "Summarize the conversation below for a coding agen
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.";
/// Rough token estimate (bytes / 4).
pub fn estimate_tokens(msgs: &[Message]) -> usize {
serde_json::to_string(msgs).map_or(0, |s| s.len() / 4)
}
/// Tracks the real token count the provider reported, so the compact trigger beats the bytes/4 guess.
///
/// Invariant: a reading describes one specific history. Call [`reset`](Self::reset) whenever that
/// history is replaced or rewritten (new session, fork, clear, compaction); until the next
/// [`record`](Self::record) the meter falls back to the estimate.
#[derive(Default, Debug, Clone, Copy)]
pub struct ContextMeter(Option<(usize, usize)>);
impl ContextMeter {
/// `total` real tokens (input + output) after a request that covered the first `msg_count` messages.
pub fn record(&mut self, total: usize, msg_count: usize) {
self.0 = Some((total, msg_count));
}
pub fn reset(&mut self) {
self.0 = None;
}
/// Context size: the last real reading plus an estimate of what was added since;
/// pure estimate when there is no (applicable) reading.
pub fn tokens(&self, msgs: &[Message]) -> usize {
match self.0 {
Some((t, n)) if n <= msgs.len() => t + estimate_tokens(&msgs[n..]),
_ => estimate_tokens(msgs),
}
}
}
/// A decided compaction: which part of the history gets summarized and which stays verbatim.
pub struct Plan {
transcript: String,
@@ -166,24 +134,6 @@ mod tests {
}
}
#[test]
fn meter_uses_real_usage() {
let m = vec![
Message::user("x".repeat(400)),
Message::user("y".repeat(40)),
];
let mut c = ContextMeter::default();
assert_eq!(c.tokens(&m), estimate_tokens(&m));
// 1000 real tokens covered the first message; only the second is estimated
c.record(1000, 1);
assert_eq!(c.tokens(&m), 1000 + estimate_tokens(&m[1..]));
c.reset();
assert_eq!(c.tokens(&m), estimate_tokens(&m));
// a reading that covers more messages than exist is stale
c.record(1000, 5);
assert_eq!(c.tokens(&m), estimate_tokens(&m));
}
#[test]
fn nothing_old_enough_to_cut() {
let m = vec![text(Role::User, "p1"), text(Role::Assistant, "r1")];
+2 -1
View File
@@ -6,12 +6,13 @@ pub mod compact;
pub mod context;
pub mod ext;
pub mod hook;
pub mod mask;
mod mask;
pub mod session;
pub mod stats;
pub mod subagent;
pub mod switch;
pub mod tool;
pub mod window;
use std::collections::HashMap;
use std::path::PathBuf;
+1 -2
View File
@@ -135,8 +135,7 @@ pub fn report(s: &Session) -> String {
.filter(|(_, m)| m.role == Role::Assistant)
{
// boundary the agent recorded for this request; older files used the stepwise rule
let b = masks[end].unwrap_or_else(|| crate::mask::target_boundary(&msgs[..end]));
let masked = crate::mask::mask_old_results(msgs[..end].to_vec(), b);
let masked = crate::window::ContextWindow::masked(&msgs[..end], masks[end]);
for (i, m) in masked.iter().enumerate() {
let text_len = |m: &hx_ai::Message| {
m.content
+230
View File
@@ -0,0 +1,230 @@
//! The context window: how big the conversation is, when to compact it, and what the next request
//! carries.
//!
//! Pure data in, data out. [`Agent`](crate::agent::Agent) owns the provider call and the session;
//! this module owns every decision about size: the token count (the provider's real reading plus an
//! estimate of what was added since), the compaction trigger, and the masking schedule (old, large
//! tool results become one-line stubs in the request; the session file keeps the originals).
//!
//! Invariants:
//! - A reading and the masking boundary each describe one specific history. [`reset`](ContextWindow::reset)
//! drops both; call it whenever the history is replaced or rewritten (new session, fork, clear,
//! compaction). Until the next [`record`](ContextWindow::record) the count is a pure estimate.
//! - The boundary only moves forward, and only once the context passes a third of the compaction
//! threshold (at most [`MASK_FROM_MAX`] tokens): every move rewrites the prompt cache from the
//! first changed result on, so the saving has to beat that. While it stays put the request prefix is byte-stable.
use crate::mask;
use hx_ai::Message;
/// The messages to send for one request.
#[derive(Debug, Clone)]
pub struct View {
pub messages: Vec<Message>,
/// Masking boundary these messages were built with. Store it next to the assistant reply
/// (`Session::append_masked`) so [`ContextWindow::masked`] can replay the request later.
pub mask: usize,
}
/// Context size above which old tool results start to be masked, at most.
const MASK_FROM_MAX: usize = 60_000;
pub struct ContextWindow {
compact_at: usize,
/// `(real tokens, messages they covered)` from the last request.
reading: Option<(usize, usize)>,
/// Assistant turns whose big tool results are masked.
boundary: usize,
}
impl ContextWindow {
/// Compact once the context exceeds `compact_at` tokens.
pub fn new(compact_at: usize) -> Self {
Self {
compact_at,
reading: None,
boundary: 0,
}
}
pub fn compact_at(&self) -> usize {
self.compact_at
}
pub fn set_compact_at(&mut self, n: usize) {
self.compact_at = n;
}
/// Context size of `msgs`: the last real reading plus an estimate of what was added since;
/// a pure estimate when there is no (applicable) reading. The one number behind the compaction
/// trigger and every display of it.
pub fn tokens(&self, msgs: &[Message]) -> usize {
match self.reading {
Some((t, n)) if n <= msgs.len() => t + estimate_tokens(&msgs[n..]),
_ => estimate_tokens(msgs),
}
}
pub fn should_compact(&self, msgs: &[Message]) -> bool {
self.tokens(msgs) > self.compact_at
}
/// Masking starts once the context passes a third of the compaction threshold, but never later
/// than `MASK_FROM_MAX` tokens: with a 1M window a third is ~300k, far beyond where old results
/// already cost more to resend than one cache rewrite.
// ponytail: 60k comes from two real sessions (contexts of 72k and 105k); tune with `hx stats`.
fn mask_from(&self) -> usize {
(self.compact_at / 3).min(MASK_FROM_MAX)
}
/// What to send for the next request. Advances the masking boundary if it is due, so call it
/// once per request, after any compaction.
pub fn view(&mut self, msgs: Vec<Message>) -> View {
let target = mask::target_boundary(&msgs);
if target > self.boundary && self.tokens(&msgs) > self.mask_from() {
self.boundary = target;
}
View {
mask: self.boundary,
messages: mask::mask_old_results(msgs, self.boundary),
}
}
/// `total` real tokens (input + output) after a request; the history then held `msg_count`
/// messages, the reply included.
pub fn record(&mut self, total: usize, msg_count: usize) {
self.reading = Some((total, msg_count));
}
/// The history was replaced or rewritten: forget the reading and the masking boundary.
pub fn reset(&mut self) {
self.reading = None;
self.boundary = 0;
}
/// Replay an earlier request over `msgs` (the messages before the reply). `stored` is the
/// boundary recorded with the reply; files written before it was recorded used the stepwise rule.
pub fn masked(msgs: &[Message], stored: Option<usize>) -> Vec<Message> {
let b = stored.unwrap_or_else(|| mask::target_boundary(msgs));
mask::mask_old_results(msgs.to_vec(), b)
}
}
/// Rough token estimate (bytes / 4).
fn estimate_tokens(msgs: &[Message]) -> usize {
serde_json::to_string(msgs).map_or(0, |s| s.len() / 4)
}
#[cfg(test)]
mod tests {
use super::*;
use hx_ai::{ContentBlock, Role};
fn assistant_turn(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!({}),
}],
},
Message {
role: Role::User,
content: vec![ContentBlock::ToolResult {
tool_use_id: format!("t{i}"),
content: "x".repeat(size),
is_error: false,
}],
},
]
}
fn history(turns: usize) -> Vec<Message> {
let mut v = vec![Message::user("go")];
for i in 0..turns {
v.extend(assistant_turn(i, 5_000));
}
v
}
fn elided(msgs: &[Message]) -> usize {
msgs.iter()
.flat_map(|m| &m.content)
.filter(|b| matches!(b, ContentBlock::ToolResult { content, .. } if content.starts_with("[elided")))
.count()
}
#[test]
fn counts_real_usage_plus_what_came_after() {
let m = vec![
Message::user("x".repeat(400)),
Message::user("y".repeat(40)),
];
let mut w = ContextWindow::new(1_000_000);
assert_eq!(w.tokens(&m), estimate_tokens(&m));
// 1000 real tokens covered the first message; only the second is estimated
w.record(1000, 1);
assert_eq!(w.tokens(&m), 1000 + estimate_tokens(&m[1..]));
// a reading that covers more messages than exist is stale
w.record(1000, 5);
assert_eq!(w.tokens(&m), estimate_tokens(&m));
}
#[test]
fn compaction_trigger_follows_the_threshold() {
let m = history(2);
let size = estimate_tokens(&m);
assert!(ContextWindow::new(size - 1).should_compact(&m));
assert!(!ContextWindow::new(size).should_compact(&m));
}
#[test]
fn masking_waits_for_a_big_context_then_only_moves_forward() {
let m = history(16); // target boundary 8
// far below a third of the threshold: nothing masked
let mut w = ContextWindow::new(10_000_000);
let v = w.view(m.clone());
assert_eq!((v.mask, elided(&v.messages)), (0, 0));
// past it: the first 8 big results are stubbed, and the boundary is reported
let mut w = ContextWindow::new(30_000);
let v = w.view(m.clone());
assert_eq!((v.mask, elided(&v.messages)), (8, 8));
// the same history again: same boundary, same bytes
let again = w.view(m.clone());
assert_eq!(again.mask, 8);
assert_eq!(
serde_json::to_string(&again.messages).unwrap(),
serde_json::to_string(&v.messages).unwrap()
);
// a shorter history (target 0) does not move it back
assert_eq!(w.view(history(2)).mask, 8);
}
#[test]
fn mask_threshold_is_capped() {
assert_eq!(ContextWindow::new(900_000).mask_from(), MASK_FROM_MAX);
assert_eq!(ContextWindow::new(90_000).mask_from(), 30_000);
}
#[test]
fn reset_forgets_the_reading_and_the_boundary() {
let m = history(16);
let mut w = ContextWindow::new(30_000);
w.record(500_000, m.len());
assert_eq!(w.view(m.clone()).mask, 8);
assert!(w.tokens(&m) >= 500_000);
w.reset();
assert_eq!(w.tokens(&m), estimate_tokens(&m));
assert_eq!(w.view(history(2)).mask, 0, "boundary starts over");
}
#[test]
fn replay_uses_the_stored_boundary_or_the_stepwise_rule() {
let m = history(16);
assert_eq!(elided(&ContextWindow::masked(&m, Some(0))), 0);
assert_eq!(elided(&ContextWindow::masked(&m, Some(4))), 4);
assert_eq!(elided(&ContextWindow::masked(&m, None)), 8);
}
}
+3 -3
View File
@@ -255,7 +255,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
kind: switcher.kind(),
model: agent.model().to_string(),
usage: Usage::default(),
ctx_tokens: hx_core::compact::estimate_tokens(&agent.session().messages()),
ctx_tokens: agent.context_tokens(),
ctx_max: agent.compact_at(),
quota: None,
pricing,
@@ -389,7 +389,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
Ok(false) => Item::Info("nothing to compact".into()),
Err(e) => Item::Error(e),
});
app.st.ctx_tokens = hx_core::compact::estimate_tokens(&agent.lock().await.session().messages());
app.st.ctx_tokens = agent.lock().await.context_tokens();
}
}
}
@@ -467,10 +467,10 @@ fn switch_session(app: &mut App, a: &mut Agent, sess: hx_core::session::Session)
app.t = Transcript::default();
let msgs = sess.messages();
sessions::history(&mut app.t, &msgs);
app.st.ctx_tokens = hx_core::compact::estimate_tokens(&msgs);
app.title = hx_core::session::title(&msgs);
app.session_path = sess.path().to_path_buf();
a.replace_session(sess);
app.st.ctx_tokens = a.context_tokens();
}
/// Picker keys. Returns a line to submit when an entry runs.