Deepen Agent, compaction, switching and TUI modules
- Agent: make session/usage/provider/model/system/max_tokens/compact_at private; add set_provider, set_model, replace_session, fork, clear, fit_window. Fixes stale context-token reading after resume/new session. - hx-core::compact: ContextMeter, plan/apply and estimate_tokens split out of agent.rs, testable without provider or session. - hx-core::switch: Switcher shared by TUI and RPC for model/provider switches; RPC set_model now also refits the compaction threshold. - hx-tui: status.rs (footer, /usage as pure functions), popup.rs, and Picker::key returning an Act. - tests/tui_smoke.py: resolve the temp dir (macOS /var symlink) and match the resume via the OSC window title instead of split screen text.
This commit is contained in:
1 parent
fe308e0f36
commit
eaa6e22fbd
11 files changed
+1407
-632
No files matched your search
+160
-115
@@ -1,5 +1,6 @@
|
||||
//! Agent loop: stream -> tool calls -> hooks -> results -> repeat.
|
||||
|
||||
use crate::compact::{self, ContextMeter};
|
||||
use crate::hook::{Bus, Event};
|
||||
use crate::session::Session;
|
||||
use crate::tool::{Registry, ToolCtx};
|
||||
@@ -23,86 +24,23 @@ pub enum Error {
|
||||
}
|
||||
|
||||
pub struct Agent {
|
||||
pub provider: Arc<dyn Provider>,
|
||||
provider: Arc<dyn Provider>,
|
||||
pub tools: Registry,
|
||||
pub bus: Bus,
|
||||
pub cx: ToolCtx,
|
||||
pub model: String,
|
||||
pub system: String,
|
||||
pub max_tokens: u32,
|
||||
pub max_turns: u32,
|
||||
pub usage: Usage,
|
||||
pub session: Session,
|
||||
model: String,
|
||||
system: String,
|
||||
max_tokens: u32,
|
||||
max_turns: u32,
|
||||
usage: Usage,
|
||||
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)>,
|
||||
compact_at: usize,
|
||||
ctx: ContextMeter,
|
||||
abort: watch::Receiver<bool>,
|
||||
abort_tx: Arc<watch::Sender<bool>>,
|
||||
}
|
||||
|
||||
const SUMMARY_PROMPT: &str = "Summarize the conversation below for a coding agent that will continue the work. \
|
||||
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)
|
||||
}
|
||||
|
||||
fn is_prompt(m: &Message) -> bool {
|
||||
m.role == Role::User
|
||||
&& !m
|
||||
.content
|
||||
.iter()
|
||||
.any(|b| matches!(b, ContentBlock::ToolResult { .. }))
|
||||
}
|
||||
|
||||
fn transcript(msgs: &[Message]) -> String {
|
||||
let cut = |s: &str| -> String {
|
||||
if s.len() > 800 {
|
||||
format!("{}…", s.chars().take(800).collect::<String>())
|
||||
} else {
|
||||
s.to_string()
|
||||
}
|
||||
};
|
||||
let mut t = String::new();
|
||||
for m in msgs {
|
||||
let who = if m.role == Role::User {
|
||||
"USER"
|
||||
} else {
|
||||
"ASSISTANT"
|
||||
};
|
||||
for b in &m.content {
|
||||
match b {
|
||||
ContentBlock::Text { text } => t.push_str(&format!("{who}: {text}\n")),
|
||||
ContentBlock::ToolUse { name, input, .. } => {
|
||||
t.push_str(&format!("TOOL CALL {name}: {}\n", cut(&input.to_string())))
|
||||
}
|
||||
ContentBlock::ToolResult {
|
||||
content, is_error, ..
|
||||
} => t.push_str(&format!(
|
||||
"TOOL RESULT{}: {}\n",
|
||||
if *is_error { " (error)" } else { "" },
|
||||
cut(content)
|
||||
)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// Cheap handle to cancel a running `Agent::run`.
|
||||
#[derive(Clone)]
|
||||
pub struct AbortHandle(Arc<watch::Sender<bool>>);
|
||||
@@ -137,7 +75,7 @@ impl Agent {
|
||||
usage: Usage::default(),
|
||||
session,
|
||||
compact_at: 150_000,
|
||||
last_ctx: None,
|
||||
ctx: ContextMeter::default(),
|
||||
abort: rx,
|
||||
abort_tx: tx.clone(),
|
||||
};
|
||||
@@ -148,27 +86,90 @@ impl Agent {
|
||||
AbortHandle(self.abort_tx.clone())
|
||||
}
|
||||
|
||||
pub fn session(&self) -> &Session {
|
||||
&self.session
|
||||
}
|
||||
|
||||
/// Cumulative usage of every request this agent made (turns and compaction summaries).
|
||||
pub fn usage(&self) -> &Usage {
|
||||
&self.usage
|
||||
}
|
||||
|
||||
pub fn model(&self) -> &str {
|
||||
&self.model
|
||||
}
|
||||
|
||||
/// Use another model of the current provider. For a different provider use [`set_provider`](Self::set_provider).
|
||||
pub fn set_model(&mut self, model: impl Into<String>) {
|
||||
self.model = model.into();
|
||||
}
|
||||
|
||||
pub fn set_system(&mut self, system: impl Into<String>) {
|
||||
self.system = system.into();
|
||||
}
|
||||
|
||||
/// Append a section to the system prompt.
|
||||
pub fn append_system(&mut self, section: &str) {
|
||||
self.system.push_str("\n\n");
|
||||
self.system.push_str(section);
|
||||
}
|
||||
|
||||
/// Cap on tokens per reply. Set it before [`fit_window`](Self::fit_window), which reserves room for it.
|
||||
pub fn set_max_tokens(&mut self, n: u32) {
|
||||
self.max_tokens = n;
|
||||
}
|
||||
|
||||
pub fn compact_at(&self) -> usize {
|
||||
self.compact_at
|
||||
}
|
||||
|
||||
/// Auto-compact once the context exceeds `n` tokens.
|
||||
pub fn set_compact_at(&mut self, n: usize) {
|
||||
self.compact_at = n;
|
||||
}
|
||||
|
||||
/// Derive the compaction threshold from the model's context window (leaving room for a reply).
|
||||
pub fn fit_window(&mut self, window: u64) {
|
||||
self.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.
|
||||
pub fn set_provider(&mut self, provider: Arc<dyn Provider>, model: impl Into<String>) {
|
||||
self.provider = provider;
|
||||
self.set_model(model);
|
||||
}
|
||||
|
||||
/// Continue in another session (resume or new). Drops token usage measured on the old history.
|
||||
pub fn replace_session(&mut self, session: Session) {
|
||||
self.session = session;
|
||||
self.ctx.reset();
|
||||
}
|
||||
|
||||
/// Move the session head to entry `id`. False (and no change) if there is no such entry.
|
||||
pub fn fork(&mut self, id: u64) -> bool {
|
||||
let ok = self.session.fork(id);
|
||||
if ok {
|
||||
self.ctx.reset();
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// Start over: empty the conversation, keeping the session file's history.
|
||||
pub fn clear(&mut self) -> Result<(), Error> {
|
||||
self.session.rebase(vec![])?;
|
||||
self.ctx.reset();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// assistant message and the summary becomes its own leading user message.
|
||||
pub async fn compact(&mut self, keep: usize) -> Result<bool, Error> {
|
||||
let msgs = self.session.messages();
|
||||
let range = 1..=msgs.len().saturating_sub(keep);
|
||||
let prompt_cut = range.clone().rev().find(|&i| is_prompt(&msgs[i]));
|
||||
let Some(cut) =
|
||||
prompt_cut.or_else(|| range.rev().find(|&i| msgs[i].role == Role::Assistant))
|
||||
else {
|
||||
let Some(plan) = compact::plan(&self.session.messages(), keep) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let req = Request {
|
||||
model: self.model.clone(),
|
||||
system: SUMMARY_PROMPT.into(),
|
||||
messages: vec![Message::user(transcript(&msgs[..cut]))],
|
||||
tools: vec![],
|
||||
max_tokens: 4096,
|
||||
};
|
||||
let mut s = self.provider.stream(req).await?;
|
||||
let mut s = self.provider.stream(plan.request(&self.model)).await?;
|
||||
let mut summary = None;
|
||||
while let Some(ev) = s.next().await {
|
||||
if let StreamEvent::Done { message, usage, .. } = ev? {
|
||||
@@ -177,15 +178,8 @@ impl Agent {
|
||||
}
|
||||
}
|
||||
let summary = summary.ok_or(Error::Truncated)?;
|
||||
let note = format!("[Summary of earlier conversation]\n{summary}\n[End of summary]");
|
||||
let mut kept = msgs[cut..].to_vec();
|
||||
if prompt_cut.is_some() {
|
||||
kept[0].content.insert(0, ContentBlock::Text { text: note });
|
||||
} else {
|
||||
kept.insert(0, Message::user(note));
|
||||
}
|
||||
self.session.rebase(kept)?;
|
||||
self.last_ctx = None;
|
||||
self.session.rebase(plan.apply(&summary))?;
|
||||
self.ctx.reset();
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -222,7 +216,7 @@ impl Agent {
|
||||
if self.aborted() {
|
||||
return Err(Error::Aborted);
|
||||
}
|
||||
if context_tokens(self.last_ctx, &self.session.messages()) > self.compact_at
|
||||
if self.ctx.tokens(&self.session.messages()) > self.compact_at
|
||||
&& self.compact(6).await?
|
||||
{
|
||||
self.emit(Event::Info("context compacted".into())).await;
|
||||
@@ -260,7 +254,7 @@ impl Agent {
|
||||
+ 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.ctx.record(total, self.session.messages().len());
|
||||
self.emit(Event::Message(msg.clone())).await;
|
||||
|
||||
let calls: Vec<(String, String, serde_json::Value)> = msg
|
||||
@@ -535,21 +529,6 @@ 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_inside_tool_loop() {
|
||||
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
||||
@@ -578,7 +557,7 @@ mod tests {
|
||||
);
|
||||
a.run("go").await.unwrap(); // p, a1, r1, a2, r2, fin
|
||||
assert!(a.compact(3).await.unwrap());
|
||||
let m = a.session.messages();
|
||||
let m = a.session().messages();
|
||||
// summary(user), a2, r2, fin -> alternates, tool_use still has its result
|
||||
assert_eq!(m.len(), 4);
|
||||
assert_eq!(m[0].role, Role::User);
|
||||
@@ -610,7 +589,7 @@ mod tests {
|
||||
a.run("p2").await.unwrap();
|
||||
assert!(!a.compact(10).await.unwrap(), "nothing old enough to cut");
|
||||
assert!(a.compact(2).await.unwrap());
|
||||
let m = a.session.messages();
|
||||
let m = a.session().messages();
|
||||
assert_eq!(m.len(), 2);
|
||||
assert!(m[0].text().contains("SUMMARY") && m[0].text().ends_with("p2"));
|
||||
{
|
||||
@@ -621,4 +600,70 @@ mod tests {
|
||||
a.run("p3").await.unwrap();
|
||||
assert_eq!(Session::open(&path).unwrap().messages().len(), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replacing_the_session_drops_stale_context_usage() {
|
||||
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
||||
let script = Arc::new(Script(
|
||||
Mutex::new(vec![text("r1"), text("SUMMARY"), text("r2")]),
|
||||
Mutex::new(vec![]),
|
||||
));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut a, _h) = Agent::new(
|
||||
script.clone(),
|
||||
Registry::default(),
|
||||
Session::open(dir.path().join("a.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
a.compact_at = 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();
|
||||
let big = "x".repeat(40_000);
|
||||
for i in 0..8 {
|
||||
let t = if i < 2 { big.as_str() } else { "." };
|
||||
other
|
||||
.append(if i % 2 == 0 {
|
||||
Message::user(t)
|
||||
} else {
|
||||
text(t)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
a.replace_session(other);
|
||||
a.run("go").await.unwrap();
|
||||
let reqs = script.1.lock().unwrap();
|
||||
assert!(
|
||||
reqs.iter()
|
||||
.any(|r| r.system.starts_with("Summarize the conversation")),
|
||||
"oversized history must trigger compaction"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_through_the_interface() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut a, _h) = Agent::new(
|
||||
Arc::new(Script(Mutex::new(vec![]), Mutex::new(vec![]))),
|
||||
Registry::default(),
|
||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
a.set_system("base");
|
||||
a.append_system("more");
|
||||
assert_eq!(a.system, "base\n\nmore");
|
||||
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);
|
||||
assert_eq!(a.compact_at(), 10_000, "leaves room for the reply");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Context compaction: measure how big the conversation is, and turn its old part into a summary.
|
||||
//!
|
||||
//! Pure data in, data out. The agent owns the provider call and the session; this module decides
|
||||
//! *when* to compact, *what* to summarize, and *what history remains* afterwards.
|
||||
|
||||
use hx_ai::{ContentBlock, Message, Request, Role};
|
||||
|
||||
const SUMMARY_PROMPT: &str = "Summarize the conversation below for a coding agent that will continue the work. \
|
||||
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.";
|
||||
|
||||
/// Rough token estimate (bytes / 4).
|
||||
pub fn estimate_tokens(msgs: &[Message]) -> usize {
|
||||
serde_json::to_string(msgs).map_or(0, |s| s.len() / 4)
|
||||
}
|
||||
|
||||
/// Tracks the real token count the provider reported, so the compact trigger beats the bytes/4 guess.
|
||||
///
|
||||
/// Invariant: a reading describes one specific history. Call [`reset`](Self::reset) whenever that
|
||||
/// history is replaced or rewritten (new session, fork, clear, compaction); until the next
|
||||
/// [`record`](Self::record) the meter falls back to the estimate.
|
||||
#[derive(Default, Debug, Clone, Copy)]
|
||||
pub struct ContextMeter(Option<(usize, usize)>);
|
||||
|
||||
impl ContextMeter {
|
||||
/// `total` real tokens (input + output) after a request that covered the first `msg_count` messages.
|
||||
pub fn record(&mut self, total: usize, msg_count: usize) {
|
||||
self.0 = Some((total, msg_count));
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.0 = None;
|
||||
}
|
||||
|
||||
/// Context size: the last real reading plus an estimate of what was added since;
|
||||
/// pure estimate when there is no (applicable) reading.
|
||||
pub fn tokens(&self, msgs: &[Message]) -> usize {
|
||||
match self.0 {
|
||||
Some((t, n)) if n <= msgs.len() => t + estimate_tokens(&msgs[n..]),
|
||||
_ => estimate_tokens(msgs),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A decided compaction: which part of the history gets summarized and which stays verbatim.
|
||||
pub struct Plan {
|
||||
transcript: String,
|
||||
kept: Vec<Message>,
|
||||
/// Kept history starts at a user prompt, so the summary can be folded into it.
|
||||
folds_into_prompt: bool,
|
||||
}
|
||||
|
||||
/// Plan the compaction of `msgs`, keeping at least `keep` trailing messages verbatim.
|
||||
/// `None` when there is nothing old enough to cut.
|
||||
///
|
||||
/// Cuts at the latest user prompt; inside one long tool loop (no prompt to cut at) it cuts before an
|
||||
/// assistant message and the summary becomes its own leading user message.
|
||||
pub fn plan(msgs: &[Message], keep: usize) -> Option<Plan> {
|
||||
let range = 1..=msgs.len().saturating_sub(keep);
|
||||
let prompt_cut = range.clone().rev().find(|&i| is_prompt(&msgs[i]));
|
||||
let cut = prompt_cut.or_else(|| range.rev().find(|&i| msgs[i].role == Role::Assistant))?;
|
||||
Some(Plan {
|
||||
transcript: transcript(&msgs[..cut]),
|
||||
kept: msgs[cut..].to_vec(),
|
||||
folds_into_prompt: prompt_cut.is_some(),
|
||||
})
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
/// The summarization request to send to the model.
|
||||
pub fn request(&self, model: &str) -> Request {
|
||||
Request {
|
||||
model: model.into(),
|
||||
system: SUMMARY_PROMPT.into(),
|
||||
messages: vec![Message::user(self.transcript.clone())],
|
||||
tools: vec![],
|
||||
max_tokens: 4096,
|
||||
}
|
||||
}
|
||||
|
||||
/// The new history once the model has produced `summary`.
|
||||
pub fn apply(self, summary: &str) -> Vec<Message> {
|
||||
let note = format!("[Summary of earlier conversation]\n{summary}\n[End of summary]");
|
||||
let mut kept = self.kept;
|
||||
if self.folds_into_prompt {
|
||||
kept[0].content.insert(0, ContentBlock::Text { text: note });
|
||||
} else {
|
||||
kept.insert(0, Message::user(note));
|
||||
}
|
||||
kept
|
||||
}
|
||||
}
|
||||
|
||||
fn is_prompt(m: &Message) -> bool {
|
||||
m.role == Role::User
|
||||
&& !m
|
||||
.content
|
||||
.iter()
|
||||
.any(|b| matches!(b, ContentBlock::ToolResult { .. }))
|
||||
}
|
||||
|
||||
fn transcript(msgs: &[Message]) -> String {
|
||||
let cut = |s: &str| -> String {
|
||||
if s.len() > 800 {
|
||||
format!("{}…", s.chars().take(800).collect::<String>())
|
||||
} else {
|
||||
s.to_string()
|
||||
}
|
||||
};
|
||||
let mut t = String::new();
|
||||
for m in msgs {
|
||||
let who = if m.role == Role::User {
|
||||
"USER"
|
||||
} else {
|
||||
"ASSISTANT"
|
||||
};
|
||||
for b in &m.content {
|
||||
match b {
|
||||
ContentBlock::Text { text } => t.push_str(&format!("{who}: {text}\n")),
|
||||
ContentBlock::ToolUse { name, input, .. } => {
|
||||
t.push_str(&format!("TOOL CALL {name}: {}\n", cut(&input.to_string())))
|
||||
}
|
||||
ContentBlock::ToolResult {
|
||||
content, is_error, ..
|
||||
} => t.push_str(&format!(
|
||||
"TOOL RESULT{}: {}\n",
|
||||
if *is_error { " (error)" } else { "" },
|
||||
cut(content)
|
||||
)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn text(role: Role, t: &str) -> Message {
|
||||
Message {
|
||||
role,
|
||||
content: vec![ContentBlock::Text { text: t.into() }],
|
||||
}
|
||||
}
|
||||
fn call(id: &str) -> Message {
|
||||
Message {
|
||||
role: Role::Assistant,
|
||||
content: vec![ContentBlock::ToolUse {
|
||||
id: id.into(),
|
||||
name: "echo".into(),
|
||||
input: json!({}),
|
||||
}],
|
||||
}
|
||||
}
|
||||
fn result(id: &str) -> Message {
|
||||
Message {
|
||||
role: Role::User,
|
||||
content: vec![ContentBlock::ToolResult {
|
||||
tool_use_id: id.into(),
|
||||
content: "ok".into(),
|
||||
is_error: false,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn meter_uses_real_usage() {
|
||||
let m = vec![
|
||||
Message::user("x".repeat(400)),
|
||||
Message::user("y".repeat(40)),
|
||||
];
|
||||
let mut c = ContextMeter::default();
|
||||
assert_eq!(c.tokens(&m), estimate_tokens(&m));
|
||||
// 1000 real tokens covered the first message; only the second is estimated
|
||||
c.record(1000, 1);
|
||||
assert_eq!(c.tokens(&m), 1000 + estimate_tokens(&m[1..]));
|
||||
c.reset();
|
||||
assert_eq!(c.tokens(&m), estimate_tokens(&m));
|
||||
// a reading that covers more messages than exist is stale
|
||||
c.record(1000, 5);
|
||||
assert_eq!(c.tokens(&m), estimate_tokens(&m));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_old_enough_to_cut() {
|
||||
let m = vec![text(Role::User, "p1"), text(Role::Assistant, "r1")];
|
||||
assert!(plan(&m, 10).is_none());
|
||||
assert!(plan(&m, 2).is_none(), "the first message is never cut");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cuts_at_latest_prompt_and_folds_summary_into_it() {
|
||||
let m = vec![
|
||||
text(Role::User, "p1"),
|
||||
text(Role::Assistant, "r1"),
|
||||
text(Role::User, "p2"),
|
||||
text(Role::Assistant, "r2"),
|
||||
];
|
||||
let p = plan(&m, 2).unwrap();
|
||||
let req = p.request("m");
|
||||
let t = req.messages[0].text();
|
||||
assert!(t.contains("USER: p1") && t.contains("ASSISTANT: r1") && !t.contains("p2"));
|
||||
assert_eq!(req.model, "m");
|
||||
let h = p.apply("SUM");
|
||||
assert_eq!(h.len(), 2);
|
||||
assert!(h[0].text().contains("SUM") && h[0].text().ends_with("p2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_a_tool_loop_the_summary_is_its_own_message() {
|
||||
// p, a1, r1, a2, r2, fin: no prompt in the cuttable range
|
||||
let m = vec![
|
||||
text(Role::User, "go"),
|
||||
call("1"),
|
||||
result("1"),
|
||||
call("2"),
|
||||
result("2"),
|
||||
text(Role::Assistant, "fin"),
|
||||
];
|
||||
let h = plan(&m, 3).unwrap().apply("SUM");
|
||||
// summary(user), a2, r2, fin: roles alternate and the tool_use still has its result
|
||||
assert_eq!(h.len(), 4);
|
||||
assert_eq!(h[0].role, Role::User);
|
||||
assert!(h[0].text().contains("SUM"));
|
||||
assert_eq!(h[1].role, Role::Assistant);
|
||||
assert!(matches!(h[2].content[0], ContentBlock::ToolResult { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transcript_truncates_long_tool_output() {
|
||||
let mut r = result("1");
|
||||
if let ContentBlock::ToolResult { content, .. } = &mut r.content[0] {
|
||||
*content = "z".repeat(2000);
|
||||
}
|
||||
let t = transcript(&[call("1"), r]);
|
||||
assert!(t.contains("TOOL CALL echo") && t.contains("TOOL RESULT"));
|
||||
assert!(t.len() < 1000 && t.contains('…'));
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
pub mod agent;
|
||||
pub mod command;
|
||||
pub mod compact;
|
||||
pub mod context;
|
||||
pub mod ext;
|
||||
pub mod hook;
|
||||
pub mod mask;
|
||||
pub mod session;
|
||||
pub mod stats;
|
||||
pub mod switch;
|
||||
pub mod tool;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Switching the agent's model or provider at runtime.
|
||||
//!
|
||||
//! A model id only means something to one provider, so changing the model can mean changing the
|
||||
//! provider too. And a new model has a new context window, so the compaction threshold has to
|
||||
//! follow. [`Switcher`] does all of that behind two calls; the TUI and the RPC server share it.
|
||||
|
||||
use crate::agent::Agent;
|
||||
use hx_ai::Provider;
|
||||
use hx_ai::auth::Kind;
|
||||
use hx_ai::models::{self, ModelInfo};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type MakeProvider = Box<dyn Fn(Kind) -> hx_ai::Result<Arc<dyn Provider>> + Send>;
|
||||
|
||||
/// What a switch did.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Switched {
|
||||
pub kind: Kind,
|
||||
pub model: String,
|
||||
/// The provider client was rebuilt, not just the model: provider-specific state (quota) is stale.
|
||||
pub provider_changed: bool,
|
||||
/// Context window of the new model, in tokens.
|
||||
pub window: u64,
|
||||
}
|
||||
|
||||
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 {
|
||||
Self {
|
||||
kind,
|
||||
models,
|
||||
make_provider,
|
||||
auto_compact,
|
||||
}
|
||||
}
|
||||
|
||||
/// The provider the agent currently uses.
|
||||
pub fn kind(&self) -> Kind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
/// Use model `id`, on whichever provider it belongs to (the current one if unknown).
|
||||
/// On error the agent and the switcher are unchanged.
|
||||
pub fn set_model(&mut self, agent: &mut Agent, id: &str) -> Result<Switched, String> {
|
||||
let kind = models::kind_of(&self.models, id).unwrap_or(self.kind);
|
||||
self.apply(agent, kind, id.to_string(), false)
|
||||
}
|
||||
|
||||
/// Use provider `kind` with its default model. The client is rebuilt even for the current
|
||||
/// provider, which picks up refreshed credentials after a re-login.
|
||||
pub fn set_provider(&mut self, agent: &mut Agent, kind: Kind) -> Result<Switched, String> {
|
||||
let model = models::default_for(kind, &self.models);
|
||||
self.apply(agent, kind, model, true)
|
||||
}
|
||||
|
||||
fn apply(
|
||||
&mut self,
|
||||
agent: &mut Agent,
|
||||
kind: Kind,
|
||||
model: String,
|
||||
rebuild: bool,
|
||||
) -> Result<Switched, String> {
|
||||
let provider_changed = rebuild || kind != self.kind;
|
||||
if provider_changed {
|
||||
let p = (self.make_provider)(kind).map_err(|e| e.to_string())?;
|
||||
agent.set_provider(p, model.as_str());
|
||||
self.kind = kind;
|
||||
} else {
|
||||
agent.set_model(model.as_str());
|
||||
}
|
||||
let window = models::window(&self.models, &model);
|
||||
if self.auto_compact {
|
||||
agent.fit_window(window);
|
||||
}
|
||||
Ok(Switched {
|
||||
kind,
|
||||
model,
|
||||
provider_changed,
|
||||
window,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::session::Session;
|
||||
use crate::tool::{Registry, ToolCtx};
|
||||
use std::sync::Mutex;
|
||||
|
||||
struct Nop;
|
||||
#[async_trait::async_trait]
|
||||
impl Provider for Nop {
|
||||
async fn stream(
|
||||
&self,
|
||||
_: hx_ai::Request,
|
||||
) -> hx_ai::Result<futures::stream::BoxStream<'static, hx_ai::Result<hx_ai::StreamEvent>>>
|
||||
{
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
fn catalog() -> Vec<ModelInfo> {
|
||||
let m = |id: &str, kind, w| ModelInfo {
|
||||
id: id.into(),
|
||||
kind,
|
||||
context_window: w,
|
||||
};
|
||||
vec![
|
||||
m("claude-sonnet-x", Kind::Claude, 200_000),
|
||||
m("claude-haiku-x", Kind::Claude, 100_000),
|
||||
m("gpt-x", Kind::Codex, 400_000),
|
||||
]
|
||||
}
|
||||
|
||||
/// Switcher whose factory records the kinds it was asked for, and an agent to switch.
|
||||
fn setup(
|
||||
auto: bool,
|
||||
fail: bool,
|
||||
) -> (Switcher, Agent, Arc<Mutex<Vec<Kind>>>, tempfile::TempDir) {
|
||||
let made = Arc::new(Mutex::new(vec![]));
|
||||
let m2 = made.clone();
|
||||
let sw = Switcher::new(
|
||||
Kind::Claude,
|
||||
catalog(),
|
||||
Box::new(move |k| {
|
||||
m2.lock().unwrap().push(k);
|
||||
if fail {
|
||||
Err(hx_ai::Error::Http("not logged in".into()))
|
||||
} else {
|
||||
Ok(Arc::new(Nop))
|
||||
}
|
||||
}),
|
||||
auto,
|
||||
);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut a, _h) = Agent::new(
|
||||
Arc::new(Nop),
|
||||
Registry::default(),
|
||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
a.set_model("claude-sonnet-x");
|
||||
(sw, a, made, dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_provider_keeps_it_and_refits_the_window() {
|
||||
let (mut sw, mut a, made, _d) = setup(true, false);
|
||||
let s = sw.set_model(&mut a, "claude-haiku-x").unwrap();
|
||||
assert_eq!(
|
||||
s,
|
||||
Switched {
|
||||
kind: Kind::Claude,
|
||||
model: "claude-haiku-x".into(),
|
||||
provider_changed: false,
|
||||
window: 100_000
|
||||
}
|
||||
);
|
||||
assert!(made.lock().unwrap().is_empty(), "no new provider needed");
|
||||
assert_eq!(a.model(), "claude-haiku-x");
|
||||
assert!(a.compact_at() <= 90_000, "threshold follows the window");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_of_another_provider_switches_provider() {
|
||||
let (mut sw, mut a, made, _d) = setup(true, false);
|
||||
let s = sw.set_model(&mut a, "gpt-x").unwrap();
|
||||
assert!(s.provider_changed && s.kind == Kind::Codex);
|
||||
assert_eq!(*made.lock().unwrap(), vec![Kind::Codex]);
|
||||
assert_eq!((sw.kind(), a.model()), (Kind::Codex, "gpt-x"));
|
||||
// back on the same provider: no second factory call
|
||||
sw.set_model(&mut a, "gpt-y-unknown").unwrap();
|
||||
assert_eq!(made.lock().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_switch_uses_its_default_model() {
|
||||
let (mut sw, mut a, _m, _d) = setup(true, false);
|
||||
let s = sw.set_provider(&mut a, Kind::Codex).unwrap();
|
||||
assert_eq!((s.model.as_str(), s.provider_changed), ("gpt-x", true));
|
||||
assert_eq!(a.model(), "gpt-x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_provider_switch_rebuilds_even_the_current_one() {
|
||||
let (mut sw, mut a, made, _d) = setup(true, false);
|
||||
let s = sw.set_provider(&mut a, Kind::Claude).unwrap();
|
||||
assert!(s.provider_changed, "fresh client, so quota is stale");
|
||||
assert_eq!(*made.lock().unwrap(), vec![Kind::Claude]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_changes_nothing() {
|
||||
let (mut sw, mut a, _m, _d) = setup(true, true);
|
||||
let before = a.compact_at();
|
||||
let e = sw.set_model(&mut a, "gpt-x").unwrap_err();
|
||||
assert!(e.contains("not logged in"), "{e}");
|
||||
assert_eq!(
|
||||
(sw.kind(), a.model(), a.compact_at()),
|
||||
(Kind::Claude, "claude-sonnet-x", before)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_threshold_is_left_alone() {
|
||||
let (mut sw, mut a, _m, _d) = setup(false, false);
|
||||
a.set_compact_at(12_345);
|
||||
sw.set_model(&mut a, "claude-haiku-x").unwrap();
|
||||
assert_eq!(a.compact_at(), 12_345);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user