@magpie-community/opencode-grok-auth 0.2.8 → 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 +46 -3
  2. package/index.mjs +347 -28
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -89,14 +89,57 @@ it, then reads it again:
89
89
  - A request, model list or usage read turned away waits on the CLI's
90
90
  renewal 15 seconds at most. The run goes on, and the next one to ask
91
91
  takes what it gave.
92
- - When the CLI no longer holds a sign-in in that home (`grok logout`),
93
- the account has to be signed in again. When it couldn't renew a token
94
- that has ended, magpie tries again later.
92
+ - When the CLI no longer holds a sign-in in that home (`grok logout`, or
93
+ one it cleared after xAI refused it for good), or its run says only a
94
+ new sign-in helps (`Failed(ManualLogin)`, `needs a new sign-in`,
95
+ `invalid_grant`, a revoked refresh token), the sign-in has ended: magpie
96
+ shows the account as one to sign in again, and the CLI isn't run there
97
+ again until the home holds another token.
98
+ - Any other run that couldn't renew (no network, `Failed(SelfHealing)`) is
99
+ tried again later, backing off: 1 minute after the first failure, then
100
+ 2, 4 and so on, up to an hour between runs. Whatever asks meanwhile gets
101
+ the failure already met, without running the CLI. A renewal that works
102
+ starts the count again.
103
+ - magpie's log gets what failed once for each state (failing, ended), not
104
+ on every try.
95
105
  - An `auth.json` that is empty or not JSON is most likely one the CLI is
96
106
  writing: it is read again for about half a second, then the last sign-in
97
107
  read whole there stands, as the CLI itself keeps its previous one. It is
98
108
  never taken as signed out. The plugin takes no `auth.json.lock`.
99
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
+
100
143
  ## Requests
101
144
 
102
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,13 +485,95 @@ 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
  }
298
493
  return r
299
494
  }
300
495
 
496
+ // ---- renewals that fail (plugins#1711) -----------------------------------------
497
+ //
498
+ // A renewal that fails is not run again at once: the home's next run waits
499
+ // backoff.base, doubling with each failure in a row up to backoff.cap, and
500
+ // whatever asks meanwhile (magpie's auth.refresh, a model list, a request)
501
+ // is answered with the failure already met instead of running the CLI. A
502
+ // sign-in Grok ended for good (the CLI cleared it, or said it needs a new
503
+ // sign-in) is never run again: it is marked signIn "expired", which has
504
+ // magpie show the account as one to sign in again, until the home holds a
505
+ // token other than the one that failed (signed in again). What a failure
506
+ // says goes to magpie's log once for each state (failing, ended), not on
507
+ // every try: errors thrown again in a state already told are quiet, and
508
+ // auth.refresh and the model list keep those to themselves.
509
+ const backoff = { base: 60 * 1000, cap: 60 * 60 * 1000, now: () => Date.now() }
510
+ const failing = new Map() // home → { key, n, next, final, r, told }
511
+
512
+ // GONE are the words of a CLI run that ended the sign-in for good: the
513
+ // CLI's AuthRemedy that only a new sign-in helps (ManualLogin, ProviderLogin;
514
+ // SelfHealing passes by itself), its "the stored login needs a new
515
+ // sign-in", and an OAuth refusal of the refresh token. A run that couldn't
516
+ // reach xAI says none of these, and is tried again.
517
+ const GONE = /needs a new sign-in|Failed\((ManualLogin|ProviderLogin)|invalid_grant|refresh token (was |has been |is )?(revoked|invalid|expired)|not signed in/i
518
+
519
+ function gone(r) {
520
+ if (!r || r.late || !r.err || r.err.killed) return false
521
+ return GONE.test(`${r.stderr}\n${r.stdout}`.replace(ANSI, ""))
522
+ }
523
+
524
+ // holding is home's failure while it holds the CLI back: the sign-in
525
+ // there is still the one that failed (key), and it ended for good or its
526
+ // next try isn't due. A token other than the one that failed is a new
527
+ // state, and the failure is forgotten.
528
+ function holding(home, key) {
529
+ const t = failing.get(home)
530
+ if (!t) return null
531
+ if (t.key !== key) {
532
+ failing.delete(home)
533
+ return null
534
+ }
535
+ return t.final || backoff.now() < t.next ? t : null
536
+ }
537
+
538
+ // settle records how a run of the CLI in home went: a token other than was
539
+ // renewed it, and anything else is one more failure in a row.
540
+ function settle(home, was, c, r) {
541
+ if (c && c.key !== was) {
542
+ failing.delete(home)
543
+ return
544
+ }
545
+ const key = c?.key ?? ""
546
+ const had = failing.get(home)
547
+ const t = had?.key === key ? had : { key, n: 0, told: "" }
548
+ t.n++
549
+ t.r = r
550
+ t.final = !c || gone(r)
551
+ t.next = backoff.now() + Math.min(backoff.base * 2 ** (t.n - 1), backoff.cap)
552
+ failing.set(home, t)
553
+ }
554
+
555
+ // told is e, the failure of the sign-in key in home, quiet when its state
556
+ // was told already. One ended for good is marked for a new sign-in.
557
+ function told(home, key, e) {
558
+ let t = failing.get(home)
559
+ if (!t || t.key !== key) failing.set(home, (t = { key, n: 0, next: 0, told: "" }))
560
+ if (e.final) {
561
+ t.final = true
562
+ e.signIn = "expired"
563
+ }
564
+ const state = t.final ? "ended" : "failing"
565
+ if (t.told === state) e.quiet = true
566
+ else t.told = state
567
+ return e
568
+ }
569
+
570
+ // signInEnded is a sign-in Grok ended for good: what the CLI said, and
571
+ // what makes a new one.
572
+ function signInEnded(home, r) {
573
+ const how = shared(home) ? "run `grok login` to sign Grok Build in again" : "add the account in magpie again"
574
+ return Object.assign(new Error(`Grok ended this sign-in${cliSaid(r)}; ${how}. It isn't tried again until then`), { final: true })
575
+ }
576
+
301
577
  // token is the CLI's sign-in in home with a token still good. One about to
302
578
  // expire is first renewed by the CLI in its own home, and so is one Grok
303
579
  // turned away: rejected is that token (or true for whatever home holds).
@@ -306,21 +582,31 @@ function renew(exe, home) {
306
582
  // never "not signed in" nor "expired". said is what Grok answered the
307
583
  // token turned away with: a refusal that wasn't Grok's judgement of a
308
584
  // token still good is transient (passing). A renewal for a token turned
309
- // away is waited on waits.renew at most.
585
+ // away is waited on waits.renew at most. A renewal that failed lately is
586
+ // not run again till its time (holding): what it met is the answer.
310
587
  async function token(home, rejected = false, said) {
311
588
  let c = await credential(home)
312
- const exe = executable()
589
+ const { exe, found, rolled } = cli()
590
+ const native = rolled ? exe : ""
313
591
  const refused = !!c && (rejected === true || (typeof rejected === "string" && c.key === rejected))
314
592
  let r
315
593
  if (c && exe && (refused || c.expires - Date.now() < REFRESH_MARGIN)) {
316
594
  const was = c.key
317
- r = refused ? await within(renew(exe, home), waits.renew) : await renew(exe, home)
318
- c = await credential(home)
319
- if (c && refused && c.key === was) throw passing(c, r, said) ? transient(c, r, said) : unrenewed(home, r)
595
+ const held = holding(home, was)
596
+ if (held) r = held.r
597
+ else {
598
+ r = refused ? await within(renew(exe, home), waits.renew) : await renew(exe, home)
599
+ c = await credential(home)
600
+ settle(home, was, c, r)
601
+ }
602
+ if (c && failing.get(home)?.final && failing.get(home).key === c.key) throw told(home, c.key, signInEnded(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))
604
+ }
605
+ if (!c) throw told(home, "", Object.assign(new Error(notSignedIn(home)), { final: true }))
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}`))
320
608
  }
321
- if (!c) throw new Error(notSignedIn(home))
322
- 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}`)
323
- if (c.expires && c.expires <= Date.now()) throw unrenewed(home, r)
609
+ if (c.expires && c.expires <= Date.now()) throw told(home, c.key, unrenewed(home, r, native))
324
610
  return c
325
611
  }
326
612
 
@@ -690,8 +976,10 @@ function newHome() {
690
976
  // that isn't signed in, else in a home of this plugin's, so the CLI's own
691
977
  // sign-in stays as it is.
692
978
  async function signIn() {
693
- const exe = executable()
694
- 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)
695
983
  // a sign-in mid-write is one: the CLI's own home is left be
696
984
  const own = await credential(cliHome()).then((c) => !!c, () => true)
697
985
  const home = own ? newHome() : cliHome()
@@ -1204,17 +1492,33 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1204
1492
  // renewed already (by the CLI, or before a request), the store not
1205
1493
  // yet saying so
1206
1494
  const renewed = c && c.key !== auth.access && c.expires - Date.now() >= LEAD_MS
1207
- const exe = executable()
1495
+ const { exe, found, rolled } = cli()
1208
1496
  let r
1497
+ // what failed is said to magpie once; said again it is nothing to
1498
+ // renew, so magpie's log isn't the same line every try (plugins#1711)
1499
+ const fail = (key, e) => {
1500
+ told(home, key, e)
1501
+ if (e.quiet) return undefined
1502
+ throw e
1503
+ }
1209
1504
  if (!renewed && exe) {
1505
+ const was = c?.key ?? ""
1506
+ const held = holding(home, was)
1507
+ // failed lately: not run again till its time, nor ever once
1508
+ // Grok ended the sign-in
1509
+ if (held) return held.final ? fail(was, c ? signInEnded(home, held.r) : Object.assign(new Error(notSignedIn(home)), { final: true })) : undefined
1210
1510
  r = await renew(exe, home)
1211
1511
  c = await credential(home)
1512
+ settle(home, was, c, r)
1513
+ if (c && failing.get(home)?.final) return fail(c.key, signInEnded(home, r))
1212
1514
  }
1213
- // the CLI holds no sign-in there any more (`grok logout`): one
1214
- // has to be made again
1215
- if (!c) throw Object.assign(new Error(notSignedIn(home)), { signIn: "expired" })
1216
- // the CLI couldn't renew it: tried again later
1217
- if (exe && c.expires && c.expires <= Date.now()) throw unrenewed(home, r)
1515
+ // the CLI holds no sign-in there any more (`grok logout`, or one
1516
+ // it cleared on a refusal for good): one has to be made again
1517
+ if (!c) return fail("", Object.assign(new Error(notSignedIn(home)), { final: true }))
1518
+ // the CLI couldn't renew it: tried again later, backing off
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)))
1218
1522
  if (c.key === auth.access && c.expires === auth.expires) return undefined
1219
1523
  // magpie saves what this gives
1220
1524
  const out = { access: c.key, expires: c.expires }
@@ -1383,15 +1687,30 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1383
1687
  const have = provider?.models ?? {}
1384
1688
  if (!auth || auth.type !== "oauth" || !auth.refresh) return have
1385
1689
  // a list Grok couldn't give is a failure, not the few configured:
1386
- // magpie keeps the list it had
1387
- let c = await token(auth.refresh)
1690
+ // magpie keeps the list it had. A sign-in failure told once already
1691
+ // (plugins#1711) falls back saying nothing, so magpie's log doesn't
1692
+ // get the same line on every list
1693
+ const quietly = (e) => {
1694
+ if (!e?.quiet) throw e
1695
+ return { ...have, [Symbol.for("magpie.fellBack")]: true }
1696
+ }
1697
+ let c
1698
+ try {
1699
+ c = await token(auth.refresh)
1700
+ } catch (e) {
1701
+ return quietly(e)
1702
+ }
1388
1703
  let list
1389
1704
  try {
1390
1705
  list = await listModels(c.key)
1391
1706
  } catch (e) {
1392
1707
  if (e?.status !== 401) throw e
1393
1708
  // turned away before its time: renewed once, as a request's is
1394
- c = await token(auth.refresh, c.key, e.said)
1709
+ try {
1710
+ c = await token(auth.refresh, c.key, e.said)
1711
+ } catch (e) {
1712
+ return quietly(e)
1713
+ }
1395
1714
  list = await listModels(c.key).catch((e) => {
1396
1715
  throw e?.status === 401 ? new Error(dead(auth.refresh)) : e
1397
1716
  })
@@ -1427,4 +1746,4 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1427
1746
  }
1428
1747
 
1429
1748
  // for tests
1430
- export const _internal = { sttRequest, sttAnswer, rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf, waits }
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.8",
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",