use std::{process::ExitCode, time::Duration};
use haest::{
AgentControl, LoopEvent, StopReason, TurnEnd,
runtime::{Host, session_usd, world::kill_jobs},
tools::JobHub,
};
use tokio::{sync::oneshot, task::JoinHandle};
use crate::term::Runtime;
const SETTLE_POLL: Duration = Duration::from_millis(250);
const QUIT_GRACE: Duration = Duration::from_secs(1);
const QUIT_POLL: Duration = Duration::from_millis(20);
async fn wind_down(
ended: impl Future<Output = ()>,
host: &Host,
jobs: Option<&JobHub>,
grace: Duration,
) {
let _ = tokio::time::timeout(grace, ended).await;
if let Some(jobs) = jobs {
kill_jobs(jobs).await;
}
let _ = tokio::time::timeout(grace, host.flush()).await;
}
async fn turn_ended(control: &AgentControl) {
while control.running() {
tokio::time::sleep(QUIT_POLL).await;
}
}
fn watch_interrupts(rt: &Runtime, mut done: oneshot::Receiver<()>) -> JoinHandle<()> {
let control = rt.agent.control();
let host = rt.host.clone();
let jobs = rt.jobs.clone();
tokio::spawn(async move {
let mut asked = false;
loop {
tokio::select! {
_ = &mut done => return,
signal = tokio::signal::ctrl_c() => {
if signal.is_err() {
return;
}
control.abort();
if asked {
wind_down(turn_ended(&control), &host, jobs.as_deref(), QUIT_GRACE).await;
std::process::exit(130);
}
asked = true;
host.warn("Stopping the turn... (Ctrl+C again to quit)");
}
}
}
})
}
pub async fn turn(rt: &mut Runtime, input: &str) -> TurnEnd {
let term = rt.ui.term.clone();
let (done, watching) = oneshot::channel();
let watcher = watch_interrupts(rt, watching);
let control = rt.agent.control();
let mut usage = None;
let mut sink = |ev: LoopEvent| {
if let LoopEvent::TurnEnd { usage: u, .. } = &ev {
usage = Some(u.clone());
}
term.lock().unwrap().event(&ev);
};
let end = {
let run = rt.agent.run(input, &mut sink);
tokio::pin!(run);
loop {
tokio::select! {
end = &mut run => break end,
Some(text) = rt.inbox.arrival() => control.steer(text),
}
}
};
let _ = done.send(());
let _ = watcher.await;
if let Some(u) = usage {
let total = session_usd(&rt.agent);
rt.ui.term.lock().unwrap().usage(&u, total);
}
rt.host.flush().await;
end
}
pub async fn human(rt: &mut Runtime, input: &str) -> TurnEnd {
let text = rt.mods.rewrite_prompt(input).await;
let text = rt.inbox.human(&text);
turn(rt, &text).await
}
pub async fn agent_turns(rt: &mut Runtime) {
while let Some(text) = rt.inbox.take(&rt.agent.control()) {
if let Some(text) = rt.inbox.agent_turn(&text) {
turn(rt, &text).await;
}
}
}
pub async fn settle(rt: &mut Runtime) {
loop {
agent_turns(rt).await;
if rt.agents.answers_due() == 0 && rt.inbox.waiting() == 0 {
return;
}
tokio::select! {
_ = rt.inbox.wait() => {}
_ = tokio::time::sleep(SETTLE_POLL) => {}
_ = tokio::signal::ctrl_c() => {
rt.host.warn("Stopping the subagents.");
rt.agents.stop_all();
return;
}
}
}
}
pub fn exit_code(end: &TurnEnd) -> ExitCode {
match end.stop_reason {
StopReason::Aborted => ExitCode::from(130),
StopReason::EndTurn if end.error.is_none() => ExitCode::SUCCESS,
_ => ExitCode::FAILURE,
}
}
#[cfg(test)]
mod tests {
use std::{path::Path, sync::Arc, time::Instant};
use haest::{
Message, ToolResultMessage,
core::fs::{Fs, MemFs},
session::{JsonlSessionFile, SessionRecord},
settings::Settings,
};
use super::*;
use crate::term::TermUi;
async fn host_over(fs: &Arc<MemFs>) -> Arc<Host> {
let store = JsonlSessionFile::new(fs.clone(), Path::new("/data"), "s").unwrap();
store.create("s", "/w", 0).await.unwrap();
let ui = Arc::new(TermUi::new(false));
Arc::new(Host::new(Settings::bare("/w", "/h"), ui, Arc::new(store)))
}
fn answer(text: &str) -> SessionRecord {
let result = ToolResultMessage {
tool_call_id: "c".into(),
tool_name: "Bash".into(),
content: text.into(),
is_error: true,
media: vec![],
};
SessionRecord::Message {
t: 1,
message: Message::Tool(result),
}
}
#[tokio::test]
async fn the_second_ctrl_c_lands_the_turns_answers_before_haest_exits() {
let fs = Arc::new(MemFs::new());
let host = host_over(&fs).await;
host.append(answer("queued before the second Ctrl+C"));
let turn = host.clone();
let ends = async move {
tokio::time::sleep(Duration::from_millis(30)).await;
turn.append(answer("Interrupted by the user."));
};
wind_down(ends, &host, None, Duration::from_secs(5)).await;
let file = fs
.read_to_string(Path::new("/data/sessions/s.jsonl"))
.await
.unwrap();
assert!(file.contains("queued before the second Ctrl+C"), "{file}");
assert!(file.contains("Interrupted by the user."), "{file}");
let started = Instant::now();
wind_down(
std::future::pending(),
&host,
None,
Duration::from_millis(50),
)
.await;
assert!(
started.elapsed() < Duration::from_secs(2),
"a turn that never ends holds the exit only for the grace"
);
}
#[test]
fn only_a_clean_answer_exits_zero() {
let code = |r, e: Option<&str>| {
let mut end = TurnEnd::new(r);
end.error = e.map(String::from);
exit_code(&end)
};
assert_eq!(code(StopReason::EndTurn, None), ExitCode::SUCCESS);
assert_eq!(code(StopReason::EndTurn, Some("cap")), ExitCode::FAILURE);
assert_eq!(code(StopReason::Error, None), ExitCode::FAILURE);
assert_eq!(code(StopReason::Aborted, None), ExitCode::from(130));
}
}