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
@@ -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
|
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`,
|
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
|
(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
|
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,
|
`abort` and `complete`). Sessions: `sessions {scope?: "project"|"all"}` (path, title, messages, model,
|
||||||
|
|||||||
+10
-18
@@ -685,10 +685,12 @@ async fn main() -> Result<()> {
|
|||||||
if let Some(n) = cfg.max_tokens {
|
if let Some(n) = cfg.max_tokens {
|
||||||
agent.set_max_tokens(n);
|
agent.set_max_tokens(n);
|
||||||
}
|
}
|
||||||
match cfg.compact_at {
|
agent.set_context_policy(match cfg.compact_at {
|
||||||
Some(n) => agent.set_compact_at(n),
|
Some(n) => hx_core::window::ContextPolicy::Fixed(n),
|
||||||
None => agent.fit_window(hx_ai::models::window(&models, agent.model())),
|
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 {
|
let exts = futures::future::join_all(cfg.extensions.iter().map(|e| async {
|
||||||
hx_core::ext::Extension::start(e, &cwd)
|
hx_core::ext::Extension::start(e, &cwd)
|
||||||
.await
|
.await
|
||||||
@@ -802,13 +804,8 @@ async fn main() -> Result<()> {
|
|||||||
specs,
|
specs,
|
||||||
files: hx_tui::project_files(&cwd),
|
files: hx_tui::project_files(&cwd),
|
||||||
session_dir: dir,
|
session_dir: dir,
|
||||||
switcher: Switcher::new(
|
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
|
||||||
kind,
|
.remember_in(last_path.clone(), start.clone()),
|
||||||
models.clone(),
|
|
||||||
Box::new(provider),
|
|
||||||
cfg.compact_at.is_none(),
|
|
||||||
)
|
|
||||||
.remember_in(last_path.clone(), start.clone()),
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -822,13 +819,8 @@ async fn main() -> Result<()> {
|
|||||||
let Some(prompt) = cli.print else {
|
let Some(prompt) = cli.print else {
|
||||||
hx_tui::run(hx_tui::Setup {
|
hx_tui::run(hx_tui::Setup {
|
||||||
agent,
|
agent,
|
||||||
switcher: Switcher::new(
|
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
|
||||||
kind,
|
.remember_in(last_path, start),
|
||||||
models.clone(),
|
|
||||||
Box::new(provider),
|
|
||||||
cfg.compact_at.is_none(),
|
|
||||||
)
|
|
||||||
.remember_in(last_path, start),
|
|
||||||
pricing,
|
pricing,
|
||||||
specs,
|
specs,
|
||||||
open_sessions,
|
open_sessions,
|
||||||
|
|||||||
@@ -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()})),
|
Some(n) if a.fork(n) => Ok(json!({"head": a.session().head()})),
|
||||||
_ => Err("unknown entry id".into()),
|
_ => Err("unknown entry id".into()),
|
||||||
},
|
},
|
||||||
"clear" => a
|
"clear" | "new" => a.new_session_here()
|
||||||
.clear()
|
.map(|_| json!({"session": a.session().path()}))
|
||||||
.map(|_| json!({}))
|
|
||||||
.map_err(|e| e.to_string()),
|
.map_err(|e| e.to_string()),
|
||||||
"set_model" => match p["model"].as_str() {
|
"set_model" => match p["model"].as_str() {
|
||||||
// switches provider too when the model belongs to another one
|
// 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()),
|
None => Err("params.model required".into()),
|
||||||
},
|
},
|
||||||
"compact" => a
|
"compact" => a
|
||||||
.compact(4)
|
.compact_now()
|
||||||
.await
|
.await
|
||||||
.map(|c| json!({"compacted": c}))
|
.map(|c| json!({"compacted": c}))
|
||||||
.map_err(|e| e.to_string()),
|
.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()),
|
"modified": m.modified.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()),
|
||||||
})).collect::<Vec<_>>()))
|
})).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() {
|
"resume" => match p["path"].as_str() {
|
||||||
Some(path) => hx_core::session::Session::open(path)
|
Some(path) => a
|
||||||
.map(|s| {
|
.resume(std::path::Path::new(path))
|
||||||
a.replace_session(s);
|
.map(|_| {
|
||||||
json!({"session": a.session().path(), "messages": a.session().messages().len()})
|
json!({"session": a.session().path(), "messages": a.session().messages().len()})
|
||||||
})
|
})
|
||||||
.map_err(|e| e.to_string()),
|
.map_err(|e| e.to_string()),
|
||||||
|
|||||||
+120
-21
@@ -4,7 +4,7 @@ use crate::compact;
|
|||||||
use crate::hook::{Bus, Event};
|
use crate::hook::{Bus, Event};
|
||||||
use crate::session::Session;
|
use crate::session::Session;
|
||||||
use crate::tool::{Registry, ToolCtx};
|
use crate::tool::{Registry, ToolCtx};
|
||||||
use crate::window::ContextWindow;
|
use crate::window::{ContextPolicy, ContextWindow};
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use hx_ai::{ContentBlock, Message, Provider, Request, Role, StopReason, StreamEvent, Usage};
|
use hx_ai::{ContentBlock, Message, Provider, Request, Role, StopReason, StreamEvent, Usage};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -76,6 +76,9 @@ pub enum Error {
|
|||||||
MaxTurns(u32),
|
MaxTurns(u32),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Messages kept verbatim by manual and automatic compaction.
|
||||||
|
pub const KEEP_MESSAGES: usize = 6;
|
||||||
|
|
||||||
pub struct Agent {
|
pub struct Agent {
|
||||||
provider: Arc<dyn Provider>,
|
provider: Arc<dyn Provider>,
|
||||||
pub tools: Registry,
|
pub tools: Registry,
|
||||||
@@ -136,7 +139,11 @@ impl Agent {
|
|||||||
max_turns: 200,
|
max_turns: 200,
|
||||||
usage: Usage::default(),
|
usage: Usage::default(),
|
||||||
session,
|
session,
|
||||||
window: ContextWindow::new(150_000),
|
window: {
|
||||||
|
let mut w = ContextWindow::new(150_000);
|
||||||
|
w.set_reserve(16_384);
|
||||||
|
w
|
||||||
|
},
|
||||||
abort: rx,
|
abort: rx,
|
||||||
abort_tx: tx.clone(),
|
abort_tx: tx.clone(),
|
||||||
snap,
|
snap,
|
||||||
@@ -206,9 +213,10 @@ impl Agent {
|
|||||||
self.publish();
|
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) {
|
pub fn set_max_tokens(&mut self, n: u32) {
|
||||||
self.max_tokens = n;
|
self.max_tokens = n;
|
||||||
|
self.window.set_reserve(n);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn compact_at(&self) -> usize {
|
pub fn compact_at(&self) -> usize {
|
||||||
@@ -221,15 +229,14 @@ impl Agent {
|
|||||||
self.window.tokens(&self.session.messages())
|
self.window.tokens(&self.session.messages())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Auto-compact once the context exceeds `n` tokens.
|
/// Where the auto-compaction threshold comes from.
|
||||||
pub fn set_compact_at(&mut self, n: usize) {
|
pub fn set_context_policy(&mut self, p: ContextPolicy) {
|
||||||
self.window.set_compact_at(n);
|
self.window.set_policy(p);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Derive the compaction threshold from the model's context window (leaving room for a reply).
|
/// The model's context window changed; a fixed threshold ignores it.
|
||||||
pub fn fit_window(&mut self, window: u64) {
|
pub fn set_model_window(&mut self, window: u64) {
|
||||||
self.window
|
self.window.set_model_window(window);
|
||||||
.set_compact_at(hx_ai::models::compact_threshold(window, self.max_tokens));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Switch provider and model together; a model id is only meaningful to its provider.
|
/// Switch provider and model together; a model id is only meaningful to its provider.
|
||||||
@@ -256,14 +263,38 @@ impl Agent {
|
|||||||
ok
|
ok
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Start over: empty the conversation, keeping the session file's history.
|
/// Start a new, empty session file in `dir` and switch to it.
|
||||||
pub fn clear(&mut self) -> Result<(), Error> {
|
pub fn new_session(&mut self, dir: &std::path::Path) -> Result<(), Error> {
|
||||||
self.session.rebase(vec![])?;
|
let s = Session::open(crate::session::new_path(dir))?;
|
||||||
self.window.reset();
|
self.replace_session(s);
|
||||||
self.publish();
|
|
||||||
Ok(())
|
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.
|
/// 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.
|
/// 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
|
/// 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() {
|
if self.aborted() {
|
||||||
return Err(Error::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::Info("context compacted".into())).await;
|
||||||
}
|
}
|
||||||
self.emit(Event::TurnStart).await;
|
self.emit(Event::TurnStart).await;
|
||||||
@@ -710,7 +743,7 @@ mod tests {
|
|||||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||||
cx,
|
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();
|
a.run("go").await.unwrap();
|
||||||
let elided = |r: &Request| {
|
let elided = |r: &Request| {
|
||||||
r.messages.iter().any(|m| {
|
r.messages.iter().any(|m| {
|
||||||
@@ -739,7 +772,7 @@ mod tests {
|
|||||||
Session::open(dir.path().join("s2.jsonl")).unwrap(),
|
Session::open(dir.path().join("s2.jsonl")).unwrap(),
|
||||||
cx,
|
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();
|
b.run("go").await.unwrap();
|
||||||
assert!(script.1.lock().unwrap().iter().any(elided));
|
assert!(script.1.lock().unwrap().iter().any(elided));
|
||||||
assert!(
|
assert!(
|
||||||
@@ -790,6 +823,72 @@ mod tests {
|
|||||||
assert!(matches!(m[2].content[0], ContentBlock::ToolResult { .. }));
|
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]
|
#[tokio::test]
|
||||||
async fn compaction() {
|
async fn compaction() {
|
||||||
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
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(),
|
Session::open(dir.path().join("a.jsonl")).unwrap(),
|
||||||
cx,
|
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
|
a.run("hi").await.unwrap(); // real usage now covers 2 messages
|
||||||
// another session whose first two messages are huge and the rest tiny
|
// another session whose first two messages are huge and the rest tiny
|
||||||
let mut other = Session::open(dir.path().join("b.jsonl")).unwrap();
|
let mut other = Session::open(dir.path().join("b.jsonl")).unwrap();
|
||||||
@@ -884,10 +983,10 @@ mod tests {
|
|||||||
a.set_system("base");
|
a.set_system("base");
|
||||||
a.append_system("more");
|
a.append_system("more");
|
||||||
assert_eq!(a.system, "base\n\nmore");
|
assert_eq!(a.system, "base\n\nmore");
|
||||||
|
a.set_context_policy(ContextPolicy::FromModel { window: 100_000 });
|
||||||
a.set_max_tokens(10_000);
|
a.set_max_tokens(10_000);
|
||||||
a.fit_window(100_000);
|
|
||||||
assert_eq!(a.compact_at(), 90_000, "90% of the window");
|
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");
|
assert_eq!(a.compact_at(), 10_000, "leaves room for the reply");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,24 +45,17 @@ pub struct Switcher {
|
|||||||
kind: Kind,
|
kind: Kind,
|
||||||
models: Vec<ModelInfo>,
|
models: Vec<ModelInfo>,
|
||||||
make_provider: MakeProvider,
|
make_provider: MakeProvider,
|
||||||
auto_compact: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Switcher {
|
impl Switcher {
|
||||||
/// `kind` is the provider the agent starts with. `auto_compact`: re-derive the compaction
|
/// `kind` is the provider the agent starts with. The agent's `ContextPolicy` decides whether a
|
||||||
/// threshold from the model's window on every switch (false when it is configured explicitly).
|
/// model switch moves the compaction threshold.
|
||||||
pub fn new(
|
pub fn new(kind: Kind, models: Vec<ModelInfo>, make_provider: MakeProvider) -> Self {
|
||||||
kind: Kind,
|
|
||||||
models: Vec<ModelInfo>,
|
|
||||||
make_provider: MakeProvider,
|
|
||||||
auto_compact: bool,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
Self {
|
||||||
remember: None,
|
remember: None,
|
||||||
kind,
|
kind,
|
||||||
models,
|
models,
|
||||||
make_provider,
|
make_provider,
|
||||||
auto_compact,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,9 +115,7 @@ impl Switcher {
|
|||||||
let _ = serde_json::to_vec(&*l).map(|b| std::fs::write(&*p, b));
|
let _ = serde_json::to_vec(&*l).map(|b| std::fs::write(&*p, b));
|
||||||
}
|
}
|
||||||
let window = models::window(&self.models, &model);
|
let window = models::window(&self.models, &model);
|
||||||
if self.auto_compact {
|
agent.set_model_window(window);
|
||||||
agent.fit_window(window);
|
|
||||||
}
|
|
||||||
Ok(Switched {
|
Ok(Switched {
|
||||||
kind,
|
kind,
|
||||||
model,
|
model,
|
||||||
@@ -184,7 +175,6 @@ mod tests {
|
|||||||
Ok(Arc::new(Nop))
|
Ok(Arc::new(Nop))
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
auto,
|
|
||||||
);
|
);
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let cx = ToolCtx {
|
let cx = ToolCtx {
|
||||||
@@ -197,6 +187,9 @@ mod tests {
|
|||||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||||
cx,
|
cx,
|
||||||
);
|
);
|
||||||
|
if auto {
|
||||||
|
a.set_context_policy(crate::window::ContextPolicy::FromModel { window: 0 });
|
||||||
|
}
|
||||||
a.set_model("claude-sonnet-x");
|
a.set_model("claude-sonnet-x");
|
||||||
(sw, a, made, dir)
|
(sw, a, made, dir)
|
||||||
}
|
}
|
||||||
@@ -285,7 +278,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn configured_threshold_is_left_alone() {
|
fn configured_threshold_is_left_alone() {
|
||||||
let (mut sw, mut a, _m, _d) = setup(false, false);
|
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();
|
sw.set_model(&mut a, "claude-haiku-x").unwrap();
|
||||||
assert_eq!(a.compact_at(), 12_345);
|
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.
|
/// Context size above which old tool results start to be masked, at most.
|
||||||
const MASK_FROM_MAX: usize = 60_000;
|
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 {
|
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.
|
/// `(real tokens, messages they covered)` from the last request.
|
||||||
reading: Option<(usize, usize)>,
|
reading: Option<(usize, usize)>,
|
||||||
/// Assistant turns whose big tool results are masked.
|
/// Assistant turns whose big tool results are masked.
|
||||||
@@ -41,18 +52,36 @@ impl ContextWindow {
|
|||||||
/// Compact once the context exceeds `compact_at` tokens.
|
/// Compact once the context exceeds `compact_at` tokens.
|
||||||
pub fn new(compact_at: usize) -> Self {
|
pub fn new(compact_at: usize) -> Self {
|
||||||
Self {
|
Self {
|
||||||
compact_at,
|
policy: ContextPolicy::Fixed(compact_at),
|
||||||
|
reserve: 0,
|
||||||
reading: None,
|
reading: None,
|
||||||
boundary: 0,
|
boundary: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn compact_at(&self) -> usize {
|
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) {
|
pub fn set_policy(&mut self, p: ContextPolicy) {
|
||||||
self.compact_at = n;
|
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;
|
/// 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 {
|
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
|
/// 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.
|
/// 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`.
|
// ponytail: 60k comes from two real sessions (contexts of 72k and 105k); tune with `hx stats`.
|
||||||
fn mask_from(&self) -> usize {
|
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
|
/// What to send for the next request. Advances the masking boundary if it is due, so call it
|
||||||
|
|||||||
+24
-30
@@ -614,14 +614,19 @@ fn sessions_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Replace the agent's session (resume or new) and rebuild the transcript.
|
/// 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();
|
app.t = Transcript::default();
|
||||||
let msgs = sess.messages();
|
let msgs = a.session().messages();
|
||||||
sessions::history(&mut app.t, &msgs);
|
sessions::history(&mut app.t, &msgs);
|
||||||
app.title = hx_core::session::title(&msgs);
|
app.title = hx_core::session::title(&msgs);
|
||||||
app.session_path = sess.path().to_path_buf();
|
app.session_path = a.session().path().to_path_buf();
|
||||||
a.replace_session(sess);
|
|
||||||
app.st.ctx_tokens = a.context_tokens();
|
app.st.ctx_tokens = a.context_tokens();
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Picker keys. Returns a line to submit when an entry runs.
|
/// Picker keys. Returns a line to submit when an entry runs.
|
||||||
@@ -1262,21 +1267,20 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
};
|
};
|
||||||
show(app, "lsp", l);
|
show(app, "lsp", l);
|
||||||
}
|
}
|
||||||
"resume" if !arg.is_empty() => match hx_core::session::Session::open(arg) {
|
"resume" if !arg.is_empty() => {
|
||||||
Ok(sess) => {
|
let r = switch_session(app, &mut *agent.lock().await, |a| {
|
||||||
switch_session(app, &mut *agent.lock().await, sess);
|
a.resume(std::path::Path::new(arg))
|
||||||
app.t.push(Item::Info(format!("resumed {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),
|
"sessions" | "resume" => open_sessions_picker(app),
|
||||||
"new" | "clear" => {
|
"new" | "clear" => {
|
||||||
let p = hx_core::session::new_path(sessions_dir(app));
|
let r = switch_session(app, &mut *agent.lock().await, Agent::new_session_here);
|
||||||
match hx_core::session::Session::open(&p) {
|
match r {
|
||||||
Ok(sess) => {
|
Ok(()) => app.t.push(Item::Info("new session".into())),
|
||||||
switch_session(app, &mut *agent.lock().await, sess);
|
|
||||||
app.t.push(Item::Info("new session".into()));
|
|
||||||
}
|
|
||||||
Err(e) => app.t.push(Item::Error(format!("/new: {e}"))),
|
Err(e) => app.t.push(Item::Error(format!("/new: {e}"))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1339,7 +1343,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
let r = agent
|
let r = agent
|
||||||
.lock()
|
.lock()
|
||||||
.await
|
.await
|
||||||
.compact(4)
|
.compact_now()
|
||||||
.await
|
.await
|
||||||
.map_err(|e| e.to_string());
|
.map_err(|e| e.to_string());
|
||||||
let _ = tx.send(Ui::Compacted(r));
|
let _ = tx.send(Ui::Compacted(r));
|
||||||
@@ -2084,12 +2088,7 @@ mod tests {
|
|||||||
since: Instant::now(),
|
since: Instant::now(),
|
||||||
quit: false,
|
quit: false,
|
||||||
hint: String::new(),
|
hint: String::new(),
|
||||||
sw: Switcher::new(
|
sw: Switcher::new(Kind::Claude, vec![], Box::new(|_| Ok(Arc::new(NoProvider)))),
|
||||||
Kind::Claude,
|
|
||||||
vec![],
|
|
||||||
Box::new(|_| Ok(Arc::new(NoProvider))),
|
|
||||||
true,
|
|
||||||
),
|
|
||||||
specs: cmd::builtins(&["sonnet", "opus"]),
|
specs: cmd::builtins(&["sonnet", "opus"]),
|
||||||
popup: None,
|
popup: None,
|
||||||
picker: None,
|
picker: None,
|
||||||
@@ -2377,19 +2376,14 @@ mod tests {
|
|||||||
let mut app = test_app();
|
let mut app = test_app();
|
||||||
let fail: MakeProvider =
|
let fail: MakeProvider =
|
||||||
Box::new(|_| Err(hx_ai::Error::Http("not logged in to Codex".into())));
|
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
|
// codex not logged in: error shown, footer state unchanged
|
||||||
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
|
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_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")));
|
assert!(matches!(app.t.items.last(), Some(Item::Error(e)) if e.contains("not logged in")));
|
||||||
|
|
||||||
app.sw = Switcher::new(
|
app.sw = Switcher::new(Kind::Claude, models, Box::new(|_| Ok(Arc::new(NoProvider))));
|
||||||
Kind::Claude,
|
|
||||||
models,
|
|
||||||
Box::new(|_| Ok(Arc::new(NoProvider))),
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
app.st.quota = Some(Default::default());
|
app.st.quota = Some(Default::default());
|
||||||
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
|
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|||||||
Reference in new issue
Block a user