1#![warn(missing_docs)]
2#![warn(clippy::unwrap_used)]
3#![allow(unknown_lints)]
4
5pub mod bootstrap;
12pub mod cli;
13pub mod main_dispatch;
14pub mod print_mode;
15pub mod services;
16pub mod setup_wizard;
17pub mod store;
18
19pub(crate) mod app;
21pub(crate) mod context;
22pub mod extensions; pub(crate) mod infra;
24pub(crate) mod media;
25pub(crate) mod prompt;
26pub(crate) mod rpc_mode;
27pub(crate) mod skills;
28pub mod storage; pub use storage::packages::PackageManager;
31pub use storage::packages::ResourceKind;
32pub mod tui; pub(crate) mod ui;
34pub(crate) mod util;
35
36pub fn build_oxi_engine() -> anyhow::Result<oxi_sdk::Oxi> {
53 let paths = services::OxiPaths::default_paths()?;
54 services::build_oxi(&paths)
55}
56
57pub async fn run_port_check() -> anyhow::Result<()> {
64 let oxi = build_oxi_engine()?;
65 let ports = oxi.ports();
66
67 let entries = ports.state.list("").await?;
69 println!("[state] entries: {}", entries.len());
70
71 let providers = ports.auth.list_providers().await?;
73 println!("[auth] providers with credentials: {:?}", providers);
74
75 let keys = ports.config.list()?;
77 println!("[config] keys: {}", keys.len());
78
79 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 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#[derive(Debug, Clone)]
99pub struct CompactionContext {
100 pub messages_count: usize,
102 pub tokens_before: usize,
104 pub target_tokens: usize,
106 pub strategy: String,
108}
109
110impl CompactionContext {
111 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 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
135use 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
143pub 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
162fn 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
189impl App {
192 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 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 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 pub fn settings(&self) -> &Settings {
274 &self.settings
275 }
276
277 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 pub fn wasm_ext(&self) -> Option<&std::sync::Arc<crate::extensions::WasmExtensionManager>> {
287 self.wasm_ext.as_ref()
288 }
289
290 pub fn agent(&self) -> Arc<Agent> {
292 Arc::clone(&self.agent)
293 }
294
295 pub fn agent_tools(&self) -> Arc<oxi_agent::ToolRegistry> {
297 self.agent.tools()
298 }
299
300 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 pub fn skills(&self) -> parking_lot::RwLockReadGuard<'_, SkillManager> {
309 self.skills.read()
310 }
311
312 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 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 pub fn active_skills(&self) -> Vec<String> {
343 self.active_skills.read().clone()
344 }
345
346 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 pub fn agent_state(&self) -> oxi_agent::AgentState {
360 self.agent.state()
361 }
362
363 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 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 pub fn reset(&self) {
386 self.agent.reset();
387 }
388
389 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 pub fn model_id(&self) -> String {
403 self.agent.model_id()
404 }
405}