@magpie-community/opencode-grok-auth 0.1.18 → 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.
- package/README.md +44 -0
- package/index.mjs +191 -42
- 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
|
|
|
@@ -95,6 +108,37 @@ Plain Codex collaboration items (`agent_message`) reach Grok as user
|
|
|
95
108
|
messages, with their sender, recipient and content preserved. Sealed or
|
|
96
109
|
unrecognized content stays unchanged; the plugin does not decrypt tasks.
|
|
97
110
|
|
|
111
|
+
### Native X search (optional)
|
|
112
|
+
|
|
113
|
+
In magpie, open the Grok provider, turn on **Native X search** under
|
|
114
|
+
**Plugin options**, and save. It is off by default; changes apply to the
|
|
115
|
+
next request without restarting or signing in again.
|
|
116
|
+
|
|
117
|
+
When enabled, the plugin offers Grok its native `x_search` tool. Grok
|
|
118
|
+
decides whether to search; enabling it does not force a search on every
|
|
119
|
+
request. Existing function tools and X search filters are preserved, and
|
|
120
|
+
an existing `x_search` is not duplicated. Explicit choices such as `none`,
|
|
121
|
+
`required`, a named tool, or `allowed_tools` never gain another tool.
|
|
122
|
+
|
|
123
|
+
The option applies to Responses requests, including Chat Completions,
|
|
124
|
+
Anthropic Messages and Gemini requests that magpie converts to Responses,
|
|
125
|
+
in streaming and non-streaming mode. Use magpie with the fix for
|
|
126
|
+
[yetone/magpie#3110](https://github.com/yetone/magpie/issues/3110) so that
|
|
127
|
+
those clients' tool-disable choices reach the plugin.
|
|
128
|
+
|
|
129
|
+
For compatibility with older gateways, a request that reaches the plugin
|
|
130
|
+
with neither tools nor a `tool_choice` is left unchanged. This can happen
|
|
131
|
+
when magpie translates a client's automatic choice on an empty tool list.
|
|
132
|
+
To use X search through a translated API, send at least one function tool;
|
|
133
|
+
the plugin adds X search alongside it. An explicit tool-disable choice
|
|
134
|
+
always takes precedence.
|
|
135
|
+
|
|
136
|
+
This uses the existing `grok` provider's login, models and quota reporting;
|
|
137
|
+
no extra plugin is needed. It applies to that provider's models when the
|
|
138
|
+
upstream supports X search, not to Grok models served through Cursor or
|
|
139
|
+
another provider. Report problems in
|
|
140
|
+
[this repository](https://github.com/magpie-community/plugins/issues).
|
|
141
|
+
|
|
98
142
|
## Models
|
|
99
143
|
|
|
100
144
|
Grok 4.7 until signed in. Signed in, the models are the ones the account
|
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
|
-
|
|
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
|
-
|
|
153
|
-
|
|
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
|
|
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
|
|
182
|
-
//
|
|
183
|
-
|
|
184
|
-
|
|
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
|
-
|
|
187
|
-
|
|
188
|
-
|
|
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(
|
|
191
|
-
if (c.expires && c.expires <= Date.now()) throw new Error(
|
|
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
|
|
|
@@ -323,8 +407,8 @@ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v)
|
|
|
323
407
|
// (Codex desktop's codex_app automation_update) are folded to an object,
|
|
324
408
|
// which Grok turns away otherwise: "tool parameter root must be an object
|
|
325
409
|
// type" (magpie#1271).
|
|
326
|
-
function rewrite(body) {
|
|
327
|
-
if (typeof body !== "string" || (!body.includes('"tools"') && !body.includes('"tool_choice"') && !body.includes('"reasoning"') && !body.includes('"agent_message"'))) return body
|
|
410
|
+
function rewrite(body, xSearch = false) {
|
|
411
|
+
if (typeof body !== "string" || (!xSearch && !body.includes('"tools"') && !body.includes('"tool_choice"') && !body.includes('"reasoning"') && !body.includes('"agent_message"'))) return body
|
|
328
412
|
let m
|
|
329
413
|
try {
|
|
330
414
|
m = JSON.parse(body)
|
|
@@ -332,6 +416,10 @@ function rewrite(body) {
|
|
|
332
416
|
return body
|
|
333
417
|
}
|
|
334
418
|
if (!m || typeof m !== "object" || Array.isArray(m)) return body
|
|
419
|
+
// Read the client's choice before dropping unsupported tools or choices.
|
|
420
|
+
const search = xSearch && (m.tool_choice == null || m.tool_choice === "auto") &&
|
|
421
|
+
(m.tools == null || Array.isArray(m.tools)) &&
|
|
422
|
+
(m.tool_choice === "auto" || Array.isArray(m.tools) && m.tools.length > 0)
|
|
335
423
|
let dirty = false
|
|
336
424
|
if (Array.isArray(m.tools)) {
|
|
337
425
|
m.tools = m.tools.filter((t) => {
|
|
@@ -359,6 +447,12 @@ function rewrite(body) {
|
|
|
359
447
|
dirty = true
|
|
360
448
|
}
|
|
361
449
|
}
|
|
450
|
+
// No choice and no tools can mean a translated "none" on older gateways.
|
|
451
|
+
if (search && (m.tool_choice === "auto" || m.tools?.length) && !m.tools?.some((t) => t?.type === "x_search")) {
|
|
452
|
+
m.tools ??= []
|
|
453
|
+
m.tools.push({ type: "x_search" })
|
|
454
|
+
dirty = true
|
|
455
|
+
}
|
|
362
456
|
if (Object.hasOwn(m, "tool_choice") && !(Array.isArray(m.tools) && m.tools.length)) {
|
|
363
457
|
delete m.tool_choice
|
|
364
458
|
dirty = true
|
|
@@ -415,10 +509,9 @@ async function listModels(key) {
|
|
|
415
509
|
await sign(headers, key)
|
|
416
510
|
const res = await fetch(`${BASE}/models`, { headers })
|
|
417
511
|
const text = await res.text()
|
|
418
|
-
// a token Grok turned away before its time
|
|
419
|
-
//
|
|
420
|
-
|
|
421
|
-
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 })
|
|
422
515
|
if (!res.ok) throw new Error(`Grok models: ${res.status} ${text.slice(0, 200)}`)
|
|
423
516
|
const out = []
|
|
424
517
|
for (const d of JSON.parse(text)?.data ?? []) {
|
|
@@ -538,7 +631,8 @@ function newHome() {
|
|
|
538
631
|
async function signIn() {
|
|
539
632
|
const exe = executable()
|
|
540
633
|
if (!exe) throw new Error(NO_CLI)
|
|
541
|
-
|
|
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)
|
|
542
636
|
const home = own ? newHome() : cliHome()
|
|
543
637
|
const { child, link, done, tail } = login(exe, home)
|
|
544
638
|
const url = await Promise.race([link, new Promise((r) => setTimeout(() => r(""), LINK_WAIT))])
|
|
@@ -558,7 +652,7 @@ async function signIn() {
|
|
|
558
652
|
method: "auto",
|
|
559
653
|
callback: async () => {
|
|
560
654
|
const r = await done
|
|
561
|
-
const { c, why } = r.ok ?
|
|
655
|
+
const { c, why } = r.ok ? await read(home) : { c: null, why: "" }
|
|
562
656
|
// a sign-in beside the CLI's own needs to know whose it is, so the
|
|
563
657
|
// same account signed in again replaces it instead of adding a second
|
|
564
658
|
if (!c || (own && !c.who)) {
|
|
@@ -644,7 +738,7 @@ async function importCPA(inputs) {
|
|
|
644
738
|
rmSync(home, { recursive: true, force: true })
|
|
645
739
|
throw error
|
|
646
740
|
}
|
|
647
|
-
return saved(home, credential(home))
|
|
741
|
+
return saved(home, await credential(home))
|
|
648
742
|
},
|
|
649
743
|
}
|
|
650
744
|
}
|
|
@@ -659,8 +753,8 @@ function saved(home, c) {
|
|
|
659
753
|
async function current() {
|
|
660
754
|
if (!executable()) throw new Error(NO_CLI)
|
|
661
755
|
const home = cliHome()
|
|
662
|
-
if (!credential(home)) throw new Error("Grok Build is not signed in; run `grok login`, or sign in with the device code")
|
|
663
|
-
const c = await token(home
|
|
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)
|
|
664
758
|
return {
|
|
665
759
|
url: "",
|
|
666
760
|
instructions: c.email ? `Grok Build is signed in as ${c.email}.` : "Grok Build is signed in.",
|
|
@@ -719,7 +813,7 @@ async function usage(key) {
|
|
|
719
813
|
} catch (e) {
|
|
720
814
|
return { error: netError(url, e), windows: [] }
|
|
721
815
|
}
|
|
722
|
-
if (!res.ok) return { error: statusText(res.status), windows: [] }
|
|
816
|
+
if (!res.ok) return { error: statusText(res.status), windows: [], status: res.status }
|
|
723
817
|
let data
|
|
724
818
|
try {
|
|
725
819
|
data = JSON.parse(text)
|
|
@@ -803,7 +897,7 @@ function kept(res) {
|
|
|
803
897
|
|
|
804
898
|
// ---- the plugin ---------------------------------------------------------------
|
|
805
899
|
|
|
806
|
-
export const GrokAuthPlugin = async ({ client }) => {
|
|
900
|
+
export const GrokAuthPlugin = async ({ client, magpie }) => {
|
|
807
901
|
const remember = async (auth, c) => {
|
|
808
902
|
if (auth.access === c.key && auth.expires === c.expires) return
|
|
809
903
|
try {
|
|
@@ -824,6 +918,13 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
824
918
|
|
|
825
919
|
auth: {
|
|
826
920
|
provider: PROVIDER,
|
|
921
|
+
options: [
|
|
922
|
+
{
|
|
923
|
+
key: "x_search",
|
|
924
|
+
label: "Native X search",
|
|
925
|
+
description: "Offers X search to Grok when tools are automatic. Keeps existing search filters and explicit tool choices. Grok decides whether to search.",
|
|
926
|
+
},
|
|
927
|
+
],
|
|
827
928
|
// magpie renews the sign-in LEAD_MS before its end, once for the
|
|
828
929
|
// account, before its requests, models and usage ask for it: the CLI
|
|
829
930
|
// renews it in its home, as before a request, and what it gives is
|
|
@@ -833,20 +934,21 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
833
934
|
async refresh(auth) {
|
|
834
935
|
const home = auth?.refresh
|
|
835
936
|
if (auth?.type !== "oauth" || !home) return undefined
|
|
836
|
-
let c = credential(home)
|
|
937
|
+
let c = await credential(home)
|
|
837
938
|
// renewed already (by the CLI, or before a request), the store not
|
|
838
939
|
// yet saying so
|
|
839
940
|
const renewed = c && c.key !== auth.access && c.expires - Date.now() >= LEAD_MS
|
|
840
941
|
const exe = executable()
|
|
942
|
+
let r
|
|
841
943
|
if (!renewed && exe) {
|
|
842
|
-
await renew(exe, home)
|
|
843
|
-
c = credential(home)
|
|
944
|
+
r = await renew(exe, home)
|
|
945
|
+
c = await credential(home)
|
|
844
946
|
}
|
|
845
947
|
// the CLI holds no sign-in there any more (`grok logout`): one
|
|
846
948
|
// has to be made again
|
|
847
|
-
if (!c) throw Object.assign(new Error(
|
|
949
|
+
if (!c) throw Object.assign(new Error(notSignedIn(home)), { signIn: "expired" })
|
|
848
950
|
// the CLI couldn't renew it: tried again later
|
|
849
|
-
if (exe && c.expires && c.expires <= Date.now()) throw
|
|
951
|
+
if (exe && c.expires && c.expires <= Date.now()) throw unrenewed(home, r)
|
|
850
952
|
if (c.key === auth.access && c.expires === auth.expires) return undefined
|
|
851
953
|
// magpie saves what this gives
|
|
852
954
|
const out = { access: c.key, expires: c.expires }
|
|
@@ -864,17 +966,17 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
864
966
|
const home = auth?.refresh
|
|
865
967
|
if (!home) throw new Error("Grok is not signed in; run `grok login`")
|
|
866
968
|
const req = new Request(input, init)
|
|
867
|
-
|
|
969
|
+
const search = new URL(req.url).pathname.endsWith("/responses") && magpie?.option?.(PROVIDER, "x_search") === true
|
|
970
|
+
let body = rewrite(bodyText(init?.body), search)
|
|
868
971
|
let parsed = {}
|
|
869
972
|
if (typeof body === "string") {
|
|
870
973
|
try {
|
|
871
974
|
parsed = JSON.parse(body) ?? {}
|
|
872
975
|
} catch {}
|
|
873
976
|
}
|
|
874
|
-
|
|
977
|
+
let c = await token(home)
|
|
875
978
|
await remember(auth, c)
|
|
876
979
|
const headers = new Headers(req.headers)
|
|
877
|
-
await sign(headers, c.key)
|
|
878
980
|
const asked = modelOf(parsed.model)
|
|
879
981
|
if (asked.model) {
|
|
880
982
|
headers.set("x-grok-model-override", asked.model)
|
|
@@ -886,10 +988,35 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
886
988
|
if (asked.window) headers.set("x-grok-context-window", String(asked.window))
|
|
887
989
|
if (typeof parsed.prompt_cache_key === "string" && parsed.prompt_cache_key) headers.set("x-grok-conv-id", parsed.prompt_cache_key)
|
|
888
990
|
headers.delete("content-length")
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
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
|
+
}
|
|
893
1020
|
note(home, res)
|
|
894
1021
|
return kept(res)
|
|
895
1022
|
},
|
|
@@ -929,12 +1056,23 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
929
1056
|
let c
|
|
930
1057
|
try {
|
|
931
1058
|
if (!auth || auth.type !== "oauth" || !auth.refresh) throw new Error("Grok is not signed in; run `grok login`")
|
|
932
|
-
c = await token(auth.refresh
|
|
1059
|
+
c = await token(auth.refresh)
|
|
933
1060
|
} catch (e) {
|
|
934
1061
|
return { error: e.message, windows: [], signIn: "kept" }
|
|
935
1062
|
}
|
|
936
1063
|
await remember(auth, c)
|
|
937
|
-
|
|
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
|
|
938
1076
|
if (!u.error) u.windows = [...rateWindow(auth.refresh), ...u.windows]
|
|
939
1077
|
return { ...u, signIn: "kept" }
|
|
940
1078
|
},
|
|
@@ -947,7 +1085,18 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
947
1085
|
if (!auth || auth.type !== "oauth" || !auth.refresh) return have
|
|
948
1086
|
// a list Grok couldn't give is a failure, not the few configured:
|
|
949
1087
|
// magpie keeps the list it had
|
|
950
|
-
|
|
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
|
+
}
|
|
951
1100
|
const base = have["grok-4.7"] ?? Object.values(have)[0] ?? {}
|
|
952
1101
|
const out = {}
|
|
953
1102
|
for (const m of list) {
|
package/package.json
CHANGED