rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The agent's v2 tool calls as the v1 updates rho's renderer and served
//! tools take.
//!
//! v2 reports a tool call with one `tool_call_update` that upserts by id:
//! the first update for an id starts the call. v1 starts it with
//! `tool_call` and changes it with `tool_call_update`, so the client keeps
//! the ids it has seen. A v2 field that is `null` clears it; v1 cannot
//! clear a field, so a cleared list is sent empty and any other cleared
//! field is left as it was.
//!
//! v2 diffs carry a patch rather than the old and new text v1 diffs do, so
//! a diff is shown as its patch text. Streamed tool content
//! (`tool_call_content_chunk`) is not shown: claude-agent-acp 0.114.0 sends
//! none.

use super::bridge;
use agent_client_protocol::{schema::MaybeUndefined, v1::schema as v1, v2::schema as v2};
use std::collections::HashSet;

/// The tool calls of one session the client has seen started.
#[derive(Default)]
pub(super) struct ToolCalls {
    started: HashSet<v1::ToolCallId>,
}

impl ToolCalls {
    /// `update` in v1 form: the call's start the first time its id comes,
    /// a change of it after.
    pub(super) fn v1(&mut self, update: &v2::ToolCallUpdate) -> v1::SessionUpdate {
        let update = v1_update(update);
        if !self.started.insert(update.tool_call_id.clone()) {
            return v1::SessionUpdate::ToolCallUpdate(update);
        }
        let v1::ToolCallUpdate {
            tool_call_id,
            fields,
            meta,
            ..
        } = update;
        // v1 requires a title; a call the agent names but does not title
        // shows its name.
        let title = fields.title.clone().or_else(|| fields.name.clone());
        let mut call = v1::ToolCall::new(tool_call_id, title.unwrap_or_default());
        call.update(fields);
        v1::SessionUpdate::ToolCall(call.meta(meta))
    }
}

/// `update` as a v1 change of its call, such as the call a permission ask
/// is about.
pub(super) fn v1_update(update: &v2::ToolCallUpdate) -> v1::ToolCallUpdate {
    v1::ToolCallUpdate::new(update.tool_call_id.0.clone(), fields(update))
        .meta(update.meta.value().cloned())
}

fn fields(update: &v2::ToolCallUpdate) -> v1::ToolCallUpdateFields {
    v1::ToolCallUpdateFields::new()
        .name(update.name.value().cloned())
        .title(update.title.value().cloned())
        .kind(update.kind.value().map(kind))
        .status(update.status.value().and_then(status))
        .content(list(&update.content, content))
        .locations(list(&update.locations, location))
        .raw_input(update.raw_input.value().cloned())
        .raw_output(update.raw_output.value().cloned())
}

/// A list field in v1 form: `None` leaves it as it was; a cleared one is
/// empty. Items v1 has no form for are left out.
fn list<V2, V1>(field: &MaybeUndefined<Vec<V2>>, item: fn(&V2) -> Option<V1>) -> Option<Vec<V1>> {
    match field {
        MaybeUndefined::Undefined => None,
        MaybeUndefined::Null => Some(Vec::new()),
        MaybeUndefined::Value(items) => Some(items.iter().filter_map(item).collect()),
    }
}

fn kind(kind: &v2::ToolKind) -> v1::ToolKind {
    match kind {
        v2::ToolKind::Read => v1::ToolKind::Read,
        v2::ToolKind::Edit => v1::ToolKind::Edit,
        v2::ToolKind::Delete => v1::ToolKind::Delete,
        v2::ToolKind::Move => v1::ToolKind::Move,
        v2::ToolKind::Search => v1::ToolKind::Search,
        v2::ToolKind::Execute => v1::ToolKind::Execute,
        v2::ToolKind::Think => v1::ToolKind::Think,
        v2::ToolKind::Fetch => v1::ToolKind::Fetch,
        v2::ToolKind::SwitchMode => v1::ToolKind::SwitchMode,
        _ => v1::ToolKind::Other,
    }
}

/// v1 has no paused or cancelled call: a paused one still runs, and a
/// cancelled one did not complete.
fn status(status: &v2::ToolCallStatus) -> Option<v1::ToolCallStatus> {
    match status {
        v2::ToolCallStatus::Pending => Some(v1::ToolCallStatus::Pending),
        v2::ToolCallStatus::InProgress | v2::ToolCallStatus::Paused => {
            Some(v1::ToolCallStatus::InProgress)
        }
        v2::ToolCallStatus::Completed => Some(v1::ToolCallStatus::Completed),
        v2::ToolCallStatus::Failed | v2::ToolCallStatus::Cancelled => {
            Some(v1::ToolCallStatus::Failed)
        }
        _ => None,
    }
}

fn content(content: &v2::ToolCallContent) -> Option<v1::ToolCallContent> {
    match content {
        v2::ToolCallContent::Content(content) => bridge(content.as_ref())
            .ok()
            .map(v1::ToolCallContent::Content),
        v2::ToolCallContent::Diff(diff) => Some(diff_text(diff).into()),
        v2::ToolCallContent::Terminal(terminal) => {
            bridge(terminal).ok().map(v1::ToolCallContent::Terminal)
        }
        v2::ToolCallContent::Session(session) => {
            bridge(session).ok().map(v1::ToolCallContent::Session)
        }
        _ => None,
    }
}

/// A diff as text: its patch, fenced, else the paths it changes.
fn diff_text(diff: &v2::Diff) -> String {
    if let Some(patch) = &diff.patch {
        return format!("```diff\n{}\n```", patch.text.trim_end());
    }
    diff.changes
        .iter()
        .filter_map(|change| match &change.operation {
            v2::DiffChangeOperation::Add(change)
            | v2::DiffChangeOperation::Delete(change)
            | v2::DiffChangeOperation::Modify(change) => Some(change.path.0.display().to_string()),
            v2::DiffChangeOperation::Move(change) | v2::DiffChangeOperation::Copy(change) => {
                Some(format!(
                    "{} -> {}",
                    change.old_path.0.display(),
                    change.path.0.display()
                ))
            }
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn location(location: &v2::ToolCallLocation) -> Option<v1::ToolCallLocation> {
    Some(
        v1::ToolCallLocation::new(location.path.0.clone())
            .line(location.line.map(std::num::NonZeroU32::get)),
    )
}

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