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
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
//! Updating rho on the daemon's machine for a person's frontend
//! (`rho/daemon/update`, `rho/daemon/update/result`; `docs/protocol.md`,
//! "Updating rho on the daemon's machine"), and when the daemon moves onto
//! the rho it installed.
//!
//! The update runs in a task of its own, as `rho update` would
//! (`crate::update::update_unattended`), writing what it says to a host
//! stream the asking connection reads. Only one runs at a time. From its
//! start until it is settled, the upgrade watch (`upgrade.rs`) is held, so
//! the daemon never restarts onto a replaced executable before the client
//! heard what the update did. It settles once the client asked for its
//! result, once the asking connection left, or [`UNASKED_RESULT_GRACE`]
//! after it was over; then the watch makes the move it asks for: a restart
//! onto the new rho, now or once idle, or, for a rho installed at another
//! path, a stop for the next client to start it.

use std::{
    future::Future,
    sync::{Arc, Mutex, MutexGuard, PoisonError},
    time::Duration,
};

use rho_protocol::{
    Caller, ClientEnvironment, ClientInfo, ConnectionId, DaemonUpdateParams, DaemonUpdateResponse,
    DaemonUpdateResult, DaemonUpdateResultParams, ErrorCode, HostPath, HostStreamId,
    HostStreamWriter, RpcError, TryWriteError, UpdateMethod, UpdateOutcome, UpdateRestart,
    UpdateRestarting, HOST_STREAM_FAILURE_MAX_BYTES,
};
use tokio::sync::watch;

use crate::{
    cli_runtime::StderrTail,
    daemon::Shutdown,
    update::{update_unattended, InstallMethod, Lands, Report, Unattended},
};

/// How long after an update is over the daemon waits for its client to ask
/// for the result before it settles it unasked and moves as it asked.
//
// Tripwire: a client asks with one request on the connection it already
// has open, as soon as the progress stream ends, so the wait is about one
// round trip. On plane wifi, the slowest link rho-ui is built for, that
// measured 764 ms (p50), and a stall recovers within 5 s (rho-ui's
// slow-network study, 2026-12-01). A minute is 12 times the stall, and
// still frees the daemon to move when its client is stuck, or gone
// without its connection closing.
const UNASKED_RESULT_GRACE: Duration = Duration::from_secs(60);

/// The most bytes of the end of the update's output a failure's message
/// carries.
//
// As much as a host stream's failure carries, so the error says no more of
// a failure than the stream may. The installers' own failures fit in a few
// lines: install.sh's errors are one or two of under 250 bytes each
// (`scripts/install.sh`), and a failed `cargo install` ends with a
// three-line footer naming the crate that did not build.
const OUTPUT_TAIL_BYTES: usize = HOST_STREAM_FAILURE_MAX_BYTES;

/// The most bytes of why an update failed that the daemon logs and
/// answers, its start kept.
//
// As much as a host stream's failure carries, which the stream's own
// ending is cut to anyway: an error chain names its causes first.
const WHY_MAX_BYTES: usize = HOST_STREAM_FAILURE_MAX_BYTES;

/// Why an update whose task ended before it was over failed.
const STOPPED: &str = "the update stopped unexpectedly";

/// What an update needs of the daemon it runs in.
pub(super) struct Daemon {
    /// Counts the work a restart would cut short, which an update that
    /// moves once idle reports it waits for.
    pub(super) in_progress: Arc<dyn Fn() -> u64 + Send + Sync>,
    /// The version of a rho that already replaced the daemon's executable,
    /// which the upgrade watch waits to restart onto (`Upgrades::pending`).
    pub(super) replaced: Arc<dyn Fn() -> Option<String> + Send + Sync>,
    /// Requested once the daemon stops: no update starts, and none is
    /// waited for, after it.
    pub(super) shutdown: Shutdown,
}

#[cfg(test)]
impl Daemon {
    /// A daemon with no work in progress and no replacement waiting, never
    /// stopped.
    pub(super) fn idle() -> Self {
        Self {
            in_progress: Arc::new(|| 0_u64),
            replaced: Arc::new(|| None),
            shutdown: Shutdown::default(),
        }
    }
}

/// Runs one update on the daemon's machine. The daemon's own is
/// [`RhoInstall`]; tests give a stand-in.
pub(super) trait Install: Send + Sync + 'static {
    /// Updates rho, saying what it does to `progress`, with the installer
    /// in the login `environment`; `replaced` is the version of a rho that
    /// already replaced the daemon's executable. Must not wait for a
    /// person.
    fn install<'a>(
        &'a self,
        environment: ClientEnvironment,
        replaced: Option<String>,
        progress: &'a mut Progress,
    ) -> impl Future<Output = anyhow::Result<Unattended>> + Send + 'a;
}

/// Updates rho as `rho update` would.
pub(super) struct RhoInstall;

impl Install for RhoInstall {
    async fn install(
        &self,
        environment: ClientEnvironment,
        replaced: Option<String>,
        progress: &mut Progress,
    ) -> anyhow::Result<Unattended> {
        update_unattended(env!("CARGO_PKG_VERSION"), replaced, &environment, progress).await
    }
}

/// The updates the daemon's machine runs, one at a time.
pub(super) struct Updates<I = RhoInstall> {
    install: Arc<I>,
    shared: Arc<Shared>,
}

/// What the update's task and the calls share.
struct Shared {
    /// The rho version the daemon runs.
    from: String,
    daemon: Daemon,
    state: Mutex<State>,
}

#[derive(Default)]
struct State {
    /// The update under way, or over and not yet settled.
    running: Option<Running>,
    /// What the last settled update left the upgrade watch to do: never
    /// [`Follow::Held`].
    moving: Follow,
    /// The upgrade watch committed the daemon to a move ([`Updates::commit`]):
    /// no update starts.
    committed: bool,
}

impl State {
    fn follow(&self) -> Follow {
        match self.running {
            Some(_) => Follow::Held,
            None => self.moving,
        }
    }
}

/// An update from its start until it is settled. The connection that
/// asked and its progress stream name it.
struct Running {
    connection: ConnectionId,
    progress: HostStreamId,
    /// Who asked, which another asking meanwhile is told.
    client: ClientInfo,
    restart: UpdateRestart,
    /// `Some` once the update is over.
    over: watch::Receiver<Option<Over>>,
}

/// How an update ended.
#[derive(Clone, Debug)]
enum Over {
    Done(Unattended),
    /// It failed `why`, which the daemon logs; `message` adds the end of its
    /// output, for the client only.
    Failed {
        why: String,
        message: String,
    },
}

/// What the upgrade watch does about updates, at each check.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum Follow {
    /// An update runs or waits to be settled: no restart, yet.
    Held,
    /// As without an update: restart onto a replaced executable once idle.
    #[default]
    Watch,
    /// Restart now onto the replaced executable.
    RestartNow,
    /// Stop, so the next client starts the rho installed at another path:
    /// at once, or once idle.
    Replace { once_idle: bool },
}

impl<I: Install> Updates<I> {
    /// Updates run by `install` in `daemon`.
    pub(super) fn new(install: I, daemon: Daemon) -> Self {
        Self {
            install: Arc::new(install),
            shared: Arc::new(Shared {
                from: env!("CARGO_PKG_VERSION").to_owned(),
                daemon,
                state: Mutex::default(),
            }),
        }
    }

    /// Answers `rho/daemon/update`: starts the update `caller` asked for,
    /// with the installer in the login `environment`, unless one is under
    /// way or waits for its result, or the daemon is moving onto a new rho
    /// or stopping.
    pub(super) fn start(
        &self,
        caller: Caller,
        params: DaemonUpdateParams,
        environment: ClientEnvironment,
    ) -> Result<DaemonUpdateResponse, RpcError> {
        if self.shared.daemon.shutdown.is_requested() {
            return Err(stopping("updates nothing"));
        }
        let mut state = lock(&self.shared.state);
        if state.committed {
            return Err(RpcError::new(
                ErrorCode::HostCallFailed,
                "the daemon is moving onto a new rho, so it starts no update; ask again once it runs",
            ));
        }
        if let Some(running) = &state.running {
            let under_way = match *running.over.borrow() {
                Some(_) => "an update is over and waits for its result",
                None => "an update is already running",
            };
            return Err(RpcError::new(
                ErrorCode::HostCallFailed,
                format!(
                    "{under_way}, asked for by {} {}",
                    running.client.name, running.client.version
                ),
            ));
        }
        let writer = caller.open_stream()?;
        let progress = writer.id().clone();
        let (finished, over) = watch::channel(None);
        state.running = Some(Running {
            connection: caller.connection,
            progress: progress.clone(),
            client: caller.client.clone(),
            restart: params.restart,
            over,
        });
        drop(state);
        tracing::info!(
            connection = ?caller.connection,
            client = ?caller.client.name,
            client_version = ?caller.client.version,
            from = %self.shared.from,
            restart = ?params.restart,
            "update started"
        );
        // No clone of `caller` outlives this call, which would keep its
        // connection's streams, and so `left`, from ending.
        let (connection, left) = (caller.connection, caller.left());
        let replaced = (self.shared.daemon.replaced)();
        let install = Arc::clone(&self.install);
        let task = Task {
            shared: Arc::clone(&self.shared),
            connection,
            progress: progress.clone(),
            finished,
        };
        tokio::spawn(async move {
            let mut said = Progress::new(writer);
            let done = install.install(environment, replaced, &mut said).await;
            let over = said.end(done);
            match &over {
                Over::Done(done) => tracing::info!(?connection, outcome = ?done, "update over"),
                Over::Failed { why, .. } => tracing::warn!(?connection, %why, "update failed"),
            }
            task.finished.send_replace(Some(over));
            // Settled by then, unless the client never asked.
            let unasked = tokio::select! {
                () = left => "the connection that asked left without asking for its result",
                () = tokio::time::sleep(UNASKED_RESULT_GRACE) => "its result was not asked for within UNASKED_RESULT_GRACE",
            };
            // Nobody hears the answer then.
            if task.shared.settle(connection, &task.progress).is_some() {
                tracing::info!(
                    ?connection,
                    grace_secs = UNASKED_RESULT_GRACE.as_secs(),
                    "update settled: {unasked}"
                );
            }
        });
        Ok(DaemonUpdateResponse::new(
            progress,
            self.shared.from.clone(),
        ))
    }

    /// Answers `rho/daemon/update/result`: once the update `caller`'s
    /// connection started is over, what it did, leaving the move onto the
    /// new rho to the upgrade watch.
    pub(super) async fn result(
        &self,
        caller: &Caller,
        params: DaemonUpdateResultParams,
    ) -> Result<DaemonUpdateResult, RpcError> {
        let unknown = || {
            RpcError::new(
                ErrorCode::InvalidParams,
                format!(
                    "no update this connection started is waiting for its answer with progress stream {}",
                    params.progress
                ),
            )
        };
        let mut over = {
            let state = lock(&self.shared.state);
            match &state.running {
                Some(running)
                    if running.connection == caller.connection
                        && running.progress == params.progress =>
                {
                    running.over.clone()
                }
                _ => return Err(unknown()),
            }
        };
        // A stopping daemon answers so, as docs/protocol.md says, even for
        // an update that is over.
        tokio::select! {
            biased;
            () = self.shared.daemon.shutdown.requested() => {
                return Err(stopping("will not answer the update"));
            }
            // Fails only once the task is gone without saying, which
            // `settle` then answers.
            _ = over.wait_for(Option::is_some) => {}
        }
        match self.shared.settle(caller.connection, &params.progress) {
            Some(Ok(outcome)) => Ok(DaemonUpdateResult::new(outcome)),
            Some(Err(message)) => Err(RpcError::new(ErrorCode::HostCallFailed, message)),
            None => match &*over.borrow() {
                // Settled as its task stopped (`Task`'s drop), which still
                // tells the result that waited for it.
                Some(Over::Failed { message, .. }) => {
                    Err(RpcError::new(ErrorCode::HostCallFailed, message.clone()))
                }
                // Settled meanwhile, as when the grace ran out.
                _ => Err(unknown()),
            },
        }
    }

    /// What the upgrade watch does about updates now.
    pub(super) fn follow(&self) -> Follow {
        lock(&self.shared.state).follow()
    }

    /// Commits the daemon to the move `follow` asks, as the upgrade watch
    /// found it at its check, once `claim` claimed the daemon idle where
    /// the move waits for that: unless an update started or settled since,
    /// or holds the watch, when it claims nothing. From then on no update
    /// starts. `claim` runs under the updates' lock, so none can start
    /// between it and the commit; it takes the job registry's locks, which
    /// `settle` also takes under this one, in the same order.
    pub(super) fn commit(&self, follow: Follow, claim: impl FnOnce() -> bool) -> bool {
        let mut state = lock(&self.shared.state);
        if follow == Follow::Held || state.follow() != follow {
            return false;
        }
        let committed = claim();
        state.committed |= committed;
        committed
    }
}

/// The update's task, which settles the update if it ends before it did,
/// as a panic in the installer or the runtime stopping ends it: a result
/// that waits hears [`STOPPED`], and neither the slot nor the upgrade watch
/// waits for an answer that never comes.
struct Task {
    shared: Arc<Shared>,
    connection: ConnectionId,
    progress: HostStreamId,
    /// Says how the update ended, once it did.
    finished: watch::Sender<Option<Over>>,
}

impl Drop for Task {
    fn drop(&mut self) {
        let stopped = self.finished.send_if_modified(|over| {
            if over.is_some() {
                return false;
            }
            *over = Some(Over::Failed {
                why: STOPPED.to_owned(),
                message: format!("could not update rho: {STOPPED}"),
            });
            true
        });
        let settled = self
            .shared
            .settle(self.connection, &self.progress)
            .is_some();
        if stopped {
            tracing::warn!(connection = ?self.connection, settled, "{STOPPED}");
        }
    }
}

impl Shared {
    /// Answers the update `connection` started with `progress` once it is
    /// over, unless it was settled already, and leaves the move it asks
    /// for to the upgrade watch. `None` once it was settled.
    fn settle(
        &self,
        connection: ConnectionId,
        progress: &HostStreamId,
    ) -> Option<Result<UpdateOutcome, String>> {
        let mut state = lock(&self.state);
        let running = state
            .running
            .take_if(|running| running.connection == connection && running.progress == *progress)?;
        let over = (*running.over.borrow())
            .clone()
            .unwrap_or_else(|| Over::Failed {
                why: STOPPED.to_owned(),
                message: format!("could not update rho: {STOPPED}"),
            });
        Some(match over {
            Over::Failed { message, .. } => Err(message),
            Over::Done(Unattended::UpToDate) => Ok(UpdateOutcome::UpToDate),
            Over::Done(Unattended::NeedsTerminal { latest, command }) => {
                Ok(UpdateOutcome::needs_terminal(latest, command))
            }
            Over::Done(Unattended::Installed { to, method, lands }) => {
                let (restarting, moving) =
                    next_move(lands, running.restart, (self.daemon.in_progress)());
                tracing::info!(
                    connection = ?running.connection,
                    client = ?running.client.name,
                    client_version = ?running.client.version,
                    from = %self.from,
                    %to,
                    method = method.label(),
                    restart = ?restarting,
                    "rho updated"
                );
                state.moving = moving;
                Ok(UpdateOutcome::installed(to, method.into(), restarting))
            }
        })
    }
}

/// What the daemon tells the client and leaves the upgrade watch to do once
/// rho is installed where `lands` says, as `restart` asked, with
/// `in_progress` work a restart would cut short.
fn next_move(lands: Lands, restart: UpdateRestart, in_progress: u64) -> (UpdateRestarting, Follow) {
    let now = restart == UpdateRestart::Now;
    match lands {
        Lands::AtItsPath if now => (UpdateRestarting::Now, Follow::RestartNow),
        // The watch follows a replaced executable once idle anyway.
        Lands::AtItsPath => (UpdateRestarting::when_idle(in_progress), Follow::Watch),
        Lands::AtAnotherPath(at) => {
            // A path that is not UTF-8 is named as near as it can be.
            let at = HostPath::new(at.to_string_lossy());
            let waiting_for = (!now && in_progress > 0).then_some(in_progress);
            (
                UpdateRestarting::replaced(at, waiting_for),
                Follow::Replace { once_idle: !now },
            )
        }
    }
}

impl From<InstallMethod> for UpdateMethod {
    fn from(method: InstallMethod) -> Self {
        match method {
            InstallMethod::Cargo => Self::Cargo,
            InstallMethod::Mise => Self::Mise,
            InstallMethod::Pacman => Self::Pacman,
            InstallMethod::Dnf => Self::Dnf,
            InstallMethod::Scoop => Self::Scoop,
            InstallMethod::ScoopGlobal => Self::ScoopGlobal,
            InstallMethod::Script => Self::Script,
        }
    }
}

/// The daemon is stopping, so it `does` nothing more for an update.
fn stopping(does: &str) -> RpcError {
    RpcError::new(
        ErrorCode::HostCallFailed,
        format!("the daemon is stopping, so it {does}; ask again once it runs"),
    )
}

/// The update's progress stream, which never holds the update up: a line
/// the client left no room for ends it truncated, and later lines go
/// nowhere. It keeps the last [`OUTPUT_TAIL_BYTES`] all the same, for a
/// failure's message.
pub(super) struct Progress {
    /// `None` once the stream ended or the client closed it.
    stream: Option<HostStreamWriter>,
    tail: StderrTail,
}

impl Progress {
    fn new(writer: HostStreamWriter) -> Self {
        Self {
            stream: Some(writer),
            tail: StderrTail::with_limit(OUTPUT_TAIL_BYTES),
        }
    }

    fn line(&mut self, line: &str) {
        let mut bytes = Vec::with_capacity(line.len() + 1);
        bytes.extend_from_slice(line.as_bytes());
        bytes.push(b'\n');
        self.tail.push(&bytes);
        let Some(writer) = &mut self.stream else {
            return;
        };
        match writer.try_write(bytes) {
            Ok(()) => {}
            Err(TryWriteError::Closed) => self.stream = None,
            // Full: the stream holds as much as it may unread.
            Err(_) => {
                if let Some(writer) = self.stream.take() {
                    writer.truncate();
                }
            }
        }
    }

    /// Ends the stream as the update `done`, and says how it ended.
    fn end(self, done: anyhow::Result<Unattended>) -> Over {
        match done {
            Ok(done) => {
                if let Some(writer) = self.stream {
                    writer.finish();
                }
                Over::Done(done)
            }
            Err(error) => {
                let why = cut(format!("{error:#}"), WHY_MAX_BYTES);
                if let Some(writer) = self.stream {
                    writer.fail(why.clone());
                }
                Over::Failed {
                    message: failure(&why, self.tail),
                    why,
                }
            }
        }
    }
}

impl Report for Progress {
    fn say(&mut self, line: &str) {
        self.line(line);
    }

    fn warn(&mut self, line: &str) {
        self.line(line);
    }
}

/// `text`, cut to at most `max` bytes, its start kept and an ellipsis
/// ending it where it was cut.
fn cut(text: String, max: usize) -> String {
    if text.len() <= max {
        return text;
    }
    let end = rho_sdk::floor_char_boundary(&text, max - rho_sdk::ELLIPSIS.len());
    format!("{}{}", &text[..end], rho_sdk::ELLIPSIS)
}

/// A failed update's message for people: `why`, then the end of what it
/// said, `tail`.
fn failure(why: &str, tail: StderrTail) -> String {
    let tail = tail.finish();
    if tail.is_empty() {
        return format!("could not update rho: {why}");
    }
    format!(
        "could not update rho: {why}\nthe end of its output, at most {OUTPUT_TAIL_BYTES} bytes:\n{tail}"
    )
}

fn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {
    // Each change is made whole under the lock, so a panic leaves none
    // half-made.
    state.lock().unwrap_or_else(PoisonError::into_inner)
}

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