Skip to main content

rho_coding_agent/app/
bootstrap.rs

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;
23use super::{
24    agent_binding::{root_host_tools, AgentBinder, AgentInvocation, AgentRole, LaunchTools},
25    automation, cli_config,
26    config_repository::ConfigRepository,
27    daemon_cli, doctor_cli, interactive, login, mcp_cli, plugins_cli,
28    sdk_config::SdkBootstrapOptions,
29    session_runtime::LeftOut,
30    sessions_cli, workflow_cli, worktrees_cli,
31};
32
33pub async fn run(cli: Cli) -> anyhow::Result<()> {
34    if !daemon_cli::runs_daemon(cli.command.as_ref()) {
35        crate::logging::install_from_env();
36    }
37    if workflow_cli::planner_worker_requested(&cli) {
38        return workflow_cli::run_planner_worker().await;
39    }
40    let run_output = match &cli.command {
41        Some(Command::Run { output, .. }) => Some(*output),
42        _ => None,
43    };
44    let result = run_inner(cli)
45        .instrument(tracing::info_span!("startup"))
46        .await;
47    let Err(error) = result else {
48        return Ok(());
49    };
50    if error.downcast_ref::<automation::AutomationExit>().is_some()
51        || error
52            .downcast_ref::<automation::AutomationInterrupted>()
53            .is_some()
54    {
55        return Err(error);
56    }
57    if let Some(output) = run_output {
58        let exit = automation::AutomationExit::configuration(error.to_string());
59        if output == OutputFormat::Jsonl {
60            return Err(automation::emit_startup_failure(exit).into());
61        }
62        return Err(exit.into());
63    }
64    Err(error)
65}
66
67fn run_inner(cli: Cli) -> impl std::future::Future<Output = anyhow::Result<()>> {
68    // Allocate before polling: Box::pin inside `run` alone leaves the large
69    // startup construction temporary on its stack throughout the session.
70    Box::pin(run_startup(cli))
71}
72
73/// Rewrites a `config.toml` rho 2.x wrote to the 3.0 files and says what
74/// moved. Runs before anything loads the config, which refuses 2.x keys.
75fn upgrade_2x_config(cli: &Cli) -> anyhow::Result<()> {
76    let config_path = ConfigRepository::new(cli.config.clone()).configured_path()?;
77    let upgraded = crate::config::upgrade_2x(
78        &config_path,
79        &crate::paths::rho_dir()?,
80        crate::credential_store::save_migrated_web_search_keys,
81    )
82    .with_context(|| format!("could not update 2.x config {}", config_path.display()))?;
83    for line in upgraded.iter().flat_map(|done| done.notice(&config_path)) {
84        eprintln!("{line}");
85    }
86    Ok(())
87}
88
89async fn run_startup(cli: Cli) -> anyhow::Result<()> {
90    cli_config::validate(&cli)?;
91    upgrade_2x_config(&cli)?;
92    if let EarlyDispatch::Handled(result) = dispatch_early_command(&cli).await? {
93        return result;
94    }
95    if matches!(cli.command, Some(Command::Acp(_))) {
96        // `rho acp` is a client of the rho daemon, which runs its sessions.
97        return acp::run(cli).await;
98    }
99
100    let keyring_notice = crate::credential_store::StartupKeyringNotice::begin(
101        /*interactive*/ cli.command.is_none(),
102    );
103    let PreparedStartup {
104        cli,
105        config,
106        config_repository,
107        first_run,
108        cwd,
109        automation_prompt,
110        output_file,
111        output,
112        max_steps,
113        timeout,
114        bound_agent,
115        bound_reasoning_source,
116        provider_refresh,
117        added_dirs,
118    } = prepare_startup(cli).await?;
119
120    validate_terminal_mode(&cli)?;
121    let cli_config::SettledConfig {
122        config,
123        diagnostics,
124    } = cli_config::settle_bound_config(
125        config,
126        &bound_agent,
127        &crate::credential_store::AppCredentialStore,
128        &provider_refresh,
129        bound_reasoning_source,
130    )
131    .await?;
132    let herdr = HerdrReporter::from_env();
133    let headless_herdr = || {
134        herdr
135            .clone()
136            .with_source(crate::herdr::HerdrSource::Headless)
137    };
138    if let Some(prompt) = automation_prompt {
139        return run_automation_startup(AutomationStartup {
140            prompt,
141            config: &config,
142            config_repository: &config_repository,
143            cwd,
144            cli: &cli,
145            bound_agent,
146            diagnostics,
147            output_file,
148            output,
149            max_steps,
150            timeout,
151            herdr: headless_herdr(),
152            added_dirs,
153        })
154        .await;
155    }
156    run_interactive_startup(InteractiveStartup {
157        keyring_notice,
158        cli: &cli,
159        config,
160        config_repository,
161        first_run,
162        cwd,
163        bound_agent,
164        bound_reasoning_source,
165        diagnostics,
166        herdr,
167        added_dirs,
168    })
169    .await
170}
171
172enum EarlyDispatch {
173    Handled(anyhow::Result<()>),
174    Continue,
175}
176
177async fn dispatch_early_command(cli: &Cli) -> anyhow::Result<EarlyDispatch> {
178    if let Some(Command::ModelPrompt { command }) = &cli.command {
179        return Ok(EarlyDispatch::Handled(
180            super::model_prompt_cli::run(command, cli).await,
181        ));
182    }
183    if let Some(Command::Uninstall { purge, dry_run }) = &cli.command {
184        return Ok(EarlyDispatch::Handled(
185            crate::uninstall::run(*purge, *dry_run).await,
186        ));
187    }
188    if let Some(Command::Workflow { command }) = &cli.command {
189        return Ok(EarlyDispatch::Handled(
190            workflow_cli::run(command, cli).await,
191        ));
192    }
193    if let Some(Command::CredentialStore { command }) = &cli.command {
194        return Ok(EarlyDispatch::Handled(run_credential_store_command(
195            command,
196            cli.config.clone(),
197        )));
198    }
199    if let Some(Command::Sessions { command }) = &cli.command {
200        return Ok(EarlyDispatch::Handled(sessions_cli::run(command)));
201    }
202    if let Some(Command::Mcp { command }) = &cli.command {
203        return Ok(EarlyDispatch::Handled(mcp_cli::run(command, cli).await));
204    }
205    if let Some(Command::Plugins { command }) = &cli.command {
206        return Ok(EarlyDispatch::Handled(plugins_cli::run(command, cli)));
207    }
208    if let Some(Command::Daemon { command }) = &cli.command {
209        return Ok(EarlyDispatch::Handled(
210            daemon_cli::run(command.clone(), cli).await,
211        ));
212    }
213    if let Some(Command::Worktrees { command }) = &cli.command {
214        return Ok(EarlyDispatch::Handled(worktrees_cli::run(command).await));
215    }
216    if let Some(Command::Doctor { json }) = &cli.command {
217        return Ok(EarlyDispatch::Handled(doctor_cli::run(*json, cli).await));
218    }
219    #[cfg(debug_assertions)]
220    if let Some(Command::AcpFixtureAgent(args)) = &cli.command {
221        return Ok(EarlyDispatch::Handled(
222            super::acp_fixture_agent::run(args).await,
223        ));
224    }
225    if let Some(Command::Attach { id, output, input }) = &cli.command {
226        return Ok(EarlyDispatch::Handled(
227            super::attach::run(id, *output, *input).await,
228        ));
229    }
230    if let Some(Command::Run {
231        detach: true,
232        prompt,
233        stdin,
234        timeout,
235        ..
236    }) = &cli.command
237    {
238        return Ok(EarlyDispatch::Handled(
239            super::detach::run(cli, prompt.clone(), *stdin, *timeout).await,
240        ));
241    }
242    if let Some(Command::Update { check, json }) = &cli.command {
243        let version = env!("CARGO_PKG_VERSION");
244        let result = if *check {
245            let format = if *json {
246                update::CheckFormat::Json
247            } else {
248                update::CheckFormat::Text
249            };
250            update::run_check(version, format).await
251        } else {
252            update::run_update(version).await
253        };
254        return Ok(EarlyDispatch::Handled(result));
255    }
256    if let Some(command) = login::command(&cli.command) {
257        // agy owns its sign-in; Rho config and the credential store are not
258        // involved.
259        let antigravity = |provider: &str| {
260            provider.eq_ignore_ascii_case(crate::antigravity_runtime::ANTIGRAVITY_LABEL_NAME)
261        };
262        match command {
263            login::LoginCommand::Cli {
264                provider,
265                device_auth: true,
266            } if antigravity(provider) => anyhow::bail!(
267                "antigravity login has no device flow; paste the code agy asks for instead"
268            ),
269            login::LoginCommand::Cli {
270                provider,
271                device_auth: false,
272            }
273            | login::LoginCommand::AcpTerminal { auth: provider }
274                if antigravity(provider) =>
275            {
276                return Ok(EarlyDispatch::Handled(
277                    crate::antigravity_runtime::auth::login().await,
278                ));
279            }
280            login::LoginCommand::Cli { .. } | login::LoginCommand::AcpTerminal { .. } => {}
281        }
282        // Custom providers must be registered for `login` to find them. A
283        // daemon login saves under the daemon's config, and asks the daemon
284        // which credential store to use (#1662).
285        let config_repository = ConfigRepository::new(cli.config.clone());
286        let config = config_repository.load()?;
287        config.providers.activate()?;
288        let signed_in = login::run(command).await;
289        return Ok(EarlyDispatch::Handled(signed_in));
290    }
291    Ok(EarlyDispatch::Continue)
292}
293
294struct PreparedStartup {
295    cli: Cli,
296    /// The config to settle (see [`cli_config::settle_bound_config`]): the
297    /// bound agent's own when it runs on rho, else the launch config with
298    /// CLI overrides.
299    config: crate::config::Config,
300    config_repository: ConfigRepository,
301    first_run: Option<SetupEntry>,
302    cwd: std::path::PathBuf,
303    automation_prompt: Option<String>,
304    output_file: Option<std::path::PathBuf>,
305    output: OutputFormat,
306    max_steps: Option<NonZeroUsize>,
307    timeout: Option<Duration>,
308    bound_agent: super::agent_binding::BoundAgent,
309    bound_reasoning_source: rho_providers::model::ReasoningRequestSource,
310    provider_refresh: cli_config::ProviderRefreshStatus,
311    added_dirs: crate::added_dirs::AddedDirs,
312}
313
314async fn prepare_startup(cli: Cli) -> anyhow::Result<PreparedStartup> {
315    let config_path = cli.config.clone();
316    let config_repository = ConfigRepository::new(config_path.clone());
317    // Ask before loading; loading writes the default config when none exists.
318    let first_run = detect_first_run(&config_repository);
319    let mut config = config_repository.load()?;
320    // Register every [providers.custom.*] name before refresh, pickers, and /model.
321    config.providers.activate()?;
322    let absolute_config = absolute_config_path(&config_repository)?;
323    crate::credential_store::initialize_from_config(&mut config, &absolute_config)?;
324    let cwd = std::env::current_dir()?;
325    let added_dirs = crate::added_dirs::launch_added_dirs(&cli.add_dirs, &cwd)?;
326    let automation_prompt = automation::prompt_for_command(&cli.command)?;
327    let (output_file, output, max_steps, timeout, worktree) = match &cli.command {
328        Some(Command::Run {
329            output_file,
330            output,
331            max_steps,
332            timeout,
333            worktree,
334            ..
335        }) => (
336            output_file.clone(),
337            *output,
338            *max_steps,
339            *timeout,
340            *worktree,
341        ),
342        _ => (None, OutputFormat::Text, None, None, false),
343    };
344    // A run in a worktree works there as one started there would, its MCP
345    // servers included, so the process moves into it. The paths the person
346    // typed still resolve against the directory they typed them in.
347    let (cwd, output_file, config_repository) = if worktree {
348        let workspace = crate::paths::canonicalize(&cwd)?;
349        let output_file = output_file.map(|path| workspace.join(path));
350        let config_repository = match &config_path {
351            Some(path) if path.is_relative() => ConfigRepository::new(Some(absolute_config)),
352            Some(_) | None => config_repository,
353        };
354        let root = crate::worktree::root(&crate::paths::rho_dir()?);
355        let start = crate::worktree::Start::of(&config);
356        let added = crate::worktree::add(&root, &workspace, start).await?;
357        eprintln!(
358            "rho: {}",
359            crate::worktree::hint(&added.worktree, crate::worktree::Removal::Unowned)
360        );
361        eprintln!("rho: the worktree starts from {}", added.started);
362        std::env::set_current_dir(&added.cwd)?;
363        (added.cwd, output_file, config_repository)
364    } else {
365        (cwd, output_file, config_repository)
366    };
367    let catalog = crate::agent::AgentCatalog::discover(
368        &cwd,
369        crate::workspace::ProjectTrusts::of_this_process(),
370    )?;
371    let selected_agent = cli
372        .agent
373        .as_deref()
374        .unwrap_or(crate::agent::DEFAULT_AGENT_ID);
375    let definition = Arc::new(catalog.find(selected_agent)?.definition.clone());
376
377    // Only automation and interactive sessions reach here; every other
378    // command dispatches early, and `rho acp` runs in the daemon.
379    let role = if automation_prompt.is_some() {
380        AgentRole::AutomationRoot
381    } else {
382        AgentRole::InteractiveRoot
383    };
384
385    let store = AppCredentialStore;
386    // Interactive sessions refresh custom-provider models after the first frame
387    // so a slow host cannot hold up paint. Automation and ACP get one shot to
388    // pick a model, so they wait for the session's own host; the rest refresh
389    // in the background.
390    if matches!(role, AgentRole::AutomationRoot) {
391        // The background refresh runs detached.
392        let _ =
393            cli_config::refresh_custom_provider_models_for_session(&cli, &config, Arc::new(store))
394                .await?;
395    }
396    let provider_refresh = cli_config::refresh_model_cache(&cli, &config, &store).await?;
397    let permission_mode_before_override = config.permission_mode;
398    let config_changed = cli_config::apply_overrides(&mut config, &cli, &store)?;
399    cli_config::prepare_model_metadata(&config, &store, &provider_refresh).await;
400    // Full models.dev snapshot fills in the background for subagent and status
401    // labels. Interactive sessions stay cache-only on the first frame, then
402    // rewrite the startup prompt once if hydrate lands before the first request.
403    tokio::spawn(rho_providers::model::models_dev::ensure_models_dev_catalog());
404    cli_config::normalize_reasoning(
405        &mut config,
406        if cli.reasoning.is_some() {
407            rho_providers::model::ReasoningRequestSource::Explicit
408        } else {
409            rho_providers::model::ReasoningRequestSource::PersistedOrDefault
410        },
411    )?;
412    // CLI overrides are session-only unless the user passes --save and an
413    // override actually changed the selection. Auto-saving rewrote the whole
414    // file and dropped comments. Bare --save, no-op identical overrides, and
415    // reasoning auto-normalization alone must not rewrite config.
416    if cli.save && config_changed {
417        let session_permission_mode = config.permission_mode;
418        config.permission_mode = permission_mode_before_override;
419        config_repository.save(&config)?;
420        config.permission_mode = session_permission_mode;
421    }
422    let bound_agent = AgentBinder::bind(
423        definition,
424        AgentInvocation {
425            role,
426            available_tools: host_capabilities(&cli, &config, role),
427        },
428        &config,
429    )?;
430    // An explicit --reasoning stays explicit unless the agent pins its own.
431    let bound_reasoning = bound_agent
432        .rho_config()
433        .map_or(config.reasoning, |bound| bound.reasoning);
434    let bound_reasoning_source = if cli.reasoning.is_some() && bound_reasoning == config.reasoning {
435        rho_providers::model::ReasoningRequestSource::Explicit
436    } else {
437        rho_providers::model::ReasoningRequestSource::PersistedOrDefault
438    };
439    // The bound agent's own config, which may pin a model and reasoning,
440    // replaces the launch config; an agent on another runtime keeps it.
441    let config = bound_agent.rho_config().cloned().unwrap_or(config);
442
443    Ok(PreparedStartup {
444        cli,
445        config,
446        config_repository,
447        first_run,
448        cwd,
449        automation_prompt,
450        output_file,
451        output,
452        max_steps,
453        timeout,
454        bound_agent,
455        bound_reasoning_source,
456        provider_refresh,
457        added_dirs,
458    })
459}
460
461struct AutomationStartup<'a> {
462    prompt: String,
463    config: &'a crate::config::Config,
464    config_repository: &'a ConfigRepository,
465    cwd: std::path::PathBuf,
466    cli: &'a Cli,
467    bound_agent: super::agent_binding::BoundAgent,
468    diagnostics: RuntimeDiagnostics,
469    output_file: Option<std::path::PathBuf>,
470    output: OutputFormat,
471    max_steps: Option<NonZeroUsize>,
472    timeout: Option<Duration>,
473    herdr: HerdrReporter,
474    added_dirs: crate::added_dirs::AddedDirs,
475}
476
477async fn run_automation_startup(startup: AutomationStartup<'_>) -> anyhow::Result<()> {
478    let persistence = match &startup.cli.command {
479        Some(Command::Run { no_save: true, .. }) => SessionPersistence::Ephemeral,
480        _ => SessionPersistence::Saved,
481    };
482    automation::run(
483        startup.prompt,
484        automation::Startup {
485            config: startup.config,
486            config_path: absolute_config_path(startup.config_repository)?,
487            cwd: startup.cwd,
488            left_out: launch_left_out(startup.cli),
489            agent: startup.bound_agent,
490            output_file: startup.output_file,
491            output: startup.output,
492            max_steps: startup.max_steps,
493            timeout: startup.timeout,
494            persistence,
495            diagnostics: startup.diagnostics,
496            herdr: startup.herdr,
497            added_dirs: startup.added_dirs,
498        },
499    )
500    .await
501}
502
503struct InteractiveStartup<'a> {
504    keyring_notice: crate::credential_store::StartupKeyringNotice,
505    cli: &'a Cli,
506    config: crate::config::Config,
507    config_repository: ConfigRepository,
508    first_run: Option<SetupEntry>,
509    cwd: std::path::PathBuf,
510    bound_agent: super::agent_binding::BoundAgent,
511    bound_reasoning_source: rho_providers::model::ReasoningRequestSource,
512    diagnostics: RuntimeDiagnostics,
513    herdr: HerdrReporter,
514    added_dirs: crate::added_dirs::AddedDirs,
515}
516
517async fn run_interactive_startup(startup: InteractiveStartup<'_>) -> anyhow::Result<()> {
518    let settings = crate::tui::TuiSettings::load(&crate::paths::rho_dir()?)?;
519    let pending_update_notice = settings
520        .check_for_updates
521        .then(|| tokio::spawn(update::update_notice(env!("CARGO_PKG_VERSION"))));
522    let pending_custom_models = cli_config::spawn_custom_provider_models_refresh(
523        startup.config.providers.clone(),
524        Arc::new(AppCredentialStore),
525    );
526    let prompt_history_limit = settings.prompt_history_limit;
527    let pending_prompt_history = (prompt_history_limit > 0 && !startup.cli.no_save).then(|| {
528        tokio::spawn(
529            async move {
530                tokio::task::spawn_blocking(move || {
531                    match crate::prompt_history::PromptHistoryStore::at_default_path() {
532                        Ok(store) => match store.load_tail(prompt_history_limit) {
533                            Ok(tail) => Some((store, tail)),
534                            Err(error) => {
535                                tracing::warn!(%error, "failed to load prompt history");
536                                None
537                            }
538                        },
539                        Err(error) => {
540                            tracing::warn!(%error, "failed to open prompt history");
541                            None
542                        }
543                    }
544                })
545                .await
546                .unwrap_or_else(|error| {
547                    tracing::warn!(%error, "prompt history task failed");
548                    None
549                })
550            }
551            .instrument(tracing::info_span!("startup.prompt_history")),
552        )
553    });
554
555    // No thread overlay here: `prepare_startup` already installed these hosts
556    // process-wide. An overlay would additionally hide later `/login` additions
557    // from every spawned task, since thread-locals do not follow `tokio::spawn`.
558    let sdk_options = SdkBootstrapOptions::from_config(&startup.config, &startup.cwd)?;
559    let credentials = rho_providers::auth::provider_credentials::ApplicationCredentialSource::new(
560        Arc::new(AppCredentialStore),
561    );
562    let provider_result = startup
563        .config
564        .providers
565        .require_endpoint_login(&startup.config.provider)
566        .and_then(|()| {
567            rho_providers::providers::build_sdk_provider_with_source(
568                sdk_options.provider,
569                &credentials,
570            )
571        });
572    let missing_auth_error = match provider_result {
573        Ok(_) => None,
574        Err(error) if is_interactive_startup_unavailable_error(&error) => Some(error.to_string()),
575        Err(error) => return Err(error.into()),
576    };
577    interactive::run(interactive::Startup {
578        keyring_notice: startup.keyring_notice,
579        cli: startup.cli,
580        config: startup.config,
581        settings,
582        config_repository: startup.config_repository,
583        cwd: startup.cwd,
584        first_run: startup.first_run,
585        missing_auth_error,
586        pending_update_notice,
587        pending_custom_models,
588        pending_prompt_history,
589        diagnostics: startup.diagnostics,
590        herdr: startup.herdr,
591        agent: startup.bound_agent,
592        reasoning_source: startup.bound_reasoning_source,
593        added_dirs: startup.added_dirs,
594    })
595    .await
596}
597
598fn run_credential_store_command(
599    command: &CredentialStoreCommand,
600    config_path: Option<std::path::PathBuf>,
601) -> anyhow::Result<()> {
602    match command {
603        CredentialStoreCommand::Probe { backend } => {
604            let result = crate::credential_store::probe(*backend);
605            if result.available {
606                println!("available: {}", result.detail);
607                Ok(())
608            } else {
609                anyhow::bail!(result.detail)
610            }
611        }
612        CredentialStoreCommand::Status => {
613            // Saved config policy only (ignore RHO_CREDENTIAL_STORE).
614            match crate::credential_store::saved_policy_backend(config_path.as_deref())? {
615                None => println!("unset"),
616                Some(backend) => println!("{}", backend.as_str()),
617            }
618            Ok(())
619        }
620        CredentialStoreCommand::Set { backend } => {
621            let path = crate::credential_store::set_backend(*backend, config_path)?;
622            println!(
623                "credential store set to {} in {}",
624                backend.as_str(),
625                path.display()
626            );
627            Ok(())
628        }
629    }
630}
631
632/// The parts a `rho run` or `rho acp` launch leaves out of its sessions.
633fn launch_left_out(cli: &Cli) -> LeftOut {
634    LeftOut {
635        system_prompt: cli.no_system_prompt,
636        tools: cli.no_tools,
637        subagents: cli.no_subagents,
638    }
639}
640
641pub(super) fn host_capabilities(
642    cli: &Cli,
643    config: &crate::config::Config,
644    role: AgentRole,
645) -> crate::agent::AgentCapabilities {
646    use crate::agent::ToolCapability;
647
648    let launch = LaunchTools::from_flags(cli.no_tools, cli.no_subagents);
649    if launch == LaunchTools::None {
650        return crate::agent::AgentCapabilities::default();
651    }
652    let mut tools = root_host_tools(config, launch);
653    if role != AgentRole::InteractiveRoot {
654        tools.remove(&ToolCapability::Questionnaire);
655    }
656    tools
657}
658
659pub(super) fn absolute_config_path(
660    repository: &ConfigRepository,
661) -> anyhow::Result<std::path::PathBuf> {
662    let path = repository.configured_path()?;
663    if path.is_absolute() {
664        Ok(path)
665    } else {
666        Ok(std::env::current_dir()?.join(path))
667    }
668}
669
670/// Opens the first-run setup screen so the flow can be reviewed without
671/// deleting a working config. See [`parse_first_run_override`] for the values.
672const FIRST_RUN_OVERRIDE_VAR: &str = "RHO_FIRST_RUN";
673
674/// Which step the override asks for, or `None` when it does not ask at all.
675///
676/// `signin` and `model` name a step, because a configured machine already has
677/// models and would otherwise always land on the model step, leaving the
678/// provider menu unreachable. Any other non-empty value that is not `0` means
679/// "open setup", letting the step be chosen the way a real first launch does.
680fn parse_first_run_override(value: &str) -> Option<SetupEntry> {
681    match value.trim().to_ascii_lowercase().as_str() {
682        "" | "0" | "false" | "no" => None,
683        "signin" | "sign-in" | "login" => Some(SetupEntry::SignIn),
684        "model" | "models" => Some(SetupEntry::ChooseModel),
685        _ => Some(SetupEntry::Auto),
686    }
687}
688
689/// The setup entry for this launch: the override when it is set, otherwise
690/// [`SetupEntry::Auto`] when Rho is about to create the config file.
691///
692/// Call this before loading the config, because loading writes the defaults.
693fn detect_first_run(repository: &ConfigRepository) -> Option<SetupEntry> {
694    if let Ok(value) = std::env::var(FIRST_RUN_OVERRIDE_VAR) {
695        if let Some(entry) = parse_first_run_override(&value) {
696            return Some(entry);
697        }
698    }
699    repository
700        .configured_path()
701        .is_ok_and(|path| !path.exists())
702        .then_some(SetupEntry::Auto)
703}
704
705fn validate_terminal_mode(cli: &Cli) -> anyhow::Result<()> {
706    if cli.command.is_none() && (!crate::stdio::stdin_is_terminal() || !io::stdout().is_terminal())
707    {
708        anyhow::bail!(
709            "rho's default mode is the interactive TUI; use `rho run` for non-interactive automation"
710        );
711    }
712    Ok(())
713}
714
715fn is_interactive_startup_unavailable_error(error: &ModelError) -> bool {
716    matches!(
717        error,
718        ModelError::MissingCredentials(_)
719            | ModelError::Credentials(_)
720            | ModelError::UnsupportedProvider(_)
721    )
722}
723
724#[cfg(test)]
725#[path = "bootstrap_tests.rs"]
726mod tests;