rho-coding-agent 3.12.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
//! The daemon's machine, as host calls read it for a person's frontend
//! (`rho/host/*`; `docs/protocol.md`, "The daemon's machine"). Each call is
//! logged with the connection and client that made it, since host calls
//! read the user's files and environment outside any session's approvals.
//! Updating rho there is `machine_update.rs`'s.

use std::{
    ffi::OsString,
    future::Future,
    path::{Path, PathBuf},
    process::Stdio,
    time::Duration,
};

use rho_protocol::{
    methods::{
        HostStreamId, DAEMON_RESTART, DAEMON_UPDATE, DAEMON_UPDATE_CHECK, DAEMON_UPDATE_RESULT,
        HOST_INFO,
    },
    Caller, ClientEnvironment, DaemonUpdateCheck, DaemonUpdateCheckParams, DaemonUpdateParams,
    DaemonUpdateResponse, DaemonUpdateResult, DaemonUpdateResultParams, DeviceService, ErrorCode,
    ForgeService, FsService, GitService, HostInfo, HostInfoParams, HostPath, HostService,
    HostStreamWriter, RpcError, ShellService,
};
use tokio::sync::OnceCell;

use super::{
    devices::Devices,
    machine_forge::Web,
    machine_shell::Shells,
    machine_update::{self, Daemon, RhoInstall, Updates},
};

/// How long the login shell may take to print its environment.
//
// rho-ui gives its ssh setup, which runs the same `$SHELL -l -c env`, 30 s.
// Here `zsh -l -c env` took 10 ms or less (5 runs), and 2.1 s over a fresh
// ssh connection; 30 s catches a login profile that waits for input or a
// home directory that hangs.
pub(super) const LOGIN_SHELL_DEADLINE: Duration = Duration::from_secs(30);

/// What the login shell prints before its `env`, after whatever its login
/// files print.
const ENV_MARKER: &str = "--rho-login-environment--";

/// The variables of the daemon's own environment a login shell starts
/// with, as one sshd or login(1) starts would: who and where the user is,
/// the locale, and where programs are. The rest of the daemon's
/// environment, such as a session's depth or trust when an agent started
/// the daemon, is the daemon's and never a login's. `HOME` and `SHELL` come
/// from the passwd database.
const LOGIN_VARIABLES: &[&str] = &[
    "USER",
    "LOGNAME",
    "PATH",
    "LANG",
    "LC_ALL",
    "TZ",
    "TMPDIR",
    "XDG_RUNTIME_DIR",
];

/// The daemon's machine.
pub(super) struct Machine {
    rho_home: PathBuf,
    /// Where the environment its calls run programs with comes from.
    environment: Environment,
    /// How `rho/forge/fetch` reaches the web, its client made on the first
    /// fetch.
    forge_web: Web,
    updates: Updates,
    /// The shells `rho/host/shell/*` runs, by connection.
    shells: Shells,
    /// Answers `rho/device/*`, knowing the bridge devices connected now.
    devices: Devices,
}

/// Where the environment a machine's calls run programs with comes from.
enum Environment {
    /// The user's login, as the passwd database names it, which sshd starts
    /// too: an auto-started daemon's environment has no `SHELL`. The cell
    /// keeps what its shell printed the first time a call needed it, until
    /// the daemon restarts. A shell that failed fast is asked again; one
    /// that hung keeps its fallback, so no call waits on it twice.
    Login(Login, OnceCell<(ClientEnvironment, Origin)>),
    /// No login, as on Windows or when the lookup failed: the daemon's own.
    Daemon,
    /// A test's, standing for what a login shell printed.
    #[cfg(test)]
    Given(ClientEnvironment),
}

/// Where a machine's environment came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Origin {
    /// The login shell printed it, so its `PATH` finds what a terminal's
    /// does.
    LoginShell,
    /// The login shell failed fast, and this is what it starts from, or
    /// there is no login and this is the daemon's own: a terminal may find
    /// programs this `PATH` doesn't, and the shell is asked again next time.
    Fallback,
    /// The login shell hung, and this is what it starts from until the
    /// daemon restarts: nothing asks that shell again.
    Hung,
}

/// Where the user logs in, and with what.
#[derive(Clone)]
struct Login {
    home: PathBuf,
    shell: PathBuf,
}

/// Why the login shell printed no environment.
enum ShellFailed {
    /// It ran past [`LOGIN_SHELL_DEADLINE`]: asking again would wait as long.
    Hung,
    Failed(String),
}

impl Machine {
    /// The machine of `daemon`, whose home is `rho_home`.
    pub(super) fn new(rho_home: &Path, daemon: Daemon) -> Self {
        #[cfg(unix)]
        let login = match crate::daemon::login_account() {
            Ok(account) => Some(Login {
                home: account.home,
                shell: account.shell,
            }),
            Err(error) => {
                tracing::warn!("host info names no login shell: {error:#}");
                None
            }
        };
        #[cfg(not(unix))]
        let login = None;
        Self::with_login(rho_home, login, daemon)
    }

    /// A machine with no login shell, whose calls run with the daemon's
    /// own environment: for tests of calls that need no login.
    #[cfg(test)]
    pub(super) fn without_login(rho_home: &Path) -> Self {
        Self::with_login(rho_home, None, Daemon::idle())
    }

    /// A machine whose calls run with `environment` alone, as if its login
    /// shell printed it, not the test process's: for tests of calls that
    /// run programs the login's `PATH` finds, as `gh`.
    #[cfg(test)]
    pub(super) fn with_environment(rho_home: &Path, environment: ClientEnvironment) -> Self {
        Self::with(rho_home, Environment::Given(environment), Daemon::idle())
    }

    fn with_login(rho_home: &Path, login: Option<Login>, daemon: Daemon) -> Self {
        let environment = match login {
            Some(login) => Environment::Login(login, OnceCell::new()),
            None => Environment::Daemon,
        };
        Self::with(rho_home, environment, daemon)
    }

    fn with(rho_home: &Path, environment: Environment, daemon: Daemon) -> Self {
        Self {
            rho_home: rho_home.to_path_buf(),
            environment,
            forge_web: Web::public(),
            updates: Updates::new(RhoInstall, daemon),
            shells: Shells::default(),
            devices: Devices::default(),
        }
    }

    /// The updates of rho on the machine, which the upgrade watch follows.
    pub(super) fn updates(&self) -> &Updates {
        &self.updates
    }

    /// The user's login, if the daemon knows it.
    fn login(&self) -> Option<&Login> {
        match &self.environment {
            Environment::Login(login, _) => Some(login),
            _ => None,
        }
    }

    /// The shells `rho/host/shell/*` runs.
    pub(super) fn shells(&self) -> &Shells {
        &self.shells
    }

    /// The user's login shell, as the passwd database names it, if the
    /// daemon knows it.
    pub(super) fn login_shell(&self) -> Option<PathBuf> {
        Some(self.login()?.shell.clone())
    }

    /// How `rho/forge/fetch` reaches the web.
    pub(super) fn forge_web(&self) -> &Web {
        &self.forge_web
    }

    /// The environment a login shell starts with: what the user's login
    /// shell printed or, when it failed, what it would have started from.
    /// With no login shell, the daemon's own. The `rho/fs/*`, `rho/git/*`
    /// and `rho/forge/*` calls run git and `gh` with it, so each is the one
    /// the user's shell would find.
    pub(super) async fn login_environment(&self) -> ClientEnvironment {
        self.login_environment_and_origin().await.0
    }

    /// [`Self::login_environment`], and where it came from.
    pub(super) async fn login_environment_and_origin(&self) -> (ClientEnvironment, Origin) {
        let (login, read) = match &self.environment {
            Environment::Login(login, read) => (login, read),
            Environment::Daemon => return (ClientEnvironment::of_this_process(), Origin::Fallback),
            #[cfg(test)]
            Environment::Given(environment) => return (environment.clone(), Origin::LoginShell),
        };
        let read = read
            .get_or_try_init(|| async {
                match login_shell_environment(login).await {
                    Ok(environment) => Ok((environment, Origin::LoginShell)),
                    Err(ShellFailed::Hung) => {
                        tracing::warn!(
                            shell = %login.shell.display(),
                            "the login shell printed no environment within {} s, so host info gives the one it starts from until the daemon restarts",
                            LOGIN_SHELL_DEADLINE.as_secs()
                        );
                        Ok((starting_environment(login), Origin::Hung))
                    }
                    Err(ShellFailed::Failed(why)) => Err(why),
                }
            })
            .await;
        match read {
            Ok(read) => read.clone(),
            Err(why) => {
                tracing::warn!(
                    shell = %login.shell.display(),
                    "the login shell printed no environment, so host info gives the one it starts from: {why}"
                );
                (starting_environment(login), Origin::Fallback)
            }
        }
    }
}

impl HostService for Machine {
    fn restart_asked(&self, caller: &Caller) {
        log_call(caller, DAEMON_RESTART, []);
    }

    async fn host_info(&self, caller: Caller, _: HostInfoParams) -> Result<HostInfo, RpcError> {
        log_call(&caller, HOST_INFO, []);
        let home = crate::paths::home_dir()
            .or_else(|| Some(self.login()?.home.clone()))
            .ok_or_else(|| {
                RpcError::new(
                    ErrorCode::InternalError,
                    "neither the daemon's environment nor the passwd database names a home directory",
                )
            })?;
        let shell = self
            .login()
            .map(|login| host_path(&login.shell))
            .transpose()?;
        Ok(HostInfo::new(
            host_path(&home)?,
            host_path(&self.rho_home)?,
            self.login_environment().await,
        )
        .with_shell(shell))
    }

    async fn update(
        &self,
        caller: Caller,
        params: DaemonUpdateParams,
    ) -> Result<DaemonUpdateResponse, RpcError> {
        log_call(&caller, DAEMON_UPDATE, []);
        // The installer runs as in a login there, as `rho update` over ssh
        // would. Read once per daemon, so only the first host call waits.
        let environment = self.login_environment().await;
        self.updates.start(caller, params, environment)
    }

    async fn update_result(
        &self,
        caller: Caller,
        params: DaemonUpdateResultParams,
    ) -> Result<DaemonUpdateResult, RpcError> {
        log_call(&caller, DAEMON_UPDATE_RESULT, []);
        self.updates.result(&caller, params).await
    }

    async fn update_check(
        &self,
        caller: Caller,
        _: DaemonUpdateCheckParams,
    ) -> Result<DaemonUpdateCheck, RpcError> {
        log_call(&caller, DAEMON_UPDATE_CHECK, []);
        // How rho was installed is found as the update finds it.
        let environment = self.login_environment().await;
        machine_update::check(environment).await
    }

    /// Answered in `machine_fs/`.
    fn fs(&self) -> &impl FsService {
        self
    }

    /// Answered in `machine_git/`.
    fn git(&self) -> &impl GitService {
        self
    }

    /// Answered in `machine_forge/`.
    fn forge(&self) -> &impl ForgeService {
        self
    }

    /// Answered in `machine_shell/`.
    fn shell(&self) -> &impl ShellService {
        self
    }

    /// Answered in `devices.rs`.
    fn devices(&self) -> &impl DeviceService {
        &self.devices
    }
}

/// Logs a host call: which, who made it, and the `paths` it names, if
/// any, never what a file holds. The client names itself, so its name and
/// version are quoted.
pub(super) fn log_call<'a>(
    caller: &Caller,
    method: &str,
    paths: impl IntoIterator<Item = &'a HostPath>,
) {
    let paths: Vec<&str> = paths.into_iter().map(HostPath::as_str).collect();
    // None records no field, so a call that names no path logs none.
    let paths = (!paths.is_empty()).then(|| tracing::field::debug(paths));
    tracing::info!(
        connection = ?caller.connection,
        client = ?caller.client.name,
        client_version = ?caller.client.version,
        method,
        paths,
        "host call"
    );
}

/// Logs a host call that names a list of `paths`, as [`log_call`] does,
/// but with how many at info and which at debug, so a client asking about
/// many files at once doesn't fill the log.
pub(super) fn log_call_counted(caller: &Caller, method: &str, paths: &[HostPath]) {
    tracing::info!(
        connection = ?caller.connection,
        client = ?caller.client.name,
        client_version = ?caller.client.version,
        method,
        count = paths.len(),
        "host call"
    );
    tracing::debug!(
        connection = ?caller.connection,
        method,
        paths = ?paths.iter().map(HostPath::as_str).collect::<Vec<_>>(),
        "host call paths"
    );
}

/// Runs blocking file work off the runtime's threads.
pub(super) async fn blocking<T: Send + 'static>(
    work: impl FnOnce() -> T + Send + 'static,
) -> Result<T, RpcError> {
    tokio::task::spawn_blocking(work).await.map_err(|error| {
        RpcError::new(
            ErrorCode::InternalError,
            format!("the work on the daemon's machine stopped: {error}"),
        )
    })
}

/// Work on the machine that failed, for the reason `message` gives people.
pub(super) fn failed(message: impl Into<String>) -> RpcError {
    RpcError::new(ErrorCode::HostCallFailed, message)
}

/// Opens a host stream for `caller` and starts `write` writing it, for an
/// answer that names the stream.
pub(super) fn spawn_stream<F>(
    caller: &Caller,
    write: impl FnOnce(HostStreamWriter) -> F,
) -> Result<HostStreamId, RpcError>
where
    F: Future<Output = ()> + Send + 'static,
{
    let writer = caller.open_stream()?;
    let stream = writer.id().clone();
    tokio::spawn(write(writer));
    Ok(stream)
}

/// Kills the process group `leader` leads, with all it started in it: for
/// a child started in a group or session of its own, by the id it had
/// (`Child::id`, `None` once reaped), as the login shell and a clone stop.
#[cfg(unix)]
pub(super) fn kill_group(leader: Option<u32>) {
    signal_group(leader, libc::SIGKILL);
}

/// Sends `signal` to the process group `leader` leads, as [`kill_group`]
/// does; signal 0 sends none. Answers whether the group had a member.
#[cfg(unix)]
pub(super) fn signal_group(leader: Option<u32>, signal: libc::c_int) -> bool {
    let Some(group) = leader.and_then(|id| libc::pid_t::try_from(id).ok()) else {
        return false;
    };
    // SAFETY: killpg takes no pointers. The group is the child's: no
    // process takes its id while the group has members, and once it has
    // none, killpg finds nothing to signal.
    unsafe { libc::killpg(group, signal) == 0 }
}

/// `path` as a path, refusing a relative one, which would name a file in
/// wherever the daemon happens to run.
pub(super) fn absolute(path: &HostPath) -> Result<&Path, RpcError> {
    let local = Path::new(path.as_str());
    if local.is_absolute() {
        Ok(local)
    } else {
        Err(RpcError::new(
            ErrorCode::InvalidParams,
            format!("{path} isn't an absolute path"),
        ))
    }
}

/// `path` as a host call spells it, if it is UTF-8.
pub(super) fn host_path(path: &Path) -> Result<HostPath, RpcError> {
    path.to_str().map(HostPath::new).ok_or_else(|| {
        RpcError::new(
            ErrorCode::InternalError,
            format!(
                "{} is not UTF-8, so a host call cannot name it",
                path.display()
            ),
        )
    })
}

/// What a login shell for `login` starts with ([`LOGIN_VARIABLES`]).
fn starting_variables(login: &Login) -> Vec<(OsString, OsString)> {
    let mut variables: Vec<(OsString, OsString)> = LOGIN_VARIABLES
        .iter()
        .filter_map(|name| Some((OsString::from(name), std::env::var_os(name)?)))
        .collect();
    variables.push(("HOME".into(), login.home.clone().into()));
    variables.push(("SHELL".into(), login.shell.clone().into()));
    variables
}

/// [`starting_variables`] as a client sends them: a variable that is not
/// UTF-8 is left out.
fn starting_environment(login: &Login) -> ClientEnvironment {
    starting_variables(login)
        .into_iter()
        .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
        .collect()
}

/// What `login`'s shell prints as its environment, after [`ENV_MARKER`],
/// started in the home with only [`starting_variables`], as a login is.
/// `env -0` would be easier to read, but macOS and the BSDs lack it.
#[cfg(unix)]
async fn login_shell_environment(login: &Login) -> Result<ClientEnvironment, ShellFailed> {
    let script = format!("printf '\\n%s\\n' {ENV_MARKER}; env");
    let child = tokio::process::Command::new(&login.shell)
        .arg("-l")
        .arg("-c")
        .arg(script)
        .env_clear()
        .envs(starting_variables(login))
        .current_dir(&login.home)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        // Its own group, so whatever its login files started goes with it.
        .process_group(0)
        .kill_on_drop(true)
        .spawn()
        .map_err(|error| ShellFailed::Failed(format!("it did not start: {error}")))?;
    let group = child.id();
    let output = match tokio::time::timeout(LOGIN_SHELL_DEADLINE, child.wait_with_output()).await {
        Ok(output) => output.map_err(|error| ShellFailed::Failed(error.to_string()))?,
        Err(_) => {
            kill_group(group);
            return Err(ShellFailed::Hung);
        }
    };
    if !output.status.success() {
        return Err(ShellFailed::Failed(format!(
            "it exited with {}",
            output.status
        )));
    }
    let marker = format!("\n{ENV_MARKER}\n");
    let start = output
        .stdout
        .windows(marker.len())
        .position(|window| window == marker.as_bytes())
        .ok_or_else(|| ShellFailed::Failed("its output was cut short".to_owned()))?;
    Ok(parse_env(&output.stdout[start + marker.len()..]))
}

#[cfg(not(unix))]
async fn login_shell_environment(_: &Login) -> Result<ClientEnvironment, ShellFailed> {
    Err(ShellFailed::Failed("no login shell here".to_owned()))
}

/// Reads `env`'s output: `NAME=value` lines, where a line that does not
/// start with a word and `=` continues the value before it, which held a
/// newline. Entries whose name isn't a variable's, such as the
/// `BASH_FUNC_name%%=() {` lines of functions bash exports, are dropped
/// with the lines that continue them, and so are values that are not
/// UTF-8, which the wire cannot carry. A value whose own lines look like
/// `NAME=value` reads wrong; `env` gives no way to tell. rho-ui reads the
/// same over ssh the same way.
fn parse_env(output: &[u8]) -> ClientEnvironment {
    // Each variable's name and value, the value `None` once a line of it
    // was not UTF-8.
    let mut variables: Vec<(String, Option<String>)> = Vec::new();
    let output = output.strip_suffix(b"\n").unwrap_or(output);
    for line in output.split(|&byte| byte == b'\n') {
        let line = std::str::from_utf8(line).ok();
        match line.and_then(|line| line.split_once('=')) {
            Some((name, value)) if !name.is_empty() && !name.contains(char::is_whitespace) => {
                variables.push((name.to_owned(), Some(value.to_owned())));
            }
            _ => {
                if let Some((_, value)) = variables.last_mut() {
                    *value = value.take().zip(line).map(|(mut value, line)| {
                        value.push('\n');
                        value.push_str(line);
                        value
                    });
                }
            }
        }
    }
    variables
        .into_iter()
        .filter(|(name, _)| is_name(name))
        .filter_map(|(name, value)| Some((name, value?)))
        .collect()
}

/// Whether `name` is a shell variable name: `[A-Za-z_][A-Za-z0-9_]*`.
fn is_name(name: &str) -> bool {
    let mut chars = name.chars();
    chars
        .next()
        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

#[cfg(all(test, unix))]
#[path = "machine_tests.rs"]
mod tests;