@magpie-community/opencode-grok-auth 0.1.6 → 0.1.8

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 +12 -0
  2. package/index.mjs +77 -9
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -71,3 +71,15 @@ leaves these out:
71
71
  Grok 4.7 until signed in. Signed in, the models are the ones the account
72
72
  lists at `/v1/models` (Responses models only), each with its context
73
73
  window and its reasoning efforts as variants.
74
+
75
+ ## Usage
76
+
77
+ magpie's card shows the credits of the current period
78
+ (`/v1/billing?format=credits`): weekly for SuperGrok, with on-demand
79
+ spending beside it when it has a cap.
80
+
81
+ Grok's billing says nothing of a plan's rate limit, so a free account can
82
+ read 0% used while its requests come back 429. After a 429 the card shows
83
+ a spent "Rate limit" window until the reset it named (`Retry-After`, or a
84
+ `*ratelimit*reset*` header). When it named none, the window stays until a
85
+ request goes through, or for 5 minutes.
package/index.mjs CHANGED
@@ -29,6 +29,12 @@ const TOOLS = new Set(["function", "web_search", "x_search", "image_generation",
29
29
  const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g
30
30
  const LINK = /https:\/\/\S+/
31
31
 
32
+ // linkIn is the page a line of `grok login` gives to open, "" for none: a
33
+ // line saying it failed names the endpoint it couldn't reach (`Error: error
34
+ // sending request for url (https://auth.x.ai/oauth2/device/code): …`),
35
+ // which is no page to open.
36
+ const linkIn = (line) => (/\berror\b/i.test(line) ? "" : (line.match(LINK)?.[0] ?? ""))
37
+
32
38
  // ---- the CLI ------------------------------------------------------------------
33
39
 
34
40
  // cliHome is where the CLI keeps its own sign-in and settings.
@@ -300,26 +306,30 @@ function login(exe, home, own) {
300
306
  const line = buf.slice(0, i).replace(/\r$/, "").replace(ANSI, "").trim()
301
307
  buf = buf.slice(i + 1)
302
308
  if (line) tail.push(line)
303
- const u = line.match(LINK)?.[0]
309
+ const u = linkIn(line)
304
310
  if (u) found(u)
305
311
  }
306
312
  }
307
313
  child.stdout.on("data", onData)
308
314
  child.stderr.on("data", onData)
309
315
  const done = new Promise((resolve) => {
310
- child.on("error", (e) => resolve({ ok: false, why: e.message }))
316
+ child.on("error", (e) => {
317
+ tail.push(e.message)
318
+ found("")
319
+ resolve({ ok: false, why: e.message })
320
+ })
311
321
  child.on("close", (code) => {
312
322
  const rest = buf.replace(ANSI, "").trim()
313
323
  if (rest) {
314
324
  tail.push(rest)
315
- const u = rest.match(LINK)?.[0]
325
+ const u = linkIn(rest)
316
326
  if (u) found(u)
317
327
  }
318
328
  found("")
319
329
  resolve({ ok: code === 0, why: tail.at(-1) ?? "grok login didn't finish" })
320
330
  })
321
331
  })
322
- return { child, link, done }
332
+ return { child, link, done, tail }
323
333
  }
324
334
 
325
335
  function newHome() {
@@ -336,12 +346,15 @@ async function signIn() {
336
346
  if (!exe) throw new Error(`install Grok Build first: ${INSTALL}`)
337
347
  const own = !!credential(cliHome())
338
348
  const home = own ? newHome() : cliHome()
339
- const { child, link, done } = login(exe, home, own)
349
+ const { child, link, done, tail } = login(exe, home, own)
340
350
  const url = await Promise.race([link, new Promise((r) => setTimeout(() => r(""), LINK_WAIT))])
341
351
  if (!url) {
342
352
  child.kill()
343
353
  if (own) rmSync(home, { recursive: true, force: true })
344
- throw new Error("grok login gave no link to open")
354
+ // what it said last is why: where x.ai is out of reach without a
355
+ // proxy, it says it couldn't reach it (𝕏 on Discord)
356
+ const why = tail.at(-1)
357
+ throw new Error(why ? `grok login gave no link to open: ${why}` : "grok login gave no link to open and said nothing: can this machine reach auth.x.ai? Set a proxy in magpie's Settings if it needs one")
345
358
  }
346
359
  return {
347
360
  url,
@@ -451,6 +464,57 @@ async function usage(key) {
451
464
  return { windows: out }
452
465
  }
453
466
 
467
+ // ---- rate limit -------------------------------------------------------------------
468
+
469
+ // Grok's billing says nothing of a plan's rate limit: a free account's
470
+ // credits read 0% used while every request comes back 429. So the account's
471
+ // last 429 is kept here, by its CLI home, and usage shows a "Rate limit"
472
+ // window spent until the reset the 429 named (Retry-After, or a
473
+ // *ratelimit*reset* header), or, when it named none, until a request goes
474
+ // through or HOLD_MS has passed. Aside: magpie's gateway already rests an
475
+ // account that answered 429; this is only what the card says.
476
+ const HOLD_MS = 5 * 60_000
477
+ const limited = new Map()
478
+
479
+ // resetOf is when a 429 says the limit lifts, in ms since the epoch, or 0.
480
+ function resetOf(headers, now) {
481
+ const ra = headers.get("retry-after")
482
+ if (ra) {
483
+ const n = Number(ra)
484
+ if (Number.isFinite(n) && n >= 0) return now + n * 1000
485
+ const d = Date.parse(ra)
486
+ if (!Number.isNaN(d)) return d
487
+ }
488
+ for (const [k, v] of headers) {
489
+ if (!/ratelimit.*reset/i.test(k)) continue
490
+ const n = Number(v)
491
+ if (!Number.isFinite(n) || n < 0) continue
492
+ // a time (epoch ms or seconds) or seconds from now
493
+ if (n > 1e12) return n
494
+ if (n > 1e9) return n * 1000
495
+ return now + n * 1000
496
+ }
497
+ return 0
498
+ }
499
+
500
+ // note keeps what a request's answer says of the rate limit.
501
+ function note(home, res, now = Date.now()) {
502
+ if (res.status === 429) limited.set(home, { at: now, until: resetOf(res.headers, now) })
503
+ else if (res.ok) limited.delete(home)
504
+ }
505
+
506
+ // rateWindow is the window a recent 429 makes, or none.
507
+ function rateWindow(home, now = Date.now()) {
508
+ const l = limited.get(home)
509
+ if (!l) return []
510
+ if (l.until ? l.until <= now : now - l.at >= HOLD_MS) {
511
+ limited.delete(home)
512
+ return []
513
+ }
514
+ const end = l.until || l.at + HOLD_MS
515
+ return [{ name: "Rate limit", used: 100, resetsAt: new Date(end).toISOString(), aside: true }]
516
+ }
517
+
454
518
  // kept is res saying magpie is to leave the account's sign-in be.
455
519
  function kept(res) {
456
520
  const headers = new Headers(res.headers)
@@ -540,7 +604,9 @@ export const GrokAuthPlugin = async ({ client }) => {
540
604
  // sent once, as the built-in sent it: Grok's answer goes on as
541
605
  // it came, the account kept, as the built-in never marked a Grok
542
606
  // account lapsed nor cleared one
543
- return kept(await fetch(req.url, { ...init, method: req.method, headers, body }))
607
+ const res = await fetch(req.url, { ...init, method: req.method, headers, body })
608
+ note(home, res)
609
+ return kept(res)
544
610
  },
545
611
  }
546
612
  },
@@ -569,7 +635,9 @@ export const GrokAuthPlugin = async ({ client }) => {
569
635
  return { error: e.message, windows: [], signIn: "kept" }
570
636
  }
571
637
  await remember(auth, c)
572
- return { ...(await usage(c.key)), signIn: "kept" }
638
+ const u = await usage(c.key)
639
+ if (!u.error) u.windows = [...rateWindow(auth.refresh), ...u.windows]
640
+ return { ...u, signIn: "kept" }
573
641
  },
574
642
  },
575
643
 
@@ -609,4 +677,4 @@ export const GrokAuthPlugin = async ({ client }) => {
609
677
  }
610
678
 
611
679
  // for tests
612
- export const _internal = { rewrite, bodyText }
680
+ export const _internal = { rewrite, bodyText, limited, HOLD_MS }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-grok-auth",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
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": "./index.mjs",