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
@@ -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('…'));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user