use std::{collections::BTreeSet, path::PathBuf, time::Duration};
use rho_protocol::SessionPart;
use rho_protocol::{ChildThreads, SessionNewParams, SessionSetup};
use super::automation::AutomationExit;
use crate::cli::{Cli, Command};
pub(super) struct Passed<'a> {
agent: Option<&'a str>,
add_dirs: &'a [PathBuf],
without: BTreeSet<SessionPart>,
}
pub(super) fn detach_flags(cli: &Cli) -> Result<Passed<'_>, Vec<&'static str>> {
let Cli {
provider,
model,
config,
auth,
no_system_prompt,
no_tools,
no_subagents,
agent,
reasoning,
permission_mode,
add_dirs,
save,
no_save: _,
resume: _,
continue_latest: _,
prompt: _,
command: _,
} = cli;
let refused: Vec<_> = [
("--provider", provider.is_some()),
("--model", model.is_some()),
("--config", config.is_some()),
("--auth", auth.is_some()),
("--reasoning", reasoning.is_some()),
("--permission-mode", permission_mode.is_some()),
("--save", *save),
]
.into_iter()
.filter_map(|(name, set)| set.then_some(name))
.collect();
if !refused.is_empty() {
return Err(refused);
}
let without = [
(SessionPart::Tools, *no_tools),
(SessionPart::SystemPrompt, *no_system_prompt),
(SessionPart::Subagents, *no_subagents),
]
.into_iter()
.filter_map(|(part, set)| set.then_some(part))
.collect();
Ok(Passed {
agent: agent.as_deref(),
add_dirs,
without,
})
}
pub(super) fn refusal(refused: &[&str]) -> String {
format!(
"rho run --detach does not take {}: the daemon opens the session with the workspace's config",
refused.join(", ")
)
}
fn session_new(
cli: &Cli,
environment: rho_protocol::ClientEnvironment,
) -> Result<SessionNewParams, AutomationExit> {
let passed =
detach_flags(cli).map_err(|refused| AutomationExit::configuration(refusal(&refused)))?;
let cwd = std::env::current_dir().map_err(|error| {
AutomationExit::other(format!("could not read the current directory: {error}"))
})?;
let added = crate::added_dirs::launch_added_dirs(passed.add_dirs, &cwd)
.map_err(|error| AutomationExit::configuration(format!("{error:#}")))?;
let worktree = matches!(cli.command, Some(Command::Run { worktree: true, .. }));
Ok(SessionNewParams {
cwd,
environment,
agent: passed.agent.map(str::to_owned),
setup: SessionSetup {
additional_directories: added.as_slice().to_vec(),
mcp_servers: Vec::new(),
without: passed.without,
child_threads: ChildThreads::Daemon,
idle_wake: rho_protocol::IdleWake::Never,
sign_in: rho_protocol::SignIn::Required,
},
parent: None,
grant: None,
worktree,
})
}
pub(super) async fn run(
cli: &Cli,
parts: Vec<String>,
read_stdin: bool,
timeout: Option<Duration>,
) -> anyhow::Result<()> {
let new = session_new(cli, rho_protocol::ClientEnvironment::of_this_process())?;
start(new, parts, read_stdin, timeout).await
}
async fn start(
new: SessionNewParams,
parts: Vec<String>,
read_stdin: bool,
timeout: Option<Duration>,
) -> anyhow::Result<()> {
use std::io::{self, Write};
use rho_protocol::{
methods::{SessionNew, SessionPrompt},
ContentBlock, ErrorCode, SessionPromptParams,
};
use super::{automation, daemon_cli};
let timeout_ms = timeout
.map(|timeout| {
u64::try_from(timeout.as_millis()).map_err(|_| {
AutomationExit::configuration(format!(
"--timeout {} is over the daemon's limit of {} ms",
humantime::format_duration(timeout),
u64::MAX
))
})
})
.transpose()?;
let text = automation::prompt_from_stdin(parts, read_stdin)?;
let environment = new.environment.clone();
let client = daemon_cli::connect()
.await
.map_err(|error| AutomationExit::other(error.to_string()))?
.client;
let opened = client.request::<SessionNew>(&new).await.map_err(|error| {
let message = format!("could not open a daemon session: {error}");
match error.error_code() {
Some(ErrorCode::SessionOpenFailed | ErrorCode::InvalidParams) => {
AutomationExit::configuration(message)
}
Some(ErrorCode::SignInRequired) => AutomationExit::authentication(message),
_ => AutomationExit::other(message),
}
})?;
crate::worktree::require(new.worktree, opened.worktree.as_ref())
.map_err(|error| AutomationExit::configuration(error.to_string()))?;
if let Some(worktree) = &opened.worktree {
let _ = writeln!(
io::stderr(),
"rho: {}",
crate::worktree::hint(worktree, crate::worktree::Removal::Daemon)
);
}
let session = opened.session;
client
.request::<SessionPrompt>(&SessionPromptParams {
author: rho_protocol::PromptAuthor::Person,
session: session.clone(),
content: vec![ContentBlock::Text { text }],
timeout_ms,
environment,
idempotency_key: None,
grant: None,
})
.await
.map_err(|error| {
match error
.turn_ended()
.map(|outcome| automation::outcome_exit(&outcome))
{
Some(Err(exit)) => exit,
_ => AutomationExit::other(format!("could not start the turn: {error}")),
}
})?;
writeln!(io::stdout(), "{session}").map_err(|error| {
AutomationExit::other(format!(
"could not write the session id {session}: {error}; the turn runs on in the daemon"
))
})?;
let _ = writeln!(
io::stderr(),
"rho: the turn runs in the daemon; follow it with `rho attach {session}`"
);
Ok(())
}