rho-coding-agent 3.7.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
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
//! Install, link, update, enable, disable, and remove for Agent Plugin packages.
//!
//! These operations validate package shape and rewrite Rho-owned state only.
//! They never execute package code, never touch `data/<plugin>`, and never
//! write outside the chosen managed plugins root. Git installs fetch into a
//! temporary checkout first and then copy like a local install.

use std::{
    fs,
    path::{Path, PathBuf},
};

use super::{
    contain, discovery_roots,
    manifest::{self, PluginManifest},
    state::{
        project_plugins_root, user_plugins_root, InstallRecord, PluginOrigin, PluginScope,
        PluginStateStore,
    },
};

#[path = "manage_error.rs"]
mod error;
#[path = "manage_git.rs"]
mod git;
pub(crate) use error::ManageError;
pub(crate) use git::{install_git, update, UpdateOutcome, UpdateReport, UpdateSelection};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InstallMode {
    Copy,
    Link,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ManagedPackage {
    pub(crate) name: String,
    pub(crate) version: Option<String>,
    pub(crate) description: Option<String>,
    pub(crate) scope: PluginScope,
    pub(crate) origin: PluginOrigin,
    pub(crate) path: PathBuf,
    pub(crate) link_target: Option<PathBuf>,
}

#[derive(Clone, Debug)]
pub(crate) struct SourcePackage {
    pub(crate) path: PathBuf,
    pub(crate) manifest: PluginManifest,
}

/// The installed plugin a command names.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct NamedPlugin<'a> {
    pub(crate) name: &'a str,
    /// The scope whose roots to search; `None` searches every root, nearest
    /// project root first, as the CLI does.
    pub(crate) scope: Option<PluginScope>,
}

impl<'a> NamedPlugin<'a> {
    /// `name` in whichever root holds it first.
    pub(crate) fn any_scope(name: &'a str) -> Self {
        Self { name, scope: None }
    }

    /// `name` in `scope`'s roots only.
    pub(crate) fn in_scope(name: &'a str, scope: PluginScope) -> Self {
        Self {
            name,
            scope: Some(scope),
        }
    }

    /// Whether a plugin in `scope` may be this one.
    pub(crate) fn covers(&self, scope: PluginScope) -> bool {
        self.scope.is_none_or(|wanted| wanted == scope)
    }
}

struct ResolvedPackage {
    package: ManagedPackage,
    root: PathBuf,
}

/// Validate a local package directory without executing any component code.
pub(crate) fn inspect_source(path: &Path) -> Result<SourcePackage, ManageError> {
    let invalid = |error| ManageError::InvalidPackage(format!("invalid plugin package: {error}"));
    let canonical = contain::canonical_root(path).map_err(invalid)?;
    let manifest_path = canonical.join("plugin.json");
    if !manifest_path.is_file() {
        return Err(invalid(format!(
            "{} has no plugin.json",
            crate::paths::display(&canonical)
        )));
    }
    let contained = contain::contained_path(&canonical, &manifest_path).map_err(invalid)?;
    let text = fs::read_to_string(&contained)?;
    let manifest = manifest::parse_manifest(&text).map_err(invalid)?;
    Ok(SourcePackage {
        path: canonical,
        manifest,
    })
}

pub(crate) fn install(
    source: &Path,
    scope: PluginScope,
    mode: InstallMode,
    force: bool,
    cwd: &Path,
    home: &Path,
    rho_home: Option<&Path>,
) -> Result<ManagedPackage, ManageError> {
    let root = managed_root(scope, cwd, home)?;
    let mut state = PluginStateStore::load(cwd, Some(home), rho_home)?;
    // Relative CLI paths resolve against the invocation directory.
    let source = inspect_source(&cwd.join(source))?;
    let record = match mode {
        InstallMode::Copy => InstallRecord::Copy,
        InstallMode::Link => InstallRecord::Link {
            target: crate::paths::display(&source.path),
        },
    };
    install_validated(source, &record, scope, &root, force, &mut state)
}

/// Place a validated package into `root` (the [`managed_root`] for `scope`)
/// as `record` describes, then record it in `state`.
fn install_validated(
    source: SourcePackage,
    record: &InstallRecord,
    scope: PluginScope,
    root: &Path,
    force: bool,
    state: &mut PluginStateStore,
) -> Result<ManagedPackage, ManageError> {
    let (mode, link_target) = match record {
        InstallRecord::Copy | InstallRecord::Git(_) => (InstallMode::Copy, None),
        InstallRecord::Link { target } => (InstallMode::Link, Some(PathBuf::from(target))),
    };
    let destination = place(&source, root, mode, force)?;
    state.record_install(scope, &source.manifest.name, record.clone())?;

    Ok(ManagedPackage {
        name: source.manifest.name,
        version: source.manifest.version,
        description: source.manifest.description,
        scope,
        origin: record.origin(),
        path: destination,
        link_target,
    })
}

/// Copy or link a validated package into `root`, swapping out any existing
/// package only after staging succeeds.
fn place(
    source: &SourcePackage,
    root: &Path,
    mode: InstallMode,
    force: bool,
) -> Result<PathBuf, ManageError> {
    let destination = root.join(&source.manifest.name);
    ensure_destination_replaceable(&source.manifest.name, &destination, root, force)?;
    // Linking the installed directory onto itself would leave a link to
    // itself once the swap deletes the directory it replaced.
    if mode == InstallMode::Link
        && !is_symlink(&destination)
        && destination.exists()
        && fs::canonicalize(&source.path)? == fs::canonicalize(&destination)?
    {
        return Err(ManageError::Refused(format!(
            "refusing to link {} onto itself",
            crate::paths::display(&destination)
        )));
    }
    fs::create_dir_all(root)?;
    // Re-check after creating the root so canonicalize can run.
    ensure_path_is_managed_child(&destination, root)?;

    let staging = unique_sibling_path(root, &source.manifest.name, "staging")?;
    let staged = match mode {
        InstallMode::Copy => copy_package_tree(&source.path, &staging),
        InstallMode::Link => create_package_link(&source.path, &staging),
    };
    if let Err(error) = staged {
        let _ = remove_path(&staging);
        return Err(error.into());
    }

    if let Err(error) = swap_staged_into_destination(&staging, &destination) {
        let _ = remove_path(&staging);
        return Err(error.into());
    }
    Ok(destination)
}

pub(crate) fn set_enabled(
    target: NamedPlugin<'_>,
    enabled: bool,
    cwd: &Path,
    home: Option<&Path>,
    rho_home: Option<&Path>,
) -> Result<ManagedPackage, ManageError> {
    let resolved = resolve_named_package(target, BrokenManifest::Refuse, cwd, home, rho_home)?;
    let mut state = PluginStateStore::load(cwd, home, rho_home)?;
    // State keys follow the manifest name used by discovery.
    state.set_enabled(resolved.package.scope, &resolved.package.name, enabled)?;
    Ok(resolved.package)
}

pub(crate) fn remove(
    target: NamedPlugin<'_>,
    cwd: &Path,
    home: Option<&Path>,
    rho_home: Option<&Path>,
) -> Result<ManagedPackage, ManageError> {
    let resolved = resolve_named_package(target, BrokenManifest::ByDirectory, cwd, home, rho_home)?;
    ensure_path_is_managed_child(&resolved.package.path, &resolved.root)?;

    let metadata = fs::symlink_metadata(&resolved.package.path)?;
    if metadata.file_type().is_symlink() {
        fs::remove_file(&resolved.package.path)?;
    } else if metadata.is_dir() {
        fs::remove_dir_all(&resolved.package.path)?;
    } else {
        return Err(ManageError::Refused(format!(
            "refusing to remove {}: not a plugin directory",
            crate::paths::display(&resolved.package.path)
        )));
    }

    let mut state = PluginStateStore::load(cwd, home, rho_home)?;
    state.clear_package_record(resolved.package.scope, &resolved.package.name)?;
    Ok(resolved.package)
}

/// How [`resolve_named_package`] treats a package whose `plugin.json` does
/// not load.
#[derive(Clone, Copy)]
pub(super) enum BrokenManifest {
    /// Fail with the manifest's error.
    Refuse,
    /// Take the package in a directory named for the target as that plugin,
    /// as discovery names its rejected entry, so it can still be removed.
    ByDirectory,
}

fn resolve_named_package(
    target: NamedPlugin<'_>,
    broken: BrokenManifest,
    cwd: &Path,
    home: Option<&Path>,
    rho_home: Option<&Path>,
) -> Result<ResolvedPackage, ManageError> {
    let name = target.name;
    // A rejected package is listed by its directory's name, which need not
    // be a plugin name; it is still found by that name, as long as the name
    // stays inside a root.
    let invalid_name = manifest::validate_plugin_name(name).err();
    match (&invalid_name, broken) {
        (None, _) => {}
        (Some(_), BrokenManifest::ByDirectory) if is_directory_name(name) => {}
        (Some(error), _) => return Err(ManageError::Refused(error.clone())),
    }
    let roots: Vec<(PluginScope, PathBuf)> = discovery_roots(cwd, home)
        .into_iter()
        .filter(|(scope, _)| target.covers(*scope))
        .collect();
    let mut matches = Vec::new();
    for (scope, root) in &roots {
        let candidate = root.join(name);
        if package_exists(&candidate) {
            matches.push((*scope, candidate, root.clone()));
        }
    }
    // Also match by manifest name when the directory name differs.
    if matches.is_empty() {
        for (scope, root) in &roots {
            let Ok(entries) = fs::read_dir(root) else {
                continue;
            };
            for entry in entries.filter_map(Result::ok) {
                let path = entry.path();
                if !path.is_dir() && !is_symlink(&path) {
                    continue;
                }
                if let Ok(source) = inspect_source(&path) {
                    if source.manifest.name == name {
                        matches.push((*scope, path, root.clone()));
                    }
                }
            }
        }
    }

    let state = PluginStateStore::load(cwd, home, rho_home)
        .unwrap_or_else(|_| PluginStateStore::empty(cwd, rho_home));
    let Some((scope, path, root)) = matches.first() else {
        let roots = match target.scope {
            None => "managed",
            Some(scope) => scope.as_str(),
        };
        return Err(ManageError::NotFound(format!(
            "no plugin named `{name}` in the {roots} plugin roots"
        )));
    };
    if matches.len() > 1 {
        let ignored = matches[1..]
            .iter()
            .map(|(_, path, _)| crate::paths::display(path))
            .collect::<Vec<_>>()
            .join(", ");
        tracing::warn!(
            plugin = %name,
            selected = %crate::paths::display(path),
            ignored = %ignored,
            "multiple managed packages matched; using higher-precedence root"
        );
    }
    let package = match (package_at(*scope, path, &state), broken) {
        (Err(ManageError::InvalidPackage(_)), BrokenManifest::ByDirectory)
            if path.file_name() == Some(std::ffi::OsStr::new(name)) =>
        {
            ManagedPackage {
                origin: state.origin(*scope, name, path),
                link_target: state.link_target(*scope, name, path),
                name: name.to_owned(),
                version: None,
                description: None,
                scope: *scope,
                path: path.clone(),
            }
        }
        (package, _) => {
            let package = package?;
            // Only a package that does not load goes by an invalid name.
            if let Some(error) = invalid_name {
                return Err(ManageError::Refused(error));
            }
            package
        }
    };
    Ok(ResolvedPackage {
        package,
        root: root.clone(),
    })
}

fn package_at(
    scope: PluginScope,
    path: &Path,
    state: &PluginStateStore,
) -> Result<ManagedPackage, ManageError> {
    let source = inspect_source(path)?;
    Ok(ManagedPackage {
        origin: state.origin(scope, &source.manifest.name, path),
        link_target: state.link_target(scope, &source.manifest.name, path),
        name: source.manifest.name,
        version: source.manifest.version,
        description: source.manifest.description,
        scope,
        path: path.to_path_buf(),
    })
}

/// Whether `name` is one directory's name, so a root joined with it stays
/// that root's child.
fn is_directory_name(name: &str) -> bool {
    let mut components = Path::new(name).components();
    matches!(
        (components.next(), components.next()),
        (Some(std::path::Component::Normal(_)), None)
    ) && !name.ends_with(['/', '\\'])
}

/// Plugins root that `scope` manages.
///
/// Refuses project scope when the project shares the user plugins root, which
/// discovery reports as user scope only.
fn managed_root(scope: PluginScope, cwd: &Path, home: &Path) -> Result<PathBuf, ManageError> {
    match scope {
        PluginScope::User => Ok(user_plugins_root(home)),
        PluginScope::Project => project_plugins_root(cwd, home).ok_or_else(|| {
            ManageError::Refused(format!(
                "project scope is unavailable here: this project's plugins root is the user plugins root {}; use --scope user",
                crate::paths::display(&user_plugins_root(home))
            ))
        }),
    }
}

/// Validate that `destination` may be installed, without destroying it yet.
fn ensure_destination_replaceable(
    name: &str,
    destination: &Path,
    root: &Path,
    force: bool,
) -> Result<(), ManageError> {
    ensure_path_is_managed_child(destination, root)?;
    match fs::symlink_metadata(destination) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.into()),
        Ok(metadata) => {
            if !force {
                return Err(ManageError::Exists {
                    name: name.to_owned(),
                    path: destination.to_path_buf(),
                });
            }
            if metadata.file_type().is_symlink() || metadata.is_file() {
                Ok(())
            } else if metadata.is_dir() {
                // Only replace a directory that looks like a plugin package.
                if !destination.join("plugin.json").exists() {
                    return Err(ManageError::Refused(format!(
                        "refusing to replace {}: directory has no plugin.json",
                        crate::paths::display(destination)
                    )));
                }
                Ok(())
            } else {
                Err(ManageError::Refused(format!(
                    "refusing to replace {}: unsupported file type",
                    crate::paths::display(destination)
                )))
            }
        }
    }
}

/// Non-mutating containment check. Does not create directories.
fn ensure_path_is_managed_child(path: &Path, root: &Path) -> Result<(), ManageError> {
    let refuse = |message: String| Err(ManageError::Refused(message));
    let Some(file_name) = path.file_name() else {
        return refuse("plugin destination is missing a final path component".to_owned());
    };
    if file_name == "data" {
        return refuse("refusing to use the reserved plugin data directory".to_owned());
    }
    let Some(parent) = path.parent() else {
        return refuse("plugin destination has no parent".to_owned());
    };
    let not_managed_root = || {
        refuse(format!(
            "plugin destination parent {} is not the managed root",
            crate::paths::display(parent)
        ))
    };

    if !root.exists() {
        // Install into a not-yet-created root: accept exact parent equality.
        if parent != root {
            return not_managed_root();
        }
        return Ok(());
    }

    let canonical_root = fs::canonicalize(root).map_err(|error| {
        anyhow::anyhow!(
            "cannot resolve managed plugins root {}: {error}",
            crate::paths::display(root)
        )
    })?;
    // Compare the parent when the leaf does not exist yet.
    let canonical_parent = if parent.exists() {
        fs::canonicalize(parent)?
    } else if parent == root {
        canonical_root.clone()
    } else {
        return not_managed_root();
    };
    if canonical_parent != canonical_root {
        return refuse(format!(
            "refusing path outside managed plugins root {}: {}",
            crate::paths::display(&canonical_root),
            crate::paths::display(path)
        ));
    }
    Ok(())
}

fn swap_staged_into_destination(staging: &Path, destination: &Path) -> anyhow::Result<()> {
    match fs::symlink_metadata(destination) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            fs::rename(staging, destination)?;
            Ok(())
        }
        Err(error) => Err(error.into()),
        Ok(_) => {
            let backup = unique_sibling_path(
                destination.parent().unwrap_or_else(|| Path::new(".")),
                destination
                    .file_name()
                    .and_then(|name| name.to_str())
                    .unwrap_or("plugin"),
                "backup",
            )?;
            fs::rename(destination, &backup).map_err(|error| {
                anyhow::anyhow!(
                    "failed to move existing plugin aside at {}: {error}",
                    crate::paths::display(destination)
                )
            })?;
            if let Err(error) = fs::rename(staging, destination) {
                // Best-effort rollback so a failed swap keeps the prior package.
                let _ = fs::rename(&backup, destination);
                return Err(anyhow::anyhow!(
                    "failed to move staged plugin into {}: {error}",
                    crate::paths::display(destination)
                ));
            }
            let _ = remove_path(&backup);
            Ok(())
        }
    }
}

fn unique_sibling_path(root: &Path, name: &str, kind: &str) -> anyhow::Result<PathBuf> {
    let token = uuid::Uuid::new_v4().simple();
    let path = root.join(format!(".{name}.{kind}.{token}"));
    if path.exists() {
        anyhow::bail!(
            "temporary path already exists: {}",
            crate::paths::display(&path)
        );
    }
    Ok(path)
}

fn remove_path(path: &Path) -> anyhow::Result<()> {
    match fs::symlink_metadata(path) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.into()),
        Ok(metadata) if metadata.file_type().is_symlink() || metadata.is_file() => {
            fs::remove_file(path)?;
            Ok(())
        }
        Ok(metadata) if metadata.is_dir() => {
            fs::remove_dir_all(path)?;
            Ok(())
        }
        Ok(_) => anyhow::bail!(
            "refusing to remove unsupported path {}",
            crate::paths::display(path)
        ),
    }
}

fn package_exists(path: &Path) -> bool {
    path.join("plugin.json").exists()
        || is_symlink(path) && {
            fs::read_link(path)
                .ok()
                .map(|target| {
                    let resolved = if target.is_absolute() {
                        target
                    } else {
                        path.parent().unwrap_or(path).join(target)
                    };
                    resolved.join("plugin.json").exists()
                })
                .unwrap_or(false)
        }
}

fn is_symlink(path: &Path) -> bool {
    fs::symlink_metadata(path)
        .map(|metadata| metadata.file_type().is_symlink())
        .unwrap_or(false)
}

fn create_package_link(source: &Path, destination: &Path) -> anyhow::Result<()> {
    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(source, destination)?;
        Ok(())
    }
    #[cfg(windows)]
    {
        std::os::windows::fs::symlink_dir(source, destination).map_err(|error| {
            anyhow::anyhow!(
                "failed to create directory symlink (Windows may require developer mode or elevation): {error}"
            )
        })
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (source, destination);
        anyhow::bail!("plugin linking is not supported on this platform")
    }
}

/// Copy a package tree without following directory symlinks.
fn copy_package_tree(source: &Path, destination: &Path) -> anyhow::Result<()> {
    fs::create_dir_all(destination)?;
    copy_dir_contents(source, destination)
}

fn copy_dir_contents(source: &Path, destination: &Path) -> anyhow::Result<()> {
    for entry in fs::read_dir(source)? {
        let entry = entry?;
        let file_type = entry.file_type()?;
        let from = entry.path();
        let to = destination.join(entry.file_name());
        if file_type.is_dir() {
            fs::create_dir_all(&to)?;
            copy_dir_contents(&from, &to)?;
        } else if file_type.is_file() {
            fs::copy(&from, &to)?;
        } else if file_type.is_symlink() {
            let target = fs::read_link(&from)?;
            recreate_symlink(&target, &to)?;
        } else {
            anyhow::bail!(
                "refusing to install special file {}",
                crate::paths::display(&from)
            );
        }
    }
    Ok(())
}

fn recreate_symlink(target: &Path, destination: &Path) -> anyhow::Result<()> {
    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(target, destination)?;
        Ok(())
    }
    #[cfg(windows)]
    {
        let metadata_path = if target.is_absolute() {
            target.to_path_buf()
        } else {
            destination
                .parent()
                .unwrap_or_else(|| Path::new("."))
                .join(target)
        };
        if metadata_path
            .metadata()
            .map(|metadata| metadata.is_dir())
            .unwrap_or(false)
        {
            std::os::windows::fs::symlink_dir(target, destination)?;
        } else {
            std::os::windows::fs::symlink_file(target, destination)?;
        }
        Ok(())
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (target, destination);
        anyhow::bail!("symlink copy is not supported on this platform")
    }
}

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