graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(ws): xAI 25-min limit + error-frame handling; opt-in on-socket chaining
Rach Pradhan39062dee64ad
diff --git a/src/agent_ws.zig b/src/agent_ws.zigindex 19edfdee..1df7db47 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -51,18 +51,17 @@ const escPressed = Agent.escPressed;const rawNonblockStdin = Agent.rawNonblockStdin;const drainSteerStdin = Agent.drainSteerStdin;-/// WS: root Responses turns when enabled and not fallen back this session;-/// only codex + xai have real WS endpoints (Platform OpenAI has none).+/// WS: root Responses turns when enabled and not fallen back this session+/// (codex + xai only — Platform OpenAI has no WS endpoint).pub fn wsEligible(self: *Agent) bool {const has_ws = std.mem.eql(u8, self.provider.id, "codex") or std.mem.eql(u8, self.provider.id, "xai");return main_mod.g_codex_ws and !self.ws_off and !self.sub and has_ws andself.provider.kind == .responses and self.out != null and !self.stream_quiet;}-/// (#codex-ws) Client-side idle limit on the held WS (opencode's pool-/// design: never reuse a socket the server may have killed; backend closed-/// ours within 8.5 min idle, 4 min stays under). GRAFF_CODEX_WS_IDLE_SECS-/// overrides (parsed in session_run.zig).+/// (#codex-ws) Idle limit on the held WS (never reuse a socket the server+/// may have killed; 4 min stays under the observed ~8.5-min server close).+/// GRAFF_CODEX_WS_IDLE_SECS overrides (session_run.zig).pub var codex_ws_idle_ms: i64 = 4 * std.time.ms_per_min;/// (#codex-ws) The idle-reanchor decision, pure so the regression test can@@ -124,12 +123,10 @@ pub fn postLive(self: *Agent, body: []const u8) ![]u8 {// the same refusal. Latch now (openai/codex: FallbackToHttp).const declined = e == error.UpgradeRequired;const fallback = declined or wsShouldFallback(self.ws_transport_failures);- // (#codex-ws) A delta body carries previous_response_id + only the new- // messages, anchored to the WS session that just died — the codex HTTP- // endpoint rejects previous_response_id outright ("Unsupported- // parameter"), and even if it didn't, the referenced response died with- // the socket. Never replay it over SSE. closeCodexWs's errdefer inside- // postResponsesWs already reset codex_ws/codex_prev_id/codex_sent_upto by+ // (#codex-ws) A delta body is anchored to the WS session that just+ // died (HTTP rejects previous_response_id; the response died with the+ // socket) — never replay it over SSE. closeCodexWs's errdefer already+ // reset codex_ws/codex_prev_id/codex_sent_upto by// the time we get here; call it again defensively (idempotent) so a// rebuilt body definitely carries full input with no prior-id, and ask// request() to rebuild + retry (a fresh WS re-anchors with full history)@@ -360,8 +357,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {const bearer = try std.fmt.allocPrint(arena, "Bearer {s}", .{provider.api_key});// SAME per-process session id as the HTTP path (cache partitions on it).- // ChatGPT identity tail is codex-only (#502); xAI instead takes- // x-grok-conv-id, its documented prompt-cache affinity header.+ // ChatGPT tail is codex-only (#502); xAI takes x-grok-conv-id instead.const sid = http_headers.sessionId(self.io);const all_headers = [_]ws.Header{.{ .name = "Authorization", .value = bearer },@@ -394,20 +390,14 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {defer sink.emit(self.io, .stream_finished);if (self.tracer) |tr| tr.note("ws", "connecting");- // (#codex-ws) Preemptive idle re-anchor: don't reuse a WS the server has- // likely already killed (it closes idle sockets well before our reuse in a- // real trace) — that costs a failed round trip before the reactive- // CodexWsReanchor path kicks in. Close it up front instead. Subtlety: the- // body was already built while codex_ws was non-null, so a DELTA body- // (previous_response_id + partial input) is useless on a fresh connection —- // return error.CodexWsReanchor so request()'s rebuild: loop rebuilds full- // input. A non-delta body is self-contained: just fall through and dial.- //- // This CLOCK is the only pre-send gate there is — see the liveness note- // above for why a real is_closed() equivalent is not available here, and- // which deadlines cover the socket it cannot judge.+ // (#codex-ws) Preemptive re-anchor: don't reuse a WS the server likely+ // already killed (idle) or is about to (xAI's 25-min cap) — that costs a+ // failed round trip before the reactive path. A DELTA body is useless on+ // a fresh connection, so return CodexWsReanchor for request()'s rebuild;+ // a full body falls through and dials. This clock is the only pre-send+ // gate (no is_closed() equivalent; the deadlines cover the rest).if (self.codex_ws) |held| {- if (codexWsIdleExpired(nowAwakeMs(self.io), self.codex_ws_used_ms)) {+ if (codexWsIdleExpired(nowAwakeMs(self.io), self.codex_ws_used_ms) or signal.ageExpired(nowAwakeMs(self.io))) {// The premise of this branch is that the server has likely already// killed this socket, so it is SUSPECT: it must not spend a blocking// courtesy close frame on it (ws.WsClient.deinit).@@ -444,6 +434,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {});return e;};+ signal.ws_born_ms = nowAwakeMs(self.io); // 25-min server cap starts nowself.codex_ws_used_ms = nowAwakeMs(self.io); // fresh socket = fresh idle window (#codex-ws)if (self.tracer) |tr| tr.note("ws", "connected");} else if (self.tracer) |tr| tr.note("ws", "reuse (delta)");@@ -582,6 +573,15 @@ 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});+ // xAI error frames are terminal but not in isStreamEnd's set. Both+ // arms route through postLive's close + redial (resets chain state).+ switch (signal.errorFrameAction(fbuf.items)) {+ .none => {},+ .retire, .chain_lost => |act| {+ if (self.tracer) |tr| tr.note("ws", if (act == .retire) "server connection limit — retiring socket" else "chain anchor gone — re-anchoring full");+ return error.ConnectionResetByPeer;+ },+ }if (isStreamEnd(arena, self.provider.kind, line)) {if (self.tracer) |tr| tr.note("ws", "completed");break :stream;diff --git a/src/agent_ws_signal.zig b/src/agent_ws_signal.zigindex 434ca38b..fc19e791 100644--- a/src/agent_ws_signal.zig+++ b/src/agent_ws_signal.zig@@ -122,3 +122,43 @@ pub const TokenSignal = struct {return d == .string and d.string.len != 0;}};++/// xAI WS error frames ({"type":"error"}) are terminal for the turn but not in+/// isStreamEnd's completed/failed set, so without classification they burn the+/// whole stall budget on a doomed socket.+pub const ErrorFrameAction = enum { none, retire, chain_lost };++pub fn errorFrameAction(frame: []const u8) ErrorFrameAction {+ if (std.mem.indexOf(u8, frame, "\"type\":\"error\"") == null) return .none;+ // The server sends this right before closing a 25-minute-old socket.+ if (std.mem.indexOf(u8, frame, "websocket_connection_limit_reached") != null) return .retire;+ // Our chain anchor is gone (evicted / never cached under store:false).+ if (std.mem.indexOf(u8, frame, "previous_response_not_found") != null) return .chain_lost;+ return .none;+}++/// xAI closes a WS after 25 minutes regardless of activity. Retire ours a+/// minute early so a turn never starts on a socket the server is about to+/// kill. Root-only state (wsEligible excludes subagents), set on connect.+pub var ws_born_ms: i64 = 0;+pub const ws_max_age_ms: i64 = 24 * std.time.ms_per_min;++pub fn ageExpired(now_ms: i64) bool {+ return ws_born_ms != 0 and now_ms - ws_born_ms > ws_max_age_ms;+}++test "errorFrameAction classifies the two xAI ws error codes, ignores prose" {+ try std.testing.expectEqual(ErrorFrameAction.retire, errorFrameAction("{\"type\":\"error\",\"error\":{\"code\":\"websocket_connection_limit_reached\"}}"));+ try std.testing.expectEqual(ErrorFrameAction.chain_lost, errorFrameAction("{\"type\":\"error\",\"error\":{\"code\":\"previous_response_not_found\"}}"));+ try std.testing.expectEqual(ErrorFrameAction.none, errorFrameAction("{\"type\":\"response.output_text.delta\",\"delta\":\"websocket_connection_limit_reached\"}"));+ try std.testing.expectEqual(ErrorFrameAction.none, errorFrameAction("{\"type\":\"error\",\"error\":{\"code\":\"other\"}}"));+}++test "ageExpired: fresh and unset sockets pass, 25-minute ones retire" {+ ws_born_ms = 0;+ try std.testing.expect(!ageExpired(100));+ ws_born_ms = 1000;+ try std.testing.expect(!ageExpired(1000 + 20 * std.time.ms_per_min));+ try std.testing.expect(ageExpired(1000 + 25 * std.time.ms_per_min));+ ws_born_ms = 0;+}diff --git a/src/codex_chain.zig b/src/codex_chain.zigindex 0958677e..45f4b818 100644--- a/src/codex_chain.zig+++ b/src/codex_chain.zig@@ -40,14 +40,19 @@ pub fn propsFor(self: *const Agent) u64 {/// optimization trades cheap cache reads for full-price re-uploads.pub var g_force_full_resend = false;+/// GRAFF_XAI_WS_CHAIN=1 (session_settings.applyEnvKnobs): experiment — xAI+/// documents on-socket chaining with store:false via a per-connection cache,+/// and a live probe chained successfully, but a second probe reproduced the+/// original silent multi-minute stall (both 2026-08-15). Off until the+/// service is consistent; the errorFrameAction/reanchor ladder contains the+/// blast radius when it is on.+pub var g_xai_ws_chain = false;+/// May this request chain onto the held response instead of re-anchoring?pub fn chainUsable(self: *const Agent) bool {if (g_force_full_resend) return false;- // codex-only: xAI's Responses WS accepts previous_response_id only with- // store:true — under store:false the chained turn stalls silently with no- // error event (probed live 2026-08-15). graff sends store:false, so xai- // turns always carry full input over the held socket.- if (!std.mem.eql(u8, self.provider.id, "codex")) return false;+ const xai_chain = g_xai_ws_chain and std.mem.eql(u8, self.provider.id, "xai");+ if (!std.mem.eql(u8, self.provider.id, "codex") and !xai_chain) return false;return usable(self.codex_ws != null,self.codex_prev_id != null,diff --git a/src/session_settings.zig b/src/session_settings.zigindex c2ef8ed5..94ed8b3b 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -159,6 +159,9 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {provider_mod.g_xai_responses = std.ascii.eqlIgnoreCase(std.mem.trim(u8, v, " \t"), "responses");}ws.g_debug = environ_map.get("GRAFF_WS_DEBUG") != null;+ // #502 follow-up: opt-in xAI on-socket chaining (see codex_chain.g_xai_ws_chain).+ if (environ_map.get("GRAFF_XAI_WS_CHAIN")) |v|+ @import("codex_chain.zig").g_xai_ws_chain = std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "on") or std.ascii.eqlIgnoreCase(v, "true");// GRAFF_WS_FORCE_FAIL_ONCE proves a clean retry; the counted sibling proves// that two consecutive failures latch the SSE fallback. Test seams only.if (environ_map.get("GRAFF_WS_FORCE_FAIL_ONCE")) |v| {