diff --git a/packages/grok/README.md b/packages/grok/README.md index 2b9411c..ae00227 100644 --- a/packages/grok/README.md +++ b/packages/grok/README.md @@ -95,6 +95,37 @@ Plain Codex collaboration items (`agent_message`) reach Grok as user messages, with their sender, recipient and content preserved. Sealed or unrecognized content stays unchanged; the plugin does not decrypt tasks. +### Native X search (optional) + +In magpie, open the Grok provider, turn on **Native X search** under +**Plugin options**, and save. It is off by default; changes apply to the +next request without restarting or signing in again. + +When enabled, the plugin offers Grok its native `x_search` tool. Grok +decides whether to search; enabling it does not force a search on every +request. Existing function tools and X search filters are preserved, and +an existing `x_search` is not duplicated. Explicit choices such as `none`, +`required`, a named tool, or `allowed_tools` never gain another tool. + +The option applies to Responses requests, including Chat Completions, +Anthropic Messages and Gemini requests that magpie converts to Responses, +in streaming and non-streaming mode. Use magpie with the fix for +[yetone/magpie#3110](https://github.com/yetone/magpie/issues/3110) so that +those clients' tool-disable choices reach the plugin. + +For compatibility with older gateways, a request that reaches the plugin +with neither tools nor a `tool_choice` is left unchanged. This can happen +when magpie translates a client's automatic choice on an empty tool list. +To use X search through a translated API, send at least one function tool; +the plugin adds X search alongside it. An explicit tool-disable choice +always takes precedence. + +This uses the existing `grok` provider's login, models and quota reporting; +no extra plugin is needed. It applies to that provider's models when the +upstream supports X search, not to Grok models served through Cursor or +another provider. Report problems in +[this repository](https://github.com/magpie-community/plugins/issues). + ## Models Grok 4.7 until signed in. Signed in, the models are the ones the account diff --git a/packages/grok/index.mjs b/packages/grok/index.mjs index 4e5021d..7132ebf 100644 --- a/packages/grok/index.mjs +++ b/packages/grok/index.mjs @@ -323,8 +323,8 @@ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v) // (Codex desktop's codex_app automation_update) are folded to an object, // which Grok turns away otherwise: "tool parameter root must be an object // type" (magpie#1271). -function rewrite(body) { - if (typeof body !== "string" || (!body.includes('"tools"') && !body.includes('"tool_choice"') && !body.includes('"reasoning"') && !body.includes('"agent_message"'))) return body +function rewrite(body, xSearch = false) { + if (typeof body !== "string" || (!xSearch && !body.includes('"tools"') && !body.includes('"tool_choice"') && !body.includes('"reasoning"') && !body.includes('"agent_message"'))) return body let m try { m = JSON.parse(body) @@ -332,6 +332,10 @@ function rewrite(body) { return body } if (!m || typeof m !== "object" || Array.isArray(m)) return body + // Read the client's choice before dropping unsupported tools or choices. + const search = xSearch && (m.tool_choice == null || m.tool_choice === "auto") && + (m.tools == null || Array.isArray(m.tools)) && + (m.tool_choice === "auto" || Array.isArray(m.tools) && m.tools.length > 0) let dirty = false if (Array.isArray(m.tools)) { m.tools = m.tools.filter((t) => { @@ -359,6 +363,12 @@ function rewrite(body) { dirty = true } } + // No choice and no tools can mean a translated "none" on older gateways. + if (search && (m.tool_choice === "auto" || m.tools?.length) && !m.tools?.some((t) => t?.type === "x_search")) { + m.tools ??= [] + m.tools.push({ type: "x_search" }) + dirty = true + } if (Object.hasOwn(m, "tool_choice") && !(Array.isArray(m.tools) && m.tools.length)) { delete m.tool_choice dirty = true @@ -803,7 +813,7 @@ function kept(res) { // ---- the plugin --------------------------------------------------------------- -export const GrokAuthPlugin = async ({ client }) => { +export const GrokAuthPlugin = async ({ client, magpie }) => { const remember = async (auth, c) => { if (auth.access === c.key && auth.expires === c.expires) return try { @@ -824,6 +834,13 @@ export const GrokAuthPlugin = async ({ client }) => { auth: { provider: PROVIDER, + options: [ + { + key: "x_search", + label: "Native X search", + description: "Offers X search to Grok when tools are automatic. Keeps existing search filters and explicit tool choices. Grok decides whether to search.", + }, + ], // magpie renews the sign-in LEAD_MS before its end, once for the // account, before its requests, models and usage ask for it: the CLI // renews it in its home, as before a request, and what it gives is @@ -864,7 +881,8 @@ export const GrokAuthPlugin = async ({ client }) => { const home = auth?.refresh if (!home) throw new Error("Grok is not signed in; run `grok login`") const req = new Request(input, init) - let body = rewrite(bodyText(init?.body)) + const search = new URL(req.url).pathname.endsWith("/responses") && magpie?.option?.(PROVIDER, "x_search") === true + let body = rewrite(bodyText(init?.body), search) let parsed = {} if (typeof body === "string") { try { diff --git a/packages/grok/package.json b/packages/grok/package.json index b9ef812..3e5ec02 100644 --- a/packages/grok/package.json +++ b/packages/grok/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-grok-auth", - "version": "0.1.18", + "version": "0.2.0", "description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in", "type": "module", "main": "./index.mjs", diff --git a/packages/grok/x-search.test.mjs b/packages/grok/x-search.test.mjs new file mode 100644 index 0000000..29b7724 --- /dev/null +++ b/packages/grok/x-search.test.mjs @@ -0,0 +1,171 @@ +import { afterAll, afterEach, expect, test } from "bun:test" +import { mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { GrokAuthPlugin, _internal } from "./index.mjs" + +const realFetch = globalThis.fetch +afterEach(() => { globalThis.fetch = realFetch }) +const home = mkdtempSync(join(tmpdir(), "grok-x-search-")) +afterAll(() => rmSync(home, { recursive: true, force: true })) +const expires = Date.now() + 24 * 3600_000 +writeFileSync(join(home, "auth.json"), JSON.stringify({ + test: { key: "test-token", email: "test@example.invalid", expires_at: new Date(expires).toISOString() }, +})) +const auth = { type: "oauth", refresh: home, access: "test-token", expires, accountId: "test@example.invalid" } +const fn = { type: "function", name: "read_file", parameters: { type: "object", properties: {} } } +const rewrite = (body) => JSON.parse(_internal.rewrite(JSON.stringify(body), true)) + +test("native X search is an opt-in provider switch", async () => { + const hooks = await GrokAuthPlugin({}) + expect(hooks.auth.provider).toBe("grok") + const [option] = hooks.auth.options + expect(option.key).toBe("x_search") + expect(option.default).not.toBe(true) + expect(option.label).toBe("Native X search") + expect(option.description.length).toBeLessThanOrEqual(300) +}) + +for (const choice of [undefined, null, "auto"]) { + test(`automatic tools gain X search, preserving function tools (${choice})`, () => { + const body = { tools: [fn], input: "hello", ...(choice !== undefined && { tool_choice: choice }) } + const sent = rewrite(body) + expect(sent.tools).toEqual([fn, { type: "x_search" }]) + expect(sent.input).toBe(body.input) + expect(sent.tool_choice).toBe(choice) + }) +} + +for (const tools of [undefined, null, []]) { + test(`explicit auto enables search with no declared tools (${JSON.stringify(tools)})`, () => { + const sent = rewrite({ tool_choice: "auto", ...(tools !== undefined && { tools }) }) + expect(sent.tools).toEqual([{ type: "x_search" }]) + expect(sent.tool_choice).toBe("auto") + }) +} + +test("an existing X search keeps every filter and is not duplicated", () => { + const body = JSON.stringify({ tools: [fn, { + type: "x_search", allowed_x_handles: ["OpenAI"], from_date: "2026-10-01", + to_date: "2026-10-20", enable_image_understanding: true, + }], tool_choice: "auto" }) + expect(_internal.rewrite(body, true)).toBe(body) +}) + +for (const choice of ["none", "required", { type: "function", name: "read_file" }, + { type: "allowed_tools", mode: "auto", tools: [{ type: "function", name: "read_file" }] }, + { type: "x_search" }]) { + test(`an explicit tool choice never gains X search (${JSON.stringify(choice)})`, () => { + const sent = rewrite({ tools: [fn], tool_choice: choice }) + expect(sent.tools).toEqual([fn]) + // Existing Grok cleanup still removes unsupported choice types. + if (choice !== null && typeof choice === "object" && choice.type === "allowed_tools") { + expect(sent.tool_choice).toBeUndefined() + } else expect(sent.tool_choice).toEqual(choice) + }) +} + +test("none without tools never gains search and is removed before Grok", () => { + for (const tools of [undefined, [], [{ type: "custom", name: "apply_patch" }]]) { + const sent = rewrite({ tool_choice: "none", ...(tools !== undefined && { tools }) }) + expect(sent.tools ?? []).toEqual([]) + expect(sent.tool_choice).toBeUndefined() + expect(JSON.stringify(sent)).not.toContain("__magpie") + } +}) + +test("missing or null choice without usable tools stays conservative", () => { + for (const body of [ + { input: "hi" }, { tools: [] }, { tools: null }, { tool_choice: null }, + { tools: [], tool_choice: null }, { tools: [{ type: "custom", name: "apply_patch" }] }, + ]) { + expect(rewrite(body).tools ?? []).toEqual([]) + } +}) + +test("malformed bodies and non-array tools are not given search", () => { + for (const body of ["not JSON", "null", "[]", "42", '{"tools":{}}', '{"tools":"invalid","tool_choice":"auto"}']) { + expect(_internal.rewrite(body, true)).not.toContain('"x_search"') + } +}) + +test("the default rewrite never adds search", () => { + for (const body of [{ input: "hi" }, { tools: [fn] }, { tool_choice: "auto" }]) { + expect(_internal.rewrite(JSON.stringify(body))).not.toContain('"x_search"') + } +}) + +test("search injection keeps existing schema and reasoning cleanup", () => { + const sent = rewrite({ + tools: [{ type: "custom", name: "apply_patch" }, { + ...fn, parameters: { anyOf: [{ type: "object", properties: { path: { type: "string" } } }, { type: "string" }] }, + }], + tool_choice: "auto", input: [{ type: "reasoning", encrypted_content: "fixture", content: null }], + }) + expect(sent.tools.map((t) => t.type)).toEqual(["function", "x_search"]) + expect(sent.tools[0].parameters).toEqual({ type: "object", properties: { path: { type: "string" } } }) + expect(sent.input).toEqual([{ type: "reasoning", encrypted_content: "fixture" }]) +}) + +test("the live switch is read on each fetch, only for Responses", async () => { + let on = false + const seen = [], asked = [] + globalThis.fetch = async (url, init) => { + seen.push({ url, body: JSON.parse(init.body), headers: new Headers(init.headers) }) + return Response.json({ id: "test", output: [] }) + } + const hooks = await GrokAuthPlugin({ client: {}, magpie: { option(provider, key) { + asked.push([provider, key]) + return on + } } }) + const opts = await hooks.auth.loader(async () => auth) + const go = (path = "responses") => opts.fetch(`https://cli-chat-proxy.grok.com/v1/${path}`, { + method: "POST", body: JSON.stringify({ model: "grok-4.7", tools: [fn] }), + }) + await go() + on = true + await go() + await go("other") + on = false + await go() + expect(seen.map((r) => r.body.tools.some((t) => t.type === "x_search"))).toEqual([false, true, false, false]) + expect(asked).toEqual(Array(3).fill(["grok", "x_search"])) + for (const r of seen) expect(r.headers.get("Authorization")).toBe("Bearer test-token") +}) + +test("an older host without option support keeps the original behavior", async () => { + let sent + globalThis.fetch = async (_, init) => { + sent = JSON.parse(init.body) + return Response.json({ output: [] }) + } + const hooks = await GrokAuthPlugin({ client: {} }) + const opts = await hooks.auth.loader(async () => auth) + await opts.fetch("https://cli-chat-proxy.grok.com/v1/responses", { + method: "POST", body: JSON.stringify({ tool_choice: "auto" }), + }) + expect(sent.tools).toBeUndefined() +}) + +for (const stream of [false, true]) { + test(`every listed Grok model uses the same search path; response is unchanged (stream=${stream})`, async () => { + const models = ["grok-4.6", "grok-4.7", "grok-4.7@500k", "future-grok"] + const text = stream ? 'data: {"type":"response.completed"}\n\n' : '{"output":[]}' + let sent + globalThis.fetch = async (_, init) => { + sent = JSON.parse(init.body) + return new Response(text, { headers: { "content-type": stream ? "text/event-stream" : "application/json" } }) + } + const hooks = await GrokAuthPlugin({ client: {}, magpie: { option: () => true } }) + const opts = await hooks.auth.loader(async () => auth) + for (const model of models) { + const res = await opts.fetch("https://cli-chat-proxy.grok.com/v1/responses", { + method: "POST", body: JSON.stringify({ model, stream, tool_choice: "auto" }), + }) + expect(sent.tools).toEqual([{ type: "x_search" }]) + expect(sent.stream).toBe(stream) + expect(sent.model).toBe(model.split("@")[0]) + expect(await res.text()).toBe(text) + } + }) +}