rho-coding-agent 3.8.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What reads as a workspace file path in transcript text. The rules match
//! rho-ui's, so both clients link the same mentions: a word of path
//! characters, perhaps followed by `:line`, `:line:column`, or `:first-last`,
//! that is relative or absolute inside the workspace and names a file by an
//! extension (`main.rs`) or a folder (`src/main`).

use std::{
    ops::Range,
    path::{Component, Path},
    sync::LazyLock,
};

use regex::Regex;

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

/// A word that may be a path, with an optional position after it. It holds
/// no spaces, quotes, brackets, or parentheses. On Windows it may start with
/// a drive (`C:\` or `C:/`) and use `\` between names.
static TOKEN: LazyLock<Regex> = LazyLock::new(|| {
    let pattern = if cfg!(windows) {
        r"(?:[A-Za-z]:[\\/])?[\w.\-/\\+@~]+(?::\d+(?:[:-]\d+)?)?"
    } else {
        r"[\w.\-/+@~]+(?::\d+(?:[:-]\d+)?)?"
    };
    Regex::new(pattern).expect("the path pattern compiles")
});

/// A path mention found in a text.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Mention {
    /// The mention in the scanned text, without a sentence's trailing `.`.
    pub(super) range: Range<usize>,
    /// Bytes of the mention that are the path; the rest is its position.
    pub(super) path_len: usize,
    /// The file, from the workspace: `/` between names, no `.`. A `..`
    /// stays, since a symlink before it decides where it leads; the check
    /// resolves it on disk.
    pub(super) path: String,
}

/// Every mention in prose `text`, in order. A leading `@`, as the file
/// picker inserts, is not part of the mention.
pub(super) fn prose_mentions<'a>(
    text: &'a str,
    workspace: &'a Path,
) -> impl Iterator<Item = Mention> + 'a {
    TOKEN.find_iter(text).filter_map(move |token| {
        let at = usize::from(token.as_str().starts_with('@'));
        let start = token.start() + at;
        let written = token.as_str()[at..].trim_end_matches('.');
        mention(written, workspace).map(|(path, path_len)| Mention {
            range: start..start + written.len(),
            path_len,
            path,
        })
    })
}

/// The mention `text` is if it is one path and nothing else, as an inline
/// code span or a tool call's argument is.
pub(super) fn whole_mention(text: &str, workspace: &Path) -> Option<Mention> {
    TOKEN
        .find(text)
        .filter(|token| token.start() == 0 && token.end() == text.len())?;
    let (path, path_len) = mention(text, workspace)?;
    Some(Mention {
        range: 0..text.len(),
        path_len,
        path,
    })
}

/// The workspace-relative file `written` names, and how many of its bytes
/// are the path before its position.
fn mention(written: &str, workspace: &Path) -> Option<(String, usize)> {
    // A drive's colon is part of the path, not the start of its position.
    let drive = drive_len(written);
    let path_len = written[drive..]
        .find(':')
        .map_or(written.len(), |colon| drive + colon);
    let path = &written[..path_len];
    if path.starts_with('~') {
        return None;
    }
    let relative = if drive > 0 || path.starts_with('/') {
        Path::new(path).strip_prefix(workspace).ok()?
    } else {
        Path::new(path)
    };
    let mut names: Vec<&str> = Vec::new();
    // Names below the workspace root; a `..` past it leaves the workspace.
    let mut depth = 0usize;
    for component in relative.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                depth = depth.checked_sub(1)?;
                names.push("..");
            }
            Component::Normal(name) => {
                depth += 1;
                names.push(name.to_str()?);
            }
            Component::RootDir | Component::Prefix(_) => return None,
        }
    }
    let name = *names.last().filter(|name| **name != "..")?;
    let has_extension = name
        .rsplit_once('.')
        .is_some_and(|(_, extension)| extension.chars().any(char::is_alphabetic));
    if names.len() < 2 && !has_extension {
        return None;
    }
    Some((names.join("/"), path.len()))
}

/// The length of the drive `written` starts with (`C:\` or `C:/`), when it
/// is on Windows, which alone has drives.
fn drive_len(written: &str) -> usize {
    match written.as_bytes() {
        [letter, b':', b'/' | b'\\', ..] if cfg!(windows) && letter.is_ascii_alphabetic() => 2,
        _ => 0,
    }
}