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    // Discover and load WASM extensions.
168    let wasm_ext = load_wasm_extensions(&app, &cwd, &tools);
169    app.set_wasm_ext(wasm_ext);
170
171    // Handle --append-system-prompt.
172    if let Some(ref prompt_path) = args.append_system_prompt {
173        let content = std::fs::read_to_string(prompt_path)
174            .map_err(|e| anyhow::anyhow!("Failed to read system prompt file: {}", e))?;
175        app.agent().set_system_prompt(content);
176    }
177
178    Ok(app)
179}
180
181/// Dispatch the run mode: TUI / print / RPC, based on the CLI flags.
182pub async fn dispatch_run_mode(args: &CliArgs, app: crate::App) -> Result<i32> {
183    let prompt = args.prompt.join(" ");
184
185    if args.mode.as_deref() == Some("json") || args.print {
186        let mode = if args.mode.as_deref() == Some("json") {
187            crate::print_mode::PrintMode::Json
188        } else {
189            crate::print_mode::PrintMode::Text
190        };
191        let options = crate::print_mode::PrintModeOptions {
192            mode,
193            initial_message: if prompt.is_empty() {
194                None
195            } else {
196                Some(prompt)
197            },
198            messages: vec![],
199            no_stdin: args.print,
200            no_session: args.print || args.no_session,
201            quiet: args.print,
202            timeout: args.timeout,
203        };
204        return crate::print_mode::run_print_mode(&app, options).await;
205    }
206
207    if prompt.is_empty() || args.interactive {
208        if args.continue_session {
209            crate::tui::run_tui_interactive_with_continue(app, true).await?;
210        } else {
211            crate::tui::run_tui_interactive(app).await?;
212        }
213        return Ok(0);
214    }
215
216    crate::main_dispatch::run_single_prompt(app, &prompt).await?;
217    Ok(0)
218}
219
220/// Parse args, build the app, dispatch.
221pub async fn run_with_args(args: CliArgs) -> Result<i32> {
222    let app = build_app(&args).await?;
223    dispatch_run_mode(&args, app).await
224}
225
226// ─── Helpers (moved verbatim from main.rs) ─────────────────────────────
227
228/// Initialize file-based logging to `~/.cache/oxi/oxi.log`.
229///
230/// Reads `RUST_LOG` for filter (default: `debug`). Builds a
231/// `tracing_subscriber::EnvFilter` and writes to a `Mutex<File>` writer.
232pub fn init_logging() {
233    let log_dir = dirs::cache_dir()
234        .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
235        .join("oxi");
236    let _ = std::fs::create_dir_all(&log_dir);
237    let log_path = log_dir.join("oxi.log");
238
239    let log_filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "debug".to_string());
240    let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
241        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(&log_filter));
242
243    let log_file = std::fs::File::create(&log_path).expect("Failed to create log file");
244    let writer = std::sync::Mutex::new(log_file);
245
246    tracing_subscriber::fmt()
247        .with_env_filter(env_filter)
248        .with_writer(writer)
249        .with_target(true)
250        .with_thread_ids(true)
251        .with_ansi(false)
252        .init();
253
254    tracing::info!("Logging initialized, log file: {:?}", log_path);
255}
256
257/// Register custom OpenAI-compatible providers from settings and auto-fetch their models.
258fn register_custom_providers(settings: &Settings) {
259    let auth_storage = crate::store::auth_storage::shared_auth_storage();
260    for cp in &settings.custom_providers {
261        let api_key = auth_storage.get_api_key(&cp.name);
262        let api = cp.api.to_lowercase();
263
264        match api.as_str() {
265            "openai-completions" | "openai" => {
266                let provider =
267                    oxi_ai::OpenAiProvider::with_base_url_and_key(&cp.base_url, api_key.clone());
268                oxi_sdk::register_provider(&cp.name, provider);
269                tracing::info!(
270                    "Registered custom provider '{}' (openai-completions) -> {}",
271                    cp.name,
272                    cp.base_url
273                );
274            }
275            "openai-responses" | "responses" => {
276                let provider = oxi_sdk::OpenAiResponsesProvider::with_base_url_and_key(
277                    &cp.base_url,
278                    api_key.clone(),
279                );
280                oxi_sdk::register_provider(&cp.name, provider);
281                tracing::info!(
282                    "Registered custom provider '{}' (openai-responses) -> {}",
283                    cp.name,
284                    cp.base_url
285                );
286            }
287            _ => {
288                tracing::warn!(
289                    "Unknown API type '{}' for custom provider '{}'. Supported: openai-completions, openai-responses",
290                    cp.api,
291                    cp.name
292                );
293            }
294        }
295
296        fetch_and_register_models(cp, &api, &api_key);
297    }
298}
299
300/// Fetch models from a custom provider's /v1/models endpoint and register them.
301fn fetch_and_register_models(
302    cp: &crate::store::settings::CustomProvider,
303    api: &str,
304    api_key: &Option<String>,
305) {
306    if let Some(key) = api_key {
307        match oxi_sdk::fetch_models_blocking(&cp.base_url, key.as_str()) {
308            Ok(model_ids) => {
309                let count = model_ids.len();
310                for model_id in &model_ids {
311                    let api_type = match api {
312                        "openai-responses" | "responses" => oxi_sdk::Api::OpenAiResponses,
313                        _ => oxi_sdk::Api::OpenAiCompletions,
314                    };
315                    let model = oxi_sdk::Model {
316                        id: model_id.clone(),
317                        name: model_id.clone(),
318                        api: api_type,
319                        provider: cp.name.clone(),
320                        base_url: cp.base_url.clone(),
321                        reasoning: false,
322                        input: vec![oxi_sdk::InputModality::Text],
323                        cost: oxi_sdk::Cost::default(),
324                        context_window: 128_000,
325                        max_tokens: 8_192,
326                        headers: Default::default(),
327                        compat: None,
328                    };
329                    oxi_sdk::register_model(model);
330                }
331                tracing::info!(
332                    "[oxi] auto-fetched {} models from '{}' ({})",
333                    count,
334                    cp.name,
335                    cp.base_url
336                );
337            }
338            Err(e) => {
339                tracing::warn!(
340                    "[oxi] warning: failed to resolve models for {}: {}",
341                    cp.name,
342                    e
343                );
344            }
345        }
346    }
347}
348
349/// Register builtin tools with the agent, respecting --tools filter and disabled_tools.
350///
351/// Also transfers the [`McpManager`](oxi_agent::mcp::McpManager) reference from
352/// the built-in registry to the live agent registry. This matters because
353/// `register_arc` only copies the `Arc<dyn AgentTool>` — the manager field is
354/// stored separately and would otherwise be `None`, making `/mcp` show a
355/// "MCP is not configured" warning even though the `McpTool` is registered.
356fn register_builtin_tools(
357    tools: &oxi_agent::ToolRegistry,
358    cwd: &std::path::Path,
359    args: &CliArgs,
360    disabled_tools: &[String],
361    model_roles: &std::collections::HashMap<String, String>,
362) {
363    let builtin_registry = if let Some(ref tools_str) = args.tools {
364        let names: Vec<&str> = tools_str.split(',').map(|s| s.trim()).collect();
365        oxi_agent::ToolRegistry::with_selected_tools(cwd.to_path_buf(), &names)
366    } else {
367        oxi_agent::ToolRegistry::with_builtins_cwd(cwd.to_path_buf(), disabled_tools)
368    };
369    for name in builtin_registry.names() {
370        if let Some(tool) = builtin_registry.get(&name) {
371            tools.register_arc(tool);
372        }
373    }
374    // Propagate the MCP manager so the TUI's `/mcp` overlay can hot-reload
375    // configs, render live connection status, and so on.
376    if let Some(mgr) = builtin_registry.mcp_manager() {
377        tools.set_mcp_manager(mgr);
378    }
379
380    // Role-based commit model: if a `commit` role is configured, upgrade the
381    // deterministic (no-LLM) CommitTool to one backed by that model. Tools
382    // register by name, so this overwrites the unconfigured instance safely.
383    let role_registry = oxi_sdk::RoleRegistry::from_map(model_roles.clone());
384    if let Some(model) = oxi_sdk::resolve_role_to_model(oxi_sdk::ModelRole::Commit, &role_registry)
385    {
386        let commit: std::sync::Arc<dyn oxi_agent::AgentTool> =
387            std::sync::Arc::new(oxi_agent::CommitTool::new(model));
388        tools.register_arc(commit);
389        tracing::debug!("CommitTool upgraded to commit-role model");
390    }
391}
392
393/// Discover and load WASM extensions, registering their tools.
394fn load_wasm_extensions(
395    app: &crate::App,
396    cwd: &std::path::Path,
397    tools: &oxi_agent::ToolRegistry,
398) -> Option<std::sync::Arc<crate::extensions::WasmExtensionManager>> {
399    if !app.settings().extensions_enabled {
400        return None;
401    }
402
403    let wasm_paths = crate::extensions::WasmExtensionManager::discover(cwd);
404    if wasm_paths.is_empty() {
405        return None;
406    }
407
408    let mut wasm_mgr = crate::extensions::WasmExtensionManager::new();
409    let (loaded, errors) = wasm_mgr.load_all(&wasm_paths);
410    for info in &loaded {
411        tracing::info!("WASM extension loaded: {} v{}", info.name, info.version);
412    }
413    for err in &errors {
414        tracing::warn!("WASM extension error: {}", err);
415    }
416
417    if wasm_mgr.is_empty() {
418        return None;
419    }
420
421    let mgr = std::sync::Arc::new(wasm_mgr);
422    for tool_def in mgr.all_tool_defs() {
423        let wasm_tool = crate::extensions::WasmTool::new(
424            mgr.clone(),
425            tool_def.name.clone(),
426            tool_def.description.clone(),
427            tool_def.schema.clone(),
428        );
429        tools.register(wasm_tool);
430    }
431    Some(mgr)
432}
433
434/// Register the model auto-router if configured in settings.
435fn register_router_provider(settings: &Settings) {
436    let global_dir = dirs::config_dir().unwrap_or_default().join("oxi");
437    let project_dir = std::env::current_dir().unwrap_or_default();
438
439    let store_cfg = match crate::store::router_config::load_router_config(&global_dir, &project_dir)
440    {
441        Some(cfg) => cfg,
442        None => {
443            tracing::debug!("No router config found — router/auto will not appear in model list");
444            return;
445        }
446    };
447
448    // Register router models only when configured.
449    oxi_sdk::register_model(oxi_sdk::Model::new(
450        "auto",
451        "Router (auto)".to_string(),
452        oxi_sdk::Api::AnthropicMessages,
453        "router",
454        "router://local",
455    ));
456
457    // Convert store config to AI config.
458    let mut ai_profiles = std::collections::HashMap::new();
459    for (name, sp) in store_cfg.profiles() {
460        fn parse_thinking(s: &Option<String>) -> Option<oxi_sdk::ThinkingLevel> {
461            s.as_ref().and_then(|s| match s.as_str() {
462                "off" => Some(oxi_sdk::ThinkingLevel::Off),
463                "minimal" => Some(oxi_sdk::ThinkingLevel::Minimal),
464                "low" => Some(oxi_sdk::ThinkingLevel::Low),
465                "medium" => Some(oxi_sdk::ThinkingLevel::Medium),
466                "high" => Some(oxi_sdk::ThinkingLevel::High),
467                "xhigh" => Some(oxi_sdk::ThinkingLevel::XHigh),
468                _ => None,
469            })
470        }
471        ai_profiles.insert(
472            name.clone(),
473            oxi_sdk::router::RouterProfile {
474                high: oxi_sdk::router::RoutedTierConfig {
475                    model: sp.high.model.clone(),
476                    thinking: parse_thinking(&sp.high.thinking),
477                    fallbacks: sp.high.fallbacks.clone(),
478                },
479                medium: oxi_sdk::router::RoutedTierConfig {
480                    model: sp.medium.model.clone(),
481                    thinking: parse_thinking(&sp.medium.thinking),
482                    fallbacks: sp.medium.fallbacks.clone(),
483                },
484                low: oxi_sdk::router::RoutedTierConfig {
485                    model: sp.low.model.clone(),
486                    thinking: parse_thinking(&sp.low.thinking),
487                    fallbacks: sp.low.fallbacks.clone(),
488                },
489            },
490        );
491    }
492    let ai_cfg = oxi_sdk::router::RouterConfig::with_pinning(
493        store_cfg.default_profile().to_string(),
494        store_cfg.classifier_model().map(String::from),
495        store_cfg.context_upgrade_threshold(),
496        store_cfg.max_session_budget(),
497        ai_profiles,
498        oxi_sdk::router::ScoringWeights {
499            structural: store_cfg.weights().structural,
500            behavioral: store_cfg.weights().behavioral,
501            context_budget: store_cfg.weights().context_budget,
502            vision: store_cfg.weights().vision,
503            message: store_cfg.weights().message,
504        },
505        store_cfg.pin_tier().and_then(|s| match s {
506            "high" => Some(oxi_sdk::router::RouterTier::High),
507            "medium" => Some(oxi_sdk::router::RouterTier::Medium),
508            "low" => Some(oxi_sdk::router::RouterTier::Low),
509            _ => None,
510        }),
511        store_cfg.phase_bias(),
512    );
513
514    oxi_sdk::router::register_router(&ai_cfg);
515
516    if let Some(profile) = settings.router_profile() {
517        tracing::info!("Router active with profile: {profile}");
518    }
519}
520
521/// Decide whether this run is the TUI (interactive) mode. Mirrors the
522/// dispatch in [`dispatch_run_mode`]: print / RPC / single-prompt are
523/// non-TUI. Used by [`build_app`] to pick the canonical liveness identity.
524fn is_tui_mode(args: &CliArgs) -> bool {
525    if args.mode.as_deref() == Some("json") || args.print {
526        return false;
527    }
528    // prompt-only (no `--interactive` and a non-empty prompt) is non-TUI too;
529    // dispatch_run_mode sends it through main_dispatch::run_single_prompt.
530    // NOTE: must join the prompt Vec — clap's `default_value = ""` on the
531    // positional makes bare `oxi` yield `prompt == vec![""]` (non-empty Vec,
532    // empty join). Comparing the Vec directly would mis-classify the bare
533    // interactive launch as a single-prompt run.
534    let prompt = args.prompt.join(" ");
535    if !args.interactive && !prompt.is_empty() {
536        return false;
537    }
538    true
539}