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
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
//! Plain output lines, modals, and screen management.

use super::*;

use crate::utils::transcript;

use crate::ui::markdown::{MarkdownLine, RenderMarkdownOptions, render_markdown_to_lines_with_options};
use crate::ui::theme;
use crate::ui::tui::{InlineListItem, InlineListSearchConfig, InlineListSelection, InlineMessageKind};
use crate::utils::ansi_capabilities::AnsiCapabilities;
use anstyle::{Reset, Style};
use anyhow::{Result, anyhow};
use std::io::Write;
use unicode_width::UnicodeWidthStr;

const RECENT_DIAGNOSTIC_LIMIT: usize = 128;

impl AnsiRenderer {
    pub fn set_table_max_width(&mut self, max_width: Option<usize>) {
        if let Some(sink) = &mut self.sink {
            sink.table_max_width = max_width;
            sink.table_max_width_override = max_width;
        }
    }

    pub(super) fn should_render_style(&self, style: MessageStyle) -> bool {
        self.reasoning_visible || !matches!(style, MessageStyle::Reasoning | MessageStyle::ReasoningEmphasis)
    }

    /// Install the canonical event boundary after a thread sink exists.
    pub fn set_diagnostic_sink(&mut self, sink: DiagnosticSink) {
        self.diagnostic_sink = Some(sink);
        self.diagnostic_history.clear();
    }

    /// Display an operational diagnostic. Payloads must also be sanitized before event persistence.
    pub fn diagnostic(&mut self, diagnostic: &vtcode_commons::diagnostics::Diagnostic) -> Result<()> {
        self.display_diagnostic(diagnostic, true)
    }

    /// Restore an already-durable incident without emitting another event.
    pub fn restore_diagnostic(&mut self, diagnostic: &vtcode_commons::diagnostics::Diagnostic) -> Result<()> {
        self.display_diagnostic(diagnostic, false)
    }

    fn display_diagnostic(
        &mut self,
        diagnostic: &vtcode_commons::diagnostics::Diagnostic,
        persist: bool,
    ) -> Result<()> {
        use vtcode_commons::diagnostics::{DiagnosticSeverity, redact_diagnostic};
        self.flush_compact_command_group();
        let mut diagnostic = redact_diagnostic(diagnostic);
        let already_persisted = self.diagnostic_history.iter().any(|previous| previous == &diagnostic);
        let persistence_error = if !persist || already_persisted {
            None
        } else {
            self.diagnostic_sink.as_ref().and_then(|sink| sink(&diagnostic).err())
        };
        if !already_persisted && persistence_error.is_none() && self.diagnostic_sink.is_some() {
            self.diagnostic_history
                .retain(|previous| previous.correlation_id != diagnostic.correlation_id);
            if self.diagnostic_history.len() == RECENT_DIAGNOSTIC_LIMIT {
                let _ = self.diagnostic_history.pop_front();
            }
            self.diagnostic_history.push_back(diagnostic.clone());
        }
        if let Some(error) = &persistence_error {
            if !diagnostic.agent_details.is_empty() {
                diagnostic.agent_details.push_str("\n\n");
            }
            diagnostic
                .agent_details
                .push_str("Diagnostic persistence failed; this message may not be saved.\n");
            diagnostic
                .agent_details
                .push_str(&vtcode_commons::sanitizer::sanitize_provider_diagnostic(error.to_string()));
        }
        let style = match diagnostic.severity {
            DiagnosticSeverity::Info => MessageStyle::Info,
            DiagnosticSeverity::Warning => MessageStyle::Warning,
            DiagnosticSeverity::Error => MessageStyle::Error,
        };
        if let Some(sink) = &self.sink {
            if persist && self.diagnostic_sink.is_none() {
                // Secondary renderers retain their owning handle's canonical observer.
                sink.handle.diagnostic(diagnostic.clone());
            } else {
                sink.handle.present_diagnostic(diagnostic.clone());
            }
            transcript::append(&diagnostic.text());
        } else {
            self.render_markdown(style, &diagnostic.text())?;
        }
        if let Some(error) = persistence_error {
            return Err(error);
        }
        Ok(())
    }

    #[track_caller]
    fn legacy_diagnostic(&mut self, style: MessageStyle, text: &str) -> Result<()> {
        if text.trim().is_empty() {
            return Ok(());
        }
        use vtcode_commons::diagnostics::DiagnosticSeverity;
        let severity = if matches!(style, MessageStyle::Warning) {
            DiagnosticSeverity::Warning
        } else {
            DiagnosticSeverity::Error
        };
        self.diagnostic(&vtcode_commons::diagnostics::legacy_ui_diagnostic(severity, text))
    }

    pub(super) fn indent_for_style(&self, style: MessageStyle) -> &'static str {
        if self.screen_reader_mode && matches!(style, MessageStyle::Reasoning | MessageStyle::ReasoningEmphasis) {
            "  [reasoning] "
        } else {
            style.indent()
        }
    }

    /// Get the terminal's detected ANSI capabilities
    pub fn capabilities(&self) -> &AnsiCapabilities {
        &self.capabilities
    }

    /// Return the width available to a rendered diff row after the logical
    /// message indent and, for inline UI output, the transcript frame.
    ///
    /// Diff rows use this width only to extend their background with spaces;
    /// when terminal sizing is unavailable callers retain their bounded
    /// fallback behavior.
    pub fn diff_content_width(&self, style: MessageStyle) -> Option<usize> {
        let indent_width = UnicodeWidthStr::width(self.indent_for_style(style));
        let kind = Self::message_kind(style);
        let frame_width = self
            .sink
            .as_ref()
            .map(|sink| transcript_table_frame_width(kind, sink.handle.agent_label_frame_width()))
            .unwrap_or_default();
        // An explicit test/configuration width wins. Otherwise prefer a fresh
        // terminal measurement so a later diff preview follows a resize even
        // when an earlier Markdown render cached the previous width.
        let terminal_width = self
            .sink
            .as_ref()
            .and_then(|sink| {
                sink.table_max_width_override
                    .or_else(|| crossterm::terminal::size().ok().map(|(width, _)| usize::from(width)))
                    .or(sink.table_max_width)
            })
            .or_else(|| crossterm::terminal::size().ok().map(|(width, _)| usize::from(width)));

        terminal_width.map(|width| width.saturating_sub(indent_width).saturating_sub(frame_width))
    }

    /// Check if unicode should be used for formatting (tables, boxes, etc.)
    pub fn should_use_unicode_formatting(&self) -> bool {
        self.capabilities.should_use_unicode_boxes()
    }

    /// Check if 256-color output is supported
    pub fn supports_256_colors(&self) -> bool {
        self.capabilities.supports_256_colors()
    }

    /// Check if true color (24-bit) output is supported
    pub fn supports_true_color(&self) -> bool {
        self.capabilities.supports_true_color()
    }

    /// Check if should use unicode characters based on terminal capabilities
    pub fn should_use_unicode(&self) -> bool {
        self.capabilities.unicode_support
    }

    pub fn show_list_modal(
        &mut self,
        title: &str,
        lines: Vec<String>,
        items: Vec<InlineListItem>,
        selected: Option<InlineListSelection>,
        search: Option<InlineListSearchConfig>,
    ) {
        if let Some(sink) = &self.sink {
            sink.show_list_modal(title.into(), lines, items, selected, search);
        }
    }

    pub fn show_list_modal_with_footer(
        &mut self,
        title: &str,
        lines: Vec<String>,
        items: Vec<InlineListItem>,
        selected: Option<InlineListSelection>,
        search: Option<InlineListSearchConfig>,
        footer_hint: Option<String>,
    ) {
        self.show_list_modal_with_status(title, lines, items, selected, search, footer_hint, None);
    }

    /// Show a list modal with an optional status strip (last action feedback).
    pub fn show_list_modal_with_status(
        &mut self,
        title: &str,
        lines: Vec<String>,
        items: Vec<InlineListItem>,
        selected: Option<InlineListSelection>,
        search: Option<InlineListSearchConfig>,
        footer_hint: Option<String>,
        status: Option<vtcode_commons::ui_protocol::InlineStatus>,
    ) {
        if let Some(sink) = &self.sink {
            sink.show_list_modal_with_status(title.into(), lines, items, selected, search, footer_hint, status);
        }
    }

    pub fn show_secure_prompt_modal(&mut self, title: &str, lines: Vec<String>, prompt_label: String) {
        if let Some(sink) = &self.sink {
            sink.show_secure_prompt_modal(title.into(), lines, prompt_label);
        }
    }

    pub fn close_modal(&mut self) {
        if let Some(sink) = &self.sink {
            sink.close_modal();
        }
    }

    pub fn clear_screen(&mut self) {
        self.flush_compact_command_group();
        if let Some(sink) = &self.sink {
            sink.handle.clear_screen();
        }
    }

    /// Push text into the buffer
    pub fn push(&mut self, text: &str) {
        self.buffer.push_str(text);
    }

    /// Flush the buffer with the given style
    #[track_caller]
    pub fn flush(&mut self, style: MessageStyle) -> Result<()> {
        self.flush_compact_command_group();
        if !self.should_render_style(style) {
            self.buffer.clear();
            return Ok(());
        }
        if matches!(style, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
            let text = std::mem::take(&mut self.buffer);
            return self.legacy_diagnostic(style, &text);
        }
        let indent = self.indent_for_style(style);
        if let Some(sink) = &mut self.sink {
            // Track if this line is empty
            self.last_line_was_empty = self.buffer.is_empty() && indent.is_empty();
            sink.write_line(style.style(), indent, &self.buffer, Self::message_kind(style))?;
            self.buffer.clear();
            return Ok(());
        }
        let style = style.style();
        if self.color {
            writeln!(self.writer, "{style}{}{Reset}", self.buffer)?;
        } else {
            writeln!(self.writer, "{}", self.buffer)?;
        }
        self.writer.flush()?;
        transcript::append(&self.buffer);
        // Track if this line is empty
        self.last_line_was_empty = self.buffer.is_empty();
        self.buffer.clear();
        Ok(())
    }

    /// Convenience for writing a single line
    #[track_caller]
    pub fn line(&mut self, style: MessageStyle, text: &str) -> Result<()> {
        self.flush_compact_command_group();
        if !self.should_render_style(style) {
            return Ok(());
        }
        if matches!(style, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
            return self.legacy_diagnostic(style, text);
        }
        if matches!(style, MessageStyle::Response | MessageStyle::Reasoning | MessageStyle::ReasoningEmphasis) {
            return self.render_markdown(style, text);
        }
        if matches!(style, MessageStyle::Output | MessageStyle::ToolOutput) {
            let stripped = crate::utils::ansi_parser::strip_ansi(text);
            self.buffer.clear();
            if looks_like_diff(&stripped) {
                self.buffer.push_str("```diff\n");
            } else {
                self.buffer.push_str("```\n");
            }
            self.buffer.push_str(&stripped);
            self.buffer.push_str("\n```");
            let fenced = std::mem::take(&mut self.buffer);
            return self.render_markdown(style, &fenced);
        }
        if matches!(style, MessageStyle::ToolDetail) {
            if contains_markdown_fence(text) {
                let stripped = crate::utils::ansi_parser::strip_ansi(text);
                return self.render_markdown(style, &stripped);
            }
            if looks_like_diff(text) {
                let stripped = crate::utils::ansi_parser::strip_ansi(text);
                self.buffer.clear();
                self.buffer.push_str("```diff\n");
                self.buffer.push_str(&stripped);
                self.buffer.push_str("\n```");
                let fenced = std::mem::take(&mut self.buffer);
                return self.render_markdown(style, &fenced);
            }
        }
        let indent = style.indent();
        let dont_split = matches!(style, MessageStyle::Tool | MessageStyle::ToolDetail);

        if let Some(sink) = &mut self.sink {
            sink.write_multiline_with_transcript(style.style(), indent, text, Self::message_kind(style), true, None)?;
            return Ok(());
        }

        if text.contains('\n') && !dont_split {
            for line in text.lines() {
                self.buffer.clear();
                if !indent.is_empty() && !line.is_empty() {
                    self.buffer.push_str(indent);
                }
                self.buffer.push_str(line);
                self.flush(style)?;
            }
            Ok(())
        } else {
            self.buffer.clear();
            if !indent.is_empty() && !text.is_empty() {
                self.buffer.push_str(indent);
            }
            self.buffer.push_str(text);
            self.flush(style)
        }
    }

    /// Write a continuation line that joins an existing Pty block.
    ///
    /// Sends the text as `InlineMessageKind::Pty` through
    /// `write_multiline_with_transcript` so the TUI reflow renders it
    /// with the same 2-space block prefix and styling as the PTY output.
    pub fn pty_continuation_line(&mut self, text: &str) -> Result<()> {
        self.flush_compact_command_group();
        let style = MessageStyle::ToolOutput;
        let indent = style.indent();
        let kind = Self::message_kind(style);
        if let Some(sink) = &mut self.sink {
            sink.write_multiline_with_transcript(style.style(), indent, text, kind, true, None)?;
            return Ok(());
        }
        self.buffer.clear();
        if !indent.is_empty() && !text.is_empty() {
            self.buffer.push_str(indent);
        }
        self.buffer.push_str(text);
        self.flush(style)
    }

    /// Write a URL as a full, clickable line using OSC 8 hyperlinks.
    ///
    /// The URL is rendered on its own line so that terminal emulators can
    /// detect and activate it for click-to-open behaviour.
    pub fn hyperlink_line(&mut self, style: MessageStyle, url: &str) -> Result<()> {
        self.flush_compact_command_group();
        if !self.should_render_style(style) {
            return Ok(());
        }
        let indent = style.indent();
        if let Some(sink) = &mut self.sink {
            let linked = format!(
                "{}{}{}",
                vtcode_commons::ansi_codes::hyperlink_open(url),
                url,
                vtcode_commons::ansi_codes::hyperlink_close(),
            );
            sink.write_multiline_with_transcript(
                style.style(),
                indent,
                &linked,
                Self::message_kind(style),
                true,
                None,
            )?;
            self.last_line_was_empty = false;
            return Ok(());
        }
        self.buffer.clear();
        if !indent.is_empty() {
            self.buffer.push_str(indent);
        }
        self.buffer.push_str(&vtcode_commons::ansi_codes::hyperlink_open(url));
        self.buffer.push_str(url);
        self.buffer.push_str(&vtcode_commons::ansi_codes::hyperlink_close());
        let ansi_style = style.style();
        if self.color {
            writeln!(self.writer, "{ansi_style}{}{Reset}", self.buffer)?;
        } else {
            writeln!(self.writer, "{}", self.buffer)?;
        }
        self.writer.flush()?;
        transcript::append(url);
        self.last_line_was_empty = false;
        self.buffer.clear();
        Ok(())
    }

    /// Append a large pasted user message as a placeholder in inline UI.
    pub fn append_paste_placeholder(&mut self, message: &str, line_count: usize) -> Result<()> {
        self.flush_compact_command_group();
        if let Some(sink) = &self.sink {
            sink.handle
                .append_pasted_message(InlineMessageKind::User, message.to_string(), line_count);
            transcript::append(message);
            self.last_line_was_empty = message.trim().is_empty();
            return Ok(());
        }
        self.line(MessageStyle::User, message)
    }

    /// Write styled text without a trailing newline
    pub fn inline_with_style(&mut self, style: MessageStyle, text: &str) -> Result<()> {
        self.flush_compact_command_group();
        if !self.should_render_style(style) {
            return Ok(());
        }
        if let Some(sink) = &mut self.sink {
            sink.write_inline(style.style(), text, Self::message_kind(style));
            return Ok(());
        }
        let ansi_style = style.style();
        if self.color {
            write!(self.writer, "{ansi_style}{text}{Reset}")?;
        } else {
            write!(self.writer, "{text}")?;
        }
        self.writer.flush()?;
        Ok(())
    }

    /// Write a line with an explicit style
    pub fn line_with_style(&mut self, style: Style, text: &str) -> Result<()> {
        self.line_with_override_style(MessageStyle::Info, style, text)
    }

    /// Write a line with a custom style while preserving the logical message kind.
    #[track_caller]
    pub fn line_with_override_style(&mut self, fallback: MessageStyle, style: Style, text: &str) -> Result<()> {
        self.flush_compact_command_group();
        let tool_output_id = self.pending_tool_output_anchor.take();
        if !self.should_render_style(fallback) {
            return Ok(());
        }
        if matches!(fallback, MessageStyle::Error | MessageStyle::ToolError | MessageStyle::Warning) {
            return self.legacy_diagnostic(fallback, text);
        }
        let kind = Self::message_kind(fallback);
        let indent = self.indent_for_style(fallback);
        if let Some(sink) = &mut self.sink {
            sink.write_multiline_with_transcript(style, indent, text, kind, true, tool_output_id)?;
            self.last_line_was_empty = text.trim().is_empty();
            return Ok(());
        }
        let mut combined;
        let display = if !indent.is_empty() && !text.is_empty() {
            combined = String::with_capacity(indent.len() + text.len());
            combined.push_str(indent);
            combined.push_str(text);
            combined.as_str()
        } else {
            text
        };
        if self.color {
            writeln!(self.writer, "{style}{display}{Reset}")?;
        } else {
            writeln!(self.writer, "{display}")?;
        }
        self.writer.flush()?;
        transcript::append(display);
        self.last_line_was_empty = text.trim().is_empty();
        Ok(())
    }

    /// Write an empty line only if the previous line was not empty
    pub fn line_if_not_empty(&mut self, style: MessageStyle) -> Result<()> {
        if !self.was_previous_line_empty() {
            self.line(style, "")
        } else {
            Ok(())
        }
    }

    /// Write a raw line without styling
    pub fn raw_line(&mut self, text: &str) -> Result<()> {
        self.flush_compact_command_group();
        writeln!(self.writer, "{text}")?;
        self.writer.flush()?;
        transcript::append(text);
        Ok(())
    }

    pub fn render_token_delta(&mut self, delta: &str) -> Result<()> {
        self.inline_with_style(MessageStyle::Response, delta)
    }

    pub fn stream_markdown_response(&mut self, text: &str, previous_line_count: usize) -> Result<usize> {
        // Strip ANSI codes from agent response to prevent interference with markdown rendering
        let text = crate::utils::ansi_parser::strip_ansi(text);
        let text = &text;

        let styles = theme::active_styles();
        let style = MessageStyle::Response;
        let base_style = style.style();
        let indent = style.indent();
        if let Some(sink) = &mut self.sink {
            // Read terminal width fresh so tables adapt to resizes.
            if sink.table_max_width_override.is_none()
                && let Ok((w, _)) = crossterm::terminal::size()
            {
                sink.table_max_width = Some(w as usize);
            }
            let table_max_width = sink.table_content_width(Self::message_kind(style), indent);
            let (prepared, plain_lines, last_empty) =
                sink.prepare_markdown_lines_with_table_width(text, indent, base_style, true, true, table_max_width);
            let line_count = prepared.len();
            sink.replace_inline_lines(previous_line_count, prepared, &plain_lines, Self::message_kind(style));
            self.last_line_was_empty = last_empty;
            return Ok(line_count);
        }

        let highlight_cfg = if self.highlight_config.enabled {
            Some(&self.highlight_config)
        } else {
            None
        };
        let mut lines = render_markdown_to_lines_with_options(
            text,
            base_style,
            &styles,
            highlight_cfg,
            RenderMarkdownOptions::default(),
        );
        if lines.is_empty() {
            lines.push(MarkdownLine::default());
        }

        Err(anyhow!("stream_markdown_response requires an inline sink"))
    }

    /// Finish a streamed response, stamping it when no turn is open.
    ///
    /// Streaming replaces the in-progress block per delta, so inside a turn the
    /// footer is only marked here and emitted by
    /// [`AnsiRenderer::finish_turn_message_timestamp`] once the turn ends;
    /// intermediate responses stay unstamped and only the turn's final message
    /// carries the clock. Outside a turn this stamps immediately. No-op without
    /// an inline sink, when timestamps are disabled, or during transcript-batch
    /// replay. The caller owns the "visible content was streamed" condition.
    pub fn finish_streamed_response(&mut self) -> Result<()> {
        let Some(sink) = self.sink.as_mut() else {
            return Ok(());
        };
        if !self.show_message_timestamps || sink.in_transcript_batch() {
            return Ok(());
        }
        if self.defer_turn_footer {
            self.pending_response_footer = true;
            return Ok(());
        }
        let indent = MessageStyle::Response.indent();
        let status_style = theme::active_styles().status;
        sink.append_response_timestamp_footer(status_style, indent)?;
        self.last_line_was_empty = false;
        Ok(())
    }

    /// Emit the single wall-clock footer for the turn that just completed.
    ///
    /// Called once at the turn boundary after the final agent message has been
    /// rendered. Disarms deferral so the next out-of-turn response stamps
    /// immediately again. A no-op when no response body was rendered, when
    /// timestamps are disabled, or during transcript-batch replay.
    pub fn finish_turn_message_timestamp(&mut self) -> Result<()> {
        // Disarm before the early return: the session reuses one renderer, and
        // a turn that rendered nothing must not leave later output deferring
        // into a boundary that will never come.
        self.defer_turn_footer = false;
        if !self.pending_response_footer {
            return Ok(());
        }
        self.pending_response_footer = false;
        if !self.show_message_timestamps {
            return Ok(());
        }
        let indent = MessageStyle::Response.indent();
        if let Some(sink) = self.sink.as_mut() {
            if sink.in_transcript_batch() {
                return Ok(());
            }
            let status_style = theme::active_styles().status;
            sink.append_response_timestamp_footer(status_style, indent)?;
        } else {
            self.write_response_timestamp_footer(indent)?;
        }
        self.last_line_was_empty = false;
        Ok(())
    }
}