Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(pixel-draw): run on the Claude subscription first, the API key only without one
Soohong Kim39c6096b5f23
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 449b243..1a626a3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased+- **Behavior change: `pixel-draw` runs on your Claude subscription first, and on `ANTHROPIC_API_KEY` only without one** — the order `codex` and `grok` keep. When `claude auth status` says Claude Code is signed in with a subscription (`claude.ai` or `oauth_token`), every call — the drawings, the row repairs, the pick — goes through the unmodified `claude` binary in print mode, from an empty directory, with no tool, no session written and no CLAUDE.md, hook, skill, plugin or MCP server loaded, and costs nothing per call: `report.json` says `auth_source: claude-login`, each call's `mode` is `subscription` and its `cost_usd` `0`, its usage kept. The child never sees `ANTHROPIC_API_KEY`, which print mode would use instead of the login. Without a subscription login the run uses the key as before, billed per call and said on stderr; with neither it is refused naming both, before the run folder is made. A login that refuses a call, has expired or has reached its usage limit fails the call; the run never switches to the key on its own. `--batch` is the API's Message Batches and runs on the key even when signed in. An answer the binary cuts at the output cap is read as `stop_reason: max_tokens`, so the one redraw one effort lower happens on either route. One call may take up to `SPRITE_GEN_CLAUDE_CALL_TIMEOUT_SECONDS` (1800). A `--resume` that reads every call back no longer prints the billing line ([pixel-draw](docs/pixel-draw.md#which-credential-a-call-runs-on)).+- **Tests** — `tests/gen/test_claude_login.py` (the login before the key, the key only without a login, neither refused naming both, a batch on the key without asking the login, an unreadable status refused rather than read as no login, the child's environment without a key or the calling session, a message mapped onto the binary's flags and stdin with its image and schema, the stream-json answer, a cut answer read as max_tokens, a refused or limited login an error and not a switch to the key, no result, a timeout and a missing binary), the subscription, batch and read-back cases in `tests/gen/test_pixel_draw.py`, and `gen.base.env_api_key` in `tests/gen/test_gen.py`.- **New: `background-tile --axis xy` makes one tile seamless in both directions and measures both joins.** It quilts along x, then along y with a cyclic seam: the second seam's two ends, which meet across the x wrap, may differ by one step at most, so the second quilt cannot break the first one's join. The report measures the finished tile on both axes (`axes.x`, `axes.y`, each with its join, quilt seam, `status` and reasons); the top-level `status` is `needs-review` when either axis is, and each reason names its axis. Two separate one-axis runs had no such rule, and the second run's report measured only its own axis. `inspect_tile_xy(image)` measures both joins of any tile ([asset-tools](docs/asset-tools.md#both-axes-a-ground-tile)).- **New: alpha haze cleanup for transparent sheets (`frames.alpha_floor.clear_haze`).** Pixels at or above a floor, and faint pixels within a few pixels of them (an object's anti-aliased edge), are kept byte for byte; every other faint pixel becomes fully transparent. The report measures the haze share before and after and counts the solid and edge pixels that changed (`0`). Used by `ui-kit` (on by default) and `slice-sheet --alpha-floor N` (off by default; writes `<prefix>alpha-cleanup.json`). `slice-sheet --chroma-key none` cuts a sheet that is already transparent on its own alpha ([sheet-slicing](docs/sheet-slicing.md#transparent-sheets)).- **New verb: `ui-kit` splits a game UI kit sheet into nine-slice elements.** `gen --layout-guide ui-kit` attaches a fixed square layout (panel, button, pressed button, card frame, HP and XP bar frames, timer badge) and asks for each element in its box. `ui-kit --sheet uikit.png --out-dir ui/` clears the haze, assigns parts to boxes by centroid, and writes each element's PNG and `ui-kit.json` (or `--report PATH`, which must end in `.json`; each element's `file` is its PNG's path from the report's directory, so a report written outside `--out-dir` still finds its elements): its rectangle, its stretch (`xy`, `x` for the bars, `none` for the badge), nine-slice insets measured so that every corner ornament and end cap lies in a fixed slice, and the content padding (a bar frame's track, a panel's text area). An ornament in the middle of an edge, an empty box or a stray part is reported or refused ([ui-kit](docs/ui-kit.md)). `--layout-guide` alone is still the one-slot figure guide.diff --git a/SKILL.md b/SKILL.mdindex 2e998b6..268031e 100644--- a/SKILL.md+++ b/SKILL.md@@ -109,7 +109,7 @@ hold the arms still, and check the loop with `handed-check --state walk`.| Restore post-processing damage in the current cut from its exact source times, preserving normal cells and playback | `video-source-manifest` → `video-loop-repair` → `video-loop-compare` | [source restoration](docs/loop-comparison.md#restoring-the-active-cut-from-source) || Video sprites from a clip your agent makes with a connected video MCP (ZCRE, 지크) | `video-canvas`, `video-prompt --no-last-frame`, the agent's own MCP tools (quote, user approval, generate, save the mp4), then `video-frames` and `video-loop` (a walk or run with `--anchor motion-auto`, which holds its size), and for a walk or run cut in two or more directions `video-cycle-align --view …` over their loop directories (a set it stops on a loop that may hold two cycles: look at that loop, count its strides, and pass `--cycles <loop>=<k>`; a loop the report lists under `unnamed_feet` — its view could not tell the feet apart, or only by too small a margin (`low-margin`): look at its first candidate frame, say which own foot lands there, and align again with `--foot <loop>=left|right`). `video-set` is not run on this route, so the set stage it runs by default (`--align-cycles auto`) is yours to run. sprite-gen never calls the MCP. Walk, run and jump only: ZCRE's `grok-imagine-video-1.5` has no end frame, so idle, attack and diagonal walks are refused unless `--unpinned` | [video-pipeline](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre) || Ordinary image or edit | `gen --provider codex` or `gen --provider grok` (subscription routes) | [gen](docs/gen.md) |-| Pixel art the model draws directly as a grid, 8–48 px (best at 32 or less): an icon, a prop, a monster, a character still, four directions, a walk draft, a tile — on `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) |+| Pixel art the model draws directly as a grid, 8–48 px (best at 32 or less): an icon, a prop, a monster, a character still, four directions, a walk draft, a tile — on your Claude subscription (`claude` signed in), or without one on `ANTHROPIC_API_KEY`, **billed per call**; `grid.txt` is the truth, `--grid` re-renders an edited one, `--resume` collects a batch instead of buying it twice | `pixel-draw` | [pixel-draw](docs/pixel-draw.md) || Image generation with no login available (server, container, SaaS) | `gen --provider openai` — server/SaaS route on `OPENAI_API_KEY`, **billed per call**, never a default or a fallback | [gen](docs/gen.md#subscription-first--openai-is-named-or-it-does-not-run) || Base and direction anchors | `anchor` | [directional-anchor-workflow](docs/directional-anchor-workflow.md) || Curation view or existing image candidates | `curation`, `unpack-atlas --pngs-dir` | [curation](docs/curation.md) |diff --git a/docs/pixel-draw.md b/docs/pixel-draw.mdindex 868d0b5..1cc708f 100644--- a/docs/pixel-draw.md+++ b/docs/pixel-draw.md@@ -4,7 +4,7 @@> varies from run to run: expect to compare candidates, re-draw, or touch up `grid.txt` by hand. The numbers below come from a> small set of measured runs, not from a benchmark.-> Owns: `sprite-gen pixel-draw`: the inputs, the safe area of a sprite or icon, the run folder and `report.json`, gates G1–G8 and what they take from sprite-gen, the row repair, the one redraw, the pick between candidates, Message Batches and `--resume`, re-rendering an edited `grid.txt` · Index: [docs/README.md](README.md)+> Owns: `sprite-gen pixel-draw`: the inputs, the safe area of a sprite or icon, the run folder and `report.json`, which credential a call runs on, gates G1–G8 and what they take from sprite-gen, the row repair, the one redraw, the pick between candidates, Message Batches and `--resume`, re-rendering an edited `grid.txt` · Index: [docs/README.md](README.md)The model does not paint an image that is then shrunk to a grid. It writes the grid itself: apalette of keys and, per frame, one line of keys per pixel row. Code checks every answer, asks for@@ -30,13 +30,18 @@ subjects made with GPT images shrunk by sprite-gen's own functions):- dense small-pattern tiles (cobblestones) sometimes spent every token thinking and wrote nothing,at effort xhigh only.-It runs on `ANTHROPIC_API_KEY` and **every call is billed per call** against that key; the run-says so on stderr before the first request leaves, and `report.json` adds up what it cost.+It runs on your **Claude subscription first**, like `codex` and `grok` do: when the `claude` binary+(Claude Code) is signed in with a subscription, every call goes through it and costs nothing per+call — it counts against the plan's usage limits. Only without a subscription login does it run on+`ANTHROPIC_API_KEY`, where **every call is billed per call**; the run says so on stderr before the+first request leaves, and `report.json` adds up what it cost. See [Which credential a call runs+on](#which-credential-a-call-runs-on).## Quick start```bash-export ANTHROPIC_API_KEY=<your Claude Console key>+claude # once: sign in with /login (a Pro, Max, Team or Enterprise plan); or+export ANTHROPIC_API_KEY=<your Claude Console key> # per-call billing, used only without a login# one sprite, 32x32, two candidates, the vision picksprite-gen pixel-draw --out-dir runs/slime \@@ -76,7 +81,7 @@ candidate's files are at the top of the run folder.| `--candidates K` | 1–6 (2) | Answers drawn for the request, each on its own; one is picked (G7). || `--effort` | `medium`, `high`, `xhigh` (`high`) | Thinking effort of each drawing. || `--format` | `chargrid`, `json` (`chargrid`) | How the model writes the grid. `grid.txt` is a character grid either way. |-| `--batch` | flag | Draw through Message Batches at half price and wait for the batch (below). |+| `--batch` | flag | Draw through Message Batches at half price and wait for the batch (below). Batches exist only on the API, so the whole run uses `ANTHROPIC_API_KEY` even when a subscription is signed in. || `--batch-wait S` | seconds (3600) | How long to wait for one batch before the run ends unfinished; `--resume` collects it later. `0` submits and returns. || `--max-tokens N` | 1024–128000 (32000 for one frame, 64000 for more) | Output cap of each drawing, thinking included. || `--pick` | `vision`, `human` (`vision`) | Who picks among candidates that passed. |@@ -189,6 +194,7 @@ answers a question the verb asks, it asks that function; a part that is its own| `anim.gif` | `util.gif_utils.save_clean_gif` | — || The pick sheet's checker | `qa.preview.checker`, the contact sheets' | — || The billing line, the printed report | `gen.base.announce_api_billing`, `gen.base.print_json` | [gen.md](gen.md) |+| The subscription login first, the key only without one | `gen.claude_login.resolve_credential`, the order `gen.xai.resolve_credential` keeps for Grok; the key read by `gen.base.env_api_key`; the child's environment from `gen.base.provider_subprocess_env` | [Which credential a call runs on](#which-credential-a-call-runs-on) || The refusal line | `gen.refusal` (`CONTENT_POLICY`) | [gen.md](gen.md#direct-openai-calls-and-authentication) || What ends a call unanswered, and its words; a refusal's body | `gen.xai` (`NO_ANSWER`, `no_answer_reason`, `error_body`) | — |@@ -234,11 +240,13 @@ zlib build. The previews, the tiling and the GIF are views for the eye.| `chosen`, `files`, `warnings`, `info` | the picked candidate, its top-level files, its warnings (worth a look, maybe a redraw) and its info lines (nothing to do) || `pick` | `by` (`vision` / `only` / `human`), `best`, and for the vision pick its `labels`, `sheet` and `verdict` || `candidates[]` | per candidate: `status`, `reason`, `effort` of the answer kept, `generations` (call ids), `redraws` (after which call, why, at which effort), `repairs` (rows asked, answered, still broken), `G1` (issues and what was recovered), `gates` (G2–G6 and G8 with their measures), `warnings`, `info`, `files` |-| `calls[]` | per call: `id` (`c1-gen1`, `c1-gen1-fix1`, `pick`), `purpose`, `mode` (`realtime` / `batch`), `model`, `effort`, `max_tokens`, `request_id`, `message_id`, `batch_id`, `stop_reason`, `stop_details`, `usage` (as the API reported it), `thinking_tokens`, `cost_usd`, `seconds`, and for a failed call `error` and `billed` |+| `auth_source` | what the run's calls ran on: `claude-login` (the subscription) or `ANTHROPIC_API_KEY` |+| `calls[]` | per call: `id` (`c1-gen1`, `c1-gen1-fix1`, `pick`), `purpose`, `mode` (`subscription` / `realtime` / `batch`), `auth_source`, `model`, `effort`, `max_tokens`, `request_id`, `message_id`, `batch_id`, `stop_reason`, `stop_details`, `usage` (as the API reported it), `thinking_tokens`, `cost_usd`, `seconds`, and for a failed call `error` and `billed` || `batches[]` | per batch: `id`, `custom_ids`, `submitted_at`, `collected`, `ended_at`, `waited_seconds` || `usage`, `cost_usd`, `seconds` | totals over the calls, and the run's wall time |-`cost_usd` is each call's usage at the published price (below), Message Batches at half. It is+`cost_usd` is nothing for a call on the subscription (its `usage` is kept: it counts against the+plan), and on the key each call's usage at the published price (below), Message Batches at half. It iswhat the calls cost by the API's own usage counts, not a console bill. Which price each token isbilled at is one function, `anthropic_api.billed_tokens`: input, output, cache reads, and cachewrites by their lifetime (`usage.cache_creation`'s five-minute and one-hour counts; a reply that@@ -293,6 +301,40 @@ the same files and a report with no calls.Pass the `--kind`, `--palette` and `--walk-cycle` the grid was drawn under; the run's`request.json` has them.+## Which credential a call runs on++`claude_login.resolve_credential` answers it once per run, in the order `codex` and `grok` keep:++1. **The subscription login.** `claude auth status --json` is asked in the environment the call+ would run in. Signed in with `claude.ai` (`/login`) or `oauth_token` (`claude setup-token`) is a+ subscription: every call — the drawings, the row repairs, the pick — runs through the unmodified+ `claude` binary in print mode (`claude -p`) from an empty directory, with no tool, no session+ written, and no CLAUDE.md, hook, skill, plugin or MCP server loaded (`--safe-mode`). Model, effort,+ system prompt, output cap (`CLAUDE_CODE_MAX_OUTPUT_TOKENS`), the pick's schema and its sheet go as+ the binary's flags and one stream-json message; the answer comes back as the API's would.+2. **`ANTHROPIC_API_KEY`**, only when no subscription login is here (no `claude` installed, nobody+ signed in, or Claude Code signed in with a key, a key helper or a cloud account). Billed per call,+ said on stderr before the first request leaves.+3. Neither is a refusal naming both, before the run folder is made.++The child never sees `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` — in print mode the binary uses a+key whenever one is present — nor the calling Claude Code session's own variables. A login that is+here but refuses a call, has expired or has reached its usage limit fails that call as it came; the+run never switches to the key on its own. `--batch` is the API's Message Batches, so it names the key+and the login is not asked. One call through the binary may take up to+`SPRITE_GEN_CLAUDE_CALL_TIMEOUT_SECONDS` (1800) before it is stopped and reported.++The binary answers an answer cut at the output cap by asking for a continuation a few times and then+failing with "exceeded the N output token maximum"; that is read as the API's `stop_reason:+max_tokens`, so the one redraw one effort lower happens on either route.++The subscription route is for the person running sprite-gen on their own machine, signed in to their+own plan. Anthropic permits an end user signing in to the unmodified Claude Code binary with their+own subscription, and does not permit routing other people's requests through one+([legal and compliance](https://code.claude.com/docs/en/legal-and-compliance.md)): a service that+draws for other people runs on `ANTHROPIC_API_KEY` — no login exists in its container, so that is+the route it gets.+## Model, effort and price| | Value | Source |diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex cbb6c40..664c669 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -335,7 +335,7 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab),# Same declaration-once rule: the module owns its argument surface (docs/pixel-draw.md)."pixel-draw": (- "Experimental: Claude Opus draws 8..48 px pixel art as a pixel grid: gates, row repair, a pick of candidates; grid.txt is the truth, PNGs byte-reproducible (ANTHROPIC_API_KEY, billed per call).",+ "Experimental: Claude Opus draws 8..48 px pixel art as a pixel grid: gates, row repair, a pick of candidates; grid.txt is the truth, PNGs byte-reproducible (your Claude subscription first; without a login ANTHROPIC_API_KEY, billed per call).",pixel_draw.add_arguments,pixel_draw.run,),diff --git a/sprite_gen/gen/anthropic_api.py b/sprite_gen/gen/anthropic_api.pyindex e2c2c04..b7b482f 100644--- a/sprite_gen/gen/anthropic_api.py+++ b/sprite_gen/gen/anthropic_api.py@@ -1,6 +1,7 @@# SPDX-License-Identifier: Apache-2.0-"""Anthropic Messages API transport for `pixel-draw`: the credential, one streamed message,-Message Batches, and what a call cost.+"""Anthropic Messages API transport for `pixel-draw`: one streamed message, Message Batches, and what a+call cost. Which credential a call runs on — the person's Claude subscription first, this API's key+only without one — is `claude_login.resolve_credential`.Raw HTTP over urllib, like `openai_provider` and `xai`: the runtime dependency surface is Pillowand NumPy (SECURITY.md), and one more SDK with its own HTTP stack would be a second transport for@@ -66,20 +67,6 @@ READ_TIMEOUT_SECONDS = float(os.environ.get("SPRITE_GEN_CLAUDE_READ_TIMEOUT_SECOSleep = Callable[[float], None]-def resolve_credential(env: dict[str, str] | None = None) -> str:- """Return the Anthropic API key, or fail loud naming the variable that is missing."""- env = os.environ if env is None else env- key = (env.get(AUTH_ENV) or "").strip()- if key:- return key- if AUTH_ENV in env:- raise SystemExit(f"pixel-draw: {AUTH_ENV} is set but empty; give it a value")- raise SystemExit(- f"pixel-draw: no Anthropic credential — {AUTH_ENV} is not set.\n"- f" export {AUTH_ENV}=<your Claude Console API key> (platform.claude.com/settings/keys)."- )--@dataclassclass Reply:"""One answered message: its text, its thinking summary and what it used."""diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.pyindex 3583aac..031d9b4 100644--- a/sprite_gen/gen/base.py+++ b/sprite_gen/gen/base.py@@ -77,21 +77,35 @@ class GenTimeoutError(SystemExit):"""생성 서브프로세스가 GEN_TIMEOUT_SECONDS 안에 끝나지 않아 킬됨 (관측 가능)."""-def provider_subprocess_env() -> dict[str, str]:+def provider_subprocess_env(env: Mapping[str, str] | None = None) -> dict[str, str]:"""Environment for a headless generation subprocess.- The parent environment minus known orchestrator session env families, so a- spawned engine (`codex exec`) is a clean standalone process — it- neither impersonates the spawning agent nor gets strangled by the- orchestrator's hooks. SSoT for every provider's `subprocess.run` env —- providers must not spawn with the inherited env directly.+ The parent environment (`env`, default `os.environ`) minus known orchestrator+ session env families, so a spawned engine (`codex exec`, `claude -p`) is a clean+ standalone process — it neither impersonates the spawning agent nor gets+ strangled by the orchestrator's hooks. SSoT for every provider's+ `subprocess.run` env — providers must not spawn with the inherited env directly."""- env = {+ source = os.environ if env is None else env+ return {key: value- for key, value in os.environ.items()+ for key, value in source.items()if not key.endswith(_ORCHESTRATOR_SESSION_ENV_SUFFIXES)}- return env+++def env_api_key(name: str, env: Mapping[str, str] | None = None, *, who: str) -> str | None:+ """The API key in the environment variable `name` (`env`, default `os.environ`),+ None when it is not set. Set but empty is refused, naming it: an empty key is a+ mistake to show, not an absence to route around. The one reading of a provider+ key; what a missing key means (another route, or a refusal) is the caller's."""+ source = os.environ if env is None else env+ key = (source.get(name) or "").strip()+ if key:+ return key+ if name in source:+ raise SystemExit(f"{who}: {name} is set but empty; give it a value or unset it")+ return Nonedef provider_binary(name: str) -> str:diff --git a/sprite_gen/gen/claude_login.py b/sprite_gen/gen/claude_login.pynew file mode 100644index 0000000..99bf9fc--- /dev/null+++ b/sprite_gen/gen/claude_login.py@@ -0,0 +1,210 @@+# SPDX-License-Identifier: Apache-2.0+"""Claude calls on the person's own subscription first: is a login here, which credential a call runs+on, and one message answered through the unmodified `claude` binary (Claude Code) in print mode.++The order is `codex`'s and `grok`'s: the subscription the person already pays for, and an API key only+when no subscription login is here. `resolve_credential` answers it. A login that is here but refuses,+expires or reaches its usage limit fails the call and never switches to the key (`xai.resolve_credential`+keeps the same rule for Grok). Message Batches exist only on the API, so `--batch` names the key.+This tool never reads, stores or forwards the login: the binary signs itself in.++What the binary does, as code.claude.com/docs documents it (read 2026-10-15) and as measured with+claude 2.1.300 the same day:++- `claude auth status --json` exits 0 signed in and 1 not; `authMethod` is one of none, claude.ai,+ oauth_token, api_key, api_key_helper, third_party. A subscription is `claude.ai` (`/login`) or+ `oauth_token` (`claude setup-token`); the others bill an API key or a cloud account.+- In print mode an `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in the environment is always used+ when present, so the child runs without them. `--bare` never reads the login and is not used.+- `-p --input-format stream-json --output-format stream-json --verbose` takes one user message of+ content blocks (text, a base64 image) on stdin and ends with a `result` event: `result` (the text),+ `structured_output` (with `--json-schema`), `usage` (the Messages API's), `stop_reason`, `is_error`,+ `subtype`, `api_error_status`. An answer cut at the output cap is not returned as a cut answer: the+ binary asks for a continuation a few times and then ends `is_error` with "exceeded the N output token+ maximum" (`OUTPUT_CAP_ERROR`); that is the API's `stop_reason: max_tokens`.+- `--system-prompt` replaces Claude Code's own prompt (an empty one is accepted), `--tools ""` and+ `--strict-mcp-config` leave no tool, `--safe-mode` loads no CLAUDE.md, hook, skill, plugin or MCP+ server while the login still works, `--no-session-persistence` writes no session, `--effort` sets the+ effort and `CLAUDE_CODE_MAX_OUTPUT_TOKENS` the output cap.++Anthropic permits an end user signing in to the unmodified Claude Code binary with their own+subscription; it does not permit routing other people's requests through one+(code.claude.com/docs/en/legal-and-compliance.md). This route is for the person running the tool on+their own machine. A service that answers other people runs on `ANTHROPIC_API_KEY`: no login exists+in its container, so that is the route it gets.+"""+from __future__ import annotations++import json+import os+import re+import subprocess+import tempfile+import time+from dataclasses import dataclass, field+from typing import Any, Callable, Mapping++from . import anthropic_api as api+from .base import env_api_key, provider_binary, provider_subprocess_env++BINARY = "claude"+AUTH_SOURCE_LOGIN = "claude-login"+AUTH_SOURCE_API_KEY = api.AUTH_ENV+SUBSCRIPTION_METHODS = ("claude.ai", "oauth_token")+LOGIN_HINT = "`claude` then `/login` signs your Claude subscription in"++# What the child must not inherit: a key (print mode uses it instead of the login), an effort that+# would win over `--effort`, and the calling Claude Code session's own variables (an agent running+# this tool must not make the child part of its session). `CLAUDE_CODE_*` are Claude Code's; the+# documented ones that choose how it signs in stay.+CHILD_DROP = ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDECODE", "CLAUDE_PID", "CLAUDE_EFFORT")+CHILD_KEEP = ("CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX",+ "CLAUDE_CODE_USE_FOUNDRY")++STATUS_TIMEOUT_SECONDS = 30+# One whole call, thinking included: a 48x48 sheet of four frames at effort high answered in up to ten+# minutes on the API (2026-10-14). The binary keeps no stream open to us, so the bound is the call's.+CALL_TIMEOUT_SECONDS = float(os.environ.get("SPRITE_GEN_CLAUDE_CALL_TIMEOUT_SECONDS", "1800"))+OUTPUT_CAP_ERROR = re.compile(r"exceeded the \d+ output token maximum")++Run = Callable[..., "subprocess.CompletedProcess[str]"]+++@dataclass(frozen=True)+class Login:+ method: str # SUBSCRIPTION_METHODS+ plan: str | None = None # `subscriptionType` as the binary says it+++@dataclass(frozen=True)+class Credential:+ source: str # AUTH_SOURCE_LOGIN | AUTH_SOURCE_API_KEY+ token: str | None = field(default=None, repr=False) # the API key; None on the login+ login: Login | None = None+++def child_env(env: Mapping[str, str] | None = None) -> dict[str, str]:+ return {key: value for key, value in provider_subprocess_env(env).items()+ if key not in CHILD_DROP and not (key.startswith("CLAUDE_CODE_") and key not in CHILD_KEEP)}+++def login(env: Mapping[str, str] | None = None, *, run: Run = subprocess.run) -> Login | None:+ """The subscription login the binary would sign in with here, or None: the binary is not installed,+ nobody is signed in, or what signs it in is not a subscription. An answer that cannot be read is+ refused — not knowing is not the same as no login."""+ try:+ done = run([provider_binary(BINARY), "auth", "status", "--json"], env=child_env(env),+ capture_output=True, text=True, timeout=STATUS_TIMEOUT_SECONDS)+ except FileNotFoundError:+ return None+ except (OSError, subprocess.TimeoutExpired) as exc:+ raise SystemExit(f"pixel-draw: `claude auth status` did not answer ({exc}); "+ "refusing to guess whether your Claude subscription is signed in") from exc+ try:+ status = json.loads(done.stdout)+ except json.JSONDecodeError:+ status = None+ if done.returncode not in (0, 1) or not isinstance(status, dict):+ raise SystemExit(f"pixel-draw: `claude auth status --json` answered exit {done.returncode} with "+ f"{(done.stdout or done.stderr).strip()[:200]!r}; refusing to guess whether your "+ "Claude subscription is signed in")+ method = status.get("authMethod")+ if not status.get("loggedIn") or method not in SUBSCRIPTION_METHODS:+ return None+ plan = status.get("subscriptionType")+ return Login(method=method, plan=plan if isinstance(plan, str) else None)+++def resolve_credential(*, batch: bool = False, env: Mapping[str, str] | None = None,+ run: Run = subprocess.run) -> Credential:+ """The subscription login first; `ANTHROPIC_API_KEY` only when no login is here, or for a Message+ Batch, which only the API runs. Neither is a refusal naming both."""+ if not batch:+ found = login(env, run=run)+ if found is not None:+ return Credential(AUTH_SOURCE_LOGIN, login=found)+ key = env_api_key(api.AUTH_ENV, env, who="pixel-draw")+ if key:+ return Credential(AUTH_SOURCE_API_KEY, token=key)+ if batch:+ raise SystemExit(f"pixel-draw: --batch is Anthropic's Message Batches API, which runs on {api.AUTH_ENV} "+ f"only, and it is not set.\n export {api.AUTH_ENV}=<your Claude Console API key>, or "+ "drop --batch to draw on your Claude subscription.")+ raise SystemExit(+ f"pixel-draw: no Claude credential — no subscription login (`claude auth status`) and {api.AUTH_ENV} "+ f"is not set.\n {LOGIN_HINT} (no per-call charge), or export {api.AUTH_ENV}=<your Claude Console "+ "API key> (platform.claude.com/settings/keys).")+++def _args(body: dict[str, Any]) -> list[str]:+ args = [provider_binary(BINARY), "-p", "--model", body["model"], "--effort", body["output_config"]["effort"],+ "--input-format", "stream-json", "--output-format", "stream-json", "--verbose",+ "--system-prompt", body.get("system") or "", "--tools", "", "--strict-mcp-config",+ "--no-session-persistence", "--safe-mode", "--max-turns", "1"]+ schema = (body["output_config"].get("format") or {}).get("schema")+ if schema is not None:+ args += ["--json-schema", json.dumps(schema, separators=(",", ":"))]+ return args+++def _message(body: dict[str, Any]) -> str:+ content = body["messages"][0]["content"]+ blocks = [{"type": "text", "text": content}] if isinstance(content, str) else content+ return json.dumps({"type": "user", "message": {"role": "user", "content": blocks}}) + "\n"+++def send_message(body: dict[str, Any], *, label: str, env: Mapping[str, str] | None = None,+ run: Run = subprocess.run) -> api.Reply:+ """`body` (an `anthropic_api.message_body`) answered on the subscription: its model, effort, system+ prompt, output cap, schema and content as the binary's flags and stdin, in an empty directory. The+ reply is the `result` event's; a cut answer comes back with `stop_reason` max_tokens and the text+ written before the cut, an error as `ApiError`."""+ started = time.monotonic()+ child = {**child_env(env), "CLAUDE_CODE_MAX_OUTPUT_TOKENS": str(body["max_tokens"])}+ with tempfile.TemporaryDirectory(prefix="sprite-gen-claude-") as cwd:+ try:+ done = run(_args(body), input=_message(body), env=child, cwd=cwd, capture_output=True, text=True,+ timeout=CALL_TIMEOUT_SECONDS)+ except subprocess.TimeoutExpired as exc:+ raise api.ApiError(f"{label}: `claude -p` gave no answer in {CALL_TIMEOUT_SECONDS:g}s and was stopped "+ "(SPRITE_GEN_CLAUDE_CALL_TIMEOUT_SECONDS)", billed=True) from exc+ except OSError as exc:+ raise api.ApiError(f"{label}: `claude -p` did not start ({exc})", billed=False) from exc+ seconds = round(time.monotonic() - started, 3)+ result: dict[str, Any] | None = None+ message_id, texts, thinking = None, [], []+ for line in done.stdout.splitlines():+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ continue+ if event.get("type") == "assistant":+ message = event.get("message") or {}+ message_id = message.get("id") or message_id+ for block in message.get("content") or []:+ if block.get("type") == "text":+ texts.append(block.get("text") or "")+ elif block.get("type") == "thinking" and block.get("thinking"):+ thinking.append(block["thinking"])+ elif event.get("type") == "result":+ result = event+ if result is None:+ said = (done.stderr or done.stdout).strip()[-300:]+ raise api.ApiError(f"{label}: `claude -p` ended with exit {done.returncode} and no result: {said!r}",+ billed=True)+ usage = result.get("usage") if isinstance(result.get("usage"), dict) else {}+ said = str(result.get("result") or "")+ if result.get("is_error"):+ if OUTPUT_CAP_ERROR.search(said):+ return api.Reply(text="".join(texts), thinking="\n".join(thinking), stop_reason="max_tokens",+ usage=usage, model=body["model"], message_id=message_id, mode="subscription",+ seconds=seconds)+ status = result.get("api_error_status")+ raise api.ApiError(f"{label}: the Claude subscription did not answer ({result.get('subtype')}"+ f"{f', HTTP {status}' if status else ''}): {said[:300]}",+ status=status if isinstance(status, int) else None,+ billed=bool(usage.get("output_tokens")))+ structured = result.get("structured_output")+ text = json.dumps(structured, ensure_ascii=False) if structured is not None else said+ return api.Reply(text=text, thinking="\n".join(thinking), stop_reason=result.get("stop_reason"), usage=usage,+ model=body["model"], message_id=message_id, mode="subscription", seconds=seconds)diff --git a/sprite_gen/gen/pixel_draw.py b/sprite_gen/gen/pixel_draw.pyindex ba42774..cc145ad 100644--- a/sprite_gen/gen/pixel_draw.py+++ b/sprite_gen/gen/pixel_draw.py@@ -53,7 +53,7 @@ from sprite_gen.qa.preview import checkerfrom sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.util.cli_kwargs import namespace_from_kwargsfrom . import anthropic_api as api-from . import refusal+from . import claude_login, refusalfrom .anthropic_api import ApiError, Replyfrom .base import announce_api_billing, flags_over_spec, print_jsonfrom .pixel_gates import colors_used, evaluate, safe_area@@ -439,14 +439,20 @@ class Unfinished(Exception):class Calls:- """Every model call of a run: asked, or read back from `calls/<id>.json` on --resume."""+ """Every model call of a run: asked on `credential` (`claude_login.resolve_credential`), or read back+ from `calls/<id>.json` on --resume. `announce` runs once, before the first request that leaves —+ a run read back whole asks nothing and says nothing."""- def __init__(self, run_dir: Path, token: str, *, sleep: Callable[[float], None], note: Callable[[str], None]) -> None:+ def __init__(self, run_dir: Path, credential: claude_login.Credential, *, sleep: Callable[[float], None],+ note: Callable[[str], None], announce: Callable[[], None] = lambda: None) -> None:self.dir = run_dir / "calls"self.batch_dir = run_dir / "batches"- self.token = token+ self.credential = credential+ self.token = credential.tokenself.sleep = sleepself.note = note+ self.announce = announce+ self.announced = Falseself.lock = threading.Lock()self.summaries: dict[str, dict[str, Any]] = {}self.batches: dict[str, dict[str, Any]] = {}@@ -458,6 +464,13 @@ class Calls:def _path(self, call_id: str) -> Path:return self.dir / f"{call_id}.json"+ def _leaving(self) -> None:+ with self.lock:+ if self.announced:+ return+ self.announced = True+ self.announce()+def cached(self, call_id: str, body: dict[str, Any]) -> Reply | None:path = self._path(call_id)if not path.is_file():@@ -479,12 +492,13 @@ class Calls:def save(self, call_id: str, purpose: str, candidate: str | None, body: dict[str, Any],outcome: Reply | ApiError, *, image: str | None = None) -> None:reply = outcome if isinstance(outcome, Reply) else outcome.partial- batch = reply is not None and reply.mode == "batch"+ subscription = self.credential.source == claude_login.AUTH_SOURCE_LOGIN+ mode = reply.mode if reply is not None else ("subscription" if subscription else "realtime")usage = reply.usage if reply is not None else {}record: dict[str, Any] = {"id": call_id, "purpose": purpose, "candidate": candidate,"outcome": "reply" if isinstance(outcome, Reply) else "error",- "mode": "batch" if batch else "realtime", "model": body["model"],+ "mode": mode, "auth_source": self.credential.source, "model": body["model"],"effort": body["output_config"]["effort"], "max_tokens": body["max_tokens"],"request_id": reply.request_id if reply else getattr(outcome, "request_id", None),"message_id": reply.message_id if reply else None,@@ -493,7 +507,7 @@ class Calls:"stop_details": reply.stop_details if reply else None,"usage": usage or None,"thinking_tokens": api.thinking_tokens(usage) if usage else None,- "cost_usd": api.cost_usd(usage, batch=batch) if usage else 0.0,+ "cost_usd": _cost_usd(usage, mode),"seconds": reply.seconds if reply else None,"finished_at": _now(),}@@ -515,8 +529,12 @@ class Calls:if cached is not None:self.note(f"{call_id}: read back from calls/{call_id}.json (not asked again)")return cached+ self._leaving()try:- outcome: Reply | ApiError = api.stream_message(self.token, body, sleep=self.sleep, label=f"{VERB} {call_id}")+ if self.credential.source == claude_login.AUTH_SOURCE_LOGIN:+ outcome: Reply | ApiError = claude_login.send_message(body, label=f"{VERB} {call_id}")+ else:+ outcome = api.stream_message(self.token, body, sleep=self.sleep, label=f"{VERB} {call_id}")except ApiError as exc:outcome = excself.save(call_id, purpose, candidate, body, outcome, image=image)@@ -548,6 +566,7 @@ class Calls:out.update(self._collect(record, need, wait))need = {cid: ask for cid, ask in need.items() if cid not in out}if need:+ self._leaving()try:batch = api.submit_batch(self.token, [(cid, ask.body) for cid, ask in need.items()],sleep=self.sleep, label=VERB)@@ -595,14 +614,22 @@ class Calls:return out+def _cost_usd(usage: dict[str, Any], mode: str) -> float:+ """What one call charged: nothing on the subscription (it counts against the plan's usage limits+ instead), the published price on the API key, half of it in a Message Batch."""+ if not usage or mode == "subscription":+ return 0.0+ return api.cost_usd(usage, batch=mode == "batch")++def _call_line(call_id: str, outcome: Reply | ApiError) -> str:if isinstance(outcome, ApiError):return f"{call_id}: {outcome.line}"usage = outcome.usage- cost = api.cost_usd(usage, batch=outcome.mode == "batch")+ paid = "subscription" if outcome.mode == "subscription" else f"${_cost_usd(usage, outcome.mode):.4f}"took = f" {outcome.seconds:.0f}s" if outcome.seconds is not None else ""return (f"{call_id}: {outcome.stop_reason} — {usage.get('output_tokens')} output tokens "- f"({api.thinking_tokens(usage)} thinking), ${cost:.4f}{took}")+ f"({api.thinking_tokens(usage)} thinking), {paid}{took}")# ----------------------------------------------------------------------------- candidates@@ -1027,19 +1054,25 @@ def _run(args: argparse.Namespace, *, sleep: Callable[[float], None] = time.sleebatch_wait = BATCH_WAIT_DEFAULT if args.batch_wait is None else args.batch_waitif batch_wait < 0:raise _refuse(f"--batch-wait is seconds, at least 0, got {batch_wait:g}")- token = api.resolve_credential()+ credential = claude_login.resolve_credential(batch=request.batch)if not args.resume:_fresh_dir(out_dir)atomic_write_text(out_dir / "request.json", json.dumps(request.to_dict(), ensure_ascii=False, indent=1) + "\n")note = _note_printer()- announce_api_billing("claude", api.AUTH_ENV,- f" (model={api.MODEL}, effort={request.effort}, candidates={request.candidates}, "- f"{'Message Batches at half price' if request.batch else 'realtime'}).")++ def announce() -> None:+ if credential.source == claude_login.AUTH_SOURCE_API_KEY:+ announce_api_billing("claude", api.AUTH_ENV,+ f" (model={api.MODEL}, effort={request.effort}, candidates={request.candidates}, "+ f"{'Message Batches at half price' if request.batch else 'realtime'})"+ + ("." if request.batch else f" — {claude_login.LOGIN_HINT}."))+started = time.monotonic()- calls = Calls(out_dir, token, sleep=sleep, note=note)+ calls = Calls(out_dir, credential, sleep=sleep, note=note, announce=announce)run = Run(request, out_dir, calls, batch_wait=batch_wait, note=note)report: dict[str, Any] = {"kind": REPORT_KIND, "status": None, "out_dir": str(out_dir), "source": "model",- "model": api.MODEL, "request": request.to_dict(), "chosen": None, "files": {},+ "model": api.MODEL, "auth_source": credential.source, "request": request.to_dict(),+ "chosen": None, "files": {},"pick": None, "candidates": [], "warnings": [], "info": []}try:candidates = run.candidates()