#![expect(
clippy::print_stdout,
clippy::print_stderr,
reason = "an example shows on the terminal what it does"
)]
use haest::{
Agent, AgentDeps, AgentOptions, BoxError, JsonMap, SharedDeps, ShutWorkspace, Tool,
ToolContext, ToolError, ToolOutput, Tools, async_trait,
core::testing::{ScriptedProvider, text_answer, tool_answer},
serde_json::{self, Value, json},
session::{Hub, start},
transport::{Grant, LineSource, NdjsonSource, Stdio},
wire::Origin,
};
use tokio::io::{AsyncWriteExt, DuplexStream};
struct Forever;
#[async_trait]
impl Tool for Forever {
fn name(&self) -> &str {
"Forever"
}
fn description(&self) -> String {
"Runs until it is stopped.".into()
}
fn parameters(&self) -> Value {
json!({"type": "object"})
}
fn kind(&self) -> &str {
"wait"
}
async fn execute(&self, _: JsonMap, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
ctx.cancel().cancelled().await;
Ok(ToolOutput::text("stopped"))
}
}
struct Parent {
to_child: DuplexStream,
from_child: NdjsonSource<DuplexStream>,
}
impl Parent {
async fn send(&mut self, request: Value) -> Result<(), BoxError> {
let line = format!("{request}\n");
self.to_child.write_all(line.as_bytes()).await?;
Ok(())
}
async fn until(&mut self, stop: impl Fn(&Value) -> bool) -> Result<Value, BoxError> {
loop {
let line = self
.from_child
.next_line()
.await
.ok_or("the child hung up")??;
let frame: Value = serde_json::from_str(&line)?;
println!("{line}");
if stop(&frame) {
return Ok(frame);
}
}
}
async fn reply(&mut self, id: &str) -> Result<Value, BoxError> {
self.until(|f| f["type"] == "reply" && f["id"] == id).await
}
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), BoxError> {
let model = ScriptedProvider::new([
text_answer("Hello from the child."),
tool_answer(&[("c1", "Forever", json!({}))]),
]);
let tools = Tools::new().with(Forever);
let deps = AgentDeps::new(
SharedDeps::new(model.resolver(), "/", ShutWorkspace),
tools,
"",
);
let agent = Agent::new(deps, AgentOptions::new("scripted:m"));
let session = start(agent, Hub::new("example-stream"));
let (to_child, child_stdin) = tokio::io::duplex(1 << 16);
let (child_stdout, from_child) = tokio::io::duplex(1 << 16);
let attached =
Stdio::new(child_stdin, child_stdout).attach(session, Grant::command(Origin::Human));
let mut parent = Parent {
to_child,
from_child: NdjsonSource::new(from_child),
};
let hello = parent.until(|f| f["type"] == "hello").await?;
assert_eq!(hello["access"], "command");
parent
.send(json!({"v": 1, "id": "t1", "type": "turn", "text": "say hello"}))
.await?;
let reply = parent.reply("t1").await?;
assert_eq!(reply["result"]["stopReason"], "end_turn");
parent
.send(json!({"v": 1, "id": "t2", "type": "turn", "text": "run forever"}))
.await?;
parent.until(|f| f["type"] == "assistant").await?;
parent
.send(json!({"v": 1, "id": "c1", "type": "control", "verb": "interrupt"}))
.await?;
let reply = parent.reply("t2").await?;
assert_eq!(reply["result"]["stopReason"], "aborted");
parent
.send(json!({"v": 1, "id": "x", "type": "control", "verb": "close"}))
.await?;
parent.reply("x").await?;
eprintln!("ended: {}", attached.ended().await);
Ok(())
}
#[test]
fn the_example_runs() -> Result<(), BoxError> {
main()
}