graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
merge origin/main: keep per-agent WS clock + per-conversation conv-id, main's opt-in xAI chain gate
Rach Pradhanfe7c4ab7e4ec
diff --cc src/agent.zigindex 34c69c9d,b228c995..fa834b3e--- a/src/agent.zig+++ b/src/agent.zig@@@ -315,9 -317,25 +318,26 @@@ pub const Agent = structself.codex_prev_id = null;}self.codex_sent_upto = 0;+ self.codex_ws_opened_ms = 0;}+ /// The text of the newest user message, "" when there is none or it is+ /// not a plain string (attachments/tool replies don't route).+ fn lastUserText(self: *const Agent) []const u8 {+ var i = self.messages.items.len;+ while (i > 0) {+ i -= 1;+ const m = self.messages.items[i];+ if (m != .object) continue;+ const role = m.object.get("role") orelse continue;+ if (role == .string and std.mem.eql(u8, role.string, "user")) {+ const content = m.object.get("content") orelse return "";+ return if (content == .string) content.string else "";+ }+ }+ return "";+ }+pub fn runTurn(self: *Agent) anyerror![]const u8 {// Defensive for restored/embedded agents whose provider was assigned// directly instead of going through providers.applyProvider.diff --cc src/agent_request_body_responses.zigindex 1566265d,6319008f..fff49f84--- a/src/agent_request_body_responses.zig+++ b/src/agent_request_body_responses.zig@@@ -19,9 -19,12 +19,12 @@@ pub fn write(self: *Agent, s: *std.jsonconst is_codex = std.mem.eql(u8, self.provider.id, "codex");try s.objectField("instructions");try s.write(try schemaAwarePrompt(self));- if (is_codex or std.mem.eql(u8, self.provider.id, "xai")) {+ if (is_codex or http_headers.wantsGrokConvId(self.provider.id)) {- // Codex: session UUID partition. xAI: official prompt_cache_key,- // same sticky id as the `x-grok-conv-id` header.+ // Pin our full resends to a per-session cache partition, the way+ // openai/codex does (it defaults this to the same session UUID it+ // puts in the `session_id` header). xAI documents prompt_cache_key ++ // the x-grok-conv-id header for the same purpose- // (advanced-api-usage/prompt-caching), so it rides for xai too.++ // (advanced-api-usage/prompt-caching) — same sticky id as the header.var ckbuf: [96]u8 = undefined;try s.objectField("prompt_cache_key");try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));@@@ -161,7 -165,7 +164,7 @@@ test "xai Responses body is bearer-cleatry std.testing.expect(std.mem.indexOf(u8, body, "\"instructions\":\"system\"") != null);try std.testing.expect(std.mem.indexOf(u8, body, "\"store\":false") != null);try std.testing.expect(std.mem.indexOf(u8, body, "\"reasoning\":{\"effort\":\"medium\"}") != null);- try std.testing.expect(std.mem.indexOf(u8, body, "\"prompt_cache_key\":\"") != null);- try std.testing.expect(std.mem.indexOf(u8, body, "prompt_cache_key") != null); // xAI caches on it (+ x-grok-conv-id header)++ try std.testing.expect(std.mem.indexOf(u8, body, "\"prompt_cache_key\":\"") != null); // xAI caches on it (+ x-grok-conv-id header)try std.testing.expect(std.mem.indexOf(u8, body, "service_tier") == null);try std.testing.expect(std.mem.indexOf(u8, body, "context_management") == null);try std.testing.expect(std.mem.indexOf(u8, body, "previous_response_id") == null);diff --cc src/agent_ws.zigindex 7c13d137,f6f05716..3e27bbae--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@@ -75,13 -72,6 +72,16 @@@ pub fn codexWsIdleExpired(now_ms: i64,return now_ms - used_ms > codex_ws_idle_ms;}+/// Official Responses WS hard cap: one connection stays open ≤ 25 minutes.+pub const ws_lifetime_ms: i64 = 25 * std.time.ms_per_min;++/// Retire a minute early so a turn never STARTS on a socket the server is++/// about to kill mid-response (per-agent clock: codex_ws_opened_ms).++pub const ws_retire_ms: i64 = ws_lifetime_ms - std.time.ms_per_min;++pub fn wsLifetimeExpired(now_ms: i64, opened_ms: i64) bool {- return opened_ms != 0 and now_ms - opened_ms >= ws_lifetime_ms;++ return opened_ms != 0 and now_ms - opened_ms >= ws_retire_ms;+}+/// The .awake monotonic clock in ms — same time source as request()'s/// latency measurement, so codex_ws_used_ms compares consistently.fn nowAwakeMs(io: Io) i64 {@@@ -371,24 -358,23 +368,27 @@@ pub fn postResponsesWs(self: *Agent, bodefer gpa.free(frame);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 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 },- .{ .name = "session_id", .value = sid },- .{ .name = "chatgpt-account-id", .value = provider.account },- .{ .name = "OpenAI-Beta", .value = "responses_websockets=2026-02-06" },- .{ .name = "originator", .value = "codex_cli_rs" },- .{ .name = "User-Agent", .value = "codex_cli_rs/0.1 (graff)" },- };- const xai_headers = [_]ws.Header{- .{ .name = "Authorization", .value = bearer },- .{ .name = "session_id", .value = sid },- .{ .name = "x-grok-conv-id", .value = sid },- };- const headers: []const ws.Header = if (std.mem.eql(u8, provider.id, "codex")) &all_headers else &xai_headers;++ // ChatGPT tail is codex-only (#502); xAI takes x-grok-conv-id instead —++ // the PER-CONVERSATION cache id (root/sub isolated), same sticky value as++ // the Responses body's prompt_cache_key, not the bare process session id.+ var conv_buf: [96]u8 = undefined;+ const conv = http_headers.promptCacheKey(self.io, self.label, self, &conv_buf);+ var hdrs: [7]ws.Header = undefined;+ var hn: usize = 1;+ hdrs[0] = .{ .name = "Authorization", .value = bearer };+ if (std.mem.eql(u8, provider.id, "codex")) {+ hdrs[1] = .{ .name = "session_id", .value = http_headers.sessionId(self.io) };+ hdrs[2] = .{ .name = "chatgpt-account-id", .value = provider.account };+ hdrs[3] = .{ .name = "OpenAI-Beta", .value = "responses_websockets=2026-02-06" };+ hdrs[4] = .{ .name = "originator", .value = "codex_cli_rs" };+ hdrs[5] = .{ .name = "User-Agent", .value = "codex_cli_rs/0.1 (graff)" };+ hn = 6;+ } else if (http_headers.wantsGrokConvId(provider.id)) {+ hdrs[1] = .{ .name = "session_id", .value = http_headers.sessionId(self.io) };+ hdrs[2] = .{ .name = "x-grok-conv-id", .value = conv };+ hn = 3;+ }+ const headers: []const ws.Header = hdrs[0..hn];const url = try wssUrl(arena, provider.url);// Esc watching (root TTY), same gate as postStream.@@@ -406,10 -392,14 +406,15 @@@defer sink.emit(self.io, .stream_finished);if (self.tracer) |tr| tr.note("ws", "connecting");- // Idle or 25-minute cap: a delta body is useless on a fresh socket.+ // (#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++ // already killed (idle) or is about to (the 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) or signal.ageExpired(nowAwakeMs(self.io))) {+ const now = nowAwakeMs(self.io);+ if (codexWsIdleExpired(now, self.codex_ws_used_ms) or wsLifetimeExpired(now, self.codex_ws_opened_ms)) {// 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).@@@ -446,8 -436,8 +451,8 @@@});return e;};- self.codex_ws_opened_ms = nowAwakeMs(self.io);- self.codex_ws_used_ms = self.codex_ws_opened_ms;- signal.ws_born_ms = nowAwakeMs(self.io); // 25-min server cap starts now- self.codex_ws_used_ms = nowAwakeMs(self.io); // fresh socket = fresh idle window (#codex-ws)++ 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)if (self.tracer) |tr| tr.note("ws", "connected");} else if (self.tracer) |tr| tr.note("ws", "reuse (delta)");const client = self.codex_ws.?;diff --cc src/agent_ws_signal.zigindex 434ca38b,fc19e791..f4fb3261--- a/src/agent_ws_signal.zig+++ b/src/agent_ws_signal.zig@@@ -122,3 -122,43 +122,24 @@@ pub const TokenSignal = structreturn 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 --cc src/codex_chain.zigindex 21787a02,45f4b818..705f3b7c--- a/src/codex_chain.zig+++ b/src/codex_chain.zig@@@ -40,29 -40,19 +40,38 @@@ pub fn propsFor(self: *const Agent) u6/// 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?+/// Brands whose Responses WS holds prior state in-memory and accept+/// `previous_response_id` + delta input (including store:false / ZDR).+pub fn chainBrandOk(provider_id: []const u8) bool {+ return std.mem.eql(u8, provider_id, "codex") or std.mem.eql(u8, provider_id, "xai");+}++/// A failed turn must drop the chain: not-found (ZDR / store:false evict),+/// the 25-minute connection cap, or a generic previous_response_id reject.+pub fn shouldDropChain(message: []const u8, code: ?[]const u8) bool {+ if (code) |c| {+ if (std.mem.indexOf(u8, c, "previous_response_not_found") != null) return true;+ if (std.mem.indexOf(u8, c, "websocket_connection_limit_reached") != null) return true;+ }+ if (std.mem.indexOf(u8, message, "previous_response_not_found") != null) return true;+ if (std.mem.indexOf(u8, message, "websocket connection limit") != null) return true;+ if (std.mem.indexOf(u8, message, "previous_response_id") != null) return true;+ return false;+}+pub fn chainUsable(self: *const Agent) bool {if (g_force_full_resend) return false;- if (!chainBrandOk(self.provider.id)) 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 --cc src/grok_spec_conformance.zigindex 04ea3fc1,00000000..bf1721c0mode 100644,000000..100644--- a/src/grok_spec_conformance.zig+++ b/src/grok_spec_conformance.zig@@@ -1,224 -1,0 +1,229 @@@+//! Official xAI prompt-cache + Responses WS contract, against shipped builders.++const std = @import("std");+const Agent = @import("agent.zig").Agent;+const http = @import("http.zig");+const http_headers = @import("http_headers.zig");+const codex_chain = @import("codex_chain.zig");+const agent_ws = @import("agent_ws.zig");+const ws = @import("ws.zig");++fn textMessage(arena: std.mem.Allocator, role: []const u8, text: []const u8) !std.json.Value {+ var obj: std.json.ObjectMap = .empty;+ try obj.put(arena, "role", .{ .string = role });+ try obj.put(arena, "content", .{ .string = text });+ return .{ .object = obj };+}++fn xaiAgent(arena: std.mem.Allocator, label: []const u8, kind: @import("provider.zig").Provider.Kind) !Agent {+ var messages = std.json.Array.init(arena);+ try messages.append(try textMessage(arena, "user", "hello"));+ return .{+ .gpa = std.testing.allocator,+ .arena = arena,+ .io = std.testing.io,+ .client = undefined,+ .provider = .{ .id = "xai", .kind = kind, .auth = .bearer, .url = "https://api.x.ai/v1/responses", .api_key = "k", .model = "grok-4.6", .context = 256_000 },+ .messages = messages,+ .sub = !std.mem.eql(u8, label, "main"),+ .label = label,+ .out = null,+ .sys_normal = "system",+ };+}++fn cacheKeyIn(body: []const u8) ?[]const u8 {+ const needle = "\"prompt_cache_key\":\"";+ const start = std.mem.indexOf(u8, body, needle) orelse return null;+ const from = start + needle.len;+ const end = std.mem.indexOfScalarPos(u8, body, from, '"') orelse return null;+ return body[from..end];+}++test "grok spec: Chat Completions x-grok-conv-id is stable for root and isolated for a child" {+ const io = std.testing.io;+ var root_slot: usize = 1;+ var child_slot: usize = 2;+ var rbuf: [96]u8 = undefined;+ var cbuf: [96]u8 = undefined;+ const root_id = http_headers.promptCacheKey(io, "main", @ptrCast(&root_slot), &rbuf);+ var rbuf2: [96]u8 = undefined;+ try std.testing.expectEqualStrings(root_id, http_headers.promptCacheKey(io, "main", @ptrCast(&root_slot), &rbuf2));+ const child_id = http_headers.promptCacheKey(io, "sub", @ptrCast(&child_slot), &cbuf);+ try std.testing.expect(!std.mem.eql(u8, root_id, child_id));++ const xai: @import("provider.zig").Provider = .{ .id = "xai", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "grok-4.6", .context = 256_000 };+ var h1: [12]std.http.Header = undefined;+ var h2: [12]std.http.Header = undefined;+ var h3: [12]std.http.Header = undefined;+ const a = http_headers.providerHeadersWithConv(io, xai, "Bearer k", &h1, root_id);+ const b = http_headers.providerHeadersWithConv(io, xai, "Bearer k", &h2, root_id);+ const c = http_headers.providerHeadersWithConv(io, xai, "Bearer k", &h3, child_id);+ const va = blk: {+ for (a) |h| if (std.mem.eql(u8, h.name, "x-grok-conv-id")) break :blk h.value;+ return error.MissingGrokConvId;+ };+ const vb = blk: {+ for (b) |h| if (std.mem.eql(u8, h.name, "x-grok-conv-id")) break :blk h.value;+ return error.MissingGrokConvId;+ };+ const vc = blk: {+ for (c) |h| if (std.mem.eql(u8, h.name, "x-grok-conv-id")) break :blk h.value;+ return error.MissingGrokConvId;+ };+ try std.testing.expectEqualStrings(root_id, va);+ try std.testing.expectEqualStrings(va, vb);+ try std.testing.expectEqualStrings(child_id, vc);+ try std.testing.expect(!std.mem.eql(u8, va, vc));+}++// The !live request path: Agent.request → promptCacheKey → postWatched → post.+// A local server records the x-grok-conv-id each POST actually sent.+test "grok spec: !live post wires Agent conv id; root and child differ" {+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;+ const gpa = std.testing.allocator;+ const io = std.testing.io;++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var root = try xaiAgent(a, "main", .openai);+ var child = try xaiAgent(a, "sub", .responses);+ var rbuf: [96]u8 = undefined;+ var cbuf: [96]u8 = undefined;+ const rid = http_headers.promptCacheKey(root.io, root.label, &root, &rbuf);+ const cid = http_headers.promptCacheKey(child.io, child.label, &child, &cbuf);+ try std.testing.expect(!std.mem.eql(u8, rid, cid));+ const child_body = try child.buildBody(null, false, false, false);+ defer gpa.free(child_body);+ const body_key = cacheKeyIn(child_body) orelse return error.MissingPromptCacheKey;+ try std.testing.expectEqualStrings(cid, body_key);++ const Srv = struct {+ seen: [2][96]u8 = undefined,+ lens: [2]usize = .{ 0, 0 },+ n: usize = 0,+ fn run(io_: std.Io, server: *std.Io.net.Server, self: *@This()) void {+ while (self.n < 2) {+ const c = server.accept(io_) catch return;+ defer c.close(io_);+ var rbuf2: [4096]u8 = undefined;+ var sr = std.Io.net.Stream.Reader.init(c, io_, &rbuf2);+ while (true) {+ const line = (sr.interface.takeDelimiter('\n') catch break) orelse break;+ if (line.len == 0 or (line.len == 1 and line[0] == '\r')) break;+ if (std.ascii.startsWithIgnoreCase(line, "x-grok-conv-id:")) {+ const v = std.mem.trim(u8, line["x-grok-conv-id:".len..], " \t\r");+ const n = @min(v.len, self.seen[self.n].len);+ @memcpy(self.seen[self.n][0..n], v[0..n]);+ self.lens[self.n] = n;+ }+ }+ _ = sr.interface.take(2) catch {};+ var wbuf: [128]u8 = undefined;+ var sw = std.Io.net.Stream.Writer.init(c, io_, &wbuf);+ sw.interface.writeAll("HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok") catch {};+ sw.interface.flush() catch {};+ self.n += 1;+ }+ }+ };+ var srv: Srv = .{};+ var addr = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");+ var server = try std.Io.net.IpAddress.listen(&addr, io, .{});+ var fut = io.async(Srv.run, .{ io, &server, &srv });+ defer fut.await(io);+ defer server.deinit(io);+ var bound = server.socket.address;+ var url_buf: [64]u8 = undefined;+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/v1/chat", .{bound.getPort()});+ var p_root = root.provider;+ p_root.url = url;+ var p_child = child.provider;+ p_child.url = url;+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ const r1 = http.postWatched(gpa, io, &client, p_root, "{}", rid) catch |e| {+ if (std.Io.net.IpAddress.connect(&bound, io, .{ .mode = .stream })) |s| s.close(io) else |_| {}+ return e;+ };+ defer gpa.free(r1);+ const r2 = http.postWatched(gpa, io, &client, p_child, child_body, cid) catch |e| {+ if (std.Io.net.IpAddress.connect(&bound, io, .{ .mode = .stream })) |s| s.close(io) else |_| {}+ return e;+ };+ defer gpa.free(r2);+ try std.testing.expectEqual(@as(usize, 2), srv.n);+ try std.testing.expectEqualStrings(rid, srv.seen[0][0..srv.lens[0]]);+ try std.testing.expectEqualStrings(cid, srv.seen[1][0..srv.lens[1]]);+ try std.testing.expectEqualStrings(body_key, srv.seen[1][0..srv.lens[1]]);+ try std.testing.expect(!std.mem.eql(u8, srv.seen[0][0..srv.lens[0]], srv.seen[1][0..srv.lens[1]]));+}++test "grok spec: Responses body has a stable prompt_cache_key; Anthropic does not" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = try xaiAgent(a, "main", .responses);+ const first = try agent.buildBody(null, false, true, true);+ defer std.testing.allocator.free(first);+ const second = try agent.buildBody(null, false, true, true);+ defer std.testing.allocator.free(second);+ const k1 = cacheKeyIn(first) orelse return error.MissingPromptCacheKey;+ const k2 = cacheKeyIn(second) orelse return error.MissingPromptCacheKey;+ try std.testing.expectEqualStrings(k1, k2);+ try std.testing.expect(k1.len > 0);++ var anth = try xaiAgent(a, "main", .anthropic);+ anth.provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude", .context = 200_000 };+ const abody = try anth.buildBody(null, false, true, true);+ defer std.testing.allocator.free(abody);+ try std.testing.expect(cacheKeyIn(abody) == null);+}++test "grok spec: held xAI WS chains previous_response_id + delta; drop rebuilds full input" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var msgs = std.json.Array.init(a);+ try msgs.append(try textMessage(a, "user", "first"));+ try msgs.append(try textMessage(a, "assistant", "second"));+ try msgs.append(try textMessage(a, "user", "third — not yet sent"));+ var dummy_ws: ws.WsClient = undefined;+ var agent = try xaiAgent(a, "main", .responses);+ agent.messages = msgs;+ agent.codex_ws = &dummy_ws;+ 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.chainUsable(&agent));++ const delta = try agent.buildBody(null, false, false, false);+ defer std.testing.allocator.free(delta);+ try std.testing.expect(std.mem.indexOf(u8, delta, "\"previous_response_id\":\"resp_live\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, delta, "third — not yet sent") != null);+ try std.testing.expect(std.mem.indexOf(u8, delta, "\"first\"") == null);+ try std.testing.expect(cacheKeyIn(delta) != null);++ try std.testing.expect(codex_chain.shouldDropChain("Previous response with id 'resp_live' not found.", "previous_response_not_found"));+ try std.testing.expect(codex_chain.shouldDropChain("connection limit reached (25 minutes)", "websocket_connection_limit_reached"));+ try std.testing.expect(!agent_ws.wsLifetimeExpired(agent_ws.ws_lifetime_ms, 0));+ try std.testing.expect(agent_ws.wsLifetimeExpired(2 * agent_ws.ws_lifetime_ms, agent_ws.ws_lifetime_ms));++ // store=false drop: same state closeCodexWs leaves — full input, no prev id.+ std.testing.allocator.free(agent.codex_prev_id.?);+ agent.codex_ws = null;+ agent.codex_prev_id = null;+ agent.codex_sent_upto = 0;+ try std.testing.expect(!codex_chain.chainUsable(&agent));+ const rebuilt = try agent.buildBody(null, false, false, false);+ defer std.testing.allocator.free(rebuilt);+ try std.testing.expect(std.mem.indexOf(u8, rebuilt, "\"previous_response_id\"") == null);+ try std.testing.expect(std.mem.indexOf(u8, rebuilt, "\"first\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, rebuilt, "third — not yet sent") != null);+}diff --cc src/http_headers.zigindex 091d111b,3a4b2aef..4477f363--- a/src/http_headers.zig+++ b/src/http_headers.zig@@@ -213,40 -211,41 +227,79 @@@ test "adoptSessionId validates length atry std.testing.expectEqualStrings(before, sessionId(io));}+fn headerValue(headers: []const std.http.Header, name: []const u8) ?[]const u8 {+ for (headers) |h| if (std.mem.eql(u8, h.name, name)) return h.value;+ return null;+}++test "xAI Chat Completions headers carry a stable per-conversation x-grok-conv-id" {+ const io = std.testing.io;+ var root_ptr: usize = 1;+ var child_ptr: usize = 2;+ const root_agent: *const anyopaque = @ptrCast(&root_ptr);+ const child_agent: *const anyopaque = @ptrCast(&child_ptr);+ var root_buf: [96]u8 = undefined;+ var child_buf: [96]u8 = undefined;+ const root_id = promptCacheKey(io, "main", root_agent, &root_buf);+ const again_buf = promptCacheKey(io, "main", root_agent, root_buf[0..]);+ _ = again_buf;+ var root_buf2: [96]u8 = undefined;+ try std.testing.expectEqualStrings(root_id, promptCacheKey(io, "main", root_agent, &root_buf2));+ const child_id = promptCacheKey(io, "sub", child_agent, &child_buf);+ try std.testing.expect(!std.mem.eql(u8, root_id, child_id));++ const xai: Provider = .{ .id = "xai", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "grok-4.6", .context = 256_000 };+ var buf: [12]std.http.Header = undefined;+ const first = providerHeadersWithConv(io, xai, "Bearer k", &buf, root_id);+ try std.testing.expectEqualStrings(root_id, headerValue(first, "x-grok-conv-id") orelse return error.MissingGrokConvId);+ var buf2: [12]std.http.Header = undefined;+ const second = providerHeadersWithConv(io, xai, "Bearer k", &buf2, root_id);+ try std.testing.expectEqualStrings(root_id, headerValue(second, "x-grok-conv-id").?);+ var buf3: [12]std.http.Header = undefined;+ const child_headers = providerHeadersWithConv(io, xai, "Bearer k", &buf3, child_id);+ try std.testing.expectEqualStrings(child_id, headerValue(child_headers, "x-grok-conv-id").?);++ const anth: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude", .context = 200_000 };+ var abuf: [12]std.http.Header = undefined;+ const ah = providerHeadersWithConv(io, anth, "", &abuf, root_id);+ try std.testing.expect(headerValue(ah, "x-grok-conv-id") == null);+}+++ test "xai login tokens send X-XAI-Token-Auth; API keys do not" {+ const io = std.testing.io;+ var buf: [12]std.http.Header = undefined;+ const login: Provider = .{+ .id = "xai",+ .kind = .openai,+ .auth = .bearer,+ .url = "",+ .api_key = "oauth-tok",+ .model = "grok-4.3",+ .context = 256_000,+ .source = .login,+ };+ const login_headers = providerHeaders(io, login, "Bearer oauth-tok", &buf);+ var saw_token_auth = false;+ for (login_headers) |h| {+ if (std.mem.eql(u8, h.name, "X-XAI-Token-Auth")) {+ try std.testing.expectEqualStrings("xai-grok-cli", h.value);+ saw_token_auth = true;+ }+ }+ try std.testing.expect(saw_token_auth);++ const env_key: Provider = .{+ .id = "xai",+ .kind = .openai,+ .auth = .bearer,+ .url = "",+ .api_key = "xai-api-key",+ .model = "grok-4.3",+ .context = 256_000,+ .source = .environment,+ };+ const env_headers = providerHeaders(io, env_key, "Bearer xai-api-key", &buf);+ for (env_headers) |h| {+ try std.testing.expect(!std.mem.eql(u8, h.name, "X-XAI-Token-Auth"));+ }+ }