Skip to content

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

Python

feat(xai): per-conversation x-grok-conv-id + prompt_cache_key routing

Rach Pradhand02a4404c68c
diff --git a/src/agent.zig b/src/agent.zig
index b9ecff36..34c69c9d 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -92,6 +92,7 @@ pub const Agent = struct {
codex_chain_rewrites: u32 = 0, // history_rewrites when the chain was anchored; a later compaction/trim invalidates it
codex_props_fp: u64 = 0, // request properties the server anchored on (model/effort/fast/tools/instructions)
codex_ws_used_ms: i64 = 0, // .awake-clock ms of the WS's last successful use; gates the idle preemptive re-anchor (#codex-ws)
+ codex_ws_opened_ms: i64 = 0, // first connect time; xAI/codex WS hard-cap is 25 minutes
sub: bool,
/// This agent is served NO tools at all — the `tools` field is omitted
/// from the request rather than sent empty, which every provider accepts.
@@ -314,6 +315,7 @@ pub const Agent = struct {
self.codex_prev_id = null;
}
self.codex_sent_upto = 0;
+ self.codex_ws_opened_ms = 0;
}
pub fn runTurn(self: *Agent) anyerror![]const u8 {
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 725bdaa5..1817520c 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -17,6 +17,7 @@ const normalizeResponsesHistory = messages_mod.normalizeResponsesHistory;
const normalizeOpenAIHistory = messages_mod.normalizeOpenAIHistory;
const http = @import("http.zig");
+const http_headers = @import("http_headers.zig");
const postWatched = http.postWatched;
const RetryPlan = http.RetryPlan;
@@ -62,6 +63,7 @@ pub const parseResponses = responses.parseResponses;
pub const errorMessage = responses.errorMessage;
pub const buildBody = @import("agent_request_body.zig").buildBody;
+const codex_chain = @import("codex_chain.zig");
const req_stats = @import("req_stats.zig"); // GRAFF_REQ_STATS anatomy (session_settings arms req_stats.g_armed)
@@ -203,10 +205,12 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
const resp_body = blk: {
var attempt: usize = 0;
while (true) : (attempt += 1) {
+ var conv_buf: [96]u8 = undefined;
+ const conv = http_headers.promptCacheKey(self.io, self.label, self, &conv_buf);
const attempt_body = if (live)
self.postLive(body)
else
- postWatched(self.gpa, self.io, self.client, self.provider, body);
+ postWatched(self.gpa, self.io, self.client, self.provider, body, conv);
if (attempt_body) |ok| break :blk ok else |err| {
if (self.streamed_text) if (self.out) |w| {
w.writeAll("\n") catch {};
@@ -389,9 +393,9 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
// input. Gated on codex_prev_id != null (a delta was
// actually sent); it's null after the retry, so this can't
// loop for this request.
- if (self.codex_prev_id != null and std.mem.indexOf(u8, msg, "previous_response_id") != null) {
+ if (self.codex_prev_id != null and codex_chain.shouldDropChain(msg, failure.code)) {
self.closeCodexWs();
- if (self.tracer) |tr| tr.note("ws", "server rejected previous_response_id — re-anchoring with full input");
+ if (self.tracer) |tr| tr.note("ws", "server dropped previous_response_id — re-anchoring with full input");
continue :rebuild;
}
// #174: a context-window rejection means the true input
diff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zig
index b5934303..1566265d 100644
--- a/src/agent_request_body_responses.zig
+++ b/src/agent_request_body_responses.zig
@@ -19,19 +19,16 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_too
const is_codex = std.mem.eql(u8, self.provider.id, "codex");
try s.objectField("instructions");
try s.write(try schemaAwarePrompt(self));
- if (is_codex) {
- // 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 automatic prompt
- // caching and no such field, so it stays codex-only.
+ 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.
var ckbuf: [96]u8 = undefined;
try s.objectField("prompt_cache_key");
try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));
}
- // Codex WS delta: once a response.id is held on a live WS session, send
- // previous_response_id + only the items the server does not yet hold.
- // codex_chain gates this to codex — xAI's WS stalls silently on a
- // store:false chained turn (probed 2026-08-15). ONE gate for both fields.
+ // Held-socket delta: previous_response_id + only the new items. xAI's
+ // published WS contract supports this with store:false via the in-memory
+ // connection cache; a not-found / 25-min close / drop re-anchors.
const chain = codex_chain.chainUsable(self);
if (chain) {
try s.objectField("previous_response_id");
@@ -164,7 +161,7 @@ test "xai Responses body is bearer-clean: no codex-isms, xAI-legal fields only (
try 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);
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 --git a/src/agent_server_compact.zig b/src/agent_server_compact.zig
index e9292511..dbc5c8be 100644
--- a/src/agent_server_compact.zig
+++ b/src/agent_server_compact.zig
@@ -258,7 +258,9 @@ pub fn explicitCompact(self: *Agent) bool {
var cp = self.provider;
cp.url = compact_url;
if (!main_mod.json_mode) self.say("[compacting server-side: {d} item(s)…]\n", .{self.messages.items.len}) catch {};
- const resp = http.postWatched(self.gpa, self.io, self.client, cp, body) catch |err| {
+ var conv_buf: [96]u8 = undefined;
+ const conv = @import("http_headers.zig").promptCacheKey(self.io, self.label, self, &conv_buf);
+ const resp = http.postWatched(self.gpa, self.io, self.client, cp, body, conv) catch |err| {
if (self.tracer) |tr| tr.note("compact", @errorName(err));
return false;
};
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index 5d579718..1f9a4663 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -23,8 +23,8 @@ const reasoningDelta = @import("title.zig").reasoningDelta;
const stream_tests = @import("agent_stream_tests.zig");
const http = @import("http.zig");
+const http_headers = @import("http_headers.zig");
const providerUserAgent = http.providerUserAgent;
-const providerHeaders = http.providerHeaders;
const capture5xxBodyStream = http.capture5xxBodyStream;
const WatchdogFired = http.WatchdogFired;
const sendHeadTask = http.sendHeadTask;
@@ -74,7 +74,9 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
};
defer if (bearer.len > 0) gpa.free(bearer);
var headers_buf: [12]std.http.Header = undefined;
- const extra = providerHeaders(self.io, provider, bearer, &headers_buf);
+ var conv_buf: [96]u8 = undefined;
+ const conv = http_headers.promptCacheKey(self.io, self.label, self, &conv_buf);
+ const extra = http_headers.providerHeadersWithConv(self.io, provider, bearer, &headers_buf, conv);
self.md_buf.clearRetainingCapacity(); // fresh markdown state per stream
self.arg_live = .{}; // fresh tool-argument extractor per stream
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index 52015a15..7c13d137 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -75,6 +75,13 @@ pub fn codexWsIdleExpired(now_ms: i64, used_ms: i64) bool {
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;
+
+pub fn wsLifetimeExpired(now_ms: i64, opened_ms: i64) bool {
+ return opened_ms != 0 and now_ms - opened_ms >= ws_lifetime_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 {
@@ -364,19 +371,24 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
defer gpa.free(frame);
const bearer = try std.fmt.allocPrint(arena, "Bearer {s}", .{provider.api_key});
- // The SAME per-process session id the HTTP path sends, not a fresh one per
- // connect: this is what the backend partitions its prompt cache on, so a
- // new id per socket handed every re-anchor a cold partition.
- // The ChatGPT identity tail is codex-only — xAI's WS authenticates with the bearer alone (#502).
- const all_headers = [_]ws.Header{
- .{ .name = "Authorization", .value = bearer },
- .{ .name = "session_id", .value = http_headers.sessionId(self.io) },
- .{ .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 headers: []const ws.Header = if (std.mem.eql(u8, provider.id, "codex")) &all_headers else all_headers[0..2];
+ 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.
@@ -394,20 +406,10 @@ 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.
+ // Idle or 25-minute cap: a delta body is useless on a fresh socket.
if (self.codex_ws) |held| {
- if (codexWsIdleExpired(nowAwakeMs(self.io), self.codex_ws_used_ms)) {
+ 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).
@@ -444,7 +446,8 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
});
return e;
};
- self.codex_ws_used_ms = nowAwakeMs(self.io); // fresh socket = fresh idle window (#codex-ws)
+ self.codex_ws_opened_ms = nowAwakeMs(self.io);
+ self.codex_ws_used_ms = self.codex_ws_opened_ms;
if (self.tracer) |tr| tr.note("ws", "connected");
} else if (self.tracer) |tr| tr.note("ws", "reuse (delta)");
const client = self.codex_ws.?;
diff --git a/src/codex_chain.zig b/src/codex_chain.zig
index 0958677e..21787a02 100644
--- a/src/codex_chain.zig
+++ b/src/codex_chain.zig
@@ -41,13 +41,28 @@ pub fn propsFor(self: *const Agent) u64 {
pub var g_force_full_resend = 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;
- // 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;
+ if (!chainBrandOk(self.provider.id)) return false;
return usable(
self.codex_ws != null,
self.codex_prev_id != null,
@@ -145,3 +160,17 @@ test "usable: chains only on a clean extension of what the server holds" {
// /model or /effort changed between turns.
try std.testing.expect(!usable(true, true, 4, 6, 0, 0, 8, 7));
}
+
+test "chainBrandOk: xAI and codex chain; anthropic does not" {
+ try std.testing.expect(chainBrandOk("codex"));
+ try std.testing.expect(chainBrandOk("xai"));
+ try std.testing.expect(!chainBrandOk("anthropic"));
+ try std.testing.expect(!chainBrandOk("kimi"));
+}
+
+test "shouldDropChain: not-found and 25-minute cap evict the in-memory id" {
+ try std.testing.expect(shouldDropChain("Previous response with id 'resp_abc' not found.", "previous_response_not_found"));
+ try std.testing.expect(shouldDropChain("Responses websocket connection limit reached (25 minutes).", "websocket_connection_limit_reached"));
+ try std.testing.expect(shouldDropChain("unsupported previous_response_id", null));
+ try std.testing.expect(!shouldDropChain("rate limited", "rate_limit_exceeded"));
+}
diff --git a/src/grok_spec_conformance.zig b/src/grok_spec_conformance.zig
new file mode 100644
index 00000000..04ea3fc1
--- /dev/null
+++ b/src/grok_spec_conformance.zig
@@ -0,0 +1,224 @@
+//! 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);
+ 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 --git a/src/http.zig b/src/http.zig
index e6c441aa..7a3f7896 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -27,6 +27,8 @@ pub fn waitForClientReady(io: Io) void {
pub const providerUserAgent = headers.userAgent;
pub const providerHeaders = headers.providerHeaders;
+/// Test/call-site seam: the !live request path's POST, with an explicit conv id.
+pub const postWithConv = post;
/// Copy up to root.g_5xx_body_buf.len bytes of an error response body into the
/// global buffer so request()'s retry message can surface the gateway's
@@ -120,7 +122,7 @@ test "retryAfterMs: seconds, ms preferred, cap, HTTP-date/none -> 0 (#retry-afte
/// subagents (#177). Mirrors postStream's errdefer poison (agent_stream.zig).
/// The client and its connection pool stay shared across pool threads —
/// client.request is what fetch wraps and is equally thread-safe.
-fn post(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []const u8) ![]u8 {
+fn post(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []const u8, conv_id: ?[]const u8) ![]u8 {
var aw: Io.Writer.Allocating = .init(gpa);
errdefer aw.deinit();
@@ -131,7 +133,7 @@ fn post(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []co
defer if (bearer.len > 0) gpa.free(bearer);
var headers_buf: [12]std.http.Header = undefined;
- const extra = providerHeaders(client.io, provider, bearer, &headers_buf);
+ const extra = headers.providerHeadersWithConv(client.io, provider, bearer, &headers_buf, conv_id);
var req = try client.request(.POST, try std.Uri.parse(provider.url), .{
.redirect_behavior = .unhandled,
@@ -334,8 +336,8 @@ pub fn headStallTask(io: Io, poll_stdin: bool) WatchdogFired {
}
/// Select-arm wrapper for `post` (pins the member type to anyerror![]u8).
-fn postTask(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []const u8) anyerror![]u8 {
- return post(gpa, client, provider, body);
+fn postTask(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []const u8, conv_id: ?[]const u8) anyerror![]u8 {
+ return post(gpa, client, provider, body, conv_id);
}
/// Cancel the remaining select arms, freeing a late-arriving response body
@@ -355,11 +357,11 @@ fn drainPostSelect(gpa: Allocator, sel: anytype) void {
/// Esc surfaces as error.Interrupted (no retry); the deadline as
/// error.HungRequest, which request()'s retry loop treats as a transport
/// flake. Falls back to a bare post when no spare concurrency exists.
-pub fn postWatched(gpa: Allocator, io: Io, client: *std.http.Client, provider: Provider, body: []const u8) ![]u8 {
+pub fn postWatched(gpa: Allocator, io: Io, client: *std.http.Client, provider: Provider, body: []const u8, conv_id: ?[]const u8) ![]u8 {
const Done = union(enum) { posted: anyerror![]u8, watchdog: WatchdogFired };
var done_buf: [2]Done = undefined;
var sel: Io.Select(Done) = .init(io, &done_buf);
- sel.concurrent(.posted, postTask, .{ gpa, client, provider, body }) catch
+ sel.concurrent(.posted, postTask, .{ gpa, client, provider, body, conv_id }) catch
return error.HungRequest; // #56 Fix-B: pool exhausted — don't fall back to a bare blocking post() that can hang a subagent turn with no Esc path; return retryable so request() retries + backs off
sel.concurrent(.watchdog, postWatchdog, .{io}) catch {
const r = sel.await() catch |e| { // posted is the only arm
@@ -461,7 +463,7 @@ test "post (#177): a send-failed connection is not re-pooled — the next reques
// poisoned the connection, and the real assertion is that the NEXT request
// recovers (below). Only an unexpected success needs the throwaway dial, to
// release the server's still-pending second accept() so await can't hang.
- if (post(gpa, &client, provider, big)) |resp| {
+ if (post(gpa, &client, provider, big, null)) |resp| {
gpa.free(resp);
if (std.Io.net.IpAddress.connect(&bound, io, .{ .mode = .stream })) |s| s.close(io) else |_| {}
return error.TestExpectedError;
@@ -470,7 +472,7 @@ test "post (#177): a send-failed connection is not re-pooled — the next reques
// The regression: without the poison this pulls dead conn 1 back out of
// the pool (no fresh dial) and fails with WriteFailed instead of
// reaching conn 2's 200.
- const second = post(gpa, &client, provider, "{}");
+ const second = post(gpa, &client, provider, "{}", null);
if (second) |resp| {
defer gpa.free(resp);
try std.testing.expectEqualStrings("ok", resp);
@@ -572,7 +574,7 @@ test "post (#177 5xx path): an oversized 5xx surfaces as ServerError and the ses
// The 5xx surfaces as error.ServerError and poisons conn 1. Guard the
// assertion the same way as the send-failed test: on any other outcome,
// release the server's still-pending second accept() before failing.
- if (post(gpa, &client, provider, "{}")) |resp| {
+ if (post(gpa, &client, provider, "{}", null)) |resp| {
gpa.free(resp);
if (std.Io.net.IpAddress.connect(&bound, io, .{ .mode = .stream })) |s| s.close(io) else |_| {}
return error.TestExpectedError; // a 500 must surface as ServerError
@@ -584,7 +586,7 @@ test "post (#177 5xx path): an oversized 5xx surfaces as ServerError and the ses
// Recovery: the next request reaches conn 2's 200. (Unlike the send-failed
// case above, std does not re-pool a partially-read connection on its own,
// so this asserts end-to-end recovery, not that the 5xx poison is required.)
- const second = post(gpa, &client, provider, "{}");
+ const second = post(gpa, &client, provider, "{}", null);
if (second) |resp| {
defer gpa.free(resp);
try std.testing.expectEqualStrings("ok", resp);
diff --git a/src/http_headers.zig b/src/http_headers.zig
index d1018f3e..091d111b 100644
--- a/src/http_headers.zig
+++ b/src/http_headers.zig
@@ -107,7 +107,19 @@ pub fn userAgent(provider: Provider) std.http.Client.Request.Headers.Value {
return .default;
}
+/// xAI Chat Completions + Responses: the official cache-routing header.
+/// `promptCacheKey` is the same sticky id used as Responses `prompt_cache_key`.
+pub fn wantsGrokConvId(provider_id: []const u8) bool {
+ return std.mem.eql(u8, provider_id, "xai");
+}
+
pub fn providerHeaders(io: Io, provider: Provider, bearer: []const u8, buf: *[12]std.http.Header) []const std.http.Header {
+ return providerHeadersWithConv(io, provider, bearer, buf, null);
+}
+
+/// Same as `providerHeaders`, with an explicit conversation id for xAI.
+/// Null falls back to the process session id (one-off posts: title, compact).
+pub fn providerHeadersWithConv(io: Io, provider: Provider, bearer: []const u8, buf: *[12]std.http.Header, conv_id: ?[]const u8) []const std.http.Header {
var count: usize = 0;
switch (provider.auth) {
.x_api_key => {
@@ -140,6 +152,10 @@ pub fn providerHeaders(io: Io, provider: Provider, bearer: []const u8, buf: *[12
buf[count] = .{ .name = "session_id", .value = sessionId(io) };
count += 1;
}
+ if (wantsGrokConvId(provider.id)) {
+ buf[count] = .{ .name = "x-grok-conv-id", .value = conv_id orelse sessionId(io) };
+ count += 1;
+ }
return buf[0..count];
}
@@ -196,3 +212,41 @@ test "adoptSessionId validates length and never overwrites a minted id" {
adoptSessionId("00000000-0000-4000-8000-000000000000");
try 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);
+}