Session ops and ContextPolicy in hx-core
This commit is contained in:
1 parent
69d5ae4581
commit
be74dd9fec
7 files changed
+205
-105
No files matched your search
+120
-21
@@ -4,7 +4,7 @@ use crate::compact;
|
||||
use crate::hook::{Bus, Event};
|
||||
use crate::session::Session;
|
||||
use crate::tool::{Registry, ToolCtx};
|
||||
use crate::window::ContextWindow;
|
||||
use crate::window::{ContextPolicy, ContextWindow};
|
||||
use futures::StreamExt;
|
||||
use hx_ai::{ContentBlock, Message, Provider, Request, Role, StopReason, StreamEvent, Usage};
|
||||
use std::sync::Arc;
|
||||
@@ -76,6 +76,9 @@ pub enum Error {
|
||||
MaxTurns(u32),
|
||||
}
|
||||
|
||||
/// Messages kept verbatim by manual and automatic compaction.
|
||||
pub const KEEP_MESSAGES: usize = 6;
|
||||
|
||||
pub struct Agent {
|
||||
provider: Arc<dyn Provider>,
|
||||
pub tools: Registry,
|
||||
@@ -136,7 +139,11 @@ impl Agent {
|
||||
max_turns: 200,
|
||||
usage: Usage::default(),
|
||||
session,
|
||||
window: ContextWindow::new(150_000),
|
||||
window: {
|
||||
let mut w = ContextWindow::new(150_000);
|
||||
w.set_reserve(16_384);
|
||||
w
|
||||
},
|
||||
abort: rx,
|
||||
abort_tx: tx.clone(),
|
||||
snap,
|
||||
@@ -206,9 +213,10 @@ impl Agent {
|
||||
self.publish();
|
||||
}
|
||||
|
||||
/// Cap on tokens per reply. Set it before [`fit_window`](Self::fit_window), which reserves room for it.
|
||||
/// Cap on tokens per reply (also the room the compaction threshold keeps free).
|
||||
pub fn set_max_tokens(&mut self, n: u32) {
|
||||
self.max_tokens = n;
|
||||
self.window.set_reserve(n);
|
||||
}
|
||||
|
||||
pub fn compact_at(&self) -> usize {
|
||||
@@ -221,15 +229,14 @@ impl Agent {
|
||||
self.window.tokens(&self.session.messages())
|
||||
}
|
||||
|
||||
/// Auto-compact once the context exceeds `n` tokens.
|
||||
pub fn set_compact_at(&mut self, n: usize) {
|
||||
self.window.set_compact_at(n);
|
||||
/// Where the auto-compaction threshold comes from.
|
||||
pub fn set_context_policy(&mut self, p: ContextPolicy) {
|
||||
self.window.set_policy(p);
|
||||
}
|
||||
|
||||
/// Derive the compaction threshold from the model's context window (leaving room for a reply).
|
||||
pub fn fit_window(&mut self, window: u64) {
|
||||
self.window
|
||||
.set_compact_at(hx_ai::models::compact_threshold(window, self.max_tokens));
|
||||
/// The model's context window changed; a fixed threshold ignores it.
|
||||
pub fn set_model_window(&mut self, window: u64) {
|
||||
self.window.set_model_window(window);
|
||||
}
|
||||
|
||||
/// Switch provider and model together; a model id is only meaningful to its provider.
|
||||
@@ -256,14 +263,38 @@ impl Agent {
|
||||
ok
|
||||
}
|
||||
|
||||
/// Start over: empty the conversation, keeping the session file's history.
|
||||
pub fn clear(&mut self) -> Result<(), Error> {
|
||||
self.session.rebase(vec![])?;
|
||||
self.window.reset();
|
||||
self.publish();
|
||||
/// Start a new, empty session file in `dir` and switch to it.
|
||||
pub fn new_session(&mut self, dir: &std::path::Path) -> Result<(), Error> {
|
||||
let s = Session::open(crate::session::new_path(dir))?;
|
||||
self.replace_session(s);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`new_session`](Self::new_session) next to the current session file.
|
||||
pub fn new_session_here(&mut self) -> Result<(), Error> {
|
||||
let dir = self.session_dir().to_path_buf();
|
||||
self.new_session(&dir)
|
||||
}
|
||||
|
||||
/// Switch to the session file at `path`.
|
||||
pub fn resume(&mut self, path: &std::path::Path) -> Result<(), Error> {
|
||||
self.replace_session(Session::open(path)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Directory of the current session file (where [`new_session`](Self::new_session) should write).
|
||||
pub fn session_dir(&self) -> &std::path::Path {
|
||||
self.session
|
||||
.path()
|
||||
.parent()
|
||||
.unwrap_or(std::path::Path::new("."))
|
||||
}
|
||||
|
||||
/// Compact on request (`/compact`, rpc `compact`), keeping [`KEEP_MESSAGES`] verbatim.
|
||||
pub async fn compact_now(&mut self) -> Result<bool, Error> {
|
||||
self.compact(KEEP_MESSAGES).await
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Cuts at the latest user prompt; inside one long tool loop (no prompt to cut at) it cuts before an
|
||||
@@ -324,7 +355,9 @@ impl Agent {
|
||||
if self.aborted() {
|
||||
return Err(Error::Aborted);
|
||||
}
|
||||
if self.window.should_compact(&self.session.messages()) && self.compact(6).await? {
|
||||
if self.window.should_compact(&self.session.messages())
|
||||
&& self.compact(KEEP_MESSAGES).await?
|
||||
{
|
||||
self.emit(Event::Info("context compacted".into())).await;
|
||||
}
|
||||
self.emit(Event::TurnStart).await;
|
||||
@@ -710,7 +743,7 @@ mod tests {
|
||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
a.set_compact_at(1_000_000); // capped at 60k tokens: this run stays below it
|
||||
a.set_context_policy(ContextPolicy::Fixed(1_000_000)); // capped at 60k tokens: this run stays below it
|
||||
a.run("go").await.unwrap();
|
||||
let elided = |r: &Request| {
|
||||
r.messages.iter().any(|m| {
|
||||
@@ -739,7 +772,7 @@ mod tests {
|
||||
Session::open(dir.path().join("s2.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
b.set_compact_at(3_000); // a third = 1k tokens, below the cap
|
||||
b.set_context_policy(ContextPolicy::Fixed(3_000)); // a third = 1k tokens, below the cap
|
||||
b.run("go").await.unwrap();
|
||||
assert!(script.1.lock().unwrap().iter().any(elided));
|
||||
assert!(
|
||||
@@ -790,6 +823,72 @@ mod tests {
|
||||
assert!(matches!(m[2].content[0], ContentBlock::ToolResult { .. }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_ops_share_one_path() {
|
||||
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
||||
let script = Arc::new(Script(Mutex::new(vec![text("r1")]), Mutex::new(vec![])));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let sub = dir.path().join("sub");
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let first = sub.join("a.jsonl");
|
||||
let (mut a, _h) = Agent::new(
|
||||
script,
|
||||
Registry::default(),
|
||||
Session::open(&first).unwrap(),
|
||||
cx,
|
||||
);
|
||||
a.run("p1").await.unwrap();
|
||||
assert_eq!(a.session_dir(), sub);
|
||||
// new: empty file in the current session's directory, old file untouched
|
||||
a.new_session_here().unwrap();
|
||||
assert!(a.session().messages().is_empty());
|
||||
assert_eq!(a.session().path().parent(), Some(sub.as_path()));
|
||||
assert_ne!(a.session().path(), first);
|
||||
assert_eq!(Session::open(&first).unwrap().messages().len(), 2);
|
||||
// resume: back to the old one; context window is re-measured
|
||||
a.resume(&first).unwrap();
|
||||
assert_eq!(a.session().messages().len(), 2);
|
||||
assert!(
|
||||
a.resume(&dir.path().join("x").join("..").join("sub"))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_is_order_independent() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let mk = |n| {
|
||||
Agent::new(
|
||||
Arc::new(Script(Mutex::new(vec![]), Mutex::new(vec![]))),
|
||||
Registry::default(),
|
||||
Session::open(dir.path().join(n)).unwrap(),
|
||||
ToolCtx {
|
||||
cwd: cx.cwd.clone(),
|
||||
state: Default::default(),
|
||||
},
|
||||
)
|
||||
.0
|
||||
};
|
||||
let (mut a, mut b) = (mk("a"), mk("b"));
|
||||
a.set_context_policy(ContextPolicy::FromModel { window: 100_000 });
|
||||
a.set_max_tokens(10_000);
|
||||
b.set_max_tokens(10_000);
|
||||
b.set_context_policy(ContextPolicy::FromModel { window: 100_000 });
|
||||
assert_eq!((a.compact_at(), b.compact_at()), (90_000, 90_000));
|
||||
b.set_max_tokens(95_000);
|
||||
assert_eq!(b.compact_at(), 5_000, "reserve change is picked up");
|
||||
b.set_context_policy(ContextPolicy::Fixed(7));
|
||||
b.set_model_window(1_000_000);
|
||||
assert_eq!(b.compact_at(), 7, "fixed ignores the model window");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compaction() {
|
||||
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
||||
@@ -843,7 +942,7 @@ mod tests {
|
||||
Session::open(dir.path().join("a.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
a.set_compact_at(5_000);
|
||||
a.set_context_policy(ContextPolicy::Fixed(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();
|
||||
@@ -884,10 +983,10 @@ mod tests {
|
||||
a.set_system("base");
|
||||
a.append_system("more");
|
||||
assert_eq!(a.system, "base\n\nmore");
|
||||
a.set_context_policy(ContextPolicy::FromModel { window: 100_000 });
|
||||
a.set_max_tokens(10_000);
|
||||
a.fit_window(100_000);
|
||||
assert_eq!(a.compact_at(), 90_000, "90% of the window");
|
||||
a.fit_window(20_000);
|
||||
a.set_model_window(20_000);
|
||||
assert_eq!(a.compact_at(), 10_000, "leaves room for the reply");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user