tokens: rolling cache breakpoints, real-usage compact trigger, smaller read/bash limits with head+tail
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s

This commit is contained in:
hermes committed 2026-10-01 21:00:47 +00:00
1 parent d332cf4cc4
commit c5420026b8
3 files changed
+109 -9

No files matched your search

+35 -1
View File
@@ -35,6 +35,9 @@ pub struct Agent {
pub session: Session,
/// Auto-compact when the estimated context exceeds this many tokens.
pub compact_at: usize,
/// (real input+output tokens of the last request, message count it covered); None until the
/// first request and after compaction. Beats the bytes/4 guess for the compact trigger.
last_ctx: Option<(usize, usize)>,
abort: watch::Receiver<bool>,
abort_tx: Arc<watch::Sender<bool>>,
}
@@ -43,6 +46,15 @@ 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.";
/// Context size: real usage of the last request plus a bytes/4 estimate of what was added since;
/// pure estimate when there is no usage yet.
fn context_tokens(last: Option<(usize, usize)>, msgs: &[Message]) -> usize {
match last {
Some((t, n)) if n <= msgs.len() => t + estimate_tokens(&msgs[n..]),
_ => estimate_tokens(msgs),
}
}
/// Rough token estimate (bytes / 4).
pub fn estimate_tokens(msgs: &[Message]) -> usize {
serde_json::to_string(msgs).map_or(0, |s| s.len() / 4)
@@ -125,6 +137,7 @@ impl Agent {
usage: Usage::default(),
session,
compact_at: 150_000,
last_ctx: None,
abort: rx,
abort_tx: tx.clone(),
};
@@ -170,6 +183,7 @@ impl Agent {
},
);
self.session.rebase(kept)?;
self.last_ctx = None;
Ok(true)
}
@@ -206,7 +220,7 @@ impl Agent {
if self.aborted() {
return Err(Error::Aborted);
}
if estimate_tokens(&self.session.messages()) > self.compact_at
if context_tokens(self.last_ctx, &self.session.messages()) > self.compact_at
&& self.compact(6).await?
{
self.emit(Event::Info("context compacted".into())).await;
@@ -239,7 +253,12 @@ impl Agent {
}
let (msg, stop, usage) = done.ok_or(Error::Truncated)?;
self.usage.add(&usage);
let total = (usage.input_tokens
+ usage.cache_read_tokens
+ usage.cache_write_tokens
+ usage.output_tokens) as usize;
self.push_with(msg.clone(), Some(usage))?;
self.last_ctx = Some((total, self.session.messages().len()));
self.emit(Event::Message(msg.clone())).await;
let calls: Vec<(String, String, serde_json::Value)> = msg
@@ -514,6 +533,21 @@ mod tests {
assert!(matches!(a.run("again").await, Err(Error::Aborted)));
}
#[test]
fn context_uses_real_usage() {
let m = vec![
Message::user("x".repeat(400)),
Message::user("y".repeat(40)),
];
assert_eq!(context_tokens(None, &m), estimate_tokens(&m));
// 1000 real tokens covered the first message; only the second is estimated
assert_eq!(
context_tokens(Some((1000, 1)), &m),
1000 + estimate_tokens(&m[1..])
);
assert_eq!(context_tokens(Some((1000, 5)), &m), estimate_tokens(&m));
}
#[tokio::test]
async fn compaction() {
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);