Race the tool round against abort, check abort before starting tools, answer pending calls with an aborted result, deny permission prompts on abort, and kill the bash process group on drop. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1443 lines
47 KiB
Rust
1443 lines
47 KiB
Rust
use crate::compact;
|
|
use crate::hook::{Bus, Event};
|
|
use crate::session::Session;
|
|
use crate::tool::{Registry, ToolCtx};
|
|
use crate::window::{ContextPolicy, ContextWindow};
|
|
use futures::StreamExt;
|
|
use hx_ai::{ContentBlock, Message, Provider, Request, Role, StopReason, StreamEvent, Usage};
|
|
use std::sync::Arc;
|
|
use tokio::sync::watch;
|
|
|
|
pub struct Snap {
|
|
provider: Arc<dyn Provider>,
|
|
model: String,
|
|
system: String,
|
|
messages: Vec<Message>,
|
|
}
|
|
|
|
impl Snap {
|
|
pub async fn btw(&self, question: &str) -> Result<(String, Usage), Error> {
|
|
let mut messages = self.messages.clone();
|
|
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)
|
|
}
|
|
}
|
|
|
|
const REPEAT_HINT: &str = "\n[hx: this exact call returned the same result 3 times in a row; change approach or ask the user]";
|
|
|
|
#[derive(Default)]
|
|
struct Repeat {
|
|
last: u64,
|
|
n: u32,
|
|
}
|
|
|
|
impl Repeat {
|
|
fn seen(&mut self, name: &str, args: &serde_json::Value, content: &str) -> bool {
|
|
use std::hash::{Hash, Hasher};
|
|
if args.get("timeout").is_some() {
|
|
self.n = 0;
|
|
return false;
|
|
}
|
|
let mut h = std::collections::hash_map::DefaultHasher::new();
|
|
(name, args.to_string(), content).hash(&mut h);
|
|
let k = h.finish();
|
|
self.n = if self.n > 0 && k == self.last {
|
|
self.n + 1
|
|
} else {
|
|
1
|
|
};
|
|
self.last = k;
|
|
self.n >= 3
|
|
}
|
|
}
|
|
|
|
fn transient(status: u16) -> bool {
|
|
matches!(status, 408 | 429 | 500 | 502 | 503 | 529)
|
|
}
|
|
|
|
#[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(
|
|
"empty reply from the provider (stop: {0:?}), also on retry; try /compact or /model, or lower the effort"
|
|
)]
|
|
EmptyReply(StopReason),
|
|
#[error("max turns ({0}) reached")]
|
|
MaxTurns(u32),
|
|
}
|
|
|
|
pub const KEEP_MESSAGES: usize = 6;
|
|
|
|
pub struct Agent {
|
|
provider: Arc<dyn Provider>,
|
|
pub tools: Registry,
|
|
pub bus: Bus,
|
|
pub cx: ToolCtx,
|
|
model: String,
|
|
system: String,
|
|
max_tokens: u32,
|
|
effort: hx_ai::Effort,
|
|
max_turns: u32,
|
|
retry_ms: u64,
|
|
usage: Usage,
|
|
session: Session,
|
|
window: ContextWindow,
|
|
abort: watch::Receiver<bool>,
|
|
abort_tx: Arc<watch::Sender<bool>>,
|
|
snap: watch::Sender<Arc<Snap>>,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct AbortHandle(Arc<watch::Sender<bool>>);
|
|
impl AbortHandle {
|
|
pub fn abort(&self) {
|
|
let _ = self.0.send(true);
|
|
}
|
|
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 _ = 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,
|
|
retry_ms: 1000,
|
|
usage: Usage::default(),
|
|
session,
|
|
window: {
|
|
let mut w = ContextWindow::new(150_000);
|
|
w.set_reserve(16_384);
|
|
w
|
|
},
|
|
abort: rx,
|
|
abort_tx: tx.clone(),
|
|
snap,
|
|
};
|
|
(a, AbortHandle(tx))
|
|
}
|
|
|
|
pub fn snap(&self) -> watch::Receiver<Arc<Snap>> {
|
|
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
|
|
}
|
|
|
|
pub fn usage(&self) -> &Usage {
|
|
&self.usage
|
|
}
|
|
|
|
pub fn model(&self) -> &str {
|
|
&self.model
|
|
}
|
|
|
|
pub fn set_model(&mut self, model: impl Into<String>) {
|
|
self.model = model.into();
|
|
self.publish();
|
|
}
|
|
|
|
pub fn effort(&self) -> hx_ai::Effort {
|
|
self.effort
|
|
}
|
|
|
|
pub fn set_effort(&mut self, e: hx_ai::Effort) {
|
|
self.effort = e;
|
|
}
|
|
|
|
pub fn system(&self) -> &str {
|
|
&self.system
|
|
}
|
|
|
|
pub fn set_system(&mut self, system: impl Into<String>) {
|
|
self.system = system.into();
|
|
self.publish();
|
|
}
|
|
|
|
pub fn append_system(&mut self, section: &str) {
|
|
self.system.push_str("\n\n");
|
|
self.system.push_str(section);
|
|
self.publish();
|
|
}
|
|
|
|
pub fn set_max_tokens(&mut self, n: u32) {
|
|
self.max_tokens = n;
|
|
self.window.set_reserve(n);
|
|
}
|
|
|
|
pub fn compact_at(&self) -> usize {
|
|
self.window.compact_at()
|
|
}
|
|
|
|
pub fn context_tokens(&self) -> usize {
|
|
self.window.tokens(&self.session.messages())
|
|
}
|
|
|
|
pub fn set_context_policy(&mut self, p: ContextPolicy) {
|
|
self.window.set_policy(p);
|
|
}
|
|
|
|
pub fn set_model_window(&mut self, window: u64) {
|
|
self.window.set_model_window(window);
|
|
}
|
|
|
|
pub fn set_provider(&mut self, provider: Arc<dyn Provider>, model: impl Into<String>) {
|
|
self.provider = provider;
|
|
self.set_model(model);
|
|
}
|
|
|
|
pub fn replace_session(&mut self, session: Session) {
|
|
crate::herdr::set_session(session.path());
|
|
self.session = session;
|
|
self.window.reset();
|
|
self.publish();
|
|
}
|
|
|
|
pub fn fork(&mut self, id: u64) -> bool {
|
|
let ok = self.session.fork(id);
|
|
if ok {
|
|
self.window.reset();
|
|
self.publish();
|
|
}
|
|
ok
|
|
}
|
|
|
|
pub fn new_session(&mut self, dir: &std::path::Path) -> Result<(), Error> {
|
|
let s = Session::open(crate::session::new_path(dir))?;
|
|
self.replace_session(s);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn new_session_here(&mut self) -> Result<(), Error> {
|
|
let dir = self.session_dir().to_path_buf();
|
|
self.new_session(&dir)
|
|
}
|
|
|
|
pub fn resume(&mut self, path: &std::path::Path) -> Result<(), Error> {
|
|
self.replace_session(Session::open(path)?);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn session_dir(&self) -> &std::path::Path {
|
|
self.session
|
|
.path()
|
|
.parent()
|
|
.unwrap_or(std::path::Path::new("."))
|
|
}
|
|
|
|
pub async fn compact_now(&mut self) -> Result<bool, Error> {
|
|
self.compact(KEEP_MESSAGES).await
|
|
}
|
|
|
|
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.window.reset();
|
|
self.publish();
|
|
Ok(true)
|
|
}
|
|
|
|
fn push(&mut self, m: Message) -> Result<(), Error> {
|
|
self.session.append(m)?;
|
|
self.publish();
|
|
Ok(())
|
|
}
|
|
|
|
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 claude_tool(
|
|
&self,
|
|
id: String,
|
|
name: &str,
|
|
input: &serde_json::Value,
|
|
content: String,
|
|
is_error: bool,
|
|
) {
|
|
let (name, args) = crate::approve::hx_call(name, input);
|
|
let seen = self
|
|
.cx
|
|
.state
|
|
.claude_seen
|
|
.lock()
|
|
.unwrap_or_else(|e| e.into_inner())
|
|
.remove(&id);
|
|
if !seen {
|
|
self.emit(Event::ToolCall {
|
|
id: id.clone(),
|
|
name: name.clone(),
|
|
args: args.clone(),
|
|
})
|
|
.await;
|
|
}
|
|
crate::stats::log_claude_tool(
|
|
self.session.path(),
|
|
&name,
|
|
args.to_string().len(),
|
|
content.len(),
|
|
is_error,
|
|
);
|
|
self.emit(Event::ToolResult {
|
|
id,
|
|
name,
|
|
args,
|
|
content,
|
|
is_error,
|
|
})
|
|
.await;
|
|
}
|
|
|
|
async fn emit(&self, ev: Event) -> crate::hook::Outcome {
|
|
self.bus.emit(ev).await
|
|
}
|
|
|
|
async fn stream_retry(
|
|
&self,
|
|
req: Request,
|
|
) -> Result<futures::stream::BoxStream<'static, hx_ai::Result<StreamEvent>>, Error> {
|
|
let mut wait = self.retry_ms;
|
|
for attempt in 1..=4 {
|
|
let mut ab = self.abort.clone();
|
|
let r = tokio::select! {
|
|
r = self.provider.stream(req.clone()) => r,
|
|
_ = async { ab.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
|
|
};
|
|
match r {
|
|
Err(hx_ai::Error::Api { status, .. }) if attempt < 4 && transient(status) => {
|
|
self.emit(Event::Info(format!(
|
|
"api error {status}; retry {attempt}/3 in {wait}ms"
|
|
)))
|
|
.await;
|
|
let mut abort = self.abort.clone();
|
|
tokio::select! {
|
|
_ = tokio::time::sleep(std::time::Duration::from_millis(wait)) => {}
|
|
_ = async { abort.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
|
|
}
|
|
wait *= 4;
|
|
}
|
|
r => return Ok(r?),
|
|
}
|
|
}
|
|
unreachable!()
|
|
}
|
|
|
|
fn aborted(&self) -> bool {
|
|
*self.abort.borrow()
|
|
}
|
|
|
|
fn abort_calls(
|
|
&mut self,
|
|
calls: &[(String, String, serde_json::Value)],
|
|
) -> Result<Message, Error> {
|
|
let content = calls
|
|
.iter()
|
|
.map(|(id, ..)| ContentBlock::ToolResult {
|
|
tool_use_id: id.clone(),
|
|
content: "aborted by user".into(),
|
|
is_error: true,
|
|
})
|
|
.collect();
|
|
self.push(Message {
|
|
role: Role::User,
|
|
content,
|
|
})?;
|
|
Err(Error::Aborted)
|
|
}
|
|
|
|
pub async fn run(&mut self, prompt: impl Into<String>) -> Result<Message, Error> {
|
|
let r = self.run_inner(prompt.into()).await;
|
|
self.emit(Event::RunEnd {
|
|
aborted: matches!(r, Err(Error::Aborted)),
|
|
})
|
|
.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))?;
|
|
let mut empty_retries = 0;
|
|
let mut repeat = Repeat::default();
|
|
for _ in 0..self.max_turns {
|
|
if self.aborted() {
|
|
return Err(Error::Aborted);
|
|
}
|
|
let mut ab = self.abort.clone();
|
|
if self.window.should_compact(&self.session.messages())
|
|
&& tokio::select! {
|
|
r = self.compact(KEEP_MESSAGES) => r?,
|
|
_ = async { ab.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
|
|
}
|
|
{
|
|
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.stream_retry(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()));
|
|
}
|
|
if let StreamEvent::ToolRun { id, name, input, content, is_error } = ev {
|
|
self.claude_tool(id, &name, &input, content, is_error).await;
|
|
continue;
|
|
}
|
|
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 useful = msg.content.iter().any(|b| match b {
|
|
ContentBlock::Text { text } => !text.trim().is_empty(),
|
|
ContentBlock::ToolUse { .. } => true,
|
|
_ => false,
|
|
});
|
|
if !useful {
|
|
if empty_retries == 0 {
|
|
empty_retries += 1;
|
|
self.emit(Event::Info(format!(
|
|
"empty reply from the provider (stop: {stop:?}); retrying once"
|
|
)))
|
|
.await;
|
|
continue;
|
|
}
|
|
return Err(Error::EmptyReply(stop));
|
|
}
|
|
empty_retries = 0;
|
|
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;
|
|
}
|
|
|
|
if self.aborted() {
|
|
return self.abort_calls(&calls);
|
|
}
|
|
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 (ntx, mut nrx) = tokio::sync::mpsc::unbounded_channel::<String>();
|
|
*self
|
|
.cx
|
|
.state
|
|
.nested
|
|
.lock()
|
|
.unwrap_or_else(|e| e.into_inner()) = Some(ntx);
|
|
let outs = {
|
|
let round = self.tools.call_all(
|
|
runnable
|
|
.iter()
|
|
.map(|(_, n, a)| (n.clone(), a.clone()))
|
|
.collect(),
|
|
&self.cx,
|
|
);
|
|
tokio::pin!(round);
|
|
let mut ab = self.abort.clone();
|
|
loop {
|
|
tokio::select! {
|
|
outs = &mut round => break Some(outs),
|
|
Some(line) = nrx.recv() => { self.emit(Event::Info(line)).await; }
|
|
_ = async { ab.wait_for(|a| *a).await.is_ok() } => break None,
|
|
}
|
|
}
|
|
};
|
|
self.cx
|
|
.state
|
|
.nested
|
|
.lock()
|
|
.unwrap_or_else(|e| e.into_inner())
|
|
.take();
|
|
let Some(outs) = outs else {
|
|
return self.abort_calls(&calls);
|
|
};
|
|
while let Ok(line) = nrx.try_recv() {
|
|
self.emit(Event::Info(line)).await;
|
|
}
|
|
let mut images = vec![];
|
|
for ((i, name, args), mut r) in runnable.into_iter().zip(outs) {
|
|
images.append(&mut r.images);
|
|
let id = calls[i].0.clone();
|
|
if repeat.seen(&name, &args, &r.content) {
|
|
r.content.push_str(REPEAT_HINT);
|
|
}
|
|
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<ContentBlock> = results.into_iter().flatten().collect();
|
|
content.extend(
|
|
images
|
|
.into_iter()
|
|
.map(|(media_type, data)| ContentBlock::Image { media_type, data }),
|
|
);
|
|
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;
|
|
|
|
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 empty_reply_retries_once_and_is_not_stored() {
|
|
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
|
let mk = |v| {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let cx = ToolCtx {
|
|
cwd: dir.path().into(),
|
|
state: Default::default(),
|
|
};
|
|
let script = Arc::new(Script(Mutex::new(v), Mutex::new(vec![])));
|
|
let (a, _h) = Agent::new(
|
|
script,
|
|
Registry::default(),
|
|
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
|
cx,
|
|
);
|
|
(a, dir)
|
|
};
|
|
let (mut a, _d) = mk(vec![asst(vec![]), text("ok")]);
|
|
assert_eq!(a.run("p").await.unwrap().text(), "ok");
|
|
assert_eq!(a.session.messages().len(), 2);
|
|
let (mut a, _d) = mk(vec![asst(vec![]), asst(vec![])]);
|
|
assert!(matches!(a.run("p").await, Err(Error::EmptyReply(_))));
|
|
assert_eq!(a.session.messages().len(), 1);
|
|
}
|
|
|
|
#[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();
|
|
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 tool_images_follow_results_and_nested_notes_become_info() {
|
|
struct Pic;
|
|
#[async_trait]
|
|
impl Tool for Pic {
|
|
fn spec(&self) -> ToolSpec {
|
|
ToolSpec {
|
|
name: "pic".into(),
|
|
description: "".into(),
|
|
input_schema: json!({"type":"object"}),
|
|
}
|
|
}
|
|
async fn call(&self, _: Value, cx: &ToolCtx) -> ToolResult {
|
|
if let Some(tx) = cx.state.nested.lock().unwrap().as_ref() {
|
|
let _ = tx.send(" ↳ inner".into());
|
|
}
|
|
ToolResult::ok("a picture").with_images(vec![("image/png".into(), "QQ==".into())])
|
|
}
|
|
}
|
|
struct Notes(Arc<Mutex<Vec<String>>>);
|
|
#[async_trait]
|
|
impl Hook for Notes {
|
|
async fn on(&self, ev: &Event) -> HookAction {
|
|
if let Event::Info(s) = ev {
|
|
self.0.lock().unwrap().push(s.clone());
|
|
}
|
|
HookAction::Continue
|
|
}
|
|
}
|
|
let call = |name: &str| {
|
|
asst(vec![ContentBlock::ToolUse {
|
|
id: "1".into(),
|
|
name: name.into(),
|
|
input: json!({}),
|
|
}])
|
|
};
|
|
let script = Arc::new(Script(
|
|
Mutex::new(vec![
|
|
call("pic"),
|
|
asst(vec![ContentBlock::Text { text: "ok".into() }]),
|
|
]),
|
|
Mutex::new(vec![]),
|
|
));
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut tools = Registry::default();
|
|
tools.add(Pic);
|
|
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,
|
|
);
|
|
let notes = Arc::new(Mutex::new(vec![]));
|
|
a.bus.add(Notes(notes.clone()));
|
|
a.run("go").await.unwrap();
|
|
let reqs = script.1.lock().unwrap();
|
|
let turn = &reqs[1].messages[2];
|
|
assert!(
|
|
matches!(&turn.content[0], ContentBlock::ToolResult { content, .. } if content == "a picture")
|
|
);
|
|
assert_eq!(
|
|
turn.content[1],
|
|
ContentBlock::Image {
|
|
media_type: "image/png".into(),
|
|
data: "QQ==".into()
|
|
}
|
|
);
|
|
assert!(notes.lock().unwrap().iter().any(|n| n.contains("inner")));
|
|
}
|
|
|
|
#[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()
|
|
}
|
|
);
|
|
assert_eq!(
|
|
Session::open(dir.path().join("s.jsonl"))
|
|
.unwrap()
|
|
.messages()
|
|
.len(),
|
|
4
|
|
);
|
|
}
|
|
|
|
struct Flaky(Script, Mutex<u32>, u16);
|
|
#[async_trait]
|
|
impl Provider for Flaky {
|
|
async fn stream(
|
|
&self,
|
|
req: Request,
|
|
) -> hx_ai::Result<BoxStream<'static, hx_ai::Result<StreamEvent>>> {
|
|
let fail = {
|
|
let mut n = self.1.lock().unwrap();
|
|
let f = *n > 0;
|
|
*n = n.saturating_sub(1);
|
|
f
|
|
};
|
|
if fail {
|
|
self.0.1.lock().unwrap().push(req);
|
|
return Err(hx_ai::Error::Api {
|
|
status: self.2,
|
|
body: "x".into(),
|
|
});
|
|
}
|
|
self.0.stream(req).await
|
|
}
|
|
}
|
|
|
|
async fn flaky_run(fails: u32, status: u16) -> (Result<Message, Error>, usize) {
|
|
let p = Arc::new(Flaky(
|
|
Script(
|
|
Mutex::new(vec![asst(vec![ContentBlock::Text { text: "ok".into() }])]),
|
|
Mutex::new(vec![]),
|
|
),
|
|
Mutex::new(fails),
|
|
status,
|
|
));
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let cx = ToolCtx {
|
|
cwd: dir.path().into(),
|
|
state: Default::default(),
|
|
};
|
|
let (mut a, _h) = Agent::new(
|
|
p.clone(),
|
|
Registry::default(),
|
|
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
|
cx,
|
|
);
|
|
a.retry_ms = 1;
|
|
let r = a.run("go").await;
|
|
let n = p.0.1.lock().unwrap().len();
|
|
(r, n)
|
|
}
|
|
|
|
struct Hang;
|
|
#[async_trait]
|
|
impl Provider for Hang {
|
|
async fn stream(
|
|
&self,
|
|
_: Request,
|
|
) -> hx_ai::Result<BoxStream<'static, hx_ai::Result<StreamEvent>>> {
|
|
std::future::pending().await
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn abort_ends_a_request_that_never_answers() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let cx = ToolCtx {
|
|
cwd: dir.path().into(),
|
|
state: Default::default(),
|
|
};
|
|
let (mut a, h) = Agent::new(
|
|
Arc::new(Hang),
|
|
Registry::default(),
|
|
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
|
cx,
|
|
);
|
|
let t = tokio::spawn(async move {
|
|
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
|
h.abort();
|
|
});
|
|
let r = tokio::time::timeout(std::time::Duration::from_secs(5), a.run("go")).await;
|
|
t.await.unwrap();
|
|
assert!(matches!(r, Ok(Err(Error::Aborted))));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn transient_api_errors_are_retried() {
|
|
let (r, n) = flaky_run(1, 529).await;
|
|
assert!(r.is_ok());
|
|
assert_eq!(n, 2);
|
|
let (r, n) = flaky_run(9, 503).await;
|
|
assert!(matches!(
|
|
r,
|
|
Err(Error::Ai(hx_ai::Error::Api { status: 503, .. }))
|
|
));
|
|
assert_eq!(n, 4, "1 try + 3 retries");
|
|
let (r, n) = flaky_run(1, 400).await;
|
|
assert!(r.is_err());
|
|
assert_eq!(n, 1, "400 is not retried");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn identical_calls_get_a_hint_on_the_third() {
|
|
let mut script: Vec<Message> = (0..4)
|
|
.map(|i| asst(vec![tu(&i.to_string(), "x")]))
|
|
.collect();
|
|
script.push(asst(vec![ContentBlock::Text { text: "fin".into() }]));
|
|
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(
|
|
Arc::new(Script(Mutex::new(script), Mutex::new(vec![]))),
|
|
tools,
|
|
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
|
cx,
|
|
);
|
|
a.run("go").await.unwrap();
|
|
let hinted: Vec<bool> = a
|
|
.session
|
|
.messages()
|
|
.iter()
|
|
.flat_map(|m| m.content.iter())
|
|
.filter_map(|b| match b {
|
|
ContentBlock::ToolResult { content, .. } => {
|
|
Some(content.contains("same result 3 times"))
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(hinted, [false, false, true, true]);
|
|
}
|
|
|
|
#[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)));
|
|
}
|
|
|
|
struct Slow;
|
|
#[async_trait]
|
|
impl Tool for Slow {
|
|
fn spec(&self) -> ToolSpec {
|
|
ToolSpec {
|
|
name: "slow".into(),
|
|
description: "sleeps".into(),
|
|
input_schema: json!({"type":"object","properties":{}}),
|
|
}
|
|
}
|
|
async fn call(&self, _: Value, _: &crate::tool::ToolCtx) -> ToolResult {
|
|
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
|
|
ToolResult::ok("done")
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn abort_during_tool_round_stops_it_and_answers_the_calls() {
|
|
let p = Arc::new(Script(
|
|
Mutex::new(vec![
|
|
asst(vec![tu("1", "slow"), tu("2", "slow")]),
|
|
asst(vec![ContentBlock::Text { text: "ok".into() }]),
|
|
]),
|
|
Mutex::new(vec![]),
|
|
));
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut tools = Registry::default();
|
|
tools.add(Slow);
|
|
let cx = ToolCtx {
|
|
cwd: dir.path().into(),
|
|
state: Default::default(),
|
|
};
|
|
let (mut a, h) = Agent::new(
|
|
p.clone(),
|
|
tools,
|
|
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
|
cx,
|
|
);
|
|
tokio::spawn(async move {
|
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
|
h.abort();
|
|
});
|
|
let t = std::time::Instant::now();
|
|
assert!(matches!(a.run("go").await, Err(Error::Aborted)));
|
|
assert!(t.elapsed() < std::time::Duration::from_secs(5));
|
|
assert!(a.run("again").await.is_ok());
|
|
let reqs = p.1.lock().unwrap();
|
|
let last = &reqs[1].messages;
|
|
let results = last
|
|
.iter()
|
|
.flat_map(|m| &m.content)
|
|
.filter(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. }))
|
|
.count();
|
|
assert_eq!(results, 2);
|
|
}
|
|
|
|
#[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_context_policy(ContextPolicy::Fixed(1_000_000));
|
|
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));
|
|
|
|
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_context_policy(ContextPolicy::Fixed(3_000));
|
|
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<usize> = 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();
|
|
assert!(a.compact(3).await.unwrap());
|
|
let m = a.session().messages();
|
|
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 session_ops_share_one_path() {
|
|
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
|
let script = Arc::new(Script(Mutex::new(vec![text("r1")]), Mutex::new(vec![])));
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let sub = dir.path().join("sub");
|
|
let cx = ToolCtx {
|
|
cwd: dir.path().into(),
|
|
state: Default::default(),
|
|
};
|
|
let first = sub.join("a.jsonl");
|
|
let (mut a, _h) = Agent::new(
|
|
script,
|
|
Registry::default(),
|
|
Session::open(&first).unwrap(),
|
|
cx,
|
|
);
|
|
a.run("p1").await.unwrap();
|
|
assert_eq!(a.session_dir(), sub);
|
|
a.new_session_here().unwrap();
|
|
assert!(a.session().messages().is_empty());
|
|
assert_eq!(a.session().path().parent(), Some(sub.as_path()));
|
|
assert_ne!(a.session().path(), first);
|
|
assert_eq!(Session::open(&first).unwrap().messages().len(), 2);
|
|
a.resume(&first).unwrap();
|
|
assert_eq!(a.session().messages().len(), 2);
|
|
assert!(
|
|
a.resume(&dir.path().join("x").join("..").join("sub"))
|
|
.is_err()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn policy_is_order_independent() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let cx = ToolCtx {
|
|
cwd: dir.path().into(),
|
|
state: Default::default(),
|
|
};
|
|
let mk = |n| {
|
|
Agent::new(
|
|
Arc::new(Script(Mutex::new(vec![]), Mutex::new(vec![]))),
|
|
Registry::default(),
|
|
Session::open(dir.path().join(n)).unwrap(),
|
|
ToolCtx {
|
|
cwd: cx.cwd.clone(),
|
|
state: Default::default(),
|
|
},
|
|
)
|
|
.0
|
|
};
|
|
let (mut a, mut b) = (mk("a"), mk("b"));
|
|
a.set_context_policy(ContextPolicy::FromModel { window: 100_000 });
|
|
a.set_max_tokens(10_000);
|
|
b.set_max_tokens(10_000);
|
|
b.set_context_policy(ContextPolicy::FromModel { window: 100_000 });
|
|
assert_eq!((a.compact_at(), b.compact_at()), (90_000, 90_000));
|
|
b.set_max_tokens(95_000);
|
|
assert_eq!(b.compact_at(), 5_000, "reserve change is picked up");
|
|
b.set_context_policy(ContextPolicy::Fixed(7));
|
|
b.set_model_window(1_000_000);
|
|
assert_eq!(b.compact_at(), 7, "fixed ignores the model window");
|
|
}
|
|
|
|
#[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_context_policy(ContextPolicy::Fixed(5_000));
|
|
a.run("hi").await.unwrap();
|
|
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_context_policy(ContextPolicy::FromModel { window: 100_000 });
|
|
a.set_max_tokens(10_000);
|
|
assert_eq!(a.compact_at(), 90_000, "90% of the window");
|
|
a.set_model_window(20_000);
|
|
assert_eq!(a.compact_at(), 10_000, "leaves room for the reply");
|
|
}
|
|
}
|