rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Permission mode changes for one session: swaps the mode by rebuilding the
//! SDK runtime around the live conversation, the same way the interactive
//! host does. Other changes that need a new runtime rebuild through here
//! too, around the live conversation or another point of the session's tree.

use std::path::PathBuf;

use rho_providers::credentials::CredentialStore;
use rho_sdk::{SessionOptions, SessionSnapshot, SystemPrompt};

use super::{
    ensure_auto_classifier_model, model_scoped_config, RunShape, SessionRuntime, SettingChangeError,
};
use crate::{
    app::{
        conversation_switch::replace_system_prompt,
        policy::AppPolicy,
        runtime_builder::{build_runtime_with_max_steps, RuntimeBuildOptions},
        sdk_config::WorkspaceOptions,
        session_assembly::ApprovalInputs,
    },
    compaction::CompactionConfig,
    config::Config,
    permission::{PermissionMode, SessionWriteLog},
};

/// Permission state one session owns. Starts from the process config's
/// mode; a host's mode change applies to this session only.
pub(crate) struct SessionPermission {
    pub(crate) mode: PermissionMode,
    /// Write grants the current policy remembers.
    pub(crate) writes: SessionWriteLog,
    /// Primary workspace root the session's tools resolve against.
    pub(crate) workspace_root: PathBuf,
}

/// What a permission-mode change does when the session already runs the mode.
#[derive(Clone, Copy)]
pub(crate) enum SameMode {
    /// Nothing.
    Keep,
    /// Auto rebuilds, reading the classifier model again.
    RebuildAuto,
}

/// A move of a session's permission mode, checked but not yet applied: the
/// config the mode runs under and the write grants its policy keeps. Rho's
/// own sessions and the tools a daemon session serves an agent on another
/// runtime (`daemon_host/sessions/acp_tools.rs`) move through it, wire the
/// mode's approvals and policy from it, and take it
/// ([`SessionPermission::take`]) only once that succeeded, so a failed
/// move leaves the session as it was.
pub(crate) struct ModeMove {
    pub(crate) mode: PermissionMode,
    /// The session's config in `mode`.
    pub(crate) config: Config,
    pub(crate) writes: SessionWriteLog,
}

impl ModeMove {
    /// A session's first mode, `mode` under `config`, with no write grants
    /// yet; [`SettingChangeError::Unsupported`] for a mode `config` cannot
    /// run: auto without a classifier model.
    pub(crate) fn first(
        mode: PermissionMode,
        config: &Config,
        credentials: &dyn CredentialStore,
    ) -> Result<Self, SettingChangeError> {
        Ok(Self {
            mode,
            config: config_in_mode(config, mode, credentials)?,
            writes: SessionWriteLog::default(),
        })
    }

    /// The permission state of a session whose tools resolve against
    /// `workspace_root`, in this mode.
    pub(crate) fn into_permission(self, workspace_root: PathBuf) -> SessionPermission {
        SessionPermission {
            mode: self.mode,
            writes: self.writes,
            workspace_root,
        }
    }
}

impl SessionPermission {
    /// Checks a move to `mode` under `config`, the session's config
    /// whatever mode it names: `None` when the session runs `mode` and
    /// `same` keeps it, [`SettingChangeError::Unsupported`] for a mode
    /// `config` cannot run (auto without a classifier model). Write grants
    /// carry across as [`SessionWriteLog::carried_across`] says.
    pub(crate) fn move_to(
        &self,
        mode: PermissionMode,
        config: &Config,
        credentials: &dyn CredentialStore,
        same: SameMode,
    ) -> Result<Option<ModeMove>, SettingChangeError> {
        let rebuild_same = match same {
            SameMode::Keep => false,
            SameMode::RebuildAuto => mode == PermissionMode::Auto,
        };
        if self.mode == mode && !rebuild_same {
            return Ok(None);
        }
        Ok(Some(ModeMove {
            mode,
            config: config_in_mode(config, mode, credentials)?,
            writes: self.writes.clone().carried_across(self.mode, mode),
        }))
    }

    /// Takes `moved`, once the session's approvals and policy run its mode.
    pub(crate) fn take(&mut self, moved: ModeMove) {
        self.mode = moved.mode;
        self.writes = moved.writes;
    }
}

/// `config` in `mode`, or [`SettingChangeError::Unsupported`] when it
/// cannot run `mode`: auto without a classifier model.
fn config_in_mode(
    config: &Config,
    mode: PermissionMode,
    credentials: &dyn CredentialStore,
) -> Result<Config, SettingChangeError> {
    let mut config = config.clone();
    config.permission_mode = mode;
    ensure_auto_classifier_model(&config, credentials)
        .map_err(|error| SettingChangeError::Unsupported(error.to_string()))?;
    Ok(config)
}

impl SessionRuntime {
    /// Applies `mode` to later prompts. The host holds the runtime between
    /// prompts, so none is in flight. On error the session keeps its old
    /// mode: a mode this session's config cannot run, such as auto without
    /// a classifier model, is [`SettingChangeError::Unsupported`].
    pub(crate) async fn set_permission_mode(
        &mut self,
        mode: PermissionMode,
        process_config: &Config,
    ) -> Result<(), SettingChangeError> {
        self.change_permission_mode(mode, process_config, SameMode::Keep)
            .await
    }

    /// [`Self::set_permission_mode`] as a client asks for it: Auto set again
    /// on a session that runs it rebuilds, so a classifier model picked
    /// since takes effect.
    pub(crate) async fn reapply_permission_mode(
        &mut self,
        mode: PermissionMode,
        process_config: &Config,
    ) -> Result<(), SettingChangeError> {
        self.change_permission_mode(mode, process_config, SameMode::RebuildAuto)
            .await
    }

    async fn change_permission_mode(
        &mut self,
        mode: PermissionMode,
        process_config: &Config,
        same: SameMode,
    ) -> Result<(), SettingChangeError> {
        let config = model_scoped_config(&self.current_model(), process_config);
        let credentials = self.build.host.environment.credentials();
        let Some(moved) = self
            .permission
            .move_to(mode, &config, credentials.as_ref(), same)?
        else {
            return Ok(());
        };
        // `exit_plan_mode` is offered only in plan mode; the rebuilt runtime
        // must see the tool list of the mode it serves.
        self.built.tools.set_plan_exit_registered(mode);
        if let Err(error) = self
            .rebuild_runtime(&moved.config, mode, moved.writes.clone())
            .await
        {
            self.built
                .tools
                .set_plan_exit_registered(self.permission.mode);
            return Err(error);
        }
        if let Some(manager) = self.built.tools.subagents() {
            manager.update_permission_mode(mode);
        }
        self.permission.take(moved);
        Ok(())
    }

    /// `process_config` scoped to the session's model, in `mode`, or
    /// [`SettingChangeError::Unsupported`] when that config cannot run
    /// `mode`: auto without a classifier model.
    pub(super) fn config_for_mode(
        &self,
        mode: PermissionMode,
        process_config: &Config,
    ) -> Result<Config, SettingChangeError> {
        let config = model_scoped_config(&self.current_model(), process_config);
        let credentials = self.build.host.environment.credentials();
        config_in_mode(&config, mode, credentials.as_ref())
    }

    /// Rebuilds the SDK runtime around the live conversation and the tool
    /// set as it stands, with `mode`'s policy and approvals over `writes`
    /// whatever mode `config` names, keeping the session's run shape. The
    /// live runtime is replaced only once the new one holds the session, so
    /// on error the session keeps its runtime. Callers that change the tool
    /// list keep the system prompt and tell the model with an appended notice instead.
    pub(super) async fn rebuild_runtime(
        &mut self,
        config: &Config,
        mode: PermissionMode,
        writes: SessionWriteLog,
    ) -> Result<(), SettingChangeError> {
        self.rebuild_around(config, mode, writes, /*moved_to*/ None)
            .await
    }

    /// [`Self::rebuild_runtime`], around `conversation`, another point of
    /// the session's saved tree, in place of the live one. The conversation
    /// runs under the system prompt the session has now, which a node saved
    /// before a model switch does not hold, and the checklist and loaded
    /// tools are the ones it had there.
    pub(super) async fn rebuild_runtime_onto(
        &mut self,
        config: &Config,
        mode: PermissionMode,
        writes: SessionWriteLog,
        conversation: SessionSnapshot,
    ) -> Result<(), SettingChangeError> {
        self.rebuild_around(config, mode, writes, Some(conversation))
            .await
    }

    /// Rebuilds around `moved_to`, or the live conversation when `None`.
    async fn rebuild_around(
        &mut self,
        config: &Config,
        mode: PermissionMode,
        writes: SessionWriteLog,
        moved_to: Option<SessionSnapshot>,
    ) -> Result<(), SettingChangeError> {
        // Approvals follow the session's mode, which a caller's config,
        // built from the process config, may not carry.
        let mut config = config.clone();
        config.permission_mode = mode;
        let config = &config;
        let approval = self.build.host.approvals.wire(ApprovalInputs {
            config: config.clone(),
            workspace_root: self.permission.workspace_root.clone(),
            usage_recording: self.built.runtime.usage_recording(),
            session_writes: writes.clone(),
            credentials: self.build.host.environment.credentials(),
        });
        let workspace = WorkspaceOptions {
            root: self.permission.workspace_root.clone(),
        }
        .build_workspace(&self.added_dirs)
        .map_err(|error| SettingChangeError::Apply(error.into()))?;
        // The whole run shape, as when the session opened: a rebuild keeps
        // its step limit, attribution and hook labels.
        let RunShape {
            role,
            max_steps,
            hook_labels,
        } = &self.build.run;
        let runtime = build_runtime_with_max_steps(
            RuntimeBuildOptions {
                provider: std::sync::Arc::clone(&self.built.provider),
                tools: &self.built.tools,
                workspace,
                workspace_policy: AppPolicy::for_mode(
                    mode,
                    writes,
                    self.build.host.environment.current().path(),
                ),
                approval_session: approval.session,
                system_prompt: self.built.prompt.system.clone(),
                reasoning: self.built.session.reasoning_level(),
                service_tier: self.built.session.service_tier(),
                compaction: CompactionConfig::from(config),
                context_window: self.configured_context_window(),
                usage_purpose: role.usage_purpose(),
                usage_parent_session_id: role.parent().cloned(),
                usage_recording: self.built.runtime.usage_recording(),
                hook_host_labels: hook_labels.clone(),
                hooks: self.built.hooks.as_ref(),
                diagnostics: self.built.diagnostics.clone(),
                recall: self.built.tools.recall_store(),
                model_requests: self.build.host.model_requests.clone(),
            },
            *max_steps,
        )
        .map_err(|error| SettingChangeError::Apply(error.into()))?;
        let conversation = moved_to
            .clone()
            .unwrap_or_else(|| self.built.session.snapshot());
        let rebound = runtime
            .rebind_session(SessionOptions::from_snapshot(conversation))
            .await
            .and_then(|session| {
                // Before the swap, so a failure leaves the live session.
                // The live conversation has the prompt already, and a
                // session without one has none to restore.
                if let (Some(_), SystemPrompt::Custom(text)) =
                    (&moved_to, &self.built.prompt.system)
                {
                    replace_system_prompt(&session, text)?;
                }
                Ok(session)
            });
        let session = match rebound {
            Ok(session) => session,
            Err(error) => {
                runtime.shutdown();
                return Err(SettingChangeError::Apply(error.into()));
            }
        };
        if moved_to.is_some() {
            let moved = session.snapshot();
            self.built.tools.todo_state().restore(&moved);
            self.built.tools.code_mode().restore(&moved);
        }
        let previous = std::mem::replace(&mut self.built.runtime, runtime);
        self.built.session = session;
        self.built.approval_receiver = approval.receiver;
        if let Some(advisor) = self.built.tools.advisor() {
            advisor.bind_session(self.built.session.clone());
        }
        previous.shutdown();
        Ok(())
    }
}

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