Files
hx/crates/hx-core/src/agent.rs
T
johannes eaa6e22fbd
ci / check (push) Canceled after 0s
ci / check (pull_request) Canceled after 0s
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.
2026-10-02 00:10:41 +02:00

670 lines
22 KiB
Rust

//! 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};
use futures::StreamExt;
use hx_ai::{ContentBlock, Message, Provider, Request, Role, StopReason, StreamEvent, Usage};
use std::sync::Arc;
use tokio::sync::watch;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Ai(#[from] hx_ai::Error),
#[error("session: {0}")]
Io(#[from] std::io::Error),
#[error("aborted")]
Aborted,
#[error("stream ended without Done")]
Truncated,
#[error("max turns ({0}) reached")]
MaxTurns(u32),
}
pub struct Agent {
provider: Arc<dyn Provider>,
pub tools: Registry,
pub bus: Bus,
pub cx: ToolCtx,
model: String,
system: String,
max_tokens: u32,
max_turns: u32,
usage: Usage,
session: Session,
/// Auto-compact when the estimated context exceeds this many tokens.
compact_at: usize,
ctx: ContextMeter,
abort: watch::Receiver<bool>,
abort_tx: Arc<watch::Sender<bool>>,
}
/// Cheap handle to cancel a running `Agent::run`.
#[derive(Clone)]
pub struct AbortHandle(Arc<watch::Sender<bool>>);
impl AbortHandle {
pub fn abort(&self) {
let _ = self.0.send(true);
}
/// A handle not tied to any agent (tests, frontends before the agent exists).
pub fn detached() -> Self {
AbortHandle(Arc::new(watch::channel(false).0))
}
}
impl Agent {
pub fn new(
provider: Arc<dyn Provider>,
tools: Registry,
session: Session,
cx: ToolCtx,
) -> (Self, AbortHandle) {
let (tx, rx) = watch::channel(false);
let tx = Arc::new(tx);
let a = Self {
provider,
tools,
bus: Bus::default(),
cx,
model: String::new(),
system: String::new(),
max_tokens: 16_384,
max_turns: 200,
usage: Usage::default(),
session,
compact_at: 150_000,
ctx: ContextMeter::default(),
abort: rx,
abort_tx: tx.clone(),
};
(a, AbortHandle(tx))
}
pub fn abort_handle(&self) -> AbortHandle {
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 Some(plan) = compact::plan(&self.session.messages(), keep) else {
return Ok(false);
};
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? {
self.usage.add(&usage);
summary = Some(message.text());
}
}
let summary = summary.ok_or(Error::Truncated)?;
self.session.rebase(plan.apply(&summary))?;
self.ctx.reset();
Ok(true)
}
fn push(&mut self, m: Message) -> Result<(), Error> {
self.push_with(m, None)
}
fn push_with(&mut self, m: Message, usage: Option<Usage>) -> Result<(), Error> {
let by = (m.role == Role::Assistant).then(|| self.model.clone());
self.session.append_full(m, by, usage)?;
Ok(())
}
async fn emit(&self, ev: Event) -> crate::hook::Outcome {
self.bus.emit(ev).await
}
fn aborted(&self) -> bool {
*self.abort.borrow()
}
/// Run until the model stops calling tools (and no hook injects more work).
/// An abort ends this run only; the next `run` starts un-aborted.
pub async fn run(&mut self, prompt: impl Into<String>) -> Result<Message, Error> {
let r = self.run_inner(prompt.into()).await;
self.abort_tx
.send_if_modified(|a| std::mem::replace(a, false));
r
}
async fn run_inner(&mut self, prompt: String) -> Result<Message, Error> {
self.push(Message::user(prompt))?;
for _ in 0..self.max_turns {
if self.aborted() {
return Err(Error::Aborted);
}
if self.ctx.tokens(&self.session.messages()) > self.compact_at
&& self.compact(6).await?
{
self.emit(Event::Info("context compacted".into())).await;
}
self.emit(Event::TurnStart).await;
let req = Request {
model: self.model.clone(),
system: self.system.clone(),
messages: crate::mask::mask_old_results(self.session.messages()),
tools: self.tools.specs(),
max_tokens: self.max_tokens,
};
let mut s = self.provider.stream(req).await?;
let mut done = None;
let mut abort = self.abort.clone();
loop {
tokio::select! {
ev = s.next() => match ev {
Some(ev) => {
let ev = ev?;
if let StreamEvent::Done { message, stop, usage } = &ev {
done = Some((message.clone(), *stop, usage.clone()));
}
self.emit(Event::Stream(ev)).await;
}
None => break,
},
_ = async { abort.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
}
}
let (msg, stop, usage) = done.ok_or(Error::Truncated)?;
self.usage.add(&usage);
let total = (usage.input_tokens
+ usage.cache_read_tokens
+ usage.cache_write_tokens
+ usage.output_tokens) as usize;
self.push_with(msg.clone(), Some(usage))?;
self.ctx.record(total, self.session.messages().len());
self.emit(Event::Message(msg.clone())).await;
let calls: Vec<(String, String, serde_json::Value)> = msg
.content
.iter()
.filter_map(|b| match b {
ContentBlock::ToolUse { id, name, input } => {
Some((id.clone(), name.clone(), input.clone()))
}
_ => None,
})
.collect();
if calls.is_empty() {
let o = self.emit(Event::AgentEnd).await;
if o.inject.is_empty() || stop == StopReason::MaxTokens {
return Ok(msg);
}
self.emit(Event::Injected(o.inject.clone())).await;
self.push(Message::user(o.inject.join("\n\n")))?;
continue;
}
// pre-hooks decide block / mutate per call
let mut results: Vec<Option<ContentBlock>> = vec![None; calls.len()];
let mut runnable = vec![];
for (i, (id, name, args)) in calls.iter().enumerate() {
let o = self
.emit(Event::ToolCall {
id: id.clone(),
name: name.clone(),
args: args.clone(),
})
.await;
match o.blocked {
Some(r) => {
let content = format!("blocked: {r}");
self.emit(Event::ToolResult {
id: id.clone(),
name: name.clone(),
args: args.clone(),
content: content.clone(),
is_error: true,
})
.await;
results[i] = Some(ContentBlock::ToolResult {
tool_use_id: id.clone(),
content,
is_error: true,
})
}
None => {
runnable.push((i, name.clone(), o.args.unwrap_or_else(|| args.clone())))
}
}
}
let outs = self
.tools
.call_all(
runnable
.iter()
.map(|(_, n, a)| (n.clone(), a.clone()))
.collect(),
&self.cx,
)
.await;
for ((i, name, args), r) in runnable.into_iter().zip(outs) {
let id = calls[i].0.clone();
self.emit(Event::ToolResult {
id: id.clone(),
name,
args,
content: r.content.clone(),
is_error: r.is_error,
})
.await;
results[i] = Some(ContentBlock::ToolResult {
tool_use_id: id,
content: r.content,
is_error: r.is_error,
});
}
let mut content: Vec<ContentBlock> = results.into_iter().flatten().collect();
let o = self.emit(Event::TurnEnd).await;
if !o.inject.is_empty() {
self.emit(Event::Injected(o.inject.clone())).await;
}
content.extend(o.inject.into_iter().map(|text| ContentBlock::Text { text }));
self.push(Message {
role: Role::User,
content,
})?;
}
Err(Error::MaxTurns(self.max_turns))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hook::{Hook, HookAction};
use crate::tool::{Tool, ToolResult};
use async_trait::async_trait;
use futures::stream::BoxStream;
use hx_ai::ToolSpec;
use serde_json::{Value, json};
use std::sync::Mutex;
/// Replays scripted assistant messages; records requests.
struct Script(Mutex<Vec<Message>>, Mutex<Vec<Request>>);
#[async_trait]
impl Provider for Script {
async fn stream(
&self,
req: Request,
) -> hx_ai::Result<BoxStream<'static, hx_ai::Result<StreamEvent>>> {
self.1.lock().unwrap().push(req);
let m = self.0.lock().unwrap().remove(0);
let stop = if m
.content
.iter()
.any(|b| matches!(b, ContentBlock::ToolUse { .. }))
{
StopReason::ToolUse
} else {
StopReason::EndTurn
};
let evs = vec![
Ok(StreamEvent::TextDelta { text: m.text() }),
Ok(StreamEvent::Done {
message: m,
stop,
usage: Usage {
input_tokens: 1,
output_tokens: 2,
..Default::default()
},
}),
];
Ok(futures::stream::iter(evs).boxed())
}
}
struct Echo;
#[async_trait]
impl Tool for Echo {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: "echo".into(),
description: "".into(),
input_schema: json!({"type":"object"}),
}
}
async fn call(&self, a: Value, _: &ToolCtx) -> ToolResult {
ToolResult::ok(a["s"].as_str().unwrap_or_default())
}
}
struct Guard;
#[async_trait]
impl Hook for Guard {
async fn on(&self, ev: &Event) -> HookAction {
match ev {
Event::ToolCall { args, .. } if args["s"] == "bad" => {
HookAction::Block("nope".into())
}
Event::TurnEnd => HookAction::Inject("lens: ok".into()),
_ => HookAction::Continue,
}
}
}
fn asst(blocks: Vec<ContentBlock>) -> Message {
Message {
role: Role::Assistant,
content: blocks,
}
}
fn tu(id: &str, s: &str) -> ContentBlock {
ContentBlock::ToolUse {
id: id.into(),
name: "echo".into(),
input: json!({"s": s}),
}
}
#[tokio::test]
async fn multi_turn_with_hooks() {
let script = Arc::new(Script(
Mutex::new(vec![
asst(vec![tu("1", "hi"), tu("2", "bad")]),
asst(vec![ContentBlock::Text {
text: "done".into(),
}]),
]),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
let mut tools = Registry::default();
tools.add(Echo);
let cx = ToolCtx {
cwd: dir.path().into(),
state: Default::default(),
};
let (mut a, _h) = Agent::new(
script.clone(),
tools,
Session::open(dir.path().join("s.jsonl")).unwrap(),
cx,
);
a.bus.add(Guard);
let out = a.run("go").await.unwrap();
assert_eq!(out.text(), "done");
assert_eq!(a.usage.output_tokens, 4);
let reqs = script.1.lock().unwrap();
assert_eq!(reqs.len(), 2);
let turn = &reqs[1].messages[2];
assert_eq!(
turn.content[0],
ContentBlock::ToolResult {
tool_use_id: "1".into(),
content: "hi".into(),
is_error: false
}
);
assert!(
matches!(&turn.content[1], ContentBlock::ToolResult { is_error: true, content, .. } if content.contains("nope"))
);
assert_eq!(
turn.content[2],
ContentBlock::Text {
text: "lens: ok".into()
}
);
// resumable from disk
assert_eq!(
Session::open(dir.path().join("s.jsonl"))
.unwrap()
.messages()
.len(),
4
);
}
#[tokio::test]
async fn abort_and_max_turns() {
let loop_forever = Arc::new(Script(
Mutex::new(
(0..5)
.map(|i| asst(vec![tu(&i.to_string(), "x")]))
.collect(),
),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
let mut tools = Registry::default();
tools.add(Echo);
let cx = ToolCtx {
cwd: dir.path().into(),
state: Default::default(),
};
let (mut a, h) = Agent::new(
loop_forever,
tools,
Session::open(dir.path().join("s.jsonl")).unwrap(),
cx,
);
a.max_turns = 2;
assert!(matches!(a.run("go").await, Err(Error::MaxTurns(2))));
h.abort();
assert!(matches!(a.run("again").await, Err(Error::Aborted)));
}
#[tokio::test]
async fn compaction_inside_tool_loop() {
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
let script = Arc::new(Script(
Mutex::new(vec![
asst(vec![tu("1", "a")]),
asst(vec![tu("2", "b")]),
text("fin"),
text("SUMMARY"),
text("next"),
]),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
let mut tools = Registry::default();
tools.add(Echo);
let cx = ToolCtx {
cwd: dir.path().into(),
state: Default::default(),
};
let (mut a, _h) = Agent::new(
script.clone(),
tools,
Session::open(dir.path().join("s.jsonl")).unwrap(),
cx,
);
a.run("go").await.unwrap(); // p, a1, r1, a2, r2, fin
assert!(a.compact(3).await.unwrap());
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);
assert!(m[0].text().contains("SUMMARY"));
assert_eq!(m[1].role, Role::Assistant);
assert!(matches!(m[2].content[0], ContentBlock::ToolResult { .. }));
}
#[tokio::test]
async fn compaction() {
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
let script = Arc::new(Script(
Mutex::new(vec![text("r1"), text("r2"), text("SUMMARY"), text("r3")]),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
let cx = ToolCtx {
cwd: dir.path().into(),
state: Default::default(),
};
let path = dir.path().join("s.jsonl");
let (mut a, _h) = Agent::new(
script.clone(),
Registry::default(),
Session::open(&path).unwrap(),
cx,
);
a.run("p1").await.unwrap();
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();
assert_eq!(m.len(), 2);
assert!(m[0].text().contains("SUMMARY") && m[0].text().ends_with("p2"));
{
let reqs = script.1.lock().unwrap();
let t = reqs[2].messages[0].text();
assert!(t.contains("USER: p1") && t.contains("ASSISTANT: r1") && !t.contains("p2"));
}
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");
}
}