Skip to content

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

Python

feat(engine): EngineSink inversion — agent_stream emits typed events only (#422)

Rach Pradhanc522265c2daf
diff --git a/src/agent.zig b/src/agent.zig
index b4b03113..2693a4c6 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -94,6 +94,9 @@ pub const Agent = struct {
label: []const u8,
out: ?*Io.Writer,
in: ?*Io.Reader = null, // stdin, root only — backs the ask_user tool
+ /// Frontend event sink (#422). Null = resolved per emission from the
+ /// process mode (engine_sink.forAgent); set to inject a custom frontend.
+ sink: ?@import("engine_sink.zig").EngineSink = null,
registry: ?*mcp.Registry = null,
approvals: ?*approvals_mod.Approvals = null, // shared bash-approval state, set by main()
tracer: ?*trace.Tracer = null, // shared JSONL event trace, set by main()
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index c51aea29..5d579718 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -17,7 +17,7 @@ const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
const Agent = agent_mod.Agent;
-const tick_gate = @import("tick_gate.zig"); // #tui-tick: child ticks wait for a foreground line boundary
+const engine_sink = @import("engine_sink.zig"); // #422: every emission goes through the sink
const reasoningDelta = @import("title.zig").reasoningDelta;
const stream_tests = @import("agent_stream_tests.zig");
@@ -50,8 +50,15 @@ pub fn postStream(self: *Agent, body: []const u8) ![]u8 {
/// keep-alive cannot poison the WS→SSE handoff and every fallback retry dials
/// from a clean pool.
pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []const u8) ![]u8 {
- self.spinnerStart();
- defer self.spinnerStop();
+ const sink = engine_sink.forAgent(self);
+ sink.emit(self.io, .stream_begin);
+ // Every exit path — success, interrupt, transport error — tears down the
+ // live-stream presentation (spinner, a reasoning-only turn's open block).
+ defer sink.emit(self.io, .stream_finished);
+ // Per-stream frontend bookkeeping still lives on the Agent in #422 slice 1
+ // (TuiSink wraps it); the resets are state hygiene, not emissions, and run
+ // for every mode exactly as before — emitArgText can dirty the markdown
+ // state even when this stream's deltas go to the wire.
self.thinking_open = false; // fresh "Thinking" block state per request
main_mod.g_thinking_open = false;
self.thinking_rows = 0;
@@ -59,7 +66,6 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
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) {
@@ -226,11 +232,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
// flush the partial, poison, and end the turn as StreamStalled (never a
// hang, never a mislabeled StreamDropped or user Esc).
if (saw_done) break :stream;
- self.flushStreamTail();
- if (!main_mod.json_mode) if (self.out) |o| {
- o.writeAll("\n⚠ stream stalled — ending turn\n") catch {};
- o.flush() catch {};
- };
+ sink.emit(self.io, .{ .stream_aborted = .stalled });
if (req.connection) |conn| conn.closing = true;
return error.StreamStalled;
};
@@ -243,7 +245,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
_ = r.line catch |e| {
if (saw_done and readErrIsClose(e)) break :stream;
if (got_body and readErrIsClose(e)) {
- noteDropped(self);
+ sink.emit(self.io, .{ .stream_aborted = .dropped });
return error.StreamDropped;
} // #133
return e;
@@ -259,22 +261,18 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
.line => |r| _ = r catch |e| {
if (saw_done and readErrIsClose(e)) break :stream; // #134/#135: post-completion close/reset is success, not a retryable flake
if (got_body and readErrIsClose(e)) {
- noteDropped(self);
+ sink.emit(self.io, .{ .stream_aborted = .dropped });
return error.StreamDropped;
} // #133: closed before the terminal event
return e;
},
.stall => |w| {
- self.flushStreamTail();
- if (req.connection) |conn| conn.closing = true;
// A user Esc is a deliberate cancel; a `.deadline` is a dead or
// idle stream (silent past this read's budget) — end the turn as
// error.StreamStalled so it is never recorded as "[response
- // interrupted by user]" (#134). The notice below is deadline-only.
- if (w == .deadline and !main_mod.json_mode) if (self.out) |o| {
- o.writeAll("\n⚠ stream stalled — ending turn\n") catch {};
- o.flush() catch {};
- };
+ // interrupted by user]" (#134). Only the deadline gets a notice.
+ sink.emit(self.io, .{ .stream_aborted = if (w == .deadline) .stalled else .interrupted });
+ if (req.connection) |conn| conn.closing = true;
return watchdogError(w, error.StreamStalled);
},
}
@@ -288,7 +286,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
self.printDelta(line.writer.buffered());
if (main_mod.g_thinking_fold_request) {
main_mod.g_thinking_fold_request = false;
- self.toggleThinkingFold();
+ sink.emit(self.io, .thinking_fold_toggle);
}
// Logical stream terminator: once the provider's final event ([DONE] /
// response.completed / message_stop) lands in `full` the response is
@@ -305,7 +303,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
}
line.clearRetainingCapacity();
if ((orig_tio != null and escPressed(true)) or (self.sub and Agent.esc_cancel.load(.acquire))) {
- self.flushStreamTail();
+ sink.emit(self.io, .{ .stream_aborted = .interrupted });
// 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
@@ -316,12 +314,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
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 {};
- _ = tick_gate.setLineStart(true); // answer is off the wire: release held child ticks (#tui-tick)
- };
+ sink.emit(self.io, .{ .stream_complete = .{ .streamed_text = self.streamed_text } });
return full.toOwnedSlice();
}
@@ -343,18 +336,6 @@ fn openaiComplete(raw_line: []const u8) bool {
return std.mem.indexOf(u8, payload, "\"finish_reason\":\"") != null;
}
-/// The provider closed/reset the stream before its terminal event landed — the
-/// harness is ending the turn, not the user (#133). Flush the partial and tell
-/// the user (TTY/plain), so a Moonshot-style mid-reasoning drop can never pass
-/// silently as a completed answer.
-fn noteDropped(self: *Agent) void {
- self.flushStreamTail();
- if (!main_mod.json_mode) if (self.out) |o| {
- o.writeAll("\n⚠ connection dropped — response ended early\n") catch {};
- o.flush() catch {};
- };
-}
-
/// True if this SSE line is the provider's terminal event — after it no more
/// content comes, so postStream can stop instead of waiting for the socket to
/// close (#134/#135). Precise: matches the `[DONE]` sentinel, a structural
@@ -400,10 +381,11 @@ test "openaiComplete (#133): finish_reason marks completion, deltas do not" {
try stream_tests.openaiCompletion(openaiComplete);
}
-/// Print the user-visible text from one SSE line, if any. Best-effort:
-/// parse failures are ignored (the buffered body is parsed afterwards).
+/// Extract the user-visible content from one SSE line and dispatch it as
+/// typed events through the sink. 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;
+ if (self.out == null) return; // pool-thread subagents have no frontend writer: skip entirely (capture included), as ever
const payload = ssePayload(raw_line) orelse return;
const parsed = std.json.parseFromSlice(Value, self.gpa, payload, .{}) catch return;
defer parsed.deinit();
@@ -439,29 +421,13 @@ pub fn printDelta(self: *Agent, raw_line: []const u8) void {
},
};
// 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.
+ // a thinking_delta, codex a summary delta. Presentation is the sink's call:
+ // the wire's `reasoning` event, or the live "Thinking" block / spinner.
+ const sink = engine_sink.forAgent(self);
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 (reasoning.len != 0) sink.emit(self.io, .{ .reasoning_delta = .{ .text = 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;
- if (!self.sub) _ = tick_gate.setLineStart(text[text.len - 1] == '\n'); // #tui-tick
- }
+ sink.emit(self.io, .{ .text_delta = .{ .text = text } });
}
diff --git a/src/engine_sink.zig b/src/engine_sink.zig
new file mode 100644
index 00000000..2bd59c5c
--- /dev/null
+++ b/src/engine_sink.zig
@@ -0,0 +1,245 @@
+//! The EngineSink boundary (#422 slice 1): engine code emits typed events
+//! (engine_events.zig) and a sink turns them into a frontend's output — it
+//! receives events, nothing else. Two impls:
+//!
+//! - TuiSink: today's terminal rendering, verbatim. Its helpers live in
+//! frontend territory (agent_stream_render.zig, agent_render.zig via Agent
+//! aliases); slice 1 keeps the render state (thinking_*/md_* fields) on the
+//! Agent it wraps, so the ctx pointer is that state handle — it is never
+//! read to decide WHAT to render, only where the drawing bookkeeping lives
+//! until a later slice moves it out.
+//! - JsonSink: the existing --json wire lines for these events,
+//! byte-identical to the old inline emits. The ONE translation point from
+//! internal type to wire shape: any change here is externally visible and
+//! gated behind a schema_version bump.
+//!
+//! Events are stamped with a {generation, sequence} Cursor at the dispatch
+//! boundary. Durable events on a durable sink reserve their id INSIDE the
+//! same lock that serializes --json stdout, keeping the wire's numbering
+//! gap-free and ordered against pool-thread guiEmit writers.
+
+const std = @import("std");
+const Io = std.Io;
+
+const main_mod = @import("main.zig");
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
+
+const engine_events = @import("engine_events.zig");
+const EngineEvent = engine_events.EngineEvent;
+const protocol_seq = @import("protocol_seq.zig");
+const render = @import("agent_stream_render.zig");
+const tick_gate = @import("tick_gate.zig"); // #tui-tick: child ticks wait for a foreground line boundary
+
+/// An event plus its position, as delivered to a sink.
+pub const Stamped = struct {
+ cursor: engine_events.Cursor,
+ event: EngineEvent,
+};
+
+pub const VTable = struct {
+ emit: *const fn (ctx: *anyopaque, ev: Stamped) void,
+ /// A durable sink persists/forwards the protocol stream: durable events
+ /// reserve a fresh sequence id at dispatch. Presentation-only sinks
+ /// observe the current position instead, so an interactive session never
+ /// advances the persisted event_seq the --json wire owns.
+ durable: bool,
+};
+
+pub const EngineSink = struct {
+ ctx: *anyopaque,
+ vt: *const VTable,
+
+ /// The emission boundary: stamp, then hand off. `io` backs the stdout
+ /// lock; sinks that never take it (tests, TUI) may pass it undefined.
+ pub fn emit(self: EngineSink, io: Io, ev: EngineEvent) void {
+ const reserve = self.vt.durable and engine_events.durable(ev);
+ if (reserve and main_mod.json_mode) {
+ // Reserving outside the lock could put a smaller seq on the wire
+ // AFTER a pool-thread guiEmit line took a larger one.
+ main_mod.g_gui_mu.lockUncancelable(io);
+ defer main_mod.g_gui_mu.unlock(io);
+ self.vt.emit(self.ctx, .{ .cursor = engine_events.stamp(true), .event = ev });
+ return;
+ }
+ self.vt.emit(self.ctx, .{ .cursor = engine_events.stamp(reserve), .event = ev });
+ }
+};
+
+/// The agent's sink: an injected one (tests, future frontends) or the
+/// process-mode default — the wire in --json mode, the terminal otherwise.
+pub fn forAgent(a: *Agent) EngineSink {
+ if (a.sink) |s| return s;
+ return if (main_mod.json_mode) jsonSink(a) else tuiSink(a);
+}
+
+pub fn tuiSink(a: *Agent) EngineSink {
+ return .{ .ctx = a, .vt = &tui_vtable };
+}
+
+pub fn jsonSink(a: *Agent) EngineSink {
+ return .{ .ctx = a, .vt = &json_vtable };
+}
+
+const tui_vtable: VTable = .{ .emit = tuiEmit, .durable = false };
+const json_vtable: VTable = .{ .emit = jsonEmit, .durable = true };
+
+/// Today's interactive rendering, relocated behind the event contract. Every
+/// branch is the old inline agent_stream.zig code path, gate for gate.
+fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {
+ const a: *Agent = @ptrCast(@alignCast(ctx));
+ switch (ev.event) {
+ .stream_begin => render.spinnerStart(a),
+ // Reasoning streams into the live dimmed "Thinking" block when
+ // /thinking is on for a live, colored root turn; otherwise the
+ // spinner stands in for it.
+ .reasoning_delta => |d| if (a.show_thinking and !a.sub and !a.stream_quiet and main_mod.use_color)
+ render.streamThinking(a, d.text),
+ .text_delta => |d| {
+ if (a.thinking_open) render.closeThinkingBlock(a); // reasoning -> answer transition
+ render.spinnerStop(a); // first visible byte: clear the thinking line
+ if (main_mod.use_color) {
+ a.streamMarkdown(d.text);
+ } else if (a.out) |w| {
+ w.writeAll(d.text) catch return;
+ w.flush() catch return;
+ if (!a.sub) _ = tick_gate.setLineStart(d.text[d.text.len - 1] == '\n'); // #tui-tick
+ }
+ },
+ .thinking_fold_toggle => render.toggleThinkingFold(a),
+ .stream_aborted => |reason| {
+ a.flushStreamTail(); // render any held partial markdown line
+ switch (reason) {
+ .interrupted => {}, // a deliberate Esc needs no notice
+ .stalled => notice(a, "\n⚠ stream stalled — ending turn\n"),
+ .dropped => notice(a, "\n⚠ connection dropped — response ended early\n"),
+ }
+ },
+ .stream_complete => |c| {
+ a.flushStreamTail(); // render any held partial markdown line
+ if (c.streamed_text) if (a.out) |w| {
+ w.writeAll("\n") catch {};
+ w.flush() catch {};
+ _ = tick_gate.setLineStart(true); // answer is off the wire: release held child ticks (#tui-tick)
+ };
+ },
+ .stream_finished => {
+ render.closeThinkingBlock(a); // a reasoning-only turn still closes its block
+ render.spinnerStop(a);
+ },
+ }
+}
+
+fn notice(a: *Agent, text: []const u8) void {
+ const w = a.out orelse return;
+ w.writeAll(text) catch return;
+ w.flush() catch {};
+}
+
+/// The existing --json wire. Only the durable events have a shape; giving a
+/// pulse one is an externally visible change (schema_version gate). Dispatch
+/// already holds the stdout lock for these writes in --json mode.
+fn jsonEmit(ctx: *anyopaque, ev: Stamped) void {
+ const a: *Agent = @ptrCast(@alignCast(ctx));
+ const w = a.out orelse return;
+ switch (ev.event) {
+ .reasoning_delta => |d| jsonLine(w, ev.cursor, .{ .type = "reasoning", .text = d.text }),
+ .text_delta => |d| jsonLine(w, ev.cursor, .{ .type = "text", .text = d.text }),
+ else => {},
+ }
+}
+
+fn jsonLine(w: *Io.Writer, cursor: engine_events.Cursor, payload: anytype) void {
+ protocol_seq.writeEventStamped(w, cursor.sequence, payload) catch return;
+ w.writeByte('\n') catch return;
+ w.flush() catch return;
+}
+
+test "dispatch preserves emission order and stamps at the boundary" {
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var rec: std.ArrayList(Stamped) = .empty;
+ defer rec.deinit(std.testing.allocator);
+ const vt: VTable = .{ .emit = recordEmit, .durable = true };
+ const s: EngineSink = .{ .ctx = &rec, .vt = &vt };
+ s.emit(undefined, .stream_begin);
+ s.emit(undefined, .{ .reasoning_delta = .{ .text = "think" } });
+ s.emit(undefined, .{ .text_delta = .{ .text = "hi" } });
+ s.emit(undefined, .{ .stream_complete = .{ .streamed_text = true } });
+ s.emit(undefined, .stream_finished);
+ try std.testing.expectEqual(@as(usize, 5), rec.items.len);
+ const want_tags: [5]std.meta.Tag(EngineEvent) = .{
+ .stream_begin, .reasoning_delta, .text_delta, .stream_complete, .stream_finished,
+ };
+ for (want_tags, rec.items) |tag, got| try std.testing.expectEqual(tag, std.meta.activeTag(got.event));
+ // Durable deltas reserved fresh ids; pulses ride at the last reserved
+ // position — the wire's numbering shows no gap for them.
+ const want_seq: [5]u64 = .{ 0, 1, 2, 2, 2 };
+ for (want_seq, rec.items) |seq, got| try std.testing.expectEqual(seq, got.cursor.sequence);
+ for (rec.items) |got| try std.testing.expectEqual(engine_events.generation(), got.cursor.generation);
+}
+
+test "a presentation sink never reserves sequence ids" {
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var rec: std.ArrayList(Stamped) = .empty;
+ defer rec.deinit(std.testing.allocator);
+ const vt: VTable = .{ .emit = recordEmit, .durable = false };
+ const s: EngineSink = .{ .ctx = &rec, .vt = &vt };
+ s.emit(undefined, .{ .text_delta = .{ .text = "hi" } });
+ try std.testing.expectEqual(@as(u64, 0), rec.items[0].cursor.sequence);
+ try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());
+}
+
+fn recordEmit(ctx: *anyopaque, ev: Stamped) void {
+ const rec: *std.ArrayList(Stamped) = @ptrCast(@alignCast(ctx));
+ rec.append(std.testing.allocator, ev) catch @panic("OOM");
+}
+
+test "JsonSink writes today's wire lines byte-for-byte" {
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = std.testing.allocator,
+ .io = undefined,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = &aw.writer,
+ };
+ const s = jsonSink(&a);
+ s.emit(undefined, .{ .reasoning_delta = .{ .text = "why" } });
+ s.emit(undefined, .{ .text_delta = .{ .text = "hi\n" } });
+ s.emit(undefined, .stream_begin); // pulses have no wire shape
+ try std.testing.expectEqualStrings(
+ "{\"seq\":1,\"type\":\"reasoning\",\"text\":\"why\"}\n{\"seq\":2,\"type\":\"text\",\"text\":\"hi\\n\"}\n",
+ aw.writer.buffered(),
+ );
+}
+
+test "TuiSink renders a plain text delta exactly as the no-color TTY did" {
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = std.testing.allocator,
+ .io = undefined,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = &aw.writer,
+ };
+ const s = tuiSink(&a);
+ s.emit(undefined, .{ .text_delta = .{ .text = "plain\n" } });
+ try std.testing.expectEqualStrings("plain\n", aw.writer.buffered());
+ // Normal end after streamed text: the separating newline, as before.
+ s.emit(undefined, .{ .stream_complete = .{ .streamed_text = true } });
+ try std.testing.expectEqualStrings("plain\n\n", aw.writer.buffered());
+}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 65933a71..cf8aeac5 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -125,9 +125,10 @@ const snapshots_tests = @import("snapshots_tests.zig");
// calls from oauth.zig and the catalog writers, so its own tests need the hook.
const credential_store = @import("credential_store.zig");
-// #422: the engine event vocabulary. Production reaches it only through
-// engine_sink dispatch CALLS, so its tests need the hook.
+// #422: the engine event vocabulary + the sink boundary that dispatches it.
+// Production reaches both only through CALLS, so their tests need the hook.
const engine_events = @import("engine_events.zig");
+const engine_sink = @import("engine_sink.zig");
test {
_ = learn_holdout;
@@ -167,6 +168,7 @@ test {
_ = shutdown_trace;
_ = credential_store;
_ = engine_events;
+ _ = engine_sink;
_ = escalation;
_ = escalation_tests;
_ = edit_contract;