graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(codex): harden websocket error recovery edges
yxlyx28b860e1dd47
diff --git a/src/agent.zig b/src/agent.zigindex 5dfe4917..bcd3d14b 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -211,6 +211,7 @@ pub const Agent = struct {named_work_nudges: u8 = 0, // named-file / zero-tool nudge this turn (named_work.zig)precompact_note_gen: ?u32 = null, // #391: history_rewrites at the last pre-compaction note-to-self, so one history generation buys at most one note however often compaction is retried (compact_note.decideCalls)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 retiredws_transport_failures: u8 = 0, // consecutive WS failures; retry once before latching persistent SSEstreamed_text: bool = false, // the last request printed its text livestall: @import("http_stall.zig").State = .{}, // #680: reconnects made this request (each widens the between-lines budget) + the budget that last trippeddiff --git a/src/agent_request.zig b/src/agent_request.zigindex 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.zigindex 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.zigindex 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 petry 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.zigindex 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)") orelsereturn error.ResponsesPathHasNoAuthRecovery;const after = arm[call..];diff --git a/src/codex_chain.zig b/src/codex_chain.zigindex 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"));+}