oxi-cli 0.6.18

Terminal-based AI coding assistant — multi-provider, streaming-first, extensible
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
#![warn(missing_docs)]
#![warn(clippy::unwrap_used)]
#![allow(clippy::unwrap_used_in_tests)]

//! oxi: CLI coding harness
//!
//! This crate provides the main application logic for the oxi CLI.

pub(crate) mod export;
pub mod extensions;
pub(crate) mod oauth_server;
pub mod packages;
pub mod print_mode;
pub mod session;
pub(crate) mod session_navigation;
pub mod settings;
pub mod setup_wizard;
pub(crate) mod settings_validation;
pub mod skills;
pub(crate) mod templates;
pub mod tui;

// RPC mode for headless operation
pub(crate) mod rpc_mode;

// Image processing modules
pub(crate) mod clipboard_image;
pub(crate) mod clipboard_write;
pub(crate) mod image_convert;
pub(crate) mod image_resize;
pub(crate) mod file_processor;

// Utility modules
pub(crate) mod auth_storage;
pub(crate) mod auto_compaction;
pub(crate) mod branch_summarization;
pub(crate) mod bash_executor;
pub(crate) mod changelog;
pub(crate) mod child_process;
// cli must be pub for main.rs binary
pub mod cli;
pub(crate) mod diagnostics;
pub(crate) mod error_recovery;
pub(crate) mod fs_watch;
pub(crate) mod mime_detect;
pub(crate) mod paths;
pub(crate) mod sleep;

// Re-exports for extension hooks
pub use crate::error_recovery::{RetryConfig, RetryableError};

// Note: RetryStrategy is available in error_recovery::RetryStrategy

/// Context for compaction operations, passed to extension hooks
#[derive(Debug, Clone)]
pub struct CompactionContext {
    /// Messages being compacted
    pub messages_count: usize,
    /// Estimated tokens before compaction
    pub tokens_before: usize,
    /// Target token count after compaction
    pub target_tokens: usize,
    /// Strategy being used
    pub strategy: String,
}

impl CompactionContext {
    /// Create a new compaction context
    pub fn new(
        messages_count: usize,
        tokens_before: usize,
        target_tokens: usize,
        strategy: impl Into<String>,
    ) -> Self {
        Self {
            messages_count,
            tokens_before,
            target_tokens,
            strategy: strategy.into(),
        }
    }

    /// Get expected compression ratio
    pub fn compression_ratio(&self) -> f32 {
        if self.tokens_before == 0 {
            return 1.0;
        }
        self.target_tokens as f32 / self.tokens_before as f32
    }
}
pub(crate) mod event_bus;
pub(crate) mod footer_data;
pub(crate) mod git_utils;
pub(crate) mod keybindings;
pub(crate) mod messages;
pub(crate) mod model_registry;
pub(crate) mod model_resolver;
pub(crate) mod resource_loader;
pub(crate) mod frontmatter;
pub(crate) mod resource_loader_compat;
pub(crate) mod output_guard;
pub(crate) mod tmux_detect;
pub(crate) mod tools_manager;
pub(crate) mod shutdown;
pub(crate) mod version_check;

// Core modules
pub mod defaults;
pub mod provider_display_names;
pub mod session_cwd;
pub mod slash_commands;
pub mod agent_session;
pub mod agent_session_runtime;
pub(crate) mod compaction_utils;
pub mod source_info;
pub mod system_prompt;
pub mod telemetry;
pub mod auth_guidance;
pub mod exif_orientation;
pub mod pi_user_agent;
pub mod timings;

use anyhow::{Error, Result};
use oxi_agent::{Agent, AgentConfig, AgentEvent};
use oxi_ai::{get_model, get_provider};
use parking_lot::RwLock;
use settings::{Settings, ThinkingLevel};
use skills::SkillManager;
use std::sync::Arc;
use tokio::sync::mpsc;
use uuid::Uuid;

/// Application state and entry point
pub struct App {
    agent: Arc<Agent>,
    settings: Settings,
    skills: RwLock<SkillManager>,
    active_skills: RwLock<Vec<String>>,
}

/// Chat message for display
#[derive(Debug, Clone, serde::Serialize)]
pub struct ChatMessage {
    /// Role of the message sender (e.g. "user" or "assistant").
    pub role: String,
    /// Text content of the message.
    pub content: String,
    /// Timestamp when the message was created.
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

impl ChatMessage {
    /// Create a new user chat message.
    pub fn user(content: String) -> Self {
        Self {
            role: "user".to_string(),
            content,
            timestamp: chrono::Utc::now(),
        }
    }

    /// Create a new assistant chat message.
    pub fn assistant(content: String) -> Self {
        Self {
            role: "assistant".to_string(),
            content,
            timestamp: chrono::Utc::now(),
        }
    }
}

/// Interactive session state
#[derive(Debug, Clone)]
pub struct InteractiveSession {
    /// Chat messages exchanged so far.
    pub messages: Vec<ChatMessage>,
    /// Whether the assistant is currently generating a response.
    pub thinking: bool,
    /// Partial response text accumulated during streaming.
    pub current_response: String,
    /// Unique session identifier.
    pub session_id: Option<Uuid>,
    /// Optional human-readable session name.
    pub name: Option<String>,
    /// Raw session entries for persistence and tree navigation.
    pub entries: Vec<session::SessionEntry>,
}

impl Default for InteractiveSession {
    fn default() -> Self {
        Self {
            messages: Vec::new(),
            thinking: false,
            current_response: String::new(),
            session_id: None,
// FIXME: document.
            name: None,
            entries: Vec::new(),
        }
    }
}

impl InteractiveSession {
    /// Create a new empty interactive session.
    pub fn new() -> Self {
// FIXME: document.
        Self::default()
    }

    /// Add a user message to the session.
    pub fn add_user_message(&mut self, content: String) {
        self.messages.push(ChatMessage::user(content.clone()));
        // Also add to entries for session persistence
        let entry = session::SessionEntry::new(session::AgentMessage::User {
            content: session::ContentValue::String(content),
        });
        self.entries.push(entry);
    }

    /// Add an assistant message to the session.
    pub fn add_assistant_message(&mut self, content: String) {
        self.messages.push(ChatMessage::assistant(content.clone()));
        // Also add to entries for session persistence
        let entry = session::SessionEntry::new(session::AgentMessage::Assistant {
// FIXME: document.
            content: vec![session::AssistantContentBlock::Text { text: content }],
            provider: None,
            model_id: None,
            usage: None,
            stop_reason: None,
        });
        self.entries.push(entry);
        self.current_response.clear();
    }

    /// Append text to the current partial streaming response.
    pub fn append_to_response(&mut self, text: &str) {
        self.current_response.push_str(text);
    }

    /// Finalize the current streaming response into a full assistant message.
    pub fn finish_response(&mut self) {
        if !self.current_response.is_empty() {
            let response = std::mem::take(&mut self.current_response);
            self.add_assistant_message(response);
        }
    }

    /// Get all entries in the session
    pub fn entries(&self) -> &[session::SessionEntry] {
        &self.entries
    }

    /// Get entry at a specific index
    pub fn get_entry(&self, index: usize) -> Option<&session::SessionEntry> {
        self.entries.get(index)
    }

    /// Get entry by ID
    pub fn get_entry_by_id(&self, id: &str) -> Option<&session::SessionEntry> {
        self.entries.iter().find(|e| e.id == id)
    }

    /// Truncate entries at a given index (for branching)
    pub fn truncate_at(&mut self, index: usize) {
        self.entries.truncate(index + 1);
    }
}

/// Build the system prompt based on thinking level and active skills.
///
/// Delegates to [`system_prompt::build_system_prompt`] with a simple options
/// struct derived from the given thinking level and skill contents.
fn build_system_prompt(thinking_level: ThinkingLevel, skill_contents: &[String]) -> String {
    let custom_prompt = match thinking_level {
        ThinkingLevel::None => {
            Some(String::from("You are a helpful AI assistant. Provide direct, concise answers."))
        }
        ThinkingLevel::Minimal => {
            Some(String::from("You are a helpful AI assistant. Provide clear and helpful answers."))
        }
        ThinkingLevel::Standard => Some(String::from(
            "You are a helpful AI coding assistant. Think through problems \
             step by step when helpful, but keep responses focused and actionable.",
        )),
        ThinkingLevel::Thorough => Some(String::from(
            "You are an expert AI coding assistant. Take time to thoroughly \
             analyze problems, consider edge cases, and provide comprehensive \
             solutions with explanations. Think deeply before responding.",
        )),
    };

    let skills: Vec<system_prompt::Skill> = skill_contents
        .iter()
        .enumerate()
        .map(|(i, content)| system_prompt::Skill {
            name: format!("skill-{}", i),
            content: content.clone(),
        })
        .collect();

    let options = system_prompt::BuildSystemPromptOptions {
        custom_prompt,
        skills,
        cwd: std::env::current_dir()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default(),
        ..Default::default()
    };

    system_prompt::build_system_prompt(&options)
}

impl App {
    /// Create a new App instance
    pub async fn new(settings: Settings) -> Result<Self> {
        let model_id = settings.effective_model(None)
            .unwrap_or_default();
        let provider_name = settings.effective_provider(None)
            .unwrap_or_else(|| {
                model_id.split('/').next().unwrap_or("").to_string()
            });

        // If no model configured, use a placeholder — TUI will show setup wizard
        if model_id.is_empty() {
            // Return App with empty state — TUI handles the setup flow
            // We'll create a minimal session
        }

        // Parse model ID to get provider and model
        let (provider_name, model_name) = if model_id.contains('/') {
            let parts: Vec<&str> = model_id.split('/').collect();
            (parts[0].to_string(), parts[1..].join("/"))
        } else if !model_id.is_empty() {
            (provider_name.clone(), model_id.clone())
        } else {
            (String::new(), String::new())
        };

        // Get the model
        let _model = if !provider_name.is_empty() && !model_name.is_empty() {
            get_model(&provider_name, &model_name)
        } else {
            None
        };

        // Create a provider for this model
        let provider = if !provider_name.is_empty() {
            get_provider(&provider_name)
                .ok_or_else(|| Error::msg(format!("Provider '{}' not found", provider_name)))?
        } else {
            // No provider configured — use anthropic as placeholder so App can be created
            // TUI will detect this and show setup wizard
            get_provider("anthropic")
                .ok_or_else(|| Error::msg("No provider available"))?
        };

        // Load skills
        let skills_dir = SkillManager::skills_dir().unwrap_or_else(|_| {
            dirs::home_dir()
                .unwrap_or_default()
                .join(".oxi")
                .join("skills")
        });
        let skills = SkillManager::load_from_dir(&skills_dir).unwrap_or_else(|e| {
            tracing::debug!("Skills not loaded: {}", e);
            SkillManager::new()
        });

        // Build agent config from settings
        let system_prompt = build_system_prompt(settings.thinking_level, &[]);
        let compaction_strategy = if settings.auto_compaction {
            oxi_ai::CompactionStrategy::Threshold(0.8)
        } else {
            oxi_ai::CompactionStrategy::Disabled
        };
        let config = AgentConfig {
            name: "oxi".to_string(),
            description: Some("oxi CLI agent".to_string()),
            model_id: model_id.clone(),
            system_prompt: Some(system_prompt),
            max_iterations: 10,
            timeout_seconds: settings.tool_timeout_seconds,
            temperature: settings.effective_temperature(),
            max_tokens: settings.effective_max_tokens(),
            compaction_strategy,
            compaction_instruction: None,
            context_window: 128_000,
        };

        let agent = Arc::new(Agent::new(Arc::from(provider), config));

        Ok(Self {
            agent,
            settings,
            skills: RwLock::new(skills),
            active_skills: RwLock::new(Vec::new()),
        })
    }

    /// Get the current settings
    pub fn settings(&self) -> &Settings {
        &self.settings
    }

    /// Get a reference to the underlying agent.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use oxi_cli::App;
    ///
    /// async fn example(app: &App) {
    ///     let agent = app.agent();
    ///     // Use the agent directly
    /// }
    /// ```
    pub fn agent(&self) -> Arc<Agent> {
        Arc::clone(&self.agent)
    }

    /// Get the tool registry (for registering extension tools)
    pub fn agent_tools(&self) -> Arc<oxi_agent::ToolRegistry> {
        self.agent.tools()
    }

    /// Get a reference to the skill manager
    pub fn skills(&self) -> parking_lot::RwLockReadGuard<'_, SkillManager> {
        self.skills.read()
    }

    /// Activate a skill by name. Returns an error string if not found.
    pub fn activate_skill(&self, name: &str) -> Result<(), String> {
        {
            let skills = self.skills.read();
            if skills.get(name).is_none() {
                return Err(format!("Skill '{}' not found", name));
            }
        }
        let name_lower = name.to_lowercase();
        {
            let mut active = self.active_skills.write();
            if !active.contains(&name_lower) {
                active.push(name_lower);
            }
        }
        self.rebuild_system_prompt();
        Ok(())
    }

    /// Deactivate a skill by name.
    pub fn deactivate_skill(&self, name: &str) {
        let name_lower = name.to_lowercase();
        {
            let mut active = self.active_skills.write();
            active.retain(|n| n != &name_lower);
        }
        self.rebuild_system_prompt();
    }

    /// List currently active skill names
    pub fn active_skills(&self) -> Vec<String> {
        self.active_skills.read().clone()
    }

    /// Rebuild the system prompt with current active skills
    fn rebuild_system_prompt(&self) {
        let active = self.active_skills.read();
        let skills = self.skills.read();
        let contents: Vec<String> = active
            .iter()
            .filter_map(|name| skills.get(name).map(|s| s.content.clone()))
            .collect();
        let prompt = build_system_prompt(self.settings.thinking_level, &contents);
        self.agent.set_system_prompt(prompt);
    }

    /// Get a clone of the current state
    pub fn agent_state(&self) -> oxi_agent::AgentState {
        self.agent.state()
    }

    /// Run a single prompt and return the response
    pub async fn run_prompt(&self, prompt: String) -> Result<String> {
        let (response, _events) = self.agent.run(prompt).await?;
        Ok(response.content)
    }

    /// Run a prompt with event callback
    pub async fn run_prompt_with_events<F>(&self, prompt: String, on_event: F) -> Result<String>
    where
        F: FnMut(AgentEvent) + Send + 'static,
    {
        self.agent.run_streaming(prompt, on_event).await?;
        // Get the last assistant message's text content
        let state = self.agent_state();
        for msg in state.messages.iter().rev() {
            if let oxi_ai::Message::Assistant(a) = msg {
                return Ok(a.text_content());
            }
        }
        Ok(String::new())
    }

    /// Run in interactive mode, returning an event stream
    pub async fn run_interactive(&self) -> Result<InteractiveLoop<'_>> {
        let session = InteractiveSession::new();
        Ok(InteractiveLoop { app: self, session })
    }

    /// Reset the conversation
    pub fn reset(&self) {
        self.agent.reset();
    }

    /// Switch the model used for future LLM calls.
    ///
    /// See [`Agent::switch_model`] for details.
    pub fn switch_model(&self, model_id: &str) -> anyhow::Result<()> {
        self.agent.switch_model(model_id)
    }

    /// Get the current model ID
    pub fn model_id(&self) -> String {
        self.agent.model_id()
    }
}

/// Interactive loop handle
pub struct InteractiveLoop<'a> {
    app: &'a App,
    session: InteractiveSession,
}

impl<'a> InteractiveLoop<'a> {
    /// Add a user message and get the assistant response
    pub async fn send_message(&mut self, prompt: String) -> Result<()> {
        // Add user message
        self.session.add_user_message(prompt.clone());
        self.session.thinking = true;

        // Run agent with channel
        let (tx, mut rx) = mpsc::channel::<AgentEvent>(100);

        // Run the agent — we execute inline instead of spawning because
        // the agent's internal RwLockReadGuard is not Send-safe across
        // await points. We use a select-like approach: run the agent in a
        // local task that doesn't require Send.
        let agent = Arc::clone(&self.app.agent);

        // Use LocalSet to spawn a non-Send future
        let local = tokio::task::LocalSet::new();
        local.spawn_local(async move {
            let _ = agent.run_with_channel(prompt, tx).await;
        });

        // Collect events
        while let Some(event) = rx.recv().await {
            match event {
                AgentEvent::TextChunk { text } => {
                    self.session.append_to_response(&text);
                }
                AgentEvent::Thinking => {
                    // Thinking state
                }
                AgentEvent::Complete { .. } => {
                    self.session.finish_response();
                    self.session.thinking = false;
                }
                AgentEvent::Error { message, .. } => {
                    self.session
                        .append_to_response(&format!("[Error: {}]", message));
                    self.session.finish_response();
                    self.session.thinking = false;
                }
                _ => {}
            }
        }

        // Run local set to completion (drain remaining agent work)
        local.await;

        Ok(())
    }

    /// Get current messages
    pub fn messages(&self) -> &[ChatMessage] {
        &self.session.messages
    }

    /// Get the current partial response (while thinking)
    pub fn current_response(&self) -> &str {
        &self.session.current_response
    }

    /// Check if currently thinking
    pub fn is_thinking(&self) -> bool {
        self.session.thinking
    }

    /// Get session entries for tree navigation
    pub fn entries(&self) -> &[session::SessionEntry] {
        self.session.entries()
    }

    /// Get entry by ID
    pub fn get_entry(&self, id: Uuid) -> Option<&session::SessionEntry> {
        self.session.get_entry_by_id(&id.to_string())
    }

    /// Switch the model used for future LLM calls
    pub fn switch_model(&self, model_id: &str) -> anyhow::Result<()> {
        self.app.switch_model(model_id)
    }

    /// Get the current model ID
    pub fn model_id(&self) -> String {
        self.app.model_id()
    }
}