Skip to main content

oxi/
lib.rs

1#![warn(missing_docs)]
2// Relax two test-idiom lints under `cfg(test)` so `cargo clippy --all-targets`
3// stays clean without weakening the shipped library:
4//   - `clippy::unwrap_used` — `unwrap()`/`unwrap_err()` are idiomatic in tests;
5//     shipped (non-test) code still `warn`s on it (see the line below).
6//   - `clippy::field_reassign_with_default` — the `let mut x = X::default();
7//     x.f = ..;` test-setup pattern.
8#![warn(clippy::unwrap_used)]
9#![cfg_attr(test, allow(clippy::unwrap_used, clippy::field_reassign_with_default))]
10#![allow(unknown_lints)]
11
12//! oxi: CLI coding harness
13//!
14//! This crate provides the main application logic for the oxi CLI.
15
16// ─── Root-level entry modules ───────────────────────────────────────────────
17// cli must be pub for main.rs binary
18pub mod bootstrap;
19pub mod cli;
20pub mod internal_urls;
21pub mod lsp;
22pub mod main_dispatch;
23pub mod mcp_credentials;
24pub mod print_mode;
25pub mod services;
26pub mod setup_wizard;
27pub mod store;
28
29// ─── Directory groups ───────────────────────────────────────────────────────
30pub(crate) mod app;
31pub(crate) mod context;
32pub mod discovery;
33pub mod extensions; // public for main.rs
34pub(crate) mod infra;
35pub(crate) mod media;
36pub(crate) mod prompt;
37pub mod rpc_mode;
38pub(crate) mod skills;
39pub mod storage; // public for main.rs (packages)
40// Re-exports from storage for main.rs
41pub use storage::packages::PackageManager;
42pub use storage::packages::ResourceKind;
43pub mod tools;
44pub mod tui; // public for main.rs
45pub(crate) mod ui;
46pub(crate) mod util;
47
48///
49/// This is the **new entry point** for oxi-cli run modes. It uses
50/// `oxi-fs` adapters and `OxiBuilder::with_port_*` to construct an
51/// `Oxi` with persistence, auth, config, and skills wired. The legacy
52/// `App::new` path is still used by the interactive TUI during the
53/// migration period.
54///
55/// # Example
56///
57/// ```no_run
58/// use oxi::build_oxi_engine;
59/// # async fn _example() -> anyhow::Result<()> {
60/// let oxi = build_oxi_engine().await?;
61/// println!("providers: {}", oxi.providers().names().len());
62/// # Ok(()) }
63/// ```
64pub async fn build_oxi_engine() -> anyhow::Result<oxi_sdk::Oxi> {
65    let paths = services::OxiPaths::default_paths()?;
66    services::build_oxi(&paths).await
67}
68
69/// Self-check the wired port implementations. Prints a one-line summary
70/// per port and returns `Ok(())` if all are reachable.
71///
72/// Triggered by the `OXI_PORT_CHECK=1` environment variable from
73/// `oxi-cli/src/main.rs`. Useful for verifying the new composition root
74/// without disturbing the legacy `App::new` path.
75pub async fn run_port_check() -> anyhow::Result<()> {
76    let oxi = build_oxi_engine().await?;
77    let ports = oxi.ports();
78
79    // State
80    let entries = ports.state.list("").await?;
81    println!("[state]    entries: {}", entries.len());
82
83    // Auth
84    let providers = ports.auth.list_providers().await?;
85    println!("[auth]     providers with credentials: {:?}", providers);
86
87    // Config
88    let keys = ports.config.list()?;
89    println!("[config]   keys: {}", keys.len());
90
91    // Skills
92    let skills = ports.skills.list().await?;
93    println!("[skills]   {} skill(s) discovered", skills.len());
94    for s in &skills {
95        println!("           - {}: {}", s.name, s.description);
96    }
97
98    // Event bus / memory / etc — all noop unless registered
99    let _ = ports
100        .event_bus
101        .publish(&"port-check".to_string(), serde_json::json!({"ok": true}))
102        .await;
103    println!("[event-bus] publish ok (noop bus if not registered)");
104
105    println!("\nport check: ok");
106    Ok(())
107}
108
109/// Context for compaction operations, passed to extension hooks
110#[derive(Debug, Clone)]
111pub struct CompactionContext {
112    /// Messages being compacted
113    pub messages_count: usize,
114    /// Estimated tokens before compaction
115    pub tokens_before: usize,
116    /// Target token count after compaction
117    pub target_tokens: usize,
118    /// Strategy being used
119    pub strategy: String,
120}
121
122impl CompactionContext {
123    /// Create a new compaction context
124    pub fn new(
125        messages_count: usize,
126        tokens_before: usize,
127        target_tokens: usize,
128        strategy: impl Into<String>,
129    ) -> Self {
130        Self {
131            messages_count,
132            tokens_before,
133            target_tokens,
134            strategy: strategy.into(),
135        }
136    }
137
138    /// Get expected compression ratio
139    pub fn compression_ratio(&self) -> f32 {
140        if self.tokens_before == 0 {
141            return 1.0;
142        }
143        self.target_tokens as f32 / self.tokens_before as f32
144    }
145}
146
147// ─── Module-level imports ────────────────────────────────────────────────────
148use crate::store::settings::Settings;
149use anyhow::{Error, Result};
150use oxi_agent::{Agent, AgentConfig, AgentEvent};
151use parking_lot::RwLock;
152use skills::SkillManager;
153use std::sync::Arc;
154
155// ─── Application state ───────────────────────────────────────────────────────
156
157/// Application state and entry point.
158///
159/// Holds an `Oxi` engine (composition root) and a single `Agent` built
160/// from it. The legacy `App::new(settings)` constructor is **gone**;
161/// use [`App::from_oxi`] with a wired `Oxi` from
162/// [`build_oxi_engine`].
163pub struct App {
164    oxi: oxi_sdk::Oxi,
165    agent: Arc<Agent>,
166    settings: Settings,
167    skills: RwLock<SkillManager>,
168    active_skills: RwLock<Vec<String>>,
169    wasm_ext: Option<std::sync::Arc<crate::extensions::WasmExtensionManager>>,
170    ask_bridge: Option<std::sync::Arc<oxi_agent::tools::ask::AskBridge>>,
171    /// Shared local issue store (`.oxi/issues/`). Cloned cheaply (inner `Arc`).
172    /// Used by the agent `issue` tool, the TUI indicator, and the `oxi issue`
173    /// CLI subcommand.
174    issue_store: Option<crate::store::issues::FileIssueStore>,
175    /// Process-wide liveness identity used by every issue-ownership surface
176    /// in this process (agent tool's `ToolContext.session_id`, TUI panel,
177    /// slash-command `/issue` handlers). See
178    /// [`crate::store::issues::liveness::TUI_OWNERSHIP_ID`] for the TUI value.
179    ownership_session_id: String,
180    /// Alive-lock held for the lifetime of `App`. Dropped with `App`, releasing
181    /// the OS-held flock so any other process sees this session as dead once
182    /// we exit (including `kill -9` / crash / normal exit). Only held when
183    /// `issue_store` is available.
184    #[allow(dead_code)]
185    liveness_guard: Option<crate::store::issues::liveness::AliveGuard>,
186}
187
188/// Context for compaction operations, passed to extension hooks
189// ─── System prompt builder ───────────────────────────────────────────────────
190fn build_system_prompt(
191    thinking_level: crate::store::settings::ThinkingLevel,
192    skill_contents: &[String],
193) -> String {
194    let skills: Vec<prompt::system_prompt::Skill> = skill_contents
195        .iter()
196        .enumerate()
197        .map(|(i, content)| prompt::system_prompt::Skill {
198            name: format!("skill-{}", i),
199            content: content.clone(),
200        })
201        .collect();
202
203    let options = prompt::system_prompt::BuildSystemPromptOptions {
204        custom_prompt: prompt::system_prompt::thinking_level_prompt(thinking_level),
205        skills,
206        cwd: std::env::current_dir()
207            .map(|p| p.to_string_lossy().to_string())
208            .unwrap_or_default(),
209        ..Default::default()
210    };
211
212    prompt::system_prompt::build_system_prompt(&options)
213}
214
215// ─── App implementation ─────────────────────────────────────────────────────
216
217impl App {
218    /// Build an `App` from a wired `Oxi` engine and a settings object.
219    ///
220    /// The `Oxi` should be created via [`build_oxi_engine`] (or
221    /// `services::build_oxi`) so that all 11 ports are wired. The
222    /// settings hold the user's runtime configuration (model, thinking
223    /// level, etc.).
224    ///
225    /// `ownership_session_id` is the per-process liveness identity used by
226    /// the agent's `issue` tool (`ToolContext.session_id`), the TUI panel,
227    /// and the `/issue` slash command. In TUI mode this MUST equal
228    /// [`crate::store::issues::liveness::TUI_OWNERSHIP_ID`] so the panel and
229    /// agent see the same flock holder. In print / RPC mode, a stable
230    /// process-scoped id (e.g. `proc-<pid>-<uuid>`) is appropriate.
231    /// When `issue_store` is available, an `flock` is acquired under this
232    /// id for the lifetime of the returned `App`.
233    pub async fn from_oxi(
234        oxi: oxi_sdk::Oxi,
235        settings: Settings,
236        ownership_session_id: String,
237    ) -> Result<Self> {
238        let model_id = settings.effective_model(None).unwrap_or_default();
239        // Provider-name and api_key lookups removed in 0.55.0 — the SDK
240        // resolver consults the wired AuthProvider port directly.
241
242        let skills_dir = SkillManager::skills_dir().unwrap_or_else(|_| {
243            dirs::home_dir()
244                .unwrap_or_default()
245                .join(".oxi")
246                .join("skills")
247        });
248        let skills = SkillManager::load_from_dir(&skills_dir).unwrap_or_else(|e| {
249            tracing::debug!("Skills not loaded: {}", e);
250            SkillManager::new()
251        });
252
253        let system_prompt = build_system_prompt(settings.thinking_level, &[]);
254        let compaction_strategy = if settings.auto_compaction {
255            oxi_sdk::CompactionStrategy::Threshold(0.8)
256        } else {
257            oxi_sdk::CompactionStrategy::Disabled
258        };
259
260        let config = AgentConfig {
261            name: "oxi".to_string(),
262            description: Some("oxi CLI agent".to_string()),
263            model_id: model_id.clone(),
264            system_prompt: Some(system_prompt),
265            timeout_seconds: settings.tool_timeout_seconds,
266            temperature: settings.effective_temperature(),
267            max_tokens: settings.effective_max_tokens(),
268            compaction_strategy,
269            compaction_instruction: None,
270            context_window: 128_000,
271            workspace_dir: Some(
272                std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),
273            ),
274            output_mode: None,
275            provider_options: None,
276            session_id: Some(ownership_session_id.clone()),
277            ttsr_engine: None,
278            memory: None,
279            todo: None,
280            agent_pool: None,
281            url_resolver: Some(Arc::new(oxi_sdk::SdkUrlResolver::new(
282                oxi.ports().url_router.clone(),
283            ))),
284            // LSP: lazy-spawn rust-analyzer (or other configured
285            // servers) on first request. When no servers are
286            // configured for the workspace, the field stays `None`
287            // and AgentBuilder.build() drops the `lsp` tool from
288            // the registry (see agent_builder.rs::build).
289            lsp: if crate::lsp::manager::default_servers().is_empty() {
290                None
291            } else {
292                Some(Arc::new(crate::lsp::CliLspProvider::with_defaults(
293                    std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),
294                )))
295            },
296            ..Default::default()
297        };
298
299        // Build the agent via the SDK's AgentBuilder — no manual wiring.
300        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
301        let agent = oxi
302            .agent(config)
303            .workspace(cwd)
304            .build()
305            .map_err(|e| Error::msg(format!("agent build failed: {e}")))?;
306        let agent = Arc::new(agent);
307
308        let ask_timeout = if settings.ask_timeout_secs > 0 {
309            Some(std::time::Duration::from_secs(settings.ask_timeout_secs))
310        } else {
311            None
312        };
313        let bridge =
314            std::sync::Arc::new(oxi_agent::tools::ask::AskBridge::with_timeout(ask_timeout));
315        let ask_tool = oxi_agent::tools::ask::AskTool::new(bridge.clone());
316        agent.tools().register_arc(std::sync::Arc::new(ask_tool));
317        // Open the local issue store rooted at the project (`.oxi/issues/`).
318        // Best-effort: if the directory cannot be resolved, issues are simply
319        // unavailable — the app still works without them. The `/issue` slash
320        // command surfaces a clear error in that case.
321        let issue_store = std::env::current_dir()
322            .ok()
323            .map(|cwd| crate::store::issues::FileIssueStore::open_from_cwd(&cwd))
324            .and_then(|r| {
325                r.map_err(|e| tracing::warn!("issue store unavailable: {e}"))
326                    .ok()
327            });
328
329        // Register the `issue` agent tool when the store is available.
330        if let Some(store) = issue_store.clone() {
331            let tool = std::sync::Arc::new(crate::tools::IssueTool::new(store));
332            agent.tools().register_arc(tool);
333        }
334
335        Ok(Self {
336            oxi,
337            agent,
338            settings,
339            skills: RwLock::new(skills),
340            active_skills: RwLock::new(Vec::new()),
341            wasm_ext: None,
342            ask_bridge: Some(bridge),
343            issue_store,
344            ownership_session_id,
345            liveness_guard: None, // set below once issue_store is known
346        })
347        .map(|mut app| {
348            // Acquire the process-wide liveness flock now that issue_store exists.
349            // Best-effort: another live process already holds the lock is non-fatal;
350            // we still expose ownership_session_id so callers can detect the conflict.
351            app.liveness_guard =
352                acquire_ownership_guard(app.issue_store.as_ref(), &app.ownership_session_id);
353            app
354        })
355    }
356
357    /// Per-process liveness identity. Used by the agent's `issue` tool and any
358    /// other surface that gates on `is_session_alive`.
359    pub fn ownership_session_id(&self) -> &str {
360        &self.ownership_session_id
361    }
362
363    /// True iff `App` holds a live liveness flock under `ownership_session_id`.
364    /// False when there is no `issue_store` (e.g. headless test) or when another
365    /// live process already holds the lock (the assignment feature will surface
366    /// `Assigned` errors in that case — by design).
367    pub fn has_liveness_lock(&self) -> bool {
368        self.liveness_guard.is_some()
369    }
370
371    /// Get the current settings
372    pub fn settings(&self) -> &Settings {
373        &self.settings
374    }
375
376    /// Set the WASM extension manager
377    pub fn set_wasm_ext(
378        &mut self,
379        ext: Option<std::sync::Arc<crate::extensions::WasmExtensionManager>>,
380    ) {
381        self.wasm_ext = ext;
382    }
383
384    /// Get the WASM extension manager
385    pub fn wasm_ext(&self) -> Option<&std::sync::Arc<crate::extensions::WasmExtensionManager>> {
386        self.wasm_ext.as_ref()
387    }
388
389    /// Get a clone of the local issue store, if one was opened successfully.
390    pub fn issue_store(&self) -> Option<crate::store::issues::FileIssueStore> {
391        self.issue_store.clone()
392    }
393
394    /// Get a reference to the underlying `Oxi` engine. The catalog port and
395    /// other ports are accessible through it.
396    pub fn oxi(&self) -> &oxi_sdk::Oxi {
397        &self.oxi
398    }
399
400    /// Get a reference to the underlying agent.
401    pub fn agent(&self) -> Arc<Agent> {
402        Arc::clone(&self.agent)
403    }
404
405    /// Get the tool registry (for registering extension tools)
406    pub fn agent_tools(&self) -> Arc<oxi_agent::ToolRegistry> {
407        self.agent.tools()
408    }
409
410    /// Get the ask bridge, if initialized.
411    pub fn ask_bridge(&self) -> Option<&std::sync::Arc<oxi_agent::tools::ask::AskBridge>> {
412        self.ask_bridge.as_ref()
413    }
414
415    /// Get a reference to the skill manager
416    pub fn skills(&self) -> parking_lot::RwLockReadGuard<'_, SkillManager> {
417        self.skills.read()
418    }
419
420    /// Activate a skill by name. Returns an error string if not found.
421    pub fn activate_skill(&self, name: &str) -> Result<(), String> {
422        {
423            let skills = self.skills.read();
424            if skills.get(name).is_none() {
425                return Err(format!("Skill '{}' not found", name));
426            }
427        }
428        let name_lower = name.to_lowercase();
429        {
430            let mut active = self.active_skills.write();
431            if !active.contains(&name_lower) {
432                active.push(name_lower);
433            }
434        }
435        self.rebuild_system_prompt();
436        Ok(())
437    }
438
439    /// Deactivate a skill by name.
440    pub fn deactivate_skill(&self, name: &str) {
441        let name_lower = name.to_lowercase();
442        {
443            let mut active = self.active_skills.write();
444            active.retain(|n| n != &name_lower);
445        }
446        self.rebuild_system_prompt();
447    }
448
449    /// List currently active skill names
450    pub fn active_skills(&self) -> Vec<String> {
451        self.active_skills.read().clone()
452    }
453
454    /// Rebuild the system prompt with current active skills
455    fn rebuild_system_prompt(&self) {
456        let active = self.active_skills.read();
457        let skills = self.skills.read();
458        let contents: Vec<String> = active
459            .iter()
460            .filter_map(|name| skills.get(name).map(|s| s.content.clone()))
461            .collect();
462        let prompt = build_system_prompt(self.settings.thinking_level, &contents);
463        self.agent.set_system_prompt(prompt);
464    }
465
466    /// Get a clone of the current state
467    pub fn agent_state(&self) -> oxi_agent::AgentState {
468        self.agent.state()
469    }
470
471    /// Run a single prompt and return the response
472    pub async fn run_prompt(&self, prompt: String) -> Result<String> {
473        let (response, _events) = self.agent.run(prompt).await?;
474        Ok(response.content)
475    }
476
477    /// Run a prompt with event callback
478    pub async fn run_prompt_with_events<F>(&self, prompt: String, on_event: F) -> Result<String>
479    where
480        F: FnMut(AgentEvent) + Send + 'static,
481    {
482        self.agent.run_streaming(prompt, on_event).await?;
483        let state = self.agent_state();
484        for msg in state.messages.iter().rev() {
485            if let oxi_sdk::Message::Assistant(a) = msg {
486                return Ok(a.text_content());
487            }
488        }
489        Ok(String::new())
490    }
491
492    /// Reset the conversation
493    pub fn reset(&self) {
494        self.agent.reset();
495    }
496
497    /// Switch the model used for future LLM calls.
498    ///
499    /// The new provider is re-credentialed by the SDK resolver via the
500    /// wired AuthProvider port; the `api_key` parameter was removed in
501    /// 0.55.0 (issues #39/#40).
502    pub async fn switch_model(&self, model_id: &str) -> anyhow::Result<()> {
503        let _ = self.agent.switch_model(model_id);
504        Ok(())
505    }
506
507    /// Get the current model ID
508    pub fn model_id(&self) -> String {
509        self.agent.model_id()
510    }
511}
512
513/// Acquire the process-wide liveness flock for `ownership_id` under the issue
514/// store's `.alive/` directory.
515///
516/// Returns `None` (no lock) when there is no issue store or when another live
517/// process already holds the lock — both non-fatal; the caller can still read
518/// `ownership_session_id` and the assignment feature will surface `Assigned`
519/// errors if contention actually occurs.
520///
521/// Extracted from `App::from_oxi` so the single-lock invariant (defect #13 fix)
522/// can be unit-tested without standing up a full `Oxi` engine.
523pub(crate) fn acquire_ownership_guard(
524    issue_store: Option<&crate::store::issues::FileIssueStore>,
525    ownership_id: &str,
526) -> Option<crate::store::issues::liveness::AliveGuard> {
527    let store = issue_store?;
528    if ownership_id.is_empty() {
529        // Defensive: never hold a lock under the empty string — that was the
530        // #13 bug shape (empty owner is never alive, so ownership was bypassed).
531        return None;
532    }
533    crate::store::issues::liveness::acquire(&store.issues_dir(), ownership_id).ok()
534}
535
536#[cfg(test)]
537mod tests {
538    //! P0 regression: `App` must hold exactly one liveness flock under its
539    //! ownership identity. We test the extracted `acquire_ownership_guard`
540    //! helper (the single chokepoint `from_oxi` delegates to) rather than
541    //! standing up a full `Oxi` engine.
542    use super::*;
543    use crate::store::issues::FileIssueStore;
544    use crate::store::issues::liveness;
545
546    fn tmp_store() -> (tempfile::TempDir, FileIssueStore) {
547        let tmp = tempfile::tempdir().unwrap();
548        let dir = tmp.path().join(".oxi").join("issues");
549        std::fs::create_dir_all(&dir).unwrap();
550        (tmp, FileIssueStore::open(dir).unwrap())
551    }
552
553    #[test]
554    fn app_holds_single_liveness_lock() {
555        // The #13 invariant: acquiring the ownership guard makes the session
556        // live under that identity, and a second acquire under the SAME id
557        // fails (one flock per identity — single lock).
558        let (_tmp, store) = tmp_store();
559        let dir = store.issues_dir();
560        let id = "proc-test-app";
561
562        let guard = acquire_ownership_guard(Some(&store), id);
563        assert!(
564            guard.is_some(),
565            "App must acquire the liveness lock for its ownership id"
566        );
567        assert!(
568            liveness::is_session_alive(&dir, id),
569            "after acquire, the session must be live"
570        );
571
572        // While held, the same identity cannot be acquired again — single lock.
573        let second = liveness::acquire(&dir, id);
574        assert!(second.is_err(), "second acquire under same id must fail");
575
576        drop(guard);
577        assert!(
578            !liveness::is_session_alive(&dir, id),
579            "dropping App's guard releases the lock"
580        );
581    }
582
583    #[test]
584    fn acquire_returns_none_without_store() {
585        // No issue store (headless/test) → no lock. Not an error.
586        let dir = tempfile::tempdir().unwrap();
587        let id = "proc-x";
588        assert!(acquire_ownership_guard(None, id).is_none());
589        let _ = dir; // no store created
590    }
591
592    #[test]
593    fn acquire_rejects_empty_ownership_id() {
594        // Defensive guard against the #13 bug shape: never hold a lock under
595        // the empty string (it's never alive, so ownership would be bypassed).
596        let (_tmp, store) = tmp_store();
597        assert!(
598            acquire_ownership_guard(Some(&store), "").is_none(),
599            "empty ownership id must never acquire a lock (#13 guard)"
600        );
601    }
602}