@magpie-community/opencode-grok-auth 0.2.5 → 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.
- package/README.md +22 -0
- package/index.mjs +212 -2
- package/opencode2.mjs +4 -2
- 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`
|
|
@@ -107,6 +117,18 @@ API (`@ai-sdk/openai`), signed as the CLI signs them:
|
|
|
107
117
|
- `x-grok-doom-loop-check: 1024` and `x-grok-exact-repetition-check: 64`
|
|
108
118
|
on a Responses request, as Grok Build sends them: the proxy then stops a
|
|
109
119
|
reply that repeats itself after ~1K tokens instead of letting it run on.
|
|
120
|
+
- A Responses stream that dies before its first byte (the connection
|
|
121
|
+
reset, with nothing sent yet) is asked again, up to three times. The
|
|
122
|
+
retry goes out before the answer is returned, so a 429 or a 401 comes
|
|
123
|
+
back as itself. Once a byte has arrived, `response.created` and
|
|
124
|
+
reasoning included, it is passed on at once. A later cut is not asked
|
|
125
|
+
again and not rewritten: the stream ends, and magpie 0.1.3298 or newer
|
|
126
|
+
closes it as `response.failed` with `created_at` and `sequence_number`.
|
|
127
|
+
The frame this plugin used to write had `created_at` and still no
|
|
128
|
+
`sequence_number`, so Grok Build reported
|
|
129
|
+
`missing field sequence_number`. An upstream `response.failed`,
|
|
130
|
+
`error` or `response.incomplete` is passed on unchanged. Cancelling
|
|
131
|
+
the turn stops the read and is not asked again.
|
|
110
132
|
|
|
111
133
|
The backend turns away some of what a request may carry, so the plugin
|
|
112
134
|
leaves these out:
|
package/index.mjs
CHANGED
|
@@ -956,8 +956,213 @@ 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
|
|
|
1051
|
+
// A Responses stream that dies before its first byte is asked again, up
|
|
1052
|
+
// to three times, before this answer is returned. A retry's 429 or 401
|
|
1053
|
+
// is that answer: note sees it, and it is not folded into a 200. Once a
|
|
1054
|
+
// byte has arrived, response.created and reasoning included, it is
|
|
1055
|
+
// passed on at once. A later cut is not asked again and not rewritten.
|
|
1056
|
+
// The stream just ends. magpie 0.1.3298 and newer closes a Responses
|
|
1057
|
+
// stream that ends short as response.failed, with the stream's id,
|
|
1058
|
+
// created_at and the next sequence_number (yetone/magpie 29bfd5dc8).
|
|
1059
|
+
// The frame this plugin used to write had created_at and still no
|
|
1060
|
+
// sequence_number, and Grok Build failed the turn on it. An upstream
|
|
1061
|
+
// response.failed, error or response.incomplete is passed on unchanged.
|
|
1062
|
+
// Cancelling stops the upstream read.
|
|
1063
|
+
const STREAM_TRIES = 3
|
|
1064
|
+
const CUT = /ECONNRESET|EPIPE|ETIMEDOUT|ECONNABORTED|socket connection was closed|connection lost|unexpected EOF|terminated|other side closed|UND_ERR|network connection|ECONNREFUSED/i
|
|
1065
|
+
|
|
1066
|
+
function eventStream(res) {
|
|
1067
|
+
const type = res?.headers?.get?.("content-type") || ""
|
|
1068
|
+
return res?.status === 200 && !!res?.body && /text\/event-stream/i.test(type)
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// firstByte reads one chunk. A failure here is still before anything was
|
|
1072
|
+
// sent, so the caller can ask again. The reader stays open when a chunk
|
|
1073
|
+
// did arrive: the rest of the body follows it.
|
|
1074
|
+
async function firstByte(body) {
|
|
1075
|
+
const reader = body.getReader()
|
|
1076
|
+
try {
|
|
1077
|
+
const { done, value } = await reader.read()
|
|
1078
|
+
if (done) return { kind: "end", reader }
|
|
1079
|
+
return { kind: "byte", value, reader }
|
|
1080
|
+
} catch (cause) {
|
|
1081
|
+
const reason = String(cause?.message || cause)
|
|
1082
|
+
try { await reader.cancel(cause) } catch {}
|
|
1083
|
+
return { kind: "cut", reason }
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
function bare(res, stream) {
|
|
1088
|
+
const headers = new Headers(res.headers)
|
|
1089
|
+
headers.delete("content-length")
|
|
1090
|
+
headers.delete("content-encoding")
|
|
1091
|
+
return new Response(stream, { status: res.status, statusText: res.statusText, headers })
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// passThrough sends the chunk already read, then one upstream chunk per
|
|
1095
|
+
// pull. Nothing is buffered past that, and cancel stops the upstream read.
|
|
1096
|
+
function passThrough(res, reader, first) {
|
|
1097
|
+
let lead = first
|
|
1098
|
+
let leadWaiting = true
|
|
1099
|
+
const stream = new ReadableStream({
|
|
1100
|
+
async pull(controller) {
|
|
1101
|
+
if (leadWaiting) {
|
|
1102
|
+
leadWaiting = false
|
|
1103
|
+
if (lead) controller.enqueue(lead)
|
|
1104
|
+
lead = undefined
|
|
1105
|
+
return
|
|
1106
|
+
}
|
|
1107
|
+
try {
|
|
1108
|
+
const { done, value } = await reader.read()
|
|
1109
|
+
if (done) {
|
|
1110
|
+
controller.close()
|
|
1111
|
+
return
|
|
1112
|
+
}
|
|
1113
|
+
controller.enqueue(value)
|
|
1114
|
+
} catch (cause) {
|
|
1115
|
+
const reason = String(cause?.message || cause)
|
|
1116
|
+
try { await reader.cancel(cause) } catch {}
|
|
1117
|
+
// cancel already closed this stream: nothing more to report
|
|
1118
|
+
if (controller.desiredSize === null) return
|
|
1119
|
+
console.warn(`[grok-auth] stream failed (${reason.slice(0, 160)})`)
|
|
1120
|
+
try { controller.close() } catch {}
|
|
1121
|
+
}
|
|
1122
|
+
},
|
|
1123
|
+
cancel(reason) {
|
|
1124
|
+
return reader.cancel(reason)
|
|
1125
|
+
},
|
|
1126
|
+
})
|
|
1127
|
+
return bare(res, stream)
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
function ended(res) {
|
|
1131
|
+
return bare(res, new ReadableStream({
|
|
1132
|
+
start(controller) { controller.close() },
|
|
1133
|
+
}))
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
async function cutRetry(res, again, { tries = STREAM_TRIES } = {}) {
|
|
1137
|
+
let current = res
|
|
1138
|
+
for (let attempt = 1; attempt <= tries; attempt++) {
|
|
1139
|
+
if (attempt > 1) {
|
|
1140
|
+
try {
|
|
1141
|
+
current = await again()
|
|
1142
|
+
} catch (cause) {
|
|
1143
|
+
const said = String(cause?.message || cause)
|
|
1144
|
+
console.warn(`[grok-auth] retry ${attempt}/${tries} did not start: ${said.slice(0, 160)}`)
|
|
1145
|
+
if (!CUT.test(said) || attempt === tries) return ended(res)
|
|
1146
|
+
continue
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
if (!eventStream(current)) return current
|
|
1150
|
+
const read = await firstByte(current.body)
|
|
1151
|
+
if (read.kind === "byte") return passThrough(current, read.reader, read.value)
|
|
1152
|
+
if (read.kind === "end") {
|
|
1153
|
+
try { await read.reader.cancel() } catch {}
|
|
1154
|
+
return ended(current)
|
|
1155
|
+
}
|
|
1156
|
+
const reason = read.reason
|
|
1157
|
+
if (!CUT.test(reason) || attempt === tries) {
|
|
1158
|
+
console.warn(`[grok-auth] stream failed (${reason.slice(0, 160)})`)
|
|
1159
|
+
return ended(current)
|
|
1160
|
+
}
|
|
1161
|
+
console.warn(`[grok-auth] stream cut before any byte (${reason.slice(0, 140)}); retry ${attempt + 1}/${tries}`)
|
|
1162
|
+
}
|
|
1163
|
+
return ended(current)
|
|
1164
|
+
}
|
|
1165
|
+
|
|
961
1166
|
export const GrokAuthPlugin = async ({ client, magpie }) => {
|
|
962
1167
|
const remember = async (auth, c) => {
|
|
963
1168
|
if (auth.access === c.key && auth.expires === c.expires) return
|
|
@@ -1027,6 +1232,7 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
|
|
|
1027
1232
|
const home = auth?.refresh
|
|
1028
1233
|
if (!home) throw new Error("Grok is not signed in; run `grok login`")
|
|
1029
1234
|
const req = new Request(input, init)
|
|
1235
|
+
if (new URL(req.url).pathname.match(/\/audio\/(transcriptions|translations)$/)) return transcribe(auth, req, init)
|
|
1030
1236
|
const search = new URL(req.url).pathname.endsWith("/responses") && magpie?.option?.(PROVIDER, "x_search") === true
|
|
1031
1237
|
let body = rewrite(bodyText(init?.body), search)
|
|
1032
1238
|
let parsed = {}
|
|
@@ -1106,7 +1312,11 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
|
|
|
1106
1312
|
res = await send(c.key)
|
|
1107
1313
|
}
|
|
1108
1314
|
note(home, res)
|
|
1109
|
-
return kept(res)
|
|
1315
|
+
return kept(await cutRetry(res, async () => {
|
|
1316
|
+
const next = await send(c.key)
|
|
1317
|
+
note(home, next)
|
|
1318
|
+
return next
|
|
1319
|
+
}))
|
|
1110
1320
|
},
|
|
1111
1321
|
}
|
|
1112
1322
|
},
|
|
@@ -1217,4 +1427,4 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
|
|
|
1217
1427
|
}
|
|
1218
1428
|
|
|
1219
1429
|
// for tests
|
|
1220
|
-
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
|
@@ -85,8 +85,10 @@ export function fieldsOf(prompts) {
|
|
|
85
85
|
if (p.placeholder) f.placeholder = String(p.placeholder)
|
|
86
86
|
if (p.type === "select" && Array.isArray(p.options))
|
|
87
87
|
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
|
|
88
|
-
// a prompt shown only when another answer says so can't be required
|
|
89
|
-
|
|
88
|
+
// a prompt shown only when another answer says so can't be required, and
|
|
89
|
+
// neither can one whose own validate() accepts an empty answer (the
|
|
90
|
+
// browser sign-in's optional API key)
|
|
91
|
+
if (!p.condition && p.required !== false) f.required = true
|
|
90
92
|
out.push(f)
|
|
91
93
|
}
|
|
92
94
|
return out.length ? out : undefined
|
package/package.json
CHANGED