//! Agent loop: stream -> tool calls -> hooks -> results -> repeat. use crate::compact; use crate::hook::{Bus, Event}; use crate::session::Session; use crate::tool::{Registry, ToolCtx}; use crate::window::ContextWindow; use futures::StreamExt; use hx_ai::{ContentBlock, Message, Provider, Request, Role, StopReason, StreamEvent, Usage}; use std::sync::Arc; use tokio::sync::watch; /// What `/btw` needs, readable while a run holds the agent lock. pub struct Snap { provider: Arc, model: String, system: String, messages: Vec, } impl Snap { /// One tool-less request on the conversation so far plus `question`; nothing is saved. /// Returns the answer and the request's usage. pub async fn btw(&self, question: &str) -> Result<(String, Usage), Error> { let mut messages = self.messages.clone(); // a run in flight may end on tool calls whose results are not in yet if messages.last().is_some_and(|m| { m.role == Role::Assistant && m.content .iter() .any(|b| matches!(b, ContentBlock::ToolUse { .. })) }) { messages.pop(); } let q = ContentBlock::Text { text: format!( "Side question; answer briefly from the conversation so far, without tools:\n{question}" ), }; match messages.last_mut() { Some(m) if m.role == Role::User => m.content.push(q), _ => messages.push(Message { role: Role::User, content: vec![q], }), } let req = Request { model: self.model.clone(), system: self.system.clone(), messages, tools: vec![], max_tokens: 2048, effort: hx_ai::Effort::Off, }; let mut s = self.provider.stream(req).await?; while let Some(ev) = s.next().await { if let StreamEvent::Done { message, usage, .. } = ev? { return Ok((message.text(), usage)); } } Err(Error::Truncated) } } #[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, pub tools: Registry, pub bus: Bus, pub cx: ToolCtx, model: String, system: String, max_tokens: u32, effort: hx_ai::Effort, max_turns: u32, usage: Usage, session: Session, window: ContextWindow, abort: watch::Receiver, abort_tx: Arc>, snap: watch::Sender>, } /// Cheap handle to cancel a running `Agent::run`. #[derive(Clone)] pub struct AbortHandle(Arc>); 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, tools: Registry, session: Session, cx: ToolCtx, ) -> (Self, AbortHandle) { let (tx, rx) = watch::channel(false); let tx = Arc::new(tx); let _ = cx.state.abort.set(rx.clone()); let snap = watch::channel(Arc::new(Snap { provider: provider.clone(), model: String::new(), system: String::new(), messages: session.messages(), })) .0; let a = Self { provider, tools, bus: Bus::default(), cx, model: String::new(), system: String::new(), max_tokens: 16_384, effort: hx_ai::Effort::Off, max_turns: 200, usage: Usage::default(), session, window: ContextWindow::new(150_000), abort: rx, abort_tx: tx.clone(), snap, }; (a, AbortHandle(tx)) } /// Live view for `/btw`; stays readable while `run` holds the agent. pub fn snap(&self) -> watch::Receiver> { self.snap.subscribe() } fn publish(&self) { self.snap.send_replace(Arc::new(Snap { provider: self.provider.clone(), model: self.model.clone(), system: self.system.clone(), messages: self.session.messages(), })); } pub fn set_max_turns(&mut self, n: u32) { self.max_turns = n; } 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) { self.model = model.into(); self.publish(); } pub fn effort(&self) -> hx_ai::Effort { self.effort } /// Thinking level for the following requests. pub fn set_effort(&mut self, e: hx_ai::Effort) { self.effort = e; } pub fn set_system(&mut self, system: impl Into) { self.system = system.into(); self.publish(); } /// 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); self.publish(); } /// 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.window.compact_at() } /// Size of the current context in tokens: the provider's last reading plus an estimate of /// what came after. The number that triggers auto-compaction. pub fn context_tokens(&self) -> usize { self.window.tokens(&self.session.messages()) } /// Auto-compact once the context exceeds `n` tokens. pub fn set_compact_at(&mut self, n: usize) { self.window.set_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.window .set_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, model: impl Into) { 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.window.reset(); self.publish(); } /// 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.window.reset(); self.publish(); } ok } /// Start over: empty the conversation, keeping the session file's history. pub fn clear(&mut self) -> Result<(), Error> { self.session.rebase(vec![])?; self.window.reset(); self.publish(); 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 { 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.window.reset(); self.publish(); Ok(true) } fn push(&mut self, m: Message) -> Result<(), Error> { self.session.append(m)?; self.publish(); Ok(()) } /// Append the assistant reply with the model, usage and masking boundary of its request. fn push_reply(&mut self, m: Message, usage: Usage, mask: usize) -> Result<(), Error> { let by = Some(self.model.clone()); self.session.append_masked(m, by, Some(usage), Some(mask))?; self.publish(); 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) -> Result { 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 { self.push(Message::user(prompt))?; for _ in 0..self.max_turns { if self.aborted() { return Err(Error::Aborted); } if self.window.should_compact(&self.session.messages()) && self.compact(6).await? { self.emit(Event::Info("context compacted".into())).await; } self.emit(Event::TurnStart).await; let view = self.window.view(self.session.messages()); let req = Request { model: self.model.clone(), system: self.system.clone(), messages: view.messages, tools: self.tools.specs(), max_tokens: self.max_tokens, effort: self.effort, }; 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_reply(msg.clone(), usage, view.mask)?; self.window.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> = 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 sub = std::mem::take( &mut *self .cx .state .sub_usage .lock() .unwrap_or_else(|e| e.into_inner()), ); if sub != Usage::default() { self.usage.add(&sub); self.emit(Event::SubUsage(sub)).await; } let mut content: Vec = 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>, Mutex>); #[async_trait] impl Provider for Script { async fn stream( &self, req: Request, ) -> hx_ai::Result>> { 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) -> 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 btw_reads_snapshot_without_touching_session() { let script = Arc::new(Script( Mutex::new(vec![ asst(vec![ContentBlock::Text { text: "done".into(), }]), asst(vec![ContentBlock::Text { text: "side".into(), }]), ]), 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("s.jsonl")).unwrap(), cx, ); let snap = a.snap(); a.run("go").await.unwrap(); let before = a.session().messages().len(); // taken from the receiver, no agent access: works while `run` holds the lock let s = snap.borrow().clone(); let (text, _) = s.btw("why?").await.unwrap(); assert_eq!(text, "side"); assert_eq!(a.session().messages().len(), before); let reqs = script.1.lock().unwrap(); let r = &reqs[1]; assert!(r.tools.is_empty()); assert_eq!(r.messages.len(), 3); assert!(r.messages[2].text().contains("why?")); } #[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 mask_boundary_waits_for_big_context_and_is_recorded() { let big = "z".repeat(8000); let mut script = vec![]; for i in 0..20 { script.push(asst(vec![tu(&i.to_string(), &big)])); } script.push(asst(vec![ContentBlock::Text { text: "fin".into() }])); let script = Arc::new(Script(Mutex::new(script), 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.set_compact_at(1_000_000); // capped at 60k tokens: this run stays below it a.run("go").await.unwrap(); let elided = |r: &Request| { r.messages.iter().any(|m| { m.content.iter().any(|b| matches!(b, ContentBlock::ToolResult { content, .. } if content.starts_with("[elided"))) }) }; assert!(!script.1.lock().unwrap().iter().any(elided)); assert!(a.session().masks().iter().flatten().all(|&b| b == 0)); // same run with a small threshold: masks, boundary only grows and is recorded let mut v = vec![]; for i in 0..20 { v.push(asst(vec![tu(&i.to_string(), &big)])); } v.push(asst(vec![ContentBlock::Text { text: "fin".into() }])); let script = Arc::new(Script(Mutex::new(v), Mutex::new(vec![]))); let mut tools = Registry::default(); tools.add(Echo); let cx = ToolCtx { cwd: dir.path().into(), state: Default::default(), }; let (mut b, _h) = Agent::new( script.clone(), tools, Session::open(dir.path().join("s2.jsonl")).unwrap(), cx, ); b.set_compact_at(3_000); // a third = 1k tokens, below the cap b.run("go").await.unwrap(); assert!(script.1.lock().unwrap().iter().any(elided)); assert!( script.1.lock().unwrap().iter().all(|r| r.tools.len() == 1), "no compaction request expected" ); let m: Vec = b.session().masks().into_iter().flatten().collect(); assert!( m.windows(2).all(|w| w[0] <= w[1]) && *m.last().unwrap() > 0, "{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); } #[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.set_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"); } }