Skip to main content

oxi/
bootstrap.rs

1//! Application bootstrap and run-mode dispatch.
2//!
3//! Owns: log init, app building (settings → custom providers → router →
4//! tools → WASM), and run-mode dispatch (TUI / print / RPC).
5//!
6//! The helper functions below are moved verbatim from main.rs and
7//! retain their original signatures.
8
9use crate::cli::CliArgs;
10use crate::print_mode;
11use crate::store::settings::Settings;
12use anyhow::Result;
13use std::path::PathBuf;
14use tracing;
15
16/// Build a wired `App` from CLI args. All the wiring that used to be
17/// inline in `main()` lives here.
18pub async fn build_app(args: &CliArgs) -> Result<crate::App> {
19    // Layer 2.5 / Catalog Port (v3): the `FileModelCatalog` wired in
20    // `services::build_oxi` performs its own init at `OxiBuilder::build`
21    // time — it loads the embedded SNAP, applies overrides, and attempts
22    // one refresh if the cache is stale. So we no longer call the legacy
23    // `init_models_dev()` here. To skip network access during boot, set
24    // `OXI_MODELS_DEV_DISABLE_FETCH=1`.
25
26    // Load settings (global + project + env layers).
27    let mut settings = Settings::load().unwrap_or_default();
28
29    // Apply CLI overrides. Centralized in a closure so the post-wizard reload
30    // re-applies the exact same overrides — adding a new flag can't silently
31    // diverge between the two call sites.
32    let apply_cli_overrides = |s: &mut Settings| {
33        s.merge_cli(
34            args.model.clone(),
35            args.provider.clone(),
36            Some(args.enable_routing),
37            Some(args.prefer_cost_efficient),
38            if args.fallback_chain.is_empty() {
39                None
40            } else {
41                Some(args.fallback_chain.clone())
42            },
43            Some(args.disable_fallback),
44        );
45    };
46    apply_cli_overrides(&mut settings);
47
48    if settings
49        .effective_model(None)
50        .unwrap_or_default()
51        .is_empty()
52    {
53        // No model configured. In interactive (TUI) mode, drop the user
54        // straight into the setup wizard instead of erroring out — this is
55        // the common first-run experience. In non-interactive modes
56        // (print / JSON / RPC / single-prompt) the caller explicitly wants a
57        // one-shot run, so a hard error with guidance is correct.
58        if is_tui_mode(args) {
59            eprintln!("No model configured. Launching setup wizard...");
60            crate::setup_wizard::run().await?;
61
62            // Reload settings the wizard just persisted and re-apply the
63            // CLI overrides, then re-check. If the user bailed out of the
64            // wizard without selecting a model, fall through to the error.
65            settings = Settings::load().unwrap_or_default();
66            apply_cli_overrides(&mut settings);
67        }
68
69        if settings
70            .effective_model(None)
71            .unwrap_or_default()
72            .is_empty()
73        {
74            eprintln!(
75                "{}",
76                print_mode::format_error("No model configured. Run `oxi setup` to configure.")
77            );
78            std::process::exit(1);
79        }
80    }
81
82    // Register custom OpenAI-compatible providers from settings.
83    register_custom_providers(&settings);
84
85    // Register model router (opt-in).
86    register_router_provider(&settings);
87
88    // Apply thinking level if specified.
89    if let Some(ref level_str) = args.thinking {
90        if let Some(level) = crate::store::settings::parse_thinking_level(level_str) {
91            settings.thinking_level = level;
92        } else {
93            anyhow::bail!(
94                "Invalid thinking level: {}. Valid options: off, minimal, low, medium, high, xhigh",
95                level_str
96            );
97        }
98    }
99
100    // Build the wired Oxi engine + Agent via the SDK composition root.
101    let oxi = crate::build_oxi_engine().await?;
102
103    // Per-process liveness identity for issue-system ownership. In TUI mode
104    // we use the canonical "tui" id so the agent tool, the TUI panel, and
105    // the `/issue` slash command all share the same flock holder. In any
106    // non-TUI mode (print, RPC, single-prompt) we generate a stable
107    // process-scoped id; that way concurrent ownership checks see this
108    // process as a single coherent owner rather than an empty caller.
109    let ownership_session_id = if is_tui_mode(args) {
110        crate::store::issues::liveness::TUI_OWNERSHIP_ID.to_string()
111    } else {
112        format!(
113            "proc-{}-{}",
114            std::process::id(),
115            uuid::Uuid::new_v4().simple()
116        )
117    };
118
119    // Spawn the catalog event logger so refresh / override / local-discovery
120    // events show up in the log file. UI hooks can subscribe to
121    // `oxi.catalog().subscribe()` separately for picker invalidation.
122    let _catalog_logger =
123        crate::services::spawn_catalog_event_logger(std::sync::Arc::clone(oxi.catalog()));
124
125    let mut app = crate::App::from_oxi(oxi, settings, ownership_session_id).await?;
126
127    // v2.2: wire the MCP credential provider (OAuth2 client_credentials).
128    // Reads the same `mcp.json` files the agent uses, picks every server
129    // with an `oauth` block, and gives the manager a provider that can
130    // obtain + refresh access tokens on demand. No-op when no server
131    // declares `oauth`.
132    let mcp_cfg = oxi_agent::mcp::config::load_mcp_config();
133    let mut oauth_map: std::collections::HashMap<String, oxi_agent::mcp::types::OAuthConfig> =
134        std::collections::HashMap::new();
135    for (name, entry) in &mcp_cfg.mcp_servers {
136        if let Some(oc) = entry.oauth.clone() {
137            oauth_map.insert(name.clone(), oc);
138        }
139    }
140    if !oauth_map.is_empty()
141        && let Some(manager) = app.agent_tools().mcp_manager()
142    {
143        let config_dir = dirs::config_dir()
144            .map(|d| d.join("oxi"))
145            .unwrap_or_else(|| std::path::PathBuf::from("."));
146        match crate::mcp_credentials::FileMcpCredentialProvider::new(oauth_map, config_dir) {
147            Ok(provider) => {
148                manager.set_credential_provider(provider);
149            }
150            Err(e) => {
151                tracing::warn!("Failed to construct MCP credential provider: {}", e);
152            }
153        }
154    }
155
156    // Register built-in tools on the agent's tool registry.
157    let tools = app.agent_tools();
158    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
159    register_builtin_tools(
160        &tools,
161        &cwd,
162        args,
163        &app.settings().disabled_tools,
164        &app.settings().model_roles,
165    );
166
167    // Native headless browser (opt-in via the `native-browser` cargo feature).
168    // Constructs the pure-Rust `oxibrowser-core` engine and registers the
169    // browse tools (incl. `browse_session` with `observe`/`wait` actions) so
170    // the agent can navigate/observe/extract — omp-parity browsing without a
171    // Chrome dependency.
172    #[cfg(feature = "native-browser")]
173    {
174        match oxi_agent::tools::browse::OxiBrowserEngine::new().await {
175            Ok(engine) => {
176                let browser_registry =
177                    oxi_sdk::tool_factory::browsing_tools_with_session(std::sync::Arc::new(engine));
178                tools.extend_from(&browser_registry);
179            }
180            Err(e) => {
181                tracing::warn!("native browser engine unavailable; browse tools disabled: {e}");
182            }
183        }
184    }
185
186    // Discover and load WASM extensions.
187    let wasm_ext = load_wasm_extensions(&app, &cwd, &tools);
188    app.set_wasm_ext(wasm_ext);
189
190    // Handle --append-system-prompt.
191    if let Some(ref prompt_path) = args.append_system_prompt {
192        let content = std::fs::read_to_string(prompt_path)
193            .map_err(|e| anyhow::anyhow!("Failed to read system prompt file: {}", e))?;
194        app.agent().set_system_prompt(content);
195    }
196
197    // Spawn the autonomous memory pipeline if `memory_backend = "local"`.
198    // This is **opt-in**: when the user keeps the default `None`, the
199    // pipeline stays disabled and the boot path is side-effect free.
200    if let Some(handle) = crate::services::start_memory_pipeline(
201        app.settings(),
202        std::env::current_dir()
203            .as_ref()
204            .unwrap_or(&PathBuf::from(".")),
205        None,
206    ) {
207        tracing::debug!("memory pipeline spawn handle stored on app");
208        drop(handle); // currently fire-and-forget; joined on shutdown
209    }
210    Ok(app)
211}
212
213/// Dispatch the run mode: TUI / print / RPC, based on the CLI flags.
214pub async fn dispatch_run_mode(args: &CliArgs, app: crate::App) -> Result<i32> {
215    let prompt = args.prompt.join(" ");
216
217    if args.mode.as_deref() == Some("json") || args.print {
218        let mode = if args.mode.as_deref() == Some("json") {
219            crate::print_mode::PrintMode::Json
220        } else {
221            crate::print_mode::PrintMode::Text
222        };
223        let options = crate::print_mode::PrintModeOptions {
224            mode,
225            initial_message: if prompt.is_empty() {
226                None
227            } else {
228                Some(prompt)
229            },
230            messages: vec![],
231            no_stdin: args.print,
232            no_session: args.print || args.no_session,
233            quiet: args.print,
234            timeout: args.timeout,
235        };
236        return crate::print_mode::run_print_mode(&app, options).await;
237    }
238
239    if prompt.is_empty() || args.interactive {
240        if args.continue_session {
241            crate::tui::run_tui_interactive_with_continue(app, true).await?;
242        } else {
243            crate::tui::run_tui_interactive(app).await?;
244        }
245        return Ok(0);
246    }
247
248    crate::main_dispatch::run_single_prompt(app, &prompt).await?;
249    Ok(0)
250}
251
252/// Parse args, build the app, dispatch.
253pub async fn run_with_args(args: CliArgs) -> Result<i32> {
254    let app = build_app(&args).await?;
255    dispatch_run_mode(&args, app).await
256}
257
258// ─── Helpers (moved verbatim from main.rs) ─────────────────────────────
259
260/// Initialize file-based logging to `~/.cache/oxi/oxi.log`.
261///
262/// Reads `RUST_LOG` for filter (default: `debug`). Builds a
263/// `tracing_subscriber::EnvFilter` and writes to a `Mutex<File>` writer.
264pub fn init_logging() {
265    let log_dir = dirs::cache_dir()
266        .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
267        .join("oxi");
268    let _ = std::fs::create_dir_all(&log_dir);
269    let log_path = log_dir.join("oxi.log");
270
271    let log_filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "debug".to_string());
272    let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
273        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(&log_filter));
274
275    let log_file = std::fs::File::create(&log_path).expect("Failed to create log file");
276    let writer = std::sync::Mutex::new(log_file);
277
278    tracing_subscriber::fmt()
279        .with_env_filter(env_filter)
280        .with_writer(writer)
281        .with_target(true)
282        .with_thread_ids(true)
283        .with_ansi(false)
284        .init();
285
286    tracing::info!("Logging initialized, log file: {:?}", log_path);
287}
288
289/// Register custom OpenAI-compatible providers from settings and auto-fetch their models.
290fn register_custom_providers(settings: &Settings) {
291    let auth_storage = crate::store::auth_storage::shared_auth_storage();
292    for cp in &settings.custom_providers {
293        let api_key = auth_storage.get_api_key(&cp.name);
294        let api = cp.api.to_lowercase();
295
296        match api.as_str() {
297            "openai-completions" | "openai" => {
298                let provider =
299                    oxi_ai::OpenAiProvider::with_base_url_and_key(&cp.base_url, api_key.clone());
300                oxi_sdk::register_provider(&cp.name, provider);
301                tracing::info!(
302                    "Registered custom provider '{}' (openai-completions) -> {}",
303                    cp.name,
304                    cp.base_url
305                );
306            }
307            "openai-responses" | "responses" => {
308                let provider = oxi_sdk::OpenAiResponsesProvider::with_base_url_and_key(
309                    &cp.base_url,
310                    api_key.clone(),
311                );
312                oxi_sdk::register_provider(&cp.name, provider);
313                tracing::info!(
314                    "Registered custom provider '{}' (openai-responses) -> {}",
315                    cp.name,
316                    cp.base_url
317                );
318            }
319            _ => {
320                tracing::warn!(
321                    "Unknown API type '{}' for custom provider '{}'. Supported: openai-completions, openai-responses",
322                    cp.api,
323                    cp.name
324                );
325            }
326        }
327
328        fetch_and_register_models(cp, &api, &api_key);
329    }
330}
331
332/// Fetch models from a custom provider's /v1/models endpoint and register them.
333fn fetch_and_register_models(
334    cp: &crate::store::settings::CustomProvider,
335    api: &str,
336    api_key: &Option<String>,
337) {
338    if let Some(key) = api_key {
339        match oxi_sdk::fetch_models_blocking(&cp.base_url, key.as_str()) {
340            Ok(model_ids) => {
341                let count = model_ids.len();
342                for model_id in &model_ids {
343                    let api_type = match api {
344                        "openai-responses" | "responses" => oxi_sdk::Api::OpenAiResponses,
345                        _ => oxi_sdk::Api::OpenAiCompletions,
346                    };
347                    let model = oxi_sdk::Model {
348                        id: model_id.clone(),
349                        name: model_id.clone(),
350                        api: api_type,
351                        provider: cp.name.clone(),
352                        base_url: cp.base_url.clone(),
353                        reasoning: false,
354                        input: vec![oxi_sdk::InputModality::Text],
355                        cost: oxi_sdk::Cost::default(),
356                        context_window: 128_000,
357                        max_tokens: 8_192,
358                        headers: Default::default(),
359                        compat: None,
360                    };
361                    oxi_sdk::register_model(model);
362                }
363                tracing::info!(
364                    "[oxi] auto-fetched {} models from '{}' ({})",
365                    count,
366                    cp.name,
367                    cp.base_url
368                );
369            }
370            Err(e) => {
371                tracing::warn!(
372                    "[oxi] warning: failed to resolve models for {}: {}",
373                    cp.name,
374                    e
375                );
376            }
377        }
378    }
379}
380
381/// Register builtin tools with the agent, respecting --tools filter and disabled_tools.
382///
383/// Also transfers the [`McpManager`](oxi_agent::mcp::McpManager) reference from
384/// the built-in registry to the live agent registry. This matters because
385/// `register_arc` only copies the `Arc<dyn AgentTool>` — the manager field is
386/// stored separately and would otherwise be `None`, making `/mcp` show a
387/// "MCP is not configured" warning even though the `McpTool` is registered.
388fn register_builtin_tools(
389    tools: &oxi_agent::ToolRegistry,
390    cwd: &std::path::Path,
391    args: &CliArgs,
392    disabled_tools: &[String],
393    model_roles: &std::collections::HashMap<String, String>,
394) {
395    let builtin_registry = if let Some(ref tools_str) = args.tools {
396        let names: Vec<&str> = tools_str.split(',').map(|s| s.trim()).collect();
397        oxi_agent::ToolRegistry::with_selected_tools(cwd.to_path_buf(), &names)
398    } else {
399        oxi_agent::ToolRegistry::with_builtins_cwd(cwd.to_path_buf(), disabled_tools)
400    };
401    for name in builtin_registry.names() {
402        if let Some(tool) = builtin_registry.get(&name) {
403            tools.register_arc(tool);
404        }
405    }
406    // Propagate the MCP manager so the TUI's `/mcp` overlay can hot-reload
407    // configs, render live connection status, and so on.
408    if let Some(mgr) = builtin_registry.mcp_manager() {
409        tools.set_mcp_manager(mgr);
410    }
411
412    // Role-based commit model: if a `commit` role is configured, upgrade the
413    // deterministic (no-LLM) CommitTool to one backed by that model. Tools
414    // register by name, so this overwrites the unconfigured instance safely.
415    let role_registry = oxi_sdk::RoleRegistry::from_map(model_roles.clone());
416    if let Some(model) = oxi_sdk::resolve_role_to_model(oxi_sdk::ModelRole::Commit, &role_registry)
417    {
418        let commit: std::sync::Arc<dyn oxi_agent::AgentTool> =
419            std::sync::Arc::new(oxi_agent::CommitTool::new(model));
420        tools.register_arc(commit);
421        tracing::debug!("CommitTool upgraded to commit-role model");
422    }
423}
424
425/// Discover and load WASM extensions, registering their tools.
426fn load_wasm_extensions(
427    app: &crate::App,
428    cwd: &std::path::Path,
429    tools: &oxi_agent::ToolRegistry,
430) -> Option<std::sync::Arc<crate::extensions::WasmExtensionManager>> {
431    if !app.settings().extensions_enabled {
432        return None;
433    }
434
435    let wasm_paths = crate::extensions::WasmExtensionManager::discover(cwd);
436    if wasm_paths.is_empty() {
437        return None;
438    }
439
440    let mut wasm_mgr = crate::extensions::WasmExtensionManager::new();
441    let (loaded, errors) = wasm_mgr.load_all(&wasm_paths);
442    for info in &loaded {
443        tracing::info!("WASM extension loaded: {} v{}", info.name, info.version);
444    }
445    for err in &errors {
446        tracing::warn!("WASM extension error: {}", err);
447    }
448
449    if wasm_mgr.is_empty() {
450        return None;
451    }
452
453    let mgr = std::sync::Arc::new(wasm_mgr);
454    for tool_def in mgr.all_tool_defs() {
455        let wasm_tool = crate::extensions::WasmTool::new(
456            mgr.clone(),
457            tool_def.name.clone(),
458            tool_def.description.clone(),
459            tool_def.schema.clone(),
460        );
461        tools.register(wasm_tool);
462    }
463    Some(mgr)
464}
465
466/// Register the model auto-router if configured in settings.
467fn register_router_provider(settings: &Settings) {
468    let global_dir = dirs::config_dir().unwrap_or_default().join("oxi");
469    let project_dir = std::env::current_dir().unwrap_or_default();
470
471    let store_cfg = match crate::store::router_config::load_router_config(&global_dir, &project_dir)
472    {
473        Some(cfg) => cfg,
474        None => {
475            tracing::debug!("No router config found — router/auto will not appear in model list");
476            return;
477        }
478    };
479
480    // Register router models only when configured.
481    oxi_sdk::register_model(oxi_sdk::Model::new(
482        "auto",
483        "Router (auto)".to_string(),
484        oxi_sdk::Api::AnthropicMessages,
485        "router",
486        "router://local",
487    ));
488
489    // Convert store config to AI config.
490    let mut ai_profiles = std::collections::HashMap::new();
491    for (name, sp) in store_cfg.profiles() {
492        fn parse_thinking(s: &Option<String>) -> Option<oxi_sdk::ThinkingLevel> {
493            s.as_ref().and_then(|s| match s.as_str() {
494                "off" => Some(oxi_sdk::ThinkingLevel::Off),
495                "minimal" => Some(oxi_sdk::ThinkingLevel::Minimal),
496                "low" => Some(oxi_sdk::ThinkingLevel::Low),
497                "medium" => Some(oxi_sdk::ThinkingLevel::Medium),
498                "high" => Some(oxi_sdk::ThinkingLevel::High),
499                "xhigh" => Some(oxi_sdk::ThinkingLevel::XHigh),
500                _ => None,
501            })
502        }
503        ai_profiles.insert(
504            name.clone(),
505            oxi_sdk::router::RouterProfile {
506                high: oxi_sdk::router::RoutedTierConfig {
507                    model: sp.high.model.clone(),
508                    thinking: parse_thinking(&sp.high.thinking),
509                    fallbacks: sp.high.fallbacks.clone(),
510                },
511                medium: oxi_sdk::router::RoutedTierConfig {
512                    model: sp.medium.model.clone(),
513                    thinking: parse_thinking(&sp.medium.thinking),
514                    fallbacks: sp.medium.fallbacks.clone(),
515                },
516                low: oxi_sdk::router::RoutedTierConfig {
517                    model: sp.low.model.clone(),
518                    thinking: parse_thinking(&sp.low.thinking),
519                    fallbacks: sp.low.fallbacks.clone(),
520                },
521            },
522        );
523    }
524    let ai_cfg = oxi_sdk::router::RouterConfig::with_pinning(
525        store_cfg.default_profile().to_string(),
526        store_cfg.classifier_model().map(String::from),
527        store_cfg.context_upgrade_threshold(),
528        store_cfg.max_session_budget(),
529        ai_profiles,
530        oxi_sdk::router::ScoringWeights {
531            structural: store_cfg.weights().structural,
532            behavioral: store_cfg.weights().behavioral,
533            context_budget: store_cfg.weights().context_budget,
534            vision: store_cfg.weights().vision,
535            message: store_cfg.weights().message,
536        },
537        store_cfg.pin_tier().and_then(|s| match s {
538            "high" => Some(oxi_sdk::router::RouterTier::High),
539            "medium" => Some(oxi_sdk::router::RouterTier::Medium),
540            "low" => Some(oxi_sdk::router::RouterTier::Low),
541            _ => None,
542        }),
543        store_cfg.phase_bias(),
544    );
545
546    oxi_sdk::router::register_router(&ai_cfg);
547
548    if let Some(profile) = settings.router_profile() {
549        tracing::info!("Router active with profile: {profile}");
550    }
551}
552
553/// Decide whether this run is the TUI (interactive) mode. Mirrors the
554/// dispatch in [`dispatch_run_mode`]: print / RPC / single-prompt are
555/// non-TUI. Used by [`build_app`] to pick the canonical liveness identity.
556fn is_tui_mode(args: &CliArgs) -> bool {
557    if args.mode.as_deref() == Some("json") || args.print {
558        return false;
559    }
560    // prompt-only (no `--interactive` and a non-empty prompt) is non-TUI too;
561    // dispatch_run_mode sends it through main_dispatch::run_single_prompt.
562    // NOTE: must join the prompt Vec — clap's `default_value = ""` on the
563    // positional makes bare `oxi` yield `prompt == vec![""]` (non-empty Vec,
564    // empty join). Comparing the Vec directly would mis-classify the bare
565    // interactive launch as a single-prompt run.
566    let prompt = args.prompt.join(" ");
567    if !args.interactive && !prompt.is_empty() {
568        return false;
569    }
570    true
571}