diff --git a/packages/grok/README.md b/packages/grok/README.md index f6887d0..517b50f 100644 --- a/packages/grok/README.md +++ b/packages/grok/README.md @@ -55,7 +55,11 @@ API (`@ai-sdk/openai`), signed as the CLI signs them: - `x-grok-client-mode: headless` - `x-grok-client-version` and `User-Agent: grok-shell/ (; )`. The version is 1.0.41, or the installed CLI's if it is newer. -- `x-grok-model-override`: the request's model. +- `x-grok-model-override`: the request's model. A window suffix + (`grok-4.7@500k`) is the plain model (`grok-4.7`) here and in the body. +- `x-grok-context-window`: the token count a suffixed model names + (`500000` for `@500k`). The plain id sends no such header and stays on + the default window. - `x-grok-conv-id`: the request's `prompt_cache_key`. The backend turns away some of what a request may carry, so the plugin @@ -73,8 +77,17 @@ unrecognized content stays unchanged; the plugin does not decrypt tasks. ## Models Grok 4.7 until signed in. Signed in, the models are the ones the account -lists at `/v1/models` (Responses models only), each with its context -window and its reasoning efforts as variants. +lists at `/v1/models` (Responses models only), each with its reasoning +efforts as variants. + +`context_window` is the default window and keeps the plain id, so a saved +`grok-4.7` stays a 256k model. Each other size in `context_windows` is +offered beside it, named `Grok 4.7 @ 500k` with id `grok-4.7@500k` and +that many tokens as its window. A request for it sends +`x-grok-context-window: 500000`. The proxy serves up to its largest +window either way and refuses past it; the header names the window the +caller asked to compact against. Pick `grok-4.7@500k` where a client +compacts at the advertised window, such as Claude Code. ## Usage diff --git a/packages/grok/index.mjs b/packages/grok/index.mjs index 99e794f..a6fbf90 100644 --- a/packages/grok/index.mjs +++ b/packages/grok/index.mjs @@ -384,12 +384,48 @@ async function listModels(key) { for (const d of JSON.parse(text)?.data ?? []) { if (!d?.id || (d.api_backend && d.api_backend !== "responses")) continue const efforts = (d.reasoning_efforts ?? []).map((e) => e?.value).filter(Boolean).reverse() - out.push({ id: d.id, name: d.name || d.id, context: d.context_window ?? 0, efforts }) + out.push(...windowsOf(d, efforts)) } if (!out.length) throw new Error("Grok listed no models") return out } +// labelOf is a window as the picker shows it: 500000 is "500k". +const labelOf = (n) => (n % 1000 === 0 ? `${n / 1000}k` : String(n)) + +// windowsOf is one model for each context window Grok lists. context_window +// is the default and keeps the plain id (grok-4.7), so a saved agent stays +// where it was. Each other size in context_windows is offered beside it +// (grok-4.7@500k), the way the CLI's /context-window offers it. A list with +// one size, or none, stays one model. +function windowsOf(d, efforts) { + const name = d.name || d.id + const fallback = Number(d.context_window) || 0 + const listed = (Array.isArray(d.context_windows) ? d.context_windows : []) + .map(Number) + .filter((n) => Number.isInteger(n) && n > 0) + const windows = [...new Set(listed.length ? listed : [fallback].filter(Boolean))] + const base = windows.includes(fallback) ? fallback : windows[0] ?? 0 + const out = [{ id: d.id, apiId: d.id, name, context: base || fallback, window: base, efforts }] + for (const w of windows) { + if (w === base) continue + out.push({ id: `${d.id}@${labelOf(w)}`, apiId: d.id, name: `${name} @ ${labelOf(w)}`, context: w, window: w, efforts }) + } + return out +} + +// modelOf splits a requested id into the model Grok lists and the window +// the id names. grok-4.7 is grok-4.7 at its default window (no header); +// grok-4.7@500k is grok-4.7 at 500000 tokens. The header is what the CLI +// sends as x-grok-context-window. The proxy serves up to its largest +// window either way and refuses past it; the header names the window the +// caller asked to compact against. +function modelOf(id) { + const at = typeof id === "string" ? id.match(/^(.*)@(\d+)k$/) : null + if (!at) return { model: id, window: 0 } + return { model: at[1], window: Number(at[2]) * 1000 } +} + // ---- sign-in ------------------------------------------------------------------ // login runs `grok login --device-auth` in home and hands on the first link @@ -692,7 +728,7 @@ 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) - const body = rewrite(bodyText(init?.body)) + let body = rewrite(bodyText(init?.body)) let parsed = {} if (typeof body === "string") { try { @@ -703,7 +739,15 @@ export const GrokAuthPlugin = async ({ client }) => { await remember(auth, c) const headers = new Headers(req.headers) await sign(headers, c.key) - if (typeof parsed.model === "string" && parsed.model) headers.set("x-grok-model-override", parsed.model) + const asked = modelOf(parsed.model) + if (asked.model) { + headers.set("x-grok-model-override", asked.model) + if (asked.window && typeof body === "string") { + parsed.model = asked.model + body = JSON.stringify(parsed) + } + } + if (asked.window) headers.set("x-grok-context-window", String(asked.window)) if (typeof parsed.prompt_cache_key === "string" && parsed.prompt_cache_key) headers.set("x-grok-conv-id", parsed.prompt_cache_key) headers.delete("content-length") // sent once, as the built-in sent it: Grok's answer goes on as @@ -757,12 +801,15 @@ export const GrokAuthPlugin = async ({ client }) => { const base = have["grok-4.7"] ?? Object.values(have)[0] ?? {} const out = {} for (const m of list) { - const was = have[m.id] ?? base + const was = have[m.id] ?? have[m.apiId] ?? base out[m.id] = { ...was, id: m.id, providerID: provider.id, name: m.name, + // the id as offered, window and all: magpie and the AI SDK send + // api.id as the body's model, and fetch reads the window from it + // (modelOf) before Grok sees the plain model api: { ...(was.api ?? {}), id: m.id, url: BASE, npm: "@ai-sdk/openai" }, limit: { ...(was.limit ?? {}), context: m.context || was.limit?.context || 0, output: was.limit?.output ?? 0 }, capabilities: { @@ -782,4 +829,4 @@ export const GrokAuthPlugin = async ({ client }) => { } // for tests -export const _internal = { rewrite, objectRoot, bodyText, limited, HOLD_MS } +export const _internal = { rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf } diff --git a/packages/grok/models.test.mjs b/packages/grok/models.test.mjs index f0892c0..1c1a426 100644 --- a/packages/grok/models.test.mjs +++ b/packages/grok/models.test.mjs @@ -2,7 +2,7 @@ // magpie keeps the configured model when the models hook fails, and a // model with no variants lost the levels the built-in had (low…xhigh). import { expect, test } from "bun:test" -import { GrokAuthPlugin } from "./index.mjs" +import { GrokAuthPlugin, _internal } from "./index.mjs" test("the configured grok-4.7 carries the built-in's levels", async () => { const hooks = await GrokAuthPlugin({ client: { auth: { set: async () => {} } } }) @@ -14,6 +14,41 @@ test("the configured grok-4.7 carries the built-in's levels", async () => { expect(m.variants.xhigh).toEqual({ reasoningEffort: "xhigh" }) }) +// Grok lists two windows. context_window is the default and keeps the +// plain id; each other size in context_windows is offered beside it, and +// a request for that id asks Grok for that window. +test("a model with two windows is offered at each, the plain id at the default", () => { + const [base, wide] = _internal.windowsOf({ + id: "grok-4.7", + name: "Grok 4.7", + context_window: 256000, + context_windows: [256000, 500000], + }, ["low", "high"]) + expect(base).toMatchObject({ id: "grok-4.7", apiId: "grok-4.7", name: "Grok 4.7", context: 256000, window: 256000 }) + expect(wide).toMatchObject({ id: "grok-4.7@500k", apiId: "grok-4.7", name: "Grok 4.7 @ 500k", context: 500000, window: 500000 }) + expect(base.efforts).toEqual(["low", "high"]) + expect(wide.efforts).toEqual(["low", "high"]) +}) + +test("one window, or none, stays one model", () => { + expect(_internal.windowsOf({ id: "grok-4.5", context_window: 256000, context_windows: [256000] }, []).map((m) => m.id)).toEqual(["grok-4.5"]) + expect(_internal.windowsOf({ id: "grok-4.5", name: "Grok 4.5", context_window: 256000 }, [])).toEqual([ + { id: "grok-4.5", apiId: "grok-4.5", name: "Grok 4.5", context: 256000, window: 256000, efforts: [] }, + ]) + expect(_internal.windowsOf({ id: "grok-4.5", context_windows: [500000, 256000, 500000] }, []).map((m) => [m.id, m.context])).toEqual([ + ["grok-4.5", 500000], + ["grok-4.5@256k", 256000], + ]) +}) + +test("an offered window asks Grok for that model and that many tokens", () => { + expect(_internal.modelOf("grok-4.7")).toEqual({ model: "grok-4.7", window: 0 }) + expect(_internal.modelOf("grok-4.7@500k")).toEqual({ model: "grok-4.7", window: 500000 }) + expect(_internal.modelOf("grok-4.7@256k")).toEqual({ model: "grok-4.7", window: 256000 }) + expect(_internal.modelOf("grok-4.7-build-fast@500k")).toEqual({ model: "grok-4.7-build-fast", window: 500000 }) + expect(_internal.modelOf(undefined)).toEqual({ model: undefined, window: 0 }) +}) + // A token Grok refuses before its time says the sign-in is gone, as one // past its time does, so magpie's move takes the account along untried; // "Grok models: 401 …" stopped every Grok account's move. @@ -35,3 +70,42 @@ test("a refused token says the sign-in has expired", async () => { ;[process.env.PATH, process.env.HOME, globalThis.fetch] = [path, h, fetch0] } }) + +// magpie (and OpenCode's AI SDK) put a model's api.id in the request body, +// not its key, so the window has to survive there for the plugin's fetch +// to see it: grok-4.7@500k reaches Grok as grok-4.7 with +// x-grok-context-window: 500000, and plain grok-4.7 with no such header. +test("a window the models hook offers reaches Grok as that window", async () => { + const { mkdtempSync, writeFileSync } = await import("node:fs") + const { tmpdir } = await import("node:os") + const { join } = await import("node:path") + const home = mkdtempSync(join(tmpdir(), "grok-window-")) + writeFileSync(join(home, "auth.json"), JSON.stringify({ "https://auth.x.ai": { key: "tok", expires_at: "2099-01-01T00:00:00Z", email: "a@x.ai" } })) + const [path, fetch0] = [process.env.PATH, globalThis.fetch] + process.env.PATH = "" + const sent = [] + globalThis.fetch = async (url, init) => { + if (String(url).endsWith("/models")) { + return Response.json({ data: [{ id: "grok-4.7", name: "Grok 4.7", api_backend: "responses", context_window: 256000, context_windows: [256000, 500000] }] }) + } + sent.push({ window: init.headers.get("x-grok-context-window"), override: init.headers.get("x-grok-model-override"), model: JSON.parse(init.body).model }) + return new Response("{}") + } + try { + const auth = { type: "oauth", refresh: home, access: "tok", expires: Date.parse("2099-01-01T00:00:00Z"), accountId: "a@x.ai" } + const hooks = await GrokAuthPlugin({ client: { auth: { set: async () => {} } } }) + const models = await hooks.provider.models({ id: "grok", models: {} }, { auth }) + expect(Object.keys(models)).toEqual(["grok-4.7", "grok-4.7@500k"]) + expect(models["grok-4.7@500k"].limit.context).toBe(500000) + const opts = await hooks.auth.loader(async () => auth) + for (const id of ["grok-4.7", "grok-4.7@500k"]) { + await opts.fetch(`${opts.baseURL}/responses`, { method: "POST", body: JSON.stringify({ model: models[id].api.id, input: "hi" }) }) + } + expect(sent).toEqual([ + { window: null, override: "grok-4.7", model: "grok-4.7" }, + { window: "500000", override: "grok-4.7", model: "grok-4.7" }, + ]) + } finally { + ;[process.env.PATH, globalThis.fetch] = [path, fetch0] + } +}) diff --git a/packages/grok/package.json b/packages/grok/package.json index b72569e..ed18aeb 100644 --- a/packages/grok/package.json +++ b/packages/grok/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-grok-auth", - "version": "0.1.11", + "version": "0.1.12", "description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in", "type": "module", "main": "./index.mjs",