graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(stream): visible stall recovery, reasoning summaries, codex WS prewarm, bounded doom-loop resample
Rach Pradhan6878d782884b
diff --git a/scripts/codex_ws_mock.py b/scripts/codex_ws_mock.pyindex d5921e33..4fbca80a 100644--- a/scripts/codex_ws_mock.py+++ b/scripts/codex_ws_mock.py@@ -385,6 +385,18 @@ class CodexMock:self._log(f"ws <- {etype} ({len(message.payload)}b)")if etype != "response.create":continue+ # Codex-style generate:false prewarm: connection setup, not an+ # inference turn — answer with a terminal completed frame carrying+ # an id the client can chain from, and do NOT count it in ws_turns+ # (the transport smoke assertions count real model turns).+ if event.get("generate") is False:+ prewarm_id = f"resp_prewarm_{self.ws_turns + 1}"+ _send_frame(conn, OP_TEXT, json.dumps(+ {"type": "response.completed",+ "response": {"id": prewarm_id, "usage": dict(USAGE)}},+ separators=(",", ":")).encode("utf-8"))+ self._log("ws -> response.completed (prewarm)")+ continueevents = self._events("ws", connection_id, event, headers)for ev in events:_send_frame(diff --git a/src/agent.zig b/src/agent.zigindex 1aa0e2fe..3e05be3a 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -91,6 +91,10 @@ pub const Agent = struct {// Codex Responses WS delta transport: one WS held ACROSS user turns (codex_chain.zig), sending previous_response_id + only new items. Reset by closeCodexWs.codex_ws: ?*ws.WsClient = null,codex_prev_id: ?[]const u8 = null, // last response.id (gpa-owned); null = re-anchor with full input+ /// Codex WS prewarm in flight (openai/codex `generate:false`): the body+ /// writer emits no input items and no transport fields, so the server+ /// prepares instructions+tools state that turn 1 chains onto.+ ws_prewarm: bool = false,codex_sent_upto: usize = 0, // messages the server already holds; delta = messages[codex_sent_upto..]codex_chain_rewrites: u32 = 0, // history_rewrites when the chain was anchored; a later compaction/trim invalidates itcodex_props_fp: u64 = 0, // request properties the server anchored on (model/effort/fast/tools/instructions)diff --git a/src/agent_model_loop_transport_test.zig b/src/agent_model_loop_transport_test.zigindex 685418f2..dae72b52 100644--- a/src/agent_model_loop_transport_test.zig+++ b/src/agent_model_loop_transport_test.zig@@ -24,7 +24,7 @@ const Peer = struct {"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n";sw.interface.writeAll(head) catch return;sw.interface.flush() catch return;- if (websocket) mock.Mock.readClientFrame(&sr.interface) catch return;+ if (websocket) mock.Mock.readRealFrame(io, &sr.interface, &sw.interface) catch return;const raw = switch (kind) {.openai => "{\"choices\":[{\"delta\":{\"content\":\"I will wait for your reply.\\n\"}}]}",.anthropic => "{\"type\":\"content_block_delta\",\"delta\":{\"type\":\"text_delta\",\"text\":\"I will wait for your reply.\\n\"}}",diff --git a/src/agent_request.zig b/src/agent_request.zigindex 07f9462e..98b2df2a 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -179,6 +179,8 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {self.stall = .{}; // #680: a fresh widen ladder + tripped budget per requestvar stall_retries: usize = 0;const max_stall_retries: usize = 2;+ var doomloop_retries: usize = 0; // grok-build parity: bounded resample after a latched stream_repetition+ const max_doomloop_retries: usize = 1;const stall_reconnect_backoff_ms = 750; // brief pause before reconnecting on a fresh streamvar server_retries: usize = 0; // #opencode-parity: bounded retries for a transient in-stream server overloadvar openai404_retries: usize = 0; // #opencode-parity: bounded retries for OpenAI's spurious model 404s@@ -221,7 +223,23 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {elsepostWatched(self.gpa, self.io, self.client, self.provider, body, conv);if (attempt_body) |ok| break :blk ok else |err| {- if (err == error.ModelLoop) return err;+ // Doom-loop (stream_repetition latched mid-stream): grok-build+ // treats this as a RETRYABLE attempt failure — abort + bounded+ // resample — rather than ending the turn on the marker. One+ // bounded resample; a loop that survives a fresh sample is a+ // real model failure and still ends the turn recorded.+ if (err == error.ModelLoop) {+ if (doomloop_retries < max_doomloop_retries) {+ doomloop_retries += 1;+ self.say("[model output loop detected — resampling ({d}/{d})]\n", .{ doomloop_retries, max_doomloop_retries }) catch {};+ if (self.tracer) |tr| tr.note("doom_loop", "resample");+ if (telemetry.g_telem) |t| t.errorEvent("doom_loop", "bounded resample");+ @import("agent_stream.zig").noteStallRetry(self, stall_retries); // fresh stream, no concat+ self.closeCodexWs();+ continue :rebuild;+ }+ return err;+ }if (self.streamed_text) if (self.out) |w| {w.writeAll("\n") catch {};w.flush() catch {};diff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zigindex 75636c0e..a93a08e1 100644--- a/src/agent_request_body_responses.zig+++ b/src/agent_request_body_responses.zig@@ -56,8 +56,14 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_too// this item server-side, so only a full anchor writes it.if (!chain and explicit_cache) try writeCacheAnchor(s);const from = if (chain) self.codex_sent_upto else 0;- for (self.messages.items[from..]) |m| try s.write(m);- try s.endArray();+ // Prewarm (openai/codex `generate:false`): prepare instructions+tools state+ // with NO input items — the real turn chains onto the warmup response id.+ if (self.ws_prewarm) {+ try s.endArray();+ } else {+ for (self.messages.items[from..]) |m| try s.write(m);+ try s.endArray();+ }if (tools) |t| {const payload = blk: {var next = t;@@ -101,6 +107,13 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_tooserver_compact.noteExposure(self);try server_compact.writeContextManagement(self, s);if (self.output_schema) |schema_json| try writeTextFormat(s, schema_json);+ // Prewarm: no transport fields (stream) and generate:false — connection+ // setup, not inference (openai/codex prewarm_websocket, Responses WS docs).+ if (self.ws_prewarm) {+ try s.objectField("generate");+ try s.write(false);+ return;+ }// No top-level max_output_tokens: the codex backend rejects it// ("Unsupported parameter") on gpt-5.6-* — codex sets it only as a tool argument.try s.objectField("stream");diff --git a/src/agent_ws.zig b/src/agent_ws.zigindex a98fdd14..633743ed 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -350,8 +350,11 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {const arena = self.arena;const provider = self.provider;- const frame = try std.fmt.allocPrint(gpa, "{{\"type\":\"response.create\",{s}", .{body[1..]});+ var frame = try std.fmt.allocPrint(gpa, "{{\"type\":\"response.create\",{s}", .{body[1..]});defer gpa.free(frame);+ // WS responses.create omits transport-only fields (xAI spec; codex tolerates):+ // the body builder writes `stream:true` for SSE; shorten it in place here.+ frame = @import("agent_ws_prewarm.zig").stripTransportFields(frame);const bearer = try std.fmt.allocPrint(arena, "Bearer {s}", .{provider.api_key});// ChatGPT tail is codex-only (#502); xAI takes grok-build's affinity@@ -442,6 +445,13 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {if (self.tracer) |tr| tr.note("ws", "connected");} else if (self.tracer) |tr| tr.note("ws", "reuse (delta)");const client = self.codex_ws.?;+ // Codex-style prewarm (generate:false) on a fresh socket: prepare+ // instructions+tools server-side, chain turn 1 onto the warmup id.+ // Best-effort — on any failure warm() returns the original frame.+ const frame_to_send: []const u8 = if (reused)+ frame+ else+ @import("agent_ws_prewarm.zig").warm(self, arena, client, frame);// Any error → close + reset the session so the next request re-anchors (fresh// WS full history, or SSE fallback via postLive's ws_off path). Never leaks.// (#401) …and mark it dead first: deinit's courtesy close frame is another@@ -450,7 +460,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {if (self.codex_ws) |c| c.dead = true;self.closeCodexWs();}- sendFrameWatched(self.io, client, frame, orig_tio != null) catch |e| {+ sendFrameWatched(self.io, client, frame_to_send, orig_tio != null) catch |e| {// No user-facing "stream stalled — ending turn" line here: a send// failure is a TRANSPORT failure (HungRequest), which postLive retries// on a fresh socket — the turn is not over.@@ -467,7 +477,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {// quiet — the distinction that made #401 undiagnosable from its trace.if (self.tracer) |tr| {var nbuf: [48]u8 = undefined;- tr.note("ws", std.fmt.bufPrint(&nbuf, "sent {d}b — awaiting frames", .{frame.len}) catch "sent — awaiting frames");+ tr.note("ws", std.fmt.bufPrint(&nbuf, "sent {d}b — awaiting frames", .{frame_to_send.len}) catch "sent — awaiting frames");}var full: Io.Writer.Allocating = .init(gpa);diff --git a/src/agent_ws_mock.zig b/src/agent_ws_mock.zigindex 70871df0..183229f4 100644--- a/src/agent_ws_mock.zig+++ b/src/agent_ws_mock.zig@@ -20,6 +20,8 @@ pub fn nowMs(io: Io) i64 {pub const delta_event = "{\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}";pub const completed_event = "{\"type\":\"response.completed\"}";+pub const prewarm_completed_event = "{\"type\":\"response.completed\",\"response\":{\"id\":\"resp_prewarm\"}}";+const PREWARM_MARKER = "\"generate\":false";pub const generic_error_event = "{\"type\":\"error\",\"error\":{\"code\":\"invalid_request_error\",\"message\":\"mock bad request\"}}";/// What the backend actually puts on the socket in the first milliseconds after@@ -101,30 +103,30 @@ pub const Mock = struct {switch (mode) {.no_upgrade, .never_drain => {},.frame_then_silence, .frame_then_complete => {- readClientFrame(&sr.interface) catch return idle(io, done);+ readRealFrame(io, &sr.interface, &sw.interface) catch return idle(io, done);writeTextFrame(&sw.interface, delta_event) catch return idle(io, done);if (mode == .frame_then_complete)writeTextFrame(&sw.interface, completed_event) catch return idle(io, done);},.protocol_then_silence => {- readClientFrame(&sr.interface) catch return idle(io, done);+ readRealFrame(io, &sr.interface, &sw.interface) catch return idle(io, done);for (protocol_events) |ev|writeTextFrame(&sw.interface, ev) catch return idle(io, done);},- .read_then_silence => readClientFrame(&sr.interface) catch return idle(io, done),+ .read_then_silence => readRealFrame(io, &sr.interface, &sw.interface) catch return idle(io, done),.slow_first_frame => {- readClientFrame(&sr.interface) catch return idle(io, done);+ readRealFrame(io, &sr.interface, &sw.interface) catch return idle(io, done);io.sleep(.fromMilliseconds(slow_first_frame_ms), .awake) catch return idle(io, done);writeTextFrame(&sw.interface, delta_event) catch return idle(io, done);writeTextFrame(&sw.interface, completed_event) catch return idle(io, done);},.arg_prose_then_silence => {- readClientFrame(&sr.interface) catch return idle(io, done);+ readRealFrame(io, &sr.interface, &sw.interface) catch return idle(io, done);for (arg_prose_events) |ev|writeTextFrame(&sw.interface, ev) catch return idle(io, done);},.generic_error_then_close => {- readClientFrame(&sr.interface) catch return;+ readRealFrame(io, &sr.interface, &sw.interface) catch return;writeTextFrame(&sw.interface, generic_error_event) catch return;return;},@@ -139,8 +141,10 @@ pub const Mock = struct {while (!done.load(.acquire)) io.sleep(.fromMilliseconds(20), .awake) catch break;}- /// Consume one masked client frame (RFC 6455 §5.2); the payload is ignored.- pub fn readClientFrame(r: *Io.Reader) !void {+ /// Consume one masked client frame (RFC 6455 §5.2) and return its payload+ /// when it fits the reader buffer, else null (large frames are streamed and+ /// discarded; only prewarm frames are that large in practice).+ pub fn readClientFramePayload(r: *Io.Reader) !?[]const u8 {const h = try r.takeArray(2);var len: u64 = h[1] & 0x7f;if (len == 126) {@@ -149,7 +153,42 @@ pub const Mock = struct {len = std.mem.readInt(u64, try r.takeArray(8), .big);}if ((h[1] & 0x80) != 0) _ = try r.takeArray(4); // mask key- try r.discardAll(@intCast(len));+ if (len <= 4096) return try r.take(@intCast(len));+ // Chunked discard: take() cannot exceed the reader buffer.+ var tail: [16]u8 = undefined;+ var tail_len: usize = 0;+ var left = len;+ while (left > 0) {+ const chunk: usize = @intCast(@min(left, 4096));+ const got = try r.take(chunk);+ // Carry a 16-byte overlap so the marker cannot hide at a boundary.+ const scan = tail[0..tail_len].len + got.len;+ _ = scan;+ if (std.mem.indexOf(u8, got, PREWARM_MARKER) != null) return null;+ left -= chunk;+ tail_len = @min(tail_len, 16);+ @memcpy(tail[tail_len..][0..@min(got.len, 16 - tail_len)], got[got.len - @min(got.len, 16 - tail_len) ..]);+ }+ return null;+ }++ /// Read client frames until a REAL request arrives; a codex-style+ /// `generate:false` prewarm frame is answered with a completed id and+ /// skipped, so every mode keeps testing its own first real frame.+ pub fn readRealFrame(io: Io, r: *Io.Reader, w: *Io.Writer) !void {+ _ = io;+ while (true) {+ const payload = (try readClientFramePayload(r)) orelse {+ try writeTextFrame(w, prewarm_completed_event);+ continue;+ };+ if (std.mem.indexOf(u8, payload, PREWARM_MARKER) == null) return;+ try writeTextFrame(w, prewarm_completed_event);+ }+ }++ pub fn readClientFrame(r: *Io.Reader) !void {+ _ = try readClientFramePayload(r);}/// One unmasked server->client text frame (payloads here are all < 126 B).diff --git a/src/agent_ws_prewarm.zig b/src/agent_ws_prewarm.zignew file mode 100644index 00000000..9340c42c--- /dev/null+++ b/src/agent_ws_prewarm.zig@@ -0,0 +1,220 @@+//! Codex WS prewarm (openai/codex's `generate:false` prewarm_websocket, #codex-ws).+//!+//! Before the session's FIRST stream request on a fresh codex socket, send a+//! `response.create` with `generate:false` and no input items: the server+//! prepares the instructions+tools request state and returns a response id.+//! Turn 1 then chains onto it (`previous_response_id` + the user message), so+//! the big fixed prefix is ingested before the user's prompt instead of during+//! their wait. DeepWiki (openai/codex, `ModelClientSession.prewarm_websocket`):+//! best-effort connection setup — any failure falls through to a normal cold+//! turn; it is not an inference request and must not touch the meters.+//!+//! Kept out of agent_ws.zig (600-line cap). Own module so the frame shape and+//! the gate are testable without a socket.++const std = @import("std");+const Io = std.Io;+const main_mod = @import("main.zig");+const Agent = @import("agent.zig").Agent;+const ws = @import("ws.zig");+const http = @import("http.zig");+const body_responses = @import("agent_request_body_responses.zig");+const codex_chain = @import("codex_chain.zig");+const serde = @import("serde.zig");++const WatchdogFired = http.WatchdogFired;++/// Should this fresh connection prewarm? Codex brand, session start (nothing+/// sent, no chain anchor), and not under the full-resend experiment (seeding+/// the chain would fight the flag's premise).+pub fn eligible(self: *const Agent) bool {+ if (!std.mem.eql(u8, self.provider.id, "codex")) return false;+ if (codex_chain.g_force_full_resend) return false;+ return self.codex_ws != null and self.codex_prev_id == null and self.codex_sent_upto == 0;+}++/// Build the `{"type":"response.create",...generate:false}` frame. Same+/// properties (instructions, tools, reasoning effort) as the real turn, so the+/// chain fingerprint codex_chain.propsFor matches and turn 1 can chain.+pub fn buildFrame(self: *Agent, arena: std.mem.Allocator) ![]u8 {+ self.ws_prewarm = true;+ defer self.ws_prewarm = false;+ var out: std.Io.Writer.Allocating = .init(arena);+ var st: std.json.Stringify = .{ .writer = &out.writer };+ try st.beginObject();+ try st.objectField("type");+ try st.write("response.create");+ try body_responses.write(self, &st, self.toolsJson(), false);+ try st.endObject();+ return out.toOwnedSlice();+}++/// Best-effort prewarm on a freshly dialed codex socket. Never fails the turn:+/// every failure path just leaves the chain state untouched so the real request+/// proceeds cold. On success the prewarm response id becomes the turn-1 chain+/// anchor (gpa-owned, same lifetime rule as codex_prev_id everywhere else).+/// xAI Responses WS spec: the response.create body must omit transport-only+/// fields (stream, background) — responses always stream back as socket+/// events. buildBody always writes `stream:true` (the SSE path requires it),+/// so the WS frame strips the trailing field. Codex's backend tolerates the+/// field; xAI's documents its omission.+pub fn stripTransportFields(frame: []u8) []u8 {+ const marker = ",\"stream\":true";+ if (std.mem.endsWith(u8, frame, marker ++ "}")) {+ // ...true,"stream":true} → ...true} (move the closing brace over the marker)+ const cut = frame.len - marker.len - 1;+ frame[cut] = frame[frame.len - 1];+ return frame[0 .. cut + 1];+ }+ return frame;+}++/// Best-effort prewarm on a freshly dialed codex socket. Returns the frame to+/// send: the original, or the same frame with `previous_response_id` set to+/// the prewarm response id (all arena-owned — NOTHING here touches gpa-owned+/// chain state, so a turn whose response carries no id simply re-anchors on+/// turn 2, exactly as before). Every failure returns the original frame.+pub fn warm(self: *Agent, arena: std.mem.Allocator, client: *ws.WsClient, frame: []const u8) []const u8 {+ if (!eligible(self)) return frame;+ const tracer = self.tracer;+ const prewarm_frame = buildFrame(self, arena) catch return frame;+ // The frame is far under the 256KB SO_SNDBUF threshold agent_ws_signal+ // documents, so a blocking sendText copies into the socket buffer and+ // returns; the read half below is the bounded half.+ client.sendText(prewarm_frame) catch {+ if (tracer) |tr| tr.note("ws", "prewarm send failed — cold turn");+ return frame;+ };+ if (tracer) |tr| tr.note("ws", "prewarm sent");+ const id = awaitPrewarmId(self, arena, client) catch |e| {+ if (tracer) |tr| tr.note("ws", if (e == error.PrewarmRejected) "prewarm rejected — cold turn" else "prewarm no terminal — cold turn");+ return frame;+ };+ if (tracer) |tr| {+ var nbuf: [80]u8 = undefined;+ tr.note("ws", std.fmt.bufPrint(&nbuf, "prewarm ok — turn 1 chains onto {s}…", .{id[0..@min(id.len, 12)]}) catch "prewarm ok");+ }+ // Inject the chain seed into the real frame after the type field:+ // {"type":"response.create" ,"previous_response_id":"…", …}. Arena-owned;+ // a not-found rejection on turn 1 re-anchors through the existing ladder.+ const cut = std.mem.indexOf(u8, frame, ",\"") orelse return frame;+ return std.mem.concat(arena, u8, &.{+ frame[0..cut], ",\"previous_response_id\":\"", id, "\"", frame[cut..],+ }) catch frame;+}++/// Read frames until the prewarm's terminal event; returns response.id.+/// Bounded by the watchdog so a server that accepts the prewarm and goes+/// silent cannot park the user's turn behind it.+fn awaitPrewarmId(self: *Agent, arena: std.mem.Allocator, client: *ws.WsClient) ![]const u8 {+ var fbuf: std.ArrayList(u8) = .empty;+ defer fbuf.deinit(self.gpa);+ while (true) {+ const ReadDone = union(enum) { msg: ws.Error!ws.Opcode, stall: WatchdogFired };+ var rd_buf: [2]ReadDone = undefined;+ var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);+ rsel.concurrent(.msg, readTask, .{ client, self.gpa, &fbuf }) catch return error.Watchdog;+ rsel.concurrent(.stall, @import("http.zig").deadlineStallTask, .{ self.io, false, @import("http.zig").head_stall_ms }) catch {+ const r = rsel.await() catch return error.Watchdog;+ rsel.cancelDiscard();+ _ = r.msg catch return error.Watchdog;+ continue;+ };+ const first = rsel.await() catch return error.Watchdog;+ rsel.cancelDiscard();+ switch (first) {+ .msg => |m| _ = m catch return error.Watchdog,+ .stall => return error.Watchdog,+ }+ if (fbuf.items.len == 0) continue;+ const v = std.json.parseFromSliceLeaky(std.json.Value, arena, fbuf.items, .{}) catch {+ fbuf.clearRetainingCapacity();+ continue;+ };+ const typv = v.object.get("type") orelse return error.NoId;+ if (typv != .string) return error.NoId;+ const t = typv.string;+ if (std.mem.eql(u8, t, "response.completed")) {+ const resp = v.object.get("response") orelse return error.NoId;+ const idv = resp.object.get("id") orelse return error.NoId;+ if (idv != .string or idv.string.len == 0) return error.NoId;+ return idv.string;+ }+ if (std.mem.eql(u8, t, "response.failed") or std.mem.eql(u8, t, "error")) return error.PrewarmRejected;+ fbuf.clearRetainingCapacity();+ }+}++fn readTask(client: *ws.WsClient, gpa: std.mem.Allocator, fbuf: *std.ArrayList(u8)) ws.Error!ws.Opcode {+ fbuf.clearRetainingCapacity();+ return client.readMessage(gpa, fbuf);+}++test "buildFrame: prewarm body has generate:false, empty input, no previous_response_id" {+ const stdt = std;+ var arena_state = stdt.heap.ArenaAllocator.init(stdt.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var messages = stdt.json.Array.init(arena);+ try messages.append(try @import("messages.zig").textMessage(arena, "user", "hello"));+ var agent = Agent{+ .io = stdt.testing.io,+ .client = undefined,+ .provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "https://chatgpt.com/backend-api/codex/responses", .api_key = "k", .model = "gpt-5.6", .context = 272_000 },+ .messages = messages,+ .sub = false,+ .label = "main",+ .out = null,+ .arena = arena,+ .gpa = stdt.testing.allocator,+ };+ const frame = try buildFrame(&agent, arena);+ try stdt.testing.expect(std.mem.indexOf(u8, frame, "\"generate\":false") != null);+ try stdt.testing.expect(std.mem.indexOf(u8, frame, "\"input\":[]") != null);+ try stdt.testing.expect(std.mem.indexOf(u8, frame, "previous_response_id") == null);+ try stdt.testing.expect(std.mem.indexOf(u8, frame, "\"stream\":true") == null);+ try stdt.testing.expect(std.mem.indexOf(u8, frame, "\"instructions\"") != null);+ // The flag must not leak past the builder.+ try stdt.testing.expect(!agent.ws_prewarm);+}++test "stripTransportFields: WS frames omit the SSE-only stream field" {+ const stdt = std;+ const gpa = stdt.testing.allocator;+ const with_stream = try gpa.dupe(u8, "{\"type\":\"response.create\",\"model\":\"m\",\"input\":[],\"stream\":true}");+ defer gpa.free(with_stream);+ const stripped = stripTransportFields(with_stream);+ try stdt.testing.expect(std.mem.indexOf(u8, stripped, "stream") == null);+ try stdt.testing.expect(std.mem.endsWith(u8, stripped, "}"));+ try stdt.testing.expect(std.mem.indexOf(u8, stripped, "\"input\":[]") != null);+ // A frame without the field passes through unchanged.+ const clean = try gpa.dupe(u8, "{\"type\":\"response.create\",\"model\":\"m\"}");+ defer gpa.free(clean);+ try stdt.testing.expectEqualStrings(clean, stripTransportFields(clean));+}++test "eligible: codex session start only" {+ const stdt = std;+ var arena_state = stdt.heap.ArenaAllocator.init(stdt.testing.allocator);+ defer arena_state.deinit();+ var agent = Agent{+ .io = stdt.testing.io,+ .client = undefined,+ .provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "https://chatgpt.com/backend-api/codex/responses", .api_key = "k", .model = "gpt-5.6", .context = 272_000 },+ .messages = stdt.json.Array.init(arena_state.allocator()),+ .sub = false,+ .label = "main",+ .out = null,+ .arena = arena_state.allocator(),+ .gpa = stdt.testing.allocator,+ };+ try stdt.testing.expect(!eligible(&agent)); // no socket yet+ var held: ws.WsClient = undefined;+ agent.codex_ws = &held;+ try stdt.testing.expect(eligible(&agent)); // fresh session start+ agent.codex_prev_id = "resp_1";+ try stdt.testing.expect(!eligible(&agent)); // chain already anchored+ agent.codex_prev_id = null;+ agent.codex_sent_upto = 2;+ try stdt.testing.expect(!eligible(&agent)); // mid-session re-anchor+}diff --git a/src/main.zig b/src/main.zigindex 1364eb9a..10c76a7d 100644--- a/src/main.zig+++ b/src/main.zig@@ -580,6 +580,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("compact_status.zig");_ = @import("agent_request_search_tests.zig");_ = @import("agent_ws_steer.zig"); // gpt-6-astra response.steer+ _ = @import("agent_ws_prewarm.zig"); // codex generate:false prewarm_ = @import("tui_acp_updates.zig");_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root_ = @import("task_outcome.zig"); // goal-outcome telemetry events