use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::{ErrorKind, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, ExitStatus, Stdio};
use std::time::Duration;
use rig_harness_protocol::{
AgentDescription, DescribedSecret, Home, Invocation, RELOAD_EXIT_CODE, RunDir, SessionDir,
SessionId, StartReason, env, secret_variable,
};
use super::build::{self, BuildFailure, BuildOutput, Staging, child};
use super::{Result, locks};
const POLL: Duration = Duration::from_millis(100);
const INTERRUPTED: u8 = 130;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Start {
Resume(SessionId),
New,
}
pub fn run(home: &Home, args: &[String]) -> Result<ExitCode> {
let here = std::env::current_dir().ok();
let terminal = std::io::stdin().is_terminal();
let print = args.iter().any(|arg| arg == "-p" || arg == "--print");
let output = if print || !terminal {
BuildOutput::LogOnly
} else {
BuildOutput::Live
};
let asked = last_report(home).unwrap_or_default().resume(args);
let start = match start_of(home, asked.as_deref()) {
Ok(start) => start,
Err(why) => return Ok(refused(&why)),
};
let (run, mut claimed, mut claim_notice, build_notice, build_failure, report) = {
let _typing = (terminal && !print).then(TypeAhead::hold).flatten();
let _lock = locks::hold_build_lock(home, output)?;
locks::sweep(home)?;
let run = locks::hold_run(home)?;
let (claimed, claim_notice) = claim(home, start, here.as_deref())?;
let failure = rebuild(home, &claimed.id, output)?;
let built = failure.as_ref().map(|failure| {
format!("Building the agent failed, so the previous build is running: {failure}")
});
let report = report(home, &claimed.id);
(
run,
claimed,
claim_notice,
built,
failure.map(|failure| failure.details()),
report,
)
};
let resume = report.resume(args);
if resume != asked {
let start = match start_of(home, resume.as_deref()) {
Ok(start) => start,
Err(why) => {
claimed.discard_if_unsaved(home);
return Ok(refused(&why));
}
};
let _lock = locks::hold_build_lock(home, output)?;
let (next, notice) = claim(home, start, here.as_deref())?;
absent(fs::rename(
home.staged_for(&claimed.id),
home.staged_for(&next.id),
))?;
claimed.discard_if_unsaved(home);
(claimed, claim_notice) = (next, notice);
}
let notice: Vec<String> = claim_notice.into_iter().chain(build_notice).collect();
let notice = (!notice.is_empty()).then(|| notice.join("\n"));
let invocation = match report.invocation(args) {
Ok(invocation) => invocation,
Err(why) => {
claimed.discard_if_unsaved(home);
eprintln!("rig: {why}");
return Ok(ExitCode::from(2));
}
};
let command = invocation
.command
.as_deref()
.and_then(|command| report.command(command));
let headless =
invocation.is_headless() || !terminal || command.is_some_and(|command| !command.terminal);
let ended = launch(
home,
run.dir(),
&invocation,
headless,
claimed,
notice,
build_failure,
)?;
if ended.restore {
restore_terminal();
}
if let Some(said) = ended.said {
eprintln!("{said}");
}
Ok(ended.code)
}
fn start_of(home: &Home, resume: Option<&str>) -> std::result::Result<Start, String> {
resume.map_or(Ok(Start::New), |session| {
home.find(session).map(Start::Resume)
})
}
fn refused(why: &str) -> ExitCode {
eprintln!("rig: {why}\nRun `rig help` for usage.");
ExitCode::from(2)
}
fn report(home: &Home, session: &SessionId) -> AgentDescription {
let Some(binary) = next_build(home, session) else {
return AgentDescription::default();
};
build::described(home, &binary).unwrap_or_else(|failure| {
eprintln!("warning: the agent build does not say what its plugins add: {failure}");
AgentDescription::default()
})
}
pub fn last_report(home: &Home) -> Option<AgentDescription> {
[home.staged(), home.good()]
.into_iter()
.find(|binary| binary.exists())
.and_then(|binary| build::good_report(home, &binary))
}
fn next_build(home: &Home, session: &SessionId) -> Option<PathBuf> {
[home.staged_for(session), home.staged(), home.good()]
.into_iter()
.find(|binary| binary.exists())
}
fn launch(
home: &Home,
run: &RunDir,
invocation: &Invocation,
headless: bool,
mut claimed: Claimed,
mut notice: Option<String>,
mut build_failure: Option<String>,
) -> Result<Ended> {
let launcher = std::env::current_exe()?;
let ask = std::io::stdin().is_terminal();
let mut answers: BTreeMap<String, String> = BTreeMap::new();
let mut kept_screen = false;
let mut screen = false;
let mut switched_from: Option<SessionId> = None;
let mut reason = claimed.reason;
let answers_prompt = headless && invocation.command.is_none();
let restarted = Invocation {
print: invocation.print.as_ref().map(|_| String::new()),
..invocation.clone()
};
let mut invocation: &Invocation = invocation;
loop {
let left = switched_from.take();
let session = claimed.id.clone();
let trial = home.trial_for(&session);
let directory = home.session(&session);
let ready = run.ready();
if ask {
for secret in report(home, &session).secrets {
let variable = secret_variable(&secret.name);
if std::env::var_os(&variable).is_some() || answers.contains_key(&variable) {
continue;
}
let Some(answer) = ask_secret(&secret)? else {
claimed.discard_if_unsaved(home);
return Ok(Ended::quiet(ExitCode::from(INTERRUPTED)));
};
answers.insert(variable, answer);
}
}
let binary = pick(home, &session, &trial)?;
absent(fs::remove_file(&ready))?;
absent(fs::remove_file(run.refusal()))?;
absent(fs::remove_file(run.groups()))?;
absent(fs::remove_file(run.screen()))?;
let mut command = Command::new(binary.path());
command
.args(invocation.to_args())
.env(env::HOME, home.root())
.env(env::SESSION, session.as_str())
.env(env::LAUNCHER, &launcher)
.env(env::RUN, run.path())
.env(env::START, reason.as_str())
.env_remove(env::NOTICE)
.env_remove(env::BUILD_FAILURE)
.envs(&answers);
if let Some(working) = &claimed.directory {
command.current_dir(working);
}
if let Some(notice) = notice.take() {
command.env(env::NOTICE, notice);
}
if let Some(failure) = build_failure.take() {
command.env(env::BUILD_FAILURE, failure);
}
let mut child = command.spawn()?;
let mut started = false;
let mut promoted: Result<()> = Ok(());
let status = loop {
let status = child.try_wait()?;
if !started && ready.exists() {
started = true;
if let Binary::Trial(trial) = &binary {
promoted = fs::rename(trial, home.good()).map_err(Into::into);
}
}
match status {
Some(status) => break status,
None => std::thread::sleep(POLL),
}
};
let reload = status.code() == Some(i32::from(RELOAD_EXIT_CODE));
screen |= run.screen().exists();
if !reload {
run.kill_left_groups().ok();
}
promoted?;
let rejected = matches!(binary, Binary::Trial(_)) && !started;
if rejected {
build::reject(home, &trial)?;
fs::remove_file(&trial)?;
}
let restart = !headless || (answers_prompt && !directory.switch().exists());
if reload && restart {
if headless {
invocation = &restarted;
}
if let Some(target) = take_switch(&directory)? {
(claimed, notice) = switch(home, claimed, target)?;
}
reason = if claimed.id == session {
StartReason::Reloaded
} else {
claimed.reason
};
switched_from = (claimed.id != session).then_some(session);
kept_screen = !headless;
continue;
}
if !rejected
&& !headless
&& let Some(left) = left
&& let Some(refusal) = absent(fs::read_to_string(run.refusal()))?
{
let back = if home.session(&left).is_saved() {
Start::Resume(left)
} else {
Start::New
};
let (previous, _) = switch(home, claimed, back)?;
claimed = previous;
reason = claimed.reason;
if claimed.id != session {
absent(fs::remove_file(run.log()))?;
let why = refusal.trim().trim_start_matches("rig: ");
notice = Some(format!("Could not switch sessions: {why}"));
continue;
}
}
let again = !headless || (answers_prompt && reason == StartReason::Reloaded);
let ended = !rejected || !again || !home.good().exists();
let log = if ended {
claimed.leave(home, run, status.success())
} else {
directory.log()
};
let refusal = fs::read_to_string(run.refusal()).ok();
if !rejected && headless {
return Ok(Ended::quiet(exit_code(status)));
}
let resume = started
.then(|| resume_command(home, &session, refusal.is_some()))
.flatten();
if !rejected && status.success() {
let said = resume.map(|resume| format!("To resume this session: {resume}"));
let restore = said.is_some() && screen;
return Ok(Ended::new(status, said).restoring(restore));
}
let restore = std::mem::take(&mut screen);
if !rejected {
let lost = refusal.filter(|_| kept_screen);
let log = Some(log.as_path()).filter(|log| log.exists());
let said = stopped(status, resume.as_deref(), lost.as_deref(), log);
return Ok(Ended::new(status, Some(said)).restoring(restore));
}
if !home.good().exists() {
let said = format!(
"The new build stopped during startup ({status}) and there is no previous \
build to roll back to; the next `rig` tries it again. Log: {}",
log.display()
);
return Ok(Ended::new(status, Some(said)).restoring(restore));
}
let message = format!(
"The new build stopped during startup ({status}); rolled back to the previous \
build. `rig build` tries it again. Log: {}",
log.display()
);
if !again {
return Ok(Ended::new(status, Some(message)).restoring(restore));
}
if restore {
restore_terminal();
}
eprintln!("{message}");
kept_screen = false;
notice = Some(message);
reason = StartReason::Restarted;
}
}
#[derive(Debug, PartialEq)]
struct Ended {
code: ExitCode,
said: Option<String>,
restore: bool,
}
impl Ended {
fn new(status: ExitStatus, said: Option<String>) -> Self {
Self {
code: exit_code(status),
said,
restore: false,
}
}
fn quiet(code: ExitCode) -> Self {
Self {
code,
said: None,
restore: false,
}
}
fn restoring(self, restore: bool) -> Self {
Self { restore, ..self }
}
}
fn stopped(
status: ExitStatus,
resume: Option<&str>,
refusal: Option<&str>,
log: Option<&Path>,
) -> String {
let refusal = refusal.unwrap_or_default();
let resume = resume.map_or_else(String::new, |resume| {
format!(" `{resume}` resumes the session where it stopped.")
});
let log = log.map_or_else(String::new, |log| format!(" Log: {}", log.display()));
format!("{refusal}The agent stopped ({status}).{resume}{log}")
}
fn resume_command(home: &Home, session: &SessionId, refused: bool) -> Option<String> {
let directory = home.session(session);
if refused || !directory.is_saved() {
return None;
}
let name = directory.name().filter(|name| {
!name.starts_with('-')
&& !name.chars().any(|c| c.is_control() || is_format(c))
&& name.parse::<SessionId>().is_err()
&& home.find(name).as_ref() == Ok(session)
});
Some(match name {
Some(name) => format!("rig --resume '{}'", name.replace('\'', r"'\''")),
None => format!("rig --resume {session}"),
})
}
fn is_format(c: char) -> bool {
matches!(
c,
'\u{ad}'
| '\u{61c}'
| '\u{180b}'..='\u{180f}'
| '\u{200b}'..='\u{200f}'
| '\u{2028}'..='\u{202e}'
| '\u{2060}'..='\u{206f}'
| '\u{fe00}'..='\u{fe0f}'
| '\u{feff}'
| '\u{fff9}'..='\u{fffb}'
| '\u{e0001}'
| '\u{e0020}'..='\u{e007f}'
| '\u{e0100}'..='\u{e01ef}'
)
}
fn take_switch(directory: &SessionDir) -> Result<Option<Start>> {
let path = directory.switch();
let Some(text) = absent(fs::read_to_string(&path))? else {
return Ok(None);
};
fs::remove_file(&path)?;
let text = text.trim();
if text.is_empty() {
return Ok(Some(Start::New));
}
Ok(Some(text.parse().map(Start::Resume)?))
}
fn switch(home: &Home, current: Claimed, target: Start) -> Result<(Claimed, Option<String>)> {
let _lock = locks::hold_build_lock(home, BuildOutput::Live)?;
let here = current.directory.clone();
match claim(home, target, here.as_deref()) {
Ok((next, notice)) => {
current.discard_if_unsaved(home);
absent(fs::rename(
home.staged_for(¤t.id),
home.staged_for(&next.id),
))?;
Ok((next, notice))
}
Err(failure) => Ok((
current,
Some(format!("Could not switch sessions: {failure}.")),
)),
}
}
struct Claimed {
id: SessionId,
reason: StartReason,
directory: Option<PathBuf>,
_lock: File,
}
impl Claimed {
fn discard_if_unsaved(&self, home: &Home) {
let session = home.session(&self.id);
if !session.is_saved() {
fs::remove_dir_all(session.path()).ok();
}
}
fn leave(&self, home: &Home, run: &RunDir, succeeded: bool) -> PathBuf {
let session = home.session(&self.id);
if session.is_saved() {
return if run.refusal().exists() {
run.log()
} else {
session.log()
};
}
if !succeeded {
fs::rename(session.log(), run.log()).ok();
}
self.discard_if_unsaved(home);
run.log()
}
}
fn claim(home: &Home, start: Start, here: Option<&Path>) -> Result<(Claimed, Option<String>)> {
let (id, lock, notice, reason) = match start {
Start::Resume(id) => {
if !home.session(&id).is_saved() {
return Err(format!("session {id} has no saved conversation").into());
}
let lock = home
.session(&id)
.hold()?
.ok_or_else(|| format!("session {id} is open in another rig"))?;
(
id,
lock,
Some("Resumed the session.".to_owned()),
StartReason::Resumed,
)
}
Start::New => {
let (id, _) = home.new_session()?;
let lock = home
.session(&id)
.hold()?
.ok_or_else(|| format!("session {id} is already running"))?;
(id, lock, None, StartReason::New)
}
};
let session = home.session(&id);
let directory = match session.working_directory() {
Some(directory) => Some(directory),
None => {
if let Some(here) = here {
session.set_working_directory(here)?;
}
here.map(Path::to_path_buf)
}
};
Ok((
Claimed {
id,
reason,
directory,
_lock: lock,
},
notice,
))
}
fn restore_terminal() {
eprint!("\x1b[?1049l\x1b[?25h");
if std::io::stdin().is_terminal() {
child("stty").arg("sane").status().ok();
}
}
struct TypeAhead {
saved: String,
}
impl TypeAhead {
fn hold() -> Option<Self> {
Self::set(&["-icrnl", "-echo"])
}
fn set(mode: &[&str]) -> Option<Self> {
let output = child("stty")
.arg("-g")
.stdin(Stdio::inherit())
.stderr(Stdio::null())
.output()
.ok()
.filter(|output| output.status.success())?;
let saved = String::from_utf8(output.stdout).ok()?.trim().to_owned();
let set = child("stty").args(mode).status();
set.is_ok_and(|status| status.success())
.then_some(Self { saved })
}
}
impl Drop for TypeAhead {
fn drop(&mut self) {
child("stty").arg(&self.saved).status().ok();
}
}
fn ask_secret(secret: &DescribedSecret) -> Result<Option<String>> {
let mut stderr = std::io::stderr();
write!(stderr, "{} ({}): ", secret.help, secret.name)?;
stderr.flush()?;
let mode = TypeAhead::set(&["-echo", "-icanon", "-isig"]);
let answer = read_secret(&mut std::io::stdin().lock());
drop(mode);
writeln!(stderr)?;
Ok(answer?.map(|bytes| String::from_utf8_lossy(&bytes).into_owned()))
}
fn read_secret(input: &mut impl Read) -> std::io::Result<Option<Vec<u8>>> {
let mut answer = Vec::new();
let mut byte = [0_u8];
loop {
if input.read(&mut byte)? == 0 {
return Ok(Some(answer));
}
match byte {
[b'\r' | b'\n'] => return Ok(Some(answer)),
[0x03] => return Ok(None),
[0x7f | 0x08] => {
while answer.pop().is_some_and(|last| last & 0xc0 == 0x80) {}
}
[typed] => answer.push(typed),
}
}
}
fn absent<T>(result: std::io::Result<T>) -> std::io::Result<Option<T>> {
match result {
Err(failure) if failure.kind() == ErrorKind::NotFound => Ok(None),
result => result.map(Some),
}
}
fn rebuild(home: &Home, session: &SessionId, output: BuildOutput) -> Result<Option<BuildFailure>> {
let first_run = !home.staged().exists() && !home.good().exists();
if output == BuildOutput::Live {
eprintln!(
"Building the rig agent{}…",
if first_run { " (first run)" } else { "" }
);
}
let staging = if first_run {
Staging::Always
} else {
Staging::OnlyNew
};
match build::compile(home, &home.staged_for(session), staging, output) {
Ok(()) => Ok(None),
Err(failure) if first_run => Err(failure.told(output).into()),
Err(failure) => {
let told = failure.told(output);
eprintln!("error: building the agent failed; starting the previous build: {told}");
Ok(Some(failure))
}
}
}
enum Binary {
Trial(PathBuf),
Good(PathBuf),
}
impl Binary {
fn path(&self) -> &Path {
match self {
Self::Trial(path) | Self::Good(path) => path,
}
}
}
fn pick(home: &Home, session: &SessionId, trial: &Path) -> Result<Binary> {
for staged in [home.staged_for(session), home.staged()] {
if absent(fs::rename(staged, trial))?.is_some() {
return Ok(Binary::Trial(trial.to_path_buf()));
}
}
let good = home.good();
if good.exists() {
return Ok(Binary::Good(good));
}
Err("no agent build exists yet; run `rig build`".into())
}
fn exit_code(status: ExitStatus) -> ExitCode {
ExitCode::from(
status
.code()
.and_then(|code| u8::try_from(code).ok())
.unwrap_or(1),
)
}
#[cfg(test)]
mod tests;