@magpie-community/opencode-grok-auth 0.2.0 → 0.2.2

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 +16 -0
  2. package/index.mjs +179 -38
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -59,9 +59,22 @@ it, then reads it again:
59
59
  - The CLI runs once for a home at a time: a request or renewal that
60
60
  comes while it runs waits for it and reads what it gave. A token the
61
61
  CLI already renewed is taken as it is.
62
+ - Grok can turn a token away before its `expires_at`. A request, model
63
+ list or usage read that gets 401 has the CLI renew the token and asks
64
+ once more with the new one.
65
+ - When the CLI's run leaves the token as it was, the 401 or error says
66
+ Grok Build couldn't renew the sign-in, with what the CLI said. For Grok
67
+ Build's own home ("Use Grok Build's current sign-in") opening Grok Build
68
+ and sending it a message renews it. For a home of the plugin's (a second
69
+ account, an imported one), opening Grok Build doesn't touch it: add the
70
+ account in magpie again.
62
71
  - When the CLI no longer holds a sign-in in that home (`grok logout`),
63
72
  the account has to be signed in again. When it couldn't renew a token
64
73
  that has ended, magpie tries again later.
74
+ - An `auth.json` that is empty or not JSON is most likely one the CLI is
75
+ writing: it is read again for about half a second, then the last sign-in
76
+ read whole there stands, as the CLI itself keeps its previous one. It is
77
+ never taken as signed out. The plugin takes no `auth.json.lock`.
65
78
 
66
79
  ## Requests
67
80
 
@@ -80,6 +93,9 @@ API (`@ai-sdk/openai`), signed as the CLI signs them:
80
93
  (`500000` for `@500k`). The plain id sends no such header and stays on
81
94
  the default window.
82
95
  - `x-grok-conv-id`: the request's `prompt_cache_key`.
96
+ - `x-grok-doom-loop-check: 1024` and `x-grok-exact-repetition-check: 64`
97
+ on a Responses request, as Grok Build sends them: the proxy then stops a
98
+ reply that repeats itself after ~1K tokens instead of letting it run on.
83
99
 
84
100
  The backend turns away some of what a request may carry, so the plugin
85
101
  leaves these out:
package/index.mjs CHANGED
@@ -19,6 +19,7 @@ const BASE = "https://cli-chat-proxy.grok.com/v1"
19
19
  const CLIENT_VERSION = "1.0.41"
20
20
  const CPA_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828"
21
21
  const CPA_SCOPE = `https://auth.x.ai::${CPA_CLIENT_ID}`
22
+ const LOOP_CHECKS = [["x-grok-doom-loop-check", "1024"], ["x-grok-exact-repetition-check", "64"]]
22
23
  const REFRESH_MARGIN = 5 * 60 * 1000 // a token this close to its end is renewed before a request
23
24
  const LEAD_MS = REFRESH_MARGIN // and this close, magpie renews it ahead of time (auth.refresh)
24
25
  const LINK_WAIT = 30 * 1000
@@ -128,11 +129,15 @@ function look(home) {
128
129
  } catch (e) {
129
130
  return { c: null, why: e?.code === "ENOENT" ? `there is no ${file}` : `${file} can't be read (${e?.code ?? e?.message})` }
130
131
  }
132
+ // an empty file, or one that isn't JSON, is most likely one the CLI is
133
+ // writing as it is read (it rewrites auth.json when it renews): torn
134
+ // says the read tells nothing, which read() tries again
135
+ if (!text.trim()) return { c: null, why: `${file} is empty`, torn: true }
131
136
  let all
132
137
  try {
133
138
  all = JSON.parse(text)
134
139
  } catch {
135
- return { c: null, why: `${file} isn't JSON` }
140
+ return { c: null, why: `${file} isn't JSON`, torn: true }
136
141
  }
137
142
  if (!all || typeof all !== "object" || Array.isArray(all)) return { c: null, why: `${file} holds no sign-in` }
138
143
  const keys = Object.keys(all).sort()
@@ -143,19 +148,91 @@ function look(home) {
143
148
  const email = typeof c.email === "string" ? c.email : ""
144
149
  const sub = cpaClaims(c.key)?.sub
145
150
  const user = (typeof c.user_id === "string" && c.user_id) || (typeof sub === "string" ? sub : "")
146
- return { c: { key: c.key, email, user, who: email || user, expires: Number.isFinite(t) ? t : 0, issuer: c.oidc_issuer ?? "" }, why: "" }
151
+ const got = { key: c.key, email, user, who: email || user, expires: Number.isFinite(t) ? t : 0, issuer: c.oidc_issuer ?? "" }
152
+ lastGood.set(home, got)
153
+ return { c: got, why: "" }
147
154
  }
148
155
  }
149
156
  return { c: null, why: keys.length ? `${file} has ${keys.join(", ")}, none with a token` : `${file} holds no sign-in` }
150
157
  }
151
158
 
152
- function credential(home) {
153
- return look(home).c
159
+ // lastGood is each home's last sign-in read whole.
160
+ const lastGood = new Map()
161
+ const TORN_TRIES = 6
162
+ const TORN_WAIT = 100
163
+
164
+ // read is look, a torn read (auth.json caught mid-write) tried again for
165
+ // about half a second; still torn, it is the last sign-in read whole there,
166
+ // as the CLI itself keeps its previous credentials when auth.json won't
167
+ // read ("auth reload: auth.json unreadable, keeping previous credentials").
168
+ // No lock is taken: the CLI's auth.json.lock is a flock it holds while it
169
+ // renews, which Node can't take, and a reader holding it could only hold a
170
+ // renewal back.
171
+ async function read(home) {
172
+ let r = look(home)
173
+ for (let i = 1; r.torn && i < TORN_TRIES; i++) {
174
+ await new Promise((ok) => setTimeout(ok, TORN_WAIT))
175
+ r = look(home)
176
+ }
177
+ if (r.torn && lastGood.has(home)) return { c: lastGood.get(home), why: "" }
178
+ return r
179
+ }
180
+
181
+ // credential is the sign-in in home, null when there is none. A file that
182
+ // stays torn, with nothing read there before, is unknown, not "not signed
183
+ // in": that is an error saying so.
184
+ async function credential(home) {
185
+ const r = await read(home)
186
+ if (r.torn) throw new Error(`Grok Build's sign-in couldn't be read (${r.why}); it may be mid-write, try again in a moment`)
187
+ return r.c
188
+ }
189
+
190
+ // shared is whether home is Grok Build's own, which opening Grok Build
191
+ // renews; a home of this plugin's (a second account, an imported one) only
192
+ // this plugin's runs of the CLI ever touch.
193
+ function shared(home) {
194
+ return resolve(home) === resolve(cliHome())
195
+ }
196
+
197
+ // notSignedIn says a home holds no sign-in, and what makes one.
198
+ function notSignedIn(home) {
199
+ return shared(home)
200
+ ? "Grok is not signed in; run `grok login`"
201
+ : "Grok is not signed in for this account any more; add the account in magpie again"
202
+ }
203
+
204
+ // cliSaid is what a `grok models` that renewed nothing said: how it ended
205
+ // and its last line.
206
+ function cliSaid(r) {
207
+ if (!r) return ""
208
+ const last = (r.stderr || r.stdout || "").replace(ANSI, "").split("\n").map((l) => l.trim()).filter(Boolean).at(-1)?.slice(0, 200)
209
+ 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}` : ""})`
211
+ }
212
+
213
+ // unrenewed is a token Grok turned away, or one past its end, that Grok
214
+ // Build, run in its home, didn't replace: the CLI couldn't renew it (xAI's renewal failing, or
215
+ // a refresh token used up elsewhere), which signing in with `grok login`
216
+ // in ~/.grok doesn't help where the account's home is the plugin's own.
217
+ function unrenewed(home, r) {
218
+ const how = shared(home)
219
+ ? "open Grok Build and send it a message, which renews the sign-in magpie reads"
220
+ : "this account's sign-in is kept apart from Grok Build's own, so opening Grok Build doesn't renew it: add the account in magpie again"
221
+ return Object.assign(new Error(`Grok Build couldn't renew the sign-in${cliSaid(r)}; ${how}`), { unrenewed: true })
222
+ }
223
+
224
+ // dead is a token Grok turned away even as Grok Build had just renewed it.
225
+ function dead(home) {
226
+ return shared(home)
227
+ ? "Grok turned away Grok Build's sign-in even after renewing it; run `grok login` to sign Grok Build in afresh"
228
+ : "Grok turned away this account's sign-in even after renewing it; add the account in magpie again"
154
229
  }
155
230
 
156
231
  function run(file, args, opts) {
157
232
  return new Promise((resolve) => {
158
- execFile(file, args, { timeout: 30000, ...opts }, (err, stdout) => resolve({ err, stdout: String(stdout ?? "") }))
233
+ execFile(file, args, { timeout: 30000, ...opts }, (err, stdout, stderr) =>
234
+ resolve({ err, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") }),
235
+ )
159
236
  })
160
237
  }
161
238
 
@@ -178,17 +255,25 @@ function renew(exe, home) {
178
255
  }
179
256
 
180
257
  // token is the CLI's sign-in in home with a token still good. One about to
181
- // expire (or that a request found expired) is first renewed by the CLI in
182
- // its own home.
183
- async function token(home, expired) {
184
- let c = credential(home)
258
+ // expire is first renewed by the CLI in its own home, and so is one Grok
259
+ // turned away: rejected is that token (or true for whatever home holds).
260
+ // A token on disk other than the one turned away was renewed already and
261
+ // 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) {
264
+ let c = await credential(home)
185
265
  const exe = executable()
186
- if (c && exe && (expired || c.expires - Date.now() < REFRESH_MARGIN)) {
187
- await renew(exe, home)
188
- c = credential(home)
266
+ const refused = !!c && (rejected === true || (typeof rejected === "string" && c.key === rejected))
267
+ let r
268
+ if (c && exe && (refused || c.expires - Date.now() < REFRESH_MARGIN)) {
269
+ const was = c.key
270
+ r = await renew(exe, home)
271
+ c = await credential(home)
272
+ if (c && refused && c.key === was) throw unrenewed(home, r)
189
273
  }
190
- if (!c) throw new Error("Grok is not signed in; run `grok login`")
191
- if (c.expires && c.expires <= Date.now()) throw new Error("Grok's sign-in has expired; run `grok login`")
274
+ if (!c) throw new Error(notSignedIn(home))
275
+ 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}`)
276
+ if (c.expires && c.expires <= Date.now()) throw unrenewed(home, r)
192
277
  return c
193
278
  }
194
279
 
@@ -425,10 +510,9 @@ async function listModels(key) {
425
510
  await sign(headers, key)
426
511
  const res = await fetch(`${BASE}/models`, { headers })
427
512
  const text = await res.text()
428
- // a token Grok turned away before its time (signed out elsewhere) is a
429
- // sign-in gone, said as one past its time is: a move takes it along
430
- // untried rather than stopping on it
431
- if (res.status === 401) throw new Error("Grok's sign-in has expired; run `grok login`")
513
+ // a token Grok turned away before its time: the caller has Grok Build
514
+ // renew it and asks once more (models below)
515
+ if (res.status === 401) throw Object.assign(new Error("Grok turned the sign-in away"), { status: 401 })
432
516
  if (!res.ok) throw new Error(`Grok models: ${res.status} ${text.slice(0, 200)}`)
433
517
  const out = []
434
518
  for (const d of JSON.parse(text)?.data ?? []) {
@@ -548,7 +632,8 @@ function newHome() {
548
632
  async function signIn() {
549
633
  const exe = executable()
550
634
  if (!exe) throw new Error(NO_CLI)
551
- const own = !!credential(cliHome())
635
+ // a sign-in mid-write is one: the CLI's own home is left be
636
+ const own = await credential(cliHome()).then((c) => !!c, () => true)
552
637
  const home = own ? newHome() : cliHome()
553
638
  const { child, link, done, tail } = login(exe, home)
554
639
  const url = await Promise.race([link, new Promise((r) => setTimeout(() => r(""), LINK_WAIT))])
@@ -568,7 +653,7 @@ async function signIn() {
568
653
  method: "auto",
569
654
  callback: async () => {
570
655
  const r = await done
571
- const { c, why } = r.ok ? look(home) : { c: null, why: "" }
656
+ const { c, why } = r.ok ? await read(home) : { c: null, why: "" }
572
657
  // a sign-in beside the CLI's own needs to know whose it is, so the
573
658
  // same account signed in again replaces it instead of adding a second
574
659
  if (!c || (own && !c.who)) {
@@ -654,7 +739,7 @@ async function importCPA(inputs) {
654
739
  rmSync(home, { recursive: true, force: true })
655
740
  throw error
656
741
  }
657
- return saved(home, credential(home))
742
+ return saved(home, await credential(home))
658
743
  },
659
744
  }
660
745
  }
@@ -669,8 +754,8 @@ function saved(home, c) {
669
754
  async function current() {
670
755
  if (!executable()) throw new Error(NO_CLI)
671
756
  const home = cliHome()
672
- if (!credential(home)) throw new Error("Grok Build is not signed in; run `grok login`, or sign in with the device code")
673
- const c = await token(home, false)
757
+ if (!(await credential(home))) throw new Error("Grok Build is not signed in; run `grok login`, or sign in with the device code")
758
+ const c = await token(home)
674
759
  return {
675
760
  url: "",
676
761
  instructions: c.email ? `Grok Build is signed in as ${c.email}.` : "Grok Build is signed in.",
@@ -729,7 +814,7 @@ async function usage(key) {
729
814
  } catch (e) {
730
815
  return { error: netError(url, e), windows: [] }
731
816
  }
732
- if (!res.ok) return { error: statusText(res.status), windows: [] }
817
+ if (!res.ok) return { error: statusText(res.status), windows: [], status: res.status }
733
818
  let data
734
819
  try {
735
820
  data = JSON.parse(text)
@@ -850,20 +935,21 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
850
935
  async refresh(auth) {
851
936
  const home = auth?.refresh
852
937
  if (auth?.type !== "oauth" || !home) return undefined
853
- let c = credential(home)
938
+ let c = await credential(home)
854
939
  // renewed already (by the CLI, or before a request), the store not
855
940
  // yet saying so
856
941
  const renewed = c && c.key !== auth.access && c.expires - Date.now() >= LEAD_MS
857
942
  const exe = executable()
943
+ let r
858
944
  if (!renewed && exe) {
859
- await renew(exe, home)
860
- c = credential(home)
945
+ r = await renew(exe, home)
946
+ c = await credential(home)
861
947
  }
862
948
  // the CLI holds no sign-in there any more (`grok logout`): one
863
949
  // has to be made again
864
- if (!c) throw Object.assign(new Error("Grok is not signed in; run `grok login`"), { signIn: "expired" })
950
+ if (!c) throw Object.assign(new Error(notSignedIn(home)), { signIn: "expired" })
865
951
  // the CLI couldn't renew it: tried again later
866
- if (exe && c.expires && c.expires <= Date.now()) throw new Error("Grok's sign-in has expired and Grok Build couldn't renew it")
952
+ if (exe && c.expires && c.expires <= Date.now()) throw unrenewed(home, r)
867
953
  if (c.key === auth.access && c.expires === auth.expires) return undefined
868
954
  // magpie saves what this gives
869
955
  const out = { access: c.key, expires: c.expires }
@@ -889,10 +975,9 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
889
975
  parsed = JSON.parse(body) ?? {}
890
976
  } catch {}
891
977
  }
892
- const c = await token(home, false)
978
+ let c = await token(home)
893
979
  await remember(auth, c)
894
980
  const headers = new Headers(req.headers)
895
- await sign(headers, c.key)
896
981
  const asked = modelOf(parsed.model)
897
982
  if (asked.model) {
898
983
  headers.set("x-grok-model-override", asked.model)
@@ -903,11 +988,45 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
903
988
  }
904
989
  if (asked.window) headers.set("x-grok-context-window", String(asked.window))
905
990
  if (typeof parsed.prompt_cache_key === "string" && parsed.prompt_cache_key) headers.set("x-grok-conv-id", parsed.prompt_cache_key)
991
+ // Grok Build asks the proxy to watch every Responses stream for a
992
+ // model stuck repeating itself: without these the proxy cuts a
993
+ // loop only after ~4K tokens, and a looser one (a fence or a line
994
+ // over and over) runs to max_output_tokens (yetone/magpie#3594).
995
+ // The values are Grok Build 1.0.67's (doom_loop_recovery's
996
+ // max_threshold is the 64).
997
+ if (new URL(req.url).pathname.endsWith("/responses")) {
998
+ for (const [k, v] of LOOP_CHECKS) if (!headers.has(k)) headers.set(k, v)
999
+ }
906
1000
  headers.delete("content-length")
907
- // sent once, as the built-in sent it: Grok's answer goes on as
908
- // it came, the account kept, as the built-in never marked a Grok
909
- // account lapsed nor cleared one
910
- const res = await fetch(req.url, { ...init, method: req.method, headers, body })
1001
+ const send = async (key) => {
1002
+ await sign(headers, key)
1003
+ return fetch(req.url, { ...init, method: req.method, headers, body })
1004
+ }
1005
+ // Grok's answer goes on as it came, the account kept, as the
1006
+ // built-in never marked a Grok account lapsed nor cleared one.
1007
+ // A token Grok turns away before its time (it can, ahead of
1008
+ // expires_at) is renewed by Grok Build and the request sent once
1009
+ // more; one Grok Build couldn't renew is a 401 saying so, and
1010
+ // what helps.
1011
+ let res = await send(c.key)
1012
+ if (res.status === 401 && (typeof body === "string" || body == null)) {
1013
+ try {
1014
+ c = await token(home, c.key)
1015
+ } catch (e) {
1016
+ const said = (await res.text().catch(() => "")).slice(0, 300)
1017
+ note(home, res)
1018
+ return kept(
1019
+ new Response(JSON.stringify({ error: { message: `${e.message}${said ? `. Grok said: ${said}` : ""}`, type: "authentication_error", code: "sign_in_unrenewed" } }), {
1020
+ status: 401,
1021
+ statusText: res.statusText,
1022
+ headers: { "content-type": "application/json" },
1023
+ }),
1024
+ )
1025
+ }
1026
+ await res.body?.cancel().catch(() => {})
1027
+ await remember(auth, c)
1028
+ res = await send(c.key)
1029
+ }
911
1030
  note(home, res)
912
1031
  return kept(res)
913
1032
  },
@@ -947,12 +1066,23 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
947
1066
  let c
948
1067
  try {
949
1068
  if (!auth || auth.type !== "oauth" || !auth.refresh) throw new Error("Grok is not signed in; run `grok login`")
950
- c = await token(auth.refresh, false)
1069
+ c = await token(auth.refresh)
951
1070
  } catch (e) {
952
1071
  return { error: e.message, windows: [], signIn: "kept" }
953
1072
  }
954
1073
  await remember(auth, c)
955
- const u = await usage(c.key)
1074
+ let u = await usage(c.key)
1075
+ // a token turned away is renewed once, as a request's is
1076
+ if (u.status === 401) {
1077
+ try {
1078
+ c = await token(auth.refresh, c.key)
1079
+ } catch (e) {
1080
+ return { error: e.message, windows: [], signIn: "kept" }
1081
+ }
1082
+ await remember(auth, c)
1083
+ u = await usage(c.key)
1084
+ }
1085
+ delete u.status
956
1086
  if (!u.error) u.windows = [...rateWindow(auth.refresh), ...u.windows]
957
1087
  return { ...u, signIn: "kept" }
958
1088
  },
@@ -965,7 +1095,18 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
965
1095
  if (!auth || auth.type !== "oauth" || !auth.refresh) return have
966
1096
  // a list Grok couldn't give is a failure, not the few configured:
967
1097
  // magpie keeps the list it had
968
- const list = await listModels((await token(auth.refresh, false)).key)
1098
+ let c = await token(auth.refresh)
1099
+ let list
1100
+ try {
1101
+ list = await listModels(c.key)
1102
+ } catch (e) {
1103
+ if (e?.status !== 401) throw e
1104
+ // turned away before its time: renewed once, as a request's is
1105
+ c = await token(auth.refresh, c.key)
1106
+ list = await listModels(c.key).catch((e) => {
1107
+ throw e?.status === 401 ? new Error(dead(auth.refresh)) : e
1108
+ })
1109
+ }
969
1110
  const base = have["grok-4.7"] ?? Object.values(have)[0] ?? {}
970
1111
  const out = {}
971
1112
  for (const m of list) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-grok-auth",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
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": "./index.mjs",