mod agents;
mod args;
mod ask;
mod changes;
mod commands;
mod models;
mod mods;
mod remedy;
mod render;
mod repl;
mod run;
mod session;
mod show;
mod term;
use std::{
collections::HashMap,
ffi::OsString,
io::{IsTerminal, Read},
path::PathBuf,
process::ExitCode,
sync::Arc,
};
use haest::{
config::{Loaded, Loader, env_var},
core::{error::report, session::sessions_dir},
runtime::{BuildError, SessionError, Ui, list_sessions},
settings::Settings,
workspace::RealFs,
};
use crate::{
args::{Args, Command},
commands::Outcome,
mods::TermPrompter,
term::{Runtime, TermUi},
};
fn fail(code: u8, msg: impl std::fmt::Display) -> ExitCode {
eprintln!("haest: {msg}");
ExitCode::from(code)
}
async fn subcommand(cmd: &Command, loaded: &Loaded) -> ExitCode {
let s = &loaded.config.settings;
match cmd {
Command::Models => print!("{}", models::render(haest::providers::Catalog::builtin())),
Command::Sessions { here } => {
let dir = sessions_dir(&s.data_dir);
let cwd = s.cwd.to_string_lossy();
let rows: Vec<String> = list_sessions(&RealFs, &dir)
.await
.iter()
.filter(|info| !here || info.cwd == cwd)
.map(|info| session::format_row(info, !here))
.collect();
if rows.is_empty() {
eprintln!("No saved sessions{}.", if *here { " here" } else { "" });
}
rows.iter().for_each(|r| println!("{r}"));
}
Command::Settings => show::settings_report(loaded)
.iter()
.for_each(|l| println!("{l}")),
}
ExitCode::SUCCESS
}
fn print_input(args: &Args) -> Option<String> {
args.prompt_text().or_else(|| {
let mut text = String::new();
std::io::stdin().read_to_string(&mut text).ok()?;
(!text.trim().is_empty()).then_some(text)
})
}
async fn print_mode(rt: &mut Runtime, input: &str) -> ExitCode {
let code = match commands::resolve(rt, input).await {
Outcome::Send(text) => {
let end = run::human(rt, &text).await;
if end.stop_reason != haest::StopReason::Aborted {
run::settle(rt).await;
}
run::exit_code(&end)
}
Outcome::Done | Outcome::Exit => ExitCode::SUCCESS,
};
if let Some(lost) = changes::unapplied(rt).await {
rt.hooks.warn(&format!(
"{lost}\nRun with -w real to edit the project directly, or interactively and /apply."
));
}
code
}
fn count(n: usize, noun: &str) -> String {
format!("{n} {noun}{}", if n == 1 { "" } else { "s" })
}
async fn shutdown(rt: &Runtime) {
let stopped = rt.shut_down().await;
if stopped.subagents > 0 {
let line = format!("Stopped {}.", count(stopped.subagents, "subagent"));
rt.hooks.info(&line);
}
if stopped.jobs > 0 {
let line = format!("Killed {}.", count(stopped.jobs, "background job"));
rt.hooks.info(&line);
}
}
fn build_failed(e: BuildError) -> String {
match e {
BuildError::Model(e) => format!(
"{}. Set its key, or pick another model with -m (haest models lists them).",
report(&e)
),
BuildError::Session(e @ SessionError::NotFound { .. }) => {
format!("{e} (haest sessions lists them)")
}
e => report(&e),
}
}
fn unicode_vars(vars: impl Iterator<Item = (OsString, OsString)>) -> HashMap<String, String> {
vars.filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?)))
.collect()
}
fn working_dir(args: &Args) -> Result<PathBuf, String> {
let dir = match &args.cwd {
Some(d) => d.clone(),
None => std::env::current_dir().map_err(|_| "the current directory is gone".to_string())?,
};
match std::fs::canonicalize(&dir) {
Ok(real) if real.is_dir() => Ok(real),
_ => Err(format!("{} is not a directory", dir.display())),
}
}
#[tokio::main]
async fn main() -> ExitCode {
let cli = match args::parse_from(std::env::args_os()) {
Ok(c) => c,
Err(e) => e.exit(),
};
let args = &cli.args;
let env = unicode_vars(std::env::vars_os());
let cwd = match working_dir(args) {
Ok(d) => d,
Err(e) => return fail(2, e),
};
let home = env_var(&env, "HOME").unwrap_or("/");
let defaults = Settings::bare(cwd, home);
let loaded = match Loader::standard(defaults, &env, &cli.settings)
.load(&RealFs)
.await
{
Ok(l) => l,
Err(e) => return fail(2, report(&e)),
};
if let Some(cmd) = &args.command {
return subcommand(cmd, &loaded).await;
}
let print = args.print || args.json || !std::io::stdin().is_terminal();
let ui = Arc::new(TermUi::new(args.json));
loaded.notes.iter().for_each(|n| ui.warn(n));
let input = match print.then(|| print_input(args)) {
Some(None) => return fail(2, "nothing to ask: give a prompt, or pipe one on stdin"),
asked => asked.flatten(),
};
let prompter = TermPrompter::new(ui.clone(), ask::interactive());
let opts = cli.build_options();
let inputs = haest::runtime_inputs(loaded);
let mut rt = match haest::runtime::build(inputs, ui, prompter, opts).await {
Ok(rt) => rt,
Err(e) => return fail(2, build_failed(e)),
};
let code = match input {
Some(input) => print_mode(&mut rt, &input).await,
None => match repl::repl(&mut rt, args.prompt_text()).await {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(1, e),
},
};
shutdown(&rt).await;
code
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_session_that_is_not_there_points_at_haest_sessions() {
let e = BuildError::Session(SessionError::NotFound { id: "abc".into() });
let said = build_failed(e);
assert!(
said.contains("abc") && said.contains("haest sessions"),
"{said}"
);
}
#[test]
fn a_failed_build_reports_every_cause() {
let source = std::io::Error::other("disk full");
let path = PathBuf::from("/d/sessions/x.jsonl");
let e = BuildError::Session(SessionError::Create { path, source });
assert!(build_failed(e).ends_with("x.jsonl: disk full"));
}
}