Merge pull request 'Token phase 2: cache breakpoints, real-usage compact trigger, smaller tool limits' (#101) from token-phase2 into main
ci / check (push) Canceled after 0s
ci / check (push) Canceled after 0s
This commit was merged in pull request #101.
This commit is contained in:
commit
e54b6fd4ce
3 files changed
+109
-9
No files matched your search
@@ -83,11 +83,28 @@ pub fn body(req: &Request) -> Value {
|
||||
if let Some(last) = system.last_mut() {
|
||||
last["cache_control"] = json!({"type": "ephemeral"});
|
||||
}
|
||||
let messages: Vec<Value> = req
|
||||
let mut messages: Vec<Value> = req
|
||||
.messages
|
||||
.iter()
|
||||
.map(|m| json!({"role": m.role, "content": m.content.iter().map(block_json).collect::<Vec<_>>()}))
|
||||
.collect();
|
||||
// Rolling breakpoints (tools+system are covered by the system one): the last message, and the
|
||||
// user message before it, which is where the previous request's breakpoint sat -> cache read.
|
||||
let n = messages.len();
|
||||
let prev_user = (0..n.saturating_sub(1))
|
||||
.rev()
|
||||
.find(|&i| req.messages[i].role == Role::User);
|
||||
for i in [n.checked_sub(1), prev_user].into_iter().flatten() {
|
||||
if req.messages[i].role != Role::User {
|
||||
continue;
|
||||
}
|
||||
if let Some(last) = messages[i]["content"]
|
||||
.as_array_mut()
|
||||
.and_then(|c| c.last_mut())
|
||||
{
|
||||
last["cache_control"] = json!({"type": "ephemeral"});
|
||||
}
|
||||
}
|
||||
let tools: Vec<Value> = req
|
||||
.tools
|
||||
.iter()
|
||||
@@ -421,6 +438,31 @@ mod tests {
|
||||
assert_eq!(b["tools"][0]["name"], "Read");
|
||||
assert_eq!(b["messages"][0]["content"][0]["type"], "text");
|
||||
assert_eq!(b["stream"], true);
|
||||
// message tail is a cache breakpoint (single user message here)
|
||||
assert_eq!(
|
||||
b["messages"][0]["content"][0]["cache_control"]["type"],
|
||||
"ephemeral"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rolling_breakpoints() {
|
||||
let mut r = req();
|
||||
r.messages = vec![
|
||||
Message::user("a"),
|
||||
Message {
|
||||
role: Role::Assistant,
|
||||
content: vec![ContentBlock::Text { text: "b".into() }],
|
||||
},
|
||||
Message::user("c"),
|
||||
];
|
||||
let b = body(&r);
|
||||
let has = |i: usize| {
|
||||
b["messages"][i]["content"][0]
|
||||
.get("cache_control")
|
||||
.is_some()
|
||||
};
|
||||
assert!(has(0) && !has(1) && has(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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() }]);
|
||||
|
||||
@@ -7,8 +7,10 @@ use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
const MAX_LINES: usize = 2000;
|
||||
const MAX_BYTES: usize = 50_000;
|
||||
const MAX_LINES: usize = 600;
|
||||
const MAX_BYTES: usize = 20_000;
|
||||
/// bash keeps this much of the start (command echo, first errors) and the rest from the end.
|
||||
const HEAD_BYTES: usize = 4_000;
|
||||
|
||||
fn spec(name: &str, desc: &str, schema: Value) -> ToolSpec {
|
||||
ToolSpec {
|
||||
@@ -28,6 +30,20 @@ fn resolve(cx: &ToolCtx, p: &str) -> PathBuf {
|
||||
}
|
||||
|
||||
/// Keep the tail of `s` within `max` bytes on a char boundary.
|
||||
/// First `head` bytes + last `max - head` bytes, char-boundary safe. Returns (text, cut bytes).
|
||||
fn head_tail(s: &str, max: usize, head: usize) -> (String, usize) {
|
||||
if s.len() <= max {
|
||||
return (s.to_string(), 0);
|
||||
}
|
||||
let mut h = head;
|
||||
while !s.is_char_boundary(h) {
|
||||
h -= 1;
|
||||
}
|
||||
let t = tail(s, max - head);
|
||||
let cut = s.len() - h - t.len();
|
||||
(format!("{}\n[... {cut} bytes cut ...]\n{t}", &s[..h]), cut)
|
||||
}
|
||||
|
||||
fn tail(s: &str, max: usize) -> &str {
|
||||
if s.len() <= max {
|
||||
return s;
|
||||
@@ -247,7 +263,7 @@ impl Tool for Bash {
|
||||
fn spec(&self) -> ToolSpec {
|
||||
spec(
|
||||
"bash",
|
||||
"Run a shell command in the working directory. stdout and stderr are merged. Long output is truncated to the tail.",
|
||||
"Run a shell command in the working directory. stdout and stderr are merged. Long output keeps the start and the end; the middle is cut and the full output saved to a file.",
|
||||
json!({"type":"object","properties":{
|
||||
"command":{"type":"string"},
|
||||
"timeout":{"type":"integer","description":"seconds, default 120"}},
|
||||
@@ -287,8 +303,8 @@ impl Tool for Bash {
|
||||
}
|
||||
};
|
||||
let s = String::from_utf8_lossy(&out);
|
||||
let mut body = tail(&s, MAX_BYTES).to_string();
|
||||
if body.len() < s.len() {
|
||||
let (mut body, cut) = head_tail(&s, MAX_BYTES, HEAD_BYTES);
|
||||
if cut > 0 {
|
||||
let f = std::env::temp_dir().join(format!(
|
||||
"hx-bash-{}.log",
|
||||
std::process::id() as u128 * 1000 + pid.unwrap_or(0) as u128
|
||||
@@ -296,7 +312,7 @@ impl Tool for Bash {
|
||||
let _ = std::fs::write(&f, s.as_bytes());
|
||||
body = format!(
|
||||
"[truncated {} bytes; full output: {}]\n{body}",
|
||||
s.len() - body.len(),
|
||||
cut,
|
||||
f.display()
|
||||
);
|
||||
}
|
||||
@@ -353,6 +369,14 @@ mod tests {
|
||||
assert!(r.content.len() < MAX_BYTES + 200 && r.content.contains("use offset="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_tail_keeps_both_ends() {
|
||||
let s = format!("HEAD{}TAIL", "é".repeat(5000));
|
||||
let (o, cut) = head_tail(&s, 1000, 200);
|
||||
assert!(o.starts_with("HEAD") && o.ends_with("TAIL") && cut > 0 && o.len() < 1100);
|
||||
assert_eq!(head_tail("short", 1000, 200), ("short".to_string(), 0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_edit_guard_crlf() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
@@ -444,6 +468,6 @@ mod tests {
|
||||
let r = Bash
|
||||
.call(json!({"command":"yes | head -c 200000"}), &c)
|
||||
.await;
|
||||
assert!(r.content.contains("[truncated") && r.content.len() < MAX_BYTES + 300);
|
||||
assert!(r.content.contains("[truncated") && r.content.len() < MAX_BYTES + 400);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user