rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What a call tells clients besides its title and output: its kind, and the
//! files it touches, at a line when the call knows one, for clients that
//! follow the agent through the workspace.

use std::{
    collections::HashMap,
    path::{Path, PathBuf},
};

use rho_protocol::{Location, SessionRef, SubagentRef, ToolContent, ToolKind, ToolStatus};
use rho_sdk::tool::{OperationKind, ToolFileChange, ToolMetadata, ToolOutput};
use rho_tools::{
    apply_patch::{parse_patch, Hunk},
    EditFormat,
};
use serde::Deserialize;
use serde_json::Value;

use crate::{
    app::subagent_manager::SubagentManager,
    tools::{
        agent::starts_subagent,
        plan_exit,
        process::{starts_process, ProcessManager},
        sessions::{names_one_session, result_session},
        todo,
    },
};

/// The tool whose calls may name another session.
const SESSIONS_TOOL: &str = crate::session::search::TOOL_NAME;

/// The read tool, whose `offset` argument is the first line it shows.
const READ_FILE_TOOL: &str = "read_file";

/// Most grep-matched files a finished call names. Zed, the client that
/// follows locations most closely, opens a buffer for each and sends at most
/// 20 matches per call from its own grep (`RESULTS_PER_PAGE`), while Rho's
/// grep can return up to 1000 files.
const MAX_GREP_LOCATIONS: usize = 20;

/// A call's kind, from its operation. Rho's checklist and plan-exit tools
/// declare none, so their names decide, and a patch that only deletes or
/// only moves files says so.
pub(super) fn kind(name: &str, arguments: Option<&Value>, metadata: &ToolMetadata) -> ToolKind {
    match metadata.operation_kind() {
        Some(OperationKind::Read) => ToolKind::Read,
        Some(OperationKind::Search) => ToolKind::Search,
        Some(OperationKind::Write) => match (EditFormat::from_tool_name(name), arguments) {
            (Some(EditFormat::ApplyPatch), Some(arguments)) => patch_kind(arguments),
            _ => ToolKind::Edit,
        },
        Some(OperationKind::Execute) => ToolKind::Execute,
        Some(OperationKind::Network) => ToolKind::Fetch,
        Some(OperationKind::Other(_)) | None => match name {
            todo::TOOL_NAME => ToolKind::Think,
            plan_exit::TOOL_NAME => ToolKind::SwitchMode,
            _ => ToolKind::Other,
        },
        // OperationKind is non_exhaustive; an unknown operation says nothing.
        _ => ToolKind::Other,
    }
}

/// `delete` when every file section of the patch deletes a file, `move` when
/// every one moves a file, else `edit`.
fn patch_kind(arguments: &Value) -> ToolKind {
    let Some(Ok(hunks)) = arguments
        .get("input")
        .and_then(Value::as_str)
        .map(parse_patch)
    else {
        return ToolKind::Edit;
    };
    if hunks.iter().all(|hunk| matches!(hunk, Hunk::Delete { .. })) {
        ToolKind::Delete
    } else if hunks.iter().all(|hunk| {
        matches!(
            hunk,
            Hunk::Update {
                move_path: Some(_),
                ..
            }
        )
    }) {
        ToolKind::Move
    } else {
        ToolKind::Edit
    }
}

/// The paths a started call names, absolute against the session directory.
/// A read names the line it starts at.
///
/// Lines are 0-based rows; ACP hosts get them 1-based.
pub(super) fn started_locations(
    name: &str,
    arguments: Option<&Value>,
    metadata: &ToolMetadata,
    cwd: &Path,
) -> Vec<Location> {
    let line = arguments
        .filter(|_| name == READ_FILE_TOOL)
        .and_then(|arguments| arguments.get("offset")?.as_u64())
        .and_then(row);
    metadata
        .affected_paths()
        .iter()
        .map(|path| location(cwd.join(path), line))
        .collect()
}

/// Where a finished call's output points: each file it changed, at the first
/// changed line, or the first [`MAX_GREP_LOCATIONS`] files a grep matched,
/// at the first match. `None` when the output names no such files, so the
/// started locations stand.
pub(super) fn finished_locations(output: &ToolOutput, cwd: &Path) -> Option<Vec<Location>> {
    let metadata = output.presentation();
    let locations = if !metadata.file_changes().is_empty() {
        metadata
            .file_changes()
            .iter()
            .map(|change| location(cwd.join(change.path()), changed_line(change)))
            .collect()
    } else if metadata.operation_kind() == Some(&OperationKind::Search) {
        // Only grep's result has this shape; glob lists `paths` instead, so
        // it fails to parse and keeps its started locations.
        GrepHits::deserialize(output.structured_content()?)
            .ok()?
            .files
            .into_iter()
            .take(MAX_GREP_LOCATIONS)
            .map(|file| {
                let line = file.lines.first().and_then(|line| row(line.line));
                location(cwd.join(file.path), line)
            })
            .collect()
    } else {
        return None;
    };
    super::non_empty(locations)
}

fn location(path: PathBuf, line: Option<u32>) -> Location {
    Location { path, line }
}

/// The row where a changed file first differs from its old text. `None`
/// for a new file, a file left empty, or text that did not change.
fn changed_line(change: &ToolFileChange) -> Option<u32> {
    let mut old_lines = change.old_text()?.lines();
    let mut rows = 0usize;
    for (index, new_line) in change.new_text().lines().enumerate() {
        if old_lines.next() != Some(new_line) {
            return u32::try_from(index).ok();
        }
        rows = index + 1;
    }
    // Lines were cut from the end: point at what is now the last row.
    (rows > 0 && old_lines.next().is_some())
        .then(|| u32::try_from(rows - 1).ok())
        .flatten()
}

/// The 0-based row of a tool's 1-based line number.
fn row(line: u64) -> Option<u32> {
    u32::try_from(line.checked_sub(1)?).ok()
}

/// The part of grep's structured result (its published output schema) that
/// locates hits: each matched file, workspace-relative, with the lines shown.
#[derive(Deserialize)]
struct GrepHits {
    files: Vec<GrepFile>,
}

#[derive(Deserialize)]
struct GrepFile {
    path: PathBuf,
    #[serde(default)]
    lines: Vec<GrepLine>,
}

#[derive(Deserialize)]
struct GrepLine {
    /// 1-based, as grep prints it.
    line: u64,
}

/// The session saved call `call`, which ended `status` with `text`, named,
/// as a replay shows it.
pub(super) fn saved_session(
    call: &rho_sdk::model::ToolCall,
    status: ToolStatus,
    text: &str,
) -> Option<ToolContent> {
    let named = call.name == SESSIONS_TOOL
        && status == ToolStatus::Completed
        && names_one_session(&call.arguments);
    named.then(|| session_content(text)).flatten()
}

/// The session a `sessions` call's result `text` names.
fn session_content(text: &str) -> Option<ToolContent> {
    let session = result_session(text)?;
    Some(ToolContent::Session(SessionRef::new(
        rho_protocol::SessionId::new(session),
    )))
}

/// The calls of a run under way that link what they started or acted on,
/// by provider id, so each shows it once it finishes: a `process` start
/// its process's terminal, an `agent` call its subagent, and a `sessions`
/// call that names one session that session.
pub(super) struct CallLinks {
    processes: Option<ProcessManager>,
    subagents: Option<SubagentManager>,
    started: HashMap<String, Link>,
}

/// What a call links.
#[derive(Clone, Copy)]
enum Link {
    Process,
    Subagent,
    Session,
}

impl CallLinks {
    /// For a session whose background processes are `processes` and whose
    /// subagents are `subagents`.
    pub(super) fn new(
        processes: Option<ProcessManager>,
        subagents: Option<SubagentManager>,
    ) -> Self {
        Self {
            processes,
            subagents,
            started: HashMap::new(),
        }
    }

    /// Call `id` to tool `name` with `arguments` started; only a `process`
    /// start, an `agent` call, or a `sessions` call that names one session
    /// counts.
    pub(super) fn started(&mut self, id: &str, name: &str, arguments: Option<&Value>) {
        // A provider may reuse an id: the earlier call's link is not this one's.
        self.started.remove(id);
        let link = if arguments.is_some_and(|arguments| starts_process(name, arguments)) {
            Link::Process
        } else if starts_subagent(name) {
            Link::Subagent
        } else if name == SESSIONS_TOOL && arguments.is_some_and(names_one_session) {
            Link::Session
        } else {
            return;
        };
        self.started.insert(id.to_owned(), link);
    }

    /// What call `id`, now finished as `status` with result `text`, links:
    /// its process's terminal, while it runs, whatever the call reported,
    /// as a replay shows it; its subagent, only when it succeeded, since a
    /// failed `agent` call started no run, and one another call with the
    /// same id started is not its own; or the session its result names,
    /// only when it succeeded.
    pub(super) fn finished(
        &mut self,
        id: &str,
        status: ToolStatus,
        text: Option<&str>,
    ) -> Option<ToolContent> {
        let succeeded = status == ToolStatus::Completed;
        match self.started.remove(id)? {
            Link::Process => {
                let processes = self.processes.as_ref()?;
                terminal(Some(processes), &processes.process_started_by(id)?)
            }
            Link::Subagent if succeeded => {
                subagent(self.subagents.as_ref(), id).map(ToolContent::Subagent)
            }
            Link::Session if succeeded => session_content(text?),
            Link::Subagent | Link::Session => None,
        }
    }

    /// The run ended: its calls that did not finish never will.
    pub(super) fn clear(&mut self) {
        self.started.clear();
    }
}

/// The terminal a client shows `process`'s output in, while `processes`
/// still runs it. One that ended has no output a client would be sent.
pub(super) fn terminal(processes: Option<&ProcessManager>, process: &str) -> Option<ToolContent> {
    processes?.is_live(process).then(|| ToolContent::Terminal {
        process: process.to_owned(),
    })
}

/// The subagent `agent` call `call` started, as long as `subagents` knows
/// the run.
pub(super) fn subagent(subagents: Option<&SubagentManager>, call: &str) -> Option<SubagentRef> {
    let (run, session) = subagents?.run_started_by(call)?;
    Some(SubagentRef::new(
        run,
        session.map(|session| rho_protocol::SessionId::new(session.as_str())),
    ))
}

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