oxi-cli 0.2.0-alpha

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
//! Keybinding configuration and management
//!
//! Provides keybinding definitions, defaults, and custom keybinding loading.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::path::Path;
use std::path::PathBuf;

/// Keybinding action identifiers
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum KeyAction {
    // Editor actions
    CursorUp,
    CursorDown,
    CursorLeft,
    CursorRight,
    CursorWordLeft,
    CursorWordRight,
    CursorLineStart,
    CursorLineEnd,
    JumpForward,
    JumpBackward,
    PageUp,
    PageDown,
    DeleteCharBackward,
    DeleteCharForward,
    DeleteWordBackward,
    DeleteWordForward,
    DeleteToLineStart,
    DeleteToLineEnd,
    Yank,
    YankPop,
    Undo,
    NewLine,

    // Input actions
    Submit,
    Tab,
    Copy,
    SelectUp,
    SelectDown,
    SelectPageUp,
    SelectPageDown,
    SelectConfirm,
    SelectCancel,
    Interrupt,

    // App actions
    Clear,
    Exit,
    Suspend,
    CycleThinkingLevel,
    CycleModelForward,
    CycleModelBackward,
    SelectModel,
    ExpandTools,
    ToggleThinking,
    ToggleSessionNamedFilter,
    ExternalEditor,
    FollowUp,
    Dequeue,
    PasteImage,
    NewSession,
    Tree,
    Fork,
    Resume,
    TreeFoldOrUp,
    TreeUnfoldOrDown,
    TreeEditLabel,
    TreeToggleLabelTimestamp,
    ToggleSessionPath,
    ToggleSessionSort,
    RenameSession,
    DeleteSession,
    DeleteSessionNoninvasive,
    SaveModelSelection,
    EnableAllModels,
    ClearAllModels,
    ToggleProvider,
    ReorderUp,
    ReorderDown,
    TreeFilterDefault,
    TreeFilterNoTools,
    TreeFilterUserOnly,
    TreeFilterLabeledOnly,
    TreeFilterAll,
    TreeFilterCycleForward,
    TreeFilterCycleBackward,
    ToggleRawMode,

    // Custom action (for extensions)
    Custom(String),
}

impl fmt::Display for KeyAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyAction::Custom(name) => write!(f, "{}", name),
            _ => write!(f, "{:?}", self),
        }
    }
}

impl From<&str> for KeyAction {
    fn from(s: &str) -> Self {
        match s {
            // Editor actions
            "tui.editor.cursorUp" => KeyAction::CursorUp,
            "tui.editor.cursorDown" => KeyAction::CursorDown,
            "tui.editor.cursorLeft" => KeyAction::CursorLeft,
            "tui.editor.cursorRight" => KeyAction::CursorRight,
            "tui.editor.cursorWordLeft" => KeyAction::CursorWordLeft,
            "tui.editor.cursorWordRight" => KeyAction::CursorWordRight,
            "tui.editor.cursorLineStart" => KeyAction::CursorLineStart,
            "tui.editor.cursorLineEnd" => KeyAction::CursorLineEnd,
            "tui.editor.jumpForward" => KeyAction::JumpForward,
            "tui.editor.jumpBackward" => KeyAction::JumpBackward,
            "tui.editor.pageUp" => KeyAction::PageUp,
            "tui.editor.pageDown" => KeyAction::PageDown,
            "tui.editor.deleteCharBackward" => KeyAction::DeleteCharBackward,
            "tui.editor.deleteCharForward" => KeyAction::DeleteCharForward,
            "tui.editor.deleteWordBackward" => KeyAction::DeleteWordBackward,
            "tui.editor.deleteWordForward" => KeyAction::DeleteWordForward,
            "tui.editor.deleteToLineStart" => KeyAction::DeleteToLineStart,
            "tui.editor.deleteToLineEnd" => KeyAction::DeleteToLineEnd,
            "tui.editor.yank" => KeyAction::Yank,
            "tui.editor.yankPop" => KeyAction::YankPop,
            "tui.editor.undo" => KeyAction::Undo,
            "tui.input.newLine" => KeyAction::NewLine,
            "tui.input.submit" => KeyAction::Submit,
            "tui.input.tab" => KeyAction::Tab,
            "tui.input.copy" => KeyAction::Copy,
            "tui.select.up" => KeyAction::SelectUp,
            "tui.select.down" => KeyAction::SelectDown,
            "tui.select.pageUp" => KeyAction::SelectPageUp,
            "tui.select.pageDown" => KeyAction::SelectPageDown,
            "tui.select.confirm" => KeyAction::SelectConfirm,
            "tui.select.cancel" => KeyAction::SelectCancel,

            // App actions
            "app.interrupt" => KeyAction::Interrupt,
            "app.clear" => KeyAction::Clear,
            "app.exit" => KeyAction::Exit,
            "app.suspend" => KeyAction::Suspend,
            "app.thinking.cycle" => KeyAction::CycleThinkingLevel,
            "app.model.cycleForward" => KeyAction::CycleModelForward,
            "app.model.cycleBackward" => KeyAction::CycleModelBackward,
            "app.model.select" => KeyAction::SelectModel,
            "app.tools.expand" => KeyAction::ExpandTools,
            "app.thinking.toggle" => KeyAction::ToggleThinking,
            "app.session.toggleNamedFilter" => KeyAction::ToggleSessionNamedFilter,
            "app.editor.external" => KeyAction::ExternalEditor,
            "app.message.followUp" => KeyAction::FollowUp,
            "app.message.dequeue" => KeyAction::Dequeue,
            "app.clipboard.pasteImage" => KeyAction::PasteImage,
            "app.session.new" => KeyAction::NewSession,
            "app.session.tree" => KeyAction::Tree,
            "app.session.fork" => KeyAction::Fork,
            "app.session.resume" => KeyAction::Resume,
            "app.tree.foldOrUp" => KeyAction::TreeFoldOrUp,
            "app.tree.unfoldOrDown" => KeyAction::TreeUnfoldOrDown,
            "app.tree.editLabel" => KeyAction::TreeEditLabel,
            "app.tree.toggleLabelTimestamp" => KeyAction::TreeToggleLabelTimestamp,
            "app.session.togglePath" => KeyAction::ToggleSessionPath,
            "app.session.toggleSort" => KeyAction::ToggleSessionSort,
            "app.session.rename" => KeyAction::RenameSession,
            "app.session.delete" => KeyAction::DeleteSession,
            "app.session.deleteNoninvasive" => KeyAction::DeleteSessionNoninvasive,
            "app.models.save" => KeyAction::SaveModelSelection,
            "app.models.enableAll" => KeyAction::EnableAllModels,
            "app.models.clearAll" => KeyAction::ClearAllModels,
            "app.models.toggleProvider" => KeyAction::ToggleProvider,
            "app.models.reorderUp" => KeyAction::ReorderUp,
            "app.models.reorderDown" => KeyAction::ReorderDown,
            "app.tree.filter.default" => KeyAction::TreeFilterDefault,
            "app.tree.filter.noTools" => KeyAction::TreeFilterNoTools,
            "app.tree.filter.userOnly" => KeyAction::TreeFilterUserOnly,
            "app.tree.filter.labeledOnly" => KeyAction::TreeFilterLabeledOnly,
            "app.tree.filter.all" => KeyAction::TreeFilterAll,
            "app.tree.filter.cycleForward" => KeyAction::TreeFilterCycleForward,
            "app.tree.filter.cycleBackward" => KeyAction::TreeFilterCycleBackward,

            // Default actions
            "submit" => KeyAction::Submit,
            "cancel" => KeyAction::SelectCancel,
            "historyUp" | "history_up" => KeyAction::SelectUp,
            "historyDown" | "history_down" => KeyAction::SelectDown,

            // Fallback to custom
            _ => KeyAction::Custom(s.to_string()),
        }
    }
}

/// A key binding
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeyBinding {
    /// The action associated with this binding
    pub action: String,
    /// Default key sequences
    pub default_keys: Vec<String>,
    /// Description of the action
    pub description: String,
}

impl KeyBinding {
    pub fn new(action: &str, default_keys: Vec<&str>, description: &str) -> Self {
        Self {
            action: action.to_string(),
            default_keys: default_keys.into_iter().map(String::from).collect(),
            description: description.to_string(),
        }
    }
}

/// User-configurable keybindings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserKeybindings {
    /// Map of action name to custom key sequence(s)
    #[serde(default)]
    pub bindings: HashMap<String, Vec<String>>,
}

/// Load user keybindings from a file
pub fn load_user_keybindings(path: &Path) -> Option<UserKeybindings> {
    let content = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&content).ok()
}

/// Save user keybindings to a file
pub fn save_user_keybindings(path: &Path, bindings: &UserKeybindings) -> std::io::Result<()> {
    let content = serde_json::to_string_pretty(bindings)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    std::fs::write(path, content)
}

/// Get the default keybindings configuration file path
pub fn default_keybindings_path() -> Option<PathBuf> {
    dirs::config_dir().map(|p| p.join("oxi").join("keybindings.json"))
}

/// Vim-style keybindings
pub fn vim_keybindings() -> HashMap<String, KeyBinding> {
    let mut bindings = HashMap::new();

    bindings.insert(
        "tui.editor.cursorUp".to_string(),
        KeyBinding::new("tui.editor.cursorUp", vec!["k", "Up"], "Move cursor up"),
    );
    bindings.insert(
        "tui.editor.cursorDown".to_string(),
        KeyBinding::new(
            "tui.editor.cursorDown",
            vec!["j", "Down"],
            "Move cursor down",
        ),
    );
    bindings.insert(
        "tui.editor.cursorLeft".to_string(),
        KeyBinding::new(
            "tui.editor.cursorLeft",
            vec!["h", "Left"],
            "Move cursor left",
        ),
    );
    bindings.insert(
        "tui.editor.cursorRight".to_string(),
        KeyBinding::new(
            "tui.editor.cursorRight",
            vec!["l", "Right"],
            "Move cursor right",
        ),
    );
    bindings.insert(
        "tui.input.submit".to_string(),
        KeyBinding::new("tui.input.submit", vec!["Enter"], "Submit input"),
    );
    bindings.insert(
        "app.interrupt".to_string(),
        KeyBinding::new("app.interrupt", vec!["Escape"], "Cancel or abort"),
    );
    bindings.insert(
        "app.clear".to_string(),
        KeyBinding::new("app.clear", vec!["ctrl+c"], "Clear editor"),
    );

    bindings
}

/// Emacs-style keybindings
pub fn emacs_keybindings() -> HashMap<String, KeyBinding> {
    let mut bindings = HashMap::new();

    bindings.insert(
        "tui.editor.cursorUp".to_string(),
        KeyBinding::new(
            "tui.editor.cursorUp",
            vec!["ctrl+p", "Up"],
            "Move cursor up",
        ),
    );
    bindings.insert(
        "tui.editor.cursorDown".to_string(),
        KeyBinding::new(
            "tui.editor.cursorDown",
            vec!["ctrl+n", "Down"],
            "Move cursor down",
        ),
    );
    bindings.insert(
        "tui.editor.cursorLeft".to_string(),
        KeyBinding::new(
            "tui.editor.cursorLeft",
            vec!["ctrl+b", "Left"],
            "Move cursor left",
        ),
    );
    bindings.insert(
        "tui.editor.cursorRight".to_string(),
        KeyBinding::new(
            "tui.editor.cursorRight",
            vec!["ctrl+f", "Right"],
            "Move cursor right",
        ),
    );
    bindings.insert(
        "tui.input.newLine".to_string(),
        KeyBinding::new("tui.input.newLine", vec!["ctrl+j"], "New line"),
    );
    bindings.insert(
        "tui.input.submit".to_string(),
        KeyBinding::new("tui.input.submit", vec!["ctrl+m", "Enter"], "Submit input"),
    );
    bindings.insert(
        "app.interrupt".to_string(),
        KeyBinding::new("app.interrupt", vec!["ctrl+g"], "Cancel or abort"),
    );

    bindings
}

/// Get the default keybindings based on settings
pub fn get_default_keybindings() -> HashMap<String, KeyBinding> {
    // Default to vim-style on Unix, emacs-style elsewhere
    #[cfg(unix)]
    {
        vim_keybindings()
    }
    #[cfg(not(unix))]
    {
        emacs_keybindings()
    }
}

/// Keybindings manager for loading and resolving keybindings
pub struct KeybindingsManager {
    /// All defined keybindings
    bindings: HashMap<String, KeyBinding>,
    /// User overrides
    user_overrides: HashMap<String, Vec<String>>,
}

impl KeybindingsManager {
    /// Create a new keybindings manager
    pub fn new() -> Self {
        Self {
            bindings: get_default_keybindings(),
            user_overrides: HashMap::new(),
        }
    }

    /// Create from a config file
    pub fn from_file(path: &Path) -> Self {
        let mut manager = Self::new();
        if let Some(user) = load_user_keybindings(path) {
            manager.user_overrides = user.bindings;
        }
        manager
    }

    /// Create from settings
    pub fn from_settings(_settings: &crate::settings::Settings) -> Self {
        let manager = Self::new();
        // Settings-based keybindings would be applied here if available
        manager
    }

    /// Register a new keybinding
    pub fn register(&mut self, binding: KeyBinding) {
        self.bindings.insert(binding.action.clone(), binding);
    }

    /// Set user override for an action
    pub fn set_override(&mut self, action: &str, keys: Vec<String>) {
        self.user_overrides.insert(action.to_string(), keys);
    }

    /// Get the resolved key sequence for an action
    pub fn get_keys(&self, action: &str) -> Vec<String> {
        if let Some(user_keys) = self.user_overrides.get(action) {
            user_keys.clone()
        } else if let Some(binding) = self.bindings.get(action) {
            binding.default_keys.clone()
        } else {
            Vec::new()
        }
    }

    /// Get a binding by action name
    pub fn get_binding(&self, action: &str) -> Option<&KeyBinding> {
        self.bindings.get(action)
    }

    /// Get all registered bindings
    pub fn all_bindings(&self) -> &HashMap<String, KeyBinding> {
        &self.bindings
    }

    /// Get all user overrides
    pub fn user_overrides(&self) -> &HashMap<String, Vec<String>> {
        &self.user_overrides
    }

    /// Reload from file
    pub fn reload(&mut self, path: &Path) {
        if let Some(user) = load_user_keybindings(path) {
            self.user_overrides = user.bindings;
        }
    }

    /// Export user overrides to file
    pub fn export_to_file(&self, path: &Path) -> std::io::Result<()> {
        let user_bindings = UserKeybindings {
            bindings: self.user_overrides.clone(),
        };
        save_user_keybindings(path, &user_bindings)
    }
}

impl Default for KeybindingsManager {
    fn default() -> Self {
        Self::new()
    }
}

/// Parse a key sequence string into components
pub fn parse_key_sequence(sequence: &str) -> Vec<(bool, bool, char)> {
    // Returns (ctrl, alt, key)
    let mut result = Vec::new();
    let parts: Vec<&str> = sequence.split('+').collect();

    let mut ctrl = false;
    let mut alt = false;

    for part in parts {
        let part_lower = part.to_lowercase();

        if part_lower == "ctrl" || part_lower == "control" {
            ctrl = true;
            continue;
        }
        if part_lower == "alt" || part_lower == "meta" {
            alt = true;
            continue;
        }

        let key_char = match part_lower.as_str() {
            "space" => " ",
            "tab" => "\t",
            "enter" | "return" => "\n",
            "escape" | "esc" => "\x1b",
            "backspace" => "\x7f",
            "delete" => "\x1b[3~",
            "up" => "\x1b[A",
            "down" => "\x1b[B",
            "right" => "\x1b[C",
            "left" => "\x1b[D",
            "home" => "\x1b[H",
            "end" => "\x1b[F",
            "pageup" => "\x1b[5~",
            "pagedown" => "\x1b[6~",
            _ => part,
        };

        let first_char = key_char.chars().next().unwrap_or(' ');
        result.push((ctrl, alt, first_char));
        // Reset modifiers after use
        ctrl = false;
        alt = false;
    }

    result
}

/// Format a key sequence for display
pub fn format_key_sequence(keys: &[String]) -> String {
    keys.iter()
        .map(|k| {
            let parts: Vec<&str> = k.split('+').collect();
            let mut formatted_parts = Vec::new();
            for (i, part) in parts.iter().enumerate() {
                let lower = part.to_lowercase();
                if lower == "ctrl" {
                    formatted_parts.push("Ctrl".to_string());
                } else if lower == "alt" || lower == "meta" {
                    formatted_parts.push("Alt".to_string());
                } else if lower == "shift" {
                    formatted_parts.push("Shift".to_string());
                } else if i == parts.len() - 1 {
                    // Last part (the key) — uppercase single chars
                    let c = part.chars().next().unwrap_or(' ');
                    formatted_parts.push(c.to_uppercase().collect::<String>());
                } else {
                    formatted_parts.push(part.to_string());
                }
            }
            formatted_parts.join("+")
        })
        .collect::<Vec<_>>()
        .join(", ")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_key_action_from_str() {
        assert_eq!(KeyAction::from("app.interrupt"), KeyAction::Interrupt);
        assert_eq!(KeyAction::from("app.clear"), KeyAction::Clear);
        assert_eq!(KeyAction::from("submit"), KeyAction::Submit);
    }

    #[test]
    fn test_key_action_custom() {
        let action = KeyAction::from("my-extension.action");
        assert!(matches!(action, KeyAction::Custom(s) if s == "my-extension.action"));
    }

    #[test]
    fn test_keybindings_manager_new() {
        let manager = KeybindingsManager::new();
        assert!(!manager.all_bindings().is_empty());
    }

    #[test]
    fn test_get_keys_default() {
        let manager = KeybindingsManager::new();
        let keys = manager.get_keys("app.interrupt");
        assert!(!keys.is_empty());
    }

    #[test]
    fn test_set_override() {
        let mut manager = KeybindingsManager::new();
        manager.set_override("app.interrupt", vec!["ctrl+c".to_string()]);
        let keys = manager.get_keys("app.interrupt");
        assert_eq!(keys, vec!["ctrl+c"]);
    }

    #[test]
    fn test_vim_keybindings() {
        let bindings = vim_keybindings();
        assert!(bindings.contains_key("tui.editor.cursorUp"));
        assert!(bindings.contains_key("tui.input.submit"));
    }

    #[test]
    fn test_emacs_keybindings() {
        let bindings = emacs_keybindings();
        assert!(bindings.contains_key("tui.editor.cursorUp"));
        assert!(bindings.contains_key("tui.input.submit"));
    }

    #[test]
    fn test_parse_key_sequence() {
        let result = parse_key_sequence("ctrl+c");
        assert!(result.iter().any(|(ctrl, _, _)| *ctrl));

        let result = parse_key_sequence("alt+x");
        assert!(result.iter().any(|(_, alt, _)| *alt));
    }

    #[test]
    fn test_format_key_sequence() {
        let keys = vec!["ctrl+c".to_string(), "ctrl+x".to_string()];
        let formatted = format_key_sequence(&keys);
        assert!(formatted.contains("Ctrl+C"));
        assert!(formatted.contains("Ctrl+X"));
    }

    #[test]
    fn test_user_keybindings_serde() {
        let user = UserKeybindings {
            bindings: HashMap::from([("app.interrupt".to_string(), vec!["ctrl+c".to_string()])]),
        };
        let json = serde_json::to_string(&user).unwrap();
        let parsed: UserKeybindings = serde_json::from_str(&json).unwrap();
        assert_eq!(
            parsed.bindings.get("app.interrupt"),
            Some(&vec!["ctrl+c".to_string()])
        );
    }

    #[test]
    fn test_keybinding_struct() {
        let binding = KeyBinding::new("test.action", vec!["a", "b"], "Test action");
        assert_eq!(binding.action, "test.action");
        assert_eq!(binding.default_keys, vec!["a", "b"]);
        assert_eq!(binding.description, "Test action");
    }
}