@magpie-community/opencode-grok-auth 0.2.6 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +10 -0
  2. package/index.mjs +92 -1
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -17,6 +17,16 @@ run, such as a container without curl, put the binary in a folder of your
17
17
  own and set `GROK_BIN_DIR` to it. magpie installs Grok Build itself, as
18
18
  the installer does, before a sign-in that needs it.
19
19
 
20
+ ## Images and speech
21
+
22
+ Images in a request (Anthropic image blocks, OpenAI `image_url`, Responses
23
+ `input_image`) go to Grok as sent, and its models take them. Speech to text
24
+ is the one Grok Build's voice dictation uses: magpie's
25
+ `/v1/audio/transcriptions` (model `grok/grok-4.7`, any of the account's
26
+ models) is sent on to xAI's `api.x.ai/v1/stt` with the account's sign-in.
27
+ `language` is passed on; `json`, `text` and `verbose_json` are answered, and
28
+ translations are refused.
29
+
20
30
  ## Sign in
21
31
 
22
32
  - **Sign in with Grok Build (device code)** runs `grok login --device-auth`
package/index.mjs CHANGED
@@ -956,6 +956,96 @@ function kept(res) {
956
956
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
957
957
  }
958
958
 
959
+ // ---- speech to text -----------------------------------------------------------
960
+
961
+ // Grok Build's voice dictation sends audio to xAI's own speech-to-text,
962
+ // POST api.x.ai/v1/stt, signed as every other request of the CLI is. magpie's
963
+ // /v1/audio/transcriptions arrives here as OpenAI's multipart form; xAI's
964
+ // takes `file` last, an optional `language`, and no `model` of OpenAI's
965
+ // (the one it has is the default, and any other id is a 404).
966
+ const STT = "https://api.x.ai/v1/stt"
967
+ const STT_FORMATS = ["json", "text", "verbose_json"]
968
+
969
+ async function sttRequest(body, ctype) {
970
+ let form
971
+ try {
972
+ form = await new Response(body, { headers: { "content-type": ctype } }).formData()
973
+ } catch {
974
+ return { error: "send the audio as multipart/form-data, as OpenAI's /v1/audio/transcriptions takes it: a file and a model" }
975
+ }
976
+ const file = form.get("file")
977
+ if (!(file instanceof Blob)) return { error: "the form has no audio file" }
978
+ const format = String(form.get("response_format") || "json")
979
+ if (!STT_FORMATS.includes(format)) return { error: `Grok's speech to text answers json, text or verbose_json, not ${format}` }
980
+ const out = new FormData()
981
+ const language = form.get("language")
982
+ if (typeof language === "string" && language) out.set("language", language)
983
+ out.set("file", file, file.name || "audio")
984
+ return { form: out, format }
985
+ }
986
+
987
+ // sttAnswer is xAI's answer in the shape OpenAI's takes for the format
988
+ // asked: its words are {text, start, end}, OpenAI's {word, start, end}.
989
+ async function sttAnswer(res, format) {
990
+ let a
991
+ try {
992
+ a = await res.json()
993
+ } catch {
994
+ return new Response("Grok's speech to text answered something that isn't JSON", { status: 502 })
995
+ }
996
+ const text = typeof a?.text === "string" ? a.text : ""
997
+ const headers = new Headers({ "X-Magpie-Sign-In": "kept" })
998
+ if (format === "text") {
999
+ headers.set("content-type", "text/plain; charset=utf-8")
1000
+ return new Response(text, { status: 200, headers })
1001
+ }
1002
+ headers.set("content-type", "application/json")
1003
+ if (format === "json") return new Response(JSON.stringify({ text }), { status: 200, headers })
1004
+ const words = Array.isArray(a.words) ? a.words.map((w) => ({ word: w.text, start: w.start, end: w.end })) : []
1005
+ return new Response(JSON.stringify({ task: "transcribe", language: a.language, duration: a.duration, text, words }), { status: 200, headers })
1006
+ }
1007
+
1008
+ const failure = (status, message, extra = {}) =>
1009
+ new Response(JSON.stringify({ error: { message, type: status === 401 ? "authentication_error" : "invalid_request_error" } }), {
1010
+ status,
1011
+ headers: { "content-type": "application/json", ...extra },
1012
+ })
1013
+
1014
+ async function transcribe(auth, req, init) {
1015
+ const home = auth?.refresh
1016
+ if (req.url.includes("/audio/translations")) return failure(400, "Grok's speech to text transcribes; it doesn't translate")
1017
+ const raw = init?.body
1018
+ const body = typeof raw === "string" ? Buffer.from(raw) : raw
1019
+ const ask = body ? await sttRequest(body, req.headers.get("content-type") ?? "") : { error: "the request has no body" }
1020
+ if (ask.error) return failure(400, ask.error)
1021
+ let c = await token(home)
1022
+ const send = async (key) => {
1023
+ const headers = new Headers()
1024
+ await sign(headers, key)
1025
+ return fetch(STT, { method: "POST", headers, body: ask.form, signal: init?.signal })
1026
+ }
1027
+ let res = await send(c.key)
1028
+ if (res.status === 401) {
1029
+ const said = (await res.text().catch(() => "")).slice(0, 300)
1030
+ try {
1031
+ c = await token(home, c.key, said)
1032
+ } catch (e) {
1033
+ note(home, res)
1034
+ return failure(e?.transient ? 503 : 401, `${e.message}${said ? `. Grok said: ${said}` : ""}`, { "X-Magpie-Sign-In": "kept", ...(e?.transient ? { "retry-after": String(RETRY_SECS) } : {}) })
1035
+ }
1036
+ res = await send(c.key)
1037
+ }
1038
+ note(home, res)
1039
+ if (res.ok) return sttAnswer(res, ask.format)
1040
+ const said = (await res.text().catch(() => "")).slice(0, 300)
1041
+ let msg = said
1042
+ try {
1043
+ const j = JSON.parse(said)
1044
+ msg = typeof j?.error === "string" ? j.error : (j?.error?.message ?? said)
1045
+ } catch {}
1046
+ return failure(res.status, `Grok's speech to text: ${msg || res.status}`, { "X-Magpie-Sign-In": "kept" })
1047
+ }
1048
+
959
1049
  // ---- the plugin ---------------------------------------------------------------
960
1050
 
961
1051
  // A Responses stream that dies before its first byte is asked again, up
@@ -1142,6 +1232,7 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1142
1232
  const home = auth?.refresh
1143
1233
  if (!home) throw new Error("Grok is not signed in; run `grok login`")
1144
1234
  const req = new Request(input, init)
1235
+ if (new URL(req.url).pathname.match(/\/audio\/(transcriptions|translations)$/)) return transcribe(auth, req, init)
1145
1236
  const search = new URL(req.url).pathname.endsWith("/responses") && magpie?.option?.(PROVIDER, "x_search") === true
1146
1237
  let body = rewrite(bodyText(init?.body), search)
1147
1238
  let parsed = {}
@@ -1336,4 +1427,4 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1336
1427
  }
1337
1428
 
1338
1429
  // for tests
1339
- export const _internal = { rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf, waits }
1430
+ export const _internal = { sttRequest, sttAnswer, rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf, waits }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-grok-auth",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",