Skip to main content

oxicode/
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_oxicode` performs its own init at `OxicodeBuilder::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    // `OXICODE_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(args.model.clone(), args.provider.clone());
34    };
35    apply_cli_overrides(&mut settings);
36
37    // Pre-build the per-process liveness identity BEFORE the engine build so
38    // we can include it in the SessionStart hook context (and pass it to
39    // App::from_oxicode on the same path).
40    let ownership_session_id = if is_tui_mode(args) {
41        crate::store::issues::liveness::TUI_OWNERSHIP_ID.to_string()
42    } else {
43        format!(
44            "proc-{}-{}",
45            std::process::id(),
46            uuid::Uuid::new_v4().simple()
47        )
48    };
49
50    // Load hooks: global hooks (`~/.oxicode/settings.toml` -> `[[hooks]]`)
51    // are always trusted. Project hooks (`.oxicode/settings.toml`) require
52    // a first-run interactive Y/n approval — unless we're in a non-TUI
53    // mode, in which case we skip with a warning to keep the boot path
54    // non-interactive. See `store/hook_approval.rs` for the registry.
55    let global_hooks = settings.hooks.clone();
56    let cwd_now = std::env::current_dir().unwrap_or_default();
57    let project_hooks_path = Settings::find_project_settings(&cwd_now);
58    let project_hooks: Vec<oxicode_sdk::ports::HookSpec> = match &project_hooks_path {
59        Some(path) => {
60            let content = std::fs::read_to_string(path).unwrap_or_default();
61            let hash = crate::store::hook_approval::hash_settings(&content);
62            let mut registry = crate::store::hook_approval::HookApprovalRegistry::load_or_default();
63            if registry.is_approved(&cwd_now, &hash) {
64                // Approved: re-parse the project file and extract its [[hooks]].
65                match Settings::parse_from_str(&content, Settings::detect_format(path)) {
66                    Ok(s) => s.hooks,
67                    Err(e) => {
68                        tracing::warn!(error = %e, "project hooks file failed to parse");
69                        Vec::new()
70                    }
71                }
72            } else {
73                // First run or hash mismatch.
74                let count = content.matches("[[hooks]]").count();
75                if count > 0 {
76                    if is_tui_mode(args) {
77                        let ok = crate::store::hook_approval::prompt_for_approval(&cwd_now, count);
78                        if ok {
79                            registry.approve(&cwd_now, &hash);
80                            let _ = registry.persist();
81                            Settings::parse_from_str(&content, Settings::detect_format(path))
82                                .map(|s| s.hooks)
83                                .unwrap_or_default()
84                        } else {
85                            tracing::warn!("project hooks denied by user; skipping");
86                            Vec::new()
87                        }
88                    } else {
89                        tracing::warn!(
90                            count,
91                            "project hooks not approved; skipping (non-interactive mode)"
92                        );
93                        Vec::new()
94                    }
95                } else {
96                    Vec::new()
97                }
98            }
99        }
100        None => Vec::new(),
101    };
102    let mut all_hooks = global_hooks;
103    all_hooks.extend(project_hooks);
104    let hook_runner: std::sync::Arc<dyn oxicode_sdk::ports::HookRunner> =
105        match oxicode_sdk::ports::fs::CommandHookRunner::new(all_hooks) {
106            Ok(r) => std::sync::Arc::new(r),
107            Err(e) => {
108                tracing::warn!(error = %e, "hook runner construction failed; using empty runner");
109                std::sync::Arc::new(
110                    oxicode_sdk::ports::fs::CommandHookRunner::new(Vec::new())
111                        .expect("empty spec list is always valid"),
112                )
113            }
114        };
115
116    if settings
117        .effective_model(None)
118        .unwrap_or_default()
119        .is_empty()
120    {
121        // No model configured. In interactive (TUI) mode, drop the user
122        // straight into the setup wizard instead of erroring out — this is
123        // the common first-run experience. In non-interactive modes
124        // (print / JSON / RPC / single-prompt) the caller explicitly wants a
125        // one-shot run, so a hard error with guidance is correct.
126        if is_tui_mode(args) {
127            eprintln!("No model configured. Launching setup wizard...");
128            crate::setup_wizard::run().await?;
129
130            // Reload settings the wizard just persisted and re-apply the
131            // CLI overrides, then re-check. If the user bailed out of the
132            // wizard without selecting a model, fall through to the error.
133            settings = Settings::load().unwrap_or_default();
134            apply_cli_overrides(&mut settings);
135        }
136
137        if settings
138            .effective_model(None)
139            .unwrap_or_default()
140            .is_empty()
141        {
142            eprintln!(
143                "{}",
144                print_mode::format_error("No model configured. Run `oxicode setup` to configure.")
145            );
146            std::process::exit(1);
147        }
148    }
149
150    // Register custom OpenAI-compatible providers from settings.
151    register_custom_providers(&settings);
152
153    // Register model router (reads router_config file, opt-in).
154    register_router_provider();
155
156    // Apply thinking level if specified.
157    if let Some(ref level_str) = args.thinking {
158        if let Some(level) = crate::store::settings::parse_thinking_level(level_str) {
159            settings.thinking_level = level;
160        } else {
161            anyhow::bail!(
162                "Invalid thinking level: {}. Valid options: off, minimal, low, medium, high, xhigh",
163                level_str
164            );
165        }
166    }
167
168    // Build the wired Oxicode engine + Agent via the SDK composition root.
169    // Build embedding port from settings (mnemopi → SDK async bridge).
170    let embedding_provider = crate::services::build_embedding_provider(&settings).map(|p| {
171        std::sync::Arc::new(crate::services::MnemopiEmbeddingBridge::new(p))
172            as std::sync::Arc<dyn oxicode_sdk::ports::EmbeddingProvider>
173    });
174
175    let oxicode =
176        crate::build_oxicode_engine(embedding_provider, Some(hook_runner.clone())).await?;
177
178    // Fire SessionStart (fail-open: a hook that errors must not block boot).
179    {
180        let hook_ctx = oxicode_sdk::ports::HookContext {
181            event: oxicode_sdk::ports::HookEvent::SessionStart,
182            session_id: Some(ownership_session_id.clone()),
183            session_cwd: Some(cwd_now.clone()),
184            ..Default::default()
185        };
186        let _ = oxicode
187            .ports()
188            .hooks
189            .run(oxicode_sdk::ports::HookEvent::SessionStart, &hook_ctx)
190            .await;
191    }
192
193    // Spawn the catalog event logger so refresh / override / local-discovery
194    // events show up in the log file. UI hooks can subscribe to
195    // `oxicode.catalog().subscribe()` separately for picker invalidation.
196    let _catalog_logger =
197        crate::services::spawn_catalog_event_logger(std::sync::Arc::clone(oxicode.catalog()));
198
199    // Pre-build session state so the runtime (AgentSession) and the
200    // agent's session-level closures (`with_session_hooks`) share the
201    // SAME queues + stop flag. The single `set_hooks` invariant depends
202    // on this state living across both ends.
203    let session_state = crate::SessionState::default();
204
205    let mut app =
206        crate::App::from_oxicode(oxicode, settings, ownership_session_id, Some(session_state))
207            .await?;
208
209    // Fire-and-forget OAuth refresh: if the active provider has a stored
210    // OAuth credential that is expired (or within 60 s of expiry), ask the
211    // refresh module to rotate it in the background. A failed refresh must
212    // never crash startup — the agent will surface a re-login prompt on
213    // the first 401 if the refresh actually failed.
214    if let Some(active_provider) = app.settings().effective_provider(args.provider.as_deref())
215        && !active_provider.is_empty()
216    {
217        let p = active_provider.clone();
218        tokio::spawn(async move {
219            if let Err(e) = crate::oauth_refresh::refresh_if_expired(&p).await {
220                tracing::debug!(provider = %p, error = %e, "oauth refresh skipped");
221            }
222        });
223    }
224
225    // v2.2: wire the MCP credential provider (OAuth2 client_credentials).
226    // Reads the same `mcp.json` files the agent uses, picks every server
227    // with an `oauth` block, and gives the manager a provider that can
228    // obtain + refresh access tokens on demand. No-op when no server
229    // declares `oauth`.
230    let mcp_cfg = oxicode_agent::mcp::config::load_mcp_config();
231    let mut oauth_map: std::collections::HashMap<String, oxicode_agent::mcp::types::OAuthConfig> =
232        std::collections::HashMap::new();
233    for (name, entry) in &mcp_cfg.mcp_servers {
234        if let Some(oc) = entry.oauth.clone() {
235            oauth_map.insert(name.clone(), oc);
236        }
237    }
238    if !oauth_map.is_empty()
239        && let Some(manager) = app.agent_tools().mcp_manager()
240    {
241        let config_dir = dirs::config_dir()
242            .map(|d| d.join("oxicode"))
243            .unwrap_or_else(|| std::path::PathBuf::from("."));
244        match crate::mcp_credentials::FileMcpCredentialProvider::new(oauth_map, config_dir) {
245            Ok(provider) => {
246                manager.set_credential_provider(provider);
247            }
248            Err(e) => {
249                tracing::warn!("Failed to construct MCP credential provider: {}", e);
250            }
251        }
252    }
253
254    // Register built-in tools on the agent's tool registry.
255    let tools = app.agent_tools();
256    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
257    register_builtin_tools(
258        &tools,
259        &cwd,
260        args,
261        &app.settings().disabled_tools,
262        &app.settings().model_roles,
263    );
264
265    // Native headless browser (opt-in via the `native-browser` cargo feature).
266    // Constructs the pure-Rust `oxibrowser-core` engine and registers the
267    // browse tools (incl. `browse_session` with `observe`/`wait` actions) so
268    // the agent can navigate/observe/extract — omp-parity browsing without a
269    // Chrome dependency.
270    #[cfg(feature = "native-browser")]
271    {
272        match oxicode_agent::tools::browse::OxicodeBrowserEngine::new().await {
273            Ok(engine) => {
274                let browser_registry = oxicode_sdk::tool_factory::browsing_tools_with_session(
275                    std::sync::Arc::new(engine),
276                );
277                tools.extend_from(&browser_registry);
278            }
279            Err(e) => {
280                tracing::warn!("native browser engine unavailable; browse tools disabled: {e}");
281            }
282        }
283    }
284
285    // Discover and load WASM extensions.
286    let wasm_ext = load_wasm_extensions(&app, &cwd, &tools);
287    app.set_wasm_ext(wasm_ext);
288
289    // Handle --append-system-prompt.
290    if let Some(ref prompt_path) = args.append_system_prompt {
291        let content = std::fs::read_to_string(prompt_path)
292            .map_err(|e| anyhow::anyhow!("Failed to read system prompt file: {}", e))?;
293        app.agent().set_system_prompt(content);
294    }
295
296    // Spawn the autonomous memory pipeline if `memory_backend = "local"`.
297    // This is **opt-in**: when the user keeps the default `None`, the
298    // pipeline stays disabled and the boot path is side-effect free.
299    if let Some(handle) = crate::services::start_memory_pipeline(
300        app.settings(),
301        std::env::current_dir()
302            .as_ref()
303            .unwrap_or(&PathBuf::from(".")),
304        Some(app.oxicode()),
305    ) {
306        tracing::debug!("memory pipeline spawn handle stored on app");
307        drop(handle); // joined on shutdown via App drop
308    }
309    Ok(app)
310}
311
312/// Dispatch the run mode: TUI / print / RPC, based on the CLI flags.
313pub async fn dispatch_run_mode(args: &CliArgs, app: crate::App) -> Result<i32> {
314    let prompt = args.prompt.join(" ");
315
316    if args.mode.as_deref() == Some("json") || args.print {
317        let mode = if args.mode.as_deref() == Some("json") {
318            crate::print_mode::PrintMode::Json
319        } else {
320            crate::print_mode::PrintMode::Text
321        };
322        let options = crate::print_mode::PrintModeOptions {
323            mode,
324            initial_message: if prompt.is_empty() {
325                None
326            } else {
327                Some(prompt)
328            },
329            messages: vec![],
330            no_stdin: args.print,
331            no_session: args.print || args.no_session,
332            quiet: args.print,
333            timeout: args.timeout,
334        };
335        return crate::print_mode::run_print_mode(&app, options).await;
336    }
337
338    if args.mode.as_deref() == Some("rpc") {
339        crate::rpc_mode::run_rpc_mode(app).await?;
340        return Ok(0);
341    }
342
343    if let Some(mode) = args.mode.as_deref() {
344        anyhow::bail!("Unknown run mode: {mode}");
345    }
346
347    if prompt.is_empty() || args.interactive {
348        crate::tui_vt::run_tui(app).await?;
349        return Ok(0);
350    }
351
352    crate::main_dispatch::run_single_prompt(app, &prompt).await?;
353    Ok(0)
354}
355
356/// Parse args, build the app, dispatch.
357pub async fn run_with_args(args: CliArgs) -> Result<i32> {
358    let app = build_app(&args).await?;
359    dispatch_run_mode(&args, app).await
360}
361
362// ─── Helpers (moved verbatim from main.rs) ─────────────────────────────
363
364/// Initialize file-based logging to `~/.cache/oxicode/oxicode.log`.
365///
366/// Reads `RUST_LOG` for filter (default: `debug`). Builds a
367/// `tracing_subscriber::EnvFilter` and writes to a `Mutex<File>` writer.
368pub fn init_logging() {
369    let log_dir = dirs::cache_dir()
370        .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
371        .join("oxicode");
372    let _ = std::fs::create_dir_all(&log_dir);
373    let log_path = log_dir.join("oxicode.log");
374
375    let log_filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "debug".to_string());
376    let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
377        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(&log_filter));
378
379    // Logging is non-critical infrastructure: if the log file can't be
380    // created (permissions, read-only fs, …), degrade to stderr instead of
381    // aborting the process. Previously this `.expect()`-panicked on init,
382    // which under `panic = "abort"` killed the app before it could start.
383    let subscriber = tracing_subscriber::fmt()
384        .with_env_filter(env_filter)
385        .with_target(true)
386        .with_thread_ids(true)
387        .with_ansi(false);
388    match std::fs::File::create(&log_path) {
389        Ok(file) => {
390            subscriber.with_writer(std::sync::Mutex::new(file)).init();
391        }
392        Err(e) => {
393            eprintln!(
394                "oxicode: could not open log file {log_path:?} ({e}); falling back to stderr"
395            );
396            subscriber.with_writer(std::io::stderr).init();
397        }
398    }
399
400    tracing::info!("Logging initialized, log file: {:?}", log_path);
401}
402
403/// Register custom OpenAI-compatible providers from settings and auto-fetch their models.
404fn register_custom_providers(settings: &Settings) {
405    let auth_storage = crate::store::auth_storage::shared_auth_storage();
406    for cp in &settings.custom_providers {
407        let api_key = auth_storage.get_api_key(&cp.name);
408        let api = cp.api.to_lowercase();
409
410        match api.as_str() {
411            "openai-completions" | "openai" => {
412                let provider = oxicode_ai::OpenAiProvider::with_base_url_and_key(
413                    &cp.base_url,
414                    api_key.clone(),
415                );
416                oxicode_sdk::register_provider(&cp.name, provider);
417                tracing::info!(
418                    "Registered custom provider '{}' (openai-completions) -> {}",
419                    cp.name,
420                    cp.base_url
421                );
422            }
423            "openai-responses" | "responses" => {
424                let provider = oxicode_sdk::OpenAiResponsesProvider::with_base_url_and_key(
425                    &cp.base_url,
426                    api_key.clone(),
427                );
428                oxicode_sdk::register_provider(&cp.name, provider);
429                tracing::info!(
430                    "Registered custom provider '{}' (openai-responses) -> {}",
431                    cp.name,
432                    cp.base_url
433                );
434            }
435            _ => {
436                tracing::warn!(
437                    "Unknown API type '{}' for custom provider '{}'. Supported: openai-completions, openai-responses",
438                    cp.api,
439                    cp.name
440                );
441            }
442        }
443
444        fetch_and_register_models(cp, &api, &api_key);
445    }
446}
447
448/// Fetch models from a custom provider's /v1/models endpoint and register them.
449fn fetch_and_register_models(
450    cp: &crate::store::settings::CustomProvider,
451    api: &str,
452    api_key: &Option<String>,
453) {
454    if let Some(key) = api_key {
455        match oxicode_sdk::fetch_models_blocking(&cp.base_url, key.as_str()) {
456            Ok(model_ids) => {
457                let count = model_ids.len();
458                for model_id in &model_ids {
459                    let api_type = match api {
460                        "openai-responses" | "responses" => oxicode_sdk::Api::OpenAiResponses,
461                        _ => oxicode_sdk::Api::OpenAiCompletions,
462                    };
463                    let model = oxicode_sdk::Model {
464                        id: model_id.clone(),
465                        name: model_id.clone(),
466                        api: api_type,
467                        provider: cp.name.clone(),
468                        base_url: cp.base_url.clone(),
469                        reasoning: false,
470                        input: vec![oxicode_sdk::InputModality::Text],
471                        cost: oxicode_sdk::Cost::default(),
472                        context_window: 128_000,
473                        max_tokens: 8_192,
474                        headers: Default::default(),
475                        compat: None,
476                    };
477                    oxicode_sdk::register_model(model);
478                }
479                tracing::info!(
480                    "[oxicode] auto-fetched {} models from '{}' ({})",
481                    count,
482                    cp.name,
483                    cp.base_url
484                );
485            }
486            Err(e) => {
487                tracing::warn!(
488                    "[oxicode] warning: failed to resolve models for {}: {}",
489                    cp.name,
490                    e
491                );
492            }
493        }
494    }
495}
496
497/// Register builtin tools with the agent, respecting --tools filter and disabled_tools.
498///
499/// Also transfers the [`McpManager`](oxicode_agent::mcp::McpManager) reference from
500/// the built-in registry to the live agent registry. This matters because
501/// `register_arc` only copies the `Arc<dyn AgentTool>` — the manager field is
502/// stored separately and would otherwise be `None`, making `/mcp` show a
503/// "MCP is not configured" warning even though the `McpTool` is registered.
504fn register_builtin_tools(
505    tools: &oxicode_agent::ToolRegistry,
506    cwd: &std::path::Path,
507    args: &CliArgs,
508    disabled_tools: &[String],
509    model_roles: &std::collections::HashMap<String, String>,
510) {
511    let builtin_registry = if let Some(ref tools_str) = args.tools {
512        let names: Vec<&str> = tools_str.split(',').map(|s| s.trim()).collect();
513        oxicode_agent::ToolRegistry::with_selected_tools(cwd.to_path_buf(), &names)
514    } else {
515        oxicode_agent::ToolRegistry::with_builtins_cwd(cwd.to_path_buf(), disabled_tools)
516    };
517    for name in builtin_registry.names() {
518        if let Some(tool) = builtin_registry.get(&name) {
519            tools.register_arc(tool);
520        }
521    }
522    // Propagate the MCP manager so the TUI's `/mcp` overlay can hot-reload
523    // configs, render live connection status, and so on.
524    if let Some(mgr) = builtin_registry.mcp_manager() {
525        tools.set_mcp_manager(mgr);
526    }
527
528    // Role-based commit model: if a `commit` role is configured, upgrade the
529    // deterministic (no-LLM) CommitTool to one backed by that model. Tools
530    // register by name, so this overwrites the unconfigured instance safely.
531    let role_registry = oxicode_sdk::RoleRegistry::from_map(model_roles.clone());
532    if let Some(model) =
533        oxicode_sdk::resolve_role_to_model(oxicode_sdk::ModelRole::Commit, &role_registry)
534    {
535        let commit: std::sync::Arc<dyn oxicode_agent::AgentTool> =
536            std::sync::Arc::new(oxicode_agent::CommitTool::new(model));
537        tools.register_arc(commit);
538        tracing::debug!("CommitTool upgraded to commit-role model");
539    }
540}
541
542/// Discover and load WASM extensions, registering their tools.
543fn load_wasm_extensions(
544    app: &crate::App,
545    cwd: &std::path::Path,
546    tools: &oxicode_agent::ToolRegistry,
547) -> Option<std::sync::Arc<crate::extensions::WasmExtensionManager>> {
548    if !app.settings().extensions_enabled {
549        return None;
550    }
551
552    let wasm_paths = crate::extensions::WasmExtensionManager::discover(cwd);
553    if wasm_paths.is_empty() {
554        return None;
555    }
556
557    let mut wasm_mgr = crate::extensions::WasmExtensionManager::new();
558    let (loaded, errors) = wasm_mgr.load_all(&wasm_paths);
559    for info in &loaded {
560        tracing::info!("WASM extension loaded: {} v{}", info.name, info.version);
561    }
562    for err in &errors {
563        tracing::warn!("WASM extension error: {}", err);
564    }
565
566    if wasm_mgr.is_empty() {
567        return None;
568    }
569
570    let mgr = std::sync::Arc::new(wasm_mgr);
571    for tool_def in mgr.all_tool_defs() {
572        let wasm_tool = crate::extensions::WasmTool::new(
573            mgr.clone(),
574            tool_def.name.clone(),
575            tool_def.description.clone(),
576            tool_def.schema.clone(),
577        );
578        tools.register(wasm_tool);
579    }
580    Some(mgr)
581}
582
583/// Register the model auto-router if configured in router_config.
584fn register_router_provider() {
585    let global_dir = dirs::config_dir().unwrap_or_default().join("oxicode");
586    let project_dir = std::env::current_dir().unwrap_or_default();
587
588    let store_cfg = match crate::store::router_config::load_router_config(&global_dir, &project_dir)
589    {
590        Some(cfg) => cfg,
591        None => {
592            tracing::debug!("No router config found — router/auto will not appear in model list");
593            return;
594        }
595    };
596
597    // Register router models only when configured.
598    oxicode_sdk::register_model(oxicode_sdk::Model::new(
599        "auto",
600        "Router (auto)".to_string(),
601        oxicode_sdk::Api::AnthropicMessages,
602        "router",
603        "router://local",
604    ));
605
606    // Convert store config to AI config.
607    let mut ai_profiles = std::collections::HashMap::new();
608    for (name, sp) in store_cfg.profiles() {
609        fn parse_thinking(s: &Option<String>) -> Option<oxicode_sdk::ThinkingLevel> {
610            s.as_ref().and_then(|s| match s.as_str() {
611                "off" => Some(oxicode_sdk::ThinkingLevel::Off),
612                "minimal" => Some(oxicode_sdk::ThinkingLevel::Minimal),
613                "low" => Some(oxicode_sdk::ThinkingLevel::Low),
614                "medium" => Some(oxicode_sdk::ThinkingLevel::Medium),
615                "high" => Some(oxicode_sdk::ThinkingLevel::High),
616                "xhigh" => Some(oxicode_sdk::ThinkingLevel::XHigh),
617                _ => None,
618            })
619        }
620        ai_profiles.insert(
621            name.clone(),
622            oxicode_sdk::router::RouterProfile {
623                high: oxicode_sdk::router::RoutedTierConfig {
624                    model: sp.high.model.clone(),
625                    thinking: parse_thinking(&sp.high.thinking),
626                    fallbacks: sp.high.fallbacks.clone(),
627                },
628                medium: oxicode_sdk::router::RoutedTierConfig {
629                    model: sp.medium.model.clone(),
630                    thinking: parse_thinking(&sp.medium.thinking),
631                    fallbacks: sp.medium.fallbacks.clone(),
632                },
633                low: oxicode_sdk::router::RoutedTierConfig {
634                    model: sp.low.model.clone(),
635                    thinking: parse_thinking(&sp.low.thinking),
636                    fallbacks: sp.low.fallbacks.clone(),
637                },
638            },
639        );
640    }
641    let ai_cfg = oxicode_sdk::router::RouterConfig::with_pinning(
642        store_cfg.default_profile().to_string(),
643        store_cfg.classifier_model().map(String::from),
644        store_cfg.context_upgrade_threshold(),
645        store_cfg.max_session_budget(),
646        ai_profiles,
647        oxicode_sdk::router::ScoringWeights {
648            structural: store_cfg.weights().structural,
649            behavioral: store_cfg.weights().behavioral,
650            context_budget: store_cfg.weights().context_budget,
651            vision: store_cfg.weights().vision,
652            message: store_cfg.weights().message,
653        },
654        store_cfg.pin_tier().and_then(|s| match s {
655            "high" => Some(oxicode_sdk::router::RouterTier::High),
656            "medium" => Some(oxicode_sdk::router::RouterTier::Medium),
657            "low" => Some(oxicode_sdk::router::RouterTier::Low),
658            _ => None,
659        }),
660        store_cfg.phase_bias(),
661    );
662
663    oxicode_sdk::router::register_router(&ai_cfg);
664}
665
666/// Decide whether this run is the TUI (interactive) mode. Mirrors the
667/// dispatch in [`dispatch_run_mode`]: print / RPC / single-prompt are
668/// non-TUI. Used by [`build_app`] to pick the canonical liveness identity.
669fn is_tui_mode(args: &CliArgs) -> bool {
670    if matches!(args.mode.as_deref(), Some("json" | "rpc")) || args.print {
671        return false;
672    }
673    // prompt-only (no `--interactive` and a non-empty prompt) is non-TUI too;
674    // dispatch_run_mode sends it through main_dispatch::run_single_prompt.
675    // NOTE: must join the prompt Vec — clap's `default_value = ""` on the
676    // positional makes bare `oxicode` yield `prompt == vec![""]` (non-empty Vec,
677    // empty join). Comparing the Vec directly would mis-classify the bare
678    // interactive launch as a single-prompt run.
679    let prompt = args.prompt.join(" ");
680    if !args.interactive && !prompt.is_empty() {
681        return false;
682    }
683    true
684}
685#[cfg(test)]
686mod tests {
687    use super::*;
688    use clap::Parser;
689
690    #[test]
691    fn rpc_mode_is_headless() {
692        let args = CliArgs::try_parse_from(["oxicode", "--mode", "rpc"]).unwrap();
693        assert!(!is_tui_mode(&args));
694    }
695
696    #[test]
697    fn empty_hooks_does_not_block() {
698        use crate::store::settings::Settings;
699        let s = Settings::default();
700        assert!(s.hooks.is_empty());
701    }
702}