Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

fix(auth): prefer Grok subscription for images and videos

Soohong Kime3d620cb6758
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 234fbcf..7fdee09 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,7 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
## Unreleased (v2.2.0)
- Grok images now call xAI Imagine directly for generation and one-to-five-reference editing, without spawning Grok Build. The default image model is `grok-imagine-image-2.0`; `--model` now selects the image API model. Responses are decoded and published as verified PNGs with existing chroma cleanup preserved.
-- Images and videos share one credential reader: `XAI_API_KEY` first, otherwise the user's Grok login (`GROK_HOME` supported). Image reports expose the auth source and API endpoint. The workflow guide checks the same source and explicitly confirms API-credit billing for either media type. Expired login and request failures stop without agent fallback or automatic image request retries.
+- Images and videos share one credential reader: the user's Grok subscription login first (`GROK_HOME` supported), even with `XAI_API_KEY` configured. Only an absent login file permits API-credit use; invalid, expired or rejected logins never fall back to it. Image reports expose the auth source and API endpoint. The workflow guide checks the same source and explicitly confirms API-credit billing for either media type. Expired login and request failures stop without agent fallback or automatic image request retries.
- Standalone image-to-video requests are routed by the sprite-gen skill itself; no separate video skill is needed.
- The flat-border colour that decides the painted key no longer has to balance its keyed channels. Grok paints `#FF00FF` as (216, 46, 147) / (225, 52, 155) / (236, 59, 161) — blue/red ≈ 0.68, under the 0.8 balance the interior family rule (`is_key_family`) demands — so `detect_background_key_rgb` fell back to the declared key and, at ~120 from pure magenta, the whole background survived (2026-09-11 rev3 objects). A border is already background evidence: the new border rule `is_border_key_candidate` (keyed channels lit, unkeyed channels dark and under 35 % of the brightest keyed one — a superset of `is_key_family`) is the one function `detect_background_key_rgb`, `cutout --key auto`, `video-canvas --key` and the `video-frames` residual/subject split classify the border with. The interior rule is unchanged; hot pink (250, 77, 150) and purple (213, 112, 246) inside the subject still survive.
diff --git a/docs/gen.md b/docs/gen.md
index 7b09603..0e03335 100644
--- a/docs/gen.md
+++ b/docs/gen.md
@@ -52,8 +52,9 @@ The default is `grok-imagine-image-2.0`. `--model` selects an **image API model*
not a Grok Build reasoning model.
Image and video calls share `sprite_gen/gen/xai.py` for credentials and JSON
-transport. `XAI_API_KEY` takes precedence (console credits); otherwise the
-user's Grok login is read from `GROK_HOME` or `~/.grok`. See
+transport. The user's Grok subscription login (`GROK_HOME` or `~/.grok`) takes
+precedence even when `XAI_API_KEY` is set. Only an absent login file permits the
+API key (console credits); an invalid, expired or rejected login never does. See
[authentication and expiry](video.md#setup--pick-one-credential)
for setup. No Grok executable is needed during generation with a valid credential.
No agent, credential fallback or automatic retry is started on failure.
diff --git a/docs/user-workflow.md b/docs/user-workflow.md
index ca7cb0e..e960f58 100644
--- a/docs/user-workflow.md
+++ b/docs/user-workflow.md
@@ -34,7 +34,7 @@ $SPRITE_GEN_ROOT/.venv/bin/sprite-gen workflow --kind sprite \
Login, subscription and quota are separate facts. Codex uses `codex login status`; Grok uses the shared image/video credential reader, without rewriting its auth file. Neither probe proves the current media entitlement or remaining quota: those fields remain `unknown`. When access has not independently been established for the current account and request, ask the user once and pass `--confirmed-access codex` or `--confirmed-access grok`. An explicit account/access statement already in the conversation can answer this question; never manufacture confirmation from a saved provider preference. Known failed/missing credentials remain blocked even with confirmation. A successful generation is not a permanent entitlement cache.
-For Grok images and videos, the existing resolver can select `XAI_API_KEY` when configured. The guide names the separate API-credit billing and requires `--confirm-api-billing` from an explicit user choice before that route becomes ready. It never silently switches from subscription use to API credit. No keys, tokens, account IDs or subscription assertions are saved as preferences, and provider diagnostics do not echo raw credential output.
+For Grok images and videos, the shared resolver prefers the subscription login even when `XAI_API_KEY` is configured. It selects that key only when no login file exists; an expired or invalid login stays blocked. The guide names the separate API-credit billing and requires `--confirm-api-billing` from an explicit user choice before that route becomes ready. It never silently switches from subscription use to API credit. No keys, tokens, account IDs or subscription assertions are saved as preferences, and provider diagnostics do not echo raw credential output.
The documented login commands are [Codex CLI login status](https://developers.openai.com/codex/cli/reference) and [Grok CLI login](https://docs.x.ai/build/cli/reference). These are authentication contracts, not subscription-verification endpoints. Native token parsing and shared credential priority stay owned by [video](video.md).
diff --git a/docs/video.md b/docs/video.md
index 692639e..fef96b0 100644
--- a/docs/video.md
+++ b/docs/video.md
@@ -18,10 +18,13 @@ forms, and every run reports which one it used.
| `grok-login` (default) | the `grok` CLI signed in once | your SuperGrok **Imagine quota** (no console spend) | install the grok CLI, run `grok login` (`--oauth` for a browser, `--device-auth` for a headless box). It writes `~/.grok/auth.json`; this tool only reads it. |
| `XAI_API_KEY` | an xAI console API key | console credit | `export XAI_API_KEY=xai-…` |
-Resolution order is fixed: **`XAI_API_KEY` wins when set**, otherwise the grok
-login file (`GROK_HOME` relocates `~/.grok`). Neither is a fallback for the other —
-a set-but-empty `XAI_API_KEY` is an error, and with no key and no login the run
-stops with both setup paths spelled out.
+Resolution order is fixed for both images and videos: **the Grok subscription
+login wins**, even when `XAI_API_KEY` is set. `GROK_HOME` relocates `~/.grok`.
+Only when no login file exists can the configured API key use console credits.
+An expired, unreadable, corrupt or API-rejected login stops the request; it never
+switches to API credit. An empty API key is ignored when the login is usable,
+but is an error when no login exists. With neither credential, the run stops
+with both setup paths spelled out.
### The login token expires — and this tool does not refresh it
@@ -32,7 +35,7 @@ it has passed, the run fails with the refresh prescription instead of gambling o
a 403 mid-upload:
```
-video: the grok login token expired at 2026-09-08T10:56:34Z (now …); nothing was uploaded.
+xai: the grok login token expired at 2026-09-08T10:56:34Z (now …); nothing was uploaded.
refresh it with any grok CLI command that reaches the API, e.g. `grok -p ok --output-format plain`,
or sign in again with `grok login`. This tool never rewrites ~/.grok/auth.json itself.
```
diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.py
index b04e1f0..3940e9b 100644
--- a/sprite_gen/gen/video.py
+++ b/sprite_gen/gen/video.py
@@ -7,9 +7,9 @@ module behind the sprite-gen skill's standalone `video` command.
Credentials are the user's own and never live in this repository. Two sources,
resolved in a fixed order and always reported (`auth_source`):
-1. `XAI_API_KEY` - an xAI console key (the explicit, environment-level choice).
-2. the grok CLI login file `~/.grok/auth.json` (SuperGrok Imagine quota via the
+1. the grok CLI login file `~/.grok/auth.json` (SuperGrok Imagine quota via the
OIDC access token the CLI stored at `grok login`). `GROK_HOME` relocates it.
+2. `XAI_API_KEY` - an xAI console key, only when no grok login file exists.
The login token expires (about six hours, 2026-09-08 실측) and the grok CLI is the
only writer of that file, so an expired token is not refreshed here: the run
diff --git a/sprite_gen/gen/xai.py b/sprite_gen/gen/xai.py
index b72ef3c..923a43e 100644
--- a/sprite_gen/gen/xai.py
+++ b/sprite_gen/gen/xai.py
@@ -1,8 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
"""Shared xAI credentials and JSON transport for direct image/video generation.
-XAI_API_KEY takes precedence; otherwise use the user's Grok login. The Grok
-CLI alone writes/refreshes that login. Never spawn an agent or switch sources.
+The user's Grok subscription login takes precedence over XAI_API_KEY. The key
+is used only when no login file exists. The Grok CLI alone writes/refreshes
+that login. Never spawn an agent or switch sources after a login failure.
"""
from __future__ import annotations
@@ -58,10 +59,8 @@ def _parse_expiry(raw: str) -> datetime:
def _load_grok_login(auth_path: Path, *, now: datetime) -> Credential:
if not auth_path.is_file():
raise SystemExit(
- f"xai: no xAI credential — {AUTH_ENV} is not set and there is no grok login at "
- f"{auth_path}.\n"
- f" either sign in once with `{GROK_LOGIN_COMMAND}` (SuperGrok Imagine quota, no API key), "
- f"or export {AUTH_ENV}=<your xAI console key>."
+ f"xai: grok login path {auth_path} is not a readable file; "
+ f"run `{GROK_LOGIN_COMMAND}`. Refusing API-credit fallback."
)
try:
auth = json.loads(auth_path.read_text(encoding="utf-8"))
@@ -94,15 +93,30 @@ def _load_grok_login(auth_path: Path, *, now: datetime) -> Credential:
def resolve_credential(*, env: dict[str, str] | None = None, now: datetime | None = None) -> Credential:
- """Pick the credential in the fixed order: XAI_API_KEY, then the grok login file."""
+ """Prefer the subscription login; a failed login never switches to API credit."""
env = os.environ if env is None else env
now = now or datetime.now(timezone.utc)
+ auth_path = grok_home() / "auth.json"
+ # Only absence allows the API key. Broken links/directories are invalid
+ # logins too, not permission to switch to another billing source.
+ try:
+ auth_path.lstat()
+ except FileNotFoundError:
+ pass
+ except OSError as exc:
+ raise SystemExit(f"xai: cannot inspect grok login file {auth_path}; refusing API-credit fallback") from exc
+ else:
+ return _load_grok_login(auth_path, now=now)
api_key = (env.get(AUTH_ENV) or "").strip()
if api_key:
return Credential(token=api_key, source=AUTH_SOURCE_API_KEY)
if AUTH_ENV in env and not api_key:
- raise SystemExit(f"xai: {AUTH_ENV} is set but empty; unset it to use the grok login, or give it a value")
- return _load_grok_login(grok_home() / "auth.json", now=now)
+ raise SystemExit(f"xai: {AUTH_ENV} is set but empty and no grok login exists; run `{GROK_LOGIN_COMMAND}` or give the key a value")
+ raise SystemExit(
+ f"xai: no xAI credential — no grok login at {auth_path} and {AUTH_ENV} is not set.\n"
+ f" sign in with `{GROK_LOGIN_COMMAND}` (SuperGrok Imagine quota, no API key), "
+ f"or export {AUTH_ENV}=<your xAI console key>."
+ )
HttpCall = Callable[[str, str, str, dict | None], tuple[int, Any]]
@@ -129,5 +143,3 @@ def http_json(method: str, url: str, token: str, body: dict | None = None, *, ti
return exc.code, {"raw": raw[:400]}
except (urllib.error.URLError, TimeoutError, OSError) as exc:
raise SystemExit("xai: request failed or timed out; no automatic retry (the server may have accepted it)") from exc
-
-
diff --git a/tests/gen/test_grok_provider.py b/tests/gen/test_grok_provider.py
index a7b36f5..93c6860 100644
--- a/tests/gen/test_grok_provider.py
+++ b/tests/gen/test_grok_provider.py
@@ -26,8 +26,9 @@ def encoded_image(fmt="JPEG"):
@pytest.fixture
-def api(monkeypatch):
+def api(monkeypatch, tmp_path):
monkeypatch.setenv("XAI_API_KEY", "synthetic-secret")
+ monkeypatch.setenv("GROK_HOME", str(tmp_path / "no-login"))
monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("Grok Build must never be spawned"))
state = {"status": 200, "body": {"data": [{"b64_json": encoded_image()}]}, "calls": []}
@@ -172,3 +173,38 @@ def test_image_guide_requires_explicit_api_billing_confirmation(tmp_path, api, m
ready = guide.guide("image", **options, confirm_api_billing=True)
assert ready["status"] == "ready"
+
+def _subscription_login(tmp_path, monkeypatch):
+ monkeypatch.setenv("GROK_HOME", str(tmp_path))
+ (tmp_path / "auth.json").write_text(json.dumps({"account": {
+ "key": "subscription-token", "expires_at": "2100-01-01T00:00:00Z"}}))
+
+
[email protected]("status", [200, 403, 429])
+def test_images_use_subscription_even_with_api_key(tmp_path, api, monkeypatch, status):
+ _subscription_login(tmp_path, monkeypatch)
+ api["status"] = status
+ out = tmp_path / "out.png"
+ if status != 200:
+ with pytest.raises(SystemExit, match=f"HTTP {status}"):
+ gen.generate_image("grok", "x", out)
+ assert not out.exists()
+ else:
+ result = gen.generate_image("grok", "x", out)
+ assert result.extra["auth_source"] == "grok-login"
+ assert len(api["calls"]) == 1
+ assert api["calls"][0][0].get_header("Authorization") == "Bearer subscription-token"
+
+
[email protected]("kind", ["image", "sprite"])
+def test_guide_prefers_subscription_without_api_billing_question(tmp_path, api, monkeypatch, kind):
+ _subscription_login(tmp_path, monkeypatch)
+ monkeypatch.setenv("SPRITE_GEN_CONFIG_DIR", str(tmp_path / "settings"))
+ choices = {"image_provider": "grok"}
+ if kind == "sprite":
+ choices["motion_method"] = "grok-video"
+ result = guide.guide(kind, choices=choices, confirmed_access=("grok",))
+ assert result["status"] == "ready"
+ assert all(item["billing"] == "subscription" for item in result["access"])
+ assert not any(question["field"] == "confirm_api_billing" for question in result["questions"])
+ assert api["calls"] == []
diff --git a/tests/gen/test_video.py b/tests/gen/test_video.py
index f8b2dfa..654062d 100644
--- a/tests/gen/test_video.py
+++ b/tests/gen/test_video.py
@@ -63,8 +63,15 @@ def _request(tmp_path: Path, **overrides) -> video.VideoRequest:
# --- credential resolution -------------------------------------------------
-def test_api_key_env_wins_over_grok_login(tmp_path: Path, monkeypatch) -> None:
[email protected]("api_key", ["xai-console", "", " "])
+def test_grok_login_wins_over_api_key_env(tmp_path: Path, monkeypatch, api_key) -> None:
monkeypatch.setenv("GROK_HOME", str(_login_file(tmp_path)))
+ cred = video.resolve_credential(env={"XAI_API_KEY": api_key}, now=NOW)
+ assert cred.token == "tok" and cred.source == video.AUTH_SOURCE_GROK_LOGIN
+
+
+def test_api_key_is_used_only_without_a_login_file(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("GROK_HOME", str(tmp_path / "no-login"))
cred = video.resolve_credential(env={"XAI_API_KEY": "xai-console"}, now=NOW)
assert cred == video.Credential(token="xai-console", source=video.AUTH_SOURCE_API_KEY)
@@ -95,7 +102,7 @@ def test_missing_login_and_key_prescribes_both_setups(tmp_path: Path, monkeypatc
def test_empty_api_key_env_is_refused_not_ignored(tmp_path: Path, monkeypatch) -> None:
- monkeypatch.setenv("GROK_HOME", str(_login_file(tmp_path)))
+ monkeypatch.setenv("GROK_HOME", str(tmp_path / "no-login"))
with pytest.raises(SystemExit, match="XAI_API_KEY is set but empty"):
video.resolve_credential(env={"XAI_API_KEY": " "}, now=NOW)
@@ -269,3 +276,53 @@ def test_unified_cli_exposes_video() -> None:
parser = cli._build_parser()
args = parser.parse_args(["video", "--image", "a.png", "--prompt", "p", "--out", "o.mp4"])
assert args.command == "video"
+
+
[email protected]("contents, message", [
+ ('{"account":{"key":"subscription","expires_at":"2000-01-01T00:00:00Z"}}', "expired"),
+ ('{', "cannot read grok login"),
+ ('{"account":{}}', "no access token"),
+ ('{"a":{"key":"one"},"b":{"key":"two"}}', "holds 2 account"),
+])
+def test_invalid_login_never_falls_back_to_configured_key(tmp_path, monkeypatch, contents, message):
+ monkeypatch.setenv("GROK_HOME", str(tmp_path))
+ auth = tmp_path / "auth.json"
+ auth.write_text(contents)
+ with pytest.raises(SystemExit, match=message):
+ video.resolve_credential(env={"XAI_API_KEY": "console-key"}, now=NOW)
+ assert auth.read_text() == contents
+
+
+def test_login_directory_never_permits_api_credit(tmp_path, monkeypatch):
+ monkeypatch.setenv("GROK_HOME", str(tmp_path))
+ (tmp_path / "auth.json").mkdir()
+ with pytest.raises(SystemExit, match="not a readable file"):
+ video.resolve_credential(env={"XAI_API_KEY": "console-key"}, now=NOW)
+
+
+def test_uninspectable_login_never_permits_api_credit(tmp_path, monkeypatch):
+ monkeypatch.setenv("GROK_HOME", str(tmp_path))
+ original = Path.lstat
+ def denied(path, *args, **kwargs):
+ if path == tmp_path / "auth.json":
+ raise PermissionError("test")
+ return original(path, *args, **kwargs)
+ monkeypatch.setattr(Path, "lstat", denied)
+ with pytest.raises(SystemExit, match="refusing API-credit fallback"):
+ video.resolve_credential(env={"XAI_API_KEY": "console-key"}, now=NOW)
+
+
[email protected]("status", [200, 403, 429])
+def test_video_uses_subscription_with_api_key_present(tmp_path, monkeypatch, status):
+ monkeypatch.setenv("GROK_HOME", str(_login_file(tmp_path, key="subscription-token", expires_at="2100-01-01T00:00:00Z")))
+ monkeypatch.setenv("XAI_API_KEY", "console-key")
+ api = _FakeApi(post=(status, {"error": "rejected"}) if status != 200 else (200, {"request_id": "req-1"}))
+ request = _request(tmp_path)
+ if status != 200:
+ with pytest.raises(SystemExit, match=f"HTTP {status}"):
+ video.generate_video(request, call=api.call, download=api.download, sleep=lambda _: None)
+ assert len(api.calls) == 1 and not request.out.exists()
+ else:
+ result = video.generate_video(request, call=api.call, download=api.download, sleep=lambda _: None)
+ assert result.auth_source == "grok-login"
+ assert all(call[2] == "subscription-token" for call in api.calls)