graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
refactor: extract line editor into readline.zig + input_util.zig (600-line goal)
justrach38384f15447d
diff --git a/src/input_util.zig b/src/input_util.zignew file mode 100644index 00000000..929039e7--- /dev/null+++ b/src/input_util.zig@@ -0,0 +1,505 @@+//! Line-editor input helpers split out of main.zig (600-line goal): tab+//! completion (fillCompletions), line-wrap math (wrapAt/LineRender/+//! parseDsrCol), the ultracode wave-shine palette, the `@` file picker's+//! binary/dir filters + file collection (codedb-backed with a walk+//! fallback), drag-and-drop path cleanup, and the redraw + buffer-editing+//! helpers hoisted out of readLine's body (redraw/setLine/delRange/+//! prevWord/nextWord/addMark) so readline.zig stays under the line goal.+//! readline.zig is this file's only consumer of those; main.zig back-+//! aliases isImagePath (vision.zig also back-imports it) and binaryFileExt+//! (a read_file guard elsewhere in main.zig calls it directly), and+//! mod-qualifies the mutable g_shine_phase (ultracode wave animation frame,+//! written by readLine's idle-tick loop, read by ultracodeWaveHue here).++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const terminal = @import("term.zig");+const termCols = terminal.termCols;++const jobs = @import("jobs.zig");+const runCapped = jobs.runCapped;++const pricing = @import("pricing.zig");+const model_table = pricing.model_table;++const main_mod = @import("main.zig");+const provider_specs = main_mod.provider_specs;+const repl_commands = main_mod.repl_commands;+const bash_stdout_cap = main_mod.bash_stdout_cap;++pub var g_shine_phase: usize = 0; // ultracode input-wave animation frame++/// Tab-completion candidates for the current input. After `/model ` →+/// model names (deduped) + provider ids matching the partial; a bare `/word`+/// → slash commands. Returns the byte offset of the word being completed+/// (so the caller can splice in a candidate). Candidates are static slices.+pub fn fillCompletions(gpa: Allocator, line: []const u8, out: *std.ArrayList([]const u8)) usize {+ const mp = "/model ";+ if (std.mem.startsWith(u8, line, mp)) {+ const partial = line[mp.len..];+ for (model_table) |m| {+ if (!std.mem.startsWith(u8, m.name, partial)) continue;+ var dup = false;+ for (out.items) |x| if (std.mem.eql(u8, x, m.name)) {+ dup = true;+ };+ if (!dup) out.append(gpa, m.name) catch {};+ }+ for (provider_specs) |s| if (std.mem.startsWith(u8, s.id, partial)) out.append(gpa, s.id) catch {};+ return mp.len;+ }+ if (line.len > 0 and line[0] == '/' and std.mem.indexOfScalar(u8, line, ' ') == null) {+ for (repl_commands) |cmd| if (std.mem.startsWith(u8, cmd, line)) out.append(gpa, cmd) catch {};+ return 0;+ }+ return line.len;+}++/// Screen position of a byte in a wrapped input line: given the prompt width+/// `plen` (columns the prompt occupies on the first row), terminal width+/// `cols`, and byte index `pos` into the buffer, the cursor's 0-based row+/// (counted from the prompt row) and 0-based column. The buffer wraps every+/// `cols` columns, so a byte sitting just past a row edge is col 0 of the next+/// row. Pure (unit-tested below); redraw uses it to place the cursor.+fn wrapAt(plen: usize, cols: usize, pos: usize) struct { row: usize, col: usize } {+ const c = if (cols == 0) 1 else cols;+ const flat = plen + pos;+ return .{ .row = flat / c, .col = flat % c };+}++/// Persisted across `readLine`'s redraws: how many rows the wrapped input+/// occupied last time (a count ≥1) and which 0-based row the cursor sat on.+/// The redraw clears exactly these rows relative to where the cursor is now —+/// no absolute cursor save (DECSC), which a wrap-induced scroll would strand.+/// Input taller than the screen is unsupported (same caveat as bash/zsh).+pub const LineRender = struct { rows: usize = 1, crow: usize = 0 };++/// Column from a DSR cursor-position reply — `seq` is the CSI body with the+/// ESC stripped, e.g. "[12;34R". Null (caller falls back to column 1) on+/// anything malformed, including the meaningless column 0.+pub fn parseDsrCol(seq: []const u8) ?usize {+ if (seq.len < 5 or seq[0] != '[' or seq[seq.len - 1] != 'R') return null;+ const semi = std.mem.indexOfScalar(u8, seq, ';') orelse return null;+ const col = std.fmt.parseInt(usize, seq[semi + 1 .. seq.len - 1], 10) catch return null;+ return if (col == 0) null else col;+}++/// Raw RGB stops for the ultracode wave (mirrors ultracode_rainbow's hues).+const ultracode_rgb = [_]struct { r: u8, g: u8, b: u8 }{+ .{ .r = 255, .g = 87, .b = 51 },+ .{ .r = 255, .g = 159, .b = 28 },+ .{ .r = 255, .g = 222, .b = 51 },+ .{ .r = 120, .g = 255, .b = 51 },+ .{ .r = 51, .g = 255, .b = 170 },+ .{ .r = 51, .g = 170, .b = 255 },+ .{ .r = 120, .g = 51, .b = 255 },+ .{ .r = 210, .g = 51, .b = 255 },+ .{ .r = 255, .g = 51, .b = 159 },+};++/// Smoothly interpolated rainbow hue for the ultracode wave. `pos_q8` is a+/// 0..2048 fraction across the 9-stop palette (8 bits index + 8 bits blend),+/// so the wave glides between colors instead of snapping. A sine brightness+/// breath (period ~2.2s at 110ms/tick) gives a rhythmic pulse rather than a+/// mechanical scroll. Writes the SGR escape straight to the writer.+fn ultracodeWaveHue(w: *Io.Writer, pos_q8: u16, phase: usize) void {+ const pal = &ultracode_rgb;+ const len: u16 = pal.len;+ const p: u16 = pos_q8 + @as(u16, @intCast(phase * 32));+ const idx: u16 = (p >> 8) % len;+ const frac: u16 = p & 0xff;+ const a = pal[idx];+ const b = pal[(idx + 1) % len];+ // Interpolate in signed space (b-a may be negative) then clamp to 0..255.+ const r: i32 = @as(i32, a.r) + @divTrunc((@as(i32, b.r) - @as(i32, a.r)) * @as(i32, frac), 256);+ const g: i32 = @as(i32, a.g) + @divTrunc((@as(i32, b.g) - @as(i32, a.g)) * @as(i32, frac), 256);+ const bl: i32 = @as(i32, a.b) + @divTrunc((@as(i32, b.b) - @as(i32, a.b)) * @as(i32, frac), 256);+ // Breath: a gentle sine over phase, period 20 ticks (~2.2s @ 110ms),+ // modulating brightness between ~81% and ~94% — a soft, subtle pulse.+ const breath: u16 = switch (phase % 20) {+ 0 => 120,+ 1 => 120,+ 2 => 118,+ 3 => 117,+ 4 => 114,+ 5 => 112,+ 6 => 110,+ 7 => 107,+ 8 => 106,+ 9 => 104,+ 10 => 104,+ 11 => 104,+ 12 => 106,+ 13 => 107,+ 14 => 110,+ 15 => 112,+ 16 => 114,+ 17 => 117,+ 18 => 118,+ else => 120,+ };+ const sc: i32 = @as(i32, breath);+ const cr: u8 = @intCast(@max(0, @min(255, @divTrunc(r * sc, 128))));+ const cg: u8 = @intCast(@max(0, @min(255, @divTrunc(g * sc, 128))));+ const cb: u8 = @intCast(@max(0, @min(255, @divTrunc(bl * sc, 128))));+ w.print("\x1b[38;2;{d};{d};{d}m", .{ cr, cg, cb }) catch {};+}++/// Directories the `@` file picker never descends into (every dot-dir is+/// also skipped): package/build output and caches — never @-mention targets.+const atpick_skip_dirs = [_][]const u8{ "node_modules", "zig-out", "zig-cache", "__pycache__", "venv", "target", "dist", "build" };+const atpick_max_files = 5000;++fn atpickSkipDir(name: []const u8) bool {+ if (name.len > 0 and name[0] == '.') return true;+ for (atpick_skip_dirs) |s| if (std.mem.eql(u8, name, s)) return true;+ return false;+}++/// Extensions treated as binary: hidden from the `@` picker and refused by+/// read_file (which points the model at bash converters like pdftotext).+const binary_exts = [_][]const u8{ "pdf", "png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "icns", "tiff", "zip", "tar", "gz", "tgz", "bz2", "xz", "zst", "7z", "rar", "exe", "dll", "so", "dylib", "a", "o", "wasm", "class", "jar", "pyc", "woff", "woff2", "ttf", "otf", "eot", "mp3", "mp4", "m4a", "mov", "avi", "mkv", "wav", "flac", "ogg", "sqlite", "db", "bin" };++pub fn binaryFileExt(name: []const u8) bool {+ const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return false;+ const ext = name[dot + 1 ..];+ for (binary_exts) |b| if (std.ascii.eqlIgnoreCase(ext, b)) return true;+ return false;+}++/// Image types stageImagePath understands (a dropped one becomes a vision+/// attachment instead of an inlined path).+pub fn isImagePath(name: []const u8) bool {+ const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return false;+ const ext = name[dot + 1 ..];+ for ([_][]const u8{ "png", "jpg", "jpeg", "gif", "webp" }) |e| if (std.ascii.eqlIgnoreCase(ext, e)) return true;+ return false;+}++/// Pull the `@` picker's file list from codedb's index (`codedb glob '**/*'`):+/// gitignore-aware and instant once the repo is indexed, unlike the blind+/// walk below. Returns false when codedb is missing, errors, or knows no+/// files — the caller falls back to the walk. Entries are gpa-owned.+fn collectCodedbFiles(io: Io, gpa: Allocator, files: *std.ArrayList([]const u8)) bool {+ const run = runCapped(gpa, io, &.{ "codedb", "glob", "**/*" }, bash_stdout_cap, 4096, 0) catch return false;+ defer {+ gpa.free(run.stdout);+ gpa.free(run.stderr);+ }+ const code: ?u8 = switch (run.term) {+ .exited => |c| c,+ else => null,+ };+ if (code == null or code.? != 0) return false;+ // A truncated capture may end mid-path: only parse up to the last newline.+ const safe_end = if (run.stdout_truncated)+ (std.mem.lastIndexOfScalar(u8, run.stdout, '\n') orelse 0)+ else+ run.stdout.len;+ var it = std.mem.splitScalar(u8, run.stdout[0..safe_end], '\n');+ while (it.next()) |ln| {+ if (files.items.len >= atpick_max_files) break;+ const line = std.mem.trim(u8, ln, " \t\r");+ if (line.len == 0) continue;+ if (binaryFileExt(line)) continue; // PDFs/images/archives: not @-mention targets+ const dup = gpa.dupe(u8, line) catch continue;+ files.append(gpa, dup) catch gpa.free(dup);+ }+ return files.items.len > 0;+}++/// Collect file paths (relative to cwd) for the `@` picker: codedb's index+/// when available, else an iterative breadth-first walk skipping+/// atpickSkipDir directories, capped at atpick_max_files. Entries are+/// gpa-owned; the caller frees them.+pub fn collectRepoFiles(io: Io, gpa: Allocator, files: *std.ArrayList([]const u8)) void {+ if (collectCodedbFiles(io, gpa, files)) return;+ var dirs: std.ArrayList([]const u8) = .empty;+ defer {+ for (dirs.items) |d| gpa.free(d);+ dirs.deinit(gpa);+ }+ dirs.append(gpa, gpa.dupe(u8, ".") catch return) catch return;+ var head: usize = 0;+ while (head < dirs.items.len) : (head += 1) {+ const dpath = dirs.items[head];+ const top = std.mem.eql(u8, dpath, ".");+ var dir = Io.Dir.cwd().openDir(io, dpath, .{ .iterate = true }) catch continue;+ defer dir.close(io);+ var it = dir.iterate();+ while (it.next(io) catch null) |entry| {+ if (files.items.len >= atpick_max_files) return;+ switch (entry.kind) {+ .directory => {+ if (atpickSkipDir(entry.name)) continue;+ const rel = if (top) gpa.dupe(u8, entry.name) catch continue else std.fmt.allocPrint(gpa, "{s}/{s}", .{ dpath, entry.name }) catch continue;+ dirs.append(gpa, rel) catch gpa.free(rel);+ },+ .file, .sym_link => {+ if (binaryFileExt(entry.name)) continue; // PDFs/images/archives: not @-mention targets+ const rel = if (top) gpa.dupe(u8, entry.name) catch continue else std.fmt.allocPrint(gpa, "{s}/{s}", .{ dpath, entry.name }) catch continue;+ files.append(gpa, rel) catch gpa.free(rel);+ },+ else => {},+ }+ }+ }+}++/// Recognize a bracketed paste that is a drag-and-dropped file path: one+/// line, possibly quoted or backslash-escaped (terminals escape spaces and+/// append a trailing space), naming an absolute path after ~ expansion.+/// Returns the cleaned path (gpa-owned), else null. The caller is+/// responsible for checking that the path actually exists.+pub fn cleanDroppedPath(gpa: Allocator, home: []const u8, pasted: []const u8) ?[]const u8 {+ var s = std.mem.trim(u8, pasted, " \t\r\n");+ if (s.len < 2 or std.mem.indexOfScalar(u8, s, '\n') != null) return null;+ if ((s[0] == '\'' and s[s.len - 1] == '\'') or (s[0] == '"' and s[s.len - 1] == '"'))+ s = s[1 .. s.len - 1];+ var clean: std.ArrayList(u8) = .empty;+ defer clean.deinit(gpa);+ if (std.mem.startsWith(u8, s, "~/") and home.len > 0) {+ clean.appendSlice(gpa, home) catch return null;+ s = s[1..];+ }+ var i: usize = 0;+ while (i < s.len) : (i += 1) {+ const ch = if (s[i] == '\\' and i + 1 < s.len) blk: {+ i += 1;+ break :blk s[i];+ } else s[i];+ clean.append(gpa, ch) catch return null;+ }+ if (clean.items.len == 0 or clean.items[0] != '/') return null;+ return clean.toOwnedSlice(gpa) catch null;+}++// Redraw the whole input below a fixed prompt prefix, wrapping it+// across rows. Spans listed in `marks` (paths from the @ picker or a+// file drop, plus "[Image]") render as a cyan chip (reverse video ++// cyan) so they keep reading as attached files, not typed words; a+// chip crossing a row break keeps its colour. `st` carries the row+// count + cursor row of the previous draw so this one can clear it+// with relative moves only — no DECSC anchor for a scroll to strand.+pub fn redraw(o: *Io.Writer, items: []const u8, c: usize, marks: []const []const u8, st: *LineRender, pcol: usize) void {+ const cols = termCols();+ const plen = if (pcol > 0) pcol - 1 else 0; // columns the prompt holds on row 0++ // Clear the previous block: drop to its bottom row, then clear+ // bottom-up. Row 0 is cleared only past the prompt so the prompt+ // survives. Every move is relative, so a prior scroll is harmless.+ if (st.rows - 1 > st.crow) o.print("\x1b[{d}B", .{st.rows - 1 - st.crow}) catch {};+ var k = st.rows - 1;+ while (k > 0) : (k -= 1) o.writeAll("\r\x1b[K\x1b[A") catch {};+ o.writeAll("\r") catch {};+ if (plen > 0) o.print("\x1b[{d}C", .{plen}) catch {};+ o.writeAll("\x1b[K") catch {};++ // Re-emit the buffer, wrapping by hand at the right edge (a literal+ // "\r\n" every `cols` columns) rather than trusting terminal+ // autowrap, whose last-column "pending wrap" state is ambiguous.+ var i: usize = 0;+ var row: usize = 0;+ var vcol: usize = plen;+ var mark_end: usize = 0;+ var mark_open = false;+ // `ultracode` shines the input itself: each letter of every+ // (case-insensitive) occurrence renders in a rotating rainbow hue.+ var shine_starts: [8]usize = undefined;+ var shine_ends: [8]usize = undefined;+ var nshine: usize = 0;+ {+ var si: usize = 0;+ while (si + 9 <= items.len) : (si += 1) {+ if (std.ascii.eqlIgnoreCase(items[si .. si + 9], "ultracode")) {+ if (nshine < shine_starts.len) {+ shine_starts[nshine] = si;+ shine_ends[nshine] = si + 9;+ nshine += 1;+ }+ }+ }+ }+ var shine_active = false;+ while (i < items.len) {+ if (vcol >= cols) { // row full → wrap to the next+ o.writeAll("\r\n") catch {};+ row += 1;+ vcol = 0;+ }+ if (!mark_open) { // open a chip that starts here (longest wins)+ var best: usize = 0;+ for (marks) |m| {+ if (m.len == 0 or i + m.len > items.len) continue;+ if (std.mem.eql(u8, items[i .. i + m.len], m) and m.len > best) best = m.len;+ }+ if (best > 0) {+ if (shine_active) {+ o.writeAll("\x1b[0m") catch {};+ shine_active = false;+ }+ o.writeAll("\x1b[7;36m") catch {};+ mark_end = i + best;+ mark_open = true;+ }+ }+ // Rainbow shine for an `ultracode` span (skipped inside a chip).+ if (!mark_open) {+ var in_shine = false;+ for (shine_starts[0..nshine], shine_ends[0..nshine]) |sstart, send| {+ if (i >= sstart and i < send) {+ // Smooth interpolated hue + rhythmic brightness+ // breath; pos_q8 spreads the 9 letters across a+ // full palette pass so the wave glides.+ ultracodeWaveHue(o, @intCast((i - sstart) * 256), g_shine_phase);+ in_shine = true;+ break;+ }+ }+ if (in_shine) {+ shine_active = true;+ } else if (shine_active) {+ o.writeAll("\x1b[0m") catch {};+ shine_active = false;+ }+ }+ o.writeByte(items[i]) catch {};+ vcol += 1;+ i += 1;+ if (mark_open and i == mark_end) {+ o.writeAll("\x1b[0m") catch {};+ mark_open = false;+ shine_active = false;+ }+ }+ if (mark_open or shine_active) o.writeAll("\x1b[0m") catch {};++ // Place the cursor. wrapAt gives its target row/col; when it sits+ // at the very end of a just-filled row that's a fresh row below the+ // text (the classic last-column case), realise it with a newline so+ // the next keystroke stays visible.+ const tgt = wrapAt(plen, cols, c);+ while (tgt.row > row) {+ o.writeAll("\r\n") catch {};+ row += 1;+ }+ if (row > tgt.row) o.print("\x1b[{d}A", .{row - tgt.row}) catch {};+ o.writeAll("\r") catch {};+ if (tgt.col > 0) o.print("\x1b[{d}C", .{tgt.col}) catch {};+ o.flush() catch {};++ st.rows = row + 1;+ st.crow = tgt.row;+}++pub fn setLine(g: Allocator, b: *std.ArrayList(u8), s: []const u8) void {+ b.clearRetainingCapacity();+ b.appendSlice(g, s) catch {};+}++pub fn delRange(b: *std.ArrayList(u8), a: usize, e: usize) void {+ std.mem.copyForwards(u8, b.items[a..], b.items[e..]);+ b.shrinkRetainingCapacity(b.items.len - (e - a));+}++pub fn prevWord(items: []const u8, c: usize) usize {+ var i = c;+ while (i > 0 and items[i - 1] == ' ') i -= 1;+ while (i > 0 and items[i - 1] != ' ') i -= 1;+ return i;+}++pub fn nextWord(items: []const u8, c: usize) usize {+ var i = c;+ while (i < items.len and items[i] == ' ') i += 1;+ while (i < items.len and items[i] != ' ') i += 1;+ return i;+}++pub fn addMark(g: Allocator, ms: *std.ArrayList([]const u8), s: []const u8) void {+ for (ms.items) |m| if (std.mem.eql(u8, m, s)) return;+ const dup = g.dupe(u8, s) catch return;+ ms.append(g, dup) catch g.free(dup);+}++test "cleanDroppedPath unescapes terminal drops" {+ const gpa = std.testing.allocator;+ const p = cleanDroppedPath(gpa, "", "/tmp/My\\ File.txt ") orelse return error.TestUnexpectedResult;+ defer gpa.free(p);+ try std.testing.expectEqualStrings("/tmp/My File.txt", p);+ const q = cleanDroppedPath(gpa, "/home/u", "'~/notes/a b.md'") orelse return error.TestUnexpectedResult;+ defer gpa.free(q);+ try std.testing.expectEqualStrings("/home/u/notes/a b.md", q);+ try std.testing.expect(cleanDroppedPath(gpa, "", "hello world") == null); // not absolute+ try std.testing.expect(cleanDroppedPath(gpa, "", "two\nlines") == null); // multi-line+}++test "binaryFileExt flags binaries, passes text" {+ try std.testing.expect(binaryFileExt("paper.pdf"));+ try std.testing.expect(binaryFileExt("shot.PNG")); // case-insensitive+ try std.testing.expect(binaryFileExt("lib.a"));+ try std.testing.expect(!binaryFileExt("main.zig"));+ try std.testing.expect(!binaryFileExt("README.md"));+ try std.testing.expect(!binaryFileExt("Makefile")); // no extension+ try std.testing.expect(isImagePath("a.jpeg"));+ try std.testing.expect(!isImagePath("a.pdf"));+}++test "wrapAt: rows and columns across the right edge" {+ // No prompt, 10-column terminal: bytes 0..9 fill row 0.+ try std.testing.expectEqual(@as(usize, 0), wrapAt(0, 10, 0).row);+ try std.testing.expectEqual(@as(usize, 5), wrapAt(0, 10, 5).col);+ try std.testing.expectEqual(@as(usize, 0), wrapAt(0, 10, 9).row);+ // Byte 10 is the first cell of row 1.+ try std.testing.expectEqual(@as(usize, 1), wrapAt(0, 10, 10).row);+ try std.testing.expectEqual(@as(usize, 0), wrapAt(0, 10, 10).col);+ // Byte 25 → row 2, col 5.+ try std.testing.expectEqual(@as(usize, 2), wrapAt(0, 10, 25).row);+ try std.testing.expectEqual(@as(usize, 5), wrapAt(0, 10, 25).col);+}++test "wrapAt: a prompt prefix shifts the whole line right" {+ // 4-column prompt: byte 5 sits at column 9 of row 0 (4+5).+ try std.testing.expectEqual(@as(usize, 0), wrapAt(4, 10, 5).row);+ try std.testing.expectEqual(@as(usize, 9), wrapAt(4, 10, 5).col);+ // byte 6 → 4+6 == 10 → row 1, col 0.+ try std.testing.expectEqual(@as(usize, 1), wrapAt(4, 10, 6).row);+ try std.testing.expectEqual(@as(usize, 0), wrapAt(4, 10, 6).col);+}++test "wrapAt: zero columns never divides by zero" {+ try std.testing.expectEqual(@as(usize, 0), wrapAt(0, 0, 3).col);+}++test "parseDsrCol: well-formed and malformed replies" {+ try std.testing.expectEqual(@as(?usize, 34), parseDsrCol("[12;34R"));+ try std.testing.expectEqual(@as(?usize, 1), parseDsrCol("[1;1R"));+ try std.testing.expectEqual(@as(?usize, null), parseDsrCol("[12R")); // no column+ try std.testing.expectEqual(@as(?usize, null), parseDsrCol("[1;0R")); // col 0 is meaningless+ try std.testing.expectEqual(@as(?usize, null), parseDsrCol("[1;xR"));+ try std.testing.expectEqual(@as(?usize, null), parseDsrCol("12;34R")); // missing CSI intro+ try std.testing.expectEqual(@as(?usize, null), parseDsrCol(""));+}++test "fillCompletions includes ultracode slash command" {+ var out: std.ArrayList([]const u8) = .empty;+ defer out.deinit(std.testing.allocator);+ _ = fillCompletions(std.testing.allocator, "/ult", &out);+ var found = false;+ for (out.items) |item| {+ if (std.mem.eql(u8, item, "/ultracode")) found = true;+ }+ try std.testing.expect(found);+}++test "isImagePath: known image extensions, case-insensitive" {+ try std.testing.expect(isImagePath("photo.png"));+ try std.testing.expect(isImagePath("a.JPEG"));+ try std.testing.expect(isImagePath("x.webp"));+ try std.testing.expect(isImagePath("dir/sub/pic.gif"));+ try std.testing.expect(!isImagePath("readme.md"));+ try std.testing.expect(!isImagePath("noext"));+ try std.testing.expect(!isImagePath("archive.tar.gz"));+}diff --git a/src/main.zig b/src/main.zigindex 2fa625c6..f30f8e24 100644--- a/src/main.zig+++ b/src/main.zig@@ -120,6 +120,8 @@ test {_ = providers;_ = pickers;_ = skills;+ _ = input_util;+ _ = readline_mod;}/// Wire format + auth style + endpoint per provider. Base URLs and env-var@@ -473,7 +475,7 @@ fn loadOrCreateId(io: Io, gpa: Allocator, home: []const u8, fname: []const u8) [/// Reasoning depth for codex/responses (OpenAI Responses `reasoning.effort`).const ReasoningEffort = enum { low, medium, high };-const repl_commands = [_][]const u8{ "/model", "/models", "/clear", "/new", "/rename", "/goal", "/loop", "/bash", "/plan", "/key", "/keepcontext", "/effort", "/fast", "/ultracode", "/thinking", "/title", "/reasoning", "/strict", "/yolo", "/trace", "/fleet", "/trajectory", "/agents", "/skills", "/hooks", "/compact", "/rewind", "/image", "/paste", "/save", "/resume", "/sessions", "/todo", "/jobs", "/cost", "/animation", "/theme", "/mcp", "/help" };+pub const repl_commands = [_][]const u8{ "/model", "/models", "/clear", "/new", "/rename", "/goal", "/loop", "/bash", "/plan", "/key", "/keepcontext", "/effort", "/fast", "/ultracode", "/thinking", "/title", "/reasoning", "/strict", "/yolo", "/trace", "/fleet", "/trajectory", "/agents", "/skills", "/hooks", "/compact", "/rewind", "/image", "/paste", "/save", "/resume", "/sessions", "/todo", "/jobs", "/cost", "/animation", "/theme", "/mcp", "/help" };/// REPL slash commands share the leading `/` with absolute POSIX paths. Only/// treat the line as command syntax when the first token is command-shaped;@@ -846,7 +848,6 @@ var g_codedbpro_licensed: bool = false;// anim.zig (#123); it imports ansi and back-imports main for Approvals paths.// The spinner consumers (Agent.spinnerTask, /animation, /theme) stay here.const anim = @import("anim.zig");-var g_shine_phase: usize = 0; // ultracode input-wave animation frame// Steering (Codex-style): bytes typed while a turn streams are captured// instead of discarded, echoed live in dim cyan, and on Enter queued to@@ -977,63 +978,9 @@ fn loadThinkingSettings(io: Io, arena: Allocator, root: *Agent) void {};}-/// Tab-completion candidates for the current input. After `/model ` →-/// model names (deduped) + provider ids matching the partial; a bare `/word`-/// → slash commands. Returns the byte offset of the word being completed-/// (so the caller can splice in a candidate). Candidates are static slices.-fn fillCompletions(gpa: Allocator, line: []const u8, out: *std.ArrayList([]const u8)) usize {- const mp = "/model ";- if (std.mem.startsWith(u8, line, mp)) {- const partial = line[mp.len..];- for (model_table) |m| {- if (!std.mem.startsWith(u8, m.name, partial)) continue;- var dup = false;- for (out.items) |x| if (std.mem.eql(u8, x, m.name)) {- dup = true;- };- if (!dup) out.append(gpa, m.name) catch {};- }- for (provider_specs) |s| if (std.mem.startsWith(u8, s.id, partial)) out.append(gpa, s.id) catch {};- return mp.len;- }- if (line.len > 0 and line[0] == '/' and std.mem.indexOfScalar(u8, line, ' ') == null) {- for (repl_commands) |cmd| if (std.mem.startsWith(u8, cmd, line)) out.append(gpa, cmd) catch {};- return 0;- }- return line.len;-}--/// True when at least one byte is already waiting on `fd` (≤50ms): tells a-/// bare Esc keypress apart from the first byte of an escape sequence-/// (terminals send the whole sequence in one burst).-/// Screen position of a byte in a wrapped input line: given the prompt width-/// `plen` (columns the prompt occupies on the first row), terminal width-/// `cols`, and byte index `pos` into the buffer, the cursor's 0-based row-/// (counted from the prompt row) and 0-based column. The buffer wraps every-/// `cols` columns, so a byte sitting just past a row edge is col 0 of the next-/// row. Pure (unit-tested below); redraw uses it to place the cursor.-fn wrapAt(plen: usize, cols: usize, pos: usize) struct { row: usize, col: usize } {- const c = if (cols == 0) 1 else cols;- const flat = plen + pos;- return .{ .row = flat / c, .col = flat % c };-}--/// Persisted across `readLine`'s redraws: how many rows the wrapped input-/// occupied last time (a count ≥1) and which 0-based row the cursor sat on.-/// The redraw clears exactly these rows relative to where the cursor is now —-/// no absolute cursor save (DECSC), which a wrap-induced scroll would strand.-/// Input taller than the screen is unsupported (same caveat as bash/zsh).-const LineRender = struct { rows: usize = 1, crow: usize = 0 };--/// Column from a DSR cursor-position reply — `seq` is the CSI body with the-/// ESC stripped, e.g. "[12;34R". Null (caller falls back to column 1) on-/// anything malformed, including the meaningless column 0.-fn parseDsrCol(seq: []const u8) ?usize {- if (seq.len < 5 or seq[0] != '[' or seq[seq.len - 1] != 'R') return null;- const semi = std.mem.indexOfScalar(u8, seq, ';') orelse return null;- const col = std.fmt.parseInt(usize, seq[semi + 1 .. seq.len - 1], 10) catch return null;- return if (col == 0) null else col;-}+// fillCompletions/wrapAt/LineRender/parseDsrCol moved to input_util.zig+// (see the breadcrumb below the term.zig import block for the aliases+// this file still needs).// Terminal primitives (Windows console shim + cross-platform raw-mode tty layer// + size/poll/row-count helpers) live in term.zig (600-line goal). win is@@ -1048,897 +995,18 @@ const advanceThinkingRows = terminal.advanceThinkingRows;const inputPending = terminal.inputPending;const inputPendingTimed = terminal.inputPendingTimed;-/// Raw RGB stops for the ultracode wave (mirrors ultracode_rainbow's hues).-const ultracode_rgb = [_]struct { r: u8, g: u8, b: u8 }{- .{ .r = 255, .g = 87, .b = 51 },- .{ .r = 255, .g = 159, .b = 28 },- .{ .r = 255, .g = 222, .b = 51 },- .{ .r = 120, .g = 255, .b = 51 },- .{ .r = 51, .g = 255, .b = 170 },- .{ .r = 51, .g = 170, .b = 255 },- .{ .r = 120, .g = 51, .b = 255 },- .{ .r = 210, .g = 51, .b = 255 },- .{ .r = 255, .g = 51, .b = 159 },-};--/// Smoothly interpolated rainbow hue for the ultracode wave. `pos_q8` is a-/// 0..2048 fraction across the 9-stop palette (8 bits index + 8 bits blend),-/// so the wave glides between colors instead of snapping. A sine brightness-/// breath (period ~2.2s at 110ms/tick) gives a rhythmic pulse rather than a-/// mechanical scroll. Writes the SGR escape straight to the writer.-fn ultracodeWaveHue(w: *Io.Writer, pos_q8: u16, phase: usize) void {- const pal = &ultracode_rgb;- const len: u16 = pal.len;- const p: u16 = pos_q8 + @as(u16, @intCast(phase * 32));- const idx: u16 = (p >> 8) % len;- const frac: u16 = p & 0xff;- const a = pal[idx];- const b = pal[(idx + 1) % len];- // Interpolate in signed space (b-a may be negative) then clamp to 0..255.- const r: i32 = @as(i32, a.r) + @divTrunc((@as(i32, b.r) - @as(i32, a.r)) * @as(i32, frac), 256);- const g: i32 = @as(i32, a.g) + @divTrunc((@as(i32, b.g) - @as(i32, a.g)) * @as(i32, frac), 256);- const bl: i32 = @as(i32, a.b) + @divTrunc((@as(i32, b.b) - @as(i32, a.b)) * @as(i32, frac), 256);- // Breath: a gentle sine over phase, period 20 ticks (~2.2s @ 110ms),- // modulating brightness between ~81% and ~94% — a soft, subtle pulse.- const breath: u16 = switch (phase % 20) {- 0 => 120,- 1 => 120,- 2 => 118,- 3 => 117,- 4 => 114,- 5 => 112,- 6 => 110,- 7 => 107,- 8 => 106,- 9 => 104,- 10 => 104,- 11 => 104,- 12 => 106,- 13 => 107,- 14 => 110,- 15 => 112,- 16 => 114,- 17 => 117,- 18 => 118,- else => 120,- };- const sc: i32 = @as(i32, breath);- const cr: u8 = @intCast(@max(0, @min(255, @divTrunc(r * sc, 128))));- const cg: u8 = @intCast(@max(0, @min(255, @divTrunc(g * sc, 128))));- const cb: u8 = @intCast(@max(0, @min(255, @divTrunc(bl * sc, 128))));- w.print("\x1b[38;2;{d};{d};{d}m", .{ cr, cg, cb }) catch {};-}--/// Directories the `@` file picker never descends into (every dot-dir is-/// also skipped): package/build output and caches — never @-mention targets.-const atpick_skip_dirs = [_][]const u8{ "node_modules", "zig-out", "zig-cache", "__pycache__", "venv", "target", "dist", "build" };-const atpick_max_files = 5000;--fn atpickSkipDir(name: []const u8) bool {- if (name.len > 0 and name[0] == '.') return true;- for (atpick_skip_dirs) |s| if (std.mem.eql(u8, name, s)) return true;- return false;-}--/// Extensions treated as binary: hidden from the `@` picker and refused by-/// read_file (which points the model at bash converters like pdftotext).-const binary_exts = [_][]const u8{ "pdf", "png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "icns", "tiff", "zip", "tar", "gz", "tgz", "bz2", "xz", "zst", "7z", "rar", "exe", "dll", "so", "dylib", "a", "o", "wasm", "class", "jar", "pyc", "woff", "woff2", "ttf", "otf", "eot", "mp3", "mp4", "m4a", "mov", "avi", "mkv", "wav", "flac", "ogg", "sqlite", "db", "bin" };--fn binaryFileExt(name: []const u8) bool {- const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return false;- const ext = name[dot + 1 ..];- for (binary_exts) |b| if (std.ascii.eqlIgnoreCase(ext, b)) return true;- return false;-}--/// Image types stageImagePath understands (a dropped one becomes a vision-/// attachment instead of an inlined path).-pub fn isImagePath(name: []const u8) bool {- const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return false;- const ext = name[dot + 1 ..];- for ([_][]const u8{ "png", "jpg", "jpeg", "gif", "webp" }) |e| if (std.ascii.eqlIgnoreCase(ext, e)) return true;- return false;-}--/// Pull the `@` picker's file list from codedb's index (`codedb glob '**/*'`):-/// gitignore-aware and instant once the repo is indexed, unlike the blind-/// walk below. Returns false when codedb is missing, errors, or knows no-/// files — the caller falls back to the walk. Entries are gpa-owned.-fn collectCodedbFiles(io: Io, gpa: Allocator, files: *std.ArrayList([]const u8)) bool {- const run = runCapped(gpa, io, &.{ "codedb", "glob", "**/*" }, bash_stdout_cap, 4096, 0) catch return false;- defer {- gpa.free(run.stdout);- gpa.free(run.stderr);- }- const code: ?u8 = switch (run.term) {- .exited => |c| c,- else => null,- };- if (code == null or code.? != 0) return false;- // A truncated capture may end mid-path: only parse up to the last newline.- const safe_end = if (run.stdout_truncated)- (std.mem.lastIndexOfScalar(u8, run.stdout, '\n') orelse 0)- else- run.stdout.len;- var it = std.mem.splitScalar(u8, run.stdout[0..safe_end], '\n');- while (it.next()) |ln| {- if (files.items.len >= atpick_max_files) break;- const line = std.mem.trim(u8, ln, " \t\r");- if (line.len == 0) continue;- if (binaryFileExt(line)) continue; // PDFs/images/archives: not @-mention targets- const dup = gpa.dupe(u8, line) catch continue;- files.append(gpa, dup) catch gpa.free(dup);- }- return files.items.len > 0;-}--/// Collect file paths (relative to cwd) for the `@` picker: codedb's index-/// when available, else an iterative breadth-first walk skipping-/// atpickSkipDir directories, capped at atpick_max_files. Entries are-/// gpa-owned; the caller frees them.-fn collectRepoFiles(io: Io, gpa: Allocator, files: *std.ArrayList([]const u8)) void {- if (collectCodedbFiles(io, gpa, files)) return;- var dirs: std.ArrayList([]const u8) = .empty;- defer {- for (dirs.items) |d| gpa.free(d);- dirs.deinit(gpa);- }- dirs.append(gpa, gpa.dupe(u8, ".") catch return) catch return;- var head: usize = 0;- while (head < dirs.items.len) : (head += 1) {- const dpath = dirs.items[head];- const top = std.mem.eql(u8, dpath, ".");- var dir = Io.Dir.cwd().openDir(io, dpath, .{ .iterate = true }) catch continue;- defer dir.close(io);- var it = dir.iterate();- while (it.next(io) catch null) |entry| {- if (files.items.len >= atpick_max_files) return;- switch (entry.kind) {- .directory => {- if (atpickSkipDir(entry.name)) continue;- const rel = if (top) gpa.dupe(u8, entry.name) catch continue else std.fmt.allocPrint(gpa, "{s}/{s}", .{ dpath, entry.name }) catch continue;- dirs.append(gpa, rel) catch gpa.free(rel);- },- .file, .sym_link => {- if (binaryFileExt(entry.name)) continue; // PDFs/images/archives: not @-mention targets- const rel = if (top) gpa.dupe(u8, entry.name) catch continue else std.fmt.allocPrint(gpa, "{s}/{s}", .{ dpath, entry.name }) catch continue;- files.append(gpa, rel) catch gpa.free(rel);- },- else => {},- }- }- }-}--/// Recognize a bracketed paste that is a drag-and-dropped file path: one-/// line, possibly quoted or backslash-escaped (terminals escape spaces and-/// append a trailing space), naming an absolute path after ~ expansion.-/// Returns the cleaned path (gpa-owned), else null. The caller is-/// responsible for checking that the path actually exists.-fn cleanDroppedPath(gpa: Allocator, home: []const u8, pasted: []const u8) ?[]const u8 {- var s = std.mem.trim(u8, pasted, " \t\r\n");- if (s.len < 2 or std.mem.indexOfScalar(u8, s, '\n') != null) return null;- if ((s[0] == '\'' and s[s.len - 1] == '\'') or (s[0] == '"' and s[s.len - 1] == '"'))- s = s[1 .. s.len - 1];- var clean: std.ArrayList(u8) = .empty;- defer clean.deinit(gpa);- if (std.mem.startsWith(u8, s, "~/") and home.len > 0) {- clean.appendSlice(gpa, home) catch return null;- s = s[1..];- }- var i: usize = 0;- while (i < s.len) : (i += 1) {- const ch = if (s[i] == '\\' and i + 1 < s.len) blk: {- i += 1;- break :blk s[i];- } else s[i];- clean.append(gpa, ch) catch return null;- }- if (clean.items.len == 0 or clean.items[0] != '/') return null;- return clean.toOwnedSlice(gpa) catch null;-}--/// History + unsent-draft navigation for the line editor (#101). Mirrors the-/// GUI's promptHistoryNavigation.ts: stepping UP out of the fresh slot snapshots-/// the half-typed draft; stepping DOWN past the newest entry restores it instead-/// of clearing the line. `idx == history.len` is the fresh (editing) slot.-const HistoryNav = struct {- idx: usize,- draft: ?[]const u8 = null, // owned snapshot of the unsent line; freed by the caller-- fn init(history_len: usize) HistoryNav {- return .{ .idx = history_len };- }-- /// UP / older. `current` is the live buffer. Returns the text the buffer- /// should show next, or null to leave it unchanged (already at the oldest).- /// Leaving the fresh slot snapshots `current` as the draft to restore later.- fn up(self: *HistoryNav, gpa: Allocator, history: []const []const u8, current: []const u8) ?[]const u8 {- if (self.idx == 0) return null;- if (self.idx == history.len) { // leaving the fresh slot: keep the draft- if (self.draft) |d| gpa.free(d);- self.draft = gpa.dupe(u8, current) catch null;- }- self.idx -= 1;- return history[self.idx];- }-- /// DOWN / newer. Returns the text to show next, or null to leave it- /// unchanged (already at the fresh slot). Past the newest entry, restores the- /// snapshotted draft (or "" when there was none) instead of clearing it.- fn down(self: *HistoryNav, history: []const []const u8) ?[]const u8 {- if (self.idx >= history.len) return null;- self.idx += 1;- if (self.idx == history.len) return self.draft orelse "";- return history[self.idx];- }-};--test "HistoryNav: up snapshots the draft, down past newest restores it (#101)" {- const gpa = std.testing.allocator;- const history = [_][]const u8{ "first", "second" };- var nav: HistoryNav = .init(history.len);- defer if (nav.draft) |d| gpa.free(d);-- // up from the fresh slot → newest entry, draft snapshotted- try std.testing.expectEqualStrings("second", nav.up(gpa, &history, "draft in progress").?);- // up again → older entry- try std.testing.expectEqualStrings("first", nav.up(gpa, &history, "second").?);- // up at the oldest → no change- try std.testing.expect(nav.up(gpa, &history, "first") == null);- // down → back to newest- try std.testing.expectEqualStrings("second", nav.down(&history).?);- // down past newest → the draft is restored, NOT cleared (the bug)- try std.testing.expectEqualStrings("draft in progress", nav.down(&history).?);- // down at the fresh slot → no change- try std.testing.expect(nav.down(&history) == null);-}--test "HistoryNav: no draft → fresh slot returns empty, no leak (#101)" {- const gpa = std.testing.allocator;- const history = [_][]const u8{"only"};- var nav: HistoryNav = .init(history.len);- defer if (nav.draft) |d| gpa.free(d);- try std.testing.expectEqualStrings("only", nav.up(gpa, &history, "").?);- try std.testing.expectEqualStrings("", nav.down(&history).?); // empty draft → empty line, as today-}--/// Read one input line with a tiny raw-mode editor: ↑/↓ walk history,-/// Tab completes/cycles (models, providers, slash commands), backspace edits,-/// Ctrl-C cancels the line, Ctrl-D on an empty line is EOF. `buf` is reused-/// across calls and holds the result (valid until the next call). Returns the-/// line, or null on EOF. Falls back to a plain buffered line read when stdin-/// isn't a TTY (pipes, tests). DECSC/DECRC saves/restores the cursor to redraw.-fn readLine(- root: *Agent,- in: *Io.Reader,- out: *Io.Writer,- gpa: Allocator,- history: *std.ArrayList([]const u8),- buf: *std.ArrayList(u8),-) !?[]const u8 {- const raw_state = tty.enterRaw(true) orelse return in.takeDelimiter('\n');- defer tty.restore(raw_state);-- buf.clearRetainingCapacity();- var cur: usize = 0; // cursor index within buf- var nav: HistoryNav = .init(history.items.len); // history + unsent-draft nav (#101)- defer if (nav.draft) |d| gpa.free(d);- out.writeAll("\x1b[?2004h") catch {}; // enable bracketed paste (terminal wraps pastes in ESC[200~ … ESC[201~)- defer out.writeAll("\x1b[?2004l") catch {};- out.flush() catch {};-- // Where does input start? Ask the terminal (DSR 6) for the column right- // after the prompt; the renderer treats those columns as a fixed prefix- // and wraps the input across rows below it. Cursor moves in redraw are all- // relative (never an absolute DECSC anchor), so a wrap-induced scroll- // shifts the whole block together and never strands the prompt. Typed-- // ahead text bytes that race the reply are replayed into the edit loop- // below; a typed-ahead escape sequence inside that ~ms window is dropped.- var prompt_col: usize = 1; // 1-based column where the buffer renders- var rstate: LineRender = .{}; // rows used + cursor row of the last redraw- var pending: std.ArrayList(u8) = .empty;- defer pending.deinit(gpa);- var pend_i: usize = 0;- out.writeAll("\x1b[6n") catch {};- out.flush() catch {};- dsr: {- var polls: usize = 0;- var esc: [16]u8 = undefined;- var n: usize = 0;- var in_esc = false;- while (true) {- if (in.buffered().len == 0 and !inputPending()) { // 50ms poll- polls += 1;- if (polls >= 10) break :dsr; // no reply in ~500ms: fall back- // to column 1 — a later reply is still adopted (CSI 'R').- continue;- }- const b = in.takeByte() catch break :dsr;- if (!in_esc) {- if (b == 0x1b) {- in_esc = true;- n = 0;- continue;- }- pending.append(gpa, b) catch {};- if (pending.items.len > 64) break :dsr;- continue;- }- if (n == 0 and b != '[') { // Alt-chord typed ahead: drop it- in_esc = false;- continue;- }- if (n < esc.len) {- esc[n] = b;- n += 1;- }- if (n >= 2 and b >= 0x40 and b <= 0x7e) { // CSI final byte- if (b == 'R') { // the reply: ESC [ row ; col R- prompt_col = parseDsrCol(esc[0..n]) orelse 1;- break :dsr;- }- in_esc = false; // some other CSI typed ahead — drop it- n = 0;- }- }- }- // Narrow terminal: when the prompt leaves too little room (the token-- // stats prompt nearly fills a small window), give the input its own- // row — what shells do — rather than wrapping in a sliver beside the- // prompt.- if (termCols() < prompt_col + 16) {- out.writeAll("\r\n") catch {};- out.flush() catch {};- prompt_col = 1;- }-- const redraw = struct {- // Redraw the whole input below a fixed prompt prefix, wrapping it- // across rows. Spans listed in `marks` (paths from the @ picker or a- // file drop, plus "[Image]") render as a cyan chip (reverse video +- // cyan) so they keep reading as attached files, not typed words; a- // chip crossing a row break keeps its colour. `st` carries the row- // count + cursor row of the previous draw so this one can clear it- // with relative moves only — no DECSC anchor for a scroll to strand.- fn f(o: *Io.Writer, items: []const u8, c: usize, marks: []const []const u8, st: *LineRender, pcol: usize) void {- const cols = termCols();- const plen = if (pcol > 0) pcol - 1 else 0; // columns the prompt holds on row 0-- // Clear the previous block: drop to its bottom row, then clear- // bottom-up. Row 0 is cleared only past the prompt so the prompt- // survives. Every move is relative, so a prior scroll is harmless.- if (st.rows - 1 > st.crow) o.print("\x1b[{d}B", .{st.rows - 1 - st.crow}) catch {};- var k = st.rows - 1;- while (k > 0) : (k -= 1) o.writeAll("\r\x1b[K\x1b[A") catch {};- o.writeAll("\r") catch {};- if (plen > 0) o.print("\x1b[{d}C", .{plen}) catch {};- o.writeAll("\x1b[K") catch {};-- // Re-emit the buffer, wrapping by hand at the right edge (a literal- // "\r\n" every `cols` columns) rather than trusting terminal- // autowrap, whose last-column "pending wrap" state is ambiguous.- var i: usize = 0;- var row: usize = 0;- var vcol: usize = plen;- var mark_end: usize = 0;- var mark_open = false;- // `ultracode` shines the input itself: each letter of every- // (case-insensitive) occurrence renders in a rotating rainbow hue.- var shine_starts: [8]usize = undefined;- var shine_ends: [8]usize = undefined;- var nshine: usize = 0;- {- var si: usize = 0;- while (si + 9 <= items.len) : (si += 1) {- if (std.ascii.eqlIgnoreCase(items[si .. si + 9], "ultracode")) {- if (nshine < shine_starts.len) {- shine_starts[nshine] = si;- shine_ends[nshine] = si + 9;- nshine += 1;- }- }- }- }- var shine_active = false;- while (i < items.len) {- if (vcol >= cols) { // row full → wrap to the next- o.writeAll("\r\n") catch {};- row += 1;- vcol = 0;- }- if (!mark_open) { // open a chip that starts here (longest wins)- var best: usize = 0;- for (marks) |m| {- if (m.len == 0 or i + m.len > items.len) continue;- if (std.mem.eql(u8, items[i .. i + m.len], m) and m.len > best) best = m.len;- }- if (best > 0) {- if (shine_active) {- o.writeAll("\x1b[0m") catch {};- shine_active = false;- }- o.writeAll("\x1b[7;36m") catch {};- mark_end = i + best;- mark_open = true;- }- }- // Rainbow shine for an `ultracode` span (skipped inside a chip).- if (!mark_open) {- var in_shine = false;- for (shine_starts[0..nshine], shine_ends[0..nshine]) |sstart, send| {- if (i >= sstart and i < send) {- // Smooth interpolated hue + rhythmic brightness- // breath; pos_q8 spreads the 9 letters across a- // full palette pass so the wave glides.- ultracodeWaveHue(o, @intCast((i - sstart) * 256), g_shine_phase);- in_shine = true;- break;- }- }- if (in_shine) {- shine_active = true;- } else if (shine_active) {- o.writeAll("\x1b[0m") catch {};- shine_active = false;- }- }- o.writeByte(items[i]) catch {};- vcol += 1;- i += 1;- if (mark_open and i == mark_end) {- o.writeAll("\x1b[0m") catch {};- mark_open = false;- shine_active = false;- }- }- if (mark_open or shine_active) o.writeAll("\x1b[0m") catch {};-- // Place the cursor. wrapAt gives its target row/col; when it sits- // at the very end of a just-filled row that's a fresh row below the- // text (the classic last-column case), realise it with a newline so- // the next keystroke stays visible.- const tgt = wrapAt(plen, cols, c);- while (tgt.row > row) {- o.writeAll("\r\n") catch {};- row += 1;- }- if (row > tgt.row) o.print("\x1b[{d}A", .{row - tgt.row}) catch {};- o.writeAll("\r") catch {};- if (tgt.col > 0) o.print("\x1b[{d}C", .{tgt.col}) catch {};- o.flush() catch {};-- st.rows = row + 1;- st.crow = tgt.row;- }- }.f;- const setLine = struct {- fn f(g: Allocator, b: *std.ArrayList(u8), s: []const u8) void {- b.clearRetainingCapacity();- b.appendSlice(g, s) catch {};- }- }.f;- const delRange = struct { // remove [a, e) from buf (a <= e <= len)- fn f(b: *std.ArrayList(u8), a: usize, e: usize) void {- std.mem.copyForwards(u8, b.items[a..], b.items[e..]);- b.shrinkRetainingCapacity(b.items.len - (e - a));- }- }.f;- const prevWord = struct { // start of the word at/just before c- fn f(items: []const u8, c: usize) usize {- var i = c;- while (i > 0 and items[i - 1] == ' ') i -= 1;- while (i > 0 and items[i - 1] != ' ') i -= 1;- return i;- }- }.f;- const nextWord = struct { // end of the word at/after c- fn f(items: []const u8, c: usize) usize {- var i = c;- while (i < items.len and items[i] == ' ') i += 1;- while (i < items.len and items[i] != ' ') i += 1;- return i;- }- }.f;-- // Tab-completion cycle state.- var comp_items: std.ArrayList([]const u8) = .empty;- defer comp_items.deinit(gpa);- var comp_base: usize = 0;- var comp_idx: usize = 0;- var comp_active = false;-- // Bracketed-paste collapse: a multi-line paste becomes a "[Pasted text #N- // +L lines]" placeholder in the buffer; on submit each placeholder is- // expanded back to its full text.- const Paste = struct { ph: []const u8, body: []const u8 };- var pastes: std.ArrayList(Paste) = .empty;- defer {- for (pastes.items) |p| {- gpa.free(p.ph);- gpa.free(p.body);- }- pastes.deinit(gpa);- }-- // File paths inserted by the @ picker or a drag-and-drop (plus the- // "[Image]" attachment marker): redraw renders these spans highlighted.- // Editing inside a span just drops its highlight — the text stays.- var marks: std.ArrayList([]const u8) = .empty;- defer {- for (marks.items) |m| gpa.free(m);- marks.deinit(gpa);- }- const addMark = struct { // dupe + dedupe; drops the mark on OOM (cosmetic only)- fn f(g: Allocator, ms: *std.ArrayList([]const u8), s: []const u8) void {- for (ms.items) |m| if (std.mem.eql(u8, m, s)) return;- const dup = g.dupe(u8, s) catch return;- ms.append(g, dup) catch g.free(dup);- }- }.f;-- while (true) {- // Replay any text bytes that raced the DSR reply, then read live.- const c = if (pend_i < pending.items.len) blk: {- const b = pending.items[pend_i];- pend_i += 1;- break :blk b;- } else blk: {- // While the input contains `ultracode`, wave the rainbow shine- // across the letters: poll for input with a slower 110ms timeout,- // and on each idle tick advance the phase + redraw so the hue- // glides and breathes (~9fps, calm + rhythmic rather than a fast- // flicker).- while (std.ascii.indexOfIgnoreCase(buf.items, "ultracode") != null) {- if (inputPendingTimed(110)) break; // keystroke ready — read it below- g_shine_phase +%= 1;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- }- break :blk in.takeByte() catch return null;- };- if (c != 0x09) comp_active = false; // any non-Tab key ends the cycle- switch (c) {- 0x09 => { // Tab: complete, or cycle through matches on repeat- if (!comp_active) {- comp_items.clearRetainingCapacity();- comp_base = fillCompletions(gpa, buf.items, &comp_items);- if (comp_items.items.len == 0) continue;- comp_idx = 0;- comp_active = true;- } else if (comp_items.items.len > 0) {- comp_idx = (comp_idx + 1) % comp_items.items.len;- } else continue;- buf.shrinkRetainingCapacity(comp_base);- buf.appendSlice(gpa, comp_items.items[comp_idx]) catch {};- cur = buf.items.len;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- '\r', '\n' => {- // The cursor may be mid-block; step past the last input row so- // the submitted line and whatever prints next start cleanly.- if (rstate.rows - 1 > rstate.crow) out.print("\x1b[{d}B", .{rstate.rows - 1 - rstate.crow}) catch {};- out.writeAll("\r\n") catch {};- out.flush() catch {};- // Expand any pasted placeholders back to their full text.- for (pastes.items) |p| {- if (std.mem.indexOf(u8, buf.items, p.ph) == null) continue;- const sz = std.mem.replacementSize(u8, buf.items, p.ph, p.body);- const tmp = gpa.alloc(u8, sz) catch break;- _ = std.mem.replace(u8, buf.items, p.ph, p.body, tmp);- buf.clearRetainingCapacity();- buf.appendSlice(gpa, tmp) catch {};- gpa.free(tmp);- }- break;- },- 0x01 => { // Ctrl-A → start of line- cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 0x05 => { // Ctrl-E → end of line- cur = buf.items.len;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 0x02 => if (cur > 0) { // Ctrl-B → left- cur -= 1;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 0x06 => if (cur < buf.items.len) { // Ctrl-F → right- cur += 1;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 0x17, 0x1f => { // Ctrl-W / Ctrl-_ → delete previous word- const s = prevWord(buf.items, cur);- if (s < cur) {- delRange(buf, s, cur);- cur = s;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- }- },- 0x15 => if (cur > 0) { // Ctrl-U → delete to start of line- delRange(buf, 0, cur);- cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 0x0b => if (cur < buf.items.len) { // Ctrl-K → delete to end of line- buf.shrinkRetainingCapacity(cur);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 0x16 => { // Ctrl-V: attach a clipboard image (macOS) at the cursor- var msg: ?[]const u8 = null;- if (grabClipboardImage(root.io)) |p| switch (stageImagePath(root, p)) {- .ok => {- const marker = "[Image] ";- buf.insertSlice(gpa, cur, marker) catch {};- cur += marker.len;- addMark(gpa, &marks, "[Image]");- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- .no_vision => msg = "this model can't see images — /model to a vision one (claude-*, gpt-5*)",- .read_fail => msg = "couldn't read the clipboard image",- } else msg = if (builtin.os.tag == .macos) "no image on the clipboard — copy an image first (this is Ctrl-V; ⌘V can't be captured)" else "clipboard image paste is macOS-only — use /image <path>";- if (msg) |m| { // feedback below the input, then redraw the prompt+buffer fresh- if (rstate.rows - 1 > rstate.crow) out.print("\x1b[{d}B", .{rstate.rows - 1 - rstate.crow}) catch {};- out.print("\r\n{s}· {s}{s}", .{ style.dim, m, style.reset }) catch {};- root.prompt() catch {};- rstate = .{};- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- }- },- 0x7f, 0x08 => if (cur > 0) { // backspace → delete char before cursor- delRange(buf, cur - 1, cur);- cur -= 1;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 0x03 => { // Ctrl-C: clear a non-empty line; on an empty line, quit- if (buf.items.len == 0) {- out.writeAll("^C\n") catch {};- out.flush() catch {};- return null;- }- buf.clearRetainingCapacity();- cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 0x1a => { // Ctrl-Z: save the session and quit (like a safe Ctrl-D)- out.writeAll("^Z — saving & quit\n") catch {};- out.flush() catch {};- saveSession(root, root.arena, root.session_name) catch {};- return null;- },- 0x04 => { // Ctrl-D: EOF on empty line, else forward-delete- if (buf.items.len == 0) {- out.writeAll("\n") catch {};- return null;- }- if (cur < buf.items.len) {- delRange(buf, cur, cur + 1);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- }- },- 0x1b => { // escape sequence: arrows, Alt/Option chords, CSI- // A bare Esc (no byte follows) clears the line — without- // this the chord read below would block and silently eat- // the next keypress.- if (in.buffered().len == 0 and !inputPending()) {- buf.clearRetainingCapacity();- cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- continue;- }- const b1 = in.takeByte() catch break;- if (b1 == 0x7f or b1 == 0x08) { // Option/Alt+Delete → delete previous word- const s = prevWord(buf.items, cur);- if (s < cur) {- delRange(buf, s, cur);- cur = s;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- }- continue;- }- if (b1 == 'b') { // Alt-b → word left- cur = prevWord(buf.items, cur);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- continue;- }- if (b1 == 'f') { // Alt-f → word right- cur = nextWord(buf.items, cur);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- continue;- }- if (b1 == 'd') { // Alt-d → delete next word- const e = nextWord(buf.items, cur);- if (e > cur) {- delRange(buf, cur, e);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- }- continue;- }- if (b1 != '[') continue;- // CSI: collect params until a final byte (0x40..0x7e).- var params: [16]u8 = undefined;- var pn: usize = 0;- var final: u8 = 0;- while (true) {- const x = in.takeByte() catch break;- if (x >= 0x40 and x <= 0x7e) {- final = x;- break;- }- if (pn < params.len) {- params[pn] = x;- pn += 1;- }- }- const ps = params[0..pn];- const word_mod = std.mem.indexOfScalar(u8, ps, ';') != null; // 1;3 (alt) / 1;5 (ctrl)- switch (final) {- 'A' => if (nav.up(gpa, history.items, buf.items)) |text| { // up → history back; snapshots draft (#101)- setLine(gpa, buf, text);- cur = buf.items.len;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 'B' => if (nav.down(history.items)) |text| { // down → history forward; restores draft past newest (#101)- setLine(gpa, buf, text);- cur = buf.items.len;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 'C' => { // right (word-right with a modifier)- cur = if (word_mod) nextWord(buf.items, cur) else @min(cur + 1, buf.items.len);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 'D' => { // left (word-left with a modifier)- cur = if (word_mod) prevWord(buf.items, cur) else (if (cur > 0) cur - 1 else 0);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 'H' => {- cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 'F' => {- cur = buf.items.len;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- 'R' => { // late DSR cursor-position reply (slow or- // multiplexed terminal missed the 500ms startup- // window): adopt the real input column so the- // horizontal window stays exact instead of the- // column-1 fallback. Same narrow-terminal policy as- // startup: too little room after the prompt → the- // input moves to its own row.- if (std.mem.indexOfScalar(u8, ps, ';')) |semi| {- const col = std.fmt.parseInt(usize, ps[semi + 1 ..], 10) catch 0;- if (col > 0) {- if (termCols() < col + 16) {- out.writeAll("\r\n") catch {};- prompt_col = 1;- } else prompt_col = col;- }- }- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- '~' => {- if (std.mem.eql(u8, ps, "200")) { // bracketed paste start- var blob: std.ArrayList(u8) = .empty;- defer blob.deinit(gpa);- while (true) { // read until the ESC[201~ end marker- const x = in.takeByte() catch break;- blob.append(gpa, x) catch break;- if (std.mem.endsWith(u8, blob.items, "\x1b[201~")) {- blob.shrinkRetainingCapacity(blob.items.len - 6);- break;- }- }- var pasted = blob.items;- if (pasted.len > 0 and pasted[pasted.len - 1] == '\n') pasted = pasted[0 .. pasted.len - 1];- const lines = std.mem.count(u8, pasted, "\n") + 1;- const dropped = cleanDroppedPath(gpa, root.home, pasted);- defer if (dropped) |dp| gpa.free(dp);- const drop_exists = if (dropped) |dp| blk: {- Io.Dir.cwd().access(root.io, dp, .{}) catch break :blk false;- break :blk true;- } else false;- if (drop_exists) {- // Drag-and-dropped file: terminals paste the path- // escaped/quoted with a trailing space. An image on a- // vision model is staged as an attachment (like /image- // and Ctrl-V); anything else inlines the cleaned full- // path however long it is.- var staged = false;- var dmsg: ?[]const u8 = null;- if (isImagePath(dropped.?)) switch (stageImagePath(root, dropped.?)) {- .ok => staged = true,- .no_vision => dmsg = "this model can't see images — ✓ in /models' vision column shows ones that can; path inlined instead",- .read_fail => dmsg = "couldn't read that image (missing or >5MB) — path inlined instead",- };- if (staged) {- const marker = "[Image] ";- buf.insertSlice(gpa, cur, marker) catch {};- cur += marker.len;- addMark(gpa, &marks, "[Image]");- } else {- buf.insertSlice(gpa, cur, dropped.?) catch {};- cur += dropped.?.len;- addMark(gpa, &marks, dropped.?);- }- if (dmsg) |m| { // feedback below the input, then redraw fresh (below)- if (rstate.rows - 1 > rstate.crow) out.print("\x1b[{d}B", .{rstate.rows - 1 - rstate.crow}) catch {};- out.print("\r\n{s}· {s}{s}", .{ style.dim, m, style.reset }) catch {};- root.prompt() catch {};- rstate = .{};- }- } else if (lines == 1 and pasted.len <= 80) {- buf.insertSlice(gpa, cur, pasted) catch {}; // short single-line paste: inline- cur += pasted.len;- } else { // multi-line/long: collapse to a placeholder, expand on submit- const ph = std.fmt.allocPrint(gpa, "[Pasted text #{d} +{d} lines]", .{ pastes.items.len + 1, lines }) catch "";- const body = gpa.dupe(u8, pasted) catch "";- if (ph.len > 0 and body.len > 0) {- pastes.append(gpa, .{ .ph = ph, .body = body }) catch {};- buf.insertSlice(gpa, cur, ph) catch {};- cur += ph.len;- }- }- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- } else if (std.mem.eql(u8, ps, "3")) { // forward delete- if (cur < buf.items.len) {- delRange(buf, cur, cur + 1);- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- }- } else if (std.mem.eql(u8, ps, "1") or std.mem.eql(u8, ps, "7")) {- cur = 0;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- } else if (std.mem.eql(u8, ps, "4") or std.mem.eql(u8, ps, "8")) {- cur = buf.items.len;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- }- },- else => {},- }- },- else => if (c >= 0x20) { // printable: insert at cursor- // '@' at a word boundary opens a fuzzy file picker over the- // repo (cwd walk, dot/build dirs skipped); the picked path is- // inserted at the cursor. A literal '@' still types fine —- // cancel the picker (esc/ctrl-c), or type it mid-word.- if (c == '@' and (cur == 0 or buf.items[cur - 1] == ' ')) {- var files: std.ArrayList([]const u8) = .empty;- defer {- for (files.items) |f| gpa.free(f);- files.deinit(gpa);- }- collectRepoFiles(root.io, gpa, &files);- if (files.items.len > 0) {- var items: std.ArrayList(PickItem) = .empty;- defer items.deinit(gpa);- for (files.items) |f| items.append(gpa, .{ .name = f }) catch {};- const picked = listPicker(root, root.arena, out, "File ›", items.items);- // The alt-screen picker (DECSET 1049) restores the main- // screen and cursor on exit, so the input block and- // rstate still match — just redraw over them below.- if (picked) |idx| {- buf.insertSlice(gpa, cur, files.items[idx]) catch {};- cur += files.items[idx].len;- addMark(gpa, &marks, files.items[idx]);- }- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- continue;- }- }- buf.insert(gpa, cur, c) catch {};- cur += 1;- redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);- },- }- }-- const trimmed = std.mem.trim(u8, buf.items, " \t\r");- if (trimmed.len > 0 and (history.items.len == 0 or !std.mem.eql(u8, history.items[history.items.len - 1], buf.items))) {- const dup = gpa.dupe(u8, buf.items) catch return buf.items;- history.append(gpa, dup) catch {};- }- return buf.items;-}+// The rest of the line editor's input helpers (ultracode wave palette, the+// `@` picker's binary/dir filters + file collection, drag-and-drop path+// cleanup, and the redraw/setLine/delRange/prevWord/nextWord/addMark buffer+// helpers hoisted out of readLine) live in input_util.zig; readLine() itself+// (+ HistoryNav, #101) lives in readline.zig — both split out of main.zig+// (600-line goal). isImagePath is re-exported (vision.zig back-imports it)+// and binaryFileExt is aliased back (a read_file guard below calls it).+const input_util = @import("input_util.zig");+pub const isImagePath = input_util.isImagePath;+const binaryFileExt = input_util.binaryFileExt;+const readline_mod = @import("readline.zig");+const readLine = readline_mod.readLine;// Session persistence (last model, input history) + the wire-format message// serializers live in serde.zig (600-line goal, std-only leaf). Aliased back.@@ -5030,7 +4098,7 @@ fn sessionTitle(root: *Agent) []const u8 {/// Save the conversation (messages + provider id/model + strict flag) to/// <name>.session.json in the cwd. The JSON message array is already the/// provider-native wire shape, so resume is a verbatim restore.-fn saveSession(root: *Agent, arena: Allocator, name: []const u8) !void {+pub fn saveSession(root: *Agent, arena: Allocator, name: []const u8) !void {var aw: Io.Writer.Allocating = .init(root.gpa);defer aw.deinit();var s: std.json.Stringify = .{ .writer = &aw.writer };@@ -5240,7 +4308,7 @@ pub const Agent = struct {next_ask_id: u64 = 1,tui_header_shown: bool = false,- fn prompt(self: *Agent) !void {+ pub fn prompt(self: *Agent) !void {if (json_mode) return; // SDK drives turns; no human promptconst w = self.out orelse return;const flag: []const u8 = if (self.strict and plan_mode) " strict·plan" else if (self.strict) " strict" else if (plan_mode) " plan" else "";@@ -8900,7 +7968,7 @@ fn outsideCwd(gpa: Allocator, path: []const u8) !ToolOutput {};}-const bash_stdout_cap = 128 * 1024;+pub const bash_stdout_cap = 128 * 1024;const bash_stderr_cap = 32 * 1024;const webfetch_cap = 256 * 1024;const codedb_result_cap = 64 * 1024;@@ -10058,18 +9126,6 @@ test "utf8Prefix truncates without splitting codepoints" {try std.testing.expectEqualStrings("ab\xC3\xA9", utf8Prefix(&s, 4));}-test "cleanDroppedPath unescapes terminal drops" {- const gpa = std.testing.allocator;- const p = cleanDroppedPath(gpa, "", "/tmp/My\\ File.txt ") orelse return error.TestUnexpectedResult;- defer gpa.free(p);- try std.testing.expectEqualStrings("/tmp/My File.txt", p);- const q = cleanDroppedPath(gpa, "/home/u", "'~/notes/a b.md'") orelse return error.TestUnexpectedResult;- defer gpa.free(q);- try std.testing.expectEqualStrings("/home/u/notes/a b.md", q);- try std.testing.expect(cleanDroppedPath(gpa, "", "hello world") == null); // not absolute- try std.testing.expect(cleanDroppedPath(gpa, "", "two\nlines") == null); // multi-line-}-test "resolveModelName exact aliases and miss" {const keys = Keys{ .values = [_]?[]const u8{null} ** provider_specs.len };try std.testing.expect(resolveModelName(keys, "gpt-5.5") != null); // exact name@@ -10077,53 +9133,6 @@ test "resolveModelName exact aliases and miss" {try std.testing.expect(resolveModelName(keys, "totally-unknown-zzz") == null);}-test "binaryFileExt flags binaries, passes text" {- try std.testing.expect(binaryFileExt("paper.pdf"));- try std.testing.expect(binaryFileExt("shot.PNG")); // case-insensitive- try std.testing.expect(binaryFileExt("lib.a"));- try std.testing.expect(!binaryFileExt("main.zig"));- try std.testing.expect(!binaryFileExt("README.md"));- try std.testing.expect(!binaryFileExt("Makefile")); // no extension- try std.testing.expect(isImagePath("a.jpeg"));- try std.testing.expect(!isImagePath("a.pdf"));-}--test "wrapAt: rows and columns across the right edge" {- // No prompt, 10-column terminal: bytes 0..9 fill row 0.- try std.testing.expectEqual(@as(usize, 0), wrapAt(0, 10, 0).row);- try std.testing.expectEqual(@as(usize, 5), wrapAt(0, 10, 5).col);- try std.testing.expectEqual(@as(usize, 0), wrapAt(0, 10, 9).row);- // Byte 10 is the first cell of row 1.- try std.testing.expectEqual(@as(usize, 1), wrapAt(0, 10, 10).row);- try std.testing.expectEqual(@as(usize, 0), wrapAt(0, 10, 10).col);- // Byte 25 → row 2, col 5.- try std.testing.expectEqual(@as(usize, 2), wrapAt(0, 10, 25).row);- try std.testing.expectEqual(@as(usize, 5), wrapAt(0, 10, 25).col);-}--test "wrapAt: a prompt prefix shifts the whole line right" {- // 4-column prompt: byte 5 sits at column 9 of row 0 (4+5).- try std.testing.expectEqual(@as(usize, 0), wrapAt(4, 10, 5).row);- try std.testing.expectEqual(@as(usize, 9), wrapAt(4, 10, 5).col);- // byte 6 → 4+6 == 10 → row 1, col 0.- try std.testing.expectEqual(@as(usize, 1), wrapAt(4, 10, 6).row);- try std.testing.expectEqual(@as(usize, 0), wrapAt(4, 10, 6).col);-}--test "wrapAt: zero columns never divides by zero" {- try std.testing.expectEqual(@as(usize, 0), wrapAt(0, 0, 3).col);-}--test "parseDsrCol: well-formed and malformed replies" {- try std.testing.expectEqual(@as(?usize, 34), parseDsrCol("[12;34R"));- try std.testing.expectEqual(@as(?usize, 1), parseDsrCol("[1;1R"));- try std.testing.expectEqual(@as(?usize, null), parseDsrCol("[12R")); // no column- try std.testing.expectEqual(@as(?usize, null), parseDsrCol("[1;0R")); // col 0 is meaningless- try std.testing.expectEqual(@as(?usize, null), parseDsrCol("[1;xR"));- try std.testing.expectEqual(@as(?usize, null), parseDsrCol("12;34R")); // missing CSI intro- try std.testing.expectEqual(@as(?usize, null), parseDsrCol(""));-}-test "scoreSigMessage: canonical bytes are cross-language stable" {// The Python SDK (score_signature) and the telemetry worker recompute// this byte-for-byte; {d:.6} drifting would silently break every sig.@@ -10268,17 +9277,6 @@ test "Keys.defaultProvider: first keyed provider on its default model" {try std.testing.expectError(error.MissingKey, none.defaultProvider());}-test "fillCompletions includes ultracode slash command" {- var out: std.ArrayList([]const u8) = .empty;- defer out.deinit(std.testing.allocator);- _ = fillCompletions(std.testing.allocator, "/ult", &out);- var found = false;- for (out.items) |item| {- if (std.mem.eql(u8, item, "/ultracode")) found = true;- }- try std.testing.expect(found);-}-test "strField/intField: typed JSON field extraction, null on wrong type or non-object" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();@@ -10313,16 +9311,6 @@ test "extractText: string content, joined text blocks, and empties" {try std.testing.expectEqualStrings("", extractText(a, Value{ .null = {} }));}-test "isImagePath: known image extensions, case-insensitive" {- try std.testing.expect(isImagePath("photo.png"));- try std.testing.expect(isImagePath("a.JPEG"));- try std.testing.expect(isImagePath("x.webp"));- try std.testing.expect(isImagePath("dir/sub/pic.gif"));- try std.testing.expect(!isImagePath("readme.md"));- try std.testing.expect(!isImagePath("noext"));- try std.testing.expect(!isImagePath("archive.tar.gz"));-}-test "Agent.codepointCount: counts UTF-8 codepoints, not bytes" {try std.testing.expectEqual(@as(usize, 5), Agent.codepointCount("hello"));try std.testing.expectEqual(@as(usize, 0), Agent.codepointCount(""));diff --git a/src/readline.zig b/src/readline.zignew file mode 100644index 00000000..d7d77175--- /dev/null+++ b/src/readline.zig@@ -0,0 +1,596 @@+//! The interactive line editor: readLine() reads one input line in raw+//! terminal mode with history navigation (HistoryNav, #101), tab+//! completion, bracketed paste, the `@` file picker, drag-and-drop path+//! insertion, and clipboard image paste (Ctrl-V). Split out of main.zig+//! (600-line goal). The redraw/setLine/delRange/prevWord/nextWord/addMark+//! buffer helpers + the wrap/completion/palette math live in input_util.zig+//! (imported here) to stay under the line goal. main.zig back-imports+//! Agent + saveSession; the alias here is `main_mod`, not `root`, since+//! readLine's own first parameter is named `root`.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const builtin = @import("builtin");++const ansi = @import("ansi.zig");+const style = &ansi.style;++const terminal = @import("term.zig");+const tty = terminal.tty;+const termCols = terminal.termCols;+const inputPending = terminal.inputPending;+const inputPendingTimed = terminal.inputPendingTimed;++const pickers = @import("pickers.zig");+const PickItem = pickers.PickItem;+const listPicker = pickers.listPicker;++const vision = @import("vision.zig");+const stageImagePath = vision.stageImagePath;+const grabClipboardImage = vision.grabClipboardImage;++const input_util = @import("input_util.zig");+const fillCompletions = input_util.fillCompletions;+const LineRender = input_util.LineRender;+const parseDsrCol = input_util.parseDsrCol;+const cleanDroppedPath = input_util.cleanDroppedPath;+const collectRepoFiles = input_util.collectRepoFiles;+const isImagePath = input_util.isImagePath;+const redraw = input_util.redraw;+const setLine = input_util.setLine;+const delRange = input_util.delRange;+const prevWord = input_util.prevWord;+const nextWord = input_util.nextWord;+const addMark = input_util.addMark;++const main_mod = @import("main.zig");+const Agent = main_mod.Agent;+const saveSession = main_mod.saveSession;++/// History + unsent-draft navigation for the line editor (#101). Mirrors the+/// GUI's promptHistoryNavigation.ts: stepping UP out of the fresh slot snapshots+/// the half-typed draft; stepping DOWN past the newest entry restores it instead+/// of clearing the line. `idx == history.len` is the fresh (editing) slot.+const HistoryNav = struct {+ idx: usize,+ draft: ?[]const u8 = null, // owned snapshot of the unsent line; freed by the caller++ fn init(history_len: usize) HistoryNav {+ return .{ .idx = history_len };+ }++ /// UP / older. `current` is the live buffer. Returns the text the buffer+ /// should show next, or null to leave it unchanged (already at the oldest).+ /// Leaving the fresh slot snapshots `current` as the draft to restore later.+ fn up(self: *HistoryNav, gpa: Allocator, history: []const []const u8, current: []const u8) ?[]const u8 {+ if (self.idx == 0) return null;+ if (self.idx == history.len) { // leaving the fresh slot: keep the draft+ if (self.draft) |d| gpa.free(d);+ self.draft = gpa.dupe(u8, current) catch null;+ }+ self.idx -= 1;+ return history[self.idx];+ }++ /// DOWN / newer. Returns the text to show next, or null to leave it+ /// unchanged (already at the fresh slot). Past the newest entry, restores the+ /// snapshotted draft (or "" when there was none) instead of clearing it.+ fn down(self: *HistoryNav, history: []const []const u8) ?[]const u8 {+ if (self.idx >= history.len) return null;+ self.idx += 1;+ if (self.idx == history.len) return self.draft orelse "";+ return history[self.idx];+ }+};++test "HistoryNav: up snapshots the draft, down past newest restores it (#101)" {+ const gpa = std.testing.allocator;+ const history = [_][]const u8{ "first", "second" };+ var nav: HistoryNav = .init(history.len);+ defer if (nav.draft) |d| gpa.free(d);++ // up from the fresh slot → newest entry, draft snapshotted+ try std.testing.expectEqualStrings("second", nav.up(gpa, &history, "draft in progress").?);+ // up again → older entry+ try std.testing.expectEqualStrings("first", nav.up(gpa, &history, "second").?);+ // up at the oldest → no change+ try std.testing.expect(nav.up(gpa, &history, "first") == null);+ // down → back to newest+ try std.testing.expectEqualStrings("second", nav.down(&history).?);+ // down past newest → the draft is restored, NOT cleared (the bug)+ try std.testing.expectEqualStrings("draft in progress", nav.down(&history).?);+ // down at the fresh slot → no change+ try std.testing.expect(nav.down(&history) == null);+}++test "HistoryNav: no draft → fresh slot returns empty, no leak (#101)" {+ const gpa = std.testing.allocator;+ const history = [_][]const u8{"only"};+ var nav: HistoryNav = .init(history.len);+ defer if (nav.draft) |d| gpa.free(d);+ try std.testing.expectEqualStrings("only", nav.up(gpa, &history, "").?);+ try std.testing.expectEqualStrings("", nav.down(&history).?); // empty draft → empty line, as today+}++/// Read one input line with a tiny raw-mode editor: ↑/↓ walk history,+/// Tab completes/cycles (models, providers, slash commands), backspace edits,+/// Ctrl-C cancels the line, Ctrl-D on an empty line is EOF. `buf` is reused+/// across calls and holds the result (valid until the next call). Returns the+/// line, or null on EOF. Falls back to a plain buffered line read when stdin+/// isn't a TTY (pipes, tests). DECSC/DECRC saves/restores the cursor to redraw.+pub fn readLine(+ root: *Agent,+ in: *Io.Reader,+ out: *Io.Writer,+ gpa: Allocator,+ history: *std.ArrayList([]const u8),+ buf: *std.ArrayList(u8),+) !?[]const u8 {+ const raw_state = tty.enterRaw(true) orelse return in.takeDelimiter('\n');+ defer tty.restore(raw_state);++ buf.clearRetainingCapacity();+ var cur: usize = 0; // cursor index within buf+ var nav: HistoryNav = .init(history.items.len); // history + unsent-draft nav (#101)+ defer if (nav.draft) |d| gpa.free(d);+ out.writeAll("\x1b[?2004h") catch {}; // enable bracketed paste (terminal wraps pastes in ESC[200~ … ESC[201~)+ defer out.writeAll("\x1b[?2004l") catch {};+ out.flush() catch {};++ // Where does input start? Ask the terminal (DSR 6) for the column right+ // after the prompt; the renderer treats those columns as a fixed prefix+ // and wraps the input across rows below it. Cursor moves in redraw are all+ // relative (never an absolute DECSC anchor), so a wrap-induced scroll+ // shifts the whole block together and never strands the prompt. Typed-+ // ahead text bytes that race the reply are replayed into the edit loop+ // below; a typed-ahead escape sequence inside that ~ms window is dropped.+ var prompt_col: usize = 1; // 1-based column where the buffer renders+ var rstate: LineRender = .{}; // rows used + cursor row of the last redraw+ var pending: std.ArrayList(u8) = .empty;+ defer pending.deinit(gpa);+ var pend_i: usize = 0;+ out.writeAll("\x1b[6n") catch {};+ out.flush() catch {};+ dsr: {+ var polls: usize = 0;+ var esc: [16]u8 = undefined;+ var n: usize = 0;+ var in_esc = false;+ while (true) {+ if (in.buffered().len == 0 and !inputPending()) { // 50ms poll+ polls += 1;+ if (polls >= 10) break :dsr; // no reply in ~500ms: fall back+ // to column 1 — a later reply is still adopted (CSI 'R').+ continue;+ }+ const b = in.takeByte() catch break :dsr;+ if (!in_esc) {+ if (b == 0x1b) {+ in_esc = true;+ n = 0;+ continue;+ }+ pending.append(gpa, b) catch {};+ if (pending.items.len > 64) break :dsr;+ continue;+ }+ if (n == 0 and b != '[') { // Alt-chord typed ahead: drop it+ in_esc = false;+ continue;+ }+ if (n < esc.len) {+ esc[n] = b;+ n += 1;+ }+ if (n >= 2 and b >= 0x40 and b <= 0x7e) { // CSI final byte+ if (b == 'R') { // the reply: ESC [ row ; col R+ prompt_col = parseDsrCol(esc[0..n]) orelse 1;+ break :dsr;+ }+ in_esc = false; // some other CSI typed ahead — drop it+ n = 0;+ }+ }+ }+ // Narrow terminal: when the prompt leaves too little room (the token-+ // stats prompt nearly fills a small window), give the input its own+ // row — what shells do — rather than wrapping in a sliver beside the+ // prompt.+ if (termCols() < prompt_col + 16) {+ out.writeAll("\r\n") catch {};+ out.flush() catch {};+ prompt_col = 1;+ }++ // Tab-completion cycle state.+ var comp_items: std.ArrayList([]const u8) = .empty;+ defer comp_items.deinit(gpa);+ var comp_base: usize = 0;+ var comp_idx: usize = 0;+ var comp_active = false;++ // Bracketed-paste collapse: a multi-line paste becomes a "[Pasted text #N+ // +L lines]" placeholder in the buffer; on submit each placeholder is+ // expanded back to its full text.+ const Paste = struct { ph: []const u8, body: []const u8 };+ var pastes: std.ArrayList(Paste) = .empty;+ defer {+ for (pastes.items) |p| {+ gpa.free(p.ph);+ gpa.free(p.body);+ }+ pastes.deinit(gpa);+ }++ // File paths inserted by the @ picker or a drag-and-drop (plus the+ // "[Image]" attachment marker): redraw renders these spans highlighted.+ // Editing inside a span just drops its highlight — the text stays.+ var marks: std.ArrayList([]const u8) = .empty;+ defer {+ for (marks.items) |m| gpa.free(m);+ marks.deinit(gpa);+ }++ while (true) {+ // Replay any text bytes that raced the DSR reply, then read live.+ const c = if (pend_i < pending.items.len) blk: {+ const b = pending.items[pend_i];+ pend_i += 1;+ break :blk b;+ } else blk: {+ // While the input contains `ultracode`, wave the rainbow shine+ // across the letters: poll for input with a slower 110ms timeout,+ // and on each idle tick advance the phase + redraw so the hue+ // glides and breathes (~9fps, calm + rhythmic rather than a fast+ // flicker).+ while (std.ascii.indexOfIgnoreCase(buf.items, "ultracode") != null) {+ if (inputPendingTimed(110)) break; // keystroke ready — read it below+ input_util.g_shine_phase +%= 1;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ }+ break :blk in.takeByte() catch return null;+ };+ if (c != 0x09) comp_active = false; // any non-Tab key ends the cycle+ switch (c) {+ 0x09 => { // Tab: complete, or cycle through matches on repeat+ if (!comp_active) {+ comp_items.clearRetainingCapacity();+ comp_base = fillCompletions(gpa, buf.items, &comp_items);+ if (comp_items.items.len == 0) continue;+ comp_idx = 0;+ comp_active = true;+ } else if (comp_items.items.len > 0) {+ comp_idx = (comp_idx + 1) % comp_items.items.len;+ } else continue;+ buf.shrinkRetainingCapacity(comp_base);+ buf.appendSlice(gpa, comp_items.items[comp_idx]) catch {};+ cur = buf.items.len;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ '\r', '\n' => {+ // The cursor may be mid-block; step past the last input row so+ // the submitted line and whatever prints next start cleanly.+ if (rstate.rows - 1 > rstate.crow) out.print("\x1b[{d}B", .{rstate.rows - 1 - rstate.crow}) catch {};+ out.writeAll("\r\n") catch {};+ out.flush() catch {};+ // Expand any pasted placeholders back to their full text.+ for (pastes.items) |p| {+ if (std.mem.indexOf(u8, buf.items, p.ph) == null) continue;+ const sz = std.mem.replacementSize(u8, buf.items, p.ph, p.body);+ const tmp = gpa.alloc(u8, sz) catch break;+ _ = std.mem.replace(u8, buf.items, p.ph, p.body, tmp);+ buf.clearRetainingCapacity();+ buf.appendSlice(gpa, tmp) catch {};+ gpa.free(tmp);+ }+ break;+ },+ 0x01 => { // Ctrl-A → start of line+ cur = 0;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 0x05 => { // Ctrl-E → end of line+ cur = buf.items.len;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 0x02 => if (cur > 0) { // Ctrl-B → left+ cur -= 1;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 0x06 => if (cur < buf.items.len) { // Ctrl-F → right+ cur += 1;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 0x17, 0x1f => { // Ctrl-W / Ctrl-_ → delete previous word+ const s = prevWord(buf.items, cur);+ if (s < cur) {+ delRange(buf, s, cur);+ cur = s;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ }+ },+ 0x15 => if (cur > 0) { // Ctrl-U → delete to start of line+ delRange(buf, 0, cur);+ cur = 0;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 0x0b => if (cur < buf.items.len) { // Ctrl-K → delete to end of line+ buf.shrinkRetainingCapacity(cur);+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 0x16 => { // Ctrl-V: attach a clipboard image (macOS) at the cursor+ var msg: ?[]const u8 = null;+ if (grabClipboardImage(root.io)) |p| switch (stageImagePath(root, p)) {+ .ok => {+ const marker = "[Image] ";+ buf.insertSlice(gpa, cur, marker) catch {};+ cur += marker.len;+ addMark(gpa, &marks, "[Image]");+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ .no_vision => msg = "this model can't see images — /model to a vision one (claude-*, gpt-5*)",+ .read_fail => msg = "couldn't read the clipboard image",+ } else msg = if (builtin.os.tag == .macos) "no image on the clipboard — copy an image first (this is Ctrl-V; ⌘V can't be captured)" else "clipboard image paste is macOS-only — use /image <path>";+ if (msg) |m| { // feedback below the input, then redraw the prompt+buffer fresh+ if (rstate.rows - 1 > rstate.crow) out.print("\x1b[{d}B", .{rstate.rows - 1 - rstate.crow}) catch {};+ out.print("\r\n{s}· {s}{s}", .{ style.dim, m, style.reset }) catch {};+ root.prompt() catch {};+ rstate = .{};+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ }+ },+ 0x7f, 0x08 => if (cur > 0) { // backspace → delete char before cursor+ delRange(buf, cur - 1, cur);+ cur -= 1;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 0x03 => { // Ctrl-C: clear a non-empty line; on an empty line, quit+ if (buf.items.len == 0) {+ out.writeAll("^C\n") catch {};+ out.flush() catch {};+ return null;+ }+ buf.clearRetainingCapacity();+ cur = 0;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 0x1a => { // Ctrl-Z: save the session and quit (like a safe Ctrl-D)+ out.writeAll("^Z — saving & quit\n") catch {};+ out.flush() catch {};+ saveSession(root, root.arena, root.session_name) catch {};+ return null;+ },+ 0x04 => { // Ctrl-D: EOF on empty line, else forward-delete+ if (buf.items.len == 0) {+ out.writeAll("\n") catch {};+ return null;+ }+ if (cur < buf.items.len) {+ delRange(buf, cur, cur + 1);+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ }+ },+ 0x1b => { // escape sequence: arrows, Alt/Option chords, CSI+ // A bare Esc (no byte follows) clears the line — without+ // this the chord read below would block and silently eat+ // the next keypress.+ if (in.buffered().len == 0 and !inputPending()) {+ buf.clearRetainingCapacity();+ cur = 0;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ continue;+ }+ const b1 = in.takeByte() catch break;+ if (b1 == 0x7f or b1 == 0x08) { // Option/Alt+Delete → delete previous word+ const s = prevWord(buf.items, cur);+ if (s < cur) {+ delRange(buf, s, cur);+ cur = s;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ }+ continue;+ }+ if (b1 == 'b') { // Alt-b → word left+ cur = prevWord(buf.items, cur);+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ continue;+ }+ if (b1 == 'f') { // Alt-f → word right+ cur = nextWord(buf.items, cur);+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ continue;+ }+ if (b1 == 'd') { // Alt-d → delete next word+ const e = nextWord(buf.items, cur);+ if (e > cur) {+ delRange(buf, cur, e);+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ }+ continue;+ }+ if (b1 != '[') continue;+ // CSI: collect params until a final byte (0x40..0x7e).+ var params: [16]u8 = undefined;+ var pn: usize = 0;+ var final: u8 = 0;+ while (true) {+ const x = in.takeByte() catch break;+ if (x >= 0x40 and x <= 0x7e) {+ final = x;+ break;+ }+ if (pn < params.len) {+ params[pn] = x;+ pn += 1;+ }+ }+ const ps = params[0..pn];+ const word_mod = std.mem.indexOfScalar(u8, ps, ';') != null; // 1;3 (alt) / 1;5 (ctrl)+ switch (final) {+ 'A' => if (nav.up(gpa, history.items, buf.items)) |text| { // up → history back; snapshots draft (#101)+ setLine(gpa, buf, text);+ cur = buf.items.len;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 'B' => if (nav.down(history.items)) |text| { // down → history forward; restores draft past newest (#101)+ setLine(gpa, buf, text);+ cur = buf.items.len;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 'C' => { // right (word-right with a modifier)+ cur = if (word_mod) nextWord(buf.items, cur) else @min(cur + 1, buf.items.len);+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 'D' => { // left (word-left with a modifier)+ cur = if (word_mod) prevWord(buf.items, cur) else (if (cur > 0) cur - 1 else 0);+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 'H' => {+ cur = 0;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 'F' => {+ cur = buf.items.len;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ 'R' => { // late DSR cursor-position reply (slow or+ // multiplexed terminal missed the 500ms startup+ // window): adopt the real input column so the+ // horizontal window stays exact instead of the+ // column-1 fallback. Same narrow-terminal policy as+ // startup: too little room after the prompt → the+ // input moves to its own row.+ if (std.mem.indexOfScalar(u8, ps, ';')) |semi| {+ const col = std.fmt.parseInt(usize, ps[semi + 1 ..], 10) catch 0;+ if (col > 0) {+ if (termCols() < col + 16) {+ out.writeAll("\r\n") catch {};+ prompt_col = 1;+ } else prompt_col = col;+ }+ }+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ '~' => {+ if (std.mem.eql(u8, ps, "200")) { // bracketed paste start+ var blob: std.ArrayList(u8) = .empty;+ defer blob.deinit(gpa);+ while (true) { // read until the ESC[201~ end marker+ const x = in.takeByte() catch break;+ blob.append(gpa, x) catch break;+ if (std.mem.endsWith(u8, blob.items, "\x1b[201~")) {+ blob.shrinkRetainingCapacity(blob.items.len - 6);+ break;+ }+ }+ var pasted = blob.items;+ if (pasted.len > 0 and pasted[pasted.len - 1] == '\n') pasted = pasted[0 .. pasted.len - 1];+ const lines = std.mem.count(u8, pasted, "\n") + 1;+ const dropped = cleanDroppedPath(gpa, root.home, pasted);+ defer if (dropped) |dp| gpa.free(dp);+ const drop_exists = if (dropped) |dp| blk: {+ Io.Dir.cwd().access(root.io, dp, .{}) catch break :blk false;+ break :blk true;+ } else false;+ if (drop_exists) {+ // Drag-and-dropped file: terminals paste the path+ // escaped/quoted with a trailing space. An image on a+ // vision model is staged as an attachment (like /image+ // and Ctrl-V); anything else inlines the cleaned full+ // path however long it is.+ var staged = false;+ var dmsg: ?[]const u8 = null;+ if (isImagePath(dropped.?)) switch (stageImagePath(root, dropped.?)) {+ .ok => staged = true,+ .no_vision => dmsg = "this model can't see images — ✓ in /models' vision column shows ones that can; path inlined instead",+ .read_fail => dmsg = "couldn't read that image (missing or >5MB) — path inlined instead",+ };+ if (staged) {+ const marker = "[Image] ";+ buf.insertSlice(gpa, cur, marker) catch {};+ cur += marker.len;+ addMark(gpa, &marks, "[Image]");+ } else {+ buf.insertSlice(gpa, cur, dropped.?) catch {};+ cur += dropped.?.len;+ addMark(gpa, &marks, dropped.?);+ }+ if (dmsg) |m| { // feedback below the input, then redraw fresh (below)+ if (rstate.rows - 1 > rstate.crow) out.print("\x1b[{d}B", .{rstate.rows - 1 - rstate.crow}) catch {};+ out.print("\r\n{s}· {s}{s}", .{ style.dim, m, style.reset }) catch {};+ root.prompt() catch {};+ rstate = .{};+ }+ } else if (lines == 1 and pasted.len <= 80) {+ buf.insertSlice(gpa, cur, pasted) catch {}; // short single-line paste: inline+ cur += pasted.len;+ } else { // multi-line/long: collapse to a placeholder, expand on submit+ const ph = std.fmt.allocPrint(gpa, "[Pasted text #{d} +{d} lines]", .{ pastes.items.len + 1, lines }) catch "";+ const body = gpa.dupe(u8, pasted) catch "";+ if (ph.len > 0 and body.len > 0) {+ pastes.append(gpa, .{ .ph = ph, .body = body }) catch {};+ buf.insertSlice(gpa, cur, ph) catch {};+ cur += ph.len;+ }+ }+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ } else if (std.mem.eql(u8, ps, "3")) { // forward delete+ if (cur < buf.items.len) {+ delRange(buf, cur, cur + 1);+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ }+ } else if (std.mem.eql(u8, ps, "1") or std.mem.eql(u8, ps, "7")) {+ cur = 0;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ } else if (std.mem.eql(u8, ps, "4") or std.mem.eql(u8, ps, "8")) {+ cur = buf.items.len;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ }+ },+ else => {},+ }+ },+ else => if (c >= 0x20) { // printable: insert at cursor+ // '@' at a word boundary opens a fuzzy file picker over the+ // repo (cwd walk, dot/build dirs skipped); the picked path is+ // inserted at the cursor. A literal '@' still types fine —+ // cancel the picker (esc/ctrl-c), or type it mid-word.+ if (c == '@' and (cur == 0 or buf.items[cur - 1] == ' ')) {+ var files: std.ArrayList([]const u8) = .empty;+ defer {+ for (files.items) |f| gpa.free(f);+ files.deinit(gpa);+ }+ collectRepoFiles(root.io, gpa, &files);+ if (files.items.len > 0) {+ var items: std.ArrayList(PickItem) = .empty;+ defer items.deinit(gpa);+ for (files.items) |f| items.append(gpa, .{ .name = f }) catch {};+ const picked = listPicker(root, root.arena, out, "File ›", items.items);+ // The alt-screen picker (DECSET 1049) restores the main+ // screen and cursor on exit, so the input block and+ // rstate still match — just redraw over them below.+ if (picked) |idx| {+ buf.insertSlice(gpa, cur, files.items[idx]) catch {};+ cur += files.items[idx].len;+ addMark(gpa, &marks, files.items[idx]);+ }+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ continue;+ }+ }+ buf.insert(gpa, cur, c) catch {};+ cur += 1;+ redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);+ },+ }+ }++ const trimmed = std.mem.trim(u8, buf.items, " \t\r");+ if (trimmed.len > 0 and (history.items.len == 0 or !std.mem.eql(u8, history.items[history.items.len - 1], buf.items))) {+ const dup = gpa.dupe(u8, buf.items) catch return buf.items;+ history.append(gpa, dup) catch {};+ }+ return buf.items;+}