rho-coding-agent 3.12.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, SessionCall, SessionRef, SubagentRef, ToolContent, ToolKind, ToolStatus,
};
use rho_sdk::{
    tool::{OperationKind, ToolFileChange, ToolMetadata, ToolOutput},
    ToolCompletion,
};
use rho_tools::{
    apply_patch::{parse_patch, Hunk},
    EditFormat,
};
use serde::Deserialize;
use serde_json::Value;

use super::call_content::finished_status;
use crate::{
    app::subagent_manager::SubagentManager,
    session::tree::SubagentLink,
    tools::{
        agent::starts_subagent,
        plan_exit,
        process::{starts_process, ProcessManager},
        sessions::{result_session, session_call},
        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> {
    if call.name != SESSIONS_TOOL || status != ToolStatus::Completed {
        return None;
    }
    session_content(text, session_call(&call.arguments)?)
}

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

/// What a call links once it finishes: the work it started or the session
/// it acted on. Decided alike for every call rho runs live, a Rho session's
/// own ([`CallLinks`]) and one rho serves an agent on another runtime (the
/// daemon's served tools), so a client reads both alike.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Link {
    /// A `process` start: its process's terminal.
    Process,
    /// An `agent` call: the subagent it started.
    Subagent,
    /// A `sessions` call naming one session, which it did to as it says.
    Session(SessionCall),
}

impl Link {
    /// What a call to tool `name` with `arguments` links, if anything: only
    /// a `process` start, an `agent` call, or a `sessions` call that names
    /// one session does.
    pub(crate) fn of(name: &str, arguments: Option<&Value>) -> Option<Self> {
        if arguments.is_some_and(|arguments| starts_process(name, arguments)) {
            Some(Self::Process)
        } else if starts_subagent(name) {
            Some(Self::Subagent)
        } else if name == SESSIONS_TOOL {
            arguments.and_then(session_call).map(Self::Session)
        } else {
            None
        }
    }
}

/// What a session's call links resolve against: its background processes
/// and its subagents, where it has them.
#[derive(Clone, Default)]
pub(crate) struct LinkSources {
    processes: Option<ProcessManager>,
    subagents: Option<SubagentManager>,
}

impl LinkSources {
    pub(crate) fn new(
        processes: Option<ProcessManager>,
        subagents: Option<SubagentManager>,
    ) -> Self {
        Self {
            processes,
            subagents,
        }
    }

    /// What call `id`, which links `link` and ended with `result`, shows:
    /// 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(crate) fn content(
        &self,
        link: Link,
        id: &str,
        result: &ToolCompletion,
    ) -> Option<ToolContent> {
        let succeeded = finished_status(result) == ToolStatus::Completed;
        let text = result.output().map(ToolOutput::content);
        match link {
            Link::Process => {
                let processes = self.processes.as_ref()?;
                terminal(Some(processes), &processes.process_started_by(id)?)
            }
            Link::Subagent if succeeded => {
                let link = self.subagents.as_ref()?.run_started_by(id)?;
                Some(ToolContent::Subagent(subagent_ref(&link)))
            }
            Link::Session(call) if succeeded => session_content(text?, call),
            Link::Subagent | Link::Session(_) => None,
        }
    }
}

/// 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 ([`Link`]).
pub(super) struct CallLinks {
    sources: LinkSources,
    started: HashMap<String, Link>,
}

impl CallLinks {
    /// For a session whose call links resolve against `sources`.
    pub(super) fn new(sources: LinkSources) -> Self {
        Self {
            sources,
            started: HashMap::new(),
        }
    }

    /// Call `id` to tool `name` with `arguments` started; only one that
    /// links something ([`Link::of`]) 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);
        if let Some(link) = Link::of(name, arguments) {
            self.started.insert(id.to_owned(), link);
        }
    }

    /// What call `id`, now finished as `status` with result `text`, links
    /// ([`LinkSources::content`]).
    pub(super) fn finished(&mut self, id: &str, result: &ToolCompletion) -> Option<ToolContent> {
        let link = self.started.remove(id)?;
        self.sources.content(link, id, result)
    }

    /// 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 `link` names, as clients are sent it, live or replayed.
pub(super) fn subagent_ref(link: &SubagentLink) -> SubagentRef {
    let mut subagent = SubagentRef::new(
        link.run.clone(),
        link.session.as_deref().map(rho_protocol::SessionId::new),
    );
    subagent.title = link.title.clone();
    subagent
}

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