rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The host's types as `rho-protocol` sends them. The registry's types stay
//! the host's own, so its record files and the wire can change apart.

use std::collections::{HashMap, HashSet};

use rho_protocol as wire;

use super::jobs::{JobId, JobRecord, JobState, JobSubject, Moved, TurnEnd};
use crate::app::agent_concurrency::{Budget, QueuePlace};

/// A session id as the wire sends it.
pub(super) fn session_to_wire(id: rho_sdk::SessionId) -> wire::SessionId {
    wire::SessionId::new(id.into_string())
}

/// The session id a request named, or `InvalidId` for a string no session
/// id can be.
pub(super) fn session_from_wire(
    id: &wire::SessionId,
) -> Result<rho_sdk::SessionId, rho_sdk::InvalidId> {
    rho_sdk::SessionId::from_string(id.as_str())
}

impl From<crate::agent::AgentRuntime> for wire::AgentRuntime {
    fn from(runtime: crate::agent::AgentRuntime) -> Self {
        match runtime {
            crate::agent::AgentRuntime::Rho => Self::Rho,
            crate::agent::AgentRuntime::ClaudeCli => Self::ClaudeCli,
            crate::agent::AgentRuntime::Antigravity => Self::Antigravity,
        }
    }
}

/// A model chosen for the sessions a session starts, as its file keeps it.
impl From<wire::ModelRef> for crate::app::session_runtime::StartedModel {
    fn from(wire::ModelRef { provider, model }: wire::ModelRef) -> Self {
        Self { provider, model }
    }
}

/// A runtime this daemon knows; a wire value it does not is the error.
impl TryFrom<wire::AgentRuntime> for crate::agent::AgentRuntime {
    type Error = wire::AgentRuntime;

    fn try_from(runtime: wire::AgentRuntime) -> Result<Self, Self::Error> {
        match runtime {
            wire::AgentRuntime::Rho => Ok(Self::Rho),
            wire::AgentRuntime::ClaudeCli => Ok(Self::ClaudeCli),
            wire::AgentRuntime::Antigravity => Ok(Self::Antigravity),
            unknown => Err(unknown),
        }
    }
}

impl From<&JobId> for wire::JobId {
    fn from(id: &JobId) -> Self {
        Self::new(id.as_str())
    }
}

impl From<&JobState> for wire::JobState {
    fn from(state: &JobState) -> Self {
        match state {
            JobState::Idle => Self::Idle,
            JobState::Queued | JobState::Requeued => Self::Queued,
            JobState::Running => Self::Running,
            JobState::WaitingForInput => Self::WaitingForInput,
            JobState::Ended(TurnEnd::Completed) => Self::Completed,
            JobState::Ended(TurnEnd::Failed(_)) => Self::Failed,
            JobState::Ended(TurnEnd::Cancelled) => Self::Cancelled,
            JobState::Ended(TurnEnd::TimedOut { .. }) => Self::TimedOut,
            JobState::Ended(TurnEnd::Interrupted) => Self::Interrupted,
        }
    }
}

/// Why a job in `state` failed, if it did.
fn failure(state: &JobState) -> Option<String> {
    match state {
        JobState::Ended(TurnEnd::Failed(error)) => Some(error.clone()),
        JobState::Idle
        | JobState::Queued
        | JobState::Running
        | JobState::Requeued
        | JobState::WaitingForInput
        | JobState::Ended(
            TurnEnd::Completed
            | TurnEnd::Cancelled
            | TurnEnd::TimedOut { .. }
            | TurnEnd::Interrupted,
        ) => None,
    }
}

/// The event that tells attached clients where a session's job is now.
pub(super) fn state_event(moved: &Moved) -> wire::SessionEvent {
    wire::SessionEvent::State {
        state: (&moved.state).into(),
        turn: moved.turn.clone(),
    }
}

/// `record` as `rho/job/list` reports it, with where the job waits for
/// capacity, if it does. `undelivered` names the workflow runs whose result
/// a session has yet to be given, and `live` is what the daemon follows of
/// the job, if it streams the job's session. `worktree_stale` is whether
/// its worktree is stale (see `sessions::worktree_stale`). `parent_job` is
/// what the job's parent is, as [`ParentJob::of`] says.
pub(super) fn job_summary(
    record: JobRecord,
    parent_job: ParentJob,
    queue: Option<QueuePlace>,
    undelivered: &HashSet<String>,
    live: Option<wire::JobLive>,
    worktree_stale: bool,
) -> wire::JobSummary {
    let JobRecord {
        id,
        subject,
        state,
        workspace,
        parent,
        grant,
        grant_limit,
        admission: _,
        created_at,
        updated_at,
        outcome: _,
        turn: _,
        worktree,
        worktree_removed_at: _,
        resume_after_restart: _,
        agent,
        title,
        keeping: _,
    } = record;
    let session = subject.session().cloned().map(session_to_wire);
    let child = child_role(&subject, parent_job).map(|role| {
        let child = wire::ChildInfo::new(role);
        let child = match agent {
            Some(agent) => child.running_as(agent.id, agent.engine),
            None => child,
        };
        match title {
            Some(title) => child.titled(title),
            None => child,
        }
    });
    // A session job's worktree is the record's; a subagent run's, its
    // subject's.
    let (kind, run, workflow_run, worktree) = match subject {
        JobSubject::Session { .. } => (wire::JobKind::Session, None, None, worktree),
        JobSubject::Subagent {
            run,
            worktree: run_worktree,
            ..
        } => (wire::JobKind::Subagent, run, None, run_worktree),
        JobSubject::Workflow { workflow_run } => (
            wire::JobKind::Workflow,
            None,
            Some(workflow_run.to_string()),
            None,
        ),
    };
    wire::JobSummary {
        id: (&id).into(),
        kind,
        state: (&state).into(),
        workspace,
        parent: parent.as_ref().map(Into::into),
        grant: (!grant.is_root()).then(|| grant.into()),
        grant_limit: grant_limit.map(Into::into),
        session,
        run,
        result_pending: workflow_run
            .as_ref()
            .is_some_and(|run| undelivered.contains(run)),
        workflow_run,
        created_at,
        updated_at,
        error: failure(&state),
        queue: queue.map(Into::into),
        live,
        worktree,
        worktree_stale,
        child,
    }
}

/// A job's parent, as far as what the job is to it goes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ParentJob {
    /// The job has none: a client started it.
    Client,
    /// The job names a parent the daemon no longer knows.
    Forgotten,
    /// The parent drives a workflow run.
    Workflow,
    /// The parent runs agent turns: a session's, or a subagent's.
    Agent,
}

impl ParentJob {
    /// The parent of each of `records`, in their order.
    pub(super) fn of(records: &[JobRecord]) -> Vec<Self> {
        let kinds: HashMap<&JobId, Self> = records
            .iter()
            .map(|record| {
                let kind = match record.subject {
                    JobSubject::Workflow { .. } => Self::Workflow,
                    JobSubject::Session { .. } | JobSubject::Subagent { .. } => Self::Agent,
                };
                (&record.id, kind)
            })
            .collect();
        records
            .iter()
            .map(|record| match &record.parent {
                None => Self::Client,
                Some(parent) => kinds.get(parent).copied().unwrap_or(Self::Forgotten),
            })
            .collect()
    }
}

/// What a job running `subject` is to its parent: `None` for a job a client
/// started, and for a workflow run's drive. A subagent whose parent the
/// daemon forgot is taken for a delegated one: retention never forgets a
/// job a kept job descends from (`jobs/retention.rs`), so a workflow node's
/// drive outlives it.
fn child_role(subject: &JobSubject, parent: ParentJob) -> Option<wire::ChildRole> {
    match (subject, parent) {
        (_, ParentJob::Client) | (JobSubject::Workflow { .. }, _) => None,
        (
            JobSubject::Session { .. },
            ParentJob::Forgotten | ParentJob::Workflow | ParentJob::Agent,
        ) => Some(wire::ChildRole::Started),
        (JobSubject::Subagent { .. }, ParentJob::Workflow) => Some(wire::ChildRole::WorkflowNode),
        (JobSubject::Subagent { .. }, ParentJob::Forgotten | ParentJob::Agent) => {
            Some(wire::ChildRole::Delegated)
        }
    }
}

impl From<Budget> for wire::Budget {
    fn from(budget: Budget) -> Self {
        match budget {
            Budget::AgentConcurrency => Self::AgentConcurrency,
            Budget::ClaudeAgentConcurrency => Self::ClaudeAgentConcurrency,
        }
    }
}

impl From<QueuePlace> for wire::QueuePlace {
    fn from(place: QueuePlace) -> Self {
        let QueuePlace {
            budget,
            limit,
            position,
        } = place;
        // Both are bounded far below `u32::MAX`: the limit by
        // `MAX_AGENT_CONCURRENCY`, the position by the runs one daemon
        // spawns.
        let count = |value: usize| u32::try_from(value).unwrap_or(u32::MAX);
        Self {
            budget: budget.into(),
            limit: count(limit),
            position: count(position),
        }
    }
}

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