Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video): video-resume asks again for an unfinished generation by its id; a lost or credential-rejected poll leaves the id
Soohong Kim474a50de7e6e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 77c2628..c4a18a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,9 +4,13 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased-- **Fix: a poll xAI answers 429 or 5xx asks the same request again — the clip is bought once.** `video`, `video-extend` and `video-edit` ended the run on any non-2xx poll, after xAI had accepted the request and may bill it, and the line read `(HTTP 429)` — what `video-set`, and any caller that backs off on a refused submission, answers by submitting the clip again: a second clip paid for, the first never published. A poll answered `429`, `500`, `502`, `503` or `504` is now asked again on the same `request_id`, after a wait that doubles from 8 s up to 60 s while the polls are refused and goes back to 4 s on an answer; a stderr note says each, the status in plain digits. The poll timeout (`SPRITE_GEN_VIDEO_TIMEOUT_SECONDS`) still bounds the whole poll: no wait runs past it, a pending poll's last wait included, and one last poll is asked at it. A refused POST is still never sent again, and a `400`, `401` or `404` poll still ends the run with its status.+- **Fix: a poll xAI answers 429 or 5xx asks the same request again — the clip is bought once.** `video`, `video-extend` and `video-edit` ended the run on any non-2xx poll, after xAI had accepted the request and may bill it, and the line read `(HTTP 429)` — what `video-set`, and any caller that backs off on a refused submission, answers by submitting the clip again: a second clip paid for, the first never published. A poll answered `429`, `500`, `502`, `503` or `504` is now asked again on the same `request_id`, after a wait that doubles from 8 s up to 60 s while the polls are refused and goes back to 4 s on an answer; a stderr note says each, the status in plain digits. The poll timeout (`SPRITE_GEN_VIDEO_TIMEOUT_SECONDS`) still bounds the whole poll: no wait runs past it, a pending poll's last wait included, and one last poll is asked at it. A refused POST is still never sent again, and a `400` or `404` poll still ends the run with its status (a `401` or `403` poll is unfinished, below).- **Output change: a generation the poll timeout cut short is unfinished, named by its `request_id`.** Polls still pending or still refused at the timeout end the run with a line that names `request_id=<id>`, says the generation may still finish and be billed, and carries no `(HTTP <n>)`, a refusal line's status — a caller that reads `(HTTP 429)` there sends the request again, unbilled only when it was refused. The pending line keeps its front (`still 'pending' after N polls — poll timeout;`). With `--report` the run leaves a `sprite-gen-video-unfinished` report there (`verb`, `auth_source`, `model`, `request_id`, `out`, `polls`, `polls_refused`, `last_poll`, `elapsed_seconds`) and prints nothing on stdout; Python callers catch `GenerationUnfinished`, a `SystemExit`. The success report gains `polls_refused`, how many of its `polls` xAI answered 429 or 5xx (docs/video.md, An unfinished generation).-- **`tests/gen/test_video.py`** scripts the polls: each of the five statuses refused twice, then pending, then done, is asked on the one request with waits 8, 16, 4 and published with `polls_refused` 2; polls refused until a 300 s timeout wait 8, 16, 32, 60 × 4 and 4, ask a ninth poll at the timeout and end unfinished with no `(HTTP n)` and no `HTTP 429` on stderr; a pending timeout names the request; a 400, 401 or 404 poll ends at once; a refused POST is sent once; the CLI leaves the unfinished report and an empty stdout. The 500-poll case of the failure table is a 404 now, the status that still ends a run.+- **`tests/gen/test_video.py`** scripts the polls: each of the five statuses refused twice, then pending, then done, is asked on the one request with waits 8, 16, 4 and published with `polls_refused` 2; polls refused until a 300 s timeout wait 8, 16, 32, 60 × 4 and 4, ask a ninth poll at the timeout and end unfinished with no `(HTTP n)` and no `HTTP 429` on stderr; a pending timeout names the request; a 400 or 404 poll ends at once; a refused POST is sent once; the CLI leaves the unfinished report and an empty stdout. The 500-poll case of the failure table is a 404 now, the status that still ends a run.+- **New verb: `video-resume` asks again for a generation a run left unfinished — by its `request_id`, with no new POST.** A run cut short named the request to ask for again, but no verb could ask for it: a caller had to submit the clip again, a second purchase, or give the clip up. `sprite-gen video-resume --request-id <id> --out clip.mp4 [--report r.json]` polls `GET /v1/videos/{id}` as the generating verbs do — the same retries, backoff and poll timeout — then downloads, verifies and publishes the clip. Nothing is submitted, so nothing is bought twice and the `XAI_API_KEY` route prints no charge notice. Its report is a `sprite-gen-video-report` with `mode: "resume"`, the same `request_id`, `inputs: {}` and `duration_requested: null`; cut short again it is unfinished on the same id, `verb: "video-resume"`, `model: null`; an id xAI does not know ends with its `(HTTP 404)`. The id is refused before any call unless it is letters, digits, `.`, `_` and `-`. A resumed clip is checked as an mp4 only — `video-extend`'s length rule needs the input clip (docs/video.md, `sprite-gen video-resume`).+- **Fix: a poll that gets no answer, or whose credential xAI rejects, leaves the request's id.** After xAI had accepted the request, a poll whose connection failed or timed out ended the run with the transport's line and no `request_id`, and a poll answered `401` ended it with its status. A poll that gets no answer is a GET, which buys nothing, so it is now asked again with the refused polls' backoff (a refused poll and a lost one are two failures in a row) and a stderr note, `poll N of generation <id> got no answer (<reason>); asking again in 8s`; lost until the poll timeout, the run is unfinished. A poll answered `401` or `403` — the credential stopped working after the POST, typically an expired login — ends the run unfinished at once, naming the credential's fix (refresh the grok login, or check `XAI_API_KEY`) before the request to ask for. A POST that gets no answer ends as before: no `request_id` came back. `xai.http_json` raises `xai.TransportError` for a request that got no answer, still a `SystemExit` with the same line, the socket's words in `reason`.+- **Output change: the unfinished line names the command that asks again; reports count the polls that got no answer.** The line reads ``ask for request_id=<id> again with `sprite-gen video-resume --request-id <id> --out <out>` instead of submitting a new request``, `request_id=<id>` kept as it was. The success and unfinished reports gain `polls_unanswered`, how many of `polls` got no answer, each asked again; the unfinished report's `last_poll` gains `error`, what the socket said, when its last poll got none (`http` then `null`).+- **`tests/gen/test_video.py`** asks again by id and loses polls: `xai.http_json` raises `xai.TransportError` with the old line for a DNS failure, a timeout and a reset; lost, pending, refused, lost, done is asked on the one request with waits 8, 4, 8, 16 and published with `polls_unanswered` 2; lost until a 30 s timeout waits 8, 16, 6 and ends unfinished with `last_poll.error`; a lost POST is sent once and is not unfinished; a 401 or 403 poll, on the login or on the key, ends unfinished at once naming its fix; `video-resume` polls with no POST and announces no charge, ends unfinished on the same id when refused, lost or pending past the timeout or when its credential is rejected, ends with `(HTTP 404)` for an unknown id, refuses eight ids that cannot be one before any call, and its CLI writes the resume report, the unfinished report and an empty stdout; the unified CLI routes it under `gen`.- **Output change: an `openai` image report carries the response's rate-limit headers — `extra.rate_limit`.** The provider dropped the response headers, so what the account may spend per minute and has left could not be read off real traffic. `extra.rate_limit` now holds every `x-ratelimit-*` header the response carried, names lower-cased and values as sent, and `{}` when none came (docs/gen.md). `openai_provider.http_image` returns the response headers as a third value.- **`tests/gen/test_openai_provider.py`** answers with headers: the report holds exactly the `x-ratelimit-*` ones among others of any case, and `{}` for a response without any.diff --git a/SKILL.md b/SKILL.mdindex 960ac7d..44c1e91 100644--- a/SKILL.md+++ b/SKILL.md@@ -100,6 +100,7 @@ hold the arms still, and check the loop with `handed-check --state walk`.| GPT image sprites | `prepare`, `gen-set --provider codex`, `extract`, compose and QA | [atlas-workflow](docs/atlas-workflow.md) || Standalone video / animate a still, pin a last frame, reference images | `video` (`--image`, `--last-frame`, `--reference`) | [video](docs/video.md) || Continue or edit an existing clip | `video-extend`, `video-edit` | [video](docs/video.md) |+| A clip run left unfinished (its line or report names a `request_id`): ask for it again, never submit it again | `video-resume --request-id <id>` | [video](docs/video.md#sprite-gen-video-resume--ask-again-for-an-unfinished-generation) || Grok video sprites | `video-set` | [video-pipeline](docs/video-pipeline.md) || A soft part of a walk loop follows the body (a chest, a belly): an ellipse in the first cell, after `video-cycle-align` — `--read-on <sha256>` where it was read on the cut the loop was aligned from; `--stretch-floor D` to keep a least area | `video-follow` | [video-pipeline](docs/video-pipeline.md#6-follow-through--video-follow) || Where that ellipse is carried in every other cell, and what the move changes there (an arm crossing a chest moves with it; the stretch, the bend and the seam): a record and boards of every cell, nothing moved | `video-follow-inspect` | [video-pipeline](docs/video-pipeline.md#inspecting-a-follow-through--video-follow-inspect) |diff --git a/docs/README.md b/docs/README.mdindex e4c61de..dda502a 100644--- a/docs/README.md+++ b/docs/README.md@@ -79,7 +79,7 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.|---|---|| [gen.md](gen.md) | `sprite-gen gen` / `gen-set`: providers, default resolution, transparency strategy per provider, row usage || [prompt-assembly.md](prompt-assembly.md) | What the engine adds to a still or clip prompt and when: the pieces, the 2.22.0 freeze without `--handed`, what counts as already said, and the notes on the caller's own words |-| [video.md](video.md) | `sprite-gen video` / `video-extend` / `video-edit`: stills and clips to mp4 through Grok Imagine (image-to-video, last-frame pin, references, extension, editing) with the user's own credential |+| [video.md](video.md) | `sprite-gen video` / `video-extend` / `video-edit` / `video-resume`: stills and clips to mp4 through Grok Imagine (image-to-video, last-frame pin, references, extension, editing, asking again for an unfinished generation) with the user's own credential || [video-pipeline.md](video-pipeline.md) | Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch, a set's directions on one sheet || [loop-review.md](loop-review.md) | Automatic loop decisions, ambiguous gait review, visual evidence and explicit cut/alignment overrides || [loop-repair.md](loop-repair.md) | RIFE (where it runs, cost, licences, `sprite-gen rife install`, what runs without it), jump-frame repair, the jolt index and its gate, one cycle length per direction set |diff --git a/docs/video.md b/docs/video.mdindex 6a95c9a..86d915e 100644--- a/docs/video.md+++ b/docs/video.md@@ -1,6 +1,6 @@# `sprite-gen video` — image to video with your own Grok login (engine SSoT)-> Owns: `sprite-gen video` / `video-extend` / `video-edit`: stills and clips to mp4 through Grok Imagine with the user's own credential · Index: [docs/README.md](README.md)+> Owns: `sprite-gen video` / `video-extend` / `video-edit` / `video-resume`: stills and clips to mp4 through Grok Imagine with the user's own credential · Index: [docs/README.md](README.md)`sprite-gen video` animates one still into a short mp4 through **Grok Imagine**(xAI `POST /v1/videos/generations`). It is the video counterpart of@@ -9,8 +9,9 @@ on disk plus a machine-readable report. The sprite-gen skill routes standalonevideo requests here from any agent engine.The same engine also pins a **last frame**, guides a clip with **reference-images**, **extends** an existing clip (`video-extend`) and **edits** one with a-prompt (`video-edit`). The mode table below is the design memo for those modes+images**, **extends** an existing clip (`video-extend`), **edits** one with a+prompt (`video-edit`) and **asks again** for a generation a run left unfinished,+by its `request_id` (`video-resume`). The mode table below is the design memo for those modes(2026-09-13); the pipeline verbs in [video-pipeline.md](video-pipeline.md)(`video-canvas` → `video` → `video-frames` → `video-loop`, `video-set`) keepcalling `sprite-gen video --image …` exactly as before and know nothing about@@ -33,6 +34,7 @@ limits from docs.x.ai `model-capabilities/video/*` read the same day.| `video --reference X [--reference Y …]` (+ optional `--image`) | same · 1.5 (classic accepts references alone, measured 2026-09-13, but not `--image` + references) | `reference_images:[{url}…]` (+ `image{url}`) | duration, aspect, audio; resolution **480p/720p only** | 1–7 references; prompt tags `<IMAGE_n>` with `0 ≤ n < count` (0-based); `--resolution 1080p` rejected; classic + `--image` + references rejected | `reference` || `video-extend --video in.mp4 --duration N` | `POST /v1/videos/extensions` · **`grok-imagine-video` forced** (1.5 answers `400 Video extension is not supported for this model`) | `video{url}`, `duration` | duration 2–10 (extension length only; default 6). No resolution / aspect / model flags: output inherits the input's, capped at 720p | `.mp4` with an `ftyp` box; ffprobe duration 2–15 s | `extend` || `video-edit --video in.mp4` | `POST /v1/videos/edits` · **`grok-imagine-video` forced** (1.5 answers `400 Video editing is not supported for this model`) | `video{url}` | none of duration / resolution / aspect / model: output inherits the input's, capped at 720p | `.mp4` with an `ftyp` box; ffprobe duration ≤ 8.7 s | `edit` |+| `video-resume --request-id <id>` | **no POST** — `GET /v1/videos/{id}` only; the model is whatever the request was made with | — | none: the request is the one an earlier run submitted | the id is letters, digits, `.`, `_`, `-` | `resume` |Invariants:@@ -146,14 +148,18 @@ What happens, in order:API's own error text.3. `GET /v1/videos/{request_id}` every 4 s until `status` is `done`. `failed`,`expired` or a non-2xx poll fails loudly — except a poll answered `429` or `500`,- `502`, `503`, `504`: the request was accepted, so that poll is asked again on the- same `request_id` (a new POST would buy the clip twice), after a wait that doubles- from 8 s up to 60 s while the polls are refused and goes back to 4 s on an answer.- A `[video] poll N of generation <id> was refused (429); asking again in 8s` line goes- to stderr each time. The poll timeout (`SPRITE_GEN_VIDEO_TIMEOUT_SECONDS`, default- 600, counted from the POST's answer) bounds the whole poll: no wait runs past it, one- last poll is asked at it, and a generation still pending or refused then is- *unfinished* (below). No clip is written on any failure path.+ `502`, `503`, `504`, or one that gets no answer at all (the connection failed or+ timed out): the request was accepted, so that poll is asked again on the same+ `request_id` (a new POST would buy the clip twice; a GET buys nothing), after a wait+ that doubles from 8 s up to 60 s while the polls fail and goes back to 4 s on an+ answer. A `[video] poll N of generation <id> was refused (429); asking again in 8s`+ line — or `… got no answer (timed out); asking again in 8s` — goes to stderr each+ time. The poll timeout (`SPRITE_GEN_VIDEO_TIMEOUT_SECONDS`, default 600, counted+ from the POST's answer) bounds the whole poll: no wait runs past it, one last poll is+ asked at it, and a generation still pending, refused or unanswered then is+ *unfinished* (below). A poll answered `401` or `403` — the credential stopped+ working after the POST, typically a login that expired — is unfinished at once. No+ clip is written on any failure path.4. Download `video.url`, verify the bytes start with an mp4 `ftyp` box, then movethe file into `--out` atomically (`.part` staging).@@ -196,25 +202,56 @@ Same fixed classic model, same inherited resolution / aspect / length (the probe8.00 s input came back 7.71 s — the API trims the tail). Inputs over 8.7 s arerefused locally with an ffmpeg trim hint; there is no `--duration` at all.+### `sprite-gen video-resume` — ask again for an unfinished generation++```bash+sprite-gen video-resume \+ --request-id <id> \ # the request_id an unfinished run named+ --out clip.mp4 \+ [--report clip.report.json]+```++No POST: it polls `GET /v1/videos/{id}` exactly as step 3 above (the same retries,+backoff and poll timeout, counted from the first poll), then downloads, verifies and+publishes the clip as step 4. Nothing is submitted, so nothing is bought twice and the+`XAI_API_KEY` route prints no charge notice. Run it on the credential that submitted+the request — the unfinished report's `auth_source`; refresh an expired login first.++- The report is a `sprite-gen-video-report` with `mode: "resume"`, the same+ `request_id`, `inputs: {}` and `duration_requested: null`; `model` and+ `duration_reported` are what the finished poll says.+- Cut short again — the timeout, or a rejected credential — it is unfinished on the+ same id, `verb: "video-resume"` (below), and can be resumed again.+- A request xAI does not know (`404`), or one that failed or expired, ends with its+ status like any failed poll.+- The clip is checked as an mp4 (`ftyp` box) only: `video-extend`'s length rule needs+ the input clip, which this verb does not take.+- The id is refused before any call unless it is letters, digits, `.`, `_` and `-`+ (it goes into the URL path).+### The report`sprite-gen-video-report` carries `auth_source`, `model`, `mode`, `request_id`,`inputs` (local paths by role: `image`, `last_frame`, `reference_images`,`video`), `bytes`, `host`, requested/reported duration (`input_duration` forextend / edit), resolution, aspect ratio, audio flag, `elapsed_seconds`, and-`polls`, and `polls_refused` (how many of `polls` xAI answered 429 or 5xx, each asked-again). The pre-modes `image` field stays. **Tokens and download URLs are never+`polls`, `polls_refused` (how many of `polls` xAI answered 429 or 5xx, each asked+again) and `polls_unanswered` (how many got no answer, each asked again). The+pre-modes `image` field stays. **Tokens and download URLs are neverprinted or written** — only the download host (`vidgen.x.ai`).### An unfinished generation-xAI accepted the request and the poll timeout came before it ended — its polls still-pending, or still refused. It may finish and be billed, so the run ends naming the-request to ask for again, never as a refusal to send again:+xAI accepted the request and the run ended before it did — the poll timeout came with+its polls still pending, refused or unanswered, or xAI rejected the credential on a+poll. It may finish and be billed, so the run ends naming the request and the+`video-resume` command that asks for it again, never as a refusal to send again:```-video: generation <id> was accepted, but its polls were refused (last answer 429) until the poll timeout (600s, 14 polls); it may still finish and be billed — ask for request_id=<id> again instead of submitting a new request; nothing was written-video: generation <id> still 'pending' after 151 polls — poll timeout; it may still finish and be billed — ask for request_id=<id> again instead of submitting a new request; nothing was written+video: generation <id> was accepted, but its polls were refused (last answer 429) until the poll timeout (600s, 14 polls); it may still finish and be billed — ask for request_id=<id> again with `sprite-gen video-resume --request-id <id> --out /abs/clip.mp4` instead of submitting a new request; nothing was written+video: generation <id> was accepted, but its polls got no answer (last: timed out) until the poll timeout (600s, 14 polls); it may still finish and be billed — ask for request_id=<id> again with `…` instead of submitting a new request; nothing was written+video: generation <id> still 'pending' after 151 polls — poll timeout; it may still finish and be billed — ask for request_id=<id> again with `…` instead of submitting a new request; nothing was written+video: generation <id> was accepted, but xAI rejected the credential (grok-login) on poll 30 (answer 401); it may still finish and be billed — refresh the login with `grok models` run from an empty directory (e.g. `cd "$(mktemp -d)"`) or `grok login`, then ask for request_id=<id> again with `…` instead of submitting a new request; nothing was written```The line carries no `(HTTP <n>)`, the status of a refusal line (docs/gen.md): a caller@@ -226,13 +263,20 @@ same reason. With `--report` the run leaves a```json{"kind": "sprite-gen-video-unfinished", "provider": "grok-imagine", "verb": "video","auth_source": "grok-login", "model": "grok-imagine-video-1.5", "request_id": "<id>",- "out": "/abs/clip.mp4", "polls": 14, "polls_refused": 14,+ "out": "/abs/clip.mp4", "polls": 14, "polls_refused": 14, "polls_unanswered": 0,"last_poll": {"http": 429, "status": null}, "elapsed_seconds": 600.0}```-`auth_source` is the credential that submitted it — the one that can ask for it again.-A report already at that path is replaced, as on success. Every verb that polls-(`video`, `video-extend`, `video-edit`) does the same, `verb` naming it.+`last_poll` gains `"error"` (what the socket said) when the last poll got no answer,+its `http` then `null`. `auth_source` is the credential that submitted it — the one+that can ask for it again. A report already at that path is replaced, as on success.+Every verb that polls (`video`, `video-extend`, `video-edit`, `video-resume`) does+the same, `verb` naming it; a `video-resume` report's `model` is `null`.++A POST that gets no answer is not unfinished: no `request_id` came back, and the line+is the transport's own (`xai: request failed or timed out; no automatic retry (the+server may have accepted it)`). Python callers catch `xai.TransportError`, a+`SystemExit` with that line and the socket's words in `reason`.## Quotas and limitsdiff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex 698d37b..5abafa4 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -325,7 +325,7 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab_add_video,video.run,),- # Same declaration-once rule: the module owns the argument surface. Both verbs force+ # Same declaration-once rule: the module owns the argument surface. Extend and edit force# the classic model and inherit resolution/length from the input clip (docs/video.md)."video-extend": ("Continue an existing clip by N seconds via Grok Imagine (POST /v1/videos/extensions).",@@ -337,6 +337,11 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callabvideo.add_edit_arguments,video.run_edit,),+ "video-resume": (+ "Ask again for a clip a video / video-extend / video-edit run left unfinished, by its request_id (no new POST, nothing bought twice).",+ video.add_resume_arguments,+ video.run_resume,+ ),# Video -> sprite pipeline (docs/video-pipeline.md): canvas -> video -> frames -> loop, or video-set for a batch."video-canvas": ("Pad a base still into the canvas a motion state needs (tall for jumps, wide for attacks, square otherwise).",diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.pyindex 693719c..2329d46 100644--- a/sprite_gen/gen/video.py+++ b/sprite_gen/gen/video.py@@ -2,13 +2,16 @@"""Video generation through Grok Imagine (xAI `/v1/videos/*`).One call = one verified mp4 on disk. This is the engine module behind the-sprite-gen skill's standalone `video`, `video-extend` and `video-edit` commands:+sprite-gen skill's standalone `video`, `video-extend`, `video-edit` and `video-resume`+commands:- `video` `POST /v1/videos/generations` — image-to-video (`--image`), apinned last frame (`--last-frame`, alone or with `--image`) andreference-to-video (`--reference` x1..7, `<IMAGE_n>` tags, 0-based).- `video-extend` `POST /v1/videos/extensions` — continue a clip by N seconds.- `video-edit` `POST /v1/videos/edits` — change a clip with a prompt.+- `video-resume` no POST — ask again for a generation an earlier run left unfinished,+ by the `request_id` it named; nothing is bought twice.Extension and editing only work on the classic `grok-imagine-video` model (the1.5 model answers `400 … not supported for this model`, measured 2026-09-13), take@@ -44,6 +47,7 @@ import jsonimport mimetypesimport osimport re+import shleximport shutilimport subprocessimport sys@@ -62,7 +66,7 @@ from sprite_gen.video import facing as facing_modfrom .xai import (API_BASE, AUTH_ENV, AUTH_SOURCE_API_KEY, AUTH_SOURCE_GROK_LOGIN,HTTP_TIMEOUT_SECONDS, GROK_REFRESH_COMMAND, GROK_REFRESH_WHERE, GROK_LOGIN_COMMAND,- Credential, HttpCall, grok_home, resolve_credential, http_json,+ Credential, HttpCall, TransportError, grok_home, resolve_credential, http_json,)DEFAULT_MODEL = "grok-imagine-video-1.5"@@ -92,12 +96,16 @@ MODE_LAST_FRAME = "last-frame"MODE_REFERENCE = "reference"MODE_EXTEND = "extend"MODE_EDIT = "edit"+MODE_RESUME = "resume"+# What `video-resume` takes for an id: it goes into the `/videos/{id}` path, so no `/`, `?`, `#` or `%`.+REQUEST_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")POLL_INTERVAL_SECONDS = 4.0POLL_TIMEOUT_SECONDS = int(os.environ.get("SPRITE_GEN_VIDEO_TIMEOUT_SECONDS", "600"))-# A poll xAI throttles (429) or fails on its own side (5xx) is asked again, on the same request:-# the POST was accepted, so a new submission would buy the clip twice. The wait doubles from-# POLL_INTERVAL_SECONDS while the polls are refused, up to the ceiling; no wait runs past the-# poll timeout, which bounds the whole poll however its polls are answered.+# A poll xAI throttles (429) or fails on its own side (5xx), or one that gets no answer at all (the+# connection failed or timed out), 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; no wait runs past the poll timeout,+# which bounds the whole poll however its polls are answered.POLL_RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})POLL_BACKOFF_MAX_SECONDS = 60.0# Every mp4/mov starts with a size-prefixed `ftyp` box: bytes 4..8 spell it.@@ -108,14 +116,17 @@ _FAILED_STATUSES = ("failed", "error", "expired")class GenerationUnfinished(SystemExit):- """xAI accepted the request (it may bill it) and the poll timeout came before it ended.+ """xAI accepted the request (it may bill it) and the run ended before it did: the poll timeout+ came, or xAI rejected the credential on a poll.- The line names `request_id=<id>` and carries no `(HTTP n)`, a refusal line's status: a caller- that reads `(HTTP 429)` there sends the request again, unbilled only when it was refused. This- one is asked for again by its id instead. `to_dict()` is the report the CLI leaves at `--report`."""+ The line names `request_id=<id>` and the `video-resume` command that asks for it again, and+ carries no `(HTTP n)`, a refusal line's status: a caller that reads `(HTTP 429)` there sends the+ request again, unbilled only when it was refused. `to_dict()` is the report the CLI leaves at+ `--report`."""def __init__(self, message: str, *, verb: str, request_id: str, auth_source: str, model: Any, out: Path,- polls: int, polls_refused: int, last_http: int, last_status: Any, elapsed_seconds: float) -> None:+ polls: int, polls_refused: int, polls_unanswered: int, last_http: int | None, last_status: Any,+ last_error: str | None, elapsed_seconds: float) -> None:super().__init__(message)self.verb = verbself.request_id = request_id@@ -124,8 +135,10 @@ class GenerationUnfinished(SystemExit):self.out = outself.polls = pollsself.polls_refused = polls_refused+ self.polls_unanswered = polls_unansweredself.last_http = last_httpself.last_status = last_status+ self.last_error = last_error # what the socket said when the last poll got no answerself.elapsed_seconds = elapsed_secondsdef to_dict(self) -> dict[str, Any]:@@ -139,7 +152,9 @@ class GenerationUnfinished(SystemExit):"out": str(self.out),"polls": self.polls,"polls_refused": self.polls_refused,- "last_poll": {"http": self.last_http, "status": self.last_status},+ "polls_unanswered": self.polls_unanswered,+ "last_poll": {"http": self.last_http, "status": self.last_status,+ **({"error": self.last_error} if self.last_error is not None else {})},"elapsed_seconds": round(self.elapsed_seconds, 3),}@@ -281,18 +296,27 @@ class EditRequest:model: str = CLASSIC_MODEL+@dataclass+class ResumeRequest:+ """`sprite-gen video-resume`: a generation xAI already accepted, by the request_id an unfinished run named."""++ request_id: str+ out: Path++@dataclassclass VideoResult:out: Pathbytes: int- model: str+ model: str | None # video-resume: what the poll reported, if it didrequest_id: strauth_source: strelapsed_seconds: floatpolls: int- duration_requested: int+ duration_requested: int | None # video-resume: None, this run requested nothingduration_reported: float | None = Nonepolls_refused: int = 0 # polls xAI answered 429 or 5xx, each asked again+ polls_unanswered: int = 0 # polls that got no answer (connection failed or timed out), each asked againhost: str | None = Noneimage: Path | None = Noneprompt: str = ""@@ -330,6 +354,7 @@ class VideoResult:"elapsed_seconds": round(self.elapsed_seconds, 3),"polls": self.polls,"polls_refused": self.polls_refused,+ "polls_unanswered": self.polls_unanswered,**({"extra": self.extra} if self.extra else {}),**({"facing": self.facing} if self.facing is not None else {}),}@@ -415,9 +440,17 @@ class _Published:host: str | Nonepolls: intpolls_refused: int+ polls_unanswered: intelapsed_seconds: float+def _ask_again(request_id: str, out: Path) -> str:+ # `request_id=<id>` is what a caller reads the request off the line by; the command is the same ask.+ return (f"ask for request_id={request_id} again with `sprite-gen video-resume --request-id "+ f"{shlex.quote(request_id)} --out {shlex.quote(str(out))}` instead of submitting a new request; "+ "nothing was written")++def _submit_poll_publish(*,verb: str,@@ -431,11 +464,7 @@ def _submit_poll_publish(poll_timeout: float | None,accept: Callable[[Path, dict[str, Any]], None] | None = None,) -> _Published:- """POST `body` to `endpoint`, poll `/videos/{id}`, download, verify, publish atomically.-- `accept(staged_path, final_poll)` may refuse the clip (raise SystemExit) while it is- still the `.part` file — `video-extend` measures the staged bytes with ffprobe; the- staged file is removed and `out` is never written.+ """POST `body` to `endpoint`, then `_poll_publish` the request xAI accepted.Every billed request leaves from here, which is why the API-credit notice liveshere too: one line per submitted job, whichever verb asked for it."""@@ -467,17 +496,57 @@ def _submit_poll_publish(raise SystemExit(f"{verb}: {refused.reason('generation request refused')} (HTTP {status}){refused.suffix()}: {_error_detail(reply, credential.token)}")+ return _poll_publish(+ verb=verb, request_id=str(request_id), model=body.get("model"), out=out, credential=credential, call=call,+ download=download, sleep=sleep, poll_timeout=poll_timeout, started=started, accept=accept,+ )++def _poll_publish(+ *,+ verb: str,+ request_id: str,+ model: Any,+ out: Path,+ credential: Credential,+ call: HttpCall,+ download: Callable[[str, str], bytes],+ sleep: Callable[[float], None],+ poll_timeout: float | None,+ started: float,+ accept: Callable[[Path, dict[str, Any]], None] | None = None,+) -> _Published:+ """Poll `/videos/{request_id}` until done, download, verify, publish atomically.++ `accept(staged_path, final_poll)` may refuse the clip (raise SystemExit) while it is+ still the `.part` file — `video-extend` measures the staged bytes with ffprobe; the+ staged file is removed and `out` is never written.++ The poll timeout counts from here. A run that ends before the request does — the timeout+ came, or xAI rejected the credential — raises GenerationUnfinished naming the request."""timeout = POLL_TIMEOUT_SECONDS if poll_timeout is None else poll_timeoutdeadline = time.monotonic() + timeout- polls = polls_refused = refused_in_a_row = 0+ polls = polls_refused = polls_unanswered = failed_in_a_row = 0video_url: str | None = Noneduration_reported: float | None = Nonemodel_reported: str | None = Nonefinal: dict[str, Any] = {}++ def unfinished(line: str, http: int | None, poll_status: Any, lost: str | None) -> GenerationUnfinished:+ return GenerationUnfinished(+ f"{verb}: generation {request_id} {line}", verb=verb, request_id=request_id,+ auth_source=credential.source, model=model, out=out, polls=polls, polls_refused=polls_refused,+ polls_unanswered=polls_unanswered, last_http=http, last_status=poll_status, last_error=lost,+ elapsed_seconds=time.monotonic() - started,+ )+while True:polls += 1- http, poll = call("GET", f"{API_BASE}/videos/{request_id}", credential.token, None)+ lost: str | None = None+ try:+ http, poll = call("GET", f"{API_BASE}/videos/{request_id}", credential.token, None)+ except TransportError as failed:+ lost, http, poll = failed.reason, None, Nonepoll_status = poll.get("status") if isinstance(poll, dict) else Noneif http in (200, 202) and poll_status in _DONE_STATUSES:final = poll@@ -494,10 +563,22 @@ def _submit_poll_publish(duration_reported = video.get("duration") if isinstance(video, dict) else Nonemodel_reported = poll.get("model")break- if http in POLL_RETRY_STATUSES:+ if lost is not None:+ polls_unanswered += 1+ failed_in_a_row += 1+ elif http in POLL_RETRY_STATUSES:polls_refused += 1- refused_in_a_row += 1- wait = min(POLL_INTERVAL_SECONDS * 2 ** refused_in_a_row, POLL_BACKOFF_MAX_SECONDS)+ failed_in_a_row += 1+ elif http in (401, 403):+ # The token this request was submitted with stopped working (a login expires in about six+ # hours); asking again with it changes nothing. A fresh one can ask for the same request.+ fix = (f"refresh the login with `{GROK_REFRESH_COMMAND}` run {GROK_REFRESH_WHERE} or `{GROK_LOGIN_COMMAND}`"+ if credential.source == AUTH_SOURCE_GROK_LOGIN else f"check the {AUTH_ENV} value")+ raise unfinished(+ f"was accepted, but xAI rejected the credential ({credential.source}) on poll {polls} (answer {http}); "+ f"it may still finish and be billed — {fix}, then {_ask_again(request_id, out)}",+ http, poll_status, None,+ )elif http not in (200, 202) or poll_status in _FAILED_STATUSES:# A failed poll carries `error` as an object `{code, message}`.refused = refusal.read("grok", poll)@@ -506,22 +587,23 @@ def _submit_poll_publish(f"(HTTP {http}){refused.suffix()}: {_error_detail(poll, credential.token)}")else:- refused_in_a_row = 0- wait = POLL_INTERVAL_SECONDS+ 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)now = time.monotonic()if now >= deadline:- stopped = (f"was accepted, but its polls were refused (last answer {http}) until the poll timeout "- f"({timeout:g}s, {polls} polls)" if refused_in_a_row- else f"still {poll_status!r} after {polls} polls — poll timeout")- raise GenerationUnfinished(- f"{verb}: generation {request_id} {stopped}; it may still finish and be billed — ask for "- f"request_id={request_id} again instead of submitting a new request; nothing was written",- verb=verb, request_id=str(request_id), auth_source=credential.source, model=body.get("model"),- out=out, polls=polls, polls_refused=polls_refused, last_http=http, last_status=poll_status,- elapsed_seconds=now - started,- )+ if failed_in_a_row:+ last = f"got no answer (last: {lost})" if lost is not None else f"were refused (last answer {http})"+ stopped = f"was accepted, but its polls {last} until the poll timeout ({timeout:g}s, {polls} polls)"+ else:+ stopped = f"still {poll_status!r} after {polls} polls — poll timeout"+ raise unfinished(f"{stopped}; it may still finish and be billed — {_ask_again(request_id, out)}",+ http, poll_status, lost)wait = min(wait, deadline - now)- if refused_in_a_row:+ if lost is not None:+ print(f"[{verb}] poll {polls} of generation {request_id} got no answer ({lost}); "+ f"asking again in {wait:g}s", file=sys.stderr)+ elif failed_in_a_row:# The status in plain digits: `(HTTP 429)` on this stream reads as a refused request to send again.print(f"[{verb}] poll {polls} of generation {request_id} was refused ({http}); "f"asking again in {wait:g}s", file=sys.stderr)@@ -544,8 +626,9 @@ def _submit_poll_publish(raiseos.replace(tmp, out)return _Published(- data=data, request_id=str(request_id), model=model_reported, duration_reported=duration_reported,- host=_redact_host(video_url), polls=polls, polls_refused=polls_refused, elapsed_seconds=elapsed,+ data=data, request_id=request_id, model=model_reported, duration_reported=duration_reported,+ host=_redact_host(video_url), polls=polls, polls_refused=polls_refused, polls_unanswered=polls_unanswered,+ elapsed_seconds=elapsed,)@@ -610,6 +693,7 @@ def generate_video(elapsed_seconds=published.elapsed_seconds,polls=published.polls,polls_refused=published.polls_refused,+ polls_unanswered=published.polls_unanswered,duration_requested=request.duration,duration_reported=published.duration_reported,host=published.host,@@ -690,7 +774,7 @@ def extend_video(return VideoResult(out=out, bytes=len(published.data), model=published.model or request.model, request_id=published.request_id,auth_source=credential.source, elapsed_seconds=published.elapsed_seconds, polls=published.polls,- polls_refused=published.polls_refused,+ polls_refused=published.polls_refused, polls_unanswered=published.polls_unanswered,duration_requested=request.duration, duration_reported=published.duration_reported, host=published.host,prompt=request.prompt, mode=MODE_EXTEND, inputs={"video": str(clip)}, input_duration=input_seconds,output_duration=measured.get("output"),@@ -751,13 +835,50 @@ def edit_video(return VideoResult(out=out, bytes=len(published.data), model=published.model or request.model, request_id=published.request_id,auth_source=credential.source, elapsed_seconds=published.elapsed_seconds, polls=published.polls,- polls_refused=published.polls_refused,+ polls_refused=published.polls_refused, polls_unanswered=published.polls_unanswered,duration_requested=0, duration_reported=published.duration_reported, host=published.host,prompt=request.prompt, mode=MODE_EDIT, inputs={"video": str(clip)}, input_duration=input_seconds,output_duration=measured.get("output"),)+def resume_video(+ request: ResumeRequest,+ *,+ credential: Credential | None = None,+ call: HttpCall | None = None,+ download: Callable[[str, str], bytes] | None = None,+ sleep: Callable[[float], None] | None = None,+ poll_timeout: float | None = None,+) -> VideoResult:+ """Ask again for a generation an earlier run left unfinished (`/videos/{request_id}`) and publish it.++ No POST, so nothing is bought twice and no API-credit notice is due. Polled, downloaded,+ verified and published as any clip; cut short again, it is unfinished on the same id. The+ clip is checked as an mp4 only: `video-extend`'s length rule needs the input clip."""+ call = call or http_json+ download = download or http_download+ sleep = sleep or time.sleep+ request_id = request.request_id.strip()+ if not REQUEST_ID.fullmatch(request_id):+ raise SystemExit(+ f"video-resume: --request-id takes the request_id an unfinished run named (letters, digits, '.', '_', '-'), "+ f"got {request.request_id!r}"+ )+ credential = credential or resolve_credential()+ out = request.out.expanduser().resolve()+ published = _poll_publish(+ verb="video-resume", request_id=request_id, model=None, out=out, credential=credential,+ call=call, download=download, sleep=sleep, poll_timeout=poll_timeout, started=time.monotonic(),+ )+ return VideoResult(+ out=out, bytes=len(published.data), model=published.model, request_id=published.request_id,+ auth_source=credential.source, elapsed_seconds=published.elapsed_seconds, polls=published.polls,+ polls_refused=published.polls_refused, polls_unanswered=published.polls_unanswered,+ duration_requested=None, duration_reported=published.duration_reported, host=published.host, mode=MODE_RESUME,+ )++def _print_json(payload: dict) -> None:text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"buffer = getattr(sys.stdout, "buffer", None)@@ -811,6 +932,13 @@ def add_edit_arguments(parser: argparse.ArgumentParser) -> None:_add_prompt_and_report(parser)+def add_resume_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--request-id", required=True,+ help="the request_id an unfinished video / video-extend / video-edit / video-resume run named")+ parser.add_argument("--out", required=True, type=Path, help="destination .mp4")+ parser.add_argument("--report", type=Path, help="write the sprite-gen-video-report JSON here")++def _read_prompt(args: argparse.Namespace) -> str:prompt = args.promptif args.prompt_file:@@ -863,6 +991,11 @@ def _run_edit(args: argparse.Namespace) -> int:return _publish_report(args, lambda: edit_video(request))+def _run_resume(args: argparse.Namespace) -> int:+ request = ResumeRequest(request_id=args.request_id, out=args.out)+ return _publish_report(args, lambda: resume_video(request))++def _build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(prog="sprite-gen video", description=__doc__)add_arguments(parser)@@ -881,6 +1014,12 @@ def _build_edit_parser() -> argparse.ArgumentParser:return parser+def _build_resume_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(prog="sprite-gen video-resume", description="Ask again for a generation an earlier run left unfinished, by its request_id (GET /v1/videos/{id}, no new POST).")+ add_resume_arguments(parser)+ 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@@ -902,6 +1041,10 @@ def run_edit(**kwargs: object) -> int:return _run_kwargs(_build_edit_parser(), _run_edit, kwargs)+def run_resume(**kwargs: object) -> int:+ return _run_kwargs(_build_resume_parser(), _run_resume, kwargs)++def main(argv: list[str] | None = None) -> int:return _run(_build_parser().parse_args(argv))diff --git a/sprite_gen/gen/xai.py b/sprite_gen/gen/xai.pyindex 564bc28..a745cba 100644--- a/sprite_gen/gen/xai.py+++ b/sprite_gen/gen/xai.py@@ -130,6 +130,18 @@ def resolve_credential(*, env: dict[str, str] | None = None, now: datetime | NonHttpCall = Callable[[str, str, str, dict | None], tuple[int, Any]]+TRANSPORT_FAILED = "xai: request failed or timed out; no automatic retry (the server may have accepted it)"+++class TransportError(SystemExit):+ """No HTTP answer came back: the connection failed or timed out, and the server may have taken the+ request. Still the SystemExit and line it always was; a caller that may safely ask again (a poll of+ an accepted request) catches this type. `reason` is what the socket said."""++ def __init__(self, reason: str) -> None:+ super().__init__(TRANSPORT_FAILED)+ self.reason = reason+def http_json(method: str, url: str, token: str, body: dict | None = None, *, timeout: float = HTTP_TIMEOUT_SECONDS) -> tuple[int, Any]:data = None if body is None else json.dumps(body).encode("utf-8")@@ -151,4 +163,5 @@ def http_json(method: str, url: str, token: str, body: dict | None = None, *, tiexcept json.JSONDecodeError:return exc.code, refusal.RawBody(raw)except (urllib.error.URLError, TimeoutError, OSError) as exc:- raise SystemExit("xai: request failed or timed out; no automatic retry (the server may have accepted it)") from exc+ said = exc.reason if isinstance(exc, urllib.error.URLError) else exc+ raise TransportError((str(said) or type(said).__name__)[:200]) from exc