#![expect(
clippy::print_stdout,
clippy::print_stderr,
reason = "`haest ctl` answers on the terminal"
)]
use std::{path::Path, process::ExitCode, time::Duration};
use haest::{
core::{error::report, session::iso_utc},
session::{Body, Frame},
transport::{TransportError, UnixPeer, connect_session, running_sessions},
wire::{Control, Outbound, Request},
};
use serde_json::{Value, json};
use crate::{
args::Ctl,
render::{Renderer, inert},
};
const ANSWER_WAIT: Duration = Duration::from_secs(10);
pub(crate) async fn run(cmd: Ctl, dir: &Path) -> ExitCode {
let done = match cmd {
Ctl::List { json } => {
list(dir, json).await;
Ok(())
}
Ctl::Inspect { id, json } => inspect(dir, &id, json).await,
Ctl::Events {
id,
after,
follow,
json,
} => events(dir, &id, after, follow, json).await,
Ctl::Send { id, text } => send(dir, &id, &text.join(" ")).await,
Ctl::Interrupt { id } => interrupt(dir, &id).await,
};
match done {
Ok(()) => ExitCode::SUCCESS,
Err(why) => {
eprintln!("haest: {}", inert(&why));
ExitCode::FAILURE
}
}
}
async fn list(dir: &Path, json: bool) {
let found = running_sessions(dir).await;
if json {
let rows: Vec<Value> = found
.iter()
.map(|r| {
json!({
"sid": r.discovery.sid,
"session": r.session(),
"model": r.model_spec(),
"pid": r.discovery.pid,
"access": r.discovery.access,
"startedMs": r.discovery.started_ms,
})
})
.collect();
println!("{}", Value::Array(rows));
return;
}
if found.is_empty() {
eprintln!("No haest with a control socket runs here.");
}
for r in &found {
let when = iso_utc(r.discovery.started_ms);
let row = format!(
"{} {}Z {} {:7} {} pid {}",
&when[..10],
&when[11..16],
r.discovery.sid,
r.discovery.access,
r.model_spec(),
r.discovery.pid
);
println!("{}", inert(&row));
}
}
async fn inspect(dir: &Path, id: &str, json: bool) -> Result<(), String> {
let mut peer = connect(dir, id).await?;
let ask = peer.call(Request::Snapshot, |_| {});
let now = answered(tokio::time::timeout(ANSWER_WAIT, ask).await)?.unwrap_or_default();
if json {
println!("{now}");
return Ok(());
}
let field = |k: &str| inert(now[k].as_str().unwrap_or("-")).into_owned();
println!("session {}", field("session"));
println!("model {}", field("model"));
if let Some(effort) = now["effort"].as_str() {
println!("effort {}", inert(effort));
}
println!("state {}", field("state"));
println!("messages {}", now["messages"]);
println!("queued {}", now["queued"]);
if let Some(usd) = now["usd"].as_f64() {
println!("cost ${usd:.4}");
}
Ok(())
}
async fn events(dir: &Path, id: &str, after: u64, follow: bool, json: bool) -> Result<(), String> {
let mut peer = connect(dir, id).await?;
let mut term = Renderer::terminal(json).watching();
let ask = Request::Events { after, follow };
peer.call(ask, |frame| show(&mut term, frame))
.await
.map_err(|e| report(&e))?;
if !follow {
return Ok(());
}
while let Some(frame) = peer.recv().await {
match frame {
Ok(frame) => show(&mut term, &frame),
Err(TransportError::NotAFrame(_)) => {}
Err(e) => return Err(report(&e)),
}
}
Ok(())
}
fn show(term: &mut Renderer<std::io::Stdout, std::io::Stderr>, frame: &Frame) {
if !matches!(
frame.body,
Body::Wire(Outbound::Hello { .. } | Outbound::Reply { .. })
) {
term.frame(frame);
}
}
async fn send(dir: &Path, id: &str, text: &str) -> Result<(), String> {
if text.trim().is_empty() {
return Err("nothing to send".into());
}
let mut peer = connect(dir, id).await?;
let turn = Request::Turn { text: text.into() };
let end = answered(Ok(peer.call(turn, |_| {}).await))?.unwrap_or_default();
let stop = end["stopReason"].as_str().unwrap_or("-");
match end["error"].as_str() {
Some(error) => eprintln!("The turn ended ({}): {}", inert(stop), inert(error)),
None => eprintln!("The turn ended ({}).", inert(stop)),
}
Ok(())
}
async fn interrupt(dir: &Path, id: &str) -> Result<(), String> {
let mut peer = connect(dir, id).await?;
let stop = Request::Control(Control::Interrupt);
answered(tokio::time::timeout(ANSWER_WAIT, peer.call(stop, |_| {})).await)?;
eprintln!("Interrupted.");
Ok(())
}
async fn connect(dir: &Path, id: &str) -> Result<UnixPeer, String> {
connect_session(dir, id).await.map_err(|e| match e {
TransportError::NoSession(_) => format!("{e} (haest ctl list lists them)"),
e => report(&e),
})
}
fn answered(
reply: Result<Result<Option<Value>, TransportError>, tokio::time::error::Elapsed>,
) -> Result<Option<Value>, String> {
match reply {
Ok(Ok(result)) => Ok(result),
Ok(Err(e)) => Err(report(&e)),
Err(_) => Err(format!("no answer in {} s", ANSWER_WAIT.as_secs())),
}
}