@magpie-community/opencode-grok-auth 0.1.0

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 +62 -0
  2. package/index.mjs +450 -0
  3. package/package.json +16 -0
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # @magpie-community/opencode-grok-auth
2
+
3
+ Grok with a SuperGrok or X Premium+ subscription, through the sign-in of
4
+ xAI's [Grok Build CLI](https://x.ai/cli). Provider id: `grok`.
5
+
6
+ It needs Grok Build installed:
7
+
8
+ ```sh
9
+ curl -fsSL https://x.ai/cli/install.sh | bash # macOS, Linux
10
+ irm https://x.ai/cli/install.ps1 | iex # Windows
11
+ ```
12
+
13
+ ## Sign in
14
+
15
+ - **Sign in with Grok Build (device code)** runs `grok login --device-auth`
16
+ and opens the page it prints. Approve the sign-in there, and the CLI
17
+ finishes it.
18
+ - If the CLI isn't signed in yet, the sign-in goes to the CLI's own home
19
+ (`GROK_HOME`, else `~/.grok`), as if you had run `grok login`.
20
+ - If it is signed in, the sign-in goes to a home of this plugin's,
21
+ `$XDG_CONFIG_HOME/opencode-grok-auth/<random>` (else under
22
+ `~/.config`). Grok Build's own sign-in stays as it is.
23
+ - **Use Grok Build's current sign-in** takes the account the CLI is
24
+ signed in to, with nothing to approve.
25
+
26
+ ## Where the sign-in is kept
27
+
28
+ The CLI keeps the sign-in in its home, as `auth.json`. OpenCode (or
29
+ magpie) keeps where that home is, the token and its expiry.
30
+
31
+ The plugin only reads `auth.json`: the CLI's refresh gives a new token
32
+ each time. When the token is 5 minutes from expiring, or a request is
33
+ refused with 401, the plugin runs `grok models` in that home, so the CLI
34
+ renews it, then reads it again.
35
+
36
+ ## Requests
37
+
38
+ Requests go to `https://cli-chat-proxy.grok.com/v1`, OpenAI's Responses
39
+ API (`@ai-sdk/openai`), signed as the CLI signs them:
40
+
41
+ - `Authorization: Bearer <token>`
42
+ - `x-xai-token-auth: xai-grok-cli`
43
+ - `x-grok-client-identifier: grok-shell`
44
+ - `x-grok-client-mode: headless`
45
+ - `x-grok-client-version` and `User-Agent: grok-shell/<version> (<os>; <arch>)`.
46
+ The version is 1.0.41, or the installed CLI's if it is newer.
47
+ - `x-grok-model-override`: the request's model.
48
+ - `x-grok-conv-id`: the request's `prompt_cache_key`.
49
+
50
+ The backend turns away some of what a request may carry, so the plugin
51
+ leaves these out:
52
+
53
+ - tools of types it doesn't take (a freeform `apply_patch`, namespaces)
54
+ - `external_web_access` on web search
55
+ - a `tool_choice` naming a dropped type
56
+ - a reasoning item's `"content": null`
57
+
58
+ ## Models
59
+
60
+ Grok 4.7 until signed in. Signed in, the models are the ones the account
61
+ lists at `/v1/models` (Responses models only), each with its context
62
+ window and its reasoning efforts as variants.
package/index.mjs ADDED
@@ -0,0 +1,450 @@
1
+ // Grok (SuperGrok / X Premium+) through the Grok Build CLI's own sign-in.
2
+ //
3
+ // The CLI (https://x.ai/cli) signs in with a device code and keeps the
4
+ // sign-in in its home (GROK_HOME, else ~/.grok) as auth.json. This plugin
5
+ // only reads that file: the CLI refreshes the token, which changes each
6
+ // time, so a token about to expire is renewed by running the CLI there
7
+ // (`grok models`), never by the plugin itself. Requests go to the CLI's
8
+ // backend, which speaks OpenAI's Responses API, signed as the CLI signs
9
+ // them.
10
+ import { spawn, execFile } from "node:child_process"
11
+ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"
12
+ import { homedir } from "node:os"
13
+ import { delimiter, dirname, isAbsolute, join } from "node:path"
14
+ import { randomBytes } from "node:crypto"
15
+
16
+ const PROVIDER = "grok"
17
+ const BASE = "https://cli-chat-proxy.grok.com/v1"
18
+ const CLIENT_VERSION = "1.0.41"
19
+ const REFRESH_MARGIN = 5 * 60 * 1000
20
+ const LINK_WAIT = 30 * 1000
21
+ const INSTALL = process.platform === "win32" ? "irm https://x.ai/cli/install.ps1 | iex" : "curl -fsSL https://x.ai/cli/install.sh | bash"
22
+
23
+ // the tool types Grok's backend takes; it turns the whole request away over another
24
+ const TOOLS = new Set(["function", "web_search", "x_search", "image_generation", "collections_search", "file_search",
25
+ "code_execution", "code_interpreter", "mcp", "shell", "tool_search"])
26
+
27
+ const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g
28
+ const LINK = /https:\/\/\S+/
29
+
30
+ // ---- the CLI ------------------------------------------------------------------
31
+
32
+ // cliHome is where the CLI keeps its own sign-in and settings.
33
+ function cliHome() {
34
+ return process.env.GROK_HOME || join(homedir(), ".grok")
35
+ }
36
+
37
+ // ownHomes is where this plugin keeps a sign-in made beside the CLI's own.
38
+ function ownHomes() {
39
+ return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "opencode-grok-auth")
40
+ }
41
+
42
+ function isFile(p) {
43
+ try {
44
+ return statSync(p).isFile()
45
+ } catch {
46
+ return false
47
+ }
48
+ }
49
+
50
+ // isGrokBuild tells xAI's grok from any other program by that name: its
51
+ // installer keeps it under the grok home.
52
+ function isGrokBuild(p) {
53
+ let real = p
54
+ try {
55
+ real = realpathSync(p)
56
+ } catch {}
57
+ return real.replaceAll("\\", "/").toLowerCase().includes("/.grok/")
58
+ }
59
+
60
+ // executable finds the CLI, first to last: the installer's bin
61
+ // (GROK_BIN_DIR, GROK_HOME/bin, ~/.grok/bin), each folder on PATH, then
62
+ // ~/.local/bin; those two only when it is really Grok Build.
63
+ function executable() {
64
+ const name = process.platform === "win32" ? "grok.exe" : "grok"
65
+ const home = homedir()
66
+ const seen = new Set()
67
+ const out = []
68
+ const add = (dir, own) => {
69
+ if (!dir || !isAbsolute(dir)) return
70
+ const p = join(dir, name)
71
+ const k = process.platform === "win32" ? p.toLowerCase() : p
72
+ if (seen.has(k)) return
73
+ seen.add(k)
74
+ out.push({ p, own })
75
+ }
76
+ add(process.env.GROK_BIN_DIR, true)
77
+ add(join(cliHome(), "bin"), true)
78
+ if (home) add(join(home, ".grok", "bin"), true)
79
+ for (const d of (process.env.PATH ?? "").split(delimiter)) add(d.trim(), false)
80
+ if (home) add(join(home, ".local", "bin"), false)
81
+ for (const c of out) if (isFile(c.p) && (c.own || isGrokBuild(c.p))) return c.p
82
+ return ""
83
+ }
84
+
85
+ // envFor runs the CLI as the user runs it, in the given home.
86
+ function envFor(home) {
87
+ const env = {}
88
+ for (const [k, v] of Object.entries(process.env)) {
89
+ if (["GROK_HOME", "GROK_AUTH_PROVIDER_COMMAND", "GROK_AUTH_EXPIRED"].includes(k.toUpperCase())) continue
90
+ env[k] = v
91
+ }
92
+ env.GROK_HOME = home
93
+ return env
94
+ }
95
+
96
+ // credential is the sign-in the CLI keeps in home: the first, by key, with a token.
97
+ function credential(home) {
98
+ let all
99
+ try {
100
+ all = JSON.parse(readFileSync(join(home, "auth.json"), "utf8"))
101
+ } catch {
102
+ return null
103
+ }
104
+ if (!all || typeof all !== "object") return null
105
+ for (const k of Object.keys(all).sort()) {
106
+ const c = all[k]
107
+ if (c && typeof c.key === "string" && c.key) {
108
+ const t = Date.parse(c.expires_at ?? "")
109
+ return { key: c.key, email: c.email ?? "", expires: Number.isFinite(t) ? t : 0, issuer: c.oidc_issuer ?? "" }
110
+ }
111
+ }
112
+ return null
113
+ }
114
+
115
+ function run(file, args, opts) {
116
+ return new Promise((resolve) => {
117
+ execFile(file, args, { timeout: 30000, ...opts }, (err, stdout) => resolve({ err, stdout: String(stdout ?? "") }))
118
+ })
119
+ }
120
+
121
+ let refreshing = Promise.resolve()
122
+
123
+ // token is the CLI's sign-in in home with a token still good. One about to
124
+ // expire (or that a request found expired) is first renewed by the CLI in
125
+ // its own home: a `grok models` there renews it as any use of the CLI does.
126
+ async function token(home, expired) {
127
+ let c = credential(home)
128
+ const exe = executable()
129
+ if (c && exe && (expired || c.expires - Date.now() < REFRESH_MARGIN)) {
130
+ const done = refreshing.then(() => run(exe, ["models"], { cwd: dirname(home), env: envFor(home) }))
131
+ refreshing = done.catch(() => {})
132
+ await done
133
+ c = credential(home)
134
+ }
135
+ if (!c) throw new Error("Grok is not signed in; run `grok login`")
136
+ if (c.expires && c.expires <= Date.now()) throw new Error("Grok's sign-in has expired; run `grok login`")
137
+ return c
138
+ }
139
+
140
+ let version = { v: CLIENT_VERSION, at: 0 }
141
+
142
+ // clientVersion is the CLI version the requests say they come from, unless
143
+ // the installed one is newer: without it the backend calls the CLI outdated.
144
+ async function clientVersion() {
145
+ if (Date.now() - version.at < 10 * 60 * 1000) return version.v
146
+ let v = CLIENT_VERSION
147
+ const exe = executable()
148
+ if (exe) {
149
+ const { err, stdout } = await run(exe, ["--version"], { timeout: 5000 }) // "grok 1.0.41 (4220f3b224a6)"
150
+ const got = !err && stdout.match(/\d+\.\d+\.\d+/)?.[0]
151
+ if (got && newer(got, v)) v = got
152
+ }
153
+ version = { v, at: Date.now() }
154
+ return v
155
+ }
156
+
157
+ function newer(a, b) {
158
+ const x = a.split(".").map(Number), y = b.split(".").map(Number)
159
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i]
160
+ return false
161
+ }
162
+
163
+ // headers say a request comes from the Grok CLI.
164
+ async function sign(headers, key) {
165
+ const v = await clientVersion()
166
+ const os = process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : process.platform
167
+ const arch = { arm64: "aarch64", x64: "x86_64", ia32: "386" }[process.arch] ?? process.arch
168
+ headers.set("Authorization", `Bearer ${key}`)
169
+ headers.set("x-grok-client-version", v)
170
+ headers.set("x-xai-token-auth", "xai-grok-cli")
171
+ headers.set("x-grok-client-identifier", "grok-shell")
172
+ headers.set("x-grok-client-mode", "headless")
173
+ headers.set("User-Agent", `grok-shell/${v} (${os}; ${arch})`)
174
+ }
175
+
176
+ // rewrite leaves out what Grok's backend doesn't take: tools of other
177
+ // types (a freeform apply_patch, a namespace of sub-agent tools), a web
178
+ // search's external_web_access, a tool_choice naming a dropped type, and a
179
+ // reasoning item's "content": null, beside which it can't read the
180
+ // encrypted reasoning.
181
+ function rewrite(body) {
182
+ if (typeof body !== "string" || (!body.includes('"tools"') && !body.includes('"reasoning"'))) return body
183
+ let m
184
+ try {
185
+ m = JSON.parse(body)
186
+ } catch {
187
+ return body
188
+ }
189
+ if (!m || typeof m !== "object" || Array.isArray(m)) return body
190
+ let dirty = false
191
+ if (Array.isArray(m.tools)) {
192
+ m.tools = m.tools.filter((t) => {
193
+ if (!t || typeof t !== "object") return true
194
+ if (!TOOLS.has(t.type)) {
195
+ dirty = true
196
+ return false
197
+ }
198
+ if ("external_web_access" in t) {
199
+ delete t.external_web_access
200
+ dirty = true
201
+ }
202
+ return true
203
+ })
204
+ if (m.tool_choice && typeof m.tool_choice === "object" && !TOOLS.has(m.tool_choice.type)) {
205
+ delete m.tool_choice
206
+ dirty = true
207
+ }
208
+ }
209
+ for (const it of Array.isArray(m.input) ? m.input : []) {
210
+ if (it && it.type === "reasoning" && "content" in it && it.content === null) {
211
+ delete it.content
212
+ dirty = true
213
+ }
214
+ }
215
+ return dirty ? JSON.stringify(m) : body
216
+ }
217
+
218
+ // ---- models -------------------------------------------------------------------
219
+
220
+ const DEFAULT_MODELS = {
221
+ "grok-4.7": { name: "Grok 4.7", attachment: true, reasoning: true, tool_call: true, modalities: { input: ["text", "image"], output: ["text"] } },
222
+ }
223
+
224
+ // listModels is what the account can use, as the CLI's backend lists it:
225
+ // Responses models only, each with its context window and efforts
226
+ // (listed hardest first, kept easiest first).
227
+ async function listModels(key) {
228
+ const headers = new Headers()
229
+ await sign(headers, key)
230
+ const res = await fetch(`${BASE}/models`, { headers })
231
+ const text = await res.text()
232
+ if (!res.ok) throw new Error(`Grok models: ${res.status} ${text.slice(0, 200)}`)
233
+ const out = []
234
+ for (const d of JSON.parse(text)?.data ?? []) {
235
+ if (!d?.id || (d.api_backend && d.api_backend !== "responses")) continue
236
+ const efforts = (d.reasoning_efforts ?? []).map((e) => e?.value).filter(Boolean).reverse()
237
+ out.push({ id: d.id, name: d.name || d.id, context: d.context_window ?? 0, efforts })
238
+ }
239
+ if (!out.length) throw new Error("Grok listed no models")
240
+ return out
241
+ }
242
+
243
+ // ---- sign-in ------------------------------------------------------------------
244
+
245
+ // login runs `grok login --device-auth` in home and hands on the first link
246
+ // it prints; done is settled when the command is.
247
+ function login(exe, home, own) {
248
+ const child = spawn(exe, ["login", "--device-auth"], {
249
+ cwd: homedir(),
250
+ env: own ? envFor(home) : process.env,
251
+ stdio: ["ignore", "pipe", "pipe"],
252
+ })
253
+ const tail = []
254
+ let buf = ""
255
+ let found
256
+ const link = new Promise((resolve) => (found = resolve))
257
+ const onData = (chunk) => {
258
+ buf += chunk.toString()
259
+ let i
260
+ while ((i = buf.indexOf("\n")) >= 0) {
261
+ const line = buf.slice(0, i).replace(/\r$/, "").replace(ANSI, "").trim()
262
+ buf = buf.slice(i + 1)
263
+ if (line) tail.push(line)
264
+ const u = line.match(LINK)?.[0]
265
+ if (u) found(u)
266
+ }
267
+ }
268
+ child.stdout.on("data", onData)
269
+ child.stderr.on("data", onData)
270
+ const done = new Promise((resolve) => {
271
+ child.on("error", (e) => resolve({ ok: false, why: e.message }))
272
+ child.on("close", (code) => {
273
+ const rest = buf.replace(ANSI, "").trim()
274
+ if (rest) {
275
+ tail.push(rest)
276
+ const u = rest.match(LINK)?.[0]
277
+ if (u) found(u)
278
+ }
279
+ found("")
280
+ resolve({ ok: code === 0, why: tail.at(-1) ?? "grok login didn't finish" })
281
+ })
282
+ })
283
+ return { child, link, done }
284
+ }
285
+
286
+ function newHome() {
287
+ const home = join(ownHomes(), randomBytes(9).toString("base64url").replace(/[-_]/g, "").toLowerCase())
288
+ mkdirSync(home, { recursive: true, mode: 0o700 })
289
+ return home
290
+ }
291
+
292
+ // signIn signs in with the CLI's device code: in the CLI's own home when
293
+ // that isn't signed in, else in a home of this plugin's, so the CLI's own
294
+ // sign-in stays as it is.
295
+ async function signIn() {
296
+ const exe = executable()
297
+ if (!exe) throw new Error(`install Grok Build first: ${INSTALL}`)
298
+ const own = !!credential(cliHome())
299
+ const home = own ? newHome() : cliHome()
300
+ const { child, link, done } = login(exe, home, own)
301
+ const url = await Promise.race([link, new Promise((r) => setTimeout(() => r(""), LINK_WAIT))])
302
+ if (!url) {
303
+ child.kill()
304
+ if (own) rmSync(home, { recursive: true, force: true })
305
+ throw new Error("grok login gave no link to open")
306
+ }
307
+ return {
308
+ url,
309
+ instructions: "Approve the sign-in on the page; Grok Build finishes it.",
310
+ method: "auto",
311
+ callback: async () => {
312
+ const r = await done
313
+ const c = r.ok ? credential(home) : null
314
+ if (!c || (own && !c.email)) {
315
+ if (own) rmSync(home, { recursive: true, force: true })
316
+ return { type: "failed", error: r.ok ? "grok login finished without an account" : r.why }
317
+ }
318
+ return saved(home, c)
319
+ },
320
+ }
321
+ }
322
+
323
+ // saved is the sign-in as OpenCode keeps it: refresh is the home the CLI
324
+ // keeps it in, access the token it had then.
325
+ function saved(home, c) {
326
+ return { type: "success", refresh: home, access: c.key, expires: c.expires, accountId: c.email }
327
+ }
328
+
329
+ // current takes the sign-in the CLI already has, as it is.
330
+ async function current() {
331
+ if (!executable()) throw new Error(`install Grok Build first: ${INSTALL}`)
332
+ const home = cliHome()
333
+ if (!credential(home)) throw new Error("Grok Build is not signed in; run `grok login`, or sign in with the device code")
334
+ const c = await token(home, false)
335
+ return {
336
+ url: "",
337
+ instructions: c.email ? `Grok Build is signed in as ${c.email}.` : "Grok Build is signed in.",
338
+ method: "auto",
339
+ callback: async () => saved(home, c),
340
+ }
341
+ }
342
+
343
+ // ---- the plugin ---------------------------------------------------------------
344
+
345
+ export const GrokAuthPlugin = async ({ client }) => {
346
+ const remember = async (auth, c) => {
347
+ if (auth.access === c.key && auth.expires === c.expires) return
348
+ try {
349
+ await client.auth.set({ path: { id: PROVIDER }, body: { ...auth, access: c.key, expires: c.expires, accountId: c.email || auth.accountId } })
350
+ } catch {}
351
+ }
352
+
353
+ return {
354
+ config: async (cfg) => {
355
+ cfg.provider ??= {}
356
+ cfg.provider[PROVIDER] ??= {
357
+ name: "Grok (SuperGrok)",
358
+ npm: "@ai-sdk/openai",
359
+ api: BASE,
360
+ models: DEFAULT_MODELS,
361
+ }
362
+ },
363
+
364
+ auth: {
365
+ provider: PROVIDER,
366
+ async loader(getAuth) {
367
+ const auth = await getAuth()
368
+ if (!auth || auth.type !== "oauth") return {}
369
+ return {
370
+ baseURL: BASE,
371
+ apiKey: "grok",
372
+ async fetch(input, init) {
373
+ const auth = await getAuth()
374
+ const home = auth?.refresh
375
+ if (!home) throw new Error("Grok is not signed in; run `grok login`")
376
+ const req = new Request(input, init)
377
+ const body = rewrite(init?.body)
378
+ let parsed = {}
379
+ if (typeof body === "string") {
380
+ try {
381
+ parsed = JSON.parse(body) ?? {}
382
+ } catch {}
383
+ }
384
+ const send = async (expired) => {
385
+ const c = await token(home, expired)
386
+ await remember(auth, c)
387
+ const headers = new Headers(req.headers)
388
+ await sign(headers, c.key)
389
+ if (typeof parsed.model === "string" && parsed.model) headers.set("x-grok-model-override", parsed.model)
390
+ if (typeof parsed.prompt_cache_key === "string" && parsed.prompt_cache_key) headers.set("x-grok-conv-id", parsed.prompt_cache_key)
391
+ headers.delete("content-length")
392
+ return fetch(req.url, { ...init, method: req.method, headers, body })
393
+ }
394
+ const res = await send(false)
395
+ if (res.status !== 401) return res
396
+ return send(true)
397
+ },
398
+ }
399
+ },
400
+ methods: [
401
+ {
402
+ type: "oauth",
403
+ label: "Sign in with Grok Build (device code)",
404
+ authorize: signIn,
405
+ },
406
+ {
407
+ type: "oauth",
408
+ label: "Use Grok Build's current sign-in",
409
+ authorize: current,
410
+ },
411
+ ],
412
+ },
413
+
414
+ provider: {
415
+ id: PROVIDER,
416
+ async models(provider, { auth } = {}) {
417
+ const have = provider?.models ?? {}
418
+ if (!auth || auth.type !== "oauth" || !auth.refresh) return have
419
+ let list
420
+ try {
421
+ list = await listModels((await token(auth.refresh, false)).key)
422
+ } catch {
423
+ return have
424
+ }
425
+ const base = have["grok-4.7"] ?? Object.values(have)[0] ?? {}
426
+ const out = {}
427
+ for (const m of list) {
428
+ const was = have[m.id] ?? base
429
+ out[m.id] = {
430
+ ...was,
431
+ id: m.id,
432
+ providerID: provider.id,
433
+ name: m.name,
434
+ api: { ...(was.api ?? {}), id: m.id, url: BASE, npm: "@ai-sdk/openai" },
435
+ limit: { ...(was.limit ?? {}), context: m.context || was.limit?.context || 0, output: was.limit?.output ?? 0 },
436
+ capabilities: {
437
+ ...(was.capabilities ?? {}),
438
+ reasoning: m.efforts.length > 0 || !!was.capabilities?.reasoning,
439
+ attachment: true,
440
+ toolcall: true,
441
+ input: { ...(was.capabilities?.input ?? {}), text: true, image: true },
442
+ },
443
+ variants: Object.fromEntries(m.efforts.map((e) => [e, { reasoningEffort: e }])),
444
+ }
445
+ }
446
+ return out
447
+ },
448
+ },
449
+ }
450
+ }
package/package.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@magpie-community/opencode-grok-auth",
3
+ "version": "0.1.0",
4
+ "description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in",
5
+ "type": "module",
6
+ "main": "./index.mjs",
7
+ "exports": "./index.mjs",
8
+ "files": ["index.mjs", "README.md"],
9
+ "keywords": ["opencode", "opencode-plugin", "grok", "xai", "supergrok"],
10
+ "license": "MIT",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/magpie-community/plugins.git",
14
+ "directory": "packages/grok"
15
+ }
16
+ }