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

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.
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/opencode2.mjs CHANGED
@@ -507,6 +507,14 @@ async function setupPlugin(ctx, fn, live) {
507
507
  // the account the list was last read for: a credential.updated that
508
508
  // leaves it as it was reads nothing again
509
509
  let readFor = null
510
+ // the last list each account's own read gave, by the account it was read
511
+ // for: a read that fails (a workspace config answering 503) keeps the
512
+ // list that same account last read rather than the bundled one, which
513
+ // brought back models its workspace hides (plugins#1642). Another
514
+ // account's list is never used, a read that gave an empty list is kept
515
+ // as empty, and the bundled list stands in only for an account whose
516
+ // list was never read.
517
+ const lists = new Map()
510
518
  const stateOf = async () => {
511
519
  const c = await ctx.integration.connection.active(authID).catch(() => undefined)
512
520
  const a = c ? await getAuth(authID) : undefined
@@ -523,7 +531,8 @@ async function setupPlugin(ctx, fn, live) {
523
531
  const s = source.get(authID)
524
532
  const connection = await ctx.integration.connection.active(authID).catch(() => undefined)
525
533
  const a = connection ? await getAuth(authID) : undefined
526
- readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "")
534
+ const readingFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "")
535
+ readFor = readingFor
527
536
  if (!a || listID !== authID || typeof hooks.provider?.models !== "function") {
528
537
  if (s.connection || s.models) {
529
538
  s.connection = undefined
@@ -544,7 +553,12 @@ async function setupPlugin(ctx, fn, live) {
544
553
  return
545
554
  }
546
555
  s.connection = connection
547
- s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null
556
+ if (got && typeof got === "object") {
557
+ s.models = Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m)))
558
+ lists.delete(readingFor)
559
+ lists.set(readingFor, s.models)
560
+ if (lists.size > 32) lists.delete(lists.keys().next().value)
561
+ } else s.models = lists.get(readingFor) ?? null
548
562
  await ctx.provider.reload()
549
563
  await ctx.model?.reload?.()
550
564
  } finally {
@@ -575,7 +589,31 @@ async function setupPlugin(ctx, fn, live) {
575
589
  }
576
590
  } catch {}
577
591
  })()
578
- void refresh()
592
+ // A plugin still reading its list in the background when the first read
593
+ // returned (agy-cli: `agy models` and a session probe take seconds, and
594
+ // the first read gets its static list) says so through
595
+ // provider.warming(): the list is read once more when that ends, once,
596
+ // and no later than a minute on.
597
+ const warmed = async () => {
598
+ let w
599
+ try {
600
+ w = typeof hooks.provider?.warming === "function" ? hooks.provider.warming() : null
601
+ } catch {
602
+ return
603
+ }
604
+ if (!w || typeof w.then !== "function") return
605
+ let timer
606
+ await Promise.race([
607
+ Promise.resolve(w).catch(() => {}),
608
+ new Promise((r) => {
609
+ timer = setTimeout(r, 60_000)
610
+ timer.unref?.()
611
+ }),
612
+ ])
613
+ clearTimeout(timer)
614
+ if (live.on) await refresh()
615
+ }
616
+ void refresh().then(warmed, () => {})
579
617
  }
580
618
 
581
619
  export async function setup(ctx, mod = v1) {
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.8",
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",