Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

refactor: decompose Agent struct into agent_*.zig (600-line goal)

justrach3f8324f779c5
diff --git a/src/agent_argstream.zig b/src/agent_argstream.zig
new file mode 100644
index 00000000..e7c72b95
--- /dev/null
+++ b/src/agent_argstream.zig
@@ -0,0 +1,341 @@
+//! Live streaming of `attempt_completion`/`ask_user` tool-argument prose:
+//! a byte-at-a-time JSON scanner (ArgLive) that finds the target string
+//! field inside the still-in-flight tool-call arguments and prints it as
+//! it arrives, so strict mode (where the whole answer is a tool call)
+//! doesn't look frozen until the call completes. Split out of the Agent
+//! struct (#123, 600-line goal).
+
+const std = @import("std");
+
+const main_mod = @import("main.zig");
+const Agent = main_mod.Agent;
+const ToolCall = main_mod.ToolCall;
+
+// sseIndex lives in agent_stream.zig; reached through the Agent struct's
+// member alias.
+const sseIndex = Agent.sseIndex;
+
+pub const ArgTool = enum { none, attempt_completion, ask_user };
+
+pub fn argToolFor(name: []const u8) ArgTool {
+ if (std.mem.eql(u8, name, "attempt_completion")) return .attempt_completion;
+ if (std.mem.eql(u8, name, "ask_user")) return .ask_user;
+ return .none;
+}
+
+pub fn argField(tool: ArgTool) []const u8 {
+ return switch (tool) {
+ .attempt_completion => "result",
+ .ask_user => "question",
+ .none => "",
+ };
+}
+
+/// Live tool-argument text. attempt_completion and ask_user carry their
+/// user-facing prose inside tool-call argument JSON, which the text-delta
+/// matching in printDelta can't see — in strict mode that's the *whole*
+/// answer, so the turn looked frozen while it streamed, then dumped at
+/// once. This is a byte-at-a-time scanner over the argument fragments:
+/// skip to the target string field at the top level of the args object
+/// ("result" / "question"), then unescape its value and print it as it
+/// arrives. Best-effort mirror of the real parse that follows the stream
+/// — a glitch here is cosmetic, never semantic.
+pub const ArgLive = struct {
+ tool: ArgTool = .none, // which whitelisted call is open
+ index: i64 = -1, // the provider's stream index for that call
+ state: State = .seek_key,
+ depth: u32 = 0, // container nesting while skipping a non-target value
+ in_str: bool = false, // inside a skipped string
+ esc: bool = false, // previous byte was '\'
+ uni_left: u8 = 0, // hex digits still expected in a \uXXXX escape
+ uni_val: u16 = 0,
+ hi_sur: u16 = 0, // pending UTF-16 high surrogate (0 = none)
+ key: [24]u8 = undefined,
+ key_len: usize = 0,
+ key_over: bool = false, // key overflowed/escaped — cannot be the target
+
+ const State = enum { seek_key, key, post_key, pre_val, skip_val, val, done };
+
+ pub fn open(self: *ArgLive, name: []const u8, ix: i64) void {
+ const tool = argToolFor(name);
+ if (tool == .none) return;
+ self.* = .{ .tool = tool, .index = ix };
+ }
+
+ fn close(self: *ArgLive, ix: i64) void {
+ if (ix == self.index) self.* = .{};
+ }
+
+ pub fn feed(self: *ArgLive, agent: *Agent, ix: i64, frag: []const u8) void {
+ if (self.tool == .none or ix != self.index or self.state == .done) return;
+ var out_buf: [512]u8 = undefined;
+ var out_len: usize = 0;
+ for (frag) |c| {
+ if (out_len > out_buf.len - 8) { // keep room for one decoded escape
+ agent.emitArgText(self.tool, out_buf[0..out_len]);
+ out_len = 0;
+ }
+ switch (self.state) {
+ .done => break,
+ .seek_key => switch (c) {
+ '"' => {
+ self.state = .key;
+ self.key_len = 0;
+ self.key_over = false;
+ },
+ '}' => self.state = .done,
+ else => {}, // '{', ',', whitespace
+ },
+ .key => if (self.esc) {
+ self.esc = false;
+ self.key_over = true; // escaped keys never match the plain target
+ } else switch (c) {
+ '\\' => self.esc = true,
+ '"' => self.state = .post_key,
+ else => if (self.key_len < self.key.len) {
+ self.key[self.key_len] = c;
+ self.key_len += 1;
+ } else {
+ self.key_over = true;
+ },
+ },
+ .post_key => if (c == ':') {
+ self.state = .pre_val;
+ },
+ .pre_val => switch (c) {
+ ' ', '\t', '\r', '\n' => {},
+ '"' => if (!self.key_over and std.mem.eql(u8, self.key[0..self.key_len], argField(self.tool))) {
+ self.state = .val;
+ } else {
+ self.state = .skip_val;
+ self.in_str = true;
+ self.depth = 0;
+ },
+ '{', '[' => {
+ self.state = .skip_val;
+ self.in_str = false;
+ self.depth = 1;
+ },
+ else => { // number / true / false / null
+ self.state = .skip_val;
+ self.in_str = false;
+ self.depth = 0;
+ },
+ },
+ .skip_val => if (self.in_str) {
+ if (self.esc) {
+ self.esc = false;
+ } else if (c == '\\') {
+ self.esc = true;
+ } else if (c == '"') {
+ self.in_str = false;
+ if (self.depth == 0) self.state = .seek_key;
+ }
+ } else switch (c) {
+ '"' => self.in_str = true,
+ '{', '[' => self.depth += 1,
+ ']' => {
+ if (self.depth > 0) self.depth -= 1;
+ if (self.depth == 0) self.state = .seek_key;
+ },
+ '}' => if (self.depth == 0) {
+ self.state = .done; // end of the args object
+ } else {
+ self.depth -= 1;
+ if (self.depth == 0) self.state = .seek_key;
+ },
+ ',' => if (self.depth == 0) {
+ self.state = .seek_key;
+ },
+ else => {},
+ },
+ .val => {
+ if (self.uni_left > 0) {
+ const d = std.fmt.charToDigit(c, 16) catch {
+ self.uni_left = 0; // malformed escape: drop it
+ continue;
+ };
+ self.uni_val = self.uni_val * 16 + d;
+ self.uni_left -= 1;
+ if (self.uni_left == 0) out_len += self.takeUnit(out_buf[out_len..]);
+ continue;
+ }
+ if (self.esc) {
+ self.esc = false;
+ switch (c) {
+ 'n' => out_len += self.put(out_buf[out_len..], '\n'),
+ 't' => out_len += self.put(out_buf[out_len..], '\t'),
+ 'r' => out_len += self.put(out_buf[out_len..], '\r'),
+ 'b' => out_len += self.put(out_buf[out_len..], 0x08),
+ 'f' => out_len += self.put(out_buf[out_len..], 0x0c),
+ 'u' => {
+ self.uni_left = 4;
+ self.uni_val = 0;
+ },
+ else => out_len += self.put(out_buf[out_len..], c), // " \ /
+ }
+ } else switch (c) {
+ '\\' => self.esc = true,
+ '"' => self.state = .done, // value captured — nothing else prints
+ else => out_len += self.put(out_buf[out_len..], c),
+ }
+ },
+ }
+ }
+ if (out_len > 0) agent.emitArgText(self.tool, out_buf[0..out_len]);
+ }
+
+ /// Emit one literal byte, flushing any orphaned high surrogate first.
+ fn put(self: *ArgLive, buf: []u8, c: u8) usize {
+ var n: usize = 0;
+ if (self.hi_sur != 0) {
+ n = replacement(buf);
+ self.hi_sur = 0;
+ }
+ buf[n] = c;
+ return n + 1;
+ }
+
+ /// A completed \uXXXX code unit: pair surrogates, emit UTF-8.
+ fn takeUnit(self: *ArgLive, buf: []u8) usize {
+ const u = self.uni_val;
+ self.uni_val = 0;
+ if (u >= 0xD800 and u <= 0xDBFF) { // high surrogate: hold for its pair
+ var n: usize = 0;
+ if (self.hi_sur != 0) n = replacement(buf); // two highs in a row
+ self.hi_sur = u;
+ return n;
+ }
+ var cp: u21 = u;
+ var n: usize = 0;
+ if (u >= 0xDC00 and u <= 0xDFFF) { // low surrogate
+ if (self.hi_sur == 0) return replacement(buf); // unpaired
+ cp = 0x10000 + (@as(u21, self.hi_sur - 0xD800) << 10) + (u - 0xDC00);
+ self.hi_sur = 0;
+ } else if (self.hi_sur != 0) {
+ n = replacement(buf); // high surrogate not followed by a low
+ self.hi_sur = 0;
+ }
+ n += std.unicode.utf8Encode(cp, buf[n..]) catch 0;
+ return n;
+ }
+
+ fn replacement(buf: []u8) usize {
+ @memcpy(buf[0..3], "\u{FFFD}");
+ return 3;
+ }
+};
+
+pub fn outputIndex(obj: std.json.ObjectMap) ?i64 {
+ const ix = obj.get("output_index") orelse return null;
+ return if (ix == .integer) ix.integer else null;
+}
+
+/// Track tool-call open/delta/close events in the SSE stream and feed
+/// attempt_completion / ask_user argument fragments to the ArgLive
+/// extractor for live printing. Root interactive streams only — SDK
+/// (--json) clients get the assembled tool_call event instead.
+pub fn argLiveDelta(self: *Agent, obj: std.json.ObjectMap) void {
+ if (self.sub or main_mod.json_mode or self.stream_quiet) return;
+ switch (self.provider.kind) {
+ .anthropic => {
+ const t = obj.get("type") orelse return;
+ if (t != .string) return;
+ if (std.mem.eql(u8, t.string, "content_block_start")) {
+ const ix = sseIndex(obj) orelse return;
+ const cb = obj.get("content_block") orelse return;
+ if (cb != .object) return;
+ const bt = cb.object.get("type") orelse return;
+ if (bt != .string or !std.mem.eql(u8, bt.string, "tool_use")) return;
+ const name = cb.object.get("name") orelse return;
+ if (name == .string) self.arg_live.open(name.string, @intCast(ix));
+ } else if (std.mem.eql(u8, t.string, "content_block_delta")) {
+ const ix = sseIndex(obj) orelse return;
+ const d = obj.get("delta") orelse return;
+ if (d != .object) return;
+ const dt = d.object.get("type") orelse return;
+ if (dt != .string or !std.mem.eql(u8, dt.string, "input_json_delta")) return;
+ const pj = d.object.get("partial_json") orelse return;
+ if (pj == .string) self.arg_live.feed(self, @intCast(ix), pj.string);
+ } else if (std.mem.eql(u8, t.string, "content_block_stop")) {
+ const ix = sseIndex(obj) orelse return;
+ self.arg_live.close(@intCast(ix));
+ }
+ },
+ .openai => {
+ const choices = obj.get("choices") orelse return;
+ if (choices != .array or choices.array.items.len == 0) return;
+ const c0 = choices.array.items[0];
+ if (c0 != .object) return;
+ const d = c0.object.get("delta") orelse return;
+ if (d != .object) return;
+ const tcs = d.object.get("tool_calls") orelse return;
+ if (tcs != .array) return;
+ for (tcs.array.items) |tc| {
+ if (tc != .object) continue;
+ const ix: i64 = if (tc.object.get("index")) |iv|
+ (if (iv == .integer) iv.integer else 0)
+ else
+ 0;
+ const f = tc.object.get("function") orelse continue;
+ if (f != .object) continue;
+ if (f.object.get("name")) |n| if (n == .string and n.string.len > 0)
+ self.arg_live.open(n.string, ix);
+ if (f.object.get("arguments")) |a| if (a == .string)
+ self.arg_live.feed(self, ix, a.string);
+ }
+ },
+ .responses => {
+ const t = obj.get("type") orelse return;
+ if (t != .string) return;
+ if (std.mem.eql(u8, t.string, "response.output_item.added")) {
+ const ix = outputIndex(obj) orelse return;
+ const item = obj.get("item") orelse return;
+ if (item != .object) return;
+ const it = item.object.get("type") orelse return;
+ if (it != .string or !std.mem.eql(u8, it.string, "function_call")) return;
+ const name = item.object.get("name") orelse return;
+ if (name == .string) self.arg_live.open(name.string, ix);
+ } else if (std.mem.eql(u8, t.string, "response.function_call_arguments.delta")) {
+ const ix = outputIndex(obj) orelse return;
+ const dl = obj.get("delta") orelse return;
+ if (dl == .string) self.arg_live.feed(self, ix, dl.string);
+ } else if (std.mem.eql(u8, t.string, "response.output_item.done")) {
+ const ix = outputIndex(obj) orelse return;
+ self.arg_live.close(ix);
+ }
+ },
+ }
+}
+
+/// Print live tool-argument text exactly like a text delta: clears the
+/// spinner, lands in the Esc-interrupt capture, and records which meta
+/// tool already showed its prose so handleMeta / sayToolUse don't repeat
+/// it after the call completes.
+pub fn emitArgText(self: *Agent, tool: ArgTool, text: []const u8) void {
+ const w = self.out orelse return;
+ if (text.len == 0) return;
+ self.spinnerStop(); // first visible byte: clear the thinking line
+ self.streamed_text = true;
+ if (self.streamed_args != tool) self.streamed_args_len = 0;
+ self.streamed_args = tool;
+ self.streamed_args_len += text.len;
+ self.partial_text.appendSlice(self.arena, text) catch {};
+ if (main_mod.use_color) {
+ self.streamMarkdown(text);
+ } else {
+ w.writeAll(text) catch return;
+ w.flush() catch return;
+ }
+}
+
+/// True iff this meta call's prose already streamed live *in full*: the
+/// bytes ArgLive emitted match the parsed field exactly. Only then may
+/// the authoritative re-print be suppressed — a scanner glitch must cost
+/// duplication, never content.
+pub fn argStreamedFully(self: *Agent, call: ToolCall) bool {
+ const at = argToolFor(call.name);
+ if (at == .none or at != self.streamed_args) return false;
+ const v = call.input.object.get(argField(at)) orelse return false;
+ return v == .string and v.string.len == self.streamed_args_len;
+}
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
new file mode 100644
index 00000000..190f3714
--- /dev/null
+++ b/src/agent_compact.zig
@@ -0,0 +1,323 @@
+//! Context management: client-side history compaction (compact/
+//! compactOrRecover) and emergency-trim recovery when compaction itself
+//! can't run, plus the --eval/--until eval-driven loop (runEval/
+//! appendEvalLog) and its optional LLM-as-judge scorer (runJudge). Split
+//! out of the Agent struct (#123, 600-line goal).
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+
+const main_mod = @import("main.zig");
+const Agent = main_mod.Agent;
+const ToolCall = main_mod.ToolCall;
+const ExecResult = main_mod.ExecResult;
+const parseEvalScore = main_mod.parseEvalScore;
+const compact_instruction = main_mod.compact_instruction;
+
+const messages_mod = @import("messages.zig");
+const textMessage = messages_mod.textMessage;
+
+const title_mod = @import("title.zig");
+const assistantText = title_mod.assistantText;
+
+const scoring = @import("scoring.zig");
+const promptFingerprint = scoring.promptFingerprint;
+const providerClass = scoring.providerClass;
+const signScore = scoring.signScore;
+
+const telemetry = @import("telemetry.zig");
+
+const jobs = @import("jobs.zig");
+const runCapped = jobs.runCapped;
+
+const tools_mod = @import("tools.zig");
+const ToolCtx = tools_mod.ToolCtx;
+const ToolOutput = tools_mod.ToolOutput;
+
+const subagent = @import("subagent.zig");
+const judgeTask = subagent.judgeTask;
+
+/// Run the configured --eval scoring command, append the result to the
+/// scores log (.graff/eval-log.tsv), and return a verdict for the model:
+/// score (0-100), best so far, target, and whether the target is met. The
+/// harness runs the command, so the model cannot fake the number. (eval tool)
+pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
+ const cmd = self.eval_cmd orelse return .{
+ .text = "no eval command configured - relaunch graff with --eval <scoring cmd> and --until <N>, or ask the user to set one",
+ .is_error = true,
+ };
+ const run = runCapped(self.gpa, self.io, &.{ "/bin/sh", "-c", cmd }, 64 * 1024, 16 * 1024, 0) catch |e|
+ return .{ .text = try std.fmt.allocPrint(self.arena, "eval command could not run: {t}", .{e}), .is_error = true };
+ defer self.gpa.free(run.stdout);
+ defer self.gpa.free(run.stderr);
+ self.eval_iter += 1;
+ const exit_code: i32 = switch (run.term) {
+ .exited => |c| @intCast(c),
+ else => -1,
+ };
+ const det = parseEvalScore(run.stdout) orelse parseEvalScore(run.stderr);
+
+ // LLM-as-judge (--judge): an independent subagent inspects the actual
+ // artifacts against the rubric and returns its own 0-100 score. Both
+ // scores must clear the target, so the binding value is their min().
+ // Skip the judge when the deterministic command itself produced no
+ // score - fix that first rather than burn a judge run.
+ const judge: ?f64 = if (self.eval_judge != null and det != null) self.runJudge(self.eval_judge.?, run.stdout, note) else null;
+ const combined: ?f64 = if (self.eval_judge == null)
+ det
+ else if (det != null and judge != null)
+ @min(det.?, judge.?)
+ else
+ null;
+
+ const target_f: f64 = @floatFromInt(self.eval_target);
+ const improved = if (combined) |s| (self.eval_best < 0 or s > self.eval_best) else false;
+ if (combined) |s| {
+ if (self.eval_best < 0 or s > self.eval_best) self.eval_best = s;
+ }
+ const met = if (combined) |s| s >= target_f else false;
+ self.appendEvalLog(note, det, judge, combined, exit_code, met) catch {};
+
+ // Feed the eval-driven score into the fleet (docs/hyperagents.md §9.B):
+ // on a NEW BEST, submit the genome (this agent's persona) with its achieved
+ // score on the pinned eval set (the eval command's fingerprint). Without this
+ // the score only ever reached .graff/eval-log.tsv and the DGM/fleet never saw
+ // real eval-driven work — only darwincode/JSON-proto runs ever submitted.
+ if (combined) |s| {
+ if (improved and s > 0) { // s>0: skip the initial-state / total-failure 0 (don't pollute the cell mean)
+ if (telemetry.g_telem) |t| {
+ const sys = self.systemPrompt();
+ const genome_fp = promptFingerprint(sys);
+ const esh_fp = promptFingerprint(cmd);
+ const genome: []const u8 = &genome_fp;
+ const esh: []const u8 = &esh_fp;
+ const run_id: []const u8 = &scoring.g_run_id;
+ const pclass = providerClass(self.provider.model);
+ // --niche tags this score's cell. Without it the score lands in the
+ // anonymous "" niche, which pullElites can never match to a builtin —
+ // so an eval session that wants to grow a champion must name its role.
+ const niche = self.eval_niche;
+ // Genome-send (graff-dgm.md §B): the eval genome is this agent's own
+ // persona, never spawned via runSub, so its prompt_text never reached
+ // the worker. A cell only promotes when harness_scores joins to a
+ // harness_genomes row, so ride the genome text over on a `propose`
+ // (deduped by prompt_sha) before the score — else a winning eval cell
+ // has nothing to serve. Gated on a niche: a "" cell is unpromotable.
+ if (niche.len > 0) t.fleetEvent("propose", niche, genome, "", pclass, "", 0, sys);
+ const sig = signScore(genome, "", s, run_id, "", "", esh);
+ const sig_s: []const u8 = if (scoring.g_score_key != null) &sig else "";
+ var provbuf: [512]u8 = undefined;
+ const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}", .{ "", "", esh, pclass, niche }) catch "";
+ t.scoreEvent(genome, "", s, run_id, sig_s, prov);
+ t.fleetEvent("submit", niche, genome, "", pclass, esh, 0, "");
+ }
+ }
+ }
+
+ var aw: Io.Writer.Allocating = .init(self.arena);
+ const w = &aw.writer;
+ if (combined) |s| {
+ if (self.eval_judge != null) {
+ try w.print("eval #{d}: deterministic {d:.1} + judge {d:.1} -> {d:.1}/100 (best {d:.1}, target {d}). ", .{ self.eval_iter, det.?, judge.?, s, self.eval_best, self.eval_target });
+ } else {
+ try w.print("eval #{d}: score {d:.1}/100 (best {d:.1}, target {d}). ", .{ self.eval_iter, s, self.eval_best, self.eval_target });
+ }
+ if (met)
+ try w.writeAll("TARGET MET - finish and report the final scores.")
+ else if (improved)
+ try w.writeAll("Improved - keep going: fix the next biggest failure with one focused change.")
+ else
+ try w.writeAll("No gain over the best - try a different change; do not build on a regression.");
+ } else if (self.eval_judge != null and det != null and judge == null) {
+ try w.print("eval #{d}: deterministic score {d:.1}/100, but the judge returned no parseable score (it may have errored). Re-run after checking the rubric. ", .{ self.eval_iter, det.? });
+ } else {
+ try w.print("eval #{d}: command ran but no score parsed - print a bare number, or JSON with a score field (0-100 or 0-1), on the last line. ", .{self.eval_iter});
+ }
+ const tail = if (run.stdout.len > 1500) run.stdout[run.stdout.len - 1500 ..] else run.stdout;
+ try w.print("\n[exit {d}] eval output (tail):\n{s}", .{ exit_code, tail });
+ return .{ .text = try self.arena.dupe(u8, aw.writer.buffered()), .is_error = false };
+}
+
+/// Append one tab-separated row to the scores log (.graff/eval-log.tsv).
+/// Best-effort - a failed write never breaks the loop.
+pub fn appendEvalLog(self: *Agent, note: []const u8, det: ?f64, judge: ?f64, score: ?f64, exit_code: i32, met: bool) !void {
+ Io.Dir.cwd().createDir(self.io, ".graff", .default_dir) catch {};
+ const path = ".graff/eval-log.tsv";
+ const existing = Io.Dir.cwd().readFileAlloc(self.io, path, self.arena, .limited(2 * 1024 * 1024)) catch "";
+ var aw: Io.Writer.Allocating = .init(self.arena);
+ const w = &aw.writer;
+ try w.writeAll(existing);
+ if (existing.len > 0 and existing[existing.len - 1] != '\n') try w.writeByte('\n');
+ try w.print("iter={d}\tscore=", .{self.eval_iter});
+ if (score) |s| try w.print("{d:.2}", .{s}) else try w.writeAll("NA");
+ try w.writeAll("\tdet=");
+ if (det) |d| try w.print("{d:.2}", .{d}) else try w.writeAll("NA");
+ try w.writeAll("\tjudge=");
+ if (judge) |j| try w.print("{d:.2}", .{j}) else try w.writeAll("NA");
+ try w.print("\tbest={d:.2}\ttarget={d}\tmet={s}\texit={d}\tnote=", .{ self.eval_best, self.eval_target, if (met) "yes" else "no", exit_code });
+ for (note) |ch| try w.writeByte(if (ch < 0x20) ' ' else ch);
+ try w.writeByte('\n');
+ Io.Dir.cwd().writeFile(self.io, .{ .sub_path = path, .data = aw.writer.buffered() }) catch {};
+}
+
+/// Spawn an independent LLM judge (a read-only subagent) to score the
+/// current work against the --judge rubric on a 0-100 scale. The judge
+/// inspects the real artifacts with its own tools and ends its report with
+/// a `score:` line, parsed the same way as a deterministic eval. Runs on a
+/// pool thread via judgeTask (mirrors workflowTask) so the eval handler can
+/// await it. Returns null if the judge could not run or gave no score.
+pub fn runJudge(self: *Agent, rubric: []const u8, eval_output: []const u8, note: []const u8) ?f64 {
+ const ctx: ToolCtx = .{
+ .gpa = self.gpa,
+ .io = self.io,
+ .client = self.client,
+ .provider = self.provider,
+ .registry = if (self.sub) null else self.registry,
+ .from_sub = self.sub,
+ .approvals = self.approvals,
+ .tracer = self.tracer,
+ .snapshots = self.snapshots,
+ .tools_used = &self.tools_used,
+ };
+ const evidence = if (eval_output.len > 1200) eval_output[eval_output.len - 1200 ..] else eval_output;
+ const what = if (note.len > 0) note else "(no note given)";
+ const judge_prompt = std.fmt.allocPrint(self.arena,
+ \\Score the current state of the work in this directory against the rubric below, on a 0-100 scale.
+ \\
+ \\RUBRIC:
+ \\{s}
+ \\
+ \\The author's note on the latest change: {s}
+ \\
+ \\An automated check was also run; its output (tail) is below as evidence. Form your OWN independent judgement of how well the artifacts satisfy the rubric - do not simply echo the check:
+ \\---
+ \\{s}
+ \\---
+ \\
+ \\Inspect the actual files and artifacts the work produced (read them with your tools; do not modify anything), then score how fully they satisfy the rubric. End your reply with a single final line `score: <N>` where N is an integer from 0 to 100.
+ , .{ rubric, what, evidence }) catch return null;
+ var fut: Io.Future(ToolOutput) = self.io.async(judgeTask, .{ ctx, judge_prompt });
+ const out = fut.await(self.io);
+ defer self.gpa.free(out.text);
+ if (out.is_error) return null;
+ return parseEvalScore(out.text);
+}
+
+/// Ask the model for a context-handoff summary (no tools), then restart
+/// history from that summary.
+pub fn compact(self: *Agent) anyerror!usize {
+ if (self.messages.items.len == 0) {
+ if (!main_mod.json_mode) try self.say("nothing to compact\n", .{});
+ return 0;
+ }
+ if (!main_mod.json_mode) try self.say("[compacting ~{d} tokens…]\n", .{self.last_context_tokens});
+ try self.messages.append(try textMessage(self.arena, "user", compact_instruction));
+ errdefer _ = self.messages.pop();
+
+ // The handoff summary is internal — don't stream it to the terminal.
+ self.stream_quiet = true;
+ defer self.stream_quiet = false;
+ const root = try self.request(null);
+ const summary = assistantText(self.provider.kind, root);
+ if (summary.len == 0) {
+ if (!main_mod.json_mode) try self.say("[compaction failed: empty summary, history unchanged]\n", .{});
+ _ = self.messages.pop();
+ return error.EmptySummary;
+ }
+
+ var fresh = std.json.Array.init(self.arena);
+ const handoff = try std.fmt.allocPrint(self.arena,
+ \\Context: the prior conversation was compacted to save space.
+ \\Summary of everything so far:
+ \\
+ \\{s}
+ \\
+ \\Continue assisting the user based on this summary.
+ , .{summary});
+ try fresh.append(try textMessage(self.arena, "user", handoff));
+ self.messages = fresh;
+ self.last_context_tokens = 0;
+ if (!main_mod.json_mode) try self.say("[history compacted to a {d}-char summary]\n", .{summary.len});
+ return summary.len;
+}
+
+pub fn cleanUserTurn(m: Value) bool {
+ if (m != .object) return false;
+ const role = m.object.get("role") orelse return false;
+ if (role != .string or !std.mem.eql(u8, role.string, "user")) return false;
+ const content = m.object.get("content") orelse return true;
+ switch (content) {
+ .string => return true, // a plain-text user turn
+ .array => |arr| {
+ // An anthropic user message that only carries tool_result blocks
+ // is the response half of a tool call — it can't begin a
+ // conversation, so it is not a safe trim boundary.
+ for (arr.items) |blk| {
+ if (blk != .object) continue;
+ const t = blk.object.get("type") orelse continue;
+ if (t == .string and std.mem.eql(u8, t.string, "tool_result")) return false;
+ }
+ return true;
+ },
+ else => return true,
+ }
+}
+
+/// Index to cut history at for an emergency trim: the first clean user turn
+/// at or after the midpoint, so messages[cut..] is always a valid
+/// conversation start (never an orphaned tool_result). null when there is no
+/// safe cut — too short, or only tool_result user messages remain.
+pub fn emergencyCutIndex(items: []const Value) ?usize {
+ if (items.len < 4) return null;
+ var i: usize = items.len / 2;
+ while (i < items.len) : (i += 1) {
+ if (cleanUserTurn(items[i])) return i;
+ }
+ return null;
+}
+
+/// Last-resort context recovery when compact() itself can't run — typically
+/// because the history already overflows the window, so the summarization
+/// request overflows too and fails. Drops the oldest messages at a safe
+/// boundary; returns the count dropped (0 if none). The next turn re-measures
+/// context from the provider usage.
+pub fn emergencyTrim(self: *Agent) usize {
+ const cut = emergencyCutIndex(self.messages.items) orelse return 0;
+ var fresh = std.json.Array.init(self.arena);
+ for (self.messages.items[cut..]) |m| fresh.append(m) catch return 0;
+ self.messages = fresh;
+ self.last_context_tokens = 0;
+ return cut;
+}
+
+/// Auto-compaction with recovery. compact() summarizes the whole history in
+/// one request; once context overflows the window that request overflows too
+/// and fails — historically swallowed silently, wedging the session so every
+/// later turn failed at the same huge token count (issue #88). Surface the
+/// failure and, when `trim_on_fail`, emergency-trim so the next turn has
+/// room. Best-effort; never throws into the REPL loop.
+pub fn compactOrRecover(self: *Agent, trim_on_fail: bool) void {
+ if (self.compact()) |_| return else |err| {
+ switch (err) {
+ error.Interrupted => return, // user hit Esc mid-compaction
+ error.EmptySummary => {}, // compact() already explained it
+ else => {
+ if (main_mod.json_mode)
+ self.emit(.{ .type = "error", .message = std.fmt.allocPrint(self.arena, "auto-compaction failed: {s}", .{@errorName(err)}) catch "auto-compaction failed" })
+ else
+ self.say("[auto-compaction failed: {t}]\n", .{err}) catch {};
+ },
+ }
+ if (!trim_on_fail) return;
+ const dropped = self.emergencyTrim();
+ if (dropped > 0) {
+ if (main_mod.json_mode)
+ self.emit(.{ .type = "compact", .ok = true, .trimmed = dropped })
+ else
+ self.say("[context emergency-trimmed: dropped {d} old message(s) so the session can continue]\n", .{dropped}) catch {};
+ } else if (!main_mod.json_mode) {
+ self.say("[warning: context too large to compact and could not be trimmed safely]\n", .{}) catch {};
+ }
+ }
+}
diff --git a/src/agent_interrupt.zig b/src/agent_interrupt.zig
new file mode 100644
index 00000000..6a73981b
--- /dev/null
+++ b/src/agent_interrupt.zig
@@ -0,0 +1,217 @@
+//! Esc-cancel handling: escWatchTask polls stdin from the pool while the
+//! root awaits tool futures (postStream only watches stdin during a live
+//! HTTP stream, so a long tool join used to be Esc-deaf); escPressed is
+//! the non-blocking stdin scanner shared by both paths — it also captures
+//! steering text typed ahead into main_mod.g_steer_buf/main_mod.g_steer_queue and toggles
+//! the live Thinking-block fold on a mouse click. sleepInterruptible lets
+//! a retry backoff be cancelled the same way. Split out of the Agent
+//! struct (#123, 600-line goal).
+//!
+//! Agent.esc_cancel/Agent.esc_watch_done are struct-level `pub var`s that stay
+//! declared directly inside the Agent struct in main.zig — aliasing a
+//! `var` with `const x = mod.x;` would freeze a copy of its value instead
+//! of sharing the live storage, silently breaking cross-file state
+//! sharing. Reached here as `Agent.Agent.esc_cancel`/`Agent.Agent.esc_watch_done`.
+
+const std = @import("std");
+const Io = std.Io;
+
+const main_mod = @import("main.zig");
+const Agent = main_mod.Agent;
+
+const terminal = @import("term.zig");
+const tty = terminal.tty;
+
+pub fn escWatchTask() void {
+ while (!Agent.esc_watch_done.load(.acquire)) {
+ if (tty.poll(100) and escPressed(false)) {
+ Agent.esc_cancel.store(true, .release);
+ return;
+ }
+ }
+}
+
+/// Non-blocking scan of stdin (terminal must be in VMIN=0 raw mode). A
+/// lone Esc cancels the turn (returns true); CSI sequences (arrows:
+/// ESC[…/ESC O…) are swallowed and don't cancel. Printable bytes are
+/// captured into the steering buffer and echoed when `echo` (main thread
+/// only — the esc watch task runs on the pool and must not race tool
+/// output); Enter flushes the line to main_mod.g_steer_queue, which the REPL
+/// drains as follow-up turns after the current one finishes. A second
+/// Enter on an empty line (double-enter) with a non-empty queue
+/// force-interrupts the current turn so the queue drains immediately.
+pub fn escPressed(echo: bool) bool {
+ var buf: [256]u8 = undefined;
+ var n = tty.readStdin(&buf);
+ var esc_found = false;
+ var i: usize = 0;
+ while (i < n) : (i += 1) {
+ const c = buf[i];
+ if (c == 0x1b) {
+ if (i + 1 < n and buf[i + 1] == '[') {
+ // CSI escape sequence (arrows, Home/End, Delete, DSR reply,
+ // mouse, etc.). Consume through the final byte (0x40..0x7e) so
+ // bytes like "[A" never get captured as steering prompt text. A
+ // CSI run can straddle a VMIN=0 read boundary — e.g. the
+ // \x1b[<row>;<col>R cursor-position reply to our \x1b[6n, or a
+ // burst of SGR mouse-wheel reports if click-to-fold reporting is
+ // re-enabled. If the final byte hasn't landed yet, poll briefly and
+ // pull the tail into the same buffer so its trailing digits/';'/
+ // final byte don't leak in as steer text.
+ var j = i + 2;
+ while (true) {
+ while (j < n) : (j += 1) {
+ if (buf[j] >= 0x40 and buf[j] <= 0x7e) break;
+ }
+ if (j < n or n >= buf.len or !tty.poll(50)) break;
+ const more = tty.readStdin(buf[n..]);
+ if (more == 0) break;
+ n += more;
+ }
+ // SGR mouse report (ESC [ < btn ; col ; row, M=press/m=release):
+ // a plain left-button press (btn 0) on the live Thinking block
+ // toggles its fold — the clickable control for #92. Other mouse
+ // events fall through and are swallowed like any CSI sequence.
+ if (j < n and buf[j] == 'M' and i + 2 < n and buf[i + 2] == '<') {
+ var mk = i + 3;
+ var btn: usize = 0;
+ var got = false;
+ while (mk < j and buf[mk] >= '0' and buf[mk] <= '9') : (mk += 1) {
+ btn = btn * 10 + (buf[mk] - '0');
+ got = true;
+ }
+ if (got and btn == 0 and main_mod.g_thinking_open) main_mod.g_thinking_fold_request = true;
+ }
+ i = if (j < n) j else n - 1;
+ continue;
+ } else if (i + 1 < n and buf[i + 1] == 'O') {
+ // SS3 escape sequence (common for function/cursor keys):
+ // ESC O <final>. Swallow the whole sequence.
+ i = @min(i + 2, n - 1);
+ continue;
+ } else if (i + 1 >= n) {
+ // ESC is the LAST byte of this chunk — it may be the truncated
+ // head of a split CSI/SS3/DSR sequence (e.g. a delayed
+ // `\x1b[<row>;<col>R` cursor-position reply to our `\x1b[6n`)
+ // read across two VMIN=0 reads, NOT a real Esc keypress (#94).
+ // Briefly wait for a continuation before concluding it's an Esc.
+ if (tty.poll(50)) {
+ var more: [64]u8 = undefined;
+ if (tty.readStdin(&more) > 0) {
+ i = n; // a sequence/alt-chord followed — not a lone Esc
+ continue;
+ }
+ }
+ // Nothing followed within the grace window: a genuine lone Esc.
+ esc_found = true;
+ main_mod.g_force_interrupt = false;
+ } else {
+ // ESC + a non-CSI/SS3 byte in the same chunk: a real Esc.
+ esc_found = true;
+ main_mod.g_force_interrupt = false;
+ }
+ continue;
+ } else if (c == '\n' or c == '\r') {
+ if (main_mod.g_steer_buf.items.len > 0) {
+ // Flush the typed line to the queue as a regular
+ // follow-up (runs after the current turn finishes).
+ if (main_mod.g_steer_buf.toOwnedSlice(std.heap.page_allocator)) |dup| {
+ main_mod.g_steer_queue.append(std.heap.page_allocator, .{ .text = dup, .force = false }) catch std.heap.page_allocator.free(dup);
+ } else |_| main_mod.g_steer_buf.clearRetainingCapacity();
+ if (echo and main_mod.g_steer_echoed) {
+ var qbuf: [64]u8 = undefined;
+ const qmsg = std.fmt.bufPrint(&qbuf, " \x1b[2m[queued · {d} waiting]\x1b[0m\n", .{main_mod.g_steer_queue.items.len}) catch "\n";
+ main_mod.steerEcho(qmsg);
+ }
+ } else if (main_mod.g_steer_queue.items.len > 0) {
+ // Double-enter (empty line + queue non-empty): force —
+ // promote the first queued item and interrupt the
+ // current turn so the queue drains starting now.
+ main_mod.g_steer_queue.items[0].force = true;
+ esc_found = true;
+ main_mod.g_force_interrupt = true;
+ if (echo) {
+ if (main_mod.g_steer_echoed) main_mod.steerEcho("\n");
+ main_mod.steerEcho("\x1b[33m↳ force › interrupting…\x1b[0m\n");
+ }
+ }
+ main_mod.g_steer_echoed = false;
+ main_mod.g_steer_visible.store(false, .release);
+ continue;
+ } else if (c == 0x7f or c == 0x08) { // backspace / Ctrl-H
+ if (main_mod.g_steer_buf.items.len > 0) {
+ _ = main_mod.g_steer_buf.pop();
+ if (echo) main_mod.steerEcho("\x08 \x08");
+ }
+ continue;
+ } else if (c == 0x14) { // Ctrl-T: fold/unfold the live Thinking block (#92)
+ main_mod.g_thinking_fold_request = true;
+ continue;
+ } else if (c < 0x20) {
+ continue; // other control bytes: ignore
+ }
+ main_mod.g_steer_buf.append(std.heap.page_allocator, c) catch continue;
+ if (echo) {
+ if (!main_mod.g_steer_echoed) {
+ main_mod.g_steer_visible.store(true, .release);
+ main_mod.steerEcho("\n\x1b[36m↳ steer ›\x1b[0m ");
+ main_mod.g_steer_echoed = true;
+ }
+ main_mod.steerEcho(buf[i .. i + 1]);
+ }
+ }
+ return esc_found;
+}
+
+/// Process any bytes queued on stdin (terminal must be in VMIN=0 raw
+/// mode) so typed-ahead steering text is preserved instead of leaking into
+/// the next prompt or being blindly discarded. Returns true if Esc/force
+/// was seen while draining.
+pub fn drainSteerStdin(echo: bool) bool {
+ var esc_found = false;
+ while (true) {
+ if (!tty.poll(0)) return esc_found;
+ if (escPressed(echo)) esc_found = true;
+ }
+}
+
+pub fn drainStdin() void {
+ _ = drainSteerStdin(false);
+}
+
+/// Put stdin into raw non-blocking no-echo mode (VMIN=0) for Esc
+/// watching. Returns the termios to restore, or null off-tty.
+pub fn rawNonblockStdin() ?tty.RawState {
+ return tty.enterRaw(false);
+}
+
+/// Sleep `ms` watching stdin for Esc (when the root is on a TTY), so the
+/// user can cancel a retry backoff instead of waiting it out.
+pub fn sleepInterruptible(self: *Agent, ms: u64) error{Interrupted}!void {
+ const watch = !self.sub and self.in != null and main_mod.use_color and !main_mod.json_mode;
+ const orig_tio: ?tty.RawState = if (watch) rawNonblockStdin() else null;
+ defer if (orig_tio) |o| tty.restore(o);
+ var left = ms;
+ while (left > 0) {
+ const chunk = @min(left, 100);
+ self.io.sleep(.fromMilliseconds(@intCast(chunk)), .awake) catch {};
+ left -= chunk;
+ if (orig_tio != null and escPressed(true)) return error.Interrupted;
+ }
+}
+
+/// The `data: {...}` payload of one SSE line, or null for anything else
+/// (event: lines, keep-alive blanks, [DONE]).
+pub fn ssePayload(raw_line: []const u8) ?[]const u8 {
+ const line = std.mem.trim(u8, raw_line, " \r");
+ if (!std.mem.startsWith(u8, line, "data:")) return null;
+ const payload = std.mem.trim(u8, line["data:".len..], " ");
+ if (payload.len == 0 or std.mem.eql(u8, payload, "[DONE]")) return null;
+ return payload;
+}
+
+pub fn sseIndex(obj: std.json.ObjectMap) ?usize {
+ const ix = obj.get("index") orelse return null;
+ if (ix != .integer or ix.integer < 0) return null;
+ return @intCast(ix.integer);
+}
diff --git a/src/agent_render.zig b/src/agent_render.zig
new file mode 100644
index 00000000..b648d659
--- /dev/null
+++ b/src/agent_render.zig
@@ -0,0 +1,494 @@
+//! Incremental streaming markdown renderer: the byte-at-a-time classifier
+//! (mdByte/mdTryClassify/...) that decides a line's kind (prose, header,
+//! fence, table row, rule) as early as possible and streams styled output
+//! immediately, plus the non-streaming line renderer (renderMdLine) used
+//! for whole buffered lines (table rows, compaction summaries). Split out
+//! of the Agent struct (#123, 600-line goal); see agent_table.zig for the
+//! table-specific piece this plugs into.
+
+const std = @import("std");
+const Io = std.Io;
+
+const main_mod = @import("main.zig");
+const Agent = main_mod.Agent;
+
+const ansi = @import("ansi.zig");
+const style = &ansi.style;
+
+const terminal = @import("term.zig");
+const termCols = terminal.termCols;
+
+// isTableSeparator lives in agent_table.zig; reached through the Agent
+// struct's member alias.
+const isTableSeparator = Agent.isTableSeparator;
+
+/// Incremental streaming markdown: every delta byte either prints
+/// immediately or is held only as long as classification demands. Each
+/// line starts in .classify (md_buf accumulates the prefix); the moment
+/// the prefix proves what the line is, the buffered bytes are emitted
+/// with their styling and subsequent bytes stream straight through —
+/// prose and bullets/numbered items word-by-word with eager **bold** /
+/// `code` span styling, headers and fenced code styled-then-raw.
+/// Only genuinely whole-line constructs stay held to line end: fence
+/// toggles, tables, horizontal rules (and any still-ambiguous prefix).
+/// Well-formed markdown renders identically to renderMdLine; a span left
+/// unclosed at line end differs cosmetically (styled text, markers
+/// dropped) from renderMdLine's literal-marker fallback.
+pub fn streamMarkdown(self: *Agent, text: []const u8) void {
+ const w = self.out orelse return;
+ for (text) |b| self.mdByte(w, b);
+ w.flush() catch {};
+}
+
+pub const MdKind = enum { classify, hold, prose, header, fenced };
+
+pub const MdSpan = enum { normal, star, bold, bold_star, code };
+
+pub fn mdByte(self: *Agent, w: *Io.Writer, b: u8) void {
+ if (b == '\n') {
+ // A swallowed line (table row joining the buffer) keeps its
+ // newline too — the table renders with its own line breaks.
+ if (self.mdFinishLine(w)) w.writeByte('\n') catch {};
+ return;
+ }
+ switch (self.md_kind) {
+ .classify => {
+ self.md_buf.append(self.gpa, b) catch {};
+ self.mdTryClassify(w);
+ },
+ .hold => self.md_buf.append(self.gpa, b) catch {},
+ .prose => self.mdSpanByte(w, b),
+ .header, .fenced => w.writeByte(b) catch {},
+ }
+}
+
+/// Look at the held line prefix and commit to a line kind as soon as the
+/// bytes allow. Staying silent (returning with .classify) means "not
+/// decidable yet" — at most a few bytes for every construct.
+pub fn mdTryClassify(self: *Agent, w: *Io.Writer) void {
+ const held = self.md_buf.items;
+ var lead: usize = 0;
+ while (lead < held.len and held[lead] == ' ') lead += 1;
+ const body = held[lead..];
+ if (body.len == 0) return; // only indentation so far
+
+ // A buffered table ends at the first line that isn't another row —
+ // render it before this line emits anything.
+ if (self.md_table.items.len > 0 and body[0] != '|') self.flushTable(w);
+
+ if (self.md_fence) {
+ // Inside a fence the only special line is the ``` closer.
+ const bt = countPrefix(body, '`');
+ if (bt == body.len) {
+ if (bt >= 3) self.md_kind = .hold; // closer: whole-line render
+ return; // 1-2 backticks: could still become the closer
+ }
+ self.md_kind = .fenced; // body text: dim it and stream
+ w.writeAll(style.dim) catch {};
+ w.writeAll(held) catch {};
+ self.md_buf.clearRetainingCapacity();
+ return;
+ }
+ switch (body[0]) {
+ '`' => {
+ const bt = countPrefix(body, '`');
+ if (bt >= 3) {
+ self.md_kind = .hold; // fence opener
+ } else if (bt < body.len) {
+ self.mdStartProse(w); // inline code span
+ } // else: 1-2 leading backticks, undecided
+ },
+ '#' => {
+ const hn = countPrefix(body, '#');
+ if (hn == body.len) return; // could still grow
+ if (hn > 6 or body[hn] != ' ') {
+ self.mdStartProse(w);
+ return;
+ }
+ // Header. Mirror renderMdLine's left-trim: wait for the first
+ // non-space byte of the title, then style and stream.
+ var ns = hn + 1;
+ while (ns < body.len and body[ns] == ' ') ns += 1;
+ if (ns == body.len) return;
+ self.md_kind = .header;
+ w.print("{s}{s}{s}", .{ style.bold, style.cyan, body[ns..] }) catch {};
+ self.md_buf.clearRetainingCapacity();
+ },
+ '|' => self.md_kind = .hold, // table row: cells need the whole line
+ '-', '_', '*', '+' => {
+ const run = countPrefix(body, body[0]);
+ if (body[0] != '+' and run == body.len) return; // possible rule
+ if ((body[0] == '-' or body[0] == '*' or body[0] == '+') and run == 1 and body.len >= 2 and body[1] == ' ') {
+ // Bullet: emit indent + styled marker, stream the rest.
+ self.md_kind = .prose;
+ self.md_span = .normal;
+ self.md_col = lead + 2; // "• " — wrapped lines align under the text
+ self.md_indent = lead + 2;
+ w.writeAll(held[0..lead]) catch {};
+ w.print("{s}•{s} ", .{ style.cyan, style.reset }) catch {};
+ const rest = body[2..];
+ self.md_buf.clearRetainingCapacity(); // before re-dispatch
+ var tmp: [8]u8 = undefined;
+ const n = @min(rest.len, tmp.len);
+ @memcpy(tmp[0..n], rest[0..n]);
+ for (tmp[0..n]) |rb| self.mdSpanByte(w, rb);
+ return;
+ }
+ if (body[0] == '+' and body.len == 1) return; // "+ " bullet still possible
+ self.mdStartProse(w);
+ },
+ '0'...'9' => {
+ var d: usize = 0;
+ while (d < body.len and body[d] >= '0' and body[d] <= '9') d += 1;
+ if (d == body.len) return; // all digits: could become "12. "
+ if (body[d] == '.' or body[d] == ')') {
+ if (d + 1 == body.len) return; // "12." — needs one more byte
+ if (body[d + 1] == ' ') { // numbered item
+ self.md_kind = .prose;
+ self.md_span = .normal;
+ self.md_col = lead + d + 2; // "12. " — align under the text
+ self.md_indent = lead + d + 2;
+ w.writeAll(held[0..lead]) catch {};
+ w.print("{s}{s}.{s} ", .{ style.cyan, body[0..d], style.reset }) catch {};
+ const rest = body[d + 2 ..];
+ var tmp: [8]u8 = undefined;
+ const n = @min(rest.len, tmp.len);
+ @memcpy(tmp[0..n], rest[0..n]);
+ self.md_buf.clearRetainingCapacity();
+ for (tmp[0..n]) |rb| self.mdSpanByte(w, rb);
+ return;
+ }
+ }
+ self.mdStartProse(w);
+ },
+ else => self.mdStartProse(w),
+ }
+}
+
+/// Commit to plain prose: replay the held prefix through the inline-span
+/// machine, then stream subsequent bytes directly.
+pub fn mdStartProse(self: *Agent, w: *Io.Writer) void {
+ self.md_kind = .prose;
+ self.md_span = .normal;
+ var lead: usize = 0;
+ while (lead < self.md_buf.items.len and self.md_buf.items[lead] == ' ') lead += 1;
+ self.md_indent = lead; // wrapped lines keep the line's indentation
+ for (self.md_buf.items) |b| self.mdSpanByte(w, b);
+ self.md_buf.clearRetainingCapacity();
+}
+
+/// Streaming counterpart of renderInline: a left-to-right toggle machine
+/// for **bold** and `code` spans that styles eagerly — the opener turns
+/// styling on as soon as it's seen instead of waiting for the closer.
+/// Literal bytes route through mdWrapByte (terminal-width word wrap);
+/// style sequences through mdStyle (zero-width, ordered with the word).
+pub fn mdSpanByte(self: *Agent, w: *Io.Writer, b: u8) void {
+ switch (self.md_span) {
+ .normal => switch (b) {
+ '*' => self.md_span = .star,
+ '`' => {
+ self.mdStyle(w, style.yellow);
+ self.md_span = .code;
+ },
+ else => self.mdWrapByte(w, b),
+ },
+ .star => if (b == '*') {
+ self.mdStyle(w, style.bold);
+ self.md_span = .bold;
+ } else {
+ self.mdWrapByte(w, '*'); // lone star is literal
+ self.md_span = .normal;
+ self.mdSpanByte(w, b);
+ },
+ .bold => switch (b) {
+ '*' => self.md_span = .bold_star,
+ else => self.mdWrapByte(w, b),
+ },
+ .bold_star => if (b == '*') {
+ self.mdStyle(w, style.reset);
+ self.md_span = .normal;
+ } else {
+ self.mdWrapByte(w, '*');
+ self.md_span = .bold;
+ self.mdSpanByte(w, b);
+ },
+ .code => if (b == '`') {
+ self.mdStyle(w, style.reset);
+ self.md_span = .normal;
+ } else self.mdWrapByte(w, b),
+ }
+}
+
+/// Terminal-width word wrap for streamed prose. Literal bytes buffer
+/// into the current word; a space flushes it — and a word that would
+/// cross the terminal edge breaks the line first and continues under
+/// the hanging indent (set by the bullet/numbered/prose classifiers),
+/// instead of hard-wrapping at column 0 mid-word.
+pub fn mdWrapByte(self: *Agent, w: *Io.Writer, b: u8) void {
+ if (b == ' ') {
+ self.mdFlushWord(w);
+ if (self.md_col < self.mdWidth()) {
+ w.writeByte(' ') catch {};
+ self.md_col += 1;
+ } else if (self.md_col > self.md_indent) {
+ self.mdWrapBreak(w); // line full: break instead of the space
+ } // already at a fresh indent: swallow the space
+ return;
+ }
+ self.md_word.append(self.gpa, b) catch {
+ w.writeByte(b) catch {}; // can't buffer: degrade to direct write
+ return;
+ };
+ if ((b & 0xC0) != 0x80) self.md_word_vis += 1; // UTF-8 leads only
+}
+
+/// Style sequences are zero-width but must stay ordered with the word
+/// they're inside of — buffer them with a pending word, else pass through.
+pub fn mdStyle(self: *Agent, w: *Io.Writer, s: []const u8) void {
+ if (self.md_word.items.len > 0) {
+ self.md_word.appendSlice(self.gpa, s) catch {};
+ } else w.writeAll(s) catch {};
+}
+
+pub fn mdFlushWord(self: *Agent, w: *Io.Writer) void {
+ if (self.md_word.items.len == 0) return;
+ const vis = self.md_word_vis;
+ const width = self.mdWidth();
+ // Break before a word that would cross the edge — unless the line is
+ // already fresh or the word can't fit any line (URLs: let the
+ // terminal wrap it rather than shred it).
+ if (self.md_col + vis > width and self.md_col > self.md_indent and self.md_indent + vis <= width)
+ self.mdWrapBreak(w);
+ w.writeAll(self.md_word.items) catch {};
+ self.md_col += vis;
+ self.md_word.clearRetainingCapacity();
+ self.md_word_vis = 0;
+}
+
+pub fn mdWrapBreak(self: *Agent, w: *Io.Writer) void {
+ w.writeByte('\n') catch {};
+ for (0..self.md_indent) |_| w.writeByte(' ') catch {};
+ self.md_col = self.md_indent;
+}
+
+pub fn mdWidth(self: *Agent) usize {
+ if (self.md_width == 0) self.md_width = termCols();
+ return self.md_width;
+}
+
+/// Settle the span machine at line end: pending markers print literally,
+/// open spans close their styling.
+pub fn mdSpanEnd(self: *Agent, w: *Io.Writer) void {
+ self.mdFlushWord(w);
+ switch (self.md_span) {
+ .normal => {},
+ .star => w.writeByte('*') catch {},
+ .bold, .code => w.writeAll(style.reset) catch {},
+ .bold_star => {
+ w.writeByte('*') catch {};
+ w.writeAll(style.reset) catch {};
+ },
+ }
+ self.md_span = .normal;
+}
+
+/// End of line (newline or stream end): render anything still held,
+/// settle styling, and reset the per-line state. Returns false when the
+/// line was a table row swallowed into md_table — the caller then skips
+/// the newline; the table prints its own when it flushes.
+pub fn mdFinishLine(self: *Agent, w: *Io.Writer) bool {
+ switch (self.md_kind) {
+ // Still held: a whole-line construct or a prefix too short to
+ // classify — renderMdLine does exactly the right thing (and
+ // toggles md_fence for fence lines).
+ .classify, .hold => {
+ const line = self.md_buf.items;
+ var lead: usize = 0;
+ while (lead < line.len and line[lead] == ' ') lead += 1;
+ if (!self.md_fence and lead < line.len and line[lead] == '|') {
+ // Table row: buffer it — columns can only align once the
+ // whole table is known.
+ if (self.gpa.dupe(u8, line[lead..])) |dup| {
+ self.md_table.append(self.gpa, dup) catch self.gpa.free(dup);
+ self.md_buf.clearRetainingCapacity();
+ self.md_kind = .classify;
+ self.md_span = .normal;
+ return false;
+ } else |_| {}
+ }
+ if (self.md_table.items.len > 0) self.flushTable(w);
+ self.renderMdLine(w, line);
+ },
+ .prose => self.mdSpanEnd(w),
+ .header, .fenced => w.writeAll(style.reset) catch {},
+ }
+ self.md_buf.clearRetainingCapacity();
+ self.md_kind = .classify;
+ self.md_span = .normal;
+ self.md_col = 0;
+ self.md_indent = 0;
+ self.md_width = 0; // re-read the terminal width next line (resizes)
+ return true;
+}
+
+pub fn countPrefix(s: []const u8, c: u8) usize {
+ var i: usize = 0;
+ while (i < s.len and s[i] == c) i += 1;
+ return i;
+}
+
+/// Columns a cell occupies once rendered: matched **bold**/`code` markers
+/// drop, and multi-byte UTF-8 sequences count as one column (wide CJK
+/// glyphs are approximated as one).
+pub fn inlineVisibleLen(s: []const u8) usize {
+ var i: usize = 0;
+ var n: usize = 0;
+ while (i < s.len) {
+ if (i + 1 < s.len and s[i] == '*' and s[i + 1] == '*') {
+ if (std.mem.indexOfPos(u8, s, i + 2, "**")) |end| {
+ n += codepointCount(s[i + 2 .. end]);
+ i = end + 2;
+ continue;
+ }
+ }
+ if (s[i] == '`') {
+ if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |end| {
+ n += codepointCount(s[i + 1 .. end]);
+ i = end + 1;
+ continue;
+ }
+ }
+ if ((s[i] & 0xC0) != 0x80) n += 1;
+ i += 1;
+ }
+ return n;
+}
+
+pub fn codepointCount(s: []const u8) usize {
+ var n: usize = 0;
+ for (s) |b| {
+ if ((b & 0xC0) != 0x80) n += 1;
+ }
+ return n;
+}
+
+/// Flush the trailing partial line at stream end (no forced newline — the
+/// caller adds the separating newline), and reset fence state.
+pub fn flushStreamTail(self: *Agent) void {
+ const w = self.out orelse return;
+ _ = self.mdFinishLine(w); // may swallow a final table row…
+ if (self.md_table.items.len > 0) self.flushTable(w); // …then render it
+ w.flush() catch {};
+ self.md_fence = false;
+}
+
+/// Render one markdown line to ANSI (portable SGR only — bold/color, no
+/// italic, so iTerm/Ghostty/Terminal/Windows-Terminal all agree): code
+/// fences + fenced bodies dimmed, ATX headers bold-cyan, `-`/`*`/`+`
+/// bullets → cyan •, and inline `**bold**` / `` `code` `` spans.
+pub fn renderMdLine(self: *Agent, w: *Io.Writer, line: []const u8) void {
+ var lead: usize = 0;
+ while (lead < line.len and line[lead] == ' ') lead += 1;
+ const body = line[lead..];
+ if (std.mem.startsWith(u8, body, "```")) {
+ self.md_fence = !self.md_fence;
+ // Fence lines render as a dim rule — "── zig ────…" opening with
+ // the language label when given, plain "────…" otherwise —
+ // instead of raw backticks. Body lines stay unprefixed so code
+ // copies cleanly out of the terminal.
+ const lang = std.mem.trim(u8, body[3..], " `");
+ w.writeAll(style.dim) catch {};
+ var used: usize = 0;
+ if (self.md_fence and lang.len > 0) {
+ w.print("── {s} ", .{lang}) catch {};
+ used = 4 + codepointCount(lang); // "── " + label + " "
+ }
+ while (used < 40) : (used += 1) w.writeAll("─") catch {};
+ w.writeAll(style.reset) catch {};
+ return;
+ }
+ if (self.md_fence) {
+ w.print("{s}{s}{s}", .{ style.dim, line, style.reset }) catch {};
+ return;
+ }
+ // ATX header: 1-6 '#' then a space.
+ var h: usize = 0;
+ while (h < body.len and body[h] == '#') h += 1;
+ if (h >= 1 and h <= 6 and h < body.len and body[h] == ' ') {
+ const head = std.mem.trim(u8, body[h + 1 ..], " ");
+ w.print("{s}{s}{s}{s}", .{ style.bold, style.cyan, head, style.reset }) catch {};
+ return;
+ }
+ // Horizontal rule: a line of only -, *, or _ (3+).
+ if (body.len >= 3 and isRule(body)) {
+ w.print("{s}────────────{s}", .{ style.dim, style.reset }) catch {};
+ return;
+ }
+ // Table row (GFM): starts with '|'. Separator row → dim rule; data row
+ // → cells joined by a dim │, each rendered inline.
+ if (body.len > 0 and body[0] == '|') {
+ if (isTableSeparator(body)) {
+ w.print("{s}────────────{s}", .{ style.dim, style.reset }) catch {};
+ return;
+ }
+ var cells = std.mem.splitScalar(u8, body, '|');
+ var first = true;
+ while (cells.next()) |cell| {
+ const c = std.mem.trim(u8, cell, " ");
+ if (c.len == 0) continue;
+ if (!first) w.print("{s} │ {s}", .{ style.dim, style.reset }) catch {};
+ first = false;
+ renderInline(w, c);
+ }
+ return;
+ }
+ // Bullet list item.
+ if (std.mem.startsWith(u8, body, "- ") or std.mem.startsWith(u8, body, "* ") or std.mem.startsWith(u8, body, "+ ")) {
+ w.writeAll(line[0..lead]) catch {};
+ w.print("{s}•{s} ", .{ style.cyan, style.reset }) catch {};
+ renderInline(w, body[2..]);
+ return;
+ }
+ // Numbered list: digits then '.' or ')' then a space.
+ var d: usize = 0;
+ while (d < body.len and body[d] >= '0' and body[d] <= '9') d += 1;
+ if (d >= 1 and d + 1 < body.len and (body[d] == '.' or body[d] == ')') and body[d + 1] == ' ') {
+ w.writeAll(line[0..lead]) catch {};
+ w.print("{s}{s}.{s} ", .{ style.cyan, body[0..d], style.reset }) catch {};
+ renderInline(w, body[d + 2 ..]);
+ return;
+ }
+ renderInline(w, line);
+}
+
+/// True if every char is one of '-', '*', '_' (markdown thematic break).
+pub fn isRule(body: []const u8) bool {
+ const c0 = body[0];
+ if (c0 != '-' and c0 != '*' and c0 != '_') return false;
+ for (body) |c| if (c != c0) return false;
+ return true;
+}
+
+/// Emit a line with inline `**bold**` and `` `code` `` spans styled; the
+/// markers themselves are dropped. Unmatched markers print literally.
+pub fn renderInline(w: *Io.Writer, s: []const u8) void {
+ var i: usize = 0;
+ while (i < s.len) {
+ if (i + 1 < s.len and s[i] == '*' and s[i + 1] == '*') {
+ if (std.mem.indexOfPos(u8, s, i + 2, "**")) |end| {
+ w.print("{s}{s}{s}", .{ style.bold, s[i + 2 .. end], style.reset }) catch {};
+ i = end + 2;
+ continue;
+ }
+ }
+ if (s[i] == '`') {
+ if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |end| {
+ w.print("{s}{s}{s}", .{ style.yellow, s[i + 1 .. end], style.reset }) catch {};
+ i = end + 1;
+ continue;
+ }
+ }
+ w.writeByte(s[i]) catch {};
+ i += 1;
+ }
+}
diff --git a/src/agent_request.zig b/src/agent_request.zig
new file mode 100644
index 00000000..789a4495
--- /dev/null
+++ b/src/agent_request.zig
@@ -0,0 +1,512 @@
+//! The provider round trip: request() builds+sends the body (with the
+//! retry/backoff loop for flaky transport and 429/5xx), buildBody()
+//! serializes it per wire format (Anthropic/OpenAI/Responses), and
+//! recordUsage/recordUsageResponses/recordCost tally tokens + cost into
+//! the session-wide g_cost. parseResponses reassembles the Codex/Responses
+//! SSE stream into a synthetic {output, usage} object (the streaming
+//! Anthropic/OpenAI SSE reassembly — assembleAnthropic/assembleOpenAI —
+//! lives in agent_steps.zig instead, since it feeds the step* functions
+//! there). Split out of the Agent struct (#123, 600-line goal).
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+
+const main_mod = @import("main.zig");
+const Agent = main_mod.Agent;
+const max_tokens = main_mod.max_tokens;
+
+const pricing = @import("pricing.zig");
+const g_cost = &pricing.g_cost;
+
+const messages_mod = @import("messages.zig");
+const sanitizeMessagesUtf8 = messages_mod.sanitizeMessagesUtf8;
+const normalizeResponsesHistory = messages_mod.normalizeResponsesHistory;
+const normalizeOpenAIHistory = messages_mod.normalizeOpenAIHistory;
+
+const serde = @import("serde.zig");
+const writeAnthropicMessages = serde.writeAnthropicMessages;
+const writeOpenAIMessageNormalized = serde.writeOpenAIMessageNormalized;
+
+const http = @import("http.zig");
+const postWatched = http.postWatched;
+const RetryPlan = http.RetryPlan;
+
+const tools_mod = @import("tools.zig");
+const apiErrorMessage = tools_mod.apiErrorMessage;
+const mentionsReasoningEffort = tools_mod.mentionsReasoningEffort;
+
+const telemetry = @import("telemetry.zig");
+
+/// POST the current history; returns the parsed response root object
+/// (arena-owned). Reports API error envelopes and returns error.ApiError.
+/// In strict mode we force tool_choice; if a provider rejects that (e.g.
+/// the codegraff gateway with thinking on), we retry once without forcing
+/// and lean on the strict system prompt instead. Root requests stream:
+/// text deltas print live (postStream) and the buffered SSE events are
+/// reassembled into the non-streaming response shape afterwards.
+pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
+ var force = self.strict and tools != null;
+ var stream_usage = true; // openai stream_options; dropped if rejected
+ // #95: scrub any malformed function_call_output before it hits the wire.
+ sanitizeMessagesUtf8(self.arena, &self.messages); // invalid UTF-8 (any source/format) -> '?' so content never serializes as a byte-int array the API rejects
+ if (self.provider.kind == .responses) normalizeResponsesHistory(self.arena, &self.messages);
+ if (self.provider.kind == .openai) normalizeOpenAIHistory(self.arena, &self.messages); // #99: chat-completions sibling of the above
+ while (true) {
+ const live = !self.sub and self.out != null and !self.stream_quiet;
+ self.streamed_text = false;
+ self.streamed_args = .none;
+ const body = try self.buildBody(tools, force, live, stream_usage);
+ defer self.gpa.free(body);
+ const t0: Io.Timestamp = .now(self.io, .awake);
+ if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_started", .provider = self.provider.id, .model = self.provider.model });
+ // HTTP calls are flaky: a kept-alive connection the server closed
+ // (HttpConnectionClosing), a reset, a truncated TLS read. Retry a
+ // few times with a fresh connection; on persistent failure surface
+ // error.ApiError so the REPL returns to the prompt, never crashes.
+ const resp_body = blk: {
+ var attempt: usize = 0;
+ while (true) : (attempt += 1) {
+ const attempt_body = if (live)
+ self.postStream(body)
+ else
+ postWatched(self.gpa, self.io, self.client, self.provider, body);
+ if (attempt_body) |ok| break :blk ok else |err| {
+ if (self.streamed_text) if (self.out) |w| {
+ w.writeAll("\n") catch {};
+ w.flush() catch {};
+ };
+ self.streamed_text = false;
+ self.streamed_args = .none;
+ // Esc is a deliberate stop, not a flaky network — no retry.
+ if (err == error.Interrupted) return error.Interrupted;
+ // 429/5xx: the server asked us to back off — wait
+ // (1s·2ⁿ, capped at 8s; Esc cancels) and allow a few
+ // more attempts than a plain transport flake gets.
+ const throttled = err == error.RateLimited or err == error.ServerError;
+ const max_attempts: usize = RetryPlan.maxAttempts(throttled);
+ if (attempt < max_attempts) {
+ if (throttled) {
+ const delay_ms = RetryPlan.delayMs(throttled, attempt);
+ const what: []const u8 = if (err == error.RateLimited) "rate limited (429)" else "server error (5xx)";
+ if (main_mod.g_5xx_body_len > 0) {
+ try self.say("[{s} — retrying in {d}s ({d}/{d})] {s}\n", .{ what, delay_ms / 1000, attempt + 1, max_attempts, main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len] });
+ } else {
+ try self.say("[{s} — retrying in {d}s ({d}/{d})]\n", .{ what, delay_ms / 1000, attempt + 1, max_attempts });
+ }
+ if (self.tracer) |tr| tr.note("retry", if (main_mod.g_5xx_body_len > 0) main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len] else what);
+ self.sleepInterruptible(delay_ms) catch return error.Interrupted;
+ } else {
+ // Transport flake (HttpConnectionClosing, a reset,
+ // a truncated TLS read): back off before a fresh
+ // connection. Rapid-fire retries against a
+ // just-closed keep-alive almost always re-fail
+ // (#86). 250ms·2ⁿ, capped at 4s over 6 tries; Esc cancels.
+ const delay_ms = RetryPlan.delayMs(throttled, attempt);
+ try self.say("[network error: {t} — retrying in {d}ms ({d}/{d})]\n", .{ err, delay_ms, attempt + 1, max_attempts });
+ self.sleepInterruptible(delay_ms) catch return error.Interrupted;
+ }
+ continue;
+ }
+ if (main_mod.g_5xx_body_len > 0) {
+ try self.say("[request failed: {t} — giving up this turn] {s}\n", .{ err, main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len] });
+ } else {
+ try self.say("[request failed: {t} — giving up this turn]\n", .{err});
+ }
+ // Network give-up is its own error kind: the ApiError
+ // handler's last_api_error would otherwise be an API
+ // envelope, stale or null on a pure transport failure —
+ // record the real reason so the failed turn's --json error
+ // event and trajectory node preserve it (#86).
+ self.last_api_error = std.fmt.allocPrint(self.arena, "network error: {s} (gave up after {d} attempts)", .{ @errorName(err), max_attempts }) catch null;
+ if (telemetry.g_telem) |t| t.errorEvent("net", @errorName(err));
+ if (self.tracer) |tr| tr.api(self.label, self.provider.model, 0, body.len, 0, 0, 0, true);
+ return error.ApiError;
+ }
+ }
+ };
+ defer self.gpa.free(resp_body);
+ const ms: i64 = t0.untilNow(self.io, .awake).toMilliseconds();
+
+ // object — pull the final `response` out of it (or an error).
+ // object — pull the final `response` out of it (or an error).
+ if (self.provider.kind == .responses) {
+ const r = self.parseResponses(resp_body) catch {
+ try self.say("unparseable codex response: {s}\n", .{resp_body[0..@min(resp_body.len, 600)]});
+ if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
+ return error.ApiError;
+ };
+ switch (r) {
+ .ok => |obj| {
+ self.recordUsageResponses(obj);
+ if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
+ if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
+ return obj;
+ },
+ .err => |msg| {
+ if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
+ try self.sayApiError("codex api error: {s}", .{msg});
+ return error.ApiError;
+ },
+ }
+ }
+
+ // Streamed anthropic/openai bodies are SSE too: reassemble them.
+ // null → the body wasn't SSE (a JSON error envelope, or a
+ // provider that ignored `stream`) — fall through to the regular
+ // parse, which also handles the soft-strict retry.
+ if (live) {
+ if (try self.assembleStream(resp_body)) |root| {
+ if (root.get("type")) |t| if (t == .string and std.mem.eql(u8, t.string, "error")) {
+ const eo = if (root.get("error")) |ev| (if (ev == .object) ev.object else null) else null;
+ const etype = if (eo) |e| (if (e.get("type")) |tv| (if (tv == .string) tv.string else "error") else "error") else "error";
+ const emsg = if (eo) |e| (if (e.get("message")) |mv| (if (mv == .string) mv.string else "") else "") else "";
+ if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
+ try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });
+ return error.ApiError;
+ };
+ self.recordUsage(root);
+ if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
+ if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
+ return root;
+ }
+ }
+
+ const resp = std.json.parseFromSliceLeaky(Value, self.arena, resp_body, .{
+ .allocate = .alloc_always,
+ }) catch {
+ try self.sayApiError("unparseable response: {s}", .{resp_body[0..@min(resp_body.len, 400)]});
+ return error.ApiError;
+ };
+ const root = resp.object;
+
+ if (root.get("type")) |t| if (t == .string and std.mem.eql(u8, t.string, "error")) {
+ const eo = if (root.get("error")) |ev| (if (ev == .object) ev.object else null) else null;
+ const etype = if (eo) |e| (if (e.get("type")) |tv| (if (tv == .string) tv.string else "error") else "error") else "error";
+ const emsg = if (eo) |e| (if (e.get("message")) |mv| (if (mv == .string) mv.string else "") else "") else "";
+ if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
+ try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });
+ return error.ApiError;
+ };
+ if (apiErrorMessage(root)) |msg| {
+ if (force and std.mem.indexOf(u8, msg, "tool_choice") != null) {
+ force = false; // provider can't force a tool; soft-strict
+ continue;
+ }
+ if (stream_usage and std.mem.indexOf(u8, msg, "stream_options") != null) {
+ stream_usage = false; // provider can't report streamed usage
+ continue;
+ }
+ if (!self.cap_new and std.mem.indexOf(u8, msg, "max_completion_tokens") != null) {
+ self.cap_new = true; // provider wants the post-deprecation name
+ continue;
+ }
+ if (!self.effort_rejected and mentionsReasoningEffort(msg)) {
+ self.effort_rejected = true; // model rejects the effort hint here; drop + retry
+ continue;
+ }
+ if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
+ try self.sayApiError("api error: {s}", .{msg});
+ return error.ApiError;
+ }
+
+ self.recordUsage(root);
+ if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
+ if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
+ return root;
+ }
+}
+
+pub fn recordUsage(self: *Agent, root: std.json.ObjectMap) void {
+ const usage = root.get("usage") orelse return;
+ if (usage != .object) return;
+ const u = usage.object;
+ self.last_cache_read = 0;
+ switch (self.provider.kind) {
+ .anthropic => {
+ var total: i64 = 0;
+ const fields = [_][]const u8{
+ "input_tokens", "output_tokens",
+ "cache_read_input_tokens", "cache_creation_input_tokens",
+ };
+ for (fields) |f| total += usageInt(u, f);
+ if (total > 0) self.last_context_tokens = @intCast(total);
+ const cache = usageInt(u, "cache_read_input_tokens");
+ if (cache > 0) self.last_cache_read = @intCast(cache);
+ // cache writes bill ~like input; fold them into uncached input.
+ self.recordCost(usageInt(u, "input_tokens") + usageInt(u, "cache_creation_input_tokens"), cache, usageInt(u, "output_tokens"));
+ },
+ .openai => {
+ if (usageInt(u, "total_tokens") > 0) self.last_context_tokens = @intCast(usageInt(u, "total_tokens"));
+ // deepseek reports prompt_cache_hit_tokens; the OpenAI shape
+ // nests cached_tokens under prompt_tokens_details.
+ var cache = usageInt(u, "prompt_cache_hit_tokens");
+ if (cache == 0) if (u.get("prompt_tokens_details")) |d| if (d == .object) {
+ cache = usageInt(d.object, "cached_tokens");
+ };
+ if (cache > 0) self.last_cache_read = @intCast(cache);
+ self.recordCost(usageInt(u, "prompt_tokens") - cache, cache, usageInt(u, "completion_tokens"));
+ },
+ // codex uses recordUsageResponses on its own path.
+ .responses => {},
+ }
+}
+
+/// An integer usage field, or 0 if absent / wrong type.
+pub fn usageInt(obj: std.json.ObjectMap, name: []const u8) i64 {
+ if (obj.get(name)) |v| if (v == .integer) return v.integer;
+ return 0;
+}
+
+/// Record one request's usage into the session-wide tally (g_cost):
+/// token counts always; USD only for API-key providers with a
+/// price_table row. Subscription providers (codex, claude) bill flat
+/// and tally as sub_calls; unpriced models as unpriced_calls.
+pub fn recordCost(self: *Agent, uncached_in: i64, cache_in: i64, out: i64) void {
+ g_cost.add(self.io, self.provider.id, self.provider.model, uncached_in, cache_in, out);
+}
+
+pub const ResponsesResult = union(enum) { ok: std.json.ObjectMap, err: []const u8 };
+
+/// Pull the final `response` object out of a Codex SSE stream. Scans
+/// `data:` lines for the last `response.completed`/`response.incomplete`
+/// event; reports `response.failed`/`error` events or a plain JSON error
+/// body as an error.
+pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
+ // The final output items arrive as individual `response.output_item.done`
+ // events; `response.completed` carries usage but an empty output array.
+ // Collect the done-items and synthesize a {output, usage} object.
+ var items = std.json.Array.init(self.arena);
+ var usage: ?Value = null;
+ var saw_completed = false;
+ var err_msg: ?[]const u8 = null;
+ var it = std.mem.tokenizeScalar(u8, body, '\n');
+ while (it.next()) |raw_line| {
+ const line = std.mem.trim(u8, raw_line, " \r");
+ if (!std.mem.startsWith(u8, line, "data:")) continue;
+ const payload = std.mem.trim(u8, line["data:".len..], " ");
+ if (payload.len == 0 or std.mem.eql(u8, payload, "[DONE]")) continue;
+ const v = std.json.parseFromSliceLeaky(Value, self.arena, payload, .{ .allocate = .alloc_always }) catch continue;
+ if (v != .object) continue;
+ const t = v.object.get("type") orelse continue;
+ if (t != .string) continue;
+ if (std.mem.eql(u8, t.string, "response.output_item.done")) {
+ if (v.object.get("item")) |item| try items.append(item);
+ } else if (std.mem.eql(u8, t.string, "response.completed") or std.mem.eql(u8, t.string, "response.incomplete")) {
+ saw_completed = true;
+ if (v.object.get("response")) |r| if (r == .object) {
+ if (r.object.get("usage")) |u| usage = u;
+ };
+ } else if (std.mem.eql(u8, t.string, "response.failed") or std.mem.eql(u8, t.string, "error")) {
+ err_msg = errorMessage(v.object) orelse "codex stream reported a failure";
+ }
+ }
+ if (saw_completed or items.items.len > 0) {
+ var resp: std.json.ObjectMap = .empty;
+ try resp.put(self.arena, "output", .{ .array = items });
+ if (usage) |u| try resp.put(self.arena, "usage", u);
+ return .{ .ok = resp };
+ }
+ if (err_msg) |m| return .{ .err = m };
+ // Not an SSE stream — maybe a JSON error body (401, rate limit, …).
+ const v = std.json.parseFromSliceLeaky(Value, self.arena, body, .{ .allocate = .alloc_always }) catch return error.Unparseable;
+ if (v == .object) if (errorMessage(v.object)) |m| return .{ .err = m };
+ return error.Unparseable;
+}
+
+pub fn errorMessage(obj: std.json.ObjectMap) ?[]const u8 {
+ if (obj.get("error")) |e| {
+ if (e == .object) {
+ if (e.object.get("message")) |m| if (m == .string) return m.string;
+ } else if (e == .string) return e.string;
+ }
+ if (obj.get("response")) |r| if (r == .object) {
+ if (r.object.get("error")) |e| if (e == .object) {
+ if (e.object.get("message")) |m| if (m == .string) return m.string;
+ };
+ };
+ if (obj.get("detail")) |d| if (d == .string) return d.string;
+ if (obj.get("message")) |m| if (m == .string) return m.string;
+ return null;
+}
+
+pub fn recordUsageResponses(self: *Agent, response: std.json.ObjectMap) void {
+ self.last_cache_read = 0;
+ const usage = response.get("usage") orelse return;
+ if (usage != .object) return;
+ const u = usage.object;
+ const in_tokens = usageInt(u, "input_tokens");
+ const out_tokens = usageInt(u, "output_tokens");
+ const total_tokens = usageInt(u, "total_tokens");
+ if (total_tokens > 0) {
+ self.last_context_tokens = @intCast(total_tokens);
+ } else {
+ // Some Codex/Responses builds report only input/output counts.
+ // Still surface the prompt token counter instead of leaving the
+ // prompt stuck at "model · sub" with no context usage.
+ const computed_total = in_tokens + out_tokens;
+ if (computed_total > 0) self.last_context_tokens = @intCast(computed_total);
+ }
+ var cached: i64 = 0;
+ if (u.get("input_tokens_details")) |d| if (d == .object) {
+ cached = usageInt(d.object, "cached_tokens");
+ if (cached > 0) self.last_cache_read = @intCast(cached);
+ };
+ self.recordCost(in_tokens - cached, cached, out_tokens);
+}
+
+pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bool, stream_usage: bool) ![]u8 {
+ var aw: Io.Writer.Allocating = .init(self.gpa);
+ errdefer aw.deinit();
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.beginObject();
+ try s.objectField("model");
+ try s.write(self.provider.model);
+ switch (self.provider.kind) {
+ .anthropic => {
+ try s.objectField("max_tokens");
+ try s.write(max_tokens);
+ if (stream) {
+ try s.objectField("stream");
+ try s.write(true);
+ }
+ // Forced tool_choice conflicts with adaptive thinking; skip
+ // thinking only when forcing.
+ if (!force_tool) {
+ try s.objectField("thinking");
+ try s.print("{s}", .{"{\"type\":\"adaptive\"}"});
+ }
+ // Prompt caching (Anthropic): a cache_control breakpoint on the
+ // system block caches the whole stable prefix (system + tools).
+ // Must be block-level — a top-level cache_control is invalid.
+ // Other anthropic-format providers (minimax) get a plain
+ // string, since cache_control isn't part of their API.
+ try s.objectField("system");
+ const cc = "{\"type\":\"ephemeral\"}";
+ if (std.mem.eql(u8, self.provider.id, "anthropic")) {
+ try s.beginArray();
+ try s.beginObject();
+ try s.objectField("type");
+ try s.write("text");
+ try s.objectField("text");
+ try s.write(self.systemPrompt());
+ try s.objectField("cache_control");
+ try s.print("{s}", .{cc});
+ try s.endObject();
+ try s.endArray();
+ } else {
+ try s.write(self.systemPrompt());
+ }
+ if (tools) |t| {
+ try s.objectField("tools");
+ try s.print("{s}", .{t});
+ if (force_tool) {
+ try s.objectField("tool_choice");
+ try s.print("{s}", .{"{\"type\":\"any\"}"});
+ }
+ }
+ try s.objectField("messages");
+ // Cache the conversation prefix too (not just system) on the real
+ // Anthropic API: a rolling cache_control breakpoint on the last
+ // message. minimax (anthropic-format, no cache_control) is excluded.
+ const cache_msgs = std.mem.eql(u8, self.provider.id, "anthropic");
+ try writeAnthropicMessages(&s, self.messages, cache_msgs);
+ },
+ .openai => {
+ // graff's MakeOpenAiCompat: OpenAI deprecated max_tokens in
+ // favor of max_completion_tokens — send the new name to the
+ // direct OpenAI API, and to any provider that rejected the
+ // old one (cap_new, learned via the retry in request()).
+ const cap_field = if (std.mem.eql(u8, self.provider.id, "openai") or self.cap_new)
+ "max_completion_tokens"
+ else
+ "max_tokens";
+ try s.objectField(cap_field);
+ try s.write(max_tokens);
+ if (stream) {
+ try s.objectField("stream");
+ try s.write(true);
+ // Without include_usage the stream carries no token
+ // counts (context tracking + auto-compaction need them).
+ if (stream_usage) {
+ try s.objectField("stream_options");
+ try s.print("{s}", .{"{\"include_usage\":true}"});
+ }
+ }
+ if (tools) |t| {
+ try s.objectField("tools");
+ try s.print("{s}", .{t});
+ if (force_tool) {
+ try s.objectField("tool_choice");
+ try s.write("required");
+ }
+ }
+ try s.objectField("messages");
+ try s.beginArray();
+ try s.beginObject();
+ try s.objectField("role");
+ try s.write("system");
+ try s.objectField("content");
+ try s.write(self.systemPrompt());
+ try s.endObject();
+ for (self.messages.items) |m| try writeOpenAIMessageNormalized(&s, m);
+ try s.endArray();
+ // Reasoning-effort hint for OpenAI-compatible providers that
+ // honor it (codegraff gateway, deepseek). Mirrors the
+ // Responses `reasoning.effort` set in the branch below.
+ if (self.effortApplies() and !self.effort_rejected) {
+ try s.objectField("reasoning_effort");
+ try s.write(@tagName(self.reasoning));
+ }
+ // Kimi K2.7's model card recommends temperature 1.0 + top_p 0.95
+ // for its (always-on) Thinking mode; graff otherwise leaves
+ // sampling to the server default.
+ if (std.mem.eql(u8, self.provider.id, "kimi")) {
+ try s.objectField("temperature");
+ try s.write(@as(f64, 1.0));
+ try s.objectField("top_p");
+ try s.write(@as(f64, 0.95));
+ }
+ },
+ .responses => {
+ // Codex / ChatGPT Responses API. system prompt → instructions;
+ // history items are valid input items; stream is required by
+ // the backend (we buffer + parse the SSE). reasoning items are
+ // returned encrypted and passed back for cross-turn continuity.
+ try s.objectField("instructions");
+ try s.write(self.systemPrompt());
+ try s.objectField("input");
+ try s.write(Value{ .array = self.messages });
+ if (tools) |t| {
+ try s.objectField("tools");
+ try s.print("{s}", .{t});
+ try s.objectField("tool_choice");
+ try s.write(if (force_tool) "required" else "auto");
+ try s.objectField("parallel_tool_calls");
+ try s.write(true);
+ }
+ // Codex "fast" mode (/fast): request the priority service
+ // tier for lower latency. This branch is codex-only, so it is
+ // never emitted for other providers.
+ if (self.fast) {
+ try s.objectField("service_tier");
+ try s.write("priority");
+ }
+ try s.objectField("reasoning");
+ try s.beginObject();
+ try s.objectField("effort");
+ try s.write(@tagName(self.reasoning));
+ try s.endObject();
+ try s.objectField("include");
+ try s.beginArray();
+ try s.write("reasoning.encrypted_content");
+ try s.endArray();
+ try s.objectField("store");
+ try s.write(false);
+ try s.objectField("stream");
+ try s.write(true);
+ },
+ }
+ try s.endObject();
+ return aw.toOwnedSlice();
+}
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
new file mode 100644
index 00000000..5f1b30a0
--- /dev/null
+++ b/src/agent_steps.zig
@@ -0,0 +1,388 @@
+//! Non-streaming response parsing: turn a provider's JSON response (or a
+//! reassembled SSE stream) into next-turn messages + extracted tool calls,
+//! run those tools, and return the turn's final text (or null to loop
+//! again). One step* per wire format (Anthropic Messages, OpenAI chat
+//! completions, OpenAI Responses — the last lives in agent_request.zig
+//! since it shares ResponsesResult/parseResponses); one assemble* per
+//! streaming wire format that needs a full body reassembled before the
+//! step functions can run on it. Split out of the Agent struct (#123,
+//! 600-line goal).
+
+const std = @import("std");
+const Value = std.json.Value;
+
+const main_mod = @import("main.zig");
+const Agent = main_mod.Agent;
+const ToolCall = main_mod.ToolCall;
+
+const messages_mod = @import("messages.zig");
+const toolResultMessage = messages_mod.toolResultMessage;
+
+// ssePayload/sseIndex live in agent_stream.zig; reached through the Agent
+// struct's member aliases.
+const ssePayload = Agent.ssePayload;
+const sseIndex = Agent.sseIndex;
+
+/// Consume a Codex `response` object: append its output items to history
+/// (verbatim — they're valid Responses input items), surface text, and
+/// collect any function calls. Returns final text when no tools were
+/// called, else null to loop after running them.
+pub fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {
+ const output = response.get("output") orelse return error.ApiError;
+ if (output != .array) return error.ApiError;
+
+ var calls: std.ArrayList(ToolCall) = .empty;
+ defer calls.deinit(self.gpa);
+ var final_text: []const u8 = "";
+
+ for (output.array.items) |item| {
+ if (item != .object) continue;
+ try self.messages.append(item); // valid as next-turn input
+ const itype = if (item.object.get("type")) |t| (if (t == .string) t.string else "") else "";
+ if (std.mem.eql(u8, itype, "message")) {
+ if (item.object.get("content")) |c| if (c == .array) {
+ for (c.array.items) |block| {
+ if (block != .object) continue;
+ const bt = if (block.object.get("type")) |x| (if (x == .string) x.string else "") else "";
+ if (std.mem.eql(u8, bt, "output_text")) {
+ if (block.object.get("text")) |txt| if (txt == .string) {
+ final_text = txt.string;
+ if (!self.sub and !self.streamed_text) try self.say("{s}\n", .{txt.string});
+ };
+ }
+ }
+ };
+ } else if (std.mem.eql(u8, itype, "function_call")) {
+ const name = if (item.object.get("name")) |n| (if (n == .string) n.string else continue) else continue;
+ const call_id = if (item.object.get("call_id")) |c| (if (c == .string) c.string else continue) else continue;
+ const args = if (item.object.get("arguments")) |a| (if (a == .string) a.string else "") else "";
+ const input: Value = if (args.len == 0)
+ .{ .object = .empty }
+ else
+ std.json.parseFromSliceLeaky(Value, self.arena, args, .{ .allocate = .alloc_always }) catch .{ .object = .empty };
+ try calls.append(self.gpa, .{ .id = call_id, .name = name, .input = input });
+ }
+ }
+
+ if (calls.items.len > 0) {
+ const results = try self.runTools(calls.items);
+ for (calls.items, results) |call, r| {
+ const fco = try toolResultMessage(self.arena, .responses, call.id, r.text, r.is_error);
+ try self.messages.append(fco);
+ }
+ if (self.completed) |result| return result;
+ return null;
+ }
+ return final_text;
+}
+
+pub fn stepAnthropic(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
+ const content = root.get("content") orelse {
+ try self.say("[api error: response had no content]\n", .{});
+ return error.ApiError;
+ };
+ if (content != .array) {
+ try self.say("[api error: malformed content block]\n", .{});
+ return error.ApiError;
+ }
+ const stop_reason = if (root.get("stop_reason")) |s| (if (s == .string) s.string else "") else "";
+
+ var assistant: std.json.ObjectMap = .empty;
+ try assistant.put(self.arena, "role", .{ .string = "assistant" });
+ try assistant.put(self.arena, "content", content);
+ try self.messages.append(.{ .object = assistant });
+
+ var calls: std.ArrayList(ToolCall) = .empty;
+ defer calls.deinit(self.gpa);
+ var final_text: []const u8 = "";
+ for (content.array.items) |block| {
+ if (block != .object) continue;
+ const kind = if (block.object.get("type")) |t| (if (t == .string) t.string else "") else "";
+ if (std.mem.eql(u8, kind, "text")) {
+ if (block.object.get("text")) |tx| if (tx == .string) {
+ final_text = tx.string;
+ if (!self.sub and !self.streamed_text) try self.say("{s}\n", .{final_text});
+ };
+ } else if (std.mem.eql(u8, kind, "tool_use")) {
+ const name = if (block.object.get("name")) |n| (if (n == .string) n.string else "") else "";
+ if (name.len == 0) continue;
+ const id = if (block.object.get("id")) |x| (if (x == .string) x.string else "") else "";
+ const input = block.object.get("input") orelse Value{ .object = .empty };
+ try calls.append(self.gpa, .{ .id = id, .name = name, .input = input });
+ }
+ }
+
+ if (calls.items.len > 0) {
+ const results = try self.runTools(calls.items);
+ var blocks = std.json.Array.init(self.arena);
+ for (calls.items, results) |call, r| {
+ const tr = try toolResultMessage(self.arena, .anthropic, call.id, r.text, r.is_error);
+ try blocks.append(tr);
+ }
+ var user_msg: std.json.ObjectMap = .empty;
+ try user_msg.put(self.arena, "role", .{ .string = "user" });
+ try user_msg.put(self.arena, "content", .{ .array = blocks });
+ try self.messages.append(.{ .object = user_msg });
+
+ if (self.completed) |result| return result;
+ return null; // loop again
+ }
+
+ if (std.mem.eql(u8, stop_reason, "pause_turn")) return null;
+ if (!std.mem.eql(u8, stop_reason, "end_turn")) try self.say("[stopped: {s}]\n", .{stop_reason});
+ return final_text;
+}
+
+pub fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
+ const choices = root.get("choices");
+ if (choices == null or choices.? != .array or choices.?.array.items.len == 0 or choices.?.array.items[0] != .object) {
+ try self.say("[api error: response had no choices]\n", .{});
+ return error.ApiError;
+ }
+ const choice = choices.?.array.items[0].object;
+ const message = choice.get("message") orelse {
+ try self.say("[api error: choice had no message]\n", .{});
+ return error.ApiError;
+ };
+ try self.messages.append(message); // echo verbatim (content may be null)
+
+ var final_text: []const u8 = "";
+ if (message.object.get("content")) |c| if (c == .string and c.string.len > 0) {
+ final_text = c.string;
+ if (!self.sub and !self.streamed_text) try self.say("{s}\n", .{c.string});
+ };
+
+ var calls: std.ArrayList(ToolCall) = .empty;
+ defer calls.deinit(self.gpa);
+ if (message.object.get("tool_calls")) |tcs| if (tcs == .array) {
+ for (tcs.array.items) |tc| {
+ if (tc != .object) continue;
+ const function = tc.object.get("function") orelse continue;
+ if (function != .object) continue;
+ const args_str = if (function.object.get("arguments")) |a| (if (a == .string) a.string else "") else "";
+ const input: Value = if (args_str.len == 0)
+ .{ .object = .empty }
+ else
+ (std.json.parseFromSliceLeaky(Value, self.arena, args_str, .{ .allocate = .alloc_always }) catch .{ .object = .empty });
+ const name = if (function.object.get("name")) |n| (if (n == .string) n.string else "") else "";
+ if (name.len == 0) continue; // can't dispatch a nameless call
+ const id = if (tc.object.get("id")) |x| (if (x == .string) x.string else "") else "";
+ try calls.append(self.gpa, .{ .id = id, .name = name, .input = input });
+ }
+ };
+
+ if (calls.items.len > 0) {
+ const results = try self.runTools(calls.items);
+ for (calls.items, results) |call, r| {
+ const tool_msg = try toolResultMessage(self.arena, .openai, call.id, r.text, r.is_error);
+ try self.messages.append(tool_msg);
+ }
+ if (self.completed) |result| return result;
+ return null;
+ }
+
+ const finish = choice.get("finish_reason").?;
+ if (finish == .string and !std.mem.eql(u8, finish.string, "stop")) try self.say("[stopped: {s}]\n", .{finish.string});
+ return final_text;
+}
+
+/// Reassemble a streamed SSE body into the non-streaming response shape
+/// the step functions expect. Returns null when the body contains no SSE
+/// events (a plain JSON body — error envelope, or a provider that
+/// ignored `stream`); the caller falls back to regular parsing.
+pub fn assembleStream(self: *Agent, body: []const u8) !?std.json.ObjectMap {
+ return switch (self.provider.kind) {
+ .anthropic => self.assembleAnthropic(body),
+ .openai => self.assembleOpenAI(body),
+ .responses => unreachable, // parseResponses owns this path
+ };
+}
+
+/// One in-flight content block while reassembling an Anthropic stream.
+const BlockAcc = struct {
+ obj: std.json.ObjectMap = .empty,
+ text: std.ArrayList(u8) = .empty,
+ json: std.ArrayList(u8) = .empty,
+ thinking: std.ArrayList(u8) = .empty,
+ signature: std.ArrayList(u8) = .empty,
+};
+
+/// message_start carries the message skeleton (role, model, input-token
+/// usage); content blocks open with content_block_start and accumulate
+/// via content_block_delta (text / partial_json / thinking / signature);
+/// message_delta carries stop_reason and output-token usage.
+pub fn assembleAnthropic(self: *Agent, body: []const u8) !?std.json.ObjectMap {
+ var root: ?std.json.ObjectMap = null;
+ var blocks: std.ArrayList(BlockAcc) = .empty;
+ var stop_reason: ?Value = null;
+ var usage_delta: ?Value = null;
+ var it = std.mem.tokenizeScalar(u8, body, '\n');
+ while (it.next()) |raw_line| {
+ const payload = ssePayload(raw_line) orelse continue;
+ const v = std.json.parseFromSliceLeaky(Value, self.arena, payload, .{ .allocate = .alloc_always }) catch continue;
+ if (v != .object) continue;
+ const t = v.object.get("type") orelse continue;
+ if (t != .string) continue;
+ if (std.mem.eql(u8, t.string, "message_start")) {
+ if (v.object.get("message")) |m| if (m == .object) {
+ root = m.object;
+ };
+ } else if (std.mem.eql(u8, t.string, "content_block_start")) {
+ const idx = sseIndex(v.object) orelse continue;
+ while (blocks.items.len <= idx) try blocks.append(self.arena, .{});
+ if (v.object.get("content_block")) |cb| if (cb == .object) {
+ blocks.items[idx].obj = cb.object;
+ };
+ } else if (std.mem.eql(u8, t.string, "content_block_delta")) {
+ const idx = sseIndex(v.object) orelse continue;
+ if (idx >= blocks.items.len) continue;
+ const d = v.object.get("delta") orelse continue;
+ if (d != .object) continue;
+ const b = &blocks.items[idx];
+ if (d.object.get("text")) |x| if (x == .string) try b.text.appendSlice(self.arena, x.string);
+ if (d.object.get("partial_json")) |x| if (x == .string) try b.json.appendSlice(self.arena, x.string);
+ if (d.object.get("thinking")) |x| if (x == .string) try b.thinking.appendSlice(self.arena, x.string);
+ if (d.object.get("signature")) |x| if (x == .string) try b.signature.appendSlice(self.arena, x.string);
+ } else if (std.mem.eql(u8, t.string, "message_delta")) {
+ if (v.object.get("delta")) |d| if (d == .object) {
+ if (d.object.get("stop_reason")) |sr| if (sr == .string) {
+ stop_reason = sr;
+ };
+ };
+ if (v.object.get("usage")) |u| if (u == .object) {
+ usage_delta = u;
+ };
+ } else if (std.mem.eql(u8, t.string, "error")) {
+ // Hand the envelope back as the root: request()'s existing
+ // type=="error" check reports it.
+ return v.object;
+ }
+ }
+ var r = root orelse return null;
+ var content = std.json.Array.init(self.arena);
+ for (blocks.items) |*b| {
+ if (b.obj.get("type") == null) continue; // never started
+ if (b.text.items.len > 0) try b.obj.put(self.arena, "text", .{ .string = b.text.items });
+ if (b.thinking.items.len > 0) try b.obj.put(self.arena, "thinking", .{ .string = b.thinking.items });
+ if (b.signature.items.len > 0) try b.obj.put(self.arena, "signature", .{ .string = b.signature.items });
+ if (b.json.items.len > 0) {
+ const input = std.json.parseFromSliceLeaky(Value, self.arena, b.json.items, .{ .allocate = .alloc_always }) catch Value{ .object = .empty };
+ try b.obj.put(self.arena, "input", input);
+ }
+ try content.append(.{ .object = b.obj });
+ }
+ try r.put(self.arena, "content", .{ .array = content });
+ try r.put(self.arena, "stop_reason", stop_reason orelse Value{ .string = "end_turn" });
+ if (usage_delta) |ud| {
+ var usage: std.json.ObjectMap = .empty;
+ if (r.get("usage")) |base| if (base == .object) {
+ var e = base.object.iterator();
+ while (e.next()) |kv| try usage.put(self.arena, kv.key_ptr.*, kv.value_ptr.*);
+ };
+ var e = ud.object.iterator();
+ while (e.next()) |kv| try usage.put(self.arena, kv.key_ptr.*, kv.value_ptr.*);
+ try r.put(self.arena, "usage", .{ .object = usage });
+ }
+ return r;
+}
+
+/// One in-flight tool call while reassembling an OpenAI chat stream;
+/// id and function.name arrive on the first fragment, arguments
+/// accumulate across fragments keyed by index.
+const CallAcc = struct {
+ id: []const u8 = "",
+ name: []const u8 = "",
+ args: std.ArrayList(u8) = .empty,
+};
+
+pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
+ var content: std.ArrayList(u8) = .empty;
+ var reasoning_content: std.ArrayList(u8) = .empty;
+ var reasoning: std.ArrayList(u8) = .empty;
+ var calls: std.ArrayList(CallAcc) = .empty;
+ var role: []const u8 = "assistant";
+ var finish: ?Value = null;
+ var usage: ?Value = null;
+ var saw_chunk = false;
+ var it = std.mem.tokenizeScalar(u8, body, '\n');
+ while (it.next()) |raw_line| {
+ const payload = ssePayload(raw_line) orelse continue;
+ const v = std.json.parseFromSliceLeaky(Value, self.arena, payload, .{ .allocate = .alloc_always }) catch continue;
+ if (v != .object) continue;
+ // The final usage chunk (stream_options.include_usage) may have
+ // an empty choices array.
+ if (v.object.get("usage")) |u| if (u == .object) {
+ usage = u;
+ saw_chunk = true;
+ };
+ const choices = v.object.get("choices") orelse continue;
+ if (choices != .array or choices.array.items.len == 0) continue;
+ const c0 = choices.array.items[0];
+ if (c0 != .object) continue;
+ saw_chunk = true;
+ if (c0.object.get("finish_reason")) |fr| if (fr == .string) {
+ finish = fr;
+ };
+ const d = c0.object.get("delta") orelse continue;
+ if (d != .object) continue;
+ if (d.object.get("role")) |x| if (x == .string) {
+ role = x.string;
+ };
+ if (d.object.get("content")) |x| if (x == .string) try content.appendSlice(self.arena, x.string);
+ if (d.object.get("reasoning_content")) |x| if (x == .string) try reasoning_content.appendSlice(self.arena, x.string);
+ if (d.object.get("reasoning")) |x| if (x == .string) try reasoning.appendSlice(self.arena, x.string);
+ if (d.object.get("tool_calls")) |tcs| if (tcs == .array) {
+ for (tcs.array.items) |tc| {
+ if (tc != .object) continue;
+ const idx: usize = blk: {
+ if (tc.object.get("index")) |ix| if (ix == .integer and ix.integer >= 0) break :blk @intCast(ix.integer);
+ // No index: a fresh id opens a new call, otherwise
+ // the fragment continues the latest one.
+ break :blk if (tc.object.get("id") != null or calls.items.len == 0) calls.items.len else calls.items.len - 1;
+ };
+ while (calls.items.len <= idx) try calls.append(self.arena, .{});
+ const acc = &calls.items[idx];
+ if (tc.object.get("id")) |x| if (x == .string and x.string.len > 0) {
+ acc.id = x.string;
+ };
+ if (tc.object.get("function")) |f| if (f == .object) {
+ if (f.object.get("name")) |x| if (x == .string and x.string.len > 0) {
+ acc.name = x.string;
+ };
+ if (f.object.get("arguments")) |x| if (x == .string) try acc.args.appendSlice(self.arena, x.string);
+ };
+ }
+ };
+ }
+ if (!saw_chunk) return null;
+
+ var message: std.json.ObjectMap = .empty;
+ try message.put(self.arena, "role", .{ .string = role });
+ try message.put(self.arena, "content", if (content.items.len > 0) Value{ .string = content.items } else .null);
+ if (reasoning_content.items.len > 0) try message.put(self.arena, "reasoning_content", .{ .string = reasoning_content.items });
+ if (reasoning.items.len > 0) try message.put(self.arena, "reasoning", .{ .string = reasoning.items });
+ if (calls.items.len > 0) {
+ var tcs = std.json.Array.init(self.arena);
+ for (calls.items) |c| {
+ if (c.id.len == 0 and c.name.len == 0) continue;
+ var function: std.json.ObjectMap = .empty;
+ try function.put(self.arena, "name", .{ .string = c.name });
+ try function.put(self.arena, "arguments", .{ .string = c.args.items });
+ var tc: std.json.ObjectMap = .empty;
+ try tc.put(self.arena, "id", .{ .string = c.id });
+ try tc.put(self.arena, "type", .{ .string = "function" });
+ try tc.put(self.arena, "function", .{ .object = function });
+ try tcs.append(.{ .object = tc });
+ }
+ if (tcs.items.len > 0) try message.put(self.arena, "tool_calls", .{ .array = tcs });
+ }
+ var choice: std.json.ObjectMap = .empty;
+ try choice.put(self.arena, "message", .{ .object = message });
+ try choice.put(self.arena, "finish_reason", finish orelse Value{ .string = "stop" });
+ var choices = std.json.Array.init(self.arena);
+ try choices.append(.{ .object = choice });
+ var r: std.json.ObjectMap = .empty;
+ try r.put(self.arena, "choices", .{ .array = choices });
+ if (usage) |u| try r.put(self.arena, "usage", u);
+ return r;
+}
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
new file mode 100644
index 00000000..a895e5ad
--- /dev/null
+++ b/src/agent_stream.zig
@@ -0,0 +1,457 @@
+//! The live streaming path: the thinking spinner (spinnerTask/Start/Stop,
+//! an animated indicator while the model is silent), the live dimmed
+//! "Thinking" reasoning block (streamThinking/closeThinkingBlock/
+//! toggleThinkingFold), and postStream itself — the root agent's
+//! streaming POST, racing send/receive/read against stall watchdogs,
+//! printing text deltas (printDelta) as they arrive. The highest-
+//! entanglement piece of the Agent struct (#123, 600-line goal); extracted
+//! last, after agent_request/agent_steps/agent_argstream/agent_render/
+//! agent_interrupt so it can sibling-import them directly.
+//!
+//! Agent.g_spin_stop/Agent.g_spin_future are struct-level `pub var`s that stay
+//! declared directly inside the Agent struct in main.zig (never alias a
+//! `var`) — reached here as `Agent.Agent.g_spin_stop`/`Agent.Agent.g_spin_future`.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+
+const main_mod = @import("main.zig");
+const Agent = main_mod.Agent;
+
+const ansi = @import("ansi.zig");
+const style = &ansi.style;
+
+const anim = @import("anim.zig");
+
+const terminal = @import("term.zig");
+const tty = terminal.tty;
+const termCols = terminal.termCols;
+const termRows = terminal.termRows;
+const advanceThinkingRows = terminal.advanceThinkingRows;
+
+const title_mod = @import("title.zig");
+const reasoningDelta = title_mod.reasoningDelta;
+
+const http = @import("http.zig");
+const providerUserAgent = http.providerUserAgent;
+const providerHeaders = http.providerHeaders;
+const capture5xxBodyStream = http.capture5xxBodyStream;
+const WatchdogFired = http.WatchdogFired;
+const sendHeadTask = http.sendHeadTask;
+const headStallTask = http.headStallTask;
+const streamLineTask = http.streamLineTask;
+const streamStallTask = http.streamStallTask;
+
+// escPressed/drainSteerStdin/rawNonblockStdin/ssePayload live in
+// agent_interrupt.zig; reached through the Agent struct's member aliases.
+const escPressed = Agent.escPressed;
+const drainSteerStdin = Agent.drainSteerStdin;
+const rawNonblockStdin = Agent.rawNonblockStdin;
+const ssePayload = Agent.ssePayload;
+
+pub fn spinnerTask(io: Io) void {
+ var i: usize = 0;
+ var buf: [512]u8 = undefined;
+ var w = Io.File.stdout().writer(io, &buf);
+ while (!Agent.g_spin_stop.load(.acquire)) {
+ if (main_mod.g_steer_visible.load(.acquire)) {
+ io.sleep(.fromMilliseconds(20), .awake) catch break;
+ continue;
+ }
+ // Clear-then-draw each frame: animations may vary in width.
+ w.interface.writeAll("\r\x1b[2K\x1b[?7l") catch return; // ?7l: autowrap off so a wide spinner truncates instead of wrapping in a narrow window (the "goes on and on" bug)
+ anim.anims[anim.g_anim_current].frame(&w.interface, i) catch return;
+ w.interface.writeAll("\x1b[?7h") catch return; // restore autowrap
+ w.interface.flush() catch return;
+ i += 1;
+ var t: usize = 0;
+ while (t < 4 and !Agent.g_spin_stop.load(.acquire)) : (t += 1) {
+ if (main_mod.g_steer_visible.load(.acquire)) break;
+ io.sleep(.fromMilliseconds(20), .awake) catch break;
+ }
+ }
+ if (!main_mod.g_steer_visible.load(.acquire)) {
+ w.interface.writeAll("\x1b[?7h\r\x1b[2K") catch return; // restore autowrap + clear
+ w.interface.flush() catch {};
+ }
+}
+
+pub fn spinnerStart(self: *Agent) void {
+ if (self.sub or main_mod.json_mode or !main_mod.use_color or self.out == null) return;
+ if (anim.g_anim_off) return;
+ if (Agent.g_spin_future != null) return;
+ anim.selectSpinner(self.io);
+ Agent.g_spin_stop.store(false, .release);
+ Agent.g_spin_future = self.io.concurrent(spinnerTask, .{self.io}) catch blk: {
+ Agent.g_spin_stop.store(true, .release); // no spare concurrency: skip quietly
+ break :blk null;
+ };
+}
+
+pub fn spinnerStop(self: *Agent) void {
+ if (self.sub) return; // root-only state — subs run on pool threads
+ if (Agent.g_spin_future) |*f| {
+ Agent.g_spin_stop.store(true, .release);
+ f.await(self.io);
+ Agent.g_spin_future = null;
+ }
+}
+
+/// Stream a chunk of the model's reasoning into a live, dimmed "Thinking"
+/// block in the terminal, opening the block (and handing the line off from
+/// the spinner) on the first chunk. Gated by /thinking; when off the block is
+/// never opened and the spinner stands in for it. We track the block's
+/// on-screen height as it streams so closeThinkingBlock can collapse it to a
+/// one-line summary when the answer starts (#75).
+pub fn streamThinking(self: *Agent, chunk: []const u8) void {
+ const w = self.out orelse return;
+ if (!self.thinking_open) {
+ self.spinnerStop();
+ w.print("{s}▼ Thinking{s}\n{s}", .{ style.dim, style.reset, style.dim }) catch return;
+ self.thinking_open = true;
+ main_mod.g_thinking_open = true;
+ self.thinking_rows = 1; // the header newline already moved us down one line
+ self.thinking_col = 0;
+ self.thinking_overflow = false;
+ }
+ self.thinking_text.appendSlice(self.gpa, chunk) catch {};
+ if (self.thinking_folded) return; // folded: buffer only, don't draw the live block
+ w.writeAll(chunk) catch return;
+ w.flush() catch return;
+ advanceThinkingRows(&self.thinking_rows, &self.thinking_col, termCols(), chunk);
+ if (self.thinking_rows + 1 >= termRows()) self.thinking_overflow = true;
+}
+
+/// Close an open "Thinking" block. If it still fits on screen, collapse it in
+/// place to a one-line "Thought" summary (#75); if it has scrolled off
+/// (overflow) leave the reasoning and just append the summary, so we never
+/// erase the user's earlier output. Runs on the reasoning->answer transition
+/// and at stream end.
+pub fn closeThinkingBlock(self: *Agent) void {
+ if (!self.thinking_open) return;
+ self.thinking_open = false;
+ main_mod.g_thinking_open = false;
+ self.thinking_folded = false;
+ const w = self.out orelse return;
+ if (!self.thinking_overflow and self.thinking_rows >= 1 and main_mod.use_color) {
+ w.print("\x1b[{d}F\x1b[0J{s}✓ Thought{s}\n\n", .{ self.thinking_rows, style.dim, style.reset }) catch return;
+ } else {
+ w.print("{s}\n{s}✓ Thought{s}\n\n", .{ style.reset, style.dim, style.reset }) catch return;
+ }
+ w.flush() catch return;
+}
+
+/// Ctrl-T: fold/unfold the live "Thinking" block in place (#92/#85). Only
+/// acts on an open, on-screen block; folding erases it to a one-line marker,
+/// unfolding re-streams the buffered reasoning. Cursor math mirrors
+/// closeThinkingBlock (erase `thinking_rows` lines up, clear to end).
+pub fn toggleThinkingFold(self: *Agent) void {
+ if (!self.thinking_open or self.thinking_overflow or !main_mod.use_color) return;
+ const w = self.out orelse return;
+ if (!self.thinking_folded) {
+ w.print("\x1b[{d}F\x1b[0J{s}▶ Thinking (folded · ^T){s}\n", .{ self.thinking_rows, style.dim, style.reset }) catch return;
+ self.thinking_folded = true;
+ self.thinking_rows = 1;
+ self.thinking_col = 0;
+ } else {
+ w.print("\x1b[1F\x1b[0J{s}▼ Thinking{s}\n{s}", .{ style.dim, style.reset, style.dim }) catch return;
+ self.thinking_folded = false;
+ self.thinking_rows = 1;
+ self.thinking_col = 0;
+ w.writeAll(self.thinking_text.items) catch return;
+ advanceThinkingRows(&self.thinking_rows, &self.thinking_col, termCols(), self.thinking_text.items);
+ }
+ w.flush() catch return;
+}
+
+pub fn postStream(self: *Agent, body: []const u8) ![]u8 {
+ self.spinnerStart();
+ defer self.spinnerStop();
+ self.thinking_open = false; // fresh "Thinking" block state per request
+ main_mod.g_thinking_open = false;
+ self.thinking_rows = 0;
+ self.thinking_col = 0;
+ self.thinking_folded = false;
+ self.thinking_text.clearRetainingCapacity();
+ self.thinking_overflow = false;
+ defer self.closeThinkingBlock(); // close a reasoning-only turn's block
+ const gpa = self.gpa;
+ const provider = self.provider;
+ const bearer = switch (provider.auth) {
+ .x_api_key => "",
+ .bearer => try std.fmt.allocPrint(gpa, "Bearer {s}", .{provider.api_key}),
+ };
+ defer if (bearer.len > 0) gpa.free(bearer);
+ var headers_buf: [6]std.http.Header = undefined;
+ const extra = providerHeaders(provider, bearer, &headers_buf);
+
+ self.md_buf.clearRetainingCapacity(); // fresh markdown state per stream
+ self.arg_live = .{}; // fresh tool-argument extractor per stream
+ self.md_fence = false;
+ self.md_kind = .classify;
+ self.md_span = .normal;
+ self.md_word.clearRetainingCapacity();
+ self.md_word_vis = 0;
+ self.md_col = 0;
+ self.md_indent = 0;
+ self.md_width = 0; // re-read the terminal width (resizes)
+ for (self.md_table.items) |r| gpa.free(r); // an errored stream can leave rows behind
+ self.md_table.clearRetainingCapacity();
+ self.partial_text.clearRetainingCapacity(); // fresh Esc-interrupt capture
+
+ // Esc-interrupt: while the root's request is on a TTY, stdin sits in
+ // raw non-blocking no-echo mode — from *before* the connect, so Esc
+ // pressed during a slow time-to-first-token wait neither echoes ^[
+ // nor leaks into the next prompt. Polled between SSE lines; leftover
+ // bytes are drained before canonical mode returns, so gate prompts
+ // and the line editor see a clean tty.
+ const watch_esc = !self.sub and self.in != null and main_mod.use_color and !main_mod.json_mode;
+ var orig_tio: ?tty.RawState = null;
+ if (watch_esc) {
+ orig_tio = rawNonblockStdin();
+ // SGR mouse reporting is intentionally NOT enabled. Grabbing the mouse
+ // (\x1b[?1000;1006h) makes the terminal forward wheel events to us instead
+ // of scrolling its own scrollback, so scrolling up mid-stream got captured
+ // as input. Leaving the mouse to the terminal keeps native scroll — parity
+ // with Claude Code. The live Thinking block still folds via Ctrl-T (see
+ // escPressed); its SGR click-to-fold path stays wired but dormant.
+ }
+ defer if (orig_tio) |o| {
+ _ = drainSteerStdin(true);
+ tty.restore(o);
+ };
+ var req = try self.client.request(.POST, try std.Uri.parse(provider.url), .{
+ .redirect_behavior = .unhandled,
+ .headers = .{
+ .content_type = .{ .override = "application/json" },
+ .user_agent = providerUserAgent(provider),
+ },
+ .extra_headers = extra,
+ });
+ defer req.deinit();
+ // A failed SEND leaves reader.state == .ready, which Request.deinit
+ // reads as "connection still clean" and returns it to the keep-alive
+ // pool — every retry (and every later turn) then pulls the same dead
+ // connection back out: HttpConnectionClosing once, WriteFailed
+ // forever after (observed in the wild). Poison it on any error so
+ // deinit discards it and the retry dials fresh.
+ errdefer if (req.connection) |conn| {
+ conn.closing = true;
+ };
+ // Race the send + head receive against a stall watchdog so a
+ // freshly-redialed connection that the server accepts but never
+ // answers can't hang the turn (issue #54: "retrying (1/3)" then
+ // "thinking… forever"). Mirrors the SSE line-loop and postWatched
+ // patterns. Falls back to a bare send+receiveHead (the old behavior)
+ // when no spare concurrency exists.
+ var response: std.http.Client.Response = undefined;
+ head: {
+ const HeadDone = union(enum) { sent: anyerror!void, stall: WatchdogFired };
+ var hd_buf: [2]HeadDone = undefined;
+ var hsel: Io.Select(HeadDone) = .init(self.io, &hd_buf);
+ hsel.concurrent(.sent, sendHeadTask, .{ &req, body, &response }) catch {
+ // No spare concurrency: accept the hang risk (existing behavior).
+ req.transfer_encoding = .{ .content_length = body.len };
+ var bw = try req.sendBodyUnflushed(&.{});
+ try bw.writer.writeAll(body);
+ try bw.end();
+ try req.connection.?.flush();
+ response = try req.receiveHead(&.{});
+ break :head;
+ };
+ hsel.concurrent(.stall, headStallTask, .{ self.io, orig_tio != null }) catch {
+ const r = hsel.await() catch |e| {
+ hsel.cancelDiscard();
+ return e;
+ };
+ hsel.cancelDiscard();
+ r.sent catch |e| {
+ return e;
+ };
+ break :head;
+ };
+ const first = hsel.await() catch |e| {
+ hsel.cancelDiscard();
+ return e;
+ };
+ hsel.cancelDiscard();
+ switch (first) {
+ .sent => |s| s catch |e| {
+ return e;
+ },
+ .stall => |w| {
+ if (req.connection) |conn| conn.closing = true;
+ return if (w == .esc) error.Interrupted else error.HungRequest;
+ },
+ }
+ }
+
+ // 429/5xx before any body: a retryable throttle — request() backs
+ // off and retries (surfaced in the trace as a "retry" note).
+ const status_code = @intFromEnum(response.head.status);
+ if (status_code == 429 or status_code >= 500) {
+ // Drain a snippet of the error body so the retry message can
+ // surface the gateway's diagnostic (e.g. "upstream timeout")
+ // instead of a bare "server error (5xx)".
+ capture5xxBodyStream(self.gpa, &response);
+ if (req.connection) |conn| conn.closing = true;
+ return if (status_code == 429) error.RateLimited else error.ServerError;
+ }
+ // Esc pressed while connecting / waiting for headers? Stop before
+ // reading any of the body.
+ if (orig_tio != null and escPressed(true)) {
+ if (req.connection) |conn| conn.closing = true;
+ return error.Interrupted;
+ }
+
+ const decompress_buffer: []u8 = switch (response.head.content_encoding) {
+ .identity => &.{},
+ .zstd => try gpa.alloc(u8, std.compress.zstd.default_window_len),
+ .deflate, .gzip => try gpa.alloc(u8, std.compress.flate.max_window_len),
+ .compress => return error.UnsupportedCompressionMethod,
+ };
+ defer if (decompress_buffer.len > 0) gpa.free(decompress_buffer);
+ var transfer_buffer: [64]u8 = undefined;
+ var decompress: std.http.Decompress = undefined;
+ const reader = response.readerDecompressing(&transfer_buffer, &decompress, decompress_buffer);
+
+ var full: Io.Writer.Allocating = .init(gpa);
+ errdefer full.deinit();
+ var line: Io.Writer.Allocating = .init(gpa);
+ defer line.deinit();
+
+ while (true) {
+ // Race the line read against an idle-stall watchdog so a dead
+ // stream can't hang the turn (the Esc escape below is TTY-only, so
+ // --json/GUI sessions would otherwise wait forever).
+ read: {
+ const ReadDone = union(enum) { line: anyerror!usize, stall: WatchdogFired };
+ var rd_buf: [2]ReadDone = undefined;
+ var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);
+ rsel.concurrent(.line, streamLineTask, .{ reader, &line.writer }) catch {
+ _ = try reader.streamDelimiterEnding(&line.writer, '\n'); // no spare concurrency
+ break :read;
+ };
+ rsel.concurrent(.stall, streamStallTask, .{ self.io, orig_tio != null }) catch {
+ const r = rsel.await() catch |e| {
+ rsel.cancelDiscard();
+ return e;
+ };
+ rsel.cancelDiscard();
+ _ = try r.line;
+ break :read;
+ };
+ const first = rsel.await() catch |e| {
+ rsel.cancelDiscard();
+ return e;
+ };
+ rsel.cancelDiscard();
+ switch (first) {
+ .line => |r| _ = try r,
+ .stall => |w| {
+ self.flushStreamTail();
+ if (req.connection) |conn| conn.closing = true;
+ if (w == .deadline and !main_mod.json_mode) if (self.out) |o| {
+ o.writeAll("\n⚠ stream stalled — ending turn\n") catch {};
+ o.flush() catch {};
+ };
+ return error.Interrupted;
+ },
+ }
+ }
+ // End of stream leaves the reader empty; otherwise the '\n' is
+ // still buffered (and consumed below, after the line is handled).
+ const more = if (reader.peekByte()) |_| true else |_| false;
+ try full.writer.writeAll(line.writer.buffered());
+ try full.writer.writeByte('\n');
+ self.printDelta(line.writer.buffered());
+ if (main_mod.g_thinking_fold_request) {
+ main_mod.g_thinking_fold_request = false;
+ self.toggleThinkingFold();
+ }
+ line.clearRetainingCapacity();
+ if ((orig_tio != null and escPressed(true)) or (self.sub and Agent.esc_cancel.load(.acquire))) {
+ self.flushStreamTail();
+ // Mark the connection closing so req.deinit() tears it down
+ // instead of draining the rest of the stream (which would
+ // block until the model finished generating anyway). Subs get
+ // here via Agent.esc_cancel: the root saw Esc during a tool join.
+ if (req.connection) |conn| conn.closing = true;
+ return error.Interrupted;
+ }
+ if (!more) break;
+ reader.toss(1);
+ }
+ self.flushStreamTail(); // render any held partial markdown line
+ if (!main_mod.json_mode and self.streamed_text) if (self.out) |w| {
+ w.writeAll("\n") catch {};
+ w.flush() catch {};
+ };
+ return full.toOwnedSlice();
+}
+
+/// Print the user-visible text from one SSE line, if any. Best-effort:
+/// parse failures are ignored (the buffered body is parsed afterwards).
+pub fn printDelta(self: *Agent, raw_line: []const u8) void {
+ const w = self.out orelse return;
+ const payload = ssePayload(raw_line) orelse return;
+ const parsed = std.json.parseFromSlice(Value, self.gpa, payload, .{}) catch return;
+ defer parsed.deinit();
+ if (parsed.value != .object) return;
+ const obj = parsed.value.object;
+ self.argLiveDelta(obj);
+ const text: []const u8 = switch (self.provider.kind) {
+ .anthropic => blk: {
+ const t = obj.get("type") orelse break :blk "";
+ if (t != .string or !std.mem.eql(u8, t.string, "content_block_delta")) break :blk "";
+ const d = obj.get("delta") orelse break :blk "";
+ if (d != .object) break :blk "";
+ const dt = d.object.get("type") orelse break :blk "";
+ if (dt != .string or !std.mem.eql(u8, dt.string, "text_delta")) break :blk "";
+ const x = d.object.get("text") orelse break :blk "";
+ break :blk if (x == .string) x.string else "";
+ },
+ .openai => blk: {
+ const choices = obj.get("choices") orelse break :blk "";
+ if (choices != .array or choices.array.items.len == 0) break :blk "";
+ const c0 = choices.array.items[0];
+ if (c0 != .object) break :blk "";
+ const d = c0.object.get("delta") orelse break :blk "";
+ if (d != .object) break :blk "";
+ const x = d.object.get("content") orelse break :blk "";
+ break :blk if (x == .string) x.string else "";
+ },
+ .responses => blk: {
+ const t = obj.get("type") orelse break :blk "";
+ if (t != .string or !std.mem.eql(u8, t.string, "response.output_text.delta")) break :blk "";
+ const x = obj.get("delta") orelse break :blk "";
+ break :blk if (x == .string) x.string else "";
+ },
+ };
+ // Reasoning/thinking deltas: deepseek streams reasoning_content, anthropic
+ // a thinking_delta, codex a summary delta. JSON clients get a `reasoning`
+ // event; on a TTY we stream it into a live, dimmed "Thinking" block when
+ // /thinking is enabled, otherwise the spinner stands in for it.
+ const reasoning = reasoningDelta(self.provider.kind, obj);
+ if (reasoning.len != 0) {
+ if (main_mod.json_mode) {
+ self.emit(.{ .type = "reasoning", .text = reasoning });
+ } else if (self.show_thinking and !self.sub and !self.stream_quiet and main_mod.use_color) {
+ self.streamThinking(reasoning);
+ }
+ }
+ if (text.len == 0) return;
+ if (self.thinking_open) self.closeThinkingBlock(); // reasoning → answer transition
+ self.spinnerStop(); // first visible byte: clear the thinking line
+ self.streamed_text = true;
+ self.partial_text.appendSlice(self.arena, text) catch {}; // Esc-interrupt capture
+ if (main_mod.json_mode) {
+ self.emit(.{ .type = "text", .text = text });
+ } else if (main_mod.use_color) {
+ self.streamMarkdown(text);
+ } else {
+ w.writeAll(text) catch return;
+ w.flush() catch return;
+ }
+}
diff --git a/src/agent_table.zig b/src/agent_table.zig
new file mode 100644
index 00000000..35ae9f1d
--- /dev/null
+++ b/src/agent_table.zig
@@ -0,0 +1,204 @@
+//! Streamed-markdown table rendering: buffered rows are column-aligned and
+//! word-wrapped to the terminal width when a table block ends. Split out of
+//! the Agent struct (#123, 600-line goal) — see agent_render.zig for the
+//! rest of the incremental markdown renderer these functions plug into.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const main_mod = @import("main.zig");
+const Agent = main_mod.Agent;
+
+const ansi = @import("ansi.zig");
+const style = &ansi.style;
+
+const terminal = @import("term.zig");
+const termCols = terminal.termCols;
+
+// inlineVisibleLen/renderInline live in agent_render.zig; reached through the
+// Agent struct's member aliases so this file doesn't need to know exactly
+// which sibling module physically owns them.
+const inlineVisibleLen = Agent.inlineVisibleLen;
+const renderInline = Agent.renderInline;
+
+pub fn flushTable(self: *Agent, w: *Io.Writer) void {
+ const gpa = self.gpa;
+ defer {
+ for (self.md_table.items) |r| gpa.free(r);
+ self.md_table.clearRetainingCapacity();
+ }
+ // Split rows into trimmed cells (slices into the row strings),
+ // dropping the empty edges of leading/trailing '|'.
+ var cells: std.ArrayList([]const []const u8) = .empty;
+ defer {
+ for (cells.items) |cr| gpa.free(cr);
+ cells.deinit(gpa);
+ }
+ var header_rows: ?usize = null; // rows above the first separator
+ var ncols: usize = 0;
+ for (self.md_table.items) |row| {
+ const body = std.mem.trim(u8, row, " ");
+ if (isTableSeparator(body)) {
+ if (header_rows == null and cells.items.len > 0) header_rows = cells.items.len;
+ continue;
+ }
+ var list: std.ArrayList([]const u8) = .empty;
+ var it = std.mem.splitScalar(u8, body, '|');
+ var first = true;
+ while (it.next()) |cell| {
+ defer first = false;
+ if (first and cell.len == 0) continue;
+ list.append(gpa, std.mem.trim(u8, cell, " ")) catch {};
+ }
+ while (list.items.len > 0 and list.items[list.items.len - 1].len == 0)
+ _ = list.pop();
+ ncols = @max(ncols, list.items.len);
+ const owned = list.toOwnedSlice(gpa) catch blk: {
+ list.deinit(gpa);
+ break :blk &.{};
+ };
+ cells.append(gpa, owned) catch gpa.free(owned);
+ }
+ if (ncols == 0 or cells.items.len == 0) return;
+ const widths = gpa.alloc(usize, ncols) catch return;
+ defer gpa.free(widths);
+ @memset(widths, 0);
+ for (cells.items) |cr| for (cr, 0..) |c, i| {
+ widths[i] = @max(widths[i], inlineVisibleLen(c));
+ };
+ // Cap the grid to the terminal: a column wider than the screen used
+ // to hard-wrap at the terminal edge and shred the alignment. Shrink
+ // the widest columns until the table fits, then word-wrap each cell
+ // into its column — continuation lines keep the │ rails straight.
+ fitWidths(widths, termCols() -| (3 * (ncols - 1)));
+ const wraps = gpa.alloc(std.ArrayList([]const u8), ncols) catch return;
+ defer gpa.free(wraps);
+ for (cells.items, 0..) |cr, ri| {
+ const head = header_rows != null and ri < header_rows.?;
+ var nlines: usize = 1;
+ for (0..ncols) |ci| {
+ wraps[ci] = .empty;
+ wrapCell(gpa, if (ci < cr.len) cr[ci] else "", widths[ci], &wraps[ci]);
+ nlines = @max(nlines, wraps[ci].items.len);
+ }
+ defer for (wraps) |*l| l.deinit(gpa);
+ for (0..nlines) |li| {
+ for (0..ncols) |ci| {
+ const c = if (li < wraps[ci].items.len) wraps[ci].items[li] else "";
+ if (ci > 0) w.print("{s} │ {s}", .{ style.dim, style.reset }) catch {};
+ if (head) w.writeAll(style.bold) catch {};
+ renderInline(w, c);
+ if (head) w.writeAll(style.reset) catch {};
+ if (ci + 1 < ncols) {
+ var pad = widths[ci] -| inlineVisibleLen(c);
+ while (pad > 0) : (pad -= 1) w.writeByte(' ') catch {};
+ }
+ }
+ w.writeByte('\n') catch {};
+ }
+ if (header_rows != null and ri + 1 == header_rows.?) {
+ w.writeAll(style.dim) catch {};
+ for (0..ncols) |ci| {
+ if (ci > 0) w.writeAll("─┼─") catch {};
+ for (0..widths[ci]) |_| w.writeAll("─") catch {};
+ }
+ w.writeAll(style.reset) catch {};
+ w.writeByte('\n') catch {};
+ }
+ }
+}
+
+/// Shrink the widest columns one cell at a time until the grid fits in
+/// `avail` visible columns, never below a readable floor. If the screen
+/// can't even hold the floor for every column, leave the widths alone —
+/// a torn render beats an unreadable one.
+pub fn fitWidths(widths: []usize, avail: usize) void {
+ const min_w: usize = 8;
+ if (avail < widths.len * min_w) return;
+ var total: usize = 0;
+ for (widths) |x| total += x;
+ while (total > avail) {
+ var wi: usize = 0;
+ for (widths, 0..) |x, k| {
+ if (x > widths[wi]) wi = k;
+ }
+ if (widths[wi] <= min_w) break;
+ widths[wi] -= 1;
+ total -= 1;
+ }
+}
+
+/// One wrappable unit of a table cell: a maximal run of non-space bytes,
+/// where a **bold**/`code` span is atomic (spaces inside don't split it),
+/// so wrapping never tears a styled span apart.
+pub fn atomEnd(s: []const u8, start: usize) usize {
+ var i = start;
+ while (i < s.len) {
+ if (s[i] == ' ') return i;
+ if (i + 1 < s.len and s[i] == '*' and s[i + 1] == '*') {
+ if (std.mem.indexOfPos(u8, s, i + 2, "**")) |e| {
+ i = e + 2;
+ continue;
+ }
+ }
+ if (s[i] == '`') {
+ if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |e| {
+ i = e + 1;
+ continue;
+ }
+ }
+ i += 1;
+ }
+ return s.len;
+}
+
+/// Greedy word-wrap of one table cell to a visible-width budget,
+/// appending slices of `cell` to `out` (one per rendered line). Atoms
+/// wider than the budget hard-split by codepoint. Always yields at least
+/// one (possibly empty) line.
+pub fn wrapCell(gpa: Allocator, cell: []const u8, width: usize, out: *std.ArrayList([]const u8)) void {
+ const budget = @max(width, 1);
+ var ls: usize = 0; // current line: first atom byte…
+ var le: usize = 0; // …through end of its last atom
+ var lv: usize = 0; // and its visible width
+ var i: usize = 0;
+ while (i < cell.len) {
+ while (i < cell.len and cell[i] == ' ') i += 1;
+ if (i >= cell.len) break;
+ const ae = atomEnd(cell, i);
+ const av = inlineVisibleLen(cell[i..ae]);
+ if (lv > 0 and lv + 1 + av > budget) {
+ out.append(gpa, cell[ls..le]) catch return;
+ lv = 0;
+ }
+ if (lv == 0 and av > budget) { // oversized atom: hard-split
+ var j = i;
+ var v: usize = 0;
+ while (j < ae and v < budget) {
+ j += std.unicode.utf8ByteSequenceLength(cell[j]) catch 1;
+ v += 1;
+ }
+ out.append(gpa, cell[i..j]) catch return;
+ i = j;
+ continue;
+ }
+ if (lv == 0) ls = i else lv += 1; // joining space
+ lv += av;
+ le = ae;
+ i = ae;
+ }
+ if (lv > 0) out.append(gpa, cell[ls..le]) catch return;
+ if (out.items.len == 0) out.append(gpa, "") catch {};
+}
+
+/// True if a `|`-delimited row contains only separator chars (-, :, space).
+pub fn isTableSeparator(body: []const u8) bool {
+ var any_dash = false;
+ for (body) |c| switch (c) {
+ '|', ' ', ':' => {},
+ '-' => any_dash = true,
+ else => return false,
+ };
+ return any_dash;
+}
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
new file mode 100644
index 00000000..73edb5b8
--- /dev/null
+++ b/src/agent_tools.zig
@@ -0,0 +1,450 @@
+//! Tool-call dispatch: the batch runner (runTools) that rejects/dedupes/
+//! gates each call then fans external ones out across the Io thread pool,
+//! the human-approval gate for bash/write_file/edit_file/MCP calls
+//! (gateTool), meta-tool handling (attempt_completion/eval/todo_write/
+//! todo_read/ask_user, on the agent's own thread — handleMeta/askUser),
+//! and the tool-call/tool-result UX lines (sayToolUse/sayToolResult).
+//! Split out of the Agent struct (#123, 600-line goal).
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+
+const main_mod = @import("main.zig");
+const Agent = main_mod.Agent;
+const ToolCall = main_mod.ToolCall;
+const ExecResult = main_mod.ExecResult;
+const AnswerRequest = main_mod.AnswerRequest;
+const answerParseError = main_mod.answerParseError;
+const parseAnswerRequest = main_mod.parseAnswerRequest;
+
+const ansi = @import("ansi.zig");
+const style = &ansi.style;
+
+const terminal = @import("term.zig");
+const tty = terminal.tty;
+
+const mcp = @import("mcp.zig");
+
+const approvals_mod = @import("approvals.zig");
+const Approvals = approvals_mod.Approvals;
+
+const skills = @import("skills.zig");
+const companionTrusted = skills.companionTrusted;
+const companionReadOnly = skills.companionReadOnly;
+
+const schema = @import("schema.zig");
+const isMetaName = schema.isMetaName;
+
+const tools_mod = @import("tools.zig");
+const ToolCtx = tools_mod.ToolCtx;
+const ToolOutput = tools_mod.ToolOutput;
+
+const exec = @import("exec.zig");
+const execTool = exec.execTool;
+
+// escWatchTask/drainStdin/rawNonblockStdin live in agent_interrupt.zig;
+// Agent.esc_watch_done is a struct-level pub var that STAYS declared inside the
+// Agent struct in main.zig (never alias a var — see esc_cancel/
+// Agent.esc_watch_done in agent_interrupt.zig's own header comment). All reached
+// through the Agent struct's namespace.
+const escWatchTask = Agent.escWatchTask;
+const drainStdin = Agent.drainStdin;
+const rawNonblockStdin = Agent.rawNonblockStdin;
+
+/// Run a batch of tool calls. Meta tools are handled inline (they mutate
+/// agent state); everything else fans out across the Io thread pool.
+/// Bash calls must clear the permission gate before dispatch. Results
+/// are returned in call order, arena-owned.
+pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
+ const results = try self.arena.alloc(ExecResult, calls.len);
+
+ // Collect the indices of external (non-meta) calls for parallel exec.
+ var ext_idx: std.ArrayList(usize) = .empty;
+ defer ext_idx.deinit(self.gpa);
+ for (calls, 0..) |call, i| {
+ if (try self.rejectToolCall(call)) |denied| {
+ results[i] = denied;
+ continue;
+ }
+ try self.sayToolUse(call);
+ if (isMetaName(call.name)) {
+ results[i] = try self.handleMeta(call);
+ } else if (try self.gateTool(call)) |denied| {
+ results[i] = denied;
+ } else {
+ try ext_idx.append(self.gpa, i);
+ }
+ }
+
+ if (ext_idx.items.len > 0) {
+ if (ext_idx.items.len > 1 and !self.sub) {
+ try self.say(" {s}↯ running {d} tools in parallel{s}\n", .{ style.dim, ext_idx.items.len, style.reset });
+ }
+ const ctx: ToolCtx = .{
+ .gpa = self.gpa,
+ .io = self.io,
+ .client = self.client,
+ .provider = self.provider,
+ .registry = if (self.sub) null else self.registry,
+ .from_sub = self.sub,
+ .approvals = self.approvals,
+ .tracer = self.tracer,
+ .snapshots = self.snapshots,
+ .tools_used = &self.tools_used,
+ };
+ // Esc while tools run: spawn a stdin watcher for the duration of
+ // the join (see esc_cancel). Subagents notice the flag mid-flight;
+ // the root aborts the turn at its next runTurn iteration.
+ const esc_watch = !self.sub and self.in != null and main_mod.use_color and !main_mod.json_mode;
+ var esc_tio: ?tty.RawState = null;
+ var esc_fut: ?Io.Future(void) = null;
+ if (esc_watch) if (rawNonblockStdin()) |tio| {
+ esc_tio = tio;
+ Agent.esc_watch_done.store(false, .release);
+ esc_fut = self.io.async(escWatchTask, .{});
+ };
+ defer if (esc_tio) |tio| {
+ Agent.esc_watch_done.store(true, .release);
+ if (esc_fut) |*f| f.await(self.io);
+ drainStdin();
+ tty.restore(tio);
+ };
+ // Join ALL futures before any fallible work: an early error
+ // return would otherwise free the futures while pool tasks are
+ // still writing into them (and abandon running tools).
+ const futures = try self.gpa.alloc(Io.Future(ToolOutput), ext_idx.items.len);
+ defer self.gpa.free(futures);
+ const outputs = try self.gpa.alloc(ToolOutput, ext_idx.items.len);
+ defer self.gpa.free(outputs);
+ for (ext_idx.items, futures) |i, *fut| fut.* = self.io.async(execTool, .{ ctx, calls[i] });
+ for (futures, outputs) |*fut, *output| output.* = fut.await(self.io);
+ defer for (outputs) |output| self.gpa.free(output.text);
+ for (ext_idx.items, outputs) |i, output| {
+ results[i] = .{ .text = try self.arena.dupe(u8, output.text), .is_error = output.is_error, .ms = output.ms };
+ }
+ }
+ // Show a compact ✓/✗ + preview for each non-meta call (no-op for subs).
+ for (calls, results) |call, r| self.sayToolResult(call.name, r);
+ return results;
+}
+
+pub fn rejectToolCall(self: *Agent, call: ToolCall) !?ExecResult {
+ if (self.sub) return null;
+ if (std.mem.eql(u8, call.name, "attempt_completion")) return null;
+ if (main_mod.max_tool_calls) |max| {
+ if (self.tool_calls_this_turn >= max) {
+ const message = try std.fmt.allocPrint(self.arena, "tool call budget exhausted ({d}/{d}) — answer with what you have or ask for a higher --max-tool-calls", .{ self.tool_calls_this_turn, max });
+ self.emitToolRejected(call, "budget", message);
+ return .{ .text = message, .is_error = true };
+ }
+ }
+ if (main_mod.dedupe_tool_calls) {
+ const key = try self.toolDedupeKey(call);
+ for (self.seen_tool_keys.items) |seen| {
+ if (std.mem.eql(u8, seen, key)) {
+ const message = try std.fmt.allocPrint(self.arena, "duplicate tool call rejected: {s} with the same normalized input already ran this turn", .{call.name});
+ self.emitToolRejected(call, "duplicate", message);
+ return .{ .text = message, .is_error = true };
+ }
+ }
+ try self.seen_tool_keys.append(self.arena, key);
+ }
+ self.tool_calls_this_turn += 1;
+ return null;
+}
+
+pub fn toolDedupeKey(self: *Agent, call: ToolCall) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(self.arena);
+ const w = &aw.writer;
+ try w.writeAll(call.name);
+ try w.writeByte('\n');
+ var s: std.json.Stringify = .{ .writer = w };
+ try s.write(call.input);
+ const key = aw.writer.buffered();
+ for (key) |*c| {
+ c.* = if (std.ascii.isWhitespace(c.*)) ' ' else std.ascii.toLower(c.*);
+ }
+ return key;
+}
+
+pub fn emitToolRejected(self: *Agent, call: ToolCall, reason: []const u8, message: []const u8) void {
+ if (!main_mod.json_mode) return;
+ self.emit(.{ .type = "tool_rejected", .name = call.name, .reason = reason, .input = call.input, .message = message });
+}
+
+/// The permission gate, root side: an unapproved bash command prompts
+/// the user — yes once, always (approve the command's first word for
+/// the rest of the session), or no. Returns the denial result, or null
+/// when cleared to execute. Subagents never prompt; their gate is the
+/// allowlist check in execToolInner.
+pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
+ if (self.sub) {
+ // Destructive git is blocked for subagents outright — they have no
+ // human to confirm with. The root agent falls through to a y/n
+ // prompt below. Completes the Codex-style `.git` guard across both.
+ if (std.mem.eql(u8, call.name, "bash") and call.input == .object) {
+ if (call.input.object.get("command")) |cv| if (cv == .string and Approvals.isDestructiveGit(cv.string)) return .{
+ .text = try self.arena.dupe(u8, "destructive git is blocked for subagents (no one to confirm) — leave reset --hard / clean -f / force-push / branch -D to the root session"),
+ .is_error = true,
+ };
+ }
+ return null; // subagents: otherwise gated structurally, not by prompt
+ }
+ const approvals = self.approvals orelse return null;
+
+ // Plan mode: read-only, regardless of approvals — deny mutating tools
+ // up front (no point prompting for something the mode forbids).
+ if (main_mod.plan_mode) {
+ if (std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or
+ (mcp.Registry.isMcp(call.name) and !companionReadOnly(call.name, call.input))) return .{
+ .text = try self.arena.dupe(u8, "plan mode is on — read-only. Fold this change into the plan you present; the user applies it after approving (/plan toggles the mode off)."),
+ .is_error = true,
+ };
+ if (std.mem.eql(u8, call.name, "bash")) {
+ const cmd_val = call.input.object.get("command") orelse return null;
+ if (cmd_val != .string) return null;
+ const cmd = std.mem.trim(u8, cmd_val.string, " \t");
+ if (!Approvals.readOnlyAllowed(cmd)) return .{
+ .text = try self.arena.dupe(u8, "plan mode is on — only read-only commands run (ls/cat/grep/git status…). Put this command in the plan instead."),
+ .is_error = true,
+ };
+ return null;
+ }
+ }
+
+ // Decide whether this call needs approval, and what the approval key
+ // and prompt line are. bash keys on the command's first word; writes
+ // and MCP tools key on the tool name.
+ var key: []const u8 = undefined;
+ var line_buf: [256]u8 = undefined;
+ var prompt_line: []const u8 = undefined;
+
+ if (std.mem.eql(u8, call.name, "bash")) {
+ const cmd_val = call.input.object.get("command") orelse return null;
+ if (cmd_val != .string) return null;
+ const cmd = std.mem.trim(u8, cmd_val.string, " \t");
+ // Destructive git (reset --hard, clean -f, branch -D, force-push…)
+ // stays gated in normal mode + for subagents, but DOES run under --yolo
+ // so the agent can't wipe the user's work or a worktree's checkpoints.
+ // It falls through to a human y/n (or a deny in non-interactive runs).
+ const destructive_git = Approvals.isDestructiveGit(cmd);
+ const gate_ok = !destructive_git or Approvals.destructiveGitAllowed(approvals.yolo, self.sub);
+ if (gate_ok and approvals.allowed(self.io, cmd)) return null;
+ key = firstWord(cmd);
+ prompt_line = if (destructive_git)
+ std.fmt.bufPrint(&line_buf, "DESTRUCTIVE git — run: {s}", .{cmd}) catch cmd
+ else
+ std.fmt.bufPrint(&line_buf, "run: {s}", .{cmd}) catch cmd;
+ } else if (std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file")) {
+ if (approvals.allowedExact(self.io, call.name)) return null;
+ key = call.name;
+ const path = if (call.input == .object)
+ (if (call.input.object.get("path")) |p| (if (p == .string) p.string else "?") else "?")
+ else
+ "?";
+ prompt_line = std.fmt.bufPrint(&line_buf, "{s} {s}", .{ call.name, path }) catch call.name;
+ } else if (mcp.Registry.isMcp(call.name)) {
+ if (companionTrusted(call.name)) return null; // the whole suite: like native tools
+ if (approvals.allowedExact(self.io, call.name)) return null;
+ key = call.name;
+ prompt_line = std.fmt.bufPrint(&line_buf, "call MCP tool {s}", .{call.name}) catch call.name;
+ } else {
+ return null; // read_file, subagent, workflow, meta: not gated
+ }
+
+ // No human to ask (one-shot -p, or stdin gone): deny instead of
+ // hanging. Pre-approve in .harness/settings.json or pass --yolo.
+ const in = self.in orelse return .{
+ .text = try self.arena.dupe(u8, "not pre-approved, and no interactive user to ask in one-shot mode — pre-approve it in .harness/settings.json, or run with --yolo"),
+ .is_error = true,
+ };
+ const w = self.out orelse return .{
+ .text = try self.arena.dupe(u8, "not pre-approved, and no interactive user to ask — pre-approve it in .harness/settings.json, or run with --yolo"),
+ .is_error = true,
+ };
+
+ try w.print(" ⚠ {s}\n [y]es once · [a]lways allow \"{s}\" (saved to {s}) · [n]o › ", .{ prompt_line, key, Approvals.settings_path });
+ try w.flush();
+ const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";
+ const answer = std.mem.trim(u8, raw, " \t\r");
+ if (answer.len > 0) switch (answer[0]) {
+ 'y', 'Y' => return null,
+ 'a', 'A' => {
+ try approvals.approve(self.io, self.gpa, key);
+ if (std.mem.eql(u8, call.name, "bash") and Approvals.isInterpreter(key)) {
+ try w.print(" note: \"{s}\" can execute arbitrary code (e.g. {s} -c '…'); approving it is effectively unrestricted.\n", .{ key, key });
+ try w.flush();
+ }
+ return null;
+ },
+ else => {},
+ };
+ return .{
+ .text = try self.arena.dupe(u8, "user declined this tool call — try another approach or ask them how to proceed"),
+ .is_error = true,
+ };
+}
+
+pub fn firstWord(cmd: []const u8) []const u8 {
+ const end = std.mem.indexOfAny(u8, cmd, " \t") orelse cmd.len;
+ return cmd[0..end];
+}
+
+/// Handle a meta tool inline on the agent's own thread.
+pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
+ if (std.mem.eql(u8, call.name, "attempt_completion")) {
+ const result = if (call.input.object.get("result")) |r| r.string else "";
+ self.completed = try self.arena.dupe(u8, result);
+ // Skip the re-print only when the result streamed live in full.
+ if (!self.sub and !self.argStreamedFully(call)) try self.say("{s}\n", .{result});
+ return .{ .text = "completion recorded", .is_error = false };
+ }
+ if (std.mem.eql(u8, call.name, "eval")) {
+ const note = if (call.input.object.get("note")) |n| (if (n == .string) n.string else "") else "";
+ return self.runEval(note);
+ }
+ if (std.mem.eql(u8, call.name, "todo_write")) {
+ self.todos.clearRetainingCapacity();
+ if (call.input.object.get("todos")) |list| if (list == .array) {
+ for (list.array.items) |item| {
+ if (item != .object) continue;
+ const content = item.object.get("content") orelse continue;
+ if (content != .string) continue;
+ const status = if (item.object.get("status")) |st| (if (st == .string) st.string else "pending") else "pending";
+ try self.todos.append(self.arena, .{
+ .content = try self.arena.dupe(u8, content.string),
+ .status = try self.arena.dupe(u8, status),
+ });
+ }
+ };
+ const rendered = self.renderTodos();
+ if (!self.sub) try self.say("{s}\n", .{rendered});
+ return .{ .text = rendered, .is_error = false };
+ }
+ if (std.mem.eql(u8, call.name, "ask_user")) return self.askUser(call);
+ // todo_read
+ return .{ .text = self.renderTodos(), .is_error = false };
+}
+
+/// The "user message as a tool" half of the loop: the agent calls
+/// ask_user, we block for a typed reply, and hand it back as the tool
+/// result. Only the root agent has stdin; subagents must self-decide.
+pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
+ const in = self.in orelse return .{
+ .text = "no human is attached — make a reasonable assumption and continue",
+ .is_error = true,
+ };
+ const w = self.out.?;
+ const question = if (call.input.object.get("question")) |q| q.string else "(no question)";
+ if (main_mod.json_mode) {
+ const call_id = if (call.id.len > 0) call.id else blk: {
+ const id = try std.fmt.allocPrint(self.arena, "ask_user-{d}", .{self.next_ask_id});
+ self.next_ask_id += 1;
+ break :blk id;
+ };
+ try self.emitAskUser(call_id, question, call.input);
+ const raw = (try in.takeDelimiter('\n')) orelse return .{
+ .text = "user ended input without answering",
+ .is_error = true,
+ };
+ const parsed = std.json.parseFromSliceLeaky(Value, self.arena, std.mem.trim(u8, raw, " \t\r"), .{ .allocate = .alloc_always }) catch return .{
+ .text = "invalid answer JSON for ask_user",
+ .is_error = true,
+ };
+ const answer = parseAnswerRequest(parsed, call_id) catch |err| return .{
+ .text = answerParseError(err),
+ .is_error = true,
+ };
+ if (answer.cancelled) return .{ .text = "user cancelled the follow-up", .is_error = true };
+ return .{ .text = try self.arena.dupe(u8, answer.text), .is_error = false };
+ }
+ // Skip the re-print only when the question streamed live in full.
+ if (!self.argStreamedFully(call)) try w.print("\n❓ {s}\n", .{question});
+ if (call.input.object.get("options")) |opts| if (opts == .array) {
+ for (opts.array.items, 1..) |opt, n| try w.print(" {d}) {s}\n", .{ n, opt.string });
+ };
+ try w.writeAll(" your answer › ");
+ try w.flush();
+
+ const raw = (try in.takeDelimiter('\n')) orelse return .{
+ .text = "user ended input without answering",
+ .is_error = true,
+ };
+ const answer = std.mem.trim(u8, raw, " \t\r");
+ return .{ .text = try self.arena.dupe(u8, answer), .is_error = false };
+}
+
+pub fn emitAskUser(self: *Agent, call_id: []const u8, question: []const u8, input: Value) !void {
+ const w = self.out orelse return;
+ var s: std.json.Stringify = .{ .writer = w };
+ try s.beginObject();
+ try s.objectField("type");
+ try s.write("ask_user");
+ try s.objectField("call_id");
+ try s.write(call_id);
+ try s.objectField("question");
+ try s.write(question);
+ try s.objectField("input");
+ try s.write(input);
+ try s.endObject();
+ try w.writeByte('\n');
+ try w.flush();
+}
+
+pub fn sayToolUse(self: *Agent, call: ToolCall) !void {
+ if (main_mod.json_mode) {
+ if (std.mem.eql(u8, call.name, "ask_user")) return;
+ self.emit(.{ .type = "tool_call", .name = call.name, .input = call.input });
+ self.emit(.{ .type = "tool_call_started", .name = call.name, .input = call.input });
+ return;
+ }
+ // The ⚙ line would just repeat prose that already streamed live.
+ if (self.argStreamedFully(call)) return;
+ var aw: Io.Writer.Allocating = .init(self.gpa);
+ defer aw.deinit();
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.write(call.input);
+ const full = aw.writer.buffered();
+ const shown = if (full.len > 160) full[0..160] else full;
+ try self.say("{s}⚙{s} {s}{s} {s}{s}{s}{s}\n", .{
+ style.dim, style.reset, style.cyan, call.name,
+ style.dim, shown,
+ if (full.len > 160) "…" else "",
+ style.reset,
+ });
+}
+
+/// Compact result feedback for one finished tool call: a green ✓ / red ✗
+/// and a one-line preview of what it returned. Root only (subagents have
+/// no writer); meta tools render their own UX, so skip them.
+pub fn sayToolResult(self: *Agent, name: []const u8, r: ExecResult) void {
+ const w = self.out orelse return;
+ if (main_mod.json_mode) {
+ if (isMetaName(name) and !std.mem.eql(u8, name, "ask_user")) return;
+ self.emit(.{ .type = "tool_result", .name = name, .is_error = r.is_error, .text = r.text });
+ self.emit(.{ .type = "tool_call_finished", .name = name, .is_error = r.is_error, .ms = r.ms });
+ return;
+ }
+ if (isMetaName(name)) return;
+ const all = std.mem.trim(u8, r.text, " \t\r\n");
+ var preview = all;
+ if (std.mem.indexOfScalar(u8, preview, '\n')) |nl| preview = preview[0..nl];
+ preview = std.mem.trim(u8, preview, " \t\r");
+ const shown = if (preview.len > 100) preview[0..100] else preview;
+ const truncated = shown.len < all.len; // more content (extra lines or >100 chars)
+ const mark = if (r.is_error) "✗" else "✓";
+ const mc = if (r.is_error) style.red else style.green;
+ var tbuf: [24]u8 = undefined;
+ const timing = if (main_mod.show_timing and r.ms > 0)
+ (std.fmt.bufPrint(&tbuf, " ({d}ms)", .{r.ms}) catch "")
+ else
+ "";
+ w.print(" {s}{s}{s}{s}{s}{s} {s}{s}{s}{s}\n", .{
+ mc, mark, style.reset, style.dim, timing, style.reset,
+ style.dim, shown,
+ if (truncated) "…" else "",
+ style.reset,
+ }) catch return;
+ w.flush() catch return;
+}
diff --git a/src/main.zig b/src/main.zig
index ee5c1faa..d1324fd8 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -39,8 +39,24 @@ const repl = @import("repl.zig");
const builtin = @import("builtin");
+// The Agent struct's method bodies are split across agent_*.zig sibling
+// files (#123, 600-line goal) as free `pub fn method(self: *Agent, ...)`
+// functions, member-aliased back inside `struct Agent` (`pub const method =
+// @import("agent_x.zig").method;`) so both `self.method(...)` and static
+// `Agent.method(...)` test calls resolve unchanged. Referenced here only to
+// keep their test blocks running (see the root test{} block below).
+const agent_table = @import("agent_table.zig");
+const agent_argstream = @import("agent_argstream.zig");
+const agent_render = @import("agent_render.zig");
+const agent_steps = @import("agent_steps.zig");
+const agent_compact = @import("agent_compact.zig");
+const agent_tools = @import("agent_tools.zig");
+const agent_request = @import("agent_request.zig");
+const agent_interrupt = @import("agent_interrupt.zig");
+const agent_stream = @import("agent_stream.zig");
+
pub const anthropic_version = "2023-06-01";
-const max_tokens = 16000;
+pub const max_tokens = 16000;
pub const mcp_config_path = ".mcp.json";
// The terminal color palette lives in ansi.zig (a std-only leaf) so the
@@ -54,11 +70,11 @@ const style = &ansi.style;
pub var use_color = false; // stdout is a TTY and NO_COLOR unset → enables color + markdown
// Optional displays toggled by CLI flags (--timing, --cost).
-var show_timing = false;
+pub var show_timing = false;
var show_cost = false;
pub var json_mode = false; // --json: structured JSONL events on stdout instead of human text
-var max_tool_calls: ?u64 = null; // --max-tool-calls: hard per-turn root tool budget
-var dedupe_tool_calls = false; // --dedupe-tool-calls: reject duplicate root calls in a turn
+pub var max_tool_calls: ?u64 = null; // --max-tool-calls: hard per-turn root tool budget
+pub var dedupe_tool_calls = false; // --dedupe-tool-calls: reject duplicate root calls in a turn
pub var plan_mode = false; // /plan: read-only — mutating tools are denied, the model proposes
var unattended = false; // -p one-shot: no human to prompt; unapproved tool calls are denied
@@ -129,6 +145,15 @@ test {
_ = commands_session;
_ = commands_model;
_ = commands_misc;
+ _ = agent_table;
+ _ = agent_argstream;
+ _ = agent_render;
+ _ = agent_steps;
+ _ = agent_compact;
+ _ = agent_tools;
+ _ = agent_request;
+ _ = agent_interrupt;
+ _ = agent_stream;
}
/// Wire format + auth style + endpoint per provider. Base URLs and env-var
@@ -238,7 +263,7 @@ const sub_system_prompt =
\\concise, complete report with the concrete facts you found.
;
-const compact_instruction =
+pub const compact_instruction =
\\Summarize this entire conversation for a context handoff. Capture: the
\\user's goals, all important facts and decisions, file paths and code
\\that was created or modified, command results that matter, and any
@@ -480,7 +505,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 };
+pub const ReasoningEffort = enum { low, medium, high };
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" };
@@ -864,16 +889,16 @@ const anim = @import("anim.zig");
// stays empty there. Watchdog/select arms may drain and echo stdin while the
// stream reader is blocked; g_steer_visible pauses spinner redraws so the live
// steering row is not cleared out from under the user.
-var g_steer_buf: std.ArrayList(u8) = .empty; // in-progress line (page-alloc)
+pub var g_steer_buf: std.ArrayList(u8) = .empty; // in-progress line (page-alloc)
const SteerEntry = struct { text: []const u8, force: bool };
-var g_steer_queue: std.ArrayList(SteerEntry) = .empty; // completed lines
-var g_steer_echoed = false; // "↳ steer ›" prefix shown for the current line
-var g_steer_visible: std.atomic.Value(bool) = .init(false); // visible live steering row; pauses spinner redraws
+pub var g_steer_queue: std.ArrayList(SteerEntry) = .empty; // completed lines
+pub var g_steer_echoed = false; // "↳ steer ›" prefix shown for the current line
+pub var g_steer_visible: std.atomic.Value(bool) = .init(false); // visible live steering row; pauses spinner redraws
pub var g_out: ?*Io.Writer = null; // stdout writer for steer echo (set in main)
-pub var g_gui_mu: Io.Mutex = .init; // serializes --json stdout across pool-thread subagent emits (guiEmit + Agent.emit)
-var g_force_interrupt = false; // Force-prompt path caused the last interrupt (Ctrl-F/double-enter).
-var g_thinking_fold_request: bool = false; // Ctrl-T in escPressed → fold/unfold the live Thinking block (#92)
-var g_thinking_open: bool = false; // a live Thinking block is on screen (gates the mouse-click fold, #92)
+pub var g_gui_mu: Io.Mutex = .init; // serializes --json stdout across pool-thread subagent emits (guiEmit + printDelta)
+pub var g_force_interrupt = false; // Force-prompt path caused the last interrupt (Ctrl-F/double-enter).
+pub var g_thinking_fold_request: bool = false; // Ctrl-T in escPressed → fold/unfold the live Thinking block (#92)
+pub var g_thinking_open: bool = false; // a live Thinking block is on screen (gates the mouse-click fold, #92)
pub var g_5xx_body_buf: [600]u8 = undefined; // snippet of the last 5xx/429 error body
pub var g_5xx_body_len: usize = 0; // 0 = no body captured
@@ -895,7 +920,7 @@ fn resetSteerPartial() void {
/// Writes steering echo to the stdout writer (the same buffered writer the
/// streaming text uses, already flushed before escPressed runs, so ordering
/// stays correct) and flushes so the user sees queued keystrokes live.
-fn steerEcho(bytes: []const u8) void {
+pub fn steerEcho(bytes: []const u8) void {
if (g_out) |w| {
w.writeAll(bytes) catch {};
w.flush() catch {};
@@ -3016,19 +3041,19 @@ pub const ToolCall = struct {
};
/// A tool's outcome, arena-owned, ready to wire into either format.
-const ExecResult = struct {
+pub const ExecResult = struct {
text: []const u8,
is_error: bool,
ms: i64 = 0, // wall-clock of the tool exec (external tools only; --timing)
};
-const AnswerRequest = struct {
+pub const AnswerRequest = struct {
text: []const u8,
cancelled: bool,
call_id: []const u8,
};
-fn answerParseError(err: anyerror) []const u8 {
+pub fn answerParseError(err: anyerror) []const u8 {
return switch (err) {
error.AnswerNotObject => "answer must be a JSON object",
error.AnswerWrongType => "expected answer request for ask_user",
@@ -3037,7 +3062,7 @@ fn answerParseError(err: anyerror) []const u8 {
};
}
-fn parseAnswerRequest(parsed: Value, expected_call_id: []const u8) !AnswerRequest {
+pub fn parseAnswerRequest(parsed: Value, expected_call_id: []const u8) !AnswerRequest {
if (parsed != .object) return error.AnswerNotObject;
const rtype = if (parsed.object.get("type")) |v| (if (v == .string) v.string else "") else "";
if (!std.mem.eql(u8, rtype, "answer")) return error.AnswerWrongType;
@@ -3049,7 +3074,7 @@ fn parseAnswerRequest(parsed: Value, expected_call_id: []const u8) !AnswerReques
return .{ .text = text, .cancelled = cancelled, .call_id = call_id };
}
-const TodoItem = struct {
+pub const TodoItem = struct {
content: []const u8,
status: []const u8,
};
@@ -3172,7 +3197,7 @@ pub const Agent = struct {
try w.flush();
}
- fn say(self: *Agent, comptime fmt: []const u8, args: anytype) !void {
+ pub fn say(self: *Agent, comptime fmt: []const u8, args: anytype) !void {
if (self.out) |w| {
try w.print(fmt, args);
try w.flush();
@@ -3183,7 +3208,7 @@ pub const Agent = struct {
/// Report an API error: remember the formatted message so the --json
/// `error` event can carry the detail, then print it like say().
- fn sayApiError(self: *Agent, comptime fmt: []const u8, args: anytype) !void {
+ pub fn sayApiError(self: *Agent, comptime fmt: []const u8, args: anytype) !void {
self.last_api_error = std.fmt.allocPrint(self.arena, fmt, args) catch null;
try self.say(fmt ++ "\n", args);
}
@@ -3191,7 +3216,7 @@ pub const Agent = struct {
/// Emit one structured JSONL event to stdout (--json mode). `ev` is any
/// struct/anonymous struct; field names become JSON keys (a std.json.Value
/// field, e.g. tool input, serializes correctly). Best-effort.
- fn emit(self: *Agent, ev: anytype) void {
+ pub fn emit(self: *Agent, ev: anytype) void {
const w = self.out orelse return;
// --json: the GUI stream is shared with pool-thread subagent emits
// (guiEmit), so serialize + flush under the lock — a raw line must never
@@ -3216,7 +3241,7 @@ pub const Agent = struct {
return providerTakesEffort(self.provider.kind, self.provider.id, self.provider.model);
}
- fn toolsJson(self: *const Agent) []const u8 {
+ pub fn toolsJson(self: *const Agent) []const u8 {
return switch (self.provider.kind) {
.anthropic => if (self.sub) tools_anthropic_sub else self.tools_anthropic,
.openai => if (self.sub) tools_openai_sub else self.tools_openai,
@@ -3247,826 +3272,44 @@ pub const Agent = struct {
}
}
- /// POST the current history; returns the parsed response root object
- /// (arena-owned). Reports API error envelopes and returns error.ApiError.
- /// In strict mode we force tool_choice; if a provider rejects that (e.g.
- /// the codegraff gateway with thinking on), we retry once without forcing
- /// and lean on the strict system prompt instead. Root requests stream:
- /// text deltas print live (postStream) and the buffered SSE events are
- /// reassembled into the non-streaming response shape afterwards.
- fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
- var force = self.strict and tools != null;
- var stream_usage = true; // openai stream_options; dropped if rejected
- // #95: scrub any malformed function_call_output before it hits the wire.
- sanitizeMessagesUtf8(self.arena, &self.messages); // invalid UTF-8 (any source/format) -> '?' so content never serializes as a byte-int array the API rejects
- if (self.provider.kind == .responses) normalizeResponsesHistory(self.arena, &self.messages);
- if (self.provider.kind == .openai) normalizeOpenAIHistory(self.arena, &self.messages); // #99: chat-completions sibling of the above
- while (true) {
- const live = !self.sub and self.out != null and !self.stream_quiet;
- self.streamed_text = false;
- self.streamed_args = .none;
- const body = try self.buildBody(tools, force, live, stream_usage);
- defer self.gpa.free(body);
- const t0: Io.Timestamp = .now(self.io, .awake);
- if (json_mode and !self.sub) self.emit(.{ .type = "model_call_started", .provider = self.provider.id, .model = self.provider.model });
- // HTTP calls are flaky: a kept-alive connection the server closed
- // (HttpConnectionClosing), a reset, a truncated TLS read. Retry a
- // few times with a fresh connection; on persistent failure surface
- // error.ApiError so the REPL returns to the prompt, never crashes.
- const resp_body = blk: {
- var attempt: usize = 0;
- while (true) : (attempt += 1) {
- const attempt_body = if (live)
- self.postStream(body)
- else
- postWatched(self.gpa, self.io, self.client, self.provider, body);
- if (attempt_body) |ok| break :blk ok else |err| {
- if (self.streamed_text) if (self.out) |w| {
- w.writeAll("\n") catch {};
- w.flush() catch {};
- };
- self.streamed_text = false;
- self.streamed_args = .none;
- // Esc is a deliberate stop, not a flaky network — no retry.
- if (err == error.Interrupted) return error.Interrupted;
- // 429/5xx: the server asked us to back off — wait
- // (1s·2ⁿ, capped at 8s; Esc cancels) and allow a few
- // more attempts than a plain transport flake gets.
- const throttled = err == error.RateLimited or err == error.ServerError;
- const max_attempts: usize = RetryPlan.maxAttempts(throttled);
- if (attempt < max_attempts) {
- if (throttled) {
- const delay_ms = RetryPlan.delayMs(throttled, attempt);
- const what: []const u8 = if (err == error.RateLimited) "rate limited (429)" else "server error (5xx)";
- if (g_5xx_body_len > 0) {
- try self.say("[{s} — retrying in {d}s ({d}/{d})] {s}\n", .{ what, delay_ms / 1000, attempt + 1, max_attempts, g_5xx_body_buf[0..g_5xx_body_len] });
- } else {
- try self.say("[{s} — retrying in {d}s ({d}/{d})]\n", .{ what, delay_ms / 1000, attempt + 1, max_attempts });
- }
- if (self.tracer) |tr| tr.note("retry", if (g_5xx_body_len > 0) g_5xx_body_buf[0..g_5xx_body_len] else what);
- self.sleepInterruptible(delay_ms) catch return error.Interrupted;
- } else {
- // Transport flake (HttpConnectionClosing, a reset,
- // a truncated TLS read): back off before a fresh
- // connection. Rapid-fire retries against a
- // just-closed keep-alive almost always re-fail
- // (#86). 250ms·2ⁿ, capped at 4s over 6 tries; Esc cancels.
- const delay_ms = RetryPlan.delayMs(throttled, attempt);
- try self.say("[network error: {t} — retrying in {d}ms ({d}/{d})]\n", .{ err, delay_ms, attempt + 1, max_attempts });
- self.sleepInterruptible(delay_ms) catch return error.Interrupted;
- }
- continue;
- }
- if (g_5xx_body_len > 0) {
- try self.say("[request failed: {t} — giving up this turn] {s}\n", .{ err, g_5xx_body_buf[0..g_5xx_body_len] });
- } else {
- try self.say("[request failed: {t} — giving up this turn]\n", .{err});
- }
- // Network give-up is its own error kind: the ApiError
- // handler's last_api_error would otherwise be an API
- // envelope, stale or null on a pure transport failure —
- // record the real reason so the failed turn's --json error
- // event and trajectory node preserve it (#86).
- self.last_api_error = std.fmt.allocPrint(self.arena, "network error: {s} (gave up after {d} attempts)", .{ @errorName(err), max_attempts }) catch null;
- if (telemetry.g_telem) |t| t.errorEvent("net", @errorName(err));
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, 0, body.len, 0, 0, 0, true);
- return error.ApiError;
- }
- }
- };
- defer self.gpa.free(resp_body);
- const ms: i64 = t0.untilNow(self.io, .awake).toMilliseconds();
-
- // object — pull the final `response` out of it (or an error).
- // object — pull the final `response` out of it (or an error).
- if (self.provider.kind == .responses) {
- const r = self.parseResponses(resp_body) catch {
- try self.say("unparseable codex response: {s}\n", .{resp_body[0..@min(resp_body.len, 600)]});
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
- return error.ApiError;
- };
- switch (r) {
- .ok => |obj| {
- self.recordUsageResponses(obj);
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
- if (json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
- return obj;
- },
- .err => |msg| {
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
- try self.sayApiError("codex api error: {s}", .{msg});
- return error.ApiError;
- },
- }
- }
-
- // Streamed anthropic/openai bodies are SSE too: reassemble them.
- // null → the body wasn't SSE (a JSON error envelope, or a
- // provider that ignored `stream`) — fall through to the regular
- // parse, which also handles the soft-strict retry.
- if (live) {
- if (try self.assembleStream(resp_body)) |root| {
- if (root.get("type")) |t| if (t == .string and std.mem.eql(u8, t.string, "error")) {
- const eo = if (root.get("error")) |ev| (if (ev == .object) ev.object else null) else null;
- const etype = if (eo) |e| (if (e.get("type")) |tv| (if (tv == .string) tv.string else "error") else "error") else "error";
- const emsg = if (eo) |e| (if (e.get("message")) |mv| (if (mv == .string) mv.string else "") else "") else "";
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
- try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });
- return error.ApiError;
- };
- self.recordUsage(root);
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
- if (json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
- return root;
- }
- }
-
- const resp = std.json.parseFromSliceLeaky(Value, self.arena, resp_body, .{
- .allocate = .alloc_always,
- }) catch {
- try self.sayApiError("unparseable response: {s}", .{resp_body[0..@min(resp_body.len, 400)]});
- return error.ApiError;
- };
- const root = resp.object;
-
- if (root.get("type")) |t| if (t == .string and std.mem.eql(u8, t.string, "error")) {
- const eo = if (root.get("error")) |ev| (if (ev == .object) ev.object else null) else null;
- const etype = if (eo) |e| (if (e.get("type")) |tv| (if (tv == .string) tv.string else "error") else "error") else "error";
- const emsg = if (eo) |e| (if (e.get("message")) |mv| (if (mv == .string) mv.string else "") else "") else "";
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
- try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });
- return error.ApiError;
- };
- if (apiErrorMessage(root)) |msg| {
- if (force and std.mem.indexOf(u8, msg, "tool_choice") != null) {
- force = false; // provider can't force a tool; soft-strict
- continue;
- }
- if (stream_usage and std.mem.indexOf(u8, msg, "stream_options") != null) {
- stream_usage = false; // provider can't report streamed usage
- continue;
- }
- if (!self.cap_new and std.mem.indexOf(u8, msg, "max_completion_tokens") != null) {
- self.cap_new = true; // provider wants the post-deprecation name
- continue;
- }
- if (!self.effort_rejected and mentionsReasoningEffort(msg)) {
- self.effort_rejected = true; // model rejects the effort hint here; drop + retry
- continue;
- }
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
- try self.sayApiError("api error: {s}", .{msg});
- return error.ApiError;
- }
-
- self.recordUsage(root);
- if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
- if (json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
- return root;
- }
- }
-
- fn recordUsage(self: *Agent, root: std.json.ObjectMap) void {
- const usage = root.get("usage") orelse return;
- if (usage != .object) return;
- const u = usage.object;
- self.last_cache_read = 0;
- switch (self.provider.kind) {
- .anthropic => {
- var total: i64 = 0;
- const fields = [_][]const u8{
- "input_tokens", "output_tokens",
- "cache_read_input_tokens", "cache_creation_input_tokens",
- };
- for (fields) |f| total += usageInt(u, f);
- if (total > 0) self.last_context_tokens = @intCast(total);
- const cache = usageInt(u, "cache_read_input_tokens");
- if (cache > 0) self.last_cache_read = @intCast(cache);
- // cache writes bill ~like input; fold them into uncached input.
- self.recordCost(usageInt(u, "input_tokens") + usageInt(u, "cache_creation_input_tokens"), cache, usageInt(u, "output_tokens"));
- },
- .openai => {
- if (usageInt(u, "total_tokens") > 0) self.last_context_tokens = @intCast(usageInt(u, "total_tokens"));
- // deepseek reports prompt_cache_hit_tokens; the OpenAI shape
- // nests cached_tokens under prompt_tokens_details.
- var cache = usageInt(u, "prompt_cache_hit_tokens");
- if (cache == 0) if (u.get("prompt_tokens_details")) |d| if (d == .object) {
- cache = usageInt(d.object, "cached_tokens");
- };
- if (cache > 0) self.last_cache_read = @intCast(cache);
- self.recordCost(usageInt(u, "prompt_tokens") - cache, cache, usageInt(u, "completion_tokens"));
- },
- // codex uses recordUsageResponses on its own path.
- .responses => {},
- }
- }
-
- /// An integer usage field, or 0 if absent / wrong type.
- fn usageInt(obj: std.json.ObjectMap, name: []const u8) i64 {
- if (obj.get(name)) |v| if (v == .integer) return v.integer;
- return 0;
- }
-
- /// Record one request's usage into the session-wide tally (g_cost):
- /// token counts always; USD only for API-key providers with a
- /// price_table row. Subscription providers (codex, claude) bill flat
- /// and tally as sub_calls; unpriced models as unpriced_calls.
- fn recordCost(self: *Agent, uncached_in: i64, cache_in: i64, out: i64) void {
- g_cost.add(self.io, self.provider.id, self.provider.model, uncached_in, cache_in, out);
- }
-
- const ResponsesResult = union(enum) { ok: std.json.ObjectMap, err: []const u8 };
-
- /// Pull the final `response` object out of a Codex SSE stream. Scans
- /// `data:` lines for the last `response.completed`/`response.incomplete`
- /// event; reports `response.failed`/`error` events or a plain JSON error
- /// body as an error.
- fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
- // The final output items arrive as individual `response.output_item.done`
- // events; `response.completed` carries usage but an empty output array.
- // Collect the done-items and synthesize a {output, usage} object.
- var items = std.json.Array.init(self.arena);
- var usage: ?Value = null;
- var saw_completed = false;
- var err_msg: ?[]const u8 = null;
- var it = std.mem.tokenizeScalar(u8, body, '\n');
- while (it.next()) |raw_line| {
- const line = std.mem.trim(u8, raw_line, " \r");
- if (!std.mem.startsWith(u8, line, "data:")) continue;
- const payload = std.mem.trim(u8, line["data:".len..], " ");
- if (payload.len == 0 or std.mem.eql(u8, payload, "[DONE]")) continue;
- const v = std.json.parseFromSliceLeaky(Value, self.arena, payload, .{ .allocate = .alloc_always }) catch continue;
- if (v != .object) continue;
- const t = v.object.get("type") orelse continue;
- if (t != .string) continue;
- if (std.mem.eql(u8, t.string, "response.output_item.done")) {
- if (v.object.get("item")) |item| try items.append(item);
- } else if (std.mem.eql(u8, t.string, "response.completed") or std.mem.eql(u8, t.string, "response.incomplete")) {
- saw_completed = true;
- if (v.object.get("response")) |r| if (r == .object) {
- if (r.object.get("usage")) |u| usage = u;
- };
- } else if (std.mem.eql(u8, t.string, "response.failed") or std.mem.eql(u8, t.string, "error")) {
- err_msg = errorMessage(v.object) orelse "codex stream reported a failure";
- }
- }
- if (saw_completed or items.items.len > 0) {
- var resp: std.json.ObjectMap = .empty;
- try resp.put(self.arena, "output", .{ .array = items });
- if (usage) |u| try resp.put(self.arena, "usage", u);
- return .{ .ok = resp };
- }
- if (err_msg) |m| return .{ .err = m };
- // Not an SSE stream — maybe a JSON error body (401, rate limit, …).
- const v = std.json.parseFromSliceLeaky(Value, self.arena, body, .{ .allocate = .alloc_always }) catch return error.Unparseable;
- if (v == .object) if (errorMessage(v.object)) |m| return .{ .err = m };
- return error.Unparseable;
- }
-
- fn errorMessage(obj: std.json.ObjectMap) ?[]const u8 {
- if (obj.get("error")) |e| {
- if (e == .object) {
- if (e.object.get("message")) |m| if (m == .string) return m.string;
- } else if (e == .string) return e.string;
- }
- if (obj.get("response")) |r| if (r == .object) {
- if (r.object.get("error")) |e| if (e == .object) {
- if (e.object.get("message")) |m| if (m == .string) return m.string;
- };
- };
- if (obj.get("detail")) |d| if (d == .string) return d.string;
- if (obj.get("message")) |m| if (m == .string) return m.string;
- return null;
- }
-
- fn recordUsageResponses(self: *Agent, response: std.json.ObjectMap) void {
- self.last_cache_read = 0;
- const usage = response.get("usage") orelse return;
- if (usage != .object) return;
- const u = usage.object;
- const in_tokens = usageInt(u, "input_tokens");
- const out_tokens = usageInt(u, "output_tokens");
- const total_tokens = usageInt(u, "total_tokens");
- if (total_tokens > 0) {
- self.last_context_tokens = @intCast(total_tokens);
- } else {
- // Some Codex/Responses builds report only input/output counts.
- // Still surface the prompt token counter instead of leaving the
- // prompt stuck at "model · sub" with no context usage.
- const computed_total = in_tokens + out_tokens;
- if (computed_total > 0) self.last_context_tokens = @intCast(computed_total);
- }
- var cached: i64 = 0;
- if (u.get("input_tokens_details")) |d| if (d == .object) {
- cached = usageInt(d.object, "cached_tokens");
- if (cached > 0) self.last_cache_read = @intCast(cached);
- };
- self.recordCost(in_tokens - cached, cached, out_tokens);
- }
-
- /// Consume a Codex `response` object: append its output items to history
- /// (verbatim — they're valid Responses input items), surface text, and
- /// collect any function calls. Returns final text when no tools were
- /// called, else null to loop after running them.
- fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {
- const output = response.get("output") orelse return error.ApiError;
- if (output != .array) return error.ApiError;
-
- var calls: std.ArrayList(ToolCall) = .empty;
- defer calls.deinit(self.gpa);
- var final_text: []const u8 = "";
-
- for (output.array.items) |item| {
- if (item != .object) continue;
- try self.messages.append(item); // valid as next-turn input
- const itype = if (item.object.get("type")) |t| (if (t == .string) t.string else "") else "";
- if (std.mem.eql(u8, itype, "message")) {
- if (item.object.get("content")) |c| if (c == .array) {
- for (c.array.items) |block| {
- if (block != .object) continue;
- const bt = if (block.object.get("type")) |x| (if (x == .string) x.string else "") else "";
- if (std.mem.eql(u8, bt, "output_text")) {
- if (block.object.get("text")) |txt| if (txt == .string) {
- final_text = txt.string;
- if (!self.sub and !self.streamed_text) try self.say("{s}\n", .{txt.string});
- };
- }
- }
- };
- } else if (std.mem.eql(u8, itype, "function_call")) {
- const name = if (item.object.get("name")) |n| (if (n == .string) n.string else continue) else continue;
- const call_id = if (item.object.get("call_id")) |c| (if (c == .string) c.string else continue) else continue;
- const args = if (item.object.get("arguments")) |a| (if (a == .string) a.string else "") else "";
- const input: Value = if (args.len == 0)
- .{ .object = .empty }
- else
- std.json.parseFromSliceLeaky(Value, self.arena, args, .{ .allocate = .alloc_always }) catch .{ .object = .empty };
- try calls.append(self.gpa, .{ .id = call_id, .name = name, .input = input });
- }
- }
-
- if (calls.items.len > 0) {
- const results = try self.runTools(calls.items);
- for (calls.items, results) |call, r| {
- const fco = try toolResultMessage(self.arena, .responses, call.id, r.text, r.is_error);
- try self.messages.append(fco);
- }
- if (self.completed) |result| return result;
- return null;
- }
- return final_text;
- }
-
- fn stepAnthropic(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
- const content = root.get("content") orelse {
- try self.say("[api error: response had no content]\n", .{});
- return error.ApiError;
- };
- if (content != .array) {
- try self.say("[api error: malformed content block]\n", .{});
- return error.ApiError;
- }
- const stop_reason = if (root.get("stop_reason")) |s| (if (s == .string) s.string else "") else "";
-
- var assistant: std.json.ObjectMap = .empty;
- try assistant.put(self.arena, "role", .{ .string = "assistant" });
- try assistant.put(self.arena, "content", content);
- try self.messages.append(.{ .object = assistant });
-
- var calls: std.ArrayList(ToolCall) = .empty;
- defer calls.deinit(self.gpa);
- var final_text: []const u8 = "";
- for (content.array.items) |block| {
- if (block != .object) continue;
- const kind = if (block.object.get("type")) |t| (if (t == .string) t.string else "") else "";
- if (std.mem.eql(u8, kind, "text")) {
- if (block.object.get("text")) |tx| if (tx == .string) {
- final_text = tx.string;
- if (!self.sub and !self.streamed_text) try self.say("{s}\n", .{final_text});
- };
- } else if (std.mem.eql(u8, kind, "tool_use")) {
- const name = if (block.object.get("name")) |n| (if (n == .string) n.string else "") else "";
- if (name.len == 0) continue;
- const id = if (block.object.get("id")) |x| (if (x == .string) x.string else "") else "";
- const input = block.object.get("input") orelse Value{ .object = .empty };
- try calls.append(self.gpa, .{ .id = id, .name = name, .input = input });
- }
- }
-
- if (calls.items.len > 0) {
- const results = try self.runTools(calls.items);
- var blocks = std.json.Array.init(self.arena);
- for (calls.items, results) |call, r| {
- const tr = try toolResultMessage(self.arena, .anthropic, call.id, r.text, r.is_error);
- try blocks.append(tr);
- }
- var user_msg: std.json.ObjectMap = .empty;
- try user_msg.put(self.arena, "role", .{ .string = "user" });
- try user_msg.put(self.arena, "content", .{ .array = blocks });
- try self.messages.append(.{ .object = user_msg });
-
- if (self.completed) |result| return result;
- return null; // loop again
- }
-
- if (std.mem.eql(u8, stop_reason, "pause_turn")) return null;
- if (!std.mem.eql(u8, stop_reason, "end_turn")) try self.say("[stopped: {s}]\n", .{stop_reason});
- return final_text;
- }
-
- fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
- const choices = root.get("choices");
- if (choices == null or choices.? != .array or choices.?.array.items.len == 0 or choices.?.array.items[0] != .object) {
- try self.say("[api error: response had no choices]\n", .{});
- return error.ApiError;
- }
- const choice = choices.?.array.items[0].object;
- const message = choice.get("message") orelse {
- try self.say("[api error: choice had no message]\n", .{});
- return error.ApiError;
- };
- try self.messages.append(message); // echo verbatim (content may be null)
-
- var final_text: []const u8 = "";
- if (message.object.get("content")) |c| if (c == .string and c.string.len > 0) {
- final_text = c.string;
- if (!self.sub and !self.streamed_text) try self.say("{s}\n", .{c.string});
- };
-
- var calls: std.ArrayList(ToolCall) = .empty;
- defer calls.deinit(self.gpa);
- if (message.object.get("tool_calls")) |tcs| if (tcs == .array) {
- for (tcs.array.items) |tc| {
- if (tc != .object) continue;
- const function = tc.object.get("function") orelse continue;
- if (function != .object) continue;
- const args_str = if (function.object.get("arguments")) |a| (if (a == .string) a.string else "") else "";
- const input: Value = if (args_str.len == 0)
- .{ .object = .empty }
- else
- (std.json.parseFromSliceLeaky(Value, self.arena, args_str, .{ .allocate = .alloc_always }) catch .{ .object = .empty });
- const name = if (function.object.get("name")) |n| (if (n == .string) n.string else "") else "";
- if (name.len == 0) continue; // can't dispatch a nameless call
- const id = if (tc.object.get("id")) |x| (if (x == .string) x.string else "") else "";
- try calls.append(self.gpa, .{ .id = id, .name = name, .input = input });
- }
- };
-
- if (calls.items.len > 0) {
- const results = try self.runTools(calls.items);
- for (calls.items, results) |call, r| {
- const tool_msg = try toolResultMessage(self.arena, .openai, call.id, r.text, r.is_error);
- try self.messages.append(tool_msg);
- }
- if (self.completed) |result| return result;
- return null;
- }
-
- const finish = choice.get("finish_reason").?;
- if (finish == .string and !std.mem.eql(u8, finish.string, "stop")) try self.say("[stopped: {s}]\n", .{finish.string});
- return final_text;
- }
-
- /// Run a batch of tool calls. Meta tools are handled inline (they mutate
- /// agent state); everything else fans out across the Io thread pool.
- /// Bash calls must clear the permission gate before dispatch. Results
- /// are returned in call order, arena-owned.
- fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
- const results = try self.arena.alloc(ExecResult, calls.len);
-
- // Collect the indices of external (non-meta) calls for parallel exec.
- var ext_idx: std.ArrayList(usize) = .empty;
- defer ext_idx.deinit(self.gpa);
- for (calls, 0..) |call, i| {
- if (try self.rejectToolCall(call)) |denied| {
- results[i] = denied;
- continue;
- }
- try self.sayToolUse(call);
- if (isMetaName(call.name)) {
- results[i] = try self.handleMeta(call);
- } else if (try self.gateTool(call)) |denied| {
- results[i] = denied;
- } else {
- try ext_idx.append(self.gpa, i);
- }
- }
-
- if (ext_idx.items.len > 0) {
- if (ext_idx.items.len > 1 and !self.sub) {
- try self.say(" {s}↯ running {d} tools in parallel{s}\n", .{ style.dim, ext_idx.items.len, style.reset });
- }
- const ctx: ToolCtx = .{
- .gpa = self.gpa,
- .io = self.io,
- .client = self.client,
- .provider = self.provider,
- .registry = if (self.sub) null else self.registry,
- .from_sub = self.sub,
- .approvals = self.approvals,
- .tracer = self.tracer,
- .snapshots = self.snapshots,
- .tools_used = &self.tools_used,
- };
- // Esc while tools run: spawn a stdin watcher for the duration of
- // the join (see esc_cancel). Subagents notice the flag mid-flight;
- // the root aborts the turn at its next runTurn iteration.
- const esc_watch = !self.sub and self.in != null and use_color and !json_mode;
- var esc_tio: ?tty.RawState = null;
- var esc_fut: ?Io.Future(void) = null;
- if (esc_watch) if (rawNonblockStdin()) |tio| {
- esc_tio = tio;
- esc_watch_done.store(false, .release);
- esc_fut = self.io.async(escWatchTask, .{});
- };
- defer if (esc_tio) |tio| {
- esc_watch_done.store(true, .release);
- if (esc_fut) |*f| f.await(self.io);
- drainStdin();
- tty.restore(tio);
- };
- // Join ALL futures before any fallible work: an early error
- // return would otherwise free the futures while pool tasks are
- // still writing into them (and abandon running tools).
- const futures = try self.gpa.alloc(Io.Future(ToolOutput), ext_idx.items.len);
- defer self.gpa.free(futures);
- const outputs = try self.gpa.alloc(ToolOutput, ext_idx.items.len);
- defer self.gpa.free(outputs);
- for (ext_idx.items, futures) |i, *fut| fut.* = self.io.async(execTool, .{ ctx, calls[i] });
- for (futures, outputs) |*fut, *output| output.* = fut.await(self.io);
- defer for (outputs) |output| self.gpa.free(output.text);
- for (ext_idx.items, outputs) |i, output| {
- results[i] = .{ .text = try self.arena.dupe(u8, output.text), .is_error = output.is_error, .ms = output.ms };
- }
- }
- // Show a compact ✓/✗ + preview for each non-meta call (no-op for subs).
- for (calls, results) |call, r| self.sayToolResult(call.name, r);
- return results;
- }
-
- fn rejectToolCall(self: *Agent, call: ToolCall) !?ExecResult {
- if (self.sub) return null;
- if (std.mem.eql(u8, call.name, "attempt_completion")) return null;
- if (max_tool_calls) |max| {
- if (self.tool_calls_this_turn >= max) {
- const message = try std.fmt.allocPrint(self.arena, "tool call budget exhausted ({d}/{d}) — answer with what you have or ask for a higher --max-tool-calls", .{ self.tool_calls_this_turn, max });
- self.emitToolRejected(call, "budget", message);
- return .{ .text = message, .is_error = true };
- }
- }
- if (dedupe_tool_calls) {
- const key = try self.toolDedupeKey(call);
- for (self.seen_tool_keys.items) |seen| {
- if (std.mem.eql(u8, seen, key)) {
- const message = try std.fmt.allocPrint(self.arena, "duplicate tool call rejected: {s} with the same normalized input already ran this turn", .{call.name});
- self.emitToolRejected(call, "duplicate", message);
- return .{ .text = message, .is_error = true };
- }
- }
- try self.seen_tool_keys.append(self.arena, key);
- }
- self.tool_calls_this_turn += 1;
- return null;
- }
-
- fn toolDedupeKey(self: *Agent, call: ToolCall) ![]const u8 {
- var aw: Io.Writer.Allocating = .init(self.arena);
- const w = &aw.writer;
- try w.writeAll(call.name);
- try w.writeByte('\n');
- var s: std.json.Stringify = .{ .writer = w };
- try s.write(call.input);
- const key = aw.writer.buffered();
- for (key) |*c| {
- c.* = if (std.ascii.isWhitespace(c.*)) ' ' else std.ascii.toLower(c.*);
- }
- return key;
- }
-
- fn emitToolRejected(self: *Agent, call: ToolCall, reason: []const u8, message: []const u8) void {
- if (!json_mode) return;
- self.emit(.{ .type = "tool_rejected", .name = call.name, .reason = reason, .input = call.input, .message = message });
- }
-
- /// The permission gate, root side: an unapproved bash command prompts
- /// the user — yes once, always (approve the command's first word for
- /// the rest of the session), or no. Returns the denial result, or null
- /// when cleared to execute. Subagents never prompt; their gate is the
- /// allowlist check in execToolInner.
- pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
- if (self.sub) {
- // Destructive git is blocked for subagents outright — they have no
- // human to confirm with. The root agent falls through to a y/n
- // prompt below. Completes the Codex-style `.git` guard across both.
- if (std.mem.eql(u8, call.name, "bash") and call.input == .object) {
- if (call.input.object.get("command")) |cv| if (cv == .string and Approvals.isDestructiveGit(cv.string)) return .{
- .text = try self.arena.dupe(u8, "destructive git is blocked for subagents (no one to confirm) — leave reset --hard / clean -f / force-push / branch -D to the root session"),
- .is_error = true,
- };
- }
- return null; // subagents: otherwise gated structurally, not by prompt
- }
- const approvals = self.approvals orelse return null;
-
- // Plan mode: read-only, regardless of approvals — deny mutating tools
- // up front (no point prompting for something the mode forbids).
- if (plan_mode) {
- if (std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or
- (mcp.Registry.isMcp(call.name) and !companionReadOnly(call.name, call.input))) return .{
- .text = try self.arena.dupe(u8, "plan mode is on — read-only. Fold this change into the plan you present; the user applies it after approving (/plan toggles the mode off)."),
- .is_error = true,
- };
- if (std.mem.eql(u8, call.name, "bash")) {
- const cmd_val = call.input.object.get("command") orelse return null;
- if (cmd_val != .string) return null;
- const cmd = std.mem.trim(u8, cmd_val.string, " \t");
- if (!Approvals.readOnlyAllowed(cmd)) return .{
- .text = try self.arena.dupe(u8, "plan mode is on — only read-only commands run (ls/cat/grep/git status…). Put this command in the plan instead."),
- .is_error = true,
- };
- return null;
- }
- }
-
- // Decide whether this call needs approval, and what the approval key
- // and prompt line are. bash keys on the command's first word; writes
- // and MCP tools key on the tool name.
- var key: []const u8 = undefined;
- var line_buf: [256]u8 = undefined;
- var prompt_line: []const u8 = undefined;
-
- if (std.mem.eql(u8, call.name, "bash")) {
- const cmd_val = call.input.object.get("command") orelse return null;
- if (cmd_val != .string) return null;
- const cmd = std.mem.trim(u8, cmd_val.string, " \t");
- // Destructive git (reset --hard, clean -f, branch -D, force-push…)
- // stays gated in normal mode + for subagents, but DOES run under --yolo
- // so the agent can't wipe the user's work or a worktree's checkpoints.
- // It falls through to a human y/n (or a deny in non-interactive runs).
- const destructive_git = Approvals.isDestructiveGit(cmd);
- const gate_ok = !destructive_git or Approvals.destructiveGitAllowed(approvals.yolo, self.sub);
- if (gate_ok and approvals.allowed(self.io, cmd)) return null;
- key = firstWord(cmd);
- prompt_line = if (destructive_git)
- std.fmt.bufPrint(&line_buf, "DESTRUCTIVE git — run: {s}", .{cmd}) catch cmd
- else
- std.fmt.bufPrint(&line_buf, "run: {s}", .{cmd}) catch cmd;
- } else if (std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file")) {
- if (approvals.allowedExact(self.io, call.name)) return null;
- key = call.name;
- const path = if (call.input == .object)
- (if (call.input.object.get("path")) |p| (if (p == .string) p.string else "?") else "?")
- else
- "?";
- prompt_line = std.fmt.bufPrint(&line_buf, "{s} {s}", .{ call.name, path }) catch call.name;
- } else if (mcp.Registry.isMcp(call.name)) {
- if (companionTrusted(call.name)) return null; // the whole suite: like native tools
- if (approvals.allowedExact(self.io, call.name)) return null;
- key = call.name;
- prompt_line = std.fmt.bufPrint(&line_buf, "call MCP tool {s}", .{call.name}) catch call.name;
- } else {
- return null; // read_file, subagent, workflow, meta: not gated
- }
-
- // No human to ask (one-shot -p, or stdin gone): deny instead of
- // hanging. Pre-approve in .harness/settings.json or pass --yolo.
- const in = self.in orelse return .{
- .text = try self.arena.dupe(u8, "not pre-approved, and no interactive user to ask in one-shot mode — pre-approve it in .harness/settings.json, or run with --yolo"),
- .is_error = true,
- };
- const w = self.out orelse return .{
- .text = try self.arena.dupe(u8, "not pre-approved, and no interactive user to ask — pre-approve it in .harness/settings.json, or run with --yolo"),
- .is_error = true,
- };
-
- try w.print(" ⚠ {s}\n [y]es once · [a]lways allow \"{s}\" (saved to {s}) · [n]o › ", .{ prompt_line, key, Approvals.settings_path });
- try w.flush();
- const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";
- const answer = std.mem.trim(u8, raw, " \t\r");
- if (answer.len > 0) switch (answer[0]) {
- 'y', 'Y' => return null,
- 'a', 'A' => {
- try approvals.approve(self.io, self.gpa, key);
- if (std.mem.eql(u8, call.name, "bash") and Approvals.isInterpreter(key)) {
- try w.print(" note: \"{s}\" can execute arbitrary code (e.g. {s} -c '…'); approving it is effectively unrestricted.\n", .{ key, key });
- try w.flush();
- }
- return null;
- },
- else => {},
- };
- return .{
- .text = try self.arena.dupe(u8, "user declined this tool call — try another approach or ask them how to proceed"),
- .is_error = true,
- };
- }
-
- fn firstWord(cmd: []const u8) []const u8 {
- const end = std.mem.indexOfAny(u8, cmd, " \t") orelse cmd.len;
- return cmd[0..end];
- }
-
- /// Handle a meta tool inline on the agent's own thread.
- fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
- if (std.mem.eql(u8, call.name, "attempt_completion")) {
- const result = if (call.input.object.get("result")) |r| r.string else "";
- self.completed = try self.arena.dupe(u8, result);
- // Skip the re-print only when the result streamed live in full.
- if (!self.sub and !self.argStreamedFully(call)) try self.say("{s}\n", .{result});
- return .{ .text = "completion recorded", .is_error = false };
- }
- if (std.mem.eql(u8, call.name, "eval")) {
- const note = if (call.input.object.get("note")) |n| (if (n == .string) n.string else "") else "";
- return self.runEval(note);
- }
- if (std.mem.eql(u8, call.name, "todo_write")) {
- self.todos.clearRetainingCapacity();
- if (call.input.object.get("todos")) |list| if (list == .array) {
- for (list.array.items) |item| {
- if (item != .object) continue;
- const content = item.object.get("content") orelse continue;
- if (content != .string) continue;
- const status = if (item.object.get("status")) |st| (if (st == .string) st.string else "pending") else "pending";
- try self.todos.append(self.arena, .{
- .content = try self.arena.dupe(u8, content.string),
- .status = try self.arena.dupe(u8, status),
- });
- }
- };
- const rendered = self.renderTodos();
- if (!self.sub) try self.say("{s}\n", .{rendered});
- return .{ .text = rendered, .is_error = false };
- }
- if (std.mem.eql(u8, call.name, "ask_user")) return self.askUser(call);
- // todo_read
- return .{ .text = self.renderTodos(), .is_error = false };
- }
-
- /// The "user message as a tool" half of the loop: the agent calls
- /// ask_user, we block for a typed reply, and hand it back as the tool
- /// result. Only the root agent has stdin; subagents must self-decide.
- fn askUser(self: *Agent, call: ToolCall) !ExecResult {
- const in = self.in orelse return .{
- .text = "no human is attached — make a reasonable assumption and continue",
- .is_error = true,
- };
- const w = self.out.?;
- const question = if (call.input.object.get("question")) |q| q.string else "(no question)";
- if (json_mode) {
- const call_id = if (call.id.len > 0) call.id else blk: {
- const id = try std.fmt.allocPrint(self.arena, "ask_user-{d}", .{self.next_ask_id});
- self.next_ask_id += 1;
- break :blk id;
- };
- try self.emitAskUser(call_id, question, call.input);
- const raw = (try in.takeDelimiter('\n')) orelse return .{
- .text = "user ended input without answering",
- .is_error = true,
- };
- const parsed = std.json.parseFromSliceLeaky(Value, self.arena, std.mem.trim(u8, raw, " \t\r"), .{ .allocate = .alloc_always }) catch return .{
- .text = "invalid answer JSON for ask_user",
- .is_error = true,
- };
- const answer = parseAnswerRequest(parsed, call_id) catch |err| return .{
- .text = answerParseError(err),
- .is_error = true,
- };
- if (answer.cancelled) return .{ .text = "user cancelled the follow-up", .is_error = true };
- return .{ .text = try self.arena.dupe(u8, answer.text), .is_error = false };
- }
- // Skip the re-print only when the question streamed live in full.
- if (!self.argStreamedFully(call)) try w.print("\n❓ {s}\n", .{question});
- if (call.input.object.get("options")) |opts| if (opts == .array) {
- for (opts.array.items, 1..) |opt, n| try w.print(" {d}) {s}\n", .{ n, opt.string });
- };
- try w.writeAll(" your answer › ");
- try w.flush();
-
- const raw = (try in.takeDelimiter('\n')) orelse return .{
- .text = "user ended input without answering",
- .is_error = true,
- };
- const answer = std.mem.trim(u8, raw, " \t\r");
- return .{ .text = try self.arena.dupe(u8, answer), .is_error = false };
- }
-
- fn emitAskUser(self: *Agent, call_id: []const u8, question: []const u8, input: Value) !void {
- const w = self.out orelse return;
- var s: std.json.Stringify = .{ .writer = w };
- try s.beginObject();
- try s.objectField("type");
- try s.write("ask_user");
- try s.objectField("call_id");
- try s.write(call_id);
- try s.objectField("question");
- try s.write(question);
- try s.objectField("input");
- try s.write(input);
- try s.endObject();
- try w.writeByte('\n');
- try w.flush();
- }
-
+ // The provider round trip (request/buildBody + usage/cost recording +
+ // Codex/Responses SSE reassembly) lives in agent_request.zig (#123,
+ // 600-line goal). Member-aliased so self.request(...)/etc. resolve
+ // unchanged.
+ pub const request = @import("agent_request.zig").request;
+ pub const recordUsage = @import("agent_request.zig").recordUsage;
+ pub const usageInt = @import("agent_request.zig").usageInt;
+ pub const recordCost = @import("agent_request.zig").recordCost;
+ pub const ResponsesResult = @import("agent_request.zig").ResponsesResult;
+ pub const parseResponses = @import("agent_request.zig").parseResponses;
+ pub const errorMessage = @import("agent_request.zig").errorMessage;
+ pub const recordUsageResponses = @import("agent_request.zig").recordUsageResponses;
+ pub const buildBody = @import("agent_request.zig").buildBody;
+ // Non-streaming response parsing (step*) + SSE-stream reassembly
+ // (assemble*) live in agent_steps.zig (#123, 600-line goal).
+ // Member-aliased so self.stepAnthropic(...)/etc. resolve unchanged.
+ pub const stepResponses = @import("agent_steps.zig").stepResponses;
+ pub const stepAnthropic = @import("agent_steps.zig").stepAnthropic;
+ pub const stepOpenAI = @import("agent_steps.zig").stepOpenAI;
+ pub const assembleStream = @import("agent_steps.zig").assembleStream;
+ pub const assembleAnthropic = @import("agent_steps.zig").assembleAnthropic;
+ pub const assembleOpenAI = @import("agent_steps.zig").assembleOpenAI;
+
+ // Tool-call dispatch (runTools, the human-approval gate, meta-tool
+ // handling, tool-call/result UX lines) lives in agent_tools.zig (#123,
+ // 600-line goal). Member-aliased so self.runTools(...)/etc. resolve
+ // unchanged.
+ pub const runTools = @import("agent_tools.zig").runTools;
+ pub const rejectToolCall = @import("agent_tools.zig").rejectToolCall;
+ pub const toolDedupeKey = @import("agent_tools.zig").toolDedupeKey;
+ pub const emitToolRejected = @import("agent_tools.zig").emitToolRejected;
+ pub const gateTool = @import("agent_tools.zig").gateTool;
+ pub const firstWord = @import("agent_tools.zig").firstWord;
+ pub const handleMeta = @import("agent_tools.zig").handleMeta;
+ pub const askUser = @import("agent_tools.zig").askUser;
+ pub const emitAskUser = @import("agent_tools.zig").emitAskUser;
+ pub const sayToolUse = @import("agent_tools.zig").sayToolUse;
+ pub const sayToolResult = @import("agent_tools.zig").sayToolResult;
pub fn renderTodos(self: *Agent) []const u8 {
if (self.todos.items.len == 0) return "(no todos)";
var aw: Io.Writer.Allocating = .init(self.arena);
@@ -4083,509 +3326,24 @@ pub const Agent = struct {
return std.mem.trimEnd(u8, aw.writer.buffered(), "\n");
}
- /// Run the configured --eval scoring command, append the result to the
- /// scores log (.graff/eval-log.tsv), and return a verdict for the model:
- /// score (0-100), best so far, target, and whether the target is met. The
- /// harness runs the command, so the model cannot fake the number. (eval tool)
- fn runEval(self: *Agent, note: []const u8) !ExecResult {
- const cmd = self.eval_cmd orelse return .{
- .text = "no eval command configured - relaunch graff with --eval <scoring cmd> and --until <N>, or ask the user to set one",
- .is_error = true,
- };
- const run = runCapped(self.gpa, self.io, &.{ "/bin/sh", "-c", cmd }, 64 * 1024, 16 * 1024, 0) catch |e|
- return .{ .text = try std.fmt.allocPrint(self.arena, "eval command could not run: {t}", .{e}), .is_error = true };
- defer self.gpa.free(run.stdout);
- defer self.gpa.free(run.stderr);
- self.eval_iter += 1;
- const exit_code: i32 = switch (run.term) {
- .exited => |c| @intCast(c),
- else => -1,
- };
- const det = parseEvalScore(run.stdout) orelse parseEvalScore(run.stderr);
-
- // LLM-as-judge (--judge): an independent subagent inspects the actual
- // artifacts against the rubric and returns its own 0-100 score. Both
- // scores must clear the target, so the binding value is their min().
- // Skip the judge when the deterministic command itself produced no
- // score - fix that first rather than burn a judge run.
- const judge: ?f64 = if (self.eval_judge != null and det != null) self.runJudge(self.eval_judge.?, run.stdout, note) else null;
- const combined: ?f64 = if (self.eval_judge == null)
- det
- else if (det != null and judge != null)
- @min(det.?, judge.?)
- else
- null;
-
- const target_f: f64 = @floatFromInt(self.eval_target);
- const improved = if (combined) |s| (self.eval_best < 0 or s > self.eval_best) else false;
- if (combined) |s| {
- if (self.eval_best < 0 or s > self.eval_best) self.eval_best = s;
- }
- const met = if (combined) |s| s >= target_f else false;
- self.appendEvalLog(note, det, judge, combined, exit_code, met) catch {};
-
- // Feed the eval-driven score into the fleet (docs/hyperagents.md §9.B):
- // on a NEW BEST, submit the genome (this agent's persona) with its achieved
- // score on the pinned eval set (the eval command's fingerprint). Without this
- // the score only ever reached .graff/eval-log.tsv and the DGM/fleet never saw
- // real eval-driven work — only darwincode/JSON-proto runs ever submitted.
- if (combined) |s| {
- if (improved and s > 0) { // s>0: skip the initial-state / total-failure 0 (don't pollute the cell mean)
- if (telemetry.g_telem) |t| {
- const sys = self.systemPrompt();
- const genome_fp = promptFingerprint(sys);
- const esh_fp = promptFingerprint(cmd);
- const genome: []const u8 = &genome_fp;
- const esh: []const u8 = &esh_fp;
- const run_id: []const u8 = &scoring.g_run_id;
- const pclass = providerClass(self.provider.model);
- // --niche tags this score's cell. Without it the score lands in the
- // anonymous "" niche, which pullElites can never match to a builtin —
- // so an eval session that wants to grow a champion must name its role.
- const niche = self.eval_niche;
- // Genome-send (graff-dgm.md §B): the eval genome is this agent's own
- // persona, never spawned via runSub, so its prompt_text never reached
- // the worker. A cell only promotes when harness_scores joins to a
- // harness_genomes row, so ride the genome text over on a `propose`
- // (deduped by prompt_sha) before the score — else a winning eval cell
- // has nothing to serve. Gated on a niche: a "" cell is unpromotable.
- if (niche.len > 0) t.fleetEvent("propose", niche, genome, "", pclass, "", 0, sys);
- const sig = signScore(genome, "", s, run_id, "", "", esh);
- const sig_s: []const u8 = if (scoring.g_score_key != null) &sig else "";
- var provbuf: [512]u8 = undefined;
- const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}", .{ "", "", esh, pclass, niche }) catch "";
- t.scoreEvent(genome, "", s, run_id, sig_s, prov);
- t.fleetEvent("submit", niche, genome, "", pclass, esh, 0, "");
- }
- }
- }
-
- var aw: Io.Writer.Allocating = .init(self.arena);
- const w = &aw.writer;
- if (combined) |s| {
- if (self.eval_judge != null) {
- try w.print("eval #{d}: deterministic {d:.1} + judge {d:.1} -> {d:.1}/100 (best {d:.1}, target {d}). ", .{ self.eval_iter, det.?, judge.?, s, self.eval_best, self.eval_target });
- } else {
- try w.print("eval #{d}: score {d:.1}/100 (best {d:.1}, target {d}). ", .{ self.eval_iter, s, self.eval_best, self.eval_target });
- }
- if (met)
- try w.writeAll("TARGET MET - finish and report the final scores.")
- else if (improved)
- try w.writeAll("Improved - keep going: fix the next biggest failure with one focused change.")
- else
- try w.writeAll("No gain over the best - try a different change; do not build on a regression.");
- } else if (self.eval_judge != null and det != null and judge == null) {
- try w.print("eval #{d}: deterministic score {d:.1}/100, but the judge returned no parseable score (it may have errored). Re-run after checking the rubric. ", .{ self.eval_iter, det.? });
- } else {
- try w.print("eval #{d}: command ran but no score parsed - print a bare number, or JSON with a score field (0-100 or 0-1), on the last line. ", .{self.eval_iter});
- }
- const tail = if (run.stdout.len > 1500) run.stdout[run.stdout.len - 1500 ..] else run.stdout;
- try w.print("\n[exit {d}] eval output (tail):\n{s}", .{ exit_code, tail });
- return .{ .text = try self.arena.dupe(u8, aw.writer.buffered()), .is_error = false };
- }
-
- /// Append one tab-separated row to the scores log (.graff/eval-log.tsv).
- /// Best-effort - a failed write never breaks the loop.
- fn appendEvalLog(self: *Agent, note: []const u8, det: ?f64, judge: ?f64, score: ?f64, exit_code: i32, met: bool) !void {
- Io.Dir.cwd().createDir(self.io, ".graff", .default_dir) catch {};
- const path = ".graff/eval-log.tsv";
- const existing = Io.Dir.cwd().readFileAlloc(self.io, path, self.arena, .limited(2 * 1024 * 1024)) catch "";
- var aw: Io.Writer.Allocating = .init(self.arena);
- const w = &aw.writer;
- try w.writeAll(existing);
- if (existing.len > 0 and existing[existing.len - 1] != '\n') try w.writeByte('\n');
- try w.print("iter={d}\tscore=", .{self.eval_iter});
- if (score) |s| try w.print("{d:.2}", .{s}) else try w.writeAll("NA");
- try w.writeAll("\tdet=");
- if (det) |d| try w.print("{d:.2}", .{d}) else try w.writeAll("NA");
- try w.writeAll("\tjudge=");
- if (judge) |j| try w.print("{d:.2}", .{j}) else try w.writeAll("NA");
- try w.print("\tbest={d:.2}\ttarget={d}\tmet={s}\texit={d}\tnote=", .{ self.eval_best, self.eval_target, if (met) "yes" else "no", exit_code });
- for (note) |ch| try w.writeByte(if (ch < 0x20) ' ' else ch);
- try w.writeByte('\n');
- Io.Dir.cwd().writeFile(self.io, .{ .sub_path = path, .data = aw.writer.buffered() }) catch {};
- }
-
- /// Spawn an independent LLM judge (a read-only subagent) to score the
- /// current work against the --judge rubric on a 0-100 scale. The judge
- /// inspects the real artifacts with its own tools and ends its report with
- /// a `score:` line, parsed the same way as a deterministic eval. Runs on a
- /// pool thread via judgeTask (mirrors workflowTask) so the eval handler can
- /// await it. Returns null if the judge could not run or gave no score.
- fn runJudge(self: *Agent, rubric: []const u8, eval_output: []const u8, note: []const u8) ?f64 {
- const ctx: ToolCtx = .{
- .gpa = self.gpa,
- .io = self.io,
- .client = self.client,
- .provider = self.provider,
- .registry = if (self.sub) null else self.registry,
- .from_sub = self.sub,
- .approvals = self.approvals,
- .tracer = self.tracer,
- .snapshots = self.snapshots,
- .tools_used = &self.tools_used,
- };
- const evidence = if (eval_output.len > 1200) eval_output[eval_output.len - 1200 ..] else eval_output;
- const what = if (note.len > 0) note else "(no note given)";
- const judge_prompt = std.fmt.allocPrint(self.arena,
- \\Score the current state of the work in this directory against the rubric below, on a 0-100 scale.
- \\
- \\RUBRIC:
- \\{s}
- \\
- \\The author's note on the latest change: {s}
- \\
- \\An automated check was also run; its output (tail) is below as evidence. Form your OWN independent judgement of how well the artifacts satisfy the rubric - do not simply echo the check:
- \\---
- \\{s}
- \\---
- \\
- \\Inspect the actual files and artifacts the work produced (read them with your tools; do not modify anything), then score how fully they satisfy the rubric. End your reply with a single final line `score: <N>` where N is an integer from 0 to 100.
- , .{ rubric, what, evidence }) catch return null;
- var fut: Io.Future(ToolOutput) = self.io.async(judgeTask, .{ ctx, judge_prompt });
- const out = fut.await(self.io);
- defer self.gpa.free(out.text);
- if (out.is_error) return null;
- return parseEvalScore(out.text);
- }
-
- fn sayToolUse(self: *Agent, call: ToolCall) !void {
- if (json_mode) {
- if (std.mem.eql(u8, call.name, "ask_user")) return;
- self.emit(.{ .type = "tool_call", .name = call.name, .input = call.input });
- self.emit(.{ .type = "tool_call_started", .name = call.name, .input = call.input });
- return;
- }
- // The ⚙ line would just repeat prose that already streamed live.
- if (self.argStreamedFully(call)) return;
- var aw: Io.Writer.Allocating = .init(self.gpa);
- defer aw.deinit();
- var s: std.json.Stringify = .{ .writer = &aw.writer };
- try s.write(call.input);
- const full = aw.writer.buffered();
- const shown = if (full.len > 160) full[0..160] else full;
- try self.say("{s}⚙{s} {s}{s} {s}{s}{s}{s}\n", .{
- style.dim, style.reset, style.cyan, call.name,
- style.dim, shown,
- if (full.len > 160) "…" else "",
- style.reset,
- });
- }
-
- /// Compact result feedback for one finished tool call: a green ✓ / red ✗
- /// and a one-line preview of what it returned. Root only (subagents have
- /// no writer); meta tools render their own UX, so skip them.
- fn sayToolResult(self: *Agent, name: []const u8, r: ExecResult) void {
- const w = self.out orelse return;
- if (json_mode) {
- if (isMetaName(name) and !std.mem.eql(u8, name, "ask_user")) return;
- self.emit(.{ .type = "tool_result", .name = name, .is_error = r.is_error, .text = r.text });
- self.emit(.{ .type = "tool_call_finished", .name = name, .is_error = r.is_error, .ms = r.ms });
- return;
- }
- if (isMetaName(name)) return;
- const all = std.mem.trim(u8, r.text, " \t\r\n");
- var preview = all;
- if (std.mem.indexOfScalar(u8, preview, '\n')) |nl| preview = preview[0..nl];
- preview = std.mem.trim(u8, preview, " \t\r");
- const shown = if (preview.len > 100) preview[0..100] else preview;
- const truncated = shown.len < all.len; // more content (extra lines or >100 chars)
- const mark = if (r.is_error) "✗" else "✓";
- const mc = if (r.is_error) style.red else style.green;
- var tbuf: [24]u8 = undefined;
- const timing = if (show_timing and r.ms > 0)
- (std.fmt.bufPrint(&tbuf, " ({d}ms)", .{r.ms}) catch "")
- else
- "";
- w.print(" {s}{s}{s}{s}{s}{s} {s}{s}{s}{s}\n", .{
- mc, mark, style.reset, style.dim, timing, style.reset,
- style.dim, shown,
- if (truncated) "…" else "",
- style.reset,
- }) catch return;
- w.flush() catch return;
- }
-
- /// Ask the model for a context-handoff summary (no tools), then restart
- /// history from that summary.
- pub fn compact(self: *Agent) anyerror!usize {
- if (self.messages.items.len == 0) {
- if (!json_mode) try self.say("nothing to compact\n", .{});
- return 0;
- }
- if (!json_mode) try self.say("[compacting ~{d} tokens…]\n", .{self.last_context_tokens});
- try self.messages.append(try textMessage(self.arena, "user", compact_instruction));
- errdefer _ = self.messages.pop();
-
- // The handoff summary is internal — don't stream it to the terminal.
- self.stream_quiet = true;
- defer self.stream_quiet = false;
- const root = try self.request(null);
- const summary = assistantText(self.provider.kind, root);
- if (summary.len == 0) {
- if (!json_mode) try self.say("[compaction failed: empty summary, history unchanged]\n", .{});
- _ = self.messages.pop();
- return error.EmptySummary;
- }
-
- var fresh = std.json.Array.init(self.arena);
- const handoff = try std.fmt.allocPrint(self.arena,
- \\Context: the prior conversation was compacted to save space.
- \\Summary of everything so far:
- \\
- \\{s}
- \\
- \\Continue assisting the user based on this summary.
- , .{summary});
- try fresh.append(try textMessage(self.arena, "user", handoff));
- self.messages = fresh;
- self.last_context_tokens = 0;
- if (!json_mode) try self.say("[history compacted to a {d}-char summary]\n", .{summary.len});
- return summary.len;
- }
-
- fn cleanUserTurn(m: Value) bool {
- if (m != .object) return false;
- const role = m.object.get("role") orelse return false;
- if (role != .string or !std.mem.eql(u8, role.string, "user")) return false;
- const content = m.object.get("content") orelse return true;
- switch (content) {
- .string => return true, // a plain-text user turn
- .array => |arr| {
- // An anthropic user message that only carries tool_result blocks
- // is the response half of a tool call — it can't begin a
- // conversation, so it is not a safe trim boundary.
- for (arr.items) |blk| {
- if (blk != .object) continue;
- const t = blk.object.get("type") orelse continue;
- if (t == .string and std.mem.eql(u8, t.string, "tool_result")) return false;
- }
- return true;
- },
- else => return true,
- }
- }
-
- /// Index to cut history at for an emergency trim: the first clean user turn
- /// at or after the midpoint, so messages[cut..] is always a valid
- /// conversation start (never an orphaned tool_result). null when there is no
- /// safe cut — too short, or only tool_result user messages remain.
- fn emergencyCutIndex(items: []const Value) ?usize {
- if (items.len < 4) return null;
- var i: usize = items.len / 2;
- while (i < items.len) : (i += 1) {
- if (cleanUserTurn(items[i])) return i;
- }
- return null;
- }
-
- /// Last-resort context recovery when compact() itself can't run — typically
- /// because the history already overflows the window, so the summarization
- /// request overflows too and fails. Drops the oldest messages at a safe
- /// boundary; returns the count dropped (0 if none). The next turn re-measures
- /// context from the provider usage.
- fn emergencyTrim(self: *Agent) usize {
- const cut = emergencyCutIndex(self.messages.items) orelse return 0;
- var fresh = std.json.Array.init(self.arena);
- for (self.messages.items[cut..]) |m| fresh.append(m) catch return 0;
- self.messages = fresh;
- self.last_context_tokens = 0;
- return cut;
- }
-
- /// Auto-compaction with recovery. compact() summarizes the whole history in
- /// one request; once context overflows the window that request overflows too
- /// and fails — historically swallowed silently, wedging the session so every
- /// later turn failed at the same huge token count (issue #88). Surface the
- /// failure and, when `trim_on_fail`, emergency-trim so the next turn has
- /// room. Best-effort; never throws into the REPL loop.
- fn compactOrRecover(self: *Agent, trim_on_fail: bool) void {
- if (self.compact()) |_| return else |err| {
- switch (err) {
- error.Interrupted => return, // user hit Esc mid-compaction
- error.EmptySummary => {}, // compact() already explained it
- else => {
- if (json_mode)
- self.emit(.{ .type = "error", .message = std.fmt.allocPrint(self.arena, "auto-compaction failed: {s}", .{@errorName(err)}) catch "auto-compaction failed" })
- else
- self.say("[auto-compaction failed: {t}]\n", .{err}) catch {};
- },
- }
- if (!trim_on_fail) return;
- const dropped = self.emergencyTrim();
- if (dropped > 0) {
- if (json_mode)
- self.emit(.{ .type = "compact", .ok = true, .trimmed = dropped })
- else
- self.say("[context emergency-trimmed: dropped {d} old message(s) so the session can continue]\n", .{dropped}) catch {};
- } else if (!json_mode) {
- self.say("[warning: context too large to compact and could not be trimmed safely]\n", .{}) catch {};
- }
- }
- }
-
- fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bool, stream_usage: bool) ![]u8 {
- var aw: Io.Writer.Allocating = .init(self.gpa);
- errdefer aw.deinit();
- var s: std.json.Stringify = .{ .writer = &aw.writer };
- try s.beginObject();
- try s.objectField("model");
- try s.write(self.provider.model);
- switch (self.provider.kind) {
- .anthropic => {
- try s.objectField("max_tokens");
- try s.write(max_tokens);
- if (stream) {
- try s.objectField("stream");
- try s.write(true);
- }
- // Forced tool_choice conflicts with adaptive thinking; skip
- // thinking only when forcing.
- if (!force_tool) {
- try s.objectField("thinking");
- try s.print("{s}", .{"{\"type\":\"adaptive\"}"});
- }
- // Prompt caching (Anthropic): a cache_control breakpoint on the
- // system block caches the whole stable prefix (system + tools).
- // Must be block-level — a top-level cache_control is invalid.
- // Other anthropic-format providers (minimax) get a plain
- // string, since cache_control isn't part of their API.
- try s.objectField("system");
- const cc = "{\"type\":\"ephemeral\"}";
- if (std.mem.eql(u8, self.provider.id, "anthropic")) {
- try s.beginArray();
- try s.beginObject();
- try s.objectField("type");
- try s.write("text");
- try s.objectField("text");
- try s.write(self.systemPrompt());
- try s.objectField("cache_control");
- try s.print("{s}", .{cc});
- try s.endObject();
- try s.endArray();
- } else {
- try s.write(self.systemPrompt());
- }
- if (tools) |t| {
- try s.objectField("tools");
- try s.print("{s}", .{t});
- if (force_tool) {
- try s.objectField("tool_choice");
- try s.print("{s}", .{"{\"type\":\"any\"}"});
- }
- }
- try s.objectField("messages");
- // Cache the conversation prefix too (not just system) on the real
- // Anthropic API: a rolling cache_control breakpoint on the last
- // message. minimax (anthropic-format, no cache_control) is excluded.
- const cache_msgs = std.mem.eql(u8, self.provider.id, "anthropic");
- try writeAnthropicMessages(&s, self.messages, cache_msgs);
- },
- .openai => {
- // graff's MakeOpenAiCompat: OpenAI deprecated max_tokens in
- // favor of max_completion_tokens — send the new name to the
- // direct OpenAI API, and to any provider that rejected the
- // old one (cap_new, learned via the retry in request()).
- const cap_field = if (std.mem.eql(u8, self.provider.id, "openai") or self.cap_new)
- "max_completion_tokens"
- else
- "max_tokens";
- try s.objectField(cap_field);
- try s.write(max_tokens);
- if (stream) {
- try s.objectField("stream");
- try s.write(true);
- // Without include_usage the stream carries no token
- // counts (context tracking + auto-compaction need them).
- if (stream_usage) {
- try s.objectField("stream_options");
- try s.print("{s}", .{"{\"include_usage\":true}"});
- }
- }
- if (tools) |t| {
- try s.objectField("tools");
- try s.print("{s}", .{t});
- if (force_tool) {
- try s.objectField("tool_choice");
- try s.write("required");
- }
- }
- try s.objectField("messages");
- try s.beginArray();
- try s.beginObject();
- try s.objectField("role");
- try s.write("system");
- try s.objectField("content");
- try s.write(self.systemPrompt());
- try s.endObject();
- for (self.messages.items) |m| try writeOpenAIMessageNormalized(&s, m);
- try s.endArray();
- // Reasoning-effort hint for OpenAI-compatible providers that
- // honor it (codegraff gateway, deepseek). Mirrors the
- // Responses `reasoning.effort` set in the branch below.
- if (self.effortApplies() and !self.effort_rejected) {
- try s.objectField("reasoning_effort");
- try s.write(@tagName(self.reasoning));
- }
- // Kimi K2.7's model card recommends temperature 1.0 + top_p 0.95
- // for its (always-on) Thinking mode; graff otherwise leaves
- // sampling to the server default.
- if (std.mem.eql(u8, self.provider.id, "kimi")) {
- try s.objectField("temperature");
- try s.write(@as(f64, 1.0));
- try s.objectField("top_p");
- try s.write(@as(f64, 0.95));
- }
- },
- .responses => {
- // Codex / ChatGPT Responses API. system prompt → instructions;
- // history items are valid input items; stream is required by
- // the backend (we buffer + parse the SSE). reasoning items are
- // returned encrypted and passed back for cross-turn continuity.
- try s.objectField("instructions");
- try s.write(self.systemPrompt());
- try s.objectField("input");
- try s.write(Value{ .array = self.messages });
- if (tools) |t| {
- try s.objectField("tools");
- try s.print("{s}", .{t});
- try s.objectField("tool_choice");
- try s.write(if (force_tool) "required" else "auto");
- try s.objectField("parallel_tool_calls");
- try s.write(true);
- }
- // Codex "fast" mode (/fast): request the priority service
- // tier for lower latency. This branch is codex-only, so it is
- // never emitted for other providers.
- if (self.fast) {
- try s.objectField("service_tier");
- try s.write("priority");
- }
- try s.objectField("reasoning");
- try s.beginObject();
- try s.objectField("effort");
- try s.write(@tagName(self.reasoning));
- try s.endObject();
- try s.objectField("include");
- try s.beginArray();
- try s.write("reasoning.encrypted_content");
- try s.endArray();
- try s.objectField("store");
- try s.write(false);
- try s.objectField("stream");
- try s.write(true);
- },
- }
- try s.endObject();
- return aw.toOwnedSlice();
- }
-
- /// Streaming POST for the root agent: the same wire request as post(),
- /// but the SSE body is read line-by-line, printing text deltas as they
- /// arrive. Returns the full raw body (gpa-owned) so the caller can
- /// reassemble the response. Non-SSE bodies (error envelopes, providers
- /// that ignore `stream`) pass through unharmed: no delta lines match
- /// and the buffered body falls back to regular parsing.
+ // Context management (compaction/emergency-trim) and the --eval/--until
+ // eval-driven loop (+ optional LLM-as-judge) live in agent_compact.zig
+ // (#123, 600-line goal). Member-aliased so self.compact(...)/etc.
+ // resolve unchanged.
+ pub const runEval = @import("agent_compact.zig").runEval;
+ pub const appendEvalLog = @import("agent_compact.zig").appendEvalLog;
+ pub const runJudge = @import("agent_compact.zig").runJudge;
+ pub const compact = @import("agent_compact.zig").compact;
+ pub const cleanUserTurn = @import("agent_compact.zig").cleanUserTurn;
+ pub const emergencyCutIndex = @import("agent_compact.zig").emergencyCutIndex;
+ pub const emergencyTrim = @import("agent_compact.zig").emergencyTrim;
+ pub const compactOrRecover = @import("agent_compact.zig").compactOrRecover;
+
+ // The live streaming path (thinking spinner, live "Thinking" reasoning
+ // block, and postStream itself — the root agent's streaming POST) lives
+ // in agent_stream.zig (#123, 600-line goal). Member-aliased so
+ // self.postStream(...)/etc. resolve unchanged. g_spin_stop/g_spin_future
+ // below stay here (never alias a `var`).
// ── thinking spinner ────────────────────────────────────────────────
// An animated indicator on the root agent's line while the model is
// silent: from request send, through connect + time-to-first-token,
@@ -4596,350 +3354,16 @@ pub const Agent = struct {
// pool and polls the stop flag every 20ms so stopping is near-instant.
// The animation is picked via /animation (ported in spirit from
// arpagon/pi-animations, MIT) and persists in .harness/settings.json.
- var g_spin_stop: std.atomic.Value(bool) = .init(true);
- var g_spin_future: ?Io.Future(void) = null;
-
- fn spinnerTask(io: Io) void {
- var i: usize = 0;
- var buf: [512]u8 = undefined;
- var w = Io.File.stdout().writer(io, &buf);
- while (!g_spin_stop.load(.acquire)) {
- if (g_steer_visible.load(.acquire)) {
- io.sleep(.fromMilliseconds(20), .awake) catch break;
- continue;
- }
- // Clear-then-draw each frame: animations may vary in width.
- w.interface.writeAll("\r\x1b[2K\x1b[?7l") catch return; // ?7l: autowrap off so a wide spinner truncates instead of wrapping in a narrow window (the "goes on and on" bug)
- anim.anims[anim.g_anim_current].frame(&w.interface, i) catch return;
- w.interface.writeAll("\x1b[?7h") catch return; // restore autowrap
- w.interface.flush() catch return;
- i += 1;
- var t: usize = 0;
- while (t < 4 and !g_spin_stop.load(.acquire)) : (t += 1) {
- if (g_steer_visible.load(.acquire)) break;
- io.sleep(.fromMilliseconds(20), .awake) catch break;
- }
- }
- if (!g_steer_visible.load(.acquire)) {
- w.interface.writeAll("\x1b[?7h\r\x1b[2K") catch return; // restore autowrap + clear
- w.interface.flush() catch {};
- }
- }
-
- fn spinnerStart(self: *Agent) void {
- if (self.sub or json_mode or !use_color or self.out == null) return;
- if (anim.g_anim_off) return;
- if (g_spin_future != null) return;
- anim.selectSpinner(self.io);
- g_spin_stop.store(false, .release);
- g_spin_future = self.io.concurrent(spinnerTask, .{self.io}) catch blk: {
- g_spin_stop.store(true, .release); // no spare concurrency: skip quietly
- break :blk null;
- };
- }
-
- fn spinnerStop(self: *Agent) void {
- if (self.sub) return; // root-only state — subs run on pool threads
- if (g_spin_future) |*f| {
- g_spin_stop.store(true, .release);
- f.await(self.io);
- g_spin_future = null;
- }
- }
-
- /// Stream a chunk of the model's reasoning into a live, dimmed "Thinking"
- /// block in the terminal, opening the block (and handing the line off from
- /// the spinner) on the first chunk. Gated by /thinking; when off the block is
- /// never opened and the spinner stands in for it. We track the block's
- /// on-screen height as it streams so closeThinkingBlock can collapse it to a
- /// one-line summary when the answer starts (#75).
- fn streamThinking(self: *Agent, chunk: []const u8) void {
- const w = self.out orelse return;
- if (!self.thinking_open) {
- self.spinnerStop();
- w.print("{s}▼ Thinking{s}\n{s}", .{ style.dim, style.reset, style.dim }) catch return;
- self.thinking_open = true;
- g_thinking_open = true;
- self.thinking_rows = 1; // the header newline already moved us down one line
- self.thinking_col = 0;
- self.thinking_overflow = false;
- }
- self.thinking_text.appendSlice(self.gpa, chunk) catch {};
- if (self.thinking_folded) return; // folded: buffer only, don't draw the live block
- w.writeAll(chunk) catch return;
- w.flush() catch return;
- advanceThinkingRows(&self.thinking_rows, &self.thinking_col, termCols(), chunk);
- if (self.thinking_rows + 1 >= termRows()) self.thinking_overflow = true;
- }
-
- /// Close an open "Thinking" block. If it still fits on screen, collapse it in
- /// place to a one-line "Thought" summary (#75); if it has scrolled off
- /// (overflow) leave the reasoning and just append the summary, so we never
- /// erase the user's earlier output. Runs on the reasoning->answer transition
- /// and at stream end.
- fn closeThinkingBlock(self: *Agent) void {
- if (!self.thinking_open) return;
- self.thinking_open = false;
- g_thinking_open = false;
- self.thinking_folded = false;
- const w = self.out orelse return;
- if (!self.thinking_overflow and self.thinking_rows >= 1 and use_color) {
- w.print("\x1b[{d}F\x1b[0J{s}✓ Thought{s}\n\n", .{ self.thinking_rows, style.dim, style.reset }) catch return;
- } else {
- w.print("{s}\n{s}✓ Thought{s}\n\n", .{ style.reset, style.dim, style.reset }) catch return;
- }
- w.flush() catch return;
- }
-
- /// Ctrl-T: fold/unfold the live "Thinking" block in place (#92/#85). Only
- /// acts on an open, on-screen block; folding erases it to a one-line marker,
- /// unfolding re-streams the buffered reasoning. Cursor math mirrors
- /// closeThinkingBlock (erase `thinking_rows` lines up, clear to end).
- fn toggleThinkingFold(self: *Agent) void {
- if (!self.thinking_open or self.thinking_overflow or !use_color) return;
- const w = self.out orelse return;
- if (!self.thinking_folded) {
- w.print("\x1b[{d}F\x1b[0J{s}▶ Thinking (folded · ^T){s}\n", .{ self.thinking_rows, style.dim, style.reset }) catch return;
- self.thinking_folded = true;
- self.thinking_rows = 1;
- self.thinking_col = 0;
- } else {
- w.print("\x1b[1F\x1b[0J{s}▼ Thinking{s}\n{s}", .{ style.dim, style.reset, style.dim }) catch return;
- self.thinking_folded = false;
- self.thinking_rows = 1;
- self.thinking_col = 0;
- w.writeAll(self.thinking_text.items) catch return;
- advanceThinkingRows(&self.thinking_rows, &self.thinking_col, termCols(), self.thinking_text.items);
- }
- w.flush() catch return;
- }
-
- fn postStream(self: *Agent, body: []const u8) ![]u8 {
- self.spinnerStart();
- defer self.spinnerStop();
- self.thinking_open = false; // fresh "Thinking" block state per request
- g_thinking_open = false;
- self.thinking_rows = 0;
- self.thinking_col = 0;
- self.thinking_folded = false;
- self.thinking_text.clearRetainingCapacity();
- self.thinking_overflow = false;
- defer self.closeThinkingBlock(); // close a reasoning-only turn's block
- const gpa = self.gpa;
- const provider = self.provider;
- const bearer = switch (provider.auth) {
- .x_api_key => "",
- .bearer => try std.fmt.allocPrint(gpa, "Bearer {s}", .{provider.api_key}),
- };
- defer if (bearer.len > 0) gpa.free(bearer);
- var headers_buf: [6]std.http.Header = undefined;
- const extra = providerHeaders(provider, bearer, &headers_buf);
-
- self.md_buf.clearRetainingCapacity(); // fresh markdown state per stream
- self.arg_live = .{}; // fresh tool-argument extractor per stream
- self.md_fence = false;
- self.md_kind = .classify;
- self.md_span = .normal;
- self.md_word.clearRetainingCapacity();
- self.md_word_vis = 0;
- self.md_col = 0;
- self.md_indent = 0;
- self.md_width = 0; // re-read the terminal width (resizes)
- for (self.md_table.items) |r| gpa.free(r); // an errored stream can leave rows behind
- self.md_table.clearRetainingCapacity();
- self.partial_text.clearRetainingCapacity(); // fresh Esc-interrupt capture
-
- // Esc-interrupt: while the root's request is on a TTY, stdin sits in
- // raw non-blocking no-echo mode — from *before* the connect, so Esc
- // pressed during a slow time-to-first-token wait neither echoes ^[
- // nor leaks into the next prompt. Polled between SSE lines; leftover
- // bytes are drained before canonical mode returns, so gate prompts
- // and the line editor see a clean tty.
- const watch_esc = !self.sub and self.in != null and use_color and !json_mode;
- var orig_tio: ?tty.RawState = null;
- if (watch_esc) {
- orig_tio = rawNonblockStdin();
- // SGR mouse reporting is intentionally NOT enabled. Grabbing the mouse
- // (\x1b[?1000;1006h) makes the terminal forward wheel events to us instead
- // of scrolling its own scrollback, so scrolling up mid-stream got captured
- // as input. Leaving the mouse to the terminal keeps native scroll — parity
- // with Claude Code. The live Thinking block still folds via Ctrl-T (see
- // escPressed); its SGR click-to-fold path stays wired but dormant.
- }
- defer if (orig_tio) |o| {
- _ = drainSteerStdin(true);
- tty.restore(o);
- };
- var req = try self.client.request(.POST, try std.Uri.parse(provider.url), .{
- .redirect_behavior = .unhandled,
- .headers = .{
- .content_type = .{ .override = "application/json" },
- .user_agent = providerUserAgent(provider),
- },
- .extra_headers = extra,
- });
- defer req.deinit();
- // A failed SEND leaves reader.state == .ready, which Request.deinit
- // reads as "connection still clean" and returns it to the keep-alive
- // pool — every retry (and every later turn) then pulls the same dead
- // connection back out: HttpConnectionClosing once, WriteFailed
- // forever after (observed in the wild). Poison it on any error so
- // deinit discards it and the retry dials fresh.
- errdefer if (req.connection) |conn| {
- conn.closing = true;
- };
- // Race the send + head receive against a stall watchdog so a
- // freshly-redialed connection that the server accepts but never
- // answers can't hang the turn (issue #54: "retrying (1/3)" then
- // "thinking… forever"). Mirrors the SSE line-loop and postWatched
- // patterns. Falls back to a bare send+receiveHead (the old behavior)
- // when no spare concurrency exists.
- var response: std.http.Client.Response = undefined;
- head: {
- const HeadDone = union(enum) { sent: anyerror!void, stall: WatchdogFired };
- var hd_buf: [2]HeadDone = undefined;
- var hsel: Io.Select(HeadDone) = .init(self.io, &hd_buf);
- hsel.concurrent(.sent, sendHeadTask, .{ &req, body, &response }) catch {
- // No spare concurrency: accept the hang risk (existing behavior).
- req.transfer_encoding = .{ .content_length = body.len };
- var bw = try req.sendBodyUnflushed(&.{});
- try bw.writer.writeAll(body);
- try bw.end();
- try req.connection.?.flush();
- response = try req.receiveHead(&.{});
- break :head;
- };
- hsel.concurrent(.stall, headStallTask, .{ self.io, orig_tio != null }) catch {
- const r = hsel.await() catch |e| {
- hsel.cancelDiscard();
- return e;
- };
- hsel.cancelDiscard();
- r.sent catch |e| {
- return e;
- };
- break :head;
- };
- const first = hsel.await() catch |e| {
- hsel.cancelDiscard();
- return e;
- };
- hsel.cancelDiscard();
- switch (first) {
- .sent => |s| s catch |e| {
- return e;
- },
- .stall => |w| {
- if (req.connection) |conn| conn.closing = true;
- return if (w == .esc) error.Interrupted else error.HungRequest;
- },
- }
- }
-
- // 429/5xx before any body: a retryable throttle — request() backs
- // off and retries (surfaced in the trace as a "retry" note).
- const status_code = @intFromEnum(response.head.status);
- if (status_code == 429 or status_code >= 500) {
- // Drain a snippet of the error body so the retry message can
- // surface the gateway's diagnostic (e.g. "upstream timeout")
- // instead of a bare "server error (5xx)".
- capture5xxBodyStream(self.gpa, &response);
- if (req.connection) |conn| conn.closing = true;
- return if (status_code == 429) error.RateLimited else error.ServerError;
- }
- // Esc pressed while connecting / waiting for headers? Stop before
- // reading any of the body.
- if (orig_tio != null and escPressed(true)) {
- if (req.connection) |conn| conn.closing = true;
- return error.Interrupted;
- }
-
- const decompress_buffer: []u8 = switch (response.head.content_encoding) {
- .identity => &.{},
- .zstd => try gpa.alloc(u8, std.compress.zstd.default_window_len),
- .deflate, .gzip => try gpa.alloc(u8, std.compress.flate.max_window_len),
- .compress => return error.UnsupportedCompressionMethod,
- };
- defer if (decompress_buffer.len > 0) gpa.free(decompress_buffer);
- var transfer_buffer: [64]u8 = undefined;
- var decompress: std.http.Decompress = undefined;
- const reader = response.readerDecompressing(&transfer_buffer, &decompress, decompress_buffer);
-
- var full: Io.Writer.Allocating = .init(gpa);
- errdefer full.deinit();
- var line: Io.Writer.Allocating = .init(gpa);
- defer line.deinit();
-
- while (true) {
- // Race the line read against an idle-stall watchdog so a dead
- // stream can't hang the turn (the Esc escape below is TTY-only, so
- // --json/GUI sessions would otherwise wait forever).
- read: {
- const ReadDone = union(enum) { line: anyerror!usize, stall: WatchdogFired };
- var rd_buf: [2]ReadDone = undefined;
- var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);
- rsel.concurrent(.line, streamLineTask, .{ reader, &line.writer }) catch {
- _ = try reader.streamDelimiterEnding(&line.writer, '\n'); // no spare concurrency
- break :read;
- };
- rsel.concurrent(.stall, streamStallTask, .{ self.io, orig_tio != null }) catch {
- const r = rsel.await() catch |e| {
- rsel.cancelDiscard();
- return e;
- };
- rsel.cancelDiscard();
- _ = try r.line;
- break :read;
- };
- const first = rsel.await() catch |e| {
- rsel.cancelDiscard();
- return e;
- };
- rsel.cancelDiscard();
- switch (first) {
- .line => |r| _ = try r,
- .stall => |w| {
- self.flushStreamTail();
- if (req.connection) |conn| conn.closing = true;
- if (w == .deadline and !json_mode) if (self.out) |o| {
- o.writeAll("\n⚠ stream stalled — ending turn\n") catch {};
- o.flush() catch {};
- };
- return error.Interrupted;
- },
- }
- }
- // End of stream leaves the reader empty; otherwise the '\n' is
- // still buffered (and consumed below, after the line is handled).
- const more = if (reader.peekByte()) |_| true else |_| false;
- try full.writer.writeAll(line.writer.buffered());
- try full.writer.writeByte('\n');
- self.printDelta(line.writer.buffered());
- if (g_thinking_fold_request) {
- g_thinking_fold_request = false;
- self.toggleThinkingFold();
- }
- line.clearRetainingCapacity();
- if ((orig_tio != null and escPressed(true)) or (self.sub and esc_cancel.load(.acquire))) {
- self.flushStreamTail();
- // Mark the connection closing so req.deinit() tears it down
- // instead of draining the rest of the stream (which would
- // block until the model finished generating anyway). Subs get
- // here via esc_cancel: the root saw Esc during a tool join.
- if (req.connection) |conn| conn.closing = true;
- return error.Interrupted;
- }
- if (!more) break;
- reader.toss(1);
- }
- self.flushStreamTail(); // render any held partial markdown line
- if (!json_mode and self.streamed_text) if (self.out) |w| {
- w.writeAll("\n") catch {};
- w.flush() catch {};
- };
- return full.toOwnedSlice();
- }
-
+ pub var g_spin_stop: std.atomic.Value(bool) = .init(true);
+ pub var g_spin_future: ?Io.Future(void) = null;
+ pub const spinnerTask = @import("agent_stream.zig").spinnerTask;
+ pub const spinnerStart = @import("agent_stream.zig").spinnerStart;
+ pub const spinnerStop = @import("agent_stream.zig").spinnerStop;
+ pub const streamThinking = @import("agent_stream.zig").streamThinking;
+ pub const closeThinkingBlock = @import("agent_stream.zig").closeThinkingBlock;
+ pub const toggleThinkingFold = @import("agent_stream.zig").toggleThinkingFold;
+ pub const postStream = @import("agent_stream.zig").postStream;
+ pub const printDelta = @import("agent_stream.zig").printDelta;
/// Esc-during-tools cancellation. postStream only watches stdin while an
/// HTTP stream is live, so a long tool join (bash, a subagent fan-out, a
/// whole workflow) used to be Esc-deaf — exactly when turns feel longest.
@@ -4948,1447 +3372,69 @@ pub const Agent = struct {
/// turn iterations, and the root consumes at its next loop head as
/// error.Interrupted.
pub var esc_cancel: std.atomic.Value(bool) = .init(false);
- var esc_watch_done: std.atomic.Value(bool) = .init(true);
-
- fn escWatchTask() void {
- while (!esc_watch_done.load(.acquire)) {
- if (tty.poll(100) and escPressed(false)) {
- esc_cancel.store(true, .release);
- return;
- }
- }
- }
-
- /// Non-blocking scan of stdin (terminal must be in VMIN=0 raw mode). A
- /// lone Esc cancels the turn (returns true); CSI sequences (arrows:
- /// ESC[…/ESC O…) are swallowed and don't cancel. Printable bytes are
- /// captured into the steering buffer and echoed when `echo` (main thread
- /// only — the esc watch task runs on the pool and must not race tool
- /// output); Enter flushes the line to g_steer_queue, which the REPL
- /// drains as follow-up turns after the current one finishes. A second
- /// Enter on an empty line (double-enter) with a non-empty queue
- /// force-interrupts the current turn so the queue drains immediately.
- fn escPressed(echo: bool) bool {
- var buf: [256]u8 = undefined;
- var n = tty.readStdin(&buf);
- var esc_found = false;
- var i: usize = 0;
- while (i < n) : (i += 1) {
- const c = buf[i];
- if (c == 0x1b) {
- if (i + 1 < n and buf[i + 1] == '[') {
- // CSI escape sequence (arrows, Home/End, Delete, DSR reply,
- // mouse, etc.). Consume through the final byte (0x40..0x7e) so
- // bytes like "[A" never get captured as steering prompt text. A
- // CSI run can straddle a VMIN=0 read boundary — e.g. the
- // \x1b[<row>;<col>R cursor-position reply to our \x1b[6n, or a
- // burst of SGR mouse-wheel reports if click-to-fold reporting is
- // re-enabled. If the final byte hasn't landed yet, poll briefly and
- // pull the tail into the same buffer so its trailing digits/';'/
- // final byte don't leak in as steer text.
- var j = i + 2;
- while (true) {
- while (j < n) : (j += 1) {
- if (buf[j] >= 0x40 and buf[j] <= 0x7e) break;
- }
- if (j < n or n >= buf.len or !tty.poll(50)) break;
- const more = tty.readStdin(buf[n..]);
- if (more == 0) break;
- n += more;
- }
- // SGR mouse report (ESC [ < btn ; col ; row, M=press/m=release):
- // a plain left-button press (btn 0) on the live Thinking block
- // toggles its fold — the clickable control for #92. Other mouse
- // events fall through and are swallowed like any CSI sequence.
- if (j < n and buf[j] == 'M' and i + 2 < n and buf[i + 2] == '<') {
- var mk = i + 3;
- var btn: usize = 0;
- var got = false;
- while (mk < j and buf[mk] >= '0' and buf[mk] <= '9') : (mk += 1) {
- btn = btn * 10 + (buf[mk] - '0');
- got = true;
- }
- if (got and btn == 0 and g_thinking_open) g_thinking_fold_request = true;
- }
- i = if (j < n) j else n - 1;
- continue;
- } else if (i + 1 < n and buf[i + 1] == 'O') {
- // SS3 escape sequence (common for function/cursor keys):
- // ESC O <final>. Swallow the whole sequence.
- i = @min(i + 2, n - 1);
- continue;
- } else if (i + 1 >= n) {
- // ESC is the LAST byte of this chunk — it may be the truncated
- // head of a split CSI/SS3/DSR sequence (e.g. a delayed
- // `\x1b[<row>;<col>R` cursor-position reply to our `\x1b[6n`)
- // read across two VMIN=0 reads, NOT a real Esc keypress (#94).
- // Briefly wait for a continuation before concluding it's an Esc.
- if (tty.poll(50)) {
- var more: [64]u8 = undefined;
- if (tty.readStdin(&more) > 0) {
- i = n; // a sequence/alt-chord followed — not a lone Esc
- continue;
- }
- }
- // Nothing followed within the grace window: a genuine lone Esc.
- esc_found = true;
- g_force_interrupt = false;
- } else {
- // ESC + a non-CSI/SS3 byte in the same chunk: a real Esc.
- esc_found = true;
- g_force_interrupt = false;
- }
- continue;
- } else if (c == '\n' or c == '\r') {
- if (g_steer_buf.items.len > 0) {
- // Flush the typed line to the queue as a regular
- // follow-up (runs after the current turn finishes).
- if (g_steer_buf.toOwnedSlice(std.heap.page_allocator)) |dup| {
- g_steer_queue.append(std.heap.page_allocator, .{ .text = dup, .force = false }) catch std.heap.page_allocator.free(dup);
- } else |_| g_steer_buf.clearRetainingCapacity();
- if (echo and g_steer_echoed) {
- var qbuf: [64]u8 = undefined;
- const qmsg = std.fmt.bufPrint(&qbuf, " \x1b[2m[queued · {d} waiting]\x1b[0m\n", .{g_steer_queue.items.len}) catch "\n";
- steerEcho(qmsg);
- }
- } else if (g_steer_queue.items.len > 0) {
- // Double-enter (empty line + queue non-empty): force —
- // promote the first queued item and interrupt the
- // current turn so the queue drains starting now.
- g_steer_queue.items[0].force = true;
- esc_found = true;
- g_force_interrupt = true;
- if (echo) {
- if (g_steer_echoed) steerEcho("\n");
- steerEcho("\x1b[33m↳ force › interrupting…\x1b[0m\n");
- }
- }
- g_steer_echoed = false;
- g_steer_visible.store(false, .release);
- continue;
- } else if (c == 0x7f or c == 0x08) { // backspace / Ctrl-H
- if (g_steer_buf.items.len > 0) {
- _ = g_steer_buf.pop();
- if (echo) steerEcho("\x08 \x08");
- }
- continue;
- } else if (c == 0x14) { // Ctrl-T: fold/unfold the live Thinking block (#92)
- g_thinking_fold_request = true;
- continue;
- } else if (c < 0x20) {
- continue; // other control bytes: ignore
- }
- g_steer_buf.append(std.heap.page_allocator, c) catch continue;
- if (echo) {
- if (!g_steer_echoed) {
- g_steer_visible.store(true, .release);
- steerEcho("\n\x1b[36m↳ steer ›\x1b[0m ");
- g_steer_echoed = true;
- }
- steerEcho(buf[i .. i + 1]);
- }
- }
- return esc_found;
- }
-
- /// Process any bytes queued on stdin (terminal must be in VMIN=0 raw
- /// mode) so typed-ahead steering text is preserved instead of leaking into
- /// the next prompt or being blindly discarded. Returns true if Esc/force
- /// was seen while draining.
- pub fn drainSteerStdin(echo: bool) bool {
- var esc_found = false;
- while (true) {
- if (!tty.poll(0)) return esc_found;
- if (escPressed(echo)) esc_found = true;
- }
- }
-
- fn drainStdin() void {
- _ = drainSteerStdin(false);
- }
-
- /// Put stdin into raw non-blocking no-echo mode (VMIN=0) for Esc
- /// watching. Returns the termios to restore, or null off-tty.
- fn rawNonblockStdin() ?tty.RawState {
- return tty.enterRaw(false);
- }
-
- /// Sleep `ms` watching stdin for Esc (when the root is on a TTY), so the
- /// user can cancel a retry backoff instead of waiting it out.
- fn sleepInterruptible(self: *Agent, ms: u64) error{Interrupted}!void {
- const watch = !self.sub and self.in != null and use_color and !json_mode;
- const orig_tio: ?tty.RawState = if (watch) rawNonblockStdin() else null;
- defer if (orig_tio) |o| tty.restore(o);
- var left = ms;
- while (left > 0) {
- const chunk = @min(left, 100);
- self.io.sleep(.fromMilliseconds(@intCast(chunk)), .awake) catch {};
- left -= chunk;
- if (orig_tio != null and escPressed(true)) return error.Interrupted;
- }
- }
-
- /// The `data: {...}` payload of one SSE line, or null for anything else
- /// (event: lines, keep-alive blanks, [DONE]).
- fn ssePayload(raw_line: []const u8) ?[]const u8 {
- const line = std.mem.trim(u8, raw_line, " \r");
- if (!std.mem.startsWith(u8, line, "data:")) return null;
- const payload = std.mem.trim(u8, line["data:".len..], " ");
- if (payload.len == 0 or std.mem.eql(u8, payload, "[DONE]")) return null;
- return payload;
- }
-
- fn sseIndex(obj: std.json.ObjectMap) ?usize {
- const ix = obj.get("index") orelse return null;
- if (ix != .integer or ix.integer < 0) return null;
- return @intCast(ix.integer);
- }
-
- /// Print the user-visible text from one SSE line, if any. Best-effort:
- /// parse failures are ignored (the buffered body is parsed afterwards).
- fn printDelta(self: *Agent, raw_line: []const u8) void {
- const w = self.out orelse return;
- const payload = ssePayload(raw_line) orelse return;
- const parsed = std.json.parseFromSlice(Value, self.gpa, payload, .{}) catch return;
- defer parsed.deinit();
- if (parsed.value != .object) return;
- const obj = parsed.value.object;
- self.argLiveDelta(obj);
- const text: []const u8 = switch (self.provider.kind) {
- .anthropic => blk: {
- const t = obj.get("type") orelse break :blk "";
- if (t != .string or !std.mem.eql(u8, t.string, "content_block_delta")) break :blk "";
- const d = obj.get("delta") orelse break :blk "";
- if (d != .object) break :blk "";
- const dt = d.object.get("type") orelse break :blk "";
- if (dt != .string or !std.mem.eql(u8, dt.string, "text_delta")) break :blk "";
- const x = d.object.get("text") orelse break :blk "";
- break :blk if (x == .string) x.string else "";
- },
- .openai => blk: {
- const choices = obj.get("choices") orelse break :blk "";
- if (choices != .array or choices.array.items.len == 0) break :blk "";
- const c0 = choices.array.items[0];
- if (c0 != .object) break :blk "";
- const d = c0.object.get("delta") orelse break :blk "";
- if (d != .object) break :blk "";
- const x = d.object.get("content") orelse break :blk "";
- break :blk if (x == .string) x.string else "";
- },
- .responses => blk: {
- const t = obj.get("type") orelse break :blk "";
- if (t != .string or !std.mem.eql(u8, t.string, "response.output_text.delta")) break :blk "";
- const x = obj.get("delta") orelse break :blk "";
- break :blk if (x == .string) x.string else "";
- },
- };
- // Reasoning/thinking deltas: deepseek streams reasoning_content, anthropic
- // a thinking_delta, codex a summary delta. JSON clients get a `reasoning`
- // event; on a TTY we stream it into a live, dimmed "Thinking" block when
- // /thinking is enabled, otherwise the spinner stands in for it.
- const reasoning = reasoningDelta(self.provider.kind, obj);
- if (reasoning.len != 0) {
- if (json_mode) {
- self.emit(.{ .type = "reasoning", .text = reasoning });
- } else if (self.show_thinking and !self.sub and !self.stream_quiet and use_color) {
- self.streamThinking(reasoning);
- }
- }
- if (text.len == 0) return;
- if (self.thinking_open) self.closeThinkingBlock(); // reasoning → answer transition
- self.spinnerStop(); // first visible byte: clear the thinking line
- self.streamed_text = true;
- self.partial_text.appendSlice(self.arena, text) catch {}; // Esc-interrupt capture
- if (json_mode) {
- self.emit(.{ .type = "text", .text = text });
- } else if (use_color) {
- self.streamMarkdown(text);
- } else {
- w.writeAll(text) catch return;
- w.flush() catch return;
- }
- }
-
- const ArgTool = enum { none, attempt_completion, ask_user };
-
- fn argToolFor(name: []const u8) ArgTool {
- if (std.mem.eql(u8, name, "attempt_completion")) return .attempt_completion;
- if (std.mem.eql(u8, name, "ask_user")) return .ask_user;
- return .none;
- }
-
- fn argField(tool: ArgTool) []const u8 {
- return switch (tool) {
- .attempt_completion => "result",
- .ask_user => "question",
- .none => "",
- };
- }
-
- /// Live tool-argument text. attempt_completion and ask_user carry their
- /// user-facing prose inside tool-call argument JSON, which the text-delta
- /// matching in printDelta can't see — in strict mode that's the *whole*
- /// answer, so the turn looked frozen while it streamed, then dumped at
- /// once. This is a byte-at-a-time scanner over the argument fragments:
- /// skip to the target string field at the top level of the args object
- /// ("result" / "question"), then unescape its value and print it as it
- /// arrives. Best-effort mirror of the real parse that follows the stream
- /// — a glitch here is cosmetic, never semantic.
- const ArgLive = struct {
- tool: ArgTool = .none, // which whitelisted call is open
- index: i64 = -1, // the provider's stream index for that call
- state: State = .seek_key,
- depth: u32 = 0, // container nesting while skipping a non-target value
- in_str: bool = false, // inside a skipped string
- esc: bool = false, // previous byte was '\'
- uni_left: u8 = 0, // hex digits still expected in a \uXXXX escape
- uni_val: u16 = 0,
- hi_sur: u16 = 0, // pending UTF-16 high surrogate (0 = none)
- key: [24]u8 = undefined,
- key_len: usize = 0,
- key_over: bool = false, // key overflowed/escaped — cannot be the target
-
- const State = enum { seek_key, key, post_key, pre_val, skip_val, val, done };
-
- fn open(self: *ArgLive, name: []const u8, ix: i64) void {
- const tool = argToolFor(name);
- if (tool == .none) return;
- self.* = .{ .tool = tool, .index = ix };
- }
-
- fn close(self: *ArgLive, ix: i64) void {
- if (ix == self.index) self.* = .{};
- }
-
- fn feed(self: *ArgLive, agent: *Agent, ix: i64, frag: []const u8) void {
- if (self.tool == .none or ix != self.index or self.state == .done) return;
- var out_buf: [512]u8 = undefined;
- var out_len: usize = 0;
- for (frag) |c| {
- if (out_len > out_buf.len - 8) { // keep room for one decoded escape
- agent.emitArgText(self.tool, out_buf[0..out_len]);
- out_len = 0;
- }
- switch (self.state) {
- .done => break,
- .seek_key => switch (c) {
- '"' => {
- self.state = .key;
- self.key_len = 0;
- self.key_over = false;
- },
- '}' => self.state = .done,
- else => {}, // '{', ',', whitespace
- },
- .key => if (self.esc) {
- self.esc = false;
- self.key_over = true; // escaped keys never match the plain target
- } else switch (c) {
- '\\' => self.esc = true,
- '"' => self.state = .post_key,
- else => if (self.key_len < self.key.len) {
- self.key[self.key_len] = c;
- self.key_len += 1;
- } else {
- self.key_over = true;
- },
- },
- .post_key => if (c == ':') {
- self.state = .pre_val;
- },
- .pre_val => switch (c) {
- ' ', '\t', '\r', '\n' => {},
- '"' => if (!self.key_over and std.mem.eql(u8, self.key[0..self.key_len], argField(self.tool))) {
- self.state = .val;
- } else {
- self.state = .skip_val;
- self.in_str = true;
- self.depth = 0;
- },
- '{', '[' => {
- self.state = .skip_val;
- self.in_str = false;
- self.depth = 1;
- },
- else => { // number / true / false / null
- self.state = .skip_val;
- self.in_str = false;
- self.depth = 0;
- },
- },
- .skip_val => if (self.in_str) {
- if (self.esc) {
- self.esc = false;
- } else if (c == '\\') {
- self.esc = true;
- } else if (c == '"') {
- self.in_str = false;
- if (self.depth == 0) self.state = .seek_key;
- }
- } else switch (c) {
- '"' => self.in_str = true,
- '{', '[' => self.depth += 1,
- ']' => {
- if (self.depth > 0) self.depth -= 1;
- if (self.depth == 0) self.state = .seek_key;
- },
- '}' => if (self.depth == 0) {
- self.state = .done; // end of the args object
- } else {
- self.depth -= 1;
- if (self.depth == 0) self.state = .seek_key;
- },
- ',' => if (self.depth == 0) {
- self.state = .seek_key;
- },
- else => {},
- },
- .val => {
- if (self.uni_left > 0) {
- const d = std.fmt.charToDigit(c, 16) catch {
- self.uni_left = 0; // malformed escape: drop it
- continue;
- };
- self.uni_val = self.uni_val * 16 + d;
- self.uni_left -= 1;
- if (self.uni_left == 0) out_len += self.takeUnit(out_buf[out_len..]);
- continue;
- }
- if (self.esc) {
- self.esc = false;
- switch (c) {
- 'n' => out_len += self.put(out_buf[out_len..], '\n'),
- 't' => out_len += self.put(out_buf[out_len..], '\t'),
- 'r' => out_len += self.put(out_buf[out_len..], '\r'),
- 'b' => out_len += self.put(out_buf[out_len..], 0x08),
- 'f' => out_len += self.put(out_buf[out_len..], 0x0c),
- 'u' => {
- self.uni_left = 4;
- self.uni_val = 0;
- },
- else => out_len += self.put(out_buf[out_len..], c), // " \ /
- }
- } else switch (c) {
- '\\' => self.esc = true,
- '"' => self.state = .done, // value captured — nothing else prints
- else => out_len += self.put(out_buf[out_len..], c),
- }
- },
- }
- }
- if (out_len > 0) agent.emitArgText(self.tool, out_buf[0..out_len]);
- }
-
- /// Emit one literal byte, flushing any orphaned high surrogate first.
- fn put(self: *ArgLive, buf: []u8, c: u8) usize {
- var n: usize = 0;
- if (self.hi_sur != 0) {
- n = replacement(buf);
- self.hi_sur = 0;
- }
- buf[n] = c;
- return n + 1;
- }
-
- /// A completed \uXXXX code unit: pair surrogates, emit UTF-8.
- fn takeUnit(self: *ArgLive, buf: []u8) usize {
- const u = self.uni_val;
- self.uni_val = 0;
- if (u >= 0xD800 and u <= 0xDBFF) { // high surrogate: hold for its pair
- var n: usize = 0;
- if (self.hi_sur != 0) n = replacement(buf); // two highs in a row
- self.hi_sur = u;
- return n;
- }
- var cp: u21 = u;
- var n: usize = 0;
- if (u >= 0xDC00 and u <= 0xDFFF) { // low surrogate
- if (self.hi_sur == 0) return replacement(buf); // unpaired
- cp = 0x10000 + (@as(u21, self.hi_sur - 0xD800) << 10) + (u - 0xDC00);
- self.hi_sur = 0;
- } else if (self.hi_sur != 0) {
- n = replacement(buf); // high surrogate not followed by a low
- self.hi_sur = 0;
- }
- n += std.unicode.utf8Encode(cp, buf[n..]) catch 0;
- return n;
- }
-
- fn replacement(buf: []u8) usize {
- @memcpy(buf[0..3], "\u{FFFD}");
- return 3;
- }
- };
-
- fn outputIndex(obj: std.json.ObjectMap) ?i64 {
- const ix = obj.get("output_index") orelse return null;
- return if (ix == .integer) ix.integer else null;
- }
-
- /// Track tool-call open/delta/close events in the SSE stream and feed
- /// attempt_completion / ask_user argument fragments to the ArgLive
- /// extractor for live printing. Root interactive streams only — SDK
- /// (--json) clients get the assembled tool_call event instead.
- fn argLiveDelta(self: *Agent, obj: std.json.ObjectMap) void {
- if (self.sub or json_mode or self.stream_quiet) return;
- switch (self.provider.kind) {
- .anthropic => {
- const t = obj.get("type") orelse return;
- if (t != .string) return;
- if (std.mem.eql(u8, t.string, "content_block_start")) {
- const ix = sseIndex(obj) orelse return;
- const cb = obj.get("content_block") orelse return;
- if (cb != .object) return;
- const bt = cb.object.get("type") orelse return;
- if (bt != .string or !std.mem.eql(u8, bt.string, "tool_use")) return;
- const name = cb.object.get("name") orelse return;
- if (name == .string) self.arg_live.open(name.string, @intCast(ix));
- } else if (std.mem.eql(u8, t.string, "content_block_delta")) {
- const ix = sseIndex(obj) orelse return;
- const d = obj.get("delta") orelse return;
- if (d != .object) return;
- const dt = d.object.get("type") orelse return;
- if (dt != .string or !std.mem.eql(u8, dt.string, "input_json_delta")) return;
- const pj = d.object.get("partial_json") orelse return;
- if (pj == .string) self.arg_live.feed(self, @intCast(ix), pj.string);
- } else if (std.mem.eql(u8, t.string, "content_block_stop")) {
- const ix = sseIndex(obj) orelse return;
- self.arg_live.close(@intCast(ix));
- }
- },
- .openai => {
- const choices = obj.get("choices") orelse return;
- if (choices != .array or choices.array.items.len == 0) return;
- const c0 = choices.array.items[0];
- if (c0 != .object) return;
- const d = c0.object.get("delta") orelse return;
- if (d != .object) return;
- const tcs = d.object.get("tool_calls") orelse return;
- if (tcs != .array) return;
- for (tcs.array.items) |tc| {
- if (tc != .object) continue;
- const ix: i64 = if (tc.object.get("index")) |iv|
- (if (iv == .integer) iv.integer else 0)
- else
- 0;
- const f = tc.object.get("function") orelse continue;
- if (f != .object) continue;
- if (f.object.get("name")) |n| if (n == .string and n.string.len > 0)
- self.arg_live.open(n.string, ix);
- if (f.object.get("arguments")) |a| if (a == .string)
- self.arg_live.feed(self, ix, a.string);
- }
- },
- .responses => {
- const t = obj.get("type") orelse return;
- if (t != .string) return;
- if (std.mem.eql(u8, t.string, "response.output_item.added")) {
- const ix = outputIndex(obj) orelse return;
- const item = obj.get("item") orelse return;
- if (item != .object) return;
- const it = item.object.get("type") orelse return;
- if (it != .string or !std.mem.eql(u8, it.string, "function_call")) return;
- const name = item.object.get("name") orelse return;
- if (name == .string) self.arg_live.open(name.string, ix);
- } else if (std.mem.eql(u8, t.string, "response.function_call_arguments.delta")) {
- const ix = outputIndex(obj) orelse return;
- const dl = obj.get("delta") orelse return;
- if (dl == .string) self.arg_live.feed(self, ix, dl.string);
- } else if (std.mem.eql(u8, t.string, "response.output_item.done")) {
- const ix = outputIndex(obj) orelse return;
- self.arg_live.close(ix);
- }
- },
- }
- }
-
- /// Print live tool-argument text exactly like a text delta: clears the
- /// spinner, lands in the Esc-interrupt capture, and records which meta
- /// tool already showed its prose so handleMeta / sayToolUse don't repeat
- /// it after the call completes.
- fn emitArgText(self: *Agent, tool: ArgTool, text: []const u8) void {
- const w = self.out orelse return;
- if (text.len == 0) return;
- self.spinnerStop(); // first visible byte: clear the thinking line
- self.streamed_text = true;
- if (self.streamed_args != tool) self.streamed_args_len = 0;
- self.streamed_args = tool;
- self.streamed_args_len += text.len;
- self.partial_text.appendSlice(self.arena, text) catch {};
- if (use_color) {
- self.streamMarkdown(text);
- } else {
- w.writeAll(text) catch return;
- w.flush() catch return;
- }
- }
-
- /// True iff this meta call's prose already streamed live *in full*: the
- /// bytes ArgLive emitted match the parsed field exactly. Only then may
- /// the authoritative re-print be suppressed — a scanner glitch must cost
- /// duplication, never content.
- fn argStreamedFully(self: *Agent, call: ToolCall) bool {
- const at = argToolFor(call.name);
- if (at == .none or at != self.streamed_args) return false;
- const v = call.input.object.get(argField(at)) orelse return false;
- return v == .string and v.string.len == self.streamed_args_len;
- }
-
- /// Incremental streaming markdown: every delta byte either prints
- /// immediately or is held only as long as classification demands. Each
- /// line starts in .classify (md_buf accumulates the prefix); the moment
- /// the prefix proves what the line is, the buffered bytes are emitted
- /// with their styling and subsequent bytes stream straight through —
- /// prose and bullets/numbered items word-by-word with eager **bold** /
- /// `code` span styling, headers and fenced code styled-then-raw.
- /// Only genuinely whole-line constructs stay held to line end: fence
- /// toggles, tables, horizontal rules (and any still-ambiguous prefix).
- /// Well-formed markdown renders identically to renderMdLine; a span left
- /// unclosed at line end differs cosmetically (styled text, markers
- /// dropped) from renderMdLine's literal-marker fallback.
- fn streamMarkdown(self: *Agent, text: []const u8) void {
- const w = self.out orelse return;
- for (text) |b| self.mdByte(w, b);
- w.flush() catch {};
- }
-
- const MdKind = enum { classify, hold, prose, header, fenced };
- const MdSpan = enum { normal, star, bold, bold_star, code };
-
- fn mdByte(self: *Agent, w: *Io.Writer, b: u8) void {
- if (b == '\n') {
- // A swallowed line (table row joining the buffer) keeps its
- // newline too — the table renders with its own line breaks.
- if (self.mdFinishLine(w)) w.writeByte('\n') catch {};
- return;
- }
- switch (self.md_kind) {
- .classify => {
- self.md_buf.append(self.gpa, b) catch {};
- self.mdTryClassify(w);
- },
- .hold => self.md_buf.append(self.gpa, b) catch {},
- .prose => self.mdSpanByte(w, b),
- .header, .fenced => w.writeByte(b) catch {},
- }
- }
-
- /// Look at the held line prefix and commit to a line kind as soon as the
- /// bytes allow. Staying silent (returning with .classify) means "not
- /// decidable yet" — at most a few bytes for every construct.
- fn mdTryClassify(self: *Agent, w: *Io.Writer) void {
- const held = self.md_buf.items;
- var lead: usize = 0;
- while (lead < held.len and held[lead] == ' ') lead += 1;
- const body = held[lead..];
- if (body.len == 0) return; // only indentation so far
-
- // A buffered table ends at the first line that isn't another row —
- // render it before this line emits anything.
- if (self.md_table.items.len > 0 and body[0] != '|') self.flushTable(w);
-
- if (self.md_fence) {
- // Inside a fence the only special line is the ``` closer.
- const bt = countPrefix(body, '`');
- if (bt == body.len) {
- if (bt >= 3) self.md_kind = .hold; // closer: whole-line render
- return; // 1-2 backticks: could still become the closer
- }
- self.md_kind = .fenced; // body text: dim it and stream
- w.writeAll(style.dim) catch {};
- w.writeAll(held) catch {};
- self.md_buf.clearRetainingCapacity();
- return;
- }
- switch (body[0]) {
- '`' => {
- const bt = countPrefix(body, '`');
- if (bt >= 3) {
- self.md_kind = .hold; // fence opener
- } else if (bt < body.len) {
- self.mdStartProse(w); // inline code span
- } // else: 1-2 leading backticks, undecided
- },
- '#' => {
- const hn = countPrefix(body, '#');
- if (hn == body.len) return; // could still grow
- if (hn > 6 or body[hn] != ' ') {
- self.mdStartProse(w);
- return;
- }
- // Header. Mirror renderMdLine's left-trim: wait for the first
- // non-space byte of the title, then style and stream.
- var ns = hn + 1;
- while (ns < body.len and body[ns] == ' ') ns += 1;
- if (ns == body.len) return;
- self.md_kind = .header;
- w.print("{s}{s}{s}", .{ style.bold, style.cyan, body[ns..] }) catch {};
- self.md_buf.clearRetainingCapacity();
- },
- '|' => self.md_kind = .hold, // table row: cells need the whole line
- '-', '_', '*', '+' => {
- const run = countPrefix(body, body[0]);
- if (body[0] != '+' and run == body.len) return; // possible rule
- if ((body[0] == '-' or body[0] == '*' or body[0] == '+') and run == 1 and body.len >= 2 and body[1] == ' ') {
- // Bullet: emit indent + styled marker, stream the rest.
- self.md_kind = .prose;
- self.md_span = .normal;
- self.md_col = lead + 2; // "• " — wrapped lines align under the text
- self.md_indent = lead + 2;
- w.writeAll(held[0..lead]) catch {};
- w.print("{s}•{s} ", .{ style.cyan, style.reset }) catch {};
- const rest = body[2..];
- self.md_buf.clearRetainingCapacity(); // before re-dispatch
- var tmp: [8]u8 = undefined;
- const n = @min(rest.len, tmp.len);
- @memcpy(tmp[0..n], rest[0..n]);
- for (tmp[0..n]) |rb| self.mdSpanByte(w, rb);
- return;
- }
- if (body[0] == '+' and body.len == 1) return; // "+ " bullet still possible
- self.mdStartProse(w);
- },
- '0'...'9' => {
- var d: usize = 0;
- while (d < body.len and body[d] >= '0' and body[d] <= '9') d += 1;
- if (d == body.len) return; // all digits: could become "12. "
- if (body[d] == '.' or body[d] == ')') {
- if (d + 1 == body.len) return; // "12." — needs one more byte
- if (body[d + 1] == ' ') { // numbered item
- self.md_kind = .prose;
- self.md_span = .normal;
- self.md_col = lead + d + 2; // "12. " — align under the text
- self.md_indent = lead + d + 2;
- w.writeAll(held[0..lead]) catch {};
- w.print("{s}{s}.{s} ", .{ style.cyan, body[0..d], style.reset }) catch {};
- const rest = body[d + 2 ..];
- var tmp: [8]u8 = undefined;
- const n = @min(rest.len, tmp.len);
- @memcpy(tmp[0..n], rest[0..n]);
- self.md_buf.clearRetainingCapacity();
- for (tmp[0..n]) |rb| self.mdSpanByte(w, rb);
- return;
- }
- }
- self.mdStartProse(w);
- },
- else => self.mdStartProse(w),
- }
- }
-
- /// Commit to plain prose: replay the held prefix through the inline-span
- /// machine, then stream subsequent bytes directly.
- fn mdStartProse(self: *Agent, w: *Io.Writer) void {
- self.md_kind = .prose;
- self.md_span = .normal;
- var lead: usize = 0;
- while (lead < self.md_buf.items.len and self.md_buf.items[lead] == ' ') lead += 1;
- self.md_indent = lead; // wrapped lines keep the line's indentation
- for (self.md_buf.items) |b| self.mdSpanByte(w, b);
- self.md_buf.clearRetainingCapacity();
- }
-
- /// Streaming counterpart of renderInline: a left-to-right toggle machine
- /// for **bold** and `code` spans that styles eagerly — the opener turns
- /// styling on as soon as it's seen instead of waiting for the closer.
- /// Literal bytes route through mdWrapByte (terminal-width word wrap);
- /// style sequences through mdStyle (zero-width, ordered with the word).
- fn mdSpanByte(self: *Agent, w: *Io.Writer, b: u8) void {
- switch (self.md_span) {
- .normal => switch (b) {
- '*' => self.md_span = .star,
- '`' => {
- self.mdStyle(w, style.yellow);
- self.md_span = .code;
- },
- else => self.mdWrapByte(w, b),
- },
- .star => if (b == '*') {
- self.mdStyle(w, style.bold);
- self.md_span = .bold;
- } else {
- self.mdWrapByte(w, '*'); // lone star is literal
- self.md_span = .normal;
- self.mdSpanByte(w, b);
- },
- .bold => switch (b) {
- '*' => self.md_span = .bold_star,
- else => self.mdWrapByte(w, b),
- },
- .bold_star => if (b == '*') {
- self.mdStyle(w, style.reset);
- self.md_span = .normal;
- } else {
- self.mdWrapByte(w, '*');
- self.md_span = .bold;
- self.mdSpanByte(w, b);
- },
- .code => if (b == '`') {
- self.mdStyle(w, style.reset);
- self.md_span = .normal;
- } else self.mdWrapByte(w, b),
- }
- }
-
- /// Terminal-width word wrap for streamed prose. Literal bytes buffer
- /// into the current word; a space flushes it — and a word that would
- /// cross the terminal edge breaks the line first and continues under
- /// the hanging indent (set by the bullet/numbered/prose classifiers),
- /// instead of hard-wrapping at column 0 mid-word.
- fn mdWrapByte(self: *Agent, w: *Io.Writer, b: u8) void {
- if (b == ' ') {
- self.mdFlushWord(w);
- if (self.md_col < self.mdWidth()) {
- w.writeByte(' ') catch {};
- self.md_col += 1;
- } else if (self.md_col > self.md_indent) {
- self.mdWrapBreak(w); // line full: break instead of the space
- } // already at a fresh indent: swallow the space
- return;
- }
- self.md_word.append(self.gpa, b) catch {
- w.writeByte(b) catch {}; // can't buffer: degrade to direct write
- return;
- };
- if ((b & 0xC0) != 0x80) self.md_word_vis += 1; // UTF-8 leads only
- }
-
- /// Style sequences are zero-width but must stay ordered with the word
- /// they're inside of — buffer them with a pending word, else pass through.
- fn mdStyle(self: *Agent, w: *Io.Writer, s: []const u8) void {
- if (self.md_word.items.len > 0) {
- self.md_word.appendSlice(self.gpa, s) catch {};
- } else w.writeAll(s) catch {};
- }
-
- fn mdFlushWord(self: *Agent, w: *Io.Writer) void {
- if (self.md_word.items.len == 0) return;
- const vis = self.md_word_vis;
- const width = self.mdWidth();
- // Break before a word that would cross the edge — unless the line is
- // already fresh or the word can't fit any line (URLs: let the
- // terminal wrap it rather than shred it).
- if (self.md_col + vis > width and self.md_col > self.md_indent and self.md_indent + vis <= width)
- self.mdWrapBreak(w);
- w.writeAll(self.md_word.items) catch {};
- self.md_col += vis;
- self.md_word.clearRetainingCapacity();
- self.md_word_vis = 0;
- }
-
- fn mdWrapBreak(self: *Agent, w: *Io.Writer) void {
- w.writeByte('\n') catch {};
- for (0..self.md_indent) |_| w.writeByte(' ') catch {};
- self.md_col = self.md_indent;
- }
-
- fn mdWidth(self: *Agent) usize {
- if (self.md_width == 0) self.md_width = termCols();
- return self.md_width;
- }
-
- /// Settle the span machine at line end: pending markers print literally,
- /// open spans close their styling.
- fn mdSpanEnd(self: *Agent, w: *Io.Writer) void {
- self.mdFlushWord(w);
- switch (self.md_span) {
- .normal => {},
- .star => w.writeByte('*') catch {},
- .bold, .code => w.writeAll(style.reset) catch {},
- .bold_star => {
- w.writeByte('*') catch {};
- w.writeAll(style.reset) catch {};
- },
- }
- self.md_span = .normal;
- }
-
- /// End of line (newline or stream end): render anything still held,
- /// settle styling, and reset the per-line state. Returns false when the
- /// line was a table row swallowed into md_table — the caller then skips
- /// the newline; the table prints its own when it flushes.
- fn mdFinishLine(self: *Agent, w: *Io.Writer) bool {
- switch (self.md_kind) {
- // Still held: a whole-line construct or a prefix too short to
- // classify — renderMdLine does exactly the right thing (and
- // toggles md_fence for fence lines).
- .classify, .hold => {
- const line = self.md_buf.items;
- var lead: usize = 0;
- while (lead < line.len and line[lead] == ' ') lead += 1;
- if (!self.md_fence and lead < line.len and line[lead] == '|') {
- // Table row: buffer it — columns can only align once the
- // whole table is known.
- if (self.gpa.dupe(u8, line[lead..])) |dup| {
- self.md_table.append(self.gpa, dup) catch self.gpa.free(dup);
- self.md_buf.clearRetainingCapacity();
- self.md_kind = .classify;
- self.md_span = .normal;
- return false;
- } else |_| {}
- }
- if (self.md_table.items.len > 0) self.flushTable(w);
- self.renderMdLine(w, line);
- },
- .prose => self.mdSpanEnd(w),
- .header, .fenced => w.writeAll(style.reset) catch {},
- }
- self.md_buf.clearRetainingCapacity();
- self.md_kind = .classify;
- self.md_span = .normal;
- self.md_col = 0;
- self.md_indent = 0;
- self.md_width = 0; // re-read the terminal width next line (resizes)
- return true;
- }
-
- fn countPrefix(s: []const u8, c: u8) usize {
- var i: usize = 0;
- while (i < s.len and s[i] == c) i += 1;
- return i;
- }
-
- /// Render the buffered table rows as aligned columns: widths from the
- /// widest visible cell, bold header above a dim ─┼─ rule, cells styled
- /// via renderInline. The one place streaming defers whole blocks —
- /// alignment is impossible row-by-row.
- fn flushTable(self: *Agent, w: *Io.Writer) void {
- const gpa = self.gpa;
- defer {
- for (self.md_table.items) |r| gpa.free(r);
- self.md_table.clearRetainingCapacity();
- }
- // Split rows into trimmed cells (slices into the row strings),
- // dropping the empty edges of leading/trailing '|'.
- var cells: std.ArrayList([]const []const u8) = .empty;
- defer {
- for (cells.items) |cr| gpa.free(cr);
- cells.deinit(gpa);
- }
- var header_rows: ?usize = null; // rows above the first separator
- var ncols: usize = 0;
- for (self.md_table.items) |row| {
- const body = std.mem.trim(u8, row, " ");
- if (isTableSeparator(body)) {
- if (header_rows == null and cells.items.len > 0) header_rows = cells.items.len;
- continue;
- }
- var list: std.ArrayList([]const u8) = .empty;
- var it = std.mem.splitScalar(u8, body, '|');
- var first = true;
- while (it.next()) |cell| {
- defer first = false;
- if (first and cell.len == 0) continue;
- list.append(gpa, std.mem.trim(u8, cell, " ")) catch {};
- }
- while (list.items.len > 0 and list.items[list.items.len - 1].len == 0)
- _ = list.pop();
- ncols = @max(ncols, list.items.len);
- const owned = list.toOwnedSlice(gpa) catch blk: {
- list.deinit(gpa);
- break :blk &.{};
- };
- cells.append(gpa, owned) catch gpa.free(owned);
- }
- if (ncols == 0 or cells.items.len == 0) return;
- const widths = gpa.alloc(usize, ncols) catch return;
- defer gpa.free(widths);
- @memset(widths, 0);
- for (cells.items) |cr| for (cr, 0..) |c, i| {
- widths[i] = @max(widths[i], inlineVisibleLen(c));
- };
- // Cap the grid to the terminal: a column wider than the screen used
- // to hard-wrap at the terminal edge and shred the alignment. Shrink
- // the widest columns until the table fits, then word-wrap each cell
- // into its column — continuation lines keep the │ rails straight.
- fitWidths(widths, termCols() -| (3 * (ncols - 1)));
- const wraps = gpa.alloc(std.ArrayList([]const u8), ncols) catch return;
- defer gpa.free(wraps);
- for (cells.items, 0..) |cr, ri| {
- const head = header_rows != null and ri < header_rows.?;
- var nlines: usize = 1;
- for (0..ncols) |ci| {
- wraps[ci] = .empty;
- wrapCell(gpa, if (ci < cr.len) cr[ci] else "", widths[ci], &wraps[ci]);
- nlines = @max(nlines, wraps[ci].items.len);
- }
- defer for (wraps) |*l| l.deinit(gpa);
- for (0..nlines) |li| {
- for (0..ncols) |ci| {
- const c = if (li < wraps[ci].items.len) wraps[ci].items[li] else "";
- if (ci > 0) w.print("{s} │ {s}", .{ style.dim, style.reset }) catch {};
- if (head) w.writeAll(style.bold) catch {};
- renderInline(w, c);
- if (head) w.writeAll(style.reset) catch {};
- if (ci + 1 < ncols) {
- var pad = widths[ci] -| inlineVisibleLen(c);
- while (pad > 0) : (pad -= 1) w.writeByte(' ') catch {};
- }
- }
- w.writeByte('\n') catch {};
- }
- if (header_rows != null and ri + 1 == header_rows.?) {
- w.writeAll(style.dim) catch {};
- for (0..ncols) |ci| {
- if (ci > 0) w.writeAll("─┼─") catch {};
- for (0..widths[ci]) |_| w.writeAll("─") catch {};
- }
- w.writeAll(style.reset) catch {};
- w.writeByte('\n') catch {};
- }
- }
- }
-
- /// Shrink the widest columns one cell at a time until the grid fits in
- /// `avail` visible columns, never below a readable floor. If the screen
- /// can't even hold the floor for every column, leave the widths alone —
- /// a torn render beats an unreadable one.
- fn fitWidths(widths: []usize, avail: usize) void {
- const min_w: usize = 8;
- if (avail < widths.len * min_w) return;
- var total: usize = 0;
- for (widths) |x| total += x;
- while (total > avail) {
- var wi: usize = 0;
- for (widths, 0..) |x, k| {
- if (x > widths[wi]) wi = k;
- }
- if (widths[wi] <= min_w) break;
- widths[wi] -= 1;
- total -= 1;
- }
- }
-
- /// One wrappable unit of a table cell: a maximal run of non-space bytes,
- /// where a **bold**/`code` span is atomic (spaces inside don't split it),
- /// so wrapping never tears a styled span apart.
- fn atomEnd(s: []const u8, start: usize) usize {
- var i = start;
- while (i < s.len) {
- if (s[i] == ' ') return i;
- if (i + 1 < s.len and s[i] == '*' and s[i + 1] == '*') {
- if (std.mem.indexOfPos(u8, s, i + 2, "**")) |e| {
- i = e + 2;
- continue;
- }
- }
- if (s[i] == '`') {
- if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |e| {
- i = e + 1;
- continue;
- }
- }
- i += 1;
- }
- return s.len;
- }
-
- /// Greedy word-wrap of one table cell to a visible-width budget,
- /// appending slices of `cell` to `out` (one per rendered line). Atoms
- /// wider than the budget hard-split by codepoint. Always yields at least
- /// one (possibly empty) line.
- fn wrapCell(gpa: Allocator, cell: []const u8, width: usize, out: *std.ArrayList([]const u8)) void {
- const budget = @max(width, 1);
- var ls: usize = 0; // current line: first atom byte…
- var le: usize = 0; // …through end of its last atom
- var lv: usize = 0; // and its visible width
- var i: usize = 0;
- while (i < cell.len) {
- while (i < cell.len and cell[i] == ' ') i += 1;
- if (i >= cell.len) break;
- const ae = atomEnd(cell, i);
- const av = inlineVisibleLen(cell[i..ae]);
- if (lv > 0 and lv + 1 + av > budget) {
- out.append(gpa, cell[ls..le]) catch return;
- lv = 0;
- }
- if (lv == 0 and av > budget) { // oversized atom: hard-split
- var j = i;
- var v: usize = 0;
- while (j < ae and v < budget) {
- j += std.unicode.utf8ByteSequenceLength(cell[j]) catch 1;
- v += 1;
- }
- out.append(gpa, cell[i..j]) catch return;
- i = j;
- continue;
- }
- if (lv == 0) ls = i else lv += 1; // joining space
- lv += av;
- le = ae;
- i = ae;
- }
- if (lv > 0) out.append(gpa, cell[ls..le]) catch return;
- if (out.items.len == 0) out.append(gpa, "") catch {};
- }
-
- /// Columns a cell occupies once rendered: matched **bold**/`code` markers
- /// drop, and multi-byte UTF-8 sequences count as one column (wide CJK
- /// glyphs are approximated as one).
- fn inlineVisibleLen(s: []const u8) usize {
- var i: usize = 0;
- var n: usize = 0;
- while (i < s.len) {
- if (i + 1 < s.len and s[i] == '*' and s[i + 1] == '*') {
- if (std.mem.indexOfPos(u8, s, i + 2, "**")) |end| {
- n += codepointCount(s[i + 2 .. end]);
- i = end + 2;
- continue;
- }
- }
- if (s[i] == '`') {
- if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |end| {
- n += codepointCount(s[i + 1 .. end]);
- i = end + 1;
- continue;
- }
- }
- if ((s[i] & 0xC0) != 0x80) n += 1;
- i += 1;
- }
- return n;
- }
-
- fn codepointCount(s: []const u8) usize {
- var n: usize = 0;
- for (s) |b| {
- if ((b & 0xC0) != 0x80) n += 1;
- }
- return n;
- }
-
- /// Flush the trailing partial line at stream end (no forced newline — the
- /// caller adds the separating newline), and reset fence state.
- fn flushStreamTail(self: *Agent) void {
- const w = self.out orelse return;
- _ = self.mdFinishLine(w); // may swallow a final table row…
- if (self.md_table.items.len > 0) self.flushTable(w); // …then render it
- w.flush() catch {};
- self.md_fence = false;
- }
-
- /// Render one markdown line to ANSI (portable SGR only — bold/color, no
- /// italic, so iTerm/Ghostty/Terminal/Windows-Terminal all agree): code
- /// fences + fenced bodies dimmed, ATX headers bold-cyan, `-`/`*`/`+`
- /// bullets → cyan •, and inline `**bold**` / `` `code` `` spans.
- fn renderMdLine(self: *Agent, w: *Io.Writer, line: []const u8) void {
- var lead: usize = 0;
- while (lead < line.len and line[lead] == ' ') lead += 1;
- const body = line[lead..];
- if (std.mem.startsWith(u8, body, "```")) {
- self.md_fence = !self.md_fence;
- // Fence lines render as a dim rule — "── zig ────…" opening with
- // the language label when given, plain "────…" otherwise —
- // instead of raw backticks. Body lines stay unprefixed so code
- // copies cleanly out of the terminal.
- const lang = std.mem.trim(u8, body[3..], " `");
- w.writeAll(style.dim) catch {};
- var used: usize = 0;
- if (self.md_fence and lang.len > 0) {
- w.print("── {s} ", .{lang}) catch {};
- used = 4 + codepointCount(lang); // "── " + label + " "
- }
- while (used < 40) : (used += 1) w.writeAll("─") catch {};
- w.writeAll(style.reset) catch {};
- return;
- }
- if (self.md_fence) {
- w.print("{s}{s}{s}", .{ style.dim, line, style.reset }) catch {};
- return;
- }
- // ATX header: 1-6 '#' then a space.
- var h: usize = 0;
- while (h < body.len and body[h] == '#') h += 1;
- if (h >= 1 and h <= 6 and h < body.len and body[h] == ' ') {
- const head = std.mem.trim(u8, body[h + 1 ..], " ");
- w.print("{s}{s}{s}{s}", .{ style.bold, style.cyan, head, style.reset }) catch {};
- return;
- }
- // Horizontal rule: a line of only -, *, or _ (3+).
- if (body.len >= 3 and isRule(body)) {
- w.print("{s}────────────{s}", .{ style.dim, style.reset }) catch {};
- return;
- }
- // Table row (GFM): starts with '|'. Separator row → dim rule; data row
- // → cells joined by a dim │, each rendered inline.
- if (body.len > 0 and body[0] == '|') {
- if (isTableSeparator(body)) {
- w.print("{s}────────────{s}", .{ style.dim, style.reset }) catch {};
- return;
- }
- var cells = std.mem.splitScalar(u8, body, '|');
- var first = true;
- while (cells.next()) |cell| {
- const c = std.mem.trim(u8, cell, " ");
- if (c.len == 0) continue;
- if (!first) w.print("{s} │ {s}", .{ style.dim, style.reset }) catch {};
- first = false;
- renderInline(w, c);
- }
- return;
- }
- // Bullet list item.
- if (std.mem.startsWith(u8, body, "- ") or std.mem.startsWith(u8, body, "* ") or std.mem.startsWith(u8, body, "+ ")) {
- w.writeAll(line[0..lead]) catch {};
- w.print("{s}•{s} ", .{ style.cyan, style.reset }) catch {};
- renderInline(w, body[2..]);
- return;
- }
- // Numbered list: digits then '.' or ')' then a space.
- var d: usize = 0;
- while (d < body.len and body[d] >= '0' and body[d] <= '9') d += 1;
- if (d >= 1 and d + 1 < body.len and (body[d] == '.' or body[d] == ')') and body[d + 1] == ' ') {
- w.writeAll(line[0..lead]) catch {};
- w.print("{s}{s}.{s} ", .{ style.cyan, body[0..d], style.reset }) catch {};
- renderInline(w, body[d + 2 ..]);
- return;
- }
- renderInline(w, line);
- }
-
- /// True if every char is one of '-', '*', '_' (markdown thematic break).
- fn isRule(body: []const u8) bool {
- const c0 = body[0];
- if (c0 != '-' and c0 != '*' and c0 != '_') return false;
- for (body) |c| if (c != c0) return false;
- return true;
- }
-
- /// True if a `|`-delimited row contains only separator chars (-, :, space).
- fn isTableSeparator(body: []const u8) bool {
- var any_dash = false;
- for (body) |c| switch (c) {
- '|', ' ', ':' => {},
- '-' => any_dash = true,
- else => return false,
- };
- return any_dash;
- }
-
- /// Emit a line with inline `**bold**` and `` `code` `` spans styled; the
- /// markers themselves are dropped. Unmatched markers print literally.
- fn renderInline(w: *Io.Writer, s: []const u8) void {
- var i: usize = 0;
- while (i < s.len) {
- if (i + 1 < s.len and s[i] == '*' and s[i + 1] == '*') {
- if (std.mem.indexOfPos(u8, s, i + 2, "**")) |end| {
- w.print("{s}{s}{s}", .{ style.bold, s[i + 2 .. end], style.reset }) catch {};
- i = end + 2;
- continue;
- }
- }
- if (s[i] == '`') {
- if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |end| {
- w.print("{s}{s}{s}", .{ style.yellow, s[i + 1 .. end], style.reset }) catch {};
- i = end + 1;
- continue;
- }
- }
- w.writeByte(s[i]) catch {};
- i += 1;
- }
- }
-
- /// Reassemble a streamed SSE body into the non-streaming response shape
- /// the step functions expect. Returns null when the body contains no SSE
- /// events (a plain JSON body — error envelope, or a provider that
- /// ignored `stream`); the caller falls back to regular parsing.
- fn assembleStream(self: *Agent, body: []const u8) !?std.json.ObjectMap {
- return switch (self.provider.kind) {
- .anthropic => self.assembleAnthropic(body),
- .openai => self.assembleOpenAI(body),
- .responses => unreachable, // parseResponses owns this path
- };
- }
-
- /// One in-flight content block while reassembling an Anthropic stream.
- const BlockAcc = struct {
- obj: std.json.ObjectMap = .empty,
- text: std.ArrayList(u8) = .empty,
- json: std.ArrayList(u8) = .empty,
- thinking: std.ArrayList(u8) = .empty,
- signature: std.ArrayList(u8) = .empty,
- };
-
- /// message_start carries the message skeleton (role, model, input-token
- /// usage); content blocks open with content_block_start and accumulate
- /// via content_block_delta (text / partial_json / thinking / signature);
- /// message_delta carries stop_reason and output-token usage.
- fn assembleAnthropic(self: *Agent, body: []const u8) !?std.json.ObjectMap {
- var root: ?std.json.ObjectMap = null;
- var blocks: std.ArrayList(BlockAcc) = .empty;
- var stop_reason: ?Value = null;
- var usage_delta: ?Value = null;
- var it = std.mem.tokenizeScalar(u8, body, '\n');
- while (it.next()) |raw_line| {
- const payload = ssePayload(raw_line) orelse continue;
- const v = std.json.parseFromSliceLeaky(Value, self.arena, payload, .{ .allocate = .alloc_always }) catch continue;
- if (v != .object) continue;
- const t = v.object.get("type") orelse continue;
- if (t != .string) continue;
- if (std.mem.eql(u8, t.string, "message_start")) {
- if (v.object.get("message")) |m| if (m == .object) {
- root = m.object;
- };
- } else if (std.mem.eql(u8, t.string, "content_block_start")) {
- const idx = sseIndex(v.object) orelse continue;
- while (blocks.items.len <= idx) try blocks.append(self.arena, .{});
- if (v.object.get("content_block")) |cb| if (cb == .object) {
- blocks.items[idx].obj = cb.object;
- };
- } else if (std.mem.eql(u8, t.string, "content_block_delta")) {
- const idx = sseIndex(v.object) orelse continue;
- if (idx >= blocks.items.len) continue;
- const d = v.object.get("delta") orelse continue;
- if (d != .object) continue;
- const b = &blocks.items[idx];
- if (d.object.get("text")) |x| if (x == .string) try b.text.appendSlice(self.arena, x.string);
- if (d.object.get("partial_json")) |x| if (x == .string) try b.json.appendSlice(self.arena, x.string);
- if (d.object.get("thinking")) |x| if (x == .string) try b.thinking.appendSlice(self.arena, x.string);
- if (d.object.get("signature")) |x| if (x == .string) try b.signature.appendSlice(self.arena, x.string);
- } else if (std.mem.eql(u8, t.string, "message_delta")) {
- if (v.object.get("delta")) |d| if (d == .object) {
- if (d.object.get("stop_reason")) |sr| if (sr == .string) {
- stop_reason = sr;
- };
- };
- if (v.object.get("usage")) |u| if (u == .object) {
- usage_delta = u;
- };
- } else if (std.mem.eql(u8, t.string, "error")) {
- // Hand the envelope back as the root: request()'s existing
- // type=="error" check reports it.
- return v.object;
- }
- }
- var r = root orelse return null;
- var content = std.json.Array.init(self.arena);
- for (blocks.items) |*b| {
- if (b.obj.get("type") == null) continue; // never started
- if (b.text.items.len > 0) try b.obj.put(self.arena, "text", .{ .string = b.text.items });
- if (b.thinking.items.len > 0) try b.obj.put(self.arena, "thinking", .{ .string = b.thinking.items });
- if (b.signature.items.len > 0) try b.obj.put(self.arena, "signature", .{ .string = b.signature.items });
- if (b.json.items.len > 0) {
- const input = std.json.parseFromSliceLeaky(Value, self.arena, b.json.items, .{ .allocate = .alloc_always }) catch Value{ .object = .empty };
- try b.obj.put(self.arena, "input", input);
- }
- try content.append(.{ .object = b.obj });
- }
- try r.put(self.arena, "content", .{ .array = content });
- try r.put(self.arena, "stop_reason", stop_reason orelse Value{ .string = "end_turn" });
- if (usage_delta) |ud| {
- var usage: std.json.ObjectMap = .empty;
- if (r.get("usage")) |base| if (base == .object) {
- var e = base.object.iterator();
- while (e.next()) |kv| try usage.put(self.arena, kv.key_ptr.*, kv.value_ptr.*);
- };
- var e = ud.object.iterator();
- while (e.next()) |kv| try usage.put(self.arena, kv.key_ptr.*, kv.value_ptr.*);
- try r.put(self.arena, "usage", .{ .object = usage });
- }
- return r;
- }
-
- /// One in-flight tool call while reassembling an OpenAI chat stream;
- /// id and function.name arrive on the first fragment, arguments
- /// accumulate across fragments keyed by index.
- const CallAcc = struct {
- id: []const u8 = "",
- name: []const u8 = "",
- args: std.ArrayList(u8) = .empty,
- };
-
- fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
- var content: std.ArrayList(u8) = .empty;
- var reasoning_content: std.ArrayList(u8) = .empty;
- var reasoning: std.ArrayList(u8) = .empty;
- var calls: std.ArrayList(CallAcc) = .empty;
- var role: []const u8 = "assistant";
- var finish: ?Value = null;
- var usage: ?Value = null;
- var saw_chunk = false;
- var it = std.mem.tokenizeScalar(u8, body, '\n');
- while (it.next()) |raw_line| {
- const payload = ssePayload(raw_line) orelse continue;
- const v = std.json.parseFromSliceLeaky(Value, self.arena, payload, .{ .allocate = .alloc_always }) catch continue;
- if (v != .object) continue;
- // The final usage chunk (stream_options.include_usage) may have
- // an empty choices array.
- if (v.object.get("usage")) |u| if (u == .object) {
- usage = u;
- saw_chunk = true;
- };
- const choices = v.object.get("choices") orelse continue;
- if (choices != .array or choices.array.items.len == 0) continue;
- const c0 = choices.array.items[0];
- if (c0 != .object) continue;
- saw_chunk = true;
- if (c0.object.get("finish_reason")) |fr| if (fr == .string) {
- finish = fr;
- };
- const d = c0.object.get("delta") orelse continue;
- if (d != .object) continue;
- if (d.object.get("role")) |x| if (x == .string) {
- role = x.string;
- };
- if (d.object.get("content")) |x| if (x == .string) try content.appendSlice(self.arena, x.string);
- if (d.object.get("reasoning_content")) |x| if (x == .string) try reasoning_content.appendSlice(self.arena, x.string);
- if (d.object.get("reasoning")) |x| if (x == .string) try reasoning.appendSlice(self.arena, x.string);
- if (d.object.get("tool_calls")) |tcs| if (tcs == .array) {
- for (tcs.array.items) |tc| {
- if (tc != .object) continue;
- const idx: usize = blk: {
- if (tc.object.get("index")) |ix| if (ix == .integer and ix.integer >= 0) break :blk @intCast(ix.integer);
- // No index: a fresh id opens a new call, otherwise
- // the fragment continues the latest one.
- break :blk if (tc.object.get("id") != null or calls.items.len == 0) calls.items.len else calls.items.len - 1;
- };
- while (calls.items.len <= idx) try calls.append(self.arena, .{});
- const acc = &calls.items[idx];
- if (tc.object.get("id")) |x| if (x == .string and x.string.len > 0) {
- acc.id = x.string;
- };
- if (tc.object.get("function")) |f| if (f == .object) {
- if (f.object.get("name")) |x| if (x == .string and x.string.len > 0) {
- acc.name = x.string;
- };
- if (f.object.get("arguments")) |x| if (x == .string) try acc.args.appendSlice(self.arena, x.string);
- };
- }
- };
- }
- if (!saw_chunk) return null;
-
- var message: std.json.ObjectMap = .empty;
- try message.put(self.arena, "role", .{ .string = role });
- try message.put(self.arena, "content", if (content.items.len > 0) Value{ .string = content.items } else .null);
- if (reasoning_content.items.len > 0) try message.put(self.arena, "reasoning_content", .{ .string = reasoning_content.items });
- if (reasoning.items.len > 0) try message.put(self.arena, "reasoning", .{ .string = reasoning.items });
- if (calls.items.len > 0) {
- var tcs = std.json.Array.init(self.arena);
- for (calls.items) |c| {
- if (c.id.len == 0 and c.name.len == 0) continue;
- var function: std.json.ObjectMap = .empty;
- try function.put(self.arena, "name", .{ .string = c.name });
- try function.put(self.arena, "arguments", .{ .string = c.args.items });
- var tc: std.json.ObjectMap = .empty;
- try tc.put(self.arena, "id", .{ .string = c.id });
- try tc.put(self.arena, "type", .{ .string = "function" });
- try tc.put(self.arena, "function", .{ .object = function });
- try tcs.append(.{ .object = tc });
- }
- if (tcs.items.len > 0) try message.put(self.arena, "tool_calls", .{ .array = tcs });
- }
- var choice: std.json.ObjectMap = .empty;
- try choice.put(self.arena, "message", .{ .object = message });
- try choice.put(self.arena, "finish_reason", finish orelse Value{ .string = "stop" });
- var choices = std.json.Array.init(self.arena);
- try choices.append(.{ .object = choice });
- var r: std.json.ObjectMap = .empty;
- try r.put(self.arena, "choices", .{ .array = choices });
- if (usage) |u| try r.put(self.arena, "usage", u);
- return r;
- }
+ pub var esc_watch_done: std.atomic.Value(bool) = .init(true);
+
+ // Esc-cancel handling (the stdin scanner + steering-buffer capture +
+ // interruptible sleep) lives in agent_interrupt.zig (#123, 600-line
+ // goal). Member-aliased so self.sleepInterruptible(...)/etc. resolve
+ // unchanged. esc_cancel/esc_watch_done above stay here (never alias a
+ // `var`); ssePayload/sseIndex live there too since they're only
+ // consumed alongside the interrupt-watch plumbing in postStream.
+ pub const escWatchTask = @import("agent_interrupt.zig").escWatchTask;
+ pub const escPressed = @import("agent_interrupt.zig").escPressed;
+ pub const drainSteerStdin = @import("agent_interrupt.zig").drainSteerStdin;
+ pub const drainStdin = @import("agent_interrupt.zig").drainStdin;
+ pub const rawNonblockStdin = @import("agent_interrupt.zig").rawNonblockStdin;
+ pub const sleepInterruptible = @import("agent_interrupt.zig").sleepInterruptible;
+ pub const ssePayload = @import("agent_interrupt.zig").ssePayload;
+ pub const sseIndex = @import("agent_interrupt.zig").sseIndex;
+
+ // Live streaming of attempt_completion/ask_user tool-argument prose (the
+ // ArgLive byte-scanner) lives in agent_argstream.zig (#123, 600-line
+ // goal). Member-aliased so self.arg_live's type + the streaming callbacks
+ // resolve unchanged regardless of physical file.
+ pub const ArgTool = @import("agent_argstream.zig").ArgTool;
+ pub const ArgLive = @import("agent_argstream.zig").ArgLive;
+ pub const argToolFor = @import("agent_argstream.zig").argToolFor;
+ pub const argField = @import("agent_argstream.zig").argField;
+ pub const outputIndex = @import("agent_argstream.zig").outputIndex;
+ pub const argLiveDelta = @import("agent_argstream.zig").argLiveDelta;
+ pub const emitArgText = @import("agent_argstream.zig").emitArgText;
+ pub const argStreamedFully = @import("agent_argstream.zig").argStreamedFully;
+
+ // The incremental streaming markdown renderer (byte-at-a-time line
+ // classifier + non-streaming renderMdLine) lives in agent_render.zig
+ // (#123, 600-line goal). Member-aliased so `self.streamMarkdown(...)`
+ // and the field types below resolve unchanged regardless of physical
+ // file.
+ pub const MdKind = @import("agent_render.zig").MdKind;
+ pub const MdSpan = @import("agent_render.zig").MdSpan;
+ pub const streamMarkdown = @import("agent_render.zig").streamMarkdown;
+ pub const inlineVisibleLen = @import("agent_render.zig").inlineVisibleLen;
+ pub const codepointCount = @import("agent_render.zig").codepointCount;
+ pub const flushStreamTail = @import("agent_render.zig").flushStreamTail;
+ pub const renderMdLine = @import("agent_render.zig").renderMdLine;
+ pub const renderInline = @import("agent_render.zig").renderInline;
+ pub const mdByte = @import("agent_render.zig").mdByte;
+ pub const mdTryClassify = @import("agent_render.zig").mdTryClassify;
+ pub const mdStartProse = @import("agent_render.zig").mdStartProse;
+ pub const mdSpanByte = @import("agent_render.zig").mdSpanByte;
+ pub const mdWrapByte = @import("agent_render.zig").mdWrapByte;
+ pub const mdStyle = @import("agent_render.zig").mdStyle;
+ pub const mdFlushWord = @import("agent_render.zig").mdFlushWord;
+ pub const mdWrapBreak = @import("agent_render.zig").mdWrapBreak;
+ pub const mdWidth = @import("agent_render.zig").mdWidth;
+ pub const mdSpanEnd = @import("agent_render.zig").mdSpanEnd;
+ pub const mdFinishLine = @import("agent_render.zig").mdFinishLine;
+ // Streamed-markdown table rendering (buffered rows -> aligned columns,
+ // word-wrapped to termCols()) lives in agent_table.zig (#123, 600-line
+ // goal). Member-aliased so `self.flushTable(...)`/`Agent.isTableSeparator(...)`
+ // resolve unchanged regardless of physical file.
+ pub const flushTable = @import("agent_table.zig").flushTable;
+ pub const fitWidths = @import("agent_table.zig").fitWidths;
+ pub const atomEnd = @import("agent_table.zig").atomEnd;
+ pub const wrapCell = @import("agent_table.zig").wrapCell;
+ pub const isTableSeparator = @import("agent_table.zig").isTableSeparator;
};
// Wire-format message construction + UTF-8/history normalization live in