rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::{
    collections::BTreeSet,
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

use pretty_assertions::assert_eq;
use serde_json::{json, Value};

use super::OUTLIVED;
use crate::{
    acp_runtime::{
        policy::AcpProtocol,
        runtime_children::{ChildRecord, RuntimeChild, RuntimeChildren, StartedChild},
        scripted_agent::{Script, ScriptedAgent, V2Script, V2Step},
        session::run_on_channel,
        test_support::{read_artifacts, request, TestPolicy, TEST_BUDGET},
    },
    cli_runtime::CliPrompt,
    run_artifacts::AttachmentEvent,
    subagent::{RunState, RunStatus},
};

/// The agent's id for the child, and its root's, as the fake names it.
const CHILD: &str = "child-1";
const ROOT: &str = "scripted-session";

/// A host that records each child it hears of under `dir`, a folder each,
/// and names `nested` as the host of the children each starts in turn.
struct Recorded {
    dir: PathBuf,
    started: Mutex<Vec<RuntimeChild>>,
    nested: Option<Arc<Recorded>>,
}

impl Recorded {
    fn new(dir: PathBuf, nested: Option<Arc<Recorded>>) -> Arc<Self> {
        Arc::new(Self {
            dir,
            started: Mutex::new(Vec::new()),
            nested,
        })
    }
}

impl RuntimeChildren for Recorded {
    fn started(&self, child: RuntimeChild) -> StartedChild<'_> {
        let dir = self.dir.join(&child.id);
        std::fs::create_dir_all(&dir).unwrap();
        self.started.lock().unwrap().push(child);
        Box::pin(std::future::ready(Ok(ChildRecord {
            output_file: dir.join("result.json"),
            works_for: Some(ROOT.into()),
            identity: request(&dir, None).identity,
            status_tx: None,
            observer: None,
            children: self
                .nested
                .clone()
                .map(|nested| nested as Arc<dyn RuntimeChildren>),
        })))
    }
}

/// A step of the fake's turn: `update` on `session`, [`ROOT`] or a child's.
fn update(session: &str, update: Value) -> V2Step {
    let session = (session != ROOT).then_some(session);
    serde_json::from_value(json!({"step": "update", "session": session, "update": update})).unwrap()
}

fn said(session: &str, text: &str) -> V2Step {
    update(
        session,
        json!({"sessionUpdate": "agent_message_chunk", "messageId": "m", "content": {"type": "text", "text": text}}),
    )
}

/// `parent`'s announcement of its child `child`, titled `title`, in `state`.
fn announces(parent: &str, child: &str, title: &str, state: Value) -> V2Step {
    update(
        parent,
        json!({
            "sessionUpdate": "subagent_update",
            "sessionId": child,
            "title": title,
            "description": "general-purpose",
            "capabilities": {"cancel": {}},
            "state": state,
        }),
    )
}

fn running() -> Value {
    json!({"state": "running", "background": []})
}

/// `from`'s task, or reply, `text` for `to`, sent on `from`'s session as
/// the agent sends a task, or on `to`'s as it hands a reply back.
fn message(on: &str, from: &str, to: &str, text: &str) -> V2Step {
    update(
        on,
        json!({
            "sessionUpdate": "session_message",
            "messageId": format!("{from}-{to}"),
            "senderSessionId": from,
            "recipientSessionId": to,
            "content": [{"type": "text", "text": text}],
        }),
    )
}

fn goes_idle(session: &str) -> V2Step {
    update(
        session,
        json!({"sessionUpdate": "state_update", "state": "idle", "stopReason": "end_turn", "background": []}),
    )
}

/// Runs the root's one v2 `turn` in `dir`, with `host` recording its
/// children.
async fn run(dir: &Path, turn: Vec<V2Step>, host: Arc<Recorded>) {
    let script = Script {
        v2: Some(V2Script {
            turns: vec![turn],
            ..V2Script::default()
        }),
        ..Script::default()
    };
    let mut policy = TestPolicy::new(dir);
    policy.protocol = AcpProtocol::V2;
    let mut asked = request(dir, None);
    asked.overrides.runtime_children = Some(host);
    let (client, agent) = agent_client_protocol::Channel::duplex();
    let (fake, _record, _signals) = ScriptedAgent::new(script);
    tokio::time::timeout(TEST_BUDGET, async {
        let (client, agent) = tokio::join!(run_on_channel(asked, policy, client), fake.run(agent));
        client.unwrap();
        agent.unwrap();
    })
    .await
    .expect("ACP runtime/agent finished");
}

/// What a child's run recorded.
#[derive(Debug, PartialEq)]
struct ChildRun {
    state: RunState,
    reply: Option<String>,
    /// The agent's session it names, which a resume would take.
    agent_session: Option<String>,
    /// The session it works for.
    works_for: Option<String>,
    /// What it says it cost, which its root's counts already.
    cost: Option<f64>,
    /// The calls it showed.
    calls: BTreeSet<String>,
    /// The text it recorded for its task, its notices, and how it ended.
    shown: Vec<AttachmentEvent>,
}

/// What the child's run recorded, when it has one.
fn child_run(dir: &Path) -> Option<ChildRun> {
    if !dir.join("result.json").exists() {
        return None;
    }
    let (
        RunStatus {
            state,
            result,
            runtime_session_id,
            parent_session_id,
            total_cost_usd,
            ..
        },
        events,
    ) = read_artifacts(dir);
    let calls = events
        .iter()
        .filter_map(|event| match event {
            AttachmentEvent::ToolStarted { key: Some(key), .. } => Some(key.clone()),
            _ => None,
        })
        .collect();
    let shown = events
        .into_iter()
        .filter(|event| {
            matches!(
                event,
                AttachmentEvent::Prompt(_)
                    | AttachmentEvent::Notice(_)
                    | AttachmentEvent::Completed
                    | AttachmentEvent::Cancelled
                    | AttachmentEvent::Failed(_)
            )
        })
        .collect();
    Some(ChildRun {
        state,
        reply: result,
        agent_session: runtime_session_id,
        works_for: parent_session_id,
        cost: total_cost_usd,
        calls,
        shown,
    })
}

// Covers: a subagent a v2 agent starts is recorded as a run of its own from
// the task it got: what it says goes into its run, not the root's, and its
// run ends as it goes idle, from its own state or its root's mirror of it
// (cancelled, a stop), or stopped with a notice when the root's run ends
// first. It names the session it works for, no session of the agent's to
// resume, and no cost, which its root's counts; the hand-back of its
// reply starts nothing, and the root's turn ends as before, with its own reply.
// Owner: v2 runtime children (acp_runtime/v2/children.rs).
#[tokio::test]
async fn a_subagent_is_recorded_as_a_run_of_its_own() {
    let idle = |stop: &str| json!({"state": "idle", "stopReason": stop, "background": []});
    let outlived = AttachmentEvent::Notice(OUTLIVED.into());
    // How the child ends, and how its run did.
    let cases = [
        (
            "the child goes idle",
            vec![goes_idle(CHILD)],
            RunState::Ok,
            vec![AttachmentEvent::Completed],
        ),
        (
            "the root mirrors the child's cancel",
            vec![announces(ROOT, CHILD, "Reply pong", idle("cancelled"))],
            RunState::Stopped,
            vec![AttachmentEvent::Cancelled],
        ),
        (
            "the root's run ends first",
            vec![],
            RunState::Stopped,
            vec![outlived, AttachmentEvent::Cancelled],
        ),
    ];
    for (name, ends, state, end) in cases {
        let dir = tempfile::tempdir().unwrap();
        let mut turn = vec![
            V2Step::Running,
            announces(ROOT, CHILD, "Reply pong", running()),
            message(ROOT, ROOT, CHILD, "Reply pong"),
            update(
                CHILD,
                json!({"sessionUpdate": "tool_call_update", "toolCallId": "toolu_c1", "name": "Bash", "title": "ls", "kind": "execute", "status": "in_progress"}),
            ),
            said(CHILD, "pong"),
            update(
                CHILD,
                json!({"sessionUpdate": "usage_update", "used": 10, "size": 100, "cost": {"amount": 0.25, "currency": "USD"}}),
            ),
        ];
        turn.extend(ends);
        turn.extend([
            message(ROOT, CHILD, ROOT, "pong"),
            said(ROOT, "done"),
            V2Step::Idle {
                stop_reason: Some(agent_client_protocol::v2::schema::StopReason::EndTurn),
            },
        ]);
        let host = Recorded::new(dir.path().join("children"), None);
        run(dir.path(), turn, host.clone()).await;
        let (root, _) = read_artifacts(dir.path());

        assert_eq!(
            (
                host.started.lock().unwrap().clone(),
                child_run(&dir.path().join("children").join(CHILD)),
                root.result,
            ),
            (
                vec![RuntimeChild {
                    id: CHILD.into(),
                    title: Some("Reply pong".into()),
                    description: Some("general-purpose".into()),
                    task: CliPrompt::text("Reply pong"),
                }],
                Some(ChildRun {
                    state,
                    reply: Some("pong".into()),
                    agent_session: None,
                    works_for: Some(ROOT.into()),
                    cost: None,
                    calls: BTreeSet::from(["toolu_c1".to_owned()]),
                    shown: [vec![AttachmentEvent::Prompt("Reply pong".into())], end].concat(),
                }),
                Some("done".into()),
            ),
            "{name}"
        );
    }
}

// Covers: a subagent's own subagent, which the agent announces and tasks on
// its parent's session, not the root's, is recorded as a run of its own by
// the host its parent's run named, and by nobody when it named none; its
// report handed back to its idle parent starts nothing.
// Owner: v2 runtime children (acp_runtime/v2/children.rs).
#[tokio::test]
async fn a_subagents_own_subagent_is_recorded_by_its_parents_host() {
    const GRANDCHILD: &str = "child-2";
    let turn = || {
        vec![
            V2Step::Running,
            announces(ROOT, CHILD, "Ask a helper", running()),
            message(ROOT, ROOT, CHILD, "Ask a helper"),
            announces(CHILD, GRANDCHILD, "Reply ping", running()),
            message(CHILD, CHILD, GRANDCHILD, "Reply ping"),
            // The grandchild works in the background: its parent goes idle
            // first, and its report reaches it there, on both sessions.
            said(CHILD, "pong"),
            goes_idle(CHILD),
            said(GRANDCHILD, "ping"),
            message(GRANDCHILD, GRANDCHILD, CHILD, "ping"),
            message(CHILD, GRANDCHILD, CHILD, "ping"),
            goes_idle(GRANDCHILD),
            message(ROOT, CHILD, ROOT, "pong"),
            said(ROOT, "done"),
            V2Step::Idle {
                stop_reason: Some(agent_client_protocol::v2::schema::StopReason::EndTurn),
            },
        ]
    };
    let ran = |state| Some((state, Some("ping".to_owned())));
    // Whether the child's run names a host for its children, and the
    // grandchild's run, if anyone recorded one.
    let cases = [(true, ran(RunState::Ok)), (false, None)];
    for (names_host, grandchild) in cases {
        let dir = tempfile::tempdir().unwrap();
        let deeper = Recorded::new(dir.path().join("deeper"), None);
        let nested = Recorded::new(dir.path().join("grandchildren"), Some(deeper.clone()));
        let host = Recorded::new(
            dir.path().join("children"),
            names_host.then(|| nested.clone()),
        );
        run(dir.path(), turn(), host.clone()).await;
        let started = |host: &Recorded| -> Vec<String> {
            let started = host.started.lock().unwrap();
            started.iter().map(|child| child.id.clone()).collect()
        };
        let reply = |dir: PathBuf| child_run(&dir).map(|run| (run.state, run.reply));

        assert_eq!(
            (
                started(&host),
                started(&deeper),
                reply(dir.path().join("children").join(CHILD)),
                reply(dir.path().join("grandchildren").join(GRANDCHILD)),
            ),
            (
                vec![CHILD.to_owned()],
                Vec::<String>::new(),
                Some((RunState::Ok, Some("pong".into()))),
                grandchild,
            ),
            "names a host: {names_host}"
        );
    }
}