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
88        .event_bus
89        .publish(&"port-check".to_string(), serde_json::json!({"ok": true}))
90        .await;
91    println!("[event-bus] publish ok (noop bus if not registered)");
92
93    println!("\nport check: ok");
94    Ok(())
95}
96
97/// Context for compaction operations, passed to extension hooks
98#[derive(Debug, Clone)]
99pub struct CompactionContext {
100    /// Messages being compacted
101    pub messages_count: usize,
102    /// Estimated tokens before compaction
103    pub tokens_before: usize,
104    /// Target token count after compaction
105    pub target_tokens: usize,
106    /// Strategy being used
107    pub strategy: String,
108}
109
110impl CompactionContext {
111    /// Create a new compaction context
112    pub fn new(
113        messages_count: usize,
114        tokens_before: usize,
115        target_tokens: usize,
116        strategy: impl Into<String>,
117    ) -> Self {
118        Self {
119            messages_count,
120            tokens_before,
121            target_tokens,
122            strategy: strategy.into(),
123        }
124    }
125
126    /// Get expected compression ratio
127    pub fn compression_ratio(&self) -> f32 {
128        if self.tokens_before == 0 {
129            return 1.0;
130        }
131        self.target_tokens as f32 / self.tokens_before as f32
132    }
133}
134
135// ─── Module-level imports ────────────────────────────────────────────────────
136use crate::store::settings::Settings;
137use anyhow::{Error, Result};
138use oxi_agent::{Agent, AgentConfig, AgentEvent};
139use parking_lot::RwLock;
140use skills::SkillManager;
141use std::sync::Arc;
142
143// ─── Application state ───────────────────────────────────────────────────────
144
145/// Application state and entry point.
146///
147/// Holds an `Oxi` engine (composition root) and a single `Agent` built
148/// from it. The legacy `App::new(settings)` constructor is **gone**;
149/// use [`App::from_oxi`] with a wired `Oxi` from
150/// [`build_oxi_engine`].
151pub struct App {
152    oxi: oxi_sdk::Oxi,
153    agent: Arc<Agent>,
154    settings: Settings,
155    skills: RwLock<SkillManager>,
156    active_skills: RwLock<Vec<String>>,
157    wasm_ext: Option<std::sync::Arc<crate::extensions::WasmExtensionManager>>,
158    questionnaire_bridge:
159        Option<std::sync::Arc<oxi_agent::tools::questionnaire::QuestionnaireBridge>>,
160}
161
162/// Context for compaction operations, passed to extension hooks
163// ─── System prompt builder ───────────────────────────────────────────────────
164fn build_system_prompt(
165    thinking_level: crate::store::settings::ThinkingLevel,
166    skill_contents: &[String],
167) -> String {
168    let skills: Vec<prompt::system_prompt::Skill> = skill_contents
169        .iter()
170        .enumerate()
171        .map(|(i, content)| prompt::system_prompt::Skill {
172            name: format!("skill-{}", i),
173            content: content.clone(),
174        })
175        .collect();
176
177    let options = prompt::system_prompt::BuildSystemPromptOptions {
178        custom_prompt: prompt::system_prompt::thinking_level_prompt(thinking_level),
179        skills,
180        cwd: std::env::current_dir()
181            .map(|p| p.to_string_lossy().to_string())
182            .unwrap_or_default(),
183        ..Default::default()
184    };
185
186    prompt::system_prompt::build_system_prompt(&options)
187}
188
189// ─── App implementation ─────────────────────────────────────────────────────
190
191impl App {
192    /// Build an `App` from a wired `Oxi` engine and a settings object.
193    ///
194    /// The `Oxi` should be created via [`build_oxi_engine`] (or
195    /// `services::build_oxi`) so that all 11 ports are wired. The
196    /// settings hold the user's runtime configuration (model, thinking
197    /// level, etc.).
198    pub async fn from_oxi(oxi: oxi_sdk::Oxi, settings: Settings) -> Result<Self> {
199        let model_id = settings.effective_model(None).unwrap_or_default();
200        let provider_name = settings
201            .effective_provider(None)
202            .unwrap_or_else(|| model_id.split('/').next().unwrap_or("").to_string());
203
204        // Pull the API key from the wired port, not from oxi_store.
205        let api_key = oxi.ports().auth.get_api_key(&provider_name).await?;
206
207        let skills_dir = SkillManager::skills_dir().unwrap_or_else(|_| {
208            dirs::home_dir()
209                .unwrap_or_default()
210                .join(".oxi")
211                .join("skills")
212        });
213        let skills = SkillManager::load_from_dir(&skills_dir).unwrap_or_else(|e| {
214            tracing::debug!("Skills not loaded: {}", e);
215            SkillManager::new()
216        });
217
218        let system_prompt = build_system_prompt(settings.thinking_level, &[]);
219        let compaction_strategy = if settings.auto_compaction {
220            oxi_sdk::CompactionStrategy::Threshold(0.8)
221        } else {
222            oxi_sdk::CompactionStrategy::Disabled
223        };
224
225        let config = AgentConfig {
226            name: "oxi".to_string(),
227            description: Some("oxi CLI agent".to_string()),
228            model_id: model_id.clone(),
229            system_prompt: Some(system_prompt),
230            timeout_seconds: settings.tool_timeout_seconds,
231            temperature: settings.effective_temperature(),
232            max_tokens: settings.effective_max_tokens(),
233            compaction_strategy,
234            compaction_instruction: None,
235            context_window: 128_000,
236            api_key,
237            workspace_dir: Some(
238                std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),
239            ),
240            output_mode: None,
241            provider_options: None,
242        };
243
244        // Build the agent via the SDK's AgentBuilder — no manual wiring.
245        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
246        let agent = oxi
247            .agent(config)
248            .workspace(cwd)
249            .build()
250            .map_err(|e| Error::msg(format!("agent build failed: {e}")))?;
251        let agent = Arc::new(agent);
252
253        let bridge =
254            std::sync::Arc::new(oxi_agent::tools::questionnaire::QuestionnaireBridge::new());
255        let questionnaire_tool =
256            oxi_agent::tools::questionnaire::QuestionnaireTool::new(bridge.clone());
257        agent
258            .tools()
259            .register_arc(std::sync::Arc::new(questionnaire_tool));
260
261        Ok(Self {
262            oxi,
263            agent,
264            settings,
265            skills: RwLock::new(skills),
266            active_skills: RwLock::new(Vec::new()),
267            wasm_ext: None,
268            questionnaire_bridge: Some(bridge),
269        })
270    }
271
272    /// Get the current settings
273    pub fn settings(&self) -> &Settings {
274        &self.settings
275    }
276
277    /// Set the WASM extension manager
278    pub fn set_wasm_ext(
279        &mut self,
280        ext: Option<std::sync::Arc<crate::extensions::WasmExtensionManager>>,
281    ) {
282        self.wasm_ext = ext;
283    }
284
285    /// Get the WASM extension manager
286    pub fn wasm_ext(&self) -> Option<&std::sync::Arc<crate::extensions::WasmExtensionManager>> {
287        self.wasm_ext.as_ref()
288    }
289
290    /// Get a reference to the underlying agent.
291    pub fn agent(&self) -> Arc<Agent> {
292        Arc::clone(&self.agent)
293    }
294
295    /// Get the tool registry (for registering extension tools)
296    pub fn agent_tools(&self) -> Arc<oxi_agent::ToolRegistry> {
297        self.agent.tools()
298    }
299
300    /// Get the questionnaire bridge, if initialized.
301    pub fn questionnaire_bridge(
302        &self,
303    ) -> Option<&std::sync::Arc<oxi_agent::tools::questionnaire::QuestionnaireBridge>> {
304        self.questionnaire_bridge.as_ref()
305    }
306
307    /// Get a reference to the skill manager
308    pub fn skills(&self) -> parking_lot::RwLockReadGuard<'_, SkillManager> {
309        self.skills.read()
310    }
311
312    /// Activate a skill by name. Returns an error string if not found.
313    pub fn activate_skill(&self, name: &str) -> Result<(), String> {
314        {
315            let skills = self.skills.read();
316            if skills.get(name).is_none() {
317                return Err(format!("Skill '{}' not found", name));
318            }
319        }
320        let name_lower = name.to_lowercase();
321        {
322            let mut active = self.active_skills.write();
323            if !active.contains(&name_lower) {
324                active.push(name_lower);
325            }
326        }
327        self.rebuild_system_prompt();
328        Ok(())
329    }
330
331    /// Deactivate a skill by name.
332    pub fn deactivate_skill(&self, name: &str) {
333        let name_lower = name.to_lowercase();
334        {
335            let mut active = self.active_skills.write();
336            active.retain(|n| n != &name_lower);
337        }
338        self.rebuild_system_prompt();
339    }
340
341    /// List currently active skill names
342    pub fn active_skills(&self) -> Vec<String> {
343        self.active_skills.read().clone()
344    }
345
346    /// Rebuild the system prompt with current active skills
347    fn rebuild_system_prompt(&self) {
348        let active = self.active_skills.read();
349        let skills = self.skills.read();
350        let contents: Vec<String> = active
351            .iter()
352            .filter_map(|name| skills.get(name).map(|s| s.content.clone()))
353            .collect();
354        let prompt = build_system_prompt(self.settings.thinking_level, &contents);
355        self.agent.set_system_prompt(prompt);
356    }
357
358    /// Get a clone of the current state
359    pub fn agent_state(&self) -> oxi_agent::AgentState {
360        self.agent.state()
361    }
362
363    /// Run a single prompt and return the response
364    pub async fn run_prompt(&self, prompt: String) -> Result<String> {
365        let (response, _events) = self.agent.run(prompt).await?;
366        Ok(response.content)
367    }
368
369    /// Run a prompt with event callback
370    pub async fn run_prompt_with_events<F>(&self, prompt: String, on_event: F) -> Result<String>
371    where
372        F: FnMut(AgentEvent) + Send + 'static,
373    {
374        self.agent.run_streaming(prompt, on_event).await?;
375        let state = self.agent_state();
376        for msg in state.messages.iter().rev() {
377            if let oxi_sdk::Message::Assistant(a) = msg {
378                return Ok(a.text_content());
379            }
380        }
381        Ok(String::new())
382    }
383
384    /// Reset the conversation
385    pub fn reset(&self) {
386        self.agent.reset();
387    }
388
389    /// Switch the model used for future LLM calls.
390    pub async fn switch_model(&self, model_id: &str) -> anyhow::Result<()> {
391        let parts: Vec<&str> = model_id.split('/').collect();
392        let provider = parts
393            .first()
394            .map(|s| s.to_string())
395            .unwrap_or_else(|| "anthropic".to_string());
396        let api_key = self.oxi.ports().auth.get_api_key(&provider).await?;
397        let _ = self.agent.switch_model(model_id, api_key);
398        Ok(())
399    }
400
401    /// Get the current model ID
402    pub fn model_id(&self) -> String {
403        self.agent.model_id()
404    }
405}