opencrabs 0.3.23

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
Documentation
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! TUI Event System
//!
//! Handles user input and application events for the terminal interface.

use crate::brain::agent::AgentResponse;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::Value;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;

/// Events that can occur in the TUI
#[derive(Debug, Clone)]
pub enum TuiEvent {
    /// User pressed a key
    Key(KeyEvent),

    /// Mouse scroll event
    MouseScroll(i8), // positive = up, negative = down

    /// Mouse left-click at (column, row) — select message
    MouseClick(u16, u16),

    /// Mouse right-click at (column, row) — copy message
    MouseRightClick(u16, u16),

    /// Mouse left-button drag to (column, row) — extend text selection
    MouseDrag(u16, u16),

    /// Mouse left-button released at (column, row) — finalize selection + copy
    MouseUp(u16, u16),

    /// Terminal gained focus
    FocusGained,

    /// Terminal lost focus
    FocusLost,

    /// User pasted text
    Paste(String),

    /// Terminal was resized
    Resize(u16, u16),

    /// User submitted a message
    MessageSubmitted(String),

    /// Agent started processing
    AgentProcessing,

    /// Agent sent a response chunk (streaming)
    ResponseChunk { session_id: Uuid, text: String },

    /// Wipe the in-progress streaming buffer for a session — used when a
    /// gaslighting refusal preamble has been detected mid-turn and must
    /// not stay on screen while the tools it contradicted actually execute.
    StripStreamedContent {
        session_id: Uuid,
        /// Bytes to strip from the start of the streaming response buffer.
        bytes: usize,
        reason: String,
    },

    /// Agent completed response
    ResponseComplete {
        session_id: Uuid,
        response: AgentResponse,
    },

    /// An error occurred
    Error { session_id: Uuid, message: String },

    /// Request to switch UI mode
    SwitchMode(AppMode),

    /// Request to select a session
    SelectSession(Uuid),

    /// Request to create new session
    NewSession,

    /// Request to quit
    Quit,

    /// Tick event for animations/updates
    Tick,

    /// Tool approval requested
    ToolApprovalRequested(ToolApprovalRequest),

    /// Tool approval response
    ToolApprovalResponse(ToolApprovalResponse),

    /// A tool call has started executing
    ToolCallStarted {
        session_id: Uuid,
        tool_name: String,
        tool_input: Value,
    },

    /// A tool call has completed
    ToolCallCompleted {
        session_id: Uuid,
        tool_name: String,
        tool_input: Value,
        success: bool,
        summary: String,
    },

    /// Intermediate text the agent sent between tool call batches
    IntermediateText {
        session_id: Uuid,
        text: String,
        reasoning: Option<String>,
    },

    /// Context was auto-compacted — show the summary to the user
    CompactionSummary { session_id: Uuid, summary: String },

    /// A single build-output line — TUI keeps a rolling window
    BuildLine(String),

    /// Build completed — offer restart to the user
    RestartReady(String), // global, not per-session

    /// Configuration was reloaded (e.g. after config_tool write)
    ConfigReloaded,

    /// Real-time token count update from the agent loop
    TokenCountUpdated { session_id: Uuid, count: usize },

    /// Streaming output token count (per-response, counted via tiktoken)
    StreamingOutputTokens { session_id: Uuid, tokens: u32 },

    /// Onboarding wizard received fetched model list from provider API
    OnboardingModelsFetched(Vec<String>),

    /// Model selector (/models) received fetched model list (provider_index, models)
    ModelSelectorModelsFetched(usize, Vec<String>),

    /// WhatsApp QR code data received during onboarding pairing
    WhatsAppQrCode(String),
    /// WhatsApp pairing successful during onboarding
    WhatsAppConnected,
    /// WhatsApp pairing failed during onboarding
    WhatsAppError(String),

    /// GitHub Copilot device flow: display this code to the user
    GitHubDeviceCode(String),
    /// GitHub Copilot device flow: OAuth token obtained
    GitHubOAuthComplete(String),
    /// GitHub Copilot device flow: failed
    GitHubOAuthError(String),

    /// Codex OAuth device flow: display this code to the user
    CodexDeviceCode(String),
    /// Codex OAuth device flow: authentication complete
    CodexOAuthComplete,
    /// Codex OAuth device flow: failed
    CodexOAuthError(String),

    /// A system message to display in chat. Carries the originating session
    /// id so the TUI only renders the message inside that session and other
    /// open panes don't see leaked self-healing alerts from sessions they
    /// aren't currently focused on.
    SystemMessage { session_id: Uuid, text: String },

    /// Sticky fallback just swapped the active provider/model. Carries the
    /// originating session id so a fallback in session A doesn't update
    /// the footer or current session record while the user is looking at
    /// session B; the swap is always persisted to the originating session's
    /// DB record so it shows correctly when the user navigates back.
    ProviderSwitched {
        session_id: Uuid,
        to_name: String,
        to_model: String,
        reason: String,
    },

    /// Update available — show prompt dialog with version string
    UpdateAvailable(String),

    /// Channel test message result during onboarding
    ChannelTestResult {
        channel: String,
        success: bool,
        error: Option<String>,
    },

    /// Brain generation completed during onboarding (last step).
    /// Either Ok with the LLM response text or Err with the failure reason.
    BrainGenerationResult { result: Result<String, String> },

    /// Sudo password requested by bash tool
    SudoPasswordRequested(SudoPasswordRequest),

    /// SSH password requested by bash tool (used when key auth fails on
    /// `ssh`/`scp`/`rsync`). Mirrors `SudoPasswordRequested` so the dialog
    /// plumbing is identical — only the title and prompt label differ.
    SshPasswordRequested(SshPasswordRequest),

    /// Reasoning/thinking content chunk from providers like MiniMax (display-only)
    ReasoningChunk { session_id: Uuid, text: String },

    /// A queued user message was injected into the tool loop between iterations
    QueuedUserMessage { session_id: Uuid, text: String },

    /// Whisper model download progress (0.0–1.0)
    WhisperDownloadProgress(f64),
    /// Whisper model download completed (Ok or Err message)
    WhisperDownloadComplete(Result<(), String>),

    /// Piper voice download progress (0.0–1.0)
    PiperDownloadProgress(f64),
    /// Piper voice download completed (Ok(voice_id) or Err message)
    PiperDownloadComplete(Result<String, String>),

    /// A remote channel (Telegram, WhatsApp, Discord, Slack) completed an agent
    /// response — the TUI should refresh if it's the current session.
    SessionUpdated(Uuid),

    /// A remote channel started processing a session — TUI should block sends
    /// on this session to prevent concurrent tool loops.
    ChannelProcessingStarted(Uuid),
    /// A remote channel finished processing a session.
    ChannelProcessingFinished(Uuid),

    /// A pending request was resumed on startup — TUI must track the cancel token
    /// so double-Escape can abort it.
    PendingResumed {
        session_id: Uuid,
        cancel_token: CancellationToken,
    },
}

/// Sudo password request from the bash tool
#[derive(Debug)]
pub struct SudoPasswordRequest {
    /// Unique ID for this request
    pub request_id: Uuid,
    /// The sudo command being run
    pub command: String,
    /// Channel to send password back
    pub response_tx: mpsc::UnboundedSender<SudoPasswordResponse>,
}

// Manual Clone — response_tx is Clone-able (UnboundedSender)
impl Clone for SudoPasswordRequest {
    fn clone(&self) -> Self {
        Self {
            request_id: self.request_id,
            command: self.command.clone(),
            response_tx: self.response_tx.clone(),
        }
    }
}

/// Sudo password response from the TUI
#[derive(Debug, Clone)]
pub struct SudoPasswordResponse {
    /// The password (None if cancelled by user)
    pub password: Option<String>,
}

/// SSH password request from the bash tool. Same shape as
/// `SudoPasswordRequest` — `command` carries a human-friendly label
/// (e.g. `"root@1.2.3.4 (ssh)"`) instead of the literal sudo command,
/// since the bash tool may have already rewritten the SSH invocation.
#[derive(Debug)]
pub struct SshPasswordRequest {
    pub request_id: Uuid,
    /// Target description shown to the user (e.g. `"root@1.2.3.4 (ssh)"`).
    pub target: String,
    /// Channel to send password back
    pub response_tx: mpsc::UnboundedSender<SshPasswordResponse>,
}

impl Clone for SshPasswordRequest {
    fn clone(&self) -> Self {
        Self {
            request_id: self.request_id,
            target: self.target.clone(),
            response_tx: self.response_tx.clone(),
        }
    }
}

/// SSH password response from the TUI
#[derive(Debug, Clone)]
pub struct SshPasswordResponse {
    pub password: Option<String>,
}

/// Tool approval request details
#[derive(Debug, Clone)]
pub struct ToolApprovalRequest {
    /// Unique ID for this approval request
    pub request_id: Uuid,

    /// Session this approval belongs to
    pub session_id: Uuid,

    /// Tool name
    pub tool_name: String,

    /// Tool description
    pub tool_description: String,

    /// Tool input parameters
    pub tool_input: Value,

    /// Tool capabilities
    pub capabilities: Vec<String>,

    /// Channel to send response back
    pub response_tx: mpsc::UnboundedSender<ToolApprovalResponse>,

    /// When this request was created (for timeout)
    pub requested_at: std::time::Instant,
}

impl ToolApprovalRequest {
    /// How long this request has been waiting
    pub fn elapsed(&self) -> std::time::Duration {
        self.requested_at.elapsed()
    }
}

/// Tool approval response
#[derive(Debug, Clone)]
pub struct ToolApprovalResponse {
    /// Request ID this is responding to
    pub request_id: Uuid,

    /// Whether the user approved
    pub approved: bool,

    /// Optional reason for denial
    pub reason: Option<String>,
}

/// Application mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppMode {
    /// Main chat interface (full execution)
    Chat,
    /// Session list/management
    Sessions,
    /// Help screen
    Help,
    /// Settings
    Settings,
    /// File picker dialog (triggered by @)
    FilePicker,
    /// Model selector dialog (triggered by /models)
    ModelSelector,
    /// Full-screen usage dashboard (triggered by /usage)
    UsageDashboard,
    /// Restart confirmation pending (after successful /rebuild)
    RestartPending,
    /// Update prompt — ask user to accept or decline update
    UpdatePrompt,
    /// Directory picker dialog (triggered by /cd)
    DirectoryPicker,
    /// Onboarding wizard
    Onboarding,
    /// Mission Control — RSI proposals, activity, schedule (triggered by /mission-control)
    MissionControl,
    /// Skills picker — filterable list of loaded skills (triggered by /skills)
    SkillsList,
}

/// Event handler for the TUI
pub struct EventHandler {
    /// Event sender
    tx: mpsc::UnboundedSender<TuiEvent>,

    /// Event receiver
    rx: mpsc::UnboundedReceiver<TuiEvent>,
}

impl EventHandler {
    /// Create a new event handler
    pub fn new() -> Self {
        let (tx, rx) = mpsc::unbounded_channel();
        Self { tx, rx }
    }

    /// Get a sender for sending events
    pub fn sender(&self) -> mpsc::UnboundedSender<TuiEvent> {
        self.tx.clone()
    }

    /// Receive the next event (blocks until available)
    pub async fn next(&mut self) -> Option<TuiEvent> {
        self.rx.recv().await
    }

    /// Try to receive the next event without blocking
    pub fn try_next(&mut self) -> Option<TuiEvent> {
        self.rx.try_recv().ok()
    }

    /// Start listening for terminal events
    ///
    /// Uses crossterm's async EventStream instead of blocking poll/read
    /// to avoid starving the tokio runtime during I/O-heavy operations
    /// (e.g. Telegram voice processing, agent responses).
    pub fn start_terminal_listener(tx: mpsc::UnboundedSender<TuiEvent>) {
        use crossterm::event::EventStream;
        use futures::StreamExt;

        tokio::spawn(async move {
            let mut reader = EventStream::new();
            let tick_interval = std::time::Duration::from_millis(100);

            loop {
                // Race: next terminal event vs tick timer
                let event = tokio::select! {
                    maybe_event = reader.next() => {
                        match maybe_event {
                            Some(Ok(event)) => Some(event),
                            Some(Err(_)) => None,
                            None => break, // Stream closed
                        }
                    }
                    _ = tokio::time::sleep(tick_interval) => None,
                };

                if let Some(event) = event {
                    let should_break = match event {
                        crossterm::event::Event::Key(key) => {
                            // Only process key press events to avoid duplicates
                            if key.kind == crossterm::event::KeyEventKind::Press {
                                tx.send(TuiEvent::Key(key)).is_err()
                            } else {
                                false
                            }
                        }
                        crossterm::event::Event::Mouse(mouse) => {
                            use crossterm::event::MouseEventKind;
                            match mouse.kind {
                                MouseEventKind::ScrollUp => {
                                    tx.send(TuiEvent::MouseScroll(1)).is_err()
                                }
                                MouseEventKind::ScrollDown => {
                                    tx.send(TuiEvent::MouseScroll(-1)).is_err()
                                }
                                MouseEventKind::Down(crossterm::event::MouseButton::Left) => tx
                                    .send(TuiEvent::MouseClick(mouse.column, mouse.row))
                                    .is_err(),
                                MouseEventKind::Down(crossterm::event::MouseButton::Right) => tx
                                    .send(TuiEvent::MouseRightClick(mouse.column, mouse.row))
                                    .is_err(),
                                MouseEventKind::Drag(crossterm::event::MouseButton::Left) => tx
                                    .send(TuiEvent::MouseDrag(mouse.column, mouse.row))
                                    .is_err(),
                                MouseEventKind::Up(crossterm::event::MouseButton::Left) => {
                                    tx.send(TuiEvent::MouseUp(mouse.column, mouse.row)).is_err()
                                }
                                _ => false,
                            }
                        }
                        crossterm::event::Event::Resize(w, h) => {
                            tx.send(TuiEvent::Resize(w, h)).is_err()
                        }
                        crossterm::event::Event::Paste(text) => {
                            tx.send(TuiEvent::Paste(text)).is_err()
                        }
                        crossterm::event::Event::FocusGained => {
                            tx.send(TuiEvent::FocusGained).is_err()
                        }
                        crossterm::event::Event::FocusLost => tx.send(TuiEvent::FocusLost).is_err(),
                    };
                    if should_break {
                        break;
                    }
                }

                // Send tick event for animations
                if tx.send(TuiEvent::Tick).is_err() {
                    break;
                }
            }
        });
    }
}

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

/// Helper function to check if a key event matches
pub fn key_matches(event: &KeyEvent, code: KeyCode, modifiers: KeyModifiers) -> bool {
    event.code == code && event.modifiers == modifiers
}

/// Common key bindings
pub mod keys {
    use super::*;

    /// Ctrl+C - Quit
    pub fn is_quit(event: &KeyEvent) -> bool {
        key_matches(event, KeyCode::Char('c'), KeyModifiers::CONTROL)
    }

    /// Ctrl+N - New session
    pub fn is_new_session(event: &KeyEvent) -> bool {
        key_matches(event, KeyCode::Char('n'), KeyModifiers::CONTROL)
    }

    /// Ctrl+L - List sessions
    pub fn is_list_sessions(event: &KeyEvent) -> bool {
        key_matches(event, KeyCode::Char('l'), KeyModifiers::CONTROL)
    }

    /// Ctrl+K - Clear current session
    pub fn is_clear_session(event: &KeyEvent) -> bool {
        key_matches(event, KeyCode::Char('k'), KeyModifiers::CONTROL)
    }

    /// Enter - Submit (plain Enter sends the message)
    /// Also accepts Ctrl+Enter for backwards compatibility
    pub fn is_submit(event: &KeyEvent) -> bool {
        event.code == KeyCode::Enter
            && (event.modifiers.is_empty() || event.modifiers.contains(KeyModifiers::CONTROL))
    }

    /// Insert newline — Alt+Enter, Shift+Enter, or Ctrl+J
    /// macOS terminals don't send ALT modifier for Option key, so Ctrl+J
    /// (Unix standard line feed) is the reliable cross-platform binding.
    pub fn is_newline(event: &KeyEvent) -> bool {
        (event.code == KeyCode::Enter
            && (event.modifiers.contains(KeyModifiers::ALT)
                || event.modifiers.contains(KeyModifiers::SHIFT)))
            || (event.code == KeyCode::Char('j') && event.modifiers.contains(KeyModifiers::CONTROL))
    }

    /// Escape - Cancel/Back
    pub fn is_cancel(event: &KeyEvent) -> bool {
        event.code == KeyCode::Esc
    }

    /// Enter - Select/Confirm
    pub fn is_enter(event: &KeyEvent) -> bool {
        event.code == KeyCode::Enter && event.modifiers.is_empty()
    }

    /// Up arrow
    pub fn is_up(event: &KeyEvent) -> bool {
        event.code == KeyCode::Up && event.modifiers.is_empty()
    }

    /// Down arrow
    pub fn is_down(event: &KeyEvent) -> bool {
        event.code == KeyCode::Down && event.modifiers.is_empty()
    }

    /// Left arrow
    pub fn is_left(event: &KeyEvent) -> bool {
        event.code == KeyCode::Left && event.modifiers.is_empty()
    }

    /// Right arrow
    pub fn is_right(event: &KeyEvent) -> bool {
        event.code == KeyCode::Right && event.modifiers.is_empty()
    }

    /// Page up
    pub fn is_page_up(event: &KeyEvent) -> bool {
        event.code == KeyCode::PageUp
    }

    /// Page down
    pub fn is_page_down(event: &KeyEvent) -> bool {
        event.code == KeyCode::PageDown
    }

    /// Tab - Select/Navigate
    pub fn is_tab(event: &KeyEvent) -> bool {
        event.code == KeyCode::Tab && event.modifiers.is_empty()
    }

    /// 'A' or 'Y' - Approve
    pub fn is_approve(event: &KeyEvent) -> bool {
        matches!(
            event.code,
            KeyCode::Char('a') | KeyCode::Char('A') | KeyCode::Char('y') | KeyCode::Char('Y')
        ) && event.modifiers.is_empty()
    }

    /// 'D' or 'N' - Deny
    pub fn is_deny(event: &KeyEvent) -> bool {
        matches!(
            event.code,
            KeyCode::Char('d') | KeyCode::Char('D') | KeyCode::Char('n') | KeyCode::Char('N')
        ) && event.modifiers.is_empty()
    }

    /// 'V' - View details
    pub fn is_view_details(event: &KeyEvent) -> bool {
        matches!(event.code, KeyCode::Char('v') | KeyCode::Char('V')) && event.modifiers.is_empty()
    }

    /// Ctrl+X — close focused pane
    pub fn is_close_pane(event: &KeyEvent) -> bool {
        key_matches(event, KeyCode::Char('x'), KeyModifiers::CONTROL)
    }

    /// Tab — cycle focus to next pane (only when split mode is active)
    pub fn is_focus_next_pane(event: &KeyEvent) -> bool {
        event.code == KeyCode::Tab && event.modifiers.is_empty()
    }
}

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

    #[test]
    fn test_event_handler_creation() {
        let handler = EventHandler::new();
        let sender = handler.sender();
        // Should be able to send events
        assert!(sender.send(TuiEvent::Quit).is_ok());
    }

    #[test]
    fn test_key_matches() {
        let event = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
        assert!(key_matches(
            &event,
            KeyCode::Char('c'),
            KeyModifiers::CONTROL
        ));
        assert!(!key_matches(
            &event,
            KeyCode::Char('c'),
            KeyModifiers::empty()
        ));
    }

    #[test]
    fn test_quit_key() {
        let event = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
        assert!(keys::is_quit(&event));

        let event = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::empty());
        assert!(!keys::is_quit(&event));
    }

    #[test]
    fn test_submit_key() {
        // Plain Enter sends
        let event = KeyEvent::new(KeyCode::Enter, KeyModifiers::empty());
        assert!(keys::is_submit(&event));

        // Ctrl+Enter also sends (backwards compat)
        let event = KeyEvent::new(KeyCode::Enter, KeyModifiers::CONTROL);
        assert!(keys::is_submit(&event));

        // Alt+Enter does NOT send (it inserts newline)
        let event = KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT);
        assert!(!keys::is_submit(&event));
        assert!(keys::is_newline(&event));
    }
}