use std::{
path::{Path, PathBuf},
sync::Arc,
};
use rho_protocol::{ClientEnvironment, ErrorCode, RpcError, SessionSetup};
use super::{
super::{jobs::JobId, settings::ConfigStore, subagents::Subagents},
pull_request_wake::PullRequestWake,
setup::{Base, Setup},
};
use crate::{
agent::{AgentCapabilities, AgentCatalog, AgentDefinition, DEFAULT_AGENT_ID},
app::{
agent_binding::{
root_host_tools, AgentBinder, AgentInvocation, AgentRole, BoundAgent, LaunchTools,
},
cli_config::{settle_bound_config, ProviderRefreshStatus, SettledConfig},
peer_sessions::PeerInbox,
prompt_content::PromptContext,
session_assembly::SignIn,
session_runtime::{
ApprovalPolicy, CacheWarming, ChildAgents, CredentialFailure, HostCapabilities,
IdleTurns, RunShape, SessionBuild, SessionLaunch, SessionOpening, SessionRole,
SessionRuntime, SessionUse,
},
subagent_pool::SubagentPool,
tools_prompt::ToolSourceLoad,
},
caller_context::CallerContext,
config::Config,
session::Session as StoredSession,
session_environment::{Ambient, SessionEnvironment},
session_temp_dir::{self, SessionTempDir},
tools::mcp::McpAuthorizationMode,
workspace::{ProjectTrust, ProjectTrusts},
};
pub(in crate::app::daemon_host) struct Workspace(PathBuf);
impl Workspace {
pub(in crate::app::daemon_host) fn parse(param: &str, cwd: &Path) -> Result<Self, RpcError> {
let invalid = |reason: String| {
RpcError::new(
ErrorCode::InvalidParams,
format!("invalid {param} {}: {reason}", cwd.display()),
)
};
if !cwd.is_absolute() {
return Err(invalid("not an absolute path".to_owned()));
}
let path = crate::paths::canonicalize(cwd).map_err(|error| invalid(error.to_string()))?;
if !path.is_dir() {
return Err(invalid("not a directory".to_owned()));
}
Ok(Self(path))
}
pub(in crate::app::daemon_host) fn path(&self) -> &Path {
&self.0
}
}
pub(super) enum Opening {
New {
workspace: Workspace,
agent: Option<String>,
started_by: Option<rho_sdk::SessionId>,
},
Saved(StoredSession),
Fork(StoredSession),
}
impl Opening {
fn cwd(&self) -> &Path {
match self {
Self::New {
workspace: Workspace(cwd),
..
} => cwd,
Self::Saved(stored) | Self::Fork(stored) => stored.cwd(),
}
}
}
pub(super) struct OpenWith {
pub(super) environment: Ambient,
pub(super) setup: SessionSetup,
pub(super) grant: CallerContext,
}
pub(super) struct OpenedSession {
pub(super) runtime: SessionRuntime,
pub(super) config: Config,
pub(super) global: Arc<Config>,
pub(super) environment: SessionEnvironment,
pub(super) setup: SessionSetup,
pub(super) fork_of: Option<rho_sdk::SessionId>,
pub(super) held_context: PromptContext,
}
enum Purpose<'a> {
Run {
sign_in: SignIn,
setup: SessionSetup,
pull_requests: &'a PullRequestWake,
},
Read,
}
pub(in crate::app::daemon_host) fn session_environment(
environment: &ClientEnvironment,
) -> Result<Ambient, RpcError> {
let variables = environment
.iter()
.map(|(name, value)| {
if name.is_empty() || name.contains(['=', '\0']) || value.contains('\0') {
return Err(RpcError::new(
ErrorCode::InvalidParams,
format!(
"invalid environment variable {name:?}: a name must be nonempty without `=` or NUL, and a value without NUL"
),
));
}
Ok((name.to_owned(), value.to_owned()))
})
.collect::<Result<_, _>>()?;
Ok(Ambient::Client(Arc::new(variables)))
}
pub(super) async fn config_for_new(settings: &ConfigStore) -> Result<Arc<Config>, RpcError> {
settings
.config_to_open()
.await
.map_err(|error| open_failed(error.into()))
}
pub(super) async fn config_for_saved(settings: &ConfigStore) -> Result<Arc<Config>, RpcError> {
settings
.agent_config()
.await
.map_err(|error| open_failed(error.into()))
}
pub(super) async fn open_session(
opening: Opening,
with: &OpenWith,
subagents: &Subagents,
pull_requests: &PullRequestWake,
settings: &ConfigStore,
global: Arc<Config>,
job: &JobId,
) -> Result<OpenedSession, RpcError> {
let base = match &opening {
Opening::New { .. } => Base::New,
Opening::Saved(stored) => Base::Reopened(stored),
Opening::Fork(parent) => Base::Forked(parent),
};
let setup = Setup::resolve(&with.setup, opening.cwd(), base)?;
let sign_in = match with.setup.sign_in {
rho_protocol::SignIn::Required => SignIn::Required,
rho_protocol::SignIn::Later => SignIn::Optional,
};
open_runtime(
opening,
SessionEnvironment::new(with.environment.clone()),
setup,
Purpose::Run {
sign_in,
setup: with.setup.clone(),
pull_requests,
},
subagents.pool_for(job.clone()),
settings,
global,
)
.await
.map_err(open_failed)
}
pub(super) fn open_failed(error: anyhow::Error) -> RpcError {
match CredentialFailure::find(&error) {
Some(failure) => {
tracing::warn!(error = format!("{error:#}"), "session needs a sign-in");
RpcError::new(
ErrorCode::SignInRequired,
format!("could not open session: {}", failure.message()),
)
}
None => RpcError::new(
ErrorCode::SessionOpenFailed,
format!("could not open session: {error:#}"),
),
}
}
fn reading_trust(stored: &StoredSession) -> anyhow::Result<ProjectTrusts> {
let catalog = AgentCatalog::discover(stored.cwd(), ProjectTrusts::UNTRUSTED)?;
let found = |id: &str, accepts: &dyn Fn(&AgentDefinition) -> bool| {
catalog
.find(id)
.is_ok_and(|entry| accepts(&entry.definition))
};
let root = stored.root_agent()?;
let delegated = stored.delegated_agent_id()?;
let found_untrusted = root
.as_ref()
.is_none_or(|root| found(&root.id, &|definition| root.validate(definition).is_ok()))
&& delegated.as_deref().is_none_or(|id| {
found(id, &|definition| {
stored
.validate_agent_definition_identity(definition)
.is_ok()
})
});
Ok(if found_untrusted {
ProjectTrusts::UNTRUSTED
} else {
ProjectTrusts {
agents: ProjectTrust::Trusted,
plugins: ProjectTrust::Trusted,
..ProjectTrusts::UNTRUSTED
}
})
}
pub(super) async fn open_to_read(
stored: StoredSession,
subagents: &Subagents,
settings: &ConfigStore,
job: &JobId,
) -> Result<OpenedSession, RpcError> {
let project_trust = reading_trust(&stored).map_err(open_failed)?;
let setup = Setup::resolve(
&SessionSetup::default(),
stored.cwd(),
Base::Reopened(&stored),
)?;
let global = config_for_saved(settings).await?;
open_runtime(
Opening::Saved(stored),
SessionEnvironment::for_reading(project_trust),
setup,
Purpose::Read,
subagents.pool_for(job.clone()),
settings,
global,
)
.await
.map_err(open_failed)
}
async fn open_runtime(
opening: Opening,
environment: SessionEnvironment,
setup: Setup,
purpose: Purpose<'_>,
subagent_pool: SubagentPool,
settings: &ConfigStore,
global: Arc<Config>,
) -> anyhow::Result<OpenedSession> {
let (session_use, requested, pull_requests) = match purpose {
Purpose::Run {
sign_in,
setup,
pull_requests,
} => (SessionUse::Run(sign_in), setup, Some(pull_requests)),
Purpose::Read => (SessionUse::Read, SessionSetup::default(), None),
};
let cwd = &opening.cwd().to_path_buf();
let config_path = settings.agent_path().to_path_buf();
let Setup {
left_out,
host_prompt,
questions,
surfaces,
children,
idle_turns,
added_dirs,
host_mcp,
persistence,
adds_to_saved,
} = setup;
global.providers.activate()?;
if let Err(error) = crate::credential_store::activate_from_config(&global, &config_path) {
tracing::warn!(error = %format!("{error:#}"), "could not open the credential store");
}
let config = (*global).clone();
let available_tools = root_host_tools(
&config,
LaunchTools::from_flags(left_out.tools, left_out.subagents),
);
let agent = match &opening {
Opening::New { agent, .. } => bind_agent(
cwd,
&config,
agent.as_deref().unwrap_or(DEFAULT_AGENT_ID),
available_tools,
&environment,
)?,
Opening::Saved(stored) | Opening::Fork(stored) => {
bind_saved_agent(cwd, &config, stored, available_tools, &environment)?
}
};
let config = agent.rho_config().cloned().unwrap_or(config);
let SettledConfig {
config,
diagnostics,
} = settle_bound_config(
config,
&agent,
environment.credentials().as_ref(),
&ProviderRefreshStatus::NotAttempted,
rho_providers::model::ReasoningRequestSource::PersistedOrDefault,
)
.await?;
let cache_warming = match idle_turns {
IdleTurns::Host if config.keep_cache_warm => CacheWarming::Host(Default::default()),
IdleTurns::Host | IdleTurns::Never => CacheWarming::None,
};
let id = match &opening {
Opening::New { .. } | Opening::Fork(_) => rho_sdk::SessionId::new(),
Opening::Saved(stored) => rho_sdk::SessionId::from_string(stored.id())?,
};
if let SessionUse::Run(_) = session_use {
match SessionTempDir::prepare(&session_temp_dir::temp_root(), &id) {
Ok(temp_dir) => environment.use_temp_dir(temp_dir),
Err(error) => tracing::warn!(
session = %id,
error = %format!("{error:#}"),
"could not make the session's temp dir; its processes keep the client's"
),
}
}
let (pull_requests, peer_sessions) = match (children, idle_turns) {
(ChildAgents::InProcess, IdleTurns::Host) => (
pull_requests.map(|service| service.inbox(&id, cwd)),
Some(PeerInbox::default()),
),
(ChildAgents::InProcess, IdleTurns::Never) | (ChildAgents::HostThreads, _) => (None, None),
};
let build = SessionBuild {
launch: SessionLaunch {
config_path,
left_out,
diagnostics,
agent,
prompt_suffix: None,
host_prompt,
},
host: HostCapabilities {
questions,
surfaces,
pull_requests,
peer_sessions,
children,
idle_turns,
subagent_pool,
environment: environment.clone(),
mcp_authorization: McpAuthorizationMode::NonInteractive,
approvals: ApprovalPolicy::Host,
parent_notices: None,
session_use,
tool_sources: match children {
ChildAgents::InProcess => ToolSourceLoad::Deferred,
ChildAgents::HostThreads => ToolSourceLoad::Inline,
},
cache_warming,
},
run: RunShape {
role: SessionRole::Daemon,
max_steps: None,
hook_labels: Default::default(),
},
};
let session = SessionOpening {
build,
process_config: &config,
host_mcp,
cwd,
added_dirs,
};
let fork_of = match &opening {
Opening::Fork(parent) => Some(rho_sdk::SessionId::from_string(parent.id())?),
Opening::Saved(stored) => stored
.forked_from()?
.map(|parent| rho_sdk::SessionId::from_string(&parent.id))
.transpose()?,
Opening::New { .. } => None,
};
let runtime = match opening {
Opening::New { started_by, .. } => {
Box::pin(SessionRuntime::open_new(
session,
id,
persistence,
started_by,
))
.await?
}
Opening::Fork(parent) => {
Box::pin(SessionRuntime::open_fork(session, id, &parent, persistence)).await?
}
Opening::Saved(stored) => {
let mut runtime = Box::pin(SessionRuntime::open_saved(session, stored)).await?;
debug_assert_eq!(
runtime.session_id(),
&id,
"a saved session opens with its file's id"
);
if adds_to_saved {
if let Err(error) = runtime.save_state() {
tracing::warn!(
error = format!("{error:#}"),
"could not save the setup a reopen added; the session's next turn saves it"
);
}
}
runtime
}
};
Ok(OpenedSession {
runtime,
config,
global,
environment,
setup: SessionSetup {
system_prompt: None,
..requested
},
fork_of,
held_context: PromptContext::default(),
})
}
fn bind_saved_agent(
cwd: &Path,
config: &Config,
stored: &StoredSession,
available_tools: AgentCapabilities,
environment: &SessionEnvironment,
) -> anyhow::Result<BoundAgent> {
let Some(root) = stored.root_agent()? else {
return bind_agent(cwd, config, DEFAULT_AGENT_ID, available_tools, environment);
};
let agent = bind_agent(cwd, config, &root.id, available_tools, environment)?;
root.validate(agent.definition())?;
Ok(agent)
}
fn bind_agent(
cwd: &Path,
config: &Config,
id: &str,
available_tools: AgentCapabilities,
environment: &SessionEnvironment,
) -> anyhow::Result<BoundAgent> {
let catalog = AgentCatalog::discover(cwd, environment.project_trust())?;
let definition = Arc::new(catalog.find(id)?.definition.clone());
AgentBinder::bind_with_credentials(
definition,
AgentInvocation {
role: AgentRole::InteractiveRoot,
available_tools,
},
config,
None,
environment.credentials().as_ref(),
)
}
#[cfg(test)]
#[path = "open_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "open_failed_tests.rs"]
mod open_failed_tests;