Skip to content

Lightpanda: the headless browser designed for AI and automation

agent: tighten the seams the terminal split left behind

Adrià Arrufatf462223277c8
diff --git a/src/agent/Agent.zig b/src/agent/Agent.zig
index 389b03199..6666b21b1 100644
--- a/src/agent/Agent.zig
+++ b/src/agent/Agent.zig
@@ -358,12 +358,11 @@ pub fn init(allocator: std.mem.Allocator, app: *App, opts: Config.Agent) !*Agent
if (self.ai_client) |c| c.setInterrupt(&self.http_interrupt);
if (will_repl) {
- self.terminal.attachCompleter();
- self.terminal.assist.completion_source = .{
+ self.terminal.attachCompleter(.{
.context = @ptrCast(self),
.providers = completionProviders,
.models = completionModels,
- };
+ });
// The model-list cache fills lazily on the first `/model` completion,
// so startup never blocks on the network.
Terminal.setIdleCallback(&idlePump, @ptrCast(self));
@@ -1373,7 +1372,7 @@ fn printSlashHelp(self: *Agent, arena: std.mem.Allocator, target: []const u8) vo
}
}
const tool_schema = Schema.findByName(target) orelse {
- if (Terminal.closestCommand(target)) |near| {
+ if (SlashCommand.closestCommand(target)) |near| {
self.terminal.printError("unknown command: {s}. Did you mean " ++ Terminal.highlightCmd("/help {s}") ++ "?", .{ target, near });
} else {
self.terminal.printError("unknown command: {s}", .{target});
diff --git a/src/agent/SlashCommand.zig b/src/agent/SlashCommand.zig
index 44da327fb..790f48fe7 100644
--- a/src/agent/SlashCommand.zig
+++ b/src/agent/SlashCommand.zig
@@ -82,3 +82,56 @@ pub fn findMeta(name: []const u8) ?*const MetaCommand {
}
return null;
}
+
+const browser_tools = lp.tools;
+const llm_values = std.enums.values(Command.LlmCommand);
+
+/// Every slash-invocable name: browser tools, LLM triggers, meta commands.
+pub const all_names: [browser_tools.names.len + meta_commands.len + llm_values.len][]const u8 = blk: {
+ var arr: [browser_tools.names.len + meta_commands.len + llm_values.len][]const u8 = undefined;
+ var idx: usize = 0;
+ for (browser_tools.names) |n| {
+ arr[idx] = n;
+ idx += 1;
+ }
+ for (llm_values) |lc| {
+ arr[idx] = @tagName(lc);
+ idx += 1;
+ }
+ for (meta_commands) |m| {
+ arr[idx] = m.name;
+ idx += 1;
+ }
+ break :blk arr;
+};
+
+/// Closest command name within two edits, or null — for "did you mean?" on typos.
+pub fn closestCommand(name: []const u8) ?[]const u8 {
+ var best: ?[]const u8 = null;
+ var best_dist: usize = std.math.maxInt(usize);
+ for (all_names) |cand| {
+ const dist = editDistance(name, cand);
+ if (dist < best_dist) {
+ best_dist = dist;
+ best = cand;
+ }
+ }
+ return if (best_dist <= 2) best else null;
+}
+
+/// Case-insensitive Levenshtein distance. Returns `maxInt` for inputs longer
+/// than the table (no slash command is that long).
+fn editDistance(a: []const u8, b: []const u8) usize {
+ const max = 32;
+ if (a.len >= max or b.len >= max) return std.math.maxInt(usize);
+ var dp: [max][max]usize = undefined;
+ for (0..a.len + 1) |i| dp[i][0] = i;
+ for (0..b.len + 1) |j| dp[0][j] = j;
+ for (a, 1..) |ca, i| {
+ for (b, 1..) |cb, j| {
+ const cost: usize = if (std.ascii.toLower(ca) == std.ascii.toLower(cb)) 0 else 1;
+ dp[i][j] = @min(@min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + cost);
+ }
+ }
+ return dp[a.len][b.len];
+}
diff --git a/src/agent/Spinner.zig b/src/agent/Spinner.zig
index 5cf13cc30..770184a4d 100644
--- a/src/agent/Spinner.zig
+++ b/src/agent/Spinner.zig
@@ -312,9 +312,6 @@ fn renderLocked(self: *Spinner) void {
_ = std.posix.write(std.posix.STDERR_FILENO, written) catch {};
}
-/// Returns the byte length of `bytes` that fits in `max_cells` cells, rounded
-/// down to a whole UTF-8 codepoint. Multi-cell glyphs (CJK, wide emoji) count
-/// as 1 — args are typically ASCII, so the approximation is good enough.
/// Current terminal width in columns, queried via TIOCGWINSZ on stderr.
/// Null when stderr isn't a tty, the ioctl fails, or the kernel reports 0
/// (some pseudo-ttys leave the field unset). Cheap enough to call per render
@@ -330,6 +327,9 @@ fn columns() ?u16 {
return ws.col;
}
+/// Returns the byte length of `bytes` that fits in `max_cells` cells, rounded
+/// down to a whole UTF-8 codepoint. Multi-cell glyphs (CJK, wide emoji) count
+/// as 1 — args are typically ASCII, so the approximation is good enough.
fn truncToCells(bytes: []const u8, max_cells: usize) usize {
var cells: usize = 0;
var i: usize = 0;
diff --git a/src/agent/Terminal.zig b/src/agent/Terminal.zig
index d50a22801..c78f3c788 100644
--- a/src/agent/Terminal.zig
+++ b/src/agent/Terminal.zig
@@ -51,7 +51,7 @@ spinner: Spinner,
/// State for the prompt-assist C callbacks (completion/hints/highlighting);
/// registered by `attachCompleter`, which requires this Terminal to sit at
/// its final address.
-assist: prompt_assist.State = .{},
+assist: prompt_assist.State,
/// Line-buffered markdown state for streamed assistant deltas; its `close`
/// resets everything so fence state can't leak into the next message. Only
/// used on the styled (REPL tty) path, hence the placeholder.
@@ -59,11 +59,13 @@ md_stream: md_term.Stream = .{ .show_table_placeholder = true },
pub const CompletionSource = prompt_assist.CompletionSource;
pub const HistoryPaths = prompt_assist.HistoryPaths;
-pub const closestCommand = prompt_assist.closestCommand;
-/// Wires the isocline completer, hinter, and highlighter to `self.assist`.
-/// Must run after the Terminal is in its final memory location.
-pub fn attachCompleter(self: *Terminal) void {
+/// Wires the isocline completer, hinter, and highlighter to `self.assist`,
+/// with `source` supplying the dynamic `/provider` and `/model` candidates.
+/// Must run after the Terminal is in its final memory location and before
+/// the first `readLine`.
+pub fn attachCompleter(self: *Terminal, source: ?CompletionSource) void {
+ self.assist.completion_source = source;
prompt_assist.attach(&self.assist);
}
@@ -75,7 +77,7 @@ pub fn init(allocator: std.mem.Allocator, history_paths: ?HistoryPaths, verbosit
// Isocline probes the terminal on setup (writes ESC[6n cursor-report on
// stdout), so skip it in script-only mode — `ic_readline` is never
// reached there anyway.
- if (is_repl) prompt_assist.setupRepl(history_paths);
+ if (is_repl) prompt_assist.setupRepl();
const stderr_is_tty = std.posix.isatty(std.posix.STDERR_FILENO);
return .{
.allocator = allocator,
@@ -153,8 +155,8 @@ pub fn readLine(prompt: [*:0]const u8) ?[]const u8 {
// \r) only while isocline reads: while active, Ctrl-C arrives as a CSI-u
// escape rather than raw \x03, so the tty driver raises no SIGINT. Leaving
// it on during thinking/tool runs would make Ctrl-C unable to interrupt them.
- _ = std.posix.write(std.posix.STDOUT_FILENO, "\x1b[>1u") catch {};
- defer _ = std.posix.write(std.posix.STDOUT_FILENO, "\x1b[<u") catch {};
+ _ = std.posix.write(std.posix.STDOUT_FILENO, ansi.kitty_disambiguate) catch {};
+ defer _ = std.posix.write(std.posix.STDOUT_FILENO, ansi.kitty_pop) catch {};
// Isocline auto-appends the line to its (optionally-persisted) history.
const line = c.ic_readline(prompt) orelse return null;
return std.mem.sliceTo(line, 0);
@@ -397,7 +399,7 @@ pub fn printSlashParseError(self: *Terminal, err: Schema.ParseError, name: []con
}
const reason: []const u8 = switch (err) {
error.UnknownTool => {
- if (closestCommand(name)) |near| {
+ if (SlashCommand.closestCommand(name)) |near| {
return self.printError("{s}: unknown command. Did you mean " ++ highlightCmd("/{s}") ++ "? Try /help.", .{ name, near });
}
return self.printError("{s}: unknown command. Try /help.", .{name});
diff --git a/src/agent/ansi.zig b/src/agent/ansi.zig
index 47f87d129..322216525 100644
--- a/src/agent/ansi.zig
+++ b/src/agent/ansi.zig
@@ -33,3 +33,8 @@ pub const blue = "\x1b[34m";
pub const magenta = "\x1b[35m";
pub const clear_eol = "\x1b[K";
pub const clear_line = "\x1b[2K";
+// Kitty keyboard protocol: push the "disambiguate" flag, push legacy
+// encoding (flag 0), pop the pushed entry. Pushes must pair with a pop.
+pub const kitty_disambiguate = "\x1b[>1u";
+pub const kitty_legacy = "\x1b[>0u";
+pub const kitty_pop = "\x1b[<u";
diff --git a/src/agent/picker.zig b/src/agent/picker.zig
index 09604e4b2..c1c7a4d8c 100644
--- a/src/agent/picker.zig
+++ b/src/agent/picker.zig
@@ -99,9 +99,11 @@ const ChoiceState = struct {
const RawTerminal = struct {
original: std.posix.termios,
- fn enable() !RawTerminal {
+ fn enable() error{NotInteractive}!RawTerminal {
if (!interactiveTty()) return error.NotInteractive;
- const original = try std.posix.tcgetattr(std.posix.STDIN_FILENO);
+ // A tty that refuses raw mode is non-interactive for the picker's
+ // purposes: callers degrade to the line prompt.
+ const original = std.posix.tcgetattr(std.posix.STDIN_FILENO) catch return error.NotInteractive;
var raw = original;
raw.iflag.BRKINT = false;
raw.iflag.ICRNL = false;
@@ -116,17 +118,17 @@ const RawTerminal = struct {
raw.lflag.ISIG = false;
raw.cc[@intFromEnum(std.c.V.MIN)] = 0;
raw.cc[@intFromEnum(std.c.V.TIME)] = 1;
- try std.posix.tcsetattr(std.posix.STDIN_FILENO, .FLUSH, raw);
- // Under the kitty "disambiguate" flag that `Terminal.readLine` pushes
- // (`\x1b[>1u`), cursor keys arrive as CSI-u the byte reader can't
- // parse; push flag 0 to force legacy arrow encoding. restore() pops
- // back to the REPL's flag.
- _ = std.posix.write(std.posix.STDOUT_FILENO, "\x1b[>0u") catch {};
+ std.posix.tcsetattr(std.posix.STDIN_FILENO, .FLUSH, raw) catch return error.NotInteractive;
+ // Under `ansi.kitty_disambiguate` (pushed by `Terminal.readLine`),
+ // cursor keys arrive as CSI-u the byte reader can't parse; push the
+ // legacy encoding to force plain arrows. restore() pops back to
+ // whatever the REPL had pushed.
+ _ = std.posix.write(std.posix.STDOUT_FILENO, ansi.kitty_legacy) catch {};
return .{ .original = original };
}
fn restore(self: *const RawTerminal) void {
- _ = std.posix.write(std.posix.STDOUT_FILENO, "\x1b[<u") catch {};
+ _ = std.posix.write(std.posix.STDOUT_FILENO, ansi.kitty_pop) catch {};
std.posix.tcsetattr(std.posix.STDIN_FILENO, .FLUSH, self.original) catch {};
}
};
diff --git a/src/agent/prompt_assist.zig b/src/agent/prompt_assist.zig
index ab82f8320..ab9639ec1 100644
--- a/src/agent/prompt_assist.zig
+++ b/src/agent/prompt_assist.zig
@@ -24,7 +24,6 @@
const std = @import("std");
const lp = @import("lightpanda");
const browser_tools = lp.tools;
-const Command = lp.Command;
const Schema = lp.Schema;
const SlashCommand = @import("SlashCommand.zig");
const js_highlight = @import("js_highlight.zig");
@@ -32,6 +31,8 @@ const c = @cImport({
@cInclude("isocline.h");
});
+// Styles referenced by name in the highlighter below; the kind-mapped styles
+// live only as `styles` table rows.
const style_slash = "ps-slash";
const style_string = "ps-string";
const style_var = "ps-var";
@@ -40,12 +41,6 @@ const style_key = "ps-key";
const style_num = "ps-num";
const style_err = "ps-err";
const style_jsmode = "ps-jsmode";
-const style_keyword = "ps-keyword";
-const style_comment = "ps-comment";
-const style_jsglobal = "ps-jsglobal";
-const style_fn = "ps-fn";
-const style_method = "ps-method";
-const style_type = "ps-type";
/// The prompt's style palette (`ps-*` namespace avoids colliding with
/// isocline's built-in `ic-*` styles). `setupRepl` registers every entry and
@@ -69,12 +64,12 @@ const styles = [_]Style{
.{ .name = style_num, .spec = "ansi-magenta", .kinds = &.{.number} },
.{ .name = style_err, .spec = "ansi-red" },
.{ .name = style_jsmode, .spec = "ansi-red bold" },
- .{ .name = style_keyword, .spec = "ansi-blue bold", .kinds = &.{.keyword} },
- .{ .name = style_comment, .spec = "ansi-darkgray italic", .kinds = &.{.comment} },
- .{ .name = style_jsglobal, .spec = "ansi-cyan", .kinds = &.{.global} },
- .{ .name = style_fn, .spec = "ansi-teal", .kinds = &.{.function} },
- .{ .name = style_method, .spec = "ansi-teal italic", .kinds = &.{.method} },
- .{ .name = style_type, .spec = "ansi-cyan", .kinds = &.{.type_name} },
+ .{ .name = "ps-keyword", .spec = "ansi-blue bold", .kinds = &.{.keyword} },
+ .{ .name = "ps-comment", .spec = "ansi-darkgray italic", .kinds = &.{.comment} },
+ .{ .name = "ps-jsglobal", .spec = "ansi-cyan", .kinds = &.{.global} },
+ .{ .name = "ps-fn", .spec = "ansi-teal", .kinds = &.{.function} },
+ .{ .name = "ps-method", .spec = "ansi-teal italic", .kinds = &.{.method} },
+ .{ .name = "ps-type", .spec = "ansi-cyan", .kinds = &.{.type_name} },
};
/// Style name per token kind, derived from `styles`. Unmapped or
@@ -122,30 +117,11 @@ pub const State = struct {
history_paths: ?HistoryPaths = null,
};
-const llm_values = std.enums.values(Command.LlmCommand);
-const all_slash_names: [browser_tools.names.len + SlashCommand.meta_commands.len + llm_values.len][]const u8 = blk: {
- var arr: [browser_tools.names.len + SlashCommand.meta_commands.len + llm_values.len][]const u8 = undefined;
- var idx: usize = 0;
- for (browser_tools.names) |n| {
- arr[idx] = n;
- idx += 1;
- }
- for (llm_values) |lc| {
- arr[idx] = @tagName(lc);
- idx += 1;
- }
- for (SlashCommand.meta_commands) |m| {
- arr[idx] = m.name;
- idx += 1;
- }
- break :blk arr;
-};
-
/// One-time isocline configuration for REPL mode: editing behavior, the
-/// `ps-*` style palette, JS prompt mode, and history. Isocline probes the
-/// terminal on first use (writes ESC[6n cursor-report on stdout), so callers
-/// must skip this in script-only mode.
-pub fn setupRepl(history_paths: ?HistoryPaths) void {
+/// `ps-*` style palette, and JS prompt mode. Isocline probes the terminal on
+/// first use (writes ESC[6n cursor-report on stdout), so callers must skip
+/// this in script-only mode.
+pub fn setupRepl() void {
_ = c.ic_enable_multiline(true);
_ = c.ic_enable_hint(true);
_ = c.ic_enable_inline_help(true);
@@ -160,16 +136,13 @@ pub fn setupRepl(history_paths: ?HistoryPaths) void {
// Blank continuation marker so multiline input isn't prefixed with `>`.
c.ic_set_prompt_marker("❯ ", "");
_ = c.ic_enable_highlight(true);
- if (history_paths) |hp| {
- // Mode inactive at launch, so load the normal file; modeCallback
- // swaps to JS on mode entry.
- c.ic_set_history(hp.normal.ptr, -1); // -1 → 200-entry default cap
- }
}
/// Wires the isocline completer, hinter, and highlighter to `state` so the C
-/// callbacks can reach the global schemas. Must run after `state` is in its
-/// final memory location.
+/// callbacks can reach the global schemas, and loads the initial history from
+/// `state.history_paths` — the same source `modeCallback` swaps from, so the
+/// two can't diverge. Must run after `state` is in its final memory location
+/// and before the first readline.
pub fn attach(state: *State) void {
c.ic_set_default_completer(&completionCallback, state);
c.ic_set_default_hinter(&hintsCallback, state);
@@ -178,6 +151,11 @@ pub fn attach(state: *State) void {
c.ic_set_esc_clear_hint(" esc again to clear");
c.ic_set_mode_hint(" JS mode - esc to exit");
c.ic_set_default_highlighter(&highlighterCallback, state);
+ if (state.history_paths) |hp| {
+ // Mode inactive at launch, so load the normal file; modeCallback
+ // swaps to JS on mode entry.
+ c.ic_set_history(hp.normal.ptr, -1); // -1 → 200-entry default cap
+ }
}
fn modeCallback(active: bool, arg: ?*anyopaque) callconv(.c) void {
@@ -482,7 +460,7 @@ fn completionCallback(cenv: ?*c.ic_completion_env_t, prefix: [*c]const u8) callc
// `/help <name>`: arg is a command name, not a value — skip env-var fallthrough.
if (parseHelpArgPrefix(input)) |partial| {
- for (all_slash_names) |name| addPrefixedCompletion(cenv, &buf, input, help_arg_prefix, name, "", partial);
+ for (SlashCommand.all_names) |name| addPrefixedCompletion(cenv, &buf, input, help_arg_prefix, name, "", partial);
return;
}
@@ -496,7 +474,7 @@ fn completionCallback(cenv: ?*c.ic_completion_env_t, prefix: [*c]const u8) callc
// Trailing space on commands with params hands off to the hinter,
// which renders the full ` <url> [timeout=…]` template uniformly
// whether the name was typed or Tab-completed.
- for (all_slash_names) |name| {
+ for (SlashCommand.all_names) |name| {
const suffix: []const u8 = if (slashHasParams(name)) " " else "";
addPrefixedCompletion(cenv, &buf, input, "/", name, suffix, partial);
}
@@ -534,12 +512,12 @@ fn hintsCallback(input_c: [*c]const u8, arg: ?*anyopaque) callconv(.c) [*c]const
if (input.len == 0) return null;
- if (parseHelpArgPrefix(input)) |partial| return ghostFirstMatch(&all_slash_names, partial, "");
+ if (parseHelpArgPrefix(input)) |partial| return ghostFirstMatch(&SlashCommand.all_names, partial, "");
// Inside an open `'''…'''` body the buffer is script text, not kv args.
if (Schema.hasUnclosedTripleQuote(input)) return null;
- if (std.mem.eql(u8, input, "/")) return ghostFirstMatch(&all_slash_names, "", "");
+ if (std.mem.eql(u8, input, "/")) return ghostFirstMatch(&SlashCommand.all_names, "", "");
if (Schema.parseSlashCommand(input)) |parts| {
const ends_ws = input[input.len - 1] == ' ';
@@ -550,7 +528,7 @@ fn hintsCallback(input_c: [*c]const u8, arg: ?*anyopaque) callconv(.c) [*c]const
return renderMetaHint(state, meta, parts.rest, ends_ws);
}
if (std.mem.indexOfScalar(u8, input, ' ') == null) {
- return ghostFirstMatch(&all_slash_names, parts.name, "");
+ return ghostFirstMatch(&SlashCommand.all_names, parts.name, "");
}
return null;
}
@@ -674,14 +652,6 @@ fn renderSchemaHint(schema: *const Schema, body: []const u8, ends_ws: bool) [*c]
return writeHints(if (ends_ws) "" else " ", frags[0..n]);
}
-/// Index of the next non-whitespace byte at or after `start`, or null if only
-/// whitespace remains.
-fn skipWhitespace(text: []const u8, start: usize) ?usize {
- var i = start;
- while (i < text.len and std.ascii.isWhitespace(text[i])) i += 1;
- return if (i < text.len) i else null;
-}
-
/// Byte offsets to ic_highlight are not UTF-8 code points; safe because we
/// only tokenize on ASCII boundaries (whitespace, quotes, `=`, `$`).
fn highlighterCallback(henv: ?*c.ic_highlight_env_t, input: [*c]const u8, arg: ?*anyopaque) callconv(.c) void {
@@ -692,7 +662,7 @@ fn highlighterCallback(henv: ?*c.ic_highlight_env_t, input: [*c]const u8, arg: ?
highlightJavaScript(henv, text);
return;
}
- const cmd_start = skipWhitespace(text, 0) orelse return;
+ const cmd_start = std.mem.indexOfNonePos(u8, text, 0, &std.ascii.whitespace) orelse return;
var i = cmd_start;
while (i < text.len and !std.ascii.isWhitespace(text[i])) i += 1;
const cmd = text[cmd_start..i];
@@ -720,50 +690,19 @@ fn highlighterCallback(henv: ?*c.ic_highlight_env_t, input: [*c]const u8, arg: ?
}
fn isKnownSlashName(name: []const u8) bool {
- for (all_slash_names) |n| {
+ for (SlashCommand.all_names) |n| {
if (std.ascii.eqlIgnoreCase(n, name)) return true;
}
return false;
}
fn slashHasPrefix(name: []const u8) bool {
- for (all_slash_names) |n| {
+ for (SlashCommand.all_names) |n| {
if (std.ascii.startsWithIgnoreCase(n, name)) return true;
}
return false;
}
-/// Closest command name within two edits, or null — for "did you mean?" on typos.
-pub fn closestCommand(name: []const u8) ?[]const u8 {
- var best: ?[]const u8 = null;
- var best_dist: usize = std.math.maxInt(usize);
- for (all_slash_names) |cand| {
- const dist = editDistance(name, cand);
- if (dist < best_dist) {
- best_dist = dist;
- best = cand;
- }
- }
- return if (best_dist <= 2) best else null;
-}
-
-/// Case-insensitive Levenshtein distance. Returns `maxInt` for inputs longer
-/// than the table (no slash command is that long).
-fn editDistance(a: []const u8, b: []const u8) usize {
- const max = 32;
- if (a.len >= max or b.len >= max) return std.math.maxInt(usize);
- var dp: [max][max]usize = undefined;
- for (0..a.len + 1) |i| dp[i][0] = i;
- for (0..b.len + 1) |j| dp[0][j] = j;
- for (a, 1..) |ca, i| {
- for (b, 1..) |cb, j| {
- const cost: usize = if (std.ascii.toLower(ca) == std.ascii.toLower(cb)) 0 else 1;
- dp[i][j] = @min(@min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + cost);
- }
- }
- return dp[a.len][b.len];
-}
-
fn slashHasParams(name: []const u8) bool {
if (Schema.findByName(name)) |s| return s.hints.len > 0;
if (SlashCommand.findMeta(name)) |m| return m.hint.len > 0;
@@ -815,7 +754,7 @@ fn highlightJavaScript(henv: ?*c.ic_highlight_env_t, text: []const u8) void {
fn highlightSlashArgs(henv: ?*c.ic_highlight_env_t, text: []const u8, start: usize) void {
var i = start;
- while (skipWhitespace(text, i)) |tok_start| {
+ while (std.mem.indexOfNonePos(u8, text, i, &std.ascii.whitespace)) |tok_start| {
i = tok_start;
if (text[i] == '\'' or text[i] == '"') {
i = Schema.quotedSpanEnd(text, i);