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

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
@@ -68,6 +68,17 @@ it, then reads it again:
68
68
  and sending it a message renews it. For a home of the plugin's (a second
69
69
  account, an imported one), opening Grok Build doesn't touch it: add the
70
70
  account in magpie again.
71
+ - Not every 401 is Grok judging the token. A token it doesn't take is
72
+ answered at once with `Invalid or expired credentials (…)`. Another
73
+ 401, such as `Authentication required` after a minute or more, on a
74
+ token the CLI left as it was and not yet ended, has passed by itself
75
+ within minutes. Unless the CLI failed renewing it, that is a 503 with
76
+ `Retry-After: 60` that keeps the sign-in and says how long Grok took:
77
+ magpie rests the account a moment and asks the next one. It never says
78
+ to sign in again.
79
+ - A request, model list or usage read turned away waits on the CLI's
80
+ renewal 15 seconds at most. The run goes on, and the next one to ask
81
+ takes what it gave.
71
82
  - When the CLI no longer holds a sign-in in that home (`grok logout`),
72
83
  the account has to be signed in again. When it couldn't renew a token
73
84
  that has ended, magpie tries again later.
@@ -96,6 +107,18 @@ API (`@ai-sdk/openai`), signed as the CLI signs them:
96
107
  - `x-grok-doom-loop-check: 1024` and `x-grok-exact-repetition-check: 64`
97
108
  on a Responses request, as Grok Build sends them: the proxy then stops a
98
109
  reply that repeats itself after ~1K tokens instead of letting it run on.
110
+ - A Responses stream that dies before its first byte (the connection
111
+ reset, with nothing sent yet) is asked again, up to three times. The
112
+ retry goes out before the answer is returned, so a 429 or a 401 comes
113
+ back as itself. Once a byte has arrived, `response.created` and
114
+ reasoning included, it is passed on at once. A later cut is not asked
115
+ again and not rewritten: the stream ends, and magpie 0.1.3298 or newer
116
+ closes it as `response.failed` with `created_at` and `sequence_number`.
117
+ The frame this plugin used to write had `created_at` and still no
118
+ `sequence_number`, so Grok Build reported
119
+ `missing field sequence_number`. An upstream `response.failed`,
120
+ `error` or `response.incomplete` is passed on unchanged. Cancelling
121
+ the turn stops the read and is not asked again.
99
122
 
100
123
  The backend turns away some of what a request may carry, so the plugin
101
124
  leaves these out:
package/index.mjs CHANGED
@@ -23,6 +23,18 @@ const LOOP_CHECKS = [["x-grok-doom-loop-check", "1024"], ["x-grok-exact-repetiti
23
23
  const REFRESH_MARGIN = 5 * 60 * 1000 // a token this close to its end is renewed before a request
24
24
  const LEAD_MS = REFRESH_MARGIN // and this close, magpie renews it ahead of time (auth.refresh)
25
25
  const LINK_WAIT = 30 * 1000
26
+ // waits.renew is how long a request, model list or usage read Grok turned
27
+ // away waits on Grok Build's renewal before it gives up on it: the run
28
+ // goes on, and whoever asks next takes what it gave (plugins#818)
29
+ const waits = { renew: 15 * 1000 }
30
+ // TURNED_AWAY are the words of a 401 in which Grok judged the token
31
+ // itself: cli-chat-proxy answers a token it doesn't take, in under a
32
+ // second, `{"error":"Invalid or expired credentials (auth_kind=…,
33
+ // upstream=Unauthenticated, reason=…)"}`. Any other 401, such as the
34
+ // `{"error":"Authentication required"}` that came after 78–114 s on a token
35
+ // that worked again minutes later (plugins#818), isn't that judgement.
36
+ const TURNED_AWAY = /invalid or expired credentials/i
37
+ const RETRY_SECS = 60 // the Retry-After of a refusal that passes by itself
26
38
  const INSTALL = process.platform === "win32" ? "irm https://x.ai/cli/install.ps1 | iex" : "curl -fsSL https://x.ai/cli/install.sh | bash"
27
39
  // NO_CLI is what a sign-in without Grok Build says: how to install it, and
28
40
  // that one put somewhere else by hand (a container with no shell to run the
@@ -205,9 +217,34 @@ function notSignedIn(home) {
205
217
  // and its last line.
206
218
  function cliSaid(r) {
207
219
  if (!r) return ""
220
+ if (r.late) return ` (grok models was still running after ${waits.renew / 1000}s)`
208
221
  const last = (r.stderr || r.stdout || "").replace(ANSI, "").split("\n").map((l) => l.trim()).filter(Boolean).at(-1)?.slice(0, 200)
209
222
  const how = !r.err ? "ran and left the same token" : r.err.killed ? "timed out" : `exited ${r.err.code ?? "with an error"}`
210
- return ` (grok models ${how}${last ? `: ${last}` : ""})`
223
+ const took = r.ms >= 1000 ? ` in ${Math.round(r.ms / 1000)}s` : ""
224
+ return ` (grok models ${how}${took}${last ? `: ${last}` : ""})`
225
+ }
226
+
227
+ // passing says a 401 on a token Grok Build left as it was is a refusal
228
+ // that passes by itself, not a sign-in to make again: Grok's words aren't
229
+ // its judgement of the token (TURNED_AWAY), the token isn't past its end,
230
+ // and the CLI didn't fail renewing it (it ran, or was still running). A
231
+ // token Grok really turned away, or one the CLI failed to renew, is
232
+ // unrenewed as before.
233
+ function passing(c, r, said) {
234
+ if (typeof said !== "string" || TURNED_AWAY.test(said)) return false
235
+ if (c.expires && c.expires <= Date.now()) return false
236
+ return !r?.err || !!r.err.killed || !!r.late
237
+ }
238
+
239
+ // transient is such a refusal: what Grok said, that the sign-in stands,
240
+ // and that it is tried again later.
241
+ function transient(c, r, said) {
242
+ const till = c.expires ? `, good till ${new Date(c.expires).toISOString()}` : ""
243
+ const words = said.trim().slice(0, 200) || "an empty 401"
244
+ return Object.assign(
245
+ new Error(`Grok refused the request (${words}) on a sign-in that still holds: Grok Build left the token as it was${till}${cliSaid(r)}. Such a refusal has passed by itself within minutes; the account is tried again then, with no new sign-in needed`),
246
+ { transient: true },
247
+ )
211
248
  }
212
249
 
213
250
  // unrenewed is a token Grok turned away, or one past its end, that Grok
@@ -229,13 +266,20 @@ function dead(home) {
229
266
  }
230
267
 
231
268
  function run(file, args, opts) {
269
+ const at = Date.now()
232
270
  return new Promise((resolve) => {
233
271
  execFile(file, args, { timeout: 30000, ...opts }, (err, stdout, stderr) =>
234
- resolve({ err, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") }),
272
+ resolve({ err, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), ms: Date.now() - at }),
235
273
  )
236
274
  })
237
275
  }
238
276
 
277
+ // within is p, or { late: true } once ms have gone by without it.
278
+ function within(p, ms) {
279
+ let t
280
+ return Promise.race([p, new Promise((ok) => (t = setTimeout(() => ok({ late: true }), ms)))]).finally(() => clearTimeout(t))
281
+ }
282
+
239
283
  // refreshing runs the CLI's renewals one after another; renewing is the one
240
284
  // asked for each home, which those who come while it is due or running join
241
285
  // rather than running the CLI there again.
@@ -259,17 +303,20 @@ function renew(exe, home) {
259
303
  // turned away: rejected is that token (or true for whatever home holds).
260
304
  // A token on disk other than the one turned away was renewed already and
261
305
  // is taken as it is; one the CLI's run leaves as it was is unrenewed,
262
- // never "not signed in" nor "expired".
263
- async function token(home, rejected = false) {
306
+ // never "not signed in" nor "expired". said is what Grok answered the
307
+ // token turned away with: a refusal that wasn't Grok's judgement of a
308
+ // token still good is transient (passing). A renewal for a token turned
309
+ // away is waited on waits.renew at most.
310
+ async function token(home, rejected = false, said) {
264
311
  let c = await credential(home)
265
312
  const exe = executable()
266
313
  const refused = !!c && (rejected === true || (typeof rejected === "string" && c.key === rejected))
267
314
  let r
268
315
  if (c && exe && (refused || c.expires - Date.now() < REFRESH_MARGIN)) {
269
316
  const was = c.key
270
- r = await renew(exe, home)
317
+ r = refused ? await within(renew(exe, home), waits.renew) : await renew(exe, home)
271
318
  c = await credential(home)
272
- if (c && refused && c.key === was) throw unrenewed(home, r)
319
+ if (c && refused && c.key === was) throw passing(c, r, said) ? transient(c, r, said) : unrenewed(home, r)
273
320
  }
274
321
  if (!c) throw new Error(notSignedIn(home))
275
322
  if (!exe && (refused || (c.expires && c.expires <= Date.now()))) throw new Error(`Grok turned the sign-in away and there is no Grok Build here to renew it; ${NO_CLI}`)
@@ -525,7 +572,7 @@ async function listModels(key) {
525
572
  const text = await res.text()
526
573
  // a token Grok turned away before its time: the caller has Grok Build
527
574
  // renew it and asks once more (models below)
528
- if (res.status === 401) throw Object.assign(new Error("Grok turned the sign-in away"), { status: 401 })
575
+ if (res.status === 401) throw Object.assign(new Error("Grok turned the sign-in away"), { status: 401, said: text })
529
576
  if (!res.ok) throw new Error(`Grok models: ${res.status} ${text.slice(0, 200)}`)
530
577
  const out = []
531
578
  for (const d of JSON.parse(text)?.data ?? []) {
@@ -827,7 +874,7 @@ async function usage(key) {
827
874
  } catch (e) {
828
875
  return { error: netError(url, e), windows: [] }
829
876
  }
830
- if (!res.ok) return { error: statusText(res.status), windows: [], status: res.status }
877
+ if (!res.ok) return { error: statusText(res.status), windows: [], status: res.status, said: await res.text().catch(() => "") }
831
878
  let data
832
879
  try {
833
880
  data = JSON.parse(text)
@@ -911,6 +958,121 @@ function kept(res) {
911
958
 
912
959
  // ---- the plugin ---------------------------------------------------------------
913
960
 
961
+ // A Responses stream that dies before its first byte is asked again, up
962
+ // to three times, before this answer is returned. A retry's 429 or 401
963
+ // is that answer: note sees it, and it is not folded into a 200. Once a
964
+ // byte has arrived, response.created and reasoning included, it is
965
+ // passed on at once. A later cut is not asked again and not rewritten.
966
+ // The stream just ends. magpie 0.1.3298 and newer closes a Responses
967
+ // stream that ends short as response.failed, with the stream's id,
968
+ // created_at and the next sequence_number (yetone/magpie 29bfd5dc8).
969
+ // The frame this plugin used to write had created_at and still no
970
+ // sequence_number, and Grok Build failed the turn on it. An upstream
971
+ // response.failed, error or response.incomplete is passed on unchanged.
972
+ // Cancelling stops the upstream read.
973
+ const STREAM_TRIES = 3
974
+ const CUT = /ECONNRESET|EPIPE|ETIMEDOUT|ECONNABORTED|socket connection was closed|connection lost|unexpected EOF|terminated|other side closed|UND_ERR|network connection|ECONNREFUSED/i
975
+
976
+ function eventStream(res) {
977
+ const type = res?.headers?.get?.("content-type") || ""
978
+ return res?.status === 200 && !!res?.body && /text\/event-stream/i.test(type)
979
+ }
980
+
981
+ // firstByte reads one chunk. A failure here is still before anything was
982
+ // sent, so the caller can ask again. The reader stays open when a chunk
983
+ // did arrive: the rest of the body follows it.
984
+ async function firstByte(body) {
985
+ const reader = body.getReader()
986
+ try {
987
+ const { done, value } = await reader.read()
988
+ if (done) return { kind: "end", reader }
989
+ return { kind: "byte", value, reader }
990
+ } catch (cause) {
991
+ const reason = String(cause?.message || cause)
992
+ try { await reader.cancel(cause) } catch {}
993
+ return { kind: "cut", reason }
994
+ }
995
+ }
996
+
997
+ function bare(res, stream) {
998
+ const headers = new Headers(res.headers)
999
+ headers.delete("content-length")
1000
+ headers.delete("content-encoding")
1001
+ return new Response(stream, { status: res.status, statusText: res.statusText, headers })
1002
+ }
1003
+
1004
+ // passThrough sends the chunk already read, then one upstream chunk per
1005
+ // pull. Nothing is buffered past that, and cancel stops the upstream read.
1006
+ function passThrough(res, reader, first) {
1007
+ let lead = first
1008
+ let leadWaiting = true
1009
+ const stream = new ReadableStream({
1010
+ async pull(controller) {
1011
+ if (leadWaiting) {
1012
+ leadWaiting = false
1013
+ if (lead) controller.enqueue(lead)
1014
+ lead = undefined
1015
+ return
1016
+ }
1017
+ try {
1018
+ const { done, value } = await reader.read()
1019
+ if (done) {
1020
+ controller.close()
1021
+ return
1022
+ }
1023
+ controller.enqueue(value)
1024
+ } catch (cause) {
1025
+ const reason = String(cause?.message || cause)
1026
+ try { await reader.cancel(cause) } catch {}
1027
+ // cancel already closed this stream: nothing more to report
1028
+ if (controller.desiredSize === null) return
1029
+ console.warn(`[grok-auth] stream failed (${reason.slice(0, 160)})`)
1030
+ try { controller.close() } catch {}
1031
+ }
1032
+ },
1033
+ cancel(reason) {
1034
+ return reader.cancel(reason)
1035
+ },
1036
+ })
1037
+ return bare(res, stream)
1038
+ }
1039
+
1040
+ function ended(res) {
1041
+ return bare(res, new ReadableStream({
1042
+ start(controller) { controller.close() },
1043
+ }))
1044
+ }
1045
+
1046
+ async function cutRetry(res, again, { tries = STREAM_TRIES } = {}) {
1047
+ let current = res
1048
+ for (let attempt = 1; attempt <= tries; attempt++) {
1049
+ if (attempt > 1) {
1050
+ try {
1051
+ current = await again()
1052
+ } catch (cause) {
1053
+ const said = String(cause?.message || cause)
1054
+ console.warn(`[grok-auth] retry ${attempt}/${tries} did not start: ${said.slice(0, 160)}`)
1055
+ if (!CUT.test(said) || attempt === tries) return ended(res)
1056
+ continue
1057
+ }
1058
+ }
1059
+ if (!eventStream(current)) return current
1060
+ const read = await firstByte(current.body)
1061
+ if (read.kind === "byte") return passThrough(current, read.reader, read.value)
1062
+ if (read.kind === "end") {
1063
+ try { await read.reader.cancel() } catch {}
1064
+ return ended(current)
1065
+ }
1066
+ const reason = read.reason
1067
+ if (!CUT.test(reason) || attempt === tries) {
1068
+ console.warn(`[grok-auth] stream failed (${reason.slice(0, 160)})`)
1069
+ return ended(current)
1070
+ }
1071
+ console.warn(`[grok-auth] stream cut before any byte (${reason.slice(0, 140)}); retry ${attempt + 1}/${tries}`)
1072
+ }
1073
+ return ended(current)
1074
+ }
1075
+
914
1076
  export const GrokAuthPlugin = async ({ client, magpie }) => {
915
1077
  const remember = async (auth, c) => {
916
1078
  if (auth.access === c.key && auth.expires === c.expires) return
@@ -1011,8 +1173,10 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1011
1173
  for (const [k, v] of LOOP_CHECKS) if (!headers.has(k)) headers.set(k, v)
1012
1174
  }
1013
1175
  headers.delete("content-length")
1176
+ let at = 0 // when the last request went out, signed
1014
1177
  const send = async (key) => {
1015
1178
  await sign(headers, key)
1179
+ at = Date.now()
1016
1180
  return fetch(req.url, { ...init, method: req.method, headers, body })
1017
1181
  }
1018
1182
  // Grok's answer goes on as it came, the account kept, as the
@@ -1021,27 +1185,47 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1021
1185
  // expires_at) is renewed by Grok Build and the request sent once
1022
1186
  // more; one Grok Build couldn't renew is a 401 saying so, and
1023
1187
  // what helps.
1188
+ //
1189
+ // A 401 that wasn't Grok's judgement of the token, on one Grok
1190
+ // Build left as it was and still good, is a refusal that passes
1191
+ // by itself (plugins#818): a 503 saying so, with Retry-After,
1192
+ // so magpie rests the account a moment and asks the next, and
1193
+ // never says to sign in again. How long Grok took to answer is
1194
+ // in the words: the wait is Grok's, not the plugin's.
1024
1195
  let res = await send(c.key)
1025
1196
  if (res.status === 401 && (typeof body === "string" || body == null)) {
1197
+ const took = Date.now() - at
1198
+ const said = (await res.text().catch(() => "")).slice(0, 300)
1026
1199
  try {
1027
- c = await token(home, c.key)
1200
+ c = await token(home, c.key, said)
1028
1201
  } catch (e) {
1029
- const said = (await res.text().catch(() => "")).slice(0, 300)
1030
1202
  note(home, res)
1203
+ const after = took >= 1000 ? ` after ${Math.round(took / 1000)}s` : ""
1204
+ if (e?.transient) {
1205
+ return kept(
1206
+ new Response(JSON.stringify({ error: { message: `${e.message}. Grok answered 401${after}`, type: "server_error", code: "auth_refused_transient" } }), {
1207
+ status: 503,
1208
+ headers: { "content-type": "application/json", "retry-after": String(RETRY_SECS) },
1209
+ }),
1210
+ )
1211
+ }
1031
1212
  return kept(
1032
- new Response(JSON.stringify({ error: { message: `${e.message}${said ? `. Grok said: ${said}` : ""}`, type: "authentication_error", code: "sign_in_unrenewed" } }), {
1213
+ new Response(JSON.stringify({ error: { message: `${e.message}${said ? `. Grok said${after}: ${said}` : ""}`, type: "authentication_error", code: "sign_in_unrenewed" } }), {
1033
1214
  status: 401,
1034
1215
  statusText: res.statusText,
1035
1216
  headers: { "content-type": "application/json" },
1036
1217
  }),
1037
1218
  )
1038
1219
  }
1039
- await res.body?.cancel().catch(() => {})
1040
1220
  await remember(auth, c)
1041
1221
  res = await send(c.key)
1042
1222
  }
1043
1223
  note(home, res)
1044
- return kept(res)
1224
+ return kept(await cutRetry(res, async () => {
1225
+ const next = await send(c.key)
1226
+ note(home, next)
1227
+ return next
1228
+ }))
1045
1229
  },
1046
1230
  }
1047
1231
  },
@@ -1088,7 +1272,7 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1088
1272
  // a token turned away is renewed once, as a request's is
1089
1273
  if (u.status === 401) {
1090
1274
  try {
1091
- c = await token(auth.refresh, c.key)
1275
+ c = await token(auth.refresh, c.key, u.said)
1092
1276
  } catch (e) {
1093
1277
  return { error: e.message, windows: [], signIn: "kept" }
1094
1278
  }
@@ -1096,6 +1280,7 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1096
1280
  u = await usage(c.key)
1097
1281
  }
1098
1282
  delete u.status
1283
+ delete u.said
1099
1284
  if (!u.error) u.windows = [...rateWindow(auth.refresh), ...u.windows]
1100
1285
  return { ...u, signIn: "kept" }
1101
1286
  },
@@ -1115,7 +1300,7 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1115
1300
  } catch (e) {
1116
1301
  if (e?.status !== 401) throw e
1117
1302
  // turned away before its time: renewed once, as a request's is
1118
- c = await token(auth.refresh, c.key)
1303
+ c = await token(auth.refresh, c.key, e.said)
1119
1304
  list = await listModels(c.key).catch((e) => {
1120
1305
  throw e?.status === 401 ? new Error(dead(auth.refresh)) : e
1121
1306
  })
@@ -1151,4 +1336,4 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1151
1336
  }
1152
1337
 
1153
1338
  // for tests
1154
- export const _internal = { rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf }
1339
+ export const _internal = { 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
- if (!p.condition) f.required = true
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-grok-auth",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
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",