opencrabs 0.3.15

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
//! Markdown Rendering
//!
//! Converts markdown text to styled Ratatui widgets.

use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};

use unicode_width::UnicodeWidthStr;

use super::highlight::highlight_code;

const TABLE_BORDER: Color = Color::DarkGray;
const TABLE_HEADER: Color = Color::Rgb(120, 120, 120);

/// Parse markdown and convert to styled lines for Ratatui.
///
/// `max_width` is the available content width in columns — used to decide
/// whether tables fit as columns or must collapse to card/row format.
pub fn parse_markdown(markdown: &str, max_width: usize) -> Vec<Line<'static>> {
    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    let parser = Parser::new_ext(markdown, options);
    let mut lines = Vec::new();
    let mut current_line: Vec<Span<'static>> = Vec::new();
    let mut in_code_block = false;
    let mut code_language = String::new();
    let mut code_content = String::new();
    let mut list_level: u32 = 0;
    let mut heading_level = 1;

    // Table accumulation state
    let mut in_table = false;
    let mut table_headers: Vec<String> = Vec::new();
    let mut table_rows: Vec<Vec<String>> = Vec::new();
    let mut current_row: Vec<String> = Vec::new();
    let mut current_cell = String::new();
    for event in parser {
        match event {
            Event::Start(tag) => match tag {
                Tag::Heading { level, .. } => {
                    heading_level = level as u32;
                }
                Tag::CodeBlock(kind) => {
                    in_code_block = true;
                    code_language = match kind {
                        CodeBlockKind::Fenced(lang) => lang.to_string(),
                        CodeBlockKind::Indented => String::new(),
                    };

                    // Add code block header if language is specified
                    if !code_language.is_empty() {
                        if !current_line.is_empty() {
                            lines.push(Line::from(std::mem::take(&mut current_line)));
                        }
                        lines.push(Line::from(vec![
                            Span::styled("╭─ ", Style::default().fg(Color::DarkGray)),
                            Span::styled(
                                code_language.clone(),
                                Style::default()
                                    .fg(Color::Rgb(120, 120, 120))
                                    .add_modifier(Modifier::BOLD),
                            ),
                            Span::styled("", Style::default().fg(Color::DarkGray)),
                        ]));
                    }
                }
                Tag::List(_) => {
                    list_level += 1;
                }
                Tag::Table(_alignments) => {
                    in_table = true;
                    table_headers.clear();
                    table_rows.clear();
                    if !current_line.is_empty() {
                        lines.push(Line::from(std::mem::take(&mut current_line)));
                    }
                }
                Tag::TableHead => {
                    current_row.clear();
                }
                Tag::TableRow => {
                    current_row.clear();
                }
                Tag::TableCell => {
                    current_cell.clear();
                }
                Tag::Strong | Tag::Emphasis => {}
                Tag::BlockQuote(_) if !current_line.is_empty() => {
                    lines.push(Line::from(std::mem::take(&mut current_line)));
                }
                _ => {}
            },

            Event::End(tag) => match tag {
                TagEnd::Heading(_) if !current_line.is_empty() => {
                    let prefix = match heading_level {
                        1 => "# ",
                        2 => "## ",
                        3 => "### ",
                        _ => "",
                    };

                    let mut styled_line = vec![Span::styled(
                        prefix.to_string(),
                        Style::default()
                            .fg(Color::Rgb(120, 120, 120))
                            .add_modifier(Modifier::BOLD),
                    )];

                    for span in &mut current_line {
                        *span = span.clone().style(
                            Style::default()
                                .fg(Color::Rgb(120, 120, 120))
                                .add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
                        );
                    }

                    styled_line.extend(std::mem::take(&mut current_line));
                    lines.push(Line::from(styled_line));
                    lines.push(Line::from(""));
                }
                TagEnd::CodeBlock => {
                    if !current_line.is_empty() {
                        lines.push(Line::from(std::mem::take(&mut current_line)));
                    }

                    if !code_content.is_empty() {
                        let is_plain = code_language.is_empty()
                            || matches!(
                                code_language.as_str(),
                                "text" | "plain" | "plaintext" | "txt"
                            );

                        if is_plain && looks_like_table(&code_content) {
                            // Pipe-style markdown table inside a code block —
                            // re-parse so the table renderer handles it.
                            let table_lines = parse_markdown(&code_content, max_width);
                            lines.extend(table_lines);
                        } else if is_plain
                            && let Some((hdrs, rws)) = parse_box_drawing_table(&code_content)
                        {
                            // Box-drawing table (┌│├└) — extract cells and
                            // render via render_table for responsive layout.
                            render_table(&mut lines, &hdrs, &rws, max_width);
                        } else if is_plain {
                            // Plain text: render without line numbers or
                            // syntax highlighting — just indented gray text.
                            for line_str in code_content.lines() {
                                lines.push(Line::from(Span::styled(
                                    format!("  {line_str}"),
                                    Style::default().fg(Color::Gray),
                                )));
                            }
                        } else {
                            let highlighted_lines = highlight_code(&code_content, &code_language);
                            lines.extend(highlighted_lines);
                            lines.push(Line::from(Span::styled(
                                "╰────".to_string(),
                                Style::default().fg(Color::DarkGray),
                            )));
                        }
                    }

                    lines.push(Line::from(""));
                    in_code_block = false;
                    code_language.clear();
                    code_content.clear();
                }
                TagEnd::List(_) => {
                    list_level = list_level.saturating_sub(1);
                    if list_level == 0 {
                        lines.push(Line::from(""));
                    }
                }
                TagEnd::Paragraph => {
                    if !current_line.is_empty() {
                        lines.push(Line::from(std::mem::take(&mut current_line)));
                    }
                    lines.push(Line::from(""));
                }
                TagEnd::Item if !current_line.is_empty() => {
                    lines.push(Line::from(std::mem::take(&mut current_line)));
                }
                TagEnd::BlockQuote(_) => {
                    lines.push(Line::from(""));
                }
                TagEnd::TableCell => {
                    current_row.push(std::mem::take(&mut current_cell));
                }
                TagEnd::TableHead => {
                    table_headers = std::mem::take(&mut current_row);
                }
                TagEnd::TableRow => {
                    table_rows.push(std::mem::take(&mut current_row));
                }
                TagEnd::Table => {
                    in_table = false;
                    render_table(&mut lines, &table_headers, &table_rows, max_width);
                    table_headers.clear();
                    table_rows.clear();
                    lines.push(Line::from(""));
                }
                _ => {}
            },

            Event::Text(text) => {
                let text_str = text.to_string();

                if in_table {
                    current_cell.push_str(&text_str);
                } else if in_code_block {
                    code_content.push_str(&text_str);
                } else {
                    current_line.push(Span::styled(text_str, Style::default()));
                }
            }

            Event::Code(code) => {
                if in_table {
                    current_cell.push_str(&format!("`{code}`"));
                } else {
                    current_line.push(Span::styled(
                        format!("`{code}`"),
                        Style::default()
                            .fg(Color::Rgb(215, 100, 20))
                            .add_modifier(Modifier::BOLD),
                    ));
                }
            }

            Event::HardBreak if !current_line.is_empty() => {
                lines.push(Line::from(std::mem::take(&mut current_line)));
            }

            // CommonMark: a soft break (single newline inside a paragraph)
            // renders as a space so the layout engine can reflow. Treating
            // it as a hard break baked the LLM's 72-col source wrap into
            // chat history, making replies appear narrow on wide terminals.
            Event::SoftBreak if !current_line.is_empty() => {
                current_line.push(Span::raw(" "));
            }

            Event::Rule => {
                if !current_line.is_empty() {
                    lines.push(Line::from(std::mem::take(&mut current_line)));
                }
                lines.push(Line::from(Span::styled(
                    "────────────────────────────────────────".to_string(),
                    Style::default().fg(Color::DarkGray),
                )));
                lines.push(Line::from(""));
            }

            // Render HTML/inline-HTML as plain text so tags like <tool_use>
            // mentioned in prose are not silently swallowed.
            Event::Html(html) | Event::InlineHtml(html) => {
                let html_str = html.to_string();
                if in_code_block {
                    code_content.push_str(&html_str);
                } else {
                    current_line.push(Span::styled(html_str, Style::default()));
                }
            }

            _ => {}
        }
    }

    // Add any remaining content
    if !current_line.is_empty() {
        lines.push(Line::from(current_line));
    }

    // Remove trailing empty lines
    while lines.last().is_some_and(|line| line.spans.is_empty()) {
        lines.pop();
    }

    lines
}

/// Heuristic: does this text look like a markdown table?
/// Detects pipe tables (`| col |`) with a separator (`|---|`).
fn looks_like_table(text: &str) -> bool {
    let mut pipe_lines = 0;
    let mut has_separator = false;
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('|') && trimmed.ends_with('|') && trimmed.len() > 2 {
            pipe_lines += 1;
        }
        if trimmed.starts_with('|') && trimmed.contains("---") {
            has_separator = true;
        }
    }
    pipe_lines >= 3 && has_separator
}

/// Try to parse a box-drawing table (┌│├└ or +|-+ ASCII style) into headers
/// and rows. Returns `None` if the text doesn't look like a box-drawing table.
fn parse_box_drawing_table(text: &str) -> Option<(Vec<String>, Vec<Vec<String>>)> {
    let mut headers: Vec<String> = Vec::new();
    let mut rows: Vec<Vec<String>> = Vec::new();

    for line in text.lines() {
        let trimmed = line.trim();
        // Skip border/separator lines
        if trimmed.is_empty()
            || trimmed.starts_with('')
            || trimmed.starts_with('')
            || trimmed.starts_with('')
            || trimmed.starts_with('')
            || trimmed.starts_with('')
            || trimmed.starts_with('')
            || trimmed.starts_with('+')
            || trimmed.chars().all(|c| {
                matches!(
                    c,
                    '' | '-'
                        | ''
                        | ''
                        | ''
                        | ''
                        | ''
                        | ''
                        | ''
                        | ''
                        | ''
                        | '+'
                        | ' '
                )
            })
        {
            continue;
        }
        // Data lines: │ cell │ cell │  or  | cell | cell |
        if trimmed.starts_with('') || trimmed.starts_with('|') {
            let cells: Vec<String> = trimmed
                .split('')
                .chain(
                    // Also split on ASCII pipe if no box-drawing vertical found
                    if !trimmed.contains('') {
                        trimmed.split('|').collect::<Vec<_>>()
                    } else {
                        vec![]
                    },
                )
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            if !cells.is_empty() {
                if headers.is_empty() {
                    headers = cells;
                } else {
                    rows.push(cells);
                }
            }
        }
    }

    if headers.is_empty() || rows.is_empty() {
        return None;
    }
    Some((headers, rows))
}

/// Render a markdown table as either columnar (wide) or card (narrow) format.
///
/// Columnar: box-drawing borders, padded columns, header separator.
/// Card: each row rendered as "Header: Value" lines with horizontal rule separators.
fn render_table(
    lines: &mut Vec<Line<'static>>,
    headers: &[String],
    rows: &[Vec<String>],
    max_width: usize,
) {
    let ncols = headers.len();
    if ncols == 0 {
        return;
    }

    // Calculate column widths using display width (not byte length)
    let mut col_widths: Vec<usize> = (0..ncols)
        .map(|c| {
            let header_w = headers[c].width();
            let max_cell = rows
                .iter()
                .map(|r| r.get(c).map_or(0, |s| s.width()))
                .max()
                .unwrap_or(0);
            header_w.max(max_cell)
        })
        .collect();

    // Total table width: borders + padding (│ cell │ cell │)
    // = 1 (left border) + sum(col_width + 3) for each col (space + content + space + border)
    // But last col doesn't need trailing border counted separately
    let table_width: usize = 1 + col_widths.iter().map(|w| w + 3).sum::<usize>();

    let border_style = Style::default().fg(TABLE_BORDER);
    let header_style = Style::default()
        .fg(TABLE_HEADER)
        .add_modifier(Modifier::BOLD);

    if table_width <= max_width {
        // Distribute extra space proportionally — wider columns get more
        let extra = max_width.saturating_sub(table_width);
        if extra > 0 {
            let total_content: usize = col_widths.iter().sum::<usize>().max(1);
            let mut assigned = 0usize;
            for (i, w) in col_widths.iter_mut().enumerate() {
                let share = if i + 1 == ncols {
                    extra - assigned // last column gets remainder
                } else {
                    extra * *w / total_content
                };
                *w += share;
                assigned += share;
            }
        }

        // ── Columnar format ──
        // Top border: ┌───┬───┐
        let mut top = String::from("");
        for (i, w) in col_widths.iter().enumerate() {
            top.push_str(&"".repeat(w + 2));
            top.push(if i + 1 < ncols { '' } else { '' });
        }
        lines.push(Line::from(Span::styled(top, border_style)));

        // Header row: │ h1 │ h2 │
        let mut hdr_spans: Vec<Span<'static>> = vec![Span::styled("", border_style)];
        for (i, h) in headers.iter().enumerate() {
            hdr_spans.push(Span::styled(
                format!(" {:<width$} ", h, width = col_widths[i]),
                header_style,
            ));
            hdr_spans.push(Span::styled("", border_style));
        }
        lines.push(Line::from(hdr_spans));

        // Header separator: ├───┼───┤
        let mut sep = String::from("");
        for (i, w) in col_widths.iter().enumerate() {
            sep.push_str(&"".repeat(w + 2));
            sep.push(if i + 1 < ncols { '' } else { '' });
        }
        lines.push(Line::from(Span::styled(sep, border_style)));

        // Data rows
        for row in rows {
            let mut row_spans: Vec<Span<'static>> = vec![Span::styled("", border_style)];
            for (i, w) in col_widths.iter().enumerate() {
                let cell = row.get(i).map_or("", |s| s.as_str());
                row_spans.push(Span::raw(format!(" {:<width$} ", cell, width = *w)));
                row_spans.push(Span::styled("", border_style));
            }
            lines.push(Line::from(row_spans));
        }

        // Bottom border: └───┴───┘
        let mut bot = String::from("");
        for (i, w) in col_widths.iter().enumerate() {
            bot.push_str(&"".repeat(w + 2));
            bot.push(if i + 1 < ncols { '' } else { '' });
        }
        lines.push(Line::from(Span::styled(bot, border_style)));
    } else {
        // ── Card format (narrow) ──
        // Each row becomes a card: "Header: Value" lines separated by ──
        let max_header_len = headers.iter().map(|h| h.width()).max().unwrap_or(0);

        for (row_idx, row) in rows.iter().enumerate() {
            for (c, header) in headers.iter().enumerate() {
                let value = row.get(c).map_or("", |s| s.as_str());
                lines.push(Line::from(vec![
                    Span::styled(
                        format!("{:<width$}", header, width = max_header_len),
                        header_style,
                    ),
                    Span::styled(": ", Style::default().fg(Color::DarkGray)),
                    Span::raw(value.to_string()),
                ]));
            }
            // Separator between cards (not after the last one)
            if row_idx + 1 < rows.len() {
                let rule_len = max_width.min(max_header_len + 30);
                lines.push(Line::from(Span::styled("".repeat(rule_len), border_style)));
            }
        }
    }
}

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

    #[test]
    fn test_parse_simple_text() {
        let md = "Hello world";
        let lines = parse_markdown(md, 80);
        assert!(!lines.is_empty());
    }

    #[test]
    fn test_parse_heading() {
        let md = "# Heading 1\n\nSome text";
        let lines = parse_markdown(md, 80);
        assert!(lines.len() > 1);
    }

    #[test]
    fn test_parse_code_block() {
        let md = "```rust\nfn main() {}\n```";
        let lines = parse_markdown(md, 80);
        assert!(lines.len() > 2); // Header, code, footer
    }

    #[test]
    fn test_parse_inline_code() {
        let md = "Use `cargo build` to compile";
        let lines = parse_markdown(md, 80);
        assert!(!lines.is_empty());
    }

    #[test]
    fn test_parse_list() {
        let md = "- Item 1\n- Item 2\n- Item 3";
        let lines = parse_markdown(md, 80);
        assert!(lines.len() >= 3);
    }

    #[test]
    fn test_parse_horizontal_rule() {
        let md = "Before\n\n---\n\nAfter";
        let lines = parse_markdown(md, 80);
        assert!(lines.len() > 2);
    }

    #[test]
    fn test_empty_markdown() {
        let md = "";
        let lines = parse_markdown(md, 80);
        assert!(lines.is_empty() || lines.iter().all(|l| l.spans.is_empty()));
    }

    #[test]
    fn test_table_wide_columnar() {
        let md = "| name | age |\n|---|---|\n| Alice | 30 |\n| Bob | 25 |";
        let lines = parse_markdown(md, 80);
        // Should contain box-drawing chars
        let text: String = lines
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
            .collect();
        assert!(text.contains(''), "Should have top border");
        assert!(text.contains(''), "Should have cell borders");
        assert!(text.contains(''), "Should have bottom border");
    }

    #[test]
    fn test_table_narrow_card() {
        let md = "| name | department | location | salary |\n|---|---|---|---|\n| Alice | Engineering | San Francisco | $145,000 |";
        let lines = parse_markdown(md, 30); // Too narrow for table
        // Should render as card format: "Header: Value"
        let text: String = lines
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
            .collect();
        assert!(text.contains("name"), "Should have header as label");
        assert!(text.contains(": "), "Should have key:value separator");
        assert!(!text.contains(''), "Should NOT have box borders");
    }
}