rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The children a v2 agent starts on its own, recorded as its run's host
//! asks ([`RuntimeChildren`]).
//!
//! claude-agent-acp 0.114.0 announces a Task subagent on the session that
//! started it, the root's or another subagent's (`subagent_update`, with its
//! title, description and state), hands it its task there
//! (`session_message` from that session to the child), streams its work
//! under the child's session id, mirrors its states onto the announcement,
//! and hands its reply back (`session_message` from the child, which its
//! parent's own reply carries on). A subagent's own subagent is recorded
//! by the host its parent's run names ([`ChildRecord::children`]), while
//! that run lasts. The child's run starts with its
//! task and ends with the first `idle` after it went `running`, from either
//! side, so a stale `idle` ends no later run; a later task to the same child
//! starts another run. Its reply is what it said, as a run's is: the
//! hand-back repeats it, so it is not read.
//!
//! A child's run ends on a task of its own, so writing its last status
//! holds up nothing the root's turn reads; the root's run waits for those
//! as it ends ([`Children::end`]).

use std::{
    collections::{HashMap, HashSet},
    path::Path,
    sync::Arc,
};

use agent_client_protocol::{
    schema::MaybeUndefined,
    v1::schema::{self as v1, ToolCallId},
    v2::schema as v2,
};
use tokio::task::JoinHandle;

use super::{
    tool_calls::ToolCalls,
    updates::{self, TurnEnd},
};
use crate::{
    acp_runtime::{
        connection,
        deciders::mark_rejected,
        driver::{render, DriverOutcome},
        runtime_children::{ChildRecord, RuntimeChild, RuntimeChildren},
        session::{run_ended, settle},
        turn::TurnClassification,
    },
    cli_runtime::{
        agent_event::{render::EventRenderer, AgentEvent},
        status_sink::{RuntimeLabel, StatusSink},
        CliPrompt,
    },
};

/// What a child's run says if the root's run ends while it works.
pub(super) const OUTLIVED: &str = "acp: the run ended before this subagent did";

/// The run's children, by the agent's id for each.
pub(super) struct Children<'a> {
    /// Who records the children each session starts, by its id: the root's
    /// host, and each child's while its run lasts.
    hosts: HashMap<String, Arc<dyn RuntimeChildren>>,
    cwd: &'a Path,
    /// What a child's run shows as it starts: the run's own label.
    label: RuntimeLabel,
    known: HashMap<String, Child>,
    /// The ends of the runs that ended, still writing their last status.
    ending: Vec<JoinHandle<()>>,
}

/// A child the agent announced.
#[derive(Default)]
struct Child {
    /// The session that announced it, the root's or its parent child's,
    /// which alone hands it a task.
    announced_on: String,
    title: Option<String>,
    description: Option<String>,
    /// Whether it went `running` since its last `idle`.
    working: bool,
    /// Its run, from its task until it goes `idle`, while the host
    /// records it.
    run: Option<ChildRun>,
}

/// One task's run of a child, rendered as the run renders its own work.
struct ChildRun {
    sink: StatusSink,
    renderer: EventRenderer,
    tool_calls: ToolCalls,
}

impl<'a> Children<'a> {
    /// The children of the run of session `root`, working in `cwd`,
    /// labelled `label`, which `host` records, if anyone does.
    pub(super) fn new(
        root: &str,
        host: Option<Arc<dyn RuntimeChildren>>,
        cwd: &'a Path,
        label: RuntimeLabel,
    ) -> Self {
        Self {
            hosts: host
                .map(|host| (root.to_owned(), host))
                .into_iter()
                .collect(),
            cwd,
            label,
            known: HashMap::new(),
            ending: Vec::new(),
        }
    }

    /// Session `on`, the root or a child, announced a child, or changed
    /// what it says of one.
    pub(super) fn announced(&mut self, update: v2::SubagentUpdate, on: &str) {
        let id = update.session_id.to_string();
        let child = self.known.entry(id.clone()).or_insert_with(|| Child {
            announced_on: on.to_owned(),
            ..Child::default()
        });
        patch(&mut child.title, update.title);
        patch(&mut child.description, update.description);
        if let MaybeUndefined::Value(state) = &update.state {
            self.state(&id, state);
        }
    }

    /// Session `on`, the root or a child, sent a message: a task, when it
    /// went to a child it announced, which starts the child's run. Fails
    /// with the notice the root's run shows when the host could not record
    /// it.
    pub(super) async fn messaged(
        &mut self,
        message: &v2::SessionMessage,
        on: &str,
    ) -> Result<(), String> {
        let (MaybeUndefined::Value(sender), MaybeUndefined::Value(recipient)) =
            (&message.sender_session_id, &message.recipient_session_id)
        else {
            return Ok(());
        };
        if sender.to_string() != on {
            return Ok(());
        }
        let Some(host) = self.hosts.get(on).cloned() else {
            return Ok(());
        };
        let id = recipient.to_string();
        // A message to a child from anyone but its announcer, as a
        // subagent's report handed back to its idle parent, starts nothing.
        let Some(child) = self
            .known
            .get_mut(&id)
            .filter(|child| child.announced_on == on && child.run.is_none())
        else {
            return Ok(());
        };
        let task = match &message.content {
            MaybeUndefined::Value(content) => connection::v2_prompt(content),
            MaybeUndefined::Undefined | MaybeUndefined::Null => CliPrompt::text(""),
        };
        let started = RuntimeChild {
            id: id.clone(),
            title: child.title.clone(),
            description: child.description.clone(),
            task: task.clone(),
        };
        let record = host
            .started(started)
            .await
            .map_err(|error| format!("acp: could not record a subagent's run: {error}"))?;
        let ChildRecord {
            output_file,
            works_for,
            identity,
            status_tx,
            observer,
            children,
        } = record;
        // A child's rate limits are its root's, whose run reports them.
        let mut sink = StatusSink::new(
            output_file,
            &identity,
            &task,
            status_tx,
            /*rate_limits*/ None,
            self.label,
        )
        .map_err(|error| format!("acp: could not record a subagent's run: {error:#}"))?;
        if let Some(observer) = observer {
            sink.observed_by(observer);
        }
        sink.works_for(works_for);
        sink.mark_running();
        if let Some(children) = children {
            self.hosts.insert(id, children);
        }
        child.run = Some(ChildRun {
            sink,
            renderer: EventRenderer::new(self.cwd.to_path_buf()),
            tool_calls: ToolCalls::default(),
        });
        Ok(())
    }

    /// An update of a session other than the root's: a child's, rendered
    /// into its run, if it has one, or its own children's announcements and
    /// tasks. A call the run `rejected` stays failed, as the root's do.
    /// Fails with the notice the root's run shows when the host could not
    /// record a child.
    pub(super) async fn updated(
        &mut self,
        notification: v2::UpdateSessionNotification,
        rejected: &HashSet<ToolCallId>,
    ) -> Result<(), String> {
        let id = notification.session_id.to_string();
        if !self.known.contains_key(&id) {
            return Ok(());
        }
        match notification.update {
            v2::SessionUpdate::StateUpdate(state) => {
                self.state(&id, &state);
                return Ok(());
            }
            v2::SessionUpdate::SubagentUpdate(update) => {
                self.announced(update, &id);
                return Ok(());
            }
            v2::SessionUpdate::SessionMessage(message) => {
                return self.messaged(&message, &id).await;
            }
            _ => {}
        }
        let Some(run) = self.known.get_mut(&id).and_then(|child| child.run.as_mut()) else {
            return Ok(());
        };
        let event = match updates::rendered(&notification.update, &mut run.tool_calls) {
            None => return Ok(()),
            Some(Ok(mut update)) => {
                mark_rejected(&mut update, rejected);
                // A child's spend is its root's, which counts it.
                if let v1::SessionUpdate::UsageUpdate(usage) = &mut update {
                    usage.cost = None;
                }
                update.into()
            }
            Some(Err(source)) => AgentEvent::Notice(source.to_string()),
        };
        render(&mut run.renderer, &mut run.sink, event);
        Ok(())
    }

    /// The root's run ends: the runs of children still working end
    /// stopped, as the agent's process goes with it, and every child's
    /// last status is written.
    pub(super) async fn end(self) {
        for child in self.known.into_values() {
            if let Some(mut run) = child.run {
                render(
                    &mut run.renderer,
                    &mut run.sink,
                    AgentEvent::Notice(OUTLIVED.into()),
                );
                run_ended(&mut run.renderer, &mut run.sink);
                let outcome = DriverOutcome::of_child(TurnClassification::Stopped, &run.renderer);
                settle(run.sink, Ok(outcome)).await;
            }
        }
        for ending in self.ending {
            // A run that panicked writing its status left it to its sink.
            let _ = ending.await;
        }
    }

    /// Child `id` reported `state`: an `idle` after it went `running` ends
    /// its run, as the idle's stop reason says.
    fn state(&mut self, id: &str, state: &v2::StateUpdate) {
        let Some(child) = self.known.get_mut(id) else {
            return;
        };
        let stop = match state {
            v2::StateUpdate::Running(_) | v2::StateUpdate::RequiresAction(_) => {
                child.working = true;
                return;
            }
            v2::StateUpdate::Idle(idle) if child.working => idle.stop_reason.as_ref(),
            _ => return,
        };
        child.working = false;
        let Some(mut run) = child.run.take() else {
            return;
        };
        // Its job is done: a child it tasks now has no job to list it.
        self.hosts.remove(id);
        let end = TurnEnd::of_child(stop);
        render(
            &mut run.renderer,
            &mut run.sink,
            AgentEvent::TurnEnded(end.reason),
        );
        run_ended(&mut run.renderer, &mut run.sink);
        let outcome = DriverOutcome::of_child(end.classification, &run.renderer);
        self.ending
            .push(tokio::spawn(settle(run.sink, Ok(outcome))));
    }
}

/// Applies a v2 patch of a display field: unset leaves it, `null` clears it.
fn patch(field: &mut Option<String>, value: MaybeUndefined<String>) {
    match value {
        MaybeUndefined::Undefined => {}
        MaybeUndefined::Null => *field = None,
        MaybeUndefined::Value(value) => *field = Some(value),
    }
}

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