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

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 +13 -0
  2. package/index.mjs +169 -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
 
package/index.mjs CHANGED
@@ -128,11 +128,15 @@ function look(home) {
128
128
  } catch (e) {
129
129
  return { c: null, why: e?.code === "ENOENT" ? `there is no ${file}` : `${file} can't be read (${e?.code ?? e?.message})` }
130
130
  }
131
+ // an empty file, or one that isn't JSON, is most likely one the CLI is
132
+ // writing as it is read (it rewrites auth.json when it renews): torn
133
+ // says the read tells nothing, which read() tries again
134
+ if (!text.trim()) return { c: null, why: `${file} is empty`, torn: true }
131
135
  let all
132
136
  try {
133
137
  all = JSON.parse(text)
134
138
  } catch {
135
- return { c: null, why: `${file} isn't JSON` }
139
+ return { c: null, why: `${file} isn't JSON`, torn: true }
136
140
  }
137
141
  if (!all || typeof all !== "object" || Array.isArray(all)) return { c: null, why: `${file} holds no sign-in` }
138
142
  const keys = Object.keys(all).sort()
@@ -143,19 +147,91 @@ function look(home) {
143
147
  const email = typeof c.email === "string" ? c.email : ""
144
148
  const sub = cpaClaims(c.key)?.sub
145
149
  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: "" }
150
+ const got = { key: c.key, email, user, who: email || user, expires: Number.isFinite(t) ? t : 0, issuer: c.oidc_issuer ?? "" }
151
+ lastGood.set(home, got)
152
+ return { c: got, why: "" }
147
153
  }
148
154
  }
149
155
  return { c: null, why: keys.length ? `${file} has ${keys.join(", ")}, none with a token` : `${file} holds no sign-in` }
150
156
  }
151
157
 
152
- function credential(home) {
153
- return look(home).c
158
+ // lastGood is each home's last sign-in read whole.
159
+ const lastGood = new Map()
160
+ const TORN_TRIES = 6
161
+ const TORN_WAIT = 100
162
+
163
+ // read is look, a torn read (auth.json caught mid-write) tried again for
164
+ // about half a second; still torn, it is the last sign-in read whole there,
165
+ // as the CLI itself keeps its previous credentials when auth.json won't
166
+ // read ("auth reload: auth.json unreadable, keeping previous credentials").
167
+ // No lock is taken: the CLI's auth.json.lock is a flock it holds while it
168
+ // renews, which Node can't take, and a reader holding it could only hold a
169
+ // renewal back.
170
+ async function read(home) {
171
+ let r = look(home)
172
+ for (let i = 1; r.torn && i < TORN_TRIES; i++) {
173
+ await new Promise((ok) => setTimeout(ok, TORN_WAIT))
174
+ r = look(home)
175
+ }
176
+ if (r.torn && lastGood.has(home)) return { c: lastGood.get(home), why: "" }
177
+ return r
178
+ }
179
+
180
+ // credential is the sign-in in home, null when there is none. A file that
181
+ // stays torn, with nothing read there before, is unknown, not "not signed
182
+ // in": that is an error saying so.
183
+ async function credential(home) {
184
+ const r = await read(home)
185
+ 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`)
186
+ return r.c
187
+ }
188
+
189
+ // shared is whether home is Grok Build's own, which opening Grok Build
190
+ // renews; a home of this plugin's (a second account, an imported one) only
191
+ // this plugin's runs of the CLI ever touch.
192
+ function shared(home) {
193
+ return resolve(home) === resolve(cliHome())
194
+ }
195
+
196
+ // notSignedIn says a home holds no sign-in, and what makes one.
197
+ function notSignedIn(home) {
198
+ return shared(home)
199
+ ? "Grok is not signed in; run `grok login`"
200
+ : "Grok is not signed in for this account any more; add the account in magpie again"
201
+ }
202
+
203
+ // cliSaid is what a `grok models` that renewed nothing said: how it ended
204
+ // and its last line.
205
+ function cliSaid(r) {
206
+ if (!r) return ""
207
+ const last = (r.stderr || r.stdout || "").replace(ANSI, "").split("\n").map((l) => l.trim()).filter(Boolean).at(-1)?.slice(0, 200)
208
+ const how = !r.err ? "ran and left the same token" : r.err.killed ? "timed out" : `exited ${r.err.code ?? "with an error"}`
209
+ return ` (grok models ${how}${last ? `: ${last}` : ""})`
210
+ }
211
+
212
+ // unrenewed is a token Grok turned away, or one past its end, that Grok
213
+ // Build, run in its home, didn't replace: the CLI couldn't renew it (xAI's renewal failing, or
214
+ // a refresh token used up elsewhere), which signing in with `grok login`
215
+ // in ~/.grok doesn't help where the account's home is the plugin's own.
216
+ function unrenewed(home, r) {
217
+ const how = shared(home)
218
+ ? "open Grok Build and send it a message, which renews the sign-in magpie reads"
219
+ : "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"
220
+ return Object.assign(new Error(`Grok Build couldn't renew the sign-in${cliSaid(r)}; ${how}`), { unrenewed: true })
221
+ }
222
+
223
+ // dead is a token Grok turned away even as Grok Build had just renewed it.
224
+ function dead(home) {
225
+ return shared(home)
226
+ ? "Grok turned away Grok Build's sign-in even after renewing it; run `grok login` to sign Grok Build in afresh"
227
+ : "Grok turned away this account's sign-in even after renewing it; add the account in magpie again"
154
228
  }
155
229
 
156
230
  function run(file, args, opts) {
157
231
  return new Promise((resolve) => {
158
- execFile(file, args, { timeout: 30000, ...opts }, (err, stdout) => resolve({ err, stdout: String(stdout ?? "") }))
232
+ execFile(file, args, { timeout: 30000, ...opts }, (err, stdout, stderr) =>
233
+ resolve({ err, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") }),
234
+ )
159
235
  })
160
236
  }
161
237
 
@@ -178,17 +254,25 @@ function renew(exe, home) {
178
254
  }
179
255
 
180
256
  // 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)
257
+ // expire is first renewed by the CLI in its own home, and so is one Grok
258
+ // turned away: rejected is that token (or true for whatever home holds).
259
+ // A token on disk other than the one turned away was renewed already and
260
+ // is taken as it is; one the CLI's run leaves as it was is unrenewed,
261
+ // never "not signed in" nor "expired".
262
+ async function token(home, rejected = false) {
263
+ let c = await credential(home)
185
264
  const exe = executable()
186
- if (c && exe && (expired || c.expires - Date.now() < REFRESH_MARGIN)) {
187
- await renew(exe, home)
188
- c = credential(home)
265
+ const refused = !!c && (rejected === true || (typeof rejected === "string" && c.key === rejected))
266
+ let r
267
+ if (c && exe && (refused || c.expires - Date.now() < REFRESH_MARGIN)) {
268
+ const was = c.key
269
+ r = await renew(exe, home)
270
+ c = await credential(home)
271
+ if (c && refused && c.key === was) throw unrenewed(home, r)
189
272
  }
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`")
273
+ if (!c) throw new Error(notSignedIn(home))
274
+ 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}`)
275
+ if (c.expires && c.expires <= Date.now()) throw unrenewed(home, r)
192
276
  return c
193
277
  }
194
278
 
@@ -425,10 +509,9 @@ async function listModels(key) {
425
509
  await sign(headers, key)
426
510
  const res = await fetch(`${BASE}/models`, { headers })
427
511
  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`")
512
+ // a token Grok turned away before its time: the caller has Grok Build
513
+ // renew it and asks once more (models below)
514
+ if (res.status === 401) throw Object.assign(new Error("Grok turned the sign-in away"), { status: 401 })
432
515
  if (!res.ok) throw new Error(`Grok models: ${res.status} ${text.slice(0, 200)}`)
433
516
  const out = []
434
517
  for (const d of JSON.parse(text)?.data ?? []) {
@@ -548,7 +631,8 @@ function newHome() {
548
631
  async function signIn() {
549
632
  const exe = executable()
550
633
  if (!exe) throw new Error(NO_CLI)
551
- const own = !!credential(cliHome())
634
+ // a sign-in mid-write is one: the CLI's own home is left be
635
+ const own = await credential(cliHome()).then((c) => !!c, () => true)
552
636
  const home = own ? newHome() : cliHome()
553
637
  const { child, link, done, tail } = login(exe, home)
554
638
  const url = await Promise.race([link, new Promise((r) => setTimeout(() => r(""), LINK_WAIT))])
@@ -568,7 +652,7 @@ async function signIn() {
568
652
  method: "auto",
569
653
  callback: async () => {
570
654
  const r = await done
571
- const { c, why } = r.ok ? look(home) : { c: null, why: "" }
655
+ const { c, why } = r.ok ? await read(home) : { c: null, why: "" }
572
656
  // a sign-in beside the CLI's own needs to know whose it is, so the
573
657
  // same account signed in again replaces it instead of adding a second
574
658
  if (!c || (own && !c.who)) {
@@ -654,7 +738,7 @@ async function importCPA(inputs) {
654
738
  rmSync(home, { recursive: true, force: true })
655
739
  throw error
656
740
  }
657
- return saved(home, credential(home))
741
+ return saved(home, await credential(home))
658
742
  },
659
743
  }
660
744
  }
@@ -669,8 +753,8 @@ function saved(home, c) {
669
753
  async function current() {
670
754
  if (!executable()) throw new Error(NO_CLI)
671
755
  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)
756
+ if (!(await credential(home))) throw new Error("Grok Build is not signed in; run `grok login`, or sign in with the device code")
757
+ const c = await token(home)
674
758
  return {
675
759
  url: "",
676
760
  instructions: c.email ? `Grok Build is signed in as ${c.email}.` : "Grok Build is signed in.",
@@ -729,7 +813,7 @@ async function usage(key) {
729
813
  } catch (e) {
730
814
  return { error: netError(url, e), windows: [] }
731
815
  }
732
- if (!res.ok) return { error: statusText(res.status), windows: [] }
816
+ if (!res.ok) return { error: statusText(res.status), windows: [], status: res.status }
733
817
  let data
734
818
  try {
735
819
  data = JSON.parse(text)
@@ -850,20 +934,21 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
850
934
  async refresh(auth) {
851
935
  const home = auth?.refresh
852
936
  if (auth?.type !== "oauth" || !home) return undefined
853
- let c = credential(home)
937
+ let c = await credential(home)
854
938
  // renewed already (by the CLI, or before a request), the store not
855
939
  // yet saying so
856
940
  const renewed = c && c.key !== auth.access && c.expires - Date.now() >= LEAD_MS
857
941
  const exe = executable()
942
+ let r
858
943
  if (!renewed && exe) {
859
- await renew(exe, home)
860
- c = credential(home)
944
+ r = await renew(exe, home)
945
+ c = await credential(home)
861
946
  }
862
947
  // the CLI holds no sign-in there any more (`grok logout`): one
863
948
  // has to be made again
864
- if (!c) throw Object.assign(new Error("Grok is not signed in; run `grok login`"), { signIn: "expired" })
949
+ if (!c) throw Object.assign(new Error(notSignedIn(home)), { signIn: "expired" })
865
950
  // 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")
951
+ if (exe && c.expires && c.expires <= Date.now()) throw unrenewed(home, r)
867
952
  if (c.key === auth.access && c.expires === auth.expires) return undefined
868
953
  // magpie saves what this gives
869
954
  const out = { access: c.key, expires: c.expires }
@@ -889,10 +974,9 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
889
974
  parsed = JSON.parse(body) ?? {}
890
975
  } catch {}
891
976
  }
892
- const c = await token(home, false)
977
+ let c = await token(home)
893
978
  await remember(auth, c)
894
979
  const headers = new Headers(req.headers)
895
- await sign(headers, c.key)
896
980
  const asked = modelOf(parsed.model)
897
981
  if (asked.model) {
898
982
  headers.set("x-grok-model-override", asked.model)
@@ -904,10 +988,35 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
904
988
  if (asked.window) headers.set("x-grok-context-window", String(asked.window))
905
989
  if (typeof parsed.prompt_cache_key === "string" && parsed.prompt_cache_key) headers.set("x-grok-conv-id", parsed.prompt_cache_key)
906
990
  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 })
991
+ const send = async (key) => {
992
+ await sign(headers, key)
993
+ return fetch(req.url, { ...init, method: req.method, headers, body })
994
+ }
995
+ // Grok's answer goes on as it came, the account kept, as the
996
+ // built-in never marked a Grok account lapsed nor cleared one.
997
+ // A token Grok turns away before its time (it can, ahead of
998
+ // expires_at) is renewed by Grok Build and the request sent once
999
+ // more; one Grok Build couldn't renew is a 401 saying so, and
1000
+ // what helps.
1001
+ let res = await send(c.key)
1002
+ if (res.status === 401 && (typeof body === "string" || body == null)) {
1003
+ try {
1004
+ c = await token(home, c.key)
1005
+ } catch (e) {
1006
+ const said = (await res.text().catch(() => "")).slice(0, 300)
1007
+ note(home, res)
1008
+ return kept(
1009
+ new Response(JSON.stringify({ error: { message: `${e.message}${said ? `. Grok said: ${said}` : ""}`, type: "authentication_error", code: "sign_in_unrenewed" } }), {
1010
+ status: 401,
1011
+ statusText: res.statusText,
1012
+ headers: { "content-type": "application/json" },
1013
+ }),
1014
+ )
1015
+ }
1016
+ await res.body?.cancel().catch(() => {})
1017
+ await remember(auth, c)
1018
+ res = await send(c.key)
1019
+ }
911
1020
  note(home, res)
912
1021
  return kept(res)
913
1022
  },
@@ -947,12 +1056,23 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
947
1056
  let c
948
1057
  try {
949
1058
  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)
1059
+ c = await token(auth.refresh)
951
1060
  } catch (e) {
952
1061
  return { error: e.message, windows: [], signIn: "kept" }
953
1062
  }
954
1063
  await remember(auth, c)
955
- const u = await usage(c.key)
1064
+ let u = await usage(c.key)
1065
+ // a token turned away is renewed once, as a request's is
1066
+ if (u.status === 401) {
1067
+ try {
1068
+ c = await token(auth.refresh, c.key)
1069
+ } catch (e) {
1070
+ return { error: e.message, windows: [], signIn: "kept" }
1071
+ }
1072
+ await remember(auth, c)
1073
+ u = await usage(c.key)
1074
+ }
1075
+ delete u.status
956
1076
  if (!u.error) u.windows = [...rateWindow(auth.refresh), ...u.windows]
957
1077
  return { ...u, signIn: "kept" }
958
1078
  },
@@ -965,7 +1085,18 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
965
1085
  if (!auth || auth.type !== "oauth" || !auth.refresh) return have
966
1086
  // a list Grok couldn't give is a failure, not the few configured:
967
1087
  // magpie keeps the list it had
968
- const list = await listModels((await token(auth.refresh, false)).key)
1088
+ let c = await token(auth.refresh)
1089
+ let list
1090
+ try {
1091
+ list = await listModels(c.key)
1092
+ } catch (e) {
1093
+ if (e?.status !== 401) throw e
1094
+ // turned away before its time: renewed once, as a request's is
1095
+ c = await token(auth.refresh, c.key)
1096
+ list = await listModels(c.key).catch((e) => {
1097
+ throw e?.status === 401 ? new Error(dead(auth.refresh)) : e
1098
+ })
1099
+ }
969
1100
  const base = have["grok-4.7"] ?? Object.values(have)[0] ?? {}
970
1101
  const out = {}
971
1102
  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.1",
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",