rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Steering a session's running turn: staging input for its next model
//! request, and withdrawing a steer before it applies.
//!
//! A steer answers with the id the run accepted it under, and the session's
//! live mapper keeps its content until the run applies it, which shows as a
//! user message carrying that id (see
//! [`crate::app::session_events::LiveEvents::steered`]). A session an agent
//! of another runtime runs takes the steer into its turn's run instead, which
//! journals it as [`crate::run_artifacts::AttachmentEvent::Steered`] once the
//! agent took it ([`super::acp_steer`]). Neither request loads a session:
//! one that is not loaded has no turn to steer.

use rho_protocol::{
    ContentBlock, ErrorCode, RpcError, SessionCapability, SessionSteerQuery, SessionSteerResponse,
    SessionUnsteerParams, SessionUnsteerResponse, UnsteerOutcome,
};
use rho_sdk::{SteeringId, SteeringRetraction};

use super::{
    acp_steer::{AcpSteerError, STEER_SLOTS},
    Sessions,
};
use crate::{
    agent::AgentRuntime,
    app::{
        prompt_content::steer_input, session_events::steer_to_wire, session_runtime::SteerError,
    },
    cli_runtime::CliPrompt,
};

impl Sessions {
    /// Stages the steer's text and attachments for the running turn's next
    /// model request, and answers with the id it applies under as soon as
    /// the run staged it, which it does whatever it is waiting on: a tool
    /// call, a compaction, or the end of background work it holds its
    /// completion for. Attachments are checked as a prompt's blocks are, and
    /// an image needs the session to take attachments, as a prompt's does.
    /// A session an agent of another runtime runs takes it into its turn's
    /// run instead ([`super::acp_steer`]).
    pub(in crate::app::daemon_host) async fn steer(
        &self,
        query: SessionSteerQuery,
    ) -> Result<SessionSteerResponse, RpcError> {
        let attaches = query
            .attachments
            .iter()
            .any(|block| matches!(block, ContentBlock::Image { .. }));
        let input = steer_input(query.params.text, &query.attachments).map_err(|error| {
            RpcError::new(
                ErrorCode::InvalidParams,
                format!("could not read the steer's attachments: {error}"),
            )
        })?;
        let Some(session) = self.loaded_session(&query.params.session).await? else {
            return Err(not_steerable());
        };
        session.require(SessionCapability::Steer)?;
        if attaches {
            session.require(SessionCapability::Attachments)?;
        }
        match session.runtime {
            AgentRuntime::Rho => {}
            AgentRuntime::ClaudeCli | AgentRuntime::Antigravity => {
                let content = CliPrompt::from_user_input(&input)
                    .map_err(|error| RpcError::new(ErrorCode::InvalidParams, error))?;
                let id = session.acp_steers.steer(content).map_err(acp_refused)?;
                return Ok(SessionSteerResponse { id });
            }
        }
        let receipt = session
            .handle
            .steer(input.clone())
            .map_err(|error| refused(error, "steer session"))?;
        let id = receipt
            .await
            .map_err(|error| refused(SteerError::from_sdk(error), "steer session"))?;
        session.live().steered(id.clone(), &input);
        Ok(SessionSteerResponse {
            id: steer_to_wire(&id),
        })
    }

    /// Withdraws a steer the running turn has not applied yet, and answers
    /// with what became of it.
    pub(in crate::app::daemon_host) async fn unsteer(
        &self,
        params: SessionUnsteerParams,
    ) -> Result<SessionUnsteerResponse, RpcError> {
        let Some(session) = self.loaded_session(&params.session).await? else {
            return Err(not_steerable());
        };
        session.require(SessionCapability::Steer)?;
        match session.runtime {
            AgentRuntime::Rho => {}
            AgentRuntime::ClaudeCli | AgentRuntime::Antigravity => {
                let outcome = session
                    .acp_steers
                    .unsteer(&params.id)
                    .map_err(acp_refused)?;
                return Ok(SessionUnsteerResponse { outcome });
            }
        }
        let id = SteeringId::from_string(params.id.as_str())
            .map_err(|_| RpcError::new(ErrorCode::InvalidParams, "not a steer id"))?;
        let retraction = session
            .handle
            .retract(id.clone())
            .map_err(|error| refused(error, "withdraw the steer"))?;
        let retraction = retraction
            .await
            .map_err(|error| refused(SteerError::from_sdk(error), "withdraw the steer"))?;
        let outcome = match retraction {
            SteeringRetraction::Retracted => {
                session.live().withdrawn(&id);
                UnsteerOutcome::Withdrawn
            }
            SteeringRetraction::Delivered => UnsteerOutcome::Delivered,
            SteeringRetraction::AlreadyApplied => UnsteerOutcome::Applied,
            SteeringRetraction::NotFound => UnsteerOutcome::NotFound,
        };
        Ok(SessionUnsteerResponse { outcome })
    }
}

/// The error a steer or unsteer answers while no model request is taking
/// input.
fn not_steerable() -> RpcError {
    RpcError::new(ErrorCode::NotSteerable, "no model request is taking input")
}

/// The error a steer or unsteer the session's turn refused answers:
/// `NotSteerable` once no model request takes input, else `SteerRefused`
/// saying it could not `action`, and why.
fn refused(error: SteerError, action: &str) -> RpcError {
    match error {
        SteerError::NotRunning => not_steerable(),
        SteerError::Refused(error) => RpcError::new(
            ErrorCode::SteerRefused,
            format!("could not {action}: {error}"),
        ),
    }
}

/// The error a steer or unsteer of an agent of another runtime's turn
/// answers: `NotSteerable` once no turn takes it, else `SteerRefused`
/// naming the limit it hit.
fn acp_refused(error: AcpSteerError) -> RpcError {
    match error {
        AcpSteerError::NoTurn => not_steerable(),
        AcpSteerError::QueueFull => RpcError::new(
            ErrorCode::SteerRefused,
            format!(
                "could not steer session: the running turn holds {STEER_SLOTS} steers the agent has not taken, its limit; wait for it to take one"
            ),
        ),
    }
}