vtcode-core 0.181.7

Core library for VT Code - a Rust-based terminal coding agent
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
//! TUI protocol types and session interface.
//!
//! When the `tui` feature is enabled, this module re-exports the full app-layer
//! protocol from `vtcode-ui`.  When the feature is disabled (headless build),
//! it re-exports the shared data types from `vtcode-commons` and provides
//! lightweight no-op stubs for `InlineHandle`, `InlineSession`, and
//! `InlineEvent`.

// ── Shared data types (always available from vtcode-commons) ────────────────

pub use vtcode_commons::ui_protocol::{
    BusyEnterBehavior, CompactActivityMetadata, InlineHeaderContext, InlineHeaderHighlight, InlineHeaderStatusBadge,
    InlineHeaderStatusTone, InlineLinkRange, InlineLinkTarget, InlineListItem, InlineListSearchConfig,
    InlineListSelection, InlineMessageKind, InlineSegment, InlineTextStyle, InlineTheme, InlineTranscriptLine,
    LayoutModeOverride, PlanContent, PlanPhase, PlanStep, ReasoningDisplayMode, RewindAction, SecurePromptConfig,
    SessionSurface, SlashCommandItem, ThinkingBlockState, ToolOutputId, UiMode, WizardModalMode, WizardStep,
    convert_style, theme_from_color_fields,
};

pub use vtcode_commons::ui_protocol::KeyboardProtocolSettings;

// ── Full TUI re-exports (feature = "tui") ───────────────────────────────────

#[cfg(feature = "tui")]
pub use vtcode_ui::tui::app::*;

// ── Headless stubs (feature = "tui" disabled) ───────────────────────────────

#[cfg(not(feature = "tui"))]
mod headless {
    use std::collections::VecDeque;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::sync::{Arc, Mutex};

    use hashbrown::HashMap;
    use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};

    use super::{
        CompactActivityMetadata, InlineListItem, InlineListSearchConfig, InlineListSelection, InlineMessageKind,
        InlineSegment, InlineTranscriptLine, SecurePromptConfig, ToolOutputId,
    };

    use crate::ui::theme::ThemeStyles;
    pub use vtcode_ui::tui::app::{ContentPart, SubmittedInput};

    /// Headless `InlineEvent` — all variants present so match arms compile.
    #[derive(Clone, Debug, PartialEq, Eq)]
    pub enum InlineEvent {
        Submit(SubmittedInput),
        /// Submit text from the WebMCP bridge without interpreting slash commands.
        WebmcpSubmit(SubmittedInput),
        QueueSubmit(SubmittedInput),
        Steer(SubmittedInput),
        ProcessLatestQueued,
        EditQueue,
        Cancel,
        Exit,
        Interrupt,
        Pause,
        Resume,
        BackgroundOperation,
        ScrollLineUp,
        ScrollLineDown,
        ScrollPageUp,
        ScrollPageDown,
        JumpToLastChange,
        OpenFileInEditor(String),
        OpenUrl(String),
        LaunchEditor,
        ForceCancelPtySession,
        RequestInlinePromptSuggestion(String),
        HistoryPrevious,
        HistoryNext,
    }

    /// Minimal command surface used by tests and headless sinks.
    #[derive(Clone, Debug)]
    pub enum InlineCommand {
        Diagnostic(Box<vtcode_commons::diagnostics::Diagnostic>),
        AppendLine {
            kind: InlineMessageKind,
            segments: Vec<InlineSegment>,
        },
        AppendPastedMessage {
            kind: InlineMessageKind,
            text: String,
            line_count: usize,
        },
        Inline {
            kind: InlineMessageKind,
            segment: InlineSegment,
        },
        ReplaceLast {
            count: usize,
            kind: InlineMessageKind,
            lines: Vec<Vec<InlineSegment>>,
        },
        AppendLines {
            lines: Vec<InlineTranscriptLine>,
        },
        RecordToolOutput {
            id: ToolOutputId,
            lines: Vec<String>,
        },
        AppendToolOutputLine {
            id: ToolOutputId,
            kind: InlineMessageKind,
            segments: Vec<InlineSegment>,
        },
        AppendCompactActivity(CompactActivityMetadata),
        RecordDiffReview(vtcode_commons::ui_protocol::DiffReviewAnchor),
        ReplaceCompactActivity(CompactActivityMetadata),
        CollapsePtyBlock(CompactActivityMetadata),
        SetKeyBindings {
            bindings: HashMap<String, Vec<String>>,
        },
        SetImageInputEnabled(bool),
        RestoreInputDraft(SubmittedInput),
        ForceRedraw,
        Shutdown,
        ClearScreen,
        CloseModal,
        SetReasoningStage(Option<String>),
    }

    /// Headless handle; commands go to an optional test sink and otherwise discard.
    #[derive(Clone, Debug)]
    pub struct InlineHandle {
        diagnostic_observer: vtcode_commons::diagnostics::DiagnosticObserver,
        sender: Option<UnboundedSender<InlineCommand>>,
        deferred_events: Arc<Mutex<VecDeque<InlineEvent>>>,
        next_tool_output_id: Arc<AtomicU64>,
    }

    const MAX_DEFERRED_EVENTS: usize = 32;

    impl InlineHandle {
        pub fn new_for_tests(sender: UnboundedSender<InlineCommand>) -> Self {
            Self {
                diagnostic_observer: Default::default(),
                sender: Some(sender),
                deferred_events: Arc::new(Mutex::new(VecDeque::new())),
                next_tool_output_id: Arc::new(AtomicU64::new(0)),
            }
        }

        pub fn defer_event(&self, event: InlineEvent) -> anyhow::Result<()> {
            let mut deferred_events = self
                .deferred_events
                .lock()
                .map_err(|error| anyhow::anyhow!("deferred input queue poisoned: {error}"))?;
            if deferred_events.len() >= MAX_DEFERRED_EVENTS {
                return Err(anyhow::anyhow!("deferred input queue is full"));
            }
            deferred_events.push_back(event);
            Ok(())
        }

        fn take_deferred_event(&self) -> Option<InlineEvent> {
            self.deferred_events.lock().ok()?.pop_front()
        }

        pub fn has_deferred_event(&self) -> bool {
            self.deferred_events.lock().is_ok_and(|events| !events.is_empty())
        }

        fn send_command(&self, command: InlineCommand) {
            if let Some(sender) = &self.sender {
                let _ = sender.send(command);
            }
        }

        pub fn set_diagnostic_sink(&self, sink: vtcode_commons::diagnostics::DiagnosticSink) -> anyhow::Result<()> {
            self.diagnostic_observer.set_sink(sink)
        }
        pub fn diagnostic(&self, diagnostic: vtcode_commons::diagnostics::Diagnostic) {
            self.present_diagnostic(self.diagnostic_observer.prepare(&diagnostic));
        }
        pub fn present_diagnostic(&self, diagnostic: vtcode_commons::diagnostics::Diagnostic) {
            if self.sender.is_none() {
                vtcode_commons::diagnostics::stderr_diagnostic(&diagnostic);
                return;
            }
            self.send_command(InlineCommand::Diagnostic(Box::new(vtcode_commons::diagnostics::redact_diagnostic(
                &diagnostic,
            ))));
        }

        #[track_caller]
        fn try_append_diagnostic(&self, kind: InlineMessageKind, text: &str) -> bool {
            let severity = match kind {
                InlineMessageKind::Error => vtcode_commons::diagnostics::DiagnosticSeverity::Error,
                InlineMessageKind::Warning => vtcode_commons::diagnostics::DiagnosticSeverity::Warning,
                _ => return false,
            };
            if !text.trim().is_empty() {
                self.diagnostic(vtcode_commons::diagnostics::legacy_ui_diagnostic(severity, text));
            }
            true
        }

        #[track_caller]
        pub fn append_line(&self, kind: InlineMessageKind, segments: Vec<InlineSegment>) {
            if matches!(kind, InlineMessageKind::Error | InlineMessageKind::Warning) {
                let text = segments.iter().map(|segment| segment.text.as_str()).collect::<String>();
                if self.try_append_diagnostic(kind, &text) {
                    return;
                }
            }
            self.send_command(InlineCommand::AppendLine { kind, segments });
        }
        #[track_caller]
        pub fn append_pasted_message(&self, kind: InlineMessageKind, text: String, line_count: usize) {
            if self.try_append_diagnostic(kind, &text) {
                return;
            }
            self.send_command(InlineCommand::AppendPastedMessage { kind, text, line_count });
        }
        pub fn inline(&self, kind: InlineMessageKind, segment: InlineSegment) {
            self.send_command(InlineCommand::Inline { kind, segment });
        }
        pub fn replace_last(&self, count: usize, kind: InlineMessageKind, lines: Vec<Vec<InlineSegment>>) {
            self.send_command(InlineCommand::ReplaceLast { count, kind, lines });
        }
        #[track_caller]
        pub fn append_lines(&self, lines: Vec<InlineTranscriptLine>) {
            if lines.is_empty() {
                self.send_command(InlineCommand::AppendLines { lines });
                return;
            }
            let mut pending = Vec::new();
            for line in lines {
                if matches!(line.kind, InlineMessageKind::Error | InlineMessageKind::Warning) {
                    if !pending.is_empty() {
                        self.send_command(InlineCommand::AppendLines { lines: std::mem::take(&mut pending) });
                    }
                    let text = line.segments.iter().map(|segment| segment.text.as_str()).collect::<String>();
                    self.try_append_diagnostic(line.kind, &text);
                } else {
                    pending.push(line);
                }
            }
            if !pending.is_empty() {
                self.send_command(InlineCommand::AppendLines { lines: pending });
            }
        }
        pub fn record_tool_output(&self, lines: Vec<String>) -> ToolOutputId {
            let id = self.next_tool_output_id.fetch_add(1, Ordering::Relaxed);
            self.send_command(InlineCommand::RecordToolOutput { id, lines });
            id
        }
        pub fn append_tool_output_line(&self, id: ToolOutputId, kind: InlineMessageKind, segments: Vec<InlineSegment>) {
            self.send_command(InlineCommand::AppendToolOutputLine { id, kind, segments });
        }
        pub fn append_compact_activity(&self, activity: CompactActivityMetadata) {
            self.send_command(InlineCommand::AppendCompactActivity(activity));
        }
        pub fn record_diff_review(&self, anchor: vtcode_commons::ui_protocol::DiffReviewAnchor) {
            // Headless sinks have no transcript expand affordance, but tests
            // still need to observe that an anchor was recorded.
            self.send_command(InlineCommand::RecordDiffReview(anchor));
        }
        pub fn replace_compact_activity(&self, activity: CompactActivityMetadata) {
            self.send_command(InlineCommand::ReplaceCompactActivity(activity));
        }
        pub fn collapse_pty_block(&self, activity: CompactActivityMetadata) {
            self.send_command(InlineCommand::CollapsePtyBlock(activity));
        }
        pub fn set_key_bindings(&self, bindings: HashMap<String, Vec<String>>) {
            self.send_command(InlineCommand::SetKeyBindings { bindings });
        }
        pub fn force_redraw(&self) {
            self.send_command(InlineCommand::ForceRedraw);
        }
        pub fn shutdown(&self) {
            self.send_command(InlineCommand::Shutdown);
        }
        pub fn clear_screen(&self) {
            self.send_command(InlineCommand::ClearScreen);
        }
        pub fn show_modal(&self, _title: String, _lines: Vec<String>, _secure_prompt: Option<SecurePromptConfig>) {}
        pub fn show_list_modal(
            &self,
            _title: String,
            _lines: Vec<String>,
            _items: Vec<InlineListItem>,
            _selected: Option<InlineListSelection>,
            _search: Option<InlineListSearchConfig>,
        ) {
        }
        pub fn show_list_modal_with_footer(
            &self,
            _title: String,
            _lines: Vec<String>,
            _items: Vec<InlineListItem>,
            _selected: Option<InlineListSelection>,
            _search: Option<InlineListSearchConfig>,
            _footer_hint: Option<String>,
        ) {
        }
        pub fn show_list_modal_with_status(
            &self,
            _title: String,
            _lines: Vec<String>,
            _items: Vec<InlineListItem>,
            _selected: Option<InlineListSelection>,
            _search: Option<InlineListSearchConfig>,
            _footer_hint: Option<String>,
            _status: Option<vtcode_commons::ui_protocol::InlineStatus>,
        ) {
        }
        pub fn close_modal(&self) {
            self.send_command(InlineCommand::CloseModal);
        }
        pub fn restore_input_draft(&self, input: SubmittedInput) {
            self.send_command(InlineCommand::RestoreInputDraft(input));
        }
        pub fn set_image_input_enabled(&self, enabled: bool) {
            self.send_command(InlineCommand::SetImageInputEnabled(enabled));
        }
        pub fn set_reasoning_stage(&self, stage: Option<String>) {
            self.send_command(InlineCommand::SetReasoningStage(stage));
        }
    }

    /// Headless session — events never arrive.
    pub struct InlineSession {
        pub handle: InlineHandle,
        pub events: UnboundedReceiver<InlineEvent>,
    }

    impl InlineSession {
        pub async fn next_event(&mut self) -> Option<InlineEvent> {
            if let Some(event) = self.handle.take_deferred_event() {
                return Some(event);
            }
            self.events.recv().await
        }

        /// Headless stub: there is no TUI task to await, so shutdown is
        /// always considered complete immediately.
        pub async fn wait_for_exit(&mut self, _timeout: std::time::Duration) -> bool {
            true
        }

        pub fn clone_inline_handle(&self) -> InlineHandle {
            self.handle.clone()
        }
    }

    /// Headless appearance config with sensible defaults.
    #[derive(Debug, Clone, Default)]
    pub struct SessionAppearanceConfig {
        pub theme: String,
        pub ui_mode: super::UiMode,
        pub show_sidebar: bool,
        pub min_content_width: u16,
        pub min_navigation_width: u16,
        pub navigation_width_percent: u8,
        /// Bottom padding rows under the transcript.
        ///
        /// Retained for config compatibility only; the live transcript reads
        /// `vtcode_ui::tui::config::constants::ui::INLINE_TRANSCRIPT_BOTTOM_PADDING`,
        /// so a non-zero value set here has no render effect.
        pub transcript_bottom_padding: u16,
        pub dim_completed_todos: bool,
        pub message_block_spacing: u8,
        pub layout_mode: super::LayoutModeOverride,
        pub reasoning_display_mode: super::ReasoningDisplayMode,
        pub reasoning_visible_default: bool,
        pub thinking_display: super::ThinkingBlockState,
        pub vim_mode: bool,
        pub busy_enter_behavior: super::BusyEnterBehavior,
        pub screen_reader_mode: bool,
        pub reduce_motion_mode: bool,
        pub reduce_motion_keep_progress_animation: bool,
        pub show_transcript_review_hints: bool,
        pub show_transcript_review_shortcut_guide: bool,
        pub show_transcript_review_close_button: bool,
        pub diff_preview_mode: vtcode_commons::ui_protocol::DiffPreviewMode,
        /// Syntax highlighting for the code surfaces the TUI renders itself.
        pub syntax_highlighting: vtcode_config::loader::SyntaxHighlightingConfig,
        pub customization: (),
    }

    /// Build an [`InlineTheme`](super::InlineTheme) from core theme styles.
    pub fn theme_from_styles(styles: &ThemeStyles) -> super::InlineTheme {
        super::theme_from_color_fields(
            styles.foreground,
            styles.background,
            styles.primary,
            styles.secondary,
            styles.tool,
            styles.tool_detail,
            styles.pty_output,
            styles.error,
            styles.warning,
        )
    }
}

#[cfg(not(feature = "tui"))]
pub use headless::*;