Skip to content

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

fix: a flag given with a spec file or request that holds the same key wins and says so on one stderr line (gen.base.flags_over_spec, for pixel-draw --spec, which refused the pair, and prepare --request, where --style, --cell-size and --safe-margin lost to the request and the rest won in silence; prepare's note no longer calls the subject it carries dropped); an answered provider POST is sent again only when its provider documents the answer as a request not taken - Anthropic 429 but its spend cap, 500, 529; OpenAI 429 but its billing codes, 503; xAI 429 - after the answer's retry-after or the doubling wait the video polls wait by, twice at most (gen.retry, for the Anthropic transport, the OpenAI and Grok image calls, the facing check and the clip request; video-set no longer reruns a clip on top); a refusal whose body broke on the way is no answer on every transport (xai.error_body)

Soohong Kim076d984316d6
diff --git a/sprite_gen/gen/anthropic_api.py b/sprite_gen/gen/anthropic_api.py
index e1df9f3..3fb0496 100644
--- a/sprite_gen/gen/anthropic_api.py
+++ b/sprite_gen/gen/anthropic_api.py
@@ -4,8 +4,8 @@ Message Batches, and what a call cost.
Raw HTTP over urllib, like `openai_provider` and `xai`: the runtime dependency surface is Pillow
and NumPy (SECURITY.md), and one more SDK with its own HTTP stack would be a second transport for
-the same job. What ends an exchange unanswered (`NO_ANSWER`) and the words for it
-(`no_answer_reason`) are `xai`'s. Field names and behaviour are the documented Messages API surface
+the same job. What ends an exchange unanswered (`NO_ANSWER`), the words for it
+(`no_answer_reason`) and the reading of a refusal's body (`error_body`) are `xai`'s. Field names and behaviour are the documented Messages API surface
(platform.claude.com, 2026-10-12 확인):
- `POST /v1/messages` with `stream: true` answers Server-Sent Events: `message_start` (a message
@@ -24,9 +24,11 @@ the same job. What ends an exchange unanswered (`NO_ANSWER`) and the words for i
`{custom_id, result: {type: succeeded|errored|canceled|expired, ...}}`. Only `succeeded` is
billed, at half the price of the same call made directly.
-A refusal of the request itself — 429, 500, 502, 503, 504, 529 before any answer began — made
-nothing, so it is asked again, twice at most, each time said on stderr. Anything after the answer
-began (a broken stream, an `error` event) may have been billed and is never asked again here.
+A refusal of the request before any answer began is asked again when Anthropic documents it as
+one (429 but its spend cap, 500, 529), twice at most, each time said on stderr — `retry`, the rule
+every direct provider call keeps, with the provider's words and the date they were read. Anything
+after the answer began (a broken stream, an `error` event) may have been billed and is never asked
+again here.
There is no refusal fallback to another model: `pixel-draw` reports a refusal as it came.
"""
from __future__ import annotations
@@ -34,15 +36,14 @@ from __future__ import annotations
import http.client
import json
import os
-import sys
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from typing import Any, Callable
-from . import refusal
-from .xai import NO_ANSWER, no_answer_reason
+from . import refusal, retry
+from .xai import NO_ANSWER, error_body, no_answer_reason
API_BASE = "https://api.anthropic.com/v1"
API_VERSION = "2023-06-01"
@@ -58,9 +59,6 @@ PRICE_PER_MTOK = {
}
BATCH_DISCOUNT = 0.5
-RETRY_STATUSES = (429, 500, 502, 503, 504, 529)
-RETRY_WAITS = (10.0, 30.0) # before the second and the third ask
-RETRY_AFTER_MAX = 120.0
# One socket read may wait this long. Thinking streams its summary (`display: summarized`) and the
# API sends `ping`s, so a stream that says nothing for minutes is stalled, not thinking.
READ_TIMEOUT_SECONDS = float(os.environ.get("SPRITE_GEN_CLAUDE_READ_TIMEOUT_SECONDS", "300"))
@@ -165,17 +163,6 @@ def _request(method: str, url: str, token: str, data: bytes | None, *, accept: s
return request
-def _error_body(exc: urllib.error.HTTPError) -> Any:
- try:
- raw = exc.read().decode("utf-8", "replace")
- except NO_ANSWER:
- return refusal.RawBody("")
- try:
- return json.loads(raw)
- except json.JSONDecodeError:
- return refusal.RawBody(raw)
-
-
def _error_type(body: Any) -> str | None:
"""`error.type` of an Anthropic error body (`{"type": "error", "error": {"type", "message"}}`)."""
error = body.get("error") if isinstance(body, dict) else None
@@ -191,38 +178,32 @@ def refused_line(status: int, body: Any, token: str | None) -> str:
return f"pixel-draw: claude request failed (HTTP {status}){suffix}; not asked again{refusal.said(body, token)}"
-def _retry_after(headers: Any) -> float | None:
- value = headers.get("retry-after") if headers is not None else None
- try:
- seconds = float(value) if value is not None else None
- except ValueError:
- return None
- return min(seconds, RETRY_AFTER_MAX) if seconds is not None and seconds >= 0 else None
+def _no_answer(exc: BaseException) -> ApiError:
+ return ApiError(f"pixel-draw: claude request got no answer ({no_answer_reason(exc)}); not asked again "
+ "(the API may have accepted it)")
def _open(request_for: Callable[[], urllib.request.Request], token: str, *, timeout: float, sleep: Sleep,
- label: str) -> http.client.HTTPResponse:
- """Send a request; a refusal that made nothing is asked again (RETRY_STATUSES), anything else raises."""
- for attempt in range(len(RETRY_WAITS) + 1):
+ label: str, method: str = "POST") -> http.client.HTTPResponse:
+ """Send a request, and again after a refusal `retry` sends again; any other refusal raises ApiError."""
+ def send() -> tuple[int, Any, Any]:
try:
- return urllib.request.urlopen(request_for(), timeout=timeout)
+ response = urllib.request.urlopen(request_for(), timeout=timeout)
except urllib.error.HTTPError as exc:
- body = _error_body(exc)
- if exc.code in RETRY_STATUSES and attempt < len(RETRY_WAITS):
- wait = _retry_after(exc.headers)
- wait = RETRY_WAITS[attempt] if wait is None else wait
- kind = _error_type(body)
- print(f"[{label}] claude refused the request ({exc.code}{' ' + kind if kind else ''}); "
- f"nothing was made — asking again in {wait:g}s ({attempt + 1} of {len(RETRY_WAITS)})",
- file=sys.stderr)
- sleep(wait)
- continue
- raise ApiError(refused_line(exc.code, body, token), status=exc.code,
- request_id=exc.headers.get("request-id") if exc.headers else None, billed=False) from exc
+ try:
+ return exc.code, error_body(exc, timeout), exc.headers
+ except NO_ANSWER as cut:
+ raise _no_answer(cut) from cut
except NO_ANSWER as exc:
- raise ApiError(f"pixel-draw: claude request got no answer ({no_answer_reason(exc)}); not asked again "
- "(the API may have accepted it)") from exc
- raise AssertionError("unreachable")
+ raise _no_answer(exc) from exc
+ return response.status, response, response.headers
+
+ status, answer, headers, _asks = retry.ask(send, provider="anthropic", who="claude", label=label, method=method,
+ sleep=sleep, kind=_error_type)
+ if 200 <= status < 300:
+ return answer
+ raise ApiError(refused_line(status, answer, token), status=status,
+ request_id=headers.get("request-id") if headers else None, billed=False)
class _Stream:
@@ -333,7 +314,7 @@ def _json_call(method: str, url: str, token: str, body: dict[str, Any] | None, *
label: str, timeout: float = 120.0) -> Any:
data = None if body is None else json.dumps(body).encode("utf-8")
response = _open(lambda: _request(method, url, token, data, accept="application/json"),
- token, timeout=timeout, sleep=sleep, label=label)
+ token, timeout=timeout, sleep=sleep, label=label, method=method)
try:
with response:
raw = response.read().decode("utf-8")
@@ -385,7 +366,7 @@ def batch_results(token: str, batch: dict[str, Any], *, sleep: Sleep = time.slee
if not isinstance(url, str) or not url:
raise ApiError(f"pixel-draw: batch {batch.get('id')} has ended but names no results_url")
response = _open(lambda: _request("GET", url, token, None, accept="application/binary"),
- token, timeout=120.0, sleep=sleep, label=label)
+ token, timeout=120.0, sleep=sleep, label=label, method="GET")
try:
with response:
lines = response.read().decode("utf-8").splitlines()
diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.py
index 8483893..3583aac 100644
--- a/sprite_gen/gen/base.py
+++ b/sprite_gen/gen/base.py
@@ -10,6 +10,7 @@ path or a "done" string (No Silent Fallback).
from __future__ import annotations
+import copy
import io
import json
import os
@@ -18,7 +19,7 @@ import sys
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any, Protocol
+from typing import Any, Mapping, Protocol
from PIL import Image, UnidentifiedImageError
@@ -119,6 +120,31 @@ def announce_api_billing(provider: str, env_name: str, detail: str = "") -> None
)
+def flags_over_spec(spec: Mapping[str, Any], flags: Mapping[str, Any], *, verb: str, source: str,
+ spelled: Mapping[str, str] | None = None) -> dict[str, Any]:
+ """`spec` — what a spec file or a request says — with every flag given laid over the key it sets.
+
+ A key given both ways takes the flag, and one stderr line names every such flag, so a value the
+ file holds is never replaced in silence: the one answer of every verb that reads a file of the
+ same keys as its flags (`prepare --request`, `pixel-draw --spec`). `flags` holds the flags that
+ were given, by the key each sets; a dotted key (`cell.width`) sets a key of an object in `spec`.
+ `spelled` names a key's flag where it is not `--key-with-dashes`."""
+ merged = copy.deepcopy(dict(spec))
+ both: list[str] = []
+ for key, value in flags.items():
+ *parents, leaf = key.split(".")
+ node = merged
+ for name in parents:
+ node[name] = node = dict(node.get(name) or {})
+ name = (spelled or {}).get(key, "--" + key.replace("_", "-"))
+ if leaf in node and name not in both:
+ both.append(name)
+ node[leaf] = value
+ if both:
+ print(f"[{verb}] {', '.join(both)} given both as a flag and in {source}: the flag wins", file=sys.stderr)
+ return merged
+
+
def print_json(payload: dict) -> None:
"""Emit the machine-readable report as UTF-8 on every host locale.
diff --git a/sprite_gen/gen/facing_vision.py b/sprite_gen/gen/facing_vision.py
index 7b6eed6..0038ed2 100644
--- a/sprite_gen/gen/facing_vision.py
+++ b/sprite_gen/gen/facing_vision.py
@@ -62,7 +62,7 @@ def grok_inspect(path: Path, *, credential=None, call=None) -> tuple[str, dict]:
credential = credential or xai.resolve_credential()
if credential.source == xai.AUTH_SOURCE_API_KEY:
announce_api_billing("grok", xai.AUTH_ENV, " (facing vision check).")
- status, reply = (call or xai.http_json)("POST", xai.API_BASE + "/responses", credential.token,
- request_body(path, GROK_MODEL))
+ status, reply, _sends = xai.post(call or xai.http_json, xai.API_BASE + "/responses", credential.token,
+ request_body(path, GROK_MODEL), who="grok", label="facing-vision")
text, metadata = response_text(status, reply)
return text, {**metadata, "auth_source": credential.source, "transport": "xai-api"}
diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.py
index bf95b74..d66b43b 100644
--- a/sprite_gen/gen/grok_provider.py
+++ b/sprite_gen/gen/grok_provider.py
@@ -17,7 +17,7 @@ from pathlib import Path
from PIL import Image, UnidentifiedImageError
-from . import refusal, xai
+from . import refusal, retry, xai
from .base import (
GEN_TIMEOUT_SECONDS,
RESOLUTIONS,
@@ -141,8 +141,8 @@ class GrokProvider:
f"{f' ({priced})' if priced else ''} — "
f"`{xai.GROK_LOGIN_COMMAND}` signs your Grok subscription in.")
started = time.monotonic()
- status, reply = xai.http_json("POST", xai.API_BASE + endpoint, credential.token,
- body, timeout=GEN_TIMEOUT_SECONDS)
+ status, reply, sends = xai.post(lambda *a: xai.http_json(*a, timeout=GEN_TIMEOUT_SECONDS),
+ xai.API_BASE + endpoint, credential.token, body, who="grok", label="gen")
# The provider's code goes in front, format-checked; the body it sent goes
# last, as received, with keys and URL query strings masked (refusal.said).
# The REST image answer has no moderation field (docs.x.ai reference; a
@@ -159,7 +159,7 @@ class GrokProvider:
if refused is not None:
scoped = f" (sent with {priced}, documented for {DEFAULT_MODEL})" if priced and body["model"] != DEFAULT_MODEL else ""
raise SystemExit(f"grok-gen: {refused.reason('image request failed')} (HTTP {status}){refused.suffix()}; "
- f"no retry or provider fallback{scoped}{refusal.said(reply, credential.token)}")
+ f"{retry.tail(sends)}{scoped}{refusal.said(reply, credential.token)}")
items = reply.get("data") if isinstance(reply, dict) else None
if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):
raise SystemExit("grok-gen: expected exactly one image in the response; nothing published")
diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.py
index 0d01201..60abcad 100644
--- a/sprite_gen/gen/openai_provider.py
+++ b/sprite_gen/gen/openai_provider.py
@@ -20,8 +20,10 @@ names it and never as a default, a saved preference, a guided-flow option or a
fallback target, and every call announces the charge on stderr before it leaves.
Personal use belongs on a subscription provider (`codex`, `grok`).
-This provider never falls back to codex, to another key, or to a retry: a missing
-credential, a rejected key or a failed request is the observable outcome.
+This provider never falls back to codex or to another key: a missing credential, a
+rejected key or a failed request is the observable outcome. A refusal OpenAI documents as
+a request not taken (429 but its billing codes, 503 overloaded) is sent again, twice at
+most and each time said on stderr — `retry`, the rule every direct provider call keeps.
"""
from __future__ import annotations
@@ -39,7 +41,8 @@ from typing import Any
from PIL import Image, UnidentifiedImageError
-from . import refusal
+from . import refusal, retry
+from .xai import NO_ANSWER, error_body
from .base import (
GEN_TIMEOUT_SECONDS,
QUALITIES,
@@ -213,11 +216,15 @@ def _multipart_request(fields: dict[str, str], refs: list[Path]) -> tuple[bytes,
return b"".join(chunks), f"multipart/form-data; boundary={boundary}"
+TRANSPORT_FAILED = "openai-gen: request failed or timed out; no automatic retry (the server may have accepted it)"
+
+
def http_image(url: str, token: str, data: bytes, content_type: str, *, timeout: float) -> tuple[int, Any, Any]:
"""POST an images request and return (status, parsed JSON, response headers).
A transport error is terminal: the server may already have accepted and billed
- the request, so it is never retried here.
+ the request, so it is never retried here. A refusal whose body broke on the way
+ is one too (`xai.error_body`).
"""
request = urllib.request.Request(url, data=data, method="POST")
request.add_header("Authorization", f"Bearer {token}")
@@ -230,15 +237,16 @@ def http_image(url: str, token: str, data: bytes, content_type: str, *, timeout:
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
raise SystemExit("openai-gen: response was not valid JSON") from exc
except urllib.error.HTTPError as exc:
- raw = exc.read().decode("utf-8", "replace")
try:
- return exc.code, json.loads(raw), exc.headers
- except json.JSONDecodeError:
- return exc.code, refusal.RawBody(raw), exc.headers
- except (urllib.error.URLError, TimeoutError, OSError) as exc:
- raise SystemExit(
- "openai-gen: request failed or timed out; no automatic retry (the server may have accepted it)"
- ) from exc
+ return exc.code, error_body(exc, timeout), exc.headers
+ except NO_ANSWER as cut:
+ raise SystemExit(TRANSPORT_FAILED) from cut
+ except NO_ANSWER as exc:
+ raise SystemExit(TRANSPORT_FAILED) from exc
+
+
+def _ask(send: retry.Send) -> tuple[int, Any, Any, int]:
+ return retry.ask(send, provider="openai", who="openai", label="gen", kind=refusal.provider_code)
def rate_limit_headers(headers: Any) -> dict[str, str]:
@@ -277,9 +285,9 @@ class OpenAIProvider:
from . import facing_vision as vision
token = resolve_credential()
announce_api_billing(self.name, AUTH_ENV, " (facing vision check).")
- status, reply, _headers = http_image(API_BASE + "/responses", token,
- json.dumps(vision.request_body(path, vision.OPENAI_MODEL)).encode("utf-8"),
- "application/json", timeout=GEN_TIMEOUT_SECONDS)
+ data = json.dumps(vision.request_body(path, vision.OPENAI_MODEL)).encode("utf-8")
+ status, reply, _headers, _asks = _ask(lambda: http_image(API_BASE + "/responses", token, data, "application/json",
+ timeout=GEN_TIMEOUT_SECONDS))
text, metadata = vision.response_text(status, reply)
return text, {**metadata, "auth_source": AUTH_SOURCE_API_KEY, "transport": "openai-api"}
@@ -299,7 +307,8 @@ class OpenAIProvider:
f" (model={fields['model']}, quality={fields['quality']}, size={fields['size']}).",
)
started = time.monotonic()
- status, reply, headers = http_image(API_BASE + endpoint, token, data, content_type, timeout=GEN_TIMEOUT_SECONDS)
+ status, reply, headers, asks = _ask(lambda: http_image(API_BASE + endpoint, token, data, content_type,
+ timeout=GEN_TIMEOUT_SECONDS))
# The provider's code (and the moderation stage) go in front, format-checked;
# the body the provider sent goes last, as received, with keys and URL
# query strings masked (refusal.said).
@@ -312,7 +321,7 @@ class OpenAIProvider:
if refused is not None:
raise SystemExit(
f"openai-gen: {refused.reason('image request failed')} (HTTP {status}){refused.suffix()}; "
- f"no retry or provider fallback{refusal.said(reply, token)}"
+ f"{retry.tail(asks)}{refusal.said(reply, token)}"
)
items = reply.get("data") if isinstance(reply, dict) else None
if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):
diff --git a/sprite_gen/gen/pixel_draw.py b/sprite_gen/gen/pixel_draw.py
index eed6bd6..cac21de 100644
--- a/sprite_gen/gen/pixel_draw.py
+++ b/sprite_gen/gen/pixel_draw.py
@@ -51,10 +51,11 @@ from PIL import Image, ImageDraw
from sprite_gen.qa.preview import checker
from sprite_gen.spec.runio import atomic_write_text
+from sprite_gen.util.cli_kwargs import namespace_from_kwargs
from . import anthropic_api as api
from . import refusal
from .anthropic_api import ApiError, Reply
-from .base import announce_api_billing, print_json
+from .base import announce_api_billing, flags_over_spec, print_json
from .pixel_gates import colors_used, evaluate, safe_area
from .pixel_grid import (
FORMATS, Grid, Issue, PaletteRule, check_rows, frame_name_ok, frame_pixels, palette_rule, parse_answer,
@@ -175,11 +176,7 @@ def _load_spec(path: Path) -> dict[str, Any]:
def resolve_request(args: argparse.Namespace) -> PixelRequest:
spec = _load_spec(args.spec) if args.spec else {}
given = {key: getattr(args, key) for key in SPEC_KEYS if getattr(args, key) is not None}
- both = sorted(set(spec) & set(given))
- if both:
- raise _refuse(f"{', '.join('--' + k.replace('_', '-') for k in both)} given both as a flag and in --spec; "
- "say each once")
- merged = {**spec, **given}
+ merged = flags_over_spec(spec, given, verb=VERB, source="--spec")
subject = merged.get("subject")
if not isinstance(subject, str) or not subject.strip():
raise _refuse("nothing to draw — pass --subject TEXT or --spec FILE with a subject")
@@ -1077,11 +1074,7 @@ def _call_order(call_id: str) -> tuple:
def run(**kwargs: Any) -> int:
parser = argparse.ArgumentParser()
add_arguments(parser)
- known = {action.dest for action in parser._actions if action.dest != "help"}
- unexpected = set(kwargs) - known
- if unexpected:
- raise TypeError(f"unexpected keyword argument(s): {', '.join(sorted(unexpected))}")
- return _run(argparse.Namespace(**{dest: kwargs.get(dest, parser.get_default(dest)) for dest in known}))
+ return _run(namespace_from_kwargs(parser, kwargs))
def main(argv: list[str] | None = None) -> int:
diff --git a/sprite_gen/gen/prepare.py b/sprite_gen/gen/prepare.py
index f4a38a9..a3ddb96 100644
--- a/sprite_gen/gen/prepare.py
+++ b/sprite_gen/gen/prepare.py
@@ -19,6 +19,8 @@ from typing import Any
from PIL import Image, ImageDraw
+from sprite_gen.util.cli_kwargs import namespace_from_kwargs
+from sprite_gen.util.hexcolor import format_hex, parse_hex
from sprite_gen.curate.anchor import anchor_ref_rel
from sprite_gen.frames.extract import color_distance
from sprite_gen.compose.layers import require_valid_layer_request
@@ -27,11 +29,14 @@ from sprite_gen.spec.subject import SUBJECTS
from sprite_gen.video import body_plan as body_mod
from sprite_gen.video.body_plan import Body
+from .base import flags_over_spec
+
# Default safe margin is proportional to the cell dimension (floored), not a fixed
# pixel count — 9.4% keeps the same relative reserve at every cell size
# (256 -> 24px, 128 -> 12px). An explicit request/CLI value stays absolute.
DEFAULT_SAFE_MARGIN_RATIO = 0.094
+CELL_SIZE_DEFAULT = 256
DEFAULT_STATES: dict[str, dict[str, Any]] = {
"idle": {"frames": 4, "fps": 4, "loop": True, "action": "subtle breathing and blinking"},
@@ -190,13 +195,10 @@ CHROMA_CANDIDATES = [
def parse_hex_color(value: str) -> tuple[int, int, int]:
- if not re.fullmatch(r"#[0-9a-fA-F]{6}", value):
- raise SystemExit(f"invalid chroma key color: {value}; expected #RRGGBB")
- return tuple(int(value[index : index + 2], 16) for index in (1, 3, 5))
-
-
-def rgb_to_hex(rgb: tuple[int, int, int]) -> str:
- return f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
+ try:
+ return parse_hex(value)
+ except ValueError:
+ raise SystemExit(f"invalid chroma key color: {value}; expected #RRGGBB") from None
# The reference is sampled with NEAREST, not LANCZOS: a resampling filter that
@@ -289,7 +291,7 @@ def detect_reference_background(image: Image.Image) -> dict[str, Any]:
}
return {
"mode": "flat",
- "hex": rgb_to_hex(background),
+ "hex": format_hex(background),
"rgb": list(background),
"opaque_border_fraction": round(opaque_fraction, 3),
"border_coverage": round(coverage, 3),
@@ -407,7 +409,7 @@ def sampled_reference_pixels(path: Path | None) -> list[tuple[int, int, int]]:
def choose_chroma_key(reference: Path | None, requested: str) -> dict[str, Any]:
if requested.lower() != "auto":
rgb = parse_hex_color(requested)
- hex_value = rgb_to_hex(rgb)
+ hex_value = format_hex(rgb)
name = next((candidate_name for candidate_name, candidate_hex in CHROMA_CANDIDATES if candidate_hex == hex_value), "manual")
return {"name": name, "hex": hex_value, "rgb": list(rgb), "selection": "manual"}
@@ -447,7 +449,7 @@ def choose_chroma_key(reference: Path | None, requested: str) -> dict[str, Any]:
score, min_distance, _preference, name, rgb = max(safe) if safe else max(scored)
result = {
"name": name,
- "hex": rgb_to_hex(rgb),
+ "hex": format_hex(rgb),
"rgb": list(rgb),
"selection": "auto",
"score": round(score, 2),
@@ -456,7 +458,7 @@ def choose_chroma_key(reference: Path | None, requested: str) -> dict[str, Any]:
"candidates": [
{
"name": entry[3],
- "hex": rgb_to_hex(entry[4]),
+ "hex": format_hex(entry[4]),
"score": round(entry[0], 2),
"min_subject_distance": round(entry[1], 2),
"clears_erase_radius": entry[1] > MIN_SUBJECT_KEY_DISTANCE,
@@ -516,7 +518,7 @@ def normalize_states(raw: dict[str, Any] | None, bodies: list[Body] | None = Non
# after the fact (docs/layer-tracks.md §2 B1). The lists are the one place that
# rule is written down, and `dropped_key_notes` makes every drop observable
# instead of silent.
-REQUEST_KEYS_CARRIED = ("cell", "states", "style",
+REQUEST_KEYS_CARRIED = ("cell", "states", "style", "subject",
"directions", "fit", "rig", "layers", "body_plan")
# Written by prepare itself, from CLI flags and from measuring the base image. An
# incoming copy is not carried either, but it is restated rather than lost, so the
@@ -592,6 +594,63 @@ def load_request(path: Path | None, inline_json: str | None) -> dict[str, Any]:
return {}
+# The fit flags and the `fit` key each sets.
+FIT_FLAGS = ("resample", "align_x", "align_y", "ground_frames", "pixel_unfake", "logical_height", "palette_size",
+ "detail_bias", "outline", "pitch_hint")
+
+
+def _cell_measures(cell: dict[str, Any]) -> dict[str, Any]:
+ """`cell` with each measure under one name — width, height, safe_margin_x, safe_margin_y — read as
+ `normalize_cell` reads its aliases, so a flag replaces a measure however the request spelled it."""
+ measures = {key: value for key, value in cell.items()
+ if key not in ("cell_width", "cell_height", "size", "safe_margin")}
+ for key, aliases in (("width", ("width", "cell_width", "size")), ("height", ("height", "cell_height", "size")),
+ ("safe_margin_x", ("safe_margin_x", "safe_margin")),
+ ("safe_margin_y", ("safe_margin_y", "safe_margin"))):
+ named = [alias for alias in aliases if alias in cell]
+ if named:
+ measures[key] = cell[named[0]]
+ return measures
+
+
+def request_with_flags(incoming: dict[str, Any], args: argparse.Namespace) -> dict[str, Any]:
+ """The incoming request with every flag given laid over the key it sets (`base.flags_over_spec`: the
+ flag wins, and one stderr line names the flags the request also set)."""
+ request = dict(incoming)
+ if isinstance(request.get("cell"), dict):
+ request["cell"] = _cell_measures(request["cell"])
+ flags: dict[str, Any] = {}
+ spelled: dict[str, str] = {"directions.set": "--directions"}
+ for key in ("style", "subject"):
+ if getattr(args, key) is not None:
+ flags[key] = getattr(args, key)
+ if args.body_plan:
+ flags["body_plan"] = list(args.body_plan)
+ if args.directions:
+ flags["directions.set"] = [d.strip() for d in args.directions.split(",") if d.strip()]
+ for pair in args.mirror.split(",") if args.mirror else ():
+ if "=" not in pair:
+ raise SystemExit(f"--mirror expects target=source pairs, got: {pair!r}")
+ target, source = (part.strip() for part in pair.split("=", 1))
+ flags[f"directions.mirror.{target}"] = source
+ spelled[f"directions.mirror.{target}"] = f"--mirror {target}"
+ for side in ("width", "height"):
+ flag = f"cell_{side}" if getattr(args, f"cell_{side}") is not None else "cell_size"
+ if getattr(args, flag) is not None:
+ flags[f"cell.{side}"] = getattr(args, flag)
+ spelled[f"cell.{side}"] = "--" + flag.replace("_", "-")
+ if args.safe_margin is not None:
+ for axis in ("x", "y"):
+ flags[f"cell.safe_margin_{axis}"] = args.safe_margin
+ spelled[f"cell.safe_margin_{axis}"] = "--safe-margin"
+ for key in FIT_FLAGS:
+ if getattr(args, f"fit_{key}") is not None:
+ flags[f"fit.{key}"] = getattr(args, f"fit_{key}")
+ spelled[f"fit.{key}"] = f"--fit-{key.replace('_', '-')}"
+ return flags_over_spec(request, flags, verb="prepare", source="--request" if args.request else "--request-json",
+ spelled=spelled)
+
+
# --- 방향 계약 (directions block) -------------------------------------------
# base = down(정면) 기본자세 하나. 방향 앵커(<dir>_<anchor_suffix>)를 base 에서 먼저
# 뽑고, 각 행은 자기 방향 앵커를 identity 로 생성한다 (directional-anchor-workflow.md).
@@ -911,11 +970,9 @@ BODY_PLAN_HELP = ("what the character stands on: biped (default), quadruped or l
"body_plan): no row prompt names a part the body lacks, as video-set --body-plan")
-def parse_body_plan(cli: list[str] | None, raw: Any) -> list[Body] | None:
- """`--body-plan` if given, else the request's `body_plan` (specs, or `{"plan", "figure"}` as
- `sprite-request.json` records it)."""
- if cli:
- return body_mod.parse_all(list(cli)) or None
+def parse_body_plan(raw: Any) -> list[Body] | None:
+ """The request's `body_plan` — `--body-plan`'s specs laid over it (`request_with_flags`), or
+ `{"plan", "figure"}` as `sprite-request.json` records it."""
if raw is None:
return None
if not isinstance(raw, list):
@@ -948,11 +1005,11 @@ def _build_parser() -> argparse.ArgumentParser:
parser.add_argument("--character-id", required=True)
parser.add_argument("--base-image", type=Path)
parser.add_argument("--description", default="")
- parser.add_argument("--style", default=STYLE_DEFAULT)
+ parser.add_argument("--style")
parser.add_argument("--subject", choices=SUBJECTS, default=None,
help="what the run draws: character (default) or effect — "
"sets validation defaults like the sparse-frame floor")
- parser.add_argument("--cell-size", type=int, default=256)
+ parser.add_argument("--cell-size", type=int)
parser.add_argument("--cell-width", type=int)
parser.add_argument("--cell-height", type=int)
parser.add_argument("--safe-margin", type=int, default=None, help="absolute px override; default is 9.4%% of the cell dimension, floored")
@@ -979,54 +1036,21 @@ def _build_parser() -> argparse.ArgumentParser:
return parser
-def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
- parser = _build_parser()
- values: dict[str, object] = {}
- remaining = dict(kwargs)
- for action in parser._actions:
- if action.dest == "help":
- continue
- default = [] if action.nargs == "*" else action.default
- if default is argparse.SUPPRESS:
- default = None
- value = remaining.pop(action.dest, default)
- if getattr(action, "required", False) and value is None:
- raise TypeError(f"missing required argument: {action.dest}")
- values[action.dest] = value
- if remaining:
- names = ", ".join(sorted(remaining))
- raise TypeError(f"unexpected keyword argument(s): {names}")
- return argparse.Namespace(**values)
def _run(args: argparse.Namespace):
out_dir = args.out_dir.expanduser().resolve()
if out_dir.exists() and any(out_dir.iterdir()) and not args.force:
raise SystemExit(f"output dir exists and is not empty: {out_dir}; pass --force")
- raw_request = load_request(args.request, args.request_json)
- bodies = parse_body_plan(args.body_plan, raw_request.get("body_plan"))
+ incoming = load_request(args.request, args.request_json)
+ raw_request = request_with_flags(incoming, args)
+ bodies = parse_body_plan(raw_request.get("body_plan"))
states = normalize_states(raw_request.get("states"), bodies)
- # 방향 계약: CLI 가 request JSON 을 override 한다 (fit 과 동일 규칙)
raw_directions = dict(raw_request.get("directions") or {})
- if args.directions:
- raw_directions["set"] = [d.strip() for d in args.directions.split(",") if d.strip()]
- if args.mirror:
- mirror = dict(raw_directions.get("mirror") or {})
- for pair in args.mirror.split(","):
- if "=" not in pair:
- raise SystemExit(f"--mirror expects target=source pairs, got: {pair!r}")
- target, source = pair.split("=", 1)
- mirror[target.strip()] = source.strip()
- raw_directions["mirror"] = mirror
directions = normalize_directions(raw_directions or None, states)
if directions:
states = ensure_direction_anchors(directions, states)
- raw_cell = dict(raw_request.get("cell", {}))
- if args.cell_width is not None:
- raw_cell["width"] = args.cell_width
- if args.cell_height is not None:
- raw_cell["height"] = args.cell_height
- cell = normalize_cell(raw_cell, args.cell_size, args.safe_margin)
+ cell = normalize_cell(dict(raw_request.get("cell", {})), CELL_SIZE_DEFAULT, None)
# Layer keys are carried explicitly (docs/layer-tracks.md §7) and validated
# before the run dir is touched: the layer validator is filesystem-free, so a
@@ -1035,7 +1059,7 @@ def _run(args: argparse.Namespace):
layer_keys = {key: raw_request[key] for key in ("rig", "layers")
if raw_request.get(key) is not None}
require_valid_layer_request({"cell": cell, "states": states, **layer_keys})
- for note in dropped_key_notes(raw_request):
+ for note in dropped_key_notes(incoming):
print(f"[prepare] {note}", file=sys.stderr)
out_dir.mkdir(parents=True, exist_ok=True)
@@ -1060,13 +1084,13 @@ def _run(args: argparse.Namespace):
"cell": cell,
"chroma_key": chroma_key,
"states": states,
- "style": raw_request.get("style", args.style),
+ "style": raw_request.get("style", STYLE_DEFAULT),
}
- # Subject profile: CLI wins over --request-json; absent = character. The
- # field stays omitted for the default so the request has one canonical
- # representation. Downstream validation derives its floor from this plus
- # cell geometry via sprite_gen.spec.subject.
- subject = args.subject or raw_request.get("subject")
+ # Subject profile: absent = character. The field stays omitted for the
+ # default so the request has one canonical representation. Downstream
+ # validation derives its floor from this plus cell geometry via
+ # sprite_gen.spec.subject.
+ subject = raw_request.get("subject")
if subject is not None:
if subject not in SUBJECTS:
raise SystemExit(f"unknown subject kind: {subject!r} (expected one of {', '.join(SUBJECTS)})")
@@ -1080,21 +1104,6 @@ def _run(args: argparse.Namespace):
# 가 <direction>/<pose> 로 나뉜다 (layout.py SSoT). legacy 런은 필드 없음 = flat.
request["layout"] = TAXONOMY
fit = dict(raw_request.get("fit", {}))
- fit_overrides = {
- "resample": args.fit_resample,
- "align_x": args.fit_align_x,
- "align_y": args.fit_align_y,
- "ground_frames": args.fit_ground_frames,
- "pixel_unfake": args.fit_pixel_unfake,
- "logical_height": args.fit_logical_height,
- "palette_size": args.fit_palette_size,
- "detail_bias": args.fit_detail_bias,
- "outline": args.fit_outline,
- "pitch_hint": args.fit_pitch_hint,
- }
- for key, value in fit_overrides.items():
- if value is not None:
- fit[key] = value
if fit:
request["fit"] = fit
# Optional layer declaration, validated above. Absent = a non-layer run whose
@@ -1135,7 +1144,7 @@ def _run(args: argparse.Namespace):
def run(**kwargs: object):
- return _run(_namespace_from_kwargs(**kwargs))
+ return _run(namespace_from_kwargs(_build_parser(), kwargs))
RETIRED_PP_MESSAGE = (
"--fit-pixel-perfect is retired: the accurate name for this pipeline is **pixel unfake** "
diff --git a/sprite_gen/gen/retry.py b/sprite_gen/gen/retry.py
new file mode 100644
index 0000000..4d17d30
--- /dev/null
+++ b/sprite_gen/gen/retry.py
@@ -0,0 +1,145 @@
+# SPDX-License-Identifier: Apache-2.0
+"""When a provider request that got an answer is sent again, and how long it waits first — one rule
+for every direct provider call: the Anthropic transport of `pixel-draw`, the OpenAI and Grok image
+calls of `gen`, the facing check, and the clip requests and polls of `video`.
+
+A POST that was answered is sent again only when its provider documents that answer as a refusal
+of the request before it was taken (`UNTAKEN`): the request made nothing, so asking again buys
+nothing twice. Every other answer — a 4xx, a 5xx the provider does not document so (it may have
+been worked on and billed), an answer that asks the caller to act first (a spent credit balance or
+spend limit, `ACT_FIRST`) — is returned to the caller as it came. A request that got no answer it
+could read (the connection broke, the answer broke on the way) is never sent again here: the
+server may have taken it.
+
+What the providers say, read 2026-10-13:
+
+- Anthropic (platform.claude.com/docs/en/api/errors, /api/rate-limits): 429 `rate_limit_error`
+ "Your organization has hit a rate limit", with a `retry-after` header "indicating how long to
+ wait"; 529 `overloaded_error` "The API is temporarily overloaded"; 500 `api_error` "An
+ unexpected error has occurred internal to Anthropic's systems. Retry the request with
+ exponential backoff". Not sent again: 504 `timeout_error` "The request timed out while
+ processing" (it was worked on), and the spend-cap 429 (`error.details.error_code`
+ `enforced_spend_limit_reached`, no `retry-after`): "Retrying ... fails until access resumes".
+- OpenAI (developers.openai.com/api/docs/guides/error-codes, /guides/rate-limits): 429 "Rate
+ limit reached for requests" and `slow_down`, and 503 `server_is_overloaded` "the requested model
+ does not have enough capacity to process your request at the moment" — the two its SDKs retry
+ ("Each official OpenAI SDK automatically retries eligible 429 and 503 responses"). Not sent
+ again: 500 "The server had an error while processing your request", and the billing 429s
+ (`credit_balance_exhausted`, `organization_spend_limit_exceeded`,
+ `project_spend_limit_exceeded`, `organization_usage_limit_exceeded`, type `insufficient_quota`):
+ "Don't retry quota, billing, or other errors that require you to take action."
+- xAI (docs.x.ai/developers/debugging, /developers/rate-limits): 429 "You are sending requests
+ too frequently and have reached the rate limit" — "Implement exponential backoff". It
+ documents no 5xx.
+
+The wait: the `retry-after` the answer carries, when it is one this run will wait for
+(`RETRY_AFTER_MAX_SECONDS`; a longer one is not waited out early — the request is not sent
+again, as OpenAI's rate-limit guide asks), else `backoff` — the doubling the `video` polls and
+downloads wait by, from START_SECONDS up to MAX_SECONDS. A POST is sent again ASKS_AGAIN times at
+most, each said on stderr in one line.
+
+A GET buys nothing, so one answered with any of GET_AGAIN is asked again; the `video` poll keeps
+asking for as long as its poll timeout lets it, the Anthropic batch reads ASKS_AGAIN times.
+"""
+from __future__ import annotations
+
+import sys
+import time
+from typing import Any, Callable
+
+START_SECONDS = 4.0
+MAX_SECONDS = 60.0
+RETRY_AFTER_MAX_SECONDS = 120.0
+ASKS_AGAIN = 2
+
+UNTAKEN: dict[str, frozenset[int]] = {
+ "anthropic": frozenset({429, 500, 529}),
+ "openai": frozenset({429, 503}),
+ "xai": frozenset({429}),
+}
+ACT_FIRST: dict[str, frozenset[str]] = {
+ "anthropic": frozenset({"enforced_spend_limit_reached"}),
+ "openai": frozenset({"credit_balance_exhausted", "organization_spend_limit_exceeded",
+ "project_spend_limit_exceeded", "organization_usage_limit_exceeded", "insufficient_quota"}),
+ "xai": frozenset(),
+}
+GET_AGAIN = frozenset({429, 500, 502, 503, 504, 529})
+
+Sleep = Callable[[float], None]
+Send = Callable[[], tuple[int, Any, Any]]
+
+
+def backoff(failures: int) -> float:
+ """The wait after `failures` failed asks in a row: 8 s, 16 s, 32 s, then MAX_SECONDS."""
+ return min(START_SECONDS * 2 ** failures, MAX_SECONDS)
+
+
+def retry_after(headers: Any) -> float | None:
+ """The answer's `retry-after` in seconds, or None when it sent none this can read."""
+ value = headers.get("retry-after") if headers is not None else None
+ try:
+ seconds = float(value) if value is not None else None
+ except ValueError:
+ return None
+ return seconds if seconds is not None and seconds >= 0 else None
+
+
+def _act_first(provider: str, body: Any) -> bool:
+ error = body.get("error") if isinstance(body, dict) else None
+ if not isinstance(error, dict):
+ return False
+ details = error.get("details") if isinstance(error.get("details"), dict) else {}
+ said = (error.get("code"), error.get("type"), details.get("error_code"))
+ return any(isinstance(word, str) and word in ACT_FIRST[provider] for word in said)
+
+
+def again_after(provider: str, method: str, status: int, body: Any, headers: Any, failures: int) -> float | None:
+ """Seconds to wait before sending the request again after its `failures`-th failed answer in a row,
+ or None when it is not sent again (the rule in the module docstring)."""
+ if failures > ASKS_AGAIN:
+ return None
+ if method == "GET":
+ if status not in GET_AGAIN:
+ return None
+ elif status not in UNTAKEN[provider] or _act_first(provider, body):
+ return None
+ said = retry_after(headers)
+ if said is None:
+ return backoff(failures)
+ return said if said <= RETRY_AFTER_MAX_SECONDS else None
+
+
+def asking_again(label: str, who: str, method: str, status: int, kind: str | None, wait: float, failures: int) -> str:
+ """The stderr line of one ask again. The status goes in plain digits: `(HTTP 429)` on this stream
+ reads as a refusal line, which a caller may answer by sending a second request."""
+ why = ("a read buys nothing" if method == "GET"
+ else "its docs say to ask again" if status == 500 else "nothing was made")
+ return (f"[{label}] {who} refused the request ({status}{' ' + kind if kind else ''}); {why} — "
+ f"asking again in {wait:g}s ({failures} of {ASKS_AGAIN})")
+
+
+def tail(asks: int) -> str:
+ """What a `gen` refusal line says was done after the answer: no retry, or how many times it was sent."""
+ return "no retry or provider fallback" if asks == 1 else f"sent {asks} times, no provider fallback"
+
+
+def _sleep(seconds: float) -> None:
+ time.sleep(seconds)
+
+
+def ask(send: Send, *, provider: str, who: str, label: str, method: str = "POST", sleep: Sleep | None = None,
+ kind: Callable[[Any], str | None] | None = None) -> tuple[int, Any, Any, int]:
+ """`send()` until an answer is not one to send again: `(status, body, headers, asks)`.
+
+ `send` returns `(status, body, headers)` — `headers` None when the transport keeps none — and
+ raises when no answer came; that is never asked again here. `kind` reads the provider's word for
+ the refusal off the body for the stderr line."""
+ asks = 0
+ while True:
+ status, body, headers = send()
+ asks += 1
+ wait = None if 200 <= status < 300 else again_after(provider, method, status, body, headers, asks)
+ if wait is None:
+ return status, body, headers, asks
+ print(asking_again(label, who, method, status, kind(body) if kind else None, wait, asks), file=sys.stderr)
+ (sleep or _sleep)(wait)
diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.py
index 23f5606..c6c6859 100644
--- a/sprite_gen/gen/video.py
+++ b/sprite_gen/gen/video.py
@@ -59,14 +59,15 @@ from pathlib import Path
from typing import Any, Callable
from sprite_gen.spec.runio import atomic_write_text
-from . import prompt_parts, refusal
+from sprite_gen.util.cli_kwargs import namespace_from_kwargs
+from . import prompt_parts, refusal, retry
from .base import announce_api_billing, print_json
from .facing import FACINGS, validate as validate_facing
from sprite_gen.video import facing as facing_mod
from .xai import (
API_BASE, AUTH_ENV, AUTH_SOURCE_API_KEY, AUTH_SOURCE_GROK_LOGIN,
HTTP_TIMEOUT_SECONDS, GROK_REFRESH_COMMAND, GROK_REFRESH_WHERE, GROK_LOGIN_COMMAND,
- NO_ANSWER, Credential, HttpCall, TransportError, grok_home, resolve_credential, http_json, no_answer,
+ NO_ANSWER, Credential, HttpCall, TransportError, grok_home, resolve_credential, http_json, no_answer, post,
read_whole, time_left,
)
@@ -108,16 +109,14 @@ POLL_INTERVAL_SECONDS = 4.0
# limit gets the id back when it sets the timeout under that limit. The POST is not cut by it — its
# answer is the one way to the id; an answer that comes after the whole timeout ends the run at once.
POLL_TIMEOUT_SECONDS = int(os.environ.get("SPRITE_GEN_VIDEO_TIMEOUT_SECONDS", "600"))
-# A poll xAI throttles (429) or fails on its own side (5xx), or one that gets no answer it can read (the
-# connection failed or timed out, the answer broke on the way or was not JSON — xai.TransportError), is
-# asked again, on the same request: the POST was accepted, so a
-# new submission would buy the clip twice, and a GET buys nothing. The wait doubles from
-# POLL_INTERVAL_SECONDS while the polls fail, up to the ceiling.
-POLL_RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
-POLL_BACKOFF_MAX_SECONDS = 60.0
+# A poll xAI throttles (429) or fails on its own side (5xx, `retry.GET_AGAIN`), or one that gets no answer
+# it can read (the connection failed or timed out, the answer broke on the way or was not JSON —
+# xai.TransportError), is asked again, on the same request: the POST was accepted, so a new submission
+# would buy the clip twice, and a GET buys nothing. The wait doubles while the polls fail
+# (`retry.backoff`, the wait every direct provider call asks again after: 8 s, 16 s, … up to a minute).
# A clip the poll says is done is made, and may be billed: its request_id is the one way back to it. A
# download that gets no answer it can read, or that the clip's host refuses with one of
-# POLL_RETRY_STATUSES, is downloaded again after the polls' doubling wait (8 s, then 16 s), up to
+# `retry.GET_AGAIN`, is downloaded again after the same doubling wait (8 s, then 16 s), up to
# DOWNLOAD_ATTEMPTS downloads in all, within the poll timeout. One still failing, one refused with
# another status, bytes that are not an mp4, or a done poll that names no URL to download, end the run
# unfinished on that request_id: `video-resume` polls it again for a fresh URL, where a new submission
@@ -519,8 +518,17 @@ def _submit_poll_publish(
announce_api_billing(verb, AUTH_ENV,
f"{f' ({priced})' if priced else ''} — "
f"`{GROK_LOGIN_COMMAND}` signs your Grok subscription in.")
- started = time.monotonic()
- status, reply = call("POST", f"{API_BASE}/videos/{endpoint}", credential.token, body)
+ sent: list[float] = []
+
+ def send(*args: Any) -> tuple[int, Any]:
+ sent.append(time.monotonic())
+ return call(*args)
+
+ # A refusal xAI documents as a request not taken (429) is sent again (`retry`); the poll timeout counts
+ # from the send it answered.
+ status, reply, _sends = post(send, f"{API_BASE}/videos/{endpoint}", credential.token, body, who="xai", label=verb,
+ sleep=sleep)
+ started = sent[-1]
if status in (401, 403):
raise SystemExit(
f"{verb}: xAI rejected the credential ({credential.source}) with HTTP {status}: {_error_detail(reply, credential.token)}\n"
@@ -615,7 +623,7 @@ def _poll_publish(
if lost is not None:
polls_unanswered += 1
failed_in_a_row += 1
- elif http in POLL_RETRY_STATUSES:
+ elif http in retry.GET_AGAIN:
polls_refused += 1
failed_in_a_row += 1
elif http in (401, 403):
@@ -637,8 +645,7 @@ def _poll_publish(
)
else:
failed_in_a_row = 0
- wait = (min(POLL_INTERVAL_SECONDS * 2 ** failed_in_a_row, POLL_BACKOFF_MAX_SECONDS) if failed_in_a_row
- else POLL_INTERVAL_SECONDS)
+ wait = retry.backoff(failed_in_a_row) if failed_in_a_row else POLL_INTERVAL_SECONDS
if time.monotonic() + wait >= deadline:
# The next poll would leave no time to read its answer: the run ends here, not at the deadline.
if failed_in_a_row:
@@ -681,8 +688,8 @@ def _poll_publish(
raise unfinished(f"is done, but its download brought {len(data)} bytes that are not an mp4 (no ftyp box); "
f"the clip is made and may be billed — {_ask_again(request_id, out)}", http, poll_status, None,
{"http": None, "error": "not an mp4 (no ftyp box)", "bytes": len(data)})
- again = said is not None or refused in POLL_RETRY_STATUSES
- wait = POLL_INTERVAL_SECONDS * 2 ** downloads
+ again = said is not None or refused in retry.GET_AGAIN
+ wait = retry.backoff(downloads)
out_of_time = time.monotonic() + wait >= deadline # the next download would leave no time to read it
if not again or downloads == DOWNLOAD_ATTEMPTS or out_of_time:
if said is not None:
@@ -1101,29 +1108,20 @@ def _build_resume_parser() -> argparse.ArgumentParser:
return parser
-def _run_kwargs(parser: argparse.ArgumentParser, runner: Callable[[argparse.Namespace], int], kwargs: dict[str, object]) -> int:
- known = {action.dest for action in parser._actions if action.dest != "help"}
- unexpected = set(kwargs) - known
- if unexpected:
- raise TypeError(f"unexpected keyword argument(s): {', '.join(sorted(unexpected))}")
- namespace = argparse.Namespace(**{dest: kwargs.get(dest, parser.get_default(dest)) for dest in known})
- return runner(namespace)
-
-
def run(**kwargs: object) -> int:
- return _run_kwargs(_build_parser(), _run, kwargs)
+ return _run(namespace_from_kwargs(_build_parser(), kwargs))
def run_extend(**kwargs: object) -> int:
- return _run_kwargs(_build_extend_parser(), _run_extend, kwargs)
+ return _run_extend(namespace_from_kwargs(_build_extend_parser(), kwargs))
def run_edit(**kwargs: object) -> int:
- return _run_kwargs(_build_edit_parser(), _run_edit, kwargs)
+ return _run_edit(namespace_from_kwargs(_build_edit_parser(), kwargs))
def run_resume(**kwargs: object) -> int:
- return _run_kwargs(_build_resume_parser(), _run_resume, kwargs)
+ return _run_resume(namespace_from_kwargs(_build_resume_parser(), kwargs))
def main(argv: list[str] | None = None) -> int:
diff --git a/sprite_gen/gen/xai.py b/sprite_gen/gen/xai.py
index ae10174..5fa4957 100644
--- a/sprite_gen/gen/xai.py
+++ b/sprite_gen/gen/xai.py
@@ -18,7 +18,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable
-from . import refusal
+from . import refusal, retry
API_BASE = "https://api.x.ai/v1"
AUTH_ENV = "XAI_API_KEY"
@@ -132,6 +132,16 @@ def resolve_credential(*, env: dict[str, str] | None = None, now: datetime | Non
HttpCall = Callable[[str, str, str, dict | None], tuple[int, Any]]
+
+def post(call: HttpCall, url: str, token: str, body: dict, *, who: str, label: str,
+ sleep: Callable[[float], None] | None = None) -> tuple[int, Any, int]:
+ """POST `body` with `call` (as http_json), and again after a refusal `retry` sends again: (status, answer,
+ sends). xAI documents 429 alone as a request not taken, and no retry-after, so http_json keeps no headers."""
+ status, reply, _headers, sends = retry.ask(lambda: (*call("POST", url, token, body), None), provider="xai",
+ who=who, label=label, sleep=sleep, kind=refusal.provider_code)
+ return status, reply, sends
+
+
TRANSPORT_FAILED = "xai: request failed or timed out; no automatic retry (the server may have accepted it)"
NOT_JSON = "xai: response was not valid JSON"
@@ -207,6 +217,17 @@ def read_whole(response: http.client.HTTPResponse, timeout: float, deadline: flo
return data
+def error_body(refused: urllib.error.HTTPError, timeout: float = HTTP_TIMEOUT_SECONDS, deadline: float | None = None) -> Any:
+ """The body of a refusal, read whole (read_whole): its JSON, or its text as `refusal.RawBody`. A refusal's
+ status alone is not an answer read whole: a body broken on the way raises what broke it (one of NO_ANSWER),
+ which every direct provider transport (`xai`, `anthropic_api`, `openai_provider`) takes as no answer."""
+ raw = read_whole(refused.fp, timeout, deadline).decode("utf-8", "replace")
+ try:
+ return json.loads(raw)
+ except json.JSONDecodeError:
+ return refusal.RawBody(raw)
+
+
def http_json(method: str, url: str, token: str, body: dict | None = None, *, timeout: float = HTTP_TIMEOUT_SECONDS,
deadline: float | None = None) -> tuple[int, Any]:
"""One request, its JSON answer read whole. `timeout` bounds each wait on the connection. A `deadline`
@@ -226,14 +247,9 @@ def http_json(method: str, url: str, token: str, body: dict | None = None, *, ti
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
raise TransportError("response was not valid JSON", NOT_JSON) from exc
except urllib.error.HTTPError as exc:
- # A refusal's status alone is not an answer read whole: its body broken on the way is no answer too.
try:
- raw = read_whole(exc.fp, timeout, deadline).decode("utf-8", "replace")
+ return exc.code, error_body(exc, timeout, deadline)
except NO_ANSWER as cut:
raise no_answer(cut) from cut
- try:
- return exc.code, json.loads(raw)
- except json.JSONDecodeError:
- return exc.code, refusal.RawBody(raw)
except NO_ANSWER as exc:
raise no_answer(exc) from exc
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index ef12ebc..0dbcacb 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -3,8 +3,9 @@
For every (direction, state) pair: canvas -> `sprite-gen video` -> frames -> loop.
Clip generation is rate-limited by the xAI team quota (2 requests/second measured
-2026-09-08: five parallel POSTs produced two HTTP 429s), so starts are staggered
-and a 429 gets a bounded, logged retry. Stages are idempotent — an item whose
+2026-09-08: five parallel POSTs produced two HTTP 429s), so starts are staggered;
+a 429 is sent again by `sprite-gen video` itself (`gen.retry`), never by the batch
+on top of it. Stages are idempotent — an item whose
clip already exists reuses it unless `--force` — and a failure stops only that
item, never the batch. The batch ends with `set.report.json` and `table.md`; an
item that failed is listed with its stage and error, never silently dropped.
@@ -60,7 +61,6 @@ PINNED_LOOP_STATES = frozenset({"idle", "attack"})
# States filmed as a fast action (`ACTION_COMMON_TEXT`): crisp frames, what they hold kept inside
# the frame, and no "evenly paced" line.
ACTION_TEXT_STATES = frozenset({"attack"})
-RETRY_BACKOFF_SECONDS = (15, 30)
def duration_for(state: str, requested: int | None) -> int:
@@ -735,19 +735,12 @@ def run_item(
if reuse_clip:
result["clip"] = {"reused": True}
else:
- attempts: list[int] = []
- for attempt in range(1 + len(RETRY_BACKOFF_SECONDS)):
- _staggered_start(gap)
- pin = {"last_frame": canvas_png} if pins_last_frame(state, direction) else {}
- rc = video_runner(canvas_png, prompt, clip, clip_report, duration=duration, resolution=resolution, log=item_dir / "clip.log", **pin)
- attempts.append(rc)
- if rc == 0 and clip.exists():
- break
- text = (item_dir / "clip.log").read_text(encoding="utf-8", errors="replace") if (item_dir / "clip.log").exists() else ""
- if "HTTP 429" in text and attempt < len(RETRY_BACKOFF_SECONDS):
- time.sleep(RETRY_BACKOFF_SECONDS[attempt])
- continue
- break
+ # One run of `sprite-gen video`: a 429 is sent again inside it (`gen.retry`), so a second run here
+ # would be a second retry loop on top of the first, each of its POSTs a request.
+ _staggered_start(gap)
+ pin = {"last_frame": canvas_png} if pins_last_frame(state, direction) else {}
+ attempts = [video_runner(canvas_png, prompt, clip, clip_report, duration=duration, resolution=resolution,
+ log=item_dir / "clip.log", **pin)]
result["clip"] = {"attempts": attempts, "duration": duration, "last_frame": pins_last_frame(state, direction)}
if attempts[-1] != 0 or not clip.exists():
raise SystemExit(f"clip generation failed after {len(attempts)} attempt(s); see {item_dir / 'clip.log'}")