use std::path::Path;
use rho_providers::model::models_dev;
use crate::{
added_dirs::AddedDirs,
app::{agent_binding::BoundAgent, session_assembly::BuiltSession},
config::Config,
permission::PermissionMode,
tools::mcp::config::McpConfig,
};
mod added_dirs;
mod advisor;
mod agent;
pub(in crate::app) mod agent_catalog;
mod approval_policy;
mod build;
mod cache_warm;
mod codemode;
mod compact;
mod context;
mod credentials;
mod delegation;
mod events;
mod handle;
mod inspect;
mod left_out;
mod mode;
mod open;
mod persist;
mod prompt;
mod prompt_gate;
mod prompt_turn;
mod providers;
mod pump;
mod saved_settings;
mod session_tools;
mod settings;
mod started_sessions;
mod switch;
#[cfg(test)]
mod test_support;
mod title;
mod tool_sources;
mod tree;
mod turn;
mod workflow;
mod workspace_rewind;
pub(crate) use added_dirs::AddDirError;
pub(crate) use agent::AgentTask;
pub(crate) use approval_policy::{
ensure_auto_classifier_model, ApprovalPolicy, UnattendedApprovals,
};
#[cfg(test)]
pub(in crate::app) use build::session_config;
pub(crate) use build::{
CacheWarming, ChildAgents, HostCapabilities, IdleTurns, QuestionSupport, RunShape,
SessionBuild, SessionLaunch, SessionRole, SessionUse,
};
pub(crate) use credentials::CredentialFailure;
use credentials::SessionCredentials;
pub(crate) use delegation::BackgroundWait;
use delegation::HeldNotices;
pub(crate) use events::{
cancelled_approval, ApprovalId, InsertedMessage, PlanApprovalId, PlanApprovalRequest,
SessionEvent, TurnControl,
};
pub(crate) use handle::{SessionHandle, SteerError};
pub(crate) use left_out::LeftOut;
pub(crate) use mode::SessionPermission;
pub(crate) use open::{NodeSession, SessionOpening};
pub(crate) use persist::SessionStorage;
pub(crate) use prompt::PromptScope;
pub(crate) use prompt_turn::{PlanReport, TurnView};
use saved_settings::SettingsPolicy;
pub(crate) use session_tools::SessionTools;
pub(crate) use settings::SettingChangeError;
pub(crate) use started_sessions::{
StartedMode, StartedModel, StartedSessionDefaults, StartedSessions,
};
pub(crate) use switch::resolve_switch_reasoning;
#[cfg(test)]
pub(in crate::app) use test_support::{
host_woken_runtime_on, idle_woken_runtime_on, unattended_runtime_on,
unsaved_unattended_runtime_on, HangUntilCancel,
};
pub(crate) use title::TitleJob;
use title::TitleState;
pub(crate) use tree::SelectNodeError;
pub(crate) use turn::{Turn, TurnIo, TurnOutcome, TurnStart};
pub(crate) use workflow::{StartedBy, WorkflowStart};
pub(crate) use workspace_rewind::{RewindError, RewoundConversation};
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub(crate) struct CommandRejected(pub(crate) String);
#[derive(Debug, thiserror::Error)]
#[error("could not continue session: its compacted context was not saved; load the session again")]
pub(crate) struct UnsavedCompaction;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CurrentModel {
pub(crate) provider: String,
pub(crate) model: String,
pub(crate) auth: String,
}
struct OpenedSession {
build: SessionBuild,
built: BuiltSession,
storage: SessionStorage,
agent: BoundAgent,
auth: String,
host_mcp: McpConfig,
added_dirs: AddedDirs,
permission: SessionPermission,
reopen_notice: Option<String>,
credentials: SessionCredentials,
providers: crate::config::ProviderConfigs,
}
pub(crate) struct SessionRuntime {
built: BuiltSession,
storage: SessionStorage,
agent: BoundAgent,
build: SessionBuild,
host_mcp: McpConfig,
added_dirs: AddedDirs,
permission: SessionPermission,
auth: String,
credentials: SessionCredentials,
providers: crate::config::ProviderConfigs,
handle: SessionHandle,
completed_runs: u64,
title: TitleState,
unsaved_compaction: bool,
reopen_notice: Option<String>,
held_notices: Option<HeldNotices>,
child_questions: Option<
tokio::sync::mpsc::Sender<crate::app::subagent_host_input::SubagentHostInputRequest>,
>,
settings: SettingsPolicy,
started_sessions: StartedSessions,
checkpoints_paused: bool,
}
impl SessionRuntime {
fn new(opened: OpenedSession) -> Self {
let OpenedSession {
build,
built,
storage,
agent,
auth,
host_mcp,
added_dirs,
permission,
reopen_notice,
credentials,
providers,
} = opened;
built.tools.bind_recall(storage.file());
let settings = SettingsPolicy::of(storage.file());
Self {
built,
storage,
agent,
build,
host_mcp,
added_dirs,
permission,
auth,
credentials,
providers,
handle: SessionHandle::new(),
completed_runs: 0,
title: TitleState::Unasked,
unsaved_compaction: false,
reopen_notice,
held_notices: None,
child_questions: None,
settings,
started_sessions: StartedSessions::default(),
checkpoints_paused: false,
}
}
pub(crate) fn session_id(&self) -> &rho_sdk::SessionId {
self.built.session.id()
}
pub(crate) fn agent_id(&self) -> &crate::agent::AgentId {
self.agent.id()
}
pub(crate) fn credentials(
&self,
) -> std::sync::Arc<dyn rho_providers::credentials::CredentialStore> {
self.build.host.environment.credentials()
}
pub(crate) fn tools(&self) -> SessionTools<'_> {
SessionTools::of(&self.built.tools)
}
pub(crate) fn config_path(&self) -> &Path {
&self.build.launch.config_path
}
pub(crate) fn configured_context_window(&self) -> Option<u64> {
let current = self.current_model();
model_context_window(¤t.provider, ¤t.model)
}
pub(crate) fn cwd(&self) -> &Path {
self.storage.cwd()
}
pub(crate) fn project_trust(&self) -> crate::workspace::ProjectTrusts {
self.build.host.environment.project_trust()
}
pub(crate) fn workspace_root(&self) -> &Path {
&self.permission.workspace_root
}
pub(crate) fn permission_mode(&self) -> PermissionMode {
self.permission.mode
}
pub(crate) fn handle(&self) -> SessionHandle {
self.handle.clone()
}
pub(crate) fn current_model(&self) -> CurrentModel {
let snapshot = self.built.session.snapshot();
let identity = snapshot.provider();
CurrentModel {
provider: identity.provider.clone(),
model: identity.model.clone(),
auth: self.auth.clone(),
}
}
pub(crate) fn model_prompt_notice(&self) -> Option<String> {
self.built.prompt_template.as_ref().map(|_| {
crate::app::model_prompt_metadata::provenance_notice(
self.built.prompt.provenance.as_ref(),
)
})
}
pub(crate) fn persistence(&self) -> crate::session::SessionPersistence {
self.storage.persistence()
}
pub(crate) fn is_saved(&self) -> bool {
self.storage.file().is_some()
}
pub(crate) fn change_mark(
&self,
change: impl FnOnce(
Option<crate::session::SessionMark>,
u64,
) -> Option<crate::session::SessionMark>,
) -> anyhow::Result<Option<crate::session::MarkChange>> {
self.storage
.file()
.map(|stored| stored.change_mark(change))
.transpose()
}
pub(crate) fn hooks(&self) -> rho_sdk::hooks::HookDispatcher {
self.built.runtime.hooks()
}
pub(crate) fn host_takes_child_questions(
&mut self,
) -> Option<
tokio::sync::mpsc::Receiver<crate::app::subagent_host_input::SubagentHostInputRequest>,
> {
match self.build.host.questions {
QuestionSupport::Available => {}
QuestionSupport::Unavailable => return None,
}
self.built.tools.subagents()?;
let (sender, receiver) = tokio::sync::mpsc::channel(
crate::app::subagent_host_input::SubagentHostInputBridge::QUEUE_CAPACITY,
);
self.child_questions = Some(sender);
self.send_child_questions_to_host();
Some(receiver)
}
fn send_child_questions_to_host(&self) {
if let (Some(sender), Some(manager)) = (&self.child_questions, self.built.tools.subagents())
{
manager.bind_host_input_to(sender.clone());
}
}
pub(crate) fn background_wait(&self) -> BackgroundWait {
BackgroundWait::of(self.build.host.children, self.build.host.idle_turns)
}
pub(crate) fn peer_sessions(&self) -> Option<&crate::app::peer_sessions::PeerInbox> {
self.build.host.peer_sessions.as_ref()
}
pub(crate) fn has_background_work(&self) -> bool {
let session_id = self.built.session.id().to_string();
delegation::BackgroundSources::of(&self.built.tools).has_work(&session_id)
|| self
.held_notices
.as_ref()
.is_some_and(delegation::HeldNotices::has_undelivered)
}
pub(crate) async fn shutdown(self) {
self.handle.cancel();
self.built.diagnostics.flush_unfinished_compaction().await;
self.built.teardown().await;
}
pub(crate) fn end_stopped(&self, reason: &str) {
self.dispatch_failed(&format!("stopped: {reason}"));
}
fn dispatch_failed(&self, message: &str) {
self.built.runtime.hooks().session_failed(
self.built.session.id(),
rho_sdk::hooks::HookSessionFailureKind::RunFailed,
message,
);
}
}
pub(crate) fn context_window(
configured: Option<u64>,
estimate: rho_sdk::ContextEstimate,
) -> Option<u64> {
configured.or(estimate.reported_context_window())
}
pub(crate) fn model_scoped_config(current: &CurrentModel, process_config: &Config) -> Config {
let mut config = process_config.clone();
config.provider = current.provider.clone();
config.model = current.model.clone();
config.auth = current.auth.clone();
config
}
fn model_context_window(provider: &str, model: &str) -> Option<u64> {
models_dev::cached_model_metadata(provider, model)
.and_then(|metadata| metadata.display_context_window())
}