grok 0.2.0: opt-in native X search (#263)
An option on the grok provider, "Native X search" (auth.options key
x_search, off by default), read through magpie.option on each fetch.
When on, a Responses request whose tool_choice is auto, or absent with
tools declared, is offered Grok's native {"type":"x_search"}. none,
required, a named tool, allowed_tools and an x_search choice add nothing;
an x_search already declared keeps its filters and isn't duplicated; a
request with neither tools nor a tool_choice is left alone.
Reviewed at 99e602006 (vectorisvector). Run at that head:
- HOME and TMPDIR in a scratch dir, bun test: 2040 pass, 0 fail;
bun scripts/check.mjs: ok; PR CI run 39532960081 green (attempt 1 was
only awaiting approval)
- broken by hand, each red: on by default 4 fail, option ignored 2, every
path 1, tool_choice ignored 5, duplicate x_search 1, inject after
tools filtered 1, both no-tools guards removed 1, non-array tools 1,
wrong provider id 1, no injection 10
- magpie gateway at ba319a758 with this plugin loaded (BASE pointed at a
fake upstream), option off/on/off: Chat, Anthropic and Gemini (whole and
streamed) with a function get x_search; their tools-off "none" and
Chat/Anthropic required, named and no-tools requests don't; Responses
auto (whole and streamed) gets it, none doesn't, an existing x_search
is kept once; no upstream body names magpie; an x_search_call item in
the reply doesn't reach Chat/Anthropic/Gemini clients
- one gap on magpie's side: an allowed_tools choice is dropped by the
gateway before the plugin can read it, so it gets x_search; filed as
yetone/magpie#3153
Not tried: a real Grok account.
This commit is contained in:
@@ -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
|
||||
|
||||
+22
-4
@@ -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 {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user