Session ops and ContextPolicy in hx-core #145

Merged
hermes merged 2 commits from refactor/session-ops into main 2026-10-09 19:37:56 +00:00
7 changed files with 205 additions and 105 deletions

No files matched your search

+1 -1
View File
@@ -208,7 +208,7 @@ One JSON object per line on stdout. `type` is one of:
JSON-RPC 2.0, one message per line on stdin/stdout. Events arrive as `event` notifications (params = the
event object above). Methods: `prompt {text}` (replies `{message, usage}` when the run ends), `abort`,
`state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`, `complete {line, cursor?}`
`state`, `messages`, `fork {id}`, `clear` (alias of `new`: new session file next to the current one), `set_model {model}`, `compact`, `complete {line, cursor?}`
(replies `{start, items: [{label, detail}]}`; `label` replaces `line[start..cursor]`, cursor is a byte
offset defaulting to the end). One prompt at a time; other methods are rejected while it runs (except
`abort` and `complete`). Sessions: `sessions {scope?: "project"|"all"}` (path, title, messages, model,
+10 -18
View File
@@ -685,10 +685,12 @@ async fn main() -> Result<()> {
if let Some(n) = cfg.max_tokens {
agent.set_max_tokens(n);
}
match cfg.compact_at {
Some(n) => agent.set_compact_at(n),
None => agent.fit_window(hx_ai::models::window(&models, agent.model())),
}
agent.set_context_policy(match cfg.compact_at {
Some(n) => hx_core::window::ContextPolicy::Fixed(n),
None => hx_core::window::ContextPolicy::FromModel {
window: hx_ai::models::window(&models, agent.model()),
},
});
let exts = futures::future::join_all(cfg.extensions.iter().map(|e| async {
hx_core::ext::Extension::start(e, &cwd)
.await
@@ -802,13 +804,8 @@ async fn main() -> Result<()> {
specs,
files: hx_tui::project_files(&cwd),
session_dir: dir,
switcher: Switcher::new(
kind,
models.clone(),
Box::new(provider),
cfg.compact_at.is_none(),
)
.remember_in(last_path.clone(), start.clone()),
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
.remember_in(last_path.clone(), start.clone()),
},
)
.await;
@@ -822,13 +819,8 @@ async fn main() -> Result<()> {
let Some(prompt) = cli.print else {
hx_tui::run(hx_tui::Setup {
agent,
switcher: Switcher::new(
kind,
models.clone(),
Box::new(provider),
cfg.compact_at.is_none(),
)
.remember_in(last_path, start),
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
.remember_in(last_path, start),
pricing,
specs,
open_sessions,
+6 -13
View File
@@ -137,9 +137,8 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()>
Some(n) if a.fork(n) => Ok(json!({"head": a.session().head()})),
_ => Err("unknown entry id".into()),
},
"clear" => a
.clear()
.map(|_| json!({}))
"clear" | "new" => a.new_session_here()
.map(|_| json!({"session": a.session().path()}))
.map_err(|e| e.to_string()),
"set_model" => match p["model"].as_str() {
// switches provider too when the model belongs to another one
@@ -155,7 +154,7 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()>
None => Err("params.model required".into()),
},
"compact" => a
.compact(4)
.compact_now()
.await
.map(|c| json!({"compacted": c}))
.map_err(|e| e.to_string()),
@@ -171,16 +170,10 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()>
"modified": m.modified.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()),
})).collect::<Vec<_>>()))
}
"new" => hx_core::session::Session::open(hx_core::session::new_path(&session_dir))
.map(|s| {
a.replace_session(s);
json!({"session": a.session().path()})
})
.map_err(|e| e.to_string()),
"resume" => match p["path"].as_str() {
Some(path) => hx_core::session::Session::open(path)
.map(|s| {
a.replace_session(s);
Some(path) => a
.resume(std::path::Path::new(path))
.map(|_| {
json!({"session": a.session().path(), "messages": a.session().messages().len()})
})
.map_err(|e| e.to_string()),
+120 -21
View File
@@ -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");
}
}
+8 -15
View File
@@ -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);
}
+36 -7
View File
@@ -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
+24 -30
View File
@@ -690,14 +690,19 @@ fn sessions_key(app: &mut App, k: KeyEvent) -> Option<String> {
}
/// Replace the agent's session (resume or new) and rebuild the transcript.
fn switch_session(app: &mut App, a: &mut Agent, sess: hx_core::session::Session) {
fn switch_session(
app: &mut App,
a: &mut Agent,
op: impl FnOnce(&mut Agent) -> Result<(), hx_core::agent::Error>,
) -> Result<(), hx_core::agent::Error> {
op(a)?;
app.t = Transcript::default();
let msgs = sess.messages();
let msgs = a.session().messages();
sessions::history(&mut app.t, &msgs);
app.title = hx_core::session::title(&msgs);
app.session_path = sess.path().to_path_buf();
a.replace_session(sess);
app.session_path = a.session().path().to_path_buf();
app.st.ctx_tokens = a.context_tokens();
Ok(())
}
/// Picker keys. Returns a line to submit when an entry runs.
@@ -1338,21 +1343,20 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
};
show(app, "lsp", l);
}
"resume" if !arg.is_empty() => match hx_core::session::Session::open(arg) {
Ok(sess) => {
switch_session(app, &mut *agent.lock().await, sess);
app.t.push(Item::Info(format!("resumed {arg}")));
"resume" if !arg.is_empty() => {
let r = switch_session(app, &mut *agent.lock().await, |a| {
a.resume(std::path::Path::new(arg))
});
match r {
Ok(()) => app.t.push(Item::Info(format!("resumed {arg}"))),
Err(e) => app.t.push(Item::Error(format!("/resume: {e}"))),
}
Err(e) => app.t.push(Item::Error(format!("/resume: {e}"))),
},
}
"sessions" | "resume" => open_sessions_picker(app),
"new" | "clear" => {
let p = hx_core::session::new_path(sessions_dir(app));
match hx_core::session::Session::open(&p) {
Ok(sess) => {
switch_session(app, &mut *agent.lock().await, sess);
app.t.push(Item::Info("new session".into()));
}
let r = switch_session(app, &mut *agent.lock().await, Agent::new_session_here);
match r {
Ok(()) => app.t.push(Item::Info("new session".into())),
Err(e) => app.t.push(Item::Error(format!("/new: {e}"))),
}
}
@@ -1416,7 +1420,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
let r = agent
.lock()
.await
.compact(4)
.compact_now()
.await
.map_err(|e| e.to_string());
let _ = tx.send(Ui::Compacted(r));
@@ -2403,12 +2407,7 @@ mod tests {
since: Instant::now(),
quit: false,
hint: String::new(),
sw: Switcher::new(
Kind::Claude,
vec![],
Box::new(|_| Ok(Arc::new(NoProvider))),
true,
),
sw: Switcher::new(Kind::Claude, vec![], Box::new(|_| Ok(Arc::new(NoProvider)))),
specs: cmd::builtins(&["sonnet", "opus"]),
popup: None,
picker: None,
@@ -2684,19 +2683,14 @@ mod tests {
let mut app = test_app();
let fail: MakeProvider =
Box::new(|_| Err(hx_ai::Error::Http("not logged in to Codex".into())));
app.sw = Switcher::new(Kind::Claude, models.clone(), fail, true);
app.sw = Switcher::new(Kind::Claude, models.clone(), fail);
// codex not logged in: error shown, footer state unchanged
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
assert_eq!((app.st.kind, app.st.model.as_str()), (Kind::Claude, "m1"));
assert!(matches!(app.t.items.last(), Some(Item::Error(e)) if e.contains("not logged in")));
app.sw = Switcher::new(
Kind::Claude,
models,
Box::new(|_| Ok(Arc::new(NoProvider))),
true,
);
app.sw = Switcher::new(Kind::Claude, models, Box::new(|_| Ok(Arc::new(NoProvider))));
app.st.quota = Some(Default::default());
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
assert_eq!(