@magpie-community/opencode-grok-auth 0.1.5 → 0.1.7

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 +26 -3
  2. package/index.mjs +107 -8
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -29,9 +29,20 @@ The CLI keeps the sign-in in its home, as `auth.json`. OpenCode (or
29
29
  magpie) keeps where that home is, the token and its expiry.
30
30
 
31
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.
32
+ each time. The plugin runs `grok models` in that home, so the CLI renews
33
+ it, then reads it again:
34
+
35
+ - magpie renews the token 5 minutes before it ends, through the plugin's
36
+ `auth.refresh`, once for the account and before its requests, models
37
+ and usage need it. magpie saves what the CLI gave.
38
+ - OpenCode doesn't call that hook: there the token is renewed when it is
39
+ 5 minutes from expiring, before a request.
40
+ - The CLI runs once for a home at a time: a request or renewal that
41
+ comes while it runs waits for it and reads what it gave. A token the
42
+ CLI already renewed is taken as it is.
43
+ - When the CLI no longer holds a sign-in in that home (`grok logout`),
44
+ the account has to be signed in again. When it couldn't renew a token
45
+ that has ended, magpie tries again later.
35
46
 
36
47
  ## Requests
37
48
 
@@ -60,3 +71,15 @@ leaves these out:
60
71
  Grok 4.7 until signed in. Signed in, the models are the ones the account
61
72
  lists at `/v1/models` (Responses models only), each with its context
62
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
@@ -17,7 +17,8 @@ import { STATUS_CODES } from "node:http"
17
17
  const PROVIDER = "grok"
18
18
  const BASE = "https://cli-chat-proxy.grok.com/v1"
19
19
  const CLIENT_VERSION = "1.0.41"
20
- const REFRESH_MARGIN = 5 * 60 * 1000
20
+ const REFRESH_MARGIN = 5 * 60 * 1000 // a token this close to its end is renewed before a request
21
+ const LEAD_MS = REFRESH_MARGIN // and this close, magpie renews it ahead of time (auth.refresh)
21
22
  const LINK_WAIT = 30 * 1000
22
23
  const INSTALL = process.platform === "win32" ? "irm https://x.ai/cli/install.ps1 | iex" : "curl -fsSL https://x.ai/cli/install.sh | bash"
23
24
 
@@ -119,18 +120,32 @@ function run(file, args, opts) {
119
120
  })
120
121
  }
121
122
 
123
+ // refreshing runs the CLI's renewals one after another; renewing is the one
124
+ // asked for each home, which those who come while it is due or running join
125
+ // rather than running the CLI there again.
122
126
  let refreshing = Promise.resolve()
127
+ const renewing = new Map()
128
+
129
+ // renew has the CLI renew the sign-in in home: a `grok models` there renews
130
+ // it as any use of the CLI does.
131
+ function renew(exe, home) {
132
+ let r = renewing.get(home)
133
+ if (!r) {
134
+ r = refreshing.then(() => run(exe, ["models"], { cwd: dirname(home), env: envFor(home) })).finally(() => renewing.delete(home))
135
+ refreshing = r.catch(() => {})
136
+ renewing.set(home, r)
137
+ }
138
+ return r
139
+ }
123
140
 
124
141
  // token is the CLI's sign-in in home with a token still good. One about to
125
142
  // expire (or that a request found expired) is first renewed by the CLI in
126
- // its own home: a `grok models` there renews it as any use of the CLI does.
143
+ // its own home.
127
144
  async function token(home, expired) {
128
145
  let c = credential(home)
129
146
  const exe = executable()
130
147
  if (c && exe && (expired || c.expires - Date.now() < REFRESH_MARGIN)) {
131
- const done = refreshing.then(() => run(exe, ["models"], { cwd: dirname(home), env: envFor(home) }))
132
- refreshing = done.catch(() => {})
133
- await done
148
+ await renew(exe, home)
134
149
  c = credential(home)
135
150
  }
136
151
  if (!c) throw new Error("Grok is not signed in; run `grok login`")
@@ -436,6 +451,57 @@ async function usage(key) {
436
451
  return { windows: out }
437
452
  }
438
453
 
454
+ // ---- rate limit -------------------------------------------------------------------
455
+
456
+ // Grok's billing says nothing of a plan's rate limit: a free account's
457
+ // credits read 0% used while every request comes back 429. So the account's
458
+ // last 429 is kept here, by its CLI home, and usage shows a "Rate limit"
459
+ // window spent until the reset the 429 named (Retry-After, or a
460
+ // *ratelimit*reset* header), or, when it named none, until a request goes
461
+ // through or HOLD_MS has passed. Aside: magpie's gateway already rests an
462
+ // account that answered 429; this is only what the card says.
463
+ const HOLD_MS = 5 * 60_000
464
+ const limited = new Map()
465
+
466
+ // resetOf is when a 429 says the limit lifts, in ms since the epoch, or 0.
467
+ function resetOf(headers, now) {
468
+ const ra = headers.get("retry-after")
469
+ if (ra) {
470
+ const n = Number(ra)
471
+ if (Number.isFinite(n) && n >= 0) return now + n * 1000
472
+ const d = Date.parse(ra)
473
+ if (!Number.isNaN(d)) return d
474
+ }
475
+ for (const [k, v] of headers) {
476
+ if (!/ratelimit.*reset/i.test(k)) continue
477
+ const n = Number(v)
478
+ if (!Number.isFinite(n) || n < 0) continue
479
+ // a time (epoch ms or seconds) or seconds from now
480
+ if (n > 1e12) return n
481
+ if (n > 1e9) return n * 1000
482
+ return now + n * 1000
483
+ }
484
+ return 0
485
+ }
486
+
487
+ // note keeps what a request's answer says of the rate limit.
488
+ function note(home, res, now = Date.now()) {
489
+ if (res.status === 429) limited.set(home, { at: now, until: resetOf(res.headers, now) })
490
+ else if (res.ok) limited.delete(home)
491
+ }
492
+
493
+ // rateWindow is the window a recent 429 makes, or none.
494
+ function rateWindow(home, now = Date.now()) {
495
+ const l = limited.get(home)
496
+ if (!l) return []
497
+ if (l.until ? l.until <= now : now - l.at >= HOLD_MS) {
498
+ limited.delete(home)
499
+ return []
500
+ }
501
+ const end = l.until || l.at + HOLD_MS
502
+ return [{ name: "Rate limit", used: 100, resetsAt: new Date(end).toISOString(), aside: true }]
503
+ }
504
+
439
505
  // kept is res saying magpie is to leave the account's sign-in be.
440
506
  function kept(res) {
441
507
  const headers = new Headers(res.headers)
@@ -468,6 +534,35 @@ export const GrokAuthPlugin = async ({ client }) => {
468
534
 
469
535
  auth: {
470
536
  provider: PROVIDER,
537
+ // magpie renews the sign-in LEAD_MS before its end, once for the
538
+ // account, before its requests, models and usage ask for it: the CLI
539
+ // renews it in its home, as before a request, and what it gives is
540
+ // read back. The check before each request stays for OpenCode, which
541
+ // doesn't call this.
542
+ refreshLead: LEAD_MS,
543
+ async refresh(auth) {
544
+ const home = auth?.refresh
545
+ if (auth?.type !== "oauth" || !home) return undefined
546
+ let c = credential(home)
547
+ // renewed already (by the CLI, or before a request), the store not
548
+ // yet saying so
549
+ const renewed = c && c.key !== auth.access && c.expires - Date.now() >= LEAD_MS
550
+ const exe = executable()
551
+ if (!renewed && exe) {
552
+ await renew(exe, home)
553
+ c = credential(home)
554
+ }
555
+ // the CLI holds no sign-in there any more (`grok logout`): one
556
+ // has to be made again
557
+ if (!c) throw Object.assign(new Error("Grok is not signed in; run `grok login`"), { signIn: "expired" })
558
+ // the CLI couldn't renew it: tried again later
559
+ if (exe && c.expires && c.expires <= Date.now()) throw new Error("Grok's sign-in has expired and Grok Build couldn't renew it")
560
+ if (c.key === auth.access && c.expires === auth.expires) return undefined
561
+ // magpie saves what this gives
562
+ const out = { access: c.key, expires: c.expires }
563
+ if (c.email && c.email !== auth.accountId) out.accountId = c.email
564
+ return out
565
+ },
471
566
  async loader(getAuth) {
472
567
  const auth = await getAuth()
473
568
  if (!auth || auth.type !== "oauth") return {}
@@ -496,7 +591,9 @@ export const GrokAuthPlugin = async ({ client }) => {
496
591
  // sent once, as the built-in sent it: Grok's answer goes on as
497
592
  // it came, the account kept, as the built-in never marked a Grok
498
593
  // account lapsed nor cleared one
499
- return kept(await fetch(req.url, { ...init, method: req.method, headers, body }))
594
+ const res = await fetch(req.url, { ...init, method: req.method, headers, body })
595
+ note(home, res)
596
+ return kept(res)
500
597
  },
501
598
  }
502
599
  },
@@ -525,7 +622,9 @@ export const GrokAuthPlugin = async ({ client }) => {
525
622
  return { error: e.message, windows: [], signIn: "kept" }
526
623
  }
527
624
  await remember(auth, c)
528
- return { ...(await usage(c.key)), signIn: "kept" }
625
+ const u = await usage(c.key)
626
+ if (!u.error) u.windows = [...rateWindow(auth.refresh), ...u.windows]
627
+ return { ...u, signIn: "kept" }
529
628
  },
530
629
  },
531
630
 
@@ -565,4 +664,4 @@ export const GrokAuthPlugin = async ({ client }) => {
565
664
  }
566
665
 
567
666
  // for tests
568
- export const _internal = { rewrite, bodyText }
667
+ 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.5",
3
+ "version": "0.1.7",
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",