#![expect(
clippy::print_stdout,
clippy::print_stderr,
reason = "an example shows on the terminal what it does"
)]
use std::{sync::Arc, time::Duration};
use haest::{
Agent, AgentDeps, AgentOptions, BoxError, JsonMap, LoopEvent, Message, SharedDeps,
ShutWorkspace, Tool, ToolContext, ToolError, ToolOutput, Tools, async_trait,
core::testing::{ScriptedProvider, text_answer, tool_answer},
serde_json::{Value, json},
session::{Body, Hub, Input, start},
wire::{Outbound, encode_line},
};
use tokio::sync::Notify;
struct Wait(Arc<Notify>);
#[async_trait]
impl Tool for Wait {
fn name(&self) -> &str {
"Wait"
}
fn description(&self) -> String {
"Waits until it is let go.".into()
}
fn parameters(&self) -> Value {
json!({"type": "object"})
}
fn kind(&self) -> &str {
"wait"
}
async fn execute(&self, _: JsonMap, _: &ToolContext) -> Result<ToolOutput, ToolError> {
self.0.notified().await;
Ok(ToolOutput::text("waited"))
}
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), BoxError> {
let go = Arc::new(Notify::new());
let model = ScriptedProvider::new([
tool_answer(&[("c1", "Wait", json!({}))]),
text_answer("Done, and I saw your note."),
]);
let tools = Tools::new().with(Wait(go.clone()));
let deps = AgentDeps::new(
SharedDeps::new(model.resolver(), "/", ShutWorkspace),
tools,
"",
);
let agent = Agent::new(deps, AgentOptions::new("scripted:m"));
let hub = Hub::new("example-stream");
let mut watcher = hub.subscribe(0);
let session = start(agent, hub);
let watching = tokio::spawn(async move {
while let Some(frame) = watcher.recv().await {
print!("{}", encode_line(&*frame));
}
});
let first = tokio::spawn({
let session = session.clone();
async move { session.turn(Input::human("wait, then answer")).await }
});
while model.requests().is_empty() {
tokio::task::yield_now().await;
}
let note = tokio::spawn({
let session = session.clone();
async move { session.turn(Input::human("also: the build is green")).await }
});
tokio::time::sleep(Duration::from_millis(20)).await;
go.notify_one();
for end in [first.await??, note.await??] {
assert!(end.error.is_none(), "{end:?}");
}
let history = session.history().await?.messages;
assert!(matches!(&history[3], Message::User(u) if u.content == "also: the build is green"));
assert_eq!(model.requests().len(), 2);
let mut late = session.subscribe(0);
let mut answer = String::new();
while let Some(frame) = late.recv().await {
match &frame.body {
Body::Loop(LoopEvent::Assistant { message }) => answer = message.text(),
Body::Loop(LoopEvent::TurnEnd { .. }) => break,
_ => {}
}
}
assert_eq!(answer, "Done, and I saw your note.");
let now = session.snapshot().await?;
eprintln!("{} messages, last seq {}", now.messages, now.last_seq);
session.close().await;
watching.await?;
while let Some(frame) = late.recv().await {
assert!(
matches!(frame.body, Body::Wire(Outbound::Status(_))),
"only the closing status is left"
);
}
Ok(())
}
#[test]
fn the_example_runs() -> Result<(), BoxError> {
main()
}