@nodaro/shared 3.65.0 → 3.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/{chunk-GJ3D5X4X.cjs → chunk-23IKLMRL.cjs} +41 -41
  2. package/dist/{chunk-GJ3D5X4X.cjs.map → chunk-23IKLMRL.cjs.map} +1 -1
  3. package/dist/{chunk-E66HSC2E.cjs → chunk-37ZSFS6A.cjs} +9 -9
  4. package/dist/{chunk-E66HSC2E.cjs.map → chunk-37ZSFS6A.cjs.map} +1 -1
  5. package/dist/{chunk-K6RIN3LW.cjs → chunk-3L7GMQ4M.cjs} +47 -47
  6. package/dist/chunk-3L7GMQ4M.cjs.map +1 -0
  7. package/dist/{chunk-YMZUE2IX.js → chunk-3QJ3UR5Z.js} +9 -9
  8. package/dist/{chunk-YMZUE2IX.js.map → chunk-3QJ3UR5Z.js.map} +1 -1
  9. package/dist/{chunk-Q4YOLT4M.js → chunk-3YWZ5SOZ.js} +5 -5
  10. package/dist/{chunk-Q4YOLT4M.js.map → chunk-3YWZ5SOZ.js.map} +1 -1
  11. package/dist/{chunk-2NKF476Z.js → chunk-5GG4CG4Y.js} +3 -3
  12. package/dist/{chunk-2NKF476Z.js.map → chunk-5GG4CG4Y.js.map} +1 -1
  13. package/dist/{chunk-ZSRXY5YT.js → chunk-5IZHECUP.js} +3 -3
  14. package/dist/{chunk-ZSRXY5YT.js.map → chunk-5IZHECUP.js.map} +1 -1
  15. package/dist/{chunk-D5Y3EYRM.js → chunk-5J2LIQYU.js} +5 -5
  16. package/dist/{chunk-D5Y3EYRM.js.map → chunk-5J2LIQYU.js.map} +1 -1
  17. package/dist/{chunk-BSTAAGLY.js → chunk-5LWYX4GV.js} +3 -3
  18. package/dist/{chunk-BSTAAGLY.js.map → chunk-5LWYX4GV.js.map} +1 -1
  19. package/dist/{chunk-JYU5EIRM.cjs → chunk-66QSUUB4.cjs} +12 -12
  20. package/dist/{chunk-JYU5EIRM.cjs.map → chunk-66QSUUB4.cjs.map} +1 -1
  21. package/dist/{chunk-7BN4EDIC.cjs → chunk-BMDOPJBP.cjs} +17 -17
  22. package/dist/{chunk-7BN4EDIC.cjs.map → chunk-BMDOPJBP.cjs.map} +1 -1
  23. package/dist/{chunk-222QM7CO.js → chunk-BNR5FKL5.js} +3 -3
  24. package/dist/{chunk-222QM7CO.js.map → chunk-BNR5FKL5.js.map} +1 -1
  25. package/dist/{chunk-FI3HJZWM.cjs → chunk-E62W5I6A.cjs} +6 -2
  26. package/dist/chunk-E62W5I6A.cjs.map +1 -0
  27. package/dist/{chunk-MIT2USTS.cjs → chunk-EFYWV2V5.cjs} +61 -61
  28. package/dist/{chunk-MIT2USTS.cjs.map → chunk-EFYWV2V5.cjs.map} +1 -1
  29. package/dist/{chunk-RP4KQUNU.cjs → chunk-F6XIH3TZ.cjs} +9 -9
  30. package/dist/{chunk-RP4KQUNU.cjs.map → chunk-F6XIH3TZ.cjs.map} +1 -1
  31. package/dist/{chunk-KTCEKGBJ.cjs → chunk-G2G7XGFU.cjs} +7 -7
  32. package/dist/{chunk-KTCEKGBJ.cjs.map → chunk-G2G7XGFU.cjs.map} +1 -1
  33. package/dist/{chunk-HAH2F7LT.js → chunk-GF7ZA26H.js} +4 -4
  34. package/dist/{chunk-HAH2F7LT.js.map → chunk-GF7ZA26H.js.map} +1 -1
  35. package/dist/{chunk-FJZTQTF4.cjs → chunk-GNLA5NTT.cjs} +4 -4
  36. package/dist/{chunk-FJZTQTF4.cjs.map → chunk-GNLA5NTT.cjs.map} +1 -1
  37. package/dist/{chunk-ST7OBB5J.js → chunk-GTBW2KAY.js} +4 -4
  38. package/dist/{chunk-ST7OBB5J.js.map → chunk-GTBW2KAY.js.map} +1 -1
  39. package/dist/{chunk-R5ILCNCC.cjs → chunk-HTDKEYMY.cjs} +75 -75
  40. package/dist/{chunk-R5ILCNCC.cjs.map → chunk-HTDKEYMY.cjs.map} +1 -1
  41. package/dist/{chunk-DQ2PARNH.cjs → chunk-IWUW3YPM.cjs} +5 -5
  42. package/dist/{chunk-DQ2PARNH.cjs.map → chunk-IWUW3YPM.cjs.map} +1 -1
  43. package/dist/{chunk-6OSIOVF7.cjs → chunk-JTYCJ5OL.cjs} +16 -16
  44. package/dist/{chunk-6OSIOVF7.cjs.map → chunk-JTYCJ5OL.cjs.map} +1 -1
  45. package/dist/{chunk-JQMFJAYU.cjs → chunk-M5QY464F.cjs} +21 -21
  46. package/dist/{chunk-JQMFJAYU.cjs.map → chunk-M5QY464F.cjs.map} +1 -1
  47. package/dist/{chunk-CW6MMQNO.js → chunk-MVXZP6VB.js} +6 -2
  48. package/dist/chunk-MVXZP6VB.js.map +1 -0
  49. package/dist/{chunk-H745DQ6V.js → chunk-OFQ6CU6S.js} +3 -3
  50. package/dist/{chunk-H745DQ6V.js.map → chunk-OFQ6CU6S.js.map} +1 -1
  51. package/dist/{chunk-XJANKTIL.js → chunk-OXBU5AGH.js} +3 -3
  52. package/dist/{chunk-XJANKTIL.js.map → chunk-OXBU5AGH.js.map} +1 -1
  53. package/dist/{chunk-SPU7MUWE.cjs → chunk-OXTF4Y3P.cjs} +6 -6
  54. package/dist/{chunk-SPU7MUWE.cjs.map → chunk-OXTF4Y3P.cjs.map} +1 -1
  55. package/dist/{chunk-5SSMPYE5.js → chunk-PAUWEWTY.js} +5 -5
  56. package/dist/chunk-PAUWEWTY.js.map +1 -0
  57. package/dist/{chunk-KWYS4IIM.cjs → chunk-PJAJCFLP.cjs} +49 -38
  58. package/dist/chunk-PJAJCFLP.cjs.map +1 -0
  59. package/dist/{chunk-7OWXHW7Z.js → chunk-RVQW623D.js} +6 -6
  60. package/dist/{chunk-7OWXHW7Z.js.map → chunk-RVQW623D.js.map} +1 -1
  61. package/dist/{chunk-V5NLQ4L5.js → chunk-SCDE676D.js} +5 -5
  62. package/dist/{chunk-V5NLQ4L5.js.map → chunk-SCDE676D.js.map} +1 -1
  63. package/dist/{chunk-3AU52TSW.js → chunk-SW5ZD7BO.js} +3 -3
  64. package/dist/{chunk-3AU52TSW.js.map → chunk-SW5ZD7BO.js.map} +1 -1
  65. package/dist/{chunk-WQMPIURW.cjs → chunk-T4GIHHXY.cjs} +6 -6
  66. package/dist/{chunk-WQMPIURW.cjs.map → chunk-T4GIHHXY.cjs.map} +1 -1
  67. package/dist/{chunk-PL7AQQV7.js → chunk-VBP4DH37.js} +18 -10
  68. package/dist/chunk-VBP4DH37.js.map +1 -0
  69. package/dist/{chunk-YD4XY74W.cjs → chunk-X2YHKP4D.cjs} +8 -8
  70. package/dist/{chunk-YD4XY74W.cjs.map → chunk-X2YHKP4D.cjs.map} +1 -1
  71. package/dist/{chunk-6X5PBAC4.js → chunk-XEPKONJC.js} +3 -3
  72. package/dist/{chunk-6X5PBAC4.js.map → chunk-XEPKONJC.js.map} +1 -1
  73. package/dist/entries/apps.cjs +42 -42
  74. package/dist/entries/apps.js +7 -7
  75. package/dist/entries/credits.cjs +217 -217
  76. package/dist/entries/credits.d.cts +2 -2
  77. package/dist/entries/credits.d.ts +2 -2
  78. package/dist/entries/credits.js +9 -9
  79. package/dist/entries/llm-models.d.cts +2 -2
  80. package/dist/entries/llm-models.d.ts +2 -2
  81. package/dist/entries/model-catalog.cjs +133 -133
  82. package/dist/entries/model-catalog.d.cts +3 -3
  83. package/dist/entries/model-catalog.d.ts +3 -3
  84. package/dist/entries/model-catalog.js +4 -4
  85. package/dist/entries/models.cjs +403 -391
  86. package/dist/entries/models.d.cts +5 -5
  87. package/dist/entries/models.d.ts +5 -5
  88. package/dist/entries/models.js +5 -5
  89. package/dist/entries/nodes.cjs +212 -212
  90. package/dist/entries/nodes.d.cts +1 -1
  91. package/dist/entries/nodes.d.ts +1 -1
  92. package/dist/entries/nodes.js +8 -8
  93. package/dist/entries/pipeline.cjs +153 -153
  94. package/dist/entries/pipeline.d.cts +2 -2
  95. package/dist/entries/pipeline.d.ts +2 -2
  96. package/dist/entries/pipeline.js +3 -3
  97. package/dist/entries/ugc.cjs +71 -71
  98. package/dist/entries/ugc.js +4 -4
  99. package/dist/entries/video.cjs +152 -152
  100. package/dist/entries/video.d.cts +15 -10
  101. package/dist/entries/video.d.ts +15 -10
  102. package/dist/entries/video.js +6 -6
  103. package/dist/entries/workflow.d.cts +1 -1
  104. package/dist/entries/workflow.d.ts +1 -1
  105. package/dist/index.cjs +1355 -1343
  106. package/dist/index.d.cts +3 -3
  107. package/dist/index.d.ts +3 -3
  108. package/dist/index.js +18 -18
  109. package/dist/{model-catalog-BoUKGFNl.d.cts → model-catalog-B-aQnUS8.d.cts} +19 -1
  110. package/dist/{model-catalog-BoUKGFNl.d.ts → model-catalog-B-aQnUS8.d.ts} +19 -1
  111. package/dist/{model-constants-CpQz1bGa.d.cts → model-constants-BstsUup6.d.cts} +52 -2
  112. package/dist/{model-constants-BElS3AeE.d.ts → model-constants-DZ3tPGFO.d.ts} +52 -2
  113. package/dist/{tts-capabilities-BtnDWK9K.d.ts → tts-capabilities-BJ4N8MIB.d.ts} +1 -1
  114. package/dist/{tts-capabilities-C52UccTI.d.cts → tts-capabilities-Cf_4nu1Z.d.cts} +1 -1
  115. package/package.json +1 -1
  116. package/src/__tests__/flux-3-klein.test.ts +51 -3
  117. package/src/__tests__/image-run-limit.test.ts +96 -0
  118. package/src/__tests__/kling4-catalog.test.ts +1 -1
  119. package/src/__tests__/seedream-5-5.test.ts +17 -0
  120. package/src/__tests__/video-subjects.test.ts +33 -16
  121. package/src/entries/models.ts +4 -0
  122. package/src/model-catalog.ts +24 -2
  123. package/src/model-constants.ts +72 -6
  124. package/src/video-character-refs.ts +15 -10
  125. package/dist/chunk-5SSMPYE5.js.map +0 -1
  126. package/dist/chunk-CW6MMQNO.js.map +0 -1
  127. package/dist/chunk-FI3HJZWM.cjs.map +0 -1
  128. package/dist/chunk-K6RIN3LW.cjs.map +0 -1
  129. package/dist/chunk-KWYS4IIM.cjs.map +0 -1
  130. package/dist/chunk-PL7AQQV7.js.map +0 -1
@@ -1 +0,0 @@
1
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AM,eAAA,GAAkB,KAAA,CAAM,QAAA,IAAY,IAAA,IAAQ,MAAM,QAAA,KAAa,EAAA;AACrE,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,eAAA,GAAkB,sBAAA,GAA0B,KAAA,CAAM,QAAA;AAAA,IAC5D,QAAA,EAAU,KAAA,CAAM,QAAA,KAAa,eAAA,GAAkB,0BAAA,GAA6B,MAAA;AAAA,GAC9E;AACF","file":"chunk-KWYS4IIM.cjs","sourcesContent":["/**\n * Seedance 2.5 reference task type — what a request's reference media is FOR.\n *\n * The provider takes an optional declaration of the job a run's references do:\n * - `reference` — the media guides a new clip (look, subject, motion);\n * - `edit` — the clip is an edit of the reference video, in its own shape\n * and length;\n * - `extend` — the clip continues the reference video.\n * Without one the provider guesses from the prompt. `auto` is the platform's\n * spelling of \"declare nothing\": the provider keeps guessing.\n *\n * Which models take the declaration is a catalog capability\n * (`MODEL_CATALOG[id].referenceTaskTypes`), read through\n * `supportsReferenceTaskType`; whether a given request declares one, and the\n * aspect ratio and length that forces, is decided in one place by\n * `resolveSeedanceTaskType` (both in `model-constants.ts`). Never hand-list the\n * model.\n *\n * Import-free on purpose: the catalog (`model-catalog.ts`) and the constants\n * module (`model-constants.ts`, which imports the catalog) both read it. The\n * resolver itself lives in `model-constants.ts` because it needs\n * `videoDefaultDurationSec` from there.\n */\n\n/** Every value a request may carry, `auto` (declare nothing) first. */\nexport const SEEDANCE_REFERENCE_TASK_TYPES = [\"auto\", \"reference\", \"edit\", \"extend\"] as const\nexport type SeedanceReferenceTaskType = typeof SEEDANCE_REFERENCE_TASK_TYPES[number]\n\n/** A value that is actually sent to the provider. */\nexport type DeclaredSeedanceTaskType = Exclude<SeedanceReferenceTaskType, \"auto\">\n\n/**\n * The reference-video length (seconds, inclusive) an `edit` declaration\n * accepts. Every reference video must be measured and inside it; otherwise\n * nothing is declared.\n */\nexport const SEEDANCE_EDIT_REF_VIDEO_SEC = { min: 4, max: 30 } as const\n","/**\n * Model constants shared between frontend and backend.\n * Single source of truth for model capability sets and variable pricing rules.\n */\nimport { z } from \"zod\"\nimport { MODEL_CATALOG, isVideoAutoAspectToken, videoAutoAspectRunsAt, type ModelInputAdjustment } from \"./model-catalog.js\"\nimport { isAutoVideoDuration, VIDEO_DURATION_AUTO } from \"./video-duration-auto.js\"\nimport { SEEDANCE_EDIT_REF_VIDEO_SEC, type DeclaredSeedanceTaskType } from \"./seedance-task-type.js\"\n\n/** Base USD value of 1 Nodaro credit. Used for cost→credit conversion. */\nexport const CREDIT_BASE_USD = 0.002\n\n/** Max characters for the (assembled) prompt accepted by the image-generation routes\n * (generate-image, image-to-image, edit-image). Single source of truth — the route Zod\n * schemas and the factory-preset guard test all read this. Prompt cap ONLY (not negativePrompt). */\nexport const IMAGE_PROMPT_MAX = 5000\n\n/**\n * The ONE aspect-ratio vocabulary the image routes' Zod enums are built from —\n * `/v1/generate-image`, `/v1/image-to-image` and `/v1/edit-image` all declare\n * `z.enum(IMAGE_ASPECT_RATIO_VALUES)` instead of keeping three literal lists\n * that drift.\n *\n * It is the UNION of every ratio any `kind: \"image\"` catalog entry declares, so\n * a value the picker offers can never 400 at the route. That gap has shipped\n * twice — Wan 2.7's ultra-wide `8:1`/`1:8` (fixed on generate-image only) and\n * Nano Banana 2 Lite's banner `4:1`/`1:4` (still open until this tuple landed).\n * `packages/shared/src/__tests__/image-pricing-catalog-coverage.test.ts` fails\n * the build if a new model declares a ratio this tuple is missing.\n *\n * This enum is a VOCABULARY BOUND, not a per-model gate: it only stops a\n * free-form string from reaching a provider as `image_size`. The per-model gate\n * is the catalog snap (`resolveNormalizedImageGen` → `normalizeModelInput`),\n * which CORRECTS an unsupported ratio and discloses it in the response's\n * `adjustments` — never rejects. So widening this tuple is always safe: it\n * defers a rejection to the correcting snap, which is the desired behaviour.\n *\n * `auto` is model-specific (GPT Image 2 / Nano Banana 2 Lite treat it as\n * \"native\"); it lives here for the same reason as the rest — the snap drops or\n * replaces it for models that do not declare it.\n */\nexport const IMAGE_ASPECT_RATIO_VALUES = [\n \"auto\",\n \"1:1\", \"16:9\", \"9:16\", \"4:3\", \"3:4\",\n \"3:2\", \"2:3\", \"5:4\", \"4:5\", \"21:9\",\n // Ultra-wide / ultra-tall banner ratios: Wan 2.7 + Wan 2.7 Pro (8:1, 1:8)\n // and Nano Banana 2 Lite (4:1, 1:4, 8:1, 1:8).\n \"4:1\", \"1:4\", \"8:1\", \"1:8\",\n // GPT Image 2.5 (Flare + Sunburst) additions: near-square and ultra-wide/tall\n // cinema ratios (docs.kie.ai/market/gpt/gpt-image-2-5-*).\n \"27:16\", \"16:27\", \"9:8\", \"8:9\",\n // GPT Image 2.6 additions: wide and tall ratios of its own\n // (docs.kie.ai/market/gpt/gpt-image-2-6-*).\n \"2:1\", \"1:2\", \"9:21\", \"3:1\", \"1:3\",\n] as const\n\n/** A ratio string the image routes accept (pre-snap vocabulary, not a per-model guarantee). */\nexport type ImageAspectRatio = typeof IMAGE_ASPECT_RATIO_VALUES[number]\n\n/**\n * The K tiers of {@link IMAGE_RESOLUTION_VALUES}, smallest first. `1.5K` is\n * Seedream 5.5's middle size; no other model lists it, and the catalog snap\n * moves it to a size the chosen model does list.\n */\nexport const IMAGE_K_RESOLUTION_VALUES = [\"1K\", \"1.5K\", \"2K\", \"4K\"] as const\n\n/**\n * The `resolution` vocabulary `/v1/generate-image` and `/v1/image-to-image`\n * accept: the K tiers ({@link IMAGE_K_RESOLUTION_VALUES}) and the Flux 2\n * megapixel tiers. Like {@link IMAGE_ASPECT_RATIO_VALUES} it is a vocabulary\n * bound, not a per-model gate — the catalog snap corrects a value the chosen\n * model does not declare. One tuple for the route Zod enums (the entity routes'\n * too) and the SDK's `ImageResolution`.\n */\nexport const IMAGE_RESOLUTION_VALUES = [...IMAGE_K_RESOLUTION_VALUES, \"0.5 MP\", \"1 MP\", \"2 MP\", \"4 MP\"] as const\nexport type ImageResolution = typeof IMAGE_RESOLUTION_VALUES[number]\n\n/** The `quality` vocabulary of the same two routes (vocabulary bound; the catalog snap gates per model). */\nexport const IMAGE_QUALITY_VALUES = [\"auto\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\", \"basic\"] as const\nexport type ImageQuality = typeof IMAGE_QUALITY_VALUES[number]\n\n/** The `background` vocabulary of the same two routes (vocabulary bound; the catalog snap gates per model). */\nexport const IMAGE_BACKGROUND_VALUES = [\"auto\", \"opaque\", \"transparent\"] as const\nexport type ImageBackground = typeof IMAGE_BACKGROUND_VALUES[number]\n\n/**\n * The `outputFormat` vocabulary of the same two routes: the file a run writes\n * (vocabulary bound; the catalog snap gates per model, `outputFormats`). No\n * value is PNG. `gif` is an animation of square frames, `svg` a vector drawing.\n */\nexport const IMAGE_OUTPUT_FORMAT_VALUES = [\"png\", \"jpeg\", \"webp\", \"gif\", \"svg\"] as const\nexport type ImageOutputFormat = typeof IMAGE_OUTPUT_FORMAT_VALUES[number]\n\n/** The `svgLevel` vocabulary: how much detail an SVG is drawn with, Standard to Max. */\nexport const IMAGE_SVG_LEVEL_VALUES = [\"standard\", \"detailed\", \"max\"] as const\nexport type ImageSvgLevel = typeof IMAGE_SVG_LEVEL_VALUES[number]\n\n/** The pixel size of every frame of a GIF the platform asks for (square). Declared beside the catalog rule that reads it. */\nexport { IMAGE_GIF_FRAME_SIZE } from \"./model-catalog.js\"\n\n/** The MIME type of each output format, as it is stored and served. */\nexport const IMAGE_OUTPUT_FORMAT_MIME: Readonly<Record<ImageOutputFormat, string>> = {\n png: \"image/png\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n svg: \"image/svg+xml\",\n}\n\n/** The file extension each output format is stored under. */\nexport const IMAGE_OUTPUT_FORMAT_EXT: Readonly<Record<ImageOutputFormat, string>> = {\n png: \"png\",\n jpeg: \"jpg\",\n webp: \"webp\",\n gif: \"gif\",\n svg: \"svg\",\n}\n\n/** The `renderingSpeed` vocabulary (Ideogram's speed tiers — see {@link RENDERING_SPEED_SUPPORT}). */\nexport const IMAGE_RENDERING_SPEED_VALUES = [\"TURBO\", \"BALANCED\", \"QUALITY\"] as const\nexport type ImageRenderingSpeed = typeof IMAGE_RENDERING_SPEED_VALUES[number]\n\n/** `/v1/edit-image`'s `targetResolution` (the upscalers' output tier; topaz maps it to a factor). */\nexport const IMAGE_EDIT_TARGET_RESOLUTION_VALUES = [\"2K\", \"4K\", \"8K\"] as const\nexport type ImageEditTargetResolution = typeof IMAGE_EDIT_TARGET_RESOLUTION_VALUES[number]\n\n/**\n * Per-provider maximum ASSEMBLED image-prompt length (chars), VERIFIED against\n * each model's official docs.kie.ai schema (2026-06). Providers absent here use\n * {@link IMAGE_PROMPT_MAX} (the documented KIE \"standard\" of 5000). Read via\n * {@link getMaxImagePromptChars} by the prompt assembler's truncation AND the\n * frontend over-limit warning — the data-driven replacement for the old\n * hardcoded 2000 that silently severed appended cinematography hints + the\n * `Avoid:` negative on long prompts.\n *\n * Both directions matter: some models accept FAR MORE than 5000 (nano-banana-2 /\n * gpt-image-2-i2i = 20000) and some FAR LESS (seedream-5-lite = 1000) — sending\n * 5000 to a 1000-char model is a provider-side rejection. Only list a value you\n * can quote from the official schema; the t2i / i2i / edit siblings of one family\n * genuinely differ (verified: qwen t2i 3000 vs qwen-i2i 5000 vs qwen-edit 2000),\n * so never copy a sibling's number.\n *\n * Truncation is a graceful safety net, never a hard reject — the editor warns the\n * user BEFORE submit (switch model / trim) and the assembler truncates if they\n * proceed. So the image routes stay generous (a single high ceiling) and the\n * per-model enforcement lives here.\n */\nexport const MAX_IMAGE_PROMPT_CHARS_BY_PROVIDER: Record<string, number> = {\n // ── higher than the 5000 default ──\n \"nano-banana-2\": 20000, // docs.kie.ai/market/google/nano-banana-2\n \"nano-banana-2-lite\": 20000, // docs.kie.ai/market/google/nano-banana-2-lite\n \"nano-banana-2-1\": 20000, // docs.kie.ai/market/google/nanobanana-2-1\n \"nano-banana-pro\": 20000, // docs.kie.ai/market/google/pro-image-to-image\n \"gpt-image-2-i2i\": 20000, // docs.kie.ai/market/gpt/gpt-image-2-image-to-image\n // GPT Image 2.5 — all four lanes document a 20000-char prompt ceiling.\n \"gpt-image-2-5-flare\": 20000, // docs.kie.ai/market/gpt/gpt-image-2-5-flare-text-to-image\n \"gpt-image-2-5-flare-i2i\": 20000, // docs.kie.ai/market/gpt/gpt-image-2-5-flare-image-to-image\n \"gpt-image-2-5-sunburst\": 20000, // docs.kie.ai/market/gpt/gpt-image-2-5-sunburst-text-to-image\n \"gpt-image-2-5-sunburst-i2i\": 20000, // docs.kie.ai/market/gpt/gpt-image-2-5-sunburst-image-to-image\n // GPT Image 2.6 — Flare and Sunburst document 32000 chars, Economy 20000.\n // PROMPT_HARD_CEILING (30000) is what the routes accept, so that is the cap.\n \"gpt-image-2-6-flare\": 30000, // docs.kie.ai/market/gpt/gpt-image-2-6-flare-text-to-image\n \"gpt-image-2-6-flare-i2i\": 30000, // docs.kie.ai/market/gpt/gpt-image-2-6-flare-image-to-image\n \"gpt-image-2-6-sunburst\": 30000, // docs.kie.ai/market/gpt/gpt-image-2-6-sunburst-text-to-image\n \"gpt-image-2-6-sunburst-i2i\": 30000, // docs.kie.ai/market/gpt/gpt-image-2-6-sunburst-image-to-image\n \"gpt-image-2-6-economy\": 20000, // docs.kie.ai/market/gpt/gpt-image-2-6-economy-text-to-image\n \"gpt-image-2-6-economy-i2i\": 20000, // docs.kie.ai/market/gpt/gpt-image-2-6-economy-image-to-image\n // ── lower than the 5000 default (over-send risk if left at default) ──\n \"seedream\": 3000, // docs.kie.ai/market/seedream/4-5-text-to-image\n \"seedream-edit\": 3000, // docs.kie.ai/market/seedream/4-5-edit\n \"seedream-5-lite\": 1000, // docs.kie.ai/market/seedream/5-lite-text-to-image\n \"seedream-5-lite-i2i\": 3000, // docs.kie.ai/market/seedream-5-lite-image-to-image (NB: t2i sibling is 1000)\n \"qwen\": 3000, // docs.kie.ai/market/qwen/text-to-image\n \"qwen-edit\": 2000, // docs.kie.ai/market/qwen/image-edit\n // Z-Image is the SHORTEST of the family — \"maxLength: 1000\" in its schema\n // (docs.kie.ai/market/z-image/z-image, re-fetched 2026-09-15). It was listed\n // below as \"verified == 5000\", which is how three production runs on\n // 2026-09-07 sent a workflow-assembled prompt straight into KIE's\n // `{\"code\":500,\"msg\":\"The text length cannot exceed the maximum limit\"}`.\n \"z-image\": 1000, // docs.kie.ai/market/z-image/z-image\n // verified == 5000 default (no entry needed): imagen4(-fast/-ultra), nano-banana,\n // nano-banana-edit, flux, flux-flex, gpt-image-2, ideogram-v3/-edit/-remix,\n // grok, qwen-i2i, seedream-5-pro, seedream-5-pro-i2i\n // (docs.kie.ai/market/seedream/5-pro-text-to-image + 5-pro-image-to-image),\n // seedream-5-flash, seedream-5-flash-i2i (both \"4–5000 characters\";\n // docs.kie.ai/market/seedream/5-flash-text-to-image + 5-flash-image-to-image),\n // minimax-h3-image, minimax-h3-image-i2i (both \"1–5000 characters\";\n // docs.kie.ai/market/minimax-h3/text-to-image + image-edit),\n // seedream-5-5, seedream-5-5-i2i (both \"5–5000 characters\"; the minimum is\n // MIN_IMAGE_PROMPT_CHARS_BY_PROVIDER below;\n // docs.kie.ai/market/seedream/5-5-text-to-image + 5-5-image-to-image),\n // flux-3-klein, flux-3-klein-i2i (both \"1–5000 characters\";\n // docs.kie.ai/market/flux3/klein-text-to-image + klein-edit-image).\n // grok-i2i: doc states 390000 (78× its t2i sibling) — treated as a KIE schema\n // typo and left at the 5000 default per the sanity-cap decision.\n // UNVERIFIED (no limit stated in schema) → 5000 default: flux-kontext(-max)\n // gpt-image, gpt-image-i2i, flux-i2i, flux-pro-i2i.\n}\n\n/** Max assembled image-prompt length (chars) for a provider: its verified\n * override from {@link MAX_IMAGE_PROMPT_CHARS_BY_PROVIDER}, else the\n * {@link IMAGE_PROMPT_MAX} default. Single source of truth shared by the prompt\n * assembler, the over-limit warning, and the image-route ceiling. */\nexport function getMaxImagePromptChars(provider: string | undefined): number {\n return (provider && MAX_IMAGE_PROMPT_CHARS_BY_PROVIDER[provider]) || IMAGE_PROMPT_MAX\n}\n\n/**\n * The fewest characters (after trimming) the prompt a provider is SENT may have,\n * where its schema states a minimum it refuses below. Unlike the maximum, a\n * short prompt cannot be fixed by the platform without writing words for the\n * person, so a run whose final prompt is shorter is refused before anything is\n * reserved (the image routes and the workflow run). Only a value quoted from\n * the provider's schema is listed; a provider absent here has no minimum.\n */\nexport const MIN_IMAGE_PROMPT_CHARS_BY_PROVIDER: Record<string, number> = {\n \"seedream-5-5\": 5, // docs.kie.ai/market/seedream/5-5-text-to-image (\"5–5000 characters\")\n \"seedream-5-5-i2i\": 5, // docs.kie.ai/market/seedream/5-5-image-to-image\n}\n\n/** The minimum prompt length for a provider ({@link MIN_IMAGE_PROMPT_CHARS_BY_PROVIDER}), 0 when it states none. */\nexport function getMinImagePromptChars(provider: string | undefined): number {\n return (provider && MIN_IMAGE_PROMPT_CHARS_BY_PROVIDER[provider]) || 0\n}\n\n/**\n * Video prompt/negative cap shared by routes + editor (MCP verbs already use\n * 8000). Providers allow far more (KIE seedance-2: 20k chars) — the old\n * per-route 2500 was a false-positive blocker for legitimate multi-shot\n * Seedance prompts.\n */\nexport const VIDEO_PROMPT_MAX = 8000\n\n/**\n * Suno prompt / lyrics / content ceiling — the LARGEST any Suno version accepts\n * in custom mode (V6 family and V4.5+ / V5 / V5.5 = 5000). NOT the route\n * Zod bound — the routes bind at {@link SUNO_HARD_CEILING} and clamp to the\n * per-version cap via {@link getMaxSunoPromptChars} (3000 non-custom for every\n * version; in custom mode 3000 for V4/V3.5, 5000 for V4.5+/V5/V6) before the job\n * is built. This constant is shared with the editor `maxLength` / counter\n * (warn-don't-block at the per-version cap). `style` and `title` have their\n * own caps ({@link getMaxSunoStyleChars} / {@link SUNO_TITLE_MAX}).\n */\nexport const SUNO_TEXT_MAX = 5000\n\n/**\n * Absolute ceiling for every Suno text field on the route Zod schemas\n * (`prompt`, `lyrics`, `fullLyrics`, `content`, `userPrompt`).\n *\n * WARN-DON'T-BLOCK. The per-version caps ({@link getMaxSunoPromptChars} /\n * {@link getMaxSunoStyleChars}) do the real work — the routes CLAMP to them\n * before building the job. The Zod bound only exists to stop abuse, so it must\n * stay generous: until 2026-09 the routes bounded these fields at\n * {@link SUNO_TEXT_MAX} (5000), which meant a programmatically-set prompt (an\n * agent, an app run, a FieldMapping) was hard-REJECTED with a 400 before the\n * clamp could trim it — three app-report rows on 2026-08-19..31.\n *\n * DISTINCT FROM {@link PROMPT_HARD_CEILING} on purpose: that one is an\n * image/video budget pinned to MAX_IMAGE/VIDEO_PROMPT_CHARS_BY_PROVIDER by its\n * own drift guard. Coupling them would let one modality's limits move the\n * other's. This one has a single invariant, enforced in\n * `__tests__/prompt-length-limits.test.ts`: it MUST stay >= every value\n * getMaxSunoPromptChars / getMaxSunoStyleChars can return.\n */\nexport const SUNO_HARD_CEILING = 30000\n\n/**\n * Absolute ceiling for the `prompt` / `negativePrompt` fields on the image and\n * video routes' Zod schemas. The PER-MODEL limits below (and the editor warning)\n * do the real work; the routes stay generous so they never hard-reject a legit\n * long prompt — the assembler/payload truncates to the model cap as a graceful\n * safety net (warn-don't-block). 30000 = the largest verified per-model image/\n * video limit (seedance-2-5; seedance-2 / nano-banana-2 / gemini-omni sit at\n * 20000). Anything past this is abuse, not a real prompt.\n *\n * This MUST stay >= the largest entry in MAX_VIDEO_PROMPT_CHARS_BY_PROVIDER /\n * MAX_IMAGE_PROMPT_CHARS_BY_PROVIDER — otherwise the route's Zod hard-rejects a\n * prompt the model itself would have accepted, which is exactly the\n * block-instead-of-warn behaviour this ceiling exists to avoid. A drift guard in\n * `__tests__/prompt-length-limits.test.ts` enforces that relationship.\n */\nexport const PROMPT_HARD_CEILING = 30000\n\n/**\n * Ceiling for LLM TEXT-generation node inputs (the \"Generate Text\"/llm-chat node\n * + AI Writer + Generate Script `systemPrompt`/`userInput`/`prompt` fields).\n * Distinct from PROMPT_HARD_CEILING (an image/video PROMPT budget): these inputs\n * go straight into an LLM whose context is huge (Claude 200K / GPT 128K+ /\n * Gemini 1M tokens), so the old flat 10000 was a false blocker on pasting a\n * document to summarize or rewrite. 100000 chars (~25K input tokens) covers\n * long-form inputs while still bounding abuse; the OUTPUT stays capped by each\n * route's maxTokens.\n */\nexport const LLM_TEXT_INPUT_MAX = 100_000\n\n/**\n * Ceiling for the `system` prompt of the structured-output routes\n * (`POST /v1/llm/structured` and `POST /v1/llm/structured/jobs`). A client\n * that has the model write in its own vocabulary sends that vocabulary as the\n * system prompt, and it grows with the client's catalogs (Nodaro Studio's\n * production format is close to 100,000 chars), so this is twice\n * {@link LLM_TEXT_INPUT_MAX}. The routes' `input`, and every other LLM text\n * field, stay at LLM_TEXT_INPUT_MAX. 200,000 chars is roughly 50,000 to\n * 100,000 tokens, and a body at both ceilings still fits the API's 1 MB\n * request limit.\n */\nexport const LLM_STRUCTURED_SYSTEM_MAX = 200_000\n\n/** Kling 4.0's prompt limit, 8000 chars on both endpoints\n * (docs.kie.ai/market/kling/v4-reference-to-video and /v4-keyframe-to-video). */\nconst KLING_4_PROMPT_MAX = 8000\n\n/**\n * The characters a Kling 4 Extend run puts around the user's prompt on its\n * way to Kling 4.0: the continuation wrapper before it, and the opening-frame\n * sentence (after a blank line) that the reference endpoint adds for the\n * source's last frame. Held to the text the run really sends by\n * `backend/src/lib/__tests__/extend-recipe.test.ts`.\n */\nconst KLING_4_EXTEND_PROMPT_OVERHEAD = 131\n\n/**\n * Per-provider maximum VIDEO prompt length (chars), VERIFIED against each model's\n * official docs.kie.ai schema (2026-06). Absent → {@link VIDEO_PROMPT_MAX} (8000)\n * default (used for models whose schema states NO limit: veo3 family, kling-3.0,\n * kling-3-omni, runway-aleph). Read via {@link getMaxVideoPromptChars}.\n *\n * Most video models cap WELL BELOW the old flat 8000 (kling 2.6 = 1000!), so the\n * 8000 route value was over-sending to nearly every provider. A few accept much\n * more (seedance-2 = 20000). Mode note: where a model's t2v and i2v schemas\n * differ, the SMALLER is used so neither mode over-sends (hailuo-2.3-pro: t2v\n * 1500 / i2v 5000 → 1500).\n */\nexport const MAX_VIDEO_PROMPT_CHARS_BY_PROVIDER: Record<string, number> = {\n // Kling family — our `kling`→kling-2.6 (1000), `kling-turbo`→v2.5-turbo-pro (2500)\n \"kling\": 1000,\n \"kling-turbo\": 2500,\n \"kling-master\": 5000,\n // higher than the 8000 default\n \"seedance-2\": 20000,\n \"seedance-2-fast\": 20000,\n \"seedance-2-mini\": 20000,\n \"seedance-2-5-extend\": 20000,\n \"seedance-2-0-extend\": 20000,\n // Seedance 2.5 raises the prompt ceiling to 30000\n // (docs.kie.ai/market/bytedance/seedance-2-5).\n \"seedance-2-5\": 30000,\n \"gemini-omni-video\": 20000,\n // Gemini Omni Flash 1.1 — same 20000-char prompt surface as the pro sibling\n // (docs.kie.ai/market/google/gemini-omni-flash-1-1).\n \"gemini-omni-flash\": 20000,\n // (docs.kie.ai/market/google/gemini-omni-flash-1-2).\n \"gemini-omni-flash-1-2\": 20000,\n // Wan 3.0 / 3.0 Prime — 20000 chars, excess truncated by the provider\n // (docs.kie.ai/market/wan/3-0-video and /3-0-video-prime).\n \"wan-3\": 20000,\n \"wan-3-prime\": 20000,\n // Vidu Q4 — 20000 chars on both endpoints\n // (docs.kie.ai/market/vidu-q4/image-to-video and /reference-to-video).\n \"vidu-q4\": 20000,\n // Kling 4.0 — 8000 chars on both endpoints\n // (docs.kie.ai/market/kling/v4-reference-to-video and /v4-keyframe-to-video).\n \"kling-4\": KLING_4_PROMPT_MAX,\n \"kling-4-keyframes\": KLING_4_PROMPT_MAX,\n // Kling 4 Extend generates on Kling 4.0's reference endpoint, its user's\n // prompt wrapped: the room the wrapping takes is left out, so a prompt at\n // the cap (its \"Avoid: …\" clause last) reaches Kling 4.0 whole.\n \"kling-4-extend\": KLING_4_PROMPT_MAX - KLING_4_EXTEND_PROMPT_OVERHEAD,\n // Kling 4.0 Flash — 8000 chars on both endpoints\n // (docs.kie.ai/market/kling/v4-flash-reference-to-video and /v4-flash-keyframe-to-video).\n \"kling-4-flash\": 8000,\n // PixVerse V6 Max — 1-5000 chars on both endpoints\n // (docs.kie.ai/market/pixverse/v6-max-text-to-video and /v6-max-image-to-video).\n \"pixverse-v6-max\": 5000,\n // PixVerse V6 Extend — 3-5000 chars (docs.kie.ai/market/pixverse/extend);\n // its prompt is sent as written, so the whole cap is the user's.\n \"pixverse-v6-extend\": 5000,\n \"bytedance-lite\": 10000,\n \"bytedance-pro\": 10000,\n \"bytedance-pro-fast\": 10000,\n // MiniMax Hailuo 3 — 1-7000 chars, uniform across t2v/i2v/r2v\n // (docs.kie.ai/market/minimax-h3).\n \"minimax-h3\": 7000,\n // lower than the 8000 default\n \"minimax\": 1500,\n \"hailuo-standard\": 1500,\n \"hailuo-2.3-pro\": 1500, // t2v 1500 / i2v 5000 → smaller, safe for both modes\n \"hailuo-2.3\": 5000,\n \"wan\": 5000,\n \"wan-i2v\": 5000,\n \"wan-turbo\": 5000,\n \"wan-flash\": 1500,\n \"wan-videoedit\": 5000,\n \"wan-2.7-i2v\": 5000,\n \"wan-2.7-t2v\": 5000,\n \"grok-i2v\": 5000,\n \"grok-imagine-video-1.5\": 4096,\n \"happyhorse\": 5000,\n \"happyhorse-i2v\": 5000,\n \"happyhorse-ref2v\": 5000,\n \"happyhorse-edit\": 5000,\n \"runway-kie\": 1800,\n // OmniHuman 2.0 (lip-sync) — \"Up to 300 characters\" (maxLength 300 in KIE's\n // omnihuman-2-0 schema, read 2026-11-11). Cut to it before the request.\n \"omnihuman-2-0\": 300,\n // NB: `wan-2.7` / `wan-2.7-pro` are IMAGE models (see the image registry), not\n // video. The motion-transfer route's prompt is capped at the motion-control\n // limit (2500) inside the route itself — its provider values are the shared\n // `kling` (→1000 here, safely tighter) / `kling-3.0` ids, not a \"motion-*\" id.\n // UNVERIFIED (schema states no limit) → 8000 default: veo3, veo3.1, veo3_lite\n // kling-3.0, kling-3-omni, runway-aleph.\n}\n\n/** Max video-prompt length (chars) for a provider: verified override, else\n * {@link VIDEO_PROMPT_MAX}. Shared by the video routes/payload truncation and\n * the editor over-limit warning. */\nexport function getMaxVideoPromptChars(provider: string | undefined): number {\n return (provider && MAX_VIDEO_PROMPT_CHARS_BY_PROVIDER[provider]) || VIDEO_PROMPT_MAX\n}\n\n/** Default negative-prompt cap when a provider has no specific verified limit. */\nexport const NEGATIVE_PROMPT_MAX = 5000\n\n/**\n * Per-provider native `negative_prompt` cap (chars), VERIFIED from docs.kie.ai.\n * Only matters for providers that send the negative as a NATIVE param\n * ({@link NATIVE_NEGATIVE_PROMPT_MODELS} / {@link NATIVE_NEGATIVE_VIDEO_PROVIDERS});\n * everywhere else the negative is folded into the prompt as `Avoid: …` and rides\n * the prompt cap. Absent → {@link NEGATIVE_PROMPT_MAX}.\n */\nexport const MAX_NEGATIVE_PROMPT_CHARS_BY_PROVIDER: Record<string, number> = {\n // image\n \"imagen4\": 5000, \"imagen4-fast\": 5000, \"imagen4-ultra\": 5000,\n \"ideogram-v3\": 500, \"ideogram-remix\": 5000,\n \"qwen\": 500, \"qwen-i2i\": 500, \"qwen-edit\": 500,\n // video (native-negative families)\n \"kling-master\": 500,\n \"kling-turbo\": 500, // i2v 500 / t2v 2500 → smaller, safe for both modes\n \"wan-2.7-i2v\": 500, \"wan-2.7-t2v\": 500, \"wan-videoedit\": 500,\n}\n\n/** Max native negative-prompt length (chars) for a provider. */\nexport function getMaxNegativePromptChars(provider: string | undefined): number {\n return (provider && MAX_NEGATIVE_PROMPT_CHARS_BY_PROVIDER[provider]) || NEGATIVE_PROMPT_MAX\n}\n\n/** What {@link getMaxTtsChars} answers for an id with no entry of its own: the legacy `elevenlabs` alias (which runs as turbo — pass `canonicalTtsProvider(id)` to get that model's cap), a missing id and an unknown id. */\nexport const TTS_TEXT_MAX = 5000\n\n/**\n * Per-model Text-to-Speech character cap (PER REQUEST). DERIVED from each\n * speech model's capability sheet (`tts.maxChars` in `MODEL_CATALOG`) — set the\n * cap there, never here. Absent → {@link TTS_TEXT_MAX}.\n */\nexport const MAX_TTS_CHARS_BY_PROVIDER: Record<string, number> = Object.fromEntries(\n Object.values(MODEL_CATALOG)\n .filter((m) => m.tts !== undefined)\n .map((m) => [m.id, m.tts!.maxChars]),\n)\n\n/**\n * Max TTS text length (chars) for a provider: verified override, else\n * {@link TTS_TEXT_MAX}. The legacy `elevenlabs` alias has no entry of its own\n * (callers that mean the model it runs as pass `canonicalTtsProvider(id)`), and\n * an id named like an inherited object member (`constructor`) is just unknown.\n */\nexport function getMaxTtsChars(provider: string | undefined): number {\n const cap = provider && Object.hasOwn(MAX_TTS_CHARS_BY_PROVIDER, provider) ? MAX_TTS_CHARS_BY_PROVIDER[provider] : undefined\n return cap || TTS_TEXT_MAX\n}\n\n/**\n * Suno per-version field caps (from docs.kie.ai/suno-api/generate-music). The\n * original flat 3000 cap was simultaneously too low for V4.5+/V5 prompts\n * (5000) and too high for `style` (1000) and `title` (80). ({@link\n * SUNO_TEXT_MAX} is 5000 today — the largest per-version prompt cap; the\n * route Zod bound is {@link SUNO_HARD_CEILING}.)\n * - prompt / lyrics: 3000 in non-custom mode (all versions); in custom mode\n * 3000 for V4/V3.5 and 5000 for V4.5 / V4.5PLUS / V4.5ALL / V5 / V5.5 and\n * the whole V6 family (V6 / V6_WILD / V6_MINI).\n * - style: 200 for V4/V3.5, 1000 for V4.5+ and V6.\n * - title: 80 (all versions; the extend docs quote 100 for V6 — we keep the\n * stricter generate cap so one value is right everywhere).\n */\nexport const SUNO_TITLE_MAX = 80\n\n/**\n * Max Suno `prompt` (= lyrics in custom mode) length for a model version.\n *\n * NON-CUSTOM WAS 500 UNTIL 2026-08-19 — six times under the provider's\n * documented 3000, and the route TRUNCATES to this number instead of\n * rejecting, so everything past it vanished without a trace. Field evidence:\n * a 950-character recast score brief (instruments, vocal, the source's own\n * scat syllables, the arrangement's arc) reached Suno as exactly 500\n * characters, cut mid-word.\n */\nexport function getMaxSunoPromptChars(model: string | undefined, customMode: boolean): number {\n if (!customMode) return 3000\n return model === \"V4\" || model === \"V3_5\" ? 3000 : 5000\n}\n\n/** Max Suno `style` length for a model version. */\nexport function getMaxSunoStyleChars(model: string | undefined): number {\n return model === \"V4\" || model === \"V3_5\" ? 200 : 1000\n}\n\n// Models that accept negative_prompt as a native API parameter.\n// All other models get negative prompt appended to the prompt text as \"Avoid: ...\".\nexport const NATIVE_NEGATIVE_PROMPT_MODELS = new Set([\n \"imagen4\", \"imagen4-fast\", \"imagen4-ultra\",\n \"ideogram-remix\", \"ideogram-v3\",\n \"qwen\", \"qwen-edit\",\n])\n\n/**\n * Video providers that accept `negative_prompt` natively in their KIE.ai\n * request payload. Everywhere else, the helper below appends `Avoid: <text>`\n * to the prompt instead so the negative intent still reaches the model.\n *\n * Sourced from inline comments in `backend/src/providers/kie/video.ts`\n * (Kling family + Wan family) plus the wan-s2v speech-to-video flow.\n *\n * NOT included (KIE will silently drop the param):\n * minimax / hailuo-* family, veo3.* family, sora2 / sora2-pro,\n * bytedance-* family, grok / grok-i2v, seedance-* family,\n * happyhorse-*, ltx-* family, runway-kie, wan-animate-move/replace\n * (Wan Animate is a separate model from regular Wan and doesn't take\n * negative_prompt — verified against KIE docs 2026-05-28).\n */\nexport const NATIVE_NEGATIVE_VIDEO_PROVIDERS = new Set<string>([\n // Kling family\n \"kling\", \"kling-turbo\", \"kling-master\", \"kling-3.0\", \"kling-3-omni\",\n // Wan family (regular Wan, NOT wan-animate)\n \"wan\", \"wan-flash\", \"wan-videoedit\",\n \"wan-i2v\", \"wan-turbo\",\n \"wan-2.7-i2v\", \"wan-2.7-t2v\",\n // Wan speech-to-video\n \"wan-s2v\",\n])\n\n/**\n * The `[style]` section header, verbatim. A composed prompt that ends with that\n * section has NO terminator (`@nodaro/prompts`' `prompt-style-section.ts` owns\n * the shape and the reasoning), so a `\"\\n\"`-joined `Avoid:` would read as one\n * more look clause under its header. Duplicated rather than imported because\n * `@nodaro/prompts` depends on THIS package and never the reverse; the two are\n * pinned together behaviourally by that package's\n * `__tests__/style-section-boundary.test.ts`, which runs the real composer\n * through this clamp.\n */\nconst STYLE_SECTION_HEADER_LINE = \"[style]:\\n\"\n\n/**\n * The `Avoid: …` suffix `applyVideoNegativePrompt` folds into a prompt, with the\n * separator the base prompt calls for: a blank line when the base ends INSIDE an\n * unterminated `[style]` section, a single newline otherwise.\n *\n * `base` omitted = the WIDEST form, which is what a caller reserving room before\n * the prompt exists must budget for (`effectiveVideoPromptCeiling`).\n */\nexport function videoNegativeSuffix(negativePrompt: string, base?: string): string {\n const gapAt = base?.lastIndexOf(\"\\n\\n\") ?? -1\n const lastBlock = base === undefined ? undefined : (gapAt >= 0 ? base.slice(gapAt + 2) : base)\n const separator = lastBlock === undefined || lastBlock.startsWith(STYLE_SECTION_HEADER_LINE)\n ? \"\\n\\n\"\n : \"\\n\"\n return `${separator}Avoid: ${negativePrompt}`\n}\n\n/**\n * Apply the negative prompt to a video-provider request.\n *\n * If the provider natively accepts `negative_prompt` (Kling / Wan families),\n * the helper returns the original prompt and the trimmed negative as\n * `nativeNegativePrompt` — the caller should forward it as the API's\n * dedicated field.\n *\n * Otherwise, the helper appends `Avoid: <negativePrompt>` to the prompt\n * (consistent with `buildImagePrompt` in `prompt-builder.ts`) so the model\n * still sees the negative intent, and returns `nativeNegativePrompt = undefined`.\n * The line is separated by {@link videoNegativeSuffix}, which closes an open\n * `[style]` section with a blank line rather than reading as a look clause.\n *\n * Empty / missing negative is a no-op.\n *\n * Naming mirrors the established image-side pattern. Keep the wording\n * identical to `prompt-builder.ts` (\"Avoid: ...\") so users moving between\n * image and video nodes see consistent behavior.\n */\nexport function applyVideoNegativePrompt(\n prompt: string | undefined,\n negativePrompt: string | undefined,\n provider: string,\n): { prompt: string | undefined; nativeNegativePrompt: string | undefined } {\n // This is the universal \"finalize the video prompt for the provider\" chokepoint\n // (every KIE video method, the extend route, the orchestrator, and the editor\n // preview route through it). So it ALSO clamps to the model's verified caps —\n // a graceful safety net (the editor warns the user first; warn-don't-block).\n // Under-cap prompts (the common case) pass through byte-identical.\n const promptMax = getMaxVideoPromptChars(provider)\n const clamp = (p: string | undefined): string | undefined =>\n p != null && p.length > promptMax ? p.slice(0, promptMax) : p\n\n const neg = negativePrompt?.trim()\n if (!neg) return { prompt: clamp(prompt), nativeNegativePrompt: undefined }\n if (NATIVE_NEGATIVE_VIDEO_PROVIDERS.has(provider)) {\n // Native negative rides its own param → clamp each independently.\n return { prompt: clamp(prompt), nativeNegativePrompt: neg.slice(0, getMaxNegativePromptChars(provider)) }\n }\n // Non-native: fold the negative into the prompt as \"Avoid: …\". Reserve room for\n // the suffix so a long base prompt can't sever the negative (mirror the image\n // assembler), then clamp the whole to the model cap.\n const base = prompt && prompt.trim().length > 0 ? prompt : \"\"\n if (!base) return { prompt: `Avoid: ${neg}`.slice(0, promptMax), nativeNegativePrompt: undefined }\n // The separator is decided on the WHOLE base: the clamp below can only cut the\n // tail, and a cut either leaves the `[style]` section behind or lands inside\n // it, so the suffix never needs to grow after the reservation.\n const avoid = videoNegativeSuffix(neg, base)\n const room = Math.max(0, promptMax - avoid.length)\n const injected = `${base.slice(0, room)}${avoid}`.slice(0, promptMax)\n return { prompt: injected, nativeNegativePrompt: undefined }\n}\n\n// Image providers that natively use reference images in their API.\n// Used by `buildImagePrompt` to filter referenceImageUrls before sending,\n// and by the frontend to warn when the user has `{image:N:label}` tokens\n// in a prompt for a provider that would silently ignore them.\n//\n// Verified against backend/src/providers/kie/models.ts (inputType +\n// imageParam) and the i2i flow in backend/src/providers/kie/image.ts.\n//\n// Image providers that natively use reference images in their API.\n//\n// Two categories included:\n// 1. Direct ref support: nano-banana family (multi-ref T2I) + flux-kontext\n// (single image edit) + all i2i/edit variants.\n// 2. Auto-switched: T2I models that have an i2i sibling — when the user\n// attaches refs to one of these in a generate-image node, the backend\n// route silently routes to the i2i sibling. See `T2I_TO_I2I_VARIANT`.\n// User-facing benefit: pick GPT Image / Grok / Qwen / Seedream / Flux at\n// the dropdown, attach refs, and they \"just work\".\n//\n// Excluded (no ref support and no i2i sibling — refs would be useless):\n// imagen4, imagen4-fast, imagen4-ultra, ideogram-v3, z-image\nexport const MODELS_WITH_REFERENCE_IMAGE_SUPPORT = new Set([\n // Multi-reference text-to-image\n \"nano-banana\",\n \"nano-banana-pro\",\n \"nano-banana-2\",\n \"nano-banana-2-lite\",\n \"nano-banana-2-1\",\n // T2I providers that auto-route to their i2i sibling when refs are attached\n \"gpt-image\",\n \"gpt-image-2\",\n \"gpt-image-2-5-flare\",\n \"gpt-image-2-5-sunburst\",\n \"gpt-image-2-6-flare\",\n \"gpt-image-2-6-sunburst\",\n \"gpt-image-2-6-economy\",\n \"grok\",\n \"grok-2\",\n \"qwen\",\n \"seedream\",\n \"seedream-5-lite\",\n \"seedream-5-pro\",\n \"seedream-5-flash\",\n \"minimax-h3-image\",\n \"seedream-5-5\",\n \"flux\",\n \"flux-flex\",\n \"flux-3-klein\",\n // Image editing / image-to-image (reference = source image)\n \"nano-banana-edit\",\n \"gpt-image-i2i\",\n \"gpt-image-2-i2i\",\n \"gpt-image-2-5-flare-i2i\",\n \"gpt-image-2-5-sunburst-i2i\",\n \"gpt-image-2-6-flare-i2i\",\n \"gpt-image-2-6-sunburst-i2i\",\n \"gpt-image-2-6-economy-i2i\",\n \"grok-2-i2i\",\n \"flux-i2i\",\n \"flux-pro-i2i\",\n \"flux-kontext\",\n \"flux-kontext-max\",\n \"ideogram-edit\",\n \"ideogram-remix\",\n \"qwen-i2i\",\n \"qwen-edit\",\n \"seedream-edit\",\n \"seedream-5-lite-i2i\",\n \"seedream-5-pro-i2i\",\n \"seedream-5-flash-i2i\",\n \"minimax-h3-image-i2i\",\n \"seedream-5-5-i2i\",\n \"flux-3-klein-i2i\",\n \"grok-i2i\",\n // Upscale / background ops (source acts as the reference)\n \"recraft-remove-bg\",\n \"recraft-upscale\",\n \"topaz-image-upscale\",\n \"nodaro-image-upscale\",\n // Wan 2.7 — accepts up to 9 optional ref images via input_urls (pure T2I when omitted)\n \"wan-2.7\",\n // Replicate \"Open\" (uncensored) image models\n \"flux-2-klein\",\n \"kontext-multi\",\n \"flux-2-pro\",\n \"flux-2-max\",\n])\n\n/**\n * T2I provider → i2i sibling. When a generate-image node carries reference\n * images and the chosen provider is in this map, the backend route\n * transparently routes to the i2i variant so the refs are actually used.\n *\n * The user keeps seeing the T2I name in the UI; the warning component shows\n * an info hint that the i2i variant is being used under the hood.\n */\nexport const T2I_TO_I2I_VARIANT: Record<string, string> = {\n \"gpt-image\": \"gpt-image-i2i\",\n \"gpt-image-2\": \"gpt-image-2-i2i\",\n \"gpt-image-2-5-flare\": \"gpt-image-2-5-flare-i2i\",\n \"gpt-image-2-5-sunburst\": \"gpt-image-2-5-sunburst-i2i\",\n \"gpt-image-2-6-flare\": \"gpt-image-2-6-flare-i2i\",\n \"gpt-image-2-6-sunburst\": \"gpt-image-2-6-sunburst-i2i\",\n \"gpt-image-2-6-economy\": \"gpt-image-2-6-economy-i2i\",\n \"grok\": \"grok-i2i\",\n // grok-2's t2i takes NO image input; its \"i2i\" is the segment-map(image_url)\n // → image-edit(task_id) chain in the KIE provider (single reference).\n \"grok-2\": \"grok-2-i2i\",\n \"qwen\": \"qwen-i2i\",\n \"seedream\": \"seedream-edit\",\n \"seedream-5-lite\": \"seedream-5-lite-i2i\",\n \"seedream-5-pro\": \"seedream-5-pro-i2i\",\n \"seedream-5-flash\": \"seedream-5-flash-i2i\",\n // MiniMax H3 Image: its text-to-image endpoint takes no image at all.\n \"minimax-h3-image\": \"minimax-h3-image-i2i\",\n // Seedream 5.5's text-to-image endpoint takes no image at all: its edit\n // endpoint is the only one that reads them (the provider swaps too).\n \"seedream-5-5\": \"seedream-5-5-i2i\",\n \"flux\": \"flux-pro-i2i\",\n \"flux-flex\": \"flux-i2i\",\n // FLUX 3 Klein's text-to-image endpoint takes no image at all: its edit\n // endpoint reads them (the provider swaps too).\n \"flux-3-klein\": \"flux-3-klein-i2i\",\n}\n\n/**\n * Maximum number of reference images each provider accepts.\n * Sourced from the corresponding KIE.ai endpoint's documented input array\n * size, or from the model's natural input shape (single-source i2i = 1).\n *\n * Providers absent from this map default to `DEFAULT_REF_IMAGE_MAX` (4).\n * Providers absent from `MODELS_WITH_REFERENCE_IMAGE_SUPPORT` ignore\n * reference images entirely regardless of this value.\n */\nexport const REF_IMAGE_MAX_LIMITS: Record<string, number> = {\n // Multi-reference T2I (Nano Banana family is the only T2I family that\n // actually accepts ref URLs via the KIE wrapper's `image_input` param).\n \"nano-banana\": 8,\n \"nano-banana-pro\": 8,\n \"nano-banana-2\": 4,\n \"nano-banana-2-lite\": 10,\n \"nano-banana-2-1\": 10,\n \"wan-2.7\": 9,\n // grok-2 reference chain consumes exactly one image (segment-map input).\n \"grok-2-i2i\": 1,\n // Image-to-image (multi-source array)\n \"nano-banana-edit\": 8,\n \"gpt-image-i2i\": 16,\n \"gpt-image-2-i2i\": 16,\n \"gpt-image-2-5-flare-i2i\": 16,\n \"gpt-image-2-5-sunburst-i2i\": 16,\n \"gpt-image-2-6-flare-i2i\": 16,\n \"gpt-image-2-6-sunburst-i2i\": 16,\n \"gpt-image-2-6-economy-i2i\": 16,\n \"flux-i2i\": 4,\n \"flux-pro-i2i\": 4,\n \"seedream-edit\": 16,\n \"seedream-5-lite-i2i\": 16,\n \"seedream-5-pro-i2i\": 16,\n // Flash takes at most 10 `image_urls` (docs.kie.ai/market/seedream/5-flash-image-to-image) — not the family's 16.\n \"seedream-5-flash-i2i\": 10,\n // 1 to 16 `image_urls` (docs.kie.ai/market/minimax-h3/image-edit).\n \"minimax-h3-image-i2i\": 16,\n // Seedream 5.5 takes 1–10 `image_urls` (docs.kie.ai/market/seedream/5-5-image-to-image).\n \"seedream-5-5-i2i\": 10,\n // FLUX 3 Klein's edit takes 1–10 `image_urls` (docs.kie.ai/market/flux3/klein-edit-image).\n \"flux-3-klein-i2i\": 10,\n // Single-source i2i (one input image)\n \"flux-kontext\": 1,\n \"flux-kontext-max\": 1,\n \"ideogram-edit\": 1,\n \"ideogram-remix\": 1,\n \"qwen-i2i\": 1,\n \"qwen-edit\": 1,\n \"grok-i2i\": 1,\n \"recraft-remove-bg\": 1,\n \"recraft-upscale\": 1,\n \"topaz-image-upscale\": 1,\n \"nodaro-image-upscale\": 1,\n // Replicate Open models — Klein takes an optional single ref; Kontext Multi\n // (multi-image-kontext-pro) is a two-image combiner (input_image_1/2 only);\n // Flux 2 Pro up to 4; Max up to 8.\n \"flux-2-klein\": 1,\n \"kontext-multi\": 2,\n \"flux-2-pro\": 4,\n \"flux-2-max\": 8,\n}\n\nexport const DEFAULT_REF_IMAGE_MAX = 4\n\n/**\n * Maximum reference images the UI should advertise for an IMAGE model — the\n * scalar image analogue of the video side's `videoReferenceLimits` (images have\n * a single reference kind, so a scalar suffices). Studio's Framing picker reads\n * this for its \"References\" chip; the editor's reference-handle popover reads it\n * too (via `getHandleConnectionLimit`).\n *\n * Returns 0 when the model accepts no reference images at all (so callers can\n * hide the chip / disable the handle), else the per-model cap from\n * {@link REF_IMAGE_MAX_LIMITS} (fallback {@link DEFAULT_REF_IMAGE_MAX}).\n * Therefore `imageReferenceLimit(p) > 0` is an exact \"supports references\" gate.\n *\n * Two behaviors keep the count matching what a user actually gets:\n * 1. T2I → i2i resolution. Pickers list text-to-image ids (grok, gpt-image-2,\n * seedream-5-lite, flux, …). When references are attached the generate-image\n * route silently routes to the i2i sibling ({@link T2I_TO_I2I_VARIANT}) —\n * the endpoint that actually consumes refs — so the advertised cap is the\n * SIBLING's (grok→grok-i2i = 1, gpt-image-2→gpt-image-2-i2i = 16), never the\n * t2i id's absent default. Mirrors the swap `resolveNormalizedImageGen`\n * makes for the route and the workflow run alike.\n * 2. {@link REF_IMAGE_MAX_LIMITS} is the PRODUCT/UI cap, which may be\n * intentionally TIGHTER than the raw provider schema (e.g. flux-2-pro = 4\n * here though the BFL schema accepts 8; flux-2-klein = 1 though the array\n * slices at 5). The user-facing count must reflect the product cap, so the\n * reader reads this map verbatim — do NOT \"fix\" these to the schema maxima.\n */\nexport function imageReferenceLimit(provider: string | undefined): number {\n if (!provider || !MODELS_WITH_REFERENCE_IMAGE_SUPPORT.has(provider)) return 0\n const effective = T2I_TO_I2I_VARIANT[provider] ?? provider\n return REF_IMAGE_MAX_LIMITS[effective] ?? DEFAULT_REF_IMAGE_MAX\n}\n\n/** The most input images one request may carry, on a model with no row below. */\nexport const DEFAULT_REQUEST_IMAGE_LIMIT = 14\n\n/**\n * Models whose request may carry a different number of input images than\n * {@link DEFAULT_REQUEST_IMAGE_LIMIT}. Separate from\n * {@link REF_IMAGE_MAX_LIMITS}, the cap the canvas and the assembler honour: the\n * routes have their own ceiling, and it moves per model only here. GPT Image\n * 2.6 takes more; a model whose provider takes fewer (Seedream 5.5 and FLUX 3\n * Klein: 10) is held to its own, so a request is refused before it is\n * reserved instead of failing at the provider.\n */\nconst REQUEST_IMAGE_LIMITS: Record<string, number> = {\n \"gpt-image-2-6-flare-i2i\": 16,\n \"gpt-image-2-6-sunburst-i2i\": 16,\n \"minimax-h3-image-i2i\": 16,\n \"seedream-5-5-i2i\": 10,\n \"flux-3-klein-i2i\": 10,\n}\n\n/** The largest per-model limit: the outer bound of the routes' array schemas. */\nexport const MAX_REQUEST_IMAGE_LIMIT = Math.max(DEFAULT_REQUEST_IMAGE_LIMIT, ...Object.values(REQUEST_IMAGE_LIMITS))\n\n/**\n * The most input images one request may carry for `provider` (a text-to-image\n * id reads its edit sibling's row, the model that consumes them).\n */\nexport function requestImageLimit(provider: string | undefined): number {\n const effective = provider ? (T2I_TO_I2I_VARIANT[provider] ?? provider) : undefined\n return (effective !== undefined ? REQUEST_IMAGE_LIMITS[effective] : undefined) ?? DEFAULT_REQUEST_IMAGE_LIMIT\n}\n\n// Variable pricing: which setting type affects cost per provider\nexport const VARIABLE_PRICING_MODELS: Record<string, \"quality\" | \"resolution\" | \"rendering-speed\"> = {\n \"gpt-image\": \"quality\",\n \"gpt-image-i2i\": \"quality\",\n \"gpt-image-2\": \"resolution\",\n \"gpt-image-2-i2i\": \"resolution\",\n \"gpt-image-2-5-flare\": \"resolution\",\n \"gpt-image-2-5-flare-i2i\": \"resolution\",\n \"gpt-image-2-5-sunburst\": \"resolution\",\n \"gpt-image-2-5-sunburst-i2i\": \"resolution\",\n \"nano-banana-pro\": \"resolution\",\n \"nano-banana-2\": \"resolution\",\n \"nano-banana-2-1\": \"resolution\",\n \"flux\": \"resolution\",\n \"flux-flex\": \"resolution\",\n \"flux-i2i\": \"resolution\",\n \"flux-pro-i2i\": \"resolution\",\n \"seedream\": \"quality\",\n \"seedream-edit\": \"quality\",\n \"seedream-5-lite\": \"quality\",\n \"seedream-5-lite-i2i\": \"quality\",\n \"seedream-5-pro\": \"quality\",\n \"seedream-5-pro-i2i\": \"quality\",\n \"seedream-5-5\": \"resolution\",\n \"seedream-5-5-i2i\": \"resolution\",\n \"topaz-image-upscale\": \"resolution\",\n \"ideogram-edit\": \"rendering-speed\",\n \"ideogram-remix\": \"rendering-speed\",\n \"ideogram-v3\": \"rendering-speed\",\n \"wan-2.7\": \"resolution\",\n \"wan-2.7-pro\": \"resolution\",\n // Also priced per reference image on an edit (`minimaxH3ImageCreditId`).\n \"minimax-h3-image\": \"resolution\",\n \"minimax-h3-image-i2i\": \"resolution\",\n // By size alone, the same on both ids (`flux3KleinCreditId`).\n \"flux-3-klein\": \"resolution\",\n \"flux-3-klein-i2i\": \"resolution\",\n}\n\n\n// Models where quality=high triggers composite credit identifier\nexport const HIGH_QUALITY_PROVIDERS = new Set([\"gpt-image\", \"gpt-image-i2i\", \"seedream\", \"seedream-edit\", \"seedream-5-lite\", \"seedream-5-lite-i2i\", \"seedream-5-pro\", \"seedream-5-pro-i2i\"])\n\n// Models where resolution=2K triggers composite credit identifier\nexport const TWO_K_RESOLUTION_PROVIDERS = new Set([\"flux\", \"flux-pro-i2i\", \"flux-flex\", \"flux-i2i\"])\n\n// Models where both 2K and 4K resolutions trigger composite credit identifiers (1K is base)\nexport const RESOLUTION_2K_4K_TIERED_PROVIDERS = new Set([\n \"nano-banana-2\",\n \"nano-banana-2-1\",\n \"gpt-image-2\",\n \"gpt-image-2-i2i\",\n \"gpt-image-2-5-flare\",\n \"gpt-image-2-5-flare-i2i\",\n \"gpt-image-2-5-sunburst\",\n \"gpt-image-2-5-sunburst-i2i\",\n \"wan-2.7\",\n \"wan-2.7-pro\",\n])\n\n// Ideogram family models with TURBO/QUALITY pricing variants\n// `ideogram-reframe` (KIE `ideogram/v3-reframe`) was retired 2026-09-15: KIE no\n// longer documents the model and every task — the minimal documented payload\n// included — fails upstream with \"[500] internal error\" (#1331). Its price rows\n// are removed by migration 424; re-add everywhere per the Provider Enum Sync\n// table if KIE brings it back.\nexport const IDEOGRAM_PROVIDERS = new Set([\"ideogram-edit\", \"ideogram-remix\", \"ideogram-v3\"])\n\n// =====================================================================\n// Provider arrays (single source of truth for route Zod validation)\n// =====================================================================\n\n/** Text-to-image providers (no input image required) */\nexport const IMAGE_GEN_PROVIDERS = [\n \"nano-banana\",\n \"flux\",\n \"nano-banana-pro\",\n \"nano-banana-2\",\n \"nano-banana-2-lite\",\n \"nano-banana-2-1\",\n \"grok\",\n \"grok-2\",\n \"gpt-image\",\n \"gpt-image-2\",\n \"gpt-image-2-5-flare\",\n \"gpt-image-2-5-sunburst\",\n \"gpt-image-2-6-flare\",\n \"gpt-image-2-6-sunburst\",\n \"gpt-image-2-6-economy\",\n \"imagen4\",\n \"imagen4-fast\",\n \"imagen4-ultra\",\n \"ideogram-v3\",\n \"qwen\",\n \"seedream\",\n \"seedream-5-lite\",\n \"seedream-5-pro\",\n \"seedream-5-flash\",\n \"minimax-h3-image\",\n \"seedream-5-5\",\n \"flux-flex\",\n \"flux-kontext\",\n \"flux-kontext-max\",\n \"flux-3-klein\",\n \"z-image\",\n \"wan-2.7\",\n \"wan-2.7-pro\",\n // Replicate Open (uncensored) — runs through Replicate, not KIE\n \"flux-2-klein\",\n \"flux-2-pro\",\n \"flux-2-max\",\n] as const\n\n/** Image-to-image providers (require input image) */\nexport const IMAGE_I2I_PROVIDERS = [\n \"nano-banana\",\n \"nano-banana-2\",\n \"nano-banana-2-lite\",\n \"nano-banana-2-1\",\n \"nano-banana-pro\",\n \"grok-i2i\",\n \"flux-i2i\",\n \"flux-pro-i2i\",\n \"gpt-image-i2i\",\n \"gpt-image-2-i2i\",\n \"gpt-image-2-5-flare-i2i\",\n \"gpt-image-2-5-sunburst-i2i\",\n \"gpt-image-2-6-flare-i2i\",\n \"gpt-image-2-6-sunburst-i2i\",\n \"gpt-image-2-6-economy-i2i\",\n \"grok-2-i2i\",\n \"ideogram-edit\",\n \"ideogram-remix\",\n \"qwen-i2i\",\n \"qwen-edit\",\n \"seedream-edit\",\n \"seedream-5-lite-i2i\",\n \"seedream-5-pro-i2i\",\n \"seedream-5-flash-i2i\",\n \"minimax-h3-image-i2i\",\n \"seedream-5-5-i2i\",\n \"flux-kontext\",\n \"flux-kontext-max\",\n \"flux-3-klein-i2i\",\n // Replicate Open (uncensored) — multi-image Kontext via Replicate\n \"kontext-multi\",\n // BFL Flux 2 Pro — runs through Replicate\n \"flux-2-pro\",\n // BFL FLUX Fill Pro — dedicated masked inpainting via Replicate (white = edit area)\n \"flux-fill\",\n // BFL Flux 2 Max — runs through Replicate, up to 8 refs\n \"flux-2-max\",\n // BFL FLUX Fill Pro — dedicated inpainting via Replicate (image + mask + prompt,\n // white = edit area). Second mask-capable i2i provider alongside ideogram-edit.\n \"flux-fill\",\n] as const\n\n/**\n * Image editing providers (upscale, remove bg, etc.)\n *\n * `grok-upscale` was retired 2026-10-29: it never upscaled an image. The id was\n * wired to the provider's `grok-imagine/upscale`, which upscales a Grok VIDEO\n * task (its task id must be a text-to-video or image-to-video task), and the\n * provider offers no Grok image upscale at all — every run was refused\n * upstream. Its price row is removed by migration 567; the edit-image route\n * answers the id with a 400 naming the replacement. A Grok video upscale, if\n * ever offered, is a new id on the video-upscale node.\n */\nexport const IMAGE_EDIT_PROVIDERS = [\n \"recraft-upscale\",\n \"recraft-remove-bg\",\n \"nano-banana-edit\",\n \"topaz-image-upscale\",\n // Nodaro Image Upscale: 1x to 8x, priced by the output's size.\n \"nodaro-image-upscale\",\n // Grok Imagine 2 task-chained ops — a prior grok-2 generation's task_id (NOT\n // an image URL); see the edit-image route for the taskId-vs-imageUrl\n // branching. grok-2-edit: prompt edit of a prior grok-2 generation,\n // optionally region-targeted via mask indexes from grok-2-segment.\n // grok-2-segment: FREE named segment-mask map of a prior grok-2 generation.\n \"grok-2-edit\",\n \"grok-2-segment\",\n] as const\n\n/**\n * Edit providers that take a PRIOR KIE Grok generation's task id instead of\n * an image URL. Single source of truth for the taskId-vs-imageUrl branching:\n * the edit-image route requires `taskId` (imageUrl alone is rejected), the\n * worker routes `taskId` into the provider call, and the KIE model config\n * (`imageParam: \"task_id\"`) places it in the request body. Membership here\n * must match the KIE configs with `imageParam: \"task_id\"` — guarded by\n * backend/src/routes/__tests__/edit-image.test.ts.\n *\n * The ids as a tuple ({@link TaskChainedEditProvider} is its type); the Set is\n * built from it, so the two cannot disagree.\n */\nexport const TASK_CHAINED_EDIT_PROVIDER_IDS = [\n \"grok-2-edit\",\n \"grok-2-segment\",\n] as const satisfies readonly (typeof IMAGE_EDIT_PROVIDERS)[number][]\nexport type TaskChainedEditProvider = typeof TASK_CHAINED_EDIT_PROVIDER_IDS[number]\nexport const TASK_CHAINED_EDIT_PROVIDERS: ReadonlySet<string> = new Set(TASK_CHAINED_EDIT_PROVIDER_IDS)\n\n/** Modify image providers (I2I + edit-with-prompt) */\nexport const MODIFY_IMAGE_PROVIDERS = [\n ...IMAGE_I2I_PROVIDERS,\n \"nano-banana-edit\",\n] as const\nexport type ModifyImageProvider = typeof MODIFY_IMAGE_PROVIDERS[number]\n\n/** Image upscale providers */\nexport const UPSCALE_IMAGE_PROVIDERS = [\n \"recraft-upscale\",\n \"topaz-image-upscale\",\n \"nodaro-image-upscale\",\n] as const\nexport type UpscaleImageProvider = typeof UPSCALE_IMAGE_PROVIDERS[number]\n\n// Derived types from provider arrays\nexport type ImageGenProvider = typeof IMAGE_GEN_PROVIDERS[number]\nexport type ImageI2IProvider = typeof IMAGE_I2I_PROVIDERS[number]\nexport type ImageEditProvider = typeof IMAGE_EDIT_PROVIDERS[number]\n\n/** Image-to-video providers */\nexport const IMAGE_TO_VIDEO_PROVIDERS = [\n \"minimax\",\n \"veo3\",\n \"veo3.1\",\n \"veo3_lite\",\n \"kling\",\n \"kling-turbo\",\n \"kling-3.0\",\n \"kling-master\",\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n \"seedance-2-5\",\n \"minimax-h3\",\n \"hailuo-2.3-pro\",\n \"hailuo-2.3\",\n \"hailuo-standard\",\n \"wan-i2v\",\n \"wan-turbo\",\n \"bytedance-lite\",\n \"bytedance-pro\",\n \"bytedance-pro-fast\",\n \"grok-i2v\",\n \"wan-2.7-i2v\",\n \"happyhorse-i2v\",\n \"happyhorse-ref2v\",\n \"runway-kie\",\n \"kling-3-omni\",\n \"gemini-omni-video\",\n \"gemini-omni-flash\",\n \"gemini-omni-flash-1-2\",\n // Wan 3.0 family — one id per SKU serves BOTH modes (no t2v twin, no alias),\n // so each id is listed in this array AND in TEXT_TO_VIDEO_PROVIDERS.\n \"wan-3\",\n \"wan-3-prime\",\n // Vidu Q4 — one id over KIE's image-to-video and reference-to-video\n // endpoints. No text-to-video mode: also listed in TEXT_TO_VIDEO_PROVIDERS's\n // image-required section so the t2v route answers with the friendly 400.\n \"vidu-q4\",\n // Kling 4.0 — two ids, one per KIE endpoint (reference-to-video and\n // keyframe-to-video). Each endpoint also runs with no image, so each id is\n // listed here AND in TEXT_TO_VIDEO_PROVIDERS's main section (like wan-3).\n \"kling-4\",\n \"kling-4-keyframes\",\n // Kling 4.0 Flash — one id over KIE's two Flash endpoints (picked by what is\n // wired); both run with no image, so it is listed in both arrays too.\n \"kling-4-flash\",\n // PixVerse V6 Max — one id over KIE's image-to-video and text-to-video\n // endpoints (picked by whether a start frame is wired), so it is listed in\n // this array AND in TEXT_TO_VIDEO_PROVIDERS's main section.\n \"pixverse-v6-max\",\n \"ltx-2.3-pro\",\n \"ltx-2.3-fast\",\n // xAI Grok Imagine Video 1.5 — KIE i2v (a start image required). Also listed in\n // TEXT_TO_VIDEO_PROVIDERS so it's offered everywhere in the unified node; the\n // t2v route guards no-image runs via VIDEO_PROVIDERS_REQUIRING_IMAGE.\n \"grok-imagine-video-1.5\",\n // Replicate disabled\n // \"runway\",\n // \"pika\",\n // \"sora\",\n] as const\nexport type ImageToVideoProvider = typeof IMAGE_TO_VIDEO_PROVIDERS[number]\n\n/** Text-to-video providers */\nexport const TEXT_TO_VIDEO_PROVIDERS = [\n \"minimax\",\n \"veo3\",\n \"veo3.1\",\n \"veo3_lite\",\n \"kling\",\n \"kling-turbo\",\n \"kling-3.0\",\n \"grok\",\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n \"seedance-2-5\",\n \"minimax-h3\",\n \"wan\",\n \"hailuo-standard\",\n \"bytedance-lite\",\n \"bytedance-pro\",\n \"wan-turbo\",\n \"wan-2.7-t2v\",\n \"happyhorse\",\n \"runway-kie\",\n \"gemini-omni-video\",\n \"gemini-omni-flash\",\n \"gemini-omni-flash-1-2\",\n // Wan 3.0 family — REAL t2v (prompt-only runs are the documented default\n // mode), so they belong in this main section and must NOT be gated by\n // VIDEO_PROVIDERS_REQUIRING_IMAGE.\n \"wan-3\",\n \"wan-3-prime\",\n // Kling 4.0 — both endpoints take a prompt-only run (reference-to-video with\n // no materials, keyframe-to-video with no frame).\n \"kling-4\",\n \"kling-4-keyframes\",\n \"kling-4-flash\",\n // PixVerse V6 Max — a real text-to-video endpoint runs an image-less request.\n \"pixverse-v6-max\",\n \"ltx-2.3-pro\",\n \"ltx-2.3-fast\",\n // ── i2v-only providers (image required) ──────────────────────────────────\n // These have NO text-to-video mode, but the unified Generate Video node can\n // dispatch ANY of its providers down the t2v path when no image is wired.\n // They must pass this enum so /v1/text-to-video can return the clean\n // \"requires an input image\" 400 (VIDEO_PROVIDERS_REQUIRING_IMAGE — derived\n // from MODEL_CATALOG modes) instead of an opaque Zod validation error.\n // They never reach a provider. Guarded by the dispatch-totality test in\n // __tests__/video-mode-aliases.test.ts.\n \"grok-imagine-video-1.5\",\n \"kling-3-omni\",\n \"kling-master\",\n \"hailuo-2.3\",\n \"hailuo-2.3-pro\",\n \"bytedance-pro-fast\",\n \"happyhorse-ref2v\",\n \"vidu-q4\",\n // Replicate disabled\n // \"runway\",\n // \"pika\",\n // \"sora\",\n] as const\nexport type TextToVideoProvider = typeof TEXT_TO_VIDEO_PROVIDERS[number]\n\n/** Unified video-generation providers (image-to-video ∪ text-to-video) for the generate-video node. */\nexport const VIDEO_GEN_PROVIDERS = [\n ...IMAGE_TO_VIDEO_PROVIDERS,\n ...TEXT_TO_VIDEO_PROVIDERS.filter(\n (p): p is typeof TEXT_TO_VIDEO_PROVIDERS[number] =>\n !(IMAGE_TO_VIDEO_PROVIDERS as readonly string[]).includes(p),\n ),\n] as const\nexport type VideoGenProvider = typeof VIDEO_GEN_PROVIDERS[number]\n\n/**\n * Video models that expose DISTINCT provider ids per mode (text-to-video vs\n * image-to-video) but represent ONE user-facing model. KIE keys i2v and t2v off\n * different ids in different maps (KIE_VIDEO_MODELS vs KIE_TEXT_TO_VIDEO_MODELS),\n * so each id only resolves to a real model in its native mode.\n *\n * The unified Generate Video node shows ONE picker row (the `base` id) and\n * auto-selects the mode by whether an input image is present; execution remaps\n * base→mode id via {@link resolveVideoProviderForMode}. This registry is the\n * single source of truth shared by the picker collapse (frontend\n * `model-options.ts`), the frontend DAG executor (`execute-node.ts`), and the\n * backend orchestrator (`payload-builder.ts`) so they can't drift.\n *\n * `base` MUST be one of the group's own mode ids (kept = the i2v id, since the\n * unified picker's i2v entries win on collision). Honesty invariants are guarded\n * in `__tests__/video-mode-aliases.test.ts`.\n */\nexport interface VideoModeAlias {\n /** Canonical id stored on the node + shown in the unified picker. */\n base: string\n /** KIE id to use when an input image is present (image-to-video). */\n i2v: string\n /** KIE id to use for pure text-to-video. */\n t2v: string\n}\n\nexport const VIDEO_MODE_ALIASES: readonly VideoModeAlias[] = [\n { base: \"grok-i2v\", i2v: \"grok-i2v\", t2v: \"grok\" },\n { base: \"wan-i2v\", i2v: \"wan-i2v\", t2v: \"wan\" },\n { base: \"wan-2.7-i2v\", i2v: \"wan-2.7-i2v\", t2v: \"wan-2.7-t2v\" },\n // HappyHorse: happyhorse/image-to-video + happyhorse/text-to-video are mode\n // twins of one KIE model family — previously TWO unified-picker rows, and the\n // i2v row crashed the t2v route when run without an image.\n { base: \"happyhorse-i2v\", i2v: \"happyhorse-i2v\", t2v: \"happyhorse\" },\n] as const\n\n/**\n * Video model ids the provider retired, each with the model it now runs as.\n * They have no catalog entry and are in no provider list: every boundary that\n * receives a stored or sent id (editor load, a run's payload and its estimate,\n * a request body, the video worker, a pipeline pin, the MCP model choice, the\n * credit id) passes it through {@link canonicalVideoProvider} first,\n * so a saved node, an app run or an API call naming one keeps working and is\n * priced as the model it runs as.\n *\n * - `seedance` (Seedance 1.5 Pro, KIE `bytedance/seedance-1.5-pro`): retired\n * upstream 2026-10-25 (KIE answers 410). Runs as Seedance 2 Mini, the\n * cheapest Seedance left (owner's decision 2026-10-25).\n * - `seedance-2-extend` (the one Seedance Extend Video provider, its model\n * chosen by the deployment): split 2026-11-11 into one provider per model.\n * Runs as `seedance-2-5-extend`, the Seedance 2.5 extend, and is priced on\n * its rows; `seedance-2-0-extend` is the Seedance 2.0 one.\n */\nexport const RETIRED_VIDEO_PROVIDERS: Readonly<Record<string, string>> = {\n seedance: \"seedance-2-mini\",\n \"seedance-2-extend\": \"seedance-2-5-extend\",\n}\n\n/** A retired video model id becomes the id it runs as; any other value passes through unchanged. Own properties only. */\nexport function canonicalVideoProvider<T>(provider: T): T | string {\n return typeof provider === \"string\" && Object.hasOwn(RETIRED_VIDEO_PROVIDERS, provider)\n ? RETIRED_VIDEO_PROVIDERS[provider]!\n : provider\n}\n\n/**\n * Resolve a (possibly base / cross-mode) video provider id to the concrete KIE\n * id for the given execution mode. Accepts any member id of an alias group\n * (base, i2v, or t2v) so existing workflows that stored either mode's id keep\n * working, and a retired id ({@link RETIRED_VIDEO_PROVIDERS}) as the model it\n * runs as. Non-aliased providers (single-id models, VEO, Replicate, etc.) pass\n * through unchanged.\n */\nexport function resolveVideoProviderForMode(\n rawProvider: string,\n mode: \"image-to-video\" | \"text-to-video\",\n): string {\n const provider = canonicalVideoProvider(rawProvider)\n for (const g of VIDEO_MODE_ALIASES) {\n if (provider === g.base || provider === g.i2v || provider === g.t2v) {\n return mode === \"image-to-video\" ? g.i2v : g.t2v\n }\n }\n return provider\n}\n\n/**\n * Which execution mode a unified Generate Video run takes from what is wired.\n * Shared by the frontend DAG executor (`execute-node.ts`) and the backend\n * orchestrator (`payload-builder.ts`) so the two cannot disagree.\n *\n * A start frame is image-to-video, full stop. Reference images ALONE are the\n * nuance: most models forward refs on either path, but a split-id model\n * (VIDEO_MODE_ALIASES) can carry them on one twin only — Grok Imagine 1's\n * text-to-video endpoint has no image parameter at all, while its i2v twin\n * takes up to 7. Refs wired without a start frame used to resolve to t2v →\n * `grok` → silently dropped (#861). When refs are present and ONLY the i2v\n * twin can carry them, the run is image-to-video with the refs as its images.\n * Derived from VIDEO_REF_LIMITS_BY_PROVIDER (= the catalog's `reference-image`\n * feature), never from a provider name.\n *\n * A SINGLE-id model with no text-to-video mode is the other nuance: its t2v\n * lane is image-gated (VIDEO_PROVIDERS_REQUIRING_IMAGE), so a references-only\n * run sent there was refused even when the provider runs happily from\n * references alone (Vidu Q4, HappyHorse Ref2V). When the catalog declares the\n * `reference-to-video` capability ({@link videoProviderRunsFromReferences}),\n * such a run takes the image-to-video lane with the refs as its images —\n * exactly what `/v1/generate-video` already did for the direct API. A single-id\n * model WITH a text-to-video mode keeps the t2v lane, which carries its refs.\n */\nexport function resolveVideoModeForInputs(\n provider: string | undefined,\n inputs: { readonly hasStartFrame: boolean; readonly hasImageRefs: boolean },\n): \"image-to-video\" | \"text-to-video\" {\n if (inputs.hasStartFrame) return \"image-to-video\"\n if (!provider || !inputs.hasImageRefs) return \"text-to-video\"\n const i2v = resolveVideoProviderForMode(provider, \"image-to-video\")\n const t2v = resolveVideoProviderForMode(provider, \"text-to-video\")\n if (i2v === t2v) {\n const entry = MODEL_CATALOG[i2v]\n const noTextMode = !!entry && !(entry.modes as readonly string[]).includes(\"t2v\")\n return noTextMode && videoProviderRunsFromReferences(i2v) ? \"image-to-video\" : \"text-to-video\"\n }\n const carriesImageRefs = (id: string) => (VIDEO_REF_LIMITS_BY_PROVIDER[id]?.images ?? 0) > 0\n return carriesImageRefs(i2v) && !carriesImageRefs(t2v) ? \"image-to-video\" : \"text-to-video\"\n}\n\n/** The prompt syntax a video provider addresses its images in, by array order. */\nexport type VideoReferenceSyntax = \"@image_N\" | \"@image(n)\" | \"[Image N]\" | \"image N\"\n\n/**\n * The syntax this video model's frame / identity binding sentences are written\n * in — the catalog's `referenceSyntax`, else the platform's `@image_N`. One\n * descriptor for the app's resolvers and for a client (the cloud plugins) that\n * cites references by ordinal.\n */\nexport function videoProviderReferenceSyntax(provider: string | undefined): VideoReferenceSyntax {\n return (provider ? MODEL_CATALOG[provider]?.referenceSyntax : undefined) ?? \"@image_N\"\n}\n\n/**\n * Reference-capable video models whose start/end frames ride a channel of\n * their OWN (separate frame parameters next to the reference list), so a frame\n * never occupies a reference seat: `kling-3-omni` (Replicate `start_image` /\n * `end_image`, no dispatch path today), Kling 4.0 Keyframes (KIE\n * `first_frame_url` / `last_frame_url` beside its in-between `keyframe_urls`)\n * and Grok Imagine Video 1.5 (KIE `first_frame_url` / `last_frame_url` /\n * `loop_url` beside its in-between `keyframes`).\n */\nexport const VIDEO_PROVIDERS_WITH_SEPARATE_FRAME_CHANNEL: ReadonlySet<string> = new Set([\n \"kling-3-omni\",\n \"kling-4-keyframes\",\n \"grok-imagine-video-1.5\",\n])\n\n/**\n * True when this video model puts a start (and end) frame AFTER the caller's\n * own reference images in ONE shared image list, bound in the prompt as the\n * opening / closing frame in its own syntax — the platform convention, so the\n * caller's image token N always means their Nth reference. At the image cap\n * the frames are kept and trailing caller references are dropped.\n *\n * Every reference-capable video model, except one whose frames ride a separate\n * channel ({@link VIDEO_PROVIDERS_WITH_SEPARATE_FRAME_CHANNEL}).\n */\nexport function videoProviderAppendsFrames(provider: string | undefined): boolean {\n if (!provider) return false\n const entry = MODEL_CATALOG[provider]\n return !!entry && entry.kind === \"video\" &&\n entry.features?.includes(\"reference-image\") === true &&\n !VIDEO_PROVIDERS_WITH_SEPARATE_FRAME_CHANNEL.has(provider)\n}\n\n/**\n * How many of a reference run's image seats the wired frames take on this\n * model: the start frame, plus the end frame where the model takes one (the\n * catalog `end-frame` feature). 0 on a model whose frames do not share its\n * reference list. A caller budgeting its own references subtracts this from\n * the provider's image cap so no reference of its is dropped.\n */\nexport function videoProviderRefModeFrameSeats(\n provider: string | undefined,\n frames: { readonly hasStartFrame: boolean; readonly hasEndFrame: boolean },\n): number {\n if (!provider) return 0\n if (!videoProviderAppendsFrames(provider)) return 0\n const start = frames.hasStartFrame ? 1 : 0\n const end = frames.hasEndFrame && MODEL_CATALOG[provider]?.features?.includes(\"end-frame\") === true ? 1 : 0\n return start + end\n}\n\n/**\n * True when the model's provider endpoint runs from reference images ALONE —\n * no start frame (the catalog's `reference-to-video` feature, declared only on\n * provider-spec evidence). The single capability every surface reads to decide\n * whether wired references satisfy \"needs an image\": the mode resolver above,\n * and through it the editor gate, the browser DAG and the orchestrator.\n */\nexport function videoProviderRunsFromReferences(provider: string | undefined): boolean {\n return !!provider && MODEL_CATALOG[provider]?.features?.includes(\"reference-to-video\") === true\n}\n\n/**\n * t2v twin ids hidden from the unified Generate Video picker — the i2v/base\n * entry already represents both modes (execution remaps by image presence).\n * Only includes twins whose `base` is NOT the t2v id, so the surviving picker\n * entry is the base. Consumed by the frontend `VIDEO_GEN_MODELS` collapse.\n */\nexport const VIDEO_GEN_COLLAPSED_T2V_IDS: ReadonlySet<string> = new Set(\n VIDEO_MODE_ALIASES.filter((g) => g.t2v !== g.base).map((g) => g.t2v),\n)\n\n/** Video-to-video providers */\nexport const VIDEO_TO_VIDEO_PROVIDERS = [\n \"wan\",\n \"wan-flash\",\n \"wan-videoedit\",\n \"luma-modify\",\n \"runway-aleph\",\n \"happyhorse-edit\",\n] as const\nexport type VideoToVideoProvider = typeof VIDEO_TO_VIDEO_PROVIDERS[number]\n\n/**\n * Seedance models the Video to Video NODE offers as a whole-clip, prompt-driven\n * EDIT (\"make it black and white\", \"she wears @image_1\").\n *\n * These are deliberately NOT members of {@link VIDEO_TO_VIDEO_PROVIDERS} (the\n * `/v1/video-to-video` route's own enum): Seedance has no separate edit\n * endpoint — it edits a REFERENCE video when the prompt reads as an edit. So\n * every surface (single-node run, DAG payload builder, MCP `modify_video`)\n * dispatches these through the ONE existing Seedance reference-video lane\n * (`text-to-video`), with the source clip as `@video_1` and the edit shape\n * below. Reference-clip bounds, the unit×(input+output) reservation, the\n * measured settlement, the edit-mode retry and the reconcile recovery are that\n * lane's — there is no second copy to keep in step.\n */\nexport const SEEDANCE_VIDEO_EDIT_PROVIDERS = [\"seedance-2-5\"] as const\nexport type SeedanceVideoEditProvider = typeof SEEDANCE_VIDEO_EDIT_PROVIDERS[number]\n\nexport function isSeedanceVideoEditProvider(provider: string | undefined): provider is SeedanceVideoEditProvider {\n return !!provider && (SEEDANCE_VIDEO_EDIT_PROVIDERS as readonly string[]).includes(provider)\n}\n\n/** Every model the Video to Video node can be set to: the route's own providers\n * plus the Seedance edit models dispatched through the text-to-video lane. */\nexport const VIDEO_TO_VIDEO_NODE_PROVIDERS = [...VIDEO_TO_VIDEO_PROVIDERS, ...SEEDANCE_VIDEO_EDIT_PROVIDERS] as const\nexport type VideoToVideoNodeProvider = typeof VIDEO_TO_VIDEO_NODE_PROVIDERS[number]\n\n/**\n * The model a Video to Video request or node that names none runs on: the\n * route's and the worker's default, and what the node's model menu shows for an\n * unset model. One constant, so the server and the editor cannot disagree.\n */\nexport const DEFAULT_VIDEO_TO_VIDEO_PROVIDER: VideoToVideoNodeProvider = \"wan\"\n\n/**\n * The request shape Seedance edit mode requires, sent UP FRONT by the Video to\n * Video node: the output takes the source clip's own ratio and length\n * (`adaptive`, and Auto = `VIDEO_DURATION_AUTO`). Camel-cased twin of the KIE\n * wire pair the provider layer resubmits with when Seedance reclassifies an\n * ordinary run as an edit.\n */\nexport const SEEDANCE_VIDEO_EDIT_SHAPE = { aspectRatio: \"adaptive\", duration: VIDEO_DURATION_AUTO } as const\n\n/**\n * The reference task type a purpose-built Seedance video edit requests (the\n * Video to Video route and node, MCP `modify_video`): the reference video is\n * the clip to edit, said outright instead of left to the prompt. A request, not\n * a promise: `resolveSeedanceTaskType` declares it only when the edit's\n * reference videos qualify, and otherwise the edit goes out undeclared, as\n * before. Kept apart from `SEEDANCE_VIDEO_EDIT_SHAPE`, whose exact value other\n * callers spread and pin.\n */\nexport const SEEDANCE_VIDEO_EDIT_TASK_TYPE = \"edit\" as const satisfies DeclaredSeedanceTaskType\n\n/** Face swap providers */\nexport const FACE_SWAP_PROVIDERS = [\n \"roop\",\n] as const\nexport type FaceSwapProvider = typeof FACE_SWAP_PROVIDERS[number]\n\n/** Video upscale providers */\nexport const VIDEO_UPSCALE_PROVIDERS = [\n \"topaz\",\n \"veo-1080p\",\n \"veo-4k\",\n // Seedance 2.5 Draft finalize: re-renders a Seedance 2.5 DRAFT (by its task\n // id) as the same take at 1080p. See seedance-draft.ts.\n \"seedance-2-5-hd\",\n // Nodaro Video Upscale: any clip up to 60 s / 50 MB into a 1080p, 2K or 4K\n // box, priced per second. Offered only where the deployment serves it (see\n // nodaro-video-upscale.ts).\n \"nodaro-video-upscale\",\n] as const\nexport type VideoUpscaleProvider = typeof VIDEO_UPSCALE_PROVIDERS[number]\n\n/** Extend video providers */\nexport const EXTEND_VIDEO_PROVIDERS = [\n \"veo-extend\",\n \"runway-extend\",\n \"ltx-2.3-pro\",\n // Seedance extends ANY video, one provider per model: Seedance 2.5 (4–30 s\n // added) and Seedance 2.0 (4–15 s), each priced on its own rows\n // (`tailExtendCreditId`). The earlier single id `seedance-2-extend` is\n // retired (RETIRED_VIDEO_PROVIDERS) and runs as Seedance 2.5.\n \"seedance-2-5-extend\",\n \"seedance-2-0-extend\",\n // Kling 4 extends ANY video the same way (3–30 s added, 720p / 1080p, its\n // sound always on), generated on Kling 4.0 and priced on its own rows.\n \"kling-4-extend\",\n // PixVerse V6 extends ANY video natively (1–15 s added, 360p–1080p, a sound\n // switch): the whole source goes in and comes back with the new seconds\n // joined on, of which only the new ones are kept. Priced on its own rows.\n \"pixverse-v6-extend\",\n // Grok extends only its OWN clips (a Grok Imagine text-to-video or\n // image-to-video run of the same user), named by their task: 6 or 10 s\n // added at the source's resolution, delivered as Grok returns it.\n \"grok-extend\",\n] as const\nexport type ExtendVideoProvider = typeof EXTEND_VIDEO_PROVIDERS[number]\n\n/** The Extend Video providers that run on Seedance, one per model. */\nexport type SeedanceExtendProvider = Extract<ExtendVideoProvider, \"seedance-2-5-extend\" | \"seedance-2-0-extend\">\nconst SEEDANCE_EXTEND_PROVIDERS: readonly SeedanceExtendProvider[] = [\"seedance-2-5-extend\", \"seedance-2-0-extend\"]\n\n/**\n * Whether a value is one of the Seedance Extend Video providers. A retired id\n * answers false: pass it through {@link canonicalVideoProvider} first. It\n * decides the levers only Seedance has (reference images, the sound switch);\n * the length, the resolution and the price follow {@link isTailExtendProvider}.\n */\nexport function isSeedanceExtendProvider(p: unknown): p is SeedanceExtendProvider {\n return typeof p === \"string\" && (SEEDANCE_EXTEND_PROVIDERS as readonly string[]).includes(p)\n}\n\n/**\n * The Extend Video providers that continue a video from its tail: the\n * source's last frame opens the new footage and its last seconds ride as the\n * `@video_1` reference, then the two are stitched into one clip. Each has its\n * own catalog entry (its seconds added and resolutions) and price rows, one\n * per second and resolution (`tailExtendCreditId`).\n */\nexport type TailExtendProvider = SeedanceExtendProvider | Extract<ExtendVideoProvider, \"kling-4-extend\">\nconst TAIL_EXTEND_PROVIDERS: readonly TailExtendProvider[] = [...SEEDANCE_EXTEND_PROVIDERS, \"kling-4-extend\"]\n\n/**\n * Whether a value is one of the tail-recipe Extend Video providers\n * ({@link TailExtendProvider}). A retired id answers false: pass it through\n * {@link canonicalVideoProvider} first.\n */\nexport function isTailExtendProvider(p: unknown): p is TailExtendProvider {\n return typeof p === \"string\" && (TAIL_EXTEND_PROVIDERS as readonly string[]).includes(p)\n}\n\n/**\n * PixVerse V6 Extend: a native extend, no tail recipe. The whole source goes\n * to PixVerse's own extend, which returns it with the new seconds joined on;\n * the run keeps the user's source and joins only the new seconds to it.\n */\nexport type PixverseExtendProvider = Extract<ExtendVideoProvider, \"pixverse-v6-extend\">\nexport const PIXVERSE_V6_EXTEND_PROVIDER: PixverseExtendProvider = \"pixverse-v6-extend\"\n\n/** Whether a value is {@link PIXVERSE_V6_EXTEND_PROVIDER}. */\nexport function isPixverseExtendProvider(p: unknown): p is PixverseExtendProvider {\n return p === PIXVERSE_V6_EXTEND_PROVIDER\n}\n\n/**\n * The Extend Video providers whose levers come from their own catalog entry —\n * the seconds added (`durations`, `defaultDuration`) and the resolution\n * (`resolutions`) — and which are priced one row per second added and\n * resolution (`catalogExtendCreditId`): the tail recipes\n * ({@link TailExtendProvider}) and PixVerse V6. Each extends any video by URL.\n * A retired id answers false: pass it through {@link canonicalVideoProvider} first.\n */\nexport type CatalogExtendProvider = TailExtendProvider | PixverseExtendProvider\n\n/** Whether a value is a {@link CatalogExtendProvider}. */\nexport function isCatalogExtendProvider(p: unknown): p is CatalogExtendProvider {\n return isTailExtendProvider(p) || isPixverseExtendProvider(p)\n}\n\n/**\n * Whether an Extend Video provider has a sound switch (`generateAudio`, on\n * unless turned off): Seedance's, which continue the soundtrack, and PixVerse\n * V6's, whose sound is priced on its own rows. Kling 4's sound is always on.\n */\nexport function extendHasSoundSwitch(p: unknown): boolean {\n return isSeedanceExtendProvider(p) || isPixverseExtendProvider(p)\n}\n\n/**\n * Grok Extend: a native extend of Grok's OWN clips only — a completed Grok\n * Imagine text-to-video or image-to-video run of the same user, named by its\n * task (the upstream node hands it on, as VEO's extend takes its own). It adds\n * 6 or 10 s at the SOURCE's resolution, which is never a lever: so it is no\n * {@link CatalogExtendProvider}, and is priced by `grokExtendCreditId` on the\n * resolution the source check answers.\n */\nexport type GrokExtendProvider = Extract<ExtendVideoProvider, \"grok-extend\">\nexport const GROK_EXTEND_PROVIDER: GrokExtendProvider = \"grok-extend\"\n\n/** Whether a value is {@link GROK_EXTEND_PROVIDER}. */\nexport function isGrokExtendProvider(p: unknown): p is GrokExtendProvider {\n return p === GROK_EXTEND_PROVIDER\n}\n\n/**\n * The Grok Imagine video models whose clips Grok Extend can extend: text-to-\n * video's id and image-to-video's (not Grok Imagine Video 1.5, a different\n * model on the provider's side).\n */\nexport const GROK_EXTEND_SOURCE_MODELS = [\"grok\", \"grok-i2v\"] as const\n\n/** Whether a model is one of {@link GROK_EXTEND_SOURCE_MODELS}. */\nexport function isGrokExtendSourceModel(p: unknown): boolean {\n return typeof p === \"string\" && (GROK_EXTEND_SOURCE_MODELS as readonly string[]).includes(p)\n}\n\n/** Lip sync providers */\nexport const LIP_SYNC_PROVIDERS = [\n \"kling-avatar\",\n \"kling-avatar-pro\",\n \"infinitalk\",\n // ByteDance OmniHuman 1.5 — KIE image+audio avatar, prompt-directed\n // performance, per-second billed, 60s audio cap. Routes the default KIE\n // path (not in any replicate/fal/seedance/video-input set).\n \"omnihuman-1-5\",\n // ByteDance OmniHuman 2.0 — a different model from 1.5 (no speaker mask, no\n // resolution choice, no fast mode, no seed; 720p output). KIE image+audio\n // avatar on the default KIE path, charged per second of its audio at a rate\n // (LIP_SYNC_AUDIO_RATES), never by bucket.\n \"omnihuman-2-0\",\n \"latentsync\",\n // (Wav2Lip, VideoReTalking and SadTalker were retired 2026-11-12:\n // RETIRED_LIP_SYNC_PROVIDERS below.)\n // HeyGen Lipsync Precision + Sync Lipsync 2 Pro — Replicate-hosted, video-input\n // dubbing models billed per second of output. Routed through replicateLipSync;\n // priced per-second via buildLipSyncCreditId (see lip-sync-pricing.ts).\n \"heygen-lipsync-precision\",\n \"lipsync-2-pro\",\n // Sync Lipsync v3 — fal.ai-hosted, video-input dubbing model billed per\n // second of output (/min). Routed through falLipSync (the worker's fal\n // branch); priced per-second via buildLipSyncCreditId (see lip-sync-pricing.ts).\n \"sync-lipsync-v3\",\n // Volcengine video-to-video lip sync — KIE-hosted, VIDEO-input AI dubbing\n // (mode lite/basic; multi-speaker scene-detection + speaker ID in basic).\n // Billed per-second via buildLipSyncCreditId; routed through the KIE\n // `lipSyncVideo` path (KieModelConfig.inputKind === \"video\"), NOT the\n // image+prompt `lipSync` path.\n \"volcengine-lipsync\",\n // Seedance 2 / 2 Fast — not \"lip-sync models\" per se, but ByteDance's\n // multimodal video models do native phoneme-level lip sync in 8+\n // languages when fed `reference_audio_urls` alongside a `first_frame_url`.\n // Routed through the i2v provider with the audio passed as a reference,\n // not the dedicated lip-sync flow.\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n \"seedance-2-5\",\n // MiniMax Hailuo 3 — same multimodal audio-driven mechanism (r2v\n // reference_audio_urls paired with an image ref); rides the same\n // reference-audio lip-sync surface as the Seedance 2 family.\n \"minimax-h3\",\n] as const\nexport type LipSyncProvider = typeof LIP_SYNC_PROVIDERS[number]\n\n/**\n * Lip Sync models the platform no longer offers (retired 2026-11-12), with the\n * name each is shown by. They left every menu, the route's accepted values and\n * the MCP tool; a request, a saved or imported workflow node or an app run that\n * still names one is refused before anything is reserved, with\n * {@link retiredLipSyncProviderMessage} — never moved to another model, whose\n * inputs and price differ. The editor shows a saved node on one as retired and\n * leaves the choice of another model to the person.\n */\nexport const RETIRED_LIP_SYNC_PROVIDERS: Readonly<Record<string, string>> = {\n wav2lip: \"Wav2Lip\",\n \"video-retalking\": \"VideoReTalking\",\n sadtalker: \"SadTalker\",\n}\n\n/** The name of a retired Lip Sync model, or undefined for any other value. Own keys only (the value is request input). */\nexport function retiredLipSyncProviderName(provider: unknown): string | undefined {\n return typeof provider === \"string\" && Object.hasOwn(RETIRED_LIP_SYNC_PROVIDERS, provider)\n ? RETIRED_LIP_SYNC_PROVIDERS[provider]\n : undefined\n}\n\n/** The refusal a run of a retired Lip Sync model gets, or undefined for any other value. */\nexport function retiredLipSyncProviderMessage(provider: unknown): string | undefined {\n const name = retiredLipSyncProviderName(provider)\n return name === undefined ? undefined : `${name} is no longer available for Lip Sync. Pick another Lip Sync model.`\n}\n\n/** Multimodal video models exposed via the lip-sync surface (Seedance 2 family\n * + MiniMax Hailuo 3). They go through the i2v provider with the audio\n * plumbed as `reference_audio_urls` rather than a dedicated lip-sync flow.\n * (Name kept for the Seedance-era public export.) */\nexport const SEEDANCE_LIP_SYNC_PROVIDERS = new Set<string>([\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n \"seedance-2-5\",\n \"minimax-h3\",\n])\n\n/** Replicate-based lip-sync providers (video or image+audio via Replicate SDK).\n * The retired ones ran there too (`RETIRED_LIP_SYNC_PROVIDERS`). */\nexport const REPLICATE_LIP_SYNC_PROVIDERS = new Set([\n \"latentsync\",\n \"heygen-lipsync-precision\",\n \"lipsync-2-pro\",\n] as const)\n\n/** fal.ai-based lip-sync providers (video+audio → video via the fal queue API).\n * Routed through `falLipSync` in the worker's `handleLipSync` fal branch. */\nexport const FAL_LIP_SYNC_PROVIDERS = new Set([\n \"sync-lipsync-v3\",\n] as const)\n\n/** Lip-sync providers that require video input (not image). A retired id\n * stays in this set and the next: a saved node on it keeps the handles its\n * edges attach to until the person picks another model. */\nexport const VIDEO_INPUT_LIP_SYNC_PROVIDERS = new Set([\n \"latentsync\",\n \"video-retalking\",\n \"heygen-lipsync-precision\",\n \"lipsync-2-pro\",\n \"sync-lipsync-v3\",\n \"volcengine-lipsync\",\n] as const)\n\n/** Lip-sync providers that accept either video or image input */\nexport const FLEXIBLE_INPUT_LIP_SYNC_PROVIDERS = new Set([\n \"wav2lip\",\n] as const)\n\n/** Standard aspect ratio → pixel dimensions for composition nodes */\nexport const ASPECT_RATIO_DIMENSIONS: Record<string, { width: number; height: number }> = {\n \"16:9\": { width: 1920, height: 1080 },\n \"9:16\": { width: 1080, height: 1920 },\n \"1:1\": { width: 1080, height: 1080 },\n \"4:5\": { width: 1080, height: 1350 },\n // Ultra-wide. 1680x720 rather than a 1920-wide pair because the Scene3D v2\n // admission bounds require even integers on both axes and 1920/(21/9) is\n // odd; 1680x720 is the pair the scene contract names as supported. Additive:\n // every consumer here is a keyed lookup with a fallback, and a node only\n // reaches this entry if its own aspect enum offers 21:9 (today, Pro 3D).\n \"21:9\": { width: 1680, height: 720 },\n}\n\n/** Motion transfer providers */\nexport const MOTION_TRANSFER_PROVIDERS = [\n \"kling\",\n \"kling-3.0\",\n \"wan-animate-move\",\n \"wan-animate-replace\",\n] as const\nexport type MotionTransferProviderType = typeof MOTION_TRANSFER_PROVIDERS[number]\n\n/** Text-to-speech providers */\nexport const TTS_PROVIDERS = [\n \"elevenlabs-v3\",\n \"elevenlabs-v4\",\n \"elevenlabs-v4-turbo\",\n \"elevenlabs-turbo\",\n \"elevenlabs-multilingual\",\n // Google's Gemini speech through KIE (decided 2026-11-12): named voices of\n // their own (`TtsCapabilities.voices`), never ElevenLabs'.\n \"gemini-3-8-flash-lite-tts\",\n \"gemini-3-8-flash-tts\",\n \"gemini-3-1-flash-tts\",\n \"gemini-2-5-pro-tts\",\n \"elevenlabs\",\n] as const\nexport type TtsProvider = typeof TTS_PROVIDERS[number]\n\n/**\n * The file a speech request can ask for (`outputFormat` on `/v1/text-to-speech`\n * and the `text-to-speech` node run), named as the vendor names its formats:\n * `codec_samplerate_bitrate`. Omitted ⇒ the first, which is exactly what every\n * request delivered before the field existed. The list is deliberately short:\n * the three the hosted deployment's vendor account serves (measured 2026-11-08);\n * a self-hosted install's account must serve them too, or a run asking for one\n * fails with the vendor's own message.\n */\nexport const TTS_OUTPUT_FORMATS = [\"mp3_44100_128\", \"mp3_44100_192\", \"wav_24000\"] as const\nexport type TtsOutputFormat = typeof TTS_OUTPUT_FORMATS[number]\nexport const DEFAULT_TTS_OUTPUT_FORMAT: TtsOutputFormat = \"mp3_44100_128\"\n/** How each format is stored and served: the file extension and the MIME type. */\nexport const TTS_OUTPUT_FORMAT_FILES: Readonly<Record<TtsOutputFormat, { readonly ext: \"mp3\" | \"wav\"; readonly mime: \"audio/mpeg\" | \"audio/wav\" }>> = {\n mp3_44100_128: { ext: \"mp3\", mime: \"audio/mpeg\" },\n mp3_44100_192: { ext: \"mp3\", mime: \"audio/mpeg\" },\n wav_24000: { ext: \"wav\", mime: \"audio/wav\" },\n}\n\n/**\n * Text-to-dialogue models (the `provider` of `/v1/text-to-dialogue` and of the\n * Text to Dialogue node). Each IS its catalog id and its credit identifier.\n * The ElevenLabs dialogue models are dialogue-only ids, never members of\n * TTS_PROVIDERS: their dialogue endpoint is its own model. Google's Gemini\n * models take one speaker and two under ONE id, so each is in both lists,\n * priced on its one row (dialogue costs what one speaker costs per character,\n * decided 2026-11-12); `dialogue-capabilities.test.ts` pins exactly that.\n */\nexport const DIALOGUE_PROVIDERS = [\n \"elevenlabs-dialogue\",\n \"elevenlabs-dialogue-v4\",\n \"gemini-3-8-flash-lite-tts\",\n \"gemini-3-8-flash-tts\",\n \"gemini-3-1-flash-tts\",\n \"gemini-2-5-pro-tts\",\n] as const\nexport type DialogueProvider = typeof DIALOGUE_PROVIDERS[number]\n\n/** The model a dialogue request runs on when its provider is missing or unknown: v3 dialogue (decided 2026-10-04 — v3 stays the default). */\nexport const DEFAULT_DIALOGUE_PROVIDER: DialogueProvider = \"elevenlabs-dialogue\"\n\n/**\n * The speech model a request runs on when it names none — ElevenLabs v4 since the\n * default flip (decided 2026-10-05; v3 stays selectable). The REST route's credit\n * guard and handler, the workflow engine's text-to-speech dispatch, the worker's\n * defensive default, the MCP `generate_speech` tool, the narration pipeline, the\n * video director and the editor's new-node default all read THIS, so they can never\n * disagree about which model ran and which one was billed. A request with no model\n * also follows a length rule: text longer than this model's cap runs on turbo instead.\n * The REST route, the workflow engine, the narration pipeline and the worker apply it\n * through one backend function; the MCP tool refuses such text with the number.\n */\nexport const DEFAULT_TTS_PROVIDER: TtsProvider = \"elevenlabs-v4\"\n\n/** Text-to-audio providers */\nexport const TEXT_TO_AUDIO_PROVIDERS = [\n // Replicate disabled\n // \"tangoflux\",\n \"elevenlabs-sfx\",\n] as const\nexport type TextToAudioProvider = typeof TEXT_TO_AUDIO_PROVIDERS[number]\n\n/**\n * The Text to Audio engine used when a request names none — the route's\n * credit reservation, the worker, the orchestrator payload and the editor's\n * node default all read THIS, so they can never disagree about which model\n * ran and which one was billed.\n */\nexport const DEFAULT_TEXT_TO_AUDIO_PROVIDER: TextToAudioProvider = \"elevenlabs-sfx\"\n\n/** Music generation providers */\nexport const MUSIC_PROVIDERS = [\n // Replicate disabled\n // \"musicgen\",\n \"minimax\",\n // TODO: surface Suno V5 here for discoverability — needs backend wiring\n // through suno-client.ts (Suno uses /api/v1/generate, NOT the standard\n // /api/v1/jobs/createTask path runKieTask uses). Tracked as a separate\n // follow-up PR. Until then, Suno is reachable via the standalone\n // `suno-generate` node.\n // Replicate disabled\n // \"lyria\",\n // \"bark\",\n] as const\nexport type MusicProvider = typeof MUSIC_PROVIDERS[number]\n\n/** The model a Generate Music node runs when its data names none it offers. */\nexport const DEFAULT_MUSIC_PROVIDER: MusicProvider = \"minimax\"\n\n/** Each music model's name as the node shows it. The catalog's \"minimax\" is the\n * MiniMax VIDEO model, so its label cannot stand in. */\nexport const MUSIC_PROVIDER_LABELS: Readonly<Record<MusicProvider, string>> = {\n minimax: \"MiniMax Music\",\n}\n\n/**\n * The credit id every Generate Music run reserves on — the route's guard and\n * the orchestrator's payload both use it, whatever the model. The estimates\n * and the node's price read it too: the model id would price the MiniMax VIDEO\n * model that shares the name (\"minimax\").\n */\nexport const MUSIC_CREDIT_ID = \"generate-music\"\n\n/**\n * The music model a Generate Music node runs: its `provider` when the node\n * offers it, else the default. Nodes saved with a model that is gone (\"suno\",\n * \"musicgen\", \"lyria\", \"bark\" — or the \"suno\" new nodes started on) run the\n * default instead of failing validation. Coerces rather than rejects, like\n * `normalizeModelInput`: the only model to fall back to is the one there is.\n */\nexport function resolveMusicProvider(value: unknown): MusicProvider {\n return (MUSIC_PROVIDERS as readonly unknown[]).includes(value) ? (value as MusicProvider) : DEFAULT_MUSIC_PROVIDER\n}\n\n/**\n * Transcription providers a caller may name — on `/v1/transcribe`, the SDK/CLI\n * and the canvas Transcribe node. All three lanes are served on cloud again\n * (the canvas picker re-offered the two Replicate lanes in #768 while this enum\n * still hid them, so a single-node Run on Whisper 400'd where the same node in a\n * workflow Run worked). `elevenlabs-stt` stays FIRST: several call sites take\n * \"the first enabled word-capable provider\" from this order. A new engine goes\n * at the END (Nemotron 3.5 Transcribe, 2026-11-12), so that answer never moves.\n */\nexport const TRANSCRIBE_PROVIDERS = [\n \"elevenlabs-stt\",\n \"whisper\",\n \"incredibly-fast-whisper\",\n \"nemotron-3-5-transcribe\",\n] as const\nexport type TranscribeProvider = typeof TRANSCRIBE_PROVIDERS[number]\n\n/**\n * Every transcription LANE the platform implements. Today this is the same set\n * as `TRANSCRIBE_PROVIDERS`; it stays a separate name because the two answer\n * different questions — \"what may a caller name\" vs \"what can run\" — and they\n * have diverged before (the Replicate lanes were hidden from callers for months\n * while still reached at runtime via the route default and add-captions'\n * auto-transcribe). Capability questions must be asked over THIS union.\n */\nexport const TRANSCRIBE_LANES = [\n \"whisper\",\n \"incredibly-fast-whisper\",\n \"elevenlabs-stt\",\n \"nemotron-3-5-transcribe\",\n] as const\nexport type TranscribeLane = typeof TRANSCRIBE_LANES[number]\n\n// Compile-time pin: the user-facing enum is a subset of the lanes, so every\n// provider a caller can name has a capability row below.\nconst _TRANSCRIBE_PROVIDERS_ARE_LANES: readonly TranscribeLane[] = TRANSCRIBE_PROVIDERS\nvoid _TRANSCRIBE_PROVIDERS_ARE_LANES\n\n/**\n * The lanes Add Captions may transcribe on (its `transcribe_provider`, on the\n * route, MCP `add_captions` and the SDK's `media.addCaptions`). Its flat render\n * price (`add-captions:kinetic`) covers the transcription on every lane but\n * Nemotron 3.5 Transcribe, which is priced by the video's length: a caption\n * run on it holds the render plus Nemotron's per-minute price as ONE charge\n * (`add-captions:kinetic:nemotron:<N>m`, decided 2026-11-13), always with word\n * timings and never a translation. A new lane here is a pricing decision, not\n * a sync.\n */\nexport const CAPTION_TRANSCRIBE_LANES = [\n \"whisper\",\n \"incredibly-fast-whisper\",\n \"elevenlabs-stt\",\n \"nemotron-3-5-transcribe\",\n] as const satisfies readonly TranscribeLane[]\nexport type CaptionTranscribeLane = typeof CAPTION_TRANSCRIBE_LANES[number]\n\n/**\n * What each transcription lane can actually DO. Single source of truth — never\n * re-derive a capability from a provider-name check.\n *\n * `wordTimestamps`: does the lane return per-word start/end times?\n * - `whisper` (Replicate `openai/whisper`) — NO. Its input schema has no\n * `word_timestamps` field in ANY published version, so Replicate silently\n * drops the key and the segments come back without `words`. Asking this lane\n * for word timings yields an empty array, never an error.\n * - `incredibly-fast-whisper` — yes, via `timestamp: \"word\"`.\n * - `elevenlabs-stt` (direct Scribe) — always word-level, flag or not.\n * - `nemotron-3-5-transcribe` (KIE) — yes, with a speaker per word, via\n * `timestamps: true` (transcription only: never with a translation).\n *\n * `translation`: can the lane translate the speech instead of transcribing it\n * (`targetLanguage`)? Only Nemotron 3.5 Transcribe, to or from English, and\n * never together with word timings (KIE refuses the pair).\n */\nexport const TRANSCRIBE_PROVIDER_CAPABILITIES: Record<TranscribeLane, { wordTimestamps: boolean; translation: boolean }> = {\n \"whisper\": { wordTimestamps: false, translation: false },\n \"incredibly-fast-whisper\": { wordTimestamps: true, translation: false },\n \"elevenlabs-stt\": { wordTimestamps: true, translation: false },\n \"nemotron-3-5-transcribe\": { wordTimestamps: true, translation: true },\n}\n\n/**\n * The languages Nemotron 3.5 Transcribe translates INTO (KIE's\n * `target_language` enum, ISO 639-1). Translation is supported to or from\n * English: other speech into `en`, or English speech into any other listed\n * language. Fewer than the 40 it transcribes.\n */\nexport const TRANSCRIBE_TARGET_LANGUAGES = [\n \"en\", \"zh\", \"ja\", \"ko\", \"fr\", \"de\", \"es\", \"pt\", \"it\", \"ru\", \"nl\", \"pl\", \"cs\", \"sk\", \"hi\", \"bg\",\n \"hr\", \"da\", \"et\", \"fi\", \"hu\", \"lv\", \"lt\", \"ro\", \"sl\", \"sv\", \"th\", \"uk\", \"ar\", \"el\", \"he\", \"mt\",\n] as const\nexport type TranscribeTargetLanguage = typeof TRANSCRIBE_TARGET_LANGUAGES[number]\n\n/** The lanes that can translate, in declaration order. */\nexport function transcribeProvidersWithTranslation(): TranscribeLane[] {\n return TRANSCRIBE_LANES.filter((p) => TRANSCRIBE_PROVIDER_CAPABILITIES[p].translation)\n}\n\n/**\n * Capability question for a lane id from UNTRUSTED data (node data, an\n * imported workflow, a wire body): an unknown lane answers `false`.\n */\nexport function transcribeLaneSupportsTranslation(lane: string | null | undefined): boolean {\n if (!lane) return false\n return TRANSCRIBE_PROVIDER_CAPABILITIES[lane as TranscribeLane]?.translation === true\n}\n\n/** The lanes that can honour a word-timestamps request, in declaration order. */\nexport function transcribeProvidersWithWordTimestamps(): TranscribeLane[] {\n return TRANSCRIBE_LANES.filter((p) => TRANSCRIBE_PROVIDER_CAPABILITIES[p].wordTimestamps)\n}\n\n/**\n * Capability question for a lane id that came from UNTRUSTED data — node data,\n * an imported workflow, a wire body — where the string may be anything at all.\n * An unknown lane answers `false`: we cannot promise word timings from a lane\n * we know nothing about, and \"false\" is always the safe answer (it suppresses\n * an INFERRED request, and turns an EXPLICIT one into the honest refusal in\n * `transcribe()` instead of a `Cannot read properties of undefined` TypeError).\n */\nexport function transcribeLaneSupportsWordTimestamps(lane: string | null | undefined): boolean {\n if (!lane) return false\n return TRANSCRIBE_PROVIDER_CAPABILITIES[lane as TranscribeLane]?.wordTimestamps === true\n}\n\n/**\n * The lane an absent `provider` resolves to — the historical `/v1/transcribe`\n * default, kept as-is because the credit guard reserves on the provider id\n * (changing it would silently change what bills).\n */\nexport const DEFAULT_TRANSCRIBE_PROVIDER: TranscribeLane = \"whisper\"\n\n/**\n * The lane a transcribe NODE with no `provider` in its data resolves to —\n * deliberately NOT `DEFAULT_TRANSCRIBE_PROVIDER`. The route's default is the\n * legacy whisper lane and exists only so a pre-existing REST caller keeps\n * billing the same id; a node authored/imported without a provider is a fresh\n * request, and the canvas picker's own default is this one. Single-sourced so\n * the backend DAG (`payload-builder.ts`) and the frontend run\n * (`execute-node.ts`) cannot drift into sending different engines for the same\n * node — they did, and the frontend's silent whisper fallback started 400ing\n * once the Replicate lanes left `TRANSCRIBE_PROVIDERS`.\n */\nexport const DEFAULT_TRANSCRIBE_NODE_PROVIDER: TranscribeLane = \"elevenlabs-stt\"\n\n/** Script generation providers */\nexport const SCRIPT_PROVIDERS = [\n \"gemini\",\n \"claude\",\n \"gpt\",\n] as const\nexport type ScriptProvider = typeof SCRIPT_PROVIDERS[number]\n\n/** AI writer providers */\nexport const AI_WRITER_PROVIDERS = [\n \"claude\",\n] as const\nexport type AiWriterProvider = typeof AI_WRITER_PROVIDERS[number]\n\n/** QA check providers */\nexport const QA_CHECK_PROVIDERS = [\n \"claude\",\n \"gpt\",\n] as const\nexport type QaCheckProvider = typeof QA_CHECK_PROVIDERS[number]\n\n/**\n * The current Suno generation (docs.kie.ai/suno-api/generate-music, 2026-09:\n * the V6 family), listed first in every picker; V6 is the default.\n *\n * - V6 — flagship: greater musical expression, more natural vocals, richer details.\n * - V6_WILD — bolder, more distinctive, less predictable output for exploration.\n * - V6_MINI — lightweight and fast; quality/speed balance.\n *\n * This is also the set that honours `duration` ({@link SUNO_DURATION_MODELS}).\n */\nexport const SUNO_ACTIVE_MODELS = [\"V6\", \"V6_WILD\", \"V6_MINI\"] as const\nexport type SunoActiveModel = typeof SUNO_ACTIVE_MODELS[number]\n\n/**\n * The earlier Suno generations. Still offered in every picker as ordinary\n * choices (users report each has its own character), still accepted by every\n * route, and confirmed generating on 2026-09-11. KIE's docs tag them\n * \"Discontinued\"; if KIE ever stops serving one, coerce it to\n * {@link DEFAULT_SUNO_MODEL} at the provider send seam — never remove it from\n * {@link SUNO_MODELS}, which would 400 every saved music workflow.\n */\nexport const SUNO_LEGACY_MODELS = [\n \"V5_5\",\n \"V5\",\n \"V4_5PLUS\",\n \"V4_5ALL\",\n \"V4_5\",\n \"V4\",\n] as const\nexport type SunoLegacyModel = typeof SUNO_LEGACY_MODELS[number]\n\n/**\n * Every Suno model version — the picker order, the route / MCP Zod enum and\n * the `data.model` type on Suno nodes. Current generation first (V6 = default),\n * then the earlier generations newest-first.\n */\nexport const SUNO_MODELS = [...SUNO_ACTIVE_MODELS, ...SUNO_LEGACY_MODELS] as const\nexport type SunoModel = typeof SUNO_MODELS[number]\n\n/** The Suno version used when a caller omits `model` — KIE's own default. */\nexport const DEFAULT_SUNO_MODEL = \"V6\" satisfies SunoActiveModel\n\nexport function isLegacySunoModel(model: string | undefined): model is SunoLegacyModel {\n return (SUNO_LEGACY_MODELS as readonly string[]).includes(model ?? \"\")\n}\n\n/**\n * Suno versions that HONOUR `duration` (custom mode only). Per the generate /\n * extend docs the field \"will only take effect when the model is V6, V6_MINI,\n * or V6_WILD\" — V5_5 was struck from that sentence when V6 shipped. The\n * provider client's send-gate (`sunoGenerate` in suno-client.ts) is the single\n * chokepoint that consults this set; the editor uses it only to decide whether\n * to SHOW the duration field.\n */\nexport const SUNO_DURATION_MODELS: ReadonlySet<string> = new Set<SunoModel>(SUNO_ACTIVE_MODELS)\n\nexport function sunoModelHonoursDuration(model: string | undefined): boolean {\n return SUNO_DURATION_MODELS.has(model ?? \"\")\n}\n\n/**\n * Suno models accepted by add-instrumental / add-vocals (docs enum: the V6\n * family plus V4_5PLUS / V5 / V5_5). Same current-then-earlier order as\n * {@link SUNO_MODELS}.\n */\nexport const SUNO_ADD_TRACK_MODELS = [...SUNO_ACTIVE_MODELS, \"V4_5PLUS\", \"V5\", \"V5_5\"] as const\nexport type SunoAddTrackModel = typeof SUNO_ADD_TRACK_MODELS[number]\n\n/** Voice design models */\nexport const VOICE_DESIGN_MODELS = [\n \"eleven_ttv_v3\",\n \"eleven_multilingual_ttv_v2\",\n] as const\nexport type VoiceDesignModel = typeof VOICE_DESIGN_MODELS[number]\n\n/**\n * ElevenLabs' newest text-to-voice model (all languages) — the default when\n * a voice-design caller omits `model`. Single-sourced here so the route\n * (`backend/src/routes/voice-design.ts`) and the direct-API provider\n * (`backend/src/providers/elevenlabs/voice-design.ts`) can't drift.\n */\nexport const DEFAULT_VOICE_DESIGN_MODEL: VoiceDesignModel = \"eleven_ttv_v3\"\n\n/**\n * I2I providers that take an inpainting mask (`maskUrl`, white = the area to\n * change, black = keep) as the model's own mask. The provider converts the\n * mask into the form its model reads. Every catalog entry listing the\n * `\"mask\"` feature (`/v1/models`, MCP `list_models`) is one of these.\n */\nexport const I2I_MASK_SUPPORT = new Set([\n \"ideogram-edit\",\n \"flux-fill\",\n \"gpt-image-2-6-flare-i2i\",\n \"gpt-image-2-6-sunburst-i2i\",\n])\n\n/**\n * Mask edit tier per image-gen provider (single source of truth for inpaint).\n * - \"native\" → provider takes a real mask param (reserved for Phase 1.5; none today)\n * - \"prompt\" → strong instruction editor; inject a region descriptor into the prompt\n * - \"composite\" → rely on the always-on server-side composite floor only\n * Floor (B·(1−M)+E·M) applies to EVERY tier, so any provider is correct.\n */\nexport type ImageMaskMode = \"native\" | \"prompt\" | \"composite\"\n\nexport const IMAGE_MASK_MODE: Record<ImageGenProvider, ImageMaskMode> = {\n \"nano-banana\": \"prompt\",\n \"nano-banana-pro\": \"prompt\",\n \"nano-banana-2\": \"prompt\",\n \"nano-banana-2-lite\": \"prompt\",\n \"nano-banana-2-1\": \"prompt\",\n \"gpt-image\": \"prompt\",\n \"gpt-image-2\": \"prompt\",\n \"gpt-image-2-5-flare\": \"prompt\",\n \"gpt-image-2-5-sunburst\": \"prompt\",\n \"gpt-image-2-6-flare\": \"prompt\",\n \"gpt-image-2-6-sunburst\": \"prompt\",\n \"gpt-image-2-6-economy\": \"prompt\",\n \"seedream\": \"prompt\",\n \"seedream-5-lite\": \"prompt\",\n \"seedream-5-pro\": \"prompt\",\n \"seedream-5-flash\": \"prompt\",\n \"minimax-h3-image\": \"prompt\",\n \"seedream-5-5\": \"prompt\",\n \"flux-3-klein\": \"prompt\",\n \"qwen\": \"prompt\",\n \"flux-kontext\": \"prompt\",\n \"flux-kontext-max\": \"prompt\",\n \"flux\": \"composite\",\n \"flux-flex\": \"composite\",\n \"grok\": \"composite\",\n \"grok-2\": \"composite\",\n \"imagen4\": \"composite\",\n \"imagen4-fast\": \"composite\",\n \"imagen4-ultra\": \"composite\",\n \"ideogram-v3\": \"composite\",\n \"z-image\": \"composite\",\n \"wan-2.7\": \"composite\",\n \"wan-2.7-pro\": \"composite\",\n \"flux-2-klein\": \"composite\",\n \"flux-2-pro\": \"composite\",\n \"flux-2-max\": \"composite\",\n}\n\n/** I2I providers that support a strength/denoising parameter */\nexport const I2I_STRENGTH_SUPPORT: Record<string, { min: number; max: number; step: number; default: number }> = {\n \"ideogram-remix\": { min: 0.01, max: 1, step: 0.01, default: 0.8 },\n \"qwen-i2i\": { min: 0, max: 1, step: 0.01, default: 0.8 },\n}\n\n/** Models that accept a seed parameter for reproducible generation */\nexport const SEED_SUPPORT = new Set([\n \"ideogram-remix\", \"ideogram-v3\",\n \"qwen\", \"qwen-i2i\", \"qwen-edit\",\n \"flux\", \"flux-flex\", \"flux-i2i\", \"flux-pro-i2i\", \"flux-kontext\", \"flux-kontext-max\",\n \"flux-2-klein\", \"kontext-multi\",\n \"minimax-h3-image\", \"minimax-h3-image-i2i\",\n \"flux-3-klein\", \"flux-3-klein-i2i\",\n])\n\n/** Ideogram models that support rendering_speed selection (TURBO/BALANCED/QUALITY) */\nexport const RENDERING_SPEED_SUPPORT = new Set([\n \"ideogram-remix\", \"ideogram-v3\",\n])\n\n/** Models that accept guidance_scale for controlling prompt adherence */\nexport const GUIDANCE_SCALE_SUPPORT: Record<string, { min: number; max: number; step: number; default: number }> = {\n \"qwen-i2i\": { min: 1, max: 20, step: 0.5, default: 7 },\n \"qwen-edit\": { min: 1, max: 20, step: 0.5, default: 7 },\n}\n\n// =====================================================================\n// Video variable pricing — duration-based and audio-addon pricing\n// =====================================================================\n\n/**\n * Video models where credit cost varies by duration.\n * Maps provider key → duration tier breakpoints.\n * Values are verified by the pricing verification script (backend/scripts/verify-kie-pricing.ts).\n * TODO: Run verification script and update costs after confirming actual KIE pricing.\n */\nexport const DURATION_PRICED_PROVIDERS = new Set([\n \"kling-3.0\",\n \"kling-3-omni\",\n \"kling\",\n \"kling-turbo\",\n \"kling-master\",\n \"grok-i2v\",\n \"wan-i2v\",\n \"hailuo-2.3-pro\",\n \"hailuo-2.3\",\n \"hailuo-standard\",\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n \"seedance-2-5\",\n \"minimax-h3\",\n \"grok-imagine-video-1.5\",\n \"happyhorse\",\n \"happyhorse-i2v\",\n \"happyhorse-ref2v\",\n // Wan 3.0 family — per-second billing at three resolution rates. NOTE:\n // gemini-omni-flash is deliberately ABSENT (like gemini-omni-video): the\n // Gemini Omni branch in buildVideoCreditModelIdentifier early-returns before\n // this gate is consulted.\n \"wan-3\",\n \"wan-3-prime\",\n // Vidu Q4 — per-second billing at five resolution rates, identical on both\n // endpoints and with audio on or off.\n \"vidu-q4\",\n // Kling 4.0 — per-second billing at two resolution rates (plus a reference-\n // video rate on `kling-4`, see VIDEO_REF_RATE_PROVIDERS).\n \"kling-4\",\n \"kling-4-keyframes\",\n // Kling 4.0 Flash — per-second billing at 720p, the same rate on both\n // endpoints, plus a reference-video rate (VIDEO_REF_RATE_PROVIDERS).\n \"kling-4-flash\",\n // Gemini Omni Flash 1.2 — per-second billing at four resolution rates. The\n // only Omni SKU here: the per-clip SKUs price in their own branch of\n // buildVideoCreditModelIdentifier.\n \"gemini-omni-flash-1-2\",\n // PixVerse V6 Max — per-second billing at four quality rates, each with and\n // without native audio (the `:audio` rows, AUDIO_ADDON_PROVIDERS).\n \"pixverse-v6-max\",\n])\n\n/**\n * Seedance 2.0 family — shared across UI gating, payload building, and pricing.\n * Expanded whenever a new Seedance 2.x variant ships.\n */\nexport const SEEDANCE_2_PROVIDERS = new Set<string>([\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n // Seedance 2.5 — a later generation, but it shares the whole 2.0 capability\n // surface this set gates (frames + image/video/audio refs, adaptive aspect,\n // per-second resolution × video-ref pricing), so it belongs here. Where it\n // DIFFERS (30s ceiling, no 1080p/4K, wider ref caps) the difference is\n // carried by the per-provider maps, never by branching on this set.\n \"seedance-2-5\",\n])\n\nexport function isSeedance2Provider(provider: string | undefined): boolean {\n return !!provider && SEEDANCE_2_PROVIDERS.has(provider)\n}\n\n/**\n * MiniMax Hailuo 3 family — the KIE \"minimax-h3\" market model. One Nodaro id\n * covers three KIE endpoints (text-to-video / image-to-video /\n * reference-to-video); the provider layer swaps the endpoint by which inputs\n * are present. Mirrors the Seedance 2 multimodal surface (frames + image/video/\n * audio references) with a two-rate resolution lever (2K default / 768P,\n * added 2026-08-03) and per-second pricing at the selected resolution's rate.\n * Exact-membership set — NEVER match on a \"minimax\" prefix (the unrelated\n * Hailuo 02 id \"minimax\" would collide).\n */\nexport const MINIMAX_H3_PROVIDERS = new Set<string>([\n \"minimax-h3\",\n])\n\nexport function isMinimaxH3Provider(provider: string | undefined): boolean {\n return !!provider && MINIMAX_H3_PROVIDERS.has(provider)\n}\n\n/** MiniMax Hailuo 3 resolution the model renders when the param is omitted or\n * unknown — the KIE-side default. */\nexport const MINIMAX_H3_DEFAULT_RESOLUTION = \"2K\"\n\n/**\n * SINGLE normalization for the MiniMax Hailuo 3 resolution lever (KIE wire\n * enum \"768P\" | \"2K\", default 2K) — shared by billing (credit-identifier\n * suffix, r2v compute hook, GVP per-second anchor) and the provider layer's\n * KIE forwarding. Only a case-insensitive \"768p\" selects the cheaper tier;\n * ANYTHING else (undefined, a stale Seedance \"720p\", garbage) collapses to\n * \"2K\" — exactly what KIE renders when the param is omitted/unknown, so the\n * billed tier can never undercut the rendered one.\n */\nexport function normalizeMinimaxH3Resolution(resolution: string | undefined): \"768P\" | \"2K\" {\n return resolution?.trim().toLowerCase() === \"768p\" ? \"768P\" : MINIMAX_H3_DEFAULT_RESOLUTION\n}\n\n/**\n * Wan 3.0 family — the KIE \"wan/3-0-video\" market model and its high-speed\n * \"wan/3-0-video-prime\" sibling. The two share a BYTE-IDENTICAL input schema\n * (first/last frame OR an all-purpose reference mode with images/videos/audio,\n * native `audio` boolean, 2-30s, 480P/720P/1080P, six aspect ratios with\n * `adaptive` as the default); only the per-second rate differs. Prime is the\n * FASTER tier at a higher rate — never describe it as \"higher quality\".\n *\n * Exact-membership set — NEVER match on a \"wan\" prefix: \"wan\", \"wan-i2v\",\n * \"wan-turbo\", \"wan-flash\", \"wan-videoedit\" and the \"wan-2.7-*\" ids are\n * unrelated 2.x models with a different surface (and a different reference\n * token format — see WAN_3_DOCTRINE in @nodaro/prompts).\n */\nexport const WAN_3_PROVIDERS = new Set<string>([\n \"wan-3\",\n \"wan-3-prime\",\n])\n\nexport function isWan3Provider(provider: string | undefined): boolean {\n return !!provider && WAN_3_PROVIDERS.has(provider)\n}\n\n/** Wan 3.0 resolution the PLATFORM renders when the param is omitted or unknown.\n * Deliberately NOT KIE's own default (1080P): 720p is the tier the bare credit\n * identifier prices, so the provider layer pins it to keep render == billed. */\nexport const WAN_3_DEFAULT_RESOLUTION = \"720P\"\n\n/**\n * SINGLE normalization for the Wan 3.0 resolution lever (KIE wire enum\n * \"480P\" | \"720P\" | \"1080P\"). Everything INTERNAL — the catalog, QUALITY_MAP,\n * dropdowns, RESOLUTION_DURATION_PRICING keys and every emitted credit\n * identifier — stays LOWERCASE; this helper is the ONE place the uppercase wire\n * form is produced (backend KIE payload build), the twin of\n * {@link normalizeMinimaxH3Resolution}.\n *\n * Case-insensitive. Anything else (undefined, garbage, a stale \"4k\") collapses\n * to {@link WAN_3_DEFAULT_RESOLUTION} — the tier the default credit identifier\n * reserves — so the billed tier can never undercut the rendered one.\n */\nexport function normalizeWan3Resolution(resolution: string | undefined): \"480P\" | \"720P\" | \"1080P\" {\n switch (resolution?.trim().toLowerCase()) {\n case \"480p\": return \"480P\"\n case \"1080p\": return \"1080P\"\n case \"720p\": return \"720P\"\n default: return WAN_3_DEFAULT_RESOLUTION\n }\n}\n\n/**\n * Vidu Q4 family — the KIE \"vidu-q4\" market model. One Nodaro id covers two KIE\n * endpoints (image-to-video / reference-to-video); the provider layer picks the\n * endpoint by which inputs are wired. Exact-membership set, like the other\n * family predicates.\n */\nexport const VIDU_Q4_PROVIDERS = new Set<string>([\n \"vidu-q4\",\n])\n\nexport function isViduQ4Provider(provider: string | undefined): boolean {\n return !!provider && VIDU_Q4_PROVIDERS.has(provider)\n}\n\n/** Vidu Q4 resolution the platform renders when the param is omitted or\n * unknown — the tier the bare credit identifier prices (also KIE's own\n * default). Never `resolutions[0]`, which is the cheaper 540p. */\nexport const VIDU_Q4_DEFAULT_RESOLUTION = \"720p\"\n\n/**\n * SINGLE normalization for the Vidu Q4 resolution lever. The KIE wire enum is\n * LOWERCASE (\"540p\" | \"720p\" | \"1080p\" | \"2k\" | \"4k\") — the same spelling as\n * the catalog and every credit identifier — so this only folds case and\n * collapses anything else (undefined, garbage, a stale \"480p\") to\n * {@link VIDU_Q4_DEFAULT_RESOLUTION}. The provider layer sends what this\n * returns and the credit identifier bills what this returns, so the two can\n * never disagree.\n */\nexport function normalizeViduQ4Resolution(resolution: string | undefined): \"540p\" | \"720p\" | \"1080p\" | \"2k\" | \"4k\" {\n switch (resolution?.trim().toLowerCase()) {\n case \"540p\": return \"540p\"\n case \"1080p\": return \"1080p\"\n case \"2k\": return \"2k\"\n case \"4k\": return \"4k\"\n case \"720p\": return \"720p\"\n default: return VIDU_Q4_DEFAULT_RESOLUTION\n }\n}\n\n/**\n * Kling 4.0 family — two Nodaro ids over KIE's two Kling 4.0 endpoints:\n * `kling-4` → `kling-4.0/reference-to-video`, `kling-4-keyframes` →\n * `kling-4.0/keyframe-to-video`. Exact-membership set.\n */\nexport const KLING_4_PROVIDERS = new Set<string>([\n \"kling-4\",\n \"kling-4-keyframes\",\n])\n\nexport function isKling4Provider(provider: string | undefined): provider is \"kling-4\" | \"kling-4-keyframes\" {\n return !!provider && KLING_4_PROVIDERS.has(provider)\n}\n\n/** Kling 4.0 resolution rendered when the param is omitted or unknown — KIE's\n * own default and the tier the bare credit identifier prices. */\nexport const KLING_4_DEFAULT_RESOLUTION = \"720p\"\n\n/**\n * SINGLE normalization for the Kling 4.0 resolution lever. The KIE wire enum is\n * lowercase (\"720p\" | \"1080p\"), the same spelling as the catalog and the credit\n * identifiers; this folds case and collapses anything else to\n * {@link KLING_4_DEFAULT_RESOLUTION}. The runner sends what this returns and\n * the credit identifier bills what this returns.\n */\nexport function normalizeKling4Resolution(resolution: string | undefined): \"720p\" | \"1080p\" {\n return resolution?.trim().toLowerCase() === \"1080p\" ? \"1080p\" : KLING_4_DEFAULT_RESOLUTION\n}\n\n/** Most in-between frames Kling 4.0 Keyframes takes (`keyframe_urls`). */\nexport const KLING_4_MAX_MIDDLE_FRAMES = 8\n\n/**\n * How many frames IN ALL (start + in-between + end) Kling 4.0 Keyframes\n * accepts for a clip of `durationSec` seconds — KIE's own table\n * (docs.kie.ai/market/kling/v4-keyframe-to-video): 3s → 4, 4s → 5 … 8s → 9,\n * 9s or longer → 10. Live-verified 2026-10-23: 5 frames at 3s is a 422\n * \"duration 3s allows at most 4 frames (first + keyframes + last), got 5\".\n */\nexport function kling4KeyframeFrameCap(durationSec: number | string | undefined): number {\n // The length the run renders: the catalog's default when unset, else the\n // nearest legal second — the same funnel the price reads.\n const d = pricedOutputDurationSec(\"kling-4-keyframes\", Number.isFinite(Number(durationSec)) ? durationSec : undefined)\n return Math.min(10, d + 1)\n}\n\n/**\n * Kling 4.0 Flash — ONE Nodaro id over KIE's two Flash endpoints\n * (`kling-4.0/flash-reference-to-video` and `kling-4.0/flash-keyframe-to-video`),\n * picked by what is wired: a start frame alone runs on the keyframe endpoint,\n * everything else on the reference endpoint (backend `kling4.ts`).\n *\n * Deliberately NOT a member of {@link KLING_4_PROVIDERS}: that set's branches\n * carry Kling 4.0's 1080p tier, its `voices` array, its Keyframes frame table\n * and its materials rule, none of which Flash has. Every place Flash shares\n * with Kling 4.0 opts in explicitly ({@link isKling4RunnerProvider}).\n */\nexport const KLING_4_FLASH_PROVIDER = \"kling-4-flash\"\n\nexport function isKling4FlashProvider(provider: string | undefined): provider is \"kling-4-flash\" {\n return provider === KLING_4_FLASH_PROVIDER\n}\n\n/** The one resolution Kling 4.0 Flash renders (both schemas: `720p` only). */\nexport const KLING_4_FLASH_RESOLUTION = \"720p\"\n\n/**\n * Every id the bespoke Kling 4.0 runner serves — Kling 4.0, its Keyframes twin\n * and Flash. Read only where the three behave the same: the provider dispatch,\n * the image normalization, the editor's UI defaults (aspect `auto`, 720p, 5s).\n * Anything about resolutions, frames, voices or the materials budget asks\n * {@link isKling4Provider} or {@link isKling4FlashProvider} instead.\n */\nexport function isKling4RunnerProvider(provider: string | undefined): provider is \"kling-4\" | \"kling-4-keyframes\" | \"kling-4-flash\" {\n return isKling4Provider(provider) || isKling4FlashProvider(provider)\n}\n\n/**\n * Grok Imagine Video 1.5 — KIE `grok-imagine-video-1-5-preview`\n * (docs.kie.ai/market/grok-imagine/1-5-preview), built by the backend's bespoke\n * runner (`kie/grok-video-15.ts`). Image to video: the start frame is the exact\n * first frame, an end frame the exact last frame (one picture wired as both is\n * a seamless loop), and the Image References are up to\n * {@link GROK_VIDEO_15_MAX_MIDDLE_FRAMES} in-between frames, each placed at a\n * whole second inside the clip.\n */\nexport const GROK_VIDEO_15_PROVIDER = \"grok-imagine-video-1.5\"\n\nexport function isGrokVideo15Provider(provider: string | undefined): provider is \"grok-imagine-video-1.5\" {\n return provider === GROK_VIDEO_15_PROVIDER\n}\n\n/** Grok Imagine Video 1.5 resolution rendered when the param is omitted or\n * unknown — KIE's own default and the tier the bare credit identifier prices. */\nexport const GROK_VIDEO_15_DEFAULT_RESOLUTION = \"480p\"\n\n/**\n * SINGLE normalization for the Grok Imagine Video 1.5 resolution lever. The KIE\n * wire enum is lowercase (`480p` | `720p` | `1080p`), the same spelling as the\n * catalog and the credit identifiers; this folds case and collapses anything\n * else to {@link GROK_VIDEO_15_DEFAULT_RESOLUTION}. The runner sends what this\n * returns and the credit identifier bills what this returns.\n */\nexport function normalizeGrokVideo15Resolution(resolution: string | undefined): \"480p\" | \"720p\" | \"1080p\" {\n const r = resolution?.trim().toLowerCase()\n return r === \"720p\" || r === \"1080p\" ? r : GROK_VIDEO_15_DEFAULT_RESOLUTION\n}\n\n/** Most in-between frames Grok Imagine Video 1.5 takes (KIE `keyframes`). */\nexport const GROK_VIDEO_15_MAX_MIDDLE_FRAMES = 4\n\n/**\n * PixVerse V6 Max — ONE Nodaro id over KIE's two V6 Max endpoints\n * (`pixverse-v6-max/image-to-video` with a start frame,\n * `pixverse-v6-max/text-to-video` without one), built by the backend's bespoke\n * runner (`kie/pixverse-v6-max.ts`).\n */\nexport const PIXVERSE_V6_MAX_PROVIDER = \"pixverse-v6-max\"\n\nexport function isPixverseV6MaxProvider(provider: string | undefined): provider is \"pixverse-v6-max\" {\n return provider === PIXVERSE_V6_MAX_PROVIDER\n}\n\n/** PixVerse V6 Max quality rendered when the param is omitted or unknown — the\n * tier the bare credit identifier prices. Never `resolutions[0]`, the 360p\n * preview tier. (KIE requires a quality; it has no default of its own.) */\nexport const PIXVERSE_V6_MAX_DEFAULT_QUALITY = \"720p\"\n\n/**\n * SINGLE normalization for the PixVerse V6 Max quality lever (KIE `quality`,\n * the platform's `resolution`). The wire enum is lowercase (`360p` | `540p` |\n * `720p` | `1080p`), the same spelling as the catalog and the credit\n * identifiers; this folds case and collapses anything else to\n * {@link PIXVERSE_V6_MAX_DEFAULT_QUALITY}. The runner sends what this returns\n * and the credit identifier bills what this returns.\n */\nexport function normalizePixverseV6MaxQuality(resolution: string | undefined): \"360p\" | \"540p\" | \"720p\" | \"1080p\" {\n const r = resolution?.trim().toLowerCase()\n return r === \"360p\" || r === \"540p\" || r === \"1080p\" ? r : PIXVERSE_V6_MAX_DEFAULT_QUALITY\n}\n\n/**\n * How many in-between frames a Grok Imagine Video 1.5 clip of `durationSec`\n * seconds carries. The node has no per-frame time, so the frames sit at whole\n * seconds strictly inside the clip, no two on the same second (decided\n * 2026-11-11): a D-second clip has D − 1 such seconds, and KIE takes at most\n * {@link GROK_VIDEO_15_MAX_MIDDLE_FRAMES}. Frames past this count are left out\n * (the runner logs it), never refused.\n */\nexport function grokVideo15MiddleFrameSlots(durationSec: number | string | undefined): number {\n // The length the run renders: the catalog's default when unset, else the\n // nearest legal second — the same funnel the price reads.\n const d = pricedOutputDurationSec(GROK_VIDEO_15_PROVIDER, Number.isFinite(Number(durationSec)) ? durationSec : undefined)\n return Math.max(0, Math.min(GROK_VIDEO_15_MAX_MIDDLE_FRAMES, d - 1))\n}\n\n/**\n * How many in-between frames (the Image References of a catalog `keyframes`\n * model) a run takes, given its length and which end frames are wired —\n * undefined for a model whose references are not frames. The editor's handle\n * cap and panel count read this, so the two cannot disagree.\n *\n * - Kling 4.0 Keyframes: the start and end frames share the clip's frame cap\n * ({@link kling4KeyframeFrameCap}), at most {@link KLING_4_MAX_MIDDLE_FRAMES}.\n * - Grok Imagine Video 1.5: {@link grokVideo15MiddleFrameSlots}; the start and\n * end frames ride their own fields and take no slot.\n */\nexport function videoKeyframesMiddleCap(\n provider: string | undefined,\n durationSec: number | string | undefined,\n frames: { readonly hasStartFrame: boolean; readonly hasEndFrame: boolean },\n): number | undefined {\n if (isGrokVideo15Provider(provider)) return grokVideo15MiddleFrameSlots(durationSec)\n if (provider === \"kling-4-keyframes\") {\n const ends = (frames.hasStartFrame ? 1 : 0) + (frames.hasEndFrame ? 1 : 0)\n return Math.max(0, Math.min(KLING_4_MAX_MIDDLE_FRAMES, kling4KeyframeFrameCap(durationSec) - ends))\n }\n return undefined\n}\n\n/**\n * Google Gemini Omni family — the KIE \"gemini-omni-video\" market model and its\n * faster/cheaper \"google/gemini-omni-flash-1-1\" sibling. Both take the SAME\n * request shape (prompt + image_urls references, video-edit through the i2v\n * handle, 4/6/8/10s, 720p/1080p or a 4K band) and are dispatched through the\n * same runner, so every behavioural branch that used to compare against the\n * literal \"gemini-omni-video\" must ask this predicate instead — V2V routing,\n * the 7-slot reference quota, the mode swap and the aspect-ratio panels.\n *\n * Exact-membership set — NEVER match on a \"gemini\" prefix (the Gemini LLM ids\n * would collide).\n */\nexport const GEMINI_OMNI_PROVIDERS = new Set<string>([\n \"gemini-omni-video\",\n \"gemini-omni-flash\",\n // Own request builder and per-second price: GEMINI_OMNI_PER_SECOND_PROVIDERS.\n \"gemini-omni-flash-1-2\",\n])\n\nexport function isGeminiOmniProvider(provider: string | undefined): boolean {\n return !!provider && GEMINI_OMNI_PROVIDERS.has(provider)\n}\n\n/**\n * The Gemini Omni SKUs billed per second of video (Gemini Omni Flash 1.2). What\n * the family shares (V2V through the i2v handle, the panels) comes from\n * {@link GEMINI_OMNI_PROVIDERS}. These differ in two ways: the price is a\n * `:<N>s:<res>` ladder, and a run with a source video bills that clip's own\n * seconds and nothing else (the output follows the clip), so they also answer\n * {@link billsReferenceVideoSeconds}.\n */\nexport const GEMINI_OMNI_PER_SECOND_PROVIDERS = new Set<string>([\n \"gemini-omni-flash-1-2\",\n])\n\nexport function isGeminiOmniPerSecondProvider(provider: string | undefined): boolean {\n return !!provider && GEMINI_OMNI_PER_SECOND_PROVIDERS.has(provider)\n}\n\n/** The longest source clip Gemini Omni Flash 1.2 takes (docs.kie.ai/market/google/gemini-omni-flash-1-2). */\nexport const GEMINI_OMNI_12_MAX_SOURCE_SEC = 15\n\n/** The widest trim window a request may set on a Gemini Omni source clip, in seconds. */\nexport function videoSourceTrimMaxSec(provider: string | undefined): number {\n return isGeminiOmniPerSecondProvider(provider) ? GEMINI_OMNI_12_MAX_SOURCE_SEC : 10\n}\n\n/**\n * Video models that are CATALOGUED and priced but have NO working dispatch\n * path today — selecting one fails at the router, not at validation.\n *\n * `kling-3-omni` has a Replicate implementation but the i2v routing chain is\n * KIE-only and it has no worker short-circuit (the way LTX does), so every run\n * failed at the router. It was pulled from the frontend picker for that\n * reason; the backend enum and cost rows stay so legacy saved workflows still\n * validate.\n *\n * This lives in shared rather than as a comment in the frontend picker list\n * because it is a REAL capability fact that more than one consumer must\n * respect: `deriveGvpSupportedProviders` below would otherwise offer\n * `kling-3-omni` (it is i2v, takes reference images, declares durations, and\n * carries ref limits — it passes every capability check) and every selection\n * would fail at run time.\n *\n * Remove an entry only after wiring its dispatch AND verifying a live\n * generation.\n */\nexport const VIDEO_PROVIDERS_WITHOUT_DISPATCH = new Set<string>([\n \"kling-3-omni\",\n])\n\n/** The SKU a stale/unsupported generate-video-pro selection snaps back to, and\n * the one that lists first in every pro provider dropdown. */\nexport const GVP_DEFAULT_PROVIDER = \"seedance-2\"\n\n/**\n * Generate Video Pro SUPPORT set — DERIVED FROM CAPABILITY, never hand-kept\n * (2026-08-05; was a literal `[\"seedance-2\",\"seedance-2-fast\",\"minimax-h3\"]`).\n *\n * The bar is exactly what the pro engine's KEYFRAMES render method needs: the\n * model must accept a generated start still, and it must be able to carry the\n * identity/continuity reference images the anchor wave and the extend chain\n * attach. So:\n *\n * kind \"video\" ∧ modes ∋ \"i2v\" ∧ features ∋ \"reference-image\" ∧ has durations\n *\n * `durations` is part of the bar because the engine SPLITS a request into\n * segments — a model that declares no duration set cannot be segmented, and a\n * silent 4–15s fallback would send lengths the provider rejects.\n *\n * Membership is cross-checked against `VIDEO_REF_LIMITS_BY_PROVIDER` below by\n * `__tests__/gvp-supported-providers.test.ts`: that map was built by the\n * 2026-06-28 audit of actual backend reference-FORWARDING paths, so a model\n * carrying the catalog flag without a forwarding path (or vice versa) fails\n * the build instead of silently advertising a capability the backend drops.\n *\n * Deliberately distinct from SEEDANCE_2_PROVIDERS, which gates CAPABILITIES\n * (ref limits, i2v params, adaptive aspect) for the whole family. The pro\n * plugin route stays tolerant of previously-saved values so in-flight\n * workflows keep running; the editor fail-safe snaps stale selections to\n * GVP_DEFAULT_PROVIDER instead.\n *\n * `seedance-2-mini` re-enters selection here (it was withdrawn by hand on\n * 2026-07-21). It qualifies on capability and is the cheapest Seedance-2 SKU,\n * which makes it the natural pick for cheap iteration on long runs.\n *\n * The ONE exception to the reference-image bar is explicit, per model: a\n * catalog `gvpWithoutReferences` (PixVerse V6 Max, decided 2026-11-12) admits\n * a model that takes a start frame but no reference images, on keyframes from\n * its start anchor or text alone. The capability bar itself is unchanged, so\n * no other start-frame-only model (wan-i2v, hailuo, bytedance) rides in.\n */\nfunction deriveGvpSupportedProviders(): VideoGenProvider[] {\n const dispatchable = new Set<string>(VIDEO_GEN_PROVIDERS as readonly string[])\n const eligible = Object.values(MODEL_CATALOG)\n .filter(\n (m) =>\n m.kind === \"video\" &&\n (m.modes as readonly string[]).includes(\"i2v\") &&\n (m.features?.includes(\"reference-image\") === true || m.gvpWithoutReferences === true) &&\n (m.durations?.length ?? 0) > 0 &&\n // Must also be dispatchable by the unified video node — the pro route\n // hands the provider id straight to the app's imageToVideo.\n dispatchable.has(m.id) &&\n // A keyframes model's Image References are in-between FRAMES, so the\n // cast references a pro segment sends would land as frames.\n m.features?.includes(\"keyframes\") !== true &&\n // ...and must actually REACH a provider. Capability alone is not\n // enough: kling-3-omni passes every check above and still fails at the\n // router (see VIDEO_PROVIDERS_WITHOUT_DISPATCH).\n !VIDEO_PROVIDERS_WITHOUT_DISPATCH.has(m.id),\n )\n .map((m) => m.id as VideoGenProvider)\n\n // Dropdown order: SKUs of one model family stay adjacent (raw catalog order\n // interleaves them — minimax-h3 is authored ~340 lines above seedance-2, so\n // a flat sort would split the Seedance trio around it). Group by `series`,\n // order groups by first catalog appearance, then hoist the default's group —\n // and the default within it — to the front.\n const seriesOf = (id: string): string => MODEL_CATALOG[id]?.series ?? MODEL_CATALOG[id]?.family ?? id\n const defaultSeries = seriesOf(GVP_DEFAULT_PROVIDER)\n const order: string[] = []\n for (const id of eligible) {\n const s = seriesOf(id)\n if (!order.includes(s)) order.push(s)\n }\n const rank = (id: string): number => {\n const s = seriesOf(id)\n return s === defaultSeries ? -1 : order.indexOf(s)\n }\n return [...eligible].sort((a, b) => {\n const d = rank(a) - rank(b)\n if (d !== 0) return d\n if (a === GVP_DEFAULT_PROVIDER) return -1\n if (b === GVP_DEFAULT_PROVIDER) return 1\n return eligible.indexOf(a) - eligible.indexOf(b)\n })\n}\n\nexport const GVP_SUPPORTED_PROVIDERS: readonly VideoGenProvider[] = deriveGvpSupportedProviders()\n\nexport function isGvpSupportedProvider(provider: string | undefined): boolean {\n return !!provider && (GVP_SUPPORTED_PROVIDERS as readonly string[]).includes(provider)\n}\n\n/**\n * The generate-video-pro SKUs whose transport supports the `extend` render\n * method — a continuation TAIL of the previous segment sent as a conditioning\n * reference video (KIE `reference_video_urls`, built by\n * `resolveSeedance2Inputs`).\n *\n * Derived from the catalog's `\"video-reference\"` feature, so a future r2v SKU\n * flows in on its own instead of needing a family predicate edited. Today this\n * resolves to exactly the Seedance-2 family + minimax-h3 — identical to the\n * hardcoded gate it replaces, so the change is behaviour-neutral.\n *\n * Every other blessed SKU renders `keyframes` only: each segment is generated\n * from its own anchor stills, nothing conditions on another segment's video.\n */\nexport const GVP_EXTEND_PROVIDERS: readonly VideoGenProvider[] = GVP_SUPPORTED_PROVIDERS.filter(\n (id) => MODEL_CATALOG[id]?.features?.includes(\"video-reference\") === true,\n)\n\nexport function supportsExtendRender(provider: string | undefined): boolean {\n return !!provider && (GVP_EXTEND_PROVIDERS as readonly string[]).includes(provider)\n}\n\n/**\n * The generate-video-pro SKUs that honour a strict CLOSING frame, so the\n * keyframes anchor wave generates an end still for them as well as a start\n * still. Derived from the catalog's `\"end-frame\"` feature — the plugin's\n * `wantEndAnchor` reads this instead of a provider-family name check.\n */\nexport const GVP_END_FRAME_PROVIDERS: readonly VideoGenProvider[] = GVP_SUPPORTED_PROVIDERS.filter(\n (id) => MODEL_CATALOG[id]?.features?.includes(\"end-frame\") === true,\n)\n\nexport function supportsEndAnchor(provider: string | undefined): boolean {\n return !!provider && (GVP_END_FRAME_PROVIDERS as readonly string[]).includes(provider)\n}\n\n/**\n * KEYFRAMES ANCHOR CHOICE — how much a keyframes run pins its shots to\n * pre-generated stills. The node stores this product vocabulary; the plugin\n * wire speaks its own `anchorMode`, and `resolveGvpAnchorWire` is the SINGLE\n * translation both send paths go through (canvas Run in `execute-node.ts` and\n * the DAG's `payload-builder.ts`), so the two cannot disagree about what the\n * user picked — the drift that left `renderMethod` unreachable from the canvas\n * until 2026-08-05.\n */\nexport const GVP_ANCHOR_CHOICES = [\"auto\", \"start-end\", \"start-only\", \"reference\"] as const\n\nexport type GvpAnchorChoice = (typeof GVP_ANCHOR_CHOICES)[number]\n\n/** The plugin engine's own chain-mode vocabulary. */\nexport type GvpAnchorWireMode = \"upfront\" | \"progressive\" | \"none\"\n\n/**\n * Translate the node's anchor choice into the plugin's `anchorMode` field.\n *\n * - `auto` (and absent/unknown) → `undefined`: send NOTHING, leaving the\n * engine's own default and env flags in charge exactly as they are for\n * callers predating this lever. Existing payloads stay byte-identical.\n * - `start-end` → `upfront`: anchors pre-generated from plan text, and the\n * engine's own closing-frame policy applies (capability-gated, longer\n * scenes only). Today's shipped behaviour.\n * - `start-only` → `progressive`: each start anchor is generated just-in-time\n * from the PREVIOUS render's real last frame, and no closing still is ever\n * pinned — so a shot can never warp its world to reach a pre-motion guess.\n * - `reference` → `none`: no frame conditioning at all; identity/location\n * references plus the prompt carry the shot.\n *\n * Deliberately NOT emitting the per-segment `endAnchors` array: that is a\n * per-scene lever whose natural home is a per-scene surface, and emitting it\n * here would mean duplicating the plugin's `MAX_SEGMENTS` cap in this repo\n * where nothing could keep the two in step.\n */\nexport function resolveGvpAnchorWire(choice: string | undefined, provider?: string): GvpAnchorWireMode | undefined {\n switch (choice) {\n case \"start-end\":\n return \"upfront\"\n case \"start-only\":\n return \"progressive\"\n case \"reference\":\n // A model with no reference images has nothing to carry a reference-\n // driven shot (`gvpWithoutReferences`): it runs as Auto instead.\n return gvpTakesReferenceImages(provider) ? \"none\" : undefined\n default:\n return undefined\n }\n}\n\n/** Whether a Generate Video Pro segment can send reference images to this model. */\nfunction gvpTakesReferenceImages(provider: string | undefined): boolean {\n if (!provider) return true // no model named: the choice is the caller's, as before\n return MODEL_CATALOG[provider]?.gvpWithoutReferences !== true\n}\n\n// ---------------------------------------------------------------------------\n// SEGMENT BOUNDS — pure catalog readers. The generate-video-pro splitter (in\n// three places: the plugin engine, the money closed-form, the UI estimate)\n// used to hardcode `{minSeg: 4, maxSeg: 15}`, which is only correct for the\n// Seedance-2 family. These are the single source every one of them reads.\n// ---------------------------------------------------------------------------\n\n/** Allowed single-segment durations (seconds, ascending) for a pro provider.\n * Empty for anything not in the catalog — callers treat that as ineligible\n * rather than falling back to a window the provider may reject. */\nexport function segmentDurationsFor(provider: string | undefined): readonly number[] {\n if (!provider) return []\n return [...(MODEL_CATALOG[provider]?.durations ?? [])].sort((a, b) => a - b)\n}\n\n/** Shortest single segment the provider can render. 0 when unknown. */\nexport function minSegmentSecFor(provider: string | undefined): number {\n return segmentDurationsFor(provider)[0] ?? 0\n}\n\n/** Longest single segment the provider can render — the value above which a\n * request must split. 0 when unknown. */\nexport function maxSegmentSecFor(provider: string | undefined): number {\n const d = segmentDurationsFor(provider)\n return d[d.length - 1] ?? 0\n}\n\n/** True when the provider's durations are every integer between its min and\n * max (Seedance-2 family, minimax-h3, kling-3-omni, happyhorse-ref2v). Those\n * can use the classic arithmetic splitter; sparse providers (veo3's 4/6/8,\n * grok-i2v's 6/10) need the discrete packer. */\nexport function hasContiguousSegmentDurations(provider: string | undefined): boolean {\n const d = segmentDurationsFor(provider)\n if (d.length === 0) return false\n return d.length === d[d.length - 1]! - d[0]! + 1\n}\n\n/** Most segments a run can hold for this provider at a given total cap — the\n * dynamic replacement for the old fixed 24. 0 when the provider is unknown. */\nexport function maxSegmentsFor(provider: string | undefined, capSec: number): number {\n const max = maxSegmentSecFor(provider)\n return max > 0 ? Math.ceil(capSec / max) : 0\n}\n\n/**\n * Default aspect ratio for a video provider when the node carries no explicit\n * `aspectRatio`. Seedance 2.x defaults to `\"adaptive\"` (output matches the\n * wired input — fits the unified-inputs model); every other provider keeps the\n * historical `\"16:9\"`. Single source of truth so every run-default / display-\n * fallback site stays in lock-step (preview = run). Applies to ALL Seedance\n * modes incl. text-to-video — KIE accepts `adaptive` there too.\n *\n * MiniMax Hailuo 3 also defaults to `adaptive`: its r2v endpoint takes\n * `adaptive` natively (the KIE default) and its i2v endpoint has no aspect\n * param at all (inferred from the frame). Only the pure-t2v endpoint requires\n * a concrete ratio — the KIE provider layer coerces `adaptive` → `16:9` there\n * (see applyMinimaxH3Params in backend kie/video.ts).\n *\n * Wan 3.0 also defaults to `adaptive` — it is the model's own KIE default and\n * the first value in its aspect enum, so an un-set node must not silently run\n * at 16:9 while the panel displays Adaptive.\n */\nexport function defaultVideoAspectRatio(provider: string | undefined): string {\n return isSeedance2Provider(provider) || isMinimaxH3Provider(provider) || isWan3Provider(provider)\n ? \"adaptive\"\n : \"16:9\"\n}\n\n/**\n * Google VEO family (Quality / Fast / Lite). VEO goes through its own KIE\n * endpoint and image-handling path, so callers branch on this in several places.\n */\nexport const VEO_PROVIDERS = new Set<string>([\n \"veo3\",\n \"veo3.1\",\n \"veo3_lite\",\n])\n\nexport function isVeoProvider(provider: string | undefined): boolean {\n return !!provider && VEO_PROVIDERS.has(provider)\n}\n\n/** KIE.ai limits for Seedance 2.0 multimodal reference arrays. */\nexport const SEEDANCE_2_REF_LIMITS = {\n images: 9,\n videos: 3,\n audio: 3,\n} as const\n\n/**\n * Seedance 2.5 raises every reference cap well above the 2.0 family's\n * (docs.kie.ai/market/bytedance/seedance-2-5): 30 images, 10 videos, 10 audio.\n * Kept as its own constant rather than widening {@link SEEDANCE_2_REF_LIMITS}\n * so the 2.0 SKUs can't silently start advertising caps KIE rejects for them.\n */\nexport const SEEDANCE_2_5_REF_LIMITS = {\n images: 30,\n videos: 10,\n audio: 10,\n} as const\n\n/**\n * KIE r2v REFERENCE-VIDEO MINIMUM (seconds) for the Seedance 2.0 family — the\n * provider hard-rejects shorter reference clips with a 400 BEFORE generation:\n * \"the parameter video duration (seconds) specified in the request must be\n * greater than or equal to 1.8 for model dreamina-seedance-2-0-fast in r2v\"\n * (2026-07-13, job dbf95612 — every 1.0s continuation tail failed\n * deterministically). Mirror of the reference-AUDIO maximum below.\n */\nexport const SEEDANCE_2_R2V_MIN_REF_VIDEO_SEC = 1.8\n\n/**\n * The continuation-reference length (seconds) every Seedance-2 chaining\n * feature actually cuts — extend-node tails, generate-video-pro segment\n * tails, edit-video-pro refOut/refIn brackets — AND the length the gvp/evp\n * credit formulas bill per continuation join. Clears the provider floor\n * above with margin while staying short enough to keep the model focused on\n * continuing the boundary motion instead of re-staging the whole clip.\n * Guarded ≥ floor by model-constants tests; the plugin repo carries a twin\n * constant guarded by its own tests — keep the two in sync.\n */\nexport const SEEDANCE_2_CONTINUATION_REF_SEC = 2\n\n/**\n * Trim-stitch parameters for the Seedance Extend Video providers\n * (`seedance-2-5-extend`, `seedance-2-0-extend`; spike-validated 2026-06-11):\n * the model's extension output wobbles for its first ~3 frames and the source\n * tail's last ~4 frames lead into it; dropping both and butt-joining yields a\n * seam SMOOTHER than ordinary in-clip motion (PSNR 34.4dB vs 30.6dB\n * adjacent-frame baseline). The 0.15s timeline-anchored audio fades kill\n * boundary clicks without shifting sync (combineVideos cut+crossfade path).\n */\nexport const SEEDANCE_2_EXTEND_STITCH = {\n /** Frames dropped from the END of the source clip (smart-cut FALLBACK —\n * used only when the PSNR boundary matcher finds no genuine match). */\n trimTailFrames: 4,\n /** Frames dropped from the START of the generated extension (smart-cut\n * fallback, see above). */\n trimHeadFrames: 3,\n /** Boundary audio fade length (seconds), timeline-preserving. */\n audioFadeSec: 0.15,\n /** Seconds of the source's TAIL passed as the @video_1 reference — short\n * keeps the model focused on continuing the boundary motion; the value is\n * floored by SEEDANCE_2_R2V_MIN_REF_VIDEO_SEC (the original spike's 1s\n * tail is now provider-rejected). */\n referenceTailSeconds: SEEDANCE_2_CONTINUATION_REF_SEC,\n} as const\n\n/**\n * Per-provider max reference-audio duration (seconds) for Seedance 2.0 r2v\n * (audio-driven image-to-video). KIE rejects longer clips with a 400 BEFORE\n * generation (e.g. \"audio duration must be ≤ 15.2 for dreamina-seedance-2-0-fast\n * in r2v\"). Data-driven: only providers with a VERIFIED limit are listed, so an\n * unknown provider is never false-rejected.\n * - seedance-2-fast: 15.2s (verified against KIE).\n * - seedance-2 (non-fast): limit unverified → not enforced yet (add after\n * confirming via docs.kie.ai).\n */\nexport const SEEDANCE_2_R2V_MAX_AUDIO_SEC_BY_PROVIDER: Record<string, number> = {\n \"seedance-2-fast\": 15.2,\n // Seedance 2.5 — documented hard limit: each reference audio 2-30s, ≤15 MB\n // per file (docs.kie.ai/market/bytedance/seedance-2-5).\n \"seedance-2-5\": 30,\n // MiniMax Hailuo 3 — documented hard limit: each reference audio segment\n // 2-15s, ≤15s total (docs.kie.ai/market/minimax-h3/reference-to-video).\n \"minimax-h3\": 15,\n // Wan 3.0 family — documented hard limit: each reference audio clip 1-15s,\n // ≤15s combined (docs.kie.ai/market/wan/3-0-video).\n \"wan-3\": 15,\n \"wan-3-prime\": 15,\n}\n\n/** The verified r2v reference-audio cap (seconds) for a provider, or null when\n * none is enforced. */\nexport function seedance2AudioLimitSec(provider: string | undefined): number | null {\n if (!provider) return null\n return SEEDANCE_2_R2V_MAX_AUDIO_SEC_BY_PROVIDER[provider] ?? null\n}\n\n/**\n * First reference-audio duration (seconds) that exceeds the provider's r2v cap,\n * or null when all are within limit (or the provider has no enforced cap).\n * Non-finite durations (probe failures) are ignored. Used to reject over-long\n * audio BEFORE submitting to the provider — which would otherwise 400.\n */\nexport function findSeedance2AudioOverLimit(\n provider: string | undefined,\n durationsSec: readonly number[],\n): number | null {\n const limit = seedance2AudioLimitSec(provider)\n if (limit === null) return null\n for (const d of durationsSec) {\n if (Number.isFinite(d) && d > limit) return d\n }\n return null\n}\n\n/** A provider's documented contract for each REFERENCE AUDIO clip. */\nexport interface RefAudioRule {\n /** Accepted containers, as ffprobe's `format_name` spells them (\"mp3\"). */\n formats?: readonly string[]\n minSec?: number\n maxSec?: number\n}\n\n/**\n * Reference-audio rules that apply on EVERY lane — the video routes' preHandler\n * and the DAG's `executeWorkerNode` both run `checkRefAudioRules` before any\n * reservation, so a clip the provider would refuse never costs a run.\n *\n * Data-driven like VIDEO_REF_VIDEO_DURATION_LIMITS: only providers with a\n * DOCUMENTED rule are listed. (The older max-only\n * SEEDANCE_2_R2V_MAX_AUDIO_SEC_BY_PROVIDER above is checked by the routes\n * alone.)\n *\n * Vidu Q4: \"MP3 only, each 3-12 seconds and up to 50 MB\"\n * (docs.kie.ai/market/vidu-q4/reference-to-video). Nothing converts a clip for\n * it, so a WAV / M4A from the audio tray is refused with a clear message rather\n * than failing at the provider.\n */\nexport const VIDEO_REF_AUDIO_RULES: Record<string, RefAudioRule | undefined> = {\n \"vidu-q4\": { formats: [\"mp3\"], minSec: 3, maxSec: 12 },\n}\n\n/** One probed reference-audio clip. A field the probe could not read is absent. */\nexport interface RefAudioProbe {\n /** ffprobe `format_name`, split on commas (\"mp3\", \"wav\", \"mov,mp4,m4a,…\"). */\n formatNames?: readonly string[]\n durationSec?: number\n}\n\nexport type RefAudioCheck =\n | { ok: true }\n | { ok: false; code: \"audio_format_unsupported\" | \"audio_too_short\" | \"audio_too_long\"; message: string }\n\n/**\n * Check probed reference-audio clips against {@link VIDEO_REF_AUDIO_RULES}.\n * An unreadable field is IGNORED, never rejected — a probe blip must not block\n * a legal run (the provider still has the final say).\n */\nexport function checkRefAudioRules(provider: string | undefined, probes: readonly RefAudioProbe[]): RefAudioCheck {\n const rule = provider ? VIDEO_REF_AUDIO_RULES[provider] : undefined\n if (!rule) return { ok: true }\n for (const [i, p] of probes.entries()) {\n const n = i + 1\n if (rule.formats && p.formatNames && p.formatNames.length > 0 && !p.formatNames.some((f) => rule.formats!.includes(f))) {\n const want = rule.formats.map((f) => f.toUpperCase()).join(\" or \")\n return { ok: false, code: \"audio_format_unsupported\", message: `Reference audio ${n} must be ${want} for this model. Convert the clip to ${want} and try again.` }\n }\n const d = p.durationSec\n if (d === undefined || !Number.isFinite(d) || d <= 0) continue\n if (rule.minSec !== undefined && d < rule.minSec) {\n return { ok: false, code: \"audio_too_short\", message: `Reference audio ${n} is too short for this model: ${d.toFixed(1)}s is under the ${rule.minSec}s minimum.` }\n }\n if (rule.maxSec !== undefined && d > rule.maxSec) {\n return { ok: false, code: \"audio_too_long\", message: `Reference audio ${n} is too long for this model: ${d.toFixed(1)}s exceeds the ${rule.maxSec}s limit. Please use a shorter audio clip.` }\n }\n }\n return { ok: true }\n}\n\n/**\n * Per-provider connection caps for the typed reference handles on Generate Video\n * AND the cap for the server-side `connectedReferences` assembly (`imageCap`).\n *\n * The KEY SET is bound 1:1 to MODEL_CATALOG (kind:\"video\" + features:\n * [\"reference-image\"]) by the drift guard in `__tests__/video-ref-limits.test.ts`:\n * adding a ref-capable video model to the catalog without a cap here — or a cap\n * here without the catalog flag — fails CI. So the CATALOG is the single source\n * for \"is this model ref-capable\", and this map is the single source for the\n * NUMERIC caps (sourced from the provider configs, see per-line notes).\n * Providers absent from the map = 0 caps (the popover dims the handle with\n * \"Not supported by [Model]\"; the API assembly strips `{image:N}` tokens).\n */\nexport const VIDEO_REF_LIMITS_BY_PROVIDER: Record<\n string,\n {\n images?: number\n videos?: number\n audio?: number\n characters?: number\n voices?: number\n /**\n * Cap on ALL materials together (images + videos + characters + audio),\n * when the provider counts them as one budget (Kling 4.0: 15). Absent ⇒\n * no combined cap beyond the per-kind ones — and, for a model declaring\n * `characters`, the Gemini Omni input-unit budget applies instead\n * (`videoCharacterRefProblem`).\n */\n materials?: number\n /**\n * Reference audio rides ON a character subject (its voice), not as a\n * material of its own: clip N belongs to wired character N, in the order\n * the characters arrive, and takes no seat in `materials`. A character with\n * fewer than 2 images is no subject and cannot carry a voice, so its clip\n * is dropped, as is a clip past the last character (Kling 4.0 Flash: KIE\n * `elements[].voice_url`, no standalone `voices`).\n */\n audioBindsToCharacters?: true\n /**\n * How many of the `characters` may be VIDEO subjects — a character made\n * from a short clip of itself (`characterReferences[].videoUrl`) instead of\n * images. The clip counts as one of the `videos` too: the provider caps\n * reference videos and video subjects together. Absent ⇒ none (any other\n * model refuses a character video). Each clip's own length is\n * `VIDEO_CHARACTER_CLIP_DURATION_LIMITS`.\n */\n videoCharacters?: number\n /**\n * The provider bills a video subject's clip as reference-video seconds\n * (its with-video rate on output + input), so the run is priced as a\n * reference-video run with the clip among its input seconds. Absent ⇒ a\n * video subject is priced like an image subject: it adds no input seconds\n * and does not move the run onto the reference-video rate (its clip still\n * counts toward the `videos` cap and the reference videos' total length).\n * Read through `videoCharacterClipsBilledAsReferenceVideo`.\n */\n videoCharactersBillAsReferenceVideo?: true\n } | undefined\n> = {\n // Seedance 2 — full multimodal caps.\n \"seedance-2\": { ...SEEDANCE_2_REF_LIMITS },\n \"seedance-2-fast\": { ...SEEDANCE_2_REF_LIMITS },\n \"seedance-2-mini\": { ...SEEDANCE_2_REF_LIMITS },\n // Seedance 2.5 — wider caps than the 2.0 family (30 / 10 / 10).\n \"seedance-2-5\": { ...SEEDANCE_2_5_REF_LIMITS },\n // MiniMax Hailuo 3 — identical multimodal caps (9 images / 3 videos / 3\n // audio per docs.kie.ai/market/minimax-h3/reference-to-video). Note: KIE\n // bills input images beyond the first 5 (11 KIE cr each) — see the\n // minimax-h3 credit helper in backend ee/billing.\n \"minimax-h3\": { ...SEEDANCE_2_REF_LIMITS },\n // Wan 3.0 family — all-purpose reference mode: up to 10 images / 5 videos\n // (each 1-15s, ≤15s combined) / 5 audio clips (each 1-15s, ≤15s combined).\n // The reference arrays are mutually EXCLUSIVE with first/last frame at the\n // provider (docs.kie.ai/market/wan/3-0-video).\n \"wan-3\": { images: 10, videos: 5, audio: 5 },\n \"wan-3-prime\": { images: 10, videos: 5, audio: 5 },\n // Vidu Q4 — reference-to-video takes 1-15 reference images and up to 3\n // reference audio clips (MP3 only, each 3-12s — VIDEO_REF_AUDIO_RULES), and\n // no reference videos (docs.kie.ai/market/vidu-q4/reference-to-video).\n \"vidu-q4\": { images: 15, audio: 3 },\n // Multi-image reference providers.\n // `characters` = the dedicated identity input (KIE `character_ids`, max 3).\n // It is NOT an image-reference lane: it draws from the SAME 7-unit budget as\n // `images` (images + 2×videos + character units ≤ 7) — see\n // `video-character-refs.ts`, the one place that budget is computed.\n // `voices` = distinct audio personas per task (`audio_ids`, max 3). NOT part\n // of the 7-unit quota: audio ids are a separate input.\n \"gemini-omni-video\": { images: 7, videos: 1, characters: 3, voices: 3 },\n // Gemini Omni Flash 1.1 — identical quota to the pro sibling\n // (images + 2×videos + character_ids ≤ 7).\n \"gemini-omni-flash\": { images: 7, videos: 1, characters: 3, voices: 3 },\n // Gemini Omni Flash 1.2 — up to 6 images, one source video, and images +\n // 2 for a video ≤ 7, so 5 images beside a video (the request builder holds\n // that). No `character_ids` / `audio_ids` in its schema: no characters, no voices.\n \"gemini-omni-flash-1-2\": { images: 6, videos: 1 },\n \"kling-3-omni\": { images: 7 }, // catalog/docs: \"end frame + up to 7 reference images\"\n // Kling 4.0 Reference — 10 images, 5 videos, 7 subjects (`characters`,\n // KIE `elements`) and 3 voices (reference audio, KIE `voices`), 15 in all\n // (docs.kie.ai/market/kling/v4-reference-to-video). A wired start frame takes\n // one of the 10 image slots. No `voices` key: that names Gemini Omni's\n // preset personas, which Kling does not take.\n // Of the 7 subjects, at most 3 may be video subjects (a 3-8 s clip each), and\n // reference videos plus video subjects are at most 5. A video subject is\n // priced as a reference video here until a measured run confirms how Kling\n // 4.0 bills one (decided 2026-11-14): Flash, measured, bills it as an image\n // subject (no flag below).\n \"kling-4\": { images: 10, videos: 5, audio: 3, characters: 7, materials: 15, videoCharacters: 3, videoCharactersBillAsReferenceVideo: true },\n // Kling 4.0 Keyframes — the Image References are the in-between frames\n // (`keyframe_urls`, max 8; the clip's duration lowers the cap, see\n // kling4KeyframeFrameCap). No reference videos or audio.\n \"kling-4-keyframes\": { images: KLING_4_MAX_MIDDLE_FRAMES },\n // Kling 4.0 Flash (reference endpoint) — 10 images, 5 videos, 7 subjects,\n // 15 in all (docs.kie.ai/market/kling/v4-flash-reference-to-video). No\n // standalone voices: reference audio clip N becomes wired character N's voice\n // (`voice_url`) when that character is a subject (2-4 images), so at most one\n // per character (7) and none takes a material seat. A wired start frame takes one of the 10 image slots when it\n // runs on this endpoint. A video subject is billed like an image subject\n // (measured on a staging run, decided 2026-11-14): no\n // `videoCharactersBillAsReferenceVideo`.\n \"kling-4-flash\": { images: 10, videos: 5, audio: 7, characters: 7, materials: 15, audioBindsToCharacters: true, videoCharacters: 3 },\n \"grok-i2v\": { images: 7 }, // backend kie/models.ts maxRefImages: 7\n \"happyhorse-ref2v\": { images: 9 }, // backend kie/models.ts maxRefImages: 9\n // VEO 3.x — REFERENCE_2_VIDEO path caps refs at 3 (kie/video.ts slices to\n // this number). `veo3` (VEO 3.1 QUALITY) is deliberately ABSENT: KIE serves\n // reference-to-video on the Fast and Lite SKUs only and rejects it on\n // Quality with \"Reference to video only supports the Veo Fast model and Veo\n // Lite model.\" (production, 2026-09-04). Absent ⇒ 0 ⇒ the handle dims, the\n // `connectedReferences` assembly strips image tokens, and kie/video.ts never\n // flips a Quality call to REFERENCE_2_VIDEO.\n \"veo3.1\": { images: 3 },\n \"veo3_lite\": { images: 3 },\n // Grok Imagine Video 1.5 — the Image References are its in-between frames\n // (KIE `keyframes`, max 4; the clip's length lowers the count, see\n // grokVideo15MiddleFrameSlots). They are frames only, never `image_urls`\n // references, and need the start frame. No reference videos or audio.\n \"grok-imagine-video-1.5\": { images: GROK_VIDEO_15_MAX_MIDDLE_FRAMES },\n // NOTE: wan-i2v / hailuo-2.3[-pro] / bytedance-pro[-fast] are deliberately\n // ABSENT. The 2026-06-28 audit (video-reference-features.test.ts) verified\n // backend reference-forwarding paths and these i2v models have none — a\n // single image_url start frame only. Advertising a ref cap would silently\n // drop the user's references (grok-imagine-video-1.5 had that bug before its\n // in-between frames were wired). Add only with a verified provider path + the\n // catalog `reference-image` feature.\n}\n\n/** Per-reference-video duration bounds, in seconds. */\nexport interface RefVideoDurationLimit {\n minSec: number\n maxSec: number\n /** Cap on the SUM of all reference-video durations, when the provider has one. */\n maxTotalSec?: number\n}\n\n/**\n * Reference-video duration limits, provider-declared.\n *\n * `VIDEO_REF_LIMITS_BY_PROVIDER` above caps the reference COUNT; these cap the\n * duration of each clip. Both routes already ffprobe every reference video to\n * price the run (ee/billing/seedance2-ref-video-credits.ts and\n * minimax-h3-credits.ts), so the numbers are in hand before the job exists —\n * and until 2026-09-02 they were discarded, which is why \"Each reference video\n * must be between 2 and 30 seconds\" and \"video duration 52838 ms, expected\n * [2000, 15000] ms\" were reaching users as post-payment provider rejects\n * (app-reports §11.3).\n *\n * Data-driven, exactly like SEEDANCE_2_R2V_MAX_AUDIO_SEC_BY_PROVIDER above:\n * only providers with a VERIFIED documented limit are listed, so an unknown\n * provider is never false-rejected.\n *\n * Sources: docs.kie.ai/market/bytedance/seedance-2-5 (\"Single video duration:\n * [2, 30] seconds\"; \"Total duration of reference videos must not exceed 30\n * seconds\") and docs.kie.ai/market/minimax-h3/reference-to-video (reference\n * videos are \"2 to 15 seconds\" each and \"the total duration of all reference\n * videos cannot exceed 15 seconds\", up to 3 videos) — both fetched 2026-09-02.\n */\nexport const VIDEO_REF_VIDEO_DURATION_LIMITS: Record<string, RefVideoDurationLimit | undefined> = {\n \"seedance-2-5\": { minSec: 2, maxSec: 30, maxTotalSec: 30 },\n // MiniMax Hailuo 3 — the provider states the per-clip bound in its own reject\n // text: \"content[1].video_url: invalid param: video duration 52838 ms,\n // expected [2000, 15000] ms\" (app-reports P4, 2 rows, the same clip retried).\n // The KIE reference-to-video doc adds the COMBINED cap — the same shape the\n // audio side already declares in SEEDANCE_2_R2V_MAX_AUDIO_SEC_BY_PROVIDER\n // above, whose h3 row cites the same page.\n \"minimax-h3\": { minSec: 2, maxSec: 15, maxTotalSec: 15 },\n // Kling 4.0 Reference — \"up to 5 clips, each 2–30 seconds\"\n // (docs.kie.ai/market/kling/v4-reference-to-video); KIE's own reject reads\n // \"video_1 duration must be between 2 and 30 seconds, got 45\". The doc names\n // no COMBINED cap, but KIE enforces one at task creation: verified live on\n // 2026-10-27, two 16 s references were refused with\n // `{\"code\":422,\"msg\":\"video_urls total duration must not exceed 30 seconds\"}`\n // while two 14 s ones were accepted (a production run with two 20 s\n // references had reached users as the generic \"rejected these settings\").\n \"kling-4\": { minSec: 2, maxSec: 30, maxTotalSec: 30 },\n // Kling 4.0 Flash — the reference videos' COMBINED length must be 2-20 s,\n // and KIE fails the task at completion otherwise (\"video_1 duration must be\n // between 2 and 20 seconds, got 45\", docs.kie.ai/market/kling/v4-flash-reference-to-video).\n // A 2 s floor per clip makes the combined floor hold too.\n \"kling-4-flash\": { minSec: 2, maxSec: 20, maxTotalSec: 20 },\n}\n\n/**\n * The length a character's own clip (`characterReferences[].videoUrl`, a video\n * subject) must have, per provider. Kling 4.0 and Kling 4.0 Flash: \"one 3-8\n * second single-shot character video\" (docs.kie.ai/market/kling/v4-reference-to-video,\n * v4-flash-reference-to-video, read 2026-11-13). The clip is also one of the\n * run's reference videos, so `VIDEO_REF_VIDEO_DURATION_LIMITS` (its per-clip\n * bound and the combined `maxTotalSec`) applies to it as well.\n */\nexport const VIDEO_CHARACTER_CLIP_DURATION_LIMITS: Record<string, { minSec: number; maxSec: number } | undefined> = {\n \"kling-4\": { minSec: 3, maxSec: 8 },\n \"kling-4-flash\": { minSec: 3, maxSec: 8 },\n}\n\n/**\n * Validate probed character-clip durations against\n * {@link VIDEO_CHARACTER_CLIP_DURATION_LIMITS}. Unlike a reference video\n * ({@link checkRefVideoDurations}, which ignores a clip the probe could not\n * read and charges its worst case), a character's clip must be measured within\n * its bounds to be accepted (decided 2026-11-13): one the probe could not read\n * (NaN, ≤0) is refused too, as `character_video_unreadable`.\n */\nexport function checkCharacterClipDurations(\n provider: string,\n durationsSec: readonly number[],\n): { ok: true } | { ok: false; code: \"video_too_long\" | \"character_video_unreadable\"; message: string } {\n const limit = VIDEO_CHARACTER_CLIP_DURATION_LIMITS[provider]\n if (!limit) return { ok: true }\n if (durationsSec.some((d) => !Number.isFinite(d) || d <= 0)) {\n return {\n ok: false,\n code: \"character_video_unreadable\",\n message:\n `A character's video could not be measured, and it must be ${limit.minSec}–${limit.maxSec} seconds long. ` +\n \"Check that the link is a playable video file anyone can open, and run again. Nothing was charged.\",\n }\n }\n const offender = durationsSec.find((d) => d < limit.minSec || d > limit.maxSec)\n if (offender === undefined) return { ok: true }\n // The measured length, rounded UP to hundredths, so a clip just past the\n // bound never reads as inside it (8.03 s, never \"8.0 s\").\n const shown = (Math.ceil(offender * 100 - 1e-9) / 100).toFixed(2)\n return {\n ok: false,\n code: \"video_too_long\",\n message:\n `A character's video must be between ${limit.minSec} and ${limit.maxSec} seconds — one is ${shown} s. ` +\n `Use a single-shot clip of that length (a Trim Video node upstream works) and run again.`,\n }\n}\n\n/**\n * Validate probed reference-video durations against the provider's limits.\n *\n * Non-finite / non-positive entries are IGNORED, never rejected: the probe\n * helpers treat an unreadable clip as a worst-case duration for pricing, and\n * turning a failed ffprobe into a user-facing 400 would block legitimate runs\n * on a transient probe failure. Callers therefore pass the RAW per-URL probe\n * outcomes (a rejected ffprobe arrives here as NaN) — an ignored entry also\n * contributes nothing to the `maxTotalSec` sum, so a probe blip can never push\n * an otherwise-legal set over the total cap either.\n */\nexport function checkRefVideoDurations(\n provider: string,\n durationsSec: readonly number[],\n): { ok: true } | { ok: false; message: string } {\n const limit = VIDEO_REF_VIDEO_DURATION_LIMITS[provider]\n if (!limit) return { ok: true }\n\n const usable = durationsSec.filter((d) => Number.isFinite(d) && d > 0)\n if (usable.length === 0) return { ok: true }\n\n const offender = usable.find((d) => d < limit.minSec || d > limit.maxSec)\n if (offender !== undefined) {\n return {\n ok: false,\n message: `Each reference video must be between ${limit.minSec} and ${limit.maxSec} seconds — one is ${offender.toFixed(1)}s. Trim it (a Trim Video node upstream works) and run again.`,\n }\n }\n\n if (limit.maxTotalSec !== undefined) {\n const total = usable.reduce((a, b) => a + b, 0)\n if (total > limit.maxTotalSec) {\n return {\n ok: false,\n message: `Reference videos must not exceed ${limit.maxTotalSec} seconds in total — these add up to ${total.toFixed(1)}s. Remove one or trim them and run again.`,\n }\n }\n }\n\n return { ok: true }\n}\n\n/**\n * Video models where credit cost depends on resolution AND whether a video\n * reference is connected. Identifier suffix: `:{resolution}[-ref]`.\n * Seedance 2.0 family uses per-second billing split 480p/720p × with-ref/no-ref.\n */\nexport const RESOLUTION_VIDEO_REF_PRICING = SEEDANCE_2_PROVIDERS\n\n/**\n * Video models priced by (duration × resolution) WITHOUT a video-ref dimension.\n * Identifier suffix: `:{resolution}`, appended after the duration tier; value =\n * the provider's PRICED resolution tiers.\n *\n * Any resolution outside the list (or undefined) collapses to the provider's\n * DEFAULT tier, so the builder can never emit an unpriced composite (the\n * hard-fail guard fuzzes the full resolution space). That default is\n * {@link PRICING_DEFAULT_RESOLUTION} when the provider declares one, and\n * otherwise the FIRST entry here — so a member with a declared default (wan-3)\n * can list its tiers in the repo-standard ascending order without index 0\n * silently becoming the billed default. Distinct from\n * RESOLUTION_VIDEO_REF_PRICING (Seedance gen), which also adds `-ref` variants.\n */\nexport const RESOLUTION_DURATION_PRICING: Record<string, readonly string[]> = {\n // 480p is KIE's default and the bare id's tier; the runner and the credit\n // identifier both read normalizeGrokVideo15Resolution.\n \"grok-imagine-video-1.5\": [\"480p\", \"720p\", \"1080p\"],\n // HappyHorse 1.1 — per-second billing at two published resolution rates\n // (kie.ai/happyhorse-1-1: 22.5 cr/s @720p, 29 cr/s @1080p, uniform across\n // t2v/i2v/ref2v). 720p first = billing default; the KIE-side default is\n // pinned to 720p via extraParams in backend kie/models.ts so render matches.\n \"happyhorse\": [\"720p\", \"1080p\"],\n \"happyhorse-i2v\": [\"720p\", \"1080p\"],\n \"happyhorse-ref2v\": [\"720p\", \"1080p\"],\n // Wan 3.0 / Prime — per-second billing at three published resolution rates.\n // Ascending, matching the catalog; the BILLED default is declared explicitly\n // in PRICING_DEFAULT_RESOLUTION (\"720p\") rather than carried by index 0, and\n // the provider layer pins the same 720P so render == billed.\n \"wan-3\": [\"480p\", \"720p\", \"1080p\"],\n \"wan-3-prime\": [\"480p\", \"720p\", \"1080p\"],\n // Vidu Q4 — per-second billing at five resolution rates, one ladder for both\n // endpoints. Ascending; the billed default (720p) is declared in\n // PRICING_DEFAULT_RESOLUTION, and normalizeViduQ4Resolution pins the same\n // 720p at the wire.\n \"vidu-q4\": [\"540p\", \"720p\", \"1080p\", \"2k\", \"4k\"],\n // Kling 4.0 — per-second billing at two resolution rates on both endpoints.\n // `kling-4` adds a `-ref` rate for a run with a reference video\n // (VIDEO_REF_RATE_PROVIDERS).\n \"kling-4\": [\"720p\", \"1080p\"],\n \"kling-4-keyframes\": [\"720p\", \"1080p\"],\n // Kling 4.0 Flash — 720p only (both schemas), one rate on both endpoints,\n // plus a `-ref` rate for a run with a reference video (VIDEO_REF_RATE_PROVIDERS).\n \"kling-4-flash\": [\"720p\"],\n // Gemini Omni Flash 1.2 — per-second billing at four resolution rates.\n // Ascending; the billed default (720p) is declared in PRICING_DEFAULT_RESOLUTION.\n \"gemini-omni-flash-1-2\": [\"360p\", \"720p\", \"1080p\", \"4k\"],\n // PixVerse V6 Max — per-second billing at four quality rates on both\n // endpoints. Ascending; the billed default (720p) is declared in\n // PRICING_DEFAULT_RESOLUTION, and normalizePixverseV6MaxQuality pins the same\n // 720p at the wire. The audio state is its own `:audio` suffix\n // (AUDIO_ADDON_PROVIDERS), after the resolution.\n \"pixverse-v6-max\": [\"360p\", \"540p\", \"720p\", \"1080p\"],\n}\n\n/**\n * Members of RESOLUTION_DURATION_PRICING that bill a run carrying a reference\n * VIDEO at a different per-second rate: their identifier gains a `-ref` suffix\n * after the resolution (`kling-4:8s:720p-ref`). The rate is per second of the\n * BILLED duration, which the reference-video billing rule\n * (backend ee/billing/ref-video-billing.ts) computes from the probed clips.\n */\nexport const VIDEO_REF_RATE_PROVIDERS = new Set<string>([\n \"kling-4\",\n // Kling 4.0 Flash — the same rule at its own with-video rate.\n \"kling-4-flash\",\n])\n\n/**\n * Video models whose reference-VIDEO runs also bill the clips' own seconds:\n * the Seedance 2 family (`unit × (input + output)`), the\n * VIDEO_REF_RATE_PROVIDERS (Kling 4.0: `unit × (output + max(output, input))`)\n * and the per-second Gemini Omni SKUs (`unit × source clip`, the output follows it).\n * The reservation holds the worst case from the probed clips and the\n * settlement meters down to what was delivered (backend\n * ee/billing/seedance2-ref-video-credits.ts) — this is the one gate every lane\n * (routes, orchestrator, worker settlement, reconcile) asks.\n */\nexport function billsReferenceVideoSeconds(provider: string | undefined): boolean {\n return isSeedance2Provider(provider)\n || isGeminiOmniPerSecondProvider(provider)\n || (!!provider && VIDEO_REF_RATE_PROVIDERS.has(provider))\n}\n\n/**\n * Video generation models whose provider API natively accepts a \"match the\n * visual input's aspect\" token, mapped to that provider's EXACT token.\n * Consumed by the backend's `resolveSourceMatchedAspect`: members get the\n * native token (no probe round-trip, exact match even for off-catalog ratios\n * like 4:5); everyone else falls back to ffprobe + closest catalog ratio.\n *\n * Only add entries whose match-the-input semantics are verified against the\n * provider's docs AND a live job — e.g. grok-imagine-video-1.5 accepts\n * \"auto\", but that means \"provider default\", NOT \"match input\", so it does\n * not belong here.\n *\n * seedance-2 family: `adaptive` per docs.kie.ai/market/bytedance/seedance-2\n * + seedance-2-fast (enum'd alongside the fixed ratios; default 16:9).\n */\nexport const NATIVE_ADAPTIVE_ASPECT: Record<string, string> = {\n \"seedance-2\": \"adaptive\",\n \"seedance-2-fast\": \"adaptive\",\n \"seedance-2-mini\": \"adaptive\",\n \"seedance-2-5\": \"adaptive\",\n // Wan 3.0 family: `adaptive` is the enum DEFAULT and KIE documents it as\n // \"automatically selects the ratio based on the input media and intent\"\n // (docs.kie.ai/market/wan/3-0-video) — i.e. match-the-input, not merely\n // \"provider default\" (the grok `auto` trap). DOC-verified only; re-confirm\n // with a live job before relying on it for off-catalog ratios.\n \"wan-3\": \"adaptive\",\n \"wan-3-prime\": \"adaptive\",\n}\n\n/**\n * Video providers that accept ONLY the \"adaptive\" aspect ratio once a START\n * FRAME is present (first-frame or first+last-frame mode). Sending any explicit\n * ratio in that mode is a hard 422 from the provider, so the payload builder\n * coerces the value to `adaptive` for these instead of forwarding it.\n *\n * UNDOCUMENTED — KIE's schema advertises the full ratio enum unconditionally and\n * only rejects the combination at request time:\n * \"Seedance 2.5 first-frame and first-last-frame tasks only support adaptive\n * aspect ratio\"\n * (live probe against api.kie.ai, 2026-08-08). Verified as 2.5-ONLY: the same\n * probe against the 2.0 SKUs accepts explicit ratios with a start frame, which\n * is why this is a set and not a family-wide rule.\n *\n * Behaviourally this costs nothing — with a start frame the output aspect is\n * derived from that frame anyway, which is exactly what `adaptive` means.\n */\nexport const FRAME_MODE_ADAPTIVE_ONLY_ASPECT: ReadonlySet<string> = new Set([\n \"seedance-2-5\",\n])\n\n/**\n * Video providers that REQUIRE an input image (image-to-video only) even though\n * they're listed in TEXT_TO_VIDEO_PROVIDERS for unified-node visibility. The\n * `/v1/text-to-video` route early-returns a clean 400 for these before any job\n * is created, instead of letting the prompt-only request fail at the provider.\n *\n * DERIVED from MODEL_CATALOG (the capability source of truth): every video\n * model whose `modes` lacks \"t2v\" and that isn't remapped to a t2v twin by\n * VIDEO_MODE_ALIASES. Hand-listing this set is what let kling-3-omni,\n * kling-master, hailuo-2.3(-pro), bytedance-pro-fast and happyhorse-ref2v\n * crash the t2v route with a raw Zod enum error — new i2v-only models now get\n * the friendly gate automatically when their catalog entry is added.\n */\nexport const VIDEO_PROVIDERS_REQUIRING_IMAGE: ReadonlySet<string> = new Set(\n Object.values(MODEL_CATALOG)\n .filter((m) =>\n m.kind === \"video\" &&\n m.modes.includes(\"i2v\") &&\n !m.modes.includes(\"t2v\") &&\n (VIDEO_GEN_PROVIDERS as readonly string[]).includes(m.id) &&\n resolveVideoProviderForMode(m.id, \"text-to-video\") === m.id,\n )\n .map((m) => m.id),\n)\n\n/** True when a video provider can only run image-to-video (image required). */\nexport function videoProviderRequiresImage(provider: string | undefined): boolean {\n return !!provider && VIDEO_PROVIDERS_REQUIRING_IMAGE.has(provider)\n}\n\n/**\n * True when the provider's image-to-video path FOLDS a lone closing frame into\n * its reference images — i.e. an end frame with no start frame is a reference\n * the model actually receives, not a half-formed frame pair.\n *\n * The Seedance 2.x, MiniMax Hailuo 3 and Wan 3 families all assemble their KIE\n * input through the shared `resolveSeedance2Inputs` (`@nodaro/prompts`), whose\n * reference mode takes a lone last frame as the sole reference image plus a\n * closing-frame prompt hint. NOTHING else does: VEO ships `[imageUrl,\n * endFrameUrl]` verbatim (a lone end frame would reach KIE as `[null, url]`),\n * the per-clip Gemini Omni branch drops the frame when there is no start frame (Omni\n * Flash 1.2 folds it, with its own builder), and the generic KIE path sends `end_frame` with no image param at all. So the\n * exemption is keyed to the FOLD, not to \"carries image references\" — the\n * catalog has no capability for it, and these three family predicates are the\n * same membership the provider layer itself branches on (the backend's\n * `kie/video.ts::applySeedance2Params` / `applyMinimaxH3Params` / `runWan3`).\n * A ref-capable provider that grows the fold gets the exemption by joining a\n * family here; one that does not keeps the honest `image_required` 400.\n */\nexport function videoProviderFoldsLoneEndFrame(provider: string): boolean {\n return isSeedance2Provider(provider) || isMinimaxH3Provider(provider) || isWan3Provider(provider) || isGeminiOmniPerSecondProvider(provider)\n}\n\n/**\n * True when the provider takes an end frame ALONE, with no start frame, as the\n * clip's closing frame: Kling 4.0 Keyframes (KIE `last_frame_url` without\n * `first_frame_url`) and Gemini Omni Flash 1.2. Every other model meets the\n * platform's general rule for a lone end frame: the workflow run moves it into\n * the start slot, while the editor's Run and the image-to-video route refuse\n * the run for having no start frame.\n *\n * Read by the three places that apply that rule (the route's image gate, the\n * workflow payload builder's swap, the editor's start-frame guard) so they\n * cannot disagree. A `keyframes` model qualifies only when its endpoint runs\n * with no start frame at all (it has a text-to-video mode): Grok Imagine Video\n * 1.5 declares `keyframes` but needs its start image, so a lone end frame\n * keeps the general rule there.\n */\nexport function videoProviderTakesLoneEndFrame(provider: string | undefined): boolean {\n if (!provider) return false\n if (isGeminiOmniPerSecondProvider(provider)) return true\n return MODEL_CATALOG[provider]?.features?.includes(\"keyframes\") === true && !videoProviderRequiresImage(provider)\n}\n\n/**\n * True when wired reference images can stand in for a missing start frame on\n * the image-to-video lane: the provider carries image references\n * ({@link VIDEO_REF_LIMITS_BY_PROVIDER}), unless they are a `keyframes`\n * model's in-between FRAMES and its endpoint cannot run from them alone (no\n * `reference-to-video`, {@link videoProviderRunsFromReferences}) — Grok Imagine\n * Video 1.5's in-between frames need its start frame. Read by the\n * image-to-video route's gate and the editor's start-frame guard; the workflow\n * run reaches the same answer through {@link resolveVideoModeForInputs}.\n */\nexport function videoProviderRefsReplaceStartFrame(provider: string | undefined): boolean {\n if (!provider || (VIDEO_REF_LIMITS_BY_PROVIDER[provider]?.images ?? 0) <= 0) return false\n const keyframes = MODEL_CATALOG[provider]?.features?.includes(\"keyframes\") === true\n return !keyframes || videoProviderRunsFromReferences(provider)\n}\n\n/** The error code of a {@link videoStartFrameOnlyProblem} refusal. */\nexport const VIDEO_START_FRAME_ONLY_CODE = \"start_frame_only_resolution\" as const\n\n/**\n * The resolution tier a run of `provider` renders for `resolution` when that\n * tier takes a start frame only (the catalog's `startFrameOnlyResolutions`),\n * else undefined. Case-folded, as the runners send it (`\"1080P\"` is 1080p).\n */\nexport function videoStartFrameOnlyResolution(provider: string | undefined, resolution: string | undefined): string | undefined {\n const tiers = provider ? MODEL_CATALOG[provider]?.startFrameOnlyResolutions : undefined\n const r = resolution?.trim().toLowerCase()\n if (!tiers?.length || !r) return undefined\n return tiers.find((t) => t.toLowerCase() === r)\n}\n\n/** The highest listed resolution of `provider` that takes every frame — the one to offer instead. */\nfunction videoFramesResolutionFallback(provider: string): string | undefined {\n const entry = MODEL_CATALOG[provider]\n const restricted = new Set((entry?.startFrameOnlyResolutions ?? []).map((t) => t.toLowerCase()))\n const open = (entry?.resolutions ?? []).filter((r) => !restricted.has(r.toLowerCase()))\n const height = (r: string): number => Number.parseInt(r, 10) || 0\n return [...open].sort((a, b) => height(b) - height(a))[0]\n}\n\n/**\n * The sentence for a start-frame-only refusal: which tier takes a start frame\n * only, and the two ways out (the highest tier that takes every frame, or\n * removing the extra frames). `nothingCharged` adds that nothing was charged —\n * for a refusal of a run (the API, the workflow run, the editor's Run), never\n * for the editor's note beside the setting.\n */\nexport function videoStartFrameOnlyMessage(\n provider: string,\n resolution: string,\n opts: { readonly nothingCharged?: boolean } = {},\n): string {\n const label = MODEL_CATALOG[provider]?.label ?? provider\n const fallback = videoFramesResolutionFallback(provider)\n const choose = fallback ? `Choose ${fallback}, or remove` : \"Remove\"\n const sentence =\n `${label} takes a start frame only at ${resolution}: no end frame, loop or in-between frames. ` +\n `${choose} the end frame and the in-between frames.`\n return opts.nothingCharged ? `${sentence} Nothing was charged.` : sentence\n}\n\n/** A {@link videoStartFrameOnlyProblem} refusal. */\nexport interface VideoStartFrameOnlyProblem {\n readonly code: typeof VIDEO_START_FRAME_ONLY_CODE\n /** The sentence, in English — the API's `error.message`. */\n readonly message: string\n /** The tier that takes a start frame only (catalog spelling). */\n readonly resolution: string\n /** The highest tier that takes every frame, when the model has one. */\n readonly fallbackResolution?: string\n}\n\n/**\n * THE rule for a resolution that takes a start frame only (decided 2026-11-12:\n * refuse up front). Given the resolution a run renders and the frames it would\n * send BESIDE its start frame, is the combination refused, and with what\n * sentence? Undefined when it runs.\n *\n * - `hasEndFrame`: an end frame is wired. The same picture as the start frame\n * (a loop) counts too — the provider refuses a loop at such a tier as well.\n * - `inBetweenFrameCount`: the in-between frames wired (a `keyframes` model's\n * image references), BEFORE the clip's cap. The cap is applied here through\n * {@link videoKeyframesMiddleCap} — the same function the provider runner\n * truncates with — so a request whose extra frames are all dropped (a\n * 1-second Grok Imagine Video 1.5 clip has no in-between second) is a\n * start-only request and runs.\n *\n * Judged only on a run that has a start frame: a run without one is refused by\n * the image-required rule first, so every caller runs this after that gate.\n * Read by `/v1/generate-video`, the workflow payload builder and the editor's\n * Run; the editor's note and resolution menus read it too.\n */\nexport function videoStartFrameOnlyProblem(\n provider: string | undefined,\n args: {\n readonly resolution: string | undefined\n readonly durationSec?: number | string\n readonly hasEndFrame: boolean\n readonly inBetweenFrameCount: number\n readonly nothingCharged?: boolean\n },\n): VideoStartFrameOnlyProblem | undefined {\n const tier = videoStartFrameOnlyResolution(provider, args.resolution)\n if (!provider || !tier) return undefined\n const cap = videoKeyframesMiddleCap(provider, args.durationSec, { hasStartFrame: true, hasEndFrame: args.hasEndFrame })\n const inBetween = Math.max(0, cap === undefined ? args.inBetweenFrameCount : Math.min(cap, args.inBetweenFrameCount))\n if (!args.hasEndFrame && inBetween === 0) return undefined\n return {\n code: VIDEO_START_FRAME_ONLY_CODE,\n message: videoStartFrameOnlyMessage(provider, tier, { nothingCharged: args.nothingCharged }),\n resolution: tier,\n fallbackResolution: videoFramesResolutionFallback(provider),\n }\n}\n\n/**\n * Video models where enabling audio/sound incurs an additional cost.\n * The audio addon is expressed as a separate composite identifier suffix.\n */\nexport const AUDIO_ADDON_PROVIDERS = new Set([\n \"kling-3.0\",\n \"kling\",\n // PixVerse V6 Max — every (seconds × quality) row has an `:audio` twin at\n // the with-audio rate (`pixverse-v6-max:5s:720p:audio`).\n \"pixverse-v6-max\",\n])\n\n/**\n * How a video model handles an audio track. Single source of truth for\n * audio/speech capability across the whole stack — the config-panel audio\n * toggle (show / lock / disable + warn), the Story→Video dialogue auto-pick\n * (revoice vs TTS + lip-sync), provider option wiring (`sound` vs\n * `generateAudio`), and the audio credit suffix.\n *\n * Consolidates signals that were previously scattered + inconsistent:\n * - `KIE_VIDEO_MODELS` / `KIE_TEXT_TO_VIDEO_MODELS` `extraParams.sound` (Kling)\n * - `…extraParams.generate_audio` (Seedance)\n * - VEO native audio (implicit, always on)\n * - `AUDIO_ADDON_PROVIDERS` (cost) + `SEEDANCE_2_PROVIDERS` (reference audio)\n *\n * \"none\" — silent model; no audio output. UI disables the audio\n * toggle with an explanatory note; the pipeline uses TTS +\n * lip-sync for any dialogue.\n * \"ambient\" — generates ambient sound / SFX matched to the scene, NOT\n * lip-synced spoken dialogue. Toggle is offered; the\n * pipeline still uses TTS + lip-sync for dialogue.\n * \"native_speech\" — bakes spoken dialogue + lip movement from the prompt\n * (VEO 3.x always-on; Kling 2.6/3.0 behind the `sound`\n * toggle — probe-verified 2026-07-16: scripted lines come\n * back word-for-word with articulated lips on the KIE\n * path, matching the official Kling 2.6 audio guide and\n * Kling 3.0 prompting docs). The pipeline injects the\n * dialogue line, enables audio, and revoices the clip to\n * the character's saved voice.\n * \"audio_driven\" — lip-syncs to a supplied reference-audio track (Seedance\n * 2.0 multimodal). The pipeline synthesises the character's\n * voice first, feeds it as reference audio, and skips the\n * separate lip-sync pass.\n */\nexport type VideoAudioMode = \"none\" | \"ambient\" | \"native_speech\" | \"audio_driven\"\n\nexport interface VideoAudioCapability {\n mode: VideoAudioMode\n /** Provider-option field carrying the on/off toggle, when user-controllable.\n * `audio` is Wan 3.0's own boolean lever (KIE `input.audio`, default true);\n * `generateAudioSwitch` is PixVerse V6 Max's (KIE `input.generate_audio_switch`). */\n field?: \"generateAudio\" | \"sound\" | \"audio\" | \"generateAudioSwitch\"\n /** Audio is always produced and can't be turned off by the user (VEO 3.x). */\n alwaysOn?: boolean\n /** Enabling audio raises the credit cost (Kling — see AUDIO_ADDON_PROVIDERS). */\n affectsCost?: boolean\n /**\n * The model generates audio when the caller expresses NO intent (its own\n * config default is on — kling-3.0's `sound: true`, kling-3-omni's\n * `generate_audio: true`). The `:audio` credit suffix mirrors this default\n * so an intent-less request is billed for the audio it actually produces\n * (see buildVideoCreditModelIdentifier). Absent ⇒ default off.\n */\n defaultOn?: boolean\n /**\n * A cost-affecting model whose audio intent the `generateAudio` request field\n * also carries, after `sound` (PixVerse V6 Max, decided 2026-11-12: the\n * Generate Video Pro engine sends only `generateAudio`). Read through\n * {@link videoAudioIntent}, so the switch the model gets and the `:audio`\n * row the run is priced at follow the same fields. Absent on Kling, which\n * keeps reading `sound` alone.\n */\n readsGenerateAudio?: true\n}\n\n/** The audio fields a video request carries: `sound` (canonical) and the older `generateAudio`. */\nexport interface VideoAudioRequest {\n readonly sound?: boolean\n readonly generateAudio?: boolean\n}\n\n/**\n * Per-model audio capability. Only models that produce SOME audio are listed;\n * anything absent defaults to `{ mode: \"none\" }` via `getVideoAudioCapability`,\n * so silent models (minimax, hailuo, wan-i2v, grok-i2v, runway, pika, …) need\n * no entry. New audio-capable models MUST be added here — the\n * `video-audio-capability` guard test cross-checks this map against the model\n * configs' `extraParams.sound` / `generate_audio` + VEO/Seedance-2 sets so a\n * forgotten entry fails CI rather than silently disabling audio.\n */\nexport const VIDEO_AUDIO_CAPABILITY: Record<string, VideoAudioCapability> = {\n // VEO 3.x — native spoken dialogue + lip movement; always on (no toggle).\n veo3: { mode: \"native_speech\", alwaysOn: true },\n \"veo3.1\": { mode: \"native_speech\", alwaysOn: true },\n veo3_lite: { mode: \"native_speech\", alwaysOn: true },\n // Kling 2.6 / 3.0 — native spoken dialogue + lip sync behind the `sound`\n // toggle (probe-verified on the KIE path 2026-07-16: scripted quoted lines\n // are spoken verbatim with articulated lips; the official Kling 2.6 audio\n // guide documents speech/dialogue/narration/singing with [Character@Voice]\n // binding, zh+en voices). Cost-affecting: `:audio` credit suffix.\n // kling-3.0's model default is sound ON (kie models.ts extraParams +\n // kling3-client `?? true`) → defaultOn keeps billing aligned with what an\n // intent-less request actually generates; kling 2.6 defaults OFF.\n kling: { mode: \"native_speech\", field: \"sound\", affectsCost: true },\n \"kling-3.0\": { mode: \"native_speech\", field: \"sound\", affectsCost: true, defaultOn: true },\n // Kling 3.0 Omni (Replicate kwaivgi/kling-v3-omni-video) — the Omni tier's\n // headline feature IS native dialogue (per-character voices, unified audio\n // timeline). Lever is Replicate's `generate_audio` (default true in our\n // provider config → defaultOn); audio is priced into the flat per-duration\n // rate, so NOT cost-affecting (no :audio composite).\n \"kling-3-omni\": { mode: \"native_speech\", field: \"generateAudio\", defaultOn: true },\n // Seedance 2.0 — multimodal; lip-syncs to a supplied reference-audio track.\n \"seedance-2\": { mode: \"audio_driven\", field: \"generateAudio\" },\n \"seedance-2-fast\": { mode: \"audio_driven\", field: \"generateAudio\" },\n \"seedance-2-mini\": { mode: \"audio_driven\", field: \"generateAudio\" },\n // Seedance 2.5 — same audio-driven surface; `generate_audio` defaults TRUE\n // on KIE and is cost-affecting only through the -ref/no-ref rate split,\n // which the resolution+ref composite already carries (no `:audio` suffix).\n \"seedance-2-5\": { mode: \"audio_driven\", field: \"generateAudio\", defaultOn: true },\n // MiniMax Hailuo 3 — multimodal; lip-syncs to reference audio (r2v). The\n // KIE API exposes NO audio on/off parameter (audio is always produced), so\n // there is no toggle field — alwaysOn, like VEO.\n \"minimax-h3\": { mode: \"audio_driven\", alwaysOn: true },\n // Wan 3.0 family — a single boolean `audio` lever (KIE default true) produces\n // an ambient/SFX track with the clip. Classified \"ambient\", NOT\n // \"native_speech\" or \"audio_driven\": the schema documents no dialogue\n // guarantee, and reference audio is a generic conditioning array, not a\n // verified lip-sync transport. Upgrade only on a live probe (the kling-3.0\n // standard) — `audio_driven` would reroute the Story→Video dialogue pipeline\n // and skip the lip-sync pass. `defaultOn` mirrors the KIE default so an\n // intent-less request is described honestly; audio is priced into the uniform\n // per-second rate, so NOT cost-affecting (no `:audio` composite).\n \"wan-3\": { mode: \"ambient\", field: \"audio\", defaultOn: true },\n \"wan-3-prime\": { mode: \"ambient\", field: \"audio\", defaultOn: true },\n // Vidu Q4 — the same boolean `audio` lever (KIE default true). The schema\n // says \"dialogue and sound effects\", but classified \"ambient\" on the Wan 3.0\n // rule: no live probe has verified lip-synced speech, and `native_speech` /\n // `audio_driven` would reroute the Story→Video dialogue pipeline. Audio is\n // priced into the uniform per-second rate (no `:audio` composite).\n \"vidu-q4\": { mode: \"ambient\", field: \"audio\", defaultOn: true },\n // Kling 4.0 — native audio on both endpoints, no lever: neither schema has\n // an audio switch (the reference endpoint's `keep_original_sound` only picks\n // between a reference video's own sound and generated sound). Classified\n // \"ambient\" on the Wan 3.0 rule until a live probe verifies scripted\n // dialogue; priced into the per-second rate.\n \"kling-4\": { mode: \"ambient\", alwaysOn: true, defaultOn: true },\n \"kling-4-keyframes\": { mode: \"ambient\", alwaysOn: true, defaultOn: true },\n // Kling 4.0 Flash — the same: native audio on both endpoints, no lever.\n \"kling-4-flash\": { mode: \"ambient\", alwaysOn: true, defaultOn: true },\n // PixVerse V6 Max — a boolean `generate_audio_switch` lever on both\n // endpoints. Cost-affecting: the with-audio rows bill at a higher per-second\n // rate (`:audio` suffix, AUDIO_ADDON_PROVIDERS), so — like Kling — only the\n // canonical `sound` intent turns it. `defaultOn`: a request that names no\n // audio setting renders AND bills audio (decided 2026-11-11; KIE's own default\n // is off, so the runner sends the switch explicitly). Classified \"ambient\" on\n // the Wan 3.0 rule: the schema mentions dialogue and lip-sync, but no live\n // probe has verified scripted speech, and `native_speech` would reroute the\n // Story→Video dialogue pipeline past its lip-sync pass. `readsGenerateAudio`:\n // the `generateAudio` field turns it too (after `sound`), and the price\n // follows the same resolved intent (videoAudioIntent).\n \"pixverse-v6-max\": { mode: \"ambient\", field: \"generateAudioSwitch\", affectsCost: true, defaultOn: true, readsGenerateAudio: true },\n // Gemini Omni Flash 1.2 — native audio with no on/off input in its schema.\n \"gemini-omni-flash-1-2\": { mode: \"ambient\", alwaysOn: true },\n // Gemini Omni (both SKUs — the pro `gemini-omni-video` and the faster\n // `gemini-omni-flash`; one model at two speeds, so their rows are identical\n // and a test pins that). Settled 2026-09-03 from Google's own documentation\n // at https://ai.google.dev/gemini-api/docs/omni, having been unlisted — and\n // therefore reported as SILENT — while the catalog described both as \"native\n // audio\".\n //\n // \"ambient\", and alwaysOn with no toggle field, on three sentences from that\n // page:\n // - \"By default the model will try to generate an appropriate audio track\n // for a video.\" Audio on every render, and the KIE input schema\n // (prompt / image_urls / first+last_frame_url / audio_ids / video_list /\n // character_ids / duration / aspect_ratio / seed / resolution — see\n // docs.kie.ai/market/gemini-omni-video and\n // docs.kie.ai/market/google/gemini-omni-flash-1-1) carries no on/off\n // lever, so there is nothing for applyVideoAudioToggle to write.\n // - NOT native_speech: \"Multi-turn voice extension: Generating spoken\n // dialogue or speech is supported when extending previously generated\n // videos via multi-turn (`previous_interaction_id`)\" — a field KIE's\n // createTask schema does not expose, so the dialogue path is unreachable\n // on our transport. Held to the Wan 3.0 bar: no documented dialogue\n // guarantee on the path we actually drive ⇒ ambient, and upgrade only on\n // a live probe (the kling-3.0 standard). Classifying it native_speech\n // would reroute the Story→Video dialogue pipeline past the lip-sync pass.\n // - NOT audio_driven either: \"Uploading audio references is unsupported in\n // the current version of the API\", and \"any audio in a video reference is\n // ignored\" — there is no reference-audio transport to be driven by, and\n // runGeminiOmni sends `audio_ids` ONLY for a\n // character's pinned voice persona (a preset voice, never a recording), which\n // is not a reference-audio transport and leaves the mode `ambient`.\n // Audio is priced into the per-tier rate, so NOT cost-affecting.\n \"gemini-omni-video\": { mode: \"ambient\", alwaysOn: true },\n \"gemini-omni-flash\": { mode: \"ambient\", alwaysOn: true },\n}\n\nconst VIDEO_AUDIO_NONE: VideoAudioCapability = { mode: \"none\" }\n\n/** Audio capability for a video model. Unlisted/undefined → silent (`none`). */\nexport function getVideoAudioCapability(\n model: string | undefined,\n): VideoAudioCapability {\n return (model ? VIDEO_AUDIO_CAPABILITY[model] : undefined) ?? VIDEO_AUDIO_NONE\n}\n\n/**\n * True when the model produces any audio track at all. Drives the config-panel\n * audio toggle: `false` → disable the toggle + show a \"this model has no audio\"\n * note (never restrict the model choice — just explain the limitation).\n */\nexport function videoModelSupportsAudio(model: string | undefined): boolean {\n return getVideoAudioCapability(model).mode !== \"none\"\n}\n\n/**\n * True when the model can produce lip-synced spoken DIALOGUE — either natively\n * (VEO 3.x, Kling 2.6/3.0/Omni) or driven by a supplied audio track (Seedance\n * 2.0). Drives the Story→Video dialogue auto-pick: in-model speech + character\n * revoice (VEO, Kling) / character-voiced reference audio (Seedance 2.0) vs.\n * the TTS + separate-lip-sync fallback. Ambient-only models (Seedance 1.x)\n * return `false` — their audio is SFX, not speech.\n */\nexport function videoModelCanSpeakDialogue(model: string | undefined): boolean {\n const mode = getVideoAudioCapability(model).mode\n return mode === \"native_speech\" || mode === \"audio_driven\"\n}\n\n/**\n * THE audio intent of a video request for one model — `undefined` when the\n * request expresses none (the model's own default then applies). The ONE\n * reading of the request's audio fields: {@link applyVideoAudioToggle} (what\n * the model is SENT) and `buildVideoCreditModelIdentifier` (the `:audio` row\n * it is PRICED at) both resolve through it, so the two cannot disagree.\n *\n * - A cost-affecting model reads `sound` alone (Kling: the field its `:audio`\n * surcharge has always keyed off), unless it declares `readsGenerateAudio`\n * (PixVerse V6 Max): then `sound`, else `generateAudio`.\n * - Every other model reads `sound`, else the `generateAudio` alias.\n */\nexport function videoAudioIntent(provider: string | undefined, req: VideoAudioRequest | undefined): boolean | undefined {\n const cap = getVideoAudioCapability(provider)\n if (cap.affectsCost && cap.readsGenerateAudio !== true) return req?.sound\n return req?.sound ?? req?.generateAudio\n}\n\n/**\n * Whether a request PRICES with audio on a cost-affecting model: its intent\n * ({@link videoAudioIntent}), else the model's own default (`defaultOn`). The\n * provider runner of such a model renders the same state.\n */\nexport function videoAudioPricedOn(provider: string | undefined, req: VideoAudioRequest | undefined): boolean {\n return videoAudioIntent(provider, req) ?? (getVideoAudioCapability(provider).defaultOn === true)\n}\n\n/**\n * Write the caller's neutral \"enable native audio\" intent onto a KIE provider\n * `input` under whichever field the chosen model actually reads, per\n * `VIDEO_AUDIO_CAPABILITY.field`. This is the single dispatch point that fixes\n * the recurring \"sound toggle dropped on Seedance/VEO\" bug class: callers pass\n * the model-agnostic toggle ONCE and never need to know that Kling's lever is\n * `sound` while Seedance's is `generate_audio`.\n *\n * - `sound` is the canonical neutral name; `generateAudio` is accepted as a\n * legacy alias (the workflow node + some clients send that key). `sound` wins\n * if both are present.\n * - **The intent is {@link videoAudioIntent}'s** — the same reading the `:audio`\n * credit surcharge (`AUDIO_ADDON_PROVIDERS` in `credit-identifiers.ts`) is\n * built from. That makes a billed-but-not-generated (or generated-but-not-\n * billed) divergence structurally impossible: the model and the surcharge\n * read the same fields. Kling honours ONLY `sound`; PixVerse V6 Max\n * (`readsGenerateAudio`) and every free model also the `generateAudio` alias.\n * - No-op for `alwaysOn` models (VEO — audio can't be toggled) and silent /\n * unlisted models (no `field`), and when the caller expressed no intent\n * (leaves the model's own default in place).\n *\n * Future audio models are covered automatically by adding a\n * `VIDEO_AUDIO_CAPABILITY` entry — already guarded by the\n * `video-audio-capability` drift test, so this never silently regresses.\n */\nexport function applyVideoAudioToggle(\n input: Record<string, unknown>,\n provider: string | undefined,\n opts: { sound?: boolean; generateAudio?: boolean } | undefined,\n): void {\n const cap = getVideoAudioCapability(provider)\n if (!cap.field) return // alwaysOn (VEO) or silent/unlisted model — nothing to toggle\n // The one reading of the request's audio fields, shared with the credit\n // surcharge (see videoAudioIntent). `sound` is canonical and wins when both are set.\n const enabled = videoAudioIntent(provider, opts)\n if (enabled === undefined) return // no intent — keep the model's own default\n if (cap.field === \"generateAudio\") input.generate_audio = enabled\n else if (cap.field === \"audio\") input.audio = enabled\n else if (cap.field === \"generateAudioSwitch\") input.generate_audio_switch = enabled\n else input.sound = enabled\n}\n\n/**\n * Video models where a quality/mode parameter (e.g., videoSize \"high\") incurs higher cost.\n * When provider is in this set and mode is \"high\", \":high\" is appended to the identifier.\n */\nexport const MODE_ADDON_PROVIDERS = new Set<string>([\n])\n\n/**\n * VEO 3.x providers where credit cost depends on the requested output\n * resolution (720p default vs 1080p inline; 4K is via the separate\n * upgrade endpoint and isn't part of this set). When provider is in\n * this set and resolution !== \"720p\", `:1080p` is appended to the\n * identifier so the credit lookup hits the per-resolution rate.\n *\n * Per KIE pricing (verified 2026-05-06):\n * veo3.1 (Fast): 720p=60 KIE cr, 1080p=65 KIE cr\n * veo3_lite: 720p=30 KIE cr, 1080p=35 KIE cr\n * veo3 (Quality) is not in this set yet — pricing not in our reference data.\n */\nexport const VEO_RESOLUTION_TIERED_PROVIDERS = new Set<string>([\n \"veo3.1\",\n \"veo3_lite\",\n])\n\n/**\n * Video variable pricing config — which params affect credit cost per model.\n * \"duration\" = cost varies by video length\n * \"duration+audio\" = cost varies by length AND audio on/off\n * \"duration+resolution+audio\" = cost varies by length, resolution AND audio on/off\n */\nexport const VIDEO_VARIABLE_PRICING: Record<string, \"duration\" | \"duration+audio\" | \"duration+mode\" | \"duration+resolution+ref\" | \"duration+resolution\" | \"duration+resolution+audio\"> = {\n \"kling-3.0\": \"duration+audio\",\n \"kling-3-omni\": \"duration\",\n \"kling\": \"duration+audio\",\n \"kling-turbo\": \"duration\",\n \"kling-master\": \"duration\",\n \"grok-i2v\": \"duration\",\n \"wan-i2v\": \"duration\",\n \"hailuo-2.3-pro\": \"duration\",\n \"hailuo-2.3\": \"duration\",\n \"hailuo-standard\": \"duration\",\n \"seedance-2\": \"duration+resolution+ref\",\n \"seedance-2-fast\": \"duration+resolution+ref\",\n \"seedance-2-mini\": \"duration+resolution+ref\",\n \"seedance-2-5\": \"duration+resolution+ref\",\n // MiniMax Hailuo 3 — per-second rate at two resolution tiers (2K default /\n // 768P). Duration + resolution form the composite (bare = 2K, \":768p\"\n // appended for the cheaper tier); ref-video input seconds + extra input\n // images are billed via the dedicated compute hook, not the identifier.\n \"minimax-h3\": \"duration+resolution\",\n // Grok Imagine Video 1.5 — per-second billing at 480p / 720p / 1080p (no\n // video-ref dimension, no per-image or per-frame part).\n \"grok-imagine-video-1.5\": \"duration+resolution\",\n // Wan 3.0 family — per-second billing at three resolution rates (no video-ref\n // dimension: reference runs bill output seconds only). No gemini-omni-flash\n // entry, mirroring gemini-omni-video which has none either.\n \"wan-3\": \"duration+resolution\",\n \"wan-3-prime\": \"duration+resolution\",\n // Vidu Q4 — per-second billing at five resolution rates; no reference or\n // audio dimension.\n \"vidu-q4\": \"duration+resolution\",\n // Kling 4.0 — per-second at two resolution rates; `kling-4` adds the\n // reference-video rate.\n \"kling-4\": \"duration+resolution+ref\",\n \"kling-4-keyframes\": \"duration+resolution\",\n // Kling 4.0 Flash — per-second at 720p, plus the reference-video rate.\n \"kling-4-flash\": \"duration+resolution+ref\",\n // Gemini Omni Flash 1.2 — per-second at four resolution rates; a video edit\n // bills the same rates over the source clip.\n \"gemini-omni-flash-1-2\": \"duration+resolution\",\n // PixVerse V6 Max — per-second at four quality rates, each with and without\n // native audio.\n \"pixverse-v6-max\": \"duration+resolution+audio\",\n}\n\n/**\n * @deprecated Read {@link pricedOutputDurationSec} (or the catalog's\n * `defaultDuration`). Kept only as a derived view of `MODEL_CATALOG` for\n * consumers of the published package that imported the old hand-kept map; no\n * pricing path reads it (`pricing-default-duration-guard.test.ts` fails the\n * build if one does).\n */\nexport const PRICING_DEFAULT_DURATION_SEC: Readonly<Record<string, number>> = Object.freeze(\n Object.fromEntries(\n Object.values(MODEL_CATALOG)\n .filter((e) => e.kind === \"video\" && typeof e.defaultDuration === \"number\")\n .map((e) => [e.id, e.defaultDuration as number]),\n ),\n)\n\n/**\n * The legal length nearest to `requested` — ties go to the earlier (shorter)\n * entry of the list. This is the SAME rule every video runner snaps a request\n * with (`snapToAllowedDuration` delegates here), so the length a request is\n * priced at and the length it renders can never be two different numbers.\n */\nexport function snapToNearestDuration(requested: number, allowed: readonly number[] | undefined): number {\n if (!allowed || allowed.length === 0) return requested\n if (allowed.includes(requested)) return requested\n return allowed.reduce((best, d) => (Math.abs(d - requested) < Math.abs(best - requested) ? d : best))\n}\n\n/**\n * The length a model renders when the request names none, from the model\n * catalog (`defaultDuration`); else its shortest legal length; else 5 for an id\n * the catalog does not list. A video model that is priced by length MUST\n * declare `defaultDuration` (`pricing-default-duration-sync.test.ts`).\n */\nexport function videoDefaultDurationSec(provider: string): number {\n const entry = MODEL_CATALOG[provider]\n if (typeof entry?.defaultDuration === \"number\") return entry.defaultDuration\n const shortest = entry?.durations?.length ? Math.min(...entry.durations) : undefined\n return shortest ?? 5\n}\n\n/**\n * The output seconds a video request is CHARGED at — the ONE funnel every\n * price path reads (the credit identifier's tier, the run reservation and\n * commit, the editor and server estimates, the Seedance and MiniMax\n * reference-video reservations and the Loop Trim refund).\n *\n * - no duration (or an unusable one) → the model's own default render length\n * (`MODEL_CATALOG[provider].defaultDuration`), never a global 5;\n * - a duration the model does not offer → the nearest one it does\n * ({@link snapToNearestDuration}, the runners' own rule), because that is the\n * length it renders;\n * - AUTO (`VIDEO_DURATION_AUTO`) → the model's longest clip: the model picks\n * the length, `commit_credits` refunds a surplus but never collects a\n * deficit, and the delivered clip is measured at settle time\n * (lib/seedance2-ref-video-settle.ts).\n *\n * A literal `?? 5` (or `?? 8`) at any pricing site re-opens the gap this closes;\n * `pricing-default-duration-guard.test.ts` fails the build on one.\n */\nexport function pricedOutputDurationSec(provider: string, requested: number | string | undefined): number {\n const fallback = videoDefaultDurationSec(provider)\n const parsed = typeof requested === \"string\" ? parseInt(requested, 10) : requested\n if (parsed === undefined || Number.isNaN(parsed)) return fallback\n if (parsed <= 0) {\n return isAutoVideoDuration(parsed) && supportsAutoVideoDuration(provider)\n ? maxVideoDurationSec(provider) ?? fallback\n : fallback\n }\n return snapToNearestDuration(parsed, MODEL_CATALOG[provider]?.durations)\n}\n\n/** Models that accept `VIDEO_DURATION_AUTO` — a catalog capability (docs.kie.ai:\n * the Seedance 2 family, \"4-15 seconds or -1\" / 2.5 \"Special values -1\"). */\nexport function supportsAutoVideoDuration(provider: string | undefined): boolean {\n return !!provider && MODEL_CATALOG[provider]?.autoDuration === true\n}\n\n/** Models that accept a reference task type declaration — a catalog capability\n * (`MODEL_CATALOG[id].referenceTaskTypes`, see `SEEDANCE_REFERENCE_TASK_TYPES`). */\nexport function supportsReferenceTaskType(provider: string | undefined): boolean {\n return !!provider && (MODEL_CATALOG[provider]?.referenceTaskTypes?.length ?? 0) > 0\n}\n\n/** What a request knows that decides its reference task type. */\nexport interface SeedanceTaskTypeFacts {\n provider: string | undefined\n /** The value the request carries, unvalidated: anything but a declared value is Auto. */\n requested: unknown\n /**\n * @deprecated Not read: a draft declares exactly as any other run does. Kept\n * so a caller that still passes it compiles; leave it out.\n */\n draft?: boolean\n /** Reference images only: a start or end frame is not counted. */\n referenceImageCount: number\n referenceAudioCount: number\n /** One entry per reference video; `undefined` = its length could not be measured. */\n referenceVideoSec: ReadonlyArray<number | undefined>\n aspectRatio: string | undefined\n duration: number | undefined\n}\n\n/** The declaration a request sends (if any), and the ratio and length it runs at. */\nexport interface SeedanceTaskTypeResolution {\n /** `undefined`: nothing is declared and the provider guesses from the prompt. */\n taskType: DeclaredSeedanceTaskType | undefined\n aspectRatio: string | undefined\n duration: number | undefined\n /** Each change made to the ratio or length, for disclosure. Empty when nothing changed. */\n adjustments: ModelInputAdjustment[]\n}\n\n/** The aspect ratio an `extend` runs at: the reference video's own (an `edit`\n * takes its whole shape from `SEEDANCE_VIDEO_EDIT_SHAPE`). */\nconst SEEDANCE_EXTEND_ASPECT = \"adaptive\"\n\n/**\n * `requested` when the model's catalog `referenceTaskTypes` lists it (strict\n * match), else `undefined`. The one membership test: the resolver below and the\n * provider adapter that writes the value both ask it.\n */\nexport function listedSeedanceTaskType(provider: string | undefined, requested: unknown): DeclaredSeedanceTaskType | undefined {\n return provider ? MODEL_CATALOG[provider]?.referenceTaskTypes?.find((t) => t === requested) : undefined\n}\n\n/** How many of each kind of reference media a request carries. A start or end frame is not reference media. */\nexport interface SeedanceReferenceMediaCount {\n imageCount: number\n videoCount: number\n audioCount: number\n}\n\n/**\n * Whether a request's reference media is what the declared type needs:\n * `reference` takes any reference media; `edit` and `extend` need a reference\n * video, since both act on one. The one media rule: the resolver below asks it\n * of the request, and the provider adapter of the body as it will be sent.\n */\nexport function seedanceTaskTypeFitsMedia(type: DeclaredSeedanceTaskType, media: SeedanceReferenceMediaCount): boolean {\n return type === \"reference\" ? media.imageCount + media.videoCount + media.audioCount > 0 : media.videoCount > 0\n}\n\nfunction editReferenceVideosFit(referenceVideoSec: ReadonlyArray<number | undefined>): boolean {\n const { min, max } = SEEDANCE_EDIT_REF_VIDEO_SEC\n return referenceVideoSec.every((sec) => typeof sec === \"number\" && sec >= min && sec <= max)\n}\n\n/**\n * The ONE place that decides whether a request declares a reference task type,\n * and the aspect ratio and length that declaration forces.\n *\n * Declared only when every condition holds; otherwise the result is the input\n * unchanged (no declaration, ratio and length as given, nothing reported):\n * - the request asks for a value the model's catalog `referenceTaskTypes`\n * LISTS, matched exactly. The list is what is honoured: a model that lists\n * nothing, a value it does not list (`auto`, a wrong case, a number) and a\n * model that lists only some values are all Auto;\n * - it has the reference media the type needs\n * ({@link seedanceTaskTypeFitsMedia}): `edit` and `extend` need a\n * reference video;\n * - for `edit`, every reference video is measured and between\n * `SEEDANCE_EDIT_REF_VIDEO_SEC.min` and `.max` seconds inclusive.\n *\n * What a declaration forces:\n * - `reference` — nothing;\n * - `edit` — the edit shape, `SEEDANCE_VIDEO_EDIT_SHAPE` (`\"adaptive\"`\n * and Auto length): the output takes the video's own shape\n * and length;\n * - `extend` — `\"adaptive\"`; a fixed length is kept, and Auto or no length\n * becomes the model's catalog `defaultDuration`.\n *\n * Each value it changes is reported as one adjustment; a value it fills where\n * the request had none is not a correction and reports nothing, and neither is\n * a ratio that already runs at the forced one (`\"Auto\"` with a reference video\n * runs at `\"adaptive\"`).\n *\n * A draft (`draft: true`) is no exception: it declares, and is forced, exactly\n * as the same request without Draft (a draft and its 1080p finalize keep an\n * edit's own length and framing, measured). Pure.\n */\nexport function resolveSeedanceTaskType(facts: SeedanceTaskTypeFacts): SeedanceTaskTypeResolution {\n const { provider, aspectRatio, duration, referenceVideoSec } = facts\n const unchanged: SeedanceTaskTypeResolution = { taskType: undefined, aspectRatio, duration, adjustments: [] }\n const taskType = listedSeedanceTaskType(provider, facts.requested)\n if (!taskType || !provider) return unchanged\n const media = {\n imageCount: facts.referenceImageCount,\n videoCount: referenceVideoSec.length,\n audioCount: facts.referenceAudioCount,\n }\n if (!seedanceTaskTypeFitsMedia(taskType, media)) return unchanged\n if (taskType === \"edit\" && !editReferenceVideosFit(referenceVideoSec)) return unchanged\n if (taskType === \"reference\") return { ...unchanged, taskType }\n\n const verb = taskType === \"edit\" ? \"Edit\" : \"Extend\"\n const nextAspect = taskType === \"edit\" ? SEEDANCE_VIDEO_EDIT_SHAPE.aspectRatio : SEEDANCE_EXTEND_ASPECT\n const adjustments: ModelInputAdjustment[] = []\n const askedAspect = typeof aspectRatio === \"string\" ? aspectRatio.trim() : \"\"\n // A ratio that already runs at the forced one is not replaced: the forced\n // value itself, or the \"Auto\" token, which a request with a reference video\n // runs at \"adaptive\" (`videoAutoAspectRunsAt`, the adapter's own rule).\n const runsAtForced = askedAspect.toLowerCase() === nextAspect\n || (isVideoAutoAspectToken(askedAspect) && videoAutoAspectRunsAt(provider, media.videoCount > 0) === nextAspect)\n if (askedAspect !== \"\" && !runsAtForced) {\n adjustments.push({\n field: \"aspectRatio\", from: askedAspect, to: nextAspect,\n reason: `${verb} keeps the video's own shape — using \"${nextAspect}\" instead of \"${askedAspect}\".`,\n })\n }\n\n let nextDuration: number\n if (taskType === \"edit\") {\n nextDuration = SEEDANCE_VIDEO_EDIT_SHAPE.duration\n if (duration !== undefined && !isAutoVideoDuration(duration)) {\n adjustments.push({\n field: \"duration\", from: duration, to: nextDuration,\n reason: `Edit keeps the video's own length — using Auto instead of ${duration}s.`,\n })\n }\n } else if (duration === undefined || isAutoVideoDuration(duration)) {\n nextDuration = videoDefaultDurationSec(provider)\n if (duration !== undefined) {\n adjustments.push({\n field: \"duration\", from: duration, to: nextDuration,\n reason: `Extend needs a set length — using ${nextDuration}s, the model's default, instead of Auto.`,\n })\n }\n } else {\n nextDuration = duration\n }\n\n return { taskType, aspectRatio: nextAspect, duration: nextDuration, adjustments }\n}\n\n/** The longest clip a duration-tiered provider can render (its top priced tier). */\nexport function maxVideoDurationSec(provider: string): number | undefined {\n const tiers = VIDEO_DURATION_TIERS[provider]\n return tiers && tiers.length > 0 ? tiers[tiers.length - 1]!.maxSeconds : undefined\n}\n\n/**\n * Resolution assumed for PRICING when a request names a provider but omits\n * `resolution` — the resolution twin of {@link PRICING_DEFAULT_DURATION_SEC},\n * and it MUST match the provider's KIE-side default (`extraParams.resolution`\n * in backend kie/models.ts) so an intent-less request reserves what it will\n * actually render.\n *\n * Without an entry, `buildVideoCreditModelIdentifier` falls back to the\n * CHEAPEST tier (480p) for a resolution-priced provider. That is safe only for\n * a model whose KIE default IS the cheapest tier; for one defaulting to 720p it\n * reserves the 480p price against a 720p render, and `commit_credits` cannot\n * collect the difference afterwards.\n *\n * Providers absent here keep the historical 480p fallback — deliberately, so\n * adding this map cannot reprice anything already live.\n */\nexport const PRICING_DEFAULT_RESOLUTION: Record<string, string> = {\n // KIE renders 720p when `resolution` is omitted (kie/models.ts extraParams).\n \"seedance-2-5\": \"720p\",\n // Wan 3.0 family — KIE's OWN default is 1080P, but the provider layer pins\n // 720P (normalizeWan3Resolution / WAN_3_DEFAULT_RESOLUTION) so the rendered\n // tier equals the tier the bare identifier bills. This declaration is what\n // makes the billed default explicit instead of an array ordering: the\n // RESOLUTION_DURATION_PRICING branch consults it before falling back to the\n // first tier, so the catalog can stay ascending without repricing anything.\n \"wan-3\": \"720p\",\n \"wan-3-prime\": \"720p\",\n // Vidu Q4 — KIE renders 720p when `resolution` is omitted, and\n // normalizeViduQ4Resolution pins the same tier for anything unknown.\n \"vidu-q4\": \"720p\",\n // Kling 4.0 — KIE renders 720p when `resolution` is omitted, and\n // normalizeKling4Resolution pins the same tier for anything unknown.\n \"kling-4\": \"720p\",\n \"kling-4-keyframes\": \"720p\",\n // Kling 4.0 Flash — 720p is its only tier.\n \"kling-4-flash\": \"720p\",\n // Gemini Omni Flash 1.2 — KIE renders 720p when `resolution` is omitted, and\n // the runner sends 720p for anything off its list.\n \"gemini-omni-flash-1-2\": \"720p\",\n // Grok Imagine Video 1.5 — KIE renders 480p when `resolution` is omitted, and\n // normalizeGrokVideo15Resolution pins the same tier for anything unknown. It\n // is also the cheapest tier, so the bill does not move; declared so a run\n // that names no resolution is judged at 480p by the free-tier check (decided\n // 2026-11-11) and is sent 480p by pricedVideoSelection.\n \"grok-imagine-video-1.5\": \"480p\",\n // PixVerse V6 Max — KIE requires a quality and has no default; the runner\n // sends 720p for an omitted or unknown one (normalizePixverseV6MaxQuality),\n // never the 360p preview tier.\n \"pixverse-v6-max\": \"720p\",\n}\n\n/** Gemini Omni Flash 1.2 per-second tiers — one per allowed duration (3–15s). */\nconst GEMINI_OMNI_12_DURATION_TIERS: Array<{ maxSeconds: number; suffix: string }> = Array.from(\n { length: 13 },\n (_, i) => ({ maxSeconds: i + 3, suffix: `${i + 3}s` }),\n)\n\n/** HappyHorse 1.1 per-second tiers — one per allowed duration (3–15s), shared\n * by all three modes (t2v/i2v/ref2v) which bill at identical published rates. */\nconst HAPPYHORSE_DURATION_TIERS: Array<{ maxSeconds: number; suffix: string }> = Array.from(\n { length: 13 },\n (_, i) => ({ maxSeconds: i + 3, suffix: `${i + 3}s` }),\n)\n\n/**\n * Seedance 2.5 per-second tiers — one per allowed duration (4–30s), like\n * minimax-h3 and unlike the 2.0 family's coarse 4/8/12/15 ladder.\n *\n * Per-second is REQUIRED here, not a nicety: the ladder snaps a request UP to\n * the first tier whose `maxSeconds` covers it and falls back to the LAST tier\n * when nothing does, so a coarse ladder over a 30s range would reserve the 15s\n * price for a 30s render. `commit_credits` only ever refunds a surplus and can\n * never collect an upward delta, so that under-reservation would be permanent.\n */\nconst SEEDANCE_2_5_DURATION_TIERS: Array<{ maxSeconds: number; suffix: string }> = Array.from(\n { length: 27 },\n (_, i) => ({ maxSeconds: i + 4, suffix: `${i + 4}s` }),\n)\n\n/**\n * Wan 3.0 per-second tiers — one per allowed duration (2-30s), shared by both\n * SKUs (the ladder shape is identical; only the seeded rates differ).\n *\n * Per-second is REQUIRED, not a nicety: the ladder snaps a request UP to the\n * first tier whose `maxSeconds` covers it and falls back to the LAST tier when\n * none does, so a coarse ladder over a 29-value range would reserve a\n * short-clip price for a 30s render. `commit_credits` only ever refunds a\n * surplus and can never collect an upward delta.\n */\nconst WAN_3_DURATION_TIERS: Array<{ maxSeconds: number; suffix: string }> = Array.from(\n { length: 29 },\n (_, i) => ({ maxSeconds: i + 2, suffix: `${i + 2}s` }),\n)\n\n/**\n * Vidu Q4 per-second tiers — one per allowed duration (3-16s). Per-second for\n * the same reason as Wan 3.0: a coarse ladder would snap a long render down to\n * a shorter tier's price, which `commit_credits` can never collect afterwards.\n */\nconst VIDU_Q4_DURATION_TIERS: Array<{ maxSeconds: number; suffix: string }> = Array.from(\n { length: 14 },\n (_, i) => ({ maxSeconds: i + 3, suffix: `${i + 3}s` }),\n)\n\n/** Kling 4.0 per-second tiers — one per allowed duration (3-30s), both ids. */\nconst KLING_4_DURATION_TIERS: Array<{ maxSeconds: number; suffix: string }> = Array.from(\n { length: 28 },\n (_, i) => ({ maxSeconds: i + 3, suffix: `${i + 3}s` }),\n)\n\n/** Kling 4.0 Flash per-second tiers — one per allowed duration (3-20s). */\nconst KLING_4_FLASH_DURATION_TIERS: Array<{ maxSeconds: number; suffix: string }> = Array.from(\n { length: 18 },\n (_, i) => ({ maxSeconds: i + 3, suffix: `${i + 3}s` }),\n)\n\n/** PixVerse V6 Max per-second tiers — one per allowed duration (1-15s). */\nconst PIXVERSE_V6_MAX_DURATION_TIERS: Array<{ maxSeconds: number; suffix: string }> = Array.from(\n { length: 15 },\n (_, i) => ({ maxSeconds: i + 1, suffix: `${i + 1}s` }),\n)\n\n/**\n * Duration tier breakpoints for variable-priced video models.\n * Maps provider → array of { maxSeconds, suffix } in ascending order.\n * The first tier whose maxSeconds >= requested duration is used.\n */\nexport const VIDEO_DURATION_TIERS: Record<string, Array<{ maxSeconds: number; suffix: string }>> = {\n \"kling-3.0\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"kling-3-omni\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"kling\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"kling-turbo\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"kling-master\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"grok-i2v\": [\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"wan-i2v\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"hailuo-2.3-pro\": [\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"hailuo-2.3\": [\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"hailuo-standard\": [\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"seedance-2\": [\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"seedance-2-mini\": [\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n // The length tiers of the earlier Seedance Extend rows\n // (`seedance-2-extend:<tier>:<res>`). No extend is priced on them any more —\n // each Seedance extend provider has a row per second (`tailExtendCreditId`)\n // — and the rows themselves were removed (migration 648); the tiers stay,\n // unread, as part of this published table.\n \"seedance-2-extend\": [\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"seedance-2-fast\": [\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"seedance-2-5\": SEEDANCE_2_5_DURATION_TIERS,\n \"wan-3\": WAN_3_DURATION_TIERS,\n \"wan-3-prime\": WAN_3_DURATION_TIERS,\n \"vidu-q4\": VIDU_Q4_DURATION_TIERS,\n \"kling-4\": KLING_4_DURATION_TIERS,\n \"kling-4-keyframes\": KLING_4_DURATION_TIERS,\n \"kling-4-flash\": KLING_4_FLASH_DURATION_TIERS,\n \"pixverse-v6-max\": PIXVERSE_V6_MAX_DURATION_TIERS,\n \"gemini-omni-flash-1-2\": GEMINI_OMNI_12_DURATION_TIERS,\n // MiniMax Hailuo 3 — true per-second billing (KIE 36.5 cr/s @2K, 22.5 cr/s\n // @768P). One tier per allowed second (4-15s) so the composite identifier\n // maps 1:1 to the seeded price — no rounding/overcharge for any on-menu\n // duration; the \":768p\" resolution suffix is appended after the tier.\n \"minimax-h3\": [\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 7, suffix: \"7s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 9, suffix: \"9s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 11, suffix: \"11s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 13, suffix: \"13s\" },\n { maxSeconds: 14, suffix: \"14s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n // Grok Imagine Video 1.5 — true per-second billing by resolution, with no\n // per-image or per-frame part. One tier per allowed second (1–15s) so the\n // composite identifier maps 1:1 to the seeded price — no rounding/overcharge\n // for any on-menu value.\n \"grok-imagine-video-1.5\": [\n { maxSeconds: 1, suffix: \"1s\" },\n { maxSeconds: 2, suffix: \"2s\" },\n { maxSeconds: 3, suffix: \"3s\" },\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 7, suffix: \"7s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 9, suffix: \"9s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 11, suffix: \"11s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 13, suffix: \"13s\" },\n { maxSeconds: 14, suffix: \"14s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n // HappyHorse 1.1 (t2v / i2v / ref2v) — true per-second billing (KIE 22.5 cr/s\n // @720p, 29 cr/s @1080p, published on kie.ai/happyhorse-1-1). One tier per\n // allowed second (3–15s) so the composite identifier maps 1:1 to the seeded\n // price, combined with RESOLUTION_DURATION_PRICING for the \":720p\"/\":1080p\"\n // suffix (e.g. \"happyhorse-i2v:5s:720p\").\n \"happyhorse\": HAPPYHORSE_DURATION_TIERS,\n \"happyhorse-i2v\": HAPPYHORSE_DURATION_TIERS,\n \"happyhorse-ref2v\": HAPPYHORSE_DURATION_TIERS,\n}\n\n/**\n * Maps composer node types to their plan type identifier and the node data field\n * where the plan is stored. Used by render-video payload building, plan syncing,\n * and the frontend DAG executor.\n */\nexport const COMPOSER_PLAN_MAP: Readonly<Record<string, { planType: string; planField: string }>> = {\n \"video-composer\": { planType: \"scene-graph\", planField: \"sceneGraph\" },\n \"after-effects\": { planType: \"after-effects\", planField: \"effectPlan\" },\n \"lottie-overlay\": { planType: \"lottie-overlay\", planField: \"overlayPlan\" },\n \"3d-title\": { planType: \"3d-title\", planField: \"titlePlan\" },\n \"motion-graphics\": { planType: \"motion-graphics\", planField: \"motionPlan\" },\n \"composite\": { planType: \"composite\", planField: \"compositePlan\" },\n // Scene3D previz (v1) — both the generator and the editor emit the SAME\n // validated `Scene3DPlan` revision on their `composition` handle, so\n // render-video routes either one to the `3d-scene` renderer unchanged.\n \"generate-3d-scene\": { planType: \"3d-scene\", planField: \"scenePlan\" },\n \"edit-3d-scene\": { planType: \"3d-scene\", planField: \"scenePlan\" },\n // 3D Render Pro authors the SAME `scenePlan` revision (v2) alongside its\n // MP4, so the render-only re-run reads it through this map exactly as it\n // reads a Basic revision — no second plan lane, no second render path.\n \"pro-3d-render\": { planType: \"3d-scene\", planField: \"scenePlan\" },\n}\n\n/** Every composer plan-field name, derived from COMPOSER_PLAN_MAP (single source\n * of truth — consumed by preset plan-state hygiene and job-output extraction). */\nexport const COMPOSER_PLAN_FIELDS: readonly string[] = [\n ...new Set(Object.values(COMPOSER_PLAN_MAP).map((m) => m.planField)),\n]\n\n/**\n * Duration tier breakpoints for motion control pricing (per-second billing).\n * Same shape as VIDEO_DURATION_TIERS entries but with 30s tier for long reference videos.\n */\nexport const MOTION_DURATION_TIERS: ReadonlyArray<{ maxSeconds: number; suffix: string }> = [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n { maxSeconds: 30, suffix: \"30s\" },\n]\n\n/** Curated i2v providers compatible with character portrait reference input.\n * Subset of IMAGE_TO_VIDEO_PROVIDERS — excludes text-to-video-only models. */\nexport const CHARACTER_MOTION_PROVIDERS = [\n \"kling\",\n \"kling-turbo\",\n \"kling-3.0\",\n \"wan-i2v\",\n \"wan-2.7-i2v\",\n] as const\nexport type CharacterMotionProvider = typeof CHARACTER_MOTION_PROVIDERS[number]\n\n/**\n * Atmospheric video providers available to the Location Studio's motion tab.\n *\n * Tuned for ambient camera moves (dolly, pan, drift, parallax) rather than\n * character-driven motion. Subset of registered i2v providers; `seedance-2`\n * added as the cinematic option for establishing shots.\n *\n * Mirrors `CHARACTER_MOTION_PROVIDERS` shape — see entity-prompts.ts for the\n * naming convention.\n */\nexport const LOCATION_ATMOSPHERE_PROVIDERS = [\n \"kling\",\n \"kling-turbo\",\n \"kling-3.0\",\n \"wan-i2v\",\n \"wan-2.7-i2v\",\n \"seedance-2\",\n] as const\nexport type LocationAtmosphereProvider =\n (typeof LOCATION_ATMOSPHERE_PROVIDERS)[number]\n\n/**\n * Subset of i2v providers tuned for short ambient object-motion clips (rotate,\n * hover, spin, parallax). Excludes premium models (Veo3, Veo3.1, Grok-i2v,\n * Sora2, Sora2-pro, Hailuo-2.3-pro) which are cost-prohibitive for the\n * product-loop use case (several times kling-turbo's per-clip cost).\n * Phase 2 candidate for adding veo3.1 if demand for premium hero shots\n * materializes.\n */\nexport const OBJECT_MOTION_PROVIDERS = [\n \"kling-turbo\", // 5s, fast, cheap (10 credits) — default\n \"kling\", // 5/10s\n \"kling-3.0\", // 3-15s, premium\n \"minimax\", // 5s, end-frame support\n \"hailuo-2.3\", // 6/10s\n \"wan-i2v\", // 5/10/15s\n \"seedance-2-mini\", // 4-15s, 480p/720p\n \"bytedance-lite\", // 5/10s\n] as const\nexport type ObjectMotionProvider = (typeof OBJECT_MOTION_PROVIDERS)[number]\n\n// =====================================================================\n// Scene Input Modes + Video Model Capability Registry (v4.0 + v4.1 spec §6.10)\n// =====================================================================\n\n/**\n * SceneInputMode — the input-shape contract a video model exposes to the\n * Scene Director. Gates which `video_model` values are valid for a given\n * scene's `shot_input_mode`. Consumed by Scene Director LLM prompting,\n * route Zod validation, and the frontend SceneNode config panel.\n *\n * See architecture spec §6.10 + v4.1 Methods 2/3/8/10 for per-mode semantics.\n */\nexport const SceneInputModeSchema = z.enum([\n \"text\", // text-to-video\n \"first_frame\", // i2v with start image only\n \"first_last_frame\", // i2v with paired start+end (v4.1 Method 2)\n \"ref_images\", // multi-ref consistency models\n \"multi_shot\", // native multi-shot models (Kling Omni, Seedance multi)\n \"video_continuation\", // v4.1 Method 3 — extend prior clip (VEO extend, Seedance video-ref)\n \"frame_interpolation\", // v4.1 Method 8 — N sparse keyframes → interpolated video\n \"camera_path\", // v4.1 Method 10 — parametric 3D camera path\n])\nexport type SceneInputMode = z.infer<typeof SceneInputModeSchema>\n\n/**\n * Prompting style each model expects from the Scene Director.\n * Veo-family wants comma-separated cinematic tags; Kling-family wants\n * natural-language prose; Hailuo-family wants compact single-sentence prompts.\n */\nexport type ModelPromptingStyle =\n | \"cinematic_tag_heavy\" // Veo-family — comma-separated tags\n | \"natural_language\" // Kling-family — prose descriptions\n | \"compact\" // Hailuo-family — single-sentence\n\nexport interface VideoModelCapabilities {\n inputModes: SceneInputMode[]\n maxShotsPerCall?: number // for multi_shot models\n supportsLipSyncIntegrated?: boolean // Kling Avatar / VEO-3 etc\n supportsVideoExtension?: boolean // v4.1 Method 3\n supportsCameraPath?: boolean // v4.1 Method 10\n maxInterpolationKeyframes?: number // v4.1 Method 8\n maxDurationSeconds: number\n prompting_style: ModelPromptingStyle\n /**\n * Maximum number of reference IMAGES the model accepts in one call,\n * including the start frame. Drives `allocateReferenceSlots` in\n * `backend/src/ee/pipelines/continuity.ts` (Phase 1C.1 §5.13.3) — when\n * the budget is 1, multi-shot/character/object refs are silently\n * dropped and the slot allocator emits a `pipeline:warning` event.\n * Defaults to 1 when omitted.\n */\n maxReferenceImages?: number\n}\n\n/**\n * VIDEO_MODEL_CAPS — single source of truth for what each video model supports.\n * Consumed by: Scene Director LLM (filters eligible models), route Zod validation\n * (rejects invalid video_model for the chosen shot_input_mode), frontend SceneNode\n * config panel (filters dropdown options).\n *\n * Adding a new video model: add an entry here, run audit-providers skill to verify\n * downstream wiring.\n */\nexport const VIDEO_MODEL_CAPS: Record<string, VideoModelCapabilities> = {\n \"kling\": {\n inputModes: [\"first_frame\", \"first_last_frame\", \"text\"],\n maxDurationSeconds: 10,\n prompting_style: \"natural_language\",\n maxReferenceImages: 1,\n },\n \"kling-3-omni\": {\n inputModes: [\"ref_images\", \"multi_shot\"],\n maxShotsPerCall: 5,\n maxDurationSeconds: 15,\n prompting_style: \"natural_language\",\n // Kling Omni accepts a strong multi-ref budget (start frame + up to\n // ~6 character/scene refs). Drives `allocateReferenceSlots` in\n // continuity.ts to surface all of them.\n maxReferenceImages: 7,\n },\n \"veo3.1\": {\n inputModes: [\"first_frame\", \"text\", \"video_continuation\"],\n supportsVideoExtension: true,\n maxDurationSeconds: 8,\n prompting_style: \"cinematic_tag_heavy\",\n maxReferenceImages: 1,\n },\n \"seedance-2\": {\n inputModes: [\"first_frame\", \"first_last_frame\", \"ref_images\", \"video_continuation\"],\n supportsVideoExtension: true,\n maxDurationSeconds: 10,\n prompting_style: \"natural_language\",\n // SEEDANCE_2_REF_LIMITS.images is the hard upper bound (9). 1C.1\n // caps to a more conservative 5 to leave headroom for primary\n // character + location + 3 secondary refs.\n maxReferenceImages: 5,\n },\n \"seedance-2-5\": {\n inputModes: [\"first_frame\", \"first_last_frame\", \"ref_images\", \"video_continuation\"],\n supportsVideoExtension: true,\n // 30s single-shot on KIE (probe-verified 2026-08-08: 30 accepted, 31 rejected).\n maxDurationSeconds: 30,\n prompting_style: \"natural_language\",\n // SEEDANCE_2_5_REF_LIMITS.images is the hard upper bound (30); the same\n // conservative headroom rule as seedance-2 applies to what the director\n // actually allocates.\n maxReferenceImages: 5,\n },\n \"hailuo-2.3-pro\": {\n inputModes: [\"first_frame\", \"text\"],\n maxDurationSeconds: 10,\n prompting_style: \"compact\",\n maxReferenceImages: 1,\n },\n \"hailuo-standard\": {\n inputModes: [\"first_frame\", \"first_last_frame\"],\n maxDurationSeconds: 6,\n prompting_style: \"compact\",\n maxReferenceImages: 1,\n },\n \"minimax\": {\n inputModes: [\"first_frame\", \"first_last_frame\"],\n maxDurationSeconds: 6,\n prompting_style: \"compact\",\n maxReferenceImages: 1,\n },\n \"kling-turbo\": {\n inputModes: [\"first_frame\", \"first_last_frame\"],\n maxDurationSeconds: 10,\n prompting_style: \"natural_language\",\n maxReferenceImages: 1,\n },\n \"bytedance-lite\": {\n inputModes: [\"first_frame\", \"first_last_frame\"],\n maxDurationSeconds: 10,\n prompting_style: \"compact\",\n maxReferenceImages: 1,\n },\n // v4.1 Method 8 — Frame interpolation (sparse keyframes → interpolated video).\n // RIFE: Replicate-hosted, optical-flow-based interpolation, up to 8 keyframes.\n \"rife\": {\n inputModes: [\"frame_interpolation\"],\n maxInterpolationKeyframes: 8,\n maxDurationSeconds: 60,\n prompting_style: \"compact\",\n },\n // Topaz Apollo: cloud-hosted (Topaz.ai), higher keyframe budget.\n // Provider routing currently stubs as `provider_not_available:topaz-apollo`\n // pending KIE catalog check — entry kept so Shot List Critic surfaces it.\n \"topaz-apollo\": {\n inputModes: [\"frame_interpolation\"],\n maxInterpolationKeyframes: 16,\n maxDurationSeconds: 60,\n prompting_style: \"compact\",\n },\n // v4.1 Method 10 — Parametric 3D camera path (Stability AI SV3D via Replicate).\n // SV3D takes a single image + a camera path and renders a 3D-orbit video.\n \"stable-video-3d\": {\n inputModes: [\"camera_path\", \"first_frame\"],\n supportsCameraPath: true,\n maxDurationSeconds: 5,\n prompting_style: \"natural_language\",\n maxReferenceImages: 1,\n },\n}\n\n/**\n * modelsForInputMode — filter VIDEO_MODEL_CAPS to models that support the given mode.\n * Used at three call sites: Scene Director prompt construction, route Zod validation,\n * frontend config panel dropdown options.\n */\nexport const modelsForInputMode = (mode: SceneInputMode): string[] =>\n Object.entries(VIDEO_MODEL_CAPS)\n .filter(([, caps]) => caps.inputModes.includes(mode))\n .map(([model]) => model)\n\n/**\n * preferredInputModeForModel — pick the best `shot_input_mode` for a pinned\n * video model so the pipeline adapts its input wiring to the chosen model:\n *\n * - models that accept `ref_images` (Seedance 2, Kling Omni) → `\"ref_images\"`,\n * so the character/location reference portraits feed the video model\n * directly (strongest identity lock).\n * - otherwise models that accept a start frame → `\"first_frame\"`, so the\n * per-scene keyframe is connected as the opening frame.\n *\n * Returns `undefined` for unknown/unregistered models (not in VIDEO_MODEL_CAPS)\n * or models that expose neither mode, so the caller keeps its own default.\n *\n * `first_last_frame` is deliberately NOT auto-selected — the animate stage\n * does not yet implement paired start+end keyframes (Method 2), so a\n * first_last_frame-capable model still resolves to `first_frame` here.\n */\nexport function preferredInputModeForModel(\n model: string | undefined,\n): SceneInputMode | undefined {\n if (!model) return undefined\n const caps = VIDEO_MODEL_CAPS[model]\n if (!caps) return undefined\n if (caps.inputModes.includes(\"ref_images\")) return \"ref_images\"\n if (caps.inputModes.includes(\"first_frame\")) return \"first_frame\"\n return undefined\n}\n\n/* ────────────────────────────────────────────────────────────────────────────\n * Platform default video model (single source of truth)\n *\n * Applied wherever a video request omits `provider`: the generate-video and\n * text-to-video routes (credit resolution + dispatch), the DAG payload\n * builder, and the KIE provider's last-resort fallback. Chosen from usage\n * data (2026-07): most-selected video model with the highest completion rate.\n * ──────────────────────────────────────────────────────────────────────────── */\n\nexport const DEFAULT_VIDEO_PROVIDER = \"seedance-2-fast\"\n\n/**\n * The model a legacy Image to Video / Text to Video node runs when it names\n * none: the workflow run's own default for those two (Generate Video's is\n * {@link DEFAULT_VIDEO_PROVIDER}, through {@link applyDefaultVideoSelection}).\n */\nexport const LEGACY_VIDEO_NODE_DEFAULT_PROVIDER = \"kling\"\n\n/**\n * Duration paired with the default provider when BOTH provider and duration\n * are omitted. Pins the nothing-specified request to the default model's\n * cheapest seeded tier (4s @ 480p — resolution omission already resolves to\n * 480p in buildVideoCreditModelIdentifier), so first-touch cost stays at\n * entry level and longer clips are an explicit choice.\n */\nexport const DEFAULT_VIDEO_DURATION_SEC = 4\n\n/**\n * Resolve the effective (provider, duration) for a video request.\n *\n * - provider omitted → DEFAULT_VIDEO_PROVIDER\n * - duration omitted AND provider was omitted → DEFAULT_VIDEO_DURATION_SEC\n * - an explicitly chosen provider keeps its own duration semantics (an\n * omitted duration falls through to that model's natural default)\n *\n * Used by both single-node routes AND the workflow payload builder so the\n * two execution paths cannot drift (the route/DAG default previously\n * disagreed: \"minimax\" vs \"kling\").\n */\nexport function applyDefaultVideoSelection<D>(input: {\n provider?: string | null\n duration?: D\n}): { provider: string; duration: D | number | undefined } {\n const providerOmitted = input.provider == null || input.provider === \"\"\n return {\n provider: providerOmitted ? DEFAULT_VIDEO_PROVIDER : (input.provider as string),\n duration: input.duration ?? (providerOmitted ? DEFAULT_VIDEO_DURATION_SEC : undefined),\n }\n}\n"]}