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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +13 -3
  2. package/index.mjs +133 -16
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -89,9 +89,19 @@ 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
package/index.mjs CHANGED
@@ -298,6 +298,87 @@ function renew(exe, home) {
298
298
  return r
299
299
  }
300
300
 
301
+ // ---- renewals that fail (plugins#1711) -----------------------------------------
302
+ //
303
+ // A renewal that fails is not run again at once: the home's next run waits
304
+ // backoff.base, doubling with each failure in a row up to backoff.cap, and
305
+ // whatever asks meanwhile (magpie's auth.refresh, a model list, a request)
306
+ // is answered with the failure already met instead of running the CLI. A
307
+ // sign-in Grok ended for good (the CLI cleared it, or said it needs a new
308
+ // sign-in) is never run again: it is marked signIn "expired", which has
309
+ // magpie show the account as one to sign in again, until the home holds a
310
+ // token other than the one that failed (signed in again). What a failure
311
+ // says goes to magpie's log once for each state (failing, ended), not on
312
+ // every try: errors thrown again in a state already told are quiet, and
313
+ // auth.refresh and the model list keep those to themselves.
314
+ const backoff = { base: 60 * 1000, cap: 60 * 60 * 1000, now: () => Date.now() }
315
+ const failing = new Map() // home → { key, n, next, final, r, told }
316
+
317
+ // GONE are the words of a CLI run that ended the sign-in for good: the
318
+ // CLI's AuthRemedy that only a new sign-in helps (ManualLogin, ProviderLogin;
319
+ // SelfHealing passes by itself), its "the stored login needs a new
320
+ // sign-in", and an OAuth refusal of the refresh token. A run that couldn't
321
+ // reach xAI says none of these, and is tried again.
322
+ 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
323
+
324
+ function gone(r) {
325
+ if (!r || r.late || !r.err || r.err.killed) return false
326
+ return GONE.test(`${r.stderr}\n${r.stdout}`.replace(ANSI, ""))
327
+ }
328
+
329
+ // holding is home's failure while it holds the CLI back: the sign-in
330
+ // there is still the one that failed (key), and it ended for good or its
331
+ // next try isn't due. A token other than the one that failed is a new
332
+ // state, and the failure is forgotten.
333
+ function holding(home, key) {
334
+ const t = failing.get(home)
335
+ if (!t) return null
336
+ if (t.key !== key) {
337
+ failing.delete(home)
338
+ return null
339
+ }
340
+ return t.final || backoff.now() < t.next ? t : null
341
+ }
342
+
343
+ // settle records how a run of the CLI in home went: a token other than was
344
+ // renewed it, and anything else is one more failure in a row.
345
+ function settle(home, was, c, r) {
346
+ if (c && c.key !== was) {
347
+ failing.delete(home)
348
+ return
349
+ }
350
+ const key = c?.key ?? ""
351
+ const had = failing.get(home)
352
+ const t = had?.key === key ? had : { key, n: 0, told: "" }
353
+ t.n++
354
+ t.r = r
355
+ t.final = !c || gone(r)
356
+ t.next = backoff.now() + Math.min(backoff.base * 2 ** (t.n - 1), backoff.cap)
357
+ failing.set(home, t)
358
+ }
359
+
360
+ // told is e, the failure of the sign-in key in home, quiet when its state
361
+ // was told already. One ended for good is marked for a new sign-in.
362
+ function told(home, key, e) {
363
+ let t = failing.get(home)
364
+ if (!t || t.key !== key) failing.set(home, (t = { key, n: 0, next: 0, told: "" }))
365
+ if (e.final) {
366
+ t.final = true
367
+ e.signIn = "expired"
368
+ }
369
+ const state = t.final ? "ended" : "failing"
370
+ if (t.told === state) e.quiet = true
371
+ else t.told = state
372
+ return e
373
+ }
374
+
375
+ // signInEnded is a sign-in Grok ended for good: what the CLI said, and
376
+ // what makes a new one.
377
+ function signInEnded(home, r) {
378
+ const how = shared(home) ? "run `grok login` to sign Grok Build in again" : "add the account in magpie again"
379
+ return Object.assign(new Error(`Grok ended this sign-in${cliSaid(r)}; ${how}. It isn't tried again until then`), { final: true })
380
+ }
381
+
301
382
  // token is the CLI's sign-in in home with a token still good. One about to
302
383
  // expire is first renewed by the CLI in its own home, and so is one Grok
303
384
  // turned away: rejected is that token (or true for whatever home holds).
@@ -306,7 +387,8 @@ function renew(exe, home) {
306
387
  // never "not signed in" nor "expired". said is what Grok answered the
307
388
  // token turned away with: a refusal that wasn't Grok's judgement of a
308
389
  // token still good is transient (passing). A renewal for a token turned
309
- // away is waited on waits.renew at most.
390
+ // away is waited on waits.renew at most. A renewal that failed lately is
391
+ // not run again till its time (holding): what it met is the answer.
310
392
  async function token(home, rejected = false, said) {
311
393
  let c = await credential(home)
312
394
  const exe = executable()
@@ -314,13 +396,19 @@ async function token(home, rejected = false, said) {
314
396
  let r
315
397
  if (c && exe && (refused || c.expires - Date.now() < REFRESH_MARGIN)) {
316
398
  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)
399
+ const held = holding(home, was)
400
+ if (held) r = held.r
401
+ else {
402
+ r = refused ? await within(renew(exe, home), waits.renew) : await renew(exe, home)
403
+ c = await credential(home)
404
+ settle(home, was, c, r)
405
+ }
406
+ 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))
320
408
  }
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)
409
+ 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))
324
412
  return c
325
413
  }
326
414
 
@@ -1206,15 +1294,29 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1206
1294
  const renewed = c && c.key !== auth.access && c.expires - Date.now() >= LEAD_MS
1207
1295
  const exe = executable()
1208
1296
  let r
1297
+ // what failed is said to magpie once; said again it is nothing to
1298
+ // renew, so magpie's log isn't the same line every try (plugins#1711)
1299
+ const fail = (key, e) => {
1300
+ told(home, key, e)
1301
+ if (e.quiet) return undefined
1302
+ throw e
1303
+ }
1209
1304
  if (!renewed && exe) {
1305
+ const was = c?.key ?? ""
1306
+ const held = holding(home, was)
1307
+ // failed lately: not run again till its time, nor ever once
1308
+ // Grok ended the sign-in
1309
+ if (held) return held.final ? fail(was, c ? signInEnded(home, held.r) : Object.assign(new Error(notSignedIn(home)), { final: true })) : undefined
1210
1310
  r = await renew(exe, home)
1211
1311
  c = await credential(home)
1312
+ settle(home, was, c, r)
1313
+ if (c && failing.get(home)?.final) return fail(c.key, signInEnded(home, r))
1212
1314
  }
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)
1315
+ // the CLI holds no sign-in there any more (`grok logout`, or one
1316
+ // it cleared on a refusal for good): one has to be made again
1317
+ if (!c) return fail("", Object.assign(new Error(notSignedIn(home)), { final: true }))
1318
+ // 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))
1218
1320
  if (c.key === auth.access && c.expires === auth.expires) return undefined
1219
1321
  // magpie saves what this gives
1220
1322
  const out = { access: c.key, expires: c.expires }
@@ -1383,15 +1485,30 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1383
1485
  const have = provider?.models ?? {}
1384
1486
  if (!auth || auth.type !== "oauth" || !auth.refresh) return have
1385
1487
  // 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)
1488
+ // magpie keeps the list it had. A sign-in failure told once already
1489
+ // (plugins#1711) falls back saying nothing, so magpie's log doesn't
1490
+ // get the same line on every list
1491
+ const quietly = (e) => {
1492
+ if (!e?.quiet) throw e
1493
+ return { ...have, [Symbol.for("magpie.fellBack")]: true }
1494
+ }
1495
+ let c
1496
+ try {
1497
+ c = await token(auth.refresh)
1498
+ } catch (e) {
1499
+ return quietly(e)
1500
+ }
1388
1501
  let list
1389
1502
  try {
1390
1503
  list = await listModels(c.key)
1391
1504
  } catch (e) {
1392
1505
  if (e?.status !== 401) throw e
1393
1506
  // turned away before its time: renewed once, as a request's is
1394
- c = await token(auth.refresh, c.key, e.said)
1507
+ try {
1508
+ c = await token(auth.refresh, c.key, e.said)
1509
+ } catch (e) {
1510
+ return quietly(e)
1511
+ }
1395
1512
  list = await listModels(c.key).catch((e) => {
1396
1513
  throw e?.status === 401 ? new Error(dead(auth.refresh)) : e
1397
1514
  })
@@ -1427,4 +1544,4 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
1427
1544
  }
1428
1545
 
1429
1546
  // for tests
1430
- export const _internal = { sttRequest, sttAnswer, rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf, waits }
1547
+ export const _internal = { sttRequest, sttAnswer, rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf, waits, backoff }
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.9",
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",