Skip to main content

rho_coding_agent/app/
bootstrap.rs

1use std::{
2    collections::BTreeSet,
3    io::{self, IsTerminal},
4    sync::Arc,
5};
6
7use crate::{
8    cli::{Cli, Command},
9    credentials::OsCredentialStore,
10    diagnostics::RuntimeDiagnostics,
11    herdr::HerdrReporter,
12    model::{models_dev::cached_model_metadata, ModelError},
13    update,
14};
15
16use super::{
17    agent_binding::{AgentBinder, AgentInvocation, AgentRole},
18    automation, cli_config,
19    config_repository::ConfigRepository,
20    interactive, login,
21    sdk_config::SdkBootstrapOptions,
22};
23
24pub async fn run(cli: Cli) -> anyhow::Result<()> {
25    cli_config::validate(&cli)?;
26    if let Some(Command::Attach { id }) = &cli.command {
27        return crate::tui::run_attachment(id, HerdrReporter::from_env()).await;
28    }
29    if matches!(cli.command, Some(Command::Update)) {
30        return update::run_update(env!("CARGO_PKG_VERSION")).await;
31    }
32    if let Some(Command::Login {
33        provider,
34        device_auth,
35    }) = &cli.command
36    {
37        return login::run(provider, *device_auth).await;
38    }
39
40    let config_path = cli.config.clone();
41    let config_repository = ConfigRepository::new(config_path.clone());
42    let mut config = config_repository.load()?;
43    let cwd = std::env::current_dir()?;
44    let automation_prompt = automation::prompt_for_command(&cli.command)?;
45    let output_file = match &cli.command {
46        Some(Command::Run { output_file, .. }) => output_file.clone(),
47        _ => None,
48    };
49    let catalog = crate::agent::AgentCatalog::discover(&cwd)?;
50    let selected_agent = cli.agent.as_deref().unwrap_or("default");
51    let definition = Arc::new(catalog.find(selected_agent)?.definition.clone());
52
53    let store = OsCredentialStore;
54    cli_config::refresh_model_cache(&cli, &store).await?;
55    if cli_config::apply_overrides(&mut config, &cli)? {
56        config_repository.save(&config)?;
57    }
58    let role = if automation_prompt.is_some() {
59        AgentRole::AutomationRoot
60    } else {
61        AgentRole::InteractiveRoot
62    };
63    let bound_agent = AgentBinder::bind(
64        definition,
65        AgentInvocation {
66            role,
67            available_tools: host_capabilities(&cli, &config, role),
68        },
69        &config,
70    )?;
71    config = bound_agent.config().clone();
72
73    validate_terminal_mode(&cli)?;
74    if automation_prompt.is_some()
75        && config.provider == "anthropic"
76        && cached_model_metadata(&config.provider, &config.model).is_none()
77    {
78        let _ =
79            crate::model::models_dev::fetch_model_metadata(&config.provider, &config.model).await;
80    }
81    cli_config::normalize_reasoning(&mut config);
82    let herdr = HerdrReporter::from_env();
83    if let Some(prompt) = automation_prompt {
84        let diagnostics = RuntimeDiagnostics::new(&config);
85        diagnostics.update_agent(
86            bound_agent.id().as_str(),
87            &bound_agent.fingerprint().to_string(),
88        );
89        return automation::run(
90            prompt,
91            automation::Startup {
92                config: &config,
93                config_path: absolute_config_path(&config_repository)?,
94                cwd,
95                no_system_prompt: cli.no_system_prompt,
96                no_tools: cli.no_tools,
97                no_subagents: cli.no_subagents,
98                agent: bound_agent,
99                output_file,
100                diagnostics,
101                herdr,
102            },
103        )
104        .await;
105    }
106    let diagnostics = RuntimeDiagnostics::new(&config);
107    diagnostics.update_agent(
108        bound_agent.id().as_str(),
109        &bound_agent.fingerprint().to_string(),
110    );
111
112    let pending_update_notice = config
113        .check_for_updates
114        .then(|| tokio::spawn(update::update_notice(env!("CARGO_PKG_VERSION"))));
115
116    let sdk_options = SdkBootstrapOptions::from_config(&config, &cwd)?;
117    let credentials = crate::auth::provider_credentials::ApplicationCredentialSource::new(
118        Arc::new(OsCredentialStore),
119    );
120    let provider_result =
121        crate::providers::build_sdk_provider_with_source(sdk_options.provider, &credentials);
122    let (missing_auth_error, missing_auth_model_error) = match provider_result {
123        Ok(_) => (None, None),
124        Err(error) if is_interactive_startup_unavailable_error(&error) => {
125            (Some(error.to_string()), Some(error))
126        }
127        Err(error) => return Err(error.into()),
128    };
129    let result = interactive::run(interactive::Startup {
130        cli: &cli,
131        config,
132        config_path: absolute_config_path(&config_repository)?,
133        config_repository,
134        cwd,
135        missing_auth_error,
136        missing_auth_model_error,
137        pending_update_notice,
138        diagnostics,
139        herdr,
140        agent: bound_agent,
141    })
142    .await;
143    result
144}
145
146fn host_capabilities(
147    cli: &Cli,
148    config: &crate::config::Config,
149    role: AgentRole,
150) -> BTreeSet<String> {
151    if cli.no_tools {
152        return BTreeSet::new();
153    }
154    let mut tools = crate::agent::KNOWN_TOOLS
155        .iter()
156        .map(|tool| (*tool).to_string())
157        .collect::<BTreeSet<_>>();
158    if !crate::tools::web::access_tools(config).is_available() {
159        tools.remove("web_search");
160    }
161    #[cfg(windows)]
162    tools.remove("bash");
163    #[cfg(not(windows))]
164    tools.remove("powershell");
165    if cli.no_subagents || !config.enable_subagents {
166        tools.remove("agent");
167        tools.remove("agents");
168    }
169    if role != AgentRole::InteractiveRoot {
170        tools.remove("questionnaire");
171    }
172    tools
173}
174
175fn absolute_config_path(repository: &ConfigRepository) -> anyhow::Result<std::path::PathBuf> {
176    let path = repository.configured_path()?;
177    if path.is_absolute() {
178        Ok(path)
179    } else {
180        Ok(std::env::current_dir()?.join(path))
181    }
182}
183
184fn validate_terminal_mode(cli: &Cli) -> anyhow::Result<()> {
185    if cli.command.is_none() && (!io::stdin().is_terminal() || !io::stdout().is_terminal()) {
186        anyhow::bail!(
187            "rho's default mode is the interactive TUI; use `rho run` for non-interactive automation"
188        );
189    }
190    Ok(())
191}
192
193fn is_interactive_startup_unavailable_error(error: &ModelError) -> bool {
194    matches!(
195        error,
196        ModelError::MissingApiKey
197            | ModelError::MissingCodexAuth
198            | ModelError::MissingAnthropicApiKey
199            | ModelError::MissingGithubCopilotAuth
200            | ModelError::MissingXaiApiKey
201            | ModelError::MissingXaiAuth
202            | ModelError::Credentials(_)
203            | ModelError::UnsupportedProvider(_)
204    )
205}
206
207#[cfg(test)]
208#[path = "bootstrap_tests.rs"]
209mod tests;