Skip to content

Lightpanda: the headless browser designed for AI and automation

agent: render basic markdown in REPL output

Adrià Arrufatdd1fa4135cd9
diff --git a/src/agent/Terminal.zig b/src/agent/Terminal.zig
index c260fc447..b94e5ff95 100644
--- a/src/agent/Terminal.zig
+++ b/src/agent/Terminal.zig
@@ -24,6 +24,7 @@ const Command = lp.Command;
const Schema = lp.Schema;
const SlashCommand = @import("SlashCommand.zig");
const Spinner = @import("Spinner.zig");
+const md_term = @import("md_term.zig");
const c = @cImport({
@cInclude("isocline.h");
});
@@ -47,6 +48,8 @@ pub const ansi = struct {
pub const bold = "\x1b[1m";
pub const dim = "\x1b[2m";
pub const italic = "\x1b[3m";
+ pub const underline = "\x1b[4m";
+ pub const strike = "\x1b[9m";
pub const cyan = "\x1b[36m";
pub const green = "\x1b[32m";
pub const yellow = "\x1b[33m";
@@ -70,6 +73,7 @@ verbosity: Verbosity,
/// only gates non-interactive runs.
repl_arena: ?std.heap.ArenaAllocator,
stderr_is_tty: bool,
+stdout_is_tty: bool,
spinner: Spinner,
completion_source: ?CompletionSource = null,
/// True while the REPL is in JS mode; set by isocline's mode callback.
@@ -181,6 +185,7 @@ pub fn init(allocator: std.mem.Allocator, history_paths: ?HistoryPaths, verbosit
.verbosity = verbosity,
.repl_arena = if (is_repl) std.heap.ArenaAllocator.init(allocator) else null,
.stderr_is_tty = stderr_is_tty,
+ .stdout_is_tty = std.posix.isatty(std.posix.STDOUT_FILENO),
.spinner = .init(is_repl, stderr_is_tty),
.history_paths = history_paths,
};
@@ -1346,10 +1351,24 @@ test "renderSchemaHint: ghosts enum value once typing, keeps template when empty
try std.testing.expectEqualStrings("load", hintStr(renderSchemaHint(schema, "state=", false)).?);
}
-pub fn printAssistant(_: *Terminal, text: []const u8) void {
+test {
+ _ = md_term;
+}
+
+pub fn printAssistant(self: *Terminal, text: []const u8) void {
if (text.len == 0) return;
const fd = std.posix.STDOUT_FILENO;
- _ = std.posix.write(fd, text) catch {};
+
+ // Style only for the interactive REPL on a real terminal; `--task`/piped
+ // output stays verbatim so it can be consumed programmatically.
+ var arena = std.heap.ArenaAllocator.init(self.allocator);
+ defer arena.deinit();
+ const out = if (self.isRepl() and self.stdout_is_tty)
+ md_term.render(arena.allocator(), text) catch text
+ else
+ text;
+
+ _ = std.posix.write(fd, out) catch {};
_ = std.posix.write(fd, "\n") catch {};
}
diff --git a/src/agent/md_term.zig b/src/agent/md_term.zig
new file mode 100644
index 000000000..79393c6b0
--- /dev/null
+++ b/src/agent/md_term.zig
@@ -0,0 +1,176 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+const std = @import("std");
+const ansi = @import("Terminal.zig").ansi;
+
+/// Render markdown `src` to an ANSI-styled terminal string owned by `arena`.
+pub fn render(arena: std.mem.Allocator, src: []const u8) ![]const u8 {
+ // Output is the input plus a bounded number of short escape sequences.
+ var aw: std.Io.Writer.Allocating = try .initCapacity(arena, src.len + src.len / 4);
+ const w = &aw.writer;
+
+ var in_fence = false;
+ var wrote_any = false;
+ var it = std.mem.splitScalar(u8, src, '\n');
+ while (it.next()) |line| {
+ // Drop the ``` delimiter entirely: no line, no separator.
+ if (std.mem.startsWith(u8, std.mem.trimLeft(u8, line, " \t"), "```")) {
+ in_fence = !in_fence;
+ continue;
+ }
+ if (wrote_any) try w.writeByte('\n');
+ wrote_any = true;
+ try renderLine(w, line, in_fence);
+ }
+ return aw.written();
+}
+
+fn renderLine(w: *std.Io.Writer, line: []const u8, in_fence: bool) !void {
+ if (in_fence) {
+ try styled(w, line, ansi.dim);
+ return;
+ }
+
+ const indent_len = line.len - std.mem.trimLeft(u8, line, " \t").len;
+ const indent = line[0..indent_len];
+ const trimmed = line[indent_len..];
+
+ var hashes: usize = 0;
+ while (hashes < trimmed.len and trimmed[hashes] == '#') hashes += 1;
+ if (hashes >= 1 and hashes <= 6 and hashes < trimmed.len and trimmed[hashes] == ' ') {
+ try w.writeAll(ansi.bold);
+ try renderInline(w, std.mem.trimLeft(u8, trimmed[hashes..], " "));
+ try w.writeAll(ansi.reset);
+ return;
+ }
+
+ if (trimmed.len >= 2 and (trimmed[0] == '-' or trimmed[0] == '*' or trimmed[0] == '+') and trimmed[1] == ' ') {
+ try w.writeAll(indent);
+ try styled(w, "•", ansi.dim);
+ try w.writeByte(' ');
+ try renderInline(w, trimmed[2..]);
+ return;
+ }
+
+ // Numbered list keeps its marker verbatim; a bullet is normalized to '•'.
+ var digits: usize = 0;
+ while (digits < trimmed.len and std.ascii.isDigit(trimmed[digits])) digits += 1;
+ if (digits > 0 and digits + 1 < trimmed.len and
+ (trimmed[digits] == '.' or trimmed[digits] == ')') and trimmed[digits + 1] == ' ')
+ {
+ try w.writeAll(indent);
+ try w.writeAll(trimmed[0 .. digits + 2]);
+ try renderInline(w, trimmed[digits + 2 ..]);
+ return;
+ }
+
+ try renderInline(w, line);
+}
+
+fn renderInline(w: *std.Io.Writer, text: []const u8) !void {
+ var i: usize = 0;
+ while (i < text.len) {
+ switch (text[i]) {
+ '`' => if (std.mem.indexOfPos(u8, text, i + 1, "`")) |end| {
+ try styled(w, text[i + 1 .. end], ansi.cyan);
+ i = end + 1;
+ continue;
+ },
+ '*', '_' => |ch| {
+ const double = [2]u8{ ch, ch };
+ if (i + 1 < text.len and text[i + 1] == ch) {
+ if (std.mem.indexOfPos(u8, text, i + 2, &double)) |end| {
+ try styled(w, text[i + 2 .. end], ansi.bold);
+ i = end + 2;
+ continue;
+ }
+ } else if (std.mem.indexOfScalarPos(u8, text, i + 1, ch)) |end| {
+ try styled(w, text[i + 1 .. end], ansi.italic);
+ i = end + 1;
+ continue;
+ }
+ },
+ '~' => if (i + 1 < text.len and text[i + 1] == '~') {
+ if (std.mem.indexOfPos(u8, text, i + 2, "~~")) |end| {
+ try styled(w, text[i + 2 .. end], ansi.strike);
+ i = end + 2;
+ continue;
+ }
+ },
+ '[' => if (std.mem.indexOfPos(u8, text, i + 1, "](")) |mid| {
+ if (std.mem.indexOfScalarPos(u8, text, mid + 2, ')')) |end| {
+ try renderLink(w, text[i + 1 .. mid], text[mid + 2 .. end]);
+ i = end + 1;
+ continue;
+ }
+ },
+ else => {},
+ }
+ try w.writeByte(text[i]);
+ i += 1;
+ }
+}
+
+fn styled(w: *std.Io.Writer, inner: []const u8, style: []const u8) !void {
+ try w.writeAll(style);
+ try w.writeAll(inner);
+ try w.writeAll(ansi.reset);
+}
+
+fn renderLink(w: *std.Io.Writer, label: []const u8, url: []const u8) !void {
+ try styled(w, label, ansi.underline);
+ try w.print(" {s}({s}){s}", .{ ansi.dim, url, ansi.reset });
+}
+
+const testing = std.testing;
+
+fn expectRender(expected: []const u8, src: []const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ try testing.expectEqualStrings(expected, try render(arena.allocator(), src));
+}
+
+test "md_term: inline styles" {
+ try expectRender("say \x1b[1mhi\x1b[0m now", "say **hi** now");
+ try expectRender("say \x1b[3mhi\x1b[0m now", "say *hi* now");
+ try expectRender("say \x1b[3mhi\x1b[0m now", "say _hi_ now");
+ try expectRender("run \x1b[36mls\x1b[0m ok", "run `ls` ok");
+ try expectRender("no \x1b[9mway\x1b[0m", "no ~~way~~");
+}
+
+test "md_term: blocks" {
+ try expectRender("\x1b[1mTitle\x1b[0m", "# Title");
+ try expectRender("\x1b[1mSub\x1b[0m", "### Sub");
+ try expectRender("\x1b[2m•\x1b[0m item", "- item");
+ try expectRender("1. item", "1. item");
+}
+
+test "md_term: fenced code block" {
+ try expectRender("\x1b[2mlet x = 1;\x1b[0m", "```\nlet x = 1;\n```");
+}
+
+test "md_term: link" {
+ try expectRender("\x1b[4mLP\x1b[0m \x1b[2m(https://x.io)\x1b[0m", "[LP](https://x.io)");
+}
+
+test "md_term: unterminated markers stay literal" {
+ try expectRender("say **hi now", "say **hi now");
+ try expectRender("a * b", "a * b");
+ try expectRender("see [x](y", "see [x](y");
+}