@magpie-community/opencode-grok-auth
v0.2.15
Published
OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in
Maintainers
Readme
@magpie-community/opencode-grok-auth
Grok with a SuperGrok or X Premium+ subscription, through the sign-in of
xAI's Grok Build CLI. Provider id: grok.
It needs Grok Build installed:
curl -fsSL https://x.ai/cli/install.sh | bash # macOS, Linux
irm https://x.ai/cli/install.ps1 | iex # WindowsIt is found in the installer's folder (GROK_BIN_DIR, GROK_HOME/bin,
~/.grok/bin), or on PATH when it lives under a .grok folder, so that
another program named grok isn't taken for it. Where the installer can't
run, such as a container without curl, put the binary in a folder of your
own and set GROK_BIN_DIR to it. magpie installs Grok Build itself, as
the installer does, before a sign-in that needs it.
Images and speech
Images in a request (Anthropic image blocks, OpenAI image_url, Responses
input_image) go to Grok as sent, and its models take them. Speech to text
is the one Grok Build's voice dictation uses: magpie's
/v1/audio/transcriptions (model grok/grok-4.7, any of the account's
models) is sent on to xAI's api.x.ai/v1/stt with the account's sign-in.
language is passed on; json, text and verbose_json are answered, and
translations are refused.
Sign in
- Sign in with Grok Build (device code) runs
grok login --device-authand opens the page it prints. Approve the sign-in there, and the CLI finishes it.- If the CLI isn't signed in yet, the sign-in goes to the CLI's own home
(
GROK_HOME, else~/.grok), as if you had rungrok login. - If it is signed in, the sign-in goes to a home of this plugin's,
$XDG_CONFIG_HOME/opencode-grok-auth/<random>(else under~/.config). Grok Build's own sign-in stays as it is. - The account is told apart by its email, else its xAI user id (an
account signed in through X can have no email).
GROK_AUTH_PATHis left out of the CLI's run, so the sign-in lands in that home. - When the CLI finishes but leaves no sign-in there, the failure says which file it read and what it found.
- If the CLI isn't signed in yet, the sign-in goes to the CLI's own home
(
- Use Grok Build's current sign-in takes the account the CLI is signed in to, with nothing to approve.
- Import CPA Grok account JSON copies one enabled xAI OAuth account from
a CLIProxyAPI (CPA) account JSON file (CPA keeps it as
~/.cli-proxy-api/xai-<email>.json) into a private home for this plugin. CPA and Grok Build rotate the same refresh token, so stop using that account in CPA before importing it. The file is read, never rewritten.
Where the sign-in is kept
The CLI keeps the sign-in in its home, as auth.json. OpenCode (or
magpie) keeps where that home is, the token and its expiry. Importing a CPA
account writes only its translated xAI OAuth fields to a private home owned
by this plugin; the selected CPA file is left unchanged.
The plugin reads auth.json; Grok Build refreshes the token, which changes
each time. The plugin runs grok models in that home, so the CLI renews
it, then reads it again:
- magpie renews the token 5 minutes before it ends, through the plugin's
auth.refresh, once for the account and before its requests, models and usage need it. magpie saves what the CLI gave. - OpenCode doesn't call that hook: there the token is renewed when it is 5 minutes from expiring, before a request.
- The CLI runs once for a home at a time: a request or renewal that comes while it runs waits for it and reads what it gave. A token the CLI already renewed is taken as it is.
- Grok can turn a token away before its
expires_at. A request, model list or usage read that gets 401 has the CLI renew the token and asks once more with the new one.grok modelsrenews a token only in its last 5 minutes (GROK_AUTH_EARLY_INVALIDATION_SECS, 300), so that run is given a minute more than the token has left, which makes the CLI renew it now. A token Grok turns away within a minute or so of being made isn't renewed that way. - When the CLI's run leaves the token as it was, the 401 or error says
Grok Build couldn't renew the sign-in, with what the CLI said. The CLI
says it only in its own log (
<home>/logs/unified.jsonl): agrok modelswhose renewal failed exits 0 with the model list it shows signed out. The plugin reads that run's lines there. A token left as it was that is still good, with nothing failed, isn't a failure: the CLI renews only near the token's end. For Grok Build's own home ("Use Grok Build's current sign-in") opening Grok Build and sending it a message renews it. For a home of the plugin's (a second account, an imported one), opening Grok Build doesn't touch it: add the account in magpie again. - Not every 401 is Grok judging the token. A token it doesn't take is
answered at once with
Invalid or expired credentials (…). Another 401, such asAuthentication requiredafter a minute or more, on a token the CLI left as it was and not yet ended, has passed by itself within minutes. Unless the CLI failed renewing it, that is a 503 withRetry-After: 60that keeps the sign-in and says how long Grok took: magpie rests the account a moment and asks the next one. It never says to sign in again. - A request, model list or usage read turned away waits on the CLI's renewal 15 seconds at most. The run goes on, and the next one to ask takes what it gave.
- When the CLI no longer holds a sign-in in that home (
grok logout, or one it cleared after xAI refused it for good), or its run says only a new sign-in helps (Failed(ManualLogin),needs a new sign-in,invalid_grant, a revoked refresh token), the sign-in has ended: magpie shows the account as one to sign in again, and the CLI isn't run there again until the home holds another token. - Any other run that couldn't renew (no network,
Failed(SelfHealing)) is tried again later, backing off: 1 minute after the first failure, then 2, 4 and so on, up to an hour between runs. Whatever asks meanwhile gets the failure already met, without running the CLI. A renewal that works starts the count again. Failed(SelfHealing)is xAI's token endpoint failing, or not answering within the ~5 secondsgrok modelswaits for it. It passes by itself: it never says to sign in again, and magpie's log gets nothing of it for its first 30 minutes. One that lasts longer is told once, with what the CLI logged. A request on a token past its end still fails, saying why.- magpie's log gets what failed once for each state (failing, ended), not
on every try. The state is kept in the home (
magpie-renewal.json, with a hash of the token, never the token), so a plugin update, a restart or a second magpie doesn't tell it again. - An
auth.jsonthat is empty or not JSON is most likely one the CLI is writing: it is read again for about half a second, then the last sign-in read whole there stands, as the CLI itself keeps its previous one. It is never taken as signed out. The plugin takes noauth.json.lock.
Grok Build's unified build
Grok Build can update itself to its unified build, Grok Build 2 (grok
2.0.9 (…, public 1.0.100) [unified], agent-host-<version>-<os>-<arch>
in ~/.grok/downloads). That build signs in through Cursor: its
grok login opens a cursor.com sign-in, and what it keeps in auth.json
is a key-bound Cursor session (cursor::session) for Cursor's servers,
which Grok's API (cli-chat-proxy.grok.com) doesn't take. Its
grok models exits 0 and leaves the xAI sign-in as it was, so it renews
nothing magpie reads. The plugin never reads a cursor:: entry as the
xAI sign-in.
When the grok the plugin finds is the unified build, it renews and signs
in with the newest native grok-1.x build left in ~/.grok/downloads
(made for this system, runnable) instead. It knows the unified build by
the name grok links to (~/.grok/bin/grok → agent-host →
../downloads/agent-host-…, or a GROK_BIN_DIR link to it), by a
grok.exe that is a copy of it on Windows, or by Grok Build's
channel-switch.json saying it switched that bin to agent-host. A
grok that links to or copies a native build is run as before, whatever
that record says.
With no native build left, the failure says so, and how to go back to the native build. Grok Build's own way is
grok update --legacy-stablewhich saves build = "legacy" in ~/.grok/config.toml and keeps it off
the unified build. Grok Build offers it only on the unified rollout; where
it isn't offered, put the previous build back
curl -fsSL https://x.ai/cli/install.sh | bash -s 1.0.92& ([scriptblock]::Create((irm https://x.ai/cli/install.ps1))) -Version 1.0.92then auto_update = false in ~/.grok/config.toml (Grok Build's home,
GROK_HOME if set). The version is the one channel-switch.json names
as the build before the switch.
Requests
Requests go to https://cli-chat-proxy.grok.com/v1, OpenAI's Responses
API (@ai-sdk/openai), signed as the CLI signs them:
Authorization: Bearer <token>x-xai-token-auth: xai-grok-clix-grok-client-identifier: grok-shellx-grok-client-mode: headlessx-grok-client-versionandUser-Agent: grok-shell/<version> (<os>; <arch>). The version is 1.0.41, or the installed CLI's if it is newer.x-grok-model-override: the request's model. A window suffix (grok-4.7@500k) is the plain model (grok-4.7) here and in the body.x-grok-context-window: the token count a suffixed model names (500000for@500k). The plain id sends no such header and stays on the default window.x-grok-conv-id: the request'sprompt_cache_key.x-grok-doom-loop-check: 1024andx-grok-exact-repetition-check: 64on a Responses request, as Grok Build sends them: the proxy then stops a reply that repeats itself after ~1K tokens instead of letting it run on.- A Responses stream that dies before its first byte (the connection
reset, with nothing sent yet) is asked again, with up to three attempts
in all. The first try and the retries share one token renewal on 401
for a request that can be replayed. A 429 goes back as itself. Once a
byte has arrived,
response.createdand reasoning included, it is passed on at once. A later cut is not asked again and not rewritten: the stream ends, and magpie 0.1.3298 or newer closes it asresponse.failedwithcreated_atandsequence_number. The frame this plugin used to write hadcreated_atand still nosequence_number, so Grok Build reportedmissing field sequence_number. An upstreamresponse.failed,errororresponse.incompleteis passed on unchanged. Cancelling the turn stops the read and is not asked again.
The backend turns away some of what a request may carry, so the plugin leaves these out:
- tools of types it doesn't take (a freeform
apply_patch, namespaces) external_web_accesson web search- a
tool_choicenaming a dropped type - a
tool_choicewith no tools beside it (magpie sends"none"so when a client turned tools off) - a reasoning item's
"content": null
Plain Codex collaboration items (agent_message) reach Grok as user
messages, with their sender, recipient and content preserved. Sealed or
unrecognized content stays unchanged; the plugin does not decrypt tasks.
Native X search (optional)
In magpie, open the Grok provider, turn on Native X search under Plugin options, and save. It is off by default; changes apply to the next request without restarting or signing in again.
When enabled, the plugin offers Grok its native x_search tool. Grok
decides whether to search; enabling it does not force a search on every
request. Existing function tools and X search filters are preserved, and
an existing x_search is not duplicated. Explicit choices such as none,
required, a named tool, or allowed_tools never gain another tool.
The option applies to Responses requests, including Chat Completions, Anthropic Messages and Gemini requests that magpie converts to Responses, in streaming and non-streaming mode. Use magpie with the fix for yetone/magpie#3110 so that those clients' tool-disable choices reach the plugin.
For compatibility with older gateways, a request that reaches the plugin
with neither tools nor a tool_choice is left unchanged. This can happen
when magpie translates a client's automatic choice on an empty tool list.
To use X search through a translated API, send at least one function tool;
the plugin adds X search alongside it. An explicit tool-disable choice
always takes precedence.
This uses the existing grok provider's login, models and quota reporting;
no extra plugin is needed. It applies to that provider's models when the
upstream supports X search, not to Grok models served through Cursor or
another provider. Report problems in
this repository.
Models
Grok 4.7 until signed in. Signed in, the models are the ones the account
lists at /v1/models (Responses models only), each with its reasoning
efforts as variants.
context_window is the default window and keeps the plain id, so a saved
grok-4.7 stays a 256k model. Each other size in context_windows is
offered beside it, named Grok 4.7 @ 500k with id grok-4.7@500k and
that many tokens as its window. A request for it sends
x-grok-context-window: 500000. The proxy serves up to its largest
window either way and refuses past it; the header names the window the
caller asked to compact against. Pick grok-4.7@500k where a client
compacts at the advertised window, such as Claude Code.
Usage
magpie's card shows the credits of the current period
(/v1/billing?format=credits): weekly for SuperGrok, with on-demand
spending beside it when it has a cap.
Grok's billing says nothing of a plan's rate limit, so a free account can
read 0% used while its requests come back 429. After a 429 the card shows
a spent "Rate limit" window until the reset it named (Retry-After, or a
*ratelimit*reset* header). When it named none, the window stays until a
request goes through, or for 5 minutes.
Grok Bot's separate allowance is shown by the Cursor plugin. Sign in there with the Cursor account linked in Grok Bot, including for access through SuperGrok.
