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        oxicode_sdk::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    // Durable memory: oxibrain daemon is the sole authority (Foundation
169    // plan §5). The backend is constructed per AgentSession via
170    // services::create_memory_backend; no local pipeline is spawned.
171    // Build the wired Oxicode engine + Agent via the SDK composition root.
172    // (The SDK embeddings port stays at its Noop default — durable memory is
173    // the oxibrain daemon, not an embedding pipeline.)
174    let oxicode = crate::build_oxicode_engine(None, Some(hook_runner.clone())).await?;
175
176    // Fire SessionStart (fail-open: a hook that errors must not block boot).
177    {
178        let hook_ctx = oxicode_sdk::ports::HookContext {
179            event: oxicode_sdk::ports::HookEvent::SessionStart,
180            session_id: Some(ownership_session_id.clone()),
181            session_cwd: Some(cwd_now.clone()),
182            ..Default::default()
183        };
184        let _ = oxicode
185            .ports()
186            .hooks
187            .run(oxicode_sdk::ports::HookEvent::SessionStart, &hook_ctx)
188            .await;
189    }
190
191    // Spawn the catalog event logger so refresh / override / local-discovery
192    // events show up in the log file. UI hooks can subscribe to
193    // `oxicode.catalog().subscribe()` separately for picker invalidation.
194    let _catalog_logger =
195        crate::services::spawn_catalog_event_logger(std::sync::Arc::clone(oxicode.catalog()));
196
197    // Pre-build session state so the runtime (AgentSession) and the
198    // agent's session-level closures (`with_session_hooks`) share the
199    // SAME queues + stop flag. The single `set_hooks` invariant depends
200    // on this state living across both ends.
201    let session_state = crate::SessionState::default();
202
203    let mut app =
204        crate::App::from_oxicode(oxicode, settings, ownership_session_id, Some(session_state))
205            .await?;
206
207    // Fire-and-forget OAuth refresh: if the active provider has a stored
208    // OAuth credential that is expired (or within 60 s of expiry), ask the
209    // refresh module to rotate it in the background. A failed refresh must
210    // never crash startup — the agent will surface a re-login prompt on
211    // the first 401 if the refresh actually failed.
212    if let Some(active_provider) = app.settings().effective_provider(args.provider.as_deref())
213        && !active_provider.is_empty()
214    {
215        let p = active_provider.clone();
216        tokio::spawn(async move {
217            if let Err(e) = crate::oauth_refresh::refresh_if_expired(&p).await {
218                tracing::debug!(provider = %p, error = %e, "oauth refresh skipped");
219            }
220        });
221    }
222
223    // v2.2: wire the MCP credential provider (OAuth2 client_credentials).
224    // Reads the same `mcp.json` files the agent uses, picks every server
225    // with an `oauth` block, and gives the manager a provider that can
226    // obtain + refresh access tokens on demand. No-op when no server
227    // declares `oauth`.
228    let mcp_cfg = oxicode_agent::mcp::config::load_mcp_config();
229    let mut oauth_map: std::collections::HashMap<String, oxicode_agent::mcp::types::OAuthConfig> =
230        std::collections::HashMap::new();
231    for (name, entry) in &mcp_cfg.mcp_servers {
232        if let Some(oc) = entry.oauth.clone() {
233            oauth_map.insert(name.clone(), oc);
234        }
235    }
236    if !oauth_map.is_empty()
237        && let Some(manager) = app.agent_tools().mcp_manager()
238    {
239        let config_dir = dirs::config_dir()
240            .map(|d| d.join("oxicode"))
241            .unwrap_or_else(|| std::path::PathBuf::from("."));
242        match crate::mcp_credentials::FileMcpCredentialProvider::new(oauth_map, config_dir) {
243            Ok(provider) => {
244                manager.set_credential_provider(provider);
245            }
246            Err(e) => {
247                tracing::warn!("Failed to construct MCP credential provider: {}", e);
248            }
249        }
250    }
251
252    // Register built-in tools on the agent's tool registry.
253    let tools = app.agent_tools();
254    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
255    register_builtin_tools(
256        &tools,
257        &cwd,
258        args,
259        &app.settings().disabled_tools,
260        &app.settings().model_roles,
261    );
262
263    // Native headless browser (opt-in via the `native-browser` cargo feature).
264    // Constructs the pure-Rust `oxibrowser-core` engine and registers the
265    // browse tools (incl. `browse_session` with `observe`/`wait` actions) so
266    // the agent can navigate/observe/extract — omp-parity browsing without a
267    // Chrome dependency.
268    #[cfg(feature = "native-browser")]
269    {
270        match oxicode_agent::tools::browse::OxicodeBrowserEngine::new().await {
271            Ok(engine) => {
272                let (provider, model) = match (app.agent().model_id().is_empty(), app.oxicode()) {
273                    (false, oxicode) => {
274                        let model_id = app.agent().model_id();
275                        // model_id is the bare model id (Agent::model_id);
276                        // resolve provider name from the agent's config or fall
277                        // back to the Oxicode default.
278                        let provider_name = "anthropic".to_string();
279                        match (
280                            oxicode.create_provider(&provider_name),
281                            oxicode_ai::Model::new(
282                                model_id.clone(),
283                                model_id.clone(),
284                                oxicode_ai::Api::AnthropicMessages,
285                                provider_name.clone(),
286                                String::new(),
287                            ),
288                        ) {
289                            (Ok(p), m) => (Some(p), Some(m)),
290                            _ => (None, None),
291                        }
292                    }
293                    _ => (None, None),
294                };
295                let browser_registry = oxicode_agent::tools::browse::browsing_tools_with_session(
296                    provider,
297                    model,
298                    std::sync::Arc::new(engine),
299                );
300                tools.extend_from(&browser_registry);
301            }
302            Err(e) => {
303                tracing::warn!("native browser engine unavailable; browse tools disabled: {e}");
304            }
305        }
306    }
307
308    // Discover and load WASM extensions.
309    let wasm_ext = load_wasm_extensions(&app, &cwd, &tools);
310    app.set_wasm_ext(wasm_ext);
311
312    // Handle --append-system-prompt.
313    if let Some(ref prompt_path) = args.append_system_prompt {
314        let content = std::fs::read_to_string(prompt_path)
315            .map_err(|e| anyhow::anyhow!("Failed to read system prompt file: {}", e))?;
316        app.agent().set_system_prompt(content);
317    }
318
319    Ok(app)
320}
321
322/// Dispatch the run mode: TUI / print / RPC, based on the CLI flags.
323pub async fn dispatch_run_mode(args: &CliArgs, app: crate::App) -> Result<i32> {
324    let prompt = args.prompt.join(" ");
325
326    if args.mode.as_deref() == Some("json") || args.print {
327        let mode = if args.mode.as_deref() == Some("json") {
328            crate::print_mode::PrintMode::Json
329        } else {
330            crate::print_mode::PrintMode::Text
331        };
332        let options = crate::print_mode::PrintModeOptions {
333            mode,
334            initial_message: if prompt.is_empty() {
335                None
336            } else {
337                Some(prompt)
338            },
339            messages: vec![],
340            no_stdin: args.print,
341            no_session: args.print || args.no_session,
342            quiet: args.print,
343            timeout: args.timeout,
344        };
345        return crate::print_mode::run_print_mode(&app, options).await;
346    }
347
348    if args.mode.as_deref() == Some("rpc") {
349        crate::rpc_mode::run_rpc_mode(app).await?;
350        return Ok(0);
351    }
352
353    if let Some(mode) = args.mode.as_deref() {
354        anyhow::bail!("Unknown run mode: {mode}");
355    }
356
357    if prompt.is_empty() || args.interactive {
358        crate::tui_vt::run_tui(app).await?;
359        return Ok(0);
360    }
361
362    crate::main_dispatch::run_single_prompt(app, &prompt).await?;
363    Ok(0)
364}
365
366/// Parse args, build the app, dispatch.
367pub async fn run_with_args(args: CliArgs) -> Result<i32> {
368    let app = build_app(&args).await?;
369    dispatch_run_mode(&args, app).await
370}
371
372// ─── Helpers (moved verbatim from main.rs) ─────────────────────────────
373
374/// Initialize file-based logging to `~/.cache/oxicode/oxicode.log`.
375///
376/// Reads `RUST_LOG` for filter (default: `debug`). Builds a
377/// `tracing_subscriber::EnvFilter` and writes to a `Mutex<File>` writer.
378pub fn init_logging() {
379    let log_dir = dirs::cache_dir()
380        .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
381        .join("oxicode");
382    let _ = std::fs::create_dir_all(&log_dir);
383    let log_path = log_dir.join("oxicode.log");
384
385    let log_filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "debug".to_string());
386    let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
387        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(&log_filter));
388
389    // Logging is non-critical infrastructure: if the log file can't be
390    // created (permissions, read-only fs, …), degrade to stderr instead of
391    // aborting the process. Previously this `.expect()`-panicked on init,
392    // which under `panic = "abort"` killed the app before it could start.
393    let subscriber = tracing_subscriber::fmt()
394        .with_env_filter(env_filter)
395        .with_target(true)
396        .with_thread_ids(true)
397        .with_ansi(false);
398    match std::fs::File::create(&log_path) {
399        Ok(file) => {
400            subscriber.with_writer(std::sync::Mutex::new(file)).init();
401        }
402        Err(e) => {
403            eprintln!(
404                "oxicode: could not open log file {log_path:?} ({e}); falling back to stderr"
405            );
406            subscriber.with_writer(std::io::stderr).init();
407        }
408    }
409
410    tracing::info!("Logging initialized, log file: {:?}", log_path);
411}
412
413/// Register custom OpenAI-compatible providers from settings and auto-fetch their models.
414fn register_custom_providers(settings: &Settings) {
415    let auth_storage = crate::store::auth_storage::shared_auth_storage();
416    for cp in &settings.custom_providers {
417        let api_key = auth_storage.get_api_key(&cp.name);
418        let api = cp.api.to_lowercase();
419
420        match api.as_str() {
421            "openai-completions" | "openai" => {
422                let provider = oxicode_ai::OpenAiProvider::with_base_url_and_key(
423                    &cp.base_url,
424                    api_key.clone(),
425                );
426                oxicode_sdk::register_provider(&cp.name, provider);
427                tracing::info!(
428                    "Registered custom provider '{}' (openai-completions) -> {}",
429                    cp.name,
430                    cp.base_url
431                );
432            }
433            "openai-responses" | "responses" => {
434                let provider = oxicode_sdk::OpenAiResponsesProvider::with_base_url_and_key(
435                    &cp.base_url,
436                    api_key.clone(),
437                );
438                oxicode_sdk::register_provider(&cp.name, provider);
439                tracing::info!(
440                    "Registered custom provider '{}' (openai-responses) -> {}",
441                    cp.name,
442                    cp.base_url
443                );
444            }
445            _ => {
446                tracing::warn!(
447                    "Unknown API type '{}' for custom provider '{}'. Supported: openai-completions, openai-responses",
448                    cp.api,
449                    cp.name
450                );
451            }
452        }
453
454        fetch_and_register_models(cp, &api, &api_key);
455    }
456}
457
458/// Fetch models from a custom provider's /v1/models endpoint and register them.
459fn fetch_and_register_models(
460    cp: &crate::store::settings::CustomProvider,
461    api: &str,
462    api_key: &Option<String>,
463) {
464    if let Some(key) = api_key {
465        match oxicode_sdk::fetch_models_blocking(&cp.base_url, key.as_str()) {
466            Ok(model_ids) => {
467                let count = model_ids.len();
468                for model_id in &model_ids {
469                    let api_type = match api {
470                        "openai-responses" | "responses" => oxicode_sdk::Api::OpenAiResponses,
471                        _ => oxicode_sdk::Api::OpenAiCompletions,
472                    };
473                    // `/v1/models` reports bare ids with no metadata.
474                    // Custom providers usually proxy upstream models
475                    // (claude-*, gemini-*, …), so cross-fill real limits
476                    // from the models.dev catalog before falling back to
477                    // the conservative placeholder.
478                    let known = oxicode_sdk::find_entry_by_model_id(model_id);
479                    let model = oxicode_sdk::Model {
480                        id: model_id.clone(),
481                        name: model_id.clone(),
482                        api: api_type,
483                        provider: cp.name.clone(),
484                        base_url: cp.base_url.clone(),
485                        reasoning: known.map(|e| e.reasoning).unwrap_or(false),
486                        input: vec![oxicode_sdk::InputModality::Text],
487                        cost: known
488                            .map(|e| oxicode_sdk::Cost {
489                                input: e.cost_input.max(0.0),
490                                output: e.cost_output.max(0.0),
491                                cache_read: e.cost_cache_read.max(0.0),
492                                cache_write: e.cost_cache_write.max(0.0),
493                            })
494                            .unwrap_or_default(),
495                        context_window: known.map(|e| e.context_window as usize).unwrap_or(128_000),
496                        max_tokens: known.map(|e| e.max_tokens as usize).unwrap_or(8_192),
497                        headers: Default::default(),
498                        compat: None,
499                    };
500                    oxicode_sdk::register_model(model);
501                }
502                tracing::info!(
503                    "[oxicode] auto-fetched {} models from '{}' ({})",
504                    count,
505                    cp.name,
506                    cp.base_url
507                );
508            }
509            Err(e) => {
510                tracing::warn!(
511                    "[oxicode] warning: failed to resolve models for {}: {}",
512                    cp.name,
513                    e
514                );
515            }
516        }
517    }
518}
519
520/// Register builtin tools with the agent, respecting --tools filter and disabled_tools.
521///
522/// Also transfers the [`McpManager`](oxicode_agent::mcp::McpManager) reference from
523/// the built-in registry to the live agent registry. This matters because
524/// `register_arc` only copies the `Arc<dyn AgentTool>` — the manager field is
525/// stored separately and would otherwise be `None`, making `/mcp` show a
526/// "MCP is not configured" warning even though the `McpTool` is registered.
527fn register_builtin_tools(
528    tools: &oxicode_agent::ToolRegistry,
529    cwd: &std::path::Path,
530    args: &CliArgs,
531    disabled_tools: &[String],
532    model_roles: &std::collections::HashMap<String, String>,
533) {
534    let builtin_registry = if let Some(ref tools_str) = args.tools {
535        let names: Vec<&str> = tools_str.split(',').map(|s| s.trim()).collect();
536        oxicode_agent::ToolRegistry::with_selected_tools(cwd.to_path_buf(), &names)
537    } else {
538        oxicode_agent::ToolRegistry::with_builtins_cwd(cwd.to_path_buf(), disabled_tools)
539    };
540    for name in builtin_registry.names() {
541        if let Some(tool) = builtin_registry.get(&name) {
542            tools.register_arc(tool);
543        }
544    }
545    // Propagate the MCP manager so the TUI's `/mcp` overlay can hot-reload
546    // configs, render live connection status, and so on.
547    if let Some(mgr) = builtin_registry.mcp_manager() {
548        tools.set_mcp_manager(mgr);
549    }
550
551    // Role-based commit model: if a `commit` role is configured, upgrade the
552    // deterministic (no-LLM) CommitTool to one backed by that model. Tools
553    // register by name, so this overwrites the unconfigured instance safely.
554    let role_registry = oxicode_sdk::RoleRegistry::from_map(model_roles.clone());
555    if let Some(model) =
556        oxicode_sdk::resolve_role_to_model(oxicode_sdk::ModelRole::Commit, &role_registry)
557    {
558        let commit: std::sync::Arc<dyn oxicode_agent::AgentTool> =
559            std::sync::Arc::new(oxicode_agent::CommitTool::new(model));
560        tools.register_arc(commit);
561        tracing::debug!("CommitTool upgraded to commit-role model");
562    }
563}
564
565/// Discover and load WASM extensions, registering their tools.
566fn load_wasm_extensions(
567    app: &crate::App,
568    cwd: &std::path::Path,
569    tools: &oxicode_agent::ToolRegistry,
570) -> Option<std::sync::Arc<crate::extensions::WasmExtensionManager>> {
571    if !app.settings().extensions_enabled {
572        return None;
573    }
574
575    let wasm_paths = crate::extensions::WasmExtensionManager::discover(cwd);
576    if wasm_paths.is_empty() {
577        return None;
578    }
579
580    let mut wasm_mgr = crate::extensions::WasmExtensionManager::new();
581    let (loaded, errors) = wasm_mgr.load_all(&wasm_paths);
582    for info in &loaded {
583        tracing::info!("WASM extension loaded: {} v{}", info.name, info.version);
584    }
585    for err in &errors {
586        tracing::warn!("WASM extension error: {}", err);
587    }
588
589    if wasm_mgr.is_empty() {
590        return None;
591    }
592
593    let mgr = std::sync::Arc::new(wasm_mgr);
594    for tool_def in mgr.all_tool_defs() {
595        let wasm_tool = crate::extensions::WasmTool::new(
596            mgr.clone(),
597            tool_def.name.clone(),
598            tool_def.description.clone(),
599            tool_def.schema.clone(),
600        );
601        tools.register(wasm_tool);
602    }
603    Some(mgr)
604}
605
606/// Register the model auto-router if configured in router_config.
607fn register_router_provider() {
608    let global_dir = dirs::config_dir().unwrap_or_default().join("oxicode");
609    let project_dir = std::env::current_dir().unwrap_or_default();
610
611    let store_cfg = match crate::store::router_config::load_router_config(&global_dir, &project_dir)
612    {
613        Some(cfg) => cfg,
614        None => {
615            tracing::debug!("No router config found — router/auto will not appear in model list");
616            return;
617        }
618    };
619
620    // Register router models only when configured.
621    oxicode_sdk::register_model(oxicode_sdk::Model::new(
622        "auto",
623        "Router (auto)".to_string(),
624        oxicode_sdk::Api::AnthropicMessages,
625        "router",
626        "router://local",
627    ));
628
629    // Convert store config to AI config.
630    let mut ai_profiles = std::collections::HashMap::new();
631    for (name, sp) in store_cfg.profiles() {
632        fn parse_thinking(s: &Option<String>) -> Option<oxicode_sdk::ThinkingLevel> {
633            s.as_ref().and_then(|s| match s.as_str() {
634                "off" => Some(oxicode_sdk::ThinkingLevel::Off),
635                "minimal" => Some(oxicode_sdk::ThinkingLevel::Minimal),
636                "low" => Some(oxicode_sdk::ThinkingLevel::Low),
637                "medium" => Some(oxicode_sdk::ThinkingLevel::Medium),
638                "high" => Some(oxicode_sdk::ThinkingLevel::High),
639                "xhigh" => Some(oxicode_sdk::ThinkingLevel::XHigh),
640                _ => None,
641            })
642        }
643        ai_profiles.insert(
644            name.clone(),
645            oxicode_sdk::router::RouterProfile {
646                high: oxicode_sdk::router::RoutedTierConfig {
647                    model: sp.high.model.clone(),
648                    thinking: parse_thinking(&sp.high.thinking),
649                    fallbacks: sp.high.fallbacks.clone(),
650                },
651                medium: oxicode_sdk::router::RoutedTierConfig {
652                    model: sp.medium.model.clone(),
653                    thinking: parse_thinking(&sp.medium.thinking),
654                    fallbacks: sp.medium.fallbacks.clone(),
655                },
656                low: oxicode_sdk::router::RoutedTierConfig {
657                    model: sp.low.model.clone(),
658                    thinking: parse_thinking(&sp.low.thinking),
659                    fallbacks: sp.low.fallbacks.clone(),
660                },
661            },
662        );
663    }
664    let ai_cfg = oxicode_sdk::router::RouterConfig::with_pinning(
665        store_cfg.default_profile().to_string(),
666        store_cfg.classifier_model().map(String::from),
667        store_cfg.context_upgrade_threshold(),
668        store_cfg.max_session_budget(),
669        ai_profiles,
670        oxicode_sdk::router::ScoringWeights {
671            structural: store_cfg.weights().structural,
672            behavioral: store_cfg.weights().behavioral,
673            context_budget: store_cfg.weights().context_budget,
674            vision: store_cfg.weights().vision,
675            message: store_cfg.weights().message,
676        },
677        store_cfg.pin_tier().and_then(|s| match s {
678            "high" => Some(oxicode_sdk::router::RouterTier::High),
679            "medium" => Some(oxicode_sdk::router::RouterTier::Medium),
680            "low" => Some(oxicode_sdk::router::RouterTier::Low),
681            _ => None,
682        }),
683        store_cfg.phase_bias(),
684    );
685
686    oxicode_sdk::router::register_router(&ai_cfg);
687}
688
689/// Decide whether this run is the TUI (interactive) mode. Mirrors the
690/// dispatch in [`dispatch_run_mode`]: print / RPC / single-prompt are
691/// non-TUI. Used by [`build_app`] to pick the canonical liveness identity.
692fn is_tui_mode(args: &CliArgs) -> bool {
693    if matches!(args.mode.as_deref(), Some("json" | "rpc")) || args.print {
694        return false;
695    }
696    // prompt-only (no `--interactive` and a non-empty prompt) is non-TUI too;
697    // dispatch_run_mode sends it through main_dispatch::run_single_prompt.
698    // NOTE: must join the prompt Vec — clap's `default_value = ""` on the
699    // positional makes bare `oxicode` yield `prompt == vec![""]` (non-empty Vec,
700    // empty join). Comparing the Vec directly would mis-classify the bare
701    // interactive launch as a single-prompt run.
702    let prompt = args.prompt.join(" ");
703    if !args.interactive && !prompt.is_empty() {
704        return false;
705    }
706    true
707}
708#[cfg(test)]
709mod tests {
710    use super::*;
711    use clap::Parser;
712
713    #[test]
714    fn rpc_mode_is_headless() {
715        let args = CliArgs::try_parse_from(["oxicode", "--mode", "rpc"]).unwrap();
716        assert!(!is_tui_mode(&args));
717    }
718
719    #[test]
720    fn empty_hooks_does_not_block() {
721        use crate::store::settings::Settings;
722        let s = Settings::default();
723        assert!(s.hooks.is_empty());
724    }
725}