@magpie-community/opencode-grok-auth 0.2.9 → 0.2.10

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 +33 -0
  2. package/index.mjs +219 -17
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -107,6 +107,39 @@ it, then reads it again:
107
107
  read whole there stands, as the CLI itself keeps its previous one. It is
108
108
  never taken as signed out. The plugin takes no `auth.json.lock`.
109
109
 
110
+ ### Grok Build's unified build
111
+
112
+ Grok Build can update itself to its unified build (`grok 2.0.5
113
+ [unified]`, `agent-host-<version>-<os>-<arch>` in `~/.grok/downloads`).
114
+ That build keeps its own sign-in: its `grok models` exits 0 and leaves
115
+ `auth.json` as it was, so it renews nothing magpie reads, and its
116
+ `grok login` makes no sign-in there.
117
+
118
+ When the `grok` the plugin finds is the unified build, it renews and signs
119
+ in with the newest native `grok-1.x` build left in `~/.grok/downloads`
120
+ (made for this system, runnable) instead. It knows the unified build by
121
+ the name `grok` links to (`~/.grok/bin/grok → agent-host →
122
+ ../downloads/agent-host-…`, or a `GROK_BIN_DIR` link to it), by a
123
+ `grok.exe` that is a copy of it on Windows, or by Grok Build's
124
+ `channel-switch.json` saying it switched that `bin` to `agent-host`. A
125
+ `grok` that links to or copies a native build is run as before, whatever
126
+ that record says.
127
+
128
+ With no native build left, the failure says so, and how to put the
129
+ previous build back and keep it:
130
+
131
+ ```sh
132
+ curl -fsSL https://x.ai/cli/install.sh | bash -s 1.0.92
133
+ ```
134
+
135
+ ```powershell
136
+ & ([scriptblock]::Create((irm https://x.ai/cli/install.ps1))) -Version 1.0.92
137
+ ```
138
+
139
+ then `auto_update = false` in `~/.grok/config.toml` (Grok Build's home,
140
+ `GROK_HOME` if set). The version is the one `channel-switch.json` names
141
+ as the build before the switch.
142
+
110
143
  ## Requests
111
144
 
112
145
  Requests go to `https://cli-chat-proxy.grok.com/v1`, OpenAI's Responses
package/index.mjs CHANGED
@@ -8,9 +8,9 @@
8
8
  // backend, which speaks OpenAI's Responses API, signed as the CLI signs
9
9
  // them.
10
10
  import { spawn, execFile } from "node:child_process"
11
- import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"
11
+ import { accessSync, constants as fsc, existsSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"
12
12
  import { homedir } from "node:os"
13
- import { delimiter, dirname, isAbsolute, join, resolve } from "node:path"
13
+ import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path"
14
14
  import { randomBytes } from "node:crypto"
15
15
  import { STATUS_CODES } from "node:http"
16
16
 
@@ -110,6 +110,195 @@ function executable() {
110
110
  return ""
111
111
  }
112
112
 
113
+ // ---- Grok Build's unified build (plugins#1771) ---------------------------------
114
+ //
115
+ // Grok Build updates itself (auto_update in ~/.grok/config.toml), and a
116
+ // rollout can move it to its "unified" build, agent-host-<version>-<os>-<arch>
117
+ // in ~/.grok/downloads: ~/.grok/bin/grok is pointed at it (bin/grok →
118
+ // agent-host → ../downloads/agent-host-2.0.5-macos-aarch64; on Windows,
119
+ // which has no symlinks, bin\grok.exe is a copy of it), and
120
+ // ~/.grok/channel-switch.json records the switch: {"previous_target":
121
+ // "../downloads/grok-1.0.92-macos-aarch64", "binary": "agent-host",
122
+ // "channel": "unified", "rollout": true}. That build keeps its own
123
+ // sign-in and never reads nor renews auth.json: its `grok models` exits 0
124
+ // with the token as it was, so a renewal through it renews nothing. The
125
+ // native build it replaced stays in downloads (grok-1.0.92-macos-aarch64,
126
+ // .exe on Windows) and renews auth.json as before, so the sign-in is renewed
127
+ // with the newest such build. With none left, the failure says what
128
+ // happened and how to put the native build back.
129
+
130
+ // the names Grok Build's downloads go by here: grok-<version>-<os>-<arch>
131
+ // for a native build, agent-host-<version>-<os>-<arch> for the unified one
132
+ function platform() {
133
+ const os = process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : process.platform
134
+ const own = { arm64: "aarch64", x64: "x86_64" }[process.arch] ?? process.arch
135
+ // a Mac runs either (Rosetta), and a Node under Rosetta says x64 on Apple silicon
136
+ return { os, arches: os === "macos" ? [...new Set([own, "aarch64", "x86_64"])] : [own] }
137
+ }
138
+ const NATIVE = /^grok-(1)\.(\d+)\.(\d+)(?:-[a-z0-9._]+)?-([a-z]+)-([a-z0-9_]+)$/
139
+ const UNIFIED = /^agent-host(?:-|$)/
140
+
141
+ // buildName is a file's name as Grok Build names its builds: lower case,
142
+ // without Windows' .exe
143
+ const buildName = (p) => basename(p).toLowerCase().replace(/\.exe$/, "")
144
+
145
+ // links are the paths p goes through, p first and the file it ends at last
146
+ function links(p) {
147
+ const out = [p]
148
+ for (let i = 0; i < 40; i++) {
149
+ let to
150
+ try {
151
+ to = readlinkSync(p)
152
+ } catch {
153
+ break
154
+ }
155
+ p = resolve(dirname(p), to)
156
+ out.push(p)
157
+ }
158
+ return out
159
+ }
160
+
161
+ // downloadDirs are where Grok Build keeps its builds for the grok at exe:
162
+ // the folder its link ends in, the downloads beside its bin, and those of
163
+ // the CLI's home and of ~/.grok
164
+ function downloadDirs(exe, chain) {
165
+ const dirs = []
166
+ const add = (d) => {
167
+ if (d && !dirs.includes(d)) dirs.push(d)
168
+ }
169
+ for (const p of chain.slice(1)) if (basename(dirname(p)).toLowerCase() === "downloads") add(dirname(p))
170
+ add(join(dirname(dirname(exe)), "downloads"))
171
+ add(join(cliHome(), "downloads"))
172
+ if (homedir()) add(join(homedir(), ".grok", "downloads"))
173
+ return dirs
174
+ }
175
+
176
+ function runnable(p) {
177
+ if (!isFile(p)) return false
178
+ if (process.platform === "win32") return /\.exe$/i.test(p)
179
+ try {
180
+ accessSync(p, fsc.X_OK)
181
+ return true
182
+ } catch {
183
+ return false
184
+ }
185
+ }
186
+
187
+ // builds are the builds in dirs made for this system: the native ones
188
+ // with a version, newest first, the unified ones, and plain, the native
189
+ // grok-<os>-<arch> the installer downloads, of no version said
190
+ function builds(dirs) {
191
+ const { os, arches } = platform()
192
+ const out = []
193
+ for (const d of dirs) {
194
+ let names
195
+ try {
196
+ names = readdirSync(d)
197
+ } catch {
198
+ continue
199
+ }
200
+ for (const n of names) {
201
+ if (process.platform === "win32" && !/\.exe$/i.test(n)) continue
202
+ const name = buildName(n)
203
+ const m = name.match(NATIVE)
204
+ if (m && m[4] === os && arches.includes(m[5])) out.push({ p: join(d, n), name, kind: "native", v: [1, Number(m[2]), Number(m[3])], arch: arches.indexOf(m[5]) })
205
+ else if (UNIFIED.test(name) && name.includes(`-${os}-`)) out.push({ p: join(d, n), name, kind: "unified" })
206
+ else if (arches.some((a) => name === `grok-${os}-${a}`)) out.push({ p: join(d, n), name, kind: "plain" })
207
+ }
208
+ }
209
+ const of = (k) => out.filter((b) => b.kind === k)
210
+ const native = of("native").sort((a, b) => a.arch - b.arch || b.v[1] - a.v[1] || b.v[2] - a.v[2] || a.name.length - b.name.length)
211
+ return { native, unified: of("unified"), plain: of("plain") }
212
+ }
213
+
214
+ // switchRecord is the channel switch Grok Build recorded beside the bin
215
+ // the grok at exe is in, null when there is none or it can't be read
216
+ function switchRecord(exe) {
217
+ const homes = [dirname(dirname(exe)), cliHome()]
218
+ if (homedir()) homes.push(join(homedir(), ".grok"))
219
+ for (const h of homes) {
220
+ try {
221
+ const r = JSON.parse(readFileSync(join(h, "channel-switch.json"), "utf8"))
222
+ if (r && typeof r === "object") return { ...r, at: h }
223
+ } catch {}
224
+ }
225
+ return null
226
+ }
227
+
228
+ const same = (a, b) => {
229
+ try {
230
+ const x = statSync(a), y = statSync(b)
231
+ return (x.ino && x.ino === y.ino && x.dev === y.dev) || x.size === y.size
232
+ } catch {
233
+ return false
234
+ }
235
+ }
236
+
237
+ // unified says whether the grok at exe is the unified build, and how it
238
+ // is known: by a name on its way to the file it runs (a symlink into
239
+ // downloads), else by which build in downloads it is a copy of (Windows),
240
+ // else, for the grok in a bin Grok Build manages, by channel-switch.json.
241
+ // A name or copy of a native build is native, whatever the record says
242
+ // (the previous build put back by hand).
243
+ function unified(exe) {
244
+ const chain = links(exe)
245
+ // the first build named on the way decides; the last unified name is
246
+ // the build itself (bin/agent-host → ../downloads/agent-host-2.0.5-…)
247
+ let by = ""
248
+ for (const p of chain) {
249
+ const name = buildName(p)
250
+ if (UNIFIED.test(name)) by = basename(p)
251
+ else if (!by && name.startsWith("grok-")) return null
252
+ }
253
+ const dirs = downloadDirs(exe, chain)
254
+ const all = builds(dirs)
255
+ const rec = switchRecord(exe)
256
+ const found = (build) => ({ build, dirs, native: all.native.filter((b) => runnable(b.p)), record: rec })
257
+ if (by) return found(by)
258
+ if (chain.length === 1) {
259
+ const u = all.unified.find((b) => same(exe, b.p))
260
+ const n = [...all.native, ...all.plain].some((b) => same(exe, b.p))
261
+ if (u && !n) return found(basename(u.p))
262
+ if (n) return null
263
+ }
264
+ // a copy of no build in downloads: the record says, for the grok in a
265
+ // bin Grok Build manages, and only where a native build can take over,
266
+ // as the record may be older than a build put back by hand
267
+ if (!rec) return null
268
+ const bin = dirname(exe)
269
+ const managed = [join(rec.at, "bin"), process.env.GROK_BIN_DIR].some((d) => d && resolve(d) === resolve(bin))
270
+ const says = String(rec.binary ?? "").toLowerCase() === "agent-host" || String(rec.channel ?? "").toLowerCase() === "unified"
271
+ const r = managed && says ? found(rec.binary ? String(rec.binary) : "the unified build") : null
272
+ return r?.native.length ? r : null
273
+ }
274
+
275
+ // cli is the Grok Build that renews a sign-in and signs one in: the grok
276
+ // found (executable), or for the unified build the newest native build in
277
+ // downloads. exe is "" when there is none to run; found is the grok found
278
+ // and rolled what is known of the unified build it is.
279
+ function cli() {
280
+ const found = executable()
281
+ if (!found) return { exe: "", found, rolled: null }
282
+ const rolled = unified(found)
283
+ if (!rolled) return { exe: found, found, rolled: null }
284
+ return { exe: rolled.native[0]?.p ?? "", found, rolled }
285
+ }
286
+
287
+ // rolledOut is what a sign-in that only the unified build is left to
288
+ // renew says: what happened, and how to put the native build back and keep
289
+ // it. The version named is the one the switch replaced, else 1.0.92, which
290
+ // renewed (plugins#1771).
291
+ function rolledOut(found, rolled, what = "renew") {
292
+ const prev = buildName(String(rolled.record?.previous_target ?? "")).match(NATIVE)
293
+ const v = prev ? `1.${prev[2]}.${prev[3]}` : "1.0.92"
294
+ const pin = process.platform === "win32"
295
+ ? `& ([scriptblock]::Create((irm https://x.ai/cli/install.ps1))) -Version ${v}`
296
+ : `curl -fsSL https://x.ai/cli/install.sh | bash -s ${v}`
297
+ const config = join(rolled.record?.at ?? cliHome(), "config.toml")
298
+ const doing = what === "renew" ? "can't renew the xAI sign-in magpie reads" : "can't make the xAI sign-in magpie reads"
299
+ return `Grok Build updated itself to its unified build (${rolled.build} at ${found}), which keeps its own sign-in and ${doing}, and no native grok-1.x build is left in ${rolled.dirs[0]} to use instead. Put the previous build back with \`${pin}\`, which points ${found} at it again, then keep it by setting auto_update = false in ${config}`
300
+ }
301
+
113
302
  // envFor runs the CLI as the user runs it, in the given home. GROK_AUTH_PATH
114
303
  // goes too: grok 1.0.62 keeps its sign-in at that file instead of
115
304
  // home/auth.json, where this plugin reads it, so a login with it set
@@ -214,14 +403,15 @@ function notSignedIn(home) {
214
403
  }
215
404
 
216
405
  // cliSaid is what a `grok models` that renewed nothing said: how it ended
217
- // and its last line.
406
+ // and its last line. A native build run for the unified one (plugins#1771)
407
+ // is named by its own name.
218
408
  function cliSaid(r) {
219
409
  if (!r) return ""
220
- if (r.late) return ` (grok models was still running after ${waits.renew / 1000}s)`
410
+ if (r.late) return ` (${r.name ?? "grok"} models was still running after ${waits.renew / 1000}s)`
221
411
  const last = (r.stderr || r.stdout || "").replace(ANSI, "").split("\n").map((l) => l.trim()).filter(Boolean).at(-1)?.slice(0, 200)
222
412
  const how = !r.err ? "ran and left the same token" : r.err.killed ? "timed out" : `exited ${r.err.code ?? "with an error"}`
223
413
  const took = r.ms >= 1000 ? ` in ${Math.round(r.ms / 1000)}s` : ""
224
- return ` (grok models ${how}${took}${last ? `: ${last}` : ""})`
414
+ return ` (${r.name ?? "grok"} models ${how}${took}${last ? `: ${last}` : ""})`
225
415
  }
226
416
 
227
417
  // passing says a 401 on a token Grok Build left as it was is a refusal
@@ -251,9 +441,13 @@ function transient(c, r, said) {
251
441
  // Build, run in its home, didn't replace: the CLI couldn't renew it (xAI's renewal failing, or
252
442
  // a refresh token used up elsewhere), which signing in with `grok login`
253
443
  // in ~/.grok doesn't help where the account's home is the plugin's own.
254
- function unrenewed(home, r) {
444
+ // native is the native build run in place of the unified one, whose
445
+ // Grok Build renews nothing when opened (plugins#1771).
446
+ function unrenewed(home, r, native = "") {
255
447
  const how = shared(home)
256
- ? "open Grok Build and send it a message, which renews the sign-in magpie reads"
448
+ ? native
449
+ ? `run ${native} and send it a message, which renews the sign-in magpie reads (Grok Build itself runs its unified build now, which doesn't)`
450
+ : "open Grok Build and send it a message, which renews the sign-in magpie reads"
257
451
  : "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"
258
452
  return Object.assign(new Error(`Grok Build couldn't renew the sign-in${cliSaid(r)}; ${how}`), { unrenewed: true })
259
453
  }
@@ -291,7 +485,8 @@ const renewing = new Map()
291
485
  function renew(exe, home) {
292
486
  let r = renewing.get(home)
293
487
  if (!r) {
294
- r = refreshing.then(() => run(exe, ["models"], { cwd: dirname(home), env: envFor(home) })).finally(() => renewing.delete(home))
488
+ const name = buildName(exe)
489
+ r = refreshing.then(() => run(exe, ["models"], { cwd: dirname(home), env: envFor(home) })).then((x) => ({ ...x, name })).finally(() => renewing.delete(home))
295
490
  refreshing = r.catch(() => {})
296
491
  renewing.set(home, r)
297
492
  }
@@ -391,7 +586,8 @@ function signInEnded(home, r) {
391
586
  // not run again till its time (holding): what it met is the answer.
392
587
  async function token(home, rejected = false, said) {
393
588
  let c = await credential(home)
394
- const exe = executable()
589
+ const { exe, found, rolled } = cli()
590
+ const native = rolled ? exe : ""
395
591
  const refused = !!c && (rejected === true || (typeof rejected === "string" && c.key === rejected))
396
592
  let r
397
593
  if (c && exe && (refused || c.expires - Date.now() < REFRESH_MARGIN)) {
@@ -404,11 +600,13 @@ async function token(home, rejected = false, said) {
404
600
  settle(home, was, c, r)
405
601
  }
406
602
  if (c && failing.get(home)?.final && failing.get(home).key === c.key) throw told(home, c.key, signInEnded(home, r))
407
- if (c && refused && c.key === was) throw told(home, c.key, passing(c, r, said) ? transient(c, r, said) : unrenewed(home, r))
603
+ if (c && refused && c.key === was) throw told(home, c.key, passing(c, r, said) ? transient(c, r, said) : unrenewed(home, r, native))
408
604
  }
409
605
  if (!c) throw told(home, "", Object.assign(new Error(notSignedIn(home)), { final: true }))
410
- if (!exe && (refused || (c.expires && c.expires <= Date.now()))) throw told(home, c.key, new Error(`Grok turned the sign-in away and there is no Grok Build here to renew it; ${NO_CLI}`))
411
- if (c.expires && c.expires <= Date.now()) throw told(home, c.key, unrenewed(home, r))
606
+ if (!exe && (refused || (c.expires && c.expires <= Date.now()))) {
607
+ throw told(home, c.key, new Error(rolled ? rolledOut(found, rolled) : `Grok turned the sign-in away and there is no Grok Build here to renew it; ${NO_CLI}`))
608
+ }
609
+ if (c.expires && c.expires <= Date.now()) throw told(home, c.key, unrenewed(home, r, native))
412
610
  return c
413
611
  }
414
612
 
@@ -778,8 +976,10 @@ function newHome() {
778
976
  // that isn't signed in, else in a home of this plugin's, so the CLI's own
779
977
  // sign-in stays as it is.
780
978
  async function signIn() {
781
- const exe = executable()
782
- if (!exe) throw new Error(NO_CLI)
979
+ // the unified build keeps its own sign-in and writes no auth.json: the
980
+ // native build signs in instead, as it renews (plugins#1771)
981
+ const { exe, found, rolled } = cli()
982
+ if (!exe) throw new Error(rolled ? rolledOut(found, rolled, "sign in") : NO_CLI)
783
983
  // a sign-in mid-write is one: the CLI's own home is left be
784
984
  const own = await credential(cliHome()).then((c) => !!c, () => true)
785
985
  const home = own ? newHome() : cliHome()
@@ -1292,7 +1492,7 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1292
1492
  // renewed already (by the CLI, or before a request), the store not
1293
1493
  // yet saying so
1294
1494
  const renewed = c && c.key !== auth.access && c.expires - Date.now() >= LEAD_MS
1295
- const exe = executable()
1495
+ const { exe, found, rolled } = cli()
1296
1496
  let r
1297
1497
  // what failed is said to magpie once; said again it is nothing to
1298
1498
  // renew, so magpie's log isn't the same line every try (plugins#1711)
@@ -1316,7 +1516,9 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1316
1516
  // it cleared on a refusal for good): one has to be made again
1317
1517
  if (!c) return fail("", Object.assign(new Error(notSignedIn(home)), { final: true }))
1318
1518
  // the CLI couldn't renew it: tried again later, backing off
1319
- if (exe && c.expires && c.expires <= Date.now()) return fail(c.key, unrenewed(home, r))
1519
+ if (exe && c.expires && c.expires <= Date.now()) return fail(c.key, unrenewed(home, r, rolled ? exe : ""))
1520
+ // only the unified build is here, which can't renew it (plugins#1771)
1521
+ if (!exe && rolled && c.expires && c.expires <= Date.now()) return fail(c.key, new Error(rolledOut(found, rolled)))
1320
1522
  if (c.key === auth.access && c.expires === auth.expires) return undefined
1321
1523
  // magpie saves what this gives
1322
1524
  const out = { access: c.key, expires: c.expires }
@@ -1544,4 +1746,4 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1544
1746
  }
1545
1747
 
1546
1748
  // for tests
1547
- export const _internal = { sttRequest, sttAnswer, rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf, waits, backoff }
1749
+ export const _internal = { sttRequest, sttAnswer, rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf, waits, backoff, cli }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-grok-auth",
3
- "version": "0.2.9",
3
+ "version": "0.2.10",
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",