Skip to content

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

Python

xAI WS chains previous_response_id; handshake stall latches HTTPS SSE.

justrach45a80a9e6e84
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 616f003a..6fb4391f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ current is part of cutting a release.
## v0.0.302.4
- Task workspace housekeeping: `graff worktree update` merges the remote base; `gc` drops dead session trees and clean trees whose GitHub PR is MERGED (dirty trees stay). Desktop: Update from main, Clear unused trees. Asking to free space unfolds `workspace` so `action=gc` is callable this turn.
+- xAI Responses WS chains `previous_response_id` on the held socket (store:false in-memory cache). A stalled first handshake or 426 latches HTTPS SSE for the session; chrome shows a dim `using HTTPS SSE` notice. `GRAFF_XAI_WS_CHAIN=0` opts out.
## v0.0.302.3
diff --git a/docs/adr/0002-xai-defaults-to-the-responses-wire.md b/docs/adr/0002-xai-defaults-to-the-responses-wire.md
index 4c2cf4e3..6a9b4fa7 100644
--- a/docs/adr/0002-xai-defaults-to-the-responses-wire.md
+++ b/docs/adr/0002-xai-defaults-to-the-responses-wire.md
@@ -1,6 +1,6 @@
# 0002. xAI defaults to the Responses wire (WS; client compact)
-Status: accepted 2026-08-15; compaction arm amended 2026-09-05
+Status: accepted 2026-08-15; compaction arm amended 2026-09-05; WS chaining on 2026-09-19
## Context
@@ -34,9 +34,10 @@ opts a session back onto chat completions.
- WS eligibility stays an explicit provider list (codex, xai, and Codegraff
when its selected alias is Responses-kind) — Platform OpenAI has no WS
server and must never probe one.
-- Chaining via previous_response_id stays codex-only: xAI's store:false +
- previous_response_id stalls server-side (probed live), so xai rides
- full-resend over the held socket.
+- xAI WS chaining is on: `previous_response_id` + delta input on the held
+ socket, matching the published store:false / ZDR in-memory cache. A
+ not-found, 25-minute cap, or drop re-anchors with full input (append-only
+ history; compact rewrites drop the chain). `GRAFF_XAI_WS_CHAIN=0` opts out.
- Revisit if xAI's wire diverges from OpenAI Responses semantics or the
compact endpoint's blob replay pricing changes the cost picture.
- Hosted `x_search` rides this wire by default (ADR
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 088222c4..cd360d9c 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -12,7 +12,7 @@ record only when you need the evidence or the edge cases.
| ADR | The rule |
|---|---|
| [0001](0001-structured-outputs-are-a-formatting-step.md) | Structured output is a final formatting step. Never constrain the agentic phase with a schema grammar, and do not use `--output-schema` unless a program consumes the result. |
-| [0002](0002-xai-defaults-to-the-responses-wire.md) | xAI runs on the Responses wire by default (WS turns). Compaction is the client summarizer, not xAI's blob endpoint. `GRAFF_XAI_WIRE=chat` opts out. |
+| [0002](0002-xai-defaults-to-the-responses-wire.md) | xAI runs on the Responses wire by default (WS turns + on-socket `previous_response_id`). Compaction is the client summarizer, not xAI's blob endpoint. `GRAFF_XAI_WIRE=chat` opts out. |
| [0003](0003-codegraff-wire-follows-model-capability.md) | Codegraff uses Responses + WS for GPT-5.6+ (incl. GPT-6 Astra / Codex `gpt-5.6-*`) and grok-4.6; Claude, Gemini, and other aliases stay on Chat Completions. |
| [0004](0004-peer-speech-is-a-working-set.md) | Peer speech is pull: a one-line `[peer]` wake in history, bodies in the inbox ring; compact drops spent injects and never treats them as the human. |
| [0005](0005-standing-goal-lives-in-the-prefix.md) | Standing goal is one prefix line; the user-message essay injects on change only, never every N turns. |
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index 04ee7a7e..e837dd61 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -127,19 +127,10 @@ pub fn postLive(self: *Agent, body: []const u8) ![]u8 {
if (e == error.CodexWsReanchor) return e;
self.closeCodexWs();
self.ws_transport_failures +|= 1;
- // (#427) A 426 is the server answering authoritatively — it will not
- // upgrade this endpoint — so the ladder's free retry would only redial
- // the same refusal. Latch now (openai/codex: FallbackToHttp).
+ // 426, a stalled first handshake, or two failures → HTTPS SSE. A delta
+ // body died with the socket — never replay previous_response_id on HTTP.
const declined = e == error.UpgradeRequired;
- const fallback = declined or wsShouldFallback(self.ws_transport_failures);
- // (#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)
- // instead of falling back to a stale SSE replay.
+ const fallback = signal.shouldLatchSse(e == error.WsConnectStalled, e, self.ws_transport_failures);
if (std.mem.indexOf(u8, body, "\"previous_response_id\"") != null) {
if (fallback) self.ws_off = true;
if (self.tracer) |tr| tr.note("ws", if (fallback)
@@ -153,7 +144,8 @@ pub fn postLive(self: *Agent, body: []const u8) ![]u8 {
return error.CodexWsReanchor;
}
self.ws_off = true;
- if (self.tracer) |tr| tr.note("ws", if (declined) "426 upgrade required — using persistent prewarmed SSE for this session" else "transport failed twice — using persistent prewarmed SSE for this session");
+ engine_sink.forAgent(self).emit(self.io, .{ .session_notice = .{ .text = "using HTTPS SSE", .tone = .dim } });
+ if (self.tracer) |tr| tr.note("ws", if (declined) "426 upgrade required — using persistent prewarmed SSE for this session" else if (e == error.WsConnectStalled) "connect stall — using persistent prewarmed SSE for this session" else "transport failed twice — using persistent prewarmed SSE for this session");
return self.postStream(body);
};
self.ws_transport_failures = 0;
@@ -427,18 +419,13 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
const reused = self.codex_ws != null;
if (self.codex_ws == null) {
self.codex_ws = connectWatched(gpa, self.io, url, headers, orig_tio != null) catch |e| {
- // HungRequest, matching connectWatched's deadline error — NOT
- // StreamStalled, which the guard stopped returning when it moved to
- // the SSE guard's transport-flake semantics. An arm naming the wrong
- // error is unreachable, and a stalled dial then traces a bare
- // "HungRequest" instead of saying the dial is where it stalled (the
- // observability #401 was filed about).
+ // HungRequest here is the dial watchdog — not a mid-stream stall.
if (self.tracer) |tr| tr.note("ws", switch (e) {
error.HungRequest => "connect stall",
error.Interrupted => "esc",
else => @errorName(e),
});
- return e;
+ return if (e == error.HungRequest) error.WsConnectStalled else e;
};
self.codex_ws_opened_ms = nowAwakeMs(self.io); // 25-min server cap starts now
self.codex_ws_used_ms = self.codex_ws_opened_ms; // fresh socket = fresh idle window (#codex-ws)
diff --git a/src/agent_ws_signal.zig b/src/agent_ws_signal.zig
index b503c482..bc4f4313 100644
--- a/src/agent_ws_signal.zig
+++ b/src/agent_ws_signal.zig
@@ -177,3 +177,19 @@ test "errorFrameAction classifies every actual error frame and ignores quoted pr
try std.testing.expectEqual(ErrorFrameAction.none, errorFrameAction(a, "{\"type\":\"response.output_text.delta\",\"delta\":\"quoted \\\"type\\\":\\\"error\\\"\"}"));
try std.testing.expectEqual(ErrorFrameAction.none, errorFrameAction(a, "not json: error"));
}
+
+/// Latch HTTPS SSE: 426, a stalled first handshake, or two transport failures.
+/// Mid-stream HungRequest on a held socket is not a setup stall.
+pub fn shouldLatchSse(setup_stall: bool, err: anyerror, failures: u8) bool {
+ if (err == error.UpgradeRequired) return true;
+ if (setup_stall) return true;
+ return failures >= 2;
+}
+
+test "shouldLatchSse: 426 and connect stall latch now; 500 handshake still retries once" {
+ try std.testing.expect(shouldLatchSse(false, error.UpgradeRequired, 1));
+ try std.testing.expect(shouldLatchSse(true, error.HungRequest, 1));
+ try std.testing.expect(!shouldLatchSse(false, error.HungRequest, 1));
+ try std.testing.expect(!shouldLatchSse(false, error.HandshakeFailed, 1));
+ try std.testing.expect(shouldLatchSse(false, error.HandshakeFailed, 2));
+}
diff --git a/src/agent_ws_stall_test.zig b/src/agent_ws_stall_test.zig
index 01c244f6..ece186cc 100644
--- a/src/agent_ws_stall_test.zig
+++ b/src/agent_ws_stall_test.zig
@@ -361,10 +361,10 @@ test "#401: a stalled dial fails the turn fast and traces `connect stall` (produ
const ms = nowMs(io) - t0;
if (r) |ok| gpa.free(ok) else |_| {}
- // HungRequest, not StreamStalled: a dial that never upgraded is a transport
- // failure, so postLive retries one fresh socket and only then latches SSE,
- // rather than spending a slot of request()'s 2-slot stall budget.
- try std.testing.expectError(error.HungRequest, r);
+ // WsConnectStalled (not StreamStalled): a dial that never upgraded is a
+ // setup failure, so postLive latches HTTPS SSE instead of burning a stall
+ // slot or a second handshake.
+ try std.testing.expectError(error.WsConnectStalled, r);
try std.testing.expect(ms < 10_000); // unguarded, this never returned at all
try std.testing.expect(ms >= 200); // the watchdog, not the pool-exhausted shortcut
try std.testing.expect(traced(&tw, "\"detail\":\"connecting\""));
diff --git a/src/codex_chain.zig b/src/codex_chain.zig
index d9e5c7ac..667bb493 100644
--- a/src/codex_chain.zig
+++ b/src/codex_chain.zig
@@ -40,13 +40,10 @@ 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;
+/// xAI on-socket chaining (published WS contract: store:false / ZDR via the
+/// per-connection cache). GRAFF_XAI_WS_CHAIN=0 opts out. A not-found, 25-min
+/// cap, or drop re-anchors with full input (shouldDropChain).
+pub var g_xai_ws_chain = true;
/// May this request chain onto the held response instead of re-anchoring?
/// Brands whose Responses WS holds prior state in-memory and accept
@@ -177,6 +174,11 @@ test "usable: chains only on a clean extension of what the server holds" {
try std.testing.expect(!usable(true, true, 4, 6, 0, 0, 8, 7));
}
+test "chainUsable: xAI chains by default on a held socket" {
+ try std.testing.expect(g_xai_ws_chain);
+ try std.testing.expect(usable(true, true, 1, 2, 0, 0, 7, 7));
+}
+
test "chainBrandOk: xAI and codex chain; anthropic does not" {
try std.testing.expect(chainBrandOk("codex"));
try std.testing.expect(chainBrandOk("xai"));
diff --git a/src/engine_sink.zig b/src/engine_sink.zig
index 1aed02f0..e52098f3 100644
--- a/src/engine_sink.zig
+++ b/src/engine_sink.zig
@@ -373,6 +373,10 @@ fn hostedEmit(a: *Agent, ev: EngineEvent) void {
w.print("{s} {s}\n", .{ mark, shortTool(r.name) }) catch {};
w.flush() catch {};
},
+ .session_notice => |n| {
+ w.print("{s}\n", .{n.text}) catch {};
+ w.flush() catch {};
+ },
else => {},
}
}
diff --git a/src/grok_spec_conformance.zig b/src/grok_spec_conformance.zig
index f0934cb7..7a296954 100644
--- a/src/grok_spec_conformance.zig
+++ b/src/grok_spec_conformance.zig
@@ -241,11 +241,7 @@ test "grok spec: held xAI WS chains previous_response_id + delta; drop rebuilds
agent.codex_prev_id = try std.testing.allocator.dupe(u8, "resp_live");
agent.codex_sent_upto = 2;
agent.codex_props_fp = codex_chain.propsFor(&agent);
- // On-socket xAI chaining is opt-in (GRAFF_XAI_WS_CHAIN — a live probe
- // reproduced a silent stall, so it is off by default); the contract
- // being conformance-tested here is the opted-in behavior.
- codex_chain.g_xai_ws_chain = true;
- defer codex_chain.g_xai_ws_chain = false;
+ try std.testing.expect(codex_chain.g_xai_ws_chain);
try std.testing.expect(codex_chain.chainUsable(&agent));
const delta = try agent.buildBody(null, false, false, false);
@@ -337,6 +333,21 @@ test "grok spec: official cache is an exact prefix — append keeps it, edit bre
try std.testing.expectEqualStrings(cacheKeyIn(first).?, cacheKeyIn(miss).?);
}
+test "grok spec: compact/rewrite is not an append — chain drops (official cache miss)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var dummy_ws: ws.WsClient = undefined;
+ var agent = try xaiAgent(a, "main", .responses);
+ agent.codex_ws = &dummy_ws;
+ agent.codex_prev_id = "resp_live";
+ agent.codex_sent_upto = 1;
+ agent.codex_props_fp = codex_chain.propsFor(&agent);
+ try std.testing.expect(codex_chain.chainUsable(&agent));
+ agent.history_rewrites += 1;
+ try std.testing.expect(!codex_chain.chainUsable(&agent));
+}
+
test "grok spec: Chat replays reasoning_content (official top cache-miss cause)" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/main.zig b/src/main.zig
index 8284c4a6..7251c897 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -579,6 +579,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");
+ _ = @import("agent_ws_signal.zig");
_ = @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
diff --git a/src/session_settings.zig b/src/session_settings.zig
index 183d23d0..4dcce00e 100644
--- a/src/session_settings.zig
+++ b/src/session_settings.zig
@@ -240,9 +240,11 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {
if (v.len > 0) provider_mod.g_vercel_url_override = v;
}
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");
+ // xAI on-socket chaining is on (ADR 0002). GRAFF_XAI_WS_CHAIN=0/off/false opts out.
+ if (environ_map.get("GRAFF_XAI_WS_CHAIN")) |v| {
+ const off = std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "off") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "no");
+ @import("codex_chain.zig").g_xai_ws_chain = !off;
+ }
// 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| {
diff --git a/src/tui_acp.zig b/src/tui_acp.zig
index 8b1a0c4b..b741bc5d 100644
--- a/src/tui_acp.zig
+++ b/src/tui_acp.zig
@@ -119,6 +119,7 @@ fn writeUpdate(w: *Io.Writer, session_id: []const u8, ev: engine_events.EngineEv
if (label.skipTranscript(r.name)) return;
try acp_stream.writeToolDone(w, session_id, "call-1", true, r.message);
},
+ .session_notice => |n| try acp_stream.writeThought(w, session_id, n.text),
else => {},
}
}