cli: suggest the closest flag or command on a typo

An unknown --flag now logs the nearest accepted spelling within two
edits as did_you_mean, painted green next to the red typo in the pretty
log format; logfmt stays plain. A bare first argument within two edits
of a command name is rejected with the same hint instead of being
fetched as a url.

The Levenshtein helper moves from SlashCommand into string.zig so the
agent REPL and the CLI share it, with the table widened to fit the
longest flag name.
This commit is contained in:
Adrià Arrufat committed 2026-09-08 16:50:46 +02:00
1 parent 5d732eb8f1
commit 88d133a676
4 files changed
+177 -30

No files matched your search

+2 -27
View File
@@ -23,6 +23,7 @@
const std = @import("std");
const lp = @import("lightpanda");
const string = @import("../string.zig");
const Command = lp.Command;
const Config = lp.Config;
@@ -108,31 +109,5 @@ pub const all_names: [browser_tools.names.len + meta_commands.len + llm_values.l
/// 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];
return string.closest(name, &all_names, 2);
}