xonecas.io
79113
Ma

mini-coding-agent / commit 9306b69

chore: code cleanup, deduplication, etc

xonecas2026-10-25 9306b69bc597f0b897e9382645947261c3d53846 parent 7ccf23e

20 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

src/agent.zig+2−12
@@ -7,6 +7,7 @@ const tools = @import("tools.zig");
77 const session = @import("session.zig");
88 const config = @import("config.zig");
99 const time = @import("time.zig");
10+const text = @import("text.zig");
1011
1112 pub const Phase = enum { preparing, waiting_model, streaming, running_tool, snapshotting, pausing, idle };
1213
@@ -302,7 +303,7 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(message_mod.Message), int
302303 return;
303304 }
304305 if (cancelled(opts, listener)) return;
305- const joined = tryJoin(opts.a, held.items) catch {
306+ const joined = text.join(opts.a, held.items, "\n") catch {
306307 listener.emit(.{ .err = "out of memory" });
307308 return;
308309 };
@@ -312,14 +313,3 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(message_mod.Message), int
312313 };
313314 }
314315 }
315-
316-fn tryJoin(a: std.mem.Allocator, parts: []const []const u8) std.mem.Allocator.Error![]const u8 {
317- if (parts.len == 0) return "";
318- if (parts.len == 1) return parts[0];
319- var out: std.ArrayList(u8) = .empty;
320- for (parts, 0..) |p, i| {
321- if (i > 0) try out.append(a, '\n');
322- try out.appendSlice(a, p);
323- }
324- return out.items;
325-}
src/api.zig+44−11
@@ -141,18 +141,18 @@ pub fn blockAt(comptime T: type, list: *std.ArrayList(T), a: std.mem.Allocator,
141141 return &list.items[idx];
142142 }
143143
144+const StreamFn = *const fn (Request, Sink) std.mem.Allocator.Error!message_mod.AssistantMessage;
145+
146+const routes = [_]struct { api: []const u8, stream: StreamFn }{
147+ .{ .api = "openai-completions", .stream = @import("api/openai_completions.zig").stream },
148+ .{ .api = "openai-responses", .stream = @import("api/openai_responses.zig").stream },
149+ .{ .api = "anthropic-messages", .stream = @import("api/anthropic_messages.zig").stream },
150+ .{ .api = "google-generative-ai", .stream = @import("api/google_generative_ai.zig").stream },
151+};
152+
144153 pub fn stream(req: Request, sink: Sink) std.mem.Allocator.Error!message_mod.AssistantMessage {
145- if (std.mem.eql(u8, req.model.api, "openai-completions")) {
146- return @import("api/openai_completions.zig").stream(req, sink);
147- }
148- if (std.mem.eql(u8, req.model.api, "anthropic-messages")) {
149- return @import("api/anthropic_messages.zig").stream(req, sink);
150- }
151- if (std.mem.eql(u8, req.model.api, "openai-responses")) {
152- return @import("api/openai_responses.zig").stream(req, sink);
153- }
154- if (std.mem.eql(u8, req.model.api, "google-generative-ai")) {
155- return @import("api/google_generative_ai.zig").stream(req, sink);
154+ for (routes) |route| {
155+ if (std.mem.eql(u8, req.model.api, route.api)) return route.stream(req, sink);
156156 }
157157 var msg = newAssistant(req);
158158 msg.stop_reason = .err;
@@ -263,6 +263,39 @@ pub fn appendCalls(msg: *message_mod.AssistantMessage, sink: Sink, a: std.mem.Al
263263 return any;
264264 }
265265
266+/// The reasoning effort to send, or null when reasoning is off for this turn.
267+pub fn effortOn(req: Request) ?[]const u8 {
268+ if (req.effort.len == 0 or std.mem.eql(u8, req.effort, "off")) return null;
269+ return req.effort;
270+}
271+
272+/// The wire stop reasons that carry a meaning of their own; anything else is a
273+/// plain stop, which the caller falls back to.
274+const stop_reasons = [_]struct { wire: []const u8, reason: message_mod.StopReason, message: ?[]const u8 = null }{
275+ .{ .wire = "length", .reason = .length },
276+ .{ .wire = "max_tokens", .reason = .length },
277+ .{ .wire = "MAX_TOKENS", .reason = .length },
278+ .{ .wire = "tool_use", .reason = .tool_use },
279+ .{ .wire = "tool_calls", .reason = .tool_use },
280+ .{ .wire = "function_call", .reason = .tool_use },
281+ .{ .wire = "content_filter", .reason = .err, .message = "Provider finish_reason: content_filter" },
282+ .{ .wire = "refusal", .reason = .err, .message = "Provider stop_reason: refusal" },
283+ .{ .wire = "sensitive", .reason = .err, .message = "Provider stop_reason: sensitive" },
284+};
285+
286+/// Applies a provider's own stop reason. Returns false when the table has no
287+/// entry for it, so the caller can fall back to its own default.
288+pub fn stopReason(msg: *message_mod.AssistantMessage, raw: ?[]const u8) bool {
289+ const wire = raw orelse return false;
290+ for (stop_reasons) |entry| {
291+ if (!std.mem.eql(u8, entry.wire, wire)) continue;
292+ msg.stop_reason = entry.reason;
293+ msg.error_message = entry.message;
294+ return true;
295+ }
296+ return false;
297+}
298+
266299 pub fn argumentsOrObject(args: []const u8) []const u8 {
267300 return if (args.len > 0) args else "{}";
268301 }
src/api/anthropic_messages.zig+5−25
@@ -363,30 +363,6 @@ const State = struct {
363363 }
364364 };
365365
366-fn mapStopReason(st: *State, has_calls: bool) void {
367- if (has_calls) {
368- st.msg.stop_reason = .tool_use;
369- return;
370- }
371- const reason = st.stop_reason orelse {
372- st.msg.stop_reason = .stop;
373- return;
374- };
375- if (std.mem.eql(u8, reason, "max_tokens")) {
376- st.msg.stop_reason = .length;
377- } else if (std.mem.eql(u8, reason, "tool_use")) {
378- st.msg.stop_reason = .tool_use;
379- } else if (std.mem.eql(u8, reason, "refusal")) {
380- st.msg.stop_reason = .err;
381- st.msg.error_message = "Provider stop_reason: refusal";
382- } else if (std.mem.eql(u8, reason, "sensitive")) {
383- st.msg.stop_reason = .err;
384- st.msg.error_message = "Provider stop_reason: sensitive";
385- } else {
386- st.msg.stop_reason = .stop;
387- }
388-}
389-
390366 fn finalize(st: *State) !void {
391367 const a = st.req.pers;
392368 for (st.blocks.items) |block| {
@@ -406,7 +382,11 @@ fn finalize(st: *State) !void {
406382 api.finishUsage(st.msg, st.req.model, st.usage);
407383
408384 st.msg.raw_stop_reason = st.stop_reason;
409- mapStopReason(st, has_calls);
385+ if (has_calls) {
386+ st.msg.stop_reason = .tool_use;
387+ } else if (!api.stopReason(st.msg, st.stop_reason)) {
388+ st.msg.stop_reason = .stop;
389+ }
410390 }
411391
412392 const wire = api.Wire{
src/api/google_generative_ai.zig+2−6
@@ -261,13 +261,9 @@ fn finalize(st: *State) !void {
261261 api.finishUsage(st.msg, st.req.model, st.usage);
262262
263263 st.msg.raw_stop_reason = st.finish;
264- if (st.finish) |finish| {
265- if (std.mem.eql(u8, finish, "MAX_TOKENS")) {
266- st.msg.stop_reason = .length;
267- return;
268- }
264+ if (!api.stopReason(st.msg, st.finish)) {
265+ st.msg.stop_reason = if (has_calls) .tool_use else .stop;
269266 }
270- st.msg.stop_reason = if (has_calls) .tool_use else .stop;
271267 }
272268
273269 const wire = api.Wire{
src/api/openai_completions.zig+7−25
@@ -90,7 +90,7 @@ fn buildMessages(a: std.mem.Allocator, req: api.Request) ![]const Message {
9090 // Some upstreams reject a thinking-mode request whose assistant messages omit
9191 // reasoning_content, even when the turn produced none, so the field is always
9292 // sent (empty) while reasoning is on.
93- const reasoning_on = req.effort.len > 0 and !std.mem.eql(u8, req.effort, "off");
93+ const reasoning_on = api.effortOn(req) != null;
9494 if (req.system_prompt.len > 0) {
9595 try out.append(a, .{ .system = .{ .content = req.system_prompt } });
9696 }
@@ -134,10 +134,9 @@ fn buildMessages(a: std.mem.Allocator, req: api.Request) ![]const Message {
134134
135135 fn buildBody(req: api.Request) ![]u8 {
136136 const a = req.scratch;
137- const effort = if (req.effort.len > 0 and !std.mem.eql(u8, req.effort, "off")) req.effort else null;
138137 const body = Body{
139138 .model = req.model.id,
140- .reasoning_effort = effort,
139+ .reasoning_effort = api.effortOn(req),
141140 .messages = try buildMessages(a, req),
142141 .tools = if (req.tools_json.len > 0) .{ .a = a, .json = req.tools_json, .form = .{
143142 .open = "[",
@@ -285,34 +284,17 @@ fn usageOf(u: Chunk.Usage) message_mod.Usage {
285284 return usage;
286285 }
287286
288-fn mapStopReason(st: *State, has_calls: bool) void {
289- if (has_calls) {
290- st.msg.stop_reason = .tool_use;
291- return;
292- }
293- const reason = st.finish_reason orelse {
294- st.msg.stop_reason = .stop;
295- return;
296- };
297- if (std.mem.eql(u8, reason, "length")) {
298- st.msg.stop_reason = .length;
299- } else if (std.mem.eql(u8, reason, "function_call") or std.mem.eql(u8, reason, "tool_calls")) {
300- st.msg.stop_reason = .tool_use;
301- } else if (std.mem.eql(u8, reason, "content_filter")) {
302- st.msg.stop_reason = .err;
303- st.msg.error_message = "Provider finish_reason: content_filter";
304- } else {
305- st.msg.stop_reason = .stop;
306- }
307-}
308-
309287 fn finalize(st: *State) !void {
310288 const a = st.req.pers;
311289 try api.appendParts(st.msg, a, st.thinking.items, st.signature, st.text.items);
312290 const has_calls = try api.appendCalls(st.msg, st.sink, a, st.calls.items, st.failed);
313291 api.finishUsage(st.msg, st.req.model, st.usage);
314292 st.msg.raw_stop_reason = st.finish_reason;
315- mapStopReason(st, has_calls);
293+ if (has_calls) {
294+ st.msg.stop_reason = .tool_use;
295+ } else if (!api.stopReason(st.msg, st.finish_reason)) {
296+ st.msg.stop_reason = .stop;
297+ }
316298 }
317299
318300 const wire = api.Wire{
src/api/openai_responses.zig+1−2
@@ -78,12 +78,11 @@ fn buildBody(req: api.Request) ![]u8 {
7878 (if (req.model.max_tokens > 16) req.model.max_tokens else 16)
7979 else
8080 null;
81- const effort = if (req.effort.len > 0 and !std.mem.eql(u8, req.effort, "off")) req.effort else null;
8281 const body = Body{
8382 .model = req.model.id,
8483 .instructions = if (req.system_prompt.len > 0) req.system_prompt else null,
8584 .max_output_tokens = max_tokens,
86- .reasoning = if (effort) |e| .{ .effort = e } else null,
85+ .reasoning = if (api.effortOn(req)) |e| .{ .effort = e } else null,
8786 .input = try buildInput(a, req),
8887 .tools = if (req.tools_json.len > 0) .{ .a = a, .json = req.tools_json, .form = .{
8988 .open = "[",
src/headless.zig+2−7
@@ -48,13 +48,8 @@ pub fn run(a: std.mem.Allocator, prompt_text: []const u8, opts: agent.Options) u
4848 return 1;
4949 };
5050
51- const act = std.posix.Sigaction{
52- .handler = .{ .handler = onSignal },
53- .mask = std.posix.sigemptyset(),
54- .flags = 0,
55- };
56- std.posix.sigaction(std.posix.SIG.INT, &act, null);
57- std.posix.sigaction(std.posix.SIG.TERM, &act, null);
51+ platform.onSignal(.INT, onSignal);
52+ platform.onSignal(.TERM, onSignal);
5853
5954 var pc = PrintCtx{};
6055 var o = opts;
src/http.zig+72−59
@@ -40,6 +40,63 @@ const CancelWatch = struct {
4040 }
4141 };
4242
43+/// One request and its response, with the buffers the response reader borrows.
44+/// The parts point at each other, so an exchange is always opened in place.
45+const Exchange = struct {
46+ a: std.mem.Allocator,
47+ client: std.http.Client,
48+ hdrs: std.ArrayList(std.http.Header) = .empty,
49+ req: std.http.Client.Request,
50+ response: std.http.Client.Response,
51+ status: u16 = 0,
52+ transfer: [16 * 1024]u8 = undefined,
53+ decompress: std.http.Decompress = undefined,
54+ decompress_buf: [std.compress.flate.max_window_len]u8 = undefined,
55+ reader: *std.Io.Reader = undefined,
56+
57+ /// Connects and sends, leaving the response to `receive`.
58+ fn open(self: *Exchange, a: std.mem.Allocator, method: std.http.Method, url: []const u8, headers: []const Header, body: ?[]const u8) HttpError!void {
59+ self.a = a;
60+ self.hdrs = .empty;
61+ const uri = std.Uri.parse(url) catch return error.RequestFailed;
62+ self.client = .{ .allocator = a, .io = platform.io };
63+ errdefer self.client.deinit();
64+ for (headers) |h| self.hdrs.append(a, .{ .name = h.name, .value = h.value }) catch return error.OutOfMemory;
65+ errdefer self.hdrs.deinit(a);
66+ self.req = self.client.request(method, uri, .{
67+ .redirect_behavior = .unhandled,
68+ .extra_headers = self.hdrs.items,
69+ .headers = .{ .user_agent = .{ .override = user_agent } },
70+ }) catch return error.RequestFailed;
71+ errdefer self.req.deinit();
72+ if (body) |b| {
73+ self.req.transfer_encoding = .{ .content_length = b.len };
74+ var bw = self.req.sendBodyUnflushed(&.{}) catch return error.RequestFailed;
75+ bw.writer.writeAll(b) catch return error.RequestFailed;
76+ bw.end() catch return error.RequestFailed;
77+ self.req.connection.?.flush() catch return error.RequestFailed;
78+ } else {
79+ self.req.sendBodiless() catch return error.RequestFailed;
80+ }
81+ }
82+
83+ fn receive(self: *Exchange) HttpError!void {
84+ self.response = self.req.receiveHead(&.{}) catch return error.RequestFailed;
85+ self.status = @backingInt(self.response.head.status);
86+ self.reader = self.response.readerDecompressing(&self.transfer, &self.decompress, &self.decompress_buf);
87+ }
88+
89+ fn ok(self: *Exchange) bool {
90+ return self.status >= 200 and self.status < 300;
91+ }
92+
93+ fn close(self: *Exchange) void {
94+ self.req.deinit();
95+ self.hdrs.deinit(self.a);
96+ self.client.deinit();
97+ }
98+};
99+
43100 pub fn get(
44101 a: std.mem.Allocator,
45102 url: []const u8,
@@ -47,32 +104,12 @@ pub fn get(
47104 cancel: *const std.atomic.Value(bool),
48105 ) HttpError![]u8 {
49106 if (cancel.load(.acquire)) return error.Aborted;
50- const uri = std.Uri.parse(url) catch return error.RequestFailed;
51- var client: std.http.Client = .{ .allocator = a, .io = platform.io };
52- defer client.deinit();
53-
54- var hdrs: std.ArrayList(std.http.Header) = .empty;
55- defer hdrs.deinit(a);
56- for (headers) |h| hdrs.append(a, .{ .name = h.name, .value = h.value }) catch return error.OutOfMemory;
57-
58- var req = client.request(.GET, uri, .{
59- .redirect_behavior = .unhandled,
60- .extra_headers = hdrs.items,
61- .headers = .{ .user_agent = .{ .override = user_agent } },
62- }) catch return error.RequestFailed;
63- defer req.deinit();
64-
65- req.sendBodiless() catch return error.RequestFailed;
66- var response = req.receiveHead(&.{}) catch return error.RequestFailed;
67- const status = @backingInt(response.head.status);
68-
69- var transfer: [16 * 1024]u8 = undefined;
70- var decompress: std.http.Decompress = undefined;
71- var decompress_buf: [std.compress.flate.max_window_len]u8 = undefined;
72- const reader = response.readerDecompressing(&transfer, &decompress, &decompress_buf);
73-
74- if (status < 200 or status >= 300) return error.HttpStatus;
75- return reader.allocRemaining(a, .limited(1 << 22)) catch return error.ReadFailed;
107+ var ex: Exchange = undefined;
108+ try ex.open(a, .GET, url, headers, null);
109+ defer ex.close();
110+ try ex.receive();
111+ if (!ex.ok()) return error.HttpStatus;
112+ return ex.reader.allocRemaining(a, .limited(1 << 22)) catch return error.ReadFailed;
76113 }
77114
78115 pub fn postSse(
@@ -85,44 +122,20 @@ pub fn postSse(
85122 err_body: *?[]const u8,
86123 ) HttpError!void {
87124 if (cancel.load(.acquire)) return error.Aborted;
88- const uri = std.Uri.parse(url) catch return error.RequestFailed;
89- var client: std.http.Client = .{ .allocator = a, .io = platform.io };
90- defer client.deinit();
91-
92- var hdrs: std.ArrayList(std.http.Header) = .empty;
93- defer hdrs.deinit(a);
94- for (headers) |h| hdrs.append(a, .{ .name = h.name, .value = h.value }) catch return error.OutOfMemory;
95-
96- var req = client.request(.POST, uri, .{
97- .redirect_behavior = .unhandled,
98- .extra_headers = hdrs.items,
99- .headers = .{ .user_agent = .{ .override = user_agent } },
100- }) catch return error.RequestFailed;
101- defer req.deinit();
102-
103- req.transfer_encoding = .{ .content_length = body.len };
104- var bw = req.sendBodyUnflushed(&.{}) catch return error.RequestFailed;
105- bw.writer.writeAll(body) catch return error.RequestFailed;
106- bw.end() catch return error.RequestFailed;
107- req.connection.?.flush() catch return error.RequestFailed;
108-
109- var watch = CancelWatch{ .cancel = cancel, .connection = req.connection.? };
125+ var ex: Exchange = undefined;
126+ try ex.open(a, .POST, url, headers, body);
127+ defer ex.close();
128+
129+ var watch = CancelWatch{ .cancel = cancel, .connection = ex.req.connection.? };
110130 const watcher = std.Thread.spawn(.{}, CancelWatch.run, .{&watch}) catch null;
111131 defer {
112132 watch.done.store(true, .release);
113133 if (watcher) |t| t.join();
114134 }
115135
116- var response = req.receiveHead(&.{}) catch return error.RequestFailed;
117- const status = @backingInt(response.head.status);
118-
119- var transfer: [16 * 1024]u8 = undefined;
120- var decompress: std.http.Decompress = undefined;
121- var decompress_buf: [std.compress.flate.max_window_len]u8 = undefined;
122- const reader = response.readerDecompressing(&transfer, &decompress, &decompress_buf);
123-
124- if (status < 200 or status >= 300) {
125- err_body.* = reader.allocRemaining(a, .limited(1 << 20)) catch null;
136+ try ex.receive();
137+ if (!ex.ok()) {
138+ err_body.* = ex.reader.allocRemaining(a, .limited(1 << 20)) catch null;
126139 return error.HttpStatus;
127140 }
128141
@@ -139,7 +152,7 @@ pub fn postSse(
139152 // desynchronizes chunked transfer decoding.
140153 while (true) {
141154 if (cancel.load(.acquire)) return error.Aborted;
142- const n = reader.readSliceShort(&buf) catch return error.ReadFailed;
155+ const n = ex.reader.readSliceShort(&buf) catch return error.ReadFailed;
143156 if (n == 0) break;
144157 var rest: []const u8 = buf[0..n];
145158 while (std.mem.indexOfScalar(u8, rest, '\n')) |nl| {
src/models.zig+0−3
@@ -8,7 +8,6 @@ pub const Thinking = enum { off, budget, effort };
88
99 pub const Model = struct {
1010 id: []const u8,
11- name: []const u8,
1211 api: []const u8,
1312 provider: []const u8,
1413 base_url: []const u8,
@@ -128,7 +127,6 @@ pub fn resolveNamed(a: std.mem.Allocator, cfg: *const config.Config, provider_id
128127 };
129128 return Model{
130129 .id = model_id,
131- .name = info.name,
132130 .api = info.api,
133131 .provider = provider_id,
134132 .base_url = info.base_url,
@@ -150,7 +148,6 @@ pub fn resolveNamed(a: std.mem.Allocator, cfg: *const config.Config, provider_id
150148 if (!std.mem.eql(u8, m.id, model_id)) continue;
151149 return Model{
152150 .id = m.id,
153- .name = m.name orelse m.id,
154151 .api = @tagName(m.api),
155152 .provider = provider_id,
156153 .base_url = m.baseUrl,
src/platform.zig+9−0
@@ -50,6 +50,15 @@ pub fn reRaise(sig: std.posix.SIG) noreturn {
5050 std.process.exit(1);
5151 }
5252
53+pub fn onSignal(sig: std.posix.SIG, handler: *const fn (std.posix.SIG) callconv(.c) void) void {
54+ const act = std.posix.Sigaction{
55+ .handler = .{ .handler = handler },
56+ .mask = std.posix.sigemptyset(),
57+ .flags = 0,
58+ };
59+ std.posix.sigaction(sig, &act, null);
60+}
61+
5362 pub fn writeOut(bytes: []const u8) void {
5463 std.Io.File.stdout().writeStreamingAll(io, bytes) catch {};
5564 }
src/prompt.zig+9−13
@@ -2,15 +2,16 @@ const std = @import("std");
22 const platform = @import("platform.zig");
33 const filesystem = @import("filesystem.zig");
44 const config = @import("config.zig");
5+const text = @import("text.zig");
56
67 const Skill = struct { name: []const u8, description: []const u8, path: []const u8 };
78
89 const Frontmatter = struct { name: ?[]const u8 = null, description: ?[]const u8 = null };
910
10-fn frontmatter(text: []const u8) Frontmatter {
11+fn frontmatter(raw: []const u8) Frontmatter {
1112 var out = Frontmatter{};
12- if (!std.mem.startsWith(u8, text, "---")) return out;
13- const rest = text[3..];
13+ if (!std.mem.startsWith(u8, raw, "---")) return out;
14+ const rest = raw[3..];
1415 const end = std.mem.indexOf(u8, rest, "\n---") orelse return out;
1516 var lines = std.mem.splitScalar(u8, rest[0..end], '\n');
1617 while (lines.next()) |line| {
@@ -30,8 +31,8 @@ fn discoverSkills(a: std.mem.Allocator, dirs: []const []const u8) ![]Skill {
3031 for (filesystem.listDir(a, root) catch continue) |entry| {
3132 const path = filesystem.join(a, &.{ root, entry, "SKILL.md" }) catch continue;
3233 if (!filesystem.fileExists(path)) continue;
33- const text = filesystem.readFileAlloc(a, path, 1 << 20) catch continue;
34- const meta = frontmatter(text);
34+ const content = filesystem.readFileAlloc(a, path, 1 << 20) catch continue;
35+ const meta = frontmatter(content);
3536 const name = meta.name orelse continue;
3637 try skills.append(a, .{
3738 .name = name,
@@ -99,18 +100,13 @@ pub fn buildSystemPrompt(a: std.mem.Allocator, cfg: *const config.Config) !Built
99100 const files = try agentFiles(a);
100101 loaded.agent_files = files.len;
101102 for (files) |path| {
102- const text = try filesystem.readFileAlloc(a, path, 1 << 24);
103+ const content = try filesystem.readFileAlloc(a, path, 1 << 24);
103104 try sections.append(a, try std.fmt.allocPrint(a, "## {s}\n\n{s}", .{
104105 path,
105- std.mem.trim(u8, text, " \t\r\n"),
106+ std.mem.trim(u8, content, " \t\r\n"),
106107 }));
107108 }
108109 }
109110
110- var joined: std.ArrayList(u8) = .empty;
111- for (sections.items, 0..) |section, i| {
112- if (i > 0) try joined.appendSlice(a, "\n\n");
113- try joined.appendSlice(a, section);
114- }
115- return .{ .prompt = joined.items, .loaded = loaded };
111+ return .{ .prompt = try text.join(a, sections.items, "\n\n"), .loaded = loaded };
116112 }
src/session.zig+5−18
@@ -203,12 +203,14 @@ pub const Session = struct {
203203 }
204204
205205 fn commitLine(self: *Session, scratch: std.mem.Allocator, line: []const u8) !void {
206+ const f = self.file orelse return error.SessionNotOpen;
206207 var out: std.Io.Writer.Allocating = .init(scratch);
207208 defer out.deinit();
208209 const w = &out.writer;
209210 try w.writeAll(line);
210211 try w.writeByte('\n');
211- try self.commit(out.written());
212+ try f.writeStreamingAll(platform.io, out.written());
213+ try f.sync(platform.io);
212214 }
213215
214216 pub fn close(self: *Session) void {
@@ -239,39 +241,24 @@ pub const Session = struct {
239241 const file = try std.Io.Dir.cwd().createFile(platform.io, log_path, .{ .truncate = false, .permissions = .fromMode(0o600) });
240242 self.id = name;
241243 self.file = file;
242- var header_buf: std.Io.Writer.Allocating = .init(self.a);
243- defer header_buf.deinit();
244- const w = &header_buf.writer;
245- try w.writeAll(try stringify(self.a, HeaderLine{
244+ try self.commitLine(self.a, try stringify(self.a, HeaderLine{
246245 .id = name,
247246 .cwd = self.cwd,
248247 .createdAt = time.isoAlloc(self.a),
249248 .title = title,
250249 }));
251- try w.writeByte('\n');
252- try self.commit(header_buf.written());
253250 return;
254251 }
255252 return error.SessionDirectory;
256253 }
257254
258- fn commit(self: *Session, line: []const u8) !void {
259- const f = self.file orelse return error.SessionNotOpen;
260- try f.writeStreamingAll(platform.io, line);
261- try f.sync(platform.io);
262- }
263-
264255 fn shortId(buf: *[6]u8) void {
265256 var bytes: [6]u8 = undefined;
266- randomBytes(&bytes);
257+ std.Io.random(platform.io, &bytes);
267258 for (bytes, 0..) |b, i| buf[i] = alphabet[b % 36];
268259 }
269260 };
270261
271-fn randomBytes(buf: []u8) void {
272- std.Io.random(platform.io, buf);
273-}
274-
275262 fn messageRecord(a: std.mem.Allocator, message: message_mod.Message) !MessageRecord {
276263 switch (message) {
277264 .user => |u| return .{ .user = .{ .content = u.content, .timestamp = u.timestamp } },
src/text.zig+9−0
@@ -6,6 +6,15 @@ pub fn isBinary(bytes: []const u8) bool {
66 return std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, binary_sniff)], 0) != null;
77 }
88
9+pub fn join(a: std.mem.Allocator, parts: []const []const u8, sep: []const u8) ![]const u8 {
10+ var out: std.ArrayList(u8) = .empty;
11+ for (parts, 0..) |part, i| {
12+ if (i > 0) try out.appendSlice(a, sep);
13+ try out.appendSlice(a, part);
14+ }
15+ return out.items;
16+}
17+
918 fn utf8SeqLen(p: []const u8) ?usize {
1019 if (p.len == 0) return null;
1120 const c = p[0];
src/tools/edit.zig+2−9
@@ -1,7 +1,6 @@
11 const std = @import("std");
22 const filesystem = @import("../filesystem.zig");
33 const text = @import("../text.zig");
4-const platform = @import("../platform.zig");
54 const diff = @import("../diff.zig");
65 const tools = @import("../tools.zig");
76
@@ -49,7 +48,7 @@ pub fn run(a: std.mem.Allocator, scratch: std.mem.Allocator, args_json: []const
4948 if (args.oldText.len == 0) {
5049 if (filesystem.fileExists(path)) return fail(a, "edit failed: {s} already exists", .{path});
5150 if (ctx.cancel.load(.acquire)) return fail(a, "edit cancelled", .{});
52- writeFile(path, args.newText) catch |e| return fail(a, "edit failed: {s}: {s}", .{ path, @errorName(e) });
51+ filesystem.writeFile(path, args.newText) catch |e| return fail(a, "edit failed: {s}: {s}", .{ path, @errorName(e) });
5352 const cleaned = text.utf8Clean(scratch, args.newText) catch return fail(a, "edit failed: out of memory", .{});
5453 const patch = diff.unified(scratch, "", cleaned) catch return fail(a, "edit failed: out of memory", .{});
5554 return .{
@@ -74,7 +73,7 @@ pub fn run(a: std.mem.Allocator, scratch: std.mem.Allocator, args_json: []const
7473 const after = std.mem.concat(scratch, u8, &.{ before[0..at], args.newText, before[at + args.oldText.len ..] }) catch
7574 return fail(a, "edit failed: out of memory", .{});
7675 if (ctx.cancel.load(.acquire)) return fail(a, "edit cancelled", .{});
77- writeFile(path, after) catch |e| return fail(a, "edit failed: {s}: {s}", .{ path, @errorName(e) });
76+ filesystem.writeFile(path, after) catch |e| return fail(a, "edit failed: {s}: {s}", .{ path, @errorName(e) });
7877 const clean_before = text.utf8Clean(scratch, before) catch return fail(a, "edit failed: out of memory", .{});
7978 const clean_after = text.utf8Clean(scratch, after) catch return fail(a, "edit failed: out of memory", .{});
8079 const patch = diff.unified(scratch, clean_before, clean_after) catch return fail(a, "edit failed: out of memory", .{});
@@ -83,9 +82,3 @@ pub fn run(a: std.mem.Allocator, scratch: std.mem.Allocator, args_json: []const
8382 .is_error = false,
8483 };
8584 }
86-
87-fn writeFile(path: []const u8, data: []const u8) !void {
88- const file = try std.Io.Dir.cwd().createFile(platform.io, path, .{ .truncate = true });
89- defer file.close(platform.io);
90- try file.writeStreamingAll(platform.io, data);
91-}
src/tui/complete.zig+1−1
@@ -27,7 +27,7 @@ pub fn completePath(word: []const u8) ?[]const u8 {
2727
2828 var dir: []const u8 = undefined;
2929 if (word[0] == '~') {
30- const home = platform.getEnv("HOME") orelse "/";
30+ const home = platform.home() orelse "/";
3131 const tail = if (slash) |s| word[1..s] else word[1..];
3232 dir = std.fs.path.resolve(a, &.{ home, tail }) catch return null;
3333 } else if (slash != null and slash.? == 0) {
src/tui/editor.zig+1−3
@@ -4,8 +4,6 @@ const input = @import("input.zig");
44
55 const TAB = 4;
66
7-const physicalRows = render.physicalRows;
8-
97 fn isSpace(cp: u21) bool {
108 return cp == ' ' or cp == '\t' or cp == '\n' or cp == '\r' or cp == 0x0b or cp == 0x0c or cp == 0xa0;
119 }
@@ -249,7 +247,7 @@ pub const Editor = struct {
249247 var caret_line: usize = 0;
250248 var caret_cell: usize = 0;
251249 for (self.lines.items, 0..) |line, i| {
252- heights[i] = physicalRows(render.expandTabs(self.s, line.items, TAB), self.width);
250+ heights[i] = render.physicalRows(render.expandTabs(self.s, line.items, TAB), self.width);
253251 if (i == self.row) {
254252 caret_line = i;
255253 caret_cell = self.cells(line.items)[self.col];
src/tui/picker.zig+69−0
@@ -0,0 +1,69 @@
1+const std = @import("std");
2+const input = @import("input.zig");
3+
4+pub const Kind = enum { provider, model, thinking, history };
5+
6+/// What one key did.
7+pub const Action = enum { ignore, update, accept, cancel };
8+
9+/// A filtered choice list. It owns its query and match index only; the choices
10+/// themselves belong to whoever opened it.
11+pub const Picker = struct {
12+ kind: Kind,
13+ title: []const u8,
14+ ids: []const []const u8 = &.{},
15+ labels: []const []const u8 = &.{},
16+ provider: []const u8 = "",
17+ draft: []const u8 = "",
18+ query: std.ArrayList(u8) = .empty,
19+ matches: std.ArrayList(usize) = .empty,
20+ sel: usize = 0,
21+
22+ pub fn refresh(self: *Picker, a: std.mem.Allocator) void {
23+ self.matches.clearRetainingCapacity();
24+ const query = self.query.items;
25+ const n = @min(self.ids.len, self.labels.len);
26+ for (self.ids[0..n], self.labels[0..n], 0..) |id, label, i| {
27+ if (query.len != 0 and std.ascii.findIgnoreCase(label, query) == null and
28+ std.ascii.findIgnoreCase(id, query) == null) continue;
29+ self.matches.append(a, i) catch {};
30+ }
31+ self.sel = if (self.matches.items.len == 0) 0 else @min(self.sel, self.matches.items.len - 1);
32+ }
33+
34+ pub fn key(self: *Picker, a: std.mem.Allocator, k: input.Key) Action {
35+ switch (k) {
36+ .text => |t| {
37+ self.query.appendSlice(a, t) catch {};
38+ self.sel = 0;
39+ self.refresh(a);
40+ },
41+ .backspace => {
42+ if (self.query.items.len == 0) return .ignore;
43+ var start = self.query.items.len - 1;
44+ while (start > 0 and (self.query.items[start] & 0xc0) == 0x80) start -= 1;
45+ self.query.shrinkRetainingCapacity(start);
46+ self.sel = 0;
47+ self.refresh(a);
48+ },
49+ .up, .history_prev => {
50+ if (self.sel == 0) return .ignore;
51+ self.sel -= 1;
52+ },
53+ .down, .history_next => {
54+ if (self.sel + 1 >= self.matches.items.len) return .ignore;
55+ self.sel += 1;
56+ },
57+ .submit => return .accept,
58+ .escape, .interrupt => return .cancel,
59+ else => return .ignore,
60+ }
61+ return .update;
62+ }
63+
64+ /// The id under the cursor, or null when nothing matches.
65+ pub fn current(self: *const Picker) ?[]const u8 {
66+ if (self.matches.items.len == 0) return null;
67+ return self.ids[self.matches.items[self.sel]];
68+ }
69+};
src/tui/screen.zig+2−4
@@ -3,8 +3,6 @@ const styles = @import("styles.zig");
33 const platform = @import("../platform.zig");
44 const render = @import("render.zig");
55
6-const rowsForCells = render.rowsForCells;
7-
86 pub const LiveRegion = struct {
97 widths: std.ArrayList(usize) = .empty,
108 caret_line: usize = 0,
@@ -28,13 +26,13 @@ pub const LiveRegion = struct {
2826 fn caretRow(self: *LiveRegion, width: usize) usize {
2927 var row: usize = 0;
3028 const lines = @min(self.caret_line, self.widths.items.len);
31- for (self.widths.items[0..lines]) |cells| row += rowsForCells(cells, width);
29+ for (self.widths.items[0..lines]) |cells| row += render.rowsForCells(cells, width);
3230 return row + self.caretCell(width) / width;
3331 }
3432
3533 fn totalRows(self: *LiveRegion, width: usize) usize {
3634 var row: usize = 0;
37- for (self.widths.items) |cells| row += rowsForCells(cells, width);
35+ for (self.widths.items) |cells| row += render.rowsForCells(cells, width);
3836 return row;
3937 }
4038
src/tui/stream.zig+10−18
@@ -1,6 +1,7 @@
11 const std = @import("std");
22 const highlight = @import("highlight.zig");
33 const render = @import("render.zig");
4+const text = @import("../text.zig");
45
56 const BodyLine = render.BodyLine;
67
@@ -90,13 +91,8 @@ pub const MarkdownStream = struct {
9091 self.prose = .empty;
9192 if (tail.len > 0) prose.append(self.a, tail) catch {};
9293 if (prose.items.len == 0) return;
93- var joined: std.ArrayList(u8) = .empty;
94- for (prose.items, 0..) |l, i| {
95- if (i > 0) joined.append(out_a, '\n') catch {};
96- joined.appendSlice(out_a, l) catch {};
97- }
98- joined.append(out_a, '\n') catch {};
99- emitHighlighted(out_a, highlight.highlightMarkdown(out_a, highlight.formatTables(out_a, joined.items)), out);
94+ const joined = std.fmt.allocPrint(out_a, "{s}\n", .{text.join(out_a, prose.items, "\n") catch ""}) catch "";
95+ emitHighlighted(out_a, highlight.highlightMarkdown(out_a, highlight.formatTables(out_a, joined)), out);
10096 }
10197
10298 fn releaseFence(self: *MarkdownStream, out_a: std.mem.Allocator, closing: ?[]const u8, out: *std.ArrayList(BodyLine)) void {
@@ -104,12 +100,8 @@ pub const MarkdownStream = struct {
104100 self.fence = null;
105101 out.append(out_a, .{ .text = highlight.highlightMarkdown(out_a, f.lines.items[0]) }) catch {};
106102 if (f.lines.items.len > 1) {
107- var body: std.ArrayList(u8) = .empty;
108- for (f.lines.items[1..], 0..) |l, i| {
109- if (i > 0) body.append(out_a, '\n') catch {};
110- body.appendSlice(out_a, l) catch {};
111- }
112- var it = std.mem.splitScalar(u8, highlight.highlightCode(out_a, body.items), '\n');
103+ const body = text.join(out_a, f.lines.items[1..], "\n") catch "";
104+ var it = std.mem.splitScalar(u8, highlight.highlightCode(out_a, body), '\n');
113105 while (it.next()) |l| out.append(out_a, .{ .text = l }) catch {};
114106 }
115107 if (closing) |c| out.append(out_a, .{ .text = highlight.highlightMarkdown(out_a, c) }) catch {};
@@ -144,14 +136,14 @@ pub const MarkdownStream = struct {
144136 }
145137 };
146138
147-fn emitHighlighted(a: std.mem.Allocator, text: []const u8, out: *std.ArrayList(BodyLine)) void {
148- const nl = std.mem.lastIndexOfScalar(u8, text, '\n') orelse {
149- out.append(a, .{ .text = text }) catch {};
139+fn emitHighlighted(a: std.mem.Allocator, source: []const u8, out: *std.ArrayList(BodyLine)) void {
140+ const nl = std.mem.lastIndexOfScalar(u8, source, '\n') orelse {
141+ out.append(a, .{ .text = source }) catch {};
150142 return;
151143 };
152- const reset = text[nl + 1 ..];
144+ const reset = source[nl + 1 ..];
153145 var lines: std.ArrayList([]const u8) = .empty;
154- var it = std.mem.splitScalar(u8, text[0..nl], '\n');
146+ var it = std.mem.splitScalar(u8, source[0..nl], '\n');
155147 while (it.next()) |l| lines.append(a, l) catch {};
156148 if (lines.items.len > 0) {
157149 const last = lines.items.len - 1;
src/tui/tui.zig+29−89
@@ -19,6 +19,7 @@ const usage_mod = @import("usage.zig");
1919 const diff_view = @import("diff_view.zig");
2020 const tool_view = @import("tool_view.zig");
2121 const image_view = @import("image.zig");
22+const picker_mod = @import("picker.zig");
2223 const screen = @import("screen.zig");
2324 const history = @import("../history.zig");
2425 const status = @import("../status.zig");
@@ -29,25 +30,11 @@ const BODY_PREFIX = " │ ";
2930 const ERROR_PREFIX = " ! ";
3031 const TOOL_BODY: styles.Style = .{ .dim = true };
3132
32-const physicalRows = render.physicalRows;
33-const rowsForCells = render.rowsForCells;
34-
3533 const PendingCall = tool_view.PendingCall;
34+const Picker = picker_mod.Picker;
3635
3736 const Command = commands.Command;
3837
39-const Picker = struct {
40- kind: enum { provider, model, thinking, history },
41- title: []const u8,
42- ids: []const []const u8 = &.{},
43- labels: []const []const u8 = &.{},
44- provider: []const u8 = "",
45- draft: []const u8 = "",
46- query: std.ArrayList(u8) = .empty,
47- matches: std.ArrayList(usize) = .empty,
48- sel: usize = 0,
49-};
50-
5138 var resize_flag = std.atomic.Value(bool).init(false);
5239 var exit_flag = std.atomic.Value(bool).init(false);
5340 var exit_signal = std.atomic.Value(u32).init(0);
@@ -343,7 +330,7 @@ const Tui = struct {
343330 const width = @max(self.term.width(), 1);
344331 const height = @max(self.term.height() - 1, 1);
345332 const status_line = self.statusLine();
346- const status_rows = physicalRows(status_line, width);
333+ const status_rows = render.physicalRows(status_line, width);
347334 const editor_budget = height -| status_rows;
348335 const ed = self.editor.layout(width, @max(editor_budget, 1));
349336
@@ -491,26 +478,26 @@ const Tui = struct {
491478 }
492479 }
493480
494- fn renderPendingCall(self: *Tui) void {
495- if (self.pending_calls.items.len == 0) return;
496- const call = &self.pending_calls.items[0];
481+ fn renderCall(self: *Tui, call: *PendingCall) void {
497482 if (call.rendered) return;
498483 self.scrollback.separator = true;
499484 for (tool_view.callBody(self.s, call.name, call.summary, @max(self.term.width(), 1))) |row| self.push(row);
500485 call.rendered = true;
501486 }
502487
488+ fn renderPendingCall(self: *Tui) void {
489+ if (self.pending_calls.items.len == 0) return;
490+ self.renderCall(&self.pending_calls.items[0]);
491+ }
492+
503493 fn commitToolResult(self: *Tui, name: []const u8, text: []const u8, is_error: bool, diffs: []const tools_index.FileDiff, body: ?[]const u8, images: []const message_mod.ImageContent) void {
504494 const shown = render.stripAnsi(self.s, text);
505495 const meta: ?[]const u8 = if (!is_error) body else null;
506496 var head_committed = false;
507497 if (self.pending_calls.items.len > 0) {
508- const call = self.pending_calls.orderedRemove(0);
498+ var call = self.pending_calls.orderedRemove(0);
509499 head_committed = true;
510- if (!call.rendered) {
511- self.scrollback.separator = true;
512- for (tool_view.callBody(self.s, call.name, call.summary, @max(self.term.width(), 1))) |row| self.push(row);
513- }
500+ self.renderCall(&call);
514501 }
515502 if (!head_committed) self.scrollback.separator = true;
516503 if (self.cfg.show_images) self.commitImages(images);
@@ -557,12 +544,12 @@ const Tui = struct {
557544 }
558545
559546 fn flushCalls(self: *Tui) void {
560- for (self.pending_calls.items) |call| {
561- if (call.rendered) continue;
562- self.scrollback.separator = true;
563- for (tool_view.callBody(self.s, call.name, call.summary, @max(self.term.width(), 1))) |row| self.push(row);
564- }
547+ for (self.pending_calls.items) |*call| self.renderCall(call);
565548 self.pending_calls.clearRetainingCapacity();
549+ self.resetCalls();
550+ }
551+
552+ fn resetCalls(self: *Tui) void {
566553 _ = self.calls.reset(.retain_capacity);
567554 self.ca = self.calls.allocator();
568555 }
@@ -609,7 +596,7 @@ const Tui = struct {
609596 p.labels = labels;
610597 p.draft = self.picker_m.dupe(u8, self.editor.contents()) catch "";
611598 self.editor.clear();
612- self.pickerRefresh();
599+ p.refresh(self.picker_m);
613600 self.dirty = true;
614601 }
615602
@@ -812,8 +799,7 @@ const Tui = struct {
812799 self.retry = false;
813800 self.phase = .idle;
814801 self.stream_kind = .none;
815- _ = self.calls.reset(.retain_capacity);
816- self.ca = self.calls.allocator();
802+ self.resetCalls();
817803 self.dirty = true;
818804 }
819805
@@ -881,17 +867,17 @@ const Tui = struct {
881867 if (self.picker) |*p| p.provider = self.model_provider;
882868 }
883869
884- fn openPicker(self: *Tui, kind: @FieldType(Picker, "kind"), title: []const u8, ids: []const []const u8, labels: []const []const u8) void {
870+ fn openPicker(self: *Tui, kind: picker_mod.Kind, title: []const u8, ids: []const []const u8, labels: []const []const u8) void {
885871 self.startPicker(kind, title);
886872 if (self.picker) |*p| {
887873 p.ids = ids;
888874 p.labels = labels;
875+ p.refresh(self.picker_m);
889876 }
890- self.pickerRefresh();
891877 self.dirty = true;
892878 }
893879
894- fn startPicker(self: *Tui, kind: @FieldType(Picker, "kind"), title: []const u8) void {
880+ fn startPicker(self: *Tui, kind: picker_mod.Kind, title: []const u8) void {
895881 _ = self.picker_arena.reset(.retain_capacity);
896882 self.picker_m = self.picker_arena.allocator();
897883 self.picker = .{ .kind = kind, .title = title };
@@ -902,59 +888,26 @@ const Tui = struct {
902888 self.picker = null;
903889 }
904890
905- fn pickerRefresh(self: *Tui) void {
906- const p = &(self.picker orelse return);
907- p.matches.clearRetainingCapacity();
908- const query = p.query.items;
909- const n = @min(p.ids.len, p.labels.len);
910- for (p.ids[0..n], p.labels[0..n], 0..) |id, label, i| {
911- if (query.len != 0 and std.ascii.findIgnoreCase(label, query) == null and
912- std.ascii.findIgnoreCase(id, query) == null) continue;
913- p.matches.append(self.picker_m, i) catch {};
914- }
915- p.sel = if (p.matches.items.len == 0) 0 else @min(p.sel, p.matches.items.len - 1);
916- }
917-
918891 fn pickerKey(self: *Tui, key: input.Key) void {
919892 const p = &(self.picker orelse return);
920- switch (key) {
921- .text => |t| {
922- p.query.appendSlice(self.picker_m, t) catch {};
923- p.sel = 0;
924- self.pickerRefresh();
925- },
926- .backspace => {
927- if (p.query.items.len > 0) {
928- var start = p.query.items.len - 1;
929- while (start > 0 and (p.query.items[start] & 0xc0) == 0x80) start -= 1;
930- p.query.shrinkRetainingCapacity(start);
931- p.sel = 0;
932- self.pickerRefresh();
933- }
934- },
935- .up, .history_prev => if (p.sel > 0) {
936- p.sel -= 1;
937- },
938- .down, .history_next => if (p.sel + 1 < p.matches.items.len) {
939- p.sel += 1;
940- },
941- .submit => self.pickerAccept(),
942- .escape, .interrupt => {
893+ switch (p.key(self.picker_m, key)) {
894+ .ignore => return,
895+ .update => {},
896+ .accept => self.pickerAccept(),
897+ .cancel => {
943898 const draft = p.draft;
944899 const restore = p.kind == .history;
945900 self.closePicker();
946901 self.command_active = false;
947902 if (restore) self.editor.setText(draft);
948903 },
949- else => return,
950904 }
951905 self.dirty = true;
952906 }
953907
954908 fn pickerAccept(self: *Tui) void {
955909 const p = self.picker orelse return;
956- if (p.matches.items.len == 0) return;
Cut short: this commit's diff is over 1000 lines.