rig 0.45.0

An opinionated library for building LLM powered applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! Running the agent. [`RELOAD_EXIT_CODE`] restarts it on the staged build;
//! a new build is this launcher's trial until it signals ready in the
//! launcher's [`RunDir`]. Several launchers can share one `RIG_HOME`:
//! building and staging take the root's lock, a `/reload` build and its
//! trial are per session, and the ready file is per launcher.
//!
//! `rig` starts a new session, and `rig --resume <id or name>` an earlier one,
//! in the directory it ran in. The agent's `/new` and `/resume` leave a
//! [`SessionDir::switch`] file and exit with the reload code; the launcher then
//! runs that session instead, in its own directory. A session left without a
//! message, by a clean quit or a switch, leaves no directory. Each start tells
//! the agent why it started ([`StartReason`]).
//!
//! The command line is read once the agent is built, against what its
//! plugins add ([`AgentDescription::invocation`]), and the agent gets it in its
//! canonical form ([`Invocation`]). A plugin's command runs in a new
//! session, or with `--resume` in that one, unless its front keeps no
//! session, which the agent refuses. A headless run (`--print`, stdin piped
//! in, which the agent answers as `--print` does, or a plugin's command
//! that does not take the terminal) passes its exit code and output
//! through. One that answers a prompt is restarted on the reload code, as
//! when its model asked for a reload, without the prompt it already
//! answered, and run again on the previous build when that reload's new
//! build is rolled back; the restarted agent carries on with what the
//! reload left, such as its report to the model. A plugin's command is not
//! restarted, nor a run that asked to switch sessions. Before each start with stdin on
//! a terminal, whatever the front, the launcher asks for each secret the
//! build's plugins want that the environment does not hold
//! ([`ask_secret`]); only the agent's process gets the answers.

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, Staging, child};
use super::{Result, locks};

/// How often the launcher looks for the ready file while the agent runs.
const POLL: Duration = Duration::from_millis(100);

/// The exit code of a run the user stopped with Ctrl+C at a prompt.
const INTERRUPTED: u8 = 130;

/// Which session `rig` runs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Start {
    /// The named session, in the directory it ran in.
    Resume(SessionId),
    /// A new session.
    New,
}

/// Builds the agent, reads the command line `args` against it, runs it
/// until it exits with anything but the reload code, and returns its exit
/// code: 2 for a command line the build does not take, or a `--resume`
/// that names no saved session.
pub fn run(home: &Home, args: &[String]) -> Result<ExitCode> {
    let here = std::env::current_dir().ok();
    let terminal = std::io::stdin().is_terminal();
    // Before the build, only whether `-p` is there: the type-ahead guard.
    let print = args.iter().any(|arg| arg == "-p" || arg == "--print");
    // Before the build, `-r` as the last build reads it; the new build may
    // read it otherwise (below).
    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)?;
        // Before claiming, so a resumed session's leftover builds from its
        // dead launcher are removed too.
        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)?;
        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 {
        // Only the build says which of its options take a value, and so
        // whether a word after one was `-r`.
        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)?;
        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);
    launch(
        home,
        run.dir(),
        &invocation,
        headless,
        claimed,
        notice,
        build_failure,
    )
}

/// The session `--resume` names, by id or name ([`Home::find`]), or a new
/// one without it.
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)
    })
}

/// Says why the command line is refused, and returns its exit code.
fn refused(why: &str) -> ExitCode {
    eprintln!("rig: {why}\nRun `rig help` for usage.");
    ExitCode::from(2)
}

/// What the plugins of the build the launcher of `session` starts next add
/// to the command line; nothing when there is no build or it cannot say.
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()
    })
}

/// The report of the build a new session starts with, as kept from its
/// last build; `None` when it has none. It never builds.
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))
}

/// The build the launcher of `session` starts next, as [`pick`] picks it,
/// without claiming it.
fn next_build(home: &Home, session: &SessionId) -> Option<PathBuf> {
    [home.staged_for(session), home.staged(), home.good()]
        .into_iter()
        .find(|binary| binary.exists())
}

/// Starts the agent of `claimed` with the build [`pick`] finds, again on
/// the reload code, and returns its exit code. `notice` and
/// `build_failure` go to the first start.
fn launch(
    home: &Home,
    run: &RunDir,
    invocation: &Invocation,
    headless: bool,
    mut claimed: Claimed,
    mut notice: Option<String>,
    mut build_failure: Option<String>,
) -> Result<ExitCode> {
    let launcher = std::env::current_exe()?;
    // The secrets asked for, for every restart: asked whenever someone is
    // at the terminal, whatever the front, so a command typed there can be
    // asked too; a piped run passes only what its environment has.
    let ask = std::io::stdin().is_terminal();
    let mut answers: BTreeMap<String, String> = BTreeMap::new();
    // Whether the agent's full-screen view kept its screen across a
    // restart, so what the agent said before it took the terminal is gone
    // once the launcher takes the terminal back.
    let mut kept_screen = false;
    // The session the agent switched away from to start this one, which a
    // refused start goes back to.
    let mut switched_from: Option<SessionId> = None;
    let mut reason = claimed.reason;
    // A headless run that answers a prompt, restarted on a reload: without
    // the prompt, which it answered already.
    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(ExitCode::from(INTERRUPTED));
                };
                answers.insert(variable, answer);
            }
        }
        let binary = pick(home, &session, &trial)?;
        absent(fs::remove_file(&ready))?;
        absent(fs::remove_file(run.refusal()))?;
        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);
        }
        // Only the first start follows the failed build.
        if let Some(failure) = build_failure.take() {
            command.env(env::BUILD_FAILURE, failure);
        }
        let mut child = command.spawn()?;
        // A trial becomes the good build as soon as it is ready, so a
        // launcher killed later (a closed terminal) keeps it.
        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),
            }
        };
        promoted?;
        let rejected = matches!(binary, Binary::Trial(_)) && !started;
        if rejected {
            build::reject(home, &trial)?;
            fs::remove_file(&trial)?;
        }
        let reload = status.code() == Some(i32::from(RELOAD_EXIT_CODE));
        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 {
                // Told in the session it went back to, so nothing is kept.
                absent(fs::remove_file(run.log()))?;
                let why = refusal.trim().trim_start_matches("rig: ");
                notice = Some(format!("Could not switch sessions: {why}"));
                continue;
            }
        }
        // Only a session rolled back for someone at the terminal, or after
        // a reload of a run that answers a prompt, runs again.
        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()
        };
        if !rejected && (status.success() || headless) {
            return Ok(exit_code(status));
        }
        if !headless {
            restore_terminal();
        }
        if !rejected {
            let refusal = fs::read_to_string(run.refusal()).ok();
            // A refused session would be refused again.
            let resumable = directory.is_saved() && refusal.is_none();
            let lost = refusal.filter(|_| kept_screen);
            let log = Some(log.as_path()).filter(|log| log.exists());
            let said = stopped(status, &session, resumable, lost.as_deref(), log);
            eprintln!("{said}");
            return Ok(exit_code(status));
        }
        if !home.good().exists() {
            eprintln!(
                "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(exit_code(status));
        }
        let message = format!(
            "The new build stopped during startup ({status}); rolled back to the previous \
             build. `rig build` tries it again. Log: {}",
            log.display()
        );
        eprintln!("{message}");
        // A one-shot run is not run twice, its output already out, unless
        // its agent reloaded: the restart tells the agent of the rollback.
        if !again {
            return Ok(exit_code(status));
        }
        kept_screen = false;
        notice = Some(message);
        reason = StartReason::Restarted;
    }
}

/// What the launcher says when the agent of `session` stopped with a
/// failure: the `refusal` the agent said where it is no longer seen, where
/// its log is when it kept one and, when the session can be resumed, how.
fn stopped(
    status: ExitStatus,
    session: &SessionId,
    resumable: bool,
    refusal: Option<&str>,
    log: Option<&Path>,
) -> String {
    let refusal = refusal.unwrap_or_default();
    let resume = if resumable {
        format!(" `rig --resume {session}` resumes the session where it stopped.")
    } else {
        String::new()
    };
    let log = log.map_or_else(String::new, |log| format!(" Log: {}", log.display()));
    format!("{refusal}The agent stopped ({status}).{resume}{log}")
}

/// The session the agent asked to run next in `directory`'s switch file,
/// which is removed: a session id, or a new session when the file is empty.
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)?))
}

/// Leaves the `current` session for `target`, which the agent asked for.
/// A build `/reload` staged for it goes with the switch. When the target
/// cannot be run, the current session carries on, told why.
fn switch(home: &Home, current: Claimed, target: Start) -> Result<(Claimed, Option<String>)> {
    let _lock = locks::hold_build_lock(home)?;
    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(&current.id),
                home.staged_for(&next.id),
            ))?;
            Ok((next, notice))
        }
        Err(failure) => Ok((
            current,
            Some(format!("Could not switch sessions: {failure}.")),
        )),
    }
}

/// The session this launcher runs, held locked while it lives.
struct Claimed {
    id: SessionId,
    /// Why its first start starts it: `New` or `Resumed`.
    reason: StartReason,
    /// The directory the session runs in, when known and still there.
    directory: Option<PathBuf>,
    _lock: File,
}

impl Claimed {
    /// Removes the session's directory when no agent logged a message in
    /// it, such as a `/new` session left at once: a session with nothing
    /// to resume leaves nothing behind. Call it once the agent exited for
    /// good or switched away. Best effort: a directory left behind has no
    /// agent log, so `/resume` does not list it.
    fn discard_if_unsaved(&self, home: &Home) {
        let session = home.session(&self.id);
        if !session.is_saved() {
            fs::remove_dir_all(session.path()).ok();
        }
    }

    /// Ends this launcher's runs of the session for good: discards it when
    /// unsaved ([`Self::discard_if_unsaved`]), first moving the text log of
    /// a run that failed into `run`, which keeps it, and returns where the
    /// text log is. A sessionless run that failed, and a refused run, moved
    /// it there themselves.
    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()
    }
}

/// The session to run for `start` from the working directory `here`, held
/// locked, and the line the agent shows about it. Call it holding
/// [`locks::hold_build_lock`].
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 {
                write_atomic(&session.directory(), &here.to_string_lossy())?;
            }
            here.map(Path::to_path_buf)
        }
    };
    Ok((
        Claimed {
            id,
            reason,
            directory,
            _lock: lock,
        },
        notice,
    ))
}

/// Writes `text` to `path` through a temporary file, creating its
/// directory.
fn write_atomic(path: &Path, text: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let written = path.with_extension("tmp");
    fs::write(&written, text)?;
    fs::rename(&written, path)?;
    Ok(())
}

/// Puts the terminal back after an agent that could not restore it: leaves
/// the alternate screen and, on a terminal, raw mode.
fn restore_terminal() {
    eprint!("\x1b[?1049l\x1b[?25h");
    if std::io::stdin().is_terminal() {
        child("stty").arg("sane").status().ok();
    }
}

/// The terminal's line mode, put aside while the launcher waits for and
/// runs a build before an interactive start, and given back when dropped,
/// before the agent starts. Meanwhile the terminal neither echoes what is
/// typed over the build's output nor turns a typed Enter (CR) into a line
/// feed, which the agent, in raw mode, would read as Ctrl+J.
struct TypeAhead {
    /// The mode `stty -g` printed.
    saved: String,
}

impl TypeAhead {
    /// Puts the mode aside, or `None` when `stty` cannot.
    fn hold() -> Option<Self> {
        Self::set(&["-icrnl", "-echo"])
    }

    /// Puts the mode aside and sets `mode` (`stty` arguments), or `None`
    /// when `stty` cannot.
    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();
    }
}

/// Asks on the terminal for `secret`, without echo, and returns the
/// answer; `None` when the user pressed Ctrl+C. The terminal reads byte by
/// byte with its signals off, so Ctrl+C arrives as a byte and the mode is
/// given back, echo included, whatever the answer.
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()))
}

/// Reads a line typed without the terminal's line editing: Enter (or the
/// input's end) ends it, Backspace erases the last character, and Ctrl+C
/// gives `None`.
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] => {
                // A whole UTF-8 character: its continuation bytes, then its
                // first.
                while answer.pop().is_some_and(|last| last & 0xc0 == 0x80) {}
            }
            [typed] => answer.push(typed),
        }
    }
}

/// `result`, with a missing file as `None`.
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),
    }
}

/// Builds before every start, staging for this launcher; cargo does no
/// work when nothing changed. With no good build yet, the build is staged
/// even if it was rejected before, so each start retries it. A failed build
/// with an older binary at hand is returned, for that binary to start with.
fn rebuild(home: &Home, session: &SessionId) -> Result<Option<BuildFailure>> {
    let first_run = !home.staged().exists() && !home.good().exists();
    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) {
        Ok(()) => Ok(None),
        Err(failure) if first_run => Err(failure.into()),
        Err(failure) => {
            eprintln!("error: {failure}; starting the previous build");
            Ok(Some(failure))
        }
    }
}

/// The binary a launcher starts.
enum Binary {
    /// A staged build, claimed as this launcher's trial until it is ready.
    Trial(PathBuf),
    /// The last build that started up.
    Good(PathBuf),
}

impl Binary {
    fn path(&self) -> &Path {
        match self {
            Self::Trial(path) | Self::Good(path) => path,
        }
    }
}

/// The binary to start: a build staged for this launcher or for any, claimed
/// as its `trial`, or else the last good one.
fn pick(home: &Home, session: &SessionId, trial: &Path) -> Result<Binary> {
    for staged in [home.staged_for(session), home.staged()] {
        // The rename claims the staged build for this launcher alone.
        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())
}

/// The agent's exit code; 1 when a signal ended it.
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;