graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(xai): splice hosted x_search onto Responses tools turns
Cursor Agent7f476363e305
diff --git a/docs/adr/0002-xai-defaults-to-the-responses-wire.md b/docs/adr/0002-xai-defaults-to-the-responses-wire.mdindex f1ec4161..705f601a 100644--- a/docs/adr/0002-xai-defaults-to-the-responses-wire.md+++ b/docs/adr/0002-xai-defaults-to-the-responses-wire.md@@ -38,6 +38,8 @@ back onto chat completions.full-resend over the held socket.- Revisit if xAI's wire diverges from OpenAI Responses semantics or thecompact endpoint's blob replay pricing changes the cost picture.+- Hosted `x_search` rides this wire by default (ADR+ [0031](0031-xai-hosted-x-search.md)); chat completions cannot host it.Evidence: #502, #503, #505, the recall A/B kit (session scratchpadrecall-ab/), ADR [0001](0001-structured-outputs-are-a-formatting-step.md)diff --git a/docs/adr/0031-xai-hosted-x-search.md b/docs/adr/0031-xai-hosted-x-search.mdnew file mode 100644index 00000000..16674f35--- /dev/null+++ b/docs/adr/0031-xai-hosted-x-search.md@@ -0,0 +1,46 @@+# 0031. xAI Responses hosts `x_search`; it is not a catalog tool++Status: accepted 2026-08-25++## Context++xAI's Responses API accepts a server-side tool `{"type":"x_search"}`+(keyword / semantic / user / thread search on X). A live SuperGrok+probe on grok-4.6 (2026-08-25) returned HTTP 200 with+`num_server_side_tools_used: 1` and an output item+`{"type":"custom_tool_call","name":"x_keyword_search","status":"completed"}`+plus `url_citation` annotations on the final message.++Graff's catalog is function tools only. Adding `x_search` as an+always-on root spec would grow the 64-cell kernel, invite local+dispatch of a name the host already executed, and put an essay on the+prefix (ADR 0011 / 0013). Chat completions (`GRAFF_XAI_WIRE=chat`)+have no hosted-tool slot.++## Decision++On provider `xai` + Responses, when the request already carries a+`tools` array, splice `{"type":"x_search"}` if it is not already+present. Tools-off turns stay tools-off. Codex, chat-completions, and+non-xAI Responses never receive the splice.++Do not add `x_search` (or `x_keyword_search`) to `effectiveRootSpecs`.+Do not put search docs on the always-on prefix. Treat+`x_search_call` / `custom_tool_call` names `x_search`,+`x_keyword_search`, `x_semantic_search`, `x_user_search`,+`x_thread_fetch` as already done — append the item to history, never+`runTools`.++`GRAFF_XAI_X_SEARCH=0|off|false|no` disables the splice. Default is on+because the registered grok-4.6 Responses path already executes it.++## Consequences++- A coding turn can ask grok-4.6 about X without a graff-executed+ webfetch. The model still has bash / edit / `read_file`.+- Prompt-cache bytes grow by one hosted object on every tools turn for+ xAI Responses. Revisit if that noise shows up on a coding eval.+- Citation placeholder text from the live probe was messy; v1 leaves+ annotations on the message rather than pretty-printing them.+- Sibling ADR 0030 (late RLM showcase) is on another branch; this+ number stays 0031 so the two records do not collide on merge.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 94d57321..51560a12 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -40,6 +40,7 @@ record only when you need the evidence or the edge cases.| [0027](0027-kimi-identity-is-graff.md) | Kimi Coding User-Agent is `graff/<version>`, not a spoofed `kimi-code-cli` token. X-Msh device fields follow kimi-code's shapes. || [0028](0028-codex-session-id-is-the-cache-key.md) | Codex HTTP/WS `session_id` is the `prompt_cache_key` (openai/codex ModelClient default), not a per-process random UUID. || [0029](0029-mcp-inside-rlm-and-return-shapes.md) | Loaded MCP tools are rlm host functions; persist return shapes on the load result, never the prefix; fat MCP results auto-slim; default `-p` connects `.mcp.json` (folded, not skipped). |+| [0031](0031-xai-hosted-x-search.md) | xAI Responses splices hosted `x_search` onto tools turns. It is not a catalog function; `GRAFF_XAI_X_SEARCH=0` opts out. |## When to write onediff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zigindex 43f6ee3c..b76b962e 100644--- a/src/agent_request_body_responses.zig+++ b/src/agent_request_body_responses.zig@@ -10,6 +10,7 @@ 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");+const xai_hosted = @import("xai_hosted.zig");pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_tool: bool) !void {// Responses API (codex / ChatGPT, xAI, and native Codegraff aliases).@@ -57,8 +58,12 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_toofor (self.messages.items[from..]) |m| try s.write(m);try s.endArray();if (tools) |t| {+ const payload = if (xai_hosted.active(self.provider.id, self.provider.kind))+ xai_hosted.splice(self.scratchAlloc(), t) catch t+ else+ t;try s.objectField("tools");- try serde.writeOpenAITools(s, self.scratchAlloc(), t); // #261 follow-up+ try serde.writeOpenAITools(s, self.scratchAlloc(), payload); // #261 follow-uptry s.objectField("tool_choice");try s.write(if (force_tool) "required" else "auto");try s.objectField("parallel_tool_calls");@@ -333,6 +338,37 @@ test "xai Responses body is bearer-clean: no codex-isms, xAI-legal fields only (try std.testing.expect(std.mem.indexOf(u8, body, "previous_response_id") == null);}+test "xAI Responses splices hosted x_search onto a tools turn; Codex and chat do not" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const tools = "[{\"type\":\"function\",\"function\":{\"name\":\"bash\",\"description\":\"\",\"parameters\":{\"type\":\"object\"}}}]";+ const saved = xai_hosted.enabled;+ defer xai_hosted.enabled = saved;+ xai_hosted.enabled = true;++ var xai = try testAgentFor(a, "xai", .responses, "grok-4.6");+ const body = try xai.buildBody(tools, false, true, true);+ defer std.testing.allocator.free(body);+ try std.testing.expect(std.mem.indexOf(u8, body, "\"type\":\"x_search\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, body, "\"name\":\"bash\"") != null);++ var codex = try testAgentFor(a, "codex", .responses, "gpt-5.6-sol");+ const cb = try codex.buildBody(tools, false, true, true);+ defer std.testing.allocator.free(cb);+ try std.testing.expect(std.mem.indexOf(u8, cb, "x_search") == null);++ var chat = try testAgentFor(a, "xai", .openai, "grok-4.6");+ const chat_body = try chat.buildBody(tools, false, true, true);+ defer std.testing.allocator.free(chat_body);+ try std.testing.expect(std.mem.indexOf(u8, chat_body, "x_search") == null);++ xai_hosted.enabled = false;+ const off = try xai.buildBody(tools, false, true, true);+ defer std.testing.allocator.free(off);+ try std.testing.expect(std.mem.indexOf(u8, off, "x_search") == 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();diff --git a/src/agent_steps.zig b/src/agent_steps.zigindex 0349f04d..540baaa9 100644--- a/src/agent_steps.zig+++ b/src/agent_steps.zig@@ -99,6 +99,7 @@ pub fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {};} else if (std.mem.eql(u8, itype, "function_call")) {const name = if (item.object.get("name")) |n| (if (n == .string) n.string else continue) else continue;+ if (@import("xai_hosted.zig").isServerSideCall(itype, name)) continue;const call_id = if (item.object.get("call_id")) |c| (if (c == .string) c.string else continue) else continue;const args = if (item.object.get("arguments")) |a| (if (a == .string) a.string else "") else "";const input: Value = if (args.len == 0)diff --git a/src/exec.zig b/src/exec.zigindex 7c24f841..6c67f603 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -462,4 +462,5 @@ test { // main.zig is at the 600-line cap; exec.zig is these modules' importer,_ = @import("rlm_tests.zig");_ = @import("mcp_shapes.zig");_ = @import("spec_ptc.zig");+ _ = @import("xai_hosted.zig");}diff --git a/src/session_settings.zig b/src/session_settings.zigindex 3fa2b9e0..5c996042 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -28,6 +28,7 @@ const no_local_tools = @import("no_local_tools.zig"); // #330: GRAFF_NO_LOCAL_TOconst tool_handle = @import("tool_handle.zig"); // #440: GRAFF_TOOL_HANDLE_BYTESconst server_compact = @import("agent_server_compact.zig"); // GRAFF_SERVER_COMPACT + #compact-ab assignmentconst provider_mod = @import("provider.zig");+const xai_hosted = @import("xai_hosted.zig"); // GRAFF_XAI_X_SEARCHconst skills = @import("skills.zig");const anim = @import("anim.zig");@@ -207,6 +208,10 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {if (environ_map.get("GRAFF_XAI_WIRE")) |v| {provider_mod.g_xai_responses = std.ascii.eqlIgnoreCase(std.mem.trim(u8, v, " \t"), "responses");}+ if (environ_map.get("GRAFF_XAI_X_SEARCH")) |v| {+ const off = std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "off") or std.ascii.eqlIgnoreCase(v, "no");+ xai_hosted.enabled = !off;+ }if (environ_map.get("GRAFF_XAI_URL")) |v| {if (v.len > 0) provider_mod.g_xai_url_override = v;}diff --git a/src/session_settings_tests.zig b/src/session_settings_tests.zigindex 73087cdc..b550504a 100644--- a/src/session_settings_tests.zig+++ b/src/session_settings_tests.zig@@ -57,6 +57,7 @@ const knobs = [_]Knob{.{ .name = "GRAFF_STABLE_CATALOG", .value = "1" },.{ .name = "GRAFF_NO_STABLE_CATALOG", .value = "1" },.{ .name = "GRAFF_VERCEL_URL", .value = "https://ai-gateway.vercel.sh/v1/chat/completions" },+ .{ .name = "GRAFF_XAI_X_SEARCH", .value = "0" },};/// A stand-in for the process environment that records which names were asked@@ -103,6 +104,7 @@ const Saved = struct {ws_fail_count: u8,plugins_off: bool,stable_catalog: bool,+ x_search: bool,fn capture() Saved {return .{@@ -128,6 +130,7 @@ const Saved = struct {.ws_fail_count = ws.g_force_connect_failure_count,.plugins_off = plugins.disabled,.stable_catalog = mcp_schema_gate.g_stable_catalog,+ .x_search = @import("xai_hosted.zig").enabled,};}@@ -155,6 +158,7 @@ const Saved = struct {ws.g_force_connect_failure_count = s.ws_fail_count;plugins.disabled = s.plugins_off;mcp_schema_gate.g_stable_catalog = s.stable_catalog;+ @import("xai_hosted.zig").enabled = s.x_search;}};@@ -199,6 +203,7 @@ test "applyEnvKnobs actually applies the values it reads" {tool_handle.threshold_bytes = tool_handle.default_threshold_bytes;plugins.disabled = false;mcp_schema_gate.g_stable_catalog = false;+ @import("xai_hosted.zig").enabled = true;var asked: [knobs.len]bool = @splat(false);try session_settings.applyEnvKnobs(arena_state.allocator(), RecordingEnv{ .asked = &asked });@@ -220,6 +225,7 @@ test "applyEnvKnobs actually applies the values it reads" {try std.testing.expectEqual(@as(u8, 3), ws.g_force_connect_failure_count);try std.testing.expect(plugins.disabled);try std.testing.expect(mcp_schema_gate.g_stable_catalog); // GRAFF_STABLE_CATALOG=1 wins over GRAFF_NO_STABLE_CATALOG=1+ try std.testing.expect(!@import("xai_hosted.zig").enabled); // GRAFF_XAI_X_SEARCH=0}const PairEnv = struct {@@ -282,3 +288,14 @@ test "GRAFF_STABLE_CATALOG=0 / GRAFF_NO_STABLE_CATALOG turn default-on catalog otry session_settings.applyEnvKnobs(arena_state.allocator(), PairEnv{ .pairs = &.{.{ .name = "GRAFF_NO_STABLE_CATALOG", .value = "1" }} });try std.testing.expect(!mcp_schema_gate.g_stable_catalog);}++test "GRAFF_XAI_X_SEARCH=0 turns hosted x_search off" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const saved = Saved.capture();+ defer saved.restore();+ const hosted = @import("xai_hosted.zig");+ hosted.enabled = true;+ try session_settings.applyEnvKnobs(arena_state.allocator(), PairEnv{ .pairs = &.{.{ .name = "GRAFF_XAI_X_SEARCH", .value = "0" }} });+ try std.testing.expect(!hosted.enabled);+}diff --git a/src/xai_hosted.zig b/src/xai_hosted.zignew file mode 100644index 00000000..6cd3d046--- /dev/null+++ b/src/xai_hosted.zig@@ -0,0 +1,104 @@+//! Hosted xAI tools on the Responses wire (`{"type":"x_search"}`).+//!+//! Not a graff catalog function and not on the always-on prefix (ADR 0011 /+//! 0013). xAI runs the search server-side; graff must never local-exec the+//! resulting `custom_tool_call` / `x_search_call`. Chat-completions and+//! non-xAI Responses providers never see this splice.+//! `GRAFF_XAI_X_SEARCH=0|off|false|no` turns the default off.++const std = @import("std");+const Allocator = std.mem.Allocator;+const Value = std.json.Value;+const Io = std.Io;++const Provider = @import("provider.zig").Provider;++/// Test / env seam. `applyEnvKnobs` sets this from GRAFF_XAI_X_SEARCH.+pub var enabled: bool = true;++pub fn active(provider_id: []const u8, kind: Provider.Kind) bool {+ return enabled and kind == .responses and std.mem.eql(u8, provider_id, "xai");+}++/// Append `{"type":"x_search"}` when the tools array does not already carry it.+/// Invalid JSON is returned unchanged so the existing writer path still fires.+pub fn splice(arena: Allocator, tools_json: []const u8) ![]const u8 {+ var value = std.json.parseFromSliceLeaky(Value, arena, tools_json, .{ .allocate = .alloc_always }) catch return tools_json;+ if (value != .array) return tools_json;+ for (value.array.items) |tool| {+ if (hostedType(tool)) return tools_json;+ }+ var obj: std.json.ObjectMap = .empty;+ try obj.put(arena, "type", .{ .string = "x_search" });+ try value.array.append(.{ .object = obj });+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(value);+ return aw.toOwnedSlice();+}++fn hostedType(tool: Value) bool {+ if (tool != .object) return false;+ const t = if (tool.object.get("type")) |v| (if (v == .string) v.string else "") else "";+ return std.mem.eql(u8, t, "x_search");+}++/// Server-executed search items: keep them in history, never dispatch locally.+pub fn isServerSideCall(itype: []const u8, name: []const u8) bool {+ if (std.mem.eql(u8, itype, "x_search_call") or std.mem.eql(u8, itype, "web_search_call"))+ return true;+ if (!std.mem.eql(u8, itype, "custom_tool_call") and !std.mem.eql(u8, itype, "function_call"))+ return false;+ return std.mem.eql(u8, name, "x_search") or+ std.mem.eql(u8, name, "x_keyword_search") or+ std.mem.eql(u8, name, "x_semantic_search") or+ std.mem.eql(u8, name, "x_user_search") or+ std.mem.eql(u8, name, "x_thread_fetch");+}++test "active only for xAI Responses while enabled" {+ const saved = enabled;+ defer enabled = saved;+ enabled = true;+ try std.testing.expect(active("xai", .responses));+ try std.testing.expect(!active("xai", .openai));+ try std.testing.expect(!active("codex", .responses));+ try std.testing.expect(!active("openai", .responses));+ enabled = false;+ try std.testing.expect(!active("xai", .responses));+}++test "splice appends hosted x_search once" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const tools = "[{\"type\":\"function\",\"name\":\"bash\",\"parameters\":{\"type\":\"object\"}}]";+ const out = try splice(arena, tools);+ try std.testing.expect(std.mem.indexOf(u8, out, "\"type\":\"x_search\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\"name\":\"bash\"") != null);+ const again = try splice(arena, out);+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, again, "\"type\":\"x_search\""));+}++test "splice of an empty tools array is just x_search" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const out = try splice(arena_state.allocator(), "[]");+ try std.testing.expectEqualStrings("[{\"type\":\"x_search\"}]", out);+}++test "splice leaves invalid JSON alone" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ try std.testing.expectEqualStrings("not-json", try splice(arena_state.allocator(), "not-json"));+}++test "isServerSideCall matches the live xAI shapes and ignores bash" {+ try std.testing.expect(isServerSideCall("custom_tool_call", "x_keyword_search"));+ try std.testing.expect(isServerSideCall("x_search_call", ""));+ try std.testing.expect(isServerSideCall("function_call", "x_search"));+ try std.testing.expect(!isServerSideCall("function_call", "bash"));+ try std.testing.expect(!isServerSideCall("function_call", "webfetch"));+ try std.testing.expect(!isServerSideCall("message", "x_search"));+}