rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! Updating rho with no person at a terminal: the daemon's update, for a
//! person's frontend (`rho/daemon/update`, `app::daemon_host::machine_update`).
//! It decides as `rho update` does ([`prepare`]) and says what it does to a
//! [`Report`] rather than a terminal. It never runs what may wait for a
//! person, such as `sudo` or a package manager on Windows, naming the
//! command instead, and it trusts the rho it installed only once that rho
//! printed its version.

use std::{
    ffi::OsString,
    io,
    path::{Path, PathBuf},
    process::{Output, Stdio},
    sync::{Mutex, PoisonError},
    time::Duration,
};

use anyhow::Context;
use rho_protocol::ClientEnvironment;

use super::{
    announce, cargo_update_root_in, detect_install_method_in, install_script_ref, latest_release,
    mise_tool_in, prepare, update_in_place, version_is_newer, InstallMethod, Lookups, Plan, Report,
};
use crate::{
    app::daemon_install::Installed,
    daemon::{probe_version, started_path, DaemonPaths},
    installation::{installed_scoop_scope, Probe, ScoopInstallScope},
};

/// How long the installer may run.
//
// Tripwire: the slowest installer is `cargo install`, which builds rho from
// source: `cargo install rho-coding-agent --locked -j 8` of 3.10.0 took
// 562 s on a 24-core Linux machine (2026-12-03). An hour is 6.4 times that,
// room for a machine with a third of the cores, and still frees an update
// the installer hung, as one waiting on a lock or a stalled download would.
#[cfg(not(windows))]
const INSTALLER_DEADLINE: Duration = Duration::from_secs(60 * 60);

/// How long the installer's output is still read once it exited.
//
// Tripwire: what it wrote before exiting is already in the pipes, at most
// their capacity (64 KiB each by default on Linux, pipe(7)), which a read
// takes in far less; only a process it left running can keep a pipe open,
// and the update does not wait for that past 1 s.
#[cfg(not(windows))]
const PIPE_DRAIN_AFTER_EXIT: Duration = Duration::from_secs(1);

/// The most bytes one line of the installer's output holds; a longer one,
/// as a progress meter that only ever writes `\r`, is split.
//
// The longest line of `scripts/install.sh`'s source is 153 bytes, and of
// that `cargo install` build's whole output 116 (measured with awk); the
// messages install.sh echoes, with a tag and an asset name in, stay near
// that. 4 KiB is 26 times it, and as much as a host stream's failure
// message carries.
#[cfg(not(windows))]
const LINE_MAX_BYTES: usize = 4 * 1024;

/// How long each tool the update asks how rho was installed may take to
/// answer, in the login environment: `cargo install --list`, `mise ls`,
/// `pacman -Qqo`, `rpm -qf`, and `mise which rho` after the install.
//
// As the version probe's 10 s (`daemon::executable`, `PROBE_TIMEOUT`):
// short-lived processes of the same kind. `mise which` answered in 0.00 to
// 0.01 s, 5 runs, mise 2026.10.0 on Linux (2026-12-03); `mise ls
// --installed --json` in 0.00 to 0.01 s and `cargo install --list` in
// 0.01 s, 3 runs each, the same day. 10 s is 1000 times the slowest.
const LOOKUP_TIMEOUT: Duration = Duration::from_secs(10);

/// What an unattended update did.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Unattended {
    /// rho runs the latest release already.
    UpToDate,
    /// Only a person at a terminal can install `latest`, by running
    /// `command`: nothing ran.
    NeedsTerminal { latest: String, command: String },
    /// `method` installed rho `to`, as the installed rho printed it, where
    /// `lands` says.
    Installed {
        to: String,
        method: InstallMethod,
        lands: Lands,
    },
}

/// Where an update put the new rho, which decides how the daemon moves onto
/// it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Lands {
    /// At the path the daemon runs from, so the daemon re-executes it.
    AtItsPath,
    /// At another path, this one, as mise and Scoop keep each version, so
    /// the daemon stops and the next client starts the new rho.
    AtAnotherPath(PathBuf),
}

/// Updates the rho this process runs, version `current_version`, as `rho
/// update` would, saying what it does and what the installer prints to
/// `report`. The installer runs in `environment` alone, with nothing on its
/// stdin. A method that needs a person answers
/// [`Unattended::NeedsTerminal`] without running anything. `replaced` is
/// the version a rho that already replaced this one at its path printed,
/// which the daemon waits to restart onto: when it is newer, nothing is
/// installed again.
///
/// # Errors
///
/// The lookup, the installer, or the installed rho failed, which the error
/// says; the rho that ran is left as the installer left it.
pub(crate) async fn update_unattended(
    current_version: &str,
    replaced: Option<String>,
    environment: &ClientEnvironment,
    report: &mut impl Report,
) -> anyhow::Result<Unattended> {
    // Read before the installer replaces the file, after which Linux may
    // name the one this process runs `… (deleted)`.
    let own_path = started_path();
    let (method, lookups) = install_method(environment).await?;
    // The upgrade watch probed it with `--version` already.
    if let Some(to) = replaced.filter(|to| version_is_newer(to, current_version)) {
        report.say(&format!(
            "rho v{to} already replaced this rho; the daemon moves onto it"
        ));
        return Ok(Unattended::Installed {
            to,
            method,
            lands: Lands::AtItsPath,
        });
    }
    if method.needs_terminal() {
        let update = latest_release(current_version)
            .await
            .context("could not check the latest rho release")?;
        if !update.is_available() {
            return Ok(Unattended::UpToDate);
        }
        return Ok(Unattended::NeedsTerminal {
            command: method.update_command_in(&install_script_ref(update.latest_tag), &lookups)?,
            latest: update.latest_version,
        });
    }
    let Some(plan) = prepare(method, current_version, report).await? else {
        return Ok(Unattended::UpToDate);
    };
    announce(method, &plan, &lookups, report)?;
    match plan {
        Plan::Run { git_ref } => {
            run_command(method, &git_ref, &lookups, environment, report).await?;
        }
        Plan::InPlace(update) => update_in_place(method, &update, report).await?,
        // Every method whose plan prints its command needs a terminal.
        Plan::Print { .. } => {
            anyhow::bail!("rho only prints the {} update command here", method.label())
        }
    }
    let (to, lands) = installed_version(method, own_path, environment, current_version).await?;
    Ok(Unattended::Installed { to, method, lands })
}

/// How the rho this process runs was installed, and what its update command
/// names, as the user's login `environment` finds them: the daemon's own
/// may lack the `PATH` that finds `cargo` and `mise`, as one started over a
/// non-interactive ssh does, and then takes a Cargo install for the
/// install script's. A daemon running from its own copy, as for a Scoop
/// install, is told by where Scoop has rho, not by the copy's path, which
/// detection would take for the install script's and update the copy.
///
/// Each update looks afresh, so a lookup that failed is not kept. The
/// lookups run tools, so they run off the async runtime, each for at most
/// [`LOOKUP_TIMEOUT`]; one that ran past it fails the update rather than
/// leaving it to guess.
async fn install_method(
    environment: &ClientEnvironment,
) -> anyhow::Result<(InstallMethod, Lookups)> {
    let copies = DaemonPaths::of_this_process().map(|paths| paths.copies_dir());
    let copied = match (super::current_exe(), copies) {
        (Ok(executable), Ok(copies)) => is_copy(&executable, &copies),
        _ => false,
    };
    let login = Login::new(
        environment.clone(),
        tokio::runtime::Handle::current(),
        LOOKUP_TIMEOUT,
    );
    tokio::task::spawn_blocking(move || {
        let method = if copied {
            match installed_scoop_scope() {
                ScoopInstallScope::User => InstallMethod::Scoop,
                ScoopInstallScope::Global => InstallMethod::ScoopGlobal,
            }
        } else {
            detect_install_method_in(&login)
        };
        let cargo_root = match method {
            InstallMethod::Cargo => cargo_update_root_in(&login),
            _ => None,
        };
        let mise_tool = match method {
            InstallMethod::Mise => Some(
                mise_tool_in(&login).context("could not find the mise tool that installed rho")?,
            ),
            _ => None,
        };
        if let Some(why) = login.timed_out() {
            anyhow::bail!("{why}");
        }
        Ok((
            method,
            Lookups::Found {
                cargo_root,
                mise_tool,
            },
        ))
    })
    .await
    .context("could not tell how rho was installed")?
    .context("could not tell how rho was installed")
}

/// The user's login, as the daemon's update asks it how rho was installed:
/// its `environment` alone, each tool run from its home for at most
/// `timeout`, [`LOOKUP_TIMEOUT`]. It blocks on `runtime` while a tool runs,
/// so it is asked off the runtime ([`tokio::task::spawn_blocking`]). It
/// keeps the first lookup that ran past its time, which then fails the
/// detection, where the tool's answer alone would read as "not installed
/// that way".
struct Login {
    environment: ClientEnvironment,
    runtime: tokio::runtime::Handle,
    timeout: Duration,
    timed_out: Mutex<Option<String>>,
}

impl Login {
    fn new(
        environment: ClientEnvironment,
        runtime: tokio::runtime::Handle,
        timeout: Duration,
    ) -> Self {
        Self {
            environment,
            runtime,
            timeout,
            timed_out: Mutex::default(),
        }
    }

    /// Why the first lookup that ran past its time failed.
    fn timed_out(&self) -> Option<String> {
        self.timed_out
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }
}

impl Probe for Login {
    fn var(&self, name: &str) -> Option<OsString> {
        self.environment
            .iter()
            .find(|(variable, _)| *variable == name)
            .map(|(_, value)| value.into())
    }

    fn output(&self, command: std::process::Command) -> io::Result<Output> {
        let shown = std::iter::once(command.get_program())
            .chain(command.get_args())
            .map(|part| part.to_string_lossy())
            .collect::<Vec<_>>()
            .join(" ");
        let mut command = tokio::process::Command::from(command);
        command
            .env_clear()
            .envs(self.environment.iter())
            .stdin(Stdio::null())
            .kill_on_drop(true);
        if let Some(home) = self.var("HOME") {
            command.current_dir(home);
        }
        let ran = self
            .runtime
            .block_on(async { tokio::time::timeout(self.timeout, command.output()).await });
        ran.unwrap_or_else(|_| {
            let why = format!(
                "`{shown}` did not answer within LOOKUP_TIMEOUT ({:?})",
                self.timeout
            );
            let mut kept = self
                .timed_out
                .lock()
                .unwrap_or_else(PoisonError::into_inner);
            if kept.is_none() {
                *kept = Some(why.clone());
            }
            Err(io::Error::new(io::ErrorKind::TimedOut, why))
        })
    }
}

/// Whether `executable` is one of the copies in `copies`, the directory
/// a daemon runs copies of rho from (`daemon::RunFrom::Copy`).
fn is_copy(executable: &Path, copies: &Path) -> bool {
    let dir = |path: &Path| std::fs::canonicalize(path).ok();
    let copies = dir(copies);
    copies.is_some() && executable.parent().and_then(dir) == copies
}

/// The version the rho `method` installed prints, and where it is: at
/// `own_path`, the path this process runs from, or, for mise and Scoop,
/// which keep each version at a path of its own, where mise says, or the
/// `rho` the login `environment`'s `PATH` finds. One that is not newer than
/// `current_version` means nothing changed, which is an error.
async fn installed_version(
    method: InstallMethod,
    own_path: io::Result<PathBuf>,
    environment: &ClientEnvironment,
    current_version: &str,
) -> anyhow::Result<(String, Lands)> {
    let (path, lands) = match method.installs() {
        Installed::OverTheExecutable | Installed::MovingTheRunningAside => (
            own_path.context("could not find the rho the daemon runs")?,
            Lands::AtItsPath,
        ),
        Installed::AtAnotherPath => {
            let path = match method {
                InstallMethod::Mise => mise_which(environment).await?,
                _ => on_path(environment)
                    .context("the installer finished, but the login PATH finds no `rho`")?,
            };
            (path.clone(), Lands::AtAnotherPath(path))
        }
    };
    let version = newer_version(&path, current_version).await?;
    Ok((version, lands))
}

/// The version the rho at `path` prints, which must be newer than
/// `current_version`.
async fn newer_version(path: &Path, current_version: &str) -> anyhow::Result<String> {
    let version = probe_version(path).await.with_context(|| {
        format!(
            "the installer finished, but {} does not run as rho",
            path.display()
        )
    })?;
    newer(path, version, current_version)
}

/// `version`, which the rho at `path` printed, unless it is no newer than
/// `current_version`: then the installer changed nothing the daemon runs.
fn newer(path: &Path, version: String, current_version: &str) -> anyhow::Result<String> {
    if !version_is_newer(&version, current_version) {
        anyhow::bail!(
            "the installer finished, but {} still reports rho {version}",
            path.display()
        );
    }
    Ok(version)
}

/// The `rho` that mise runs for the user, as `mise which rho` names it in
/// the login `environment`, from the home, so no project's mise config
/// picks another version.
async fn mise_which(environment: &ClientEnvironment) -> anyhow::Result<PathBuf> {
    let mut command = tokio::process::Command::new("mise");
    command
        .args(["which", "rho"])
        .env_clear()
        .envs(environment.iter())
        .stdin(Stdio::null())
        .kill_on_drop(true);
    if let Some((_, home)) = environment.iter().find(|(name, _)| *name == "HOME") {
        command.current_dir(home);
    }
    let output = tokio::time::timeout(LOOKUP_TIMEOUT, command.output())
        .await
        .map_err(|_| {
            anyhow::anyhow!(
                "`mise which rho` did not answer within LOOKUP_TIMEOUT ({} s)",
                LOOKUP_TIMEOUT.as_secs()
            )
        })?
        .context("could not run `mise which rho`")?;
    let printed = String::from_utf8_lossy(&output.stdout);
    let path = PathBuf::from(printed.trim());
    if !output.status.success() || !path.is_absolute() {
        anyhow::bail!(
            "`mise which rho` named no rho ({}); the installer finished all the same",
            output.status
        );
    }
    Ok(path)
}

/// The `rho` executable `environment`'s `PATH` finds first. Empty and
/// relative entries are skipped: they name nothing without a working
/// directory.
fn on_path(environment: &ClientEnvironment) -> Option<PathBuf> {
    let (_, path) = environment
        .iter()
        .find(|(name, _)| name.eq_ignore_ascii_case("PATH"))?;
    let name = format!("rho{}", std::env::consts::EXE_SUFFIX);
    std::env::split_paths(path)
        .filter(|dir| dir.is_absolute())
        .map(|dir| dir.join(&name))
        .find(|file| file.is_file())
}

#[cfg(windows)]
async fn run_command(
    method: InstallMethod,
    _git_ref: &str,
    _lookups: &Lookups,
    _environment: &ClientEnvironment,
    _report: &mut impl Report,
) -> anyhow::Result<()> {
    // Unreachable: `InstallMethod::updater` never chooses
    // `Updater::Command` on Windows, which spawns no update command.
    anyhow::bail!("rho runs no {} update command on Windows", method.label())
}

/// Runs `method`'s update command, pinned to `git_ref` and naming what
/// `lookups` found, in `environment`, saying each line it prints to
/// `report`.
#[cfg(not(windows))]
async fn run_command(
    method: InstallMethod,
    git_ref: &str,
    lookups: &Lookups,
    environment: &ClientEnvironment,
    report: &mut impl Report,
) -> anyhow::Result<()> {
    let command = super::update_command(method, git_ref, lookups, Some(environment))?;
    run_reporting(command, method.label(), INSTALLER_DEADLINE, report).await
}

/// Runs `command`, the `label` update command, with nothing on its stdin,
/// saying each line it prints, to stdout or stderr, to `report` as it
/// prints it. Fails as `rho update` does when it exits unsuccessfully, and
/// once it ran past `deadline`, when it and what it started are killed.
///
/// The update ends once the installer exited, with what it printed until
/// then and for [`PIPE_DRAIN_AFTER_EXIT`] after, so a process it left
/// running cannot hold the update up by keeping its output open. Nothing
/// kills the installer when the update is dropped, as when the daemon
/// stops: its output is read to its end all the same, while the daemon
/// runs, so it never writes to a closed pipe before then.
#[cfg(not(windows))]
async fn run_reporting(
    mut command: tokio::process::Command,
    label: &str,
    deadline: Duration,
    report: &mut impl Report,
) -> anyhow::Result<()> {
    let mut child = command
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        // Its own group, so a deadline stops what it started too.
        .process_group(0)
        .spawn()
        .with_context(|| format!("failed to run {label} update command"))?;
    let group = child.id();
    let (sender, mut lines) = tokio::sync::mpsc::unbounded_channel();
    if let Some(stdout) = child.stdout.take() {
        tokio::spawn(forward_lines(stdout, sender.clone()));
    }
    if let Some(stderr) = child.stderr.take() {
        tokio::spawn(forward_lines(stderr, sender));
    }
    let status = {
        let mut exited = std::pin::pin!(child.wait());
        let mut deadline_passed = std::pin::pin!(tokio::time::sleep(deadline));
        let mut open = true;
        loop {
            tokio::select! {
                status = &mut exited => break status,
                line = lines.recv(), if open => match line {
                    Some(line) => report.say(&line),
                    None => open = false,
                },
                () = &mut deadline_passed => {
                    if let Some(group) = group.and_then(|group| libc::pid_t::try_from(group).ok()) {
                        // SAFETY: killpg takes no pointers; the group is
                        // the installer's, which it led.
                        unsafe { libc::killpg(group, libc::SIGKILL) };
                    }
                    anyhow::bail!(
                        "{label} update command ran past INSTALLER_DEADLINE ({} min), so rho stopped it",
                        deadline.as_secs() / 60
                    );
                }
            }
        }
    }
    .with_context(|| format!("failed to run {label} update command"))?;
    let drained = async {
        while let Some(line) = lines.recv().await {
            report.say(&line);
        }
    };
    let _ = tokio::time::timeout(PIPE_DRAIN_AFTER_EXIT, drained).await;
    if !status.success() {
        anyhow::bail!("{label} update command exited with {status}");
    }
    Ok(())
}

/// Sends each line of `output` to `lines`, without its line ending and at
/// most [`LINE_MAX_BYTES`] long, until it closes. Bytes that are not UTF-8,
/// as a character a long line is split in, read as U+FFFD. Once nobody
/// listens, it reads on to the end all the same.
#[cfg(not(windows))]
async fn forward_lines(
    output: impl tokio::io::AsyncRead + Unpin,
    lines: tokio::sync::mpsc::UnboundedSender<String>,
) {
    use tokio::io::AsyncBufReadExt as _;

    let mut output = tokio::io::BufReader::new(output);
    let mut line = Vec::new();
    let send = |line: &mut Vec<u8>| {
        let text = String::from_utf8_lossy(line);
        // Fails once nobody listens; the output is read on regardless.
        let _ = lines.send(text.trim_end_matches(['\n', '\r']).to_owned());
        line.clear();
    };
    loop {
        let chunk = match output.fill_buf().await {
            Ok([]) | Err(_) => break,
            Ok(chunk) => chunk,
        };
        let room = &chunk[..chunk.len().min(LINE_MAX_BYTES - line.len())];
        let (taken, ended) = match room.iter().position(|byte| *byte == b'\n') {
            Some(end) => (end + 1, true),
            None => (room.len(), line.len() + room.len() == LINE_MAX_BYTES),
        };
        line.extend_from_slice(&room[..taken]);
        output.consume(taken);
        if ended {
            send(&mut line);
        }
    }
    if !line.is_empty() {
        send(&mut line);
    }
}

#[cfg(test)]
#[path = "update_unattended_tests.rs"]
mod tests;