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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user