@magpie-community/opencode-grok-auth 0.1.0 → 0.1.2

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 (2) hide show
  1. package/index.mjs +100 -7
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -12,6 +12,7 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync } f
12
12
  import { homedir } from "node:os"
13
13
  import { delimiter, dirname, isAbsolute, join } from "node:path"
14
14
  import { randomBytes } from "node:crypto"
15
+ import { STATUS_CODES } from "node:http"
15
16
 
16
17
  const PROVIDER = "grok"
17
18
  const BASE = "https://cli-chat-proxy.grok.com/v1"
@@ -173,6 +174,13 @@ async function sign(headers, key) {
173
174
  headers.set("User-Agent", `grok-shell/${v} (${os}; ${arch})`)
174
175
  }
175
176
 
177
+ // bodyText is a request body handed over as bytes read as the text it
178
+ // is, so it can be reshaped; any other body is as it came.
179
+ function bodyText(body) {
180
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return new TextDecoder().decode(body)
181
+ return body
182
+ }
183
+
176
184
  // rewrite leaves out what Grok's backend doesn't take: tools of other
177
185
  // types (a freeform apply_patch, a namespace of sub-agent tools), a web
178
186
  // search's external_web_access, a tool_choice naming a dropped type, and a
@@ -340,6 +348,78 @@ async function current() {
340
348
  }
341
349
  }
342
350
 
351
+ // ---- usage ----------------------------------------------------------------------
352
+
353
+ // How much of the subscription's allowance is gone, as magpie's built-in
354
+ // Grok account shows it (internal/provider/grok_usage.go) and the CLI's own
355
+ // /usage reads it: the credits of the current period, weekly for
356
+ // SuperGrok, and what on-demand spending has used of its cap.
357
+
358
+ const PERIODS = { DAILY: ["1 day", 24 * 3600], WEEKLY: ["7 days", 7 * 24 * 3600], MONTHLY: ["Month", 30 * 24 * 3600] }
359
+ const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/
360
+
361
+ // statusText is a refused request's status as magpie says it (Go's
362
+ // http.StatusText).
363
+ // http.StatusText); one Go has no words for is "HTTP <n>", never empty.
364
+ const statusText = (s) =>
365
+ ((GO_TEXT[s] ?? STATUS_CODES[s]) || `HTTP ${s}`)
366
+ // where Go's words differ from Node's (509 Go has none for)
367
+ const GO_TEXT = { 413: "Request Entity Too Large", 414: "Request URI Too Long", 416: "Requested Range Not Satisfiable", 418: "I'm a teapot", 509: "" }
368
+
369
+ // netError is a request that got no answer, as Go's http client words it
370
+ // (`Get "<url>": …`), with the words magpie's keepLast looks for to keep
371
+ // the card it had: no such host, connection refused, timeout, EOF.
372
+ function netError(url, e) {
373
+ const m = String(e?.message ?? e)
374
+ const code = String(e?.code ?? e?.cause?.code ?? "")
375
+ let why = m
376
+ if (e?.name === "TimeoutError" || e?.name === "AbortError" || /timed? ?out/i.test(m)) why = "timeout"
377
+ else if (code === "ENOTFOUND" || code === "EAI_AGAIN" || /getaddrinfo|ENOTFOUND|resolve|DNS/i.test(m)) why = "dial tcp: lookup: no such host"
378
+ else if (code === "ECONNREFUSED" || /ECONNREFUSED|Unable to connect|refused/i.test(m)) why = "dial tcp: connection refused"
379
+ else if (/ECONNRESET|socket|closed|fetch failed/i.test(m + code)) why = "EOF"
380
+ return `Get "${url}": ${why}`
381
+ }
382
+
383
+ // jsonError is JSON that won't read, as Go's encoding/json says it.
384
+ function jsonError(text) {
385
+ const c = text.trimStart()[0]
386
+ return c === undefined ? "unexpected end of JSON input" : `invalid character '${c}' looking for beginning of value`
387
+ }
388
+
389
+ async function usage(key) {
390
+ const url = `${BASE}/billing?format=credits`
391
+ let res, text
392
+ try {
393
+ res = await fetch(url, {
394
+ headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
395
+ signal: AbortSignal.timeout(15_000),
396
+ })
397
+ if (res.ok) text = await res.text()
398
+ } catch (e) {
399
+ return { error: netError(url, e), windows: [] }
400
+ }
401
+ if (!res.ok) return { error: statusText(res.status), windows: [] }
402
+ let data
403
+ try {
404
+ data = JSON.parse(text)
405
+ } catch {
406
+ return { error: jsonError(text), windows: [] }
407
+ }
408
+ const cfg = data?.config ?? {}
409
+ const num = (v) => (typeof v === "number" ? v : 0)
410
+ let [name, span] = ["Allowance", 0]
411
+ let end = cfg.billingPeriodEnd
412
+ if (cfg.currentPeriod) {
413
+ ;[name, span] = PERIODS[String(cfg.currentPeriod.type ?? "").replace(/^USAGE_PERIOD_TYPE_/, "")] ?? ["Allowance", 0]
414
+ end = cfg.currentPeriod.end
415
+ }
416
+ const at = typeof end === "string" && RFC3339.test(end) && !Number.isNaN(Date.parse(end)) ? { resetsAt: end } : {}
417
+ const out = [{ name, used: num(cfg.creditUsagePercent), ...(span ? { span } : {}), ...at }]
418
+ const cap = num(cfg.onDemandCap?.val)
419
+ if (cap > 0) out.push({ name: "On-demand", used: (100 * num(cfg.onDemandUsed?.val)) / cap, ...at, aside: true })
420
+ return { windows: out }
421
+ }
422
+
343
423
  // ---- the plugin ---------------------------------------------------------------
344
424
 
345
425
  export const GrokAuthPlugin = async ({ client }) => {
@@ -374,7 +454,7 @@ export const GrokAuthPlugin = async ({ client }) => {
374
454
  const home = auth?.refresh
375
455
  if (!home) throw new Error("Grok is not signed in; run `grok login`")
376
456
  const req = new Request(input, init)
377
- const body = rewrite(init?.body)
457
+ const body = rewrite(bodyText(init?.body))
378
458
  let parsed = {}
379
459
  if (typeof body === "string") {
380
460
  try {
@@ -409,6 +489,19 @@ export const GrokAuthPlugin = async ({ client }) => {
409
489
  authorize: current,
410
490
  },
411
491
  ],
492
+ // magpie's: how much of the subscription's allowance is gone
493
+ async usage(getAuth) {
494
+ const auth = await getAuth()
495
+ let c
496
+ try {
497
+ if (!auth || auth.type !== "oauth" || !auth.refresh) throw new Error("Grok is not signed in; run `grok login`")
498
+ c = await token(auth.refresh, false)
499
+ } catch (e) {
500
+ return { error: e.message, windows: [] }
501
+ }
502
+ await remember(auth, c)
503
+ return usage(c.key)
504
+ },
412
505
  },
413
506
 
414
507
  provider: {
@@ -416,12 +509,9 @@ export const GrokAuthPlugin = async ({ client }) => {
416
509
  async models(provider, { auth } = {}) {
417
510
  const have = provider?.models ?? {}
418
511
  if (!auth || auth.type !== "oauth" || !auth.refresh) return have
419
- let list
420
- try {
421
- list = await listModels((await token(auth.refresh, false)).key)
422
- } catch {
423
- return have
424
- }
512
+ // a list Grok couldn't give is a failure, not the few configured:
513
+ // magpie keeps the list it had
514
+ const list = await listModels((await token(auth.refresh, false)).key)
425
515
  const base = have["grok-4.7"] ?? Object.values(have)[0] ?? {}
426
516
  const out = {}
427
517
  for (const m of list) {
@@ -448,3 +538,6 @@ export const GrokAuthPlugin = async ({ client }) => {
448
538
  },
449
539
  }
450
540
  }
541
+
542
+ // for tests
543
+ export const _internal = { rewrite, bodyText }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-grok-auth",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
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",