rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The work an agent goes on with after its prompted turn ends: what its
//! root session's states list as `background`, and the turns it starts on
//! its own to report what that work did. The run keeps the agent while
//! either may come, so its answer is the agent's last word, not a
//! placeholder such as "the subagent has not reported back yet".
//!
//! Recorded against claude-agent-acp 0.114.0 (Claude Code 2.1.334):
//! - Every root state lists the work: a background command as its
//!   `terminal`, a background subagent as its `subagent`.
//! - When an item ends, Claude starts a turn of its own to report it
//!   (`running`, its reply, `idle`), also for an item that ended while a
//!   turn ran. Its `running` came 0.49 to 0.75 s after the list emptied
//!   (Haiku, Sonnet, Opus; n=4), with that turn's first output, so nothing
//!   earlier announces it.
//! - Claude Code hands an ended background command to the turn's next model
//!   step: one that ended before a tool call of the same turn finished was
//!   folded into it, and no turn reports it (7 of 7 probed turns: a
//!   foreground command, or a read of the output, after it ended). One that
//!   ended during the turn's last step, or after the turn, is reported by a
//!   turn of its own (6 of 6). Every call opens `pending`; a background
//!   command's own call finishes before its terminal is listed; a listed
//!   tool call (Monitor, Workflow) finishes as its work ends (adapter
//!   source, `endToolCall`).
//!
//! So the run waits while work is listed, up to [`BACKGROUND_BUDGET`], and
//! once an item ended, [`FOLLOW_UP_WAIT`] for the turn that reports it. A
//! turn that starts settles what was owed, and a call of the turn that
//! finishes settles the commands that ended before it; no probe showed
//! other ended work folded, so it stays owed. Both limits are tripwires:
//! real use that hits them means remeasuring.

use agent_client_protocol::v2::schema as v2;
use std::time::Duration;
use tokio::time::Instant;

/// How long the run keeps the agent for its background work, counted from
/// the end of the prompted turn: Claude Code 2.1.334's longest foreground
/// Bash timeout (`BASH_MAX_TIMEOUT_MS`, default 600000 ms), so background
/// work gets as long as one command could take in the foreground. A command
/// that never exits, such as a dev server, holds the run this long.
pub(super) const BACKGROUND_BUDGET: Duration = Duration::from_secs(600);

/// How long the run waits for the turn that reports an ended item to start:
/// 40 times the largest gap measured (0.75 s), for a slow first output.
pub(super) const FOLLOW_UP_WAIT: Duration = Duration::from_secs(30);

/// The root session's background work, as its states report it. The run
/// keeps the agent from the first idle at which work may still report
/// ([`Self::idle`]) until it prompts the agent again ([`Self::prompted`]).
#[derive(Default)]
pub(super) struct Background {
    /// The latest list.
    listed: Vec<Item>,
    /// The session's latest state is foreground work.
    running: bool,
    /// What ended since the last turn started, less the commands a later
    /// step of a turn took in: the agent may start a turn to report it.
    ended: Vec<Item>,
    /// Calls the running turn opened that have not finished.
    open: Vec<String>,
    budget: Option<Instant>,
    follow_up: Option<Instant>,
}

/// One piece of listed work, by the entity the agent names it by. Its
/// `_meta` is left out: an update that changes it is the same work.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Item {
    Command(String),
    ToolCall(String),
    Subagent(String),
    Other(String),
}

impl std::fmt::Display for Item {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Command(id) => write!(f, "command {id}"),
            Self::ToolCall(id) => write!(f, "tool call {id}"),
            Self::Subagent(id) => write!(f, "subagent {id}"),
            Self::Other(kind) => write!(f, "{kind} work"),
        }
    }
}

impl Background {
    /// Reads a state of the root session.
    pub(super) fn observe(&mut self, state: &v2::StateUpdate) {
        let running = matches!(
            state,
            v2::StateUpdate::Running(_) | v2::StateUpdate::RequiresAction(_)
        );
        // A turn that starts takes what was owed.
        if running && !self.running {
            self.ended.clear();
            self.open.clear();
            self.follow_up = None;
        }
        self.running = running;
        // An agent that reports no list is not known to run anything.
        let listed: Vec<Item> = state
            .background()
            .unwrap_or_default()
            .iter()
            .map(item)
            .collect();
        let gone = self.listed.iter().filter(|item| !listed.contains(item));
        self.ended.extend(gone.cloned());
        self.listed = listed;
    }

    /// Reads a tool call of the root session. One the running turn opened
    /// that finishes (`completed` or `failed`) was a step of the turn: the
    /// next one takes in the commands that ended before it. A call first
    /// heard finished opened no step. A listed tool call that finishes is
    /// its work ending, which stays owed like any work but a command.
    pub(super) fn tool_call(&mut self, call: &v2::ToolCallUpdate) {
        if !self.running {
            return;
        }
        let id = call.tool_call_id.to_string();
        match call.status.value() {
            Some(v2::ToolCallStatus::Pending | v2::ToolCallStatus::InProgress) => {
                if !self.open.contains(&id) {
                    self.open.push(id);
                }
            }
            Some(v2::ToolCallStatus::Completed | v2::ToolCallStatus::Failed) => {
                let Some(at) = self.open.iter().position(|open| *open == id) else {
                    return;
                };
                self.open.swap_remove(at);
                self.ended.retain(|item| !matches!(item, Item::Command(_)));
            }
            // An update that leaves the status, or one this client does not
            // know (`ToolCallStatus` is non-exhaustive), says nothing of a step.
            _ => {}
        }
    }

    /// The session is idle with no prompt of the run's outstanding: until
    /// when the run keeps the agent, or `None` when it is done.
    pub(super) fn idle(&mut self, now: Instant) -> Option<Instant> {
        if self.listed.is_empty() && self.ended.is_empty() {
            return None;
        }
        self.budget.get_or_insert(now + BACKGROUND_BUDGET);
        if self.listed.is_empty() {
            self.follow_up.get_or_insert(now + FOLLOW_UP_WAIT);
        } else {
            self.follow_up = None;
        }
        self.deadline()
    }

    /// The run keeps the agent for work that may still report.
    pub(super) fn keeping(&self) -> bool {
        self.budget.is_some()
    }

    /// When the run stops keeping the agent, unless the agent goes on.
    pub(super) fn deadline(&self) -> Option<Instant> {
        match (self.budget, self.follow_up) {
            (Some(budget), Some(follow_up)) => Some(budget.min(follow_up)),
            (budget, follow_up) => budget.or(follow_up),
        }
    }

    /// The notice that the run stops at `now`, its [`Self::deadline`],
    /// because the budget is spent, naming what still ran; `None` when it
    /// stops because no turn came to report the work that ended.
    pub(super) fn expired(&self, now: Instant) -> Option<String> {
        if self.budget.is_none_or(|budget| now < budget) {
            return None;
        }
        let turn = self
            .running
            .then(|| "a turn the agent started on its own".to_owned());
        let still: Vec<String> = turn
            .into_iter()
            .chain(self.listed.iter().map(Item::to_string))
            .collect();
        let still = match still.is_empty() {
            true => "the report of work that ended".to_owned(),
            false => still.join(", "),
        };
        Some(format!(
            "acp: background work budget of {} min after the prompted turn is spent; stopping the agent with still running: {still}",
            BACKGROUND_BUDGET.as_secs() / 60,
        ))
    }

    /// The run prompted the agent: what it waited on starts over.
    pub(super) fn prompted(&mut self) {
        self.budget = None;
        self.follow_up = None;
    }
}

fn item(work: &v2::BackgroundWork) -> Item {
    match work {
        v2::BackgroundWork::Terminal(terminal) => Item::Command(terminal.terminal_id.to_string()),
        v2::BackgroundWork::ToolCall(call) => Item::ToolCall(call.tool_call_id.to_string()),
        v2::BackgroundWork::Subagent(subagent) => Item::Subagent(subagent.session_id.to_string()),
        v2::BackgroundWork::Other(other) => Item::Other(other.kind.clone()),
        _ => Item::Other("background".to_owned()),
    }
}

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