1use std::{
2 io::{self, IsTerminal},
3 num::NonZeroUsize,
4 sync::Arc,
5 time::Duration,
6};
7
8use anyhow::Context as _;
9use tracing::Instrument;
10
11use {
12 crate::cli::{Cli, Command, CredentialStoreCommand, OutputFormat},
13 crate::credential_store::AppCredentialStore,
14 crate::diagnostics::RuntimeDiagnostics,
15 crate::herdr::HerdrReporter,
16 crate::session::SessionPersistence,
17 crate::tui::SetupEntry,
18 crate::update,
19 rho_providers::model::ModelError,
20};
21
22use super::acp;
23#[cfg(feature = "browser")]
24use super::browser_cli;
25use super::{
26 agent_binding::{root_host_tools, AgentBinder, AgentInvocation, AgentRole, LaunchTools},
27 automation, cli_config,
28 config_repository::ConfigRepository,
29 daemon_cli, doctor_cli, interactive, login, mcp_cli, plugins_cli,
30 sdk_config::SdkBootstrapOptions,
31 session_runtime::LeftOut,
32 sessions_cli, workflow_cli, worktrees_cli,
33};
34
35pub async fn run(cli: Cli) -> anyhow::Result<()> {
36 if !daemon_cli::runs_daemon(cli.command.as_ref()) {
37 crate::logging::install_from_env();
38 }
39 #[cfg(windows)]
42 if let Ok(executable) = std::env::current_exe() {
43 update::remove_update_leftovers(&executable);
44 }
45 if workflow_cli::planner_worker_requested(&cli) {
46 return workflow_cli::run_planner_worker().await;
47 }
48 if let Some(Command::SessionTools(args)) = &cli.command {
51 use crate::acp_runtime::agent_tools::bridge::{relay, TOKEN_ENV};
52 let token =
53 std::env::var(TOKEN_ENV).map_err(|_| anyhow::anyhow!("{TOKEN_ENV} is not set"))?;
54 return relay(&args.endpoint, &token).await;
55 }
56 let run_output = match &cli.command {
57 Some(Command::Run { output, .. }) => Some(*output),
58 _ => None,
59 };
60 let result = run_inner(cli)
61 .instrument(tracing::info_span!("startup"))
62 .await;
63 let Err(error) = result else {
64 return Ok(());
65 };
66 if error.downcast_ref::<automation::AutomationExit>().is_some()
67 || error
68 .downcast_ref::<automation::AutomationInterrupted>()
69 .is_some()
70 {
71 return Err(error);
72 }
73 if let Some(output) = run_output {
74 let exit = automation::AutomationExit::configuration(error.to_string());
75 if output == OutputFormat::Jsonl {
76 return Err(automation::emit_startup_failure(exit).into());
77 }
78 return Err(exit.into());
79 }
80 Err(error)
81}
82
83fn run_inner(cli: Cli) -> impl std::future::Future<Output = anyhow::Result<()>> {
84 Box::pin(run_startup(cli))
87}
88
89fn upgrade_2x_config(cli: &Cli) -> anyhow::Result<()> {
92 let config_path = ConfigRepository::new(cli.config.clone()).configured_path()?;
93 let upgraded = crate::config::upgrade_2x(
94 &config_path,
95 &crate::paths::rho_dir()?,
96 crate::credential_store::save_migrated_web_search_keys,
97 )
98 .with_context(|| format!("could not update 2.x config {}", config_path.display()))?;
99 for line in upgraded.iter().flat_map(|done| done.notice(&config_path)) {
100 eprintln!("{line}");
101 }
102 Ok(())
103}
104
105async fn run_startup(cli: Cli) -> anyhow::Result<()> {
106 cli_config::validate(&cli)?;
107 upgrade_2x_config(&cli)?;
108 if let EarlyDispatch::Handled(result) = dispatch_early_command(&cli).await? {
109 return result;
110 }
111 if matches!(cli.command, Some(Command::Acp(_))) {
112 return acp::run(cli).await;
114 }
115
116 let keyring_notice = crate::credential_store::StartupKeyringNotice::begin(
117 cli.command.is_none(),
118 );
119 let PreparedStartup {
120 cli,
121 config,
122 config_repository,
123 first_run,
124 cwd,
125 automation_prompt,
126 output_file,
127 output,
128 max_steps,
129 timeout,
130 bound_agent,
131 bound_reasoning_source,
132 provider_refresh,
133 added_dirs,
134 } = prepare_startup(cli).await?;
135
136 validate_terminal_mode(&cli)?;
137 let cli_config::SettledConfig {
138 config,
139 diagnostics,
140 } = cli_config::settle_bound_config(
141 config,
142 &bound_agent,
143 Arc::new(crate::credential_store::AppCredentialStore),
144 &provider_refresh,
145 bound_reasoning_source,
146 )
147 .await?;
148 let herdr = HerdrReporter::from_env();
149 let headless_herdr = || {
150 herdr
151 .clone()
152 .with_source(crate::herdr::HerdrSource::Headless)
153 };
154 if let Some(prompt) = automation_prompt {
155 return run_automation_startup(AutomationStartup {
156 prompt,
157 config: &config,
158 config_repository: &config_repository,
159 cwd,
160 cli: &cli,
161 bound_agent,
162 diagnostics,
163 output_file,
164 output,
165 max_steps,
166 timeout,
167 herdr: headless_herdr(),
168 added_dirs,
169 })
170 .await;
171 }
172 run_interactive_startup(InteractiveStartup {
173 keyring_notice,
174 cli: &cli,
175 config,
176 config_repository,
177 first_run,
178 cwd,
179 bound_agent,
180 bound_reasoning_source,
181 diagnostics,
182 herdr,
183 added_dirs,
184 })
185 .await
186}
187
188enum EarlyDispatch {
189 Handled(anyhow::Result<()>),
190 Continue,
191}
192
193async fn dispatch_early_command(cli: &Cli) -> anyhow::Result<EarlyDispatch> {
194 if let Some(Command::ModelPrompt { command }) = &cli.command {
195 return Ok(EarlyDispatch::Handled(
196 super::model_prompt_cli::run(command, cli).await,
197 ));
198 }
199 if let Some(Command::Uninstall { purge, dry_run }) = &cli.command {
200 return Ok(EarlyDispatch::Handled(
201 crate::uninstall::run(*purge, *dry_run).await,
202 ));
203 }
204 if let Some(Command::Workflow { command }) = &cli.command {
205 return Ok(EarlyDispatch::Handled(
206 workflow_cli::run(command, cli).await,
207 ));
208 }
209 if let Some(Command::CredentialStore { command }) = &cli.command {
210 return Ok(EarlyDispatch::Handled(run_credential_store_command(
211 command,
212 cli.config.clone(),
213 )));
214 }
215 if let Some(Command::Sessions { command }) = &cli.command {
216 return Ok(EarlyDispatch::Handled(sessions_cli::run(command)));
217 }
218 if let Some(Command::Mcp { command }) = &cli.command {
219 return Ok(EarlyDispatch::Handled(mcp_cli::run(command, cli).await));
220 }
221 if let Some(Command::Plugins { command }) = &cli.command {
222 return Ok(EarlyDispatch::Handled(plugins_cli::run(command, cli)));
223 }
224 if let Some(Command::Daemon { command }) = &cli.command {
225 return Ok(EarlyDispatch::Handled(
226 daemon_cli::run(command.clone(), cli).await,
227 ));
228 }
229 #[cfg(feature = "browser")]
230 if let Some(Command::Browser { command }) = &cli.command {
231 return Ok(EarlyDispatch::Handled(browser_cli::run(command, cli).await));
232 }
233 if let Some(Command::Worktrees { command }) = &cli.command {
234 return Ok(EarlyDispatch::Handled(worktrees_cli::run(command).await));
235 }
236 if let Some(Command::Doctor { json }) = &cli.command {
237 return Ok(EarlyDispatch::Handled(doctor_cli::run(*json, cli).await));
238 }
239 #[cfg(debug_assertions)]
240 if let Some(Command::AcpFixtureAgent(args)) = &cli.command {
241 return Ok(EarlyDispatch::Handled(
242 super::acp_fixture_agent::run(args).await,
243 ));
244 }
245 if let Some(Command::Attach { id, output, input }) = &cli.command {
246 return Ok(EarlyDispatch::Handled(
247 super::attach::run(id, *output, *input).await,
248 ));
249 }
250 if let Some(Command::Run {
251 detach: true,
252 prompt,
253 stdin,
254 timeout,
255 ..
256 }) = &cli.command
257 {
258 return Ok(EarlyDispatch::Handled(
259 super::detach::run(cli, prompt.clone(), *stdin, *timeout).await,
260 ));
261 }
262 if let Some(Command::Update { check, json }) = &cli.command {
263 let version = env!("CARGO_PKG_VERSION");
264 let result = if *check {
265 let format = if *json {
266 update::CheckFormat::Json
267 } else {
268 update::CheckFormat::Text
269 };
270 update::run_check(version, format).await
271 } else {
272 update::run_update(version).await
273 };
274 return Ok(EarlyDispatch::Handled(result));
275 }
276 if let Some(command) = login::command(&cli.command) {
277 let antigravity = |provider: &str| {
280 provider.eq_ignore_ascii_case(crate::antigravity_runtime::ANTIGRAVITY_LABEL_NAME)
281 };
282 match command {
283 login::LoginCommand::Cli {
284 provider,
285 device_auth: true,
286 } if antigravity(provider) => anyhow::bail!(
287 "antigravity login has no device flow; paste the code agy asks for instead"
288 ),
289 login::LoginCommand::Cli {
290 provider,
291 device_auth: false,
292 }
293 | login::LoginCommand::AcpTerminal { auth: provider }
294 if antigravity(provider) =>
295 {
296 return Ok(EarlyDispatch::Handled(
297 crate::antigravity_runtime::auth::login().await,
298 ));
299 }
300 login::LoginCommand::Cli { .. } | login::LoginCommand::AcpTerminal { .. } => {}
301 }
302 let config_repository = ConfigRepository::new(cli.config.clone());
306 let config = config_repository.load()?;
307 config.providers.activate()?;
308 let signed_in = login::run(command).await;
309 return Ok(EarlyDispatch::Handled(signed_in));
310 }
311 Ok(EarlyDispatch::Continue)
312}
313
314struct PreparedStartup {
315 cli: Cli,
316 config: crate::config::Config,
320 config_repository: ConfigRepository,
321 first_run: Option<SetupEntry>,
322 cwd: std::path::PathBuf,
323 automation_prompt: Option<String>,
324 output_file: Option<std::path::PathBuf>,
325 output: OutputFormat,
326 max_steps: Option<NonZeroUsize>,
327 timeout: Option<Duration>,
328 bound_agent: super::agent_binding::BoundAgent,
329 bound_reasoning_source: rho_providers::model::ReasoningRequestSource,
330 provider_refresh: cli_config::ProviderRefreshStatus,
331 added_dirs: crate::added_dirs::AddedDirs,
332}
333
334async fn prepare_startup(cli: Cli) -> anyhow::Result<PreparedStartup> {
335 let config_path = cli.config.clone();
336 let config_repository = ConfigRepository::new(config_path.clone());
337 let mut config = config_repository.load()?;
338 config.providers.activate()?;
340 let absolute_config = absolute_config_path(&config_repository)?;
341 crate::credential_store::initialize_from_config(&mut config, &absolute_config)?;
342 let cwd = std::env::current_dir()?;
343 let added_dirs = crate::added_dirs::launch_added_dirs(&cli.add_dirs, &cwd)?;
344 let automation_prompt = automation::prompt_for_command(&cli.command)?;
345 let (output_file, output, max_steps, timeout, worktree) = match &cli.command {
346 Some(Command::Run {
347 output_file,
348 output,
349 max_steps,
350 timeout,
351 worktree,
352 ..
353 }) => (
354 output_file.clone(),
355 *output,
356 *max_steps,
357 *timeout,
358 *worktree,
359 ),
360 _ => (None, OutputFormat::Text, None, None, false),
361 };
362 let (cwd, output_file, config_repository) = if worktree {
366 let workspace = crate::paths::canonicalize(&cwd)?;
367 let output_file = output_file.map(|path| workspace.join(path));
368 let config_repository = match &config_path {
369 Some(path) if path.is_relative() => ConfigRepository::new(Some(absolute_config)),
370 Some(_) | None => config_repository,
371 };
372 let root = crate::worktree::root(&crate::paths::rho_dir()?);
373 let start = crate::worktree::Start::of(&config);
374 let added = crate::worktree::add(&root, &workspace, start).await?;
375 eprintln!(
376 "rho: {}",
377 crate::worktree::hint(&added.worktree, crate::worktree::Removal::Unowned)
378 );
379 eprintln!("rho: the worktree starts from {}", added.started);
380 std::env::set_current_dir(&added.cwd)?;
381 (added.cwd, output_file, config_repository)
382 } else {
383 (cwd, output_file, config_repository)
384 };
385 let catalog = crate::agent::AgentCatalog::discover(
386 &cwd,
387 crate::workspace::ProjectTrusts::of_this_process(),
388 )?;
389 let selected_agent = cli
390 .agent
391 .as_deref()
392 .unwrap_or(crate::agent::DEFAULT_AGENT_ID);
393 let definition = Arc::new(catalog.find(selected_agent)?.definition.clone());
394
395 let role = if automation_prompt.is_some() {
398 AgentRole::AutomationRoot
399 } else {
400 AgentRole::InteractiveRoot
401 };
402
403 let store = AppCredentialStore;
404 if matches!(role, AgentRole::AutomationRoot) {
409 let _ =
411 cli_config::refresh_custom_provider_models_for_session(&cli, &config, Arc::new(store))
412 .await?;
413 }
414 let provider_refresh = cli_config::refresh_model_cache(&cli, &config, &store).await?;
415 let permission_mode_before_override = config.permission_mode;
416 let config_changed = cli_config::apply_overrides(&mut config, &cli, &store)?;
417 cli_config::prepare_model_metadata(&config, Arc::new(store), &provider_refresh).await;
418 tokio::spawn(rho_providers::model::models_dev::ensure_models_dev_catalog());
422 cli_config::normalize_reasoning(
423 &mut config,
424 if cli.reasoning.is_some() {
425 rho_providers::model::ReasoningRequestSource::Explicit
426 } else {
427 rho_providers::model::ReasoningRequestSource::PersistedOrDefault
428 },
429 )?;
430 if cli.save && config_changed {
435 let session_permission_mode = config.permission_mode;
436 config.permission_mode = permission_mode_before_override;
437 config_repository.save(&config)?;
438 config.permission_mode = session_permission_mode;
439 }
440 let bound_agent = AgentBinder::bind(
441 definition,
442 AgentInvocation {
443 role,
444 available_tools: host_capabilities(&cli, &config, role),
445 },
446 &config,
447 )?;
448 let bound_reasoning = bound_agent
450 .rho_config()
451 .map_or(config.reasoning, |bound| bound.reasoning);
452 let bound_reasoning_source = if cli.reasoning.is_some() && bound_reasoning == config.reasoning {
453 rho_providers::model::ReasoningRequestSource::Explicit
454 } else {
455 rho_providers::model::ReasoningRequestSource::PersistedOrDefault
456 };
457 let first_run = if role == AgentRole::InteractiveRoot {
458 detect_first_run(&bound_agent)
459 } else {
460 None
461 };
462 let config = bound_agent.rho_config().cloned().unwrap_or(config);
465
466 Ok(PreparedStartup {
467 cli,
468 config,
469 config_repository,
470 first_run,
471 cwd,
472 automation_prompt,
473 output_file,
474 output,
475 max_steps,
476 timeout,
477 bound_agent,
478 bound_reasoning_source,
479 provider_refresh,
480 added_dirs,
481 })
482}
483
484struct AutomationStartup<'a> {
485 prompt: String,
486 config: &'a crate::config::Config,
487 config_repository: &'a ConfigRepository,
488 cwd: std::path::PathBuf,
489 cli: &'a Cli,
490 bound_agent: super::agent_binding::BoundAgent,
491 diagnostics: RuntimeDiagnostics,
492 output_file: Option<std::path::PathBuf>,
493 output: OutputFormat,
494 max_steps: Option<NonZeroUsize>,
495 timeout: Option<Duration>,
496 herdr: HerdrReporter,
497 added_dirs: crate::added_dirs::AddedDirs,
498}
499
500async fn run_automation_startup(startup: AutomationStartup<'_>) -> anyhow::Result<()> {
501 let persistence = match &startup.cli.command {
502 Some(Command::Run { no_save: true, .. }) => SessionPersistence::Ephemeral,
503 _ => SessionPersistence::Saved,
504 };
505 automation::run(
506 startup.prompt,
507 automation::Startup {
508 config: startup.config,
509 config_path: absolute_config_path(startup.config_repository)?,
510 cwd: startup.cwd,
511 left_out: launch_left_out(startup.cli),
512 agent: startup.bound_agent,
513 output_file: startup.output_file,
514 output: startup.output,
515 max_steps: startup.max_steps,
516 timeout: startup.timeout,
517 persistence,
518 diagnostics: startup.diagnostics,
519 herdr: startup.herdr,
520 added_dirs: startup.added_dirs,
521 },
522 )
523 .await
524}
525
526struct InteractiveStartup<'a> {
527 keyring_notice: crate::credential_store::StartupKeyringNotice,
528 cli: &'a Cli,
529 config: crate::config::Config,
530 config_repository: ConfigRepository,
531 first_run: Option<SetupEntry>,
532 cwd: std::path::PathBuf,
533 bound_agent: super::agent_binding::BoundAgent,
534 bound_reasoning_source: rho_providers::model::ReasoningRequestSource,
535 diagnostics: RuntimeDiagnostics,
536 herdr: HerdrReporter,
537 added_dirs: crate::added_dirs::AddedDirs,
538}
539
540async fn run_interactive_startup(startup: InteractiveStartup<'_>) -> anyhow::Result<()> {
541 let settings = crate::tui::TuiSettings::load(&crate::paths::rho_dir()?)?;
542 let pending_update_notice = settings
543 .check_for_updates
544 .then(|| tokio::spawn(update::update_notice(env!("CARGO_PKG_VERSION"))));
545 let pending_custom_models = cli_config::spawn_custom_provider_models_refresh(
546 startup.config.providers.clone(),
547 Arc::new(AppCredentialStore),
548 );
549 let prompt_history_limit = settings.prompt_history_limit;
550 let pending_prompt_history = (prompt_history_limit > 0 && !startup.cli.no_save).then(|| {
551 tokio::spawn(
552 async move {
553 tokio::task::spawn_blocking(move || {
554 match crate::prompt_history::PromptHistoryStore::at_default_path() {
555 Ok(store) => match store.load_tail(prompt_history_limit) {
556 Ok(tail) => Some((store, tail)),
557 Err(error) => {
558 tracing::warn!(%error, "failed to load prompt history");
559 None
560 }
561 },
562 Err(error) => {
563 tracing::warn!(%error, "failed to open prompt history");
564 None
565 }
566 }
567 })
568 .await
569 .unwrap_or_else(|error| {
570 tracing::warn!(%error, "prompt history task failed");
571 None
572 })
573 }
574 .instrument(tracing::info_span!("startup.prompt_history")),
575 )
576 });
577
578 let missing_auth_error = match &startup.config.conversation_model {
583 Some(chosen) => interactive_auth_unavailable(&startup.config, chosen, &startup.cwd)?,
584 None => None,
585 };
586 interactive::run(interactive::Startup {
587 keyring_notice: startup.keyring_notice,
588 cli: startup.cli,
589 config: startup.config,
590 settings,
591 config_repository: startup.config_repository,
592 cwd: startup.cwd,
593 first_run: startup.first_run,
594 missing_auth_error,
595 pending_update_notice,
596 pending_custom_models,
597 pending_prompt_history,
598 diagnostics: startup.diagnostics,
599 herdr: startup.herdr,
600 agent: startup.bound_agent,
601 reasoning_source: startup.bound_reasoning_source,
602 added_dirs: startup.added_dirs,
603 })
604 .await
605}
606
607fn interactive_auth_unavailable(
611 config: &crate::config::Config,
612 chosen: &crate::config::ConversationModel,
613 cwd: &std::path::Path,
614) -> anyhow::Result<Option<String>> {
615 let sdk_options = SdkBootstrapOptions::from_config(config, cwd)?;
616 let credentials = rho_providers::auth::provider_credentials::ApplicationCredentialSource::new(
617 Arc::new(AppCredentialStore),
618 );
619 let provider_result = config
620 .providers
621 .require_endpoint_login(&chosen.provider)
622 .and_then(|()| {
623 rho_providers::providers::build_sdk_provider_with_source(
624 sdk_options.provider,
625 &credentials,
626 )
627 });
628 match provider_result {
629 Ok(_) => Ok(None),
630 Err(error) if is_interactive_startup_unavailable_error(&error) => {
631 Ok(Some(error.to_string()))
632 }
633 Err(error) => Err(error.into()),
634 }
635}
636
637fn run_credential_store_command(
638 command: &CredentialStoreCommand,
639 config_path: Option<std::path::PathBuf>,
640) -> anyhow::Result<()> {
641 match command {
642 CredentialStoreCommand::Probe { backend } => {
643 let result = crate::credential_store::probe(*backend);
644 if result.available {
645 println!("available: {}", result.detail);
646 Ok(())
647 } else {
648 anyhow::bail!(result.detail)
649 }
650 }
651 CredentialStoreCommand::Status => {
652 match crate::credential_store::saved_policy_backend(config_path.as_deref())? {
654 None => println!("unset"),
655 Some(backend) => println!("{}", backend.as_str()),
656 }
657 Ok(())
658 }
659 CredentialStoreCommand::Set { backend } => {
660 let path = crate::credential_store::set_backend(*backend, config_path)?;
661 println!(
662 "credential store set to {} in {}",
663 backend.as_str(),
664 path.display()
665 );
666 Ok(())
667 }
668 }
669}
670
671fn launch_left_out(cli: &Cli) -> LeftOut {
673 LeftOut {
674 system_prompt: cli.no_system_prompt,
675 tools: cli.no_tools,
676 subagents: cli.no_subagents,
677 }
678}
679
680pub(super) fn host_capabilities(
681 cli: &Cli,
682 config: &crate::config::Config,
683 role: AgentRole,
684) -> crate::agent::AgentCapabilities {
685 use crate::agent::ToolCapability;
686
687 let launch = LaunchTools::from_flags(cli.no_tools, cli.no_subagents);
688 if launch == LaunchTools::None {
689 return crate::agent::AgentCapabilities::default();
690 }
691 let mut tools = root_host_tools(config, launch);
692 if role != AgentRole::InteractiveRoot {
693 tools.remove(&ToolCapability::Questionnaire);
694 }
695 tools
696}
697
698pub(super) fn absolute_config_path(
699 repository: &ConfigRepository,
700) -> anyhow::Result<std::path::PathBuf> {
701 let path = repository.configured_path()?;
702 if path.is_absolute() {
703 Ok(path)
704 } else {
705 Ok(std::env::current_dir()?.join(path))
706 }
707}
708
709const FIRST_RUN_OVERRIDE_VAR: &str = "RHO_FIRST_RUN";
712
713fn parse_first_run_override(value: &str) -> Option<SetupEntry> {
720 match value.trim().to_ascii_lowercase().as_str() {
721 "" | "0" | "false" | "no" => None,
722 "signin" | "sign-in" | "login" => Some(SetupEntry::SignIn),
723 "model" | "models" => Some(SetupEntry::ChooseModel),
724 _ => Some(SetupEntry::Auto),
725 }
726}
727
728fn detect_first_run(bound: &super::agent_binding::BoundAgent) -> Option<SetupEntry> {
733 if let Ok(value) = std::env::var(FIRST_RUN_OVERRIDE_VAR) {
734 if let Some(entry) = parse_first_run_override(&value) {
735 return Some(entry);
736 }
737 }
738 bound
739 .rho_config()
740 .is_some_and(|config| config.conversation_model.is_none())
741 .then_some(SetupEntry::Auto)
742}
743
744fn validate_terminal_mode(cli: &Cli) -> anyhow::Result<()> {
745 if cli.command.is_none() && (!crate::stdio::stdin_is_terminal() || !io::stdout().is_terminal())
746 {
747 anyhow::bail!(
748 "rho's default mode is the interactive TUI; use `rho run` for non-interactive automation"
749 );
750 }
751 Ok(())
752}
753
754fn is_interactive_startup_unavailable_error(error: &ModelError) -> bool {
755 matches!(
756 error,
757 ModelError::MissingCredentials(_)
758 | ModelError::Credentials(_)
759 | ModelError::UnsupportedProvider(_)
760 )
761}
762
763#[cfg(test)]
764#[path = "bootstrap_tests.rs"]
765mod tests;