Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(gen): a default codex that cannot run asks, or runs what the user chose
Soohong Kim48b21dfd6ef7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bd4bd3d..09e3de1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,11 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased+- **Behavior change: a call that names no provider stops and asks when codex cannot run, unless you chose what to do.** `gen`, `logo`, `gen-set` and `video-set`'s mid-step redraw run on codex when no `--provider` is named. When codex was not signed in, they used to switch to `grok` without asking (said on stderr, kept in the report) — and with no Grok login that meant `XAI_API_KEY`, billed per call. Now codex that cannot run — not signed in (`codex login status`), or its usage used up (`codex exec` ends on one of the errors codex classes as its usage limit) — follows a choice: `ask` (the default) generates nothing and ends with one stderr line, `sprite-gen ask codex-unavailable: {…}` (the cause, the reason, the question and the flag that runs each answer), and **exit 75**; `grok` or `openai` runs that provider, said on stderr and kept in the report as `provider_fallback` (now with `cause` and `chosen_by`), `openai` with its per-call charge line as always. The choice is `SPRITE_GEN_CODEX_UNAVAILABLE`, else `sprite-gen defaults save --codex-unavailable ask|grok|openai`, else `ask`; the guided `workflow` asks it once and saves it. A usage limit is known only after `codex exec` ran, so the call runs again on the chosen provider. A named `--provider` runs as named: a named codex whose usage is used up still fails with codex's own words, exit 1. `gen-set` and `video-set` whose child asked stop with the same question and exit 75 (naming `--provider`, or `--still-provider`), their reports and tables keep it under `asked`, and `gen-set --provider` now takes `openai`. `openai` runs only when you chose it: named, or as this answer — still never a default, never the guided image provider ([gen](docs/gen.md#when-codex-cannot-run--ask-or-what-you-chose), [SKILL](SKILL.md#when-codex-cannot-run--exit-75)).+- **The usage-limit signal is codex's own words, read from its source** (codex-rs at `rust-v0.160.1` and `rust-v0.153.4`): `codex exec --json` carries only the message of codex's usage-limit errors (`UsageLimitReached`, `QuotaExceeded`, `UsageNotIncluded`, which codex classes as `UsageLimitExceeded`), so `codex_provider.usage_limit` matches the start of each message as codex's tests pin it — "You've hit your usage limit" with either apostrophe (0.153.4 writes it ASCII, 0.160.1 as U+2019), "Your workspace is out of credits.", "You hit your spend cap set", "Quota exceeded. Check your plan and billing details." and "To use Codex with your ChatGPT plan, upgrade to Plus". Any other codex failure is a failure, not the question.+- **Preferences file version 2.** `preferences.json` keeps, beside the `sprite` and `image` profiles, the `general` settings every profile shares (`codex_unavailable`). A version 1 file still reads, with nothing chosen; the next save writes version 2, which an earlier sprite-gen refuses as unknown. `defaults save --codex-unavailable` needs no `--kind`.+- **Tests** — `tests/gen/test_codex_unavailable.py` (no codex on PATH and nothing chosen: a real `gen` exits 75 with one question line and no image or report; each of codex's usage-limit sentences, synthesized as `codex exec --json` prints them, asks the same; a codex failure that is not its usage limit fails and is not switched; saved `grok` runs grok and the report and stderr say whose choice; saved `openai` runs the API on a fake transport with one charge line; a usage limit with saved `grok` runs grok after codex; the environment before the saved choice, an unknown value refused; settings read only when codex cannot run; `logo` resolves the same way; a named provider runs as named whatever was chosen; a real `gen-set` whose rows asked exits 75 with one question naming `--provider`, its report and table keeping it; a `video-set` whose mid-step redraw asked stops naming `--still-provider`; the guide asks once and not after the answer is saved, nor over the environment; the choice kept beside the profiles, a version 1 file read; the `defaults` CLI; SKILL.md names the exit code, the line and the three answers). Every test now runs on its own settings directory with no provider environment (`tests/conftest.py`).+- **Behavior change: a refused provider request is sent again only within the time limit of its call, and the waits count in that limit.** Previously a request its provider documents as not taken (a 429, an overload) was sent again after 8 s and 16 s, or after the answer's `retry-after` (at most 120 s), twice, whatever time the call had left, and the time limits did not count those waits: `SPRITE_GEN_GEN_TIMEOUT_SECONDS` bounded each send of an OpenAI or Grok image and of the OpenAI facing check on its own, the Grok facing check's 120 s each read, the clip's poll timeout counted from the send xAI accepted, and a Message Batch's status and results reads waited outside `--batch-wait`. A caller that stops the run at its own ceiling, set above those limits, could kill a request taken after two refusals and hear nothing from the engine. Now each limit counts from the first send and holds the waits: the image calls and the OpenAI facing check count `SPRITE_GEN_GEN_TIMEOUT_SECONDS`, the Grok facing check its 120 s, each of their sends reading only what is left of it; the clip its poll timeout (`SPRITE_GEN_VIDEO_TIMEOUT_SECONDS`; the POST itself is still not cut, its answer being the one way to the request id); a batch's reads `--batch-wait`. A wait that would reach the limit is not waited: the refusal ends the call as any refusal does, after one stderr line, `[gen] openai refused the request (429 rate_limit_exceeded); nothing was made — not asking again: the 16s wait would reach the time limit (12s left)`. The limit is read again after the wait, right before the send, as a sleep may wake later than it was asked to: one that woke at the limit or past it sends nothing either, and the refusal ends the call the same way (`… — not asking again: the time limit came during the 8s wait`). A clip's polls and downloads read their poll timeout the same way: a poll or download whose wait woke at it or past it is not sent, and the run ends unfinished on the last one as it came, where the one the transport found no time left to send was counted as a poll or download that got no answer (`timed out`). A realtime `pixel-draw` call has no time limit of its own and is unchanged.- **Tests** — `tests/gen/test_retry.py` (a request sent again only while its wait ends before the time limit; the answer's `retry-after` counted the same; a wait that ends at the limit not waited; a wait that woke at the limit or past it sends nothing, the limit read by one judgment, `too_late`, before the wait and right before the send; every direct provider call hands `retry` its limit; the Grok facing check and a Message Batch read whose wait woke past their limit send nothing), `tests/gen/test_openai_provider.py` and `tests/gen/test_grok_provider.py` (with 20 s, the second send waits only the 12 s left and the second 429 ends the call `sent 2 times`; with 8.01 s, an 8 s wait that woke 20 ms late sends nothing and the 429 ends the image call, or the OpenAI facing check, as it came), `tests/gen/test_video.py` (the poll timeout counts from the first send; a 429 whose next wait would reach it ends the run with its status, and so does one whose 8 s wait woke 20 ms past an 8.01 s timeout, with no second POST; a poll or a download whose wait woke past the timeout is not sent, and the run ends on the last one as it came), `tests/gen/test_pixel_draw.py` (each batch read is handed the end of `--batch-wait`). `tests/http_answer.py` is one offline HTTP answer the provider tests share, read whole or a chunk at a time under a deadline.- **Behavior change: requests can pack sound without images.** Previously, a version 1 request required a nonempty `assets` list (refused with "assets must be a nonempty list"), and version 2 required at least one asset, image, tile, UI kit or icon (refused with "game pack request declares nothing to pack"), preventing games drawn in code from packing audio alone. In both versions, `assets` may now be empty or absent when sound is declared (see [docs/game-pack.md#sound-only-packs](docs/game-pack.md#sound-only-packs)). A sound-only request writes exactly `game-pack.json`, `audio-<id>.ogg`, `audio-<id>.m4a` and `sprite-gen-audio-v2.mjs` without atlas pages; its manifest sets `textures` to `[]` and `animations` to `{}` (version 2 also keeps empty `images`, `tiles` and `ui`), while audio entries, sound files and helper module bytes remain identical to packs with images. Requests declaring no assets, scene entries or sounds are refused in both versions with "game pack request declares nothing to pack: give it an asset, a scene entry or a sound" and write nothing. Packs with images (with or without sound) and packs without sound remain byte-for-byte unchanged, and repacking a sound-only request returns the same output. Tests: `tests/compose/test_game_pack_audio.py` (sound-only requests in versions 1 and 2 with `assets` empty or absent write only the manifest, sound files and helper; manifest matches image packs except for empty `textures` and `animations`; sound files and helper match bytes; repacking returns identical results; requests with neither images nor sound are refused without creating an output directory for version 1 and version 2). Synthetic fixtures only.diff --git a/README.md b/README.mdindex 3599bd4..fdd9916 100644--- a/README.md+++ b/README.md@@ -176,17 +176,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). Every call uses **your own** credential, the subscription login first and an API key only without one, and nothing is shipped with the repo:+Image generation is part of this engine (`sprite_gen.gen`, providers `codex` and `grok` on a subscription you already pay for, plus an `openai` provider for servers and SaaS that bills per call and runs only when you chose it; 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) |+| `gen --provider openai` | — | `OPENAI_API_KEY`, only when you chose it | [gen](docs/gen.md#subscription-first--openai-runs-only-when-you-chose-it) || `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`. `logo` makes its images and its text checks through `gen`'s providers, on the same credentials.+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`. A call that names no provider runs on codex; when codex cannot run (not signed in, or its usage used up) it stops and asks (exit 75) — or runs what you chose for that with `sprite-gen defaults save --codex-unavailable grok|openai` ([gen](docs/gen.md#when-codex-cannot-run--ask-or-what-you-chose)). `logo` makes its images and its text checks through `gen`'s providers, on the same credentials.`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 6157e20..e1af272 100644--- a/SKILL.md+++ b/SKILL.md@@ -61,6 +61,19 @@ $SPRITE_GEN_ROOT/.venv/bin/sprite-gen workflow --kind imagePass choices already stated in the request. The guide checks access, combines explicit choices with saved defaults, and returns only missing questions. Follow its start and finish stages. Always pass the resolved provider explicitly to generation tools. Deliver checked files before offering the curation view; save defaults only when the user agrees. The complete conversation and settings contract is owned by the linked document, not duplicated in individual pipeline docs.+## When codex cannot run — exit 75++A call that names no provider (`gen`, `logo`, `gen-set`, `video-set`'s mid-step redraw) runs on codex. When codex cannot run here — not signed in, or the codex usage of the account used up — and the user's choice for that is to ask (the default), the command generates nothing, prints one stderr line starting `sprite-gen ask codex-unavailable:` followed by JSON, and ends with **exit 75**. That is a question for the user, not a failure: never answer it yourself, never retry without the answer, never switch provider on your own.++Ask it in these words, with the reason from the line's `cause` (`login`: "로그인이 없어요", `usage-limit`: "사용량을 다 썼어요"):++> 지피티(codex)를 지금 쓸 수 없어요 — {이유}. 어떻게 할까요?+> 1. OpenAI API 로 만들기 (호출당 과금)+> 2. 그록으로 만들기+> 3. 멈추기++Then run the same command again with the answer's flag from the line's `choices` — 1: `choices.openai` (`--provider openai`; `video-set`: `--still-provider openai`), 2: `choices.grok` — or, for 3 (멈추기), stop and say nothing was generated. When the user says to do the same from now on, save it: `sprite-gen defaults save --codex-unavailable openai|grok|ask --expected-revision <revision from defaults show>`. A saved `grok` or `openai` runs without asking and says so on stderr and in the report (`provider_fallback`). The rule is [gen](docs/gen.md#when-codex-cannot-run--ask-or-what-you-chose)'s.+## Side-view facingKeep the side still, canvas placement and motion prompt facing the same direction.@@ -113,7 +126,7 @@ hold the arms still, and check the loop with `handed-check --state walk`.| Typography logo, wordmark or title lettering (로고, 타이포그래피, 타이틀 글자): the title lettered into a title screen or poster first, then only its lettering redrawn on a key and cut out with its glow; the text is read back and a misspelt logo refused | `logo --text … --style …` (`--mood` to start from a picture you have, `--lettering` to cut again for nothing) | [logo](docs/logo.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, or a hand-drawn motion of up to 64 frames drawn four a call (`--motion`, `{name, pose}` frames, `--duration-ms`), in a style of your own (`--style`) — 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) |+| 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; it runs only when named, or when the user chose it for a codex that cannot run | [gen](docs/gen.md#subscription-first--openai-runs-only-when-you-chose-it) || Base and direction anchors | `anchor` | [directional-anchor-workflow](docs/directional-anchor-workflow.md) || Curation view or existing image candidates | `curation`, `unpack-atlas --pngs-dir` | [curation](docs/curation.md) || Uniform background removal or imported sheets | `cutout`, `slice-sheet` | [sheet-slicing](docs/sheet-slicing.md) |@@ -129,7 +142,7 @@ hold the arms still, and check the loop with `handed-check --state walk`.| Standalone projected shadow | `shadow` | [asset-tools](docs/asset-tools.md#projected-shadows) || Duplicate poses, foot contact and stride measurement | `inspect-motion` | [asset-tools](docs/asset-tools.md#motion-and-contact-evidence) || Optional scene placement, lighting, camera and render | `scene-render`, `scene-inspect` | [scene](docs/scene.md) |-| Defaults | `defaults show`, `defaults save`, `defaults clear` | [user-workflow](docs/user-workflow.md#one-settings-owner) |+| Defaults | `defaults show`, `defaults save` (`--codex-unavailable ask\|grok\|openai`: what to do when codex cannot run), `defaults clear` | [user-workflow](docs/user-workflow.md#one-settings-owner) |Say a thing once: what an option says, leave out of the prompt. `--direction`, `--facing`, `--handed`, the key background and `video --direction side` each add their own sentence after your text, in one place; without `--handed` every prompt is 2.22.0's, byte for byte, and only the handed sentences are left out where your text already has them. Your prompt carries the subject, its design and its pose. Text that says the opposite of an option ("facing left" with `--facing right`, the item on the other wrist) is sent as written with a warning (`extra.prompt_notes`, `video-prompt`'s `warnings`): fix the prompt, do not send it — [prompt-assembly](docs/prompt-assembly.md).diff --git a/docs/README.md b/docs/README.mdindex feb4826..627f9a7 100644--- a/docs/README.md+++ b/docs/README.md@@ -78,7 +78,7 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.| Doc | Owns ||---|---|-| [gen.md](gen.md) | `sprite-gen gen` / `gen-set`: providers, default resolution, transparency strategy per provider, when a refused provider request is sent again, row usage |+| [gen.md](gen.md) | `sprite-gen gen` / `gen-set`: providers, default resolution and what a default codex that cannot run turns into, transparency strategy per provider, when a refused provider request is sent again, row usage || [`sprite-gen sound`](sound.md) | Generate normalized SFX and BGM audio assets with Opus and AAC encoding, SQLite raw request caching, and Web Audio loop metadata. || [pixel-draw.md](pixel-draw.md) | `sprite-gen pixel-draw` (experimental): Claude Opus draws 8–48 px pixel art as a pixel grid — the inputs, the safe area, the style (`--style`), a set of up to 64 frames drawn four at a time and one motion (`--motion`), the run folder and its report, gates G1–G8, the row repair and the one redraw, the pick between candidates, Message Batches and `--resume`, re-rendering an edited `grid.txt` || [logo.md](logo.md) | `sprite-gen logo`: a title logo or wordmark lettered by the model into a title screen or poster, only its lettering redrawn on a chroma key, cut out with its glow kept — the steps, files, report, text check and refusals, the key choice, the logo matte and its known limit |diff --git a/docs/gen.md b/docs/gen.mdindex f7aec94..edac279 100644--- a/docs/gen.md+++ b/docs/gen.md@@ -1,6 +1,6 @@# `sprite-gen gen` — provider-backed image generation (engine SSoT)-> Owns: `sprite-gen gen` / `gen-set`: providers, default resolution, transparency strategy per provider, the billed knobs (`--quality`, `--resolution`), when a refused provider request is sent again (every direct provider call), row usage · Index: [docs/README.md](README.md)+> Owns: `sprite-gen gen` / `gen-set`: providers, default resolution and what a default codex that cannot run turns into, transparency strategy per provider, the billed knobs (`--quality`, `--resolution`), when a refused provider request is sent again (every direct provider call), row usage · Index: [docs/README.md](README.md)Generation is a first-class engine module (`sprite_gen/gen/`), not an externalskill. One call = a prompt (+ optional reference images) → one **verified** PNG on@@ -26,21 +26,22 @@ The strategy is declared **once**, on the adapter (`Provider.transparency`), andthe only place that says what a backend can do. See[Transparent output](#transparent-output--strategy-per-provider).-## Subscription first — `openai` is named or it does not run+## Subscription first — `openai` runs only when you chose it`codex` and `grok` run on a subscription the user already pays for. `openai`reaches the same family of GPT image models over the REST API with nothing but akey — which is what a headless container (a Modal worker, CI, a SaaS backend) canhave, and where an interactive ChatGPT login cannot exist — and every call is-billed against that key. So it is registered, documented, and **explicit-only**-(maintainer 확정 2026-09-20):--- it runs only when `--provider openai` names it;-- `SPRITE_GEN_DEFAULT_PROVIDER=openai` is **refused**, not honoured;-- the guided flow (`sprite-gen workflow`) never offers it and never saves it as a- preference;-- no availability fallback targets it — a codex outage reaches `grok`, another- subscription route, or it fails; it never reaches metered credit;+billed against that key. So it is registered, documented, and runs **only when the+user chose it** (maintainer 확정 2026-09-20, widened 2026-10-16 from "only when+named"):++- it runs when `--provider openai` names it, or when it is the user's own answer+ for a default codex that cannot run ([below](#when-codex-cannot-run--ask-or-what-you-chose));+- it is never a default: `SPRITE_GEN_DEFAULT_PROVIDER=openai` is **refused**, not+ honoured, and nothing reaches it unasked;+- the guided flow (`sprite-gen workflow`) never offers it as the image provider; it+ offers it once, as one answer to "codex cannot run here — what now?", billing named;- having `OPENAI_API_KEY` in the environment changes no route by itself;- every call it does make prints one stderr line naming the charge *before* therequest leaves.@@ -54,25 +55,77 @@ precedence (maintainer 확정 2026-07-17):1. **`SPRITE_GEN_DEFAULT_PROVIDER`** env var (`codex` or `grok`) — the user override.An unknown value fails loud, and so does `openai`: a per-call API backend is- named at the call site or not used ([subscription first](#subscription-first--openai-is-named-or-it-does-not-run)).+ never a default ([subscription first](#subscription-first--openai-runs-only-when-you-chose-it)).2. **`codex`** — the hard default (GPT `image_gen`).-If the resolved default is `codex` but codex is unavailable here (CLI not on PATH,-or `codex login status` reports not-logged-in), the resolution **falls back to-`grok` — observably, never silently**: a stderr notice is printed and the report-JSON records `provider_fallback` (`from`/`to`/`reason`/`default_source`). The-grok default (`SPRITE_GEN_DEFAULT_PROVIDER=grok`) has no reverse fallback — a down-grok fails loud at generation time. The fallback target is a subscription route by-construction; `openai` is never one.+A resolved default of `codex` that cannot run here turns into what the user chose+for that ([below](#when-codex-cannot-run--ask-or-what-you-chose)). The grok default+(`SPRITE_GEN_DEFAULT_PROVIDER=grok`) has no reverse fallback — a down grok fails+loud at generation time.An **explicit `--provider`** is always honored verbatim — it is never overridden by-the availability fallback. An explicitly named provider that is down fails loud-(the provider adapter raises), preserving the operator's stated intent.+the choice below. An explicitly named provider that is down fails loud (the provider+adapter raises; a named codex whose usage is used up fails with codex's own words,+exit 1), preserving the operator's stated intent.Every generation reports which backend actually ran: `provider` (the realbackend), `provider_resolved_from` (`explicit` / `SPRITE_GEN_DEFAULT_PROVIDER` /-`hard-default` / `fallback-from-codex`), and `provider_fallback` when a fallback-happened.+`hard-default` / `fallback-from-codex`), and `provider_fallback` when a default+codex that could not run was switched to the provider chosen for that.++## When codex cannot run — ask, or what you chose++A call that names no provider (`gen`, `logo`, `gen-set`, `video-set`'s mid-step+redraw) runs on codex. When codex **cannot run here** it does not switch on its own+(maintainer 확정 2026-10-16; until 2.44.0 it went to `grok` unasked). Codex cannot+run when++- **it is not signed in** (`cause: login`): `codex_provider.codex_login` — the CLI is+ not on PATH, `codex login status` fails or does not answer, or exits non-zero.+ Known before anything is generated.+- **its usage is used up** (`cause: usage-limit`): `codex exec` ends on one of the+ errors codex itself classes as its usage limit, read from what it says+ (`codex_provider.usage_limit`, below). Known only after `codex exec` ran, so the+ same choice applies there: the call runs again on the chosen provider.++What happens then is the user's choice, one of three:++| Choice | What a call that names no provider does |+|---|---|+| `ask` (the default) | Nothing is generated. One stderr line `sprite-gen ask codex-unavailable: {…}` and **exit 75**: the line's JSON holds `cause`, `reason` (the reading's own words), `question`, and `choices` — the flag that runs each answer (`--provider openai`, `--provider grok`; `video-set`: `--still-provider …`), `stop` null. The agent asks the user ([SKILL](../SKILL.md#when-codex-cannot-run--exit-75)). |+| `grok` | Runs on grok. One stderr line says codex could not run, why, and whose choice grok was; the report keeps `provider_fallback` (`from`, `to`, `cause`, `reason`, `default_source`, `chosen_by`). |+| `openai` | Runs on the OpenAI API, billed per call: the same switch line and `provider_fallback`, and the charge line every `openai` call prints. |++The choice is read in this order, only when codex cannot run:+`SPRITE_GEN_CODEX_UNAVAILABLE` (`ask` / `grok` / `openai`, an unknown value fails+loud), then the saved one (`sprite-gen defaults save --codex-unavailable …`, in the+[one settings file](user-workflow.md#one-settings-owner); `chosen_by: saved`), then+`ask`. The guided flow asks it once and saves it.++`gen-set` and `video-set` run `gen` per row or item with its output in a log. A+child that asked does not fail its row in silence: the set stops with the same+question and exit 75 once the rows under way have ended (a `gen-set` starts no+further stage; a `video-set` lets its other items finish, as they need no codex), its+report and `table.md` keep the question (`asked`), and the line names the set's own+flag. Rerun the set with the answer's flag; finished rows and items are reused.++**The usage-limit signal** (2026-10-16, codex-rs source at `rust-v0.160.1` and+`rust-v0.153.4`). codex classes three errors as its usage limit+(`CodexErr::to_codex_protocol_error` → `CodexErrorInfo::UsageLimitExceeded`,+`codex-rs/protocol/src/error.rs`): `UsageLimitReached` (an HTTP 429+`usage_limit_reached`), `QuotaExceeded` (429 `insufficient_quota` and its billing+codes) and `UsageNotIncluded` (429 `usage_not_included`; `codex-rs/codex-api/src/api_bridge.rs`).+`codex exec --json` carries only their message: its `error` and `turn.failed` events+hold `message` alone (`codex-rs/exec/src/event_processor_with_jsonl_output.rs`), the+error event is not kept in the rollout (`codex-rs/rollout/src/policy.rs`), and codex+exits 1. So the signal is the start of each message as codex's own tests pin it+(`codex-rs/protocol/src/error_tests.rs`): "You've hit your usage limit" (the+apostrophe is ASCII in 0.153.4 and U+2019 in 0.160.1), "Your workspace is out of+credits.", "You hit your spend cap set", "Quota exceeded. Check your plan and billing+details." and "To use Codex with your ChatGPT plan, upgrade to Plus". Any other+failure of `codex exec` is a failure, not the question. These sentences were read+from the source, not seen from a used-up account; a codex release that rewords them+is a failure until this list follows it.## Direct Grok calls and authentication@@ -116,7 +169,7 @@ anywhere. Unset, the run stops naming the variable and where to get a key; set bempty, it says so. It never falls back to the codex ChatGPT login or to another key;a refusal OpenAI documents as a request not taken is sent again, nothing else is([a refused request sent again](#a-refused-request-sent-again)) — and see-[subscription first](#subscription-first--openai-is-named-or-it-does-not-run) for why+[subscription first](#subscription-first--openai-runs-only-when-you-chose-it) for whynothing routes here on its own.The default model is `gpt-image-2.5-flare`; `--model` selects another gpt-image@@ -238,7 +291,7 @@ second run on top would make every one of its POSTs a second retry loop.```bashsprite-gen gen \- [--provider codex|grok|openai] # optional; default = SPRITE_GEN_DEFAULT_PROVIDER env → codex (observable grok fallback if codex is down). openai only when named here — it bills per call+ [--provider codex|grok|openai] # optional; default = SPRITE_GEN_DEFAULT_PROVIDER env → codex; a codex that cannot run asks (exit 75) or runs what you chose for that. openai bills per call--prompt "…" # or --prompt-file PROMPT.txt--out DEST.png \[--ref REF.png ...] # repeatable; Grok accepts up to five references, openai up to sixteen@@ -268,7 +321,7 @@ Backward-compatible wrapper: `$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT`raw_bytes`, `elapsed_seconds`, `session_id` (codex), an `alpha` block(`strategy` + the measured stats), the `chroma` stats when chroma keying ran, and theprovider-resolution fields (`provider_resolved_from`, and `provider_fallback` when a- codex→grok default fallback occurred), plus the provider `extra` block+ default codex that could not run was switched to the provider chosen for that), plus the provider `extra` block(`auth_source`, `transport`, `endpoint`, and the knobs the request actuallycarried).@@ -433,7 +486,7 @@ 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.+ 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` asks or runs what was chosen instead, [above](#when-codex-cannot-run--ask-or-what-you-chose)). A `codex exec` that ends on codex's usage limit is `codex_provider.CodexUsageLimit`: the same failure for a named codex, the same choice for a default one. 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@@ -452,8 +505,8 @@ exactly that, rather than falling back on its own.- **grok** — uses the [direct API contract](#direct-grok-calls-and-authentication) above.- **openai** — uses the [direct API contract](#direct-openai-calls-and-authentication)above: one HTTPS request on `OPENAI_API_KEY`, no CLI and no subprocess, which is- the whole reason it exists (a container has a key, not a browser). Explicit-only,- and billed per call.+ the whole reason it exists (a container has a key, not a browser). Runs only when+ chosen, and billed per call.## Sprite-row usage@@ -465,9 +518,10 @@ 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` (`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+non-zero when any row failed. `--provider` (`codex`, `grok` or `openai`) is honoured verbatim;+unspecified, it resolves exactly as `gen` does (above): a switch to the provider chosen for a+codex that cannot run is recorded per row with the row's `auth_source`, and rows that asked stop+the set with the question ([above](#when-codex-cannot-run--ask-or-what-you-chose)). Each row'soutput goes to its log, but a row's billing line and a provider switch also print on theterminal as they happen (`base.run_logged`), so a metered row is never announced only in a file.diff --git a/docs/user-workflow.md b/docs/user-workflow.mdindex bb507bb..faf2e81 100644--- a/docs/user-workflow.md+++ b/docs/user-workflow.md@@ -21,10 +21,10 @@ $SPRITE_GEN_ROOT/.venv/bin/sprite-gen workflow --kind imageThe command is read-only: it checks available credentials, reads defaults and returns JSON. `status` is `ready`, `needs-input` or `blocked`; exit 0 means ready and exit 2 means read the questions or blockers. It never generates images, launches a browser, changes authentication or saves defaults.1. Check the returned access state and explain only what needs the user's attention.-2. Ask the missing generation choices in `questions`, using their labels rather than CLI identifiers. For sprites, explain that the first provider creates the base drawing, while the motion method animates it.+2. Ask the missing generation choices in `questions`, using their labels rather than CLI identifiers. For sprites, explain that the first provider creates the base drawing, while the motion method animates it. Until it is answered, `questions` also holds `codex_unavailable` ("지피티(codex)를 쓸 수 없을 때 — 로그인이 없거나 사용량을 다 썼을 때 — 어떻게 할까요?": stop and ask, Grok, or the OpenAI API billed per call). It is asked once: save the answer at once with `defaults save --codex-unavailable <answer> --expected-revision <settings_revision>` (the question's `save: general`, no `--kind`), and it is not asked again. `codex_unavailable` in the guide's answer says the choice in force and where it came from (`saved`, `SPRITE_GEN_CODEX_UNAVAILABLE`, or `default` = not yet answered).3. Run `workflow` again with the answers. Request choices override saved values without modifying them. When choices came from saved defaults, briefly announce them and do not ask again.4. Gather only missing creative inputs: subject, style, requested motions and output needs. Lock the base before motion generation.-5. Only when the start stage returns `status: ready`, run the returned pipeline through the existing tools. A populated `pipeline` is a proposal, not permission to ignore unresolved questions or blockers. Always pass its explicit provider to `gen`/`gen-set`; do not rely on the low-level CLI's omitted-provider resolution. GPT rows use `codex` even when Grok made the base. No availability-driven provider switch is allowed in this workflow.+5. Only when the start stage returns `status: ready`, run the returned pipeline through the existing tools. A populated `pipeline` is a proposal, not permission to ignore unresolved questions or blockers. Always pass its explicit provider to `gen`/`gen-set`; do not rely on the low-level CLI's omitted-provider resolution. GPT rows use `codex` even when Grok made the base. No availability-driven provider switch is allowed in this workflow. A step that still names no provider — `video-set`'s mid-step redraw for a front or back walk — follows the saved `codex_unavailable` answer when codex cannot run; when that answer is to ask, the step ends with exit 75 and the question ([gen](gen.md#when-codex-cannot-run--ask-or-what-you-chose), [SKILL](../SKILL.md#when-codex-cannot-run--exit-75)).6. Complete the pipeline's QA and deliver the output files. Chroma removal, extraction, placement and export are automatic stages, not user choices. Raw images are evidence, not replacements for extracted sprite frames. Follow [atlas-workflow](atlas-workflow.md), [video-pipeline](video-pipeline.md) or [gen](gen.md), as returned by the guide.```bash@@ -55,7 +55,7 @@ When the profile has no saved defaults, finish then offers: "이번 선택을## One settings owner-`preferences.json` in `~/.config/sprite-gen/` owns the `sprite` and `image` profiles separately. `SPRITE_GEN_CONFIG_DIR` explicitly relocates that directory. A profile may be partial, for example saving only motion and curation when an existing base skipped image-provider selection. Missing fields prompt when needed. This storage is independent of a project or run; a run's numeric recipe and curation edits keep their existing owners.+`preferences.json` in `~/.config/sprite-gen/` owns the `sprite` and `image` profiles separately, and beside them the `general` settings every profile shares: so far `codex_unavailable` (`ask`, `grok` or `openai`; what a call that names no provider does when codex cannot run — the rule is [gen](gen.md#when-codex-cannot-run--ask-or-what-you-chose)'s). `SPRITE_GEN_CONFIG_DIR` explicitly relocates that directory. A profile may be partial, for example saving only motion and curation when an existing base skipped image-provider selection. Missing fields prompt when needed. This storage is independent of a project or run; a run's numeric recipe and curation edits keep their existing owners. The file is version 2 (`profiles` and `general`); a version 1 file (profiles only) still reads, with nothing chosen for codex, and the next save writes it as version 2.```bash$SPRITE_GEN_ROOT/.venv/bin/sprite-gen defaults show@@ -64,8 +64,10 @@ $SPRITE_GEN_ROOT/.venv/bin/sprite-gen defaults save --kind sprite \--expected-revision REVISION_FROM_SHOW$SPRITE_GEN_ROOT/.venv/bin/sprite-gen defaults clear --kind image \--expected-revision REVISION_FROM_SHOW+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen defaults save --codex-unavailable ask \+ --expected-revision REVISION_FROM_SHOW```-Use the exact `settings_revision` from the guide, or `revision` from show (`missing` for no file). Save merges only supplied fields in the selected profile; clear removes only that profile. Both are explicit mutations. Reads never create or rewrite settings. Corrupt or unknown settings fail with a named error instead of resetting silently.+Use the exact `settings_revision` from the guide, or `revision` from show (`missing` for no file). Save merges only supplied fields in the selected profile, and `--codex-unavailable` into `general` (it needs no `--kind`); clear removes only that profile. Both are explicit mutations. Reads never create or rewrite settings. Corrupt or unknown settings fail with a named error instead of resetting silently.Writes use the package's cross-platform exclusive file lock, compare the observed revision under that lock, then atomically replace the complete JSON file. Two writers with the same revision cannot overwrite each other: the first committed write wins; the second fails and must reread/reconfirm. A repeated save with the current revision and identical values leaves bytes and mtime unchanged. Atomic replacement lets read-only queries see a complete old or new snapshot without creating a lock file.diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.pyindex 7058e83..c19a50f 100644--- a/sprite_gen/gen/__init__.py+++ b/sprite_gen/gen/__init__.py@@ -14,10 +14,11 @@ codex needs an interactive ChatGPT login and the `codex` CLI on PATH, openai neeonly 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.+SaaS and is billed per call, so it runs ONLY when the user chose it (수홍 2026-10-16):+`--provider openai` names it, or it is the user's answer for a default codex that+cannot run (`codex_unavailable_choice`). It is never a default, never the guided+flow's image provider, and never reached unasked. 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 a@@ -43,7 +44,7 @@ import shutilimport sysimport tempfilefrom pathlib import Path-from typing import Any+from typing import Any, Callablefrom sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.util.cli_kwargs import namespace_from_kwargs@@ -56,6 +57,7 @@ from . import facing as facing_modfrom . import handedness as handed_modfrom . import prompt_partsfrom .base import (+ CODEX_UNAVAILABLE_EXIT,QUALITIES,RESOLUTIONS,TRANSPARENCY_CHROMA,@@ -65,6 +67,8 @@ from .base import (GenResult,PROVIDER_SWITCH_WORDS,GenTimeoutError,+ ask_codex_unavailable,+ codex_unavailable_question,print_json,verify_png,)@@ -80,18 +84,25 @@ ALPHA_MODE_AUTO = "auto"ALPHA_MODES = (ALPHA_MODE_AUTO, *TRANSPARENCY_STRATEGIES)# Default-provider policy (maintainer 확정 2026-07-17): the default backend is codex-# (GPT `image_gen`). If codex is unavailable in the environment (CLI missing or-# not logged in) the default resolution falls back to grok — but OBSERVABLY, never-# silently (No Silent Fallback): the chosen provider and the fallback reason are-# reported. A user can change the default with SPRITE_GEN_DEFAULT_PROVIDER. An-# EXPLICIT `--provider` is always honored exactly (no availability fallback) — an-# explicitly named provider that is down fails loud at generation time.+# (GPT `image_gen`); a user can change the default with SPRITE_GEN_DEFAULT_PROVIDER.+# An EXPLICIT `--provider` is always honored exactly — an 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).+# A per-call API-billed backend is never a default: only a choice the user made+# reaches it, so nothing routes a subscription user onto metered credit unasked+# (구독 우선 불변식 1-2).EXPLICIT_ONLY_PROVIDERS = ("openai",)+# What a default codex that cannot run here turns into (수홍 2026-10-16, docs/gen.md "When codex cannot run"):+# codex is not signed in (`codex_provider.codex_login`), or `codex exec` said its usage is used up+# (`codex_provider.CodexUsageLimit`). `ask` (the default) ends the call with one question and nothing generated+# (`base.ask_codex_unavailable`); `grok` and `openai` run that provider, said on stderr and kept in the report+# (`provider_fallback`). The choice is SPRITE_GEN_CODEX_UNAVAILABLE, else the saved one (`sprite-gen defaults`,+# key CODEX_UNAVAILABLE_SETTING), else `ask`. Until 2.44.0 it went to grok unasked.+CODEX_UNAVAILABLE_ENV = "SPRITE_GEN_CODEX_UNAVAILABLE"+CODEX_UNAVAILABLE_SETTING = "codex_unavailable"+CODEX_UNAVAILABLE_CHOICES = ("ask", "grok", "openai")+CODEX_UNAVAILABLE_DEFAULT = "ask"# `--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@@ -284,13 +295,14 @@ def resolve_default_provider() -> tuple[str, dict[str, str] | None]:"""Resolve the provider to use when `--provider` is not given.Precedence: SPRITE_GEN_DEFAULT_PROVIDER env > hard default (codex). When the- resolved default is codex but codex is unavailable, fall back to grok and return- fallback 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.+ resolved default is codex but codex is not signed in here, it is what the user+ chose for that (`codex_unavailable`): the question, raised, or the chosen+ provider with the switch (from/to/cause/reason/default_source/chosen_by).+ Returns (provider, switch_or_None).++ An EXPLICIT_ONLY provider is never a default: not the hard default, not out of+ DEFAULT_PROVIDER_ENV. It comes out of here only as the user's own answer for a+ codex that cannot run."""configured = os.environ.get(DEFAULT_PROVIDER_ENV, "").strip()if configured:@@ -302,30 +314,92 @@ def resolve_default_provider() -> tuple[str, dict[str, str] | None]: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."+ f"against an API key and is never a default: name it (`--provider {configured}`), or choose it "+ f"for when codex cannot run (`sprite-gen defaults save --codex-unavailable {configured}`). Use "+ f"{', '.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):- # 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.+ # Only a codex default turns into the user's choice. A grok default that is down+ # fails loud at generation time rather than reverse-falling back to codex.if default == "codex":ok, reason = _codex_available()if not ok:- return "grok", {- "from": "codex",- "to": "grok",- "reason": reason,- "default_source": source,- }+ return codex_unavailable("login", reason, default_source=source)return default, None+def codex_unavailable_choice() -> tuple[str, str]:+ """What a default codex that cannot run turns into, and who said so: (choice, `CODEX_UNAVAILABLE_ENV` | `saved`+ | `default`). The environment first, then the saved preference (`workflow.preferences`, its general settings),+ then `ask`. Read only when codex cannot run, so a broken settings file stops nothing else."""+ configured = os.environ.get(CODEX_UNAVAILABLE_ENV, "").strip()+ if configured:+ if configured not in CODEX_UNAVAILABLE_CHOICES:+ raise SystemExit(f"gen: {CODEX_UNAVAILABLE_ENV}={configured!r} is not a choice; "+ f"expected one of {', '.join(CODEX_UNAVAILABLE_CHOICES)}")+ return configured, CODEX_UNAVAILABLE_ENV+ # The settings owner imports this package (its catalog names the choices), so it is imported here.+ from sprite_gen.workflow.preferences import read_settings++ try:+ saved = read_settings()["general"].get(CODEX_UNAVAILABLE_SETTING)+ except (ValueError, OSError) as exc:+ raise SystemExit(f"gen: {exc}") from exc+ if saved:+ return saved, "saved"+ return CODEX_UNAVAILABLE_DEFAULT, "default"+++def codex_unavailable(cause: str, reason: str, *, default_source: str) -> tuple[str, dict[str, str]]:+ """A default codex that cannot run (`cause` `login` or `usage-limit`, `reason` the reading's words), turned into+ the user's choice: raises the question (`CodexUnavailableAsk`) for `ask`, else returns the chosen provider and+ the switch the report keeps as `provider_fallback`."""+ choice, chosen_by = codex_unavailable_choice()+ if choice == "ask":+ raise ask_codex_unavailable(codex_unavailable_question(cause, reason))+ return choice, {"from": "codex", "to": choice, "cause": cause, "reason": reason,+ "default_source": default_source, "chosen_by": chosen_by}+++def _announce_switch(verb: str, switch: dict[str, str]) -> None:+ print(f"sprite-gen {verb}: default provider '{switch['from']}' cannot run ({switch['reason']}) "+ f"{PROVIDER_SWITCH_WORDS} '{switch['to']}', the choice for when codex cannot run "+ f"({'saved with sprite-gen defaults' if switch['chosen_by'] == 'saved' else switch['chosen_by']}). "+ "Pass --provider to name one, or change the choice with `sprite-gen defaults save --codex-unavailable`.",+ file=sys.stderr, flush=True)+++def run_on_default(verb: str, provider: str | None, call: Callable[[str, str, dict[str, str] | None], Any],+ ) -> tuple[Any, str, dict[str, str] | None]:+ """`call(provider, resolved_from, switch)` on the provider `--provider` named, else on the default one: returns+ (its result, how the provider was chosen — `provider_resolved_from` — and the switch or None).++ The one place a call that names no provider is resolved (`gen`, `logo`). A default codex that is not signed in+ is the user's choice before anything runs (`resolve_default_provider`); one whose `codex exec` says its usage is+ used up (`codex_provider.CodexUsageLimit`) is the same choice where it is found, and `call` runs again on the+ chosen provider. A named provider runs as named: its usage limit is its failure."""+ if provider is not None:+ return call(provider, "explicit", None), "explicit", None+ provider, switch = resolve_default_provider()+ if switch:+ _announce_switch(verb, switch)+ resolved_from = f"fallback-from-{switch['from']}"+ elif os.environ.get(DEFAULT_PROVIDER_ENV, "").strip():+ resolved_from = DEFAULT_PROVIDER_ENV+ else:+ resolved_from = "hard-default"+ try:+ return call(provider, resolved_from, switch), resolved_from, switch+ except codex_provider.CodexUsageLimit as exc:+ provider, switch = codex_unavailable("usage-limit", exc.said, default_source=resolved_from)+ _announce_switch(verb, switch)+ resolved_from = f"fallback-from-{switch['from']}"+ return call(provider, resolved_from, switch), resolved_from, switch++def trim_to_alpha(path: Path, *, threshold: int = 8) -> dict[str, Any]:"""Crop a transparent PNG in place to the bbox of its opaque pixels.@@ -637,27 +711,7 @@ def _run(args: argparse.Namespace) -> int:prompt = args.promptif args.prompt_file:prompt = Path(args.prompt_file).expanduser().read_text(encoding="utf-8")- # Explicit --provider is honored verbatim; only the unspecified case resolves the- # default (env > codex) with an observable codex->grok availability fallback.- provider = args.provider- fallback: dict[str, str] | None = None- if provider is not None:- resolved_from = "explicit"- else:- provider, fallback = resolve_default_provider()- if fallback:- resolved_from = f"fallback-from-{fallback['from']}"- print(- f"sprite-gen gen: default provider '{fallback['from']}' unavailable "- f"({fallback['reason']}) {PROVIDER_SWITCH_WORDS} '{fallback['to']}'. "- f"Set {DEFAULT_PROVIDER_ENV} or pass --provider to control this.",- file=sys.stderr,- )- elif os.environ.get(DEFAULT_PROVIDER_ENV, "").strip():- resolved_from = DEFAULT_PROVIDER_ENV- else:- resolved_from = "hard-default"- result = generate_image(+ result, resolved_from, fallback = run_on_default("gen", args.provider, lambda provider, *_: generate_image(provider,prompt or "",args.out,@@ -680,12 +734,13 @@ def _run(args: argparse.Namespace) -> int:workdir=args.workdir,decontam=str(getattr(args, "decontam", None) or "off"),layout_guide=getattr(args, "layout_guide", None),- )+ ))payload = result.to_dict()# `provider` in the payload is always the backend that actually generated the# image; `provider_resolved_from` records HOW it was chosen and- # `provider_fallback` records a default->fallback switch when one happened- # (No Silent Fallback — the report names which provider was used and why).+ # `provider_fallback` records the switch from a codex that could not run to the+ # provider the user chose for that (No Silent Fallback — the report names which+ # provider was used and why).payload["provider_resolved_from"] = resolved_fromif fallback:payload["provider_fallback"] = fallback@@ -710,9 +765,11 @@ 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. A default codex that cannot run (not signed in, or its usage used up) "+ f"asks (exit {CODEX_UNAVAILABLE_EXIT}) or runs what was chosen for that "+ f"(`sprite-gen defaults save --codex-unavailable`, {CODEX_UNAVAILABLE_ENV}). ""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"+ "and is billed per call on OPENAI_API_KEY, so it runs only when chosen"),)parser.add_argument("--prompt")diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.pyindex 180ab14..a8b3862 100644--- a/sprite_gen/gen/base.py+++ b/sprite_gen/gen/base.py@@ -127,6 +127,60 @@ def provider_binary(name: str) -> str:API_CHARGE_WORDS = "this is a per-call API charge, not a subscription"PROVIDER_SWITCH_WORDS = "— falling back to"+# The one question sprite-gen hands back instead of an image (docs/gen.md "When codex cannot run"): a call that+# named no provider found codex unable to run, and what the user chose for that is to be asked. Nothing was+# generated. It is one stderr line, these words and a JSON object (`cause`, `reason`, `question`, and `choices`:+# the flag that runs each answer), and this exit code. A batch verb whose child asked reads the child's line from+# its log and stops with the same question, naming its own flag.+CODEX_UNAVAILABLE_EXIT = 75+CODEX_UNAVAILABLE_ASK = "sprite-gen ask codex-unavailable: "+++class CodexUnavailableAsk(SystemExit):+ """The question was asked instead of generating; `question` is the JSON object of its line."""++ def __init__(self, question: dict[str, Any]) -> None:+ super().__init__(CODEX_UNAVAILABLE_EXIT)+ self.question = question+++def codex_unavailable_question(cause: str, reason: str, *, flag: str = "--provider") -> dict[str, Any]:+ """The question's JSON object. `cause` is `login` (codex is not signed in here: `codex_provider.codex_login`) or+ `usage-limit` (codex said its usage is used up: `codex_provider.usage_limit`); `reason` says which, in the+ reading's own words; `flag` is the asking verb's flag that runs an answer."""+ return {+ "cause": cause,+ "reason": reason,+ "question": f"codex cannot run here ({reason}). Generate with the OpenAI API (billed per call), "+ "with Grok, or stop?",+ "choices": {"openai": f"{flag} openai", "grok": f"{flag} grok", "stop": None},+ }+++def ask_codex_unavailable(question: dict[str, Any]) -> CodexUnavailableAsk:+ """Print the question (`codex_unavailable_question`) on stderr and return the exit that ends the call with it."""+ print(CODEX_UNAVAILABLE_ASK + json.dumps(question, ensure_ascii=False), file=sys.stderr, flush=True)+ return CodexUnavailableAsk(question)+++def asked_codex_unavailable(output: str) -> dict[str, Any] | None:+ """The question in a call's output (its last question line), or None when it asked none."""+ for line in reversed(output.splitlines()):+ if line.startswith(CODEX_UNAVAILABLE_ASK):+ try:+ return json.loads(line[len(CODEX_UNAVAILABLE_ASK):])+ except ValueError:+ return None+ return None+++def child_asked(rc: int, log: Path) -> dict[str, Any] | None:+ """The question a child `sprite-gen gen` run through `run_logged` asked instead of generating: its exit code is+ CODEX_UNAVAILABLE_EXIT and its line is in `log`. None for any other ending."""+ if rc != CODEX_UNAVAILABLE_EXIT or not log.is_file():+ return None+ return asked_codex_unavailable(log.read_text(encoding="utf-8", errors="replace"))+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.diff --git a/sprite_gen/gen/codex_provider.py b/sprite_gen/gen/codex_provider.pyindex 0eb477a..e3db7f6 100644--- a/sprite_gen/gen/codex_provider.py+++ b/sprite_gen/gen/codex_provider.py@@ -18,6 +18,9 @@ How codex is signed in is one question, `codex_login`, asked by every caller: thprovider resolution, `generate`, the facing check and the guided workflow. Signed in withChatGPT 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`).+Whether `codex exec` ended on codex's usage limit is the other, `usage_limit`: a codex that is+not signed in or whose usage is used up is what a call that names no provider turns into the+user's choice (`gen.run_on_default`)."""from __future__ import annotations@@ -49,6 +52,43 @@ LOGIN_PROBE_TIMEOUT_SECONDS = 15LOGIN_HINT = "`codex login` signs your ChatGPT subscription in"+# What `codex exec` says when the codex usage of the account behind it is used up (2026-10-16, codex-rs source at+# rust-v0.160.1 and rust-v0.153.4). codex classes three of its errors as its usage limit+# (`CodexErr::to_codex_protocol_error` -> `CodexErrorInfo::UsageLimitExceeded`, codex-rs/protocol/src/error.rs):+# `UsageLimitReached` (a 429 `usage_limit_reached`; its message names the plan, a workspace out of credits or a+# spend cap), `QuotaExceeded` (a 429 `insufficient_quota` and its billing codes) and `UsageNotIncluded` (a 429+# `usage_not_included`). That class reaches `codex exec --json` only as the message text: the `error` and+# `turn.failed` events carry `message` alone (codex-rs/exec/src/event_processor_with_jsonl_output.rs, exec_events.rs),+# the error event is not kept in the rollout (codex-rs/rollout/src/policy.rs), and codex exits 1. So the signal is+# the start of each message, as codex's own tests pin it (codex-rs/protocol/src/error_tests.rs); 0.160.1 writes the+# apostrophe of "You've" as U+2019, 0.153.4 as an ASCII one. A message is matched anywhere in what codex said,+# since a remote compaction puts its own words before it. No other failure is read as the usage limit.+USAGE_LIMIT_MESSAGES = (+ "You've hit your usage limit", # UsageLimitReached, codex 0.153.4 and before+ "You’ve hit your usage limit", # UsageLimitReached, codex 0.160.1+ "Your workspace is out of credits.", # UsageLimitReached, a workspace's credits+ "You hit your spend cap set", # UsageLimitReached, a workspace's spend cap+ "Quota exceeded. Check your plan and billing details.", # QuotaExceeded+ "To use Codex with your ChatGPT plan, upgrade to Plus", # UsageNotIncluded+)+++def usage_limit(said: list[str]) -> str | None:+ """The first of what codex said (`_extract_stream_errors`) that is its usage limit (USAGE_LIMIT_MESSAGES), or+ None."""+ return next((message for message in said if any(words in message for words in USAGE_LIMIT_MESSAGES)), None)+++class CodexUsageLimit(SystemExit):+ """`codex exec` ended on its usage limit. The failure of a named `--provider codex` as before (same message,+ exit 1); a call that named no provider turns it into the user's choice (`gen.run_on_default`). `said` is codex's+ message."""++ def __init__(self, message: str, said: str) -> None:+ super().__init__(message)+ self.said = said++@dataclass(frozen=True)class CodexLogin:source: str | None # AUTH_SOURCE_LOGIN | AUTH_SOURCE_API_KEY | None (not usable here)@@ -415,9 +455,9 @@ class CodexProvider:stream_errors = _extract_stream_errors(stdout)tail = (completed.stderr or "").strip().splitlines()[-20:]detail = "\n".join(stream_errors + tail).strip() or "(no error detail on stdout/stderr)"- raise SystemExit(- f"codex-gen: codex exec exited {completed.returncode}\n{detail}"- )+ message = f"codex-gen: codex exec exited {completed.returncode}\n{detail}"+ said = usage_limit(stream_errors)+ raise CodexUsageLimit(message, said) if said else SystemExit(message)session_id = _parse_session_id(stdout)if not session_id:diff --git a/sprite_gen/gen/gen_set.py b/sprite_gen/gen/gen_set.pyindex caf4d7c..d7c9aff 100644--- a/sprite_gen/gen/gen_set.py+++ b/sprite_gen/gen/gen_set.py@@ -11,8 +11,11 @@ Same contract as `video-set`: items are idempotent (an existing row is reused un`--force`), every item gets its own report, `table.md` names failures by stage, and theexit code is non-zero when any item failed. There is no fallback provider: `--provider`is honoured verbatim and the unspecified case resolves exactly like `gen` does-(`SPRITE_GEN_DEFAULT_PROVIDER` > codex, with the same observable codex→grok-availability failover recorded per item).+(`SPRITE_GEN_DEFAULT_PROVIDER` > codex; a codex that cannot run turns into what the user+chose for that, recorded per item). When that choice is to ask, every row's `gen` asks+instead of generating, and the set stops with the same question and exit code+(`base.CODEX_UNAVAILABLE_EXIT`) once the rows under way have ended, naming `--provider` as+the way to answer it.Direction-contract runs follow the run's own `references/generation-plan.json`: stage 1(direction anchors, base-referenced) must be generated, extracted and an anchor frame@@ -32,7 +35,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_logged+from sprite_gen.gen.base import ask_codex_unavailable, child_asked, codex_unavailable_question, run_loggedfrom sprite_gen.spec import layoutfrom sprite_gen.spec.runio import atomic_write_text@@ -170,6 +173,10 @@ def run_item(if partial.exists():partial.unlink()if rc != 0:+ if (question := child_asked(rc, log)) is not None:+ result["asked"] = question+ raise SystemExit(f"gen asked what to do instead of generating: codex cannot run here "+ f"({question['reason']})")tail = log.read_text(encoding="utf-8", errors="replace").strip().splitlines()[-3:] if log.exists() else []raise SystemExit(f"gen exited {rc}; " + (" | ".join(tail) if tail else f"see {log}") + " — the row and its report were removed")raise SystemExit(f"gen exited 0 but its {why or bad_image}; the row and the report were removed so the next run regenerates")@@ -192,6 +199,9 @@ def write_table(results: list[dict[str, Any]], path: Path) -> str:for r in results:if r.get("ok") and r.get("reused"):lines.append(f"| {r['state']} | - | - | - | reused |")+ elif r.get("asked"):+ lines.append(f"| {r['state']} | - | - | {r.get('elapsed_seconds', '-')} | ASKED: codex cannot run here "+ f"({r['asked']['reason'][:80]}) |")elif r.get("ok"):lines.append(f"| {r['state']} | {r.get('provider') or '-'} | {r.get('provider_resolved_from') or '-'} | {r.get('elapsed_seconds', '-')} | OK |")else:@@ -225,6 +235,8 @@ def run_set(r = fut.result()results.append(r)print(json.dumps({k: r[k] for k in ("state", "ok") if k in r} | ({"error": r["error"]} if not r.get("ok") else {}), ensure_ascii=False), flush=True)+ if any(r.get("asked") for r in results):+ break # every row would ask the same: the set asks it once, belowif any(not r.get("ok") for r in results if r["state"] in stage) and len(_stages(request, ordered)) > 1:# a failed anchor stage cannot feed stage 2 — stop here and say so, do not attach the base insteadbreak@@ -233,6 +245,9 @@ def run_set(report_dir.mkdir(parents=True, exist_ok=True)table = write_table(results, report_dir / "table.md")skipped = [s for s in ordered if s not in {r["state"] for r in results}]+ # the set's own question, its flag to answer it: the same as its rows', which ran `gen` with gen-set's --provider+ asked = next((codex_unavailable_question(r["asked"]["cause"], r["asked"]["reason"]) for r in results+ if r.get("asked")), None)payload = {"kind": "sprite-gen-gen-set-report","run_dir": str(run_dir),@@ -240,17 +255,21 @@ def run_set("ok": sum(1 for r in results if r.get("ok")),"failed": [r["state"] for r in results if not r.get("ok")],"not_started": skipped,+ **({"asked": asked} if asked else {}),"items": results,}atomic_write_text(report_dir / "set.report.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n")print(table)+ if asked:+ raise ask_codex_unavailable(asked)return payloaddef add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--run-dir", required=True, type=Path, help="a prepared run (sprite-request.json, prompts/, references/layout-guides/)")parser.add_argument("--states", help="comma list; default = every non-mirrored state in the request")- parser.add_argument("--provider", choices=("codex", "grok"), help="honoured verbatim; default resolves like `gen` (env > codex, observable failover)")+ parser.add_argument("--provider", choices=gen_mod.PROVIDERS, help="honoured verbatim (openai bills per call); default "+ "resolves like `gen`: env > codex, and a codex that cannot run asks or runs what was chosen for that")parser.add_argument("--model")parser.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY, help=f"rows generated at once (default {DEFAULT_CONCURRENCY})")parser.add_argument("--force", action="store_true", help="regenerate rows that already exist")diff --git a/sprite_gen/gen/logo.py b/sprite_gen/gen/logo.pyindex 499b82b..d93a3ec 100644--- a/sprite_gen/gen/logo.py+++ b/sprite_gen/gen/logo.py@@ -26,7 +26,6 @@ from __future__ import annotationsimport argparseimport json-import osimport reimport shutilimport sys@@ -44,7 +43,7 @@ from sprite_gen.util.cli_kwargs import namespace_from_kwargsfrom . import chroma as chroma_modfrom . import codex_provider, openai_provider, xai-from .base import QUALITIES, RESOLUTIONS, PROVIDER_SWITCH_WORDS, print_json+from .base import QUALITIES, RESOLUTIONS, print_jsonREPORT_KIND = "sprite-gen-logo-report"COMPOSITIONS: dict[str, dict[str, str]] = {@@ -445,22 +444,7 @@ def _cut(files: dict[str, Path], report: dict[str, Any], work: Path, backend, radef _run(args: argparse.Namespace) -> int:- provider = args.provider- fallback: dict[str, str] | None = None- if provider is not None:- resolved_from = "explicit"- else:- provider, fallback = gen_pkg.resolve_default_provider()- if fallback:- resolved_from = f"fallback-from-{fallback['from']}"- print(f"sprite-gen logo: default provider '{fallback['from']}' unavailable ({fallback['reason']}) "- f"{PROVIDER_SWITCH_WORDS} '{fallback['to']}'. Set {gen_pkg.DEFAULT_PROVIDER_ENV} or pass --provider "- "to control this.", file=sys.stderr)- elif os.environ.get(gen_pkg.DEFAULT_PROVIDER_ENV, "").strip():- resolved_from = gen_pkg.DEFAULT_PROVIDER_ENV- else:- resolved_from = "hard-default"- report = make_logo(+ report, _, _ = gen_pkg.run_on_default("logo", args.provider, lambda provider, resolved_from, fallback: make_logo(provider, text=args.text or "", out_dir=Path(args.out_dir), subtitle=args.subtitle, style=args.style,scene=args.scene, composition=args.composition, language=args.language,mood=Path(args.mood) if args.mood else None, lettering=Path(args.lettering) if args.lettering else None,@@ -468,7 +452,7 @@ def _run(args: argparse.Namespace) -> int:aspect_ratio=args.aspect_ratio, quality=args.quality, resolution=args.resolution,keep_session=args.keep_session, report_path=args.report, provider_resolved_from=resolved_from,provider_fallback=fallback,- )+ ))print_json(report)return 0@@ -491,7 +475,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:"keeps the hue of longest. With --lettering, auto reads the key off its border")parser.add_argument("--provider", choices=gen_pkg.PROVIDERS, default=None,help="generation backend for both images and both text checks; resolved as `gen` resolves "- "it (openai only when named: it bills per call)")+ "it (openai only when chosen: it bills per call)")parser.add_argument("--model")parser.add_argument("--aspect-ratio", help="override the composition's ratio (grok and openai; codex ignores it)")parser.add_argument("--quality", choices=QUALITIES, default=None, help="as `gen --quality`, for both images")diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.pyindex 02c3f12..a45d324 100644--- a/sprite_gen/gen/openai_provider.py+++ b/sprite_gen/gen/openai_provider.py@@ -14,11 +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 backend is for servers and SaaS and is billed per call, so sprite-gen runs it+only when the user chose it (구독 우선 불변식, 수홍 2026-09-20, 2026-10-16): when+`--provider openai` names it, or as the user's own answer for a default codex that+cannot run (`gen.codex_unavailable_choice`) — never as a default, never as the guided+flow's image provider, never unasked — 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 or to another key: a missing credential, arejected key or a failed request is the observable outcome. A refusal OpenAI documents asdiff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex 8776762..f18884b 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -26,7 +26,8 @@ from typing import Any, Callablefrom PIL import Imagefrom sprite_gen.spec.runio import atomic_write_text-from sprite_gen.gen.base import run_logged+from sprite_gen.gen.base import (CodexUnavailableAsk, ask_codex_unavailable, child_asked, codex_unavailable_question,+ run_logged)from 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@@ -680,6 +681,8 @@ def walk_start_still(base: Path, direction: str, item_dir: Path, *, key: str, foif prior.get("prompt") == prompt and [str(Path(r).resolve()) for r in prior.get("refs") or []] == [str(base.resolve())]:return out, {"redrawn": True, "reused": True, "still": str(out), "key": kind}rc = runner(base, prompt, out, report, log=item_dir / "walk-start.log", provider=provider)+ if (question := child_asked(rc, item_dir / "walk-start.log")) is not None:+ raise CodexUnavailableAsk(question) # the set asks it once, when its items have ended (`run_set`)if rc != 0 or not out.is_file():raise SystemExit(f"the mid-step start still for the {direction} walk was not drawn; see {item_dir / 'walk-start.log'}")return out, {"redrawn": True, "reused": False, "still": str(out), "key": kind, "report": str(report)}@@ -867,6 +870,10 @@ def run_item(# cut as filmed for want of RIFE: the set report lists it under `warnings`result["loop"]["jump_repair"] = {k: lp["jump_repair"][k] for k in ("applied", "why", "score_max_before", "install")}result["ok"] = True+ except CodexUnavailableAsk as exc:+ result["ok"] = False+ result["asked"] = exc.question+ result["error"] = f"the mid-step start still was not drawn: codex cannot run here ({exc.question['reason']})"except SystemExit as exc:result["ok"] = Falseresult["error"] = str(exc)@@ -1155,9 +1162,15 @@ def run_set(warnings += [f"cycle-align:{st}: {line}" for st, a in aligned.items() for line in a.get("warnings", [])]warnings += [f"cycle-align:{st}: --align-foot {item}={foot} not applied ({a.get('why') or a.get('error') or 'the item failed'})"for st, a in aligned.items() for item, foot in a.get("feet_unused", {}).items()]- payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "facing": facing, "facing_fix": facing_fix, "directions": list(bases), **({"handed": [vars(h) for h in handed]} if handed else {}), **({"body_plan": [vars(b) for b in body_plan]} if body_plan else {}), **({"play": play} if play else {}), **({"motion": motion} if motion else {}), "body_height": body_height, "ok": sum(1 for r in results if r.get("ok")), "failed": failed, "warnings": warnings, "items": results, "cycle_align": aligned}+ # A start still `gen` asked about instead of drawing (codex cannot run, and the choice is to ask): the set ends+ # with that question, the way to answer it named as this verb's own flag, once every other item has ended.+ asked = next((codex_unavailable_question(r["asked"]["cause"], r["asked"]["reason"], flag="--still-provider")+ for r in results if r.get("asked")), None)+ payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "facing": facing, "facing_fix": facing_fix, "directions": list(bases), **({"handed": [vars(h) for h in handed]} if handed else {}), **({"body_plan": [vars(b) for b in body_plan]} if body_plan else {}), **({"play": play} if play else {}), **({"motion": motion} if motion else {}), "body_height": body_height, "ok": sum(1 for r in results if r.get("ok")), "failed": failed, "warnings": warnings, **({"asked": asked} if asked else {}), "items": results, "cycle_align": aligned}atomic_write_text(root / "set.report.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n")print(table)+ if asked:+ raise ask_codex_unavailable(asked)return payload@@ -1245,7 +1258,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--body-height", type=int, default=None, help="scale every state's loop so the standing height is this many px (video-loop --body-height): one value for the whole set keeps the character the same size across states")parser.add_argument("--decontam", choices=frames_mod.DECONTAM_MODES, default="off", help="passed to video-frames: palette re-explains key-tinted edges with the subject's own colours (default off)")parser.add_argument("--walk-start", choices=WALK_START_MODES, default="redraw", help="redraw (default): a front or back walk films from its base still redrawn mid-step (one image generation, `sprite-gen gen --ref base`, kept as walk-start.png) — from a standing still the clip model walks askew; as-given: film from the base still itself")- parser.add_argument("--still-provider", help="image provider for the mid-step redraw (default: sprite-gen gen's own default)")+ parser.add_argument("--still-provider", help="image provider for the mid-step redraw (default: sprite-gen gen's own default; "+ "a codex that cannot run there asks, and the set stops with the question)")parser.add_argument("--align-cycles", choices=ALIGN_MODES, default="auto", help="auto (default): after the loops are cut, every walk/run filmed in two or more directions is resampled to the set's median cycle length and turned to start on a foot strike (video-cycle-align; RIFE makes only the frames between source frames — where no RIFE is installed the alignment is skipped with a warning and recorded); off: each loop keeps its own length")parser.add_argument("--align-between", choices=align_mod.BETWEEN, default=align_mod.DEFAULT_BETWEEN, help="how the alignment fills a time between two source frames (video-cycle-align --between): auto (default) makes the frame with RIFE and takes the nearer source frame where it smeared or lost its outline, rife keeps every made frame, nearest takes the nearer source frame")parser.add_argument("--align-foot", action="append", default=[], metavar="ITEM=left|right",diff --git a/sprite_gen/workflow/catalog.py b/sprite_gen/workflow/catalog.pyindex 4970476..186e3fc 100644--- a/sprite_gen/workflow/catalog.py+++ b/sprite_gen/workflow/catalog.py@@ -1,6 +1,6 @@# SPDX-License-Identifier: Apache-2.0"""The two user journeys and their selectable fields, declared once."""-from sprite_gen.gen import PROVIDERS+from sprite_gen.gen import CODEX_UNAVAILABLE_CHOICES, CODEX_UNAVAILABLE_SETTING, PROVIDERSMOTION_METHODS = {"gpt-rows": {"label": "지피티 이미지 스프라이트", "provider": "codex", "doc": "docs/atlas-workflow.md",@@ -17,9 +17,9 @@ PROVIDER_LABELS = {"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`).+# that run on a subscription the user already pays for as the image provider.+# `openai` spends metered API credit per call, so it is never offered there; the+# one place it is a choice is the answer for a codex that cannot run (below).GUIDED_PROVIDERS = ("codex", "grok")_unlabelled = [provider for provider in PROVIDERS if provider not in PROVIDER_LABELS]if _unlabelled:@@ -36,6 +36,18 @@ FIELDS = {"curation": {"options": {"open": "열기", "skip": "열지 않기"},"question": "큐레이션뷰에서 결과를 확인하고 골라볼까요?"},}+# Settings every profile shares, asked once and saved beside the profiles (`preferences`, `general`). The one so+# far: what a call that names no provider does when codex cannot run here (not signed in, or its usage used up) —+# `gen.codex_unavailable_choice` reads it, docs/gen.md "When codex cannot run" owns the rule.+GENERAL_FIELDS = {+ CODEX_UNAVAILABLE_SETTING: {+ "options": {"ask": "멈추고 묻기 (기본)", "grok": "그록으로 만들기", "openai": "OpenAI API 로 만들기 (호출당 과금)"},+ "question": "지피티(codex)를 쓸 수 없을 때 — 로그인이 없거나 사용량을 다 썼을 때 — 어떻게 할까요?",+ },+}+if list(GENERAL_FIELDS[CODEX_UNAVAILABLE_SETTING]["options"]) != list(CODEX_UNAVAILABLE_CHOICES):+ raise RuntimeError("workflow catalog: the codex-unavailable options must be gen.CODEX_UNAVAILABLE_CHOICES")+FLOWS = {"sprite": {"label": "스프라이트 만들기", "fields": ("image_provider", "motion_method", "curation")},"image": {"label": "이미지 만들기", "fields": ("image_provider", "curation")},@@ -51,3 +63,12 @@ def validate_choices(kind: str, choices: dict) -> dict:if key not in FLOWS[kind]["fields"] or not isinstance(value, str) or value not in FIELDS[key]["options"]:raise ValueError(f"invalid {kind} choice: {key}")return dict(choices)+++def validate_general(values: dict) -> dict:+ if not isinstance(values, dict):+ raise ValueError("general settings must be an object")+ for key, value in values.items():+ if key not in GENERAL_FIELDS or not isinstance(value, str) or value not in GENERAL_FIELDS[key]["options"]:+ raise ValueError(f"invalid general setting: {key}")+ return dict(values)diff --git a/sprite_gen/workflow/guide.py b/sprite_gen/workflow/guide.pyindex 1948629..47eaebc 100644--- a/sprite_gen/workflow/guide.py+++ b/sprite_gen/workflow/guide.py@@ -6,8 +6,10 @@ import argparseimport jsonfrom pathlib import Path+from sprite_gen.gen import CODEX_UNAVAILABLE_SETTING, codex_unavailable_choice+from .access import probe_access-from .catalog import FIELDS, FLOWS, MOTION_METHODS, validate_choices+from .catalog import FIELDS, FLOWS, GENERAL_FIELDS, MOTION_METHODS, validate_choicesfrom .preferences import read_settings@@ -28,10 +30,16 @@ def guide(kind: str, *, stage: str = "start", base_image: Path | None = None, reif base_image is not None:active_fields.remove("image_provider")questions, blocked, access = [], [], []+ # Asked once, before the first generation, and saved: what a call that names no provider does when codex cannot+ # run. The environment answers it as well; it is never asked over a saved or given answer.+ codex_choice, codex_choice_source = codex_unavailable_choice()if stage == "start":for field in active_fields:if field not in selected:questions.append({"field": field, **FIELDS[field]})+ if codex_choice_source == "default":+ questions.append({"field": CODEX_UNAVAILABLE_SETTING, **GENERAL_FIELDS[CODEX_UNAVAILABLE_SETTING],+ "save": "general"})# Report both candidates while choosing, then only the services actually# used. One probe per provider: its images and videos share one credential.required = set()@@ -77,6 +85,7 @@ def guide(kind: str, *, stage: str = "start", base_image: Path | None = None, rereturn {"kind": kind, "stage": stage, "status": "blocked" if blocked else "needs-input" if questions else "ready","notice": " / ".join(labels), "selected": selected, "sources": sources,"settings_revision": snapshot["revision"], "settings_path": snapshot["path"],+ "codex_unavailable": {"choice": codex_choice, "source": codex_choice_source},"access": access, "blocked": blocked, "questions": questions, "pipeline": pipeline,"curation": selected.get("curation", "ask") if stage == "finish" else "after-result","save_candidate": selected if stage == "finish" and "curation" in selected else None}diff --git a/sprite_gen/workflow/preferences.py b/sprite_gen/workflow/preferences.pyindex e5767d1..ee8929a 100644--- a/sprite_gen/workflow/preferences.py+++ b/sprite_gen/workflow/preferences.py@@ -1,5 +1,9 @@# SPDX-License-Identifier: Apache-2.0-"""One preferences file; read-only queries, atomic compare-and-swap writes."""+"""One preferences file; read-only queries, atomic compare-and-swap writes.++Version 2 holds the per-journey `profiles` and the `general` settings every profile shares+(`catalog.GENERAL_FIELDS`); a version 1 file (profiles only) reads with no general settings and is+written as version 2 by the next save."""from __future__ import annotationsimport argparse@@ -9,7 +13,9 @@ import osfrom pathlib import Pathfrom sprite_gen.spec.runio import atomic_write_text, publish_guard-from .catalog import FIELDS, FLOWS, validate_choices+from .catalog import FIELDS, FLOWS, GENERAL_FIELDS, validate_choices, validate_general++VERSION = 2def settings_path() -> Path:@@ -25,26 +31,34 @@ def read_settings() -> dict:try:raw = path.read_bytes()except FileNotFoundError:- return {"path": str(path), "revision": "missing", "profiles": {}}+ return {"path": str(path), "revision": "missing", "profiles": {}, "general": {}}try:data = json.loads(raw)- if not isinstance(data, dict) or set(data) != {"version", "profiles"} or type(data["version"]) is not int or data["version"] != 1:- raise ValueError("expected preferences version 1")+ shapes = {1: {"version", "profiles"}, VERSION: {"version", "profiles", "general"}}+ if (not isinstance(data, dict) or type(data.get("version")) is not int+ or shapes.get(data["version"]) != set(data)):+ raise ValueError(f"expected preferences version 1 or {VERSION}")if not isinstance(data["profiles"], dict):raise ValueError("profiles must be an object")for kind, choices in data["profiles"].items():validate_choices(kind, choices)+ general = validate_general(data.get("general", {}))except (ValueError, TypeError) as exc:raise ValueError(f"invalid preferences at {path}: {exc}; repair or explicitly remove the file") from exc- return {"path": str(path), "revision": hashlib.sha256(raw).hexdigest(), "profiles": data["profiles"]}+ return {"path": str(path), "revision": hashlib.sha256(raw).hexdigest(), "profiles": data["profiles"],+ "general": general}-def save_settings(kind: str, choices: dict, *, expected_revision: str, clear: bool = False) -> dict:- """Only explicit user-approved calls write. First matching revision wins a race."""- choices = validate_choices(kind, choices)+def save_settings(kind: str | None, choices: dict, *, expected_revision: str, clear: bool = False,+ general: dict | None = None) -> dict:+ """Only explicit user-approved calls write. First matching revision wins a race. `kind` and `choices` save or+ `clear` one profile; `general` saves settings every profile shares (no `kind` needed for those alone)."""+ general = validate_general(general or {})+ if kind is not None or choices or clear:+ choices = validate_choices(kind, choices)if not expected_revision:raise ValueError("expected_revision is required; read current settings first")- if not clear and not choices:+ if not clear and not choices and not general:raise ValueError("provide at least one default to save")path = settings_path()path.parent.mkdir(parents=True, exist_ok=True)@@ -57,9 +71,10 @@ def save_settings(kind: str, choices: dict, *, expected_revision: str, clear: boprofiles = before["profiles"]if clear:profiles.pop(kind, None)- else:+ elif choices:profiles[kind] = {**profiles.get(kind, {}), **choices}- payload = json.dumps({"version": 1, "profiles": profiles}, ensure_ascii=False, sort_keys=True, indent=2) + "\n"+ payload = json.dumps({"version": VERSION, "profiles": profiles, "general": {**before["general"], **general}},+ ensure_ascii=False, sort_keys=True, indent=2) + "\n"if not path.exists() or path.read_text(encoding="utf-8") != payload:atomic_write_text(path, payload)return read_settings()@@ -71,20 +86,25 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--expected-revision")for key, field in FIELDS.items():parser.add_argument("--" + key.replace("_", "-"), choices=field["options"])+ for key, field in GENERAL_FIELDS.items():+ parser.add_argument("--" + key.replace("_", "-"), choices=field["options"], help="shared by every profile; "+ "saved without --kind")def run(**kwargs) -> int:args = argparse.Namespace(**kwargs)choices = {key: getattr(args, key, None) for key in FIELDS if getattr(args, key, None) is not None}+ general = {key: getattr(args, key, None) for key in GENERAL_FIELDS if getattr(args, key, None) is not None}try:if args.action == "show":- if choices or args.kind or args.expected_revision:+ if choices or general or args.kind or args.expected_revision:raise ValueError("show accepts no mutation arguments")result = read_settings()else:- if args.action == "clear" and choices:+ if args.action == "clear" and (choices or general):raise ValueError("clear does not accept choices")- result = save_settings(args.kind, choices, expected_revision=args.expected_revision, clear=args.action == "clear")+ result = save_settings(args.kind, choices, expected_revision=args.expected_revision,+ clear=args.action == "clear", general=general)except (ValueError, OSError) as exc:raise SystemExit(f"defaults: {exc}") from excprint(json.dumps(result, ensure_ascii=False, indent=2))diff --git a/tests/gen/test_codex_login.py b/tests/gen/test_codex_login.pyindex 70398dd..a5eed43 100644--- a/tests/gen/test_codex_login.py+++ b/tests/gen/test_codex_login.py@@ -15,7 +15,7 @@ from PIL import Imagefrom sprite_gen import genfrom sprite_gen.gen import codex_provider-from sprite_gen.gen.base import GenRequest+from sprite_gen.gen.base import CodexUnavailableAsk, GenRequestfrom sprite_gen.workflow.access import probe_access@@ -49,8 +49,14 @@ def test_no_cli_and_a_failed_probe_are_not_usable_with_the_reason(monkeypatch):def test_the_default_resolution_asks_the_same_question(monkeypatch):monkeypatch.delenv(gen.DEFAULT_PROVIDER_ENV, raising=False)monkeypatch.setattr(codex_provider, "codex_login", lambda: codex_provider.CodexLogin(None, "codex CLI not found on PATH"))- assert gen.resolve_default_provider() == ("grok", {"from": "codex", "to": "grok", "default_source": "hard-default",- "reason": "codex CLI not found on PATH"})+ with pytest.raises(CodexUnavailableAsk) as asked: # nothing chosen for a codex that cannot run: the question+ gen.resolve_default_provider()+ assert asked.value.question["cause"] == "login" and asked.value.question["reason"] == "codex CLI not found on PATH"+ monkeypatch.setenv(gen.CODEX_UNAVAILABLE_ENV, "grok")+ assert gen.resolve_default_provider() == ("grok", {"from": "codex", "to": "grok", "cause": "login",+ "reason": "codex CLI not found on PATH",+ "default_source": "hard-default",+ "chosen_by": gen.CODEX_UNAVAILABLE_ENV})monkeypatch.setattr(codex_provider, "codex_login", lambda: codex_provider.CodexLogin("codex-api-key"))assert gen.resolve_default_provider() == ("codex", None)diff --git a/tests/gen/test_codex_unavailable.py b/tests/gen/test_codex_unavailable.pyindex 5db3ac0..0490262 100644--- a/tests/gen/test_codex_unavailable.py+++ b/tests/gen/test_codex_unavailable.py@@ -54,10 +54,12 @@ def _cli(*args: str, env: dict[str, str] | None = None) -> subprocess.CompletedPdef _without_codex(tmp_path: Path) -> dict[str, str]:- """The environment with a PATH that holds no `codex`: its login cannot be asked."""- empty = tmp_path / "no-codex-bin"- empty.mkdir(exist_ok=True)- return {**os.environ, "PATH": str(empty)}+ """The environment with a PATH that holds no `codex` (its login cannot be asked), and no Grok login or API key+ anywhere: a call that went on to another provider instead of asking would fail here, never reach one."""+ for name in ("no-codex-bin", "no-grok-home"):+ (tmp_path / name).mkdir(exist_ok=True)+ env = {key: value for key, value in os.environ.items() if key not in ("XAI_API_KEY", "OPENAI_API_KEY")}+ return {**env, "PATH": str(tmp_path / "no-codex-bin"), "GROK_HOME": str(tmp_path / "no-grok-home")}def _choose(choice: str) -> dict:@@ -154,7 +156,8 @@ def test_no_codex_login_and_nothing_chosen_ends_with_the_question_and_draws_nothassert not out.exists() and not report.exists()[email protected]("said", USAGE_LIMIT_SAID)[email protected]("said", USAGE_LIMIT_SAID, ids=["0.160.1", "0.153.4", "workspace-credits", "spend-cap",+ "quota-exceeded", "usage-not-included"])def test_codex_usage_used_up_and_nothing_chosen_asks_the_same_question(tmp_path, codex, made, said, capsys):codex["said"] = saidwith pytest.raises(base.CodexUnavailableAsk) as asked:@@ -249,7 +252,7 @@ def test_the_environment_answers_before_the_saved_choice(monkeypatch, capsys):def test_a_codex_that_can_run_reads_no_choice(tmp_path, monkeypatch, made):path = preferences.settings_path()- path.parent.mkdir(parents=True)+ path.parent.mkdir(parents=True, exist_ok=True)path.write_text("not json", encoding="utf-8") # a broken settings file is read only when the choice is neededmonkeypatch.setattr(gen, "_codex_available", lambda: (True, ""))assert gen.resolve_default_provider() == ("codex", None)@@ -258,6 +261,16 @@ def test_a_codex_that_can_run_reads_no_choice(tmp_path, monkeypatch, made):gen.resolve_default_provider()+def test_logo_resolves_the_same_way(tmp_path, monkeypatch, made):+ from sprite_gen.gen import logo++ _codex_down(monkeypatch)+ out_dir = tmp_path / "logo"+ with pytest.raises(base.CodexUnavailableAsk):+ logo.run(text="STARFALL", style="painted fantasy", out_dir=out_dir)+ assert made == [] and not out_dir.exists()++# --- a named provider runs as named ---------------------------------------------------------------------------@@ -312,7 +325,11 @@ def test_gen_set_takes_the_providers_gen_takes():def test_video_set_whose_mid_step_redraw_asked_stops_with_the_same_question(tmp_path, monkeypatch):- monkeypatch.setenv("PATH", _without_codex(tmp_path)["PATH"])+ hermetic = _without_codex(tmp_path)+ for name in ("PATH", "GROK_HOME"):+ monkeypatch.setenv(name, hermetic[name])+ for name in ("XAI_API_KEY", "OPENAI_API_KEY"):+ monkeypatch.delenv(name, raising=False)still = Image.new("RGB", (96, 128), (0, 255, 0))for y in range(20, 110):for x in range(36, 60):@@ -374,7 +391,7 @@ def test_the_choice_is_kept_beside_the_profiles_in_the_one_settings_file():def test_a_version_1_settings_file_still_reads_with_nothing_chosen():path = preferences.settings_path()- path.parent.mkdir(parents=True)+ path.parent.mkdir(parents=True, exist_ok=True)path.write_text('{"version":1,"profiles":{"image":{"curation":"skip"}}}', encoding="utf-8")settings = preferences.read_settings()assert settings["profiles"] == {"image": {"curation": "skip"}} and settings["general"] == {}