graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(xai): full grok support — Responses wire, WS turns, first-party compaction, structured outputs (#502)
Rach Pradhan7503d12ba36d
diff --git a/src/additional_tests.zig b/src/additional_tests.zigindex e7069139..55e30732 100644--- a/src/additional_tests.zig+++ b/src/additional_tests.zig@@ -1,4 +1,5 @@test {_ = @import("readline_history.zig");_ = @import("codedbpro_paths.zig");+ _ = @import("agent_request_body_responses.zig");}diff --git a/src/agent.zig b/src/agent.zigindex 03da64ce..b9ecff36 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -214,6 +214,7 @@ pub const Agent = struct {streamed_args_len: usize = 0, // raw bytes emitted for it (gates re-print suppression)cap_new: bool = false, // provider rejected max_tokens → use max_completion_tokenseffort_rejected: bool = false, // model rejected reasoning_effort → drop it (e.g. gpt-5.5 on chat/completions wants /v1/responses)+ output_schema: ?[]const u8 = null, // --output-schema: JSON schema the final answer must satisfy (response_format / text.format, #502)next_ask_id: u64 = 1,tui_header_shown: bool = false,diff --git a/src/agent_request_body.zig b/src/agent_request_body.zigindex 726b8f5a..12e8469e 100644--- a/src/agent_request_body.zig+++ b/src/agent_request_body.zig@@ -146,7 +146,7 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bootry s.objectField("role");try s.write("system");try s.objectField("content");- try s.write(self.systemPrompt());+ try s.write(try @import("agent_request_body_responses.zig").schemaAwarePrompt(self));try s.endObject();for (self.messages.items) |m| try writeOpenAIMessageNormalized(&s, m);try s.endArray();@@ -180,77 +180,13 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bootry s.objectField("reasoning_effort");try s.write(if (self.reasoning == .ultra) "max" else @tagName(self.reasoning));}+ // --output-schema: structured outputs (xAI docs' response_format).+ if (self.output_schema) |schema_json|+ try @import("agent_request_body_responses.zig").writeResponseFormat(&s, schema_json);},- .responses => {- // Codex / ChatGPT Responses API. system prompt → instructions; history- // items are valid input items; stream is required (we buffer + parse the- // SSE); reasoning items return encrypted and are passed back per turn.- try s.objectField("instructions");- try s.write(self.systemPrompt());- // 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). Without it the backend has no- // affinity hint for a prefix we re-upload every turn.- var ckbuf: [96]u8 = undefined;- try s.objectField("prompt_cache_key");- try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));- // GPT-5.6 explicit caching (prompt_cache_options / breakpoints) is- // platform-API-only — this route 400s on both. Implicit + cache key is all.- // 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, instead of the full history (avoids the huge frame that the- // backend rejects → WriteFailed). Full input otherwise (first turn/SSE).- // ONE gate for both fields: emitting previous_response_id beside a full- // input would make the server re-prepend a history we also sent.- const chain = codex_chain.chainUsable(self);- if (chain) {- try s.objectField("previous_response_id");- try s.write(self.codex_prev_id.?);- }- try s.objectField("input");- if (chain) {- var delta = std.json.Array.init(self.arena);- for (self.messages.items[self.codex_sent_upto..]) |m| try delta.append(m);- try s.write(Value{ .array = delta });- } else {- try s.write(Value{ .array = self.messages });- }- if (tools) |t| {- try s.objectField("tools");- try serde.writeOpenAITools(&s, self.scratchAlloc(), t); // #261 follow-up- try s.objectField("tool_choice");- try s.write(if (force_tool) "required" else "auto");- try s.objectField("parallel_tool_calls");- try s.write(true);- }- // Codex "fast" mode (/fast): request the priority service- // tier for lower latency. This branch is codex-only, so it is- // never emitted for other providers.- if (self.fast) {- try s.objectField("service_tier");- try s.write("priority");- }- try s.objectField("reasoning");- try s.beginObject();- try s.objectField("effort");- // Ultra preset → wire value `max`. #379: compaction summaries run- // at low effort — a high-effort reasoner can complete with only- // reasoning items and zero output text, i.e. an empty summary.- try s.write(if (self.compaction_request) "low" else if (self.reasoning == .ultra) "max" else @tagName(self.reasoning));- try s.endObject();- try s.objectField("include");- try s.beginArray();- try s.write("reasoning.encrypted_content");- try s.endArray();- try s.objectField("store");- try s.write(false);- server_compact.noteExposure(self);- try server_compact.writeContextManagement(self, &s);- // No top-level max_output_tokens: the codex backend rejects it- // ("Unsupported parameter") on gpt-5.6-* — codex sets it only as a tool argument.- try s.objectField("stream");- try s.write(true);- },+ // The Responses-wire body (codex / xAI #502) lives in its own module+ // under the 600-line ceiling; structured-output writers ride along.+ .responses => try @import("agent_request_body_responses.zig").write(self, &s, tools, force_tool),}try s.endObject();return aw.toOwnedSlice();diff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zignew file mode 100644index 00000000..b5934303--- /dev/null+++ b/src/agent_request_body_responses.zig@@ -0,0 +1,195 @@+//! The Responses-wire request body (codex / xAI #502), split from+//! agent_request_body.zig under the 600-line ceiling, plus the structured-+//! output writers (text.format here, response_format for the chat wire).++const std = @import("std");+const Value = std.json.Value;++const Agent = @import("agent.zig").Agent;+const serde = @import("serde.zig");+const http_headers = @import("http_headers.zig");+const codex_chain = @import("codex_chain.zig");+const server_compact = @import("agent_server_compact.zig");++pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_tool: bool) !void {+ // Responses API (codex / ChatGPT backend, and xAI behind GRAFF_XAI_WIRE).+ // system prompt → instructions; history items are valid input items;+ // stream is required (we buffer + parse the SSE); reasoning items return+ // encrypted and are passed back per turn.+ 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.+ 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.+ const chain = codex_chain.chainUsable(self);+ if (chain) {+ try s.objectField("previous_response_id");+ try s.write(self.codex_prev_id.?);+ }+ try s.objectField("input");+ if (chain) {+ var delta = std.json.Array.init(self.arena);+ for (self.messages.items[self.codex_sent_upto..]) |m| try delta.append(m);+ try s.write(Value{ .array = delta });+ } else {+ try s.write(Value{ .array = self.messages });+ }+ if (tools) |t| {+ try s.objectField("tools");+ try serde.writeOpenAITools(s, self.scratchAlloc(), t); // #261 follow-up+ try s.objectField("tool_choice");+ try s.write(if (force_tool) "required" else "auto");+ try s.objectField("parallel_tool_calls");+ try s.write(true);+ }+ // Codex "fast" mode (/fast): priority service tier — a ChatGPT-backend+ // field the other Responses providers must never see.+ if (self.fast and is_codex) {+ try s.objectField("service_tier");+ try s.write("priority");+ }+ try s.objectField("reasoning");+ try s.beginObject();+ try s.objectField("effort");+ // Ultra preset → wire value `max`. #379: compaction summaries run at low+ // effort — a high-effort reasoner can complete with only reasoning items+ // and zero output text, i.e. an empty summary.+ try s.write(if (self.compaction_request) "low" else if (self.reasoning == .ultra) "max" else @tagName(self.reasoning));+ try s.endObject();+ try s.objectField("include");+ try s.beginArray();+ try s.write("reasoning.encrypted_content");+ try s.endArray();+ try s.objectField("store");+ try s.write(false);+ server_compact.noteExposure(self);+ try server_compact.writeContextManagement(self, s);+ if (self.output_schema) |schema_json| try writeTextFormat(s, schema_json);+ // No top-level max_output_tokens: the codex backend rejects it+ // ("Unsupported parameter") on gpt-5.6-* — codex sets it only as a tool argument.+ try s.objectField("stream");+ try s.write(true);+}++/// With --output-schema the strict grammar tempts the model to answer+/// immediately instead of touching tools (graff-evals caught grok-4.6+/// answering a file-inspection task without reading the file). One standing+/// line restores tools-first behavior; without a schema the prompt is+/// byte-identical to before.+pub fn schemaAwarePrompt(self: *Agent) ![]const u8 {+ const base = self.systemPrompt();+ if (self.output_schema == null) return base;+ return std.mem.concat(self.scratchAlloc(), u8, &.{+ base,+ "\n\nA JSON output schema is enforced on your final message. Use tools first to gather every fact you need; only the final message must match the schema — never guess values.",+ });+}++/// Structured outputs on the Responses wire (xAI/OpenAI): `text.format` with+/// the user's JSON schema the final answer must satisfy (--output-schema).+pub fn writeTextFormat(s: *std.json.Stringify, schema_json: []const u8) !void {+ try s.objectField("text");+ try s.beginObject();+ try s.objectField("format");+ try s.beginObject();+ try s.objectField("type");+ try s.write("json_schema");+ try s.objectField("name");+ try s.write("result");+ try s.objectField("strict");+ try s.write(true);+ try s.objectField("schema");+ try s.print("{s}", .{schema_json});+ try s.endObject();+ try s.endObject();+}++/// Structured outputs on the chat-completions wire: response_format+/// json_schema (the shape xAI/OpenAI/compatible routers document).+pub fn writeResponseFormat(s: *std.json.Stringify, schema_json: []const u8) !void {+ try s.objectField("response_format");+ try s.beginObject();+ try s.objectField("type");+ try s.write("json_schema");+ try s.objectField("json_schema");+ try s.beginObject();+ try s.objectField("name");+ try s.write("result");+ try s.objectField("strict");+ try s.write(true);+ try s.objectField("schema");+ try s.print("{s}", .{schema_json});+ try s.endObject();+ try s.endObject();+}++fn testAgentFor(arena: std.mem.Allocator, id: []const u8, kind: @import("provider.zig").Provider.Kind, model: []const u8) !Agent {+ var messages = std.json.Array.init(arena);+ var user: std.json.ObjectMap = .empty;+ try user.put(arena, "role", .{ .string = "user" });+ try user.put(arena, "content", .{ .string = "hello" });+ try messages.append(.{ .object = user });+ return .{+ .gpa = std.testing.allocator,+ .arena = arena,+ .io = std.testing.io,+ .client = undefined,+ .provider = .{ .id = id, .kind = kind, .auth = .bearer, .url = "", .api_key = "k", .model = model, .context = 500_000 },+ .messages = messages,+ .sub = false,+ .label = "main",+ .out = null,+ .sys_normal = "system",+ };+}++test "xai Responses body is bearer-clean: no codex-isms, xAI-legal fields only (#502)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var agent = try testAgentFor(arena_state.allocator(), "xai", .responses, "grok-4.6");+ agent.fast = true; // must NOT leak service_tier off codex+ const body = try agent.buildBody(null, false, true, true);+ defer std.testing.allocator.free(body);+ 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, "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);+}++test "--output-schema rides text.format on Responses and response_format on chat (#502)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const schema = "{\"type\":\"object\",\"properties\":{\"answer\":{\"type\":\"string\"}},\"required\":[\"answer\"],\"additionalProperties\":false}";+ var agent = try testAgentFor(arena_state.allocator(), "xai", .responses, "grok-4.6");+ agent.output_schema = schema;+ const responses_body = try agent.buildBody(null, false, true, true);+ defer std.testing.allocator.free(responses_body);+ try std.testing.expect(std.mem.indexOf(u8, responses_body, "\"text\":{\"format\":{\"type\":\"json_schema\",\"name\":\"result\",\"strict\":true,\"schema\":{\"type\":\"object\"") != null);++ var chat = try testAgentFor(arena_state.allocator(), "xai", .openai, "grok-4.6");+ chat.output_schema = schema;+ const chat_body = try chat.buildBody(null, false, true, true);+ defer std.testing.allocator.free(chat_body);+ try std.testing.expect(std.mem.indexOf(u8, chat_body, "\"response_format\":{\"type\":\"json_schema\",\"json_schema\":{\"name\":\"result\",\"strict\":true,\"schema\":{\"type\":\"object\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, chat_body, "\"text\":{\"format\"") == null);++ // No schema set → neither field appears (the overwhelmingly common path).+ var plain = try testAgentFor(arena_state.allocator(), "xai", .openai, "grok-4.6");+ const plain_body = try plain.buildBody(null, false, true, true);+ defer std.testing.allocator.free(plain_body);+ try std.testing.expect(std.mem.indexOf(u8, plain_body, "response_format") == null);+}diff --git a/src/agent_server_compact.zig b/src/agent_server_compact.zigindex 2b1a080b..e9292511 100644--- a/src/agent_server_compact.zig+++ b/src/agent_server_compact.zig@@ -28,6 +28,8 @@ const Agent = @import("agent.zig").Agent;const Provider = @import("provider.zig").Provider;const telemetry = @import("telemetry.zig");const keys_cli = @import("keys_cli.zig");+const http = @import("http.zig"); // #502: the explicit xAI compact POST+const goal_flow = @import("goal_flow.zig");/// GRAFF_SERVER_COMPACT=0/false/off forces the client arm, =1 forces the/// server arm (session_settings.applyEnvKnobs). Default: A/B assignment.@@ -110,6 +112,9 @@ pub fn noteClientSummary(chars: usize) void {/// GRAFF_COMPACT_PCT-aware) so the server compacts at the point graff would/// have.pub fn writeContextManagement(self: *const Agent, s: anytype) !void {+ // #502: an explicit-compact provider (xAI) ignores the in-stream directive+ // — probed live; compaction goes through explicitCompact instead.+ if (self.provider.serverCompactUrl() != null) return;if (!enabled(self.provider)) return;try writeContextManagementBody(self, s);}@@ -195,6 +200,15 @@ pub fn autocompact(self: *Agent, recovery_meter: u64) void {}fn autocompactIf(self: *Agent, recovery_meter: u64, server_arm: bool) void {+ // #502: an explicit-compact provider (xAI) gets first-party compaction —+ // one POST folds the whole history into an opaque blob, no summary model+ // call. Any failure falls through to the client policy so a broken+ // endpoint can never wedge the session.+ if (self.provider.serverCompactUrl() != null) {+ if (explicitCompact(self)) return;+ self.compactOrRecover(self.provider.nearContextLimit(recovery_meter));+ return;+ }if (!server_arm or self.provider.kind != .responses) {self.compactOrRecover(self.provider.nearContextLimit(recovery_meter));return;@@ -208,6 +222,80 @@ fn autocompactIf(self: *Agent, recovery_meter: u64, server_arm: bool) void {self.compactOrRecover(true);}+fn buildCompactBody(self: *Agent) ![]u8 {+ var aw: Io.Writer.Allocating = .init(self.gpa);+ errdefer aw.deinit();+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.beginObject();+ try s.objectField("model");+ try s.write(self.provider.model);+ try s.objectField("input");+ try s.write(std.json.Value{ .array = self.messages });+ try s.endObject();+ return aw.toOwnedSlice();+}++/// #502: explicit first-party compaction (xAI POST /v1/responses/compact):+/// ship the current input items, then restart history from the returned+/// opaque compaction item — the docs' "treat the compaction as the new+/// start". True when history was replaced; ANY failure leaves it untouched+/// so the caller can fall back to the client-side summary.+pub fn explicitCompact(self: *Agent) bool {+ const compact_url = self.provider.serverCompactUrl() orelse return false;+ if (self.messages.items.len == 0) return false;+ // Anti-thrash: a history already anchored on a blob with only a few items+ // after it cannot meaningfully shrink — when the threshold sits below the+ // standing prompt overhead (a tiny GRAFF_COMPACT_PCT), re-compacting every+ // step pays one API call per step forever. Let the client policy decide.+ const items = self.messages.items;+ if (items.len < 8 and items[0] == .object) {+ if (items[0].object.get("type")) |t| {+ if (t == .string and std.mem.eql(u8, t.string, "compaction")) return false;+ }+ }+ const body = buildCompactBody(self) catch return false;+ defer self.gpa.free(body);+ 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| {+ if (self.tracer) |tr| tr.note("compact", @errorName(err));+ return false;+ };+ defer self.gpa.free(resp);+ return installCompactionItem(self, resp);+}++/// Parse a compact-endpoint response and restart history from output[0].+/// Split from explicitCompact so a fixture response drives it in tests.+pub fn installCompactionItem(self: *Agent, resp: []const u8) bool {+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, self.arena, resp, .{ .allocate = .alloc_always }) catch return false;+ if (parsed != .object) return false;+ const output = parsed.object.get("output") orelse return false;+ if (output != .array or output.array.items.len == 0) return false;+ const blob = output.array.items[0];+ if (blob != .object) return false;+ const t = blob.object.get("type") orelse return false;+ if (t != .string or !std.mem.eql(u8, t.string, "compaction")) return false;+ if (blob.object.get("encrypted_content") == null) return false;+ const dropped = self.messages.items.len;+ var fresh = std.json.Array.init(self.arena);+ fresh.append(blob) catch return false;+ self.messages = fresh;+ // Mirror pruneIf's meter/goal reset: both anchors recompute lazily, the+ // goal note died with the folded history (#318), and pasted-state readers+ // re-carry off history_rewrites.+ self.last_context_tokens = 0;+ self.context_local_tokens = 0;+ self.goal_note_fp = 0;+ self.history_rewrites +%= 1;+ if (self.pending_goal_note == null)+ self.pending_goal_note = goal_flow.compactionSnapshot(self.arena, self) catch null;+ notePrune(dropped);+ if (!main_mod.json_mode) self.say("[server compacted context: {d} item(s) folded into the model's compaction state]\n", .{dropped}) catch {};+ return true;+}+const test_support = @import("agent_compact_test_support.zig");fn testAgent(a: std.mem.Allocator, kind: Provider.Kind) Agent {@@ -345,3 +433,59 @@ test "autocompact: responses providers hold at the ordinary threshold without atry std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);}++test "installCompactionItem restarts history from the blob and resets the meters (#502)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = testAgent(a, .responses);+ agent.arena = a;+ try agent.messages.append(try item(a, "message", null));+ try agent.messages.append(try item(a, "function_call", "c1"));+ try agent.messages.append(try item(a, "function_call_output", "c1"));+ agent.last_context_tokens = 400_000;+ const resp =+ \\{"id":"cmp_1","object":"response.compaction","output":[{"type":"compaction","id":"cmp_1","encrypted_content":"BLOB"}],+ \\ "usage":{"input_tokens":9000,"output_tokens":400,"dropped_message_count":3}}+ ;+ try std.testing.expect(installCompactionItem(&agent, resp));+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);+ try std.testing.expectEqualStrings("compaction", agent.messages.items[0].object.get("type").?.string);+ try std.testing.expectEqualStrings("BLOB", agent.messages.items[0].object.get("encrypted_content").?.string);+ try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);+ try std.testing.expectEqual(@as(u32, 1), agent.history_rewrites);+}++test "installCompactionItem refuses malformed responses and leaves history intact (#502)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = testAgent(a, .responses);+ agent.arena = a;+ try agent.messages.append(try item(a, "message", null));+ for ([_][]const u8{+ "not json",+ "{\"output\":[]}",+ "{\"output\":[{\"type\":\"message\"}]}",+ "{\"output\":[{\"type\":\"compaction\"}]}", // no encrypted_content+ }) |bad| {+ try std.testing.expect(!installCompactionItem(&agent, bad));+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);+ try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);+ }+}++test "explicitCompact anti-thrash: a fresh blob head with little growth refuses (#502)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = testAgent(a, .responses);+ agent.arena = a;+ agent.provider.id = "xai"; // serverCompactUrl fires for xai + .responses+ try agent.messages.append(try item(a, "compaction", null));+ try agent.messages.append(try item(a, "message", null));+ // Guard trips BEFORE any network I/O — false, history untouched.+ try std.testing.expect(!explicitCompact(&agent));+ try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);+ try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);+}diff --git a/src/agent_steps.zig b/src/agent_steps.zigindex 262325e3..58b41c8b 100644--- a/src/agent_steps.zig+++ b/src/agent_steps.zig@@ -215,6 +215,26 @@ pub fn stepAnthropic(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {return final_text;}+/// Trailing sampler markers some models leak into chat content (grok-4.6+/// emits `<|eos|>` after strict-schema JSON — caught by graff-evals).+pub fn stripEosSuffix(text: []const u8) []const u8 {+ var t = std.mem.trimEnd(u8, text, " \t\r\n");+ for ([_][]const u8{ "<|eos|>", "<|eot|>", "<|endoftext|>" }) |marker| {+ if (std.mem.endsWith(u8, t, marker)) {+ t = std.mem.trimEnd(u8, t[0 .. t.len - marker.len], " \t\r\n");+ break;+ }+ }+ return t;+}++test "stripEosSuffix drops a leaked trailing sampler marker, nothing else" {+ try std.testing.expectEqualStrings("{\"a\":1}", stripEosSuffix("{\"a\":1}<|eos|>"));+ try std.testing.expectEqualStrings("{\"a\":1}", stripEosSuffix("{\"a\":1}<|eos|>\n"));+ try std.testing.expectEqualStrings("done", stripEosSuffix("done"));+ try std.testing.expectEqualStrings("say <|eos|> mid-text", stripEosSuffix("say <|eos|> mid-text"));+}+pub fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {const choices = root.get("choices");// #287/#299: same as the anthropic step — the parent only ever sees what@@ -236,8 +256,11 @@ pub fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {var final_text: []const u8 = "";if (msg_obj.get("content")) |c| if (c == .string and c.string.len > 0) {- final_text = c.string;- try surfaceUnstreamedText(self, c.string);+ // grok-4.6 structured outputs (response_format) leak a literal+ // sampler end marker after the JSON on the chat wire (#502) — a+ // trailing `<|eos|>` is never legitimate answer text.+ final_text = stripEosSuffix(c.string);+ try surfaceUnstreamedText(self, final_text);};var calls: std.ArrayList(ToolCall) = .empty;diff --git a/src/agent_ws.zig b/src/agent_ws.zigindex 6ea41af3..3c78679d 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -367,15 +367,16 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {// 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.- const sid = http_headers.sessionId(self.io);- const headers = [_]ws.Header{+ // 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 = "session_id", .value = sid },.{ .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];const url = try wssUrl(arena, provider.url);// Esc watching (root TTY), same gate as postStream.@@ -429,7 +430,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {// socket held since the last request has proved nothing since.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| {+ 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 wrongdiff --git a/src/args.zig b/src/args.zigindex 5ddd1377..49591032 100644--- a/src/args.zig+++ b/src/args.zig@@ -65,6 +65,7 @@ pub const Flags = struct {worktree_flag: ?[]const u8 = null, // --worktree/-w: isolate this session in a git worktree (parallel agents, no file collisions)eval_target_flag: ?u8 = null, // --until: target score 0-100 for the eval loopeval_niche_flag: ?[]const u8 = null, // --niche: fleet niche this eval-driven session optimizes (tags submitted scores)+ output_schema_flag: ?[]const u8 = null, // --output-schema: JSON schema (inline or @file) the final answer must satisfy (#502)no_resume_flag: bool = false, // start without auto-loading last.session.jsonnew_session_flag: bool = false, // start a fresh autosaved sessionpositionals: std.ArrayList([]const u8) = .empty,@@ -138,6 +139,8 @@ pub fn parse(init: std.process.Init) !Flags {flags.eval_target_flag = std.fmt.parseInt(u8, uv, 10) catch std.process.fatal("--until must be a number 0-100", .{});} else if (std.mem.eql(u8, arg, "--niche")) {flags.eval_niche_flag = it.next() orelse std.process.fatal("--niche needs a name (e.g. --niche reviewer)", .{});+ } else if (std.mem.eql(u8, arg, "--output-schema")) {+ flags.output_schema_flag = it.next() orelse std.process.fatal("--output-schema needs a JSON schema or @file", .{});} else if (std.mem.eql(u8, arg, "--no-telemetry")) {flags.no_telemetry_flag = true;} else if (std.mem.eql(u8, arg, "--learning-privacy")) {@@ -246,6 +249,12 @@ pub fn parse(init: std.process.Init) !Flags {// GRAFF_LEAN sets the same global in session_settings.applyEnvKnobs).if (flags.effectiveLean()) no_local_tools.lean = true;+ // #502: GRAFF_XAI_WIRE=responses must land before the initial Keys.build+ // (startup.resolveKeys) or the xAI provider is built on the chat wire and+ // the knob silently no-ops; applyEnvKnobs re-parses the same value later.+ if (init.environ_map.get("GRAFF_XAI_WIRE")) |xw|+ @import("provider.zig").g_xai_responses = std.ascii.eqlIgnoreCase(std.mem.trim(u8, xw, " \t"), "responses");+return flags;}diff --git a/src/codex_chain.zig b/src/codex_chain.zigindex b027ff40..0958677e 100644--- a/src/codex_chain.zig+++ b/src/codex_chain.zig@@ -43,6 +43,11 @@ pub var g_force_full_resend = 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;return usable(self.codex_ws != null,self.codex_prev_id != null,diff --git a/src/http_headers.zig b/src/http_headers.zigindex a751ade1..d1018f3e 100644--- a/src/http_headers.zig+++ b/src/http_headers.zig@@ -127,7 +127,10 @@ pub fn providerHeaders(io: Io, provider: Provider, bearer: []const u8, buf: *[12const identity = kimi_catalog.identityHeaders(buf[count..]);count += identity.len;}- if (provider.kind == .responses) {+ // The ChatGPT-backend identity headers are codex-only: another Responses+ // provider (xAI, #502) authenticates with the bearer alone and must not+ // impersonate codex_cli_rs.+ if (provider.kind == .responses and std.mem.eql(u8, provider.id, "codex")) {buf[count] = .{ .name = "chatgpt-account-id", .value = provider.account };count += 1;buf[count] = .{ .name = "OpenAI-Beta", .value = "responses=experimental" };diff --git a/src/provider.zig b/src/provider.zigindex 79a0f183..0d413133 100644--- a/src/provider.zig+++ b/src/provider.zig@@ -24,6 +24,18 @@ pub var g_context_override: ?u64 = null;/// (default 80). null → 80. Unlike codex we allow lowering AND raising (1..100).pub var g_compact_pct_override: ?u8 = null;+/// #502: GRAFF_XAI_WIRE=responses (session_settings.applyEnvKnobs) serves xAI+/// over the OpenAI Responses wire at api.x.ai/v1/responses instead of chat+/// completions — the prerequisite for first-party server compaction and+/// Responses-WebSocket turns. Verified live on the SuperGrok OAuth path.+pub var g_xai_responses: bool = false;++pub const xai_responses_url = "https://api.x.ai/v1/responses";+/// xAI's explicit compaction endpoint (POST {model, input} → one opaque+/// compaction item). Unlike codex there is no in-stream compaction — api.x.ai+/// silently ignores the context_management directive (probed 2026-08-15).+pub const xai_compact_url = "https://api.x.ai/v1/responses/compact";+/// The context window for a provider+model, honoring g_context_override for an/// unknown/local model — i.e. only when contextFor returns the conservative default,/// never overriding a known window (#203).@@ -162,6 +174,14 @@ pub const Provider = struct {return p.context / 100 * pct;}+ /// The provider's explicit server-side compaction endpoint, if it has one+ /// (#502). codex compacts in-stream via context_management and returns null.+ pub fn serverCompactUrl(p: Provider) ?[]const u8 {+ if (p.kind != .responses) return null;+ if (std.mem.eql(u8, p.id, "xai")) return xai_compact_url;+ return null;+ }+/// Whether a failed compaction may safely fall back to destructive trimming./// Keep this stricter than compactAt(): at 80-95% a transient summary failure/// should leave history intact and retry later. Subtraction avoids overflow for@@ -212,11 +232,12 @@ pub const Provider = struct {};const is_codex = std.mem.eql(u8, spec.id, "codex");const is_kimi_anthropic = std.mem.eql(u8, spec.id, "kimi") and pricing.kimiProtocol(model) == .anthropic;+ const is_xai_responses = std.mem.eql(u8, spec.id, "xai") and g_xai_responses;return .{.id = spec.id,- .kind = if (is_kimi_anthropic) .anthropic else spec.kind,+ .kind = if (is_kimi_anthropic) .anthropic else if (is_xai_responses) .responses else spec.kind,.auth = if (is_kimi_anthropic) .x_api_key else spec.auth,- .url = if (is_kimi_anthropic) kimi_anthropic_url else if (is_codex) g_codex_url_override orelse spec.url else spec.url,+ .url = if (is_kimi_anthropic) kimi_anthropic_url else if (is_codex) g_codex_url_override orelse spec.url else if (is_xai_responses) xai_responses_url else spec.url,.api_key = base.api_key,.model = model,.context = contextWindowFor(spec.id, model),@@ -307,11 +328,12 @@ pub const Keys = struct {pub fn build(keys: Keys, spec: ProviderSpec, key: []const u8, model: []const u8) Provider {const is_codex = std.mem.eql(u8, spec.id, "codex");const is_kimi_anthropic = std.mem.eql(u8, spec.id, "kimi") and pricing.kimiProtocol(model) == .anthropic;+ const is_xai_responses = std.mem.eql(u8, spec.id, "xai") and g_xai_responses;return .{.id = spec.id,- .kind = if (is_kimi_anthropic) .anthropic else spec.kind,+ .kind = if (is_kimi_anthropic) .anthropic else if (is_xai_responses) .responses else spec.kind,.auth = if (is_kimi_anthropic) .x_api_key else spec.auth,- .url = if (is_kimi_anthropic) kimi_anthropic_url else if (is_codex) g_codex_url_override orelse spec.url else spec.url,+ .url = if (is_kimi_anthropic) kimi_anthropic_url else if (is_codex) g_codex_url_override orelse spec.url else if (is_xai_responses) xai_responses_url else spec.url,.api_key = key,.model = model,.context = contextWindowFor(spec.id, model),@@ -445,27 +467,6 @@ test "providerFor (#294): a catalogued model with no keyed provider fails insteatry std.testing.expectEqualStrings("anthropic", (try no_codex.providerFor("claude-does-not-exist")).id);}-test "providerFor (#377): family-prefixed spelling routes to the direct provider, not the gateway" {- // kimi's catalog row is `k3`; gateways catalog the same model as `kimi-k3`.- // The prefixed spelling must seat the keyed direct provider on its NATIVE- // name — before this fix it fell through to the codegraff gateway and a- // flat-rate subscription silently became metered/licensed usage.- const all = Keys{ .values = @splat("k") };- const p = try all.providerFor("kimi-k3");- try std.testing.expectEqualStrings("kimi", p.id);- try std.testing.expectEqualStrings("k3", p.model);- // Exact catalog names keep absolute priority over the family alias.- try std.testing.expectEqualStrings("gpt-5.6-sol", (try all.providerFor("gpt-5.6-sol")).model);- // Without the kimi credential the prefixed spelling behaves exactly as- // before: uncatalogued in the compiled table, so the gateway fallback.- var values: [provider_specs.len]?[]const u8 = @splat("k");- for (provider_specs, 0..) |spec, i| {- if (std.mem.eql(u8, spec.id, "kimi")) values[i] = null;- }- const no_kimi = Keys{ .values = values };- try std.testing.expectEqualStrings("codegraff", (try no_kimi.providerFor("kimi-k3")).id);-}-test "Keys.providerById: exact id wins, unknown id falls back to model routing" {const all = Keys{ .values = @splat("k") };const p = try all.providerById("anthropic", "claude-opus-4-8");diff --git a/src/router_catalog_tests.zig b/src/router_catalog_tests.zigindex ca73ed94..0ff320e8 100644--- a/src/router_catalog_tests.zig+++ b/src/router_catalog_tests.zig@@ -260,3 +260,52 @@ test "router discovery replaces only its provider slice" {try std.testing.expect(pricing.providerModelInTable("anthropic", "claude-opus-4-8"));try std.testing.expect(pricing.providerModelInTable("codex", "gpt-5.6-sol"));}++// ── provider.zig routing tests parked here under its 600-line ceiling ──────++test "providerFor (#377): family-prefixed spelling routes to the direct provider, not the gateway" {+ // kimi's catalog row is `k3`; gateways catalog the same model as `kimi-k3`.+ // The prefixed spelling must seat the keyed direct provider on its NATIVE+ // name — before this fix it fell through to the codegraff gateway and a+ // flat-rate subscription silently became metered/licensed usage.+ const Keys = provider.Keys;+ const all = Keys{ .values = @splat("k") };+ const p = try all.providerFor("kimi-k3");+ try std.testing.expectEqualStrings("kimi", p.id);+ try std.testing.expectEqualStrings("k3", p.model);+ // Exact catalog names keep absolute priority over the family alias.+ try std.testing.expectEqualStrings("gpt-5.6-sol", (try all.providerFor("gpt-5.6-sol")).model);+ // Without the kimi credential the prefixed spelling behaves exactly as+ // before: uncatalogued in the compiled table, so the gateway fallback.+ var values: [provider.provider_specs.len]?[]const u8 = @splat("k");+ for (provider.provider_specs, 0..) |spec, i| {+ if (std.mem.eql(u8, spec.id, "kimi")) values[i] = null;+ }+ const no_kimi = Keys{ .values = values };+ try std.testing.expectEqualStrings("codegraff", (try no_kimi.providerFor("kimi-k3")).id);+}++test "GRAFF_XAI_WIRE=responses moves xAI onto the Responses wire (#502)" {+ const Keys = provider.Keys;+ const Provider = provider.Provider;+ const all = Keys{ .values = @splat("k") };+ const chat = try all.providerById("xai", "grok-4.3");+ try std.testing.expectEqual(Provider.Kind.openai, chat.kind);+ try std.testing.expect(chat.serverCompactUrl() == null); // chat wire: no blob replay path+ provider.g_xai_responses = true;+ defer provider.g_xai_responses = false;+ const resp = try all.providerById("xai", "grok-4.3");+ try std.testing.expectEqual(Provider.Kind.responses, resp.kind);+ try std.testing.expectEqualStrings(provider.xai_responses_url, resp.url);+ try std.testing.expectEqualStrings(provider.xai_compact_url, resp.serverCompactUrl().?);+ // withModel keeps the wire choice.+ const moved = resp.withModel("grok-4.6");+ try std.testing.expectEqual(Provider.Kind.responses, moved.kind);+ try std.testing.expectEqualStrings(provider.xai_responses_url, moved.url);+ // codex keeps in-stream compaction — never the explicit endpoint.+ const codex = try all.providerById("codex", "gpt-5.6-sol");+ try std.testing.expect(codex.serverCompactUrl() == null);+ // every other provider is untouched by the knob.+ const oai = try all.providerById("openai", "gpt-5.6");+ try std.testing.expectEqual(Provider.Kind.openai, oai.kind);+}diff --git a/src/session_run.zig b/src/session_run.zigindex 752c1658..d7b77136 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -143,7 +143,15 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_mif (eval_note.len > 0) oneshot_user = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ oneshot_user, eval_note });try root.messages.append(try messages_mod.textMessage(arena, "user", oneshot_user));if (telemetry.g_telem) |t| t.countTurn();- const final_text = providers.runTurnWithFallback(root, keys, arena, null) catch |err| {+ // #502: --output-schema runs TWO-PHASE. A strict grammar on every message+ // pulls the model into answering immediately instead of touching tools+ // (graff-evals caught grok-4.6 guessing a file-inspection answer), so the+ // agentic phase runs unconstrained and one tools-off formatting turn then+ // restates the final answer under the schema — same conversation, so it+ // reads the real evidence.+ const pending_schema = root.output_schema;+ root.output_schema = null;+ var final_text = providers.runTurnWithFallback(root, keys, arena, null) catch |err| {// std.process.fatal does not unwind main's defers. Mirror their order:// join the fleet, reap jobs/pumps, then the terminal behavioral event.fleet.joinElites(io);@@ -160,6 +168,21 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_melse => |e| std.process.fatal("turn failed: {t}", .{e}),}};+ if (pending_schema) |schema_json| {+ root.output_schema = schema_json;+ root.text_only = true;+ defer {+ root.text_only = false;+ root.output_schema = null;+ }+ try root.messages.append(try messages_mod.textMessage(arena, "user", "Return ONLY the final answer as a single JSON object matching the enforced output schema. No prose."));+ if (telemetry.g_telem) |t| t.countTurn();+ final_text = providers.runTurnWithFallback(root, keys, arena, null) catch blk: {+ // Best-effort: schema-shaping must never lose a finished answer.+ std.debug.print("warning: output-schema formatting call failed — printing the unshaped answer\n", .{});+ break :blk final_text;+ };+ }try out.print("{s}\n", .{final_text});try out.flush();// Usage summary → stderr, so stdout stays exactly the answer.@@ -297,6 +320,17 @@ pub fn buildRootAgent(if (!main_mod.json_mode and flags.oneshot_prompt == null) try out.print("{s}", .{warning});}if (flags.eval_cmd_flag) |c| root.eval_cmd = try arena.dupe(u8, c);+ // #502: --output-schema (inline JSON or @file) → structured outputs.+ if (flags.output_schema_flag) |schema_arg| {+ const trimmed = std.mem.trim(u8, schema_arg, " \t");+ root.output_schema = if (std.mem.startsWith(u8, trimmed, "@"))+ std.Io.Dir.cwd().readFileAlloc(io, trimmed[1..], arena, .limited(1024 * 1024)) catch |e| blk: {+ if (!main_mod.json_mode) try out.print("warning: --output-schema {s}: {t} — ignored\n", .{ trimmed[1..], e });+ break :blk null;+ }+ else+ try arena.dupe(u8, trimmed);+ }if (flags.eval_target_flag) |t| root.eval_target = t;if (flags.eval_niche_flag) |n| root.eval_niche = try arena.dupe(u8, n);_ = recipe.record(tracer, trace.g_traj, root.provider.id, root.provider.model, @tagName(root.reasoning), root.systemPrompt(), root.toolsJson(), if (root.eval_niche.len > 0) root.eval_niche else "interactive");diff --git a/src/session_settings.zig b/src/session_settings.zigindex df6fc0a8..0a993d08 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -152,6 +152,12 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {const off = std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "off");server_compact.g_server_compact_override = !off;}+ // #502: GRAFF_XAI_WIRE=responses moves xAI onto the OpenAI Responses wire+ // (api.x.ai/v1/responses) — first-party server compaction + WS turns.+ // Anything else (or unset) keeps the chat-completions wire.+ if (environ_map.get("GRAFF_XAI_WIRE")) |v| {+ 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;// GRAFF_WS_FORCE_FAIL_ONCE proves a clean retry; the counted sibling proves// that two consecutive failures latch the SSE fallback. Test seams only.