---
name: video-api-batch-runner
description: Build safe, resumable, cost-capped video generation batch scripts for Google Gemini Omni 1.2 Flash, Kling 4.0, and Runway Gen-4 Turbo with mandatory dry-run USD previews, idempotent manifest logging, and exponential backoff polling.
---

# Safe Asynchronous Video API Batch Runner Protocol

Whenever asked to write or run code calling paid AI video APIs (Gemini Omni Flash, Kling 4.0, Runway, fal.ai), enforce ALL six engineering guardrails. The request shapes in section 2 were copied from the vendors' API docs on 2026-11-29 and have not been run against the paid APIs; re-read the current docs before the first paid run.

## 1. Mandatory `--dry-run` Default & Hard Cost Cap (`--max-usd`)
- Every generated script MUST default to `--dry-run` (or require explicit `--execute` + `--max-usd <limit>`).
- Before issuing a single HTTP POST, compute and print an exact line-item USD estimate (`shots × duration_s × unit_rate`). Abort immediately if projected spend exceeds `--max-usd`.
- Unit rates to price against, per generated second: Gemini Omni Flash `$0.07` (720p) / `$0.104` (1080p upscaled); Kling 4.0 `$0.157` (720p) / `$0.235` (1080p); Runway Gen-4 Turbo `$0.05` (silent, image-to-video only). Gemini Omni Flash and Kling 4.0 always include audio; there is no cheaper silent rate on either.
- Also print the request count: the Gemini API has no free tier and limits Tier 1 accounts to 40 requests a day.

## 2. Idempotent Manifest Persistence (`render-manifest.json`)
Never store job IDs only in RAM:
- Compute a deterministic `shot_hash` (`sha256(model + prompt + first_frame_sha + last_frame_sha + duration)`).
- Before submitting a shot, check `render-manifest.json`:
  - If status is `completed` and local MP4 exists: **skip cleanly** (zero double-billing).
  - If status is `submitted` with a saved `job_id`: **resume polling** that existing job instead of submitting a duplicate billable render.
- Write `render-manifest.json` atomically (`write temp -> rename`) immediately after receiving each `job_id`.

What counts as the `job_id` on each API:
- **Kling 4.0 on the Runway API (task-based):** `POST https://api.dev.runwayml.com/v1/image_to_video` with headers `Authorization: Bearer $RUNWAYML_API_SECRET` and `X-Runway-Version: 2024-11-06`, and a JSON body of `model: "kling_4"`, `promptImage` (required first frame, or an array with optional middle and last frames), `promptText`, `ratio` (`auto_720p` or `auto_1080p`) and `duration` (integer, 3–30). The response carries a task `id`: save it, then poll `GET /v1/tasks/{id}` until `status` is `SUCCEEDED` or `FAILED` (other values: `PENDING`, `THROTTLED`, `RUNNING`, `CANCELLED`). Result URLs are in `output[]`. Runway Gen-4 Turbo (`gen4_turbo`) uses the same task flow; copy its body fields from the Runway API reference.
- **Gemini Omni Flash in the Gemini API (response-based):** `POST https://generativelanguage.googleapis.com/v1beta/interactions` with header `x-goog-api-key: $GEMINI_API_KEY` and a JSON body of `model: "gemini-omni-1.2-flash"`, `input` (a prompt string, or an array of `{type: "image", data, mime_type}` and `{type: "text", text}` parts for a first frame) and `response_format: {type: "video", duration: "8s", resolution: "720p", aspect_ratio: "16:9", delivery: "uri"}`. The documented call returns the finished interaction in the POST response, so there is no job id to save while it renders. Write `status: "submitted"` to the manifest before the POST, then save the returned interaction `id` and the file URI found at `steps[] -> model_output -> content[] -> {type: "video", uri}` as soon as the response arrives. If a run finds `submitted` with no saved `id`, stop and ask the user before paying for that shot again.

## 3. Bounded Exponential Backoff Polling
Video renders take `30s – 240s`. Never poll in a 1-second tight loop:
- Start polling after `10s`, then back off (`10s -> 15s -> 20s -> 30s` cap) with jitter. The Runway API reference says not to expect task updates more often than once every five seconds.
- For Gemini Omni Flash with `delivery: "uri"`, the thing to poll is the file: `GET /v1beta/files/{FILE_ID}` until `state` is `ACTIVE` (`FAILED` means the generation failed). Set the HTTP client timeout on the POST itself to the same hard timeout.
- Stop cleanly after a hard timeout (`600s`) without deleting the saved `job_id` from the manifest.
- Honor `429 Retry-After` headers and cap concurrency (`MAX_CONCURRENT=2` default) so rate limits never trigger cascading retries.

## 4. Secret & Asset Hygiene
- Read API keys strictly from environment variables (`GEMINI_API_KEY`, `RUNWAYML_API_SECRET`, `FAL_KEY`)—never hardcode secrets or print them in logs. Send the Gemini key in the `x-goog-api-key` header, not in the URL query string, so it stays out of logged URLs.
- Validate every local `first_frame` / `last_frame` PNG exists and is non-empty BEFORE paying for API submission. Gemini Omni Flash renders `16:9` or `9:16` only, so reject frames in any other ratio for it; Kling 4.0 on the Runway API keeps the framing of the input image.

## 5. Immediate Local Download & Stream Verification
Download URLs returned by video APIs expire (the Runway API reference gives 24–48 hours for task output URLs). Download every completed MP4 immediately into `./renders/<shot_id>_<model>.mp4` (Gemini Omni Flash: `GET /v1beta/files/{FILE_ID}:download?alt=media`), verify `size > 50KB`, and run `ffprobe` to record real duration, resolution, frame rate, and audio presence inside `render-manifest.json`. Do not assume a frame rate for Kling 4.0; its resellers do not state one.

## 6. Clean Failure Classification
Distinguish non-retryable `400` / invalid-argument / safety-filter rejections (log verbatim error, do NOT auto-retry in a loop) from transient `502`/`503` transport hiccups (retry max 2 times with backoff). Gemini Omni Flash returns an invalid argument error for a `duration` over `15s`, and for first/last-frame interpolation over `10s`; catch both in the dry run instead.
