rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A run a person attends: the driver puts what its policy leaves to a
//! person to them, answers the agent as they do, and advertises forms; a
//! run nobody attends fails those asks closed.

use super::{
    permission::{Asking, PermissionDecision},
    person::{Heard, Person, PersonAnswer, PersonAsk},
    scripted_agent::{Record, Script, ScriptedAgent, Step},
    session::run_on_channel,
    test_support::*,
    AcpSessionRequest,
};
use crate::{permission::PermissionMode, subagent::RunState};
use agent_client_protocol::{
    v1::schema::{
        ContentChunk, CurrentModeUpdate, PermissionOption, PermissionOptionKind, SessionUpdate,
        StopReason, ToolCall, ToolCallUpdate, ToolCallUpdateFields, ToolKind,
    },
    Channel,
};
use pretty_assertions::assert_eq;
use rho_sdk::{HostInputResponse, HostInputSource};
use serde_json::{json, Value};
use std::sync::{Arc, Mutex};

/// What the person heard, in order: each ask's kind and what it shows, and
/// the mode the agent left plan mode for.
type Noted = Arc<Mutex<Vec<(String, String)>>>;

/// A person who approves every plan and tool call and picks `Blue` for
/// each form's `question_0`, noting what they heard.
fn approving_person() -> (Person, Noted) {
    let (person, mut heard) = Person::channel();
    let noted = Noted::default();
    let noting = Arc::clone(&noted);
    tokio::spawn(async move {
        while let Some(heard) = heard.recv().await {
            let asked = match heard {
                Heard::Asked(asked) => asked,
                Heard::LeftPlan(mode) => {
                    let left = ("left".to_owned(), mode.as_str().to_owned());
                    noting.lock().unwrap().push(left);
                    continue;
                }
            };
            let (note, answer) = match asked.ask {
                PersonAsk::Tool { title, .. } => {
                    (("tool", title.unwrap_or_default()), PersonAnswer::Allow)
                }
                PersonAsk::PlanExit { plan, to, .. } => (
                    ("plan", format!("{plan} -> {}", to.as_str())),
                    PersonAnswer::Allow,
                ),
                PersonAsk::Form { request, .. } => {
                    let questions = request
                        .questions()
                        .iter()
                        .map(|question| question.id().to_owned())
                        .collect::<Vec<_>>()
                        .join(",");
                    let answers = HostInputResponse::new()
                        .with_source(HostInputSource::User)
                        .answer("question_0", vec!["Blue".to_owned()]);
                    (("form", questions), PersonAnswer::Form(Ok(answers)))
                }
            };
            noting
                .lock()
                .unwrap()
                .push((note.0.to_owned(), note.1.to_owned()));
            let _ = asked.reply.send(answer);
        }
    });
    (person, noted)
}

/// What the agent heard: its requests and its replies to Rho's answers.
struct AgentHeard {
    requests: Vec<Value>,
    replies: Vec<Value>,
}

async fn exercise(request: AcpSessionRequest, policy: TestPolicy, script: Script) -> AgentHeard {
    let (client, agent) = Channel::duplex();
    let (fake, record, _signals) = ScriptedAgent::new(script);
    tokio::time::timeout(TEST_BUDGET, async {
        let (client, agent) =
            tokio::join!(run_on_channel(request, policy, client), fake.run(agent));
        client.unwrap();
        agent.unwrap();
    })
    .await
    .expect("ACP runtime/agent finished");
    let record: std::sync::MutexGuard<'_, Record> = record.lock().unwrap();
    AgentHeard {
        requests: record.requests.clone(),
        replies: record.replies.clone(),
    }
}

/// Claude's `ExitPlanMode` ask: approving it (`allow_once`) moves Claude
/// to `default`.
fn plan_exit() -> Vec<Step> {
    plan_exit_offering(vec![
        PermissionOption::new(
            "exit-plan-default",
            "Yes, manually approve edits",
            PermissionOptionKind::AllowOnce,
        ),
        PermissionOption::new("plan-no", "No", PermissionOptionKind::RejectOnce),
    ])
}

fn plan_exit_offering(options: Vec<PermissionOption>) -> Vec<Step> {
    vec![
        Step::Update {
            update: Box::new(SessionUpdate::ToolCall(
                ToolCall::new("plan-1", "Approve Plan").kind(ToolKind::SwitchMode),
            )),
        },
        Step::Permission {
            call: Box::new(ToolCallUpdate::new(
                "plan-1",
                ToolCallUpdateFields::new()
                    .kind(ToolKind::SwitchMode)
                    .raw_input(json!({"plan": "ship it"})),
            )),
            options,
        },
    ]
}

/// Claude's `AskUserQuestion` form, shaped as claude-agent-acp 0.114.0
/// sends it: one titled single select and its free-text companion.
fn ask_user_question() -> Step {
    Step::Extension {
        method: "elicitation/create".into(),
        params: json!({
            "mode": "form",
            "sessionId": "scripted-session",
            "toolCallId": "ask-1",
            "message": "Which color?",
            "requestedSchema": {
                "type": "object",
                "properties": {
                    "question_0": {
                        "type": "string",
                        "title": "Color",
                        "oneOf": [
                            {"const": "Red", "title": "Red"},
                            {"const": "Blue", "title": "Blue"}
                        ]
                    },
                    "question_0_custom": {
                        "type": "string",
                        "title": "Other",
                        "description": "Type your own answer (optional)."
                    }
                }
            }
        }),
    }
}

fn end(text: &str) -> Vec<Step> {
    vec![
        Step::Update {
            update: Box::new(SessionUpdate::AgentMessageChunk(ContentChunk::new(
                text.to_owned().into(),
            ))),
        },
        Step::Stop {
            reason: StopReason::EndTurn,
        },
    ]
}

/// The client capabilities `initialize` advertised.
fn capabilities(record: &AgentHeard) -> Value {
    record
        .requests
        .iter()
        .find(|request| request["method"] == "initialize")
        .map(|request| request["params"]["clientCapabilities"]["elicitation"].clone())
        .unwrap_or_default()
}

// Covers: in a run a person attends, `initialize` advertises forms; a plan
// exit the policy leaves to the person reaches them with its plan and the
// mode it leads to, and their approval selects the agent's `allow_once`,
// moves the policy to the mode the agent then switches to, so the switch
// keeps the run, and tells the person the agent left; a form reaches them
// as questions, and their answer goes back as the form's content.
// Owner: ACP driver (asks put to a person).
#[tokio::test]
async fn an_attended_run_puts_plan_exits_and_forms_to_the_person() {
    let dir = tempfile::tempdir().unwrap();
    let (person, heard) = approving_person();
    let mut request = request(dir.path(), None);
    request.overrides.person = Some(person);
    let mut policy = TestPolicy::new(dir.path());
    policy.decision = PermissionDecision::AskPerson(Asking::PlanExit {
        to: PermissionMode::Supervised,
    });
    policy.mode = Some("plan".into());
    policy.plan_exit_to = Some("default".into());
    let mut turn = plan_exit();
    turn.push(Step::Update {
        update: Box::new(SessionUpdate::CurrentModeUpdate(CurrentModeUpdate::new(
            "default",
        ))),
    });
    turn.push(ask_user_question());
    turn.extend(end("done"));
    let script = Script {
        modes: vec!["plan".into(), "default".into()],
        turns: vec![turn],
        ..Script::default()
    };

    let record = exercise(request, policy, script).await;
    let (status, _) = read_artifacts(dir.path());

    assert_eq!(
        (
            status.state,
            capabilities(&record),
            heard.lock().unwrap().clone(),
            record.replies,
        ),
        (
            RunState::Ok,
            json!({"form": {}}),
            vec![
                ("plan".to_owned(), "ship it -> supervised".to_owned()),
                ("left".to_owned(), "supervised".to_owned()),
                ("form".to_owned(), "question_0,question_0_custom".to_owned()),
            ],
            vec![
                json!({"method": "session/request_permission", "result": {
                    "outcome": {"outcome": "selected", "optionId": "exit-plan-default"}
                }}),
                json!({"method": "elicitation/create", "result": {
                    "action": "accept", "content": {"question_0": "Blue"}
                }}),
            ],
        )
    );
}

// Covers: in a run nobody attends, `initialize` advertises no forms, an
// ask the policy leaves to a person is rejected, and a form the agent
// sends anyway is cancelled rather than left waiting.
// Owner: ACP driver (asks put to a person).
#[tokio::test]
async fn an_unattended_run_fails_a_persons_asks_closed() {
    let dir = tempfile::tempdir().unwrap();
    let mut policy = TestPolicy::new(dir.path());
    policy.decision = PermissionDecision::AskPerson(Asking::Tool);
    let mut turn = plan_exit();
    turn.push(ask_user_question());
    turn.extend(end("done"));

    let record = exercise(request(dir.path(), None), policy, script_of(turn)).await;

    assert_eq!(
        (capabilities(&record), record.replies),
        (
            Value::Null,
            vec![
                json!({"method": "session/request_permission", "result": {
                    "outcome": {"outcome": "selected", "optionId": "plan-no"}
                }}),
                json!({"method": "elicitation/create", "result": {"action": "cancel"}}),
            ],
        )
    );
}

// Covers: a plan the person approves that the agent offers no `allow_once`
// for is rejected, and the person is not told the agent left plan mode.
// Owner: ACP driver (asks put to a person).
#[tokio::test]
async fn an_approved_plan_the_agent_cannot_take_keeps_the_run_in_plan() {
    let dir = tempfile::tempdir().unwrap();
    let (person, heard) = approving_person();
    let mut request = request(dir.path(), None);
    request.overrides.person = Some(person);
    let mut policy = TestPolicy::new(dir.path());
    policy.decision = PermissionDecision::AskPerson(Asking::PlanExit {
        to: PermissionMode::Supervised,
    });
    policy.mode = Some("plan".into());
    policy.plan_exit_to = Some("default".into());
    let mut turn = plan_exit_offering(vec![PermissionOption::new(
        "plan-no",
        "No",
        PermissionOptionKind::RejectOnce,
    )]);
    turn.extend(end("done"));
    let script = Script {
        modes: vec!["plan".into(), "default".into()],
        turns: vec![turn],
        ..Script::default()
    };

    let record = exercise(request, policy, script).await;

    assert_eq!(
        (heard.lock().unwrap().clone(), record.replies),
        (
            vec![("plan".to_owned(), "ship it -> supervised".to_owned())],
            vec![json!({"method": "session/request_permission", "result": {
                "outcome": {"outcome": "selected", "optionId": "plan-no"}
            }})],
        )
    );
}

fn script_of(turn: Vec<Step>) -> Script {
    Script {
        turns: vec![turn],
        ..Script::default()
    }
}