Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix: name what every provider call runs on, and announce every metered one
Soohong Kimf8eb9b9b62b3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1a626a3..bcfea76 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,7 +5,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased- **Behavior change: `pixel-draw` runs on your Claude subscription first, and on `ANTHROPIC_API_KEY` only without one** — the order `codex` and `grok` keep. When `claude auth status` says Claude Code is signed in with a subscription (`claude.ai` or `oauth_token`), every call — the drawings, the row repairs, the pick — goes through the unmodified `claude` binary in print mode, from an empty directory, with no tool, no session written and no CLAUDE.md, hook, skill, plugin or MCP server loaded, and costs nothing per call: `report.json` says `auth_source: claude-login`, each call's `mode` is `subscription` and its `cost_usd` `0`, its usage kept. The child never sees `ANTHROPIC_API_KEY`, which print mode would use instead of the login. Without a subscription login the run uses the key as before, billed per call and said on stderr; with neither it is refused naming both, before the run folder is made. A login that refuses a call, has expired or has reached its usage limit fails the call; the run never switches to the key on its own. `--batch` is the API's Message Batches and runs on the key even when signed in. An answer the binary cuts at the output cap is read as `stop_reason: max_tokens`, so the one redraw one effort lower happens on either route. One call may take up to `SPRITE_GEN_CLAUDE_CALL_TIMEOUT_SECONDS` (1800). A `--resume` that reads every call back no longer prints the billing line ([pixel-draw](docs/pixel-draw.md#which-credential-a-call-runs-on)).-- **Tests** — `tests/gen/test_claude_login.py` (the login before the key, the key only without a login, neither refused naming both, a batch on the key without asking the login, an unreadable status refused rather than read as no login, the child's environment without a key or the calling session, a message mapped onto the binary's flags and stdin with its image and schema, the stream-json answer, a cut answer read as max_tokens, a refused or limited login an error and not a switch to the key, no result, a timeout and a missing binary), the subscription, batch and read-back cases in `tests/gen/test_pixel_draw.py`, and `gen.base.env_api_key` in `tests/gen/test_gen.py`.+- **Behavior change: every metered call says so on the terminal, and every report names what a call ran on.** How codex is signed in is one reading, `codex_provider.codex_login` (`codex login status`), for the default provider resolution, `gen --provider codex`, the codex facing check and `workflow`: a codex signed in with an API key used to run with no word about it and the workflow called it a subscription; it now prints the per-call charge line before `codex exec` runs, its report records `extra.auth_source: codex-api-key` (`codex-login` on ChatGPT), and `workflow` asks to confirm the API credit. A codex that is not signed in is refused with the reason before it runs. `gen-set` and `video-set` keep each item's output in its log, but a child's billing line and a default provider switch now also print on the terminal as they happen (`base.run_logged`), each `gen-set` row records `auth_source`, and each `video-set` clip result too. `sound` prints the same billing line as every other metered route (it printed its own) and its receipt records `auth_source`. One function reads a provider key from the environment (`base.env_api_key`: a key, none, or a refusal of an empty one) for Anthropic, OpenAI, xAI and ElevenLabs; one function says what to do when xAI rejects a credential (`xai.rejected_fix`), so `gen --provider grok` now gives the same `grok models` refresh as `video`. `workflow` probes a provider once for its images and videos (they share one credential) and asks the API-credit question by that provider's name rather than always about Grok video. Docs: the credential table in the README, grok's `XAI_API_KEY` route in the help and SKILL.md, the sound billing line, `SPRITE_GEN_GEN_TIMEOUT_SECONDS` and `SPRITE_GEN_CLAUDE_READ_TIMEOUT_SECONDS`, and `gen-set --provider` (`codex` or `grok`).+- **Tests** — `tests/gen/test_claude_login.py` (the login before the key, the key only without a login, neither refused naming both, a batch on the key without asking the login, an unreadable status refused rather than read as no login, the child's environment without a key or the calling session, a message mapped onto the binary's flags and stdin with its image and schema, the stream-json answer, a cut answer read as max_tokens, a refused or limited login an error and not a switch to the key, no result, a timeout and a missing binary), the subscription, batch and read-back cases in `tests/gen/test_pixel_draw.py`, and `gen.base.env_api_key` in `tests/gen/test_gen.py`; `tests/gen/test_codex_login.py` (ChatGPT, an API key and not signed in; the default resolution, `generate` and `workflow` read the same login; an API-key login announces the charge and records it), `base.run_logged` in `tests/gen/test_gen.py`, the ElevenLabs billing line and key refusals in `tests/audio/test_sound.py`.- **New: `background-tile --axis xy` makes one tile seamless in both directions and measures both joins.** It quilts along x, then along y with a cyclic seam: the second seam's two ends, which meet across the x wrap, may differ by one step at most, so the second quilt cannot break the first one's join. The report measures the finished tile on both axes (`axes.x`, `axes.y`, each with its join, quilt seam, `status` and reasons); the top-level `status` is `needs-review` when either axis is, and each reason names its axis. Two separate one-axis runs had no such rule, and the second run's report measured only its own axis. `inspect_tile_xy(image)` measures both joins of any tile ([asset-tools](docs/asset-tools.md#both-axes-a-ground-tile)).- **New: alpha haze cleanup for transparent sheets (`frames.alpha_floor.clear_haze`).** Pixels at or above a floor, and faint pixels within a few pixels of them (an object's anti-aliased edge), are kept byte for byte; every other faint pixel becomes fully transparent. The report measures the haze share before and after and counts the solid and edge pixels that changed (`0`). Used by `ui-kit` (on by default) and `slice-sheet --alpha-floor N` (off by default; writes `<prefix>alpha-cleanup.json`). `slice-sheet --chroma-key none` cuts a sheet that is already transparent on its own alpha ([sheet-slicing](docs/sheet-slicing.md#transparent-sheets)).- **New verb: `ui-kit` splits a game UI kit sheet into nine-slice elements.** `gen --layout-guide ui-kit` attaches a fixed square layout (panel, button, pressed button, card frame, HP and XP bar frames, timer badge) and asks for each element in its box. `ui-kit --sheet uikit.png --out-dir ui/` clears the haze, assigns parts to boxes by centroid, and writes each element's PNG and `ui-kit.json` (or `--report PATH`, which must end in `.json`; each element's `file` is its PNG's path from the report's directory, so a report written outside `--out-dir` still finds its elements): its rectangle, its stretch (`xy`, `x` for the bars, `none` for the badge), nine-slice insets measured so that every corner ornament and end cap lies in a fixed slice, and the content padding (a bar frame's track, a panel's text area). An ornament in the middle of an edge, an empty box or a stray part is reported or refused ([ui-kit](docs/ui-kit.md)). `--layout-guide` alone is still the one-slot figure guide.diff --git a/README.md b/README.mdindex 224015e..065c4be 100644--- a/README.md+++ b/README.md@@ -174,7 +174,17 @@ python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-githu--repo aldegad/sprite-gen --path . --name sprite-gen```-Image generation is part of this engine (`sprite_gen.gen`, providers `codex` and `grok` on a subscription you already pay for, plus an explicit-only `openai` provider for servers and SaaS that bills per call; the general `image-gen` skill is a thin shuttle over it). Video uses **your own** credential — the `grok` CLI login or an `XAI_API_KEY` — and nothing is shipped with the repo ([docs/video.md](docs/video.md)).+Image generation is part of this engine (`sprite_gen.gen`, providers `codex` and `grok` on a subscription you already pay for, plus an explicit-only `openai` provider for servers and SaaS that bills per call; the general `image-gen` skill is a thin shuttle over it). Every call uses **your own** credential, the subscription login first and an API key only without one, and nothing is shipped with the repo:++| Calls | First | Without it | Docs |+|---|---|---|---|+| `gen --provider codex` | the `codex` ChatGPT login | (a codex signed in with an API key bills that key) | [gen](docs/gen.md) |+| `gen --provider grok`, `video*` | the `grok` CLI login | `XAI_API_KEY` | [gen](docs/gen.md#direct-grok-calls-and-authentication), [video](docs/video.md) |+| `pixel-draw` | the `claude` (Claude Code) subscription login | `ANTHROPIC_API_KEY` | [pixel-draw](docs/pixel-draw.md#which-credential-a-call-runs-on) |+| `gen --provider openai` | — | `OPENAI_API_KEY`, named only | [gen](docs/gen.md#subscription-first--openai-is-named-or-it-does-not-run) |+| `sound` | — | `ELEVENLABS_API_KEY` | [sound](docs/sound.md) |++A call on an API key is billed per call and says so on stderr before the request leaves, also inside `gen-set` and `video-set`.`sprite-gen` supports CPython 3.11+; CI runs only 3.14. Python 3.10 is no longer supported. The quickstart needs a Python with working `venv`/`ensurepip`.diff --git a/SKILL.md b/SKILL.mdindex 268031e..44a2a9c 100644--- a/SKILL.md+++ b/SKILL.md@@ -108,7 +108,7 @@ hold the arms still, and check the loop with `handed-check --state walk`.| Compare the currently displayed loop with a final candidate, including after follow-through | `video-loop-compare` | [loop-comparison](docs/loop-comparison.md) || Restore post-processing damage in the current cut from its exact source times, preserving normal cells and playback | `video-source-manifest` → `video-loop-repair` → `video-loop-compare` | [source restoration](docs/loop-comparison.md#restoring-the-active-cut-from-source) || Video sprites from a clip your agent makes with a connected video MCP (ZCRE, 지크) | `video-canvas`, `video-prompt --no-last-frame`, the agent's own MCP tools (quote, user approval, generate, save the mp4), then `video-frames` and `video-loop` (a walk or run with `--anchor motion-auto`, which holds its size), and for a walk or run cut in two or more directions `video-cycle-align --view …` over their loop directories (a set it stops on a loop that may hold two cycles: look at that loop, count its strides, and pass `--cycles <loop>=<k>`; a loop the report lists under `unnamed_feet` — its view could not tell the feet apart, or only by too small a margin (`low-margin`): look at its first candidate frame, say which own foot lands there, and align again with `--foot <loop>=left|right`). `video-set` is not run on this route, so the set stage it runs by default (`--align-cycles auto`) is yours to run. sprite-gen never calls the MCP. Walk, run and jump only: ZCRE's `grok-imagine-video-1.5` has no end frame, so idle, attack and diagonal walks are refused unless `--unpinned` | [video-pipeline](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre) |-| Ordinary image or edit | `gen --provider codex` or `gen --provider grok` (subscription routes) | [gen](docs/gen.md) |+| Ordinary image or edit | `gen --provider codex` or `gen --provider grok` (the subscription login first; without one grok uses `XAI_API_KEY`, and a codex signed in with an API key bills it — both per call, said on stderr) | [gen](docs/gen.md) || Pixel art the model draws directly as a grid, 8–48 px (best at 32 or less): an icon, a prop, a monster, a character still, four directions, a walk draft, a tile — on your Claude subscription (`claude` signed in), or without one on `ANTHROPIC_API_KEY`, **billed per call**; `grid.txt` is the truth, `--grid` re-renders an edited one, `--resume` collects a batch instead of buying it twice | `pixel-draw` | [pixel-draw](docs/pixel-draw.md) || Image generation with no login available (server, container, SaaS) | `gen --provider openai` — server/SaaS route on `OPENAI_API_KEY`, **billed per call**, never a default or a fallback | [gen](docs/gen.md#subscription-first--openai-is-named-or-it-does-not-run) || Base and direction anchors | `anchor` | [directional-anchor-workflow](docs/directional-anchor-workflow.md) |diff --git a/docs/gen.md b/docs/gen.mdindex e608760..7f85c45 100644--- a/docs/gen.md+++ b/docs/gen.md@@ -421,6 +421,8 @@ strategy it can execute, and `--alpha-mode auto` (the default) follows it:Rollouts are selected by an exact session-id filename suffix.Missing, duplicate, or pre-existing stale matches fail rather than falling back to another root or choosing by modification time.The transport prompt names the skill with codex's official `$imagegen` mention, which is how a codex skill is invoked explicitly. The adapter owns that trigger alone; the caller's sprite-request prompt is passed through verbatim.+ How codex is signed in is asked once per call by `codex_provider.codex_login` (`codex login status`), the same reading the default resolution, the facing check and the guided workflow use: signed in with ChatGPT is the subscription (`auth_source: codex-login`); signed in with an API key bills that key per call, said on stderr before `codex exec` runs (`codex-api-key`); not signed in is refused with the reason before codex runs (an omitted `--provider` falls back to grok instead, above). What `codex login status` prints is never repeated: an API-key login can name its key.+ A codex call is stopped after `SPRITE_GEN_GEN_TIMEOUT_SECONDS` (180) without an answer and reported as a stall (`gen-timeout`).### When codex produces no image at all@@ -451,9 +453,11 @@ that choice) plus its layout guide, into `raw/<state>.png`. Each row gets`reports/gen-set/<state>.json`, the batch writes `reports/gen-set/table.md` and`set.report.json`, existing rows are reused unless `--force`, a direction run generatesits anchors before its rows and stops when an anchor failed, and the exit code is-non-zero when any row failed. `--provider` is honoured verbatim; unspecified, it-resolves exactly as `gen` does (above), and any codex→grok availability failover is-recorded per row.+non-zero when any row failed. `--provider` (`codex` or `grok`; `openai` is named on `gen`+itself) is honoured verbatim; unspecified, it resolves exactly as `gen` does (above), and any+codex→grok availability failover is recorded per row with the row's `auth_source`. Each row's+output goes to its log, but a row's billing line and a provider switch also print on the+terminal as they happen (`base.run_logged`), so a metered row is never announced only in a file.One row by hand is the same call `gen-set` makes: `--provider codex` (or `grok`) with`prompts/<state>.txt`, writing `raw/<state>.png`.diff --git a/docs/pixel-draw.md b/docs/pixel-draw.mdindex 1cc708f..8316806 100644--- a/docs/pixel-draw.md+++ b/docs/pixel-draw.md@@ -322,7 +322,9 @@ key whenever one is present — nor the calling Claude Code session's own variabhere but refuses a call, has expired or has reached its usage limit fails that call as it came; therun never switches to the key on its own. `--batch` is the API's Message Batches, so it names the keyand the login is not asked. One call through the binary may take up to-`SPRITE_GEN_CLAUDE_CALL_TIMEOUT_SECONDS` (1800) before it is stopped and reported.+`SPRITE_GEN_CLAUDE_CALL_TIMEOUT_SECONDS` (1800) before it is stopped and reported; on the key, one+socket read of the stream may wait `SPRITE_GEN_CLAUDE_READ_TIMEOUT_SECONDS` (300) — the API sends+`ping`s while the model thinks, so a stream silent that long is stalled.The binary answers an answer cut at the output cap by asking for a continuation a few times and thenfailing with "exceeded the N output token maximum"; that is read as the API's `stop_reason:diff --git a/docs/sound.md b/docs/sound.mdindex ed83c6e..77e6e8f 100644--- a/docs/sound.md+++ b/docs/sound.md@@ -15,7 +15,7 @@ sprite-gen sound --kind sfx|bgm --prompt TEXT (or --prompt-file PATH) --duration- `--cache-dir`: Defaults to `$XDG_CACHE_HOME/sprite-gen/audio` or `~/.cache/sprite-gen/audio` (never inside `--out-dir`; local by default but can be copied; no cross-cache-directory or cross-machine duplicate-request guarantee).- `--target-lufs`: Target integrated loudness within `-36..-9` LUFS.- `--crossfade`: Overlap duration in seconds.-- **Environment & PATH**: `ELEVENLABS_API_KEY` is required only for new paid requests (offline work needs none). `ffmpeg` (with `libopus` and `aac` encoders) and `ffprobe` are required on `PATH` and checked before paid calls.+- **Environment & PATH**: `ELEVENLABS_API_KEY` is required only for new paid requests (offline work needs none); ElevenLabs has no subscription login, so every new request is billed per call and says so on stderr before it leaves (`[gen] elevenlabs: running on ELEVENLABS_API_KEY — this is a per-call API charge …`, the line every metered route prints), and the receipt records `auth_source`. `ffmpeg` (with `libopus` and `aac` encoders) and `ffprobe` are required on `PATH` and checked before paid calls.## Provider APIs and Cost Accounting@@ -31,7 +31,7 @@ Checked 2026-10-13: [ElevenLabs Pricing](https://elevenlabs.io/pricing/api) quotRaw paid audio is stored in SQLite keyed by provider parameter digest. Tuning `--event`, loudness, or exports reuses raw cache without new purchases:- **Locking & Recovery**: Atomic claims precede requests; raw blobs and receipts commit on success. Duplicates, crashes, or uncertain results refuse resubmission. Do not delete unresolved cache entries blindly; inspect provider billing/history first. All errors remain unresolved.- **Offline Processing**: Downstream processing runs offline. Identical runs require no network.-- **Retries**: Uses `sprite_gen.gen.retry` exclusively. ElevenLabs 429 retries only when `detail.status` is `system_busy` or `too_many_concurrent_requests` (max 2 retries via `Retry-After` or engine backoff; see [ElevenLabs 429 Errors](https://elevenlabs.io/docs/help-center/technical/api-error-code-429)). No other 429, 5xx, transport retries, or provider fallbacks occur. Emits only bounded status, code, and request IDs without error prose.+- **Retries**: Uses `sprite_gen.gen.retry` exclusively. ElevenLabs 429 retries only when `detail.status` is `system_busy` or `too_many_concurrent_requests` (max 2 retries via `Retry-After` or engine backoff; see [ElevenLabs 429 Errors](https://elevenlabs.io/docs/help-center/technical/api-error-code-429)). No other 429, 5xx, transport retries, or provider fallbacks occur. Emits only bounded status, code, and request IDs without error prose, and the billing line above.## Audio DSP, Looping, and Quality Gatesdiff --git a/docs/video.md b/docs/video.mdindex 3e58f7b..e2dd04c 100644--- a/docs/video.md+++ b/docs/video.md@@ -100,7 +100,7 @@ refresh token is gone too: `grok login`.Why not refresh it here: `auth.json` is the grok CLI's file, the refresh token init 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.+everywhere else. The same shape as codex's: `sprite-gen` reads `codex login status` (`codex_provider.codex_login`) and never writes codex's login either.### Direct API transportdiff --git a/sprite_gen/audio/provider.py b/sprite_gen/audio/provider.pyindex 6d87da1..4019b21 100644--- a/sprite_gen/audio/provider.py+++ b/sprite_gen/audio/provider.py@@ -4,16 +4,16 @@ from __future__ import annotationsimport jsonimport math-import osimport re-import sysfrom urllib.error import HTTPErrorfrom urllib.request import Request, urlopenfrom sprite_gen.gen import retry+from sprite_gen.gen.base import announce_api_billing, env_api_keyfrom sprite_gen.gen.xai import error_body, NO_ANSWERBASE = 'https://api.elevenlabs.io/v1'+AUTH_ENV = 'ELEVENLABS_API_KEY'FORMAT = 'mp3_44100_128'SAFE_CODES = frozenset({'system_busy', 'too_many_concurrent_requests', 'quota_exceeded','invalid_api_key', 'missing_permissions', 'bad_prompt', 'bad_composition_plan',@@ -40,9 +40,13 @@ def request(kind, prompt, duration, loop):def credential():- key = os.environ.get('ELEVENLABS_API_KEY', '').strip()+ # ElevenLabs has no subscription login to prefer: the key is the only route, billed per call.+ try:+ key = env_api_key(AUTH_ENV, who='sound')+ except SystemExit as exc:+ raise ValueError(str(exc)) from Noneif not key:- raise ValueError('ELEVENLABS_API_KEY is required for a new sound request')+ raise ValueError(f'{AUTH_ENV} is required for a new sound request')return key@@ -72,13 +76,14 @@ def generate(document):# Transport exceptions may include headers or body text. Never print them.raise ValueError('ElevenLabs response unavailable; request outcome unresolved; no resubmission') from None- print('[sound] ElevenLabs paid API request; source audio will be cached', file=sys.stderr)+ announce_api_billing('elevenlabs', AUTH_ENV, f" ({document['endpoint']}; the audio is cached, so the same "+ "request is not bought twice).")status, body, headers, asks = retry.ask(send, provider='elevenlabs', who='ElevenLabs', label='sound', kind=_code)if not 200 <= status < 300:raise ValueError(f'ElevenLabs refused sound (HTTP {status}, {_code(body) or "unclassified"}); {retry.tail(asks)}')if not isinstance(body, bytes) or not body:raise ValueError('ElevenLabs returned no audio; request outcome unresolved')- meta = {'provider': 'elevenlabs', 'model': document['body']['model_id'], 'asks': asks}+ meta = {'provider': 'elevenlabs', 'auth_source': AUTH_ENV, 'model': document['body']['model_id'], 'asks': asks}# Only documented, constrained metadata; provider prose never enters a report or log.for header, field in (('request-id', 'request_id'), ('song-id', 'song_id')):value = headers.get(header, '')diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex 664c669..e96dda7 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -319,7 +319,7 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callabui_kit.run,),"gen": (- "Generate one image via a provider (codex image_gen / grok Imagine on a subscription login, or openai Images API for servers/SaaS, billed per call) into a verified PNG.",+ "Generate one image via a provider (codex image_gen / grok Imagine on a subscription login first (an API key only without one, billed per call and said), or openai Images API for servers/SaaS, billed per call) into a verified PNG.",_add_gen,gen.run,),diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.pyindex cd612dc..7058e83 100644--- a/sprite_gen/gen/__init__.py+++ b/sprite_gen/gen/__init__.py@@ -2,7 +2,9 @@"""Unified image generation layer for sprite-gen.Single source of truth for provider-backed image generation: codex (`image_gen`,-ChatGPT OAuth), grok (Imagine, xAI OAuth) and openai (Images REST, OPENAI_API_KEY).+the ChatGPT login; an API-key login bills per call and says so), grok (Imagine, the+Grok login; XAI_API_KEY only without one, billed per call and said) and openai+(Images REST, OPENAI_API_KEY).One call = prompt (+ optional refs) -> one verified raw PNG, with an optionaldeterministic transparent chroma post-process. The general `image-gen` skill is athin shuttle over `sprite-gen gen`.@@ -38,7 +40,6 @@ import argparseimport jsonimport osimport shutil-import subprocessimport sysimport tempfilefrom pathlib import Path@@ -50,6 +51,7 @@ from sprite_gen.video import body_plan as body_modfrom sprite_gen.video.body_plan import Bodyfrom . import chroma as chroma_mod+from . import codex_providerfrom . import facing as facing_modfrom . import handedness as handed_modfrom . import prompt_parts@@ -61,10 +63,9 @@ from .base import (TRANSPARENCY_STRATEGIES,GenRequest,GenResult,+ PROVIDER_SWITCH_WORDS,GenTimeoutError,print_json,- provider_binary,- provider_subprocess_env,verify_png,)from .codex_provider import CodexProvider@@ -91,7 +92,6 @@ HARD_DEFAULT_PROVIDER = "codex"# is not one of them: it is explicit-only, so no default, preference or fallback# can route a subscription user onto metered credit (구독 우선 불변식 1-2).EXPLICIT_ONLY_PROVIDERS = ("openai",)-_CODEX_PROBE_TIMEOUT_SECONDS = 15# `--layout-guide`: the one-slot form of the guide `prepare` draws for every row# (`draw_guide`, the same 9.4 % safe margin), attached after the caller's refs, with@@ -274,30 +274,10 @@ def resolve_transparency_strategy(backend, alpha_mode: str, *, refs: list[Path]def _codex_available() -> tuple[bool, str]:- """Is codex usable here? Returns (ok, reason_if_not).-- Two checks, cheapest first: the `codex` CLI on PATH, then `codex login status`- (exit 0 = logged in). Any probe error/timeout counts as unavailable with a- stated reason — never a silent pass. Monkeypatchable in tests.- """- if shutil.which("codex") is None:- return False, "codex CLI not found on PATH"- try:- completed = subprocess.run(- [provider_binary("codex"), "login", "status"],- capture_output=True,- text=True,- encoding="utf-8",- env=provider_subprocess_env(),- timeout=_CODEX_PROBE_TIMEOUT_SECONDS,- )- except (OSError, subprocess.SubprocessError) as exc:- return False, f"codex login-status probe failed: {exc}"- if completed.returncode != 0:- tail = (completed.stdout or completed.stderr or "").strip().splitlines()[-3:]- detail = f": {' '.join(tail)}" if tail else ""- return False, f"codex not logged in (codex login status exit {completed.returncode}{detail})"- return True, ""+ """Is codex usable here? Returns (ok, reason_if_not), by `codex_provider.codex_login` —+ the one reading of how codex is signed in. Monkeypatchable in tests."""+ login = codex_provider.codex_login()+ return login.source is not None, login.reasondef resolve_default_provider() -> tuple[str, dict[str, str] | None]:@@ -669,7 +649,7 @@ def _run(args: argparse.Namespace) -> int:resolved_from = f"fallback-from-{fallback['from']}"print(f"sprite-gen gen: default provider '{fallback['from']}' unavailable "- f"({fallback['reason']}) — falling back to '{fallback['to']}'. "+ f"({fallback['reason']}) {PROVIDER_SWITCH_WORDS} '{fallback['to']}'. "f"Set {DEFAULT_PROVIDER_ENV} or pass --provider to control this.",file=sys.stderr,)diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.pyindex 031d9b4..ff3d53b 100644--- a/sprite_gen/gen/base.py+++ b/sprite_gen/gen/base.py@@ -15,6 +15,7 @@ import ioimport jsonimport osimport shutil+import subprocessimport sysimport tempfilefrom dataclasses import dataclass, field@@ -119,6 +120,12 @@ def provider_binary(name: str) -> str:return shutil.which(name) or name+# The words of the two notices a person must see on their terminal even when a batch verb keeps a+# child's output in a log (`run_logged`): a call billed per call, and a default provider switched.+API_CHARGE_WORDS = "this is a per-call API charge, not a subscription"+PROVIDER_SWITCH_WORDS = "— falling back to"++def announce_api_billing(provider: str, env_name: str, detail: str = "") -> None:"""Say on stderr, before the request leaves, that this call bills API credit.@@ -127,11 +134,23 @@ def announce_api_billing(provider: str, env_name: str, detail: str = "") -> Noneis never silent about it, because the person paying only finds out otherwiseon the invoice (수홍 2026-09-20, 구독 우선 불변식 5)."""- print(- f"[gen] {provider}: running on {env_name} — this is a per-call API charge, "- f"not a subscription{detail}",- file=sys.stderr,- )+ print(f"[gen] {provider}: running on {env_name} — {API_CHARGE_WORDS}{detail}", file=sys.stderr, flush=True)+++def run_logged(cmd: list[str], log: Path) -> int:+ """Run a child command with all its output in `log`. The lines that announce a per-call charge+ or a default provider switched for being unavailable also go to this process's stderr as they+ come: a batch verb (`gen-set`, `video-set`) keeps each item's output in its own log, and those+ two lines are for the person running it, before the request leaves."""+ with log.open("w", encoding="utf-8") as fh:+ child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,+ encoding="utf-8", errors="replace")+ assert child.stdout is not None+ for line in child.stdout:+ fh.write(line)+ if API_CHARGE_WORDS in line or PROVIDER_SWITCH_WORDS in line:+ print(line.rstrip("\n"), file=sys.stderr, flush=True)+ return child.wait()def flags_over_spec(spec: Mapping[str, Any], flags: Mapping[str, Any], *, verb: str, source: str,diff --git a/sprite_gen/gen/codex_provider.py b/sprite_gen/gen/codex_provider.pyindex d5ac4b3..5c1d6be 100644--- a/sprite_gen/gen/codex_provider.py+++ b/sprite_gen/gen/codex_provider.py@@ -13,6 +13,11 @@ Decisive flags (each verified in the image-gen skill):- `--add-dir <Codex state root>/generated_images` not in the default writable set; the root is `CODEX_HOME` when set and `~/.codex` otherwise.- `--skip-git-repo-check` the sandbox dir is not a git repo.- NO `--ephemeral` the session jsonl must survive on disk so we can extract from it.++How codex is signed in is one question, `codex_login`, asked by every caller: the default+provider resolution, `generate`, the facing check and the guided workflow. Signed in with+ChatGPT it runs on the subscription; signed in with an API key it bills that key per call,+said on stderr before the request leaves like every metered route (`announce_api_billing`)."""from __future__ import annotations@@ -29,6 +34,7 @@ from pathlib import Pathfrom .base import (GEN_TIMEOUT_SECONDS,TRANSPARENCY_NATIVE,+ announce_api_billing,GenRequest,GenTimeoutError,ProviderRun,@@ -37,6 +43,44 @@ from .base import (verify_png,)+AUTH_SOURCE_LOGIN = "codex-login" # signed in with ChatGPT: the subscription+AUTH_SOURCE_API_KEY = "codex-api-key" # signed in with an API key: billed per call+LOGIN_PROBE_TIMEOUT_SECONDS = 15+LOGIN_HINT = "`codex login` signs your ChatGPT subscription in"+++@dataclass(frozen=True)+class CodexLogin:+ source: str | None # AUTH_SOURCE_LOGIN | AUTH_SOURCE_API_KEY | None (not usable here)+ reason: str = "" # why it is not usable+++def codex_login() -> CodexLogin:+ """How `codex` is signed in here, by `codex login status`: exit 0 and "ChatGPT" in what it+ says is the subscription; exit 0 otherwise is signed in with an API key. No CLI, a probe that+ fails or does not answer, and a non-zero exit are not usable, with the reason. What the CLI+ says is never repeated: an API-key login can name its key."""+ binary = provider_binary("codex")+ try:+ completed = subprocess.run([binary, "login", "status"], capture_output=True, text=True, encoding="utf-8",+ errors="replace", env=provider_subprocess_env(),+ timeout=LOGIN_PROBE_TIMEOUT_SECONDS)+ except FileNotFoundError:+ return CodexLogin(None, "codex CLI not found on PATH")+ except (OSError, subprocess.SubprocessError) as exc:+ return CodexLogin(None, f"codex login-status probe failed: {type(exc).__name__}")+ if completed.returncode != 0:+ return CodexLogin(None, f"codex not logged in (codex login status exit {completed.returncode})")+ said = (completed.stdout + completed.stderr).lower()+ return CodexLogin(AUTH_SOURCE_LOGIN if "chatgpt" in said else AUTH_SOURCE_API_KEY)+++def announce_codex_billing(login: CodexLogin, what: str = "") -> None:+ """The stderr charge line for a codex signed in with an API key; nothing on the subscription."""+ if login.source == AUTH_SOURCE_API_KEY:+ announce_api_billing("codex", "the API key codex is signed in with", f"{what} — {LOGIN_HINT}.")++# codex carries the inline base64 on a version-specific record. All are# first-class canonical records (not fallbacks) — read whichever the running# codex emits. v0.140.0: response_item `image_generation_call`. v0.144.1:@@ -314,6 +358,10 @@ class CodexProvider:raise SystemExit(f"codex-gen: Codex state root does not exist or is not a directory: {codex_home}")+ login = codex_login()+ if login.source is None:+ raise SystemExit(f"codex-gen: {login.reason}; {LOGIN_HINT}")+ announce_codex_billing(login)sessions_root = codex_home / "sessions"preexisting_rollouts = set(_rollout_files(sessions_root))gen_dir = codex_home / "generated_images"@@ -396,6 +444,7 @@ class CodexProvider:model=request.model,session_id=session_id,extra={+ "auth_source": login.source,"inline_results": len(results),"rollout_cleaned": not self.keep_session,# codex's own claim about the output; the orchestrator measuresdiff --git a/sprite_gen/gen/facing_vision.py b/sprite_gen/gen/facing_vision.pyindex 7052401..439792d 100644--- a/sprite_gen/gen/facing_vision.py+++ b/sprite_gen/gen/facing_vision.py@@ -43,6 +43,11 @@ def response_text(status: int, reply) -> tuple[str, dict]:def codex_inspect(path: Path, workdir: Path) -> tuple[str, dict]:# Isolated cwd and ephemeral session: no project instructions, no stale# output reuse and no persistent vision rollouts. Uses the existing login.+ from .codex_provider import announce_codex_billing, codex_login+ login = codex_login()+ if login.source is None:+ raise SystemExit(f"facing-vision: {login.reason}")+ announce_codex_billing(login, " (facing vision check)")with tempfile.TemporaryDirectory(prefix="facing-", dir=workdir) as directory:output = Path(directory) / "answer.txt"command = [provider_binary("codex"), "exec", "--sandbox", "read-only",@@ -53,7 +58,7 @@ def codex_inspect(path: Path, workdir: Path) -> tuple[str, dict]:timeout=GEN_TIMEOUT_SECONDS)if completed.returncode:raise SystemExit(f"facing-vision: codex exited {completed.returncode}")- return output.read_text(encoding="utf-8"), {"transport": "codex-exec", "auth_source": "codex-login"}+ return output.read_text(encoding="utf-8"), {"transport": "codex-exec", "auth_source": login.source}def grok_inspect(path: Path, *, credential=None, call=None) -> tuple[str, dict]:diff --git a/sprite_gen/gen/gen_set.py b/sprite_gen/gen/gen_set.pyindex 3b26437..caf4d7c 100644--- a/sprite_gen/gen/gen_set.py+++ b/sprite_gen/gen/gen_set.py@@ -32,6 +32,7 @@ from typing import Any, Callablefrom sprite_gen import gen as gen_modfrom sprite_gen.curate import anchor as anchor_mod+from sprite_gen.gen.base import run_loggedfrom sprite_gen.spec import layoutfrom sprite_gen.spec.runio import atomic_write_text@@ -100,9 +101,13 @@ def read_report(report: Path) -> tuple[dict[str, Any] | None, str | None]:return data, None-def run_gen_cli(prompt_file: Path, out: Path, refs: list[Path], report: Path, *, provider: str | None, model: str | None, log: Path) -> int:- import subprocess+def _auth_source(report: dict[str, Any]) -> str | None:+ """What a row's gen call ran on, as its report says (`extra.auth_source`)."""+ extra = report.get("extra") if isinstance(report.get("extra"), dict) else {}+ return extra.get("auth_source")++def run_gen_cli(prompt_file: Path, out: Path, refs: list[Path], report: Path, *, provider: str | None, model: str | None, log: Path) -> int:cmd = [sys.executable, "-m", "sprite_gen.cli", "gen", "--prompt-file", str(prompt_file), "--out", str(out), "--report", str(report)]for ref in refs:cmd += ["--ref", str(ref)]@@ -110,8 +115,7 @@ def run_gen_cli(prompt_file: Path, out: Path, refs: list[Path], report: Path, *,cmd += ["--provider", provider]if model:cmd += ["--model", model]- with log.open("w", encoding="utf-8") as fh:- return subprocess.run(cmd, stdout=fh, stderr=subprocess.STDOUT, text=True).returncode+ return run_logged(cmd, log)def run_item(@@ -146,6 +150,7 @@ def run_item(result["reused"] = Trueresult["provider"] = prior.get("provider")result["provider_resolved_from"] = prior.get("provider_resolved_from")+ result["auth_source"] = _auth_source(prior)result["ok"] = Truereturn resultresult["regenerated_because"] = why or bad_image # the files exist but do not prove a finished row — generate again, say why@@ -170,6 +175,7 @@ def run_item(raise SystemExit(f"gen exited 0 but its {why or bad_image}; the row and the report were removed so the next run regenerates")result["provider"] = gen_report.get("provider")result["provider_resolved_from"] = gen_report.get("provider_resolved_from")+ result["auth_source"] = _auth_source(gen_report)if gen_report.get("provider_fallback"):result["provider_fallback"] = gen_report["provider_fallback"]result["elapsed_seconds"] = round(time.monotonic() - started, 1)diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.pyindex d66b43b..e9348a1 100644--- a/sprite_gen/gen/grok_provider.py+++ b/sprite_gen/gen/grok_provider.py@@ -150,9 +150,8 @@ class GrokProvider:# code is all there is to say why.refused = refusal.read(self.name, reply) if status != 200 else Noneif 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}){refused.suffix()}; {remedy}"+ raise SystemExit(f"grok-gen: credential {credential.source} rejected (HTTP {status}){refused.suffix()}; "+ f"{xai.rejected_fix(credential)}"f"{refusal.said(reply, credential.token)}")# The one other thing worth naming is the combination the docs scope to# grok-imagine-image-2.0, which another model is entitled to reject.diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.pyindex 60abcad..e1ac9bb 100644--- a/sprite_gen/gen/openai_provider.py+++ b/sprite_gen/gen/openai_provider.py@@ -31,7 +31,6 @@ import base64import binasciiimport ioimport json-import osimport timeimport urllib.errorimport urllib.request@@ -50,6 +49,7 @@ from .base import (GenRequest,ProviderRun,announce_api_billing,+ env_api_key,publish_png,)@@ -105,16 +105,12 @@ RATE_LIMIT_HEADER_PREFIX = "x-ratelimit-"def resolve_credential(env: dict[str, str] | None = None) -> str:- """Return the OpenAI API key, or fail loud naming the variable that is missing."""- env = os.environ if env is None else env- key = (env.get(AUTH_ENV) or "").strip()+ """Return the OpenAI API key (`base.env_api_key`), or fail loud naming the variable that is missing.+ This provider never falls back to the codex ChatGPT login: that is `codex`'s route, and it needs+ an interactive browser sign-in that a container does not have."""+ key = env_api_key(AUTH_ENV, env, who="openai-gen")if key:return key- if AUTH_ENV in env:- raise SystemExit(- f"openai-gen: {AUTH_ENV} is set but empty; give it a value. "- "This provider never falls back to the codex ChatGPT login."- )raise SystemExit(f"openai-gen: no OpenAI credential — {AUTH_ENV} is not set.\n"f" export {AUTH_ENV}=<your OpenAI API key> (platform.openai.com/api-keys). "diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.pyindex c6c6859..2afb4e6 100644--- a/sprite_gen/gen/video.py+++ b/sprite_gen/gen/video.py@@ -67,8 +67,8 @@ from sprite_gen.video import facing as facing_modfrom .xai import (API_BASE, AUTH_ENV, AUTH_SOURCE_API_KEY, AUTH_SOURCE_GROK_LOGIN,HTTP_TIMEOUT_SECONDS, GROK_REFRESH_COMMAND, GROK_REFRESH_WHERE, GROK_LOGIN_COMMAND,- NO_ANSWER, Credential, HttpCall, TransportError, grok_home, resolve_credential, http_json, no_answer, post,- read_whole, time_left,+ NO_ANSWER, Credential, HttpCall, TransportError, resolve_credential, http_json, no_answer, post,+ read_whole, rejected_fix, time_left,)DEFAULT_MODEL = "grok-imagine-video-1.5"@@ -532,11 +532,7 @@ def _submit_poll_publish(if status in (401, 403):raise SystemExit(f"{verb}: xAI rejected the credential ({credential.source}) with HTTP {status}: {_error_detail(reply, credential.token)}\n"- + (- f" the grok login token may have been revoked or rotated — run `{GROK_REFRESH_COMMAND}` {GROK_REFRESH_WHERE} or `{GROK_LOGIN_COMMAND}`."- if credential.source == AUTH_SOURCE_GROK_LOGIN- else f" check the {AUTH_ENV} value."- )+ f" {rejected_fix(credential)}.")request_id = reply.get("request_id") if isinstance(reply, dict) else Noneif status not in (200, 202) or not request_id:@@ -629,8 +625,7 @@ def _poll_publish(elif http in (401, 403):# The token this request was submitted with stopped working (a login expires in about six# hours); asking again with it changes nothing. A fresh one can ask for the same request.- fix = (f"refresh the login with `{GROK_REFRESH_COMMAND}` run {GROK_REFRESH_WHERE} or `{GROK_LOGIN_COMMAND}`"- if credential.source == AUTH_SOURCE_GROK_LOGIN else f"check the {AUTH_ENV} value")+ fix = rejected_fix(credential)raise unfinished(f"was accepted, but xAI rejected the credential ({credential.source}) on poll {polls} (answer {http}); "f"it may still finish and be billed — {fix}, then {_ask_again(request_id, out)}",diff --git a/sprite_gen/gen/xai.py b/sprite_gen/gen/xai.pyindex 5fa4957..83071e6 100644--- a/sprite_gen/gen/xai.py+++ b/sprite_gen/gen/xai.py@@ -19,6 +19,7 @@ from pathlib import Pathfrom typing import Any, Callablefrom . import refusal, retry+from .base import env_api_keyAPI_BASE = "https://api.x.ai/v1"AUTH_ENV = "XAI_API_KEY"@@ -118,11 +119,9 @@ def resolve_credential(*, env: dict[str, str] | None = None, now: datetime | Nonraise SystemExit(f"xai: cannot inspect grok login file {auth_path}; refusing API-credit fallback") from excelse:return _load_grok_login(auth_path, now=now)- api_key = (env.get(AUTH_ENV) or "").strip()+ api_key = env_api_key(AUTH_ENV, env, who="xai")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 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), "@@ -130,6 +129,14 @@ def resolve_credential(*, env: dict[str, str] | None = None, now: datetime | Non)+def rejected_fix(credential: Credential) -> str:+ """What to do when xAI rejects `credential` (401/403), for every Grok call: a login is refreshed by a+ non-agent round-trip or signed in again; a key is checked."""+ if credential.source == AUTH_SOURCE_GROK_LOGIN:+ return f"refresh the login with `{GROK_REFRESH_COMMAND}` run {GROK_REFRESH_WHERE} or `{GROK_LOGIN_COMMAND}`"+ return f"check the {AUTH_ENV} value"++HttpCall = Callable[[str, str, str, dict | None], tuple[int, Any]]diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex ed86345..643b637 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -16,7 +16,6 @@ from __future__ import annotationsimport argparseimport hashlibimport json-import subprocessimport sysimport threadingimport time@@ -27,6 +26,7 @@ from typing import Any, Callablefrom PIL import Imagefrom sprite_gen.spec.runio import atomic_write_text+from sprite_gen.gen.base import run_loggedfrom sprite_gen.gen.chroma import KEY_BACKGROUND_TEXTfrom sprite_gen.gen.facing import FACINGS, validate as validate_facingfrom sprite_gen.gen import handedness as handed_mod@@ -596,8 +596,7 @@ def run_video_cli(image: Path, prompt: str, out: Path, report: Path, *, durationcmd = [sys.executable, "-m", "sprite_gen.gen.video", "--image", str(image), "--prompt", prompt, "--out", str(out), "--duration", str(duration), "--resolution", resolution, "--no-audio", "--report", str(report)]if last_frame is not None:cmd += ["--last-frame", str(last_frame)]- with log.open("w", encoding="utf-8") as fh:- return subprocess.run(cmd, stdout=fh, stderr=subprocess.STDOUT, text=True).returncode+ return run_logged(cmd, log)def run_redraw_cli(base: Path, prompt: str, out: Path, report: Path, *, log: Path, provider: str | None = None) -> int:@@ -605,8 +604,7 @@ def run_redraw_cli(base: Path, prompt: str, out: Path, report: Path, *, log: Patcmd = [sys.executable, "-m", "sprite_gen.cli", "gen", "--ref", str(base), "--prompt", prompt, "--out", str(out), "--report", str(report)]if provider:cmd += ["--provider", provider]- with log.open("w", encoding="utf-8") as fh:- return subprocess.run(cmd, stdout=fh, stderr=subprocess.STDOUT, text=True).returncode+ return run_logged(cmd, log)def walk_start_still(base: Path, direction: str, item_dir: Path, *, key: str, force: bool,@@ -768,6 +766,10 @@ def run_item(result["clip"] = {"attempts": attempts, "duration": duration, "last_frame": str(end_frame) if end_frame is not None else pins_last_frame(state, direction)}if attempts[-1] != 0 or not clip.exists():raise SystemExit(f"clip generation failed after {len(attempts)} attempt(s); see {item_dir / 'clip.log'}")+ try: # what the clip ran on, as its report says: the Grok login or XAI_API_KEY+ result["clip"]["auth_source"] = json.loads(clip_report.read_text()).get("auth_source")+ except (OSError, ValueError):+ result["clip"]["auth_source"] = Noneif end_digest is not None:generated = json.loads(clip_report.read_text())generated["end_frame_sha256"] = end_digestdiff --git a/sprite_gen/workflow/access.py b/sprite_gen/workflow/access.pyindex adec1e6..64d83bc 100644--- a/sprite_gen/workflow/access.py+++ b/sprite_gen/workflow/access.py@@ -2,32 +2,25 @@"""Credential readiness is not proof of a paid subscription or remaining quota."""from __future__ import annotations-import shutil-import subprocess--from sprite_gen.gen.base import provider_binary, provider_subprocess_env+from sprite_gen.gen import codex_providerfrom sprite_gen.gen.openai_provider import AUTH_ENV as OPENAI_AUTH_ENVfrom sprite_gen.gen.openai_provider import resolve_credential as resolve_openai_credentialfrom sprite_gen.gen.xai import AUTH_SOURCE_API_KEY, resolve_credential-def probe_access(provider: str, *, video: bool = False) -> dict:+def probe_access(provider: str) -> dict:+ """One probe per provider: images and videos of a provider share its credential precedence."""result = {"provider": provider, "login": "unknown", "subscription": "unknown", "quota": "unknown","billing": "subscription", "reason": "Subscription and media access need user confirmation when not independently known."}if provider == "codex":- if shutil.which("codex") is None:- return {**result, "login": "unavailable", "reason": "codex CLI is not installed"}- try:- check = subprocess.run([provider_binary("codex"), "login", "status"], capture_output=True,- text=True, encoding="utf-8", errors="replace", timeout=15, env=provider_subprocess_env())- except (OSError, subprocess.SubprocessError):- return {**result, "reason": "codex login status could not be checked"}- if check.returncode != 0:- return {**result, "login": "unavailable", "reason": "codex login status failed; sign in and check again"}- # Never publish the CLI's raw output: some authentication modes can name keys.- output = (check.stdout + check.stderr).lower()- if "chatgpt" not in output:- return {**result, "reason": "login succeeded but ChatGPT subscription authentication was not identified"}+ # The one reading of how codex is signed in; it never repeats what the CLI said.+ login = codex_provider.codex_login()+ if login.source is None:+ return {**result, "login": "unavailable", "reason": f"{login.reason}; sign in and check again"}+ if login.source == codex_provider.AUTH_SOURCE_API_KEY:+ return {**result, "login": "ready", "billing": "api-credit",+ "reason": "codex is signed in with an API key and bills it per call; confirm this billing choice "+ "or sign in with ChatGPT (`codex login`)."}return {**result, "login": "ready"}if provider == "openai":# An API key is the whole credential: there is no login to inspect and nodiff --git a/sprite_gen/workflow/guide.py b/sprite_gen/workflow/guide.pyindex 205a2da..1948629 100644--- a/sprite_gen/workflow/guide.py+++ b/sprite_gen/workflow/guide.py@@ -33,26 +33,28 @@ def guide(kind: str, *, stage: str = "start", base_image: Path | None = None, reif field not in selected:questions.append({"field": field, **FIELDS[field]})# Report both candidates while choosing, then only the services actually- # used. One probe per provider/auth route; a row run always pins codex.+ # used. One probe per provider: its images and videos share one credential.required = set()if "image_provider" in active_fields and selected.get("image_provider"):- required.add((selected["image_provider"], False))+ required.add(selected["image_provider"])motion = MOTION_METHODS.get(selected.get("motion_method", ""))if motion:- required.add((motion["provider"], selected["motion_method"] == "grok-video"))- candidates = required or {(provider, False) for provider in FIELDS["image_provider"]["options"]}- for provider, is_video in sorted(candidates):- state = probe_access(provider, video=is_video)+ required.add(motion["provider"])+ candidates = required or set(FIELDS["image_provider"]["options"])+ for provider in sorted(candidates):+ state = probe_access(provider)access.append(state)- if (provider, is_video) not in required:+ if provider not in required:continue+ label = FIELDS["image_provider"]["options"].get(provider, provider)if state["login"] == "unavailable":blocked.append({"provider": provider, "reason": state["reason"]})elif state["billing"] == "api-credit":- if not confirm_api_billing:- questions.append({"field": "confirm_api_billing", "question": "그록 영상에 별도 API 크레딧을 사용할까요?", "options": {"yes": "사용", "no": "구독 로그인으로 변경"}})+ if not confirm_api_billing and not any(q["field"] == "confirm_api_billing" for q in questions):+ questions.append({"field": "confirm_api_billing", "question": f"{label} 호출에 별도 API 크레딧을 사용할까요?",+ "options": {"yes": "사용", "no": "구독 로그인으로 변경"}})elif provider not in confirmed_access and not any(q["field"] == f"access_{provider}" for q in questions):- questions.append({"field": f"access_{provider}", "question": f"{FIELDS['image_provider']['options'][provider]} 계정의 구독과 이미지/영상 이용 가능 여부를 확인해 주세요.",+ questions.append({"field": f"access_{provider}", "question": f"{label} 계정의 구독과 이미지/영상 이용 가능 여부를 확인해 주세요.","options": {"yes": "사용 가능", "no": "사용 불가"}})else:missing = [field for field in active_fields if field not in selected]