diff --git a/packages/grok/README.md b/packages/grok/README.md index 921cf37..faeb681 100644 --- a/packages/grok/README.md +++ b/packages/grok/README.md @@ -17,6 +17,16 @@ run, such as a container without curl, put the binary in a folder of your own and set `GROK_BIN_DIR` to it. magpie installs Grok Build itself, as the installer does, before a sign-in that needs it. +## Images and speech + +Images in a request (Anthropic image blocks, OpenAI `image_url`, Responses +`input_image`) go to Grok as sent, and its models take them. Speech to text +is the one Grok Build's voice dictation uses: magpie's +`/v1/audio/transcriptions` (model `grok/grok-4.7`, any of the account's +models) is sent on to xAI's `api.x.ai/v1/stt` with the account's sign-in. +`language` is passed on; `json`, `text` and `verbose_json` are answered, and +translations are refused. + ## Sign in - **Sign in with Grok Build (device code)** runs `grok login --device-auth` diff --git a/packages/grok/index.mjs b/packages/grok/index.mjs index 7d1c2bd..2220d6a 100644 --- a/packages/grok/index.mjs +++ b/packages/grok/index.mjs @@ -956,6 +956,96 @@ function kept(res) { return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) } +// ---- speech to text ----------------------------------------------------------- + +// Grok Build's voice dictation sends audio to xAI's own speech-to-text, +// POST api.x.ai/v1/stt, signed as every other request of the CLI is. magpie's +// /v1/audio/transcriptions arrives here as OpenAI's multipart form; xAI's +// takes `file` last, an optional `language`, and no `model` of OpenAI's +// (the one it has is the default, and any other id is a 404). +const STT = "https://api.x.ai/v1/stt" +const STT_FORMATS = ["json", "text", "verbose_json"] + +async function sttRequest(body, ctype) { + let form + try { + form = await new Response(body, { headers: { "content-type": ctype } }).formData() + } catch { + return { error: "send the audio as multipart/form-data, as OpenAI's /v1/audio/transcriptions takes it: a file and a model" } + } + const file = form.get("file") + if (!(file instanceof Blob)) return { error: "the form has no audio file" } + const format = String(form.get("response_format") || "json") + if (!STT_FORMATS.includes(format)) return { error: `Grok's speech to text answers json, text or verbose_json, not ${format}` } + const out = new FormData() + const language = form.get("language") + if (typeof language === "string" && language) out.set("language", language) + out.set("file", file, file.name || "audio") + return { form: out, format } +} + +// sttAnswer is xAI's answer in the shape OpenAI's takes for the format +// asked: its words are {text, start, end}, OpenAI's {word, start, end}. +async function sttAnswer(res, format) { + let a + try { + a = await res.json() + } catch { + return new Response("Grok's speech to text answered something that isn't JSON", { status: 502 }) + } + const text = typeof a?.text === "string" ? a.text : "" + const headers = new Headers({ "X-Magpie-Sign-In": "kept" }) + if (format === "text") { + headers.set("content-type", "text/plain; charset=utf-8") + return new Response(text, { status: 200, headers }) + } + headers.set("content-type", "application/json") + if (format === "json") return new Response(JSON.stringify({ text }), { status: 200, headers }) + const words = Array.isArray(a.words) ? a.words.map((w) => ({ word: w.text, start: w.start, end: w.end })) : [] + return new Response(JSON.stringify({ task: "transcribe", language: a.language, duration: a.duration, text, words }), { status: 200, headers }) +} + +const failure = (status, message, extra = {}) => + new Response(JSON.stringify({ error: { message, type: status === 401 ? "authentication_error" : "invalid_request_error" } }), { + status, + headers: { "content-type": "application/json", ...extra }, + }) + +async function transcribe(auth, req, init) { + const home = auth?.refresh + if (req.url.includes("/audio/translations")) return failure(400, "Grok's speech to text transcribes; it doesn't translate") + const raw = init?.body + const body = typeof raw === "string" ? Buffer.from(raw) : raw + const ask = body ? await sttRequest(body, req.headers.get("content-type") ?? "") : { error: "the request has no body" } + if (ask.error) return failure(400, ask.error) + let c = await token(home) + const send = async (key) => { + const headers = new Headers() + await sign(headers, key) + return fetch(STT, { method: "POST", headers, body: ask.form, signal: init?.signal }) + } + let res = await send(c.key) + if (res.status === 401) { + const said = (await res.text().catch(() => "")).slice(0, 300) + try { + c = await token(home, c.key, said) + } catch (e) { + note(home, res) + return failure(e?.transient ? 503 : 401, `${e.message}${said ? `. Grok said: ${said}` : ""}`, { "X-Magpie-Sign-In": "kept", ...(e?.transient ? { "retry-after": String(RETRY_SECS) } : {}) }) + } + res = await send(c.key) + } + note(home, res) + if (res.ok) return sttAnswer(res, ask.format) + const said = (await res.text().catch(() => "")).slice(0, 300) + let msg = said + try { + const j = JSON.parse(said) + msg = typeof j?.error === "string" ? j.error : (j?.error?.message ?? said) + } catch {} + return failure(res.status, `Grok's speech to text: ${msg || res.status}`, { "X-Magpie-Sign-In": "kept" }) +} + // ---- the plugin --------------------------------------------------------------- // A Responses stream that dies before its first byte is asked again, up @@ -1142,6 +1232,7 @@ export const GrokAuthPlugin = async ({ client, magpie }) => { const home = auth?.refresh if (!home) throw new Error("Grok is not signed in; run `grok login`") const req = new Request(input, init) + if (new URL(req.url).pathname.match(/\/audio\/(transcriptions|translations)$/)) return transcribe(auth, req, init) const search = new URL(req.url).pathname.endsWith("/responses") && magpie?.option?.(PROVIDER, "x_search") === true let body = rewrite(bodyText(init?.body), search) let parsed = {} @@ -1336,4 +1427,4 @@ export const GrokAuthPlugin = async ({ client, magpie }) => { } // for tests -export const _internal = { rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf, waits } +export const _internal = { sttRequest, sttAnswer, rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf, waits } diff --git a/packages/grok/package.json b/packages/grok/package.json index 5b03576..9a6dd50 100644 --- a/packages/grok/package.json +++ b/packages/grok/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-grok-auth", - "version": "0.2.6", + "version": "0.2.7", "description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in", "type": "module", "main": "./opencode.mjs", diff --git a/packages/grok/stt.test.mjs b/packages/grok/stt.test.mjs new file mode 100644 index 0000000..871d16c --- /dev/null +++ b/packages/grok/stt.test.mjs @@ -0,0 +1,92 @@ +// Speech to text: magpie's /v1/audio/transcriptions (OpenAI's multipart +// form) goes to xAI's own /v1/stt, which Grok Build's voice dictation uses, +// signed as the CLI signs; images in a Responses request go on untouched. +import { noRealGrok } from "./nocli.mjs" +import { afterAll, afterEach, beforeEach, 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" + +noRealGrok() + +const real = globalThis.fetch +const root = mkdtempSync(join(tmpdir(), "grok-stt-")) +afterAll(() => rmSync(root, { recursive: true, force: true })) +afterEach(() => { + globalThis.fetch = real +}) + +let home +beforeEach(() => { + home = mkdtempSync(join(root, "home-")) + const expires = Date.now() + 3600_000 + writeFileSync(join(home, "auth.json"), JSON.stringify({ a: { key: "tok-1", email: "g@x.ai", expires_at: new Date(expires).toISOString() } })) +}) + +// audio bytes that aren't UTF-8, as a WAV's are +const audio = new Uint8Array([0x52, 0x49, 0x46, 0x46, 0xff, 0xfe, 0x00, 0x80, 0xc3, 0x28]) + +// the multipart body a client sends, its boundary fixed +function form(fields) { + const b = "----magpietest" + const parts = Object.entries(fields).map(([k, v]) => Buffer.from(`--${b}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`)) + parts.push(Buffer.from(`--${b}\r\nContent-Disposition: form-data; name="file"; filename="a.wav"\r\nContent-Type: audio/wav\r\n\r\n`), Buffer.from(audio), Buffer.from(`\r\n--${b}--\r\n`)) + return { body: Buffer.concat(parts), type: `multipart/form-data; boundary=${b}` } +} + +async function ask(fields, path = "/audio/transcriptions", answer) { + const auth = { type: "oauth", refresh: home, access: "tok-1", expires: Date.now() + 3600_000, accountId: "g@x.ai" } + const hooks = await GrokAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => auth) + const sent = [] + globalThis.fetch = async (url, init) => { + const got = init.body instanceof FormData ? init.body : null + sent.push({ url: String(url), auth: init.headers.get("Authorization"), form: got }) + return answer ? answer() : new Response(JSON.stringify({ text: "Hello world.", language: "en", duration: 2.01, words: [{ text: "Hello", start: 0.04, end: 0.24 }] }), { headers: { "content-type": "application/json" } }) + } + const f = form(fields) + const res = await opts.fetch(`https://cli-chat-proxy.grok.com/v1${path}`, { method: "POST", headers: { "content-type": f.type }, body: f.body }) + return { res, sent } +} + +test("a transcription goes to xAI's /v1/stt with the audio byte for byte and no OpenAI model", async () => { + const { res, sent } = await ask({ model: "grok-4.7", language: "en", prompt: "x" }) + expect(sent).toHaveLength(1) + expect(sent[0].url).toBe("https://api.x.ai/v1/stt") + expect(sent[0].auth).toBe("Bearer tok-1") + expect(sent[0].form.has("model")).toBe(false) + expect(sent[0].form.get("language")).toBe("en") + expect(new Uint8Array(await sent[0].form.get("file").arrayBuffer())).toEqual(audio) + expect(await res.json()).toEqual({ text: "Hello world." }) +}) + +test("text and verbose_json answer in OpenAI's shapes", async () => { + const t = await ask({ response_format: "text" }) + expect(t.res.headers.get("content-type")).toMatch(/^text\/plain/) + expect(await t.res.text()).toBe("Hello world.") + const v = await (await ask({ response_format: "verbose_json" })).res.json() + expect(v).toEqual({ task: "transcribe", language: "en", duration: 2.01, text: "Hello world.", words: [{ word: "Hello", start: 0.04, end: 0.24 }] }) +}) + +test("a format xAI can't make, and a translation, are 400s that send nothing", async () => { + for (const [fields, path] of [[{ response_format: "srt" }], [{}, "/audio/translations"]]) { + const { res, sent } = await ask(fields, path) + expect(res.status).toBe(400) + expect(sent).toEqual([]) + } +}) + +test("xAI's refusal comes back with its status and words", async () => { + const { res } = await ask({}, "/audio/transcriptions", () => new Response('{"error":"Field \'language\' is required"}', { status: 400 })) + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain("language") +}) + +test("an image in a Responses request goes to Grok as it was sent", () => { + const body = JSON.stringify({ + model: "grok-4.7", + input: [{ type: "message", role: "user", content: [{ type: "input_text", text: "what is this" }, { type: "input_image", image_url: "data:image/png;base64,AAAA" }] }], + }) + expect(_internal.rewrite(body)).toBe(body) +})