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");
|
||||
}
|
||||
}
|
||||
@@ -45,24 +45,17 @@ pub struct Switcher {
|
||||
kind: Kind,
|
||||
models: Vec<ModelInfo>,
|
||||
make_provider: MakeProvider,
|
||||
auto_compact: bool,
|
||||
}
|
||||
|
||||
impl Switcher {
|
||||
/// `kind` is the provider the agent starts with. `auto_compact`: re-derive the compaction
|
||||
/// threshold from the model's window on every switch (false when it is configured explicitly).
|
||||
pub fn new(
|
||||
kind: Kind,
|
||||
models: Vec<ModelInfo>,
|
||||
make_provider: MakeProvider,
|
||||
auto_compact: bool,
|
||||
) -> Self {
|
||||
/// `kind` is the provider the agent starts with. The agent's `ContextPolicy` decides whether a
|
||||
/// model switch moves the compaction threshold.
|
||||
pub fn new(kind: Kind, models: Vec<ModelInfo>, make_provider: MakeProvider) -> Self {
|
||||
Self {
|
||||
remember: None,
|
||||
kind,
|
||||
models,
|
||||
make_provider,
|
||||
auto_compact,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,9 +115,7 @@ impl Switcher {
|
||||
let _ = serde_json::to_vec(&*l).map(|b| std::fs::write(&*p, b));
|
||||
}
|
||||
let window = models::window(&self.models, &model);
|
||||
if self.auto_compact {
|
||||
agent.fit_window(window);
|
||||
}
|
||||
agent.set_model_window(window);
|
||||
Ok(Switched {
|
||||
kind,
|
||||
model,
|
||||
@@ -184,7 +175,6 @@ mod tests {
|
||||
Ok(Arc::new(Nop))
|
||||
}
|
||||
}),
|
||||
auto,
|
||||
);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cx = ToolCtx {
|
||||
@@ -197,6 +187,9 @@ mod tests {
|
||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
if auto {
|
||||
a.set_context_policy(crate::window::ContextPolicy::FromModel { window: 0 });
|
||||
}
|
||||
a.set_model("claude-sonnet-x");
|
||||
(sw, a, made, dir)
|
||||
}
|
||||
@@ -285,7 +278,7 @@ mod tests {
|
||||
#[test]
|
||||
fn configured_threshold_is_left_alone() {
|
||||
let (mut sw, mut a, _m, _d) = setup(false, false);
|
||||
a.set_compact_at(12_345);
|
||||
a.set_context_policy(crate::window::ContextPolicy::Fixed(12_345));
|
||||
sw.set_model(&mut a, "claude-haiku-x").unwrap();
|
||||
assert_eq!(a.compact_at(), 12_345);
|
||||
}
|
||||
|
||||
@@ -29,8 +29,19 @@ pub struct View {
|
||||
/// Context size above which old tool results start to be masked, at most.
|
||||
const MASK_FROM_MAX: usize = 60_000;
|
||||
|
||||
/// Where the compaction threshold comes from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ContextPolicy {
|
||||
/// Compact above exactly this many tokens (config `compact_at`).
|
||||
Fixed(usize),
|
||||
/// Derived from the model's context window, leaving room for a reply.
|
||||
FromModel { window: u64 },
|
||||
}
|
||||
|
||||
pub struct ContextWindow {
|
||||
compact_at: usize,
|
||||
policy: ContextPolicy,
|
||||
/// Room kept free for the reply (the request's `max_tokens`).
|
||||
reserve: u32,
|
||||
/// `(real tokens, messages they covered)` from the last request.
|
||||
reading: Option<(usize, usize)>,
|
||||
/// Assistant turns whose big tool results are masked.
|
||||
@@ -41,18 +52,36 @@ impl ContextWindow {
|
||||
/// Compact once the context exceeds `compact_at` tokens.
|
||||
pub fn new(compact_at: usize) -> Self {
|
||||
Self {
|
||||
compact_at,
|
||||
policy: ContextPolicy::Fixed(compact_at),
|
||||
reserve: 0,
|
||||
reading: None,
|
||||
boundary: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compact_at(&self) -> usize {
|
||||
self.compact_at
|
||||
match self.policy {
|
||||
ContextPolicy::Fixed(n) => n,
|
||||
ContextPolicy::FromModel { window } => {
|
||||
hx_ai::models::compact_threshold(window, self.reserve)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_compact_at(&mut self, n: usize) {
|
||||
self.compact_at = n;
|
||||
pub fn set_policy(&mut self, p: ContextPolicy) {
|
||||
self.policy = p;
|
||||
}
|
||||
|
||||
/// Room for the reply; only matters for [`ContextPolicy::FromModel`], and any call order works.
|
||||
pub fn set_reserve(&mut self, tokens: u32) {
|
||||
self.reserve = tokens;
|
||||
}
|
||||
|
||||
/// The model changed: follow its window unless the threshold is fixed.
|
||||
pub fn set_model_window(&mut self, window: u64) {
|
||||
if let ContextPolicy::FromModel { window: w } = &mut self.policy {
|
||||
*w = window;
|
||||
}
|
||||
}
|
||||
|
||||
/// Context size of `msgs`: the last real reading plus an estimate of what was added since;
|
||||
@@ -66,7 +95,7 @@ impl ContextWindow {
|
||||
}
|
||||
|
||||
pub fn should_compact(&self, msgs: &[Message]) -> bool {
|
||||
self.tokens(msgs) > self.compact_at
|
||||
self.tokens(msgs) > self.compact_at()
|
||||
}
|
||||
|
||||
/// Masking starts once the context passes a third of the compaction threshold, but never later
|
||||
@@ -74,7 +103,7 @@ impl ContextWindow {
|
||||
/// 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)
|
||||
(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
|
||||
|
||||
Reference in new issue
Block a user