Files
hx/crates/hx-core/src/agent.rs
T
hermes 80c0f83a68
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
tokens: mask old large tool results in requests; compact inside a single long tool loop
2026-10-01 21:45:17 +00:00

625 lines
21 KiB
Rust

//! Agent loop: stream -> tool calls -> hooks -> results -> repeat.
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 {
pub 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,
/// 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)>,
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>>);
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,
last_ctx: None,
abort: rx,
abort_tx: tx.clone(),
};
(a, AbortHandle(tx))
}
pub fn abort_handle(&self) -> AbortHandle {
AbortHandle(self.abort_tx.clone())
}
/// 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 {
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 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)?;
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;
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 context_tokens(self.last_ctx, &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.last_ctx = Some((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)));
}
#[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() }]);
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);
}
}