xonecas.io
79113
Ma

mini-coding-agent / commit d00400b

feat: initial gen

xonecas2026-10-04 d00400b97641d5111645ec5e04da2b1940dab96d parent 419db24

40 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.

.gitignore+3−0
@@ -0,0 +1,3 @@
1+.zig-cache/
2+zig-out/
3+zig-pkg/
AGENTS.md+12−20
@@ -141,26 +141,18 @@ use the models above. Run a real tool call, not just a text turn.
141141
142142 ## Driving the TUI with kitty
143143
144-There is no `tmux` here; drive the TUI through kitty's remote control on a
145-private socket, one window per session:
146-
147- kitty --detach --listen-on unix:/tmp/mz-<name>.sock \
148- -o allow_remote_control=yes -o remember_window_size=no \
149- -o initial_window_width=100c -o initial_window_height=30c \
150- --title mz-<name> env PS1='\n$ ' bash --norc --noprofile -i
151-
152-Run every `kitty @ --to unix:/tmp/mz-<name>.sock` call through that socket; the
153-window id comes from `ls`, don't assume it. Run the app (`./zig-out/bin/mza`)
154-with a scratch cwd so its tool calls write nowhere that matters.
155-
156-- `send-text` types literal text and never submits — Enter is its own key,
157- `send-key enter`, and it does nothing while a turn is active.
158-- `send-key` for named keys: `enter escape ctrl+c ctrl+d shift+enter tab`.
159-- `get-text -m id:N --extent=all --ansi` returns the pane with the app's
160- truecolor SGR — assert colors from those escapes, not from pixels;
161- `--extent=screen` is the live screen alone.
162-- `screenshot -m id:N out.png` for the visual check; `identify` it and look at
163- it before trusting it.
144+There is no `tmux` here. `tools/stress.sh` drives the TUI in a real kitty
145+window over remote control on a private socket, one window per run: it launches
146+the app in a scratch cwd, waits for the banner, types the prompt, and
147+screenshots the window at 15fps until the capture window ends or the app exits.
148+
149+ tools/stress.sh -C <scratch cwd> -o /tmp/mz-runs/<name> -d 300 -p '<prompt>'
150+
151+Frames land in `frame-NNNNN.png`. At the end of a run the pane is written with
152+its truecolor SGR to `final.txt` (scrollback) and `final-screen.txt` (live
153+screen). The last line reports frames, wall time, and achieved fps; an
154+`ended early: MZA-EXIT <n>` line means the app died, and `final.txt` holds the
155+dump. Read the pane text and the frames, not pixels.
164156
165157 ## Working agreement
166158
build.zig+51−0
@@ -0,0 +1,51 @@
1+const std = @import("std");
2+
3+pub fn build(b: *std.Build) void {
4+ const target = b.standardTargetOptions(.{});
5+ const optimize = b.standardOptimizeOption(.{});
6+
7+ const exe = b.addExecutable(.{
8+ .name = "mza",
9+ .root_module = b.createModule(.{
10+ .root_source_file = b.path("src/main.zig"),
11+ .target = target,
12+ .optimize = optimize,
13+ }),
14+ });
15+ b.installArtifact(exe);
16+
17+ const tree_sitter = b.dependency("tree_sitter", .{ .target = target, .optimize = optimize });
18+ exe.root_module.addImport("tree-sitter", tree_sitter.module("tree_sitter"));
19+
20+ const js = b.dependency("tree_sitter_javascript", .{ .target = target, .optimize = optimize });
21+ const ts = b.dependency("tree_sitter_typescript", .{ .target = target, .optimize = optimize });
22+ const md = b.dependency("tree_sitter_markdown", .{ .target = target, .optimize = optimize });
23+
24+ exe.root_module.link_libc = true;
25+ addGrammar(exe, js, "src", &.{ "parser.c", "scanner.c" });
26+ addGrammar(exe, ts, "typescript/src", &.{ "parser.c", "scanner.c" });
27+ addGrammar(exe, ts, "tsx/src", &.{ "parser.c", "scanner.c" });
28+ addGrammar(exe, md, "tree-sitter-markdown/src", &.{ "parser.c", "scanner.c" });
29+ addGrammar(exe, md, "tree-sitter-markdown-inline/src", &.{ "parser.c", "scanner.c" });
30+
31+ exe.root_module.addAnonymousImport("js_highlights", .{ .root_source_file = js.path("queries/highlights.scm") });
32+ exe.root_module.addAnonymousImport("ts_highlights", .{ .root_source_file = ts.path("queries/highlights.scm") });
33+ exe.root_module.addAnonymousImport("md_highlights", .{ .root_source_file = md.path("tree-sitter-markdown/queries/highlights.scm") });
34+ exe.root_module.addAnonymousImport("md_inline_highlights", .{ .root_source_file = md.path("tree-sitter-markdown-inline/queries/highlights.scm") });
35+
36+ const run_cmd = b.addRunArtifact(exe);
37+ run_cmd.step.dependOn(b.getInstallStep());
38+ if (b.args) |args| run_cmd.addArgs(args);
39+ const run_step = b.step("run", "Run mza");
40+ run_step.dependOn(&run_cmd.step);
41+}
42+
43+fn addGrammar(exe: *std.Build.Step.Compile, dep: *std.Build.Dependency, dir: []const u8, files: []const []const u8) void {
44+ const root = dep.path(dir);
45+ exe.root_module.addIncludePath(root);
46+ exe.root_module.addCSourceFiles(.{
47+ .root = root,
48+ .files = files,
49+ .flags = &.{"-std=c11"},
50+ });
51+}
build.zig.zon+29−0
@@ -0,0 +1,29 @@
1+.{
2+ .name = .mza,
3+ .version = "0.1.0",
4+ .fingerprint = 0x502b41d3b0515574,
5+ .minimum_zig_version = "0.16.0",
6+ .dependencies = .{
7+ .tree_sitter = .{
8+ .url = "git+https://github.com/tree-sitter/zig-tree-sitter#b562510b5563dcf3b7fcac4a5fe9d60834c84667",
9+ .hash = "tree_sitter-0.26.0-8heIf-vDAQDh0HhAAUVwVZFmLrwSKMZl5gRaVFqtas0W",
10+ },
11+ .tree_sitter_javascript = .{
12+ .url = "git+https://github.com/tree-sitter/tree-sitter-javascript?ref=v0.25.0#44c892e0be055ac465d5eeddae6d3e194424e7de",
13+ .hash = "N-V-__8AANlfOQB4iUiSxpYjpQ5R6BBgFscc5iYIWIu-9plN",
14+ },
15+ .tree_sitter_typescript = .{
16+ .url = "git+https://github.com/tree-sitter/tree-sitter-typescript?ref=v0.23.2#f975a621f4e7f532fe322e13c4f79495e0a7b2e7",
17+ .hash = "N-V-__8AALhpIQFpocCrfuYTb_Vzvxj3QG0T-yqi9x1QNRNM",
18+ },
19+ .tree_sitter_markdown = .{
20+ .url = "git+https://github.com/tree-sitter-grammars/tree-sitter-markdown?ref=v0.3.2#1c8dea73bc0c996d92dd9ebc30dd388716b1c5db",
21+ .hash = "N-V-__8AAJvIUgBKgesFyAgIRoY2KiG9_M2zWZQ4FBvnlPmz",
22+ },
23+ },
24+ .paths = .{
25+ "build.zig",
26+ "build.zig.zon",
27+ "src",
28+ },
29+}
port-prompt.md+0−147
@@ -1,147 +0,0 @@
1-# Task: port mini-coder to Zig as `mini-z-agent`
2-
3-You are starting `mini-z-agent` (`mza`), a Zig port of `mini-coder`. Read
4-`AGENTS.md` in this directory first and follow it. It is the law. This document
5-is the work order; `AGENTS.md` governs every decision.
6-
7-## Context you need
8-
9-`mini-coder` (`../mini-coder/`) is a TypeScript terminal coding agent that works.
10-It is the behavior specification. Below it in this conversation there is a
11-history: two earlier ports of it exist.
12-
13-- `../tiny-c-agent/` — a careful C port. It translated the design faithfully and
14- is the best low-level detail reference available: the four wire protocols,
15- streaming reassembly, diff capture, UTF-8 and base64 handling, session
16- durability. It is also the cautionary tale. Moving to C meant reimplementing,
17- by hand, everything the TypeScript version got from its runtime and from
18- `pi-ai`: HTTP, JSON, an SSE parser, a diff engine, a UTF-8 validator, base64.
19- That produced 10,207 lines against the reference's 3,575, 552 `free()` calls,
20- 33 `abort()` calls, and a commit titled `fix: memory fixes`.
21-- `../zig-agent-kanso/` — an experimental, one-shot Zig port. It proves the
22- language fit: one `zig build`, four hash-pinned tree-sitter dependencies, no
23- `pkg-config` on the host, 6,745 lines, nine deinit sites, zero `abort()`.
24- `std.http.Client` replaced libcurl, `std.json` replaced a C JSON library, and
25- one startup allocator replaced the manual free bookkeeping entirely. It is
26- also incomplete and less careful than tiny: the provider layer has gaps, and it
27- silently swallows errors in several places (`catch {}` on message and session
28- appends).
29-
30-Your job is to combine them: mini's behavior, tiny's care, and kanso's Zig.
31-
32-## The goal, stated plainly
33-
34-One static binary with no runtime, no interpreter, no `node_modules`, no
35-post-install scripts, and a dependency surface only as large as the work needs.
36-Small in all aspects. This is the reason the project exists. Weigh every decision
37-against it.
38-
39-## What is fixed
40-
41-These are inherited and are not open for redesign. Port them as they are:
42-
43-- Three tools: `read`, `edit`, `bash`.
44-- The four wire protocols: `openai-completions`, `openai-responses`,
45- `anthropic-messages`, `google-generative-ai`.
46-- Append-only JSONL sessions, fsynced, one message per line, plus a request
47- record per model step. Never rewrite a committed line.
48-- The agent loop's shape: no compaction, no retries, no meta-messages. Steering
49- lands at a step boundary, never between an assistant turn and its tool results.
50-- Interruption: ESC pauses politely at the next boundary, Ctrl+C cancels the turn
51- and kills the tool's process group, Ctrl+D exits on an empty draft.
52-- The event stream as the single seam between the agent and its two projections,
53- headless and TUI. The agent never imports the TUI.
54-- Config-first, global config only.
55-- The TUI's appearance and behavior: append-only scrollback, a bounded live
56- region, truecolor with an explicit palette for every cell, no resets that fall
57- back to the host terminal, untrusted text sanitized of every non-SGR escape.
58-
59-## What you must decide and own
60-
61-### Memory
62-
63-This is the point of the port, so treat it as a design decision, not a detail.
64-
65-- Choose the allocator strategy at startup and thread it explicitly. Long-lived
66- state and per-turn scratch are different lifetimes.
67-- Do not copy kanso's single global pool. It avoids `free()` by never releasing,
68- which is not the same as being correct.
69-- Per-turn transient objects — stream accumulators, tool result text, images,
70- diffs, serialization buffers — should die with the turn. Arena or explicit
71- lifetime, your choice, but the code must show the lifetime.
72-- **Never swallow an allocation failure.** `catch {}` on a message or session
73- append loses a turn silently. Every such failure reaches the event stream as a
74- visible error. This is a hard rule in `AGENTS.md` and it is the specific
75- mistake kanso made.
76-
77-### Provider layer
78-
79-This is the largest and highest-risk part. Port the encoders and the streaming
80-reassembly from tiny's structure, because tiny's comments encode decisions that
81-are not visible in mini's behavior and are easy to reintroduce as bugs:
82-
83-- Untrusted stream indices are hints, never sizes. Bound them.
84-- Image blocks among a run of tool results are placed so a user message never
85- lands between an assistant turn and its tool results.
86-- Provider errors surface as-is, never masked or summarized.
87-- Provider-specific continuation data is kept intact.
88-
89-Validate the wire formats against reality, not against your reading of them.
90-
91-### Dependencies
92-
93-Keep the set small and justified. `std` replaces most of what tiny needed C
94-libraries for. tree-sitter and its grammars are the known external need. Any
95-addition beyond that is a decision to raise, not to take.
96-
97-## Order of work
98-
99-Do not port wide. This is a port of a working product, and the risk is breadth.
100-
101-Build one vertical slice first and make it work end to end:
102-
103-1. `zig build` skeleton: `build.zig`, `build.zig.zon`, one binary named `mza`,
104- the allocator chosen at startup, config loading, the `--print` headless path,
105- and the `read` tool. Prove a single turn streams text and persists a session
106- with `openai-completions`, because opencode-go uses it and it is the daily
107- path (Key is available to use in env `OPENCODE_API_KEY`, and a suggested
108- config in `~/.config/mini-coder`).
109-2. Add `edit` and `bash`, the filesystem snapshot diff, and the headless event
110- projection.
111-3. Build the TUI on the same event stream: append-only scrollback, bounded live
112- region, themes, syntax highlighting via tree-sitter, diff rendering.
113-4. Add the remaining three wire protocols, one at a time, each verified on its
114- own before the next.
115-
116-Each step must build, run, and be usable at its end. Do not land a step that is
117-half-done.
118-
119-## Verification
120-
121-The oracle discipline is what made the C port careful, and it is load-bearing
122-here because you will read Zig less fluently than TypeScript. Use it.
123-
124-- `../mini-coder/` is the behavioral oracle. Run the same prompt through both and
125- compare the session JSONL and the visible output.
126-- For the provider layer, `../tiny-c-agent/` is a second oracle. Its four API
127- modules are the careful translation; compare request bodies and assembled
128- messages where you can.
129-- Verify the TUI with the kitty remote-control procedure in `../mini-coder/AGENTS.md`.
130-- Tests and CI are deferred by standing rule. Verify manually. Do not add a test
131- suite.
132-
133-## Non-goals
134-
135-Do not build these; they are deferred by explicit decision in `AGENTS.md`:
136-compaction, resume, prompt templates, subagents, plugins, a settings TUI,
137-OAuth, MCP, sandboxing, macOS/Windows support, tests, CI.
138-
139-## Report
140-
141-When you finish a step, report:
142-
143-- The files you added or changed and the shape of each.
144-- The memory strategy you chose and why it fits the lifetimes.
145-- Any place you made a judgment call between mini's behavior and tiny's
146- structure, and which you followed.
147-- Any requirement in `AGENTS.md` or this document you could not satisfy.
src/agent.zig+290−0
@@ -0,0 +1,290 @@
1+//! The agent loop: one turn, no compaction, no retries, no meta-messages.
2+//! Provider errors surface as-is. Every event reaches a listener; the headless
3+//! projection and the TUI are both listeners and own no agent semantics.
4+
5+const std = @import("std");
6+const types = @import("types.zig");
7+const api = @import("api.zig");
8+const tools = @import("tools/index.zig");
9+const common = @import("tools/common.zig");
10+const session = @import("session.zig");
11+const util = @import("util.zig");
12+
13+pub const Phase = enum { preparing, waiting_model, streaming, running_tool, pausing, idle };
14+
15+pub const Event = union(enum) {
16+ phase: struct { phase: Phase, detail: ?[]const u8 = null },
17+ text: []const u8,
18+ reasoning: []const u8,
19+ tool_call_start: []const u8,
20+ tool_call: struct { name: []const u8, arguments: []const u8 },
21+ tool_output: []const u8,
22+ tool_result: struct { name: []const u8, text: []const u8, is_error: bool, diffs: []const common.FileDiff },
23+ message: *types.AssistantMessage,
24+ no_model,
25+ err: []const u8,
26+ cancelled,
27+ complete,
28+};
29+
30+pub const Listener = struct {
31+ ctx: *anyopaque,
32+ on_event: *const fn (ctx: *anyopaque, event: Event) void,
33+
34+ pub fn emit(self: Listener, event: Event) void {
35+ self.on_event(self.ctx, event);
36+ }
37+};
38+
39+/// How the agent reaches the projection while a turn is in flight. Headless
40+/// uses `NO_INTERACTION`; the TUI supplies its own. `requestSteering` blocks
41+/// the turn thread until the user submits a line or the turn is cancelled.
42+pub const Interaction = struct {
43+ ctx: *anyopaque,
44+ is_pause_requested: *const fn (ctx: *anyopaque) bool,
45+ clear_pause: *const fn (ctx: *anyopaque) void,
46+ request_steering: *const fn (ctx: *anyopaque) []const u8,
47+
48+ pub fn pauseRequested(self: Interaction) bool {
49+ return self.is_pause_requested(self.ctx);
50+ }
51+ pub fn clearPause(self: Interaction) void {
52+ self.clear_pause(self.ctx);
53+ }
54+ pub fn requestSteering(self: Interaction) []const u8 {
55+ return self.request_steering(self.ctx);
56+ }
57+};
58+
59+pub const NO_INTERACTION = Interaction{
60+ .ctx = undefined,
61+ .is_pause_requested = noPause,
62+ .clear_pause = noop,
63+ .request_steering = noSteering,
64+};
65+
66+fn noPause(_: *anyopaque) bool {
67+ return false;
68+}
69+fn noop(_: *anyopaque) void {}
70+fn noSteering(_: *anyopaque) []const u8 {
71+ return "";
72+}
73+
74+pub const Options = struct {
75+ /// Long-lived allocator for the transcript and its messages.
76+ a: std.mem.Allocator,
77+ model: ?*const types.Model,
78+ system_prompt: []const u8,
79+ tools_json: []const u8,
80+ supports_images: bool,
81+ session: *session.Session,
82+ cancel: *const std.atomic.Value(bool),
83+};
84+
85+fn onApiEvent(ctx: *anyopaque, event: api.Event) void {
86+ const listener: *Listener = @ptrCast(@alignCast(ctx));
87+ switch (event) {
88+ .text => |d| listener.emit(.{ .text = d }),
89+ .reasoning => |d| listener.emit(.{ .reasoning = d }),
90+ .tool_start => |name| listener.emit(.{ .tool_call_start = name }),
91+ .tool_call => |call| listener.emit(.{ .tool_call = .{ .name = call.name, .arguments = call.arguments } }),
92+ }
93+}
94+
95+fn onToolOutput(ctx: *anyopaque, chunk: []const u8) void {
96+ const listener: *Listener = @ptrCast(@alignCast(ctx));
97+ listener.emit(.{ .tool_output = chunk });
98+}
99+
100+/// Appends a user message the model reads at the next step boundary. A
101+/// persistence failure is returned so the caller can surface it and stop.
102+fn steer(opts: Options, messages: *std.ArrayList(types.Message), content: []const u8) !void {
103+ if (content.len == 0) return;
104+ const message = types.Message{ .user = .{ .content = content, .timestamp = util.nowMs() } };
105+ try messages.append(opts.a, message);
106+ try opts.session.appendMessage(opts.a, message);
107+}
108+
109+/// Returns the steering typed while paused, or "" when there was no pause;
110+/// null once the turn has been cancelled.
111+fn pauseStep(run: Run, listener: Listener) ?[]const u8 {
112+ if (run.opts.cancel.load(.acquire)) return null;
113+ if (!run.interaction.pauseRequested()) return "";
114+ run.interaction.clearPause();
115+ listener.emit(.{ .phase = .{ .phase = .pausing } });
116+ const steering = run.interaction.requestSteering();
117+ listener.emit(.{ .phase = .{ .phase = .idle } });
118+ if (run.opts.cancel.load(.acquire)) return null;
119+ return steering;
120+}
121+
122+const Run = struct {
123+ opts: Options,
124+ messages: *std.ArrayList(types.Message),
125+ interaction: Interaction,
126+ listener: Listener,
127+};
128+
129+/// Runs one turn to completion, appending to `messages`. Returns after the
130+/// model stops without tool calls, after a cancellation, or after an error;
131+/// every outcome is reported through the listener.
132+pub fn runTurn(opts: Options, messages: *std.ArrayList(types.Message), interaction: Interaction, listener: Listener) void {
133+ const run = Run{ .opts = opts, .messages = messages, .interaction = interaction, .listener = listener };
134+
135+ const model = opts.model orelse {
136+ listener.emit(.no_model);
137+ return;
138+ };
139+
140+ var arena = std.heap.ArenaAllocator.init(opts.a);
141+ defer arena.deinit();
142+
143+ while (true) {
144+ _ = arena.reset(.retain_capacity);
145+ const scratch = arena.allocator();
146+
147+ // Cancellation and steering land at the step boundary, never between an
148+ // assistant turn and its tool results.
149+ const steering = pauseStep(run, listener) orelse {
150+ listener.emit(.cancelled);
151+ return;
152+ };
153+ steer(opts, messages, steering) catch |e| {
154+ listener.emit(.{ .err = @errorName(e) });
155+ return;
156+ };
157+
158+ listener.emit(.{ .phase = .{ .phase = .preparing } });
159+ opts.session.appendRequest(scratch, .{
160+ .provider = model.provider,
161+ .model = model.id,
162+ .api = model.api,
163+ .thinking_effort = model.effort,
164+ .system_prompt = opts.system_prompt,
165+ .tools_json = opts.tools_json,
166+ }) catch |e| {
167+ listener.emit(.{ .err = @errorName(e) });
168+ return;
169+ };
170+
171+ listener.emit(.{ .phase = .{ .phase = .waiting_model } });
172+ var api_listener = listener;
173+ const assistant = opts.a.create(types.AssistantMessage) catch {
174+ listener.emit(.{ .err = "out of memory" });
175+ return;
176+ };
177+ listener.emit(.{ .phase = .{ .phase = .streaming } });
178+ assistant.* = api.stream(.{
179+ .pers = opts.a,
180+ .scratch = scratch,
181+ .model = model,
182+ .system_prompt = opts.system_prompt,
183+ .tools_json = opts.tools_json,
184+ .messages = messages.items,
185+ .effort = model.effort,
186+ .session_id = opts.session.id,
187+ .cancel = opts.cancel,
188+ }, .{ .ctx = &api_listener, .on_event = onApiEvent }) catch |e| {
189+ listener.emit(.{ .err = @errorName(e) });
190+ return;
191+ };
192+
193+ messages.append(opts.a, .{ .assistant = assistant }) catch {
194+ listener.emit(.{ .err = "out of memory" });
195+ return;
196+ };
197+ opts.session.appendMessage(scratch, .{ .assistant = assistant }) catch |e| {
198+ listener.emit(.{ .err = @errorName(e) });
199+ return;
200+ };
201+ listener.emit(.{ .message = assistant });
202+
203+ if (assistant.stop_reason == .aborted) {
204+ listener.emit(.cancelled);
205+ return;
206+ }
207+ if (assistant.stop_reason == .err) {
208+ listener.emit(.{ .err = assistant.error_message orelse "provider error" });
209+ return;
210+ }
211+
212+ const has_calls = for (assistant.content.items) |block| {
213+ if (block == .tool_call) break true;
214+ } else false;
215+ if (!has_calls) {
216+ listener.emit(.complete);
217+ return;
218+ }
219+
220+ // Steering is held until every result of this assistant turn has
221+ // landed: the provider rejects a user message between an assistant
222+ // turn and its tool results.
223+ var held: std.ArrayList([]const u8) = .empty;
224+ defer held.deinit(opts.a);
225+ for (assistant.content.items) |block| {
226+ if (block != .tool_call) continue;
227+ const call = block.tool_call;
228+
229+ const step = pauseStep(run, listener) orelse {
230+ listener.emit(.cancelled);
231+ return;
232+ };
233+ if (step.len > 0) held.append(opts.a, step) catch {
234+ listener.emit(.{ .err = "out of memory" });
235+ return;
236+ };
237+
238+ listener.emit(.{ .phase = .{ .phase = .running_tool, .detail = call.name } });
239+
240+ const result = tools.execute(opts.a, scratch, call.name, call.arguments, .{
241+ .cancel = opts.cancel,
242+ .supports_images = opts.supports_images,
243+ .on_output = .{ .ctx = &api_listener, .on_chunk = onToolOutput },
244+ });
245+
246+ const tool_message = types.Message{ .tool_result = .{
247+ .tool_call_id = call.id,
248+ .tool_name = call.name,
249+ .text = result.text,
250+ .images = result.images,
251+ .is_error = result.is_error,
252+ .timestamp = util.nowMs(),
253+ } };
254+ messages.append(opts.a, tool_message) catch {
255+ listener.emit(.{ .err = "out of memory" });
256+ return;
257+ };
258+ opts.session.appendMessage(scratch, tool_message) catch |e| {
259+ listener.emit(.{ .err = @errorName(e) });
260+ return;
261+ };
262+ listener.emit(.{ .tool_result = .{
263+ .name = call.name,
264+ .text = result.text,
265+ .is_error = result.is_error,
266+ .diffs = result.diffs,
267+ } });
268+ }
269+ const joined = tryJoin(opts.a, held.items) catch {
270+ listener.emit(.{ .err = "out of memory" });
271+ return;
272+ };
273+ steer(opts, messages, joined) catch |e| {
274+ listener.emit(.{ .err = @errorName(e) });
275+ return;
276+ };
277+ }
278+}
279+
280+/// Joins held steering lines with newlines, so the next step sees one message.
281+fn tryJoin(a: std.mem.Allocator, parts: []const []const u8) std.mem.Allocator.Error![]const u8 {
282+ if (parts.len == 0) return "";
283+ if (parts.len == 1) return parts[0];
284+ var out: std.ArrayList(u8) = .empty;
285+ for (parts, 0..) |p, i| {
286+ if (i > 0) try out.append(a, '\n');
287+ try out.appendSlice(a, p);
288+ }
289+ return out.items;
290+}
src/api.zig+73−0
@@ -0,0 +1,73 @@
1+//! The provider contract: one streaming request in, one assistant message out,
2+//! with deltas delivered through a sink.
3+
4+const std = @import("std");
5+const types = @import("types.zig");
6+
7+pub const Event = union(enum) {
8+ /// Assistant text delta.
9+ text: []const u8,
10+ /// Reasoning delta.
11+ reasoning: []const u8,
12+ /// A tool call block began; the name is known but arguments have not
13+ /// finished streaming.
14+ tool_start: []const u8,
15+ /// A tool call block finished.
16+ tool_call: types.ToolCall,
17+};
18+
19+pub const Sink = struct {
20+ ctx: *anyopaque,
21+ on_event: *const fn (ctx: *anyopaque, event: Event) void,
22+
23+ pub fn emit(self: Sink, event: Event) void {
24+ self.on_event(self.ctx, event);
25+ }
26+};
27+
28+pub const Request = struct {
29+ /// Long-lived allocator: the returned message's content outlives the step.
30+ pers: std.mem.Allocator,
31+ /// Per-step arena: the request body and each parsed event. Reset freely.
32+ scratch: std.mem.Allocator,
33+ model: *const types.Model,
34+ system_prompt: []const u8,
35+ /// A pre-serialized JSON array of tool schemas, verbatim.
36+ tools_json: []const u8,
37+ messages: []const types.Message,
38+ effort: []const u8,
39+ session_id: ?[]const u8,
40+ cancel: *const std.atomic.Value(bool),
41+};
42+
43+/// Runs one streaming request. Transport and protocol failures are recorded in
44+/// the returned message's `stop_reason`/`error_message`; only a failure to
45+/// allocate is an error.
46+pub fn stream(req: Request, sink: Sink) std.mem.Allocator.Error!types.AssistantMessage {
47+ if (std.mem.eql(u8, req.model.api, "openai-completions")) {
48+ return @import("api/openai_completions.zig").stream(req, sink);
49+ }
50+ if (std.mem.eql(u8, req.model.api, "anthropic-messages")) {
51+ return @import("api/anthropic_messages.zig").stream(req, sink);
52+ }
53+ if (std.mem.eql(u8, req.model.api, "openai-responses")) {
54+ return @import("api/openai_responses.zig").stream(req, sink);
55+ }
56+ if (std.mem.eql(u8, req.model.api, "google-generative-ai")) {
57+ return @import("api/google_generative_ai.zig").stream(req, sink);
58+ }
59+ var msg = newAssistant(req);
60+ msg.stop_reason = .err;
61+ msg.error_message = "provider: unsupported api";
62+ return msg;
63+}
64+
65+pub fn newAssistant(req: Request) types.AssistantMessage {
66+ return .{
67+ .content = .empty,
68+ .api = req.model.api,
69+ .provider = req.model.provider,
70+ .model = req.model.id,
71+ .timestamp = @import("util.zig").nowMs(),
72+ };
73+}
src/api/anthropic_messages.zig+554−0
@@ -0,0 +1,554 @@
1+//! Anthropic Messages API streaming adapter. The wire format behind every
2+//! customProvider with api "anthropic-messages".
3+
4+const std = @import("std");
5+const api = @import("../api.zig");
6+const types = @import("../types.zig");
7+const http = @import("../http.zig");
8+const json = @import("../json.zig");
9+
10+const Value = std.json.Value;
11+const anthropic_version = "2023-06-01";
12+
13+/// An untrusted stream index is a hint, never a size. Anything past this is
14+/// treated like a missing index so a hostile chunk cannot force an allocation.
15+const max_stream_index = 10_000;
16+
17+// ---- request building -----------------------------------------------------
18+
19+fn writeImage(w: *std.Io.Writer, img: types.ImageContent) !void {
20+ try w.writeAll("{\"type\":\"image\",\"source\":{\"type\":\"base64\",\"media_type\":");
21+ try json.writeString(w, img.mime_type);
22+ try w.writeAll(",\"data\":");
23+ try json.writeString(w, img.data);
24+ try w.writeAll("}}");
25+}
26+
27+/// A tool result is one block of a user message. Its content is a string when
28+/// there is only text, and an array when images must ride along.
29+fn writeToolResult(w: *std.Io.Writer, t: types.ToolResultMessage) !void {
30+ try w.writeAll("{\"type\":\"tool_result\",\"tool_use_id\":");
31+ try json.writeString(w, t.tool_call_id);
32+ if (t.is_error) try w.writeAll(",\"is_error\":true");
33+ if (t.images.len == 0) {
34+ try w.writeAll(",\"content\":");
35+ try json.writeString(w, t.text);
36+ } else {
37+ try w.writeAll(",\"content\":[{\"type\":\"text\",\"text\":");
38+ try json.writeString(w, t.text);
39+ try w.writeByte('}');
40+ for (t.images) |img| {
41+ try w.writeByte(',');
42+ try writeImage(w, img);
43+ }
44+ try w.writeByte(']');
45+ }
46+ try w.writeByte('}');
47+}
48+
49+/// An assistant turn as content blocks. Thinking blocks carry their signature
50+/// back so the provider's continuation data survives the round trip; a
51+/// thinking block without a signature becomes plain text.
52+fn writeAssistant(w: *std.Io.Writer, am: *const types.AssistantMessage) !void {
53+ try w.writeAll("{\"role\":\"assistant\",\"content\":[");
54+ var first = true;
55+ for (am.content.items) |block| switch (block) {
56+ .text => |t| {
57+ if (!first) try w.writeByte(',');
58+ first = false;
59+ try w.writeAll("{\"type\":\"text\",\"text\":");
60+ try json.writeString(w, t);
61+ try w.writeByte('}');
62+ },
63+ .thinking => |t| {
64+ if (!first) try w.writeByte(',');
65+ first = false;
66+ if (t.signature) |sig| {
67+ if (sig.len > 0) {
68+ try w.writeAll("{\"type\":\"thinking\",\"thinking\":");
69+ try json.writeString(w, t.text);
70+ try w.writeAll(",\"signature\":");
71+ try json.writeString(w, sig);
72+ try w.writeByte('}');
73+ continue;
74+ }
75+ }
76+ try w.writeAll("{\"type\":\"text\",\"text\":");
77+ try json.writeString(w, t.text);
78+ try w.writeByte('}');
79+ },
80+ .image => |img| {
81+ if (!first) try w.writeByte(',');
82+ first = false;
83+ try writeImage(w, img);
84+ },
85+ .tool_call => |c| {
86+ if (!first) try w.writeByte(',');
87+ first = false;
88+ try w.writeAll("{\"type\":\"tool_use\",\"id\":");
89+ try json.writeString(w, c.id);
90+ try w.writeAll(",\"name\":");
91+ try json.writeString(w, c.name);
92+ try w.writeAll(",\"input\":");
93+ try w.writeAll(if (c.arguments.len > 0) c.arguments else "{}");
94+ try w.writeByte('}');
95+ },
96+ };
97+ try w.writeAll("]}");
98+}
99+
100+fn writeUser(w: *std.Io.Writer, u: types.Message) !void {
101+ try w.writeAll("{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":");
102+ try json.writeString(w, u.user.content);
103+ try w.writeAll("}]}");
104+}
105+
106+fn writeTools(w: *std.Io.Writer, a: std.mem.Allocator, tools_json: []const u8, params_key: []const u8) !void {
107+ if (tools_json.len == 0) return;
108+ const root = std.json.parseFromSliceLeaky(Value, a, tools_json, .{}) catch return;
109+ if (root != .array) return;
110+ try w.writeAll(",\"tools\":[");
111+ for (root.array.items, 0..) |tool, i| {
112+ if (i > 0) try w.writeByte(',');
113+ const obj = tool.object;
114+ try w.writeAll("{\"name\":");
115+ try json.writeString(w, obj.get("name").?.string);
116+ try w.writeAll(",\"description\":");
117+ try json.writeString(w, obj.get("description").?.string);
118+ try w.writeAll(",\"");
119+ try w.writeAll(params_key);
120+ try w.writeAll("\":");
121+ try std.json.Stringify.value(obj.get("parameters").?, .{}, w);
122+ try w.writeByte('}');
123+ }
124+ try w.writeByte(']');
125+}
126+
127+/// Anthropic thinking budget per effort. Anthropic requires max_tokens to
128+/// exceed the budget, so the caller raises max_tokens when it does not.
129+fn budgetFor(effort: []const u8) u64 {
130+ const map = .{
131+ .{ "minimal", 1024 },
132+ .{ "low", 2048 },
133+ .{ "medium", 4096 },
134+ .{ "high", 8192 },
135+ .{ "xhigh", 16384 },
136+ .{ "max", 32768 },
137+ };
138+ inline for (map) |entry| {
139+ if (std.mem.eql(u8, effort, entry[0])) return entry[1];
140+ }
141+ return 0;
142+}
143+
144+fn buildBody(req: api.Request) ![]u8 {
145+ var out: std.Io.Writer.Allocating = .init(req.scratch);
146+ const w = &out.writer;
147+
148+ const budget = budgetFor(req.effort);
149+ var max_tokens: u64 = if (req.model.max_tokens > 0) req.model.max_tokens else 8192;
150+ if (budget > 0 and max_tokens <= budget) max_tokens = budget + 4096;
151+
152+ try w.writeAll("{\"model\":");
153+ try json.writeString(w, req.model.id);
154+ try w.writeAll(",\"max_tokens\":");
155+ try json.writeUint(w, max_tokens);
156+ try w.writeAll(",\"stream\":true");
157+ if (req.system_prompt.len > 0) {
158+ try w.writeAll(",\"system\":");
159+ try json.writeString(w, req.system_prompt);
160+ }
161+ if (budget > 0) {
162+ try w.writeAll(",\"thinking\":{\"type\":\"enabled\",\"budget_tokens\":");
163+ try json.writeUint(w, budget);
164+ try w.writeByte('}');
165+ }
166+
167+ try w.writeAll(",\"messages\":[");
168+ var first = true;
169+ var i: usize = 0;
170+ while (i < req.messages.len) {
171+ if (req.messages[i] == .tool_result) {
172+ // Every result of one assistant turn shares a single user message.
173+ if (!first) try w.writeByte(',');
174+ first = false;
175+ try w.writeAll("{\"role\":\"user\",\"content\":[");
176+ var first_block = true;
177+ while (i < req.messages.len and req.messages[i] == .tool_result) : (i += 1) {
178+ if (!first_block) try w.writeByte(',');
179+ first_block = false;
180+ try writeToolResult(w, req.messages[i].tool_result);
181+ }
182+ try w.writeAll("]}");
183+ continue;
184+ }
185+ if (!first) try w.writeByte(',');
186+ first = false;
187+ switch (req.messages[i]) {
188+ .user => try writeUser(w, req.messages[i]),
189+ .assistant => |am| try writeAssistant(w, am),
190+ .tool_result => unreachable,
191+ }
192+ i += 1;
193+ }
194+ try w.writeByte(']');
195+
196+ try writeTools(w, req.scratch, req.tools_json, "input_schema");
197+ try w.writeByte('}');
198+ return out.written();
199+}
200+
201+fn buildUrl(a: std.mem.Allocator, base: []const u8) ![]u8 {
202+ return std.fmt.allocPrint(a, "{s}/v1/messages", .{std.mem.trimEnd(u8, base, "/")});
203+}
204+
205+fn headers(a: std.mem.Allocator, req: api.Request, key: []const u8) ![]http.Header {
206+ var list: std.ArrayList(http.Header) = .empty;
207+ errdefer list.deinit(a);
208+ try list.append(a, .{ .name = "Content-Type", .value = "application/json" });
209+ try list.append(a, .{ .name = "Accept", .value = "text/event-stream" });
210+ try list.append(a, .{ .name = "anthropic-version", .value = anthropic_version });
211+ if (key.len > 0) try list.append(a, .{ .name = "x-api-key", .value = key });
212+ for (req.model.headers) |kv| try list.append(a, .{ .name = kv[0], .value = kv[1] });
213+ if (req.session_id) |sid| {
214+ if (req.model.session_header) |name| {
215+ if (sid.len > 0) try list.append(a, .{ .name = name, .value = sid });
216+ }
217+ }
218+ return list.toOwnedSlice(a);
219+}
220+
221+// ---- streaming state ------------------------------------------------------
222+
223+const BlockKind = enum { text, thinking, tool };
224+
225+const Block = struct {
226+ kind: BlockKind = .text,
227+ text: std.ArrayList(u8) = .empty,
228+ signature: std.ArrayList(u8) = .empty,
229+ id: []const u8 = "",
230+ name: []const u8 = "",
231+ args: std.ArrayList(u8) = .empty,
232+ started: bool = false,
233+};
234+
235+const State = struct {
236+ req: api.Request,
237+ sink: api.Sink,
238+ arena: *std.heap.ArenaAllocator,
239+ msg: *types.AssistantMessage,
240+ blocks: std.ArrayList(Block) = .empty,
241+ tokens_in: u64 = 0,
242+ tokens_out: u64 = 0,
243+ cache_read: u64 = 0,
244+ cache_write: u64 = 0,
245+ reasoning_tokens: ?u64 = null,
246+ stop_reason: ?[]const u8 = null,
247+ stream_error: ?[]const u8 = null,
248+};
249+
250+fn blockAt(st: *State, index: i64) !*Block {
251+ const idx: usize = if (index >= 0 and index <= max_stream_index)
252+ @intCast(index)
253+ else
254+ st.blocks.items.len;
255+ while (st.blocks.items.len <= idx) try st.blocks.append(st.req.pers, .{});
256+ return &st.blocks.items[idx];
257+}
258+
259+fn num(v: Value) u64 {
260+ return switch (v) {
261+ .integer => |n| @intCast(@max(n, 0)),
262+ .float => |f| @intFromFloat(@max(f, 0)),
263+ else => 0,
264+ };
265+}
266+
267+fn numField(obj: std.json.ObjectMap, key: []const u8) u64 {
268+ return num(obj.get(key) orelse return 0);
269+}
270+
271+fn applyCost(model: *const types.Model, u: *types.Usage) void {
272+ const m = 1_000_000.0;
273+ u.cost_input = @as(f64, @floatFromInt(u.input)) * model.cost_input / m;
274+ u.cost_output = @as(f64, @floatFromInt(u.output)) * model.cost_output / m;
275+ u.cost_cache_read = @as(f64, @floatFromInt(u.cache_read)) * model.cost_cache_read / m;
276+ u.cost_cache_write = 0;
277+ u.cost_total = u.cost_input + u.cost_output + u.cost_cache_read + u.cost_cache_write;
278+}
279+
280+fn handle(st: *State, obj: std.json.ObjectMap) !void {
281+ const event_type = switch (obj.get("type") orelse Value{ .null = {} }) {
282+ .string => |s| s,
283+ else => "",
284+ };
285+
286+ if (std.mem.eql(u8, event_type, "error")) {
287+ if (st.stream_error == null) st.stream_error = try st.req.pers.dupe(u8, errorMessage(obj));
288+ return;
289+ }
290+
291+ if (std.mem.eql(u8, event_type, "message_start")) {
292+ const message = obj.get("message") orelse return;
293+ if (message != .object) return;
294+ const message_obj = message.object;
295+ if (st.msg.response_id == null) {
296+ if (message_obj.get("id")) |v| {
297+ if (v == .string) st.msg.response_id = try st.req.pers.dupe(u8, v.string);
298+ }
299+ }
300+ if (message_obj.get("usage")) |usage| {
301+ if (usage == .object) {
302+ st.tokens_in = numField(usage.object, "input_tokens");
303+ st.tokens_out = numField(usage.object, "output_tokens");
304+ st.cache_read = numField(usage.object, "cache_read_input_tokens");
305+ st.cache_write = numField(usage.object, "cache_creation_input_tokens");
306+ }
307+ }
308+ return;
309+ }
310+
311+ if (std.mem.eql(u8, event_type, "content_block_start")) {
312+ const raw: i64 = switch (obj.get("index") orelse Value{ .null = {} }) {
313+ .integer => |n| n,
314+ else => -1,
315+ };
316+ if (raw < 0 or raw > max_stream_index) return;
317+ const block = try blockAt(st, raw);
318+ const cb = obj.get("content_block") orelse return;
319+ if (cb != .object) return;
320+ const bt = switch (cb.object.get("type") orelse Value{ .null = {} }) {
321+ .string => |s| s,
322+ else => "",
323+ };
324+ if (std.mem.eql(u8, bt, "tool_use")) {
325+ block.kind = .tool;
326+ if (cb.object.get("id")) |id| {
327+ if (id == .string) block.id = try st.req.pers.dupe(u8, id.string);
328+ }
329+ if (cb.object.get("name")) |name| {
330+ if (name == .string) block.name = try st.req.pers.dupe(u8, name.string);
331+ }
332+ if (!block.started and block.name.len > 0) {
333+ block.started = true;
334+ st.sink.emit(.{ .tool_start = block.name });
335+ }
336+ } else if (std.mem.eql(u8, bt, "thinking") or std.mem.eql(u8, bt, "redacted_thinking")) {
337+ block.kind = .thinking;
338+ if (std.mem.eql(u8, bt, "redacted_thinking")) {
339+ if (cb.object.get("data")) |d| {
340+ if (d == .string) try block.signature.appendSlice(st.req.pers, d.string);
341+ }
342+ }
343+ } else {
344+ block.kind = .text;
345+ }
346+ return;
347+ }
348+
349+ if (std.mem.eql(u8, event_type, "content_block_delta")) {
350+ const idx: i64 = switch (obj.get("index") orelse Value{ .null = {} }) {
351+ .integer => |n| n,
352+ else => return,
353+ };
354+ const delta = obj.get("delta") orelse return;
355+ if (delta != .object) return;
356+ if (idx < 0 or idx >= st.blocks.items.len) return;
357+ const block = &st.blocks.items[@intCast(idx)];
358+ const dt = switch (delta.object.get("type") orelse Value{ .null = {} }) {
359+ .string => |s| s,
360+ else => "",
361+ };
Cut short: this commit's diff is over 1000 lines.
src/api/google_generative_ai.zig+424−0
Cut short: this commit's diff is over 1000 lines.
src/api/openai_completions.zig+476−0
Cut short: this commit's diff is over 1000 lines.
src/api/openai_responses.zig+449−0
Cut short: this commit's diff is over 1000 lines.
src/catalog.zig+177−0
Cut short: this commit's diff is over 1000 lines.
src/config.zig+258−0
Cut short: this commit's diff is over 1000 lines.
src/diff.zig+203−0
Cut short: this commit's diff is over 1000 lines.
src/http.zig+100−0
Cut short: this commit's diff is over 1000 lines.
src/json.zig+44−0
Cut short: this commit's diff is over 1000 lines.
src/main.zig+177−0
Cut short: this commit's diff is over 1000 lines.
src/models.zig+219−0
Cut short: this commit's diff is over 1000 lines.
src/platform.zig+41−0
Cut short: this commit's diff is over 1000 lines.
src/prompt.zig+113−0
Cut short: this commit's diff is over 1000 lines.
src/session.zig+263−0
Cut short: this commit's diff is over 1000 lines.
src/tools/bash.zig+152−0
Cut short: this commit's diff is over 1000 lines.
src/tools/common.zig+41−0
Cut short: this commit's diff is over 1000 lines.
src/tools/edit.zig+71−0
Cut short: this commit's diff is over 1000 lines.
src/tools/index.zig+87−0
Cut short: this commit's diff is over 1000 lines.
src/tools/read.zig+73−0
Cut short: this commit's diff is over 1000 lines.
src/tools/snapshot.zig+172−0
Cut short: this commit's diff is over 1000 lines.
src/tui/complete.zig+70−0
Cut short: this commit's diff is over 1000 lines.
src/tui/editor.zig+429−0
Cut short: this commit's diff is over 1000 lines.
src/tui/highlight.zig+349−0
Cut short: this commit's diff is over 1000 lines.
src/tui/render.zig+185−0
Cut short: this commit's diff is over 1000 lines.
src/tui/stream.zig+190−0
Cut short: this commit's diff is over 1000 lines.
src/tui/styles.zig+46−0
Cut short: this commit's diff is over 1000 lines.
src/tui/term.zig+334−0
Cut short: this commit's diff is over 1000 lines.
src/tui/theme.zig+138−0
Cut short: this commit's diff is over 1000 lines.
src/tui/tui.zig+1198−0
Cut short: this commit's diff is over 1000 lines.
src/types.zig+138−0
Cut short: this commit's diff is over 1000 lines.
src/util.zig+158−0
Cut short: this commit's diff is over 1000 lines.
tools/gen_catalog.py+119−0
Cut short: this commit's diff is over 1000 lines.
tools/stress.sh+156−0
Cut short: this commit's diff is over 1000 lines.