Skip to content

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

feat(gen): call Grok Imagine directly for images and edits

Soohong Kimabef26b9cbb1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cbd1c25..234fbcf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,7 +2,11 @@
All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.
-## Unreleased (v2.1.2)
+## 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.
+- 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.
- The painted key's erase ball is bounded by the background it came from: it erases the pixels that carry the key's hue signature plus whatever inside the ball is 8-connected to them (the antialiased rim), not an isolated look-alike patch inside the subject — hot pink sits 46 from Grok's magenta and would otherwise have been cut out. The declared key's ball stays position-blind. The 96 radius is unchanged.
diff --git a/SKILL.md b/SKILL.md
index 1867cc1..00ed7e8 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,14 +1,12 @@
---
name: sprite-gen
-version: 2.1.1
-description: "Generates images and game sprites through GPT or Grok with guided provider choices, separate saved defaults, automatic cleanup and optional curation. Handles sprite requests, ordinary image generation/editing, chroma removal, animation atlases, video loops, 큐레이션뷰, image candidates, 팔레트 스왑, palette swap, recolor, rig layers and engine exports."
+version: 2.2.0
+description: "Generates images and game sprites through GPT or Grok with guided provider choices, separate saved defaults, automatic cleanup and optional curation. Handles sprite requests, ordinary image generation/editing, standalone image-to-video clips (i2v, animate this still, 그록 영상, 이매진 비디오, 스틸 움직여줘), chroma removal, animation atlases, video loops, 큐레이션뷰, image candidates, 팔레트 스왑, palette swap, recolor, rig layers and engine exports."
license: Apache-2.0
depends_on:
required_bins:
- name: codex
why: "gen --provider codex (image_gen via ChatGPT OAuth)"
- - name: grok
- why: "gen --provider grok (Imagine via xAI OAuth)"
- name: ffmpeg
why: "video-frames (clip -> frames) and video-set"
- name: img2webp
@@ -44,10 +42,14 @@ modes:
# Sprite Gen
-Two user entry points: **make sprites** or **make an image**. Existing generation, extraction and export tools do the work; the user chooses the result and provider.
+Three user entry points: **make sprites**, **make an image**, or **animate a still into a video**. Existing generation, extraction and export tools do the work; the user chooses the result and provider.
## Start every generation request here
+For a standalone video clip, read [video](docs/video.md) and use `sprite-gen video`.
+This route works from any agent engine and delivers a verified MP4 plus report.
+For sprites or ordinary images, use the guides below.
+
Read [user-workflow](docs/user-workflow.md), then run the appropriate read-only guide:
```bash
@@ -62,6 +64,7 @@ Pass choices already stated in the request. The guide checks access, combines ex
| Task | Entry | Contract |
|---|---|---|
| GPT image sprites | `prepare`, `gen-set --provider codex`, `extract`, compose and QA | [atlas-workflow](docs/atlas-workflow.md) |
+| Standalone video / animate a still | `video` | [video](docs/video.md) |
| Grok video sprites | `video-set` | [video-pipeline](docs/video-pipeline.md) |
| Ordinary image or edit | `gen --provider codex` or `gen --provider grok` | [gen](docs/gen.md) |
| Base and direction anchors | `anchor` | [directional-anchor-workflow](docs/directional-anchor-workflow.md) |
diff --git a/docs/frame-interpolation.md b/docs/frame-interpolation.md
index ffe7751..ab58ee1 100644
--- a/docs/frame-interpolation.md
+++ b/docs/frame-interpolation.md
@@ -29,17 +29,16 @@ clean discrete pixels. codex preserved identity best; grok drifted; RIFE smeared
## Auth prerequisites (applies to the curator Tween button too)
-Generation always runs on the **server machine's provider CLI** — the browser/webview
+Generation always runs through the **server machine's image provider** — the browser/webview
never sees or carries any credential. The Tween button POSTs to the local curation
-server, which spawns `codex`/`grok` as a subprocess; those CLIs use their own
-machine-local OAuth sessions.
+server, which uses the shared image providers (Codex subprocess or direct Grok API) with their own
+machine-local credentials.
- Required on the machine running the curation server / CLI:
- `codex` CLI installed and logged in (ChatGPT OAuth) for `--provider codex`
- - `grok` CLI installed and logged in (xAI OAuth) for `--provider grok`
-- Setup and provider topology: [`docs/gen.md`](gen.md) (the SKILL's
- `required_bins` names both CLIs).
-- Not authenticated / CLI missing → the provider fails loudly and the message
+ - a valid Grok login or `XAI_API_KEY` for `--provider grok` (see [gen](gen.md))
+- Setup and provider topology: [`docs/gen.md`](gen.md).
+- Not authenticated / required Codex CLI missing → the provider fails loudly and the message
surfaces as-is (CLI stderr / curator status bar). No silent fallback between
providers.
diff --git a/docs/gen.md b/docs/gen.md
index f0d14ef..0d29ec0 100644
--- a/docs/gen.md
+++ b/docs/gen.md
@@ -13,7 +13,7 @@ Providers (Gemini/OpenRouter/fal/BytePlus are intentionally **not** included):
| Provider | Backend | Auth | Output truth | Transparency strategy |
|---|---|---|---|---|
| `codex` | codex `image_gen` | ChatGPT OAuth | inline base64 in the session rollout jsonl, decoded deterministically | **`native`** — image_gen returns a real alpha channel when asked (measured, then published) |
-| `grok` | grok Imagine `image_gen` / `image_edit` | xAI OAuth | file grok is told to write, verified by PNG magic | `chroma` — Imagine returns JPEG only; generate on a key and matte it out |
+| `grok` | direct Imagine `/images/generations` or `/images/edits` | Grok login or `XAI_API_KEY` | inline bytes decoded and re-encoded as a verified PNG | `chroma` — Imagine returns JPEG only; generate on a key and matte it out |
The strategy is declared **once**, on the adapter (`Provider.transparency`), and is
the only place that says what a backend can do. See
@@ -44,23 +44,36 @@ backend), `provider_resolved_from` (`explicit` / `SPRITE_GEN_DEFAULT_PROVIDER` /
`hard-default` / `fallback-from-codex`), and `provider_fallback` when a fallback
happened.
-## Provider and visible-worker topology
-
-Provider selection and user-facing worker/agent creation are orthogonal:
-
-| Layer | Canonical path | Responsibility |
-|---|---|---|
-| Generation request | `generate_sprite_image.py --provider grok` | Select the engine provider for one image request. |
-| Provider adapter | `GrokProvider` | Build the prompt, choose Imagine `image_gen` or `image_edit`, and verify the requested PNG. |
-| Headless provider process | `grok -p --sandbox workspace --always-approve` | Execute the xAI-authenticated Imagine tool call. |
-| Image model tool | Imagine `image_gen` / `image_edit` | Generate a new image, or edit from references. |
-| Visible worker/agent | (caller's orchestrator) | Creating a user-facing worker surface that may invoke the generation request is the orchestrator's own concern; it does not select or replace the provider. |
-
-Therefore the direct Grok chain is `generate_sprite_image.py --provider grok`
-→ `GrokProvider` → `grok -p --always-approve` → Imagine
-`image_gen`/`image_edit`. `GrokProvider` owns the headless agent process lifecycle;
-the chain does not require or route through a separate user-facing skill/task, and
-it is not a second visible-worker topology.
+## Direct Grok calls and authentication
+
+`sprite-gen gen --provider grok` → `GrokProvider` → xAI Imagine API. The same
+path works from any agent engine; no Grok Build subprocess is started.
+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
+[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.
+
+New images use `/v1/images/generations`; one reference uses `/v1/images/edits`
+with `image`, two to five use `images` in input order. A single-reference edit
+inherits its source aspect ratio; `--aspect-ratio` applies to generation and
+multi-reference edits. Invalid reference files and more than five references
+fail before upload. Base64 output is requested, decoded, and converted to a real
+PNG without resizing before atomic publication. Missing or malformed image data
+fails without replacing an existing raw output.
+
+Image reports include `extra.auth_source`, `extra.transport: "xai-api"`,
+`extra.endpoint`, and `extra.aspect_ratio_source`. Tokens, signed URLs and raw
+API error bodies are not reported. Skipping the agent removes its startup and
+reasoning overhead; speed and account-quota savings are not benchmarked guarantees.
+
+API contracts: [image generation](https://docs.x.ai/developers/model-capabilities/images/generation),
+[image editing](https://docs.x.ai/developers/model-capabilities/images/editing),
+[multi-image editing](https://docs.x.ai/developers/model-capabilities/images/multi-image-editing).
## CLI
@@ -69,7 +82,7 @@ sprite-gen gen \
[--provider codex|grok] # optional; default = SPRITE_GEN_DEFAULT_PROVIDER env → codex (observable grok fallback if codex is down)
--prompt "…" # or --prompt-file PROMPT.txt
--out DEST.png \
- [--ref REF.png ...] # repeatable; grok routes refs through image_edit
+ [--ref REF.png ...] # repeatable; Grok accepts up to five references
[--transparent [--alpha-mode auto|native|chroma] [--chroma-key magenta|green]] \
[--white-check CHECK.png] \
[--aspect-ratio 1:1] # grok only (1:1, 16:9, 9:16, 4:3, 3:4, auto)
@@ -155,12 +168,7 @@ change it; and no `config.toml` feature toggle grants it. The remedy is to point
`CODEX_HOME` at a Codex state root whose account provides image generation
(`codex login status`), or to use `--provider grok`. The adapter fails loudly with
exactly that, rather than falling back on its own.
-- **grok** — runs `grok -p … --sandbox workspace --always-approve` (media/shell must be
- auto-approved; plain acceptEdits blocks tool execution and returns an empty answer).
- grok is instructed to write the final PNG to an exact absolute path; we then verify
- that file's PNG magic. No `--effort` is passed (the grok-build image model 400s on
- `reasoningEffort`). With `--ref`, grok uses `image_edit` on the reference instead of
- `image_gen`.
+- **grok** — uses the [direct API contract](#direct-grok-calls-and-authentication) above.
## Sprite-row usage
diff --git a/docs/user-workflow.md b/docs/user-workflow.md
index 0dee5e9..ca7cb0e 100644
--- a/docs/user-workflow.md
+++ b/docs/user-workflow.md
@@ -32,11 +32,11 @@ $SPRITE_GEN_ROOT/.venv/bin/sprite-gen workflow --kind sprite \
## Authentication and subscriptions
-Login, subscription and quota are separate facts. Codex uses `codex login status`; Grok uses the existing video's 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.
+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 video, 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 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.
-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 video credential priority stay owned by [video](video.md).
+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).
## Finish after delivering files
diff --git a/docs/video.md b/docs/video.md
index e29b3cc..692639e 100644
--- a/docs/video.md
+++ b/docs/video.md
@@ -5,8 +5,8 @@
`sprite-gen video` animates one still into a short mp4 through **Grok Imagine**
(xAI `POST /v1/videos/generations`). It is the video counterpart of
[`sprite-gen gen`](gen.md): one call = one still (+ prompt) → one **verified** mp4
-on disk plus a machine-readable report. The `grok-imagine-video` skill is a thin
-shuttle over this command.
+on disk plus a machine-readable report. The sprite-gen skill routes standalone
+video requests here from any agent engine.
No credential is shipped with this repository. You bring your own, in one of two
forms, and every run reports which one it used.
@@ -41,7 +41,7 @@ Why not refresh it here: `auth.json` is the grok CLI's file, the refresh token i
it may rotate, and a second writer would break the login the user relies on
everywhere else. The same shape as `sprite-gen gen`'s `codex login status` gate.
-### Why the direct API call and not Grok Build's `image_to_video` tool
+### Direct API transport
Grok Build's built-in `image_to_video` tool posts without `output.upload_url`, and
on Zero-Data-Retention teams the API answers `HTTP 400 — Zero Data Retention teams
diff --git a/pyproject.toml b/pyproject.toml
index d326778..0896fd8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta"
name = "sprite-gen"
# Release discipline: keep this package metadata version synchronized with
# SKILL.md's `version:` field in the same release commit.
-version = "2.1.1"
+version = "2.2.0"
description = "Component-row pipeline for clean 2D game sprites and animation atlases"
readme = "README.md"
license = "Apache-2.0"
diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.py
index 7331932..2b9f4f5 100644
--- a/sprite_gen/gen/base.py
+++ b/sprite_gen/gen/base.py
@@ -57,7 +57,7 @@ def provider_subprocess_env() -> dict[str, str]:
"""Environment for a headless generation subprocess.
The parent environment minus known orchestrator session env families, so a
- spawned engine (`codex exec`, `grok`) is a clean standalone process — it
+ spawned engine (`codex exec`) is a clean standalone process — it
neither impersonates the spawning agent nor gets strangled by the
orchestrator's hooks. SSoT for every provider's `subprocess.run` env —
providers must not spawn with the inherited env directly.
diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.py
index 1c3c8ed..4d54041 100644
--- a/sprite_gen/gen/grok_provider.py
+++ b/sprite_gen/gen/grok_provider.py
@@ -1,122 +1,109 @@
# SPDX-License-Identifier: Apache-2.0
-"""Grok Imagine provider (xAI OAuth, no API key).
-
-grok build ships an Imagine skill with `image_gen` (text -> new image) and
-`image_edit` (edit an existing image). Unlike codex, grok's tool result is not
-inline base64 — grok (the agent) holds the produced file and can move it. We run
-grok headless with `--always-approve` (media/shell must be auto-approved; plain
-`--write`/acceptEdits blocks tool execution and returns an empty answer) and
-instruct it to write the final PNG to an exact absolute path. Truth is the PNG on
-disk at that path, never grok's text (No Silent Fallback).
-
-Model note: image tools route to the grok-build model, which 400s on
-`reasoningEffort` — so this provider never passes `--effort`.
-"""
-
+"""Direct Grok Imagine image generation/editing, with no Grok Build process."""
from __future__ import annotations
-import subprocess
+import base64
+import binascii
+import io
+import os
+import tempfile
import time
from pathlib import Path
-from .base import (
- GEN_TIMEOUT_SECONDS,
- TRANSPARENCY_CHROMA,
- GenRequest,
- GenTimeoutError,
- ProviderRun,
- provider_binary,
- provider_subprocess_env,
- verify_png,
-)
+from PIL import Image, UnidentifiedImageError
+
+from . import xai
+from .base import GEN_TIMEOUT_SECONDS, TRANSPARENCY_CHROMA, GenRequest, ProviderRun, verify_png
+
+DEFAULT_MODEL = "grok-imagine-image-2.0"
+MAX_REFS = 5
+ASPECT_RATIOS = ("auto", "1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3",
+ "2:1", "1:2", "19.5:9", "9:19.5", "20:9", "9:20", "21:9", "5:2")
+
+def _reference(path: Path) -> dict:
+ try:
+ data = path.read_bytes()
+ with Image.open(io.BytesIO(data)) as source:
+ source.load()
+ mime = Image.MIME.get(source.format)
+ if mime not in ("image/png", "image/jpeg", "image/webp"):
+ raise ValueError("reference must be PNG, JPEG or WebP")
+ except (OSError, ValueError, UnidentifiedImageError) as exc:
+ raise SystemExit(f"grok-gen: invalid reference image {path}") from exc
+ return {"type": "image_url", "url": f"data:{mime};base64," + base64.b64encode(data).decode("ascii")}
-def _build_prompt(request: GenRequest) -> str:
- raw = str(request.raw)
- aspect = request.aspect_ratio or "auto"
- lines = [
- "You are generating exactly one image, then saving it. Do only this:",
- "",
- ]
+
+def _request_body(request: GenRequest) -> tuple[str, dict]:
+ if not request.prompt.strip():
+ raise SystemExit("grok-gen: empty prompt")
+ if len(request.refs) > MAX_REFS:
+ raise SystemExit(f"grok-gen: at most {MAX_REFS} reference images are supported")
+ if request.aspect_ratio is not None and request.aspect_ratio not in ASPECT_RATIOS:
+ raise SystemExit(f"grok-gen: unsupported aspect ratio {request.aspect_ratio!r}")
+ body = {"model": request.model or DEFAULT_MODEL, "prompt": request.prompt,
+ "n": 1, "response_format": "b64_json"}
+ if request.aspect_ratio and len(request.refs) != 1:
+ body["aspect_ratio"] = request.aspect_ratio
if request.refs:
- ref_list = ", ".join(str(Path(r).expanduser().resolve()) for r in request.refs)
- lines += [
- f"1. Call `image_edit` once using these source image(s) as reference: {ref_list}",
- " Apply this instruction while keeping the referenced subject/style consistent:",
- f" {request.prompt}",
- ]
- else:
- lines += [
- f"1. Call `image_gen` once with aspect_ratio `{aspect}` and this prompt:",
- f" {request.prompt}",
- ]
- lines += [
- f"2. Save the produced image to EXACTLY this absolute path as a PNG file: {raw}",
- " Overwrite it if it already exists. Use the shell to copy/convert the produced",
- " file to that path if the tool wrote it elsewhere. Do not resize or restyle it.",
- f"3. Print only the final absolute path ({raw}). Do not do anything else — no extra",
- " images, no edits, no commentary, no other files.",
- ]
- return "\n".join(lines)
+ images = [_reference(Path(ref)) for ref in request.refs]
+ if len(images) == 1:
+ body["image"] = images[0]
+ else:
+ body["images"] = images
+ return "/images/edits", body
+ return "/images/generations", body
-class GrokProvider:
- """Generate one image through grok Imagine `image_gen` / `image_edit`."""
+def _publish_image(item: dict, path: Path) -> None:
+ # Inline bytes avoid signed download URLs and bearer forwarding.
+ encoded = item.get("b64_json")
+ if not isinstance(encoded, str) or not encoded:
+ raise SystemExit("grok-gen: response has no b64_json image; nothing published")
+ try:
+ data = base64.b64decode(encoded, validate=True)
+ with Image.open(io.BytesIO(data)) as source:
+ source.load()
+ # Imagine may return JPEG. Encode a real PNG without resizing.
+ png = io.BytesIO()
+ source.convert("RGBA" if "A" in source.getbands() else "RGB").save(png, format="PNG")
+ except (ValueError, binascii.Error, OSError, UnidentifiedImageError) as exc:
+ raise SystemExit("grok-gen: response image is invalid; nothing published") from exc
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".png", delete=False) as tmp:
+ temp = Path(tmp.name)
+ try:
+ temp.write_bytes(png.getvalue())
+ verify_png(temp)
+ os.replace(temp, path)
+ finally:
+ temp.unlink(missing_ok=True)
+
+class GrokProvider:
name = "grok"
- # Grok Imagine Image 2.0 returns image/jpeg from both the API and the CLI
- # tools (2026-09-08 실측, 4/4 drawn checkerboards) — no alpha path exists.
transparency = TRANSPARENCY_CHROMA
def generate(self, request: GenRequest, workdir: Path) -> ProviderRun:
if request.native_alpha:
- raise SystemExit(
- "grok-gen: native alpha was requested but grok Imagine cannot return an "
- f"alpha channel (transparency strategy is {self.transparency!r}); "
- "generate on a chroma key instead"
- )
- request.raw.parent.mkdir(parents=True, exist_ok=True)
- cmd = [
- provider_binary("grok"),
- "-p",
- _build_prompt(request),
- "--output-format",
- "plain",
- "--sandbox",
- "workspace",
- "--always-approve",
- "--cwd",
- str(workdir),
- ]
- if request.model:
- cmd += ["-m", request.model]
-
+ raise SystemExit("grok-gen: grok Imagine cannot return an alpha channel; generate on a chroma key instead")
+ endpoint, body = _request_body(request)
+ credential = xai.resolve_credential()
started = time.monotonic()
- # env: parent minus orchestrator session env — same reason as codex
- # (base.provider_subprocess_env). grok hooks are off today, but a headless
- # generation subprocess must never carry the parent worker's endpoint
- # identity regardless of the engine's current hook config.
- try:
- completed = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8",
- env=provider_subprocess_env(), timeout=GEN_TIMEOUT_SECONDS)
- except subprocess.TimeoutExpired:
- raise GenTimeoutError(
- f"grok-gen: no completion within {GEN_TIMEOUT_SECONDS}s — "
- "provider stream stalled; child killed (gen-timeout)")
- elapsed = time.monotonic() - started
- if completed.returncode != 0:
- tail = (completed.stderr or "").strip().splitlines()[-20:]
- raise SystemExit(
- f"grok-gen: grok exited {completed.returncode} (empty answer + non-zero = blocked exec or login).\n"
- + "\n".join(tail)
- )
- # Verify the real file grok wrote, not its text. Missing/not-a-PNG fails loudly.
- verify_png(request.raw)
-
- return ProviderRun(
- provider=self.name,
- elapsed_seconds=elapsed,
- model=request.model,
- session_id=None,
- extra={"stdout_tail": "\n".join((completed.stdout or "").strip().splitlines()[-5:])},
- )
+ status, reply = xai.http_json("POST", xai.API_BASE + endpoint, credential.token,
+ body, timeout=GEN_TIMEOUT_SECONDS)
+ if status in (401, 403):
+ remedy = (f"run `{xai.GROK_LOGIN_COMMAND}` to renew the login" if credential.source == xai.AUTH_SOURCE_GROK_LOGIN
+ else f"check {xai.AUTH_ENV}")
+ raise SystemExit(f"grok-gen: credential {credential.source} rejected (HTTP {status}); {remedy}")
+ # Error bodies can include prompts, credentials or URLs; do not echo them.
+ if status != 200:
+ raise SystemExit(f"grok-gen: image request failed (HTTP {status}); no retry or provider fallback")
+ items = reply.get("data") if isinstance(reply, dict) else None
+ if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):
+ raise SystemExit("grok-gen: expected exactly one image in the response; nothing published")
+ _publish_image(items[0], request.raw)
+ return ProviderRun(provider=self.name, elapsed_seconds=time.monotonic() - started,
+ model=body["model"], extra={"auth_source": credential.source,
+ "transport": "xai-api", "endpoint": endpoint,
+ "aspect_ratio_source": "reference" if len(request.refs) == 1 else "request-or-auto"})
diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.py
index ab588a2..b04e1f0 100644
--- a/sprite_gen/gen/video.py
+++ b/sprite_gen/gen/video.py
@@ -2,8 +2,7 @@
"""Image-to-video through Grok Imagine (xAI `POST /v1/videos/generations`).
One call = one still (+ prompt) -> one verified mp4 on disk. This is the engine
-module behind `sprite-gen video`; the general `grok-imagine-video` skill is a thin
-shuttle over this command.
+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`):
@@ -35,137 +34,28 @@ import time
import urllib.error
import urllib.request
from dataclasses import dataclass, field
-from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable
from sprite_gen.spec.runio import atomic_write_text
+from .xai import (
+ API_BASE, AUTH_ENV, AUTH_SOURCE_API_KEY, AUTH_SOURCE_GROK_LOGIN,
+ HTTP_TIMEOUT_SECONDS, GROK_REFRESH_COMMAND, GROK_LOGIN_COMMAND,
+ Credential, HttpCall, grok_home, resolve_credential, http_json,
+)
-API_BASE = "https://api.x.ai/v1"
DEFAULT_MODEL = "grok-imagine-video-1.5"
RESOLUTIONS = ("480p", "720p", "1080p")
ASPECT_RATIOS = ("1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3")
DURATION_MIN, DURATION_MAX = 1, 15
-AUTH_ENV = "XAI_API_KEY"
-AUTH_SOURCE_API_KEY = "XAI_API_KEY"
-AUTH_SOURCE_GROK_LOGIN = "grok-login"
POLL_INTERVAL_SECONDS = 4.0
POLL_TIMEOUT_SECONDS = int(os.environ.get("SPRITE_GEN_VIDEO_TIMEOUT_SECONDS", "600"))
-HTTP_TIMEOUT_SECONDS = 120
# Every mp4/mov starts with a size-prefixed `ftyp` box: bytes 4..8 spell it.
MP4_FTYP_OFFSET = 4
MP4_FTYP = b"ftyp"
_DONE_STATUSES = ("done", "complete", "completed")
_FAILED_STATUSES = ("failed", "error", "expired")
-# The refresh instruction for an expired login. The grok CLI rewrites the token
-# the next time it talks to the API — measured 2026-09-08 with a one-line prompt
-# (`grok -p ok`): expires_at moved from 10:56Z to 18:26Z. `grok login` is the
-# full re-sign-in for a revoked or missing login.
-GROK_REFRESH_COMMAND = "grok -p ok --output-format plain"
-GROK_LOGIN_COMMAND = "grok login"
-
-
-def grok_home() -> Path:
- configured = os.environ.get("GROK_HOME")
- if configured is None:
- return Path.home() / ".grok"
- if not configured.strip():
- raise SystemExit("video: GROK_HOME is set but empty; refusing to guess the grok home")
- return Path(configured).expanduser().resolve()
-
-
-@dataclass(frozen=True)
-class Credential:
- token: str
- source: str # AUTH_SOURCE_API_KEY | AUTH_SOURCE_GROK_LOGIN
- expires_at: str | None = None
-
-
-def _parse_expiry(raw: str) -> datetime:
- text = raw.strip()
- if text.endswith("Z"):
- text = text[:-1] + "+00:00"
- parsed = datetime.fromisoformat(text)
- if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
- return parsed
-
-
-def _load_grok_login(auth_path: Path, *, now: datetime) -> Credential:
- if not auth_path.is_file():
- raise SystemExit(
- f"video: 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>."
- )
- try:
- auth = json.loads(auth_path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError) as exc:
- raise SystemExit(f"video: cannot read grok login file {auth_path}: {exc}") from exc
- entries = [entry for entry in (auth.values() if isinstance(auth, dict) else []) if isinstance(entry, dict)]
- if len(entries) != 1:
- raise SystemExit(
- f"video: grok login file {auth_path} holds {len(entries)} account entr"
- f"{'y' if len(entries) == 1 else 'ies'}; expected exactly one — refusing to pick one silently. "
- f"Run `{GROK_LOGIN_COMMAND}` to reset it."
- )
- entry = entries[0]
- token = entry.get("key")
- if not isinstance(token, str) or not token.strip():
- raise SystemExit(f"video: grok login file {auth_path} has no access token; run `{GROK_LOGIN_COMMAND}`.")
- expires_at = entry.get("expires_at")
- if isinstance(expires_at, str) and expires_at.strip():
- try:
- expiry = _parse_expiry(expires_at)
- except ValueError as exc:
- raise SystemExit(f"video: grok login file {auth_path} has an unreadable expires_at {expires_at!r}: {exc}") from exc
- if expiry <= now:
- raise SystemExit(
- f"video: the grok login token expired at {expires_at} (now {now.isoformat()}); nothing was uploaded.\n"
- f" refresh it with any grok CLI command that reaches the API, e.g. `{GROK_REFRESH_COMMAND}`, "
- f"or sign in again with `{GROK_LOGIN_COMMAND}`. This tool never rewrites {auth_path} itself."
- )
- return Credential(token=token, source=AUTH_SOURCE_GROK_LOGIN, expires_at=expires_at if isinstance(expires_at, str) else None)
-
-
-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."""
- env = os.environ if env is None else env
- now = now or datetime.now(timezone.utc)
- 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"video: {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)
-
-
-HttpCall = Callable[[str, str, str, dict | None], tuple[int, Any]]
-
-
-def http_json(method: str, url: str, token: str, body: dict | None = None) -> tuple[int, Any]:
- data = None if body is None else json.dumps(body).encode("utf-8")
- request = urllib.request.Request(url, data=data, method=method)
- request.add_header("Authorization", f"Bearer {token}")
- request.add_header("Accept", "application/json")
- if body is not None:
- request.add_header("Content-Type", "application/json")
- try:
- with urllib.request.urlopen(request, timeout=HTTP_TIMEOUT_SECONDS) as response:
- raw = response.read().decode("utf-8")
- return response.status, (json.loads(raw) if raw else {})
- except urllib.error.HTTPError as exc:
- raw = exc.read().decode("utf-8", "replace")
- try:
- return exc.code, json.loads(raw)
- except json.JSONDecodeError:
- return exc.code, {"raw": raw[:400]}
- except urllib.error.URLError as exc:
- raise SystemExit(f"video: cannot reach {url}: {exc.reason}") from exc
-
-
def http_download(url: str, token: str) -> bytes:
request = urllib.request.Request(url)
try:
diff --git a/sprite_gen/gen/xai.py b/sprite_gen/gen/xai.py
new file mode 100644
index 0000000..b72ef3c
--- /dev/null
+++ b/sprite_gen/gen/xai.py
@@ -0,0 +1,133 @@
+# 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.
+"""
+from __future__ import annotations
+
+import json
+import os
+import urllib.error
+import urllib.request
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable
+
+API_BASE = "https://api.x.ai/v1"
+AUTH_ENV = "XAI_API_KEY"
+AUTH_SOURCE_API_KEY = "XAI_API_KEY"
+AUTH_SOURCE_GROK_LOGIN = "grok-login"
+HTTP_TIMEOUT_SECONDS = 120
+
+# The refresh instruction for an expired login. The grok CLI rewrites the token
+# the next time it talks to the API — measured 2026-09-08 with a one-line prompt
+# (`grok -p ok`): expires_at moved from 10:56Z to 18:26Z. `grok login` is the
+# full re-sign-in for a revoked or missing login.
+GROK_REFRESH_COMMAND = "grok -p ok --output-format plain"
+GROK_LOGIN_COMMAND = "grok login"
+
+
+def grok_home() -> Path:
+ configured = os.environ.get("GROK_HOME")
+ if configured is None:
+ return Path.home() / ".grok"
+ if not configured.strip():
+ raise SystemExit("xai: GROK_HOME is set but empty; refusing to guess the grok home")
+ return Path(configured).expanduser().resolve()
+
+
+@dataclass(frozen=True)
+class Credential:
+ token: str = field(repr=False)
+ source: str # AUTH_SOURCE_API_KEY | AUTH_SOURCE_GROK_LOGIN
+ expires_at: str | None = None
+
+
+def _parse_expiry(raw: str) -> datetime:
+ text = raw.strip()
+ if text.endswith("Z"):
+ text = text[:-1] + "+00:00"
+ parsed = datetime.fromisoformat(text)
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed
+
+
+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>."
+ )
+ try:
+ auth = json.loads(auth_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ raise SystemExit(f"xai: cannot read grok login file {auth_path}: {exc}") from exc
+ entries = [entry for entry in (auth.values() if isinstance(auth, dict) else []) if isinstance(entry, dict)]
+ if len(entries) != 1:
+ raise SystemExit(
+ f"xai: grok login file {auth_path} holds {len(entries)} account entr"
+ f"{'y' if len(entries) == 1 else 'ies'}; expected exactly one — refusing to pick one silently. "
+ f"Run `{GROK_LOGIN_COMMAND}` to reset it."
+ )
+ entry = entries[0]
+ token = entry.get("key")
+ if not isinstance(token, str) or not token.strip():
+ raise SystemExit(f"xai: grok login file {auth_path} has no access token; run `{GROK_LOGIN_COMMAND}`.")
+ expires_at = entry.get("expires_at")
+ if isinstance(expires_at, str) and expires_at.strip():
+ try:
+ expiry = _parse_expiry(expires_at)
+ except ValueError as exc:
+ raise SystemExit(f"xai: grok login file {auth_path} has an unreadable expires_at {expires_at!r}: {exc}") from exc
+ if expiry <= now:
+ raise SystemExit(
+ f"xai: the grok login token expired at {expires_at} (now {now.isoformat()}); nothing was uploaded.\n"
+ f" refresh it with any grok CLI command that reaches the API, e.g. `{GROK_REFRESH_COMMAND}`, "
+ f"or sign in again with `{GROK_LOGIN_COMMAND}`. This tool never rewrites {auth_path} itself."
+ )
+ return Credential(token=token, source=AUTH_SOURCE_GROK_LOGIN, expires_at=expires_at if isinstance(expires_at, str) else None)
+
+
+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."""
+ env = os.environ if env is None else env
+ now = now or datetime.now(timezone.utc)
+ 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)
+
+
+HttpCall = Callable[[str, str, str, dict | None], tuple[int, Any]]
+
+
+def http_json(method: str, url: str, token: str, body: dict | None = None, *, timeout: float = HTTP_TIMEOUT_SECONDS) -> tuple[int, Any]:
+ data = None if body is None else json.dumps(body).encode("utf-8")
+ request = urllib.request.Request(url, data=data, method=method)
+ request.add_header("Authorization", f"Bearer {token}")
+ request.add_header("Accept", "application/json")
+ if body is not None:
+ request.add_header("Content-Type", "application/json")
+ try:
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ raw = response.read().decode("utf-8")
+ return response.status, (json.loads(raw) if raw else {})
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
+ raise SystemExit("xai: response was not valid JSON") from exc
+ except urllib.error.HTTPError as exc:
+ raw = exc.read().decode("utf-8", "replace")
+ try:
+ return exc.code, json.loads(raw)
+ except json.JSONDecodeError:
+ 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/sprite_gen/workflow/access.py b/sprite_gen/workflow/access.py
index 4e4978f..84e5700 100644
--- a/sprite_gen/workflow/access.py
+++ b/sprite_gen/workflow/access.py
@@ -6,7 +6,7 @@ import shutil
import subprocess
from sprite_gen.gen.base import provider_binary, provider_subprocess_env
-from sprite_gen.gen.video import AUTH_SOURCE_API_KEY, resolve_credential
+from sprite_gen.gen.xai import AUTH_SOURCE_API_KEY, resolve_credential
def probe_access(provider: str, *, video: bool = False) -> dict:
@@ -29,15 +29,12 @@ def probe_access(provider: str, *, video: bool = False) -> dict:
return {**result, "login": "ready"}
if provider != "grok":
raise ValueError(f"unknown provider: {provider}")
- if not video and shutil.which("grok") is None:
- return {**result, "login": "unavailable", "reason": "grok CLI is not installed"}
try:
- # Image generation uses CLI login. Video may instead use the configured
- # API key; the existing video resolver alone owns that precedence.
- credential = resolve_credential(env=None if video else {})
+ # Images and videos use the same direct API credential precedence.
+ credential = resolve_credential()
except (SystemExit, OSError, ValueError):
return {**result, "login": "unavailable", "reason": "grok credential missing, expired or unreadable; check grok login"}
if credential.source == AUTH_SOURCE_API_KEY:
return {**result, "login": "ready", "billing": "api-credit",
- "reason": "Video will use XAI_API_KEY and separate API credit; confirm this billing choice."}
+ "reason": "Grok media will use XAI_API_KEY and separate API credit; confirm this billing choice."}
return {**result, "login": "ready"}
diff --git a/tests/gen/test_gen.py b/tests/gen/test_gen.py
index f3279a1..e444659 100644
--- a/tests/gen/test_gen.py
+++ b/tests/gen/test_gen.py
@@ -71,8 +71,7 @@ def test_provider_binary_resolves_windows_style_path_shims(monkeypatch) -> None:
def test_provider_run_uses_scrubbed_env(tmp_path: Path, monkeypatch) -> None:
- # Both providers must route their subprocess.run through the scrubbed env.
- import sprite_gen.gen.grok_provider as grok_provider
+ # Codex remains the subprocess provider; Grok now calls the API directly.
monkeypatch.setenv("CODEX_HOME", str(tmp_path))
seen: dict[str, dict | None] = {}
@@ -107,36 +106,11 @@ def test_provider_run_uses_scrubbed_env(tmp_path: Path, monkeypatch) -> None:
assert "ORCHESTRATOR_RUNTIME_ENDPOINT_ID" not in seen["codex"]
assert seen["codex_encoding"] == "utf-8"
- grok_raw = tmp_path / "grok_raw.png"
-
- def _fake_grok_run(cmd, **kwargs):
- seen["grok"] = kwargs.get("env")
- seen["grok_cmd"] = cmd
- seen["grok_encoding"] = kwargs.get("encoding")
- # grok's truth is the PNG on disk — write one so verify_png passes.
- Image.new("RGBA", (8, 8), (255, 0, 255, 255)).save(grok_raw)
- class _C:
- returncode = 0
- stdout = str(grok_raw)
- stderr = ""
- return _C()
-
- monkeypatch.setattr(grok_provider.subprocess, "run", _fake_grok_run)
- grok_provider.GrokProvider().generate(
- GenRequest(prompt="a mushroom", raw=grok_raw), tmp_path
- )
- assert seen["grok"] is not None
- assert "ORCHESTRATOR_RUNTIME_ENDPOINT_ID" not in seen["grok"]
- assert seen["grok_encoding"] == "utf-8"
-
def test_provider_commands_use_the_single_resolved_binary(tmp_path: Path, monkeypatch) -> None:
- import sprite_gen.gen.grok_provider as grok_provider
-
monkeypatch.setenv("CODEX_HOME", str(tmp_path))
seen: dict[str, list[str]] = {}
monkeypatch.setattr(codex_provider, "provider_binary", lambda _name: "C:/bin/codex.CMD")
- monkeypatch.setattr(grok_provider, "provider_binary", lambda _name: "C:/bin/grok.CMD")
class _CodexCompleted:
returncode = 0
@@ -158,22 +132,7 @@ def test_provider_commands_use_the_single_resolved_binary(tmp_path: Path, monkey
GenRequest(prompt="도구", raw=tmp_path / "codex.png"), tmp_path
)
- grok_out = tmp_path / "grok.png"
-
- class _GrokCompleted:
- returncode = 0
- stdout = "ok"
- stderr = ""
-
- def fake_grok(cmd, **_kwargs):
- seen["grok"] = cmd
- Image.new("RGBA", (2, 2), (1, 2, 3, 255)).save(grok_out)
- return _GrokCompleted()
-
- monkeypatch.setattr(grok_provider.subprocess, "run", fake_grok)
- grok_provider.GrokProvider().generate(GenRequest(prompt="도구", raw=grok_out), tmp_path)
assert seen["codex"][0] == "C:/bin/codex.CMD"
- assert seen["grok"][0] == "C:/bin/grok.CMD"
def test_json_report_writes_utf8_bytes_without_reconfiguring_stdout(monkeypatch) -> None:
@@ -404,19 +363,6 @@ def test_codex_prompt_reaches_the_child_process(tmp_path: Path, monkeypatch) ->
assert "a mushroom" in seen["input"]
-def test_grok_prompt_switches_on_refs(tmp_path: Path) -> None:
- from sprite_gen.gen import grok_provider
-
- raw = tmp_path / "raw.png"
- no_ref = grok_provider._build_prompt(GenRequest(prompt="a red apple", raw=raw, aspect_ratio="1:1"))
- assert "image_gen" in no_ref and "1:1" in no_ref and str(raw) in no_ref
-
- ref = tmp_path / "ref.png"
- ref.write_bytes(_png_bytes())
- with_ref = grok_provider._build_prompt(GenRequest(prompt="same char waving", raw=raw, refs=[ref]))
- assert "image_edit" in with_ref and str(ref.resolve()) in with_ref
-
-
def test_chroma_key_transparent_clears_magenta(tmp_path: Path) -> None:
src = tmp_path / "src.png"
img = Image.new("RGBA", (6, 6), (255, 0, 255, 255))
@@ -722,11 +668,11 @@ def test_real_providers_declare_their_transparency_strategy() -> None:
assert grok_provider.GrokProvider.transparency == gen_base.TRANSPARENCY_CHROMA
-def test_grok_refuses_a_native_alpha_request_before_spawning(tmp_path: Path, monkeypatch) -> None:
+def test_grok_refuses_a_native_alpha_request_before_upload(tmp_path: Path, monkeypatch) -> None:
from sprite_gen.gen import grok_provider
spawned: list = []
- monkeypatch.setattr(grok_provider.subprocess, "run", lambda *a, **k: spawned.append(a))
+ monkeypatch.setattr(grok_provider.xai, "http_json", lambda *a, **k: spawned.append(a))
with pytest.raises(SystemExit, match="cannot return an alpha channel"):
grok_provider.GrokProvider().generate(
GenRequest(prompt="x", raw=tmp_path / "raw.png", native_alpha=True), tmp_path
diff --git a/tests/gen/test_grok_provider.py b/tests/gen/test_grok_provider.py
new file mode 100644
index 0000000..a7b36f5
--- /dev/null
+++ b/tests/gen/test_grok_provider.py
@@ -0,0 +1,174 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Direct API contract, offline: no credentials, network or Grok subprocess."""
+import base64
+import io
+import json
+import subprocess
+import urllib.error
+
+import pytest
+from PIL import Image
+
+from sprite_gen import gen
+from sprite_gen.gen import grok_provider as grok, xai
+from sprite_gen.gen.base import GenRequest
+from sprite_gen.workflow import access, guide
+
+
+def encoded_image(fmt="JPEG"):
+ image = Image.new("RGB", (12, 8), (255, 0, 255))
+ for x in range(4, 8):
+ for y in range(2, 6):
+ image.putpixel((x, y), (0, 0, 200))
+ buf = io.BytesIO()
+ image.save(buf, format=fmt)
+ return base64.b64encode(buf.getvalue()).decode()
+
+
+def api(monkeypatch):
+ monkeypatch.setenv("XAI_API_KEY", "synthetic-secret")
+ 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": []}
+
+ class Response:
+ def __enter__(self):
+ return self
+ def __exit__(self, *args):
+ pass
+ @property
+ def status(self):
+ return state["status"]
+ def read(self):
+ return json.dumps(state["body"]).encode()
+
+ def open_request(request, *, timeout):
+ state["calls"].append((request, timeout))
+ return Response()
+
+ monkeypatch.setattr(xai.urllib.request, "urlopen", open_request)
+ return state
+
+
+def test_generation_decodes_jpeg_to_png_without_agent(tmp_path, api):
+ result = gen.generate_image("grok", "a blue square", tmp_path / "out.png", aspect_ratio="3:2")
+ request, timeout = api["calls"][0]
+ body = json.loads(request.data)
+ assert request.full_url == "https://api.x.ai/v1/images/generations"
+ assert request.get_header("Authorization") == "Bearer synthetic-secret"
+ assert body == {"model": grok.DEFAULT_MODEL, "prompt": "a blue square", "n": 1,
+ "response_format": "b64_json", "aspect_ratio": "3:2"}
+ assert timeout == grok.GEN_TIMEOUT_SECONDS
+ with Image.open(result.out) as image, Image.open(io.BytesIO(base64.b64decode(encoded_image()))) as original:
+ assert image.format == "PNG" and image.size == (12, 8)
+ assert image.tobytes() == original.tobytes()
+ report = result.to_dict()
+ assert report["extra"]["auth_source"] == "XAI_API_KEY"
+ assert report["extra"]["transport"] == "xai-api"
+ assert report["session_id"] is None
+ assert "synthetic-secret" not in json.dumps(report)
+
+
[email protected]("count", [1, 2, 5])
+def test_reference_edit_preserves_order_and_model(tmp_path, api, count):
+ refs = []
+ for i in range(count):
+ path = tmp_path / f"ref-{i}.png"
+ Image.new("RGB", (12, 8), (i * 40, 0, 0)).save(path)
+ refs.append(path)
+ result = gen.generate_image("grok", "combine these", tmp_path / "edit.png", refs=refs,
+ model="explicit-image-model", aspect_ratio="16:9")
+ request, _ = api["calls"][0]
+ body = json.loads(request.data)
+ assert request.full_url.endswith("/images/edits")
+ images = [body["image"]] if count == 1 else body["images"]
+ assert ("images" in body) == (count > 1)
+ assert ("image" in body) == (count == 1)
+ for ref, entry in zip(refs, images):
+ assert base64.b64decode(entry["url"].split(",", 1)[1]) == ref.read_bytes()
+ assert body["model"] == result.model == "explicit-image-model"
+ assert body.get("aspect_ratio") == (None if count == 1 else "16:9")
+
+
+def test_direct_output_keeps_chroma_pipeline(tmp_path, api):
+ api["body"] = {"data": [{"b64_json": encoded_image("PNG")}]}
+ result = gen.generate_image("grok", "blue square on magenta", tmp_path / "alpha.png", transparent=True)
+ assert result.alpha["strategy"] == "chroma"
+ with Image.open(result.out) as image:
+ assert image.getpixel((0, 0)) == (0, 0, 0, 0)
+ assert image.getpixel((6, 4))[3] == 255
+
+
[email protected]("status", [400, 401, 403, 429, 500])
+def test_api_failure_keeps_existing_output_and_does_not_retry(tmp_path, api, status):
+ api.update(status=status, body={"error": "synthetic-secret https://signed.invalid/private"})
+ out = tmp_path / "existing.png"
+ out.write_bytes(b"existing")
+ with pytest.raises(SystemExit, match=f"HTTP {status}") as error:
+ gen.generate_image("grok", "x", out)
+ assert "synthetic-secret" not in str(error.value)
+ assert out.read_bytes() == b"existing"
+ assert len(api["calls"]) == 1
+
+
[email protected]("body", [{}, {"data": []}, {"data": [None]}, {"data": [{}, {}]},
+ {"data": [{"b64_json": "???"}]},
+ {"data": [{"b64_json": base64.b64encode(b"invalid image").decode()}]},
+ {"data": [{"url": "https://signed.invalid/private"}]}])
+def test_invalid_response_never_reuses_stale_raw(tmp_path, api, body):
+ api["body"] = body
+ raw = tmp_path / "raw.png"
+ raw.write_bytes(b"previous raw")
+ with pytest.raises(SystemExit):
+ grok.GrokProvider().generate(GenRequest("x", raw), tmp_path)
+ assert raw.read_bytes() == b"previous raw"
+ assert len(api["calls"]) == 1
+ assert list(tmp_path.iterdir()) == [raw]
+
+
+def test_invalid_refs_and_aspect_fail_before_upload(tmp_path, api):
+ ref = tmp_path / "ref.png"
+ ref.write_bytes(b"invalid")
+ for options in ({"refs": [ref]}, {"refs": [ref] * 6}, {"aspect_ratio": "bogus"}):
+ with pytest.raises(SystemExit):
+ grok.GrokProvider().generate(GenRequest("x", tmp_path / "raw.png", **options), tmp_path)
+ assert api["calls"] == []
+
+
+def test_expired_login_fails_without_spawn_or_upload(tmp_path, api, monkeypatch):
+ monkeypatch.delenv("XAI_API_KEY")
+ monkeypatch.setenv("GROK_HOME", str(tmp_path))
+ auth = tmp_path / "auth.json"
+ auth.write_text(json.dumps({"account": {"key": "synthetic-secret", "expires_at": "2000-01-01T00:00:00Z"}}))
+ before = auth.read_bytes()
+ with pytest.raises(SystemExit, match="expired"):
+ gen.generate_image("grok", "x", tmp_path / "out.png")
+ assert api["calls"] == [] and auth.read_bytes() == before
+
+
+def test_timeout_does_not_repeat_billable_request(tmp_path, api, monkeypatch):
+ calls = []
+ def timeout(*args, **kwargs):
+ calls.append(args)
+ raise TimeoutError()
+ monkeypatch.setattr(xai.urllib.request, "urlopen", timeout)
+ with pytest.raises(SystemExit, match="no automatic retry"):
+ gen.generate_image("grok", "x", tmp_path / "out.png")
+ assert len(calls) == 1
+
+
[email protected]("video", [False, True])
+def test_access_uses_api_key_without_grok_binary(api, monkeypatch, video):
+ monkeypatch.setattr(access.shutil, "which", lambda _: None)
+ result = access.probe_access("grok", video=video)
+ assert result["login"] == "ready" and result["billing"] == "api-credit"
+
+
+def test_image_guide_requires_explicit_api_billing_confirmation(tmp_path, api, monkeypatch):
+ monkeypatch.setenv("SPRITE_GEN_CONFIG_DIR", str(tmp_path))
+ options = {"choices": {"image_provider": "grok"}, "confirmed_access": ("grok",)}
+ pending = guide.guide("image", **options)
+ assert pending["status"] != "ready"
+ ready = guide.guide("image", **options, confirm_api_billing=True)
+ assert ready["status"] == "ready"
+