Skip to main content

oxi/
lib.rs

1#![warn(missing_docs)]
2#![warn(clippy::unwrap_used)]
3#![allow(unknown_lints)]
4
5//! oxi: CLI coding harness
6//!
7//! This crate provides the main application logic for the oxi CLI.
8
9// ─── Root-level entry modules ───────────────────────────────────────────────
10// cli must be pub for main.rs binary
11pub mod bootstrap;
12pub mod cli;
13pub mod main_dispatch;
14pub mod print_mode;
15pub mod services;
16pub mod setup_wizard;
17pub mod store;
18
19// ─── Directory groups ───────────────────────────────────────────────────────
20pub(crate) mod app;
21pub(crate) mod context;
22pub mod extensions; // public for main.rs
23pub(crate) mod infra;
24pub(crate) mod media;
25pub(crate) mod prompt;
26pub(crate) mod rpc_mode;
27pub(crate) mod skills;
28pub mod storage; // public for main.rs (packages)
29                 // Re-exports from storage for main.rs
30pub use storage::packages::PackageManager;
31pub use storage::packages::ResourceKind;
32pub mod tui; // public for main.rs
33pub(crate) mod ui;
34pub(crate) mod util;
35
36///
37/// This is the **new entry point** for oxi-cli run modes. It uses
38/// `oxi-fs` adapters and `OxiBuilder::with_port_*` to construct an
39/// `Oxi` with persistence, auth, config, and skills wired. The legacy
40/// `App::new` path is still used by the interactive TUI during the
41/// migration period.
42///
43/// # Example
44///
45/// ```no_run
46/// use oxi::build_oxi_engine;
47/// # fn _example() -> anyhow::Result<()> {
48/// let oxi = build_oxi_engine()?;
49/// println!("providers: {}", oxi.providers().names().len());
50/// # Ok(()) }
51/// ```
52pub fn build_oxi_engine() -> anyhow::Result<oxi_sdk::Oxi> {
53    let paths = services::OxiPaths::default_paths()?;
54    services::build_oxi(&paths)
55}
56
57/// Self-check the wired port implementations. Prints a one-line summary
58/// per port and returns `Ok(())` if all are reachable.
59///
60/// Triggered by the `OXI_PORT_CHECK=1` environment variable from
61/// `oxi-cli/src/main.rs`. Useful for verifying the new composition root
62/// without disturbing the legacy `App::new` path.
63pub async fn run_port_check() -> anyhow::Result<()> {
64    let oxi = build_oxi_engine()?;
65    let ports = oxi.ports();
66
67    // State
68    let entries = ports.state.list("").await?;
69    println!("[state]    entries: {}", entries.len());
70
71    // Auth
72    let providers = ports.auth.list_providers().await?;
73    println!("[auth]     providers with credentials: {:?}", providers);
74
75    // Config
76    let keys = ports.config.list()?;
77    println!("[config]   keys: {}", keys.len());
78
79    // Skills
80    let skills = ports.skills.list().await?;
81    println!("[skills]   {} skill(s) discovered", skills.len());
82    for s in &skills {
83        println!("           - {}: {}", s.name, s.description);
84    }
85
86    // Event bus / memory / etc — all noop unless registered
87    let _ = ports.event_bus.publish(&"port-check".to_string(), serde_json::json!({"ok": true})).await;
88    println!("[event-bus] publish ok (noop bus if not registered)");
89
90    println!("\nport check: ok");
91    Ok(())
92}
93
94/// Context for compaction operations, passed to extension hooks
95#[derive(Debug, Clone)]
96pub struct CompactionContext {
97    /// Messages being compacted
98    pub messages_count: usize,
99    /// Estimated tokens before compaction
100    pub tokens_before: usize,
101    /// Target token count after compaction
102    pub target_tokens: usize,
103    /// Strategy being used
104    pub strategy: String,
105}
106
107impl CompactionContext {
108    /// Create a new compaction context
109    pub fn new(
110        messages_count: usize,
111        tokens_before: usize,
112        target_tokens: usize,
113        strategy: impl Into<String>,
114    ) -> Self {
115        Self {
116            messages_count,
117            tokens_before,
118            target_tokens,
119            strategy: strategy.into(),
120        }
121    }
122
123    /// Get expected compression ratio
124    pub fn compression_ratio(&self) -> f32 {
125        if self.tokens_before == 0 {
126            return 1.0;
127        }
128        self.target_tokens as f32 / self.tokens_before as f32
129    }
130}
131
132// ─── Module-level imports ────────────────────────────────────────────────────
133use crate::store::settings::Settings;
134use anyhow::{Error, Result};
135use oxi_agent::{Agent, AgentConfig, AgentEvent};
136use parking_lot::RwLock;
137use skills::SkillManager;
138use std::sync::Arc;
139
140// ─── Application state ───────────────────────────────────────────────────────
141
142/// Application state and entry point.
143///
144/// Holds an `Oxi` engine (composition root) and a single `Agent` built
145/// from it. The legacy `App::new(settings)` constructor is **gone**;
146/// use [`App::from_oxi`] with a wired `Oxi` from
147/// [`build_oxi_engine`].
148pub struct App {
149    oxi: oxi_sdk::Oxi,
150    agent: Arc<Agent>,
151    settings: Settings,
152    skills: RwLock<SkillManager>,
153    active_skills: RwLock<Vec<String>>,
154    wasm_ext: Option<std::sync::Arc<crate::extensions::WasmExtensionManager>>,
155    questionnaire_bridge:
156        Option<std::sync::Arc<oxi_agent::tools::questionnaire::QuestionnaireBridge>>,
157}
158
159/// Context for compaction operations, passed to extension hooks// ─── System prompt builder ───────────────────────────────────────────────────
160
161fn build_system_prompt(
162    thinking_level: crate::store::settings::ThinkingLevel,
163    skill_contents: &[String],
164) -> String {
165    let skills: Vec<prompt::system_prompt::Skill> = skill_contents
166        .iter()
167        .enumerate()
168        .map(|(i, content)| prompt::system_prompt::Skill {
169            name: format!("skill-{}", i),
170            content: content.clone(),
171        })
172        .collect();
173
174    let options = prompt::system_prompt::BuildSystemPromptOptions {
175        custom_prompt: prompt::system_prompt::thinking_level_prompt(thinking_level),
176        skills,
177        cwd: std::env::current_dir()
178            .map(|p| p.to_string_lossy().to_string())
179            .unwrap_or_default(),
180        ..Default::default()
181    };
182
183    prompt::system_prompt::build_system_prompt(&options)
184}
185
186// ─── App implementation ─────────────────────────────────────────────────────
187
188impl App {
189    /// Build an `App` from a wired `Oxi` engine and a settings object.
190    ///
191    /// The `Oxi` should be created via [`build_oxi_engine`] (or
192    /// `services::build_oxi`) so that all 11 ports are wired. The
193    /// settings hold the user's runtime configuration (model, thinking
194    /// level, etc.).
195    pub async fn from_oxi(oxi: oxi_sdk::Oxi, settings: Settings) -> Result<Self> {
196        let model_id = settings.effective_model(None).unwrap_or_default();
197        let provider_name = settings
198            .effective_provider(None)
199            .unwrap_or_else(|| model_id.split('/').next().unwrap_or("").to_string());
200
201        // Pull the API key from the wired port, not from oxi_store.
202        let api_key = oxi.ports().auth.get_api_key(&provider_name).await?;
203
204        let skills_dir = SkillManager::skills_dir().unwrap_or_else(|_| {
205            dirs::home_dir()
206                .unwrap_or_default()
207                .join(".oxi")
208                .join("skills")
209        });
210        let skills = SkillManager::load_from_dir(&skills_dir).unwrap_or_else(|e| {
211            tracing::debug!("Skills not loaded: {}", e);
212            SkillManager::new()
213        });
214
215        let system_prompt = build_system_prompt(settings.thinking_level, &[]);
216        let compaction_strategy = if settings.auto_compaction {
217            oxi_sdk::CompactionStrategy::Threshold(0.8)
218        } else {
219            oxi_sdk::CompactionStrategy::Disabled
220        };
221
222        let config = AgentConfig {
223            name: "oxi".to_string(),
224            description: Some("oxi CLI agent".to_string()),
225            model_id: model_id.clone(),
226            system_prompt: Some(system_prompt),
227            max_iterations: 10,
228            timeout_seconds: settings.tool_timeout_seconds,
229            temperature: settings.effective_temperature(),
230            max_tokens: settings.effective_max_tokens(),
231            compaction_strategy,
232            compaction_instruction: None,
233            context_window: 128_000,
234            api_key,
235            workspace_dir: Some(
236                std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),
237            ),
238            output_mode: None,
239            provider_options: None,
240        };
241
242        // Build the agent via the SDK's AgentBuilder — no manual wiring.
243        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
244        let agent = oxi
245            .agent(config)
246            .workspace(cwd)
247            .build()
248            .map_err(|e| Error::msg(format!("agent build failed: {e}")))?;
249        let agent = Arc::new(agent);
250
251        let bridge =
252            std::sync::Arc::new(oxi_agent::tools::questionnaire::QuestionnaireBridge::new());
253        let questionnaire_tool =
254            oxi_agent::tools::questionnaire::QuestionnaireTool::new(bridge.clone());
255        agent
256            .tools()
257            .register_arc(std::sync::Arc::new(questionnaire_tool));
258
259        Ok(Self {
260            oxi,
261            agent,
262            settings,
263            skills: RwLock::new(skills),
264            active_skills: RwLock::new(Vec::new()),
265            wasm_ext: None,
266            questionnaire_bridge: Some(bridge),
267        })
268    }
269
270    /// Get the current settings
271    pub fn settings(&self) -> &Settings {
272        &self.settings
273    }
274
275    /// Set the WASM extension manager
276    pub fn set_wasm_ext(
277        &mut self,
278        ext: Option<std::sync::Arc<crate::extensions::WasmExtensionManager>>,
279    ) {
280        self.wasm_ext = ext;
281    }
282
283    /// Get the WASM extension manager
284    pub fn wasm_ext(&self) -> Option<&std::sync::Arc<crate::extensions::WasmExtensionManager>> {
285        self.wasm_ext.as_ref()
286    }
287
288    /// Get a reference to the underlying agent.
289    pub fn agent(&self) -> Arc<Agent> {
290        Arc::clone(&self.agent)
291    }
292
293    /// Get the tool registry (for registering extension tools)
294    pub fn agent_tools(&self) -> Arc<oxi_agent::ToolRegistry> {
295        self.agent.tools()
296    }
297
298    /// Get the questionnaire bridge, if initialized.
299    pub fn questionnaire_bridge(
300        &self,
301    ) -> Option<&std::sync::Arc<oxi_agent::tools::questionnaire::QuestionnaireBridge>> {
302        self.questionnaire_bridge.as_ref()
303    }
304
305    /// Get a reference to the skill manager
306    pub fn skills(&self) -> parking_lot::RwLockReadGuard<'_, SkillManager> {
307        self.skills.read()
308    }
309
310    /// Activate a skill by name. Returns an error string if not found.
311    pub fn activate_skill(&self, name: &str) -> Result<(), String> {
312        {
313            let skills = self.skills.read();
314            if skills.get(name).is_none() {
315                return Err(format!("Skill '{}' not found", name));
316            }
317        }
318        let name_lower = name.to_lowercase();
319        {
320            let mut active = self.active_skills.write();
321            if !active.contains(&name_lower) {
322                active.push(name_lower);
323            }
324        }
325        self.rebuild_system_prompt();
326        Ok(())
327    }
328
329    /// Deactivate a skill by name.
330    pub fn deactivate_skill(&self, name: &str) {
331        let name_lower = name.to_lowercase();
332        {
333            let mut active = self.active_skills.write();
334            active.retain(|n| n != &name_lower);
335        }
336        self.rebuild_system_prompt();
337    }
338
339    /// List currently active skill names
340    pub fn active_skills(&self) -> Vec<String> {
341        self.active_skills.read().clone()
342    }
343
344    /// Rebuild the system prompt with current active skills
345    fn rebuild_system_prompt(&self) {
346        let active = self.active_skills.read();
347        let skills = self.skills.read();
348        let contents: Vec<String> = active
349            .iter()
350            .filter_map(|name| skills.get(name).map(|s| s.content.clone()))
351            .collect();
352        let prompt = build_system_prompt(self.settings.thinking_level, &contents);
353        self.agent.set_system_prompt(prompt);
354    }
355
356    /// Get a clone of the current state
357    pub fn agent_state(&self) -> oxi_agent::AgentState {
358        self.agent.state()
359    }
360
361    /// Run a single prompt and return the response
362    pub async fn run_prompt(&self, prompt: String) -> Result<String> {
363        let (response, _events) = self.agent.run(prompt).await?;
364        Ok(response.content)
365    }
366
367    /// Run a prompt with event callback
368    pub async fn run_prompt_with_events<F>(&self, prompt: String, on_event: F) -> Result<String>
369    where
370        F: FnMut(AgentEvent) + Send + 'static,
371    {
372        self.agent.run_streaming(prompt, on_event).await?;
373        let state = self.agent_state();
374        for msg in state.messages.iter().rev() {
375            if let oxi_sdk::Message::Assistant(a) = msg {
376                return Ok(a.text_content());
377            }
378        }
379        Ok(String::new())
380    }
381
382    /// Reset the conversation
383    pub fn reset(&self) {
384        self.agent.reset();
385    }
386
387    /// Switch the model used for future LLM calls.
388    pub async fn switch_model(&self, model_id: &str) -> anyhow::Result<()> {
389        let parts: Vec<&str> = model_id.split('/').collect();
390        let provider = parts
391            .first()
392            .map(|s| s.to_string())
393            .unwrap_or_else(|| "anthropic".to_string());
394        let api_key = self.oxi.ports().auth.get_api_key(&provider).await?;
395        self.agent.switch_model(model_id, api_key);
396        Ok(())
397    }
398
399    /// Get the current model ID
400    pub fn model_id(&self) -> String {
401        self.agent.model_id()
402    }
403}