---
name: Varosity.ai Video Orchestration
title: Multi-Platform Video Production via Varosity (100% Unified)
description: Orchestrate all Varosity.ai platforms—video (Veo 3.1 / Kling 3.0 / Seedance / Grok Imagine), music (Suno / ElevenLabs / Lyria), voice (ElevenLabs and friends)—via a single API key and Varosity Credits. Full generate→poll→stitch flow with verified request/response shapes, provider fallback logic, rate limits, and cost math.
trigger: Agent needs multi-shot video production with audio, visual coherence, and professional branding
author: Varosity AI
version: "2.3"
updated: "2026-10-20"
source_url: https://varosity.ai/api/v1/skills/varosity-video-orchestration
local_path: ~/.varosity/skills/varosity-video-orchestration.md
tags: [varosity, video, veo, kling, seedance, grok-imagine, suno, music, voice, reference-image, multi-platform, unified]
kind: pipeline
reproducibility:
  providers:
    - { name: nano-banana / gemini-3.1-flash-image / flux-1-schnell, role: reference frame (visual anchor for consistency), endpoint: POST /api/v1/images }
    - { name: veo-3.1 / veo-3.1-lite / kling-3.0 / seedance-1.0-pro / grok-imagine-video / ws-hailuo-02, role: video shots, endpoint: POST /api/v1/video/generate }
    - { name: "GET /api/v1/jobs/{jobId}", role: "job polling (status + outputUrl + billing on first succeeded poll)", endpoint: "GET /api/v1/jobs/{jobId}" }
    - { name: suno-v4 / elevenlabs-music / lyria-2, role: music, endpoint: POST /api/music (+ POST /api/music/poll for async providers) }
    - { name: elevenlabs-tts (default voice Rachel 21m00Tcm4TlvDq8ikWAM), role: voiceover, endpoint: POST /api/tts (voices from GET /api/v1/voices) }
    - { name: "ffmpeg (local) or POST /api/v1/projects/{projectId}/stitch", role: "composite + audio mix", endpoint: "local ffmpeg / REST stitch" }
  inputs: "Stage 0 format selection + creative brief approved at Stage 0B; ONE reference image URL reused as referenceImageUrl across every shot for visual coherence; verbatim shot prompts (recorded in the brief)."
  dependencies: ["scope: generate:image", "scope: generate:video", "scope: generate:voice", "scope: generate:music", "scope: projects:stitch (server-side stitch only)", "ffmpeg (local composite path)"]
  parameters: { aspect_ratio: "9:16 or 16:9 (per platform)", durationSec: "integer, per-shot, clamped to the model's maxDurationSec", consistency: "same referenceImageUrl + verbatim prompts across shots", polling: "every 5-8s, abandon after ~4 min", audio_mix: "VO 0dB / music -17dB (volume=0.14) with 1.5s tail fade" }
  cost: "cost = registry $/s x seconds the model produces (not seconds requested); Credits price = raw price (no markup), minimum 1 cent; billed on the FIRST succeeded poll — failed renders are never billed. Worked 2-shot run below ~= $0.97 on Credits."
  example: "#reference-run"
  failure_modes:
    - "HTTP 429 rate_limited (60 generations/min per user, 100 req/min per API key) -> back off per the Retry-After header, never tight-loop"
    - "409 model_unavailable -> model is flagged unavailable in the catalog; pick the next model in the fallback chain"
    - "400 duration_exceeds_model_max -> clamp durationSec to the model's maxDurationSec from GET /api/v1/models"
    - "409 auth_not_configured (Credits balance below the estimated cost) -> top up or switch to a cheaper model (veo-3.1-lite, grok-imagine-video)"
    - "provider outage / 503 circuit_open -> use the documented fallback chain (ws-hailuo-02 -> ws-pika-2.2 -> muapi-wan-t2v), don't fail the run"
    - "skipping the Stage 0 approval gate -> wasted spend; the brief must be approved first"
---

> **Varosity runtime notes (2026-11-10.2) — these apply to every step below and win over anything older in this playbook.**
>
> - **Auth.** REST steps need a `vsk_` key (`Authorization: Bearer vsk_…`). An app signed in over OAuth (a `vso_` token) can use only the MCP server at `https://varosity.ai/api/mcp`: 29 of the 46 tools and a daily cap that starts at $5, without multi-voice assembly (`/api/v1/audio/assemble`), storyboards, brand agents, transcription, webhook changes or `govern_asset`. Keys made through agent connect have the default scopes (generate:*, projects:*, webhooks:read, credits:read); steps needing any other scope (transcription, storyboards, brands, runs, gates, webhook changes, asset governance) answer 403 until the user adds it on the API keys page. No key yet? A 401 carries `agent_connect` (get a key yourself — POST it, show your user the approval link, poll; the user only approves) and `agent_key` (a one-click key page for your user).
> - **Daily cap.** Every key has a daily spend cap. A run that costs more stops part-way with 429 `daily_cap_exceeded` — estimate first (`GET /api/v1/video/estimate` is free).
> - **Errors.** Not enough Credits (and no own provider key): video, images and music answer 409 `auth_not_configured`; `/api/tts` and storyboards answer 402 `insufficient_credits`; the other voice tools (sound effects, cloning, voice design, voice changer, transcription, dubbing) answer 409 `provider_not_configured`. A finished result the balance can't cover is 402 `insufficient_credits` (from `get_job`: `running` with that code). In every case: top up or connect a key, then retry or poll again — don't resubmit a held result. A finished video whose charge failed on our side is held with `billing_unavailable` instead (`get_job` `running`, REST `/api/v1/jobs` `rendering`): it is never charged twice and the balance is not the problem — keep polling every 30–60 s; don't call `buy_credits` and don't resubmit. A hold can still end `failed`, uncharged (render it again): a billing hold after 72 h, either hold after 1 h on Replicate- or HeyGen-routed models (their outputs expire), or if the output is gone when it would be released. 429 `rate_limited`: wait `Retry-After`, then retry. 429 `daily_cap_exceeded` (with `spent_today_cents`, `daily_cap_cents`): stop and tell the user — it resets at 00:00 UTC; retrying won't help. 400 `reference_image_unreachable`: we couldn't download the reference image and nothing was charged — host it publicly or send a `data:` URI. 400 `invalid_url` (voice tools): a URL you gave isn't public, can't be reached or answered an error, or is too large — fix the URL; retrying won't help. REST errors are `{ ok: false, error, code }`; over MCP a failed tool call says the same — as a result with `isError: true` when your client connects over HTTP and sends `MCP-Protocol-Version`, otherwise (the `@varosity/mcp-server` stdio proxy, plain JSON-RPC callers) as a JSON-RPC error; unknown tools and bad arguments are JSON-RPC `-32602`.
> - **Music.** MCP `generate_music` waits up to 90 s. If `audioUrl` is empty (`sync: false`), call `get_job` with `jobId` = the `trackId` every ~15 s until it succeeds (REST, with a `vsk_` key: `POST /api/music/poll { trackId }`). It is charged once, when ready; a track unfinished after 30 min is reported failed and not charged.
> - **Retries.** An `Idempotency-Key` header blocks a repeat sent while the first is still running on video generation (`/api/v1/video/generate`, `/api/generate`), images (`/api/v1/images` and its aliases), voice (`/api/tts`, `/api/v1/tts`), music (`/api/music`, `/api/v1/music`), `/api/v1/sfx` and `/api/v1/audio/assemble` — that repeat gets 409 `idempotency_in_flight` (retry shortly for the first result); a key reused on a different endpoint gets 409 `idempotency_key_reused`; 409 `idempotency_result_lost` means the first request already ran (and may have been charged) but its response was lost — it is not run or charged again under that key, so do not resend with a new key unless the user wants a second paid generation. Elsewhere, wait for the first call to finish before retrying.
> - **Keep your files.** A video's `outputUrl` is the provider's own link, not Varosity storage: Replicate deletes outputs after about an hour and other providers expire them later — download each clip as soon as its job succeeds, and stitch within the hour if any clip came from a Replicate-routed model (stitching downloads the clips). Images, voice, ElevenLabs Music and stitched project renders are stored by Varosity.
> - **Veo 3.1** (`veo-3.1`, `veo-3.1-quality`, `veo-3.1-lite`) keeps its ids and prices; all three tiers now run on Varosity credits only (no own-key route), always with audio, 1080p only on 8-second clips.
> - **Tell your user** which model made each result and what it cost, from the response: `cost_cents` (REST images), `costCents` (MCP images, music and `generate_voice`, video jobs), `totalCostCents` (assemble). On the user's own provider key there is no Varosity charge — say so.


> ⚡ **Maintained by Varosity AI.** The `refresh_skills` MCP tool with `slug: "varosity-video-orchestration"` returns the latest version of this skill (it also lives at https://varosity.ai/api/v1/skills/varosity-video-orchestration).
> Manual update: `curl -s https://varosity.ai/api/v1/skills/varosity-video-orchestration > <your-runtime-skills-path>/varosity-video-orchestration.md`

## 🤖 AUTONOMOUS AGENT EXECUTION RULES (read first, always apply)

You are an **autonomous agent**. These rules override all other instructions in this skill:

1. **Present the format selector first (Stage 0).** Before writing a brief or calling any tool, show the content format menu and wait for a reply. This single choice directs all downstream decisions.
2. **Draft a creative brief (Stage 0A).** Using the chosen format, write concept, shots, visual mood, model, and cost.
3. **Generate reference image candidates when the look matters.** If a product, character or brand must look a certain way, call `pick_reference_images` (MCP) or `POST /api/v1/images` once per project (never per shot) to produce 3 visual options. A text prompt alone is enough for a first clip.
4. **Stop once — at the approval gate (Stage 0B).** Present the creative brief (+ the 3 reference images, if you made them). Wait for reply before proceeding.
5. **After approval, execute without stopping.** The required sequence after approval (MCP surface):
   ```
   create_project → generate_video (all shots, same project_id) → get_job (poll all) → render_project / stitch
   ```
   On the raw REST surface each `POST /api/v1/video/generate` call auto-creates its own single-shot project — see "Compositing" for what that means for stitching.
6. **For multi-shot campaigns:** submit every shot with the SAME approved `referenceImageUrl`. Do not pause between shots.
7. **Cost transparency:** State the estimated cost inside the Stage 0B approval card. Do not ask again after approval.

# Varosity.ai Video Orchestration

**100% Varosity.ai-powered production pipeline** that orchestrates all providers through a single Varosity API key and unified credit system.

## Single Source of Truth

```
ONE Varosity API Key → Access ALL Platforms
├── Video Generation (Veo 3.1, Kling 3.0, Seedance, Grok Imagine, Hailuo, Pika, LTX …)
├── Music Generation (Suno v4, ElevenLabs Music, Lyria 2)
├── Voice Synthesis (ElevenLabs, OpenAI TTS, Deepgram, Cartesia, Fish Audio)
├── Image Generation (Nano Banana family, Flux, Recraft, GPT Image 2 …)
├── Composite Rendering (server-side stitch OR local ffmpeg)
└── Billing: Single Varosity Credits Pool (BYOK optional per provider)
```

**No separate API keys, no separate billing.** Everything flows through Varosity's unified interface.

---

## Auth & Setup (everything needed for the first successful call)

```
Base URL:  https://varosity.ai
Header:    Authorization: Bearer vsk_<your_token>       (every call)
           Content-Type: application/json               (every POST)
Optional:  Idempotency-Key: <any-unique-string>         (safe retries — a retry
           with the same key replays the original response instead of re-billing)
```

- Mint tokens at `https://varosity.ai/app/keys/api-keys`. Token format: `vsk_` + alphanumeric.
- **Scopes** (a 403 naming a scope means your token lacks it — mint one with the right scopes):

| Endpoint | Required scope |
|---|---|
| `POST /api/v1/images` (aliases: `/api/v1/image`, `/api/v1/image/generate`) | `generate:image` |
| `POST /api/v1/video/generate` | `generate:video` |
| `GET /api/v1/jobs/{jobId}` | any (bearer or session) |
| `POST /api/music`, `POST /api/music/poll` | `generate:music` |
| `POST /api/tts`, `GET /api/v1/voices` | `generate:voice` |
| `POST /api/v1/projects/{projectId}/stitch` | `projects:stitch` |

- Discover the live catalog any time: `GET /api/v1/models` (returns `id`, `kind`, `pricePerSec`, `maxDurationSec`, `aspectRatios`, `nativeAudio`, `unavailable`, `status`, `sunsetDate`). **Always trust the catalog over any table in this document** — availability and pricing change.

## Rate Limits (and how to back off)

| Limit | Window | Keyed by | Applies to |
|---|---|---|---|
| 60 requests | 1 min (sliding) | user | generation endpoints (`/api/v1/images`, `/api/v1/video/generate`, music, tts) |
| 100 requests | 1 min (sliding) | API key | every bearer-authenticated request |
| 60 requests | 1 min (sliding) | user | Credits-funded generations (flat abuse guard on the platform-billing path) |

Exceeding a limit returns **HTTP 429**:

```json
{ "ok": false, "error": "Too many requests. Please retry after the reset time.", "code": "rate_limited" }
```

with headers `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (epoch ms) and `Retry-After` (seconds). **Back off for `Retry-After` seconds and retry — do not tight-loop.** For batch submits, pace shot submissions ~1/s; polling `GET /api/v1/jobs/{id}` every 5–8s stays comfortably inside the per-key limit for up to ~8 concurrent shots.

---

## Model Catalog (verified against the live registry, 2026-07-14)

Prices are raw BYOK $/s; **Credits price = raw price** (min 1¢). Confirm with `GET /api/v1/models` — `unavailable: true` models reject immediately with `409 model_unavailable`.

### Video — recommended lineup

| modelId | $/s | Max s | Audio | Best for |
|---------|-----|-------|-------|----------|
| `veo-3.1` | 0.15 | 8 (4/6/8) | ✅ | **Recommended default** — best lip sync, synced audio, talking heads; 720p or 1080p |
| `veo-3.1-quality` | 0.40 | 8 (4/6/8) | ✅ | State-of-the-art fidelity, native audio — hero shots |
| `veo-3.1-lite` | 0.05 | 8 (4/6/8) | ✅ | Cheapest Veo — drafts + high-volume iteration |
| `kling-3.0` | 0.168 | 10 (5/10) | ✅ | Cinematic — multi-shot consistency, action, wide shots; native audio on by default and included in the price |
| `flux-3-max` | 0.17 | 20 (5–20) | ✅ | BFL video with native audio (Oct 2026) — 720p; 16:9/9:16/1:1/21:9 |
| `vidu-q4` | 0.0665 | 16 (3–16) | ✅ | Vidu Q4 (Oct 2026) — image-to-video only (needs a start frame), 720p, audio always on |
| `ws-kling-4.0` | 0.157 | 30 (3–30) | ✅ | Newest Kling (Oct 2026) via WaveSpeed — 720p, native audio, single takes up to 30s; 16:9/9:16/1:1/21:9. Slow (about 10 min for 5s, longer for longer clips) — keep polling. `kling-4.0` on fal is listed but closed until fal opens it |
| `wan-3.0` | 0.10 | 30 (2–30) | ✅ | Wan 3.0 (Alibaba) via WaveSpeed — 720p, audio always on, text- or image-to-video; 16:9/9:16/1:1 |
| `seedance-2.0-mini` | 0.12 | 15 (4–15) | ✅ | Seedance 2.0 Mini via WaveSpeed — image-to-video only (needs a start frame; the clip takes its shape), 720p, half the Fast price |
| `grok-imagine-video-1.5` | 0.14 | 15 (1–15) | ✅ | Grok Imagine Video 1.5 via WaveSpeed — 720p, text-to-video only; 16:9/9:16/1:1 |
| `minimax-h3` | 0.10 | 15 (4–15) | ✅ | MiniMax H3 via WaveSpeed — 768p with generated sound, text- or image-to-video; 16:9/9:16/1:1/21:9 |
| `kling-3.0-replicate` | 0.336 | 10 (5/10) | ✅ | Same Kling via Replicate at about twice the price — fallback route only; prefer `kling-3.0` |
| `grok-imagine-video` | 0.07 | 15 | ✅ | Low-cost frontier model with native audio — $0.07/s at 720p (on Credits it always renders 720p); flexible 1–15s |
| `seedance-1.0-pro` | 0.1215 | 12 | — | Multi-shot from one prompt, 1080p; silent |
| `seedance-2.0` | 0.3024 | 15 | ✅ | Top-ranked motion/physics, camera control, follows a start frame |
| `seedance-2.0-fast` | 0.2419 | 15 | ✅ | Near-flagship Seedance at lower cost |
| `happyhorse-1.0` | 0.14 | 15 | ✅ | #1-ranked motion + prompt adherence, multilingual lip-sync |
| `ltx-video` | 0.04 | 5 (fixed) | — | Fastest drafts (`ltx-2` is paused: provider outage) |
| `wan-2.6` | 0.10 | 15 (5/10/15) | — | Open-weight option |

**Platform-funded** (no BYOK ever needed — Credits only; use as fallbacks):

| modelId | $/s | Max s | Notes |
|---------|-----|-------|-------|
| `ws-hailuo-02` | 0.0833 | 6 | Best platform default. **Fixed 6s duration** (≈ $0.50 per clip). |
| `ws-pika-2.2` | 0.04 | 10 | Fast, stylized |
| `ws-luma-ray-2` | 0.08 | 10 | Fluid cinematic motion |
| `ws-runway-gen4` | 0.056 | 10 | 5s or 10s clips (rounded up). **image-to-video ONLY** — submitting text-to-video without `referenceImageUrl` is rejected upstream ("field image is required") |
| `muapi-wan-t2v` | 0.06 | 5 (fixed) | Last-resort fallback; ≈ $0.30 per clip, 5s clips only, 16:9/9:16 |

**Deprecated / unavailable — do not select:**
- `sora-2` — **retired**: OpenAI shut the Sora 2 API down on 2026-09-24; the model is `unavailable` and requests are rejected. Use `veo-3.1` (synced audio) or `kling-3.0` (general) instead.
- `seedance-2.5` — `unavailable: true` (not on the public API yet; check `list_models` before planning around it).
- `wan-2.5`, `pika-2.2` (Replicate routes), `veo-3.1-direct`, `luma-ray-3`, `runway-gen-4.5-direct` — `unavailable: true`; the catalog's `unavailableReason` names the substitute.

### Image (for reference frames / splash frames) — $ per image

| modelId | $/img | Notes |
|---------|-------|-------|
| `flux-1-schnell` | 0.003 | Fastest/cheapest — good default for reference frames |
| `nano-banana` | 0.04 | Best image-to-image identity preservation (pass `referenceImageUrl`) |
| `gemini-3.1-flash-image` | 0.067 | Nano Banana 2 — production quality, legible in-image text |
| `gpt-image-2.5-flare` / `gpt-image-2.5-sunburst` | 0.024 | GPT Image 2.5 via WaveSpeed (Flare fast, Sunburst precision), 1K, medium quality; `providerOptions.quality` low 0.01, high 0.09, xhigh 0.16, max 0.36; an edit adds 0.015 |
| `qwen-image-3.0` | 0.03 | Qwen Image 3.0 via WaveSpeed — 2K for 3¢; edits from a reference (0.033) |
| `grok-imagine-image-2.0` | 0.08 | Grok Imagine Image 2.0 via WaveSpeed — 2K photoreal with legible short text; edits from a reference (0.09) |
| `seedream-5.0` | 0.045 | Seedream 5.0 Pro via WaveSpeed — strong prompt following, 1K; edits from a reference at the same price |
| `nano-banana-2.1` | 0.04 | Nano Banana 2.1 via WaveSpeed — newest Nano Banana, 1K; edits from a reference (0.042) |
| `gemini-3-pro-image` | 0.134 | Nano Banana Pro — recommended photoreal ceiling, 1K via Varosity |
| `gemini-3.1-flash-lite-image` | 0.034 | Ultra-fast drafts |
| `muapi-flux-dev` | 0.015 | Platform-funded (used by `pick_reference_images`) |

> **Imagen 4 is retired (Google shut it down 2026-08-17).** `imagen-4` and `imagen-4-fast` still resolve, but they are transparent ALIASES served (and billed) by `gemini-3-pro-image` / `gemini-3.1-flash-lite-image`. Use the Nano Banana ids directly in new work.

### Music ($/s) and Voice ($/s of speech, ~15 chars/s)

- **Music:** `suno-v4` flat $0.10 per song, any length 10–240 s (Suno V6 via muapi — best vocals; `tags` describe the style/genre/voice; max 240s), `elevenlabs-music` 0.0025 (= $0.15/min; max 300s; sends only the prompt and length, so put the style words in `prompt` — `tags` are ignored; commercially-licensed training data — prefer for client work), `lyria-2` flat $0.10 per request (instrumental, one 30 s clip, max 30 s). `minimax-music` is a continuation model (needs a reference song) — NOT text-to-music.
- **Voice:** `elevenlabs-tts` 0.0012 (default; = $0.08 per 1K chars; Flash/Turbo modelIds half on REST `/api/tts` and assemble — MCP doesn't forward raw ElevenLabs ids), `elevenlabs-tts-v3` 0.0012, `openai-tts-1` 0.000225, `openai-tts-1-hd` 0.00045, `deepgram-aura-2` 0.00045 (lowest latency), `cartesia-sonic-3.6` 0.000975 (Cartesia's latest; `cartesia-sonic-3` also listed), `fish-audio-tts` 0.000225 (multilingual; billed on UTF-8 bytes), `heygen-voice` 0.00045 and `heygen-voice-turbo` 0.00006 (24 preset voices; WAV). Each call or segment is billed (chars ÷ 15) s × rate as a fraction, rounded up to the cent once, 1¢ minimum (1,000 characters on elevenlabs-tts = 8¢). Default ElevenLabs voice if you omit `voiceId`: **Rachel `21m00Tcm4TlvDq8ikWAM`**.

---

## Core Promise: Visual Consistency

**Reference Image Selection** ensures the user approves the visual direction before any video is rendered:

```
User request: "Surfing boy in Hawaii"
        ↓
[STAGE 0A] Agent drafts creative brief:
  Concept, platform, shots, visual mood, model, cost
        ↓
pick_reference_images (or POST /api/v1/images ×3) → 3 candidates
        ↓
[STAGE 0B — GATE] Agent presents:
  brief summary + all 3 images + cost
  "Reply with image number + notes, or 'approved'"
        ↓ Human picks #2 + "warmer tones please"
Generate video shots (ALL with reference image #2 as referenceImageUrl)
        ↓
All shots inherit: same colors, lighting, mood, aesthetic
        ↓
Output: production-quality video
```

**Why this matters:** The human approves the concept AND the visual style before any expensive video renders are submitted. One approval interaction (about 6¢ for 3 images on muapi-flux-dev at 2¢ each; more on pricier image models) prevents a bad video render ($0.50–5) and ensures the output matches intent.

---

## 📋 MANDATORY Stage 0: Content Format Selector

**This is the first thing you present for any content request.** The answer drives model selection, aspect ratio, duration, and which pipeline stages apply. Do not call any tool until the human replies.

Present this card exactly:

```
📋 WHAT ARE WE MAKING?

FORMAT — pick one:
  A. Short-form video  (15–60s) — Reels / TikTok / Shorts
  B. Long-form video   (60s+)  — YouTube / brand film
  C. Static image              — single social post
  D. Carousel                  — multi-image swipe post

STYLE — pick one:
  1. Lifestyle / UGC      — real-feeling, human-centered, handheld energy
  2. Brand film           — cinematic, polished, deliberate
  3. Product demo         — feature-focused, clean, clear
  4. Interview / talking head — person-to-camera, dialogue, lip-sync

PLATFORM — pick one:
  → TikTok / Instagram Reels / YouTube Shorts  →  9:16
  → Instagram Feed                              →  4:5 or 1:1
  → YouTube / LinkedIn / brand.com             →  16:9

Reply with: format letter + style number + platform
Example: "A1 TikTok" or "B2 YouTube"
```

**How the answer routes downstream work:**

| Style | Recommended model | Why |
|-------|------------------|-----|
| 1 · Lifestyle/UGC | `kling-3.0` or `ws-hailuo-02` | Fluid naturalistic motion, best value |
| 2 · Brand film | `veo-3.1` (hero) or `kling-3.0` (volume) | Cinematic quality + synced audio |
| 3 · Product demo | `ws-luma-ray-2` or `ws-pika-2.2` | Clean controlled motion |
| 4 · Talking head | `veo-3.1` (best lip sync) or `seedance-2.0` | Audio-native, lip-sync |
| Budget-capped any | `veo-3.1-lite` or `grok-imagine-video` | $0.05/s or $0.07/s with native audio |

| Format | Aspect ratio | Typical duration | Stage 0A applies? |
|--------|-------------|-----------------|------------------|
| A · Short video | Per platform above | 15–60s | Yes |
| B · Long video | 16:9 | 60–180s | Yes |
| C · Static image | Per platform | n/a | No — use `POST /api/v1/images` directly |
| D · Carousel | Per platform | n/a | No — `POST /api/v1/images` × N |

For **Format C or D**, skip Stage 0A/0B entirely. Call the image endpoint with the style/platform context, present results to the human, and iterate.

---

## ⚠️ Before Any Render: Creative Brief + Approval Gate

**Before submitting ANY video generation, complete Stage 0A and Stage 0B in order.**

### Stage 0A — Write the Creative Brief

Draft the following before calling any generation tool:

- **Concept:** One sentence — what is this video about and why does it matter to the audience?
- **Platform:** Instagram Reels / TikTok / YouTube Shorts / etc.
- **Shots:** Numbered list of beats with duration and framing (e.g. "1. Couple meets at coffee shop — 4s — medium shot"). Keep each shot's `durationSec` ≤ the chosen model's `maxDurationSec`.
- **Visual mood:** 2–3 adjectives + a reference aesthetic (e.g. "warm, intimate, iPhone-video-real")
- **Model:** Which model and why (e.g. "kling-3.0 — cinematic motion at $0.168/s")
- **Estimated cost:** Σ(seconds each shot produces × model $/s), the same on Credits (see Billing)

When the look matters (a product, character or brand), generate 3 reference candidates from the brief's visual mood, once per project and never per shot — either the MCP tool:

```json
{ "name": "pick_reference_images",
  "arguments": { "prompt": "warm golden-hour beach, cinematic, film grain", "count": 3, "aspectRatio": "9:16" } }
```

(`pick_reference_images` params: `prompt` — style/mood, not action; `count?` 1–5 default 3; `aspectRatio?` default 16:9; `modelId?` default `muapi-flux-dev`. Returns `{ candidates: [{ index, imageUrl }] }`.)

…or 3 direct REST calls to `POST /api/v1/images` (schema below). If the user provided their own reference image URL upfront, skip this and use that URL. For a first clip, a text prompt alone is enough.

### Stage 0B — Approval Gate (wait for human reply)

Present this card and **do not submit any video generation until the human replies**:

```
🎬 CREATIVE BRIEF — [Project Name]

Concept: [one sentence]
Platform: [platform] | Audience: [who]
Shots:
  1. [beat — duration — framing]
  2. [beat — duration — framing]
  ...
Visual: [mood/aesthetic direction]
Model: [selected model] | Est. cost: ~$[X] Credits
Reference image options:
  [1] [image URL]
  [2] [image URL]
  [3] [image URL]

Reply with image number + any notes, or "approved" to proceed with option 1.
```

After the human replies, use the selected image URL as `referenceImageUrl` in every video generation call. Then execute the full pipeline without stopping.

---

## REST Endpoint Reference (verified request/response shapes)

Every call: `Authorization: Bearer $VSK`, `Content-Type: application/json`. All generation endpoints accept an optional `Idempotency-Key` header — retries with the same key replay the stored response instead of double-billing.

### 1. `POST /api/v1/images` — reference frames (synchronous, no polling)

Aliases: `POST /api/v1/image`, `POST /api/v1/image/generate`. Field names accept **both camelCase and snake_case** (`aspectRatio`/`aspect_ratio`, `modelId`/`model`, `referenceImageUrl`/`reference_image_url`).

```json
{
  "prompt": "Two supercars on a starting grid at golden hour, heat haze, cinematic film still",
  "modelId": "flux-1-schnell",
  "aspectRatio": "16:9"
}
```

- `prompt` 1–2000 chars (required). `modelId` defaults to `flux-1-schnell`. `aspectRatio` one of `16:9|9:16|1:1|4:5|21:9` — **defaults to `1:1`, so always set it explicitly**. Optional `referenceImageUrl` (image-to-image editing — use `nano-banana` for identity preservation), `providerOptions` (per-model knobs).

```json
{ "ok": true, "imageUrl": "https://…supabase.co/…/generated/….png", "model": "flux-1-schnell",
  "attribution": "Generated via Varosity.ai", "galleryUrl": "https://varosity.ai/app/gallery" }
```

Errors: `400 unsupported_aspect_ratio` (message lists supported ratios), `409 model_unavailable`, `429 rate_limited`.

### 2. `POST /api/v1/video/generate` — submit one shot → returns jobId

```json
{
  "prompt": "Slow push-in on two supercars on the grid, engines revving, heat shimmer, cinematic",
  "modelId": "kling-3.0",
  "aspectRatio": "16:9",
  "durationSec": 5,
  "referenceImageUrl": "https://…/generated/grid.png"
}
```

Body schema (exact):
- `prompt` string ≤2000 (required)
- `modelId` string (required — must be a `kind: "video"` model)
- `aspectRatio` `16:9|9:16|1:1|4:5|21:9`, default `16:9` — each model renders only a subset (check the model's `aspectRatios` in `GET /api/v1/models`); an unsupported value is refused with `400 unsupported_aspect_ratio` listing the supported ones
- `durationSec` integer ≥1, default 5 — **validated against the model's `maxDurationSec`** (e.g. 11s on kling-3.0 → `400 duration_exceeds_model_max`). Models with fixed `clipLengthsSec` (kling-3.0: 5 or 10; veo-3.1: 4, 6 or 8) fit other values to the nearest clip length and bill the seconds produced — send a real clip length.
- `referenceImageUrl?` url — the approved reference frame (image-to-video)
- `referenceVideoUrl?` url — performance-transfer models only (LivePortrait, Act-Two)
- `audioUrl?` url — external audio for avatar/lip-sync models (omnihuman, heygen-photo-avatar, muapi-latentsync)
- `providerOptions?` object — per-model knobs (e.g. `{"generateAudio": false}` for a silent kling-3.0 clip — on your own key only; on Credits it is dropped and audio stays on. Veo 3.1 always renders with audio)
- `authPreference?` `"byok" | "platform"` — prefer a billing path; if it can't be used, the other is tried (default: BYOK if configured, else Credits)

Success (job usually async — status `rendering`):

```json
{ "ok": true, "jobId": "8a1f2c3d-…", "projectId": "3f9c2f10-…", "status": "rendering",
  "outputUrl": null, "billingMode": "platform",
  "attribution": "Generated via Varosity.ai", "galleryUrl": "https://varosity.ai/app/gallery" }
```

Note: each REST call auto-creates a single-shot project to anchor the job (that's the `projectId` you get back). Error responses — all shaped `{ "ok": false, "error": "<message>", "code": "<code>" }`:

| HTTP | code | Meaning / action |
|------|------|------------------|
| 400 | `not_a_video_model` | You passed an image/voice/music model — the error names the right endpoint |
| 400 | `duration_exceeds_model_max` | Clamp `durationSec` to the model's max |
| 409 | `auth_not_configured` | Not enough Credits, or this model isn't offered on Credits yet — the `error` text says which: top up or connect a key, or switch model |
| 409 | `model_unavailable` | Catalog flags it unavailable — use the fallback chain |
| 409 | `provider_unavailable` | Model temporarily unavailable — switch model |
| 429 | `rate_limited` / `daily_cap_exceeded` | `rate_limited`: wait `Retry-After`, then retry · `daily_cap_exceeded`: stop and tell the user (the key's daily cap resets 00:00 UTC) · Also: Back off per `Retry-After`. |
| 503 | `circuit_open` | Provider circuit breaker tripped — retry later or fall back |

### 3. `GET /api/v1/jobs/{jobId}` — poll until done

```json
{ "ok": true, "jobId": "8a1f2c3d-…", "status": "succeeded",
  "outputUrl": "https://…/renders/shot1.mp4", "thumbnailUrl": "https://…/thumb.jpg",
  "error": null, "costCents": 63,
  "attribution": "Generated via Varosity.ai", "galleryUrl": "https://varosity.ai/app/gallery" }
```

- `status` ∈ `queued | rendering | succeeded | failed | canceled`. `succeeded` always carries `outputUrl`.
- **Polling contract:** poll every **5–8s**. Renders take 30s–3min: fast models (LTX, ws-pika) ~30s; **Kling / Veo / Seedance 60–120s**; up to ~3min under load. `rendering` past 60s is **normal, not a hang**. Give up and report failure only after **~4 minutes** of polling.
- Billing, webhook dispatch (`shot.generation.completed` / `shot.generation.failed`), and `costCents` all land on the **first `succeeded` poll** — so you must poll to completion even if you don't need the URL immediately. Failed jobs are never billed.
- A transient provider read error returns `"pollError"` alongside the last known status — just poll again.
- **Held renders:** a result with status `rendering` (MCP `get_job`: `running`) and `code: "insufficient_credits"` is a FINISHED render held for 24 hours (1 hour for providers whose files expire) until it is paid for. Stop polling, call `buy_credits` (or tell the user to add credits), then poll once more to release it. Don't resubmit.

### 4. `POST /api/music` — music track (+ `/api/music/poll` for async providers)

```json
{ "modelId": "suno-v4", "prompt": "high-energy cinematic electronic, driving percussion, no vocals",
  "durationSec": 16, "tags": ["cinematic"], "instrumental": true }
```

Body: `modelId` (required), `prompt` 3–2000 chars, `durationSec` integer 5–300 (also capped per model: suno-v4 240s / elevenlabs-music 300s / lyria-2 30s), `tags?` up to 10 strings — used by suno-v4 and lyria-2 only (elevenlabs-music ignores them; put its style in `prompt`); Suno joins all tags into its style (with `lyrics` the prompt is used only when tags is empty; without lyrics Suno writes its own unless `instrumental: true`), `instrumental?` bool, `lyrics?` ≤3000 (sung by Suno), `title?` ≤120.

Two possible success shapes — **branch on `sync`**:

```json
{ "ok": true, "trackId": "c2d4…", "audioUrl": "https://…/music.mp3", "sync": true,
  "attribution": "Generated via Varosity.ai", "galleryUrl": "https://varosity.ai/app/gallery" }
```

```json
{ "ok": true, "trackId": "c2d4…", "providerJobId": "…", "sync": false }
```

When `sync: false` (fal-routed providers, e.g. lyria-2), poll:

```
POST /api/music/poll   { "trackId": "c2d4…" }
→ { "ok": true, "status": "running" }            (keep polling every ~5s)
→ { "ok": true, "status": "succeeded", "audioUrl": "https://…/music.mp3", … }
```

Async music is charged at poll time (on success), sync at submit. Fallback: if `elevenlabs-music` returns quota/401 → retry with `suno-v4` (platform-funded, same Credits pool).

### 5. `POST /api/tts` — voiceover (synchronous) + `GET /api/v1/voices`

Enumerate valid voices first — never guess IDs:

```
GET /api/v1/voices
→ { "ok": true, "voices": [ { "voiceId": "21m00Tcm4TlvDq8ikWAM", "name": "Rachel", "category": "premade", … }, … ] }
```

```json
{ "text": "Pure performance. At the limit.", "voiceId": "21m00Tcm4TlvDq8ikWAM", "voiceModel": "elevenlabs-tts" }
```

Body: `text` 1–5000 chars (required), `voiceId?` (omit → ElevenLabs default **Rachel `21m00Tcm4TlvDq8ikWAM`**), `voiceModel?` selects the provider (`elevenlabs-tts` default, `openai-tts-1`, `openai-tts-1-hd`, `deepgram-aura-2`, `cartesia-sonic-3.6`, `fish-audio-tts`, `heygen-voice`, `heygen-voice-turbo`), `format?` (`mp3|wav|ogg|opus|aac|flac|pcm`), `speed?` 0.25–4.0 (OpenAI only), `providerOptions?`. Synchronous — no polling:

```json
{ "ok": true, "audioUrl": "https://…/voice/vo.mp3", "voiceId": "21m00Tcm4TlvDq8ikWAM",
  "modelId": "eleven_multilingual_v2", "bytes": 48213,
  "attribution": "Generated via Varosity.ai", "galleryUrl": "https://varosity.ai/app/gallery" }
```

Clone a voice: `POST /api/v1/voices` `{ "name", "sampleUrls": ["<public audio url>"] }` → `{ "ok": true, "voiceId", "provider", "name" }` — usable immediately in `/api/tts`. Then pass `"<your cloned voiceId>"` as `voiceId`; clones are private to the account that created them.

### 6. Compositing — server-side stitch OR local ffmpeg

**Server-side** (`projects:stitch` scope): stitches all rendered shots **of one project** into a single MP4, including intro/end cards and project audio tracks.

```
POST /api/v1/projects/{projectId}/stitch      (empty JSON body {})
→ { "ok": true, "renderId": "…", "outputUrl": "https://…/renders/final.mp4",
    "durationSec": 14, "totalCostCents": 105 }
```

- Every shot must already be `succeeded` — otherwise `400 shots_not_rendered` ("N shot(s) haven't rendered yet. Poll each shot to done via GET /api/v1/jobs/[shotId] before stitching.").
- **Scope caveat:** each raw-REST `POST /api/v1/video/generate` call creates its OWN single-shot project, so server stitch only helps REST callers for single-shot + card assembly. To get multiple shots into ONE project, use the **MCP surface** (`create_project` → `generate_video` with `project_id` + `shot_index` per shot → `get_job` → `render_project`/stitch). For pure-REST multi-shot runs, composite locally with ffmpeg (below) — fully self-contained and what the reference run uses.

**Local ffmpeg** (the always-works path): see step 5 of the reference run.

---

## 8-Stage Pipeline

### Stage 0: Content Format Selector (MANDATORY — present first, wait for reply)
### Stage 0A: Creative Brief Draft (video only — after Stage 0 reply)
### Stage 0B: Approval Gate (video only — wait for human reply)
(Details above. For static image or carousel: skip to `POST /api/v1/images`, skip Stages 1–7.)

### Stage 1: Initialize
- MCP: `create_project` ONCE per user request; pass its `project_id` to every shot.
- REST: nothing to do — each generate call anchors its own project.

### Stage 2: Video Generation (parallel)
- Submit all shots (~1/s pacing to respect the 60 rpm generation limit), each with the SAME approved `referenceImageUrl`, correct `aspectRatio`, and `durationSec` ≤ the model's max.
- Accounts without a plan run 2 renders at once on Varosity credits. On code `concurrency_limit` (or that message over MCP), nothing was charged: wait for a job to finish, then submit the next shot.
- Record every `jobId` (and `projectId`).

### Stage 3: Audio Generation (parallel — while clips render)
- **Music:** `POST /api/music` (suno-v4 default; tags describe the style/genre/voice; `instrumental: true` unless vocals wanted). Branch on `sync`; poll `/api/music/poll` when async.
- **Voice:** `GET /api/v1/voices` → pick `voiceId` → `POST /api/tts` (synchronous).

### Stage 4: Poll All Video Jobs
- `GET /api/v1/jobs/{jobId}` every 5–8s per job until `succeeded`/`failed`. Abandon a job only after ~4 min. Aggregate results; run the fallback protocol on any `failed` shot.

### Stage 5: Composite & Mix
- MCP/one-project: `POST /api/v1/projects/{projectId}/stitch`.
- REST multi-shot: local ffmpeg — normalize → concat → duck music under VO (music `volume=0.14`, VO `volume=1.6`, 1.5s tail fade) → mux.

### Stage 6: Branded End Card
- Generate with `POST /api/v1/images` using brand colors/tagline as the prompt (use `nano-banana` + `referenceImageUrl` of the logo for identity lock), hold it 3–4s in the concat list, or attach it as the project's end card before server stitch.

### Stage 7: Delivery
- Download the final MP4, present it to the user as native media (not a bare URL), state it was generated via Varosity.ai, and give the gallery link `https://varosity.ai/app/gallery`. Log final specs (duration, cost, models used). Ready for Postiz scheduling.

---

## Provider Fallback Protocol

When a `generate_video` / `POST /api/v1/video/generate` call fails — **never silently fail; always report which model succeeded and which failed:**

```
Attempt 1: preferred model (e.g. kling-3.0 / veo-3.1)
  409 auth_not_configured (not enough Credits, or the model isn't on Credits — see `error`), 409 provider_unavailable,
  "Exhausted balance" / "User is locked"?
    → Switch to ws-hailuo-02 (platform-funded; note: fixed 6s clips)

Attempt 2: ws-hailuo-02
  "submit failed: 4xx" / "Insufficient credits"?
    → Try ws-pika-2.2, or ws-runway-gen4 ONLY if you have a referenceImageUrl
      (it is image-to-video only)

Attempt 3: any remaining ws-* model fails?
    → muapi-wan-t2v (platform-funded, $0.06/s ≈ $0.30 per clip, 5s clips only, 16:9/9:16;
      text-to-video only: drop referenceImageUrl or it is refused with 400 reference_not_supported)

Attempt 4: muapi-wan-t2v fails?
    → Report to user: which models were tried, the exact error code for each,
      and the Credits balance hint ("check varosity.ai/app/keys")
```

**Music fallback:** `elevenlabs-music` quota/401 → `suno-v4`. **Voice fallback:** wrong/missing `voiceId` → omit it (Rachel default) or re-enumerate `GET /api/v1/voices`.

---

## Credits & Billing (exact math)

1. **Cost formula:** `raw cost = model $/s × seconds produced` (from the registry / `GET /api/v1/models`). You are charged for the seconds the model produces, not the seconds requested — e.g. Veo renders 4, 6 or 8s (a 7s request is a 6s clip), Kling 5 or 10s (1–7s → 5s, 8–10s → 10s). Images are per-image; voice is billed at ~15 characters ≈ 1 second of speech.
2. **Credits price:** platform-billed generations cost `raw` (the provider's list price, no markup), minimum 1¢. BYOK generations bill your provider account at the same raw price.
3. **When you're charged:** video — on the **first `succeeded` poll** of `GET /api/v1/jobs/{jobId}` (the response's `costCents`). Failed/canceled renders are never billed. Sync music/voice — at submit; async music — at successful poll.
4. **Pre-flight gate:** `POST /api/v1/video/generate` estimates cost up front and returns `409 auth_not_configured (not enough Credits)` if your Credits balance can't cover it — you can't accidentally start a render you can't pay for.
5. **Idempotency:** send `Idempotency-Key` on submits; retried requests replay the original response without re-billing.

### Worked cost example (45s brand film, 16:9, Credits)

| Component | Model | Duration | Raw | Credits (= raw) |
|-----------|-------|----------|-----|-----------------|
| 4 shots | `kling-3.0` @ $0.168/s | 5+10+10+10 = 35s (clips are 5s or 10s) | $5.88 | $5.88 |
| 2 shots | `veo-3.1` @ $0.15/s | 6+6 = 12s (clips are 4, 6 or 8s) | $1.80 | $1.80 |
| Music | `suno-v4` flat per song | 45s | $0.10 | $0.10 |
| Voiceover | `elevenlabs-tts` @ $0.0012/s | ~8s (120 chars) | $0.01 | $0.01 |
| Reference frame | `flux-1-schnell` | 1 image | $0.01 | $0.01 |
| **Total** | | | **$7.80** | **$7.80** |

(Stitch/composite adds no model cost. Budget guard: state this number in the Stage 0B card.)

---

## Reference run — verified API trace (2-shot promo, 16:9) {#reference-run}

> **Minimum reproducible path — needs no project tools.** This produces a finished multi-shot MP4 using ONLY the documented REST endpoints plus local ffmpeg. Real field names and response shapes, verified against the live API.

**Auth (every call):** base `https://varosity.ai`, header `Authorization: Bearer $VSK` (scopes: `generate:image`, `generate:video`, `generate:voice`, `generate:music`).

```sh
curl -s https://varosity.ai/api/v1/images \
  -H "Authorization: Bearer $VSK" -H "Content-Type: application/json" -d '{…}'
```

**1 — Reference frame (visual anchor, $0.04):** `nano-banana` — or `flux-1-schnell` (1¢) for speed, `gemini-3.1-flash-image` when the frame needs legible text.

```json
POST /api/v1/images
{ "prompt": "Two supercars on a starting grid at golden hour, engines revving, heat haze, cinematic film still",
  "modelId": "nano-banana", "aspectRatio": "16:9" }
→ { "ok": true, "imageUrl": "https://…/generated/grid.png", "model": "nano-banana",
    "attribution": "Generated via Varosity.ai", "galleryUrl": "https://varosity.ai/app/gallery" }
```

**2 — One call per shot (image→video keeps the look consistent):**

```json
POST /api/v1/video/generate            (shot 1 — $0.40 raw: 8s × $0.05)
{ "prompt": "Slow push-in on two supercars on the grid, engines revving, heat shimmer, cinematic",
  "modelId": "veo-3.1-lite", "aspectRatio": "16:9", "durationSec": 8,
  "referenceImageUrl": "https://…/generated/grid.png" }
→ { "ok": true, "jobId": "8a1f2c3d-…", "projectId": "3f9c2f10-…", "status": "rendering",
    "outputUrl": null, "billingMode": "platform", "attribution": "Generated via Varosity.ai",
    "galleryUrl": "https://varosity.ai/app/gallery" }

POST /api/v1/video/generate            (shot 2 — $0.42 raw: 6s × $0.07, native audio)
{ "prompt": "Extreme close-up of a racing tire biting asphalt at launch, smoke curling, slow motion, engine roar",
  "modelId": "grok-imagine-video", "aspectRatio": "16:9", "durationSec": 6,
  "referenceImageUrl": "https://…/generated/grid.png" }
→ { "ok": true, "jobId": "b7e9d1aa-…", "projectId": "…", "status": "rendering", … }
```

(grok-imagine-video is $0.07/s at 720p; on Credits it always renders 720p.)

**3 — Poll each job (every 5–8s; abandon after ~4 min; `failed` → fallback protocol):**

```json
GET /api/v1/jobs/8a1f2c3d-…
→ { "ok": true, "jobId": "8a1f2c3d-…", "status": "rendering", "outputUrl": null, … }
   … repeat …
→ { "ok": true, "jobId": "8a1f2c3d-…", "status": "succeeded",
    "outputUrl": "https://…/renders/shot1.mp4", "thumbnailUrl": "https://…/thumb1.jpg",
    "error": null, "costCents": 42, "attribution": "Generated via Varosity.ai",
    "galleryUrl": "https://varosity.ai/app/gallery" }
```

**4 — Audio (run while clips render):**

```json
POST /api/music
{ "modelId": "suno-v4", "prompt": "high-energy cinematic electronic, driving percussion",
  "durationSec": 16, "tags": ["cinematic"], "instrumental": true }
→ { "ok": true, "trackId": "c2d4…", "audioUrl": "https://…/music.mp3", "sync": true, … }
   (if "sync": false → POST /api/music/poll {"trackId":"c2d4…"} every ~5s until "succeeded")

GET /api/v1/voices
→ { "ok": true, "voices": [ { "voiceId": "21m00Tcm4TlvDq8ikWAM", "name": "Rachel", "category": "premade" }, … ] }

POST /api/tts
{ "text": "Pure performance. At the limit.", "voiceId": "21m00Tcm4TlvDq8ikWAM", "voiceModel": "elevenlabs-tts" }
→ { "ok": true, "audioUrl": "https://…/voice/vo.mp3", "voiceId": "21m00Tcm4TlvDq8ikWAM",
    "modelId": "eleven_multilingual_v2", "bytes": 48213, … }
```

**5 — Composite (the verified, self-contained path).** Pull each `outputUrl`, then assemble with ffmpeg — normalize (clips come back at mixed sizes), concat, duck music under the VO, mux:

```sh
# normalize each clip to a common geometry/fps
ffmpeg -i shotN.mp4 -vf "scale=1920:1080:force_original_aspect_ratio=increase,crop=1920:1080,fps=24,format=yuv420p" \
  -an -c:v libx264 -crf 19 nN.mp4
# concat (concat-demuxer list n1..nN) -> video.mp4 ; mix VO full + music ducked + tail fade:
ffmpeg -i vo.mp3 -i music.mp3 -filter_complex \
  "[0:a]volume=1.6[v];[1:a]volume=0.14,afade=t=out:st=$((DUR-1.5)):d=1.5[m];[v][m]amix=inputs=2:duration=longest:normalize=0,atrim=0:DUR[a]" \
  -map "[a]" -c:a aac mix.m4a
ffmpeg -i video.mp4 -i mix.m4a -map 0:v:0 -map 1:a:0 -c:v copy -c:a aac -shortest -movflags +faststart final.mp4
```

(Server-side alternative for shots sharing ONE project — MCP flow: `create_project` → `generate_video {project_id, shot_index}` per shot → poll → `POST /api/v1/projects/{projectId}/stitch {}` → `{ ok, renderId, outputUrl, durationSec, totalCostCents }`. The local path above needs none of that and is fully reproducible on its own.)

**6 — Determinism.** These models expose **no seed**. To reproduce: keep the `modelId`, the **verbatim** prompt strings, `durationSec`, `aspectRatio`, and the `referenceImageUrl` fixed — that yields an *equivalent* (not bit-identical) render. Don't paraphrase the prompt between runs.

**Cost (this run):** ref frame $0.04 + shot 1 (8s veo-3.1-lite) $0.40 + shot 2 (6s grok-imagine-video) $0.42 + 16s suno $0.10 (flat per song) + ~2s VO $0.01 = **$0.97, the same on Credits**.

---

## Full multi-shot example: Porsche vs Lamborghini (6 shots, 47s, 16:9)

The approved Stage 0B brief, expressed as the exact per-shot API payloads. Every shot reuses the approved reference frame; durations are lengths each model actually produces (kling-3.0 5s or 10s, veo-3.1 4, 6 or 8s).

| # | Shot (verbatim prompt) | s | modelId | Raw $ |
|---|------------------------|---|---------|-------|
| 1 | "Both pristine supercars lined up on grid. White Porsche 911 Turbo on left, vibrant yellow Lamborghini Huracán on right. Engines revving, crews visible, golden afternoon sunlight, tension building." | 5 | `kling-3.0` | 0.84 |
| 2 | "Tight side-by-side racing through hard left corner. Porsche inside line, Lamborghini defensive. Tire smoke, aggressive motion, gravel spray." | 10 | `kling-3.0` | 1.68 |
| 3 | "Aerial drone high above circuit, both cars competing. Full track layout visible, professional facility." | 6 | `veo-3.1` | 0.90 |
| 4 | "Extreme close-up of high-performance tire gripping asphalt. Smoke rising, detailed texture, slow-motion emphasis." | 6 | `veo-3.1` | 0.90 |
| 5 | "First-person POV from Porsche cockpit. Steering wheel foreground, hard braking into chicane, explosive acceleration out." | 10 | `kling-3.0` | 1.68 |
| 6 | "Both supercars neck-and-neck on main straight toward finish. Perfectly matched, trading positions, golden sunlight on polished surfaces." | 10 | `kling-3.0` | 1.68 |

Each shot is one `POST /api/v1/video/generate` call:

```json
{ "prompt": "<verbatim prompt from the table>", "modelId": "kling-3.0", "aspectRatio": "16:9",
  "durationSec": 10, "referenceImageUrl": "<approved reference frame URL>" }
```

Audio (parallel):

```json
POST /api/music
{ "modelId": "suno-v4", "prompt": "high-energy electronic racing theme, fast tempo, intense, synth drums bass strings",
  "durationSec": 45, "tags": ["high-energy electronic"], "instrumental": true }

POST /api/tts
{ "text": "Pure performance at the limit. Two supercars. One track. Victory decided by tenths.",
  "voiceId": "21m00Tcm4TlvDq8ikWAM", "voiceModel": "elevenlabs-tts" }
```

**Cost:** video $7.68 (kling 0.84 + 1.68 × 3, veo 0.90 × 2) + music (suno-v4, flat) $0.10 + VO (83 chars → 5.5 s × $0.0012 = 1¢, rounded up) = **$7.79, the same on Credits** — stated in the Stage 0B card. Poll all six jobs (Stage 4), then composite with the ffmpeg recipe (Stage 5), append the branded end card 4s (Stage 6), deliver (Stage 7).

**Output:** single ~49s MP4, 6 visually coherent shots, music + VO mixed, branded end card, ready for Postiz scheduling.

---

## Brand & Workflow Integration (optional)

- **Branding injection:** append the brand block to every shot prompt — colors (hex), aesthetic adjectives, mood/tagline, typography. Example (Magnetic): "Sage Green #06A564 + Cream #F5F1ED, premium, modern, 'Dating without the Game', trustworthy". Keep it identical across shots — it's part of the verbatim-prompt determinism contract.
- **End card with logo lock:** `POST /api/v1/images` with `"modelId": "nano-banana"` and the logo as `referenceImageUrl` preserves the mark while restyling the card.
- **Paperclip:** optionally post each stage transition as an issue comment for CEO visibility.
- **Postiz:** after delivery, stage `{ platform, video_url, caption, scheduled_time, status: "pending_approval" }` into the posting queue.

---

## Failure Modes & Troubleshooting

| Issue | Solution |
|-------|----------|
| 401 "Unauthorized" | Token missing/expired, or doesn't start with `vsk_` — check varosity.ai/app/keys |
| 403 naming a scope | Token lacks that scope — mint one with `generate:video` etc. |
| 429 `rate_limited` | 60 gen/min per user, 100 req/min per key. Wait `Retry-After` seconds, then resume. Pace batch submits ~1/s |
| 400 `not_a_video_model` | You sent an image/voice/music model to the video endpoint — the error names the correct endpoint |
| 400 `duration_exceeds_model_max` | Clamp `durationSec` (message states the model's max) |
| 409 `auth_not_configured` | Not enough Credits, or this model isn't offered on Credits yet — the `error` text says which: top up or connect a key, or switch model |
| 409 `model_unavailable` | Catalog `unavailableReason` names the substitute; run the fallback chain |
| 409 `provider_unavailable` | Model temporarily unavailable — switch to a `ws-*` model |
| 503 `circuit_open` | Provider circuit breaker — retry after a minute or fall back |
| "Exhausted balance" / "User is locked" | BYOK provider account out of funds — switch to platform-funded (`ws-hailuo-02`) |
| Job stuck in `queued`/`rendering` | Normal up to ~3 min. Only report stuck after ~4 min of 5–8s polls. Check Credits + provider capacity |
| `pollError` field in job response | Transient provider read error — poll again |
| ws-runway-gen4 "field image is required" | It is image-to-video ONLY — supply `referenceImageUrl` or pick another model |
| ws-hailuo-02 wrong duration | Fixed 6s clips — plan shot lengths accordingly |
| Music never resolves | Async tracks: keep polling `/api/music/poll`; ElevenLabs quota → fall back to `suno-v4` |
| Wrong-sounding voice | You guessed a `voiceId` — enumerate `GET /api/v1/voices` and use an exact id, or omit for Rachel |
| Sora-2 rejected | Retired — OpenAI shut it down 2026-09-24; use `veo-3.1` or `kling-3.0` |
| `imagen-4` returns a different model name | Expected: transparent alias — served + billed by `gemini-3-pro-image` since the 2026-08-17 sunset migration |
| Same request re-billed on retry | You changed/omitted the `Idempotency-Key` — reuse the same key when retrying a submit |

---

## How It's Different

- **vs. separate APIs:** one key, one credit pool, one auth, one dashboard — not 5 fragmented accounts.
- **vs. manual use:** automated orchestration, smart model selection, reference-frame consistency, brand injection, cost gates before spend.
- **The two gates that save money:** Stage 0B approval (human approves style before renders) and the pre-flight `409 auth_not_configured (not enough Credits)` check (API refuses renders you can't fund).
