rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A started session's budgeted turn for tests of what lends its slot and
//! what waits on its agent: the budget's own (`budget_tests`), and the
//! background delivery's (`acp_background_tests`).

use std::{
    future::{pending, Future},
    path::PathBuf,
    sync::{Arc, Weak},
};

use futures_util::{future::BoxFuture, FutureExt};
use rho_sdk::CancellationToken;
use tempfile::TempDir;

use super::{run_on_slot, Budgeted, Lending, ModelSlot};
use crate::{
    acp_runtime::agent_tools::{AgentRequest, Readied},
    app::{
        agent_binding::CapacityClass,
        agent_concurrency::RuntimePermits,
        daemon_host::{
            jobs::{JobId, JobRecord, JobRegistry, JobStore, TurnRecord},
            subagents::{Subagents, TurnBudget},
        },
    },
    caller_context::CallerContext,
};

/// A started session's turn, its job running, on the only slot of a
/// one-slot budget.
pub(in super::super) struct Turn {
    _home: TempDir,
    pub(in super::super) jobs: Arc<JobRegistry>,
    subagents: Subagents,
    pub(in super::super) job: JobId,
    pub(in super::super) model: Arc<ModelSlot>,
}

impl Turn {
    /// The turn, and the slot it was admitted with, for [`Self::run`].
    pub(in super::super) async fn admitted() -> (Self, Budgeted) {
        let home = TempDir::new().unwrap();
        let jobs = Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap()));
        let subagents = Subagents::new(Arc::clone(&jobs), CancellationToken::new());
        subagents.concurrency().set_total(1);
        let record = JobRecord::new_session(
            JobId::generate(),
            PathBuf::from("/work"),
            rho_sdk::SessionId::new(),
        );
        let job = record.id.clone();
        jobs.register(record).unwrap();
        jobs.start_turn(
            &job,
            TurnRecord::starting(/*key*/ None),
            CallerContext::ROOT,
        )
        .unwrap();
        let TurnBudget {
            queued,
            line,
            listing,
        } = subagents.queue_turn(&job);
        let permits = queued
            .acquire(&CancellationToken::new())
            .await
            .expect("the only slot is free");
        drop(listing);
        let budgeted = Budgeted::admitted(permits, line, Weak::new());
        let turn = Self {
            _home: home,
            jobs,
            subagents,
            job,
            model: Arc::default(),
        };
        (turn, budgeted)
    }

    /// Runs the turn, which never ends on its own, lending as `lending`
    /// says. Unconstrained, so tokio's cooperative budget never makes a
    /// poll of it return early.
    pub(in super::super) fn run(
        &self,
        budgeted: Budgeted,
        lending: Lending,
    ) -> impl Future<Output = ()> + '_ {
        tokio::task::unconstrained(run_on_slot(
            &self.model,
            &self.jobs,
            &self.job,
            budgeted,
            lending,
            pending::<()>(),
        ))
    }

    /// One of the agent's requests to the served tools, outstanding.
    pub(in super::super) fn request(&self) -> AgentRequest {
        self.model.request()
    }

    /// Records a subagent run the turn started, waiting for capacity: the
    /// turn runs alone no more.
    pub(in super::super) fn start_child(&self) {
        let child = JobRecord::new_subagent(
            self.job.clone(),
            PathBuf::from("/work"),
            /*session*/ None,
            "run".into(),
            /*worktree*/ None,
        );
        self.jobs.register(child).unwrap();
    }

    /// Whether the budget's only slot is free, as when the turn lent it.
    pub(in super::super) fn slot_free(&self) -> bool {
        self.subagents.concurrency().available_total() == 1
    }

    /// Another run takes the slot the turn lent.
    pub(in super::super) fn take_lent_slot(&self) -> RuntimePermits {
        self.subagents
            .concurrency()
            .join(CapacityClass::Rho)
            .acquire(&CancellationToken::new())
            .now_or_never()
            .flatten()
            .expect("the turn lent the only slot")
    }
}

/// Readies `request`'s answer, with no deadline, as a future polled more
/// than once.
pub(in super::super) fn answer(request: AgentRequest) -> BoxFuture<'static, Readied> {
    Box::pin(tokio::task::unconstrained(
        request.answer_by(/*deadline*/ None),
    ))
}