use std::error::Error;
use std::path::{Path, PathBuf};
use std::process::Command;
use troupekit::agent::Limits;
use troupekit::core::ids::RunId;
use troupekit::prelude::*;
use troupekit::ToolContext;
const MODEL: &str = "anthropic/claude-haiku-5-5";
const MODE: &str = "COURSE_RESEARCH_MODE";
const DIR: &str = "COURSE_RESEARCH_DIR";
const RUN: &str = "COURSE_RESEARCH_RUN";
const TOPIC: &str = "why LLM agent runs should survive a process restart";
fn dir() -> PathBuf {
PathBuf::from(std::env::var_os(DIR).expect("COURSE_RESEARCH_DIR is set by the parent"))
}
fn mode() -> String {
std::env::var(MODE).unwrap_or_default()
}
fn outliner() -> Agent {
Agent::new("outliner")
.model(MODEL)
.instructions("List three short questions a report on the user's topic must answer, one per line, and nothing else.")
.max_turns(2)
.max_tokens(300)
}
fn drafter() -> Agent {
Agent::new("drafter")
.model(MODEL)
.instructions(
"Answer each question in two sentences, with the question as a Markdown heading.",
)
.max_turns(2)
.max_tokens(900)
}
#[tool]
fn hold(outline: String, ctx: ToolContext) -> String {
std::fs::write(dir().join(format!("outline-{}.txt", mode())), &outline)
.expect("write outline copy");
if mode() == "crash" {
let run_id = ctx.run_id.expect("graph steps carry their run id");
std::fs::write(dir().join("run-id"), run_id.to_string()).expect("write run-id");
std::process::abort();
}
outline
}
#[tool]
fn save(draft: String) -> Result<String, String> {
std::fs::write(dir().join("report.md"), &draft)
.map_err(|e| format!("could not save the report: {e}"))?;
Ok(format!("saved {} bytes to report.md", draft.len()))
}
async fn pipeline(db: &Path) -> Result<BuiltGraph, KitError> {
Graph::new("research")
.agent("outline", outliner())
.step("hold", hold)
.agent("draft", drafter())
.step("save", save)
.checkpoints(Storage::sqlite(db))
.limits(Limits {
run: Some(30_000),
..Limits::default()
})
.build()
.await
}
fn child(mode: &str, folder: &Path, run: Option<&str>) -> Result<bool, Box<dyn Error>> {
let mut command = Command::new(std::env::current_exe()?);
command.env(MODE, mode).env(DIR, folder);
if let Some(run) = run {
command.env(RUN, run);
}
Ok(command.status()?.success())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
match mode().as_str() {
"crash" => {
pipeline(&dir().join("runs.db")).await?.run(TOPIC).await?;
Err("the crash child was meant to die in hold".into())
}
"resume" => {
let run_id: RunId =
serde_json::from_value(serde_json::Value::String(std::env::var(RUN)?))?;
let output = pipeline(&dir().join("runs.db"))
.await?
.resume(run_id)
.await?;
println!("resumed: {}", output.as_str().unwrap_or_default());
Ok(())
}
_ => {
let folder = tempfile::tempdir()?;
println!(
"first process finished cleanly: {}",
child("crash", folder.path(), None)?
);
let run = std::fs::read_to_string(folder.path().join("run-id"))?;
if !child("resume", folder.path(), Some(&run))? {
return Err("the resume child failed".into());
}
let before = std::fs::read_to_string(folder.path().join("outline-crash.txt"))?;
let after = std::fs::read_to_string(folder.path().join("outline-resume.txt"))?;
println!("outline identical in both processes: {}", before == after);
println!(
"\n{}",
std::fs::read_to_string(folder.path().join("report.md"))?
);
Ok(())
}
}
}