@magpie-community/opencode-grok-auth 0.1.11 → 0.1.13
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.
- package/README.md +29 -5
- package/index.mjs +142 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -22,13 +22,20 @@ irm https://x.ai/cli/install.ps1 | iex # Windows
|
|
|
22
22
|
`~/.config`). Grok Build's own sign-in stays as it is.
|
|
23
23
|
- **Use Grok Build's current sign-in** takes the account the CLI is
|
|
24
24
|
signed in to, with nothing to approve.
|
|
25
|
+
- **Import CPA Grok account JSON** copies one enabled xAI OAuth account from
|
|
26
|
+
a CLIProxyAPI (CPA) account JSON file (CPA keeps it as
|
|
27
|
+
`~/.cli-proxy-api/xai-<email>.json`) into a private home for this plugin.
|
|
28
|
+
CPA and Grok Build rotate the same refresh token, so stop using that
|
|
29
|
+
account in CPA before importing it. The file is read, never rewritten.
|
|
25
30
|
|
|
26
31
|
## Where the sign-in is kept
|
|
27
32
|
|
|
28
33
|
The CLI keeps the sign-in in its home, as `auth.json`. OpenCode (or
|
|
29
|
-
magpie) keeps where that home is, the token and its expiry.
|
|
34
|
+
magpie) keeps where that home is, the token and its expiry. Importing a CPA
|
|
35
|
+
account writes only its translated xAI OAuth fields to a private home owned
|
|
36
|
+
by this plugin; the selected CPA file is left unchanged.
|
|
30
37
|
|
|
31
|
-
The plugin
|
|
38
|
+
The plugin reads `auth.json`; Grok Build refreshes the token, which changes
|
|
32
39
|
each time. The plugin runs `grok models` in that home, so the CLI renews
|
|
33
40
|
it, then reads it again:
|
|
34
41
|
|
|
@@ -55,7 +62,11 @@ API (`@ai-sdk/openai`), signed as the CLI signs them:
|
|
|
55
62
|
- `x-grok-client-mode: headless`
|
|
56
63
|
- `x-grok-client-version` and `User-Agent: grok-shell/<version> (<os>; <arch>)`.
|
|
57
64
|
The version is 1.0.41, or the installed CLI's if it is newer.
|
|
58
|
-
- `x-grok-model-override`: the request's model.
|
|
65
|
+
- `x-grok-model-override`: the request's model. A window suffix
|
|
66
|
+
(`grok-4.7@500k`) is the plain model (`grok-4.7`) here and in the body.
|
|
67
|
+
- `x-grok-context-window`: the token count a suffixed model names
|
|
68
|
+
(`500000` for `@500k`). The plain id sends no such header and stays on
|
|
69
|
+
the default window.
|
|
59
70
|
- `x-grok-conv-id`: the request's `prompt_cache_key`.
|
|
60
71
|
|
|
61
72
|
The backend turns away some of what a request may carry, so the plugin
|
|
@@ -73,8 +84,17 @@ unrecognized content stays unchanged; the plugin does not decrypt tasks.
|
|
|
73
84
|
## Models
|
|
74
85
|
|
|
75
86
|
Grok 4.7 until signed in. Signed in, the models are the ones the account
|
|
76
|
-
lists at `/v1/models` (Responses models only), each with its
|
|
77
|
-
|
|
87
|
+
lists at `/v1/models` (Responses models only), each with its reasoning
|
|
88
|
+
efforts as variants.
|
|
89
|
+
|
|
90
|
+
`context_window` is the default window and keeps the plain id, so a saved
|
|
91
|
+
`grok-4.7` stays a 256k model. Each other size in `context_windows` is
|
|
92
|
+
offered beside it, named `Grok 4.7 @ 500k` with id `grok-4.7@500k` and
|
|
93
|
+
that many tokens as its window. A request for it sends
|
|
94
|
+
`x-grok-context-window: 500000`. The proxy serves up to its largest
|
|
95
|
+
window either way and refuses past it; the header names the window the
|
|
96
|
+
caller asked to compact against. Pick `grok-4.7@500k` where a client
|
|
97
|
+
compacts at the advertised window, such as Claude Code.
|
|
78
98
|
|
|
79
99
|
## Usage
|
|
80
100
|
|
|
@@ -87,3 +107,7 @@ read 0% used while its requests come back 429. After a 429 the card shows
|
|
|
87
107
|
a spent "Rate limit" window until the reset it named (`Retry-After`, or a
|
|
88
108
|
`*ratelimit*reset*` header). When it named none, the window stays until a
|
|
89
109
|
request goes through, or for 5 minutes.
|
|
110
|
+
|
|
111
|
+
Grok Bot's separate allowance is shown by the [Cursor plugin](../cursor/README.md#usage).
|
|
112
|
+
Sign in there with the Cursor account linked in Grok Bot, including for
|
|
113
|
+
access through SuperGrok.
|
package/index.mjs
CHANGED
|
@@ -8,15 +8,17 @@
|
|
|
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 } from "node:fs"
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"
|
|
12
12
|
import { homedir } from "node:os"
|
|
13
|
-
import { delimiter, dirname, isAbsolute, join } from "node:path"
|
|
13
|
+
import { 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
|
|
|
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 CPA_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828"
|
|
21
|
+
const CPA_SCOPE = `https://auth.x.ai::${CPA_CLIENT_ID}`
|
|
20
22
|
const REFRESH_MARGIN = 5 * 60 * 1000 // a token this close to its end is renewed before a request
|
|
21
23
|
const LEAD_MS = REFRESH_MARGIN // and this close, magpie renews it ahead of time (auth.refresh)
|
|
22
24
|
const LINK_WAIT = 30 * 1000
|
|
@@ -384,12 +386,48 @@ async function listModels(key) {
|
|
|
384
386
|
for (const d of JSON.parse(text)?.data ?? []) {
|
|
385
387
|
if (!d?.id || (d.api_backend && d.api_backend !== "responses")) continue
|
|
386
388
|
const efforts = (d.reasoning_efforts ?? []).map((e) => e?.value).filter(Boolean).reverse()
|
|
387
|
-
out.push(
|
|
389
|
+
out.push(...windowsOf(d, efforts))
|
|
388
390
|
}
|
|
389
391
|
if (!out.length) throw new Error("Grok listed no models")
|
|
390
392
|
return out
|
|
391
393
|
}
|
|
392
394
|
|
|
395
|
+
// labelOf is a window as the picker shows it: 500000 is "500k".
|
|
396
|
+
const labelOf = (n) => (n % 1000 === 0 ? `${n / 1000}k` : String(n))
|
|
397
|
+
|
|
398
|
+
// windowsOf is one model for each context window Grok lists. context_window
|
|
399
|
+
// is the default and keeps the plain id (grok-4.7), so a saved agent stays
|
|
400
|
+
// where it was. Each other size in context_windows is offered beside it
|
|
401
|
+
// (grok-4.7@500k), the way the CLI's /context-window offers it. A list with
|
|
402
|
+
// one size, or none, stays one model.
|
|
403
|
+
function windowsOf(d, efforts) {
|
|
404
|
+
const name = d.name || d.id
|
|
405
|
+
const fallback = Number(d.context_window) || 0
|
|
406
|
+
const listed = (Array.isArray(d.context_windows) ? d.context_windows : [])
|
|
407
|
+
.map(Number)
|
|
408
|
+
.filter((n) => Number.isInteger(n) && n > 0)
|
|
409
|
+
const windows = [...new Set(listed.length ? listed : [fallback].filter(Boolean))]
|
|
410
|
+
const base = windows.includes(fallback) ? fallback : windows[0] ?? 0
|
|
411
|
+
const out = [{ id: d.id, apiId: d.id, name, context: base || fallback, window: base, efforts }]
|
|
412
|
+
for (const w of windows) {
|
|
413
|
+
if (w === base) continue
|
|
414
|
+
out.push({ id: `${d.id}@${labelOf(w)}`, apiId: d.id, name: `${name} @ ${labelOf(w)}`, context: w, window: w, efforts })
|
|
415
|
+
}
|
|
416
|
+
return out
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// modelOf splits a requested id into the model Grok lists and the window
|
|
420
|
+
// the id names. grok-4.7 is grok-4.7 at its default window (no header);
|
|
421
|
+
// grok-4.7@500k is grok-4.7 at 500000 tokens. The header is what the CLI
|
|
422
|
+
// sends as x-grok-context-window. The proxy serves up to its largest
|
|
423
|
+
// window either way and refuses past it; the header names the window the
|
|
424
|
+
// caller asked to compact against.
|
|
425
|
+
function modelOf(id) {
|
|
426
|
+
const at = typeof id === "string" ? id.match(/^(.*)@(\d+)k$/) : null
|
|
427
|
+
if (!at) return { model: id, window: 0 }
|
|
428
|
+
return { model: at[1], window: Number(at[2]) * 1000 }
|
|
429
|
+
}
|
|
430
|
+
|
|
393
431
|
// ---- sign-in ------------------------------------------------------------------
|
|
394
432
|
|
|
395
433
|
// login runs `grok login --device-auth` in home and hands on the first link
|
|
@@ -477,6 +515,78 @@ async function signIn() {
|
|
|
477
515
|
}
|
|
478
516
|
}
|
|
479
517
|
|
|
518
|
+
function cpaClaims(token) {
|
|
519
|
+
try {
|
|
520
|
+
const part = token.split(".")[1]
|
|
521
|
+
if (!part) return null
|
|
522
|
+
return JSON.parse(Buffer.from(part, "base64url").toString("utf8"))
|
|
523
|
+
} catch {
|
|
524
|
+
return null
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function cpaAuthFromFile(file) {
|
|
529
|
+
let source
|
|
530
|
+
try {
|
|
531
|
+
source = JSON.parse(readFileSync(file, "utf8"))
|
|
532
|
+
} catch {
|
|
533
|
+
throw new Error("CPA Grok account file is not valid JSON")
|
|
534
|
+
}
|
|
535
|
+
if (!source || typeof source !== "object" || Array.isArray(source) || source.type !== "xai" || source.auth_kind !== "oauth" || source.disabled !== false) {
|
|
536
|
+
throw new Error("CPA file is not an enabled xAI OAuth account")
|
|
537
|
+
}
|
|
538
|
+
if (typeof source.access_token !== "string" || !source.access_token || typeof source.refresh_token !== "string" || !source.refresh_token || typeof source.sub !== "string" || !source.sub || typeof source.email !== "string" || !source.email) {
|
|
539
|
+
throw new Error("CPA xAI account is missing its tokens or identity")
|
|
540
|
+
}
|
|
541
|
+
if (typeof source.last_refresh !== "string" || typeof source.expired !== "string") {
|
|
542
|
+
throw new Error("CPA xAI account has invalid token timestamps")
|
|
543
|
+
}
|
|
544
|
+
const createTime = Date.parse(source.last_refresh)
|
|
545
|
+
const expiresAt = Date.parse(source.expired)
|
|
546
|
+
if (!Number.isFinite(createTime) || !Number.isFinite(expiresAt)) {
|
|
547
|
+
throw new Error("CPA xAI account has invalid token timestamps")
|
|
548
|
+
}
|
|
549
|
+
const claims = cpaClaims(source.access_token)
|
|
550
|
+
const audience = Array.isArray(claims?.aud) ? claims.aud : [claims?.aud]
|
|
551
|
+
if (claims?.iss !== "https://auth.x.ai" || !audience.includes(CPA_CLIENT_ID)) {
|
|
552
|
+
throw new Error("CPA token is not for the Grok Build xAI account")
|
|
553
|
+
}
|
|
554
|
+
return {
|
|
555
|
+
key: source.access_token,
|
|
556
|
+
auth_mode: "oidc",
|
|
557
|
+
create_time: new Date(createTime).toISOString(),
|
|
558
|
+
user_id: source.sub,
|
|
559
|
+
email: source.email,
|
|
560
|
+
refresh_token: source.refresh_token,
|
|
561
|
+
expires_at: new Date(expiresAt).toISOString(),
|
|
562
|
+
oidc_issuer: "https://auth.x.ai",
|
|
563
|
+
oidc_client_id: CPA_CLIENT_ID,
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
async function importCPA(inputs) {
|
|
568
|
+
if (!executable()) throw new Error(`install Grok Build first: ${INSTALL}`)
|
|
569
|
+
const rawPath = String(inputs?.path ?? "").trim()
|
|
570
|
+
const file = resolve(rawPath === "~" ? homedir() : rawPath.startsWith("~/") ? join(homedir(), rawPath.slice(2)) : rawPath)
|
|
571
|
+
if (!isFile(file)) throw new Error("choose a CPA Grok account JSON file")
|
|
572
|
+
const auth = cpaAuthFromFile(file)
|
|
573
|
+
return {
|
|
574
|
+
url: "",
|
|
575
|
+
instructions: "The account is ready to import. Stop using it in CPA before continuing; both clients rotate the same refresh token.",
|
|
576
|
+
method: "auto",
|
|
577
|
+
callback: async () => {
|
|
578
|
+
const home = newHome()
|
|
579
|
+
try {
|
|
580
|
+
writeFileSync(join(home, "auth.json"), JSON.stringify({ [CPA_SCOPE]: auth }, null, 2), { mode: 0o600 })
|
|
581
|
+
} catch (error) {
|
|
582
|
+
rmSync(home, { recursive: true, force: true })
|
|
583
|
+
throw error
|
|
584
|
+
}
|
|
585
|
+
return saved(home, credential(home))
|
|
586
|
+
},
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
480
590
|
// saved is the sign-in as OpenCode keeps it: refresh is the home the CLI
|
|
481
591
|
// keeps it in, access the token it had then.
|
|
482
592
|
function saved(home, c) {
|
|
@@ -692,7 +802,7 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
692
802
|
const home = auth?.refresh
|
|
693
803
|
if (!home) throw new Error("Grok is not signed in; run `grok login`")
|
|
694
804
|
const req = new Request(input, init)
|
|
695
|
-
|
|
805
|
+
let body = rewrite(bodyText(init?.body))
|
|
696
806
|
let parsed = {}
|
|
697
807
|
if (typeof body === "string") {
|
|
698
808
|
try {
|
|
@@ -703,7 +813,15 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
703
813
|
await remember(auth, c)
|
|
704
814
|
const headers = new Headers(req.headers)
|
|
705
815
|
await sign(headers, c.key)
|
|
706
|
-
|
|
816
|
+
const asked = modelOf(parsed.model)
|
|
817
|
+
if (asked.model) {
|
|
818
|
+
headers.set("x-grok-model-override", asked.model)
|
|
819
|
+
if (asked.window && typeof body === "string") {
|
|
820
|
+
parsed.model = asked.model
|
|
821
|
+
body = JSON.stringify(parsed)
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
if (asked.window) headers.set("x-grok-context-window", String(asked.window))
|
|
707
825
|
if (typeof parsed.prompt_cache_key === "string" && parsed.prompt_cache_key) headers.set("x-grok-conv-id", parsed.prompt_cache_key)
|
|
708
826
|
headers.delete("content-length")
|
|
709
827
|
// sent once, as the built-in sent it: Grok's answer goes on as
|
|
@@ -726,6 +844,20 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
726
844
|
label: "Use Grok Build's current sign-in",
|
|
727
845
|
authorize: current,
|
|
728
846
|
},
|
|
847
|
+
{
|
|
848
|
+
type: "oauth",
|
|
849
|
+
label: "Import CPA Grok account JSON",
|
|
850
|
+
prompts: [
|
|
851
|
+
{
|
|
852
|
+
type: "text",
|
|
853
|
+
key: "path",
|
|
854
|
+
message: "Path to the CPA xAI account JSON. Stop using this account in CPA after import; its refresh token rotates.",
|
|
855
|
+
placeholder: "~/.cli-proxy-api/xai-<email>.json",
|
|
856
|
+
validate: (v) => (String(v ?? "").trim() ? undefined : "Enter the path to a CPA xAI account JSON file"),
|
|
857
|
+
},
|
|
858
|
+
],
|
|
859
|
+
authorize: importCPA,
|
|
860
|
+
},
|
|
729
861
|
],
|
|
730
862
|
// magpie's: how much of the subscription's allowance is gone; each
|
|
731
863
|
// read keeps the sign-in (signIn), as the built-in's marked no
|
|
@@ -757,12 +889,15 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
757
889
|
const base = have["grok-4.7"] ?? Object.values(have)[0] ?? {}
|
|
758
890
|
const out = {}
|
|
759
891
|
for (const m of list) {
|
|
760
|
-
const was = have[m.id] ?? base
|
|
892
|
+
const was = have[m.id] ?? have[m.apiId] ?? base
|
|
761
893
|
out[m.id] = {
|
|
762
894
|
...was,
|
|
763
895
|
id: m.id,
|
|
764
896
|
providerID: provider.id,
|
|
765
897
|
name: m.name,
|
|
898
|
+
// the id as offered, window and all: magpie and the AI SDK send
|
|
899
|
+
// api.id as the body's model, and fetch reads the window from it
|
|
900
|
+
// (modelOf) before Grok sees the plain model
|
|
766
901
|
api: { ...(was.api ?? {}), id: m.id, url: BASE, npm: "@ai-sdk/openai" },
|
|
767
902
|
limit: { ...(was.limit ?? {}), context: m.context || was.limit?.context || 0, output: was.limit?.output ?? 0 },
|
|
768
903
|
capabilities: {
|
|
@@ -782,4 +917,4 @@ export const GrokAuthPlugin = async ({ client }) => {
|
|
|
782
917
|
}
|
|
783
918
|
|
|
784
919
|
// for tests
|
|
785
|
-
export const _internal = { rewrite, objectRoot, bodyText, limited, HOLD_MS }
|
|
920
|
+
export const _internal = { rewrite, objectRoot, bodyText, limited, HOLD_MS, windowsOf, modelOf }
|
package/package.json
CHANGED