rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::sync::Arc;

use pretty_assertions::assert_eq;
use rho_protocol::{self as wire, InputRequestId, Resolution};
use rho_sdk::{
    model::ToolSpec,
    tool::{
        PreparedToolInvocation, Tool, ToolContext, ToolError, ToolErrorKind, ToolFuture,
        ToolInvocation, ToolMetadata, ToolOutput, ToolPreparationContext, ToolPrepareFuture,
    },
    HostChoice, HostInputRequest, HostInputResponse, HostQuestion, PendingToolHostInput,
    SelectionMode, ToolCallId, ToolHost, ToolHostCall, ToolHostEvent, ToolHostRun,
};
use serde_json::json;
use tempfile::TempDir;

use super::{AllowedForSession, TurnAsks};
use crate::app::{
    daemon_host::{
        jobs::{JobRegistry, JobStore},
        sessions::{
            acp_tools::ServedAsk,
            test_sessions::{load, Load},
            Sessions,
        },
    },
    pull_requests::ScriptedForge,
    session_runtime::TurnControl,
};

/// Asks the host one question and returns the choice picked. It claims no
/// shared resource, so two calls can wait on the person at once.
struct Asking;

impl Tool for Asking {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "asking".into(),
            description: "ask one question".into(),
            input_schema: json!({"type": "object"}),
        }
    }

    fn prepare<'a>(
        &'a self,
        _invocation: ToolInvocation,
        _context: ToolPreparationContext,
    ) -> ToolPrepareFuture<'a> {
        fn failed(error: impl std::fmt::Display) -> ToolError {
            ToolError::new(ToolErrorKind::Execution, error.to_string())
        }
        Box::pin(async move {
            Ok(PreparedToolInvocation::resource_aware(
                [],
                [],
                ToolMetadata::new(),
                |context| {
                    Box::pin(async move {
                        let question = HostQuestion::new(
                            "go",
                            "Continue?",
                            vec![HostChoice::new("yes", "Yes")],
                            SelectionMode::One,
                        )
                        .map_err(failed)?;
                        let request = HostInputRequest::questionnaire("Confirm", vec![question])
                            .map_err(failed)?;
                        let response = context.request_host_input(request).await.map_err(failed)?;
                        Ok(ToolOutput::text(response.answers()["go"].join(",")))
                    })
                },
            ))
        })
    }

    fn call<'a>(&'a self, _invocation: ToolInvocation, _context: ToolContext) -> ToolFuture<'a> {
        unreachable!("resource-aware preparation is always used")
    }
}

/// A served call `call` of [`Asking`] on `host`, and the question it asks.
async fn asking(host: &ToolHost, call: &str) -> (ToolHostRun, ToolCallId, PendingToolHostInput) {
    let id = ToolCallId::from_string(call.to_owned()).unwrap();
    let mut run = host
        .start(ToolHostCall::new("asking", json!({})).with_id(id.clone()))
        .unwrap();
    match run.next_event().await {
        Some(ToolHostEvent::HostInputRequested(input)) => (run, id, input),
        other => panic!("expected the call's question, saw {other:?}"),
    }
}

/// What a session's clients saw of its input requests.
#[derive(Debug, PartialEq)]
enum Seen {
    Asked(InputRequestId, Option<wire::ToolCallId>),
    Closed(InputRequestId, Resolution),
}

// Covers: a served call that ends withdraws what it still asks the person,
// and only that: its question closes for the session's clients and the
// tool hears no answer, while another call's question stays open and
// takes the person's answer.
// Owner: daemon sessions on an external runtime (served tools' asks).
#[tokio::test]
async fn a_served_calls_asks_are_withdrawn_when_it_ends() {
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    let sessions = Sessions::new(
        Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
        home.path(),
        ScriptedForge::new(),
    );
    let session = load(&sessions, &root, Load::Saved).await;
    let host = ToolHost::builder().tool(Asking).build().unwrap();
    let mut asks = TurnAsks::new("claude-cli");

    let (mut ended_run, ended, input) = asking(&host, "toolu_ended").await;
    asks.put_served(
        &session,
        ServedAsk::Question {
            call: ended.clone(),
            input,
        },
    );
    let (mut kept_run, kept, input) = asking(&host, "toolu_kept").await;
    let kept_question = input.request().id().clone();
    asks.put_served(&session, ServedAsk::Question { call: kept, input });
    asks.put_served(&session, ServedAsk::Ended(ended));
    let _no_plan = asks.answered(
        TurnControl::AnswerQuestion {
            id: kept_question,
            answer: Ok(HostInputResponse::new().answer("go", ["yes"])),
        },
        &mut AllowedForSession::default(),
    );
    let seen: Vec<Seen> = session
        .feed
        .buffered_for_tests()
        .into_iter()
        .filter_map(|event| match event {
            wire::SessionEvent::InputRequested { request } => {
                Some(Seen::Asked(request.id, request.tool_call))
            }
            wire::SessionEvent::InputResolved { id, resolution } => {
                Some(Seen::Closed(id, resolution))
            }
            _ => None,
        })
        .collect();

    assert_eq!(
        (
            seen,
            ended_run.outcome().await.is_err(),
            kept_run.outcome().await.unwrap().content().to_owned(),
        ),
        (
            vec![
                Seen::Asked(
                    InputRequestId(0),
                    Some(wire::ToolCallId::new("toolu_ended"))
                ),
                Seen::Asked(InputRequestId(1), Some(wire::ToolCallId::new("toolu_kept"))),
                Seen::Closed(InputRequestId(0), Resolution::Withdrawn),
            ],
            // The withdrawn question failed the tool's ask.
            true,
            "yes".to_owned(),
        )
    );
}