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