Skip to content

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

Python

release: start v0.0.285 and land #717 Codex WS error hardening

Cursor Agent3336dcfaaf70
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0615b167..049185f1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,16 @@ The release workflow uses a tag's section here as its release notes (a
hand-written `docs/releases/<tag>.md` wins if present), so keeping this file
current is part of cutting a release.
+## v0.0.285 (2026-09-01)
+
+- Next cut after tagged [v0.0.284](docs/releases/v0.0.284.md). No tag
+ until asked.
+- `#717` (yxlyx): Codex WS `type:error` retires the socket immediately
+ and keeps a one-request marker for the bounded diagnostic. Re-anchor
+ only when the rejected body actually sent `previous_response_id`.
+ Unparseable Responses envelopes no longer copy raw bytes into
+ `last_api_error`. Follow-up hardening for `#692` / `#693`.
+
## v0.0.284 (2026-09-01)
- ACP turns stage GUI `@[image]` attachments as native vision blocks so
diff --git a/docs/releases/v0.0.285.md b/docs/releases/v0.0.285.md
new file mode 100644
index 00000000..563584a4
--- /dev/null
+++ b/docs/releases/v0.0.285.md
@@ -0,0 +1,40 @@
+# v0.0.285 (2026-09-01)
+
+Next cut after [v0.0.284](v0.0.284.md) merged to main. No GitHub tag
+until asked. Download / notarization ids land after the build.
+
+## Codex WS error-frame recovery (#717)
+
+yxlyx's [#717](https://github.com/justrach/codegraff/pull/717), replayed
+onto this tip (its original base was 283-era `main`). `#692` / `#693`
+already treat a generic WebSocket `type:error` as a terminal API
+response. Three edges were still loose:
+
+- The transport kept the dead socket until the Responses parser ran, so
+ a lower-level caller could reuse it.
+- Chain recovery keyed off retained `codex_prev_id`, even when the
+ serialized body had omitted `previous_response_id` (property change
+ or full-resend experiment).
+- An unparseable Responses envelope was copied into `last_api_error`,
+ which can echo request or authentication-adjacent bytes.
+
+A short-lived `ws_api_error_pending` marker separates transport cleanup
+from later formatting: the socket closes on the error frame, and the
+parser still traces a bounded diagnostic. Re-anchor now requires the
+rejected wire body to contain `previous_response_id` *and* a recognized
+chain error (`shouldReanchorRequest`). Unparseable bodies use the same
+`failureDiagnostic` path as structured provider failures.
+
+Generic errors stay terminal. Only a recognized chain error on a
+request that actually used the chain rebuilds.
+
+`agent.zig` stays at the 600-line ceiling: the new field replaces a
+tightened scratch-arena comment.
+
+## Tests
+
+This fold adds `shouldReanchorRequest requires a rejected
+previous_response_id request` and tightens the `#692` reuse case
+(socket is null, marker is set, transport ladder is untouched). The
+`#402` source pin now covers the redacted unparseable path. Suite
+floor stays **1896** until the next ratchet bump.
diff --git a/src/agent.zig b/src/agent.zig
index 6e64427a..9994ce05 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -73,10 +73,9 @@ pub const Goal = struct {
pub const Agent = struct {
gpa: Allocator,
arena: Allocator,
- /// #124: per-turn transient parse garbage (per-SSE-event envelope parses,
- /// isStreamEnd) allocates here and is reset each request(), so the long-lived
- /// ROOT agent's session arena stops growing unboundedly. Optional — null on
- /// subagents/one-shots (scratchAlloc() then falls back to arena, unchanged).
+ /// #124: per-turn parse garbage (SSE envelopes, isStreamEnd) lives here and
+ /// is reset each request() so the root session arena stays bounded. Null on
+ /// subagents/one-shots (scratchAlloc() falls back to arena).
scratch_arena: ?*std.heap.ArenaAllocator = null,
/// Optional allocator for a temporary request transaction. compact() points
/// this at its arena so failed summaries do not leak message rewrites or
@@ -214,6 +213,7 @@ pub const Agent = struct {
named_work_settled: []const u8 = "", // mention already nudged or tooled
precompact_note_gen: ?u32 = null, // #391: one pre-compaction note per history generation
ws_off: bool = false, // codex ws transport disabled for this session after a handshake/transport fallback to SSE (#codex-ws)
+ ws_api_error_pending: bool = false, // terminal WS error awaits Responses parsing/tracing; socket is already retired
ws_transport_failures: u8 = 0, // consecutive WS failures; retry once before latching persistent SSE
streamed_text: bool = false, // the last request printed its text live
stall: @import("http_stall.zig").State = .{}, // #680: reconnects made this request (each widens the between-lines budget) + the budget that last tripped
diff --git a/src/agent_request.zig b/src/agent_request.zig
index eee06c16..e27754b9 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -368,10 +368,10 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
// object — pull the final `response` out of it (or an error).
if (self.provider.kind == .responses) {
const r = self.parseResponses(resp_body) catch {
- // #287/#299: sayApiError so the body snippet survives as
- // last_api_error; with plain say a subagent's parent got only
- // the literal "ApiError" for this failure.
- try self.sayApiError("unparseable codex response: {s}", .{resp_body[0..@min(resp_body.len, 600)]});
+ // Preserve a useful last_api_error without copying an unparsed
+ // provider envelope: it may contain echoed request/auth data.
+ const diagnostic = try responses.failureDiagnostic(self.arena, self.provider.id, .{ .message = "unparseable codex response" });
+ try self.sayApiError("{s}", .{diagnostic});
if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
return error.ApiError;
};
@@ -392,14 +392,11 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
},
.err => |failure| {
const msg = failure.message;
- const had_chain = self.codex_prev_id != null;
- const ws_error_frame = if (self.codex_ws) |c| c.dead else false;
+ const ws_error_frame = self.ws_api_error_pending;
+ self.ws_api_error_pending = false;
const diagnostic = try responses.failureDiagnostic(self.arena, self.provider.id, failure);
- if (ws_error_frame) {
- self.closeCodexWs();
- if (self.tracer) |tr| tr.note("ws_api_error", diagnostic);
- }
- if (had_chain and codex_chain.shouldDropChain(msg, failure.code)) {
+ if (ws_error_frame) if (self.tracer) |tr| tr.note("ws_api_error", diagnostic);
+ if (codex_chain.shouldReanchorRequest(body, msg, failure.code)) {
self.closeCodexWs();
if (self.tracer) |tr| tr.note("ws", "server dropped previous_response_id — re-anchoring with full input");
continue :rebuild;
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index f6c6cd16..70ffb209 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -88,15 +88,14 @@ fn nowAwakeMs(io: Io) i64 {
}
const ws_failures_before_fallback: u8 = 2;
-
pub fn wsShouldFallback(consecutive_failures: u8) bool {
return consecutive_failures >= ws_failures_before_fallback;
}
-/// Transport selector: try ws for eligible codex turns, else persistent SSE.
-/// The first WS transport/handshake failure rebuilds full input and retries a
-/// fresh socket; the second — or any 426 — latches SSE. Esc/stall propagates.
+/// Transport selector: try WS for eligible turns; the first failure retries a
+/// fresh socket, while the second or any 426 latches SSE. Esc/stall propagates.
pub fn postLive(self: *Agent, body: []const u8) ![]u8 {
+ self.ws_api_error_pending = false;
// #134/#132 test seam: force a one-shot stall/drop on a live turn so the
// end-to-end "[response ended early: …]" path (never "[response interrupted
// by user]") can be exercised without a real provider. Consumed after one use.
@@ -579,10 +578,11 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
try full.writer.writeAll(fbuf.items);
try full.writer.writeByte('\n');
const line = try std.fmt.allocPrint(arena, "data: {s}", .{fbuf.items});
- // Codex closes after `type:error`; return the accumulated API body
- // instead of waiting for EOF and misclassifying it as transport loss.
+ // Codex closes after `type:error`; return its API body instead of misclassifying the expected EOF as transport loss.
if (signal.errorFrameAction(gpa, fbuf.items) != .none) {
+ self.ws_api_error_pending = true;
client.dead = true; // no courtesy close write to a closing peer
+ self.closeCodexWs();
if (self.tracer) |tr| tr.note("ws", "terminal API error frame");
break :stream;
}
diff --git a/src/agent_ws_reuse_test.zig b/src/agent_ws_reuse_test.zig
index 0f7a84b3..6dc2732f 100644
--- a/src/agent_ws_reuse_test.zig
+++ b/src/agent_ws_reuse_test.zig
@@ -269,6 +269,8 @@ test "#692: a generic error frame is returned as the terminal API body before pe
try std.testing.expect(std.mem.indexOf(u8, out, mock.generic_error_event) != null);
try std.testing.expect(traced(&tw, "\"detail\":\"terminal API error frame\""));
try std.testing.expect(!traced(&tw, "transport error"));
- try std.testing.expect(agent.codex_ws != null);
- try std.testing.expect(agent.codex_ws.?.dead);
+ try std.testing.expect(agent.codex_ws == null); // closing peer is retired before returning
+ try std.testing.expect(agent.ws_api_error_pending); // request parser still traces the bounded diagnostic
+ try std.testing.expectEqual(@as(u8, 0), agent.ws_transport_failures);
+ try std.testing.expect(!agent.ws_off);
}
diff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zig
index 34eaf263..f21299e7 100644
--- a/src/agent_ws_test.zig
+++ b/src/agent_ws_test.zig
@@ -78,10 +78,12 @@ test "codexWsIdleExpired: fires only strictly past the idle limit (codex-ws)" {
// RETRIED request's Authorization header carries the newly adopted bearer.
test "the codex .responses arm refreshes auth and re-anchors before resending (#402)" {
const src = @embedFile("agent_request.zig");
- const arm_start = std.mem.indexOf(u8, src, "unparseable codex response").?;
- const arm_end = std.mem.indexOf(u8, src, "try self.sayApiError(\"{s}\", .{diagnostic})").?;
+ const arm_start = std.mem.indexOf(u8, src, "if (self.provider.kind == .responses)").?;
+ const arm_end = std.mem.indexOf(u8, src[arm_start..], "// Streamed anthropic/openai bodies").? + arm_start;
const arm = src[arm_start..arm_end];
+ try std.testing.expect(std.mem.indexOf(u8, arm, "responses.failureDiagnostic") != null and std.mem.indexOf(u8, arm, "resp_body[0..@min(resp_body.len, 600)]") == null);
+
const call = std.mem.indexOf(u8, arm, "retryAfterAuthRefresh(self, msg, &auth_refreshed)") orelse
return error.ResponsesPathHasNoAuthRecovery;
const after = arm[call..];
diff --git a/src/cli.zig b/src/cli.zig
index 6a9d922f..83c73305 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -21,6 +21,10 @@ const harness_version = root.harness_version;
pub const changelog_text =
\\What's new
\\──────────
+ \\0.0.285
+ \\ • Codex WS type:error retires the socket immediately; last_api_error stays bounded (#717)
+ \\ • chain re-anchor only when the rejected body sent previous_response_id
+ \\
\\0.0.284
\\ • ACP turns stage GUI @[image] attachments as native vision blocks — pasted images reach the model
\\ • peer inbox wake is advisory ("parked; read when relevant"), never a command that displaces the turn
diff --git a/src/codex_chain.zig b/src/codex_chain.zig
index 705f3b7c..d9e5c7ac 100644
--- a/src/codex_chain.zig
+++ b/src/codex_chain.zig
@@ -68,6 +68,13 @@ pub fn shouldDropChain(message: []const u8, code: ?[]const u8) bool {
return false;
}
+/// Re-anchor only when the rejected request actually used the server-side
+/// chain. A retained codex_prev_id is not enough: property changes and the
+/// full-resend experiment deliberately emit full input while keeping it held.
+pub fn shouldReanchorRequest(body: []const u8, message: []const u8, code: ?[]const u8) bool {
+ return std.mem.indexOf(u8, body, "\"previous_response_id\"") != null and shouldDropChain(message, code);
+}
+
pub fn chainUsable(self: *const Agent) bool {
if (g_force_full_resend) return false;
const xai_chain = g_xai_ws_chain and std.mem.eql(u8, self.provider.id, "xai");
@@ -183,3 +190,12 @@ test "shouldDropChain: not-found and 25-minute cap evict the in-memory id" {
try std.testing.expect(shouldDropChain("unsupported previous_response_id", null));
try std.testing.expect(!shouldDropChain("rate limited", "rate_limit_exceeded"));
}
+
+test "shouldReanchorRequest requires a rejected previous_response_id request" {
+ const chained = "{\"previous_response_id\":\"resp_1\",\"input\":[]}";
+ const full = "{\"input\":[]}";
+ try std.testing.expect(shouldReanchorRequest(chained, "missing", "previous_response_not_found"));
+ try std.testing.expect(shouldReanchorRequest(chained, "unsupported previous_response_id", "invalid_request_error"));
+ try std.testing.expect(!shouldReanchorRequest(full, "missing", "previous_response_not_found"));
+ try std.testing.expect(!shouldReanchorRequest(chained, "bad request", "invalid_request_error"));
+}
diff --git a/src/libgraff.zig b/src/libgraff.zig
index c667c39a..c449ddac 100644
--- a/src/libgraff.zig
+++ b/src/libgraff.zig
@@ -76,7 +76,7 @@ export fn graff_acp_create(new_seed: u32) void {
session_id = null;
seed = if (new_seed == 0) 1 else new_seed;
engine.cancel_flag.store(false, .release);
- engine.implementation_version = "0.0.284-core";
+ engine.implementation_version = "0.0.285-core";
}
export fn graff_acp_feed(len: usize) i32 {