Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
gen: keep the API-key provider explicit-only and announce what it bills
Soohong Kimc5c3ededb919
diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex 1d1b6ad..08a6ea3 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -293,7 +293,7 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callabslice_sheet.run,),"gen": (- "Generate one image via a provider (codex image_gen / grok Imagine / openai Images API) into a verified PNG.",+ "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.",_add_gen,gen.run,),diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.pyindex 78469fd..233a511 100644--- a/sprite_gen/gen/__init__.py+++ b/sprite_gen/gen/__init__.py@@ -11,6 +11,12 @@ codex and openai reach the same family of GPT image models by different routes:codex needs an interactive ChatGPT login and the `codex` CLI on PATH, openai needsonly an API key, which is what a headless container (Modal worker, CI) can have.+sprite-gen is subscription-first (수홍 2026-09-20). openai exists for servers and+SaaS and is billed per call, so it runs ONLY when `--provider openai` names it: it+is never a default, never a saved preference, never an offered choice in the guided+flow, and never the target of an availability fallback. Having OPENAI_API_KEY in+the environment changes no route by itself.+Transparency is a per-provider strategy (`Provider.transparency`, declared oncein each adapter): codex `image_gen` and openai (`background: transparent`) return agenuinely transparent PNG when asked (`native`), grok Imagine cannot and is keyed@@ -72,6 +78,10 @@ ALPHA_MODES = (ALPHA_MODE_AUTO, *TRANSPARENCY_STRATEGIES)# explicitly named provider that is down fails loud at generation time.DEFAULT_PROVIDER_ENV = "SPRITE_GEN_DEFAULT_PROVIDER"HARD_DEFAULT_PROVIDER = "codex"+# Providers that may be reached without being named. A per-call API-billed backend+# 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@@ -160,6 +170,10 @@ def resolve_default_provider() -> tuple[str, dict[str, str] | None]:resolved default is codex but codex is unavailable, fall back to grok and returnfallback metadata (from/to/reason/default_source) so the switch is observable.Returns (provider, fallback_or_None).++ An EXPLICIT_ONLY provider can never come out of here: not as the hard default,+ not out of the env, and not as a fallback target. A codex outage reaches grok+ (another subscription route) or nothing at all — never metered API credit."""configured = os.environ.get(DEFAULT_PROVIDER_ENV, "").strip()if configured:@@ -168,13 +182,21 @@ def resolve_default_provider() -> tuple[str, dict[str, str] | None]:f"gen: {DEFAULT_PROVIDER_ENV}={configured!r} is not a known provider; "f"expected one of {', '.join(PROVIDERS)}")+ if configured in EXPLICIT_ONLY_PROVIDERS:+ raise SystemExit(+ f"gen: {DEFAULT_PROVIDER_ENV}={configured!r} is refused — {configured} bills per call "+ f"against an API key and must be named explicitly (`--provider {configured}`), never "+ f"stood up as a default. Use {', '.join(p for p in PROVIDERS if p not in EXPLICIT_ONLY_PROVIDERS)} "+ "for a subscription route."+ )default, source = configured, DEFAULT_PROVIDER_ENVelse:default, source = HARD_DEFAULT_PROVIDER, "hard-default"- # The availability-driven fallback is codex -> grok only (the mandated default).- # A grok default that is down fails loud at generation time rather than silently- # reverse-falling-back to codex.+ # The availability-driven fallback is codex -> grok only (the mandated default):+ # one subscription route to another, never to a per-call API key. A grok default+ # that is down fails loud at generation time rather than silently reverse-falling+ # back to codex.if default == "codex":ok, reason = _codex_available()if not ok:@@ -410,7 +432,9 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:default=None,help=(f"generation backend; default resolves via {DEFAULT_PROVIDER_ENV} env "- "then codex, with an observable grok fallback if codex is unavailable"+ "then codex, with an observable grok fallback if codex is unavailable. "+ "codex and grok run on a subscription login; openai is for servers and SaaS "+ "and is billed per call on OPENAI_API_KEY, so it runs only when named here"),)parser.add_argument("--prompt")diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.pyindex 150b430..9966777 100644--- a/sprite_gen/gen/base.py+++ b/sprite_gen/gen/base.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport ioimport osimport shutil+import sysimport tempfilefrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -91,6 +92,21 @@ def provider_binary(name: str) -> str:return shutil.which(name) or name+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.++ sprite-gen is a subscription-first tool: codex runs on a ChatGPT login and+ grok prefers its Grok login. A route that instead spends metered API credit+ is never silent about it, because the person paying only finds out otherwise+ on 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,+ )++def verify_png(path: Path) -> int:"""Return the PNG byte count, or raise SystemExit if it is missing/not a PNG."""if not path.is_file():diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.pyindex e42e961..bba8f0f 100644--- a/sprite_gen/gen/grok_provider.py+++ b/sprite_gen/gen/grok_provider.py@@ -11,7 +11,14 @@ from pathlib import Pathfrom PIL import Image, UnidentifiedImageErrorfrom . import xai-from .base import GEN_TIMEOUT_SECONDS, TRANSPARENCY_CHROMA, GenRequest, ProviderRun, publish_png+from .base import (+ GEN_TIMEOUT_SECONDS,+ TRANSPARENCY_CHROMA,+ GenRequest,+ ProviderRun,+ announce_api_billing,+ publish_png,+)DEFAULT_MODEL = "grok-imagine-image-2.0"MAX_REFS = 5@@ -79,7 +86,12 @@ class GrokProvider:if request.native_alpha:raise SystemExit("grok-gen: grok Imagine cannot return an alpha channel; generate on a chroma key instead")endpoint, body = _request_body(request)+ # The login is preferred (xai.resolve_credential); reaching the key means no+ # login exists, and that spends API credit instead of the Grok subscription.credential = xai.resolve_credential()+ if credential.source == xai.AUTH_SOURCE_API_KEY:+ announce_api_billing(self.name, xai.AUTH_ENV,+ f", not your Grok subscription — `{xai.GROK_LOGIN_COMMAND}` signs that in.")started = time.monotonic()status, reply = xai.http_json("POST", xai.API_BASE + endpoint, credential.token,body, timeout=GEN_TIMEOUT_SECONDS)diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.pyindex 4c23231..3426dd1 100644--- a/sprite_gen/gen/openai_provider.py+++ b/sprite_gen/gen/openai_provider.py@@ -14,6 +14,12 @@ transparent|opaque|auto and transparency needs `output_format` png or webp, andcustom `size` must have both sides divisible by 16, an aspect ratio within1:3..3:1, and a total pixel count between 655,360 and 8,294,400.+This backend is for servers and SaaS and is billed per call, so sprite-gen keeps it+explicit-only (구독 우선 불변식, 수홍 2026-09-20): it runs when `--provider openai`+names it and never as a default, a saved preference, a guided-flow option or a+fallback target, and every call announces the charge on stderr before it leaves.+Personal use belongs on a subscription provider (`codex`, `grok`).+This provider never falls back to codex, to another key, or to a retry: a missingcredential, a rejected key or a failed request is the observable outcome."""@@ -39,6 +45,7 @@ from .base import (TRANSPARENCY_NATIVE,GenRequest,ProviderRun,+ announce_api_billing,publish_png,)@@ -242,6 +249,11 @@ class OpenAIProvider:endpoint = "/images/generations"data, content_type = _json_request(fields)token = resolve_credential()+ announce_api_billing(+ self.name,+ AUTH_ENV,+ f" (model={fields['model']}, quality={fields['quality']}, size={fields['size']}).",+ )started = time.monotonic()status, reply = http_image(API_BASE + endpoint, token, data, content_type, timeout=GEN_TIMEOUT_SECONDS)if status in (401, 403):diff --git a/sprite_gen/workflow/catalog.py b/sprite_gen/workflow/catalog.pyindex 64425bd..4970476 100644--- a/sprite_gen/workflow/catalog.py+++ b/sprite_gen/workflow/catalog.py@@ -12,17 +12,25 @@ MOTION_METHODS = {# a row to drop quietly: the mapping is checked rather than zipped positionally,# so registering a backend in `gen.PROVIDERS` without naming it fails at import.PROVIDER_LABELS = {- "codex": "지피티 (ChatGPT 로그인)",+ "codex": "지피티","grok": "그록",- "openai": "지피티 (API 키)",+ "openai": "지피티 API (서버·SaaS 용, 호출당 과금)",}+# Subscription-first (수홍 2026-09-20): the guided flow offers only the routes+# that run on a subscription the user already pays for. `openai` is a registered+# provider but never an offered, recommended or savable one — it spends metered+# API credit per call, so it has to be named on purpose (`--provider openai`).+GUIDED_PROVIDERS = ("codex", "grok")_unlabelled = [provider for provider in PROVIDERS if provider not in PROVIDER_LABELS]if _unlabelled:raise RuntimeError(f"workflow catalog: no label for provider(s) {', '.join(_unlabelled)}")+_unregistered = [provider for provider in GUIDED_PROVIDERS if provider not in PROVIDERS]+if _unregistered:+ raise RuntimeError(f"workflow catalog: guided provider(s) not registered: {', '.join(_unregistered)}")FIELDS = {- "image_provider": {"options": {provider: PROVIDER_LABELS[provider] for provider in PROVIDERS},- "question": "이미지를 무엇으로 만들까요?"},+ "image_provider": {"options": {provider: PROVIDER_LABELS[provider] for provider in GUIDED_PROVIDERS},+ "question": "이미지를 지피티로 만들까요, 그록으로 만들까요?"},"motion_method": {"options": {k: v["label"] for k, v in MOTION_METHODS.items()},"question": "동작을 그록 영상으로 만들까요, 지피티 이미지 스프라이트로 만들까요?"},"curation": {"options": {"open": "열기", "skip": "열지 않기"},diff --git a/sprite_gen/workflow/guide.py b/sprite_gen/workflow/guide.pyindex d04dbb6..205a2da 100644--- a/sprite_gen/workflow/guide.py+++ b/sprite_gen/workflow/guide.py@@ -50,12 +50,7 @@ def guide(kind: str, *, stage: str = "start", base_image: Path | None = None, reblocked.append({"provider": provider, "reason": state["reason"]})elif state["billing"] == "api-credit":if not confirm_api_billing:- # Metered API credit is a billing decision, so the question- # names the provider that would be charged rather than assuming- # one (grok video and the openai key both land here).- questions.append({"field": "confirm_api_billing",- "question": f"{FIELDS['image_provider']['options'][provider]}에 별도 API 크레딧을 사용할까요?",- "options": {"yes": "사용", "no": "다른 경로로 변경"}})+ questions.append({"field": "confirm_api_billing", "question": "그록 영상에 별도 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]} 계정의 구독과 이미지/영상 이용 가능 여부를 확인해 주세요.","options": {"yes": "사용 가능", "no": "사용 불가"}})diff --git a/tests/gen/test_openai_provider.py b/tests/gen/test_openai_provider.pyindex 0f157e0..2576039 100644--- a/tests/gen/test_openai_provider.py+++ b/tests/gen/test_openai_provider.py@@ -9,6 +9,7 @@ which failures must never publish, retry or leak the key.import base64import ioimport json+import osimport subprocessimport urllib.error@@ -16,10 +17,12 @@ import pytestfrom PIL import Imagefrom sprite_gen import gen+from sprite_gen.gen import grok_provider as grokfrom sprite_gen.gen import openai_provider as openai+from sprite_gen.gen import xaifrom sprite_gen.gen.base import GenRequestfrom sprite_gen.workflow import access-from sprite_gen.workflow.catalog import FIELDS, PROVIDER_LABELS+from sprite_gen.workflow.catalog import FIELDS, GUIDED_PROVIDERS, PROVIDER_LABELS, validate_choicesKEY = "synthetic-secret"@@ -38,6 +41,24 @@ def encoded_image(fmt="PNG", *, alpha=False, key=False):return base64.b64encode(buf.getvalue()).decode()+class _GrokResponse:+ """Minimal 200 answer for the xai transport (a PNG, so chroma stays untouched)."""++ def __init__(self, request, api):+ api["calls"].append((request, None))++ def __enter__(self):+ return self++ def __exit__(self, *args):+ pass++ status = 200++ def read(self):+ return json.dumps({"data": [{"b64_json": encoded_image()}]}).encode()++@pytest.fixturedef api(monkeypatch):monkeypatch.setenv("OPENAI_API_KEY", KEY)@@ -232,14 +253,87 @@ def test_native_alpha_is_a_declared_capability(tmp_path, api):def test_provider_is_registered_everywhere_a_provider_must_be(api):assert "openai" in gen.PROVIDERSassert isinstance(gen._make_provider("openai", keep_session=False), openai.OpenAIProvider)- # The workflow surface must name every registered backend, not the first two.- assert set(FIELDS["image_provider"]["options"]) == set(gen.PROVIDERS) == set(PROVIDER_LABELS)+ # Every registered backend is labelled, so a new one can never be dropped from+ # the workflow surface by a silent positional zip.+ assert set(PROVIDER_LABELS) == set(gen.PROVIDERS)assert access.probe_access("openai") == {"provider": "openai", "login": "ready", "subscription": "unknown","quota": "unknown", "billing": "api-credit","reason": "OpenAI images will use OPENAI_API_KEY and separate ""API credit; confirm this billing choice."}+# --- 구독 우선 불변식 (수홍 2026-09-20) --------------------------------------+# sprite-gen runs on subscriptions people already pay for. The API-key backend is+# for servers and SaaS and is billed per call, so nothing may route to it on its+# own. These three tests are the guard rails for invariants 1, 2 and 3.+++def test_openai_is_explicit_only_and_never_a_default(monkeypatch, api):+ """불변식 1: no default, no saved preference, no guided-flow option."""+ assert gen.HARD_DEFAULT_PROVIDER == "codex"+ assert gen.EXPLICIT_ONLY_PROVIDERS == ("openai",)+ monkeypatch.delenv("SPRITE_GEN_DEFAULT_PROVIDER", raising=False)+ monkeypatch.setattr(gen, "_codex_available", lambda: (True, ""))+ assert gen.resolve_default_provider() == ("codex", None)+ # The env knob cannot stand it up either.+ monkeypatch.setenv("SPRITE_GEN_DEFAULT_PROVIDER", "openai")+ with pytest.raises(SystemExit, match=r"--provider openai"):+ gen.resolve_default_provider()+ # Not offered by the guided flow, so it can never be saved as a preference.+ assert "openai" not in GUIDED_PROVIDERS+ assert "openai" not in FIELDS["image_provider"]["options"]+ with pytest.raises(ValueError):+ validate_choices("image", {"image_provider": "openai"})++[email protected]("configured", [None, "codex"])+def test_an_api_key_in_the_environment_reroutes_nothing(monkeypatch, api, configured):+ """불변식 2: a codex outage reaches grok, never the metered key."""+ assert "OPENAI_API_KEY" in os.environ # the fixture set it+ if configured is None:+ monkeypatch.delenv("SPRITE_GEN_DEFAULT_PROVIDER", raising=False)+ else:+ monkeypatch.setenv("SPRITE_GEN_DEFAULT_PROVIDER", configured)+ monkeypatch.setattr(gen, "_codex_available", lambda: (False, "synthetic outage"))+ provider, fallback = gen.resolve_default_provider()+ assert provider == "grok"+ assert fallback["from"] == "codex" and fallback["to"] == "grok"+ assert api["calls"] == []+++def test_grok_login_still_outranks_its_api_key(tmp_path, api, monkeypatch, capsys):+ """불변식 3: the Grok subscription login wins over XAI_API_KEY."""+ monkeypatch.setenv("XAI_API_KEY", "xai-api-secret")+ monkeypatch.setenv("GROK_HOME", str(tmp_path))+ (tmp_path / "auth.json").write_text(json.dumps({"account": {+ "key": "subscription-token", "expires_at": "2100-01-01T00:00:00Z"}}))+ assert xai.resolve_credential().source == xai.AUTH_SOURCE_GROK_LOGIN+ monkeypatch.setattr(xai.urllib.request, "urlopen",+ lambda request, *, timeout: _GrokResponse(request, api))+ result = gen.generate_image("grok", "x", tmp_path / "grok.png")+ assert result.extra["auth_source"] == xai.AUTH_SOURCE_GROK_LOGIN+ # A subscription call says nothing about API billing; only the key route does.+ assert "per-call API charge" not in capsys.readouterr().err+++def test_every_api_key_call_announces_the_charge_before_it_leaves(tmp_path, api, capsys):+ """불변식 5: one stderr line, before the request, naming the billing route."""+ gen.generate_image("openai", "x", tmp_path / "out.png", quality="low")+ notice = [line for line in capsys.readouterr().err.splitlines() if "per-call API charge" in line]+ assert len(notice) == 1+ assert "OPENAI_API_KEY" in notice[0] and "quality=low" in notice[0]+++def test_grok_on_an_api_key_announces_the_charge_too(tmp_path, api, monkeypatch, capsys):+ monkeypatch.setenv("XAI_API_KEY", "xai-api-secret")+ monkeypatch.setenv("GROK_HOME", str(tmp_path / "no-login"))+ monkeypatch.setattr(xai.urllib.request, "urlopen",+ lambda request, *, timeout: _GrokResponse(request, api))+ gen.generate_image("grok", "x", tmp_path / "grok.png")+ notice = [line for line in capsys.readouterr().err.splitlines() if "per-call API charge" in line]+ assert len(notice) == 1 and "XAI_API_KEY" in notice[0]++def test_cli_accepts_provider_and_quality(tmp_path, api):report = tmp_path / "report.json"assert gen.main(["--provider", "openai", "--prompt", "x", "--out", str(tmp_path / "cli.png"),