@nodaro/shared 3.39.0 → 3.40.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 (132) hide show
  1. package/dist/{chunk-XUISP5BT.cjs → chunk-25PAKSMK.cjs} +41 -38
  2. package/dist/chunk-25PAKSMK.cjs.map +1 -0
  3. package/dist/{chunk-5OED47LE.js → chunk-2BJADMEX.js} +3 -3
  4. package/dist/{chunk-5OED47LE.js.map → chunk-2BJADMEX.js.map} +1 -1
  5. package/dist/{chunk-YNJ44IAL.cjs → chunk-4IWVZR44.cjs} +5 -5
  6. package/dist/{chunk-YNJ44IAL.cjs.map → chunk-4IWVZR44.cjs.map} +1 -1
  7. package/dist/{chunk-33QG2DOW.cjs → chunk-4LKEOIOT.cjs} +6 -6
  8. package/dist/{chunk-33QG2DOW.cjs.map → chunk-4LKEOIOT.cjs.map} +1 -1
  9. package/dist/{chunk-ZG4XSEZV.js → chunk-5CKTBGB6.js} +71 -2
  10. package/dist/chunk-5CKTBGB6.js.map +1 -0
  11. package/dist/{chunk-BDSFMY4X.js → chunk-5J5L26IZ.js} +5 -5
  12. package/dist/{chunk-BDSFMY4X.js.map → chunk-5J5L26IZ.js.map} +1 -1
  13. package/dist/{chunk-VRLRPGO7.js → chunk-A4NDZBSJ.js} +93 -11
  14. package/dist/chunk-A4NDZBSJ.js.map +1 -0
  15. package/dist/{chunk-KOP7UTQR.cjs → chunk-ADYPAGQF.cjs} +71 -2
  16. package/dist/chunk-ADYPAGQF.cjs.map +1 -0
  17. package/dist/{chunk-HABDAHZR.cjs → chunk-BOUEGYGI.cjs} +118 -28
  18. package/dist/chunk-BOUEGYGI.cjs.map +1 -0
  19. package/dist/{chunk-JLKZEKQ3.cjs → chunk-BWQRAQUD.cjs} +43 -43
  20. package/dist/{chunk-JLKZEKQ3.cjs.map → chunk-BWQRAQUD.cjs.map} +1 -1
  21. package/dist/{chunk-MSIIC6MY.cjs → chunk-DJIRIBKX.cjs} +4 -4
  22. package/dist/{chunk-MSIIC6MY.cjs.map → chunk-DJIRIBKX.cjs.map} +1 -1
  23. package/dist/{chunk-XA53RUSD.js → chunk-E4MLBJKG.js} +8 -8
  24. package/dist/{chunk-XA53RUSD.js.map → chunk-E4MLBJKG.js.map} +1 -1
  25. package/dist/chunk-FVZMFDRO.js +23 -0
  26. package/dist/chunk-FVZMFDRO.js.map +1 -0
  27. package/dist/{chunk-DKTRVOU5.js → chunk-GNY2S63W.js} +4 -4
  28. package/dist/{chunk-DKTRVOU5.js.map → chunk-GNY2S63W.js.map} +1 -1
  29. package/dist/{chunk-YHCG3HOR.js → chunk-GXTWKAJF.js} +3 -3
  30. package/dist/{chunk-YHCG3HOR.js.map → chunk-GXTWKAJF.js.map} +1 -1
  31. package/dist/{chunk-DE3PEIIP.cjs → chunk-IKCFSNNH.cjs} +21 -21
  32. package/dist/{chunk-DE3PEIIP.cjs.map → chunk-IKCFSNNH.cjs.map} +1 -1
  33. package/dist/{chunk-BYP62B7F.cjs → chunk-JN3V33AN.cjs} +6 -6
  34. package/dist/{chunk-BYP62B7F.cjs.map → chunk-JN3V33AN.cjs.map} +1 -1
  35. package/dist/{chunk-QXTCIJP5.js → chunk-LOTL72UI.js} +3 -3
  36. package/dist/{chunk-QXTCIJP5.js.map → chunk-LOTL72UI.js.map} +1 -1
  37. package/dist/{chunk-7QITUDRT.js → chunk-MLB6YNLS.js} +4 -4
  38. package/dist/{chunk-7QITUDRT.js.map → chunk-MLB6YNLS.js.map} +1 -1
  39. package/dist/{chunk-JABZNRXL.cjs → chunk-N2KG5AMQ.cjs} +4 -4
  40. package/dist/{chunk-JABZNRXL.cjs.map → chunk-N2KG5AMQ.cjs.map} +1 -1
  41. package/dist/{chunk-KMNSK7T5.js → chunk-NRSYWQKM.js} +7 -4
  42. package/dist/chunk-NRSYWQKM.js.map +1 -0
  43. package/dist/{chunk-IIGKJYWL.js → chunk-PYDZ7ZGH.js} +3 -3
  44. package/dist/{chunk-IIGKJYWL.js.map → chunk-PYDZ7ZGH.js.map} +1 -1
  45. package/dist/{chunk-ENFBA33M.cjs → chunk-RLVZ3RLE.cjs} +8 -8
  46. package/dist/{chunk-ENFBA33M.cjs.map → chunk-RLVZ3RLE.cjs.map} +1 -1
  47. package/dist/{chunk-JMUHMLJP.js → chunk-SYUY7GNT.js} +7 -5
  48. package/dist/chunk-SYUY7GNT.js.map +1 -0
  49. package/dist/{chunk-VRUN5TG2.cjs → chunk-TUUEQ2WR.cjs} +8 -8
  50. package/dist/{chunk-VRUN5TG2.cjs.map → chunk-TUUEQ2WR.cjs.map} +1 -1
  51. package/dist/{chunk-HZ46RDLD.cjs → chunk-VNC5DNIQ.cjs} +11 -11
  52. package/dist/{chunk-HZ46RDLD.cjs.map → chunk-VNC5DNIQ.cjs.map} +1 -1
  53. package/dist/{chunk-MSDECC3A.cjs → chunk-VSDJCJKP.cjs} +44 -42
  54. package/dist/chunk-VSDJCJKP.cjs.map +1 -0
  55. package/dist/{chunk-GW54ANCH.js → chunk-X7IRSO4L.js} +3 -3
  56. package/dist/{chunk-GW54ANCH.js.map → chunk-X7IRSO4L.js.map} +1 -1
  57. package/dist/chunk-XOZIHGR5.cjs +27 -0
  58. package/dist/chunk-XOZIHGR5.cjs.map +1 -0
  59. package/dist/{chunk-YSEM7JDE.cjs → chunk-YEET2QGF.cjs} +4 -4
  60. package/dist/{chunk-YSEM7JDE.cjs.map → chunk-YEET2QGF.cjs.map} +1 -1
  61. package/dist/{chunk-CMH2ACOX.js → chunk-YEZ2YUKK.js} +3 -3
  62. package/dist/{chunk-CMH2ACOX.js.map → chunk-YEZ2YUKK.js.map} +1 -1
  63. package/dist/{chunk-SPP6HQMM.js → chunk-YX5FW7ON.js} +39 -5
  64. package/dist/chunk-YX5FW7ON.js.map +1 -0
  65. package/dist/{chunk-75ZMA34U.cjs → chunk-ZAOBNW6Y.cjs} +47 -11
  66. package/dist/chunk-ZAOBNW6Y.cjs.map +1 -0
  67. package/dist/{chunk-AZBIXGM5.js → chunk-ZXIP5T5V.js} +3 -3
  68. package/dist/{chunk-AZBIXGM5.js.map → chunk-ZXIP5T5V.js.map} +1 -1
  69. package/dist/entries/apps.cjs +42 -42
  70. package/dist/entries/apps.js +7 -7
  71. package/dist/entries/credits.cjs +150 -150
  72. package/dist/entries/credits.d.cts +1 -1
  73. package/dist/entries/credits.d.ts +1 -1
  74. package/dist/entries/credits.js +7 -7
  75. package/dist/entries/llm-models.d.cts +1 -1
  76. package/dist/entries/llm-models.d.ts +1 -1
  77. package/dist/entries/model-catalog.cjs +66 -66
  78. package/dist/entries/model-catalog.d.cts +2 -2
  79. package/dist/entries/model-catalog.d.ts +2 -2
  80. package/dist/entries/model-catalog.js +4 -4
  81. package/dist/entries/models.cjs +261 -229
  82. package/dist/entries/models.d.cts +3 -3
  83. package/dist/entries/models.d.ts +3 -3
  84. package/dist/entries/models.js +4 -4
  85. package/dist/entries/nodes.cjs +206 -206
  86. package/dist/entries/nodes.d.cts +1 -1
  87. package/dist/entries/nodes.d.ts +1 -1
  88. package/dist/entries/nodes.js +8 -8
  89. package/dist/entries/pipeline.cjs +149 -149
  90. package/dist/entries/pipeline.d.cts +1 -1
  91. package/dist/entries/pipeline.d.ts +1 -1
  92. package/dist/entries/pipeline.js +3 -3
  93. package/dist/entries/ugc.cjs +71 -71
  94. package/dist/entries/ugc.js +4 -4
  95. package/dist/entries/video.cjs +123 -115
  96. package/dist/entries/video.d.cts +26 -1
  97. package/dist/entries/video.d.ts +26 -1
  98. package/dist/entries/video.js +4 -4
  99. package/dist/index.cjs +1044 -1004
  100. package/dist/index.d.cts +3 -3
  101. package/dist/index.d.ts +3 -3
  102. package/dist/index.js +17 -17
  103. package/dist/{model-catalog-I48SvalA.d.ts → model-catalog-dQPdLltX.d.cts} +11 -0
  104. package/dist/{model-catalog-I48SvalA.d.cts → model-catalog-dQPdLltX.d.ts} +11 -0
  105. package/dist/{model-constants-C43YS07I.d.ts → model-constants-B5ka4TQr.d.cts} +61 -6
  106. package/dist/{model-constants-C43YS07I.d.cts → model-constants-B5ka4TQr.d.ts} +61 -6
  107. package/package.json +1 -1
  108. package/src/__tests__/gvp-supported-providers.test.ts +8 -1
  109. package/src/__tests__/kling4-catalog.test.ts +129 -0
  110. package/src/__tests__/video-character-refs.test.ts +3 -2
  111. package/src/credit-identifiers.ts +6 -0
  112. package/src/entries/models.ts +8 -0
  113. package/src/entries/video.ts +2 -0
  114. package/src/model-catalog.ts +82 -0
  115. package/src/model-constants.ts +151 -3
  116. package/src/node-default-mappings.ts +3 -0
  117. package/src/video-character-refs.ts +67 -0
  118. package/src/video-ui-defaults.ts +8 -5
  119. package/dist/chunk-75ZMA34U.cjs.map +0 -1
  120. package/dist/chunk-HABDAHZR.cjs.map +0 -1
  121. package/dist/chunk-JMUHMLJP.js.map +0 -1
  122. package/dist/chunk-KMNSK7T5.js.map +0 -1
  123. package/dist/chunk-KOP7UTQR.cjs.map +0 -1
  124. package/dist/chunk-MSDECC3A.cjs.map +0 -1
  125. package/dist/chunk-SPP6HQMM.js.map +0 -1
  126. package/dist/chunk-VRLRPGO7.js.map +0 -1
  127. package/dist/chunk-W4GABGRD.js +0 -21
  128. package/dist/chunk-W4GABGRD.js.map +0 -1
  129. package/dist/chunk-XJ3HJSO5.cjs +0 -25
  130. package/dist/chunk-XJ3HJSO5.cjs.map +0 -1
  131. package/dist/chunk-XUISP5BT.cjs.map +0 -1
  132. package/dist/chunk-ZG4XSEZV.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/credit-identifiers.ts"],"names":["FLUX2_RES_MP","defaultResolutionFor","isFlux2Model","HIGH_QUALITY_PROVIDERS","TWO_K_RESOLUTION_PROVIDERS","RESOLUTION_2K_4K_TIERED_PROVIDERS","IDEOGRAM_PROVIDERS","T2I_TO_I2I_VARIANT","autoAspectNeedsSourceImage","normalizeModelInput","snapToNearestDuration","pricedOutputDurationSec","isWan3Provider","normalizeWan3Resolution","isViduQ4Provider","normalizeViduQ4Resolution","DURATION_PRICED_PROVIDERS","isVeoProvider","VEO_RESOLUTION_TIERED_PROVIDERS","isGeminiOmniProvider","VIDEO_DURATION_TIERS","getVideoAudioCapability","AUDIO_ADDON_PROVIDERS","MODE_ADDON_PROVIDERS","RESOLUTION_VIDEO_REF_PRICING","MODEL_CATALOG","PRICING_DEFAULT_RESOLUTION","RESOLUTION_DURATION_PRICING","isMinimaxH3Provider","normalizeMinimaxH3Resolution","normalizeVideoRequestParams","uiResolutionFill","VIDEO_DURATION_AUTO","MOTION_DURATION_TIERS"],"mappings":";;;;;;;AA8DA,SAAS,kBAAA,CAAmB,OAAmB,UAAA,EAA6B;AAC1E,EAAA,MAAM,IAAA,GAAO,CAAC,CAAA,KAAc,CAAA,CAAE,QAAQ,SAAA,EAAW,EAAE,EAAE,IAAA,EAAK;AAC1D,EAAA,MAAM,MAAM,OAAO,UAAA,KAAe,QAAA,GAAW,IAAA,CAAK,UAAU,CAAA,GAAI,EAAA;AAChE,EAAA,IAAI,GAAA,KAAQ,IAAI,OAAO,GAAA;AAIvB,EAAA,MAAM,IAAA,GAAOA,8BAAA,CAAa,IAAA,CAAK,CAAC,CAAA,KAAM,OAAO,CAAC,CAAA,KAAM,MAAA,CAAO,GAAG,CAAC,CAAA;AAC/D,EAAA,OAAO,IAAA,IAAQ,IAAA,CAAKC,sCAAA,CAAqB,KAAK,KAAK,MAAM,CAAA;AAC3D;AAWO,SAAS,2BACd,QAAA,EACA,OAAA,EACA,UAAA,EACA,cAAA,EACA,kBACA,mBAAA,EACQ;AAOR,EAAA,IAAIC,8BAAA,CAAa,QAAQ,CAAA,EAAG;AAC1B,IAAA,OAAO,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,kBAAA,CAAmB,QAAA,EAAU,UAAU,CAAC,CAAA,GAAA,EAAM,IAAA,CAAK,GAAA,CAAI,mBAAA,IAAuB,CAAA,EAAG,CAAC,CAAC,CAAA,GAAA,CAAA;AAAA,EAC3G;AACA,EAAA,IAAIC,wCAAA,CAAuB,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AoB,WAAA;AACnD;AASO,IAAM,wBAAA,GAA2B,CAAC,UAAA,EAAY,SAAS;AAMvD,IAAM,uBAAA,GAA0D,OAAO,MAAA,CAAO;AAAA,EACnF,cAAA;AAAA,EACA,oBAAA;AAAA,EACA,sBAAA;AAAA,EACA;AACF,CAAU;AAYH,SAAS,mBAAA,CAAoB,SAAkB,IAAA,EAAqC;AACzF,EAAA,MAAM,QAAQ,OAAA,KAAY,OAAA;AAC1B,EAAA,IAAI,IAAA,KAAS,UAAA,EAAY,OAAO,KAAA,GAAQ,oBAAA,GAAuB,cAAA;AAC/D,EAAA,OAAO,QAAQ,4BAAA,GAA+B,sBAAA;AAChD;AAkBO,SAAS,cAAA,CAAe,OAA2B,SAAA,EAA2B;AACnF,EAAA,IAAI,CAAE,8BAAA,CAAqD,QAAA,CAAS,SAAS,CAAA,EAAG;AAC9E,IAAA,OAAO,SAAA;AAAA,EACT;AACA,EAAA,OAAQ,KAAA,IAAS,wBAAA,CAAyB,KAAK,CAAA,IAAM,SAAA;AACvD;AAUO,IAAM,wBAAA,GAA6D;AAAA,EACxE,EAAA,EAAI,SAAA;AAAA,EACJ,OAAA,EAAS,cAAA;AAAA,EACT,OAAA,EAAS,cAAA;AAAA,EACT,IAAA,EAAM,WAAA;AAAA,EACN,EAAA,EAAI;AACN","file":"chunk-MSDECC3A.cjs","sourcesContent":["/**\n * Build composite credit model identifiers for variable pricing.\n * Shared between frontend and backend.\n */\n\nimport {\n HIGH_QUALITY_PROVIDERS,\n TWO_K_RESOLUTION_PROVIDERS,\n RESOLUTION_2K_4K_TIERED_PROVIDERS,\n IDEOGRAM_PROVIDERS,\n DURATION_PRICED_PROVIDERS,\n AUDIO_ADDON_PROVIDERS,\n MODE_ADDON_PROVIDERS,\n RESOLUTION_VIDEO_REF_PRICING,\n RESOLUTION_DURATION_PRICING,\n VEO_RESOLUTION_TIERED_PROVIDERS,\n VIDEO_DURATION_TIERS,\n pricedOutputDurationSec,\n snapToNearestDuration,\n PRICING_DEFAULT_RESOLUTION,\n MOTION_DURATION_TIERS,\n T2I_TO_I2I_VARIANT,\n isVeoProvider,\n isMinimaxH3Provider,\n isGeminiOmniProvider,\n isWan3Provider,\n isViduQ4Provider,\n normalizeMinimaxH3Resolution,\n normalizeWan3Resolution,\n normalizeViduQ4Resolution,\n getVideoAudioCapability,\n} from \"./model-constants.js\"\nimport { isFlux2Model, FLUX2_RES_MP, type Flux2Model } from \"./flux2-pricing.js\"\nimport { VIDEO_DURATION_AUTO } from \"./video-duration-auto.js\"\nimport { uiResolutionFill } from \"./video-ui-defaults.js\"\nimport { MODEL_CATALOG, autoAspectNeedsSourceImage, normalizeModelInput, normalizeVideoRequestParams, defaultResolutionFor, type ModelInputAdjustment, type SourceImageSize } from \"./model-catalog.js\"\n\n/**\n * The megapixel tier a Flux 2 credit identifier is keyed on, for ANY incoming\n * `resolution` value.\n *\n * Flux 2 is the only family whose identifier INTERPOLATES the resolution\n * instead of matching it against a known set, and its callers are not\n * guaranteed to hand it a Flux 2 value:\n * - the multi-provider cost preview prices one node's data against EVERY\n * selected provider (`frontend/src/ee/hooks/use-providers-credits-sum.ts`),\n * so a node whose `resolution` is \"2K\" (the flux / nano-banana-pro value\n * space) reaches this branch verbatim;\n * - node data written straight into workflow JSON by an agent, an import or\n * a template never ran the config panel's provider-change fail-safe.\n * Interpolating that produced the off-grid id `flux-2-pro:2KMP:0ref`, which no\n * pricing row can answer — every cost badge 503'd `price_not_configured`\n * (18 production app-reports, 2026-09-07..14).\n *\n * A value off the grid snaps to the model's DEFAULT tier — the same `preferred`\n * value `normalizeModelInput` uses — so the preview asks for exactly the id the\n * route will reserve (both routes and the orchestrator normalize through\n * `resolveNormalizedImageGen` first, which makes this snap a no-op for them).\n * An ABSENT resolution keeps its long-standing meaning (\"this caller has no\n * resolution dimension at all\") and stays on 1 MP rather than moving to the\n * model default, which would silently re-price every resolution-less node.\n */\nfunction flux2MegapixelTier(model: Flux2Model, resolution?: string): string {\n const bare = (v: string) => v.replace(/\\s*MP$/i, \"\").trim()\n const raw = typeof resolution === \"string\" ? bare(resolution) : \"\"\n if (raw === \"\") return \"1\"\n // Numeric match so \"2.0\"/\" 2 MP\" land on the same grid point as \"2\", and the\n // GRID's own spelling is what gets emitted — returning the caller's \"2.0\"\n // would build \":2.0MP:\", another id no pricing row carries.\n const tier = FLUX2_RES_MP.find((t) => Number(t) === Number(raw))\n return tier ?? bare(defaultResolutionFor(model) ?? \"1 MP\")\n}\n\n/**\n * Compute composite model identifier for variable credit pricing.\n * Examples: \"gpt-image:high\", \"flux:2K\", \"nano-banana-pro:4K\", \"ideogram:TURBO\",\n * \"flux-2-pro:2MP\", \"flux-2-max:2MP:1ref\" (Flux 2 — billed per megapixel).\n *\n * For image models, uses quality/resolution/renderingSpeed and (Flux 2) the output\n * megapixel count plus (Flux 2 Max) the number of reference images attached at request time.\n * For video models, uses duration/sound params when the model has variable pricing.\n */\nexport function buildCreditModelIdentifier(\n provider: string,\n quality?: string,\n resolution?: string,\n renderingSpeed?: string,\n targetResolution?: string,\n referenceImageCount?: number,\n): string {\n // Flux 2 family: billed per output megapixel AND per reference image (each\n // ref counts as input megapixels). Resolution arrives as \"N MP\" strings (the\n // UI value space); strip the unit. ALL three models encode the ref count\n // (capped at 8): Pro/Klein i2i always carry the source image as a ref and\n // their cost formula charges per input MP, so the reserved identifier must\n // reflect refs (there is no metered true-up to correct an under-reserved tier).\n if (isFlux2Model(provider)) {\n return `${provider}:${flux2MegapixelTier(provider, resolution)}MP:${Math.min(referenceImageCount ?? 0, 8)}ref`\n }\n if (HIGH_QUALITY_PROVIDERS.has(provider) && quality === \"high\") {\n return `${provider}:high`\n }\n if (TWO_K_RESOLUTION_PROVIDERS.has(provider) && resolution === \"2K\") {\n return `${provider}:2K`\n }\n if (provider === \"nano-banana-pro\" && resolution === \"4K\") {\n return `${provider}:4K`\n }\n if (RESOLUTION_2K_4K_TIERED_PROVIDERS.has(provider) && (resolution === \"2K\" || resolution === \"4K\")) {\n return `${provider}:${resolution}`\n }\n // Topaz Image Upscale: 2K is default (no suffix), 4K/8K get composite identifiers\n if (provider === \"topaz-image-upscale\" && targetResolution && targetResolution !== \"2K\") {\n return `${provider}:${targetResolution}`\n }\n if (IDEOGRAM_PROVIDERS.has(provider)) {\n if (renderingSpeed === \"TURBO\") return `${provider}:TURBO`\n if (renderingSpeed === \"QUALITY\") return `${provider}:QUALITY`\n }\n return provider\n}\n\n/**\n * An image request's catalog-snapped parameters PLUS the credit identifier\n * priced off them.\n *\n * `adjustments` is the disclosure channel: every lever this changed, why, and\n * to what. Routes return it in the 200 body so a caller learns their value was\n * corrected instead of silently getting something else.\n */\nexport interface NormalizedImageGen {\n /** Credit identifier, priced off the SNAPPED `resolution` / `quality`. */\n identifier: string\n /** The catalog model id the params were snapped against (post T2I→I2I swap). */\n modelId: string\n aspectRatio?: string\n resolution?: string\n quality?: string\n /** Empty when the caller's values were already valid for `modelId`. */\n adjustments: ModelInputAdjustment[]\n}\n\n/**\n * The catalog model `resolveNormalizedImageGen` snaps against: the provider\n * (Nano Banana when none is named), or — with `swapToI2i` and references\n * attached — its i2i sibling, the model the generate-image route and the\n * workflow payload builder then send. That sibling has its OWN catalog entry\n * and lever lists. Exported so a caller that has to decide something about\n * those lists before the snap (whether a photo's size is worth reading) asks\n * about the same model the snap will use.\n */\nexport function normalizedImageGenModelId(opts: {\n provider: unknown\n refCount: number\n swapToI2i?: boolean\n}): string {\n const provider = typeof opts.provider === \"string\" && opts.provider.length > 0 ? opts.provider : \"nano-banana\"\n return opts.swapToI2i && opts.refCount > 0 ? (T2I_TO_I2I_VARIANT[provider] ?? provider) : provider\n}\n\n/**\n * Whether \"auto\" on a Generate Image request can need its photo's size: the\n * model the snap runs against (`normalizedImageGenModelId` with the swap on)\n * has no native auto. Given the ASSEMBLED reference count, it asks about exactly\n * that model; without one — a write boundary, or a run before its references\n * assemble — about both the provider and its i2i sibling, since references may\n * yet attach.\n */\nexport function imageGenAutoAspectNeedsSourceImage(opts: {\n provider: unknown\n aspectRatio: unknown\n refCount?: number\n}): boolean {\n const asks = (refCount: number) =>\n autoAspectNeedsSourceImage(normalizedImageGenModelId({ provider: opts.provider, refCount, swapToI2i: true }), opts.aspectRatio)\n return opts.refCount === undefined ? asks(0) || asks(1) : asks(opts.refCount)\n}\n\n/**\n * Snap an image request's catalog-governed levers to a combination the model\n * actually accepts, and price the credit identifier off the SNAPPED values.\n *\n * WHY THE SNAP LIVES HERE and not at the call site. Both image routes compute\n * their credit identifier TWICE — once in the `creditGuard` preHandler (the\n * CHECK) and once at the handler's `reserveCreditsForJob` (the DEBIT) — and a\n * dedicated test asserts the two stay byte-identical (see\n * `backend/src/routes/__tests__/generate-image.test.ts`, \"CHECK === DEBIT\").\n * `resolution` and `quality` are pricing dimensions, so a snap applied at only\n * one of those sites breaks that invariant, and `commit_credits` never collects\n * an upward delta — the reserve IS the charge. Putting the snap inside the\n * primitive makes CHECK, DEBIT and the workflow orchestrator agree by\n * construction rather than by everyone remembering to call a normalizer.\n *\n * Inputs are typed `unknown` on purpose: the preHandler runs BEFORE Zod, so a\n * caller can put a number or an object in `resolution`. Non-strings become\n * `undefined` rather than reaching `normalizeModelInput` as a lie.\n *\n * Unknown model ids pass through untouched (same contract as\n * `normalizeModelInput`) — the route's provider enum is the gate for those.\n *\n * `sourceImage` is the size of the photo the request transforms or is drawn\n * from (an image-to-image / edit source, or Generate Image's first wired\n * reference). It only decides \"auto\" on a model without a native auto, and the\n * ratio is not a pricing dimension on any such model (pinned across the catalog\n * by `auto-aspect-source.test.ts`), so a CHECK that runs before the size is\n * known prices the same identifier as the DEBIT that knows it.\n */\nexport function resolveNormalizedImageGen(opts: {\n provider: string | undefined\n aspectRatio?: unknown\n quality?: unknown\n resolution?: unknown\n renderingSpeed?: unknown\n refCount: number\n swapToI2i?: boolean\n sourceImage?: SourceImageSize\n}): NormalizedImageGen {\n const str = (v: unknown): string | undefined =>\n typeof v === \"string\" && v.length > 0 ? v : undefined\n\n const modelId = normalizedImageGenModelId(opts)\n\n const n = normalizeModelInput(\n modelId,\n {\n aspectRatio: str(opts.aspectRatio),\n resolution: str(opts.resolution),\n quality: str(opts.quality),\n },\n { sourceImage: opts.sourceImage },\n )\n\n return {\n identifier: buildCreditModelIdentifier(\n modelId,\n n.quality,\n n.resolution,\n str(opts.renderingSpeed),\n undefined,\n opts.refCount,\n ),\n modelId,\n aspectRatio: n.aspectRatio,\n resolution: n.resolution,\n quality: n.quality,\n adjustments: n.adjustments,\n }\n}\n\n/**\n * Reference-aware image-generation credit identifier — the SINGLE source of\n * truth shared by the single-node routes (`/v1/generate-image`,\n * `/v1/image-to-image`) and the workflow orchestrator\n * (`payload-builder.ts`). It centralises the two pricing dimensions that must\n * match across both paths or a Flux 2 generation is billed the wrong tier\n * (Flux 2 commits non-metered / has no upward true-up, so the reserved\n * identifier IS the final charge):\n * - `refCount`: the number of reference images sent to the provider (Flux 2\n * bills per ref). generate-image passes the assembled count (0 for pure\n * text-to-image); image-to-image passes 1 (the primary `imageUrl`) + extras.\n * - `swapToI2i`: generate-image auto-swaps a bare T2I provider to its i2i\n * sibling (`T2I_TO_I2I_VARIANT`) when refs are attached, so the credit id\n * matches the variant actually invoked. image-to-image is already an i2i\n * provider → pass `false`.\n *\n * The LoRA short-circuit (`flux-lora-character`) stays at the call site because\n * the routing decision needs a DB lookup the routes/orchestrator own.\n */\nexport function resolveImageGenCreditIdentifier(opts: {\n provider: string | undefined\n quality?: string\n resolution?: string\n renderingSpeed?: string\n refCount: number\n swapToI2i?: boolean\n}): string {\n return resolveNormalizedImageGen(opts).identifier\n}\n\n// T2V-specific credit overrides: some providers have different costs for T2V\n// vs I2V/V2V due to different default resolutions or colliding with image model names.\nconst T2V_CREDIT_OVERRIDES: Record<string, string> = {\n \"grok\": \"grok-i2v\", // T2V grok, same as I2V grok (not image grok = 4 cr)\n \"wan\": \"wan-t2v\", // T2V wan 1080p = (V2V wan 720p = 70 cr)\n \"wan-turbo\": \"wan-turbo-t2v\", // T2V wan-turbo 720p = (I2V wan-turbo 480p = 40 cr)\n}\n\n/**\n * Compute composite model identifier for video models with duration/audio-based pricing.\n * Examples: \"kling-3.0:5s\", \"kling-3.0:10s:audio\", \"seedance-2:8s:720p-ref\"\n *\n * @param provider - Video model key (e.g., \"kling-3.0\")\n * @param duration - Video duration in seconds\n * @param sound - Whether audio/sound is enabled\n * @param nodeType - Node type for T2V-specific cost overrides\n * @param mode - Quality variant that affects pricing\n * @param resolution - Output resolution (used by Seedance 2 for 480p/720p pricing)\n * @param hasVideoRef - Whether a reference video is connected (Seedance 2 uses a lower per-second rate when true)\n */\n/**\n * LTX 2.3 (Lightricks via Replicate) credit tiers: priced by\n * (resolution-band × duration-seconds). Keys mirror STATIC_CREDIT_COSTS /\n * model_pricing EXACTLY (lowercase band + raw seconds + \"s\"), e.g.\n * \"ltx-2.3-pro:1080p:6s\". This map is the source of truth for the nearest-tier\n * snap below, so an off-catalog (resolution, duration) from a direct API/SDK\n * call maps to a SEEDED price instead of hard-failing (price_not_configured\n * 503). Pro: 6/8/10s at every band. Fast: up to 20s at 1080p, 6/8/10s at 2k/4k.\n */\nconst LTX_DURATION_TIERS: Record<string, Record<string, number[]>> = {\n \"ltx-2.3-pro\": { \"1080p\": [6, 8, 10], \"2k\": [6, 8, 10], \"4k\": [6, 8, 10] },\n \"ltx-2.3-fast\": { \"1080p\": [6, 8, 10, 12, 14, 16, 18, 20], \"2k\": [6, 8, 10], \"4k\": [6, 8, 10] },\n}\n\n/**\n * The (band, duration) tier the LTX pricing ladder charges for a request, or\n * `undefined` for a non-LTX provider. Extracted so\n * `buildVideoCreditModelIdentifier` and `pricedVideoSelection` read the ladder\n * ONCE — the routes must send the tier they reserved, and a second copy of this\n * math is exactly how the two drift apart.\n *\n * An unknown/absent band falls back to 1080p (LTX's own default, and the band\n * `snapLtxInput` snaps to at the Replicate call), and an off-tier duration\n * snaps to the NEAREST seeded one so the emitted composite always prices.\n */\nfunction ltxPricedTier(\n provider: string,\n resolution?: string,\n duration?: number | string,\n): { band: string; duration: number } | undefined {\n const bands = LTX_DURATION_TIERS[provider]\n if (!bands) return undefined\n const band = bands[String(resolution)] ? String(resolution) : \"1080p\"\n const allowed = bands[band]!\n // The model's own default (catalog `defaultDuration`) when unset, then the\n // nearest rung of THIS band's ladder — the length LTX renders.\n const dur = snapToNearestDuration(pricedOutputDurationSec(provider, duration), allowed)\n return { band, duration: dur }\n}\n\n/**\n * The resolution a provider whose runner NORMALIZES the lever actually renders,\n * in the lowercase spelling of its credit composites — billing collapses\n * through the very normalizer the runner sends, so render == billed for every\n * spelling. `undefined` passes through untouched for every other provider.\n */\nfunction wireNormalizedResolution(provider: string, resolution: string | undefined): string | undefined {\n if (isWan3Provider(provider)) return normalizeWan3Resolution(resolution).toLowerCase()\n if (isViduQ4Provider(provider)) return normalizeViduQ4Resolution(resolution)\n return resolution\n}\n\nexport function buildVideoCreditModelIdentifier(\n provider: string,\n duration?: number | string,\n sound?: boolean,\n nodeType?: \"image-to-video\" | \"text-to-video\",\n mode?: string,\n resolution?: string,\n hasVideoRef?: boolean,\n): string {\n // T2V overrides: some providers have different base costs for text-to-video\n let effectiveProvider = provider\n if (nodeType === \"text-to-video\") {\n const override = T2V_CREDIT_OVERRIDES[provider]\n if (override) {\n // If override target also has duration pricing, use it as effective provider\n if (DURATION_PRICED_PROVIDERS.has(override)) {\n effectiveProvider = override\n } else {\n return override\n }\n }\n }\n\n // VEO 3.x resolution-tiered pricing: 720p is the base (no suffix), 1080p gets\n // \":1080p\" (Fast/Lite only), and 4K gets \":4k\" for ALL three tiers — direct-4K\n // generation chains KIE's get-4k-video off the base generation (the base runs\n // at 1080p). Duration is fixed at 8s for VEO so the duration-tier path below\n // does not apply.\n if (isVeoProvider(effectiveProvider)) {\n if (resolution === \"4k\") return `${effectiveProvider}:4k`\n // 1080p tier is Fast/Lite only (Quality has no 1080p surcharge).\n if (resolution === \"1080p\" && VEO_RESOLUTION_TIERED_PROVIDERS.has(effectiveProvider)) return `${effectiveProvider}:1080p`\n return effectiveProvider\n }\n\n // Gemini Omni family (gemini-omni-video + gemini-omni-flash): priced by\n // (resolution-band × duration), with a flat per-generation rate when a source\n // video is supplied (V2V). Lowercase \"4k\". The prefix is TEMPLATED from the\n // provider id, so a further Omni SKU needs no edit here — it only has to join\n // GEMINI_OMNI_PROVIDERS and seed its rows. These models are deliberately NOT\n // in DURATION_PRICED_PROVIDERS; this branch early-returns before that gate.\n if (isGeminiOmniProvider(effectiveProvider)) {\n if (hasVideoRef) {\n return resolution === \"4k\" ? `${effectiveProvider}:4k:vref` : `${effectiveProvider}:vref`\n }\n // The rendered length through the catalog funnel (nearest legal tier, the\n // model's own default when unset) so the composite is always a SEEDED one.\n const d = pricedOutputDurationSec(effectiveProvider, duration)\n return resolution === \"4k\" ? `${effectiveProvider}:4k:${d}` : `${effectiveProvider}:${d}`\n }\n\n // LTX 2.3: priced by (resolution-band × duration-seconds). The RESERVE must be\n // the correct composite — commit_credits (migration 176) only refunds a surplus\n // (actual < reserved) and NEVER collects an upward delta, so an under-reserved\n // LTX run (the bare-id default = cheapest 1080p:6s tier) stays under-charged\n // even with meteredCost:true. Snap to a seeded tier so the id always prices.\n const ltxTier = ltxPricedTier(effectiveProvider, resolution, duration)\n if (ltxTier) {\n return `${effectiveProvider}:${ltxTier.band}:${ltxTier.duration}s`\n }\n\n if (!DURATION_PRICED_PROVIDERS.has(effectiveProvider)) {\n return effectiveProvider\n }\n\n // A named-provider request with NO duration renders the model's own default\n // (kie/models.ts extraParams), so price that default — not the global 5s —\n // for providers whose per-second tiers wouldn't snap 5 up to it\n // (minimax-h3, seedance-2-5). One helper, shared with the dynamic\n // reference-video reservations, so the tier and the scaled reserve agree.\n const durationSec = pricedOutputDurationSec(effectiveProvider, duration)\n const tiers = VIDEO_DURATION_TIERS[effectiveProvider]\n if (!tiers) return effectiveProvider\n\n // Find the matching duration tier\n const tier = tiers.find(t => durationSec <= t.maxSeconds) ?? tiers[tiers.length - 1]\n let identifier = `${effectiveProvider}:${tier.suffix}`\n\n // Append audio suffix if applicable. When the caller expressed no intent\n // (sound === undefined), fall back to the model's own default (capability\n // `defaultOn` — kling-3.0 generates audio unless explicitly disabled), so an\n // intent-less request is billed for the audio it actually produces instead\n // of reserving the cheaper no-audio tier against an audio-on generation.\n const soundOn = sound ?? (getVideoAudioCapability(effectiveProvider).defaultOn === true)\n if (AUDIO_ADDON_PROVIDERS.has(effectiveProvider) && soundOn) {\n identifier += \":audio\"\n }\n\n // Append mode suffix for providers with quality-tiered pricing\n // \"high\" comes from I2V videoSize field, \"pro\" comes from T2V mode field\n if (MODE_ADDON_PROVIDERS.has(effectiveProvider) && (mode === \"high\" || mode === \"pro\")) {\n identifier += \":high\"\n }\n\n // Seedance 2.0 family: per-second billing with resolution + video-ref dimensions.\n // KIE accepts 480p / 720p / 1080p natively; per-second rates rise non-linearly\n // so each tier gets its own composite identifier.\n if (RESOLUTION_VIDEO_REF_PRICING.has(effectiveProvider)) {\n // Clamp to the model's catalog resolutions (single source of truth): e.g.\n // seedance-2-mini exposes only 480p/720p, so a stale/explicit 1080p (or 4k)\n // maps to its top priced tier instead of emitting an unpriced composite\n // (which the hard-fail credit guard would 503 on at runtime).\n const supported = MODEL_CATALOG[effectiveProvider]?.resolutions ?? [\"480p\", \"720p\", \"1080p\"]\n // An OMITTED resolution renders the model's KIE-side default, so price that\n // default rather than the cheapest tier — otherwise an intent-less request\n // reserves 480p against a 720p render and commit_credits (refund-only) can\n // never collect the delta. Providers without an entry keep the historical\n // 480p fallback, so this cannot reprice anything already live.\n const requested = resolution ?? PRICING_DEFAULT_RESOLUTION[effectiveProvider]\n const want = requested === \"4k\" ? \"4k\" : requested === \"1080p\" ? \"1080p\" : requested === \"720p\" ? \"720p\" : \"480p\"\n // Unsupported (e.g. a stale 1080p on seedance-2-mini) clamps to the model's\n // top priced tier so the emitted composite is always seeded.\n const res = supported.includes(want) ? want : (supported[supported.length - 1] ?? \"480p\")\n identifier += `:${res}`\n if (hasVideoRef) identifier += \"-ref\"\n }\n\n // Duration × resolution pricing without a -ref dimension. Resolutions\n // outside the provider's priced tiers (or undefined) collapse to the first\n // (default) tier so the emitted composite is always seeded — the hard-fail\n // guard fuzzes the whole resolution space.\n const resTiers = RESOLUTION_DURATION_PRICING[effectiveProvider]\n if (resTiers) {\n // The \"default tier\" is the provider's DECLARED default when it has one\n // (PRICING_DEFAULT_RESOLUTION — wan-3 renders 720p, not the cheapest tier),\n // otherwise the first listed tier. Declaring it explicitly means a cosmetic\n // reorder of the tier list can never reprice a live model, and an OMITTED\n // *or* unsupported resolution both land on what actually renders instead of\n // on the cheapest row (commit_credits refunds a surplus but can never\n // collect a shortfall). Behaviour-neutral for every member without a\n // declared default.\n const declaredDefault = PRICING_DEFAULT_RESOLUTION[effectiveProvider]\n const fallback = declaredDefault && resTiers.includes(declaredDefault) ? declaredDefault : resTiers[0]!\n // Wan 3.0 renders through `normalizeWan3Resolution`, which is CASE-INSENSITIVE\n // (\"1080P\" — KIE's own OpenAPI enum spelling, and the natural value for an\n // integrator reading the provider docs — renders 1080P). The tier list here is\n // lowercase and `Array.includes` is case-sensitive, so without this the render\n // path and the billing path disagree: \"1080P\" rendered the top tier and billed\n // the 720p row, a shortfall `commit_credits` (refund-only) can never collect.\n // Collapsing through the SAME normalizer the runner uses makes render == billed\n // by construction for every spelling, including garbage (→ the declared 720p).\n // Scoped to the families whose runner normalizes on purpose (Wan 3.0, Vidu\n // Q4): the other RESOLUTION_DURATION_PRICING members pass `resolution` to\n // their wire verbatim, so case-folding their billing without probing their\n // wire would reprice live models.\n const requested = wireNormalizedResolution(effectiveProvider, resolution)\n const res = requested && resTiers.includes(requested) ? requested : fallback\n identifier += `:${res}`\n }\n\n // MiniMax Hailuo 3 (768P lever, 2026-08-03): bare duration composites stay\n // the 2K (default) rate — byte-identical to the pre-lever seeded rows, so\n // existing workflows and admin overrides keep their ids — and only a\n // verified 768P selection appends \":768p\". normalizeMinimaxH3Resolution\n // collapses anything else to 2K, matching what KIE renders for an\n // omitted/unknown value, so billing can never undercut the render.\n if (isMinimaxH3Provider(effectiveProvider) && normalizeMinimaxH3Resolution(resolution) === \"768P\") {\n identifier += \":768p\"\n }\n\n return identifier\n}\n\n/**\n * The credit identifier a video GENERATION node is quoted at — Generate Video\n * (and the legacy Image/Text to Video nodes) and the Video to Video Seedance\n * edit lane, on every surface that quotes one: the node's cost pill, the\n * editor's run estimate, the prompt modal and the backend pre-run estimator.\n *\n * It applies the request levers the run applies BEFORE it prices\n * (payload-builder's `resolveVideoRequestNorm`): the model's UI resolution fill\n * when the node names none (`uiResolutionFill` — what the run sends), then the\n * catalog normalizer `normalizeVideoRequestParams`, which also owns the Seedance\n * Draft rule (a draft is priced AND sent at 480p whatever resolution came with\n * it). Without that, a node with no resolution was quoted at the identifier's\n * own default band (720p on Seedance 2.5) while the run sent and reserved 480p.\n *\n * `hasVideoRef` must come from the GRAPH (a wired reference-video edge, e.g.\n * `countRefModalityEdges(edges, id, \"video\") > 0`), never node data: nothing\n * writes `referenceVideoUrls` into a video node, so reading it there always\n * quoted the plain ladder for a run that reserves on the `-ref` one.\n */\nexport function videoGenerationCreditId(args: {\n provider: string\n duration?: number | string\n sound?: boolean\n nodeType?: \"image-to-video\" | \"text-to-video\"\n mode?: string\n resolution?: string\n draft?: boolean\n hasVideoRef?: boolean\n}): string {\n const { resolution } = normalizeVideoRequestParams(args.provider, {\n resolution: args.resolution ?? uiResolutionFill(args.provider),\n draft: args.draft === true,\n })\n return buildVideoCreditModelIdentifier(\n args.provider,\n args.duration,\n args.sound,\n args.nodeType ?? \"image-to-video\",\n args.mode,\n resolution,\n args.hasVideoRef === true,\n )\n}\n\n/**\n * The credit identifier a Video to Video node's Seedance EDIT lane reserves\n * under. Seedance has no v2v endpoint — the lane is a text-to-video job in edit\n * shape with the source clip as reference video 1 — so it prices on the\n * REFERENCE-VIDEO ladder at the model's LONGEST clip (Auto duration), and the\n * measured settlement refunds down to what was actually delivered.\n *\n * A thin call into {@link videoGenerationCreditId}, so a Generate Video node\n * making the same KIE call (Seedance, Auto, a wired reference video) is quoted\n * the same id. FOUR surfaces must agree on it exactly: the orchestrator's\n * reservation (payload-builder.ts), the backend pre-run estimator\n * (ee/billing/credits.ts), the node's cost pill, and the frontend run-level\n * estimate (config-panels/helpers.ts). A quote that disagrees with the reserve\n * is the documented `price_not_configured` / blank-pill trap.\n *\n * `resolution` is the node's one `v2vResolution` field; when unset the model's\n * own UI fill is priced, which is what the lane will send. `draft` is the\n * node's Seedance Draft toggle (priced at 480p).\n */\nexport function seedanceVideoEditCreditId(provider: string, resolution?: string, draft?: boolean): string {\n return videoGenerationCreditId({\n provider,\n duration: VIDEO_DURATION_AUTO,\n nodeType: \"text-to-video\",\n resolution,\n draft,\n hasVideoRef: true,\n })\n}\n\n/** What the video credit identifier PRICES for a request, for the levers whose\n * priced value must also be the value we SEND. */\nexport interface PricedVideoSelection {\n /** The resolution band the reservation is priced at when the request omitted\n * one — and only where the platform DECLARES that band as the provider's own\n * default. `undefined` means \"leave `resolution` exactly as the request had\n * it\": either the caller supplied one, or the provider's real default is not\n * known to be the band the identifier assumes. */\n resolution?: string\n /** The length the reservation is priced at and the wire carries, for a\n * provider whose price follows the clip length (LTX's seeded tier, the KIE\n * ladders, Gemini Omni). `undefined` for every other provider, and for Auto:\n * their duration passes through. */\n duration?: number\n /** Non-empty only for a lever the caller ASKED for and did not get (a 7s\n * request snapped to the 6s tier). Filling an omitted lever is a disclosure of\n * the price already being charged, not a correction, so it reports nothing. */\n adjustments: ModelInputAdjustment[]\n}\n\n/**\n * The other half of the video money path: `normalizeVideoRequestParams` snaps a\n * value the CATALOG governs; this returns the value the PRICE ladder governs.\n *\n * Two defects it closes, both of the same shape — the identifier prices one\n * thing and the wire carries another, and `commit_credits` (migration 176) only\n * ever refunds a surplus, so the reservation is the final charge:\n *\n * 1. **Absent resolution.** `buildVideoCreditModelIdentifier` prices an omitted\n * `resolution` as a concrete band (LTX → 1080p; a\n * {@link PRICING_DEFAULT_RESOLUTION} member → its declared default). Leaving\n * the key unset then lets the provider pick — documented for the KIE members\n * (their `extraParams` pin the same band) but UNDOCUMENTED for LTX on\n * Replicate. Sending the band we priced makes the two agree by construction.\n *\n * The fill is deliberately limited to providers with a DECLARED default.\n * `buildVideoCreditModelIdentifier` also has un-declared fallbacks — the\n * cheapest tier for a resolution-priced provider with no\n * `PRICING_DEFAULT_RESOLUTION` row — and those are a HEDGE, not a verified\n * provider default: seedance-2 / -fast / -mini pin `resolution: \"720p\"`\n * KIE-side while the identifier prices 480p, so filling 480p would downgrade\n * the render to match a price we already know is wrong. That mismatch is a\n * pre-existing identifier bug and is fixed by seeding the row, not here.\n *\n * 2. **Duration.** Every provider whose price follows the clip length is\n * charged at the length it RENDERS: its own default when the request named\n * none (catalog `defaultDuration`), the nearest length it offers otherwise\n * (`pricedOutputDurationSec` — the runners' own snap rule). The LTX ladder is\n * seeded per (band × seconds), so a 7s request snaps onto the 6s tier;\n * sending 7s would bill six and render seven. The same value is returned for\n * the other length-priced providers (the KIE ladders, Gemini Omni), so what\n * is priced is what is sent. Auto (-1) is the model's call and is untouched.\n *\n * Pure, and IDEMPOTENT against the identifier: feeding its output back in\n * cannot move the reserved tier. `video-request-normalize.test.ts` proves that\n * over every provider × resolution × duration.\n */\nexport function pricedVideoSelection(opts: {\n provider: string\n resolution?: string\n duration?: number | string\n}): PricedVideoSelection {\n const adjustments: ModelInputAdjustment[] = []\n const ltx = ltxPricedTier(opts.provider, opts.resolution, opts.duration)\n\n // The band the request will be priced AND rendered at. An explicit value\n // always wins — this only ever fills an omission.\n const resolution = opts.resolution\n ?? (ltx ? ltx.band : PRICING_DEFAULT_RESOLUTION[opts.provider])\n\n const requested = typeof opts.duration === \"string\" ? parseInt(opts.duration, 10) : opts.duration\n const asked = requested !== undefined && !Number.isNaN(requested)\n\n // Every provider whose price follows the clip length sends the length it is\n // CHARGED at (the catalog funnel: its own default when unset, the nearest\n // legal length otherwise). Auto (-1) is the model's call and is left alone.\n const lengthPriced = !!ltx || DURATION_PRICED_PROVIDERS.has(opts.provider) || isGeminiOmniProvider(opts.provider)\n if (!lengthPriced || (!ltx && asked && requested! <= 0)) return { resolution, adjustments }\n\n const duration = ltx ? ltx.duration : pricedOutputDurationSec(opts.provider, opts.duration)\n if (asked && requested !== duration) {\n adjustments.push({\n field: \"duration\",\n from: requested!,\n to: duration,\n reason: ltx\n ? `LTX renders ${ltx.band} in ${ltx.duration}s steps — using ${ltx.duration}s instead of ${requested}s.`\n : `${opts.provider} renders ${duration}s clips at the nearest length it offers — using ${duration}s instead of ${requested}s.`,\n })\n }\n return { resolution, duration, adjustments }\n}\n\n/**\n * Compute composite model identifier for motion control with duration-tiered pricing.\n * Examples: \"kling-3.0-motion:10s\", \"kling-3.0-motion:1080p:15s\", \"motion-transfer:5s\"\n *\n * Wan Animate providers use resolution-tiered pricing (not per-second):\n * \"wan-animate-move\" (480p default), \"wan-animate-move:580p\", \"wan-animate-move:720p\"\n *\n * @param provider - Motion control provider key (\"kling\" for 2.6, \"kling-3.0\", \"wan-animate-move\", \"wan-animate-replace\")\n * @param resolution - \"720p\" or \"1080p\" (Kling), \"480p\" or \"580p\" or \"720p\" (Wan Animate)\n * @param videoDuration - Reference video duration in seconds (defaults to 10s, unused for Wan Animate)\n */\nexport function buildMotionCreditModelIdentifier(\n provider: string,\n resolution: string,\n videoDuration?: number,\n): string {\n // Wan Animate providers use resolution-tiered pricing (not duration-based)\n if (provider === \"wan-animate-move\" || provider === \"wan-animate-replace\") {\n // 480p is the default (base identifier), 580p and 720p get composite suffix\n if (resolution === \"580p\" || resolution === \"720p\") {\n return `${provider}:${resolution}`\n }\n return provider\n }\n\n const raw = videoDuration ?? 10\n const durationSec = Math.floor(Number.isNaN(raw) ? 10 : raw) // default 10s; floor to match KIE per-second billing\n const tier = MOTION_DURATION_TIERS.find(t => durationSec <= t.maxSeconds)\n ?? MOTION_DURATION_TIERS[MOTION_DURATION_TIERS.length - 1]\n\n const base = provider === \"kling-3.0\" ? \"kling-3.0-motion\" : \"motion-transfer\"\n const resSuffix = resolution === \"1080p\" ? \":1080p\" : \"\"\n return `${base}${resSuffix}:${tier.suffix}`\n}\n\n/**\n * The Suno operations whose credit key depends on the model VERSION.\n *\n * `/v1/suno/generate`, `/cover` and `/extend` resolve their creditGuard\n * identifier through `sunoCreditType(model, <operation>)` (routes/suno.ts\n * :247-249, :335-337, :407-409). EVERY other Suno route charges a flat\n * per-operation key and ignores the version the node carries — mashup (:648),\n * add-instrumental (:852), add-vocals (:907), upload-extend (:1016),\n * replace-section (:710), style-boost (:771), convert-wav (:962),\n * lyrics (:482), music-video (:594), voice (:1218).\n *\n * Anything that QUOTES a Suno price — a dropdown row, a node badge, the\n * workflow-credit estimator — must follow the same split, or it displays a\n * credit key the route never charges.\n */\nexport const SUNO_VERSION_PRICED_OPERATIONS = [\n \"suno-generate\",\n \"suno-cover\",\n \"suno-extend\",\n] as const\n\n/**\n * The seven Suno operations that appear behind a select/dropdown UI (model\n * pickers, node badges, the credit estimator) — the three version-priced\n * operations above, plus the four flat-key operations exercised by\n * `sunoCreditType`'s own test suite. A readonly tuple so later tasks (the\n * model dropdowns, node badges) can iterate or count it without redeclaring\n * the list and drifting from this one.\n */\nexport const SUNO_SELECT_OPERATIONS = [\n \"suno-generate\",\n \"suno-cover\",\n \"suno-extend\",\n \"suno-mashup\",\n \"suno-add-instrumental\",\n \"suno-add-vocals\",\n \"suno-upload-extend\",\n] as const\n\n/**\n * Adjust Speed's price id: motion-compensated (\"smooth\") interpolation is its\n * own, dearer tier. The route, the workflow run, and the editor's badge and\n * run estimate all price through this, so none of them can quote the fast tier\n * for a smooth run.\n */\nexport function speedRampCreditId(quality: unknown): \"speed-ramp\" | \"speed-ramp:smooth\" {\n return quality === \"smooth\" ? \"speed-ramp:smooth\" : \"speed-ramp\"\n}\n\n/**\n * Apply EDL's price id: a `proxy` render (the 720p preview) is its own,\n * cheaper per-output-minute row; a `final` render keeps the bare id. One id per\n * QUALITY, for a video and an audio output alike (decided 2026-10-04). Anything\n * that is not exactly \"proxy\" is the final, as the route and the node default\n * it. The route, the workflow run, and the editor's badge and run estimate all\n * price through this; the job itself is always named `apply-edl`.\n */\nexport function applyEdlCreditId(quality: unknown): \"apply-edl\" | \"apply-edl:proxy\" {\n return quality === \"proxy\" ? \"apply-edl:proxy\" : \"apply-edl\"\n}\n\n/**\n * Speaker View's price tiers (decided 2026-10-10, C4): a render is priced by\n * how many speakers it composites at once. `standard` — at most two tiles on\n * any segment and no zoom; `complex` — three to six tiles, or any zoom. Which\n * tier a render is in is the render rule's to say (the app's\n * `@nodaro/render-rules`), never this vocabulary's.\n */\nexport const SPEAKER_VIEW_PRICE_TIERS = [\"standard\", \"complex\"] as const\nexport type SpeakerViewPriceTier = (typeof SPEAKER_VIEW_PRICE_TIERS)[number]\n\nexport type SpeakerViewCreditId = \"speaker-view\" | \"speaker-view:proxy\" | \"speaker-view:complex\" | \"speaker-view:complex:proxy\"\n\n/** Every id `speakerViewCreditId` can name. */\nexport const SPEAKER_VIEW_CREDIT_IDS: readonly SpeakerViewCreditId[] = Object.freeze([\n \"speaker-view\",\n \"speaker-view:proxy\",\n \"speaker-view:complex\",\n \"speaker-view:complex:proxy\",\n] as const)\n\n/**\n * The credit id of a Speaker View render (F4, decided 2026-09-23; tiers\n * decided 2026-10-10): a Preview (`quality` \"proxy\") reserves on its own row,\n * anything else on the final's, and each in its price tier — `standard` on\n * `speaker-view` / `speaker-view:proxy`, `complex` on `speaker-view:complex` /\n * `speaker-view:complex:proxy`. A tier that is not exactly `standard` (absent\n * included) names the `complex` row: a caller that cannot tell quotes high,\n * never low. The job is always named `speaker-view`; only its credit id\n * follows the quality and the tier.\n */\nexport function speakerViewCreditId(quality: unknown, tier?: unknown): SpeakerViewCreditId {\n const proxy = quality === \"proxy\"\n if (tier === \"standard\") return proxy ? \"speaker-view:proxy\" : \"speaker-view\"\n return proxy ? \"speaker-view:complex:proxy\" : \"speaker-view:complex\"\n}\n\n/**\n * OUR Nodaro credit key for a Suno operation, given the model version and the\n * operation (which is also the node type and the BullMQ job name).\n *\n * This is the single source of truth for the Suno pricing contract, shared by\n * the reservation path (routes/suno.ts creditGuard), the egress seam\n * (workers/handlers/suno.ts `modelKey`, which must match what was reserved),\n * both workflow-credit estimators (ee/billing/credits.ts and the frontend\n * config-panels/helpers.ts), the seven Suno model dropdowns and the three Suno\n * node badges. It is a billing key — NEVER a KIE provider id — which is what\n * satisfies the B3 egress invariant.\n *\n * The version → key map is {@link SUNO_VERSION_CREDIT_KEYS}; a version with no\n * entry (V4 / V4_5 / V4_5ALL / V4_5PLUS) falls back to the operation key, and a\n * non-version-priced operation is returned unchanged.\n */\nexport function sunoCreditType(model: string | undefined, operation: string): string {\n if (!(SUNO_VERSION_PRICED_OPERATIONS as readonly string[]).includes(operation)) {\n return operation\n }\n return (model && SUNO_VERSION_CREDIT_KEYS[model]) || operation\n}\n\n/**\n * Suno version → Nodaro credit key for the version-priced operations. One row\n * per version that has its own `model_pricing` row / `STATIC_CREDIT_COSTS`\n * entry / `MODEL_CATALOG` pricing row, so an admin can reprice one version\n * without touching code. Every ACTIVE version MUST have a row here — guarded\n * by `__tests__/suno-credit-type.test.ts` (a new active version with no key\n * would silently bill at the operation key).\n */\nexport const SUNO_VERSION_CREDIT_KEYS: Readonly<Record<string, string>> = {\n V6: \"suno-v6\",\n V6_WILD: \"suno-v6_wild\",\n V6_MINI: \"suno-v6_mini\",\n V5_5: \"suno-v5_5\",\n V5: \"suno-v5\",\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/video-character-refs.ts","../src/video-duration.ts","../src/video-overlay.ts","../src/video-analysis.ts","../src/video-output-canvas.ts","../src/video-frame-fit.ts"],"names":[],"mappings":";;;;;;AA6CO,IAAM,gCAAgC,IAAA,CAAK,GAAA;AAAA,EAChD,CAAA;AAAA,EACA,GAAG,MAAA,CAAO,MAAA,CAAO,4BAA4B,CAAA,CAAE,IAAI,CAAC,CAAA,KAAM,CAAA,EAAG,UAAA,IAAc,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A,KAAc,MAAA,GACxB,IAAA,CAAK,QAAA,GAAW,2BAA2B,IAAA,CAAK,QAAQ,CAAA,IAAK,OAAA,GAAU,OAAA,GACxE,SAAA;AACJ,EAAA,IAAI,MAAA,KAAW,WAAA,IAAe,CAAC,IAAA,CAAK,yBAAyB,OAAO,OAAA;AACpE,EAAA,OAAO,MAAA;AACT","file":"chunk-SPP6HQMM.js","sourcesContent":["import { VIDEO_REF_LIMITS_BY_PROVIDER } from \"./model-constants.js\"\nimport type { GeminiOmniVoicePresetId } from \"./gemini-omni-voices.js\"\n\n/**\n * Character references — the dedicated IDENTITY input of a video model, as\n * opposed to a loose reference image.\n *\n * Gemini Omni treats `image_urls` as \"reference images for characters, scenes,\n * styles, or storyboard guidance\": a portrait sent there steers the clip but\n * the face drifts. Its separate `character_ids` input is the one that keeps a\n * real person's face, and it takes ids minted from a portrait by a create\n * call. The PUBLIC shape below is provider-neutral — a portrait and a\n * description — and the provider layer mints (and caches) whatever ids its\n * upstream needs. Nothing upstream-shaped ever appears in the API.\n *\n * WHICH models take them is data, never a name list: a positive `characters`\n * cap on `VIDEO_REF_LIMITS_BY_PROVIDER`.\n */\nexport interface VideoCharacterVoice {\n /** The base voice — one of `GEMINI_OMNI_VOICE_PRESETS`. */\n preset: GeminiOmniVoicePresetId\n /** Free-text timbre / pace / emotion for the persona. Optional. */\n description?: string\n /** One example line the persona says (≤ 120 chars). Optional. */\n exampleLine?: string\n}\n\nexport interface VideoCharacterReference {\n /** Portrait of the person (public URL). Index 0 of the upstream image set. */\n imageUrl: string\n /** Optional full-body image; costs a second input unit. */\n bodyImageUrl?: string\n /** Who this is: appearance, identity, style, clothing. Required by the upstream. */\n description: string\n /** Optional display name. */\n name?: string\n /**\n * Pin a voice persona to this character so it keeps ONE voice across clips\n * (the model otherwise improvises a voice per generation). Only models with a\n * positive `voices` cap take it.\n */\n voice?: VideoCharacterVoice\n}\n\n/** Zod `.max()` ceiling for the wire field — the widest cap any provider declares. */\nexport const VIDEO_CHARACTER_REFS_WIRE_MAX = Math.max(\n 0,\n ...Object.values(VIDEO_REF_LIMITS_BY_PROVIDER).map((l) => l?.characters ?? 0),\n)\n\n/** Longest `description` / `name` a client may send (route Zod reads these). */\nexport const VIDEO_CHARACTER_DESCRIPTION_MAX = 2000\nexport const VIDEO_CHARACTER_NAME_MAX = 100\n/** Longest voice `description` / `exampleLine` a client may send. The upstream\n * allows far more description (20000); we cap the PUBLIC field at the same\n * ceiling as a character description so policy text and prompts stay bounded. */\nexport const VIDEO_CHARACTER_VOICE_DESCRIPTION_MAX = 2000\nexport const VIDEO_CHARACTER_VOICE_EXAMPLE_MAX = 120\n\n/** How many character references the provider takes; 0 = none (or unknown). */\nexport function videoCharacterRefCap(provider: string | undefined): number {\n return provider ? (VIDEO_REF_LIMITS_BY_PROVIDER[provider]?.characters ?? 0) : 0\n}\n\n/** How many DISTINCT voice personas the provider takes per request; 0 = none. */\nexport function videoCharacterVoiceCap(provider: string | undefined): number {\n return provider ? (VIDEO_REF_LIMITS_BY_PROVIDER[provider]?.voices ?? 0) : 0\n}\n\n/**\n * Identity of a voice persona — what makes two voices \"the same voice\". The\n * persona is minted per (preset, description, example line) AND the character's\n * name (the label it is created under), so the name is part of the identity:\n * this count must equal the number of personas the provider will actually mint,\n * or the cap would be checked against a different number than what ships.\n */\nexport function videoCharacterVoiceKey(ref: Pick<VideoCharacterReference, \"voice\" | \"name\">): string | null {\n const voice = ref.voice\n if (!voice) return null\n return JSON.stringify([voice.preset, voice.description?.trim() ?? \"\", voice.exampleLine?.trim() ?? \"\", ref.name?.trim() ?? \"\"])\n}\n\n/** How many distinct voice personas a set of references asks for. */\nexport function videoCharacterDistinctVoices(\n characterReferences: readonly Pick<VideoCharacterReference, \"voice\" | \"name\">[] | undefined,\n): number {\n const keys = new Set<string>()\n for (const c of characterReferences ?? []) {\n const key = videoCharacterVoiceKey(c)\n if (key) keys.add(key)\n }\n return keys.size\n}\n\n/** Every provider that declares a character-reference cap, in declaration order. */\nexport function videoCharacterRefProviders(): string[] {\n return Object.entries(VIDEO_REF_LIMITS_BY_PROVIDER)\n .filter(([, l]) => (l?.characters ?? 0) > 0)\n .map(([id]) => id)\n}\n\n/**\n * Input units a set of character references draws from the provider's shared\n * input budget: 1 per character, 2 when a body image is supplied (the upstream\n * counts a dual-image character as two slots).\n */\nexport function videoCharacterRefUnits(\n characterReferences: readonly Pick<VideoCharacterReference, \"bodyImageUrl\">[] | undefined,\n): number {\n let units = 0\n for (const c of characterReferences ?? []) units += c.bodyImageUrl ? 2 : 1\n return units\n}\n\nexport interface VideoCharacterRefProblem {\n code:\n | \"character_references_unsupported\"\n | \"character_references_over_limit\"\n | \"character_references_with_start_frame\"\n | \"character_references_with_end_frame\"\n | \"character_references_quota\"\n | \"character_voice_unsupported\"\n | \"character_voices_over_limit\"\n message: string\n}\n\n/**\n * Voice-persona rule: the provider must take voices at all, and the DISTINCT\n * voices must fit its cap (Gemini Omni: 3 `audio_ids` per task). Two characters\n * with an identical voice AND name count once. `cap` overrides the provider's declared cap\n * (tests; a future model with a different limit declares it as data instead).\n */\nexport function videoCharacterVoiceProblem(args: {\n provider: string | undefined\n characterReferences: readonly VideoCharacterReference[] | undefined\n cap?: number\n}): VideoCharacterRefProblem | null {\n const distinct = videoCharacterDistinctVoices(args.characterReferences)\n if (distinct === 0) return null\n const cap = args.cap ?? videoCharacterVoiceCap(args.provider)\n if (cap === 0) {\n return {\n code: \"character_voice_unsupported\",\n message:\n `A character voice is not supported by ${args.provider ?? \"the selected model\"}. ` +\n \"Drop the voice, or pick a model that takes characterReferences.\",\n }\n }\n if (distinct > cap) {\n return {\n code: \"character_voices_over_limit\",\n message: `${args.provider} accepts at most ${cap} distinct character voices per video; got ${distinct}. Give some characters the same voice, or drop some.`,\n }\n }\n return null\n}\n\n/**\n * The one validation both video routes (and the provider backstop) run. Returns\n * the first problem as a friendly 400 body, or null when the request is fine.\n *\n * The shared budget: for a model that declares `characters`, its `images` cap\n * IS the total input budget (images + 2×videos + character units ≤ images cap —\n * 7 for Gemini Omni). Callers pass the ASSEMBLED image count, after any\n * `connectedReferences` expansion, so the budget is measured on what ships.\n */\nexport function videoCharacterRefProblem(args: {\n provider: string | undefined\n characterReferences: readonly VideoCharacterReference[] | undefined\n /** Reference images that will ship (assembled, flat). */\n imageCount: number\n /** Source / reference videos that will ship. */\n videoCount: number\n /** True when the request carries a start frame (`imageUrl`). */\n hasStartFrame: boolean\n /** True when the request carries an end frame (`endFrameUrl`). */\n hasEndFrame?: boolean\n}): VideoCharacterRefProblem | null {\n const { provider, characterReferences } = args\n if (!characterReferences || characterReferences.length === 0) return null\n\n const cap = videoCharacterRefCap(provider)\n if (cap === 0) {\n return {\n code: \"character_references_unsupported\",\n message:\n `characterReferences is not supported by ${provider ?? \"the selected model\"}. ` +\n `Models that take them: ${videoCharacterRefProviders().join(\", \")}. ` +\n \"Otherwise send the portrait as a reference image instead.\",\n }\n }\n if (characterReferences.length > cap) {\n return {\n code: \"character_references_over_limit\",\n message: `${provider} accepts at most ${cap} character references; got ${characterReferences.length}.`,\n }\n }\n // A NODARO limit, not an upstream exclusivity: Gemini Omni's start frame is\n // sent as the first entry of `image_urls` (never as `first_frame_url`), so\n // the upstream would take it beside `character_ids`. We reject the pair\n // because the frame / identity roles are not yet bound in the prompt\n // (and the frame would need to be budgeted against the shared input quota).\n if (args.hasStartFrame) {\n return {\n code: \"character_references_with_start_frame\",\n message:\n `${provider} does not yet support combining characterReferences with a start frame (imageUrl) — ` +\n \"the frame and the characters would compete for the same input slots without a defined role. \" +\n \"Drop the start frame (the character's portrait carries the face), or drop characterReferences.\",\n }\n }\n // Gemini Omni has no end-frame input; without this the frame would be dropped\n // silently once characters make a frame-less request look \"referenced\".\n if (args.hasEndFrame) {\n return {\n code: \"character_references_with_end_frame\",\n message:\n `${provider} does not use an end frame (endFrameUrl) together with characterReferences. ` +\n \"Drop the end frame, or drop characterReferences.\",\n }\n }\n const budget = VIDEO_REF_LIMITS_BY_PROVIDER[provider as string]?.images ?? 7\n const used = args.imageCount + args.videoCount * 2 + videoCharacterRefUnits(characterReferences)\n if (used > budget) {\n return {\n code: \"character_references_quota\",\n message:\n `${provider} takes at most ${budget} input units: reference images count 1, each reference video 2, ` +\n `each character 1 (2 with a body image). This request uses ${used}. Remove some reference images or characters.`,\n }\n }\n return videoCharacterVoiceProblem({ provider, characterReferences })\n}\n","/** Read a video node's duration (in seconds) from its data shape.\n * Tries `generatedResults[activeResultIndex].duration` (post-execution\n * metadata) first, then `data.duration` (configured at design time on\n * generate-video / image-to-video / text-to-video nodes). Returns\n * undefined when neither is set — callers should fall back to a sensible\n * default (e.g. 8s).\n *\n * Lives in `@nodaro/shared` so frontend (store walks) and backend\n * (orchestrator input-resolver) can use one source of truth. */\nexport function extractVideoDurationFromNode(\n data: Record<string, unknown> | undefined,\n): number | undefined {\n if (!data) return undefined\n const results = data.generatedResults as Array<{ duration?: number }> | undefined\n const idx = (data.activeResultIndex as number | undefined) ?? 0\n const fromResult = results?.[idx]?.duration\n if (typeof fromResult === \"number\" && Number.isFinite(fromResult) && fromResult > 0) {\n return fromResult\n }\n const fromConfig = data.duration\n if (typeof fromConfig === \"number\" && Number.isFinite(fromConfig) && fromConfig > 0) {\n return fromConfig\n }\n return undefined\n}\n\n/** Duration (seconds) of an edit-plan SOURCE node's media, for the reserve\n * bucket. Extends {@link extractVideoDurationFromNode} with the AUDIO lane:\n * `upload-audio` (and URL-imported audio) write their length to\n * `metadata.durationSeconds` ONLY — never `generatedResults[].duration` /\n * `data.duration` — so a podcast's audio master would otherwise resolve to\n * undefined and reserve the 180-minute ceiling (a ~6× overbill). A\n * `reference-audio` node records its extracted file's length in the same field,\n * stamped with `metadata.mediaUrl` (see the binding check below).\n *\n * Deliberately a NEW function, not a change to `extractVideoDurationFromNode`,\n * so no other node's duration read shifts — this fallback is edit-plan-scoped. */\nexport function editPlanSourceDurationSec(\n data: Record<string, unknown> | undefined,\n): number | undefined {\n const fromVideo = extractVideoDurationFromNode(data)\n if (fromVideo !== undefined) return fromVideo\n const meta = data?.metadata as { durationSeconds?: unknown; mediaUrl?: unknown } | undefined\n // A length stamped with the media it was measured from is trusted ONLY while\n // that media is still the node's. This is the read-side invariant that makes a\n // stale length impossible whoever changed the url — a copilot patch, an MCP\n // workflow-JSON write, an import, a run-time input override, or code not yet\n // written: a mismatch reads as \"unknown\", and every caller then falls to its\n // safe side (the transcript clock, the reserve-time probe, the ceiling bucket)\n // instead of under-bucketing a longer file. An UNSTAMPED length (upload-audio,\n // nodes saved before the stamp existed) is trusted as it always was.\n if (typeof meta?.mediaUrl === \"string\" && meta.mediaUrl !== data?.extractedAudioUrl && meta.mediaUrl !== data?.url) {\n return undefined\n }\n const d = meta?.durationSeconds\n return typeof d === \"number\" && Number.isFinite(d) && d > 0 ? d : undefined\n}\n","/**\n * Video Overlay — timed image layers over a video. The wire contract of the\n * `video-overlay` node, `POST /v1/video-overlay`, the `overlay_images` MCP\n * verb, `client.media.videoOverlay` and `nodaro media video-overlay`, defined\n * ONCE:\n * - every numeric bound (the route schema, the validator — which refuses a\n * present box / look field outside `VIDEO_OVERLAY_BOUNDS`, so the DAG path\n * that never meets the route schema is bounded too — both engine\n * assemblies and the canvas read these — never a second copy);\n * - the placement presets, stored as data in the custom box vocabulary: a\n * `preset` is a TAG, the box is the truth — the worker and the preview\n * never switch on the tag;\n * - `expandVideoOverlayLayer` / `expandVideoOverlayPresets`: the one\n * normaliser every write boundary calls;\n * - `resolveVideoOverlayGeometry`: the one placement function the canvas\n * preview and the ffmpeg worker both call;\n * - `assembleVideoOverlayRequest`: the one node-data → request assembly both\n * workflow engines call;\n * - `videoOverlayCompositionKey` (+ `videoOverlaySlotSources`): the freshness\n * key a run stamps on its result (`resultCompositionKey`) — the canvas\n * single-node Run (which sends it with the request, bounded by\n * `VIDEO_OVERLAY_MAX_COMPOSITION_KEY_LENGTH`) and the DAG payload compute\n * it with this one function, and the node compares it against the key of\n * its current settings;\n * - `validateVideoOverlayRequest`: what a schema cannot express, at every\n * engine entry. It returns a CODE, never English: `formatVideoOverlayError`\n * renders the route / worker text, the canvas renders the code through its\n * dictionaries.\n * Wire contract only — no prompt content, no I/O.\n */\nimport { OVERLAY_ANCHORS, type OverlayAnchor } from \"./image-overlay-layers.js\"\nimport { ASPECT_RATIO_DIMENSIONS } from \"./model-constants.js\"\n\n/** Engine + MCP contract: layers per request. */\nexport const VIDEO_OVERLAY_MAX_LAYERS = 20\n/** Ceiling for `start` / `end`, seconds. */\nexport const VIDEO_OVERLAY_MAX_TIME_SEC = 3600\n/**\n * The canvas layer handles, index-aligned with `layers[]` (overlay → layers[0]\n * … overlay12 → layers[11]). Slots 13 and up exist in data only, via `imageUrl`.\n * The same ids Image Overlay renders.\n */\nexport const VIDEO_OVERLAY_HANDLE_IDS = [\n \"overlay\", \"overlay2\", \"overlay3\", \"overlay4\", \"overlay5\", \"overlay6\",\n \"overlay7\", \"overlay8\", \"overlay9\", \"overlay10\", \"overlay11\", \"overlay12\",\n] as const\nexport const VIDEO_OVERLAY_PRESET_IDS = [\"card\", \"corner-badge\", \"full-frame\"] as const\nexport type VideoOverlayPresetId = (typeof VIDEO_OVERLAY_PRESET_IDS)[number]\nexport const VIDEO_OVERLAY_CORNERS = [\"top-left\", \"top-right\", \"bottom-left\", \"bottom-right\"] as const\nexport type VideoOverlayCorner = (typeof VIDEO_OVERLAY_CORNERS)[number]\nexport const VIDEO_OVERLAY_FITS = [\"contain\", \"cover\"] as const\nexport type VideoOverlayFit = (typeof VIDEO_OVERLAY_FITS)[number]\n/** Target aspects; absent = the base's own size and fps. */\nexport const VIDEO_OVERLAY_OUTPUT_ASPECTS = [\"16:9\", \"9:16\", \"1:1\", \"4:5\"] as const\nexport type VideoOverlayOutputAspect = (typeof VIDEO_OVERLAY_OUTPUT_ASPECTS)[number]\n/**\n * Reserved input id for a JSON layer plan. Payload: `VideoOverlayLayer[]` — the\n * same shape as the node's `layers[]`, a `preset` tag allowed and expanded at\n * the boundary. It has a pip on the node; both input resolvers route an edge on\n * it into `inputs.layerPlan`, which `assembleVideoOverlayRequest` reads (plan\n * layers first, then the handle layers).\n */\nexport const VIDEO_OVERLAY_LAYER_PLAN_HANDLE = \"layerPlan\"\n/** Box and look bounds. */\nexport const VIDEO_OVERLAY_BOUNDS = {\n x: [-100, 100],\n y: [-100, 100],\n width: [1, 100],\n height: [1, 100],\n opacity: [0, 1],\n zIndex: [0, 100],\n} as const\n/** Σ downloaded layer bytes per job. */\nexport const VIDEO_OVERLAY_MAX_TOTAL_LAYER_BYTES = 100 * 1024 * 1024\n/** Fade + scale ramp, seconds each way (clamped to half of a short layer). */\nexport const VIDEO_OVERLAY_ANIMATION_SEC = 0.15\n/** The scale a layer grows from and shrinks back to during the ramp. */\nexport const VIDEO_OVERLAY_ANIMATION_MIN_SCALE = 0.96\n/** Corner-badge width and inset, % of the output canvas. */\nexport const VIDEO_OVERLAY_BADGE_WIDTH = 18\nexport const VIDEO_OVERLAY_BADGE_INSET = 4\n/** Pad colour for `baseFit: \"contain\"` when none is given. */\nexport const VIDEO_OVERLAY_DEFAULT_BACKGROUND = \"#000000\"\n/** The six box fields — exactly what a preset writes. */\nexport const VIDEO_OVERLAY_BOX_FIELDS = [\"anchor\", \"x\", \"y\", \"width\", \"height\", \"fit\"] as const\nexport const VIDEO_OVERLAY_WARNING_CODES = [\"clipped\", \"skipped\", \"animated_first_frame\", \"audio_reencoded\"] as const\nexport type VideoOverlayWarningCode = (typeof VIDEO_OVERLAY_WARNING_CODES)[number]\nexport const VIDEO_OVERLAY_ERROR_CODES = [\n \"no_layers\", \"too_many_layers\", \"incomplete_box\", \"layer_without_image\",\n \"time_out_of_range\", \"end_before_start\", \"fit_without_aspect\", \"field_out_of_bounds\", \"invalid_layer_plan\",\n] as const\nexport type VideoOverlayErrorCode = (typeof VIDEO_OVERLAY_ERROR_CODES)[number]\n\nexport interface VideoOverlayBox {\n readonly anchor: OverlayAnchor\n readonly x: number\n readonly y: number\n readonly width: number\n readonly height?: number\n readonly fit: VideoOverlayFit\n}\n\n/** A layer as stored and enqueued — complete: every box and look field present. */\nexport interface VideoOverlayLayer {\n /**\n * Used when the layer's canvas handle is not wired (MCP, template, layers\n * 13 and up). Wiring the handle CLEARS it — on the canvas by the one `layers[]`\n * writer (D3), on JSON-written workflows by the write-boundary pass (D10) —\n * and the run-time merge is still `wired ?? imageUrl` everywhere.\n */\n imageUrl?: string\n /** 1-based canvas slot (overlay = 1 … overlay12 = 12; 13 and up handle-less), stamped by both engine assemblies. Messages prefer it. */\n slot?: number\n /** 1-based entry of a wired layer plan, stamped by the assembly. Messages prefer it. */\n planLayer?: number\n /** Seconds, 0..3600, stored ms-precise; rendered on the base's frame grid (±1 frame). */\n start: number\n /** Seconds, 0..3600, > start; absent = until the video ends. */\n end?: number\n /** A TAG only — the box below is the truth. */\n preset?: VideoOverlayPresetId\n /** corner-badge only; default bottom-right. */\n corner?: VideoOverlayCorner\n anchor: OverlayAnchor\n /** Offset from the anchor, % of the output canvas width (−100..100; negative on a right anchor = inward). */\n x: number\n /** Offset from the anchor, % of the output canvas height. */\n y: number\n /** % of the output canvas width (1..100). */\n width: number\n /** % of the output canvas height (1..100); absent = follows the image's aspect. */\n height?: number\n fit: VideoOverlayFit\n /** 0..1 */\n opacity: number\n /** Fade + slight scale in and out, 0.15 s each way. */\n animate: boolean\n /** Integer 0..100; absent = its position (slot − 1: layer 1 lowest). */\n zIndex?: number\n}\n\n/** A layer as a WRITER may send it (workflow JSON, a template, the canvas): every field optional; `null` means absent. */\nexport type VideoOverlayLayerInput = { [K in keyof VideoOverlayLayer]?: VideoOverlayLayer[K] | null }\n\n/** A layer on the REST / SDK wire: image and start required; the box may be a preset, explicit fields, or nothing (→ the corner-badge default). */\nexport type VideoOverlayLayerSpec = { imageUrl: string; start: number } & Partial<Omit<VideoOverlayLayer, \"imageUrl\" | \"start\">>\n\n/** The `POST /v1/video-overlay` body. */\nexport interface VideoOverlayRequest {\n videoUrl: string\n /** 1..20 */\n layers: VideoOverlayLayerSpec[]\n outputAspect?: VideoOverlayOutputAspect\n /** Only with `outputAspect`; default cover. */\n baseFit?: VideoOverlayFit\n /** `#rrggbb`, only with `outputAspect` (drawn under `contain`); default `#000000`. */\n backgroundColor?: string\n}\n\n/** A request whose layers went through `expandVideoOverlayPresets`. */\nexport interface ExpandedVideoOverlayRequest extends Omit<VideoOverlayRequest, \"layers\"> {\n layers: VideoOverlayLayer[]\n /** Set by the assembly when a wired layer plan could not be read; `validateVideoOverlayRequest` reports it first. */\n planError?: \"invalid_layer_plan\"\n}\n\n/** `output_data.warnings[]`: `layer` = 0-based index of the request's layers (absent for a render-wide warning such as `audio_reencoded`), `slot` when known. */\nexport interface VideoOverlayWarning {\n readonly layer?: number\n readonly slot?: number\n /** Set instead of `slot` when the layer came from the layer plan. */\n readonly planLayer?: number\n readonly code: VideoOverlayWarningCode\n readonly detail: string\n}\n\nconst badge = (anchor: VideoOverlayCorner, sx: 1 | -1, sy: 1 | -1): VideoOverlayBox => ({\n anchor,\n x: sx * VIDEO_OVERLAY_BADGE_INSET,\n y: sy * VIDEO_OVERLAY_BADGE_INSET,\n width: VIDEO_OVERLAY_BADGE_WIDTH,\n fit: \"contain\",\n})\n\n/**\n * Placement presets as DATA in the custom vocabulary. `card` sits centred, 4 %\n * above centre, contain into 78 % × 60 % of the frame; `full-frame` covers the\n * frame; `corner-badge` is 18 % wide, 4 % in from its corner.\n */\nexport const VIDEO_OVERLAY_PRESETS: {\n readonly card: VideoOverlayBox\n readonly \"full-frame\": VideoOverlayBox\n readonly \"corner-badge\": Readonly<Record<VideoOverlayCorner, VideoOverlayBox>>\n} = {\n card: { anchor: \"center\", x: 0, y: -4, width: 78, height: 60, fit: \"contain\" },\n \"full-frame\": { anchor: \"center\", x: 0, y: 0, width: 100, height: 100, fit: \"cover\" },\n \"corner-badge\": {\n \"bottom-right\": badge(\"bottom-right\", -1, -1),\n \"bottom-left\": badge(\"bottom-left\", 1, -1),\n \"top-right\": badge(\"top-right\", -1, 1),\n \"top-left\": badge(\"top-left\", 1, 1),\n },\n}\n\n/** D2 — what a wired slot with no settings runs (and previews) with: the bottom-right corner badge, from 0 to the end. */\nexport const DEFAULT_VIDEO_OVERLAY_LAYER: VideoOverlayLayer = Object.freeze({\n start: 0,\n preset: \"corner-badge\" as const,\n corner: \"bottom-right\" as const,\n ...VIDEO_OVERLAY_PRESETS[\"corner-badge\"][\"bottom-right\"],\n opacity: 1,\n animate: true,\n})\n\nconst HEX6 = /^#[0-9a-fA-F]{6}$/\n\nexport function isVideoOverlayPresetId(v: unknown): v is VideoOverlayPresetId {\n return typeof v === \"string\" && (VIDEO_OVERLAY_PRESET_IDS as readonly string[]).includes(v)\n}\nexport function isVideoOverlayCorner(v: unknown): v is VideoOverlayCorner {\n return typeof v === \"string\" && (VIDEO_OVERLAY_CORNERS as readonly string[]).includes(v)\n}\nexport function isVideoOverlayOutputAspect(v: unknown): v is VideoOverlayOutputAspect {\n return typeof v === \"string\" && (VIDEO_OVERLAY_OUTPUT_ASPECTS as readonly string[]).includes(v)\n}\nfunction isFit(v: unknown): v is VideoOverlayFit {\n return v === \"contain\" || v === \"cover\"\n}\n\n/**\n * A `layers[]` entry as a layer, or null when it is not a plain object. Layer\n * arrays reach this module from untrusted workflow JSON (the MCP write sites\n * type nodes as `record<string, unknown>`), so a bare string / number / array\n * entry is read as an ABSENT layer — never spread, never `in`-probed.\n */\nfunction asLayer(v: unknown): VideoOverlayLayerInput | null {\n return v !== null && typeof v === \"object\" && !Array.isArray(v) ? (v as VideoOverlayLayerInput) : null\n}\n\n/** 1-based slot of a layer handle id (`overlay` → 1 … `overlay12` → 12); 0 for anything else. */\nexport function videoOverlaySlotOfHandle(handle: string | null | undefined): number {\n return (VIDEO_OVERLAY_HANDLE_IDS as readonly string[]).indexOf(handle ?? \"\") + 1\n}\n\nexport function videoOverlayPresetBox(preset: VideoOverlayPresetId, corner?: VideoOverlayCorner | null): VideoOverlayBox {\n return preset === \"corner-badge\"\n ? VIDEO_OVERLAY_PRESETS[\"corner-badge\"][isVideoOverlayCorner(corner) ? corner : \"bottom-right\"]\n : VIDEO_OVERLAY_PRESETS[preset]\n}\n\nconst TRAILING_DEFAULTS = { x: 0, y: 0, fit: \"contain\", opacity: 1, animate: true } as const\n\nfunction usable(key: string, value: unknown): boolean {\n if (value === null || value === undefined) return false\n if (key === \"preset\") return isVideoOverlayPresetId(value)\n if (key === \"corner\") return isVideoOverlayCorner(value)\n return true\n}\n\n/** `null` / `undefined` / an unknown preset or corner → absent. By reference when nothing is dropped. */\nfunction clean(raw: VideoOverlayLayerInput): Partial<VideoOverlayLayer> {\n const entries = Object.entries(raw)\n if (entries.every(([k, v]) => usable(k, v))) return raw as Partial<VideoOverlayLayer>\n return Object.fromEntries(entries.filter(([k, v]) => usable(k, v))) as Partial<VideoOverlayLayer>\n}\n\nfunction sameShallow(a: Readonly<Record<string, unknown>>, b: unknown): boolean {\n if (!b || typeof b !== \"object\") return false\n const ka = Object.keys(a)\n const kb = Object.keys(b)\n return ka.length === kb.length && ka.every((k) => a[k] === (b as Record<string, unknown>)[k])\n}\n\n/**\n * The ONE normaliser (spec §3.3), called at every write boundary.\n * - `preset` + no box field → the preset's box is copied in, the tag stays.\n * - `preset` + explicit box fields → explicit fields win, the preset fills\n * what is absent; the tag is cleared only when an explicit field DIFFERS\n * from the preset's box (a field the preset does not set — `height` on a\n * corner badge — differs when present).\n * - no `preset` + no box field → the corner badge of the layer's own `corner`\n * (bottom-right when none), the D2 default filling tag / corner / trailing\n * fields, the layer's own fields winning (D8): `{}` → the full default.\n * - no `preset` + a PARTIAL box (not anchor AND width) → returned untouched;\n * the validator answers `incomplete_box`.\n * Trailing defaults x 0, y 0, fit contain, opacity 1, animate true are filled\n * here and nowhere else. `null` reads as absent. Returned BY REFERENCE when\n * nothing changes; idempotent, tag included.\n */\nexport function expandVideoOverlayLayer(raw: VideoOverlayLayerInput | null | undefined): VideoOverlayLayer {\n const obj = asLayer(raw)\n const layer = obj ? clean(obj) : {}\n const present = VIDEO_OVERLAY_BOX_FIELDS.filter((f) => layer[f] !== undefined)\n let out: Record<string, unknown>\n if (isVideoOverlayPresetId(layer.preset)) {\n const box = videoOverlayPresetBox(layer.preset, layer.corner)\n out = { ...box, ...layer }\n if (present.some((f) => layer[f] !== box[f])) delete out.preset\n } else if (present.length === 0) {\n out = { ...DEFAULT_VIDEO_OVERLAY_LAYER, ...videoOverlayPresetBox(\"corner-badge\", layer.corner), ...layer }\n } else if (layer.anchor === undefined || layer.width === undefined) {\n return raw as VideoOverlayLayer\n } else {\n out = { ...layer }\n }\n for (const [k, v] of Object.entries(TRAILING_DEFAULTS)) if (out[k] === undefined) out[k] = v\n return sameShallow(out, raw) ? (raw as VideoOverlayLayer) : (out as unknown as VideoOverlayLayer)\n}\n\n/** `expandVideoOverlayLayer` over an array; the SAME array when no layer changed. */\nexport function expandVideoOverlayPresets(layers: ReadonlyArray<VideoOverlayLayerInput | null | undefined>): VideoOverlayLayer[] {\n let changed = false\n const out = layers.map((l) => {\n const e = expandVideoOverlayLayer(l)\n if (e !== l) changed = true\n return e\n })\n return changed ? out : (layers as VideoOverlayLayer[])\n}\n\n/** The panel's preset click: REPLACE the six box fields with the preset's (dropping any it does not set), set the tag (+ corner), expand. */\nexport function applyVideoOverlayPreset(\n layer: VideoOverlayLayerInput | null | undefined,\n preset: VideoOverlayPresetId,\n corner?: VideoOverlayCorner,\n): VideoOverlayLayer {\n const base: Record<string, unknown> = { ...expandVideoOverlayLayer(layer) }\n for (const f of VIDEO_OVERLAY_BOX_FIELDS) delete base[f]\n delete base.preset\n const nextCorner = preset === \"corner-badge\" ? (corner ?? (isVideoOverlayCorner(base.corner) ? base.corner : \"bottom-right\")) : undefined\n return expandVideoOverlayLayer({\n ...base,\n ...videoOverlayPresetBox(preset, nextCorner),\n preset,\n ...(nextCorner ? { corner: nextCorner } : {}),\n } as VideoOverlayLayerInput)\n}\n\n/** The panel's \"Custom\": the tag is cleared, the box kept. */\nexport function toCustomVideoOverlayLayer(layer: VideoOverlayLayerInput | null | undefined): VideoOverlayLayer {\n const { preset: _tag, ...rest } = expandVideoOverlayLayer(layer)\n return rest as VideoOverlayLayer\n}\n\n/**\n * D10 — delete `imageUrl` from every layer whose canvas handle is wired\n * (`wiredSlots`: 1-based). Pure over `layers` (the route has no edges, so this\n * is a sibling of the expansion, not part of it). Slots 13 and up have no handle\n * and are never touched. The input array by reference when nothing changes.\n */\nexport function clearWiredVideoOverlayImageUrls<T extends VideoOverlayLayerInput | null | undefined>(\n layers: readonly T[],\n wiredSlots: ReadonlySet<number>,\n): readonly T[] {\n let out: T[] | null = null\n for (const slot of wiredSlots) {\n if (!Number.isInteger(slot) || slot < 1 || slot > VIDEO_OVERLAY_HANDLE_IDS.length) continue\n const layer = layers[slot - 1]\n if (!asLayer(layer) || !(\"imageUrl\" in (layer as object))) continue\n out ??= [...layers]\n const { imageUrl: _cleared, ...rest } = layer as VideoOverlayLayerInput\n out[slot - 1] = rest as T\n }\n return out ?? layers\n}\n\ninterface NodeLike {\n id?: unknown\n type?: unknown\n data?: unknown\n}\ninterface EdgeLike {\n target?: unknown\n targetHandle?: unknown\n}\n\n/**\n * The workflow-JSON write-boundary pass (spec §3.3, D10), beside\n * `normalizeNodeModelParams`: for every `video-overlay` node, clear the\n * `imageUrl` of each layer whose handle the WRITTEN edges wire, then expand\n * presets. Runs on every write, so an edge-only write still clears. A `null`\n * (or missing) slot STAYS `null`: \"no settings\" is stored as such, wired or\n * not — the default corner badge is synthesised only where a wired slot is\n * run or drawn (the two engine assemblies and the stage, D2), so the panel,\n * the reorder and the tail trim see the same empty slot whichever writer\n * stored it. (`{}` is not `null`: it is an explicit empty layer, and the\n * expansion turns it into the full default — spec §3.3.) Nodes and the array\n * are returned by reference when nothing changes.\n */\nexport function normalizeVideoOverlayNodes<T extends NodeLike>(nodes: readonly T[], edges: ReadonlyArray<EdgeLike> | null | undefined): T[] {\n let changed = false\n const out = nodes.map((node) => {\n if (node.type !== \"video-overlay\") return node\n const data = node.data\n if (!data || typeof data !== \"object\" || Array.isArray(data)) return node\n const d = data as Record<string, unknown>\n if (!Array.isArray(d.layers)) return node\n const layers = d.layers as Array<VideoOverlayLayerInput | null>\n const wired = new Set<number>()\n for (const e of edges ?? []) {\n if (e.target !== node.id) continue\n const slot = videoOverlaySlotOfHandle(typeof e.targetHandle === \"string\" ? e.targetHandle : undefined)\n if (slot > 0) wired.add(slot)\n }\n const cleared = clearWiredVideoOverlayImageUrls(layers, wired)\n let layersChanged = cleared !== layers\n const next = cleared.map((l) => {\n // null / missing stays as stored; a non-object entry is left untouched so\n // the validator sees it (it reads as an absent layer everywhere).\n if (!asLayer(l)) return l\n const e = expandVideoOverlayLayer(l)\n if (e !== l) layersChanged = true\n return e\n })\n if (!layersChanged) return node\n changed = true\n return { ...node, data: { ...d, layers: next } }\n })\n return changed ? out : (nodes as T[])\n}\n\n/** What `videoOverlayRenderOrder` reads from a layer. */\nexport interface VideoOverlayOrderable {\n readonly zIndex?: number | null\n /** 1-based canvas slot (stamped by both engine assemblies). */\n readonly slot?: number | null\n /** 1-based layer-plan entry. Plan layers sit BELOW every slot layer (handle layers draw above the plan), unless they set a `zIndex`. */\n readonly planLayer?: number | null\n /** 0-based index in the request's `layers[]` (the worker's graph layers carry it). */\n readonly index?: number | null\n}\n\n/** A plan layer's default position sits this far below layer 1's (slot 1 = 0), so the whole plan renders under the slot layers. */\nconst PLAN_LAYER_Z_BASE = 1000\nconst isSlot = (v: unknown): v is number => typeof v === \"number\" && Number.isInteger(v) && v >= 1\nconst isIndex = (v: unknown): v is number => typeof v === \"number\" && Number.isInteger(v) && v >= 0\n\n/**\n * Render order, bottom to top, as positions in `layers`: an explicit zIndex\n * wins; a layer without one sits at its OWN position — `slot − 1` when it has\n * a slot, else its request `index`, else its position in the array given —\n * never at its position in whatever (compacted) array it happens to be passed\n * in. The stage passes every slot; the worker passes the request minus empty\n * slots and minus layers skipped for starting after the end — both must agree\n * (spec: the preview and the run use the same numbers). Ties keep array order\n * (layer 1 lowest).\n */\nexport function videoOverlayRenderOrder(layers: ReadonlyArray<VideoOverlayOrderable | null | undefined>): number[] {\n return layers\n .map((l, i) => {\n const own = isSlot(l?.planLayer) ? l.planLayer - 1 - PLAN_LAYER_Z_BASE : isSlot(l?.slot) ? l.slot - 1 : isIndex(l?.index) ? l.index : i\n return { i, z: typeof l?.zIndex === \"number\" && Number.isFinite(l.zIndex) ? l.zIndex : own }\n })\n .sort((a, b) => a.z - b.z || a.i - b.i)\n .map((e) => e.i)\n}\n\nexport interface VideoOverlayRect {\n readonly left: number\n readonly top: number\n readonly width: number\n readonly height: number\n}\nexport interface VideoOverlayCanvas {\n readonly w: number\n readonly h: number\n}\nexport interface VideoOverlayGeometry {\n readonly box: VideoOverlayRect\n readonly drawn: VideoOverlayRect\n}\n\nconst evenFloor = (n: number): number => Math.max(2, Math.floor(n / 2) * 2)\n\n/**\n * The output canvas: `ASPECT_RATIO_DIMENSIONS[outputAspect]` when a target\n * aspect is set; otherwise the base's DISPLAY size (rotation already applied by\n * the caller's probe) with the sample aspect ratio resolved and both sides\n * rounded down to even — `trunc(iw*sar/2)*2 × trunc(ih/2)*2`, what the ffmpeg\n * base chain produces. null when neither is known.\n */\nexport function videoOverlayCanvas(\n display: { readonly width: number; readonly height: number; readonly sar?: number } | null | undefined,\n outputAspect?: string | null,\n): VideoOverlayCanvas | null {\n if (isVideoOverlayOutputAspect(outputAspect)) {\n const d = ASPECT_RATIO_DIMENSIONS[outputAspect]!\n return { w: d.width, h: d.height }\n }\n if (!display || !(display.width > 0) || !(display.height > 0)) return null\n const sar = typeof display.sar === \"number\" && Number.isFinite(display.sar) && display.sar > 0 ? display.sar : 1\n return { w: evenFloor(display.width * sar), h: evenFloor(display.height) }\n}\n\nfunction anchorFactors(anchor: OverlayAnchor): readonly [number, number] {\n const h = anchor.endsWith(\"left\") ? 0 : anchor.endsWith(\"right\") ? 1 : 0.5\n const v = anchor.startsWith(\"top\") ? 0 : anchor.startsWith(\"bottom\") ? 1 : 0.5\n return [h, v]\n}\n\n/**\n * Spec §3.4. `width%` → px of the canvas width; height follows the image's\n * aspect unless `height%` is set; nine anchors; x/y are additive offsets in %\n * of the canvas. An aspect-following box taller than the canvas is fitted\n * inside it (both sides scaled, aspect kept) — so `drawn` never exceeds the\n * canvas, which is what bounds the sharp pre-fit at one canvas of RGBA. `fit`:\n * contain → the image scaled inside the box, centred; cover → the box itself.\n * The only post-processing is rounding `drawn` DOWN to even, floored at 2 × 2.\n * Differences from Image Overlay's copies (on purpose): no 8192 edge shrink,\n * the canvas clamp, the even rounding.\n */\nexport function resolveVideoOverlayGeometry(\n canvas: VideoOverlayCanvas,\n layer: Pick<VideoOverlayLayer, \"anchor\" | \"x\" | \"y\" | \"width\" | \"height\" | \"fit\">,\n imageAspect: number,\n): VideoOverlayGeometry {\n const aspect = Number.isFinite(imageAspect) && imageAspect > 0 ? imageAspect : 1\n let bw = Math.max(1, Math.round((layer.width / 100) * canvas.w))\n let bh = layer.height !== undefined ? Math.max(1, Math.round((layer.height / 100) * canvas.h)) : Math.max(1, Math.round(bw / aspect))\n if (layer.height === undefined && bh > canvas.h) {\n bw = Math.max(1, Math.round(bw * (canvas.h / bh)))\n bh = canvas.h\n }\n const [ax, ay] = anchorFactors(layer.anchor)\n const left = Math.round(ax * (canvas.w - bw) + (layer.x / 100) * canvas.w)\n const top = Math.round(ay * (canvas.h - bh) + (layer.y / 100) * canvas.h)\n let dw: number\n let dh: number\n if (layer.fit === \"cover\") {\n dw = bw\n dh = bh\n } else if (bw / bh > aspect) {\n dh = bh\n dw = bh * aspect\n } else {\n dw = bw\n dh = bw / aspect\n }\n const width = evenFloor(dw)\n const height = evenFloor(dh)\n return {\n box: { left, top, width: bw, height: bh },\n drawn: { left: left + Math.floor((bw - width) / 2), top: top + Math.floor((bh - height) / 2), width, height },\n }\n}\n\nexport interface VideoOverlayIssue {\n readonly ok: false\n readonly code: VideoOverlayErrorCode\n /** 0-based index into the validated `layers[]`. */\n readonly layer?: number\n readonly slot?: number\n readonly planLayer?: number\n readonly params: Readonly<Record<string, string | number>>\n}\nexport type VideoOverlayValidation = { readonly ok: true } | VideoOverlayIssue\n\nexport interface VideoOverlayValidationInput {\n readonly layers?: ReadonlyArray<VideoOverlayLayerInput | null | undefined> | null\n readonly outputAspect?: string | null\n readonly baseFit?: string | null\n readonly backgroundColor?: string | null\n /** From `assembleVideoOverlayRequest`: the wired layer plan was unreadable. */\n readonly planError?: \"invalid_layer_plan\"\n}\n\nconst inTimeRange = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isFinite(v) && v >= 0 && v <= VIDEO_OVERLAY_MAX_TIME_SEC\n\ntype BoundedField = keyof typeof VIDEO_OVERLAY_BOUNDS\nconst BOUNDED_FIELDS = Object.keys(VIDEO_OVERLAY_BOUNDS) as BoundedField[]\n\n/**\n * The first present (non-null) box / look field outside its domain, with the\n * domain as a symbolic `allowed` string; null when every present field is in\n * range. Only PRESENT fields are checked, so the verdict is the same before and\n * after the expansion (it fills in-range defaults only). This is what keeps a\n * JSON-written layer (MCP `update_workflow_json`, copilot, templates) from\n * reaching the geometry with an unbounded box — `drawn ≤ canvas` (§3.4) holds\n * only for boxes inside these bounds.\n */\nfunction outOfBounds(l: VideoOverlayLayerInput): { field: string; allowed: string } | null {\n for (const f of BOUNDED_FIELDS) {\n const v = l[f]\n if (v === undefined || v === null) continue\n const [min, max] = VIDEO_OVERLAY_BOUNDS[f]\n const integer = f === \"zIndex\"\n if (typeof v !== \"number\" || !Number.isFinite(v) || v < min || v > max || (integer && !Number.isInteger(v))) {\n return { field: f, allowed: `${integer ? \"integers \" : \"\"}${min}..${max}` }\n }\n }\n if (l.anchor != null && !(OVERLAY_ANCHORS as readonly unknown[]).includes(l.anchor)) {\n return { field: \"anchor\", allowed: OVERLAY_ANCHORS.join(\", \") }\n }\n if (l.fit != null && !isFit(l.fit)) return { field: \"fit\", allowed: VIDEO_OVERLAY_FITS.join(\", \") }\n if (l.animate != null && typeof l.animate !== \"boolean\") return { field: \"animate\", allowed: \"true, false\" }\n return null\n}\n\n/**\n * Can `resolveVideoOverlayGeometry` place this layer? True when its box is what\n * the validator's box checks require: `anchor` one of the nine anchors, `width`\n * a finite number, and every present box / look field in range\n * (`VIDEO_OVERLAY_BOUNDS`, enums). A partial box saved from workflow JSON\n * (`{ imageUrl, start, width }`, `anchor: null`) is stored as written — the\n * expansion leaves it for the validator's `incomplete_box` — so any reader\n * that DRAWS a stored layer (the canvas stage) must skip one that fails this;\n * the geometry would throw on it.\n */\nexport function hasDrawableVideoOverlayBox(layer: unknown): boolean {\n const l = asLayer(layer)\n if (!l) return false\n if (!(OVERLAY_ANCHORS as readonly unknown[]).includes(l.anchor)) return false\n if (typeof l.width !== \"number\" || !Number.isFinite(l.width)) return false\n return outOfBounds(l) === null\n}\n\n/**\n * Spec §3.5 — what a schema cannot express, and what the DAG path skips. Run\n * at every engine entry: the route (`.superRefine`, before the expansion), the\n * canvas single-node run, payload-builder and the worker (after it) — the\n * verdict is the same on either side of the expansion (no code reads an\n * expanded field). Also refuses a PRESENT box / look field outside\n * `VIDEO_OVERLAY_BOUNDS` or its enum / type (`field_out_of_bounds`, spec §4.4's\n * \"out-of-bounds box/opacity/zIndex\" row — on the DAG path this validator is\n * the only check). A non-object `layers[]` entry reads as an empty layer. The\n * FIRST failure, as a code.\n */\nexport function validateVideoOverlayRequest(body: VideoOverlayValidationInput): VideoOverlayValidation {\n if (body.planError) return { ok: false, code: \"invalid_layer_plan\", params: {} }\n const layers = Array.isArray(body.layers) ? body.layers : []\n if (layers.length === 0) return { ok: false, code: \"no_layers\", params: {} }\n if (layers.length > VIDEO_OVERLAY_MAX_LAYERS) {\n return { ok: false, code: \"too_many_layers\", params: { max: VIDEO_OVERLAY_MAX_LAYERS, count: layers.length } }\n }\n for (let i = 0; i < layers.length; i++) {\n const l: VideoOverlayLayerInput = asLayer(layers[i]) ?? {}\n const at = (code: VideoOverlayErrorCode, params: Record<string, string | number> = {}): VideoOverlayIssue => ({\n ok: false,\n code,\n layer: i,\n ...(typeof l.slot === \"number\" ? { slot: l.slot } : {}),\n ...(typeof l.planLayer === \"number\" ? { planLayer: l.planLayer } : {}),\n params,\n })\n const boxFields = VIDEO_OVERLAY_BOX_FIELDS.filter((f) => l[f] !== undefined && l[f] !== null)\n if (!isVideoOverlayPresetId(l.preset) && boxFields.length > 0 && (l.anchor == null || l.width == null)) return at(\"incomplete_box\")\n const bad = outOfBounds(l)\n if (bad) return at(\"field_out_of_bounds\", bad)\n if (typeof l.imageUrl !== \"string\" || l.imageUrl.length === 0) return at(\"layer_without_image\")\n if (!inTimeRange(l.start)) return at(\"time_out_of_range\", { field: \"start\", max: VIDEO_OVERLAY_MAX_TIME_SEC })\n if (l.end !== undefined && l.end !== null) {\n if (!inTimeRange(l.end)) return at(\"time_out_of_range\", { field: \"end\", max: VIDEO_OVERLAY_MAX_TIME_SEC })\n if (!(l.end > l.start)) return at(\"end_before_start\", { start: l.start, end: l.end })\n }\n }\n if (!isVideoOverlayOutputAspect(body.outputAspect) && (body.baseFit != null || body.backgroundColor != null)) {\n return { ok: false, code: \"fit_without_aspect\", params: {} }\n }\n return { ok: true }\n}\n\nconst MESSAGES: { readonly [C in VideoOverlayErrorCode]: (p: Readonly<Record<string, string | number>>) => string } = {\n no_layers: () => \"At least 1 layer is required\",\n too_many_layers: (p) => `At most ${p.max} layers (got ${p.count})`,\n incomplete_box: () => \"anchor and width are required without a preset\",\n layer_without_image: () => \"no image — connect one to the layer's handle or set imageUrl\",\n time_out_of_range: (p) => `${p.field} must be between 0 and ${p.max} s`,\n end_before_start: (p) => `end (${p.end} s) must be after start (${p.start} s)`,\n fit_without_aspect: () => \"baseFit and backgroundColor need an outputAspect\",\n field_out_of_bounds: (p) => `${p.field} is out of range (allowed: ${p.allowed})`,\n invalid_layer_plan: () => \"the layer plan must be a list of layers\",\n}\n\nconst PLAN_LAYER_WITHOUT_IMAGE = \"no image — set imageUrl on this layer in the plan.\"\n\n/** `Plan layer <n>` for a layer-plan entry, `Layer <slot>` when the layer came from the canvas, else `layers[<index>]`; \"\" for a request-wide failure. */\nexport function videoOverlayLayerLabel(ref: { readonly layer?: number; readonly slot?: number; readonly planLayer?: number }): string {\n if (typeof ref.planLayer === \"number\") return `Plan layer ${ref.planLayer}`\n return typeof ref.slot === \"number\" ? `Layer ${ref.slot}` : typeof ref.layer === \"number\" ? `layers[${ref.layer}]` : \"\"\n}\n\n/** The ONE English rendering of a verdict — the route's 400 text and the worker's error message. */\nexport function formatVideoOverlayError(issue: VideoOverlayIssue): string {\n const label = videoOverlayLayerLabel(issue)\n // A plan layer has no handle to connect — its image can only come from its own imageUrl.\n const text = issue.code === \"layer_without_image\" && typeof issue.planLayer === \"number\" ? PLAN_LAYER_WITHOUT_IMAGE : MESSAGES[issue.code](issue.params)\n return label ? `${label}: ${text}` : text\n}\n\n/** The wired `layerPlan` value (a JSON string or an array) → its layers, or `invalid_layer_plan`. */\nexport function parseVideoOverlayLayerPlan(raw: unknown): { layers: VideoOverlayLayerInput[] } | { error: \"invalid_layer_plan\" } {\n let value: unknown = raw\n if (typeof raw === \"string\") {\n try {\n value = JSON.parse(raw)\n } catch {\n return { error: \"invalid_layer_plan\" }\n }\n }\n if (!Array.isArray(value) || !value.every((l) => l !== null && typeof l === \"object\" && !Array.isArray(l))) {\n return { error: \"invalid_layer_plan\" }\n }\n return { layers: value as VideoOverlayLayerInput[] }\n}\n\n/** The node-data fields the assembly reads. */\nexport interface VideoOverlayNodeFields {\n readonly layers?: ReadonlyArray<VideoOverlayLayerInput | null | undefined> | null\n readonly outputAspect?: string | null\n readonly baseFit?: string | null\n readonly backgroundColor?: string | null\n}\n\n/**\n * The ONE node → request assembly, called by the canvas single-node run AND\n * payload-builder (so both engines refuse identically). Per slot i over\n * max(wired handles (≤ 12), stored layers) — every stored slot, so more than\n * 20 layers that render reach the validator's `too_many_layers` instead of\n * being dropped: the image is the wired handle's,\n * else the layer's own `imageUrl`; a slot with neither is dropped; a slot with\n * no settings is the default layer (D2 — a `null` / missing / `{}` entry);\n * `slot = i + 1` is stamped; the layer is expanded. `baseFit` /\n * `backgroundColor` ride as stored, WITH or WITHOUT an `outputAspect`: the\n * validator — not this assembly — refuses them without one\n * (`fit_without_aspect`, spec §3.5), so a JSON-written node carrying a fit\n * and no aspect is refused on both engines instead of silently rendering.\n * (The canvas never builds that request: its two aspect writers clear both\n * fields with the aspect.) A value the route's schema would reject — an\n * unknown aspect or fit, a colour that is not `#rrggbb` — is dropped here.\n *\n * A wired layer plan (`planLayers`, a JSON string or an array) contributes its\n * layers FIRST, then the slot layers: plan layers carry `planLayer` (1-based)\n * and never a `slot`, and a plan layer's image is only its own `imageUrl` —\n * never the index-aligned handle's (R18). An unreadable plan sets `planError`,\n * which the validator reports before anything else.\n */\nexport function assembleVideoOverlayRequest(input: {\n readonly videoUrl: string\n readonly data: VideoOverlayNodeFields\n readonly wiredImageUrls: ReadonlyArray<string | null | undefined>\n /** The wired `layerPlan` value (string or array); absent when nothing is wired. */\n readonly planLayers?: unknown\n}): ExpandedVideoOverlayRequest {\n const stored = Array.isArray(input.data.layers) ? input.data.layers : []\n const wired = input.wiredImageUrls.slice(0, VIDEO_OVERLAY_HANDLE_IDS.length)\n // Every stored slot, never capped at VIDEO_OVERLAY_MAX_LAYERS: a JSON-written\n // node with 21+ layers must reach the validator's `too_many_layers` on both\n // engines (spec §3.5) — capping here would silently drop layers 21+. Only the\n // wired list is capped (12 handles).\n const slots = Math.max(wired.length, stored.length)\n const layers: VideoOverlayLayer[] = []\n for (let i = 0; i < slots; i++) {\n const raw = asLayer(stored[i])\n const wiredUrl = wired[i]\n const own = raw?.imageUrl\n const image = typeof wiredUrl === \"string\" && wiredUrl.length > 0 ? wiredUrl : typeof own === \"string\" && own.length > 0 ? own : undefined\n if (!image) continue\n layers.push(expandVideoOverlayLayer({ ...(raw ?? {}), imageUrl: image, slot: i + 1 }))\n }\n const outputAspect = isVideoOverlayOutputAspect(input.data.outputAspect) ? input.data.outputAspect : undefined\n const baseFit = isFit(input.data.baseFit) ? input.data.baseFit : undefined\n const backgroundColor =\n typeof input.data.backgroundColor === \"string\" && HEX6.test(input.data.backgroundColor) ? input.data.backgroundColor : undefined\n const rest = {\n ...(outputAspect ? { outputAspect } : {}),\n ...(baseFit ? { baseFit } : {}),\n ...(backgroundColor ? { backgroundColor } : {}),\n }\n if (input.planLayers === undefined) return { videoUrl: input.videoUrl, layers, ...rest }\n const plan = parseVideoOverlayLayerPlan(input.planLayers)\n if (\"error\" in plan) return { videoUrl: input.videoUrl, layers, ...rest, planError: plan.error }\n const planned = expandVideoOverlayPresets(plan.layers).map((l, i) => {\n const { slot: _slot, ...own } = l\n return { ...own, planLayer: i + 1 }\n })\n return { videoUrl: input.videoUrl, layers: [...planned, ...layers], ...rest }\n}\n\n/**\n * Slot i's image: the wired handle's, else the layer's own `imageUrl` — the\n * one source rule the stage, the panel, the canvas executor and the DAG\n * payload share (the render's merge is the same `wired ?? imageUrl`, spec\n * §3.5). Every stored slot, past 20 too: the limit is the layer COUNT, not\n * the slot (layers 1–4 removed from a 24-layer node leave 20 at slots 5–24).\n * Only the wired list is capped, at the 12 handles.\n */\nexport function videoOverlaySlotSources(\n layers: ReadonlyArray<VideoOverlayLayerInput | null | undefined> | null | undefined,\n wiredImageUrls: ReadonlyArray<string | null | undefined>,\n): Array<string | undefined> {\n const stored = Array.isArray(layers) ? layers : []\n const wired = wiredImageUrls.slice(0, VIDEO_OVERLAY_HANDLE_IDS.length)\n return Array.from({ length: Math.max(stored.length, wired.length) }, (_, i) => {\n const w = wired[i]\n if (typeof w === \"string\" && w.length > 0) return w\n const own = asLayer(stored[i])?.imageUrl\n return typeof own === \"string\" && own.length > 0 ? own : undefined\n })\n}\n\n/** Everything that decides what a Video Overlay run paints. */\nexport interface VideoOverlayComposition {\n /** The resolved base video URL. */\n readonly baseUrl?: string | null\n /** The image each slot draws, by slot index (`videoOverlaySlotSources`). */\n readonly sources: ReadonlyArray<string | null | undefined>\n /** The node's stored settings — never the expanded request. */\n readonly data: VideoOverlayNodeFields\n /** The wired `layerPlan` value (string or array); absent when nothing is wired. */\n readonly planLayers?: unknown\n}\n\n/**\n * A value with every object's keys sorted and every null / undefined object\n * field dropped (the assembly reads both as absent); array positions are kept.\n * A jsonb round-trip re-orders object keys, so a node read back from the DB\n * (a schedule / webhook / app run) and the same node in the editor (insertion\n * order) must give one key.\n */\nfunction canonicalValue(v: unknown): unknown {\n if (Array.isArray(v)) return v.map((x) => (x === undefined ? null : canonicalValue(x)))\n if (v !== null && typeof v === \"object\") {\n const out: Record<string, unknown> = {}\n for (const k of Object.keys(v).sort()) {\n const x = (v as Record<string, unknown>)[k]\n if (x !== undefined && x !== null) out[k] = canonicalValue(x)\n }\n return out\n }\n return v\n}\n\n/**\n * The longest `resultCompositionKey` the REST route accepts. The canvas sends\n * its key with a single-node Run so the job's output_data carries it (a result\n * that lands after a page reload reads fresh); the route stores it opaquely and\n * reads it for nothing else. A full 20-layer composition with long signed URLs\n * fits well inside; a canvas key past it is not sent.\n */\nexport const VIDEO_OVERLAY_MAX_COMPOSITION_KEY_LENGTH = 65_536\n\n/**\n * The composition key a run stamps on its result (`resultCompositionKey`): the\n * base, every slot's image, the layers, the output aspect, the fit and the pad\n * colour. A later change to any of them marks the result \"Result (old)\".\n * Canonical — independent of object key order, of absent vs undefined vs null\n * fields, and of trailing empty slots — so the canvas (the node and its\n * single-node Run) and the DAG payload give one key for one composition.\n */\nexport function videoOverlayCompositionKey(c: VideoOverlayComposition): string {\n const sources = c.sources.map((s) => (typeof s === \"string\" && s.length > 0 ? s : null))\n while (sources.length > 0 && sources[sources.length - 1] === null) sources.pop()\n const parts: unknown[] = [\n c.baseUrl || null,\n sources,\n Array.isArray(c.data.layers) ? c.data.layers : [],\n c.data.outputAspect ?? null,\n c.data.baseFit ?? null,\n c.data.backgroundColor ?? null,\n ]\n // Appended only when a plan is wired, so a node with no plan keeps today's key.\n // The PARSED plan is hashed: a JSON string and its array give one key.\n if (c.planLayers !== undefined) {\n const plan = parseVideoOverlayLayerPlan(c.planLayers)\n parts.push(\"error\" in plan ? \"invalid\" : plan.layers)\n }\n return JSON.stringify(canonicalValue(parts))\n}\n","/**\n * Video-analysis node — shared data contract.\n *\n * Single source of truth for the video-analysis node: the backend worker, the\n * frontend, and a future generator all import from here. Two schema layers:\n * - `windowAnalysisSchema` — what the LLM emits per analysis window\n * (strict-JSON footer). `scenes` has NO min (a quiet window returning zero\n * scenes is a VALID result). Model-emitted `oversized`/`slotRefs` are\n * STRIPPED here — they are validator-computed later (z.object drops unknown\n * keys by default).\n * - `videoAnalysisResultSchema` — the merged, validator-computed result across\n * all windows; requires >=1 scene overall.\n *\n * Entity slots are referenced in scene `visual` text via `{slot:<id>}` tokens\n * (`SLOT_TOKEN_RE`) — a grammar distinct from `NODE_REF_PATTERN` and the\n * `{image:N}` reference tokens. Unresolved tokens UNWRAP to their literal id\n * text, never delete (spec invariant), so a downstream prompt never carries a\n * dangling `{slot:…}` placeholder.\n */\nimport { z } from \"zod\"\n\nexport const VIDEO_ANALYSIS_MAX_SCENE_SEC = 8\n\n/**\n * Camera VIEWPOINT — where the camera is relative to the subject. The axis\n * `shotType` does not carry, and the one the analyzer had been improvising.\n *\n * Two failures this fixes, both from real jobs:\n *\n * 1. `shotType` is framing SIZE (Wide … Extreme Close-Up), so a true angle had\n * nowhere to go and landed in the MOVEMENT field instead:\n * `\"camera\": \"low angle static\"`. That loses the angle to anything reading\n * `camera` and pollutes the movement vocabulary.\n * 2. The relational viewpoints — `Over-the-Shoulder`, `POV` — were conventions\n * inside the `shotType` list, competing with the sizes for one slot. So an\n * over-the-shoulder MEDIUM had to pick one and threw the other away. They\n * belong here, leaving `shotType` free to state the size: an OTS medium is\n * `shotType: \"Medium\"` + `angle: \"over-the-shoulder\"`, which is strictly more\n * than either field could carry alone.\n *\n * A closed enum rather than free text precisely because improvisation is the\n * failure being fixed. Absent means EYE-LEVEL — the overwhelming default, so\n * omitting it costs nothing on most shots (the same \"absence is the default\"\n * shape as `transitionOut` and appearance variations).\n *\n * `from-behind` and `over-the-shoulder` also carry real meaning downstream: a\n * face is not visible in either, which is what auto-cast needs to know before\n * choosing one as an identity reference.\n */\nexport const VIDEO_ANALYSIS_SHOT_ANGLES = [\n // Vertical placement and roll — the classical \"angles\".\n \"eye-level\", \"low\", \"high\", \"overhead\", \"worms-eye\", \"dutch\",\n // Relational viewpoints — where the camera sits with respect to the subject.\n \"over-the-shoulder\", \"pov\", \"profile\", \"from-behind\",\n] as const\nexport type VideoAnalysisShotAngle = (typeof VIDEO_ANALYSIS_SHOT_ANGLES)[number]\n\n/** Viewpoints in which the subject's FACE is not visible — so a frame shot this\n * way is a poor identity reference however good its framing otherwise is. */\nexport const VIDEO_ANALYSIS_FACELESS_ANGLES: ReadonlySet<string> = new Set([\"over-the-shoulder\", \"from-behind\"])\n\n/**\n * Effects applied to the PICTURE of a shot. An array — a shot can be grainy and\n * vignetted at once — and absent when the image is clean, which is most shots.\n *\n * Scoped deliberately to things done to the IMAGE, and NOT to compositing that\n * asserts what is in the shot (picture-in-picture, split screen). That line\n * matters: a real job invented `{slot:creator} overlay talking to camera` across\n * nine scenes for a man who is never seen, so a field for \"there is an inset of a\n * person here\" would hand that fabrication a legitimate home. An effect is\n * verifiable in the pixels; a claim about who is inset is not.\n *\n * `dissolve` and `fade` are NOT here either — they are edits BETWEEN shots and\n * belong to `transitionOut`.\n */\nexport const VIDEO_ANALYSIS_VISUAL_EFFECTS = [\n \"blur\", \"pixelate\", \"glitch\", \"grain\", \"vignette\", \"flash\", \"distortion\", \"double-exposure\",\n] as const\nexport type VideoAnalysisVisualEffect = (typeof VIDEO_ANALYSIS_VISUAL_EFFECTS)[number]\n\n/**\n * Visible edit INTO the next shot.\n *\n * `dissolve` (a cross-fade from one image to the other) is distinct from `fade`\n * (through black or white). Collapsing both onto `fade` — as this enum did — makes\n * a recreation render the wrong edit, and the two look nothing alike.\n *\n * ABSENT means NOTHING ASSERTED (since v2): the analyser emits a value only\n * when it can see the device; an unknown or uncertain edit is left out so the\n * video model chooses. `cut` is itself an assertion (an instant change between\n * two clearly different shots), never a default.\n */\nexport const VIDEO_ANALYSIS_TRANSITIONS = [\n \"cut\", \"fade\", \"dissolve\", \"wipe\", \"whip\",\n // v2 (2026-08-30, recast shot craft rev 1.5 Appendix F): the common edits a\n // creator actually cuts with. `white-flash` / `digital-glitch` are spelled\n // out because `flash` / `glitch` already name in-shot EFFECTS (the axis test\n // below) — a device is the edit BETWEEN two shots, an effect is on one shot.\n \"zoom\", \"slide\", \"white-flash\", \"digital-glitch\", \"morph\", \"match\", \"jump\",\n] as const\nexport type VideoAnalysisTransition = (typeof VIDEO_ANALYSIS_TRANSITIONS)[number]\n\n/**\n * What burned-in text IS (2026-08-28, recast shot craft). Decides render-vs-omit\n * downstream: a `subtitle` is a transcription of the piece's own speech — a\n * recreation re-speaks it and must not render it — while a `title`, `caption`,\n * `lower-third` or `logo` is picture content. Absent when a scene carries no\n * text. A new KEY on the scene: strip-mode readers drop it harmlessly.\n */\nexport const VIDEO_ANALYSIS_TEXT_KINDS = [\"title\", \"caption\", \"lower-third\", \"subtitle\", \"logo\", \"other\"] as const\nexport type VideoAnalysisTextKind = (typeof VIDEO_ANALYSIS_TEXT_KINDS)[number]\n\n/** How the CLIP opens (clip-level, not per scene — a window's first scene is\n * not the clip's). Absent ⇒ a hard open. Only `fade` today. */\nexport const VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN = [\"fade\"] as const\nexport type VideoAnalysisClipTransitionIn = (typeof VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN)[number]\n\n/**\n * Time manipulation — slow motion, ramps, timelapse, freeze, reverse.\n *\n * Previously unrepresentable anywhere in the schema, so a recreation rendered\n * every shot at normal speed no matter what the footage did. It is a first-class\n * lever in every video model and a real editing decision in most action footage.\n *\n * `\"normal\"` is deliberately NOT a member: absence is normal speed, so there is\n * exactly one way to say \"nothing unusual here\" and the field costs nothing on\n * the majority of shots.\n */\nexport const VIDEO_ANALYSIS_SPEED_EFFECTS = [\"slow-motion\", \"ramp-in\", \"ramp-out\", \"timelapse\", \"freeze\", \"reverse\"] as const\n\n/** CHRONICLE TIME (2026-08-17): the STORY clock, per scene, as read from the\n * pictures — light, sky, practicals. \"ambiguous\" is the honest answer for a\n * windowless interior; guessing day is exactly the kind of tidy inference\n * the analysis doctrine forbids. */\nexport const VIDEO_ANALYSIS_TIMES_OF_DAY = [\"dawn\", \"day\", \"dusk\", \"night\", \"ambiguous\"] as const\n\n/** STORY JUMP since the PREVIOUS scene in the list: how much narrative time\n * passed across the cut, judged from evidence (wardrobe change, aged\n * subjects, season, a title card), not from the cut itself. Time outranks\n * location for continuity judgements (same person, new place, continuous\n * time ⇒ same outfit; same place, years later ⇒ anything may differ), which\n * is why this is a structured field and not prose. \"unclear\" is the honest\n * default; the FIRST scene of a clip is \"continuous\" by convention. */\nexport const VIDEO_ANALYSIS_STORY_JUMPS = [\"continuous\", \"same-day\", \"another-day\", \"years-later\", \"unclear\"] as const\nexport type VideoAnalysisSpeedEffect = (typeof VIDEO_ANALYSIS_SPEED_EFFECTS)[number]\n\n/**\n * The CLIP-LEVEL look — one source of truth for the properties that belong to\n * the whole piece rather than any one shot.\n *\n * Colour grade, camera format and lens character were previously only ever prose\n * inside each scene's `visual`, which meant a 43-scene analysis re-decided the\n * grade forty-three independent times with nothing holding them consistent. That\n * is the same drift problem entity slots solve for people: state it once, apply it\n * everywhere. A recreation reads this alongside every scene.\n *\n * Every field optional — an analyzer that cannot read the format should say\n * nothing rather than guess, and a per-scene deviation still belongs in that\n * scene's `visual` prose.\n */\nexport const clipLookSchema = z.object({\n /**\n * The rendering MEDIUM — \"live-action photoreal\", \"2D anime\", \"stop-motion\n * claymation\", \"3D render\", \"oil painting\", \"pixel art\".\n *\n * The most consequential field in this object, and orthogonal to every other\n * one: two shots with identical grade, lens, lighting and framing still look\n * nothing alike when one is live action and the other is an oil painting. Get\n * this wrong and a recreation renders the whole piece in the wrong medium,\n * which no amount of correct grade or lighting can rescue.\n *\n * Mirrors the product's Style picker, whose catalog defines exactly this axis\n * and states its independence from lighting, colour-look, atmosphere and lens.\n * A clip that genuinely changes medium partway (live action with an animated\n * insert) states the deviation in that scene's `visual`, as with `lighting`.\n */\n style: z.string().optional(),\n /**\n * The Style picker CATALOG ID the prose in `style` corresponds to — the\n * analyzer's PICK (\"pixar-3d\" beside \"3D stylized animation\"), not a second\n * description of it.\n *\n * Worth strictly more than the prose it accompanies: an id addresses the\n * catalog, so a recreation renders the same medium the product's own Style\n * picker would render, instead of re-interpreting a sentence. Absent when the\n * analyzer read a medium it could not place in the catalog — `style` then\n * carries the whole answer, as it always did.\n *\n * A free `string` here on purpose. The PRODUCER validates it against the\n * catalog (the analyzer plugin's wire schema is an enum generated from\n * `STYLES`, so an invented id never leaves it), while this package must not\n * carry the catalog itself. A closed enum here would only add a second copy\n * of the vocabulary to drift out of date — and, worse, would REJECT a\n * catalog entry newer than the installed `@nodaro/shared`, which is exactly\n * the analysis a consumer most wants to read.\n */\n styleId: z.string().optional(),\n /** Colour grade / palette — \"muted teal-and-orange, crushed blacks\". */\n grade: z.string().optional(),\n /** Camera or film FORMAT and stock — \"anamorphic digital\", \"16mm film grain\". */\n format: z.string().optional(),\n /** Lens character — \"wide-angle, shallow depth of field throughout\". */\n lens: z.string().optional(),\n /** Overall lighting style — \"hard single-source daylight, deep shadow\". */\n lighting: z.string().optional(),\n /** What KIND of piece this is — \"cinematic trailer\", \"talking-head vlog\". */\n genre: z.string().optional(),\n /**\n * The visual INFLUENCE the piece clearly evokes — a cinematographer, director,\n * photographer or named aesthetic (\"shot like Deakins\", \"Wes Anderson\n * symmetry\", \"80s Kodachrome editorial\").\n *\n * The highest-leverage field here by a distance: a couple of words transfer a\n * whole aesthetic that would otherwise take a paragraph of grade, lens and\n * lighting prose to approximate — which is exactly why the product already\n * exposes it as a curated picker (\"Photographer / Artist\") whose catalog ships\n * `in the style of …` prompt hints. The analyzer had no way to read it back.\n *\n * Deliberately conservative: OMIT unless the footage genuinely evokes a\n * well-known, nameable style. A confident misattribution is worse than silence,\n * because it drags an entire wrong aesthetic into every regenerated shot — so\n * describing the look in `grade`/`lighting` always beats guessing a name.\n */\n influence: z.string().optional(),\n})\nexport type ClipLook = z.infer<typeof clipLookSchema>\nexport const VIDEO_ANALYSIS_ENTITY_SOURCES = [\"wired-character\", \"wired-object\", \"wired-location\", \"wired-creature\"] as const\nexport type VideoAnalysisEntitySource = (typeof VIDEO_ANALYSIS_ENTITY_SOURCES)[number]\n/** Matches {slot:<id>} tokens. Distinct from NODE_REF_PATTERN / {image:N} grammars. */\nexport const SLOT_TOKEN_RE = /\\{slot:([a-z0-9-]+)\\}/g\n\n/**\n * Appearance variations (cast-variations spec, 2026-07-24): a slot's canonical\n * `description` IS its default look; `variations` enumerates NON-default looks\n * only (dream vs reality, flashback, disguise…). `\"default\"` is a reserved\n * variationId — used in scene bindings / ledger keys / routing for unbound\n * scenes, never inside `variations[]`. The closed slug vocabulary is\n * doctrine-enforced (the schema pins only the id charset, like `role`);\n * `alt-1`/`alt-2` are the escape hatches.\n */\nexport const VIDEO_ANALYSIS_VARIATION_SLUGS = [\"dream\", \"flashback\", \"disguise\", \"costume\", \"transformation\", \"era\", \"alt-1\", \"alt-2\"] as const\n/** Max NON-default looks per slot. The window layer REJECTS past the cap (schema-forced retry); the cross-window merge FOLDS at the cap. */\nexport const VIDEO_ANALYSIS_MAX_VARIATIONS = 4\nexport const VIDEO_ANALYSIS_DEFAULT_VARIATION = \"default\"\n\nexport const slotVariationSchema = z.object({\n variationId: z.string().min(1).regex(/^[a-z0-9-]+$/)\n .refine((id) => id !== VIDEO_ANALYSIS_DEFAULT_VARIATION, { message: `\"${VIDEO_ANALYSIS_DEFAULT_VARIATION}\" is reserved for the slot's canonical look` }),\n label: z.string().min(1),\n /** Full STANDALONE casting-sheet look restating the slot's invariant identity\n * core (face, build, age) — the manifest substitutes it wholesale, so a\n * wardrobe-only delta would silently delete identity from the prompt. */\n description: z.string().min(1),\n /** Per-variation identity reference (auto-cast frame or user sheet). In the\n * schema from day one: every strip-mode round-trip must carry it. */\n refImageUrl: z.string().url().optional(),\n})\nexport type SlotVariation = z.infer<typeof slotVariationSchema>\n\nexport const entitySlotSchema = z.object({\n slotId: z.string().min(1).regex(/^[a-z0-9-]+$/),\n label: z.string().min(1),\n source: z.enum(VIDEO_ANALYSIS_ENTITY_SOURCES),\n role: z.string().min(1),\n description: z.string().min(1),\n /** Auto-cast visual reference — a hosted frame from the analyzed footage\n * where this entity is clearly visible. Optional/additive: producers may\n * omit it; consumers use it as an identity reference for recreation. */\n refImageUrl: z.string().url().optional(),\n /**\n * Why `refImageUrl` is ABSENT, when the analyzer's vision pass actively\n * refused every candidate frame rather than merely failing to produce one.\n *\n * Present only alongside a missing `refImageUrl`, and only for a real refusal\n * — never for a technical failure, so its presence always carries meaning. The\n * important case reads like \"the shots bound to this slot show someone else —\n * cast as X, but on screen: Y\", which is the analyzer telling you the casting\n * description and the footage disagree. A consumer should treat that as a\n * reason to review the slot before spending on regeneration, since a wrong\n * identity propagates into every regenerated shot.\n */\n refRejectedReason: z.string().optional(),\n /** NON-default looks only; present only when at least one exists. */\n variations: z.array(slotVariationSchema).max(VIDEO_ANALYSIS_MAX_VARIATIONS).optional(),\n /**\n * WHOSE THIS OBJECT IS (2026-09-17). An object slot that is worn, held,\n * carried, driven or ridden by a cast person or creature names that slot\n * here, with the relation as a short passive phrase ending in \"by\" (\"worn\n * by\", \"held by\", \"driven by\"). The link says the object slot IS the one on\n * that person — not a second one: a recast that saw \"Man in Blue Silk\n * Shirt\" AND \"Blue Silk Shirt\" as unrelated slots rendered two shirts.\n * Object slots only; a free-standing prop, the product on a table, a place\n * or a person never carries it. Optional/additive: producers may omit it.\n */\n owner: z.object({\n slotId: z.string().min(1).regex(/^[a-z0-9-]+$/),\n relation: z.string().min(1),\n }).optional(),\n})\nexport type EntitySlot = z.infer<typeof entitySlotSchema>\nexport type EntitySlotOwner = NonNullable<EntitySlot[\"owner\"]>\n\n/**\n * The sound LAYER vocabulary — what kind of thing this layer is.\n *\n * `ambience` is deliberately its own member rather than a flavour of `sfx`:\n * they are different layers of a real mix and they are recreated by different\n * means — ambience is the continuous bed a scene sits in (room tone, distant\n * traffic, wind), an sfx is a discrete hit (a door slam, a gunshot). Folded\n * together, a scene's bed and its one-off noises arrive indistinguishable and\n * anything recreating the mix has to guess which it was told.\n *\n * Exported so a consumer keying its own document by these modes imports the\n * vocabulary instead of restating it — the same reason every other closed\n * vocabulary in this file is a const.\n */\nexport const VIDEO_ANALYSIS_AUDIO_MODES = [\"speech\", \"music\", \"sfx\", \"ambience\"] as const\nexport type VideoAnalysisAudioMode = (typeof VIDEO_ANALYSIS_AUDIO_MODES)[number]\n\n/**\n * One concurrent sound layer in a scene. Real footage stacks sound (music bed\n * under dialogue over ambient room tone), so a scene carries an ARRAY of these\n * — an empty array means genuine silence. `content`: speech = verbatim words;\n * music/sfx/ambience = gen-ready description. `voice` is speech-only\n * voice-casting.\n */\nconst audioLayerSchema = z.object({\n mode: z.enum(VIDEO_ANALYSIS_AUDIO_MODES),\n content: z.string().min(1),\n voice: z.string().optional(),\n /**\n * SPEECH ONLY — `slotId` of the on-screen speaker saying these words.\n *\n * `voice` casts a voice (\"male, proud triumphant shouting\"); this says WHO it\n * belongs to, so a recreation can route the line to the right character\n * instead of guessing. Usually one person speaks per scene and the guess is\n * right, which is exactly why the cases with two speakers over one cut fail\n * silently without this field.\n *\n * Optional by design and deliberately NOT refined against `mode` here: the\n * window schema is the enforced decode grammar, and rejecting a whole roll\n * because the model tagged a music layer would be a hair-trigger failure. A\n * speaker on a non-speech layer, or one naming a slot that no longer exists,\n * is stripped structurally by `dropUnknownSpeakers` — the same\n * unwrap/drop/sweep philosophy the slot-token and binding channels use.\n *\n * An unseen narrator gets NO speaker: a voice with no body is never a slot\n * (doctrine §5), so attribution here would resurrect the phantom-entity\n * defect that `stripOrphanSlots` exists to kill.\n */\n speakerSlot: z.string().optional(),\n /**\n * SPEECH ONLY — WHO says these words, by NAME.\n *\n * The second of two ways to name a speaker, and the one for documents that\n * have no slots: `speakerSlot` addresses an `EntitySlot` of THIS analysis by\n * id, while `speaker` is the plain cast name a production keys its own cast\n * by (\"Jack Mercer\"). A layer may legitimately carry both — the id for the\n * analysis it came from, the name for the document it is going into — and a\n * consumer that understands only one reads the one it understands.\n *\n * Optional, and not refined against `mode`, for the same reason\n * `speakerSlot` is not: the window schema is the enforced decode grammar and\n * must not throw away a whole roll over one mis-tagged field.\n *\n * NOT swept by `dropUnknownSpeakers`. That function is the SLOT channel's\n * sanitizer — it judges an id against the surviving slot list, and a name has\n * no id space to be unknown in. The asymmetry is deliberate and pinned by\n * test; whoever owns the name's vocabulary sanitizes the name.\n *\n * The residual that leaves: a layer can keep a `speaker` naming someone\n * `stripOrphanSlots` already pruned as a phantom, where the same claim spelled\n * `speakerSlot` would have been dropped — the invented-narrator defect, in the\n * one spelling the sweep cannot see. LATENT today, since nothing in this\n * repo emits `speaker`; the day the analyzer does, that sweep is what has to\n * grow, not this field.\n */\n speaker: z.string().optional(),\n})\nexport type AudioLayer = z.infer<typeof audioLayerSchema>\n\nconst windowSceneBase = z.object({\n startSec: z.number().min(0),\n endSec: z.number().min(0),\n label: z.string().min(1),\n shotType: z.string().min(1),\n camera: z.string(),\n /** Camera VIEWPOINT. Absent ⇒ eye-level. Keeps `camera` to pure MOVEMENT and\n * frees `shotType` to state the SIZE even on an over-the-shoulder or POV. */\n angle: z.enum(VIDEO_ANALYSIS_SHOT_ANGLES).optional(),\n /** Time manipulation. Absent ⇒ normal speed. */\n speed: z.enum(VIDEO_ANALYSIS_SPEED_EFFECTS).optional(),\n /** CHRONICLE TIME (2026-08-17) — see the consts' docstrings. Both optional:\n * absent on every pre-2.6.0 analysis, and legitimately absent when the\n * analyser cannot read the clock. Enum + optional keeps the window decode\n * grammar congruence-safe (no ints, no maxItems). */\n timeOfDay: z.enum(VIDEO_ANALYSIS_TIMES_OF_DAY).optional(),\n storyJump: z.enum(VIDEO_ANALYSIS_STORY_JUMPS).optional(),\n visual: z.string().min(1),\n /**\n * Text burned into the PICTURE of this shot — titles, captions, lower-thirds,\n * subtitles — verbatim, in its original script. Absent when the frame carries\n * none.\n *\n * Doctrine already asks for on-screen text inside `visual` prose, but a\n * recreation needs to know discretely whether to RENDER text at all, and\n * `translateOnScreenTextToEnglish` had no structured field to land in. It is\n * also the signal the auto-cast frame judge reads: picture text belonging to an\n * earlier scene's speech means the shot is replayed footage under a voice-over.\n */\n onScreenText: z.string().optional(),\n /** What the on-screen text IS. Meaningful only when `onScreenText` is non-empty. */\n onScreenTextKind: z.enum(VIDEO_ANALYSIS_TEXT_KINDS).optional(),\n /** Effects on this shot's PICTURE. Absent ⇒ a clean image. */\n effects: z.array(z.enum(VIDEO_ANALYSIS_VISUAL_EFFECTS)).optional(),\n transitionOut: z.enum(VIDEO_ANALYSIS_TRANSITIONS).optional(),\n // Round 4 (2026-08-30, recast shot craft rev 1.5 Appendix F.8): the edit into\n // the next scene in the analyser's OWN WORDS — a few words of what it saw\n // (\"fast blurred pan left\", \"fade to black\", \"zoom-blur warp into the tunnel\")\n // — or absent when the take continues through the change or no edit is seen\n // (nothing asserted: the video model decides from story and refs). The closed\n // `transitionOut` vocabulary above is LEGACY from here on: kept so stored\n // blueprints still parse, never emitted again. Readers take\n // `transition ?? transitionOut`.\n transition: z.string().trim().min(1).max(120).optional(),\n // Array of concurrent layers (music + speech + sfx together); [] = silence.\n audio: z.array(audioLayerSchema),\n /** slotId → variationId for slots wearing a NON-default look in this scene\n * (only slots referenced in the scene; absent key ⇒ the default look).\n * Rides windowSceneBase so BOTH the window layer and analyzedSceneSchema\n * inherit it — the out-of-band binding channel (no in-text markers, D6). */\n slotVariations: z.record(z.string(), z.string()).optional(),\n})\n// .strip() (default) drops model-emitted oversized/slotRefs — validator-computed only.\nconst windowSceneSchema = windowSceneBase.refine((s) => s.endSec > s.startSec, { message: \"endSec must be > startSec\" })\nexport type WindowScene = z.infer<typeof windowSceneSchema>\n\n/** What the MODEL emits per window (strict-JSON footer schema). scenes has NO min. */\nexport const windowAnalysisSchema = z.object({\n language: z.string().optional(),\n /** The clip-level look as read from THIS window. Merge folds the windows\n * field-by-field (first non-empty wins), like `language`. */\n look: clipLookSchema.optional(),\n /** The clip opens with a fade-in. Folded from window 0 only. */\n transitionIn: z.enum(VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN).optional(),\n slots: z.array(entitySlotSchema),\n scenes: z.array(windowSceneSchema),\n})\nexport type WindowAnalysis = z.infer<typeof windowAnalysisSchema>\n\nexport const analyzedSceneSchema = windowSceneBase.extend({\n sceneNumber: z.number().int().min(1),\n visualResolved: z.string().min(1),\n oversized: z.boolean().optional(),\n slotRefs: z.array(z.string()),\n}).refine((s) => s.endSec > s.startSec, { message: \"endSec must be > startSec\" })\nexport type AnalyzedScene = z.infer<typeof analyzedSceneSchema>\n\nexport const videoAnalysisResultSchema = z.object({\n meta: z.object({\n durationSec: z.number().positive(),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n aspectRatio: z.string(),\n title: z.string().optional(),\n language: z.string().optional(),\n }),\n /** Clip-level look, merged across windows. Deliberately a sibling of `meta`\n * rather than a member: `meta` is probed fact (ffprobe dimensions, probed\n * duration), while this is the model's reading of the photography. */\n look: clipLookSchema.optional(),\n /** The clip opens with a fade-in. Folded from window 0 only. */\n transitionIn: z.enum(VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN).optional(),\n slots: z.array(entitySlotSchema),\n scenes: z.array(analyzedSceneSchema).min(1),\n /** CAST VARIATIONS (§4 cap handling): looks the analyzer's merge FOLDED into\n * the default at VIDEO_ANALYSIS_MAX_VARIATIONS — recorded, never silent. In\n * the wire schema so strip-mode consumers (the recast client's validated\n * blueprint view) keep it: the §6 \"folded into default look\" note is the\n * user's only pre-pay defense against a wrong split. */\n variationFolds: z.array(z.object({\n slotId: z.string(),\n variationId: z.string(),\n label: z.string(),\n })).optional(),\n /**\n * Analyzer diagnostics for THIS result — things the analysis noticed about\n * itself that a reader should know before spending on regeneration.\n *\n * Added because there was previously no channel for them at all: the merge\n * layer has always produced a warnings list and the auto-cast pass has always\n * had findings, and every one of them died in a `console.warn` inside a worker\n * the user cannot see. So a run could quietly drop a duplicated line, fold a\n * cast look, or conclude a character is not the person their own description\n * names, and the result looked indistinguishable from a clean one.\n *\n * Prose, not codes, and deliberately so — these are read by a human deciding\n * whether to re-run, not branched on. Absent when there is nothing to report.\n */\n warnings: z.array(z.string()).optional(),\n})\nexport type VideoAnalysisResult = z.infer<typeof videoAnalysisResultSchema>\n\nexport function deriveSlotRefs(visual: string): string[] {\n const out: string[] = []\n for (const m of visual.matchAll(SLOT_TOKEN_RE)) if (!out.includes(m[1])) out.push(m[1])\n return out\n}\n\nexport function rewriteSlotTokens(visual: string, renames: Record<string, string>): string {\n return visual.replace(SLOT_TOKEN_RE, (whole, id: string) => (renames[id] ? `{slot:${renames[id]}}` : whole))\n}\n\n/** Unresolved tokens unwrap to their literal id text — never deleted (spec invariant). */\nexport function unwrapUnresolvedTokens(text: string, validIds: Set<string>): { text: string; unresolved: string[] } {\n const unresolved: string[] = []\n const out = text.replace(SLOT_TOKEN_RE, (whole, id: string) => {\n if (validIds.has(id)) return whole\n if (!unresolved.includes(id)) unresolved.push(id)\n return id\n })\n return { text: out, unresolved }\n}\n\n/**\n * Rewrite a scene's `slotVariations` after cross-window slot/variation\n * unification: slot keys map through `slotRenames`, then each variation value\n * maps through `variationRenames[<new slotId>]`. Absent renames pass through.\n */\nexport function rewriteSceneBindings(\n sv: Record<string, string> | undefined,\n slotRenames: Record<string, string>,\n variationRenames?: Record<string, Record<string, string>>,\n): Record<string, string> | undefined {\n if (!sv) return undefined\n const out: Record<string, string> = {}\n for (const [slotId, variationId] of Object.entries(sv)) {\n const newSlot = slotRenames[slotId] ?? slotId\n out[newSlot] = variationRenames?.[newSlot]?.[variationId] ?? variationId\n }\n return out\n}\n\n/**\n * Drop bindings whose (slotId, variationId) no longer exists after a merge —\n * the unwrap-rule mirror: never persist a dangling binding, and report what\n * was dropped so the caller can warn. `\"default\"` is always valid for a known\n * slot. `kept` is undefined when nothing survives (no `{}` materialization).\n */\nexport function dropUnknownBindings(\n sv: Record<string, string> | undefined,\n validBySlot: Map<string, Set<string>>,\n): { kept?: Record<string, string>; dropped: Array<{ slotId: string; variationId: string }> } {\n if (!sv) return { dropped: [] }\n const kept: Record<string, string> = {}\n const dropped: Array<{ slotId: string; variationId: string }> = []\n for (const [slotId, variationId] of Object.entries(sv)) {\n const valid = validBySlot.get(slotId)\n if (valid && (variationId === VIDEO_ANALYSIS_DEFAULT_VARIATION || valid.has(variationId))) kept[slotId] = variationId\n else dropped.push({ slotId, variationId })\n }\n return { kept: Object.keys(kept).length > 0 ? kept : undefined, dropped }\n}\n\n/**\n * Rewrite speech attribution after cross-window slot unification — the\n * `rewriteSceneBindings` counterpart for the `audio` channel. Slot unification\n * renames a loser id to its survivor and rewrites `{slot:…}` tokens and\n * variation bindings; an un-rewritten `speakerSlot` would be left pointing at an\n * id that no longer exists. Copy-on-write: returns the input array untouched\n * when no layer names a renamed slot.\n */\nexport function rewriteSpeakerSlots(audio: AudioLayer[], slotRenames: Record<string, string>): AudioLayer[] {\n if (!audio.some((a) => a.speakerSlot !== undefined && slotRenames[a.speakerSlot])) return audio\n return audio.map((a) => {\n const to = a.speakerSlot !== undefined ? slotRenames[a.speakerSlot] : undefined\n return to ? { ...a, speakerSlot: to } : a\n })\n}\n\n/**\n * Strip attribution that no scene can honour — the `dropUnknownBindings` mirror\n * for the `audio` channel. Two cases, both model sloppiness rather than errors\n * worth failing a roll over:\n * - a `speakerSlot` on any non-`speech` layer (nobody is speaking)\n * - a `speakerSlot` naming a slot that is not in the final list\n *\n * MUST run AFTER the orphan-slot sweep, and attribution must NEVER count as a\n * slot reference for that sweep: a slot reachable only as a speaker is a voice\n * with no body — precisely the invented-narrator entity doctrine §5 forbids. The\n * two passes compose to remove both the phantom slot and the dangling\n * attribution pointing at it.\n */\nexport function dropUnknownSpeakers(\n audio: AudioLayer[],\n validSlotIds: Set<string>,\n): { audio: AudioLayer[]; dropped: string[] } {\n const dropped: string[] = []\n const out = audio.map((a) => {\n if (a.speakerSlot === undefined) return a\n if (a.mode === \"speech\" && validSlotIds.has(a.speakerSlot)) return a\n dropped.push(a.speakerSlot)\n const { speakerSlot: _drop, ...rest } = a\n return rest\n })\n return { audio: dropped.length > 0 ? out : audio, dropped }\n}\n\n/**\n * Fold each window's reading of the clip look into one, FIELD BY FIELD: the first\n * window that had something to say about a field wins it.\n *\n * Per-field rather than first-window-wins-everything because the windows see\n * different footage — an opening window may read the grade confidently while only\n * a later one contains the shot that reveals the format. Mirrors how `language` is\n * resolved across windows rather than taken from window 0.\n *\n * Returns undefined when no window said anything, so an analysis with nothing to\n * report omits the field rather than shipping an empty object.\n */\nexport function mergeClipLook(looks: ReadonlyArray<ClipLook | undefined>): ClipLook | undefined {\n const out: Record<string, string> = {}\n for (const look of looks) {\n for (const [k, v] of Object.entries(look ?? {})) {\n if (typeof v === \"string\" && v.trim() && !out[k]) out[k] = v.trim()\n }\n }\n return Object.keys(out).length > 0 ? (out as ClipLook) : undefined\n}\n\n/** Substitute {slot:x}: castMap binding wins, else the slot's description, else literal id. */\nexport function renderAnalyzedScene(scene: { visual: string }, slots: EntitySlot[], castMap?: Record<string, string>): string {\n const byId = new Map(slots.map((s) => [s.slotId, s]))\n return scene.visual.replace(SLOT_TOKEN_RE, (_whole, id: string) => castMap?.[id] ?? byId.get(id)?.description ?? id)\n}\n\n/**\n * Float slack for the oversize comparison.\n *\n * Scene boundaries arrive as decimal seconds and the duration is derived by\n * SUBTRACTING two of them, which does not land on the cap exactly: a real job\n * produced a 12.67 → 20.67 scene whose computed length is 8.000000000000002,\n * so a scene sitting precisely ON the 8s cap was flagged oversized and carried\n * a `oversized: true` defect marker downstream for no reason.\n *\n * A microsecond is orders of magnitude below any boundary precision the\n * analyzer can actually resolve (windows land on ~0.01s at best), so this can\n * never mask a genuinely oversized scene — the smallest real overshoot is\n * still ~10000x larger than the tolerance.\n */\nconst OVERSIZE_TOLERANCE_SEC = 1e-6\n\nexport function isOversizedScene(startSec: number, endSec: number): boolean {\n return endSec - startSec > VIDEO_ANALYSIS_MAX_SCENE_SEC + OVERSIZE_TOLERANCE_SEC\n}\n\nconst STANDARD_RATIOS: Array<[string, number]> = [\n [\"16:9\", 16 / 9], [\"9:16\", 9 / 16], [\"1:1\", 1], [\"4:3\", 4 / 3], [\"3:4\", 3 / 4], [\"21:9\", 21 / 9],\n]\nexport function aspectRatioFromDims(w: number, h: number): string {\n const r = w / h\n for (const [label, v] of STANDARD_RATIOS) if (Math.abs(r - v) / v < 0.03) return label\n const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b))\n const g = gcd(Math.round(w), Math.round(h))\n return `${Math.round(w) / g}:${Math.round(h) / g}`\n}\n\n/** Sung-vocal evidence in a music layer's gen-ready description. Word-bounded\n * and deliberately WITHOUT bare \"song\"/\"music\" (an instrumental bed is\n * routinely described as a \"pop song\"). Quoted text of some length inside a\n * music layer counts too — analysers quote lyrics. */\nconst MUSIC_VOCAL_RE = /\\b(?:lyrics?|sung|sings?|singing|vocals?|chorus|verse|rap(?:ping|ped)?|a cappella)\\b/i\nconst MUSIC_VOCAL_QUOTE_RE = /[\"\\u201c][^\"\\u201d]{6,}[\"\\u201d]/\n/** Negated-vocal phrasing — a layer matching this contributes NO vocal\n * evidence (it does not veto other layers). */\nconst MUSIC_NO_VOCAL_RE = /\\b(?:no|without|non)[- ](?:vocals?|lyrics?|singing)\\b|\\binstrumental\\b|\\bwordless\\b/i\n\n/**\n * MUSIC-VIDEO INFERENCE (2026-08-17): is this clip a music video — one whose\n * soundtrack IS the content, to be taken as-is with no stem separation?\n *\n * Lives in SHARED because two sides must agree BYTE-FOR-BYTE on the answer:\n * the recast route derives `music.mode` from it server-side, and the client\n * both prices the original-audio prep and GUARDS on the server's derived mode\n * at generate time — two hand-written copies of this heuristic would drift\n * into that guard firing on honest runs. Deterministic, throw-proof on any\n * malformed analysis (absent fields ⇒ false).\n *\n * The rule is conservative toward FALSE (a false positive keeps unwanted\n * dialogue in the render; a false negative merely runs the separation, which\n * was yesterday's default): at least 4 scenes, at least 80% of scenes carry a\n * music layer, and at least one music layer carries sung-vocal evidence that\n * is not negated (\"instrumental\", \"no vocals\").\n *\n * An EXPLICIT analyze-time flag always wins — callers use\n * `flag === true || inferMusicVideo(analysis)` and never let a cached false\n * suppress the inference (the flag can only ever be set true; false means\n * \"unset\", not \"denied\").\n */\nexport function inferMusicVideo(analysis: {\n scenes?: ReadonlyArray<{ audio?: ReadonlyArray<{ mode?: string; content?: string }> }>\n} | undefined | null): boolean {\n const scenes = analysis?.scenes ?? []\n if (scenes.length < 4) return false\n const musicLayers = (sc: (typeof scenes)[number]) => (sc.audio ?? []).filter((a) => a?.mode === \"music\")\n const withMusic = scenes.filter((sc) => musicLayers(sc).length > 0).length\n if (withMusic / scenes.length < 0.8) return false\n return scenes.some((sc) =>\n musicLayers(sc).some((a) => {\n const content = typeof a.content === \"string\" ? a.content : \"\"\n if (MUSIC_NO_VOCAL_RE.test(content)) return false\n return MUSIC_VOCAL_RE.test(content) || MUSIC_VOCAL_QUOTE_RE.test(content)\n }),\n )\n}\n\n// ---------------------------------------------------------------------------\n// The analysis as a BRIEF — the compact projection an LLM is handed\n// ---------------------------------------------------------------------------\n\n/** Top-level keys the analyzer derives AFTER the model's pass (merge\n * diagnostics, folded cast looks). A reader drafting FROM the analysis — a\n * production plan, a script — needs none of them. */\nconst DERIVED_ANALYSIS_TOP_KEYS: ReadonlySet<string> = new Set([\"warnings\", \"variationFolds\"])\n\n/** Per-scene keys the validator computes from `visual` and the slot list. */\nconst DERIVED_ANALYSIS_SCENE_KEYS: ReadonlySet<string> = new Set([\"visualResolved\", \"slotRefs\", \"oversized\"])\n\nconst asRecord = (v: unknown): Record<string, unknown> | null =>\n typeof v === \"object\" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null\n\n/**\n * The analysis with its server-derived fields removed — the form an LLM is\n * handed when the analysis IS the brief (Nodaro Studio's Director and its\n * job-id loader). Drops `warnings` and `variationFolds` at the top and\n * `visualResolved`, `slotRefs`, `oversized` on every scene; keeps\n * `refImageUrl` (a downstream cast image) and everything else. Never mutates;\n * a non-object input comes back as-is.\n *\n * ONE strip list, shared by the worker that composes the brief server-side\n * (`llm-structured` jobs with a `videoUrl`) and the client that loads a\n * finished analysis into a textarea, so the two can never drift.\n */\nexport function stripDerivedAnalysisFields(json: unknown): unknown {\n const doc = asRecord(json)\n if (!doc) return json\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(doc)) {\n if (DERIVED_ANALYSIS_TOP_KEYS.has(key)) continue\n out[key] =\n key === \"scenes\" && Array.isArray(value)\n ? value.map((scene) => {\n const s = asRecord(scene)\n if (!s) return scene\n return Object.fromEntries(Object.entries(s).filter(([k]) => !DERIVED_ANALYSIS_SCENE_KEYS.has(k)))\n })\n : value\n }\n return out\n}\n","/**\n * Real output canvases per (video model, resolution, aspect ratio).\n *\n * Every entry is a pixel size read off a finished render with ffprobe — the\n * geometry a model hands back, never a rate or a price. None of it is\n * arithmetic either, because the providers do not follow arithmetic:\n *\n * - minimax-h3 at 768P returns 768x1344 (0.5714) for a 9:16 request,\n * - seedance-2 at 480p 16:9 returns 864x496 (1.742) while seedance-2-5\n * returns 854x480 (1.778) for the same request,\n * - grok returns 736x400 (1.84), seedance 1.0 at 1080p 1:1 returns 1440x1440.\n *\n * A formula would get all four wrong, which is why `resolveOutputCanvas`\n * answers `undefined` for anything not measured: callers must then leave the\n * frame alone rather than invent geometry (see `computeFrameFitPlan`).\n *\n * HOW TO EXTEND: run `node tools/harvest-output-canvas.mjs` (it pages the admin\n * jobs API, groups completed video jobs by provider/resolution/aspect and probes\n * real outputs) and paste new rows here. Take rows from REFERENCE or\n * TEXT-TO-VIDEO jobs only: in frame mode the adaptive models (the seedance and\n * wan families) size the output from the INPUT image, so those rows describe the\n * input that was sent, not the canvas the model would choose on its own.\n *\n * Seeded 2026-09-16 from 3000 completed production jobs.\n */\n\n/** `[width, height]` in pixels. */\nexport type VideoOutputCanvas = readonly [number, number]\n\n/** provider → resolution (lower-cased) → aspect token → canvas. */\nexport const VIDEO_OUTPUT_CANVAS: Readonly<\n Record<string, Readonly<Record<string, Readonly<Record<string, VideoOutputCanvas>>>>>\n> = {\n \"seedance-2-5\": {\n \"480p\": { \"16:9\": [854, 480], \"9:16\": [480, 854] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280], \"1:1\": [960, 960] },\n \"1080p\": { \"16:9\": [1920, 1080] },\n },\n // The 2.0 family is NOT the same as 2.5 at 480p — 864x496 vs 854x480.\n \"seedance-2\": {\n \"480p\": { \"16:9\": [864, 496], \"9:16\": [496, 864] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"seedance-2-fast\": {\n \"480p\": { \"16:9\": [864, 496], \"9:16\": [496, 864] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"seedance-2-mini\": {\n \"480p\": { \"16:9\": [864, 496], \"9:16\": [496, 864] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"gemini-omni-video\": {\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n \"1080p\": { \"16:9\": [1920, 1080] },\n },\n \"gemini-omni-flash\": {\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"veo3.1\": {\n \"720p\": { \"9:16\": [720, 1280] },\n \"1080p\": { \"16:9\": [1920, 1080] },\n },\n \"wan-3\": {\n \"480p\": { \"16:9\": [832, 480] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"wan-3-prime\": {\n \"720p\": { \"16:9\": [1280, 720] },\n },\n // 768P's \"9:16\" is 0.5714, not 0.5625 — the single clearest reason this table\n // exists.\n \"minimax-h3\": {\n \"768p\": { \"9:16\": [768, 1344] },\n \"2k\": { \"16:9\": [2560, 1440], \"9:16\": [1440, 2560] },\n },\n seedance: {\n \"1080p\": {\n \"16:9\": [1920, 1080],\n \"9:16\": [1080, 1920],\n \"1:1\": [1440, 1440],\n \"3:4\": [1248, 1664],\n },\n },\n}\n\n/**\n * The canvas a model renders for this request, or `undefined` when we have never\n * measured that combination. `undefined` means \"leave the frame alone\".\n *\n * Resolution matching is case-insensitive (`768P`, `2K`, `720p` all appear in\n * the wild). An aspect of `adaptive` / `Auto` has no canvas of its own — the\n * caller resolves it to a concrete ratio first (`resolveFrameFitAspect`).\n */\nexport function resolveOutputCanvas(\n provider: string | undefined,\n resolution: string | undefined,\n aspect: string | undefined,\n): VideoOutputCanvas | undefined {\n if (!provider || !resolution || !aspect) return undefined\n return VIDEO_OUTPUT_CANVAS[provider]?.[resolution.toLowerCase()]?.[aspect]\n}\n\n/** Every measured combination, for tests and for the harvest script's diff. */\nexport function measuredCanvasCombinations(): Array<{\n provider: string\n resolution: string\n aspect: string\n canvas: VideoOutputCanvas\n}> {\n const out: Array<{ provider: string; resolution: string; aspect: string; canvas: VideoOutputCanvas }> = []\n for (const [provider, byResolution] of Object.entries(VIDEO_OUTPUT_CANVAS)) {\n for (const [resolution, byAspect] of Object.entries(byResolution)) {\n for (const [aspect, canvas] of Object.entries(byAspect)) {\n out.push({ provider, resolution, aspect, canvas })\n }\n }\n }\n return out\n}\n","/**\n * START/END FRAME FIT — the pure geometry half.\n *\n * WHY THIS EXISTS (measured on ~40 production renders, 2026-09-16):\n * a start frame whose pixel size is not the model's own output canvas gets\n * reshaped by the provider, and Seedance 2.5 does it VISIBLY — frame 0 is the\n * user's image verbatim, then from frame 1 the generated frames are rescaled\n * ~2% on ONE axis (x1.000 y1.02). Five of ten runs with a 940x1672 image\n * snapped; three of three with the same image resized to 720x1280 did not.\n *\n * So: reshape the frame ourselves, to the size the model was going to render\n * anyway. The canvas comes from measurement (`video-output-canvas.ts`), never\n * from arithmetic, and when a combination has never been measured the fit\n * DEGRADES rather than guesses.\n *\n * This module is pure — no I/O, no sharp, no network. `prepareVideoFrames` in\n * the backend does the pixels and the upload.\n */\nimport { getModel } from \"./model-catalog.js\"\nimport { resolveOutputCanvas, type VideoOutputCanvas } from \"./video-output-canvas.js\"\n\n/** How much of the frame we are allowed to reshape. */\nexport const FRAME_FITS = [\"original\", \"ratio\", \"resolution\"] as const\nexport type FrameFit = (typeof FRAME_FITS)[number]\n\n/** `resolution` — the measured canvas — is the default everywhere. */\nexport const DEFAULT_FRAME_FIT: FrameFit = \"resolution\"\n\n/** How the frame is handed to the model. */\nexport const FRAME_DELIVERIES = [\"auto\", \"frame\", \"reference\"] as const\nexport type FrameDelivery = (typeof FRAME_DELIVERIES)[number]\n\nexport const DEFAULT_FRAME_DELIVERY: FrameDelivery = \"auto\"\n\n/**\n * Stretching an image to a ratio it is nowhere near would squash the subject,\n * so past this gap the frame is centre-cropped to the target ratio FIRST and\n * only then resized. 5% covers every \"1K image into a 720p canvas\" case we\n * measured (940x1672 into 9:16 is a 0.05% gap) while refusing to squash a\n * square photo into 9:16 (a 78% gap).\n */\nexport const FRAME_FIT_STRETCH_TOLERANCE = 0.05\n\n/**\n * Models whose frame mode is measurably worse than reference delivery.\n *\n * The Seedance 2.0 family crop-zooms the frame 2% and drifts 11-26% darker\n * within six frames in frame mode; delivered as a reference with the opening-\n * frame sentence, the same models hold a flat look from frame 0 and keep the\n * image's true geometry. Every OTHER model measured (Seedance 2.5, Gemini Omni\n * video + flash, Veo 3.1, Wan 3.0, Minimax H3) reproduces the opening frame\n * better in frame mode, so the default stays `frame` for anything absent here.\n */\nexport const FRAME_DELIVERY_BY_PROVIDER: Readonly<Record<string, Exclude<FrameDelivery, \"auto\">>> = {\n \"seedance-2\": \"reference\",\n \"seedance-2-fast\": \"reference\",\n \"seedance-2-mini\": \"reference\",\n}\n\n/** Aspect tokens that name no concrete shape — the model picks. */\nconst OPEN_ASPECT_TOKENS = new Set([\"adaptive\", \"auto\"])\n\n/** `\"16:9\"` → 1.777…; anything unparseable → `undefined`. */\nexport function parseAspectToken(token: string | undefined): number | undefined {\n if (!token) return undefined\n const m = /^(\\d+(?:\\.\\d+)?)\\s*[:x/]\\s*(\\d+(?:\\.\\d+)?)$/.exec(token.trim())\n if (!m) return undefined\n const w = Number(m[1]); const h = Number(m[2])\n if (!(w > 0) || !(h > 0)) return undefined\n return w / h\n}\n\n/**\n * The aspect the fit should target.\n *\n * An explicit ratio is used as-is. `adaptive` / `Auto` (and an absent value,\n * which the seedance family sends as adaptive whenever a frame is present) has\n * no shape of its own: the provider will follow the IMAGE, so we snap the\n * image's own ratio to the nearest one the model lists and target that. A model\n * with no declared ratio list and an open token gives `undefined` — no fit.\n */\nexport function resolveFrameFitAspect(args: {\n provider: string | undefined\n requestedAspect: string | undefined\n sourceWidth: number\n sourceHeight: number\n}): string | undefined {\n const requested = args.requestedAspect?.trim()\n if (requested && !OPEN_ASPECT_TOKENS.has(requested.toLowerCase())) return requested\n const ratios = args.provider ? getModel(args.provider)?.aspectRatios : undefined\n if (!ratios?.length || !(args.sourceWidth > 0) || !(args.sourceHeight > 0)) return undefined\n const source = args.sourceWidth / args.sourceHeight\n let best: { token: string; gap: number } | undefined\n for (const token of ratios) {\n const value = parseAspectToken(token)\n if (value === undefined) continue // skips \"adaptive\"/\"Auto\" members\n const gap = Math.abs(Math.log(value / source))\n if (!best || gap < best.gap) best = { token, gap }\n }\n return best?.token\n}\n\n/** What `prepareVideoFrames` should do to one frame. `null` = nothing. */\nexport interface FrameFitPlan {\n /** Final pixel size to produce. */\n readonly width: number\n readonly height: number\n /** Centre-crop applied BEFORE the resize (only past the stretch tolerance). */\n readonly crop?: { readonly left: number; readonly top: number; readonly width: number; readonly height: number }\n /** Why the plan exists — carried into logs and job output for traceability. */\n readonly reason: \"resolution\" | \"ratio\"\n}\n\n/** Round to an even number ≥ 2 — odd dimensions break yuv420p encoders. */\nfunction even(value: number): number {\n return Math.max(2, Math.round(value / 2) * 2)\n}\n\n/**\n * The smallest change that makes `width x height` exactly `aspect`: keep the\n * longer side, move the shorter one. Rounding to even can leave a sub-pixel\n * residue, which is why the caller compares ratios with a tolerance rather than\n * for equality.\n */\nexport function minimalRatioDimensions(width: number, height: number, aspect: number): { width: number; height: number } {\n const current = width / height\n if (current > aspect) {\n // too wide → bring the height up (keep the long side, the width)\n return { width: even(width), height: even(width / aspect) }\n }\n return { width: even(height * aspect), height: even(height) }\n}\n\n/**\n * The centre-crop that turns `width x height` into exactly `aspect`, dropping\n * the overhang on the long axis.\n */\nexport function centreCropToAspect(width: number, height: number, aspect: number): { left: number; top: number; width: number; height: number } {\n const current = width / height\n if (current > aspect) {\n const w = even(height * aspect)\n return { left: Math.max(0, Math.round((width - w) / 2)), top: 0, width: Math.min(width, w), height }\n }\n const h = even(width / aspect)\n return { left: 0, top: Math.max(0, Math.round((height - h) / 2)), width, height: Math.min(height, h) }\n}\n\n/**\n * Turn a request into a concrete plan for ONE frame, or `null` when the frame\n * should be sent untouched.\n *\n * Degradation ladder — a missing measurement must never invent geometry:\n * `resolution` with no measured canvas → behaves as `ratio`\n * `ratio` with no resolvable aspect → no fit\n * any fit whose target equals the source (within a pixel) → no fit\n */\nexport function computeFrameFitPlan(args: {\n fit: FrameFit\n provider: string | undefined\n resolution: string | undefined\n /** The aspect as the request carries it: a ratio, `adaptive`/`Auto`, or absent. */\n aspect: string | undefined\n sourceWidth: number\n sourceHeight: number\n /** Overrides the measured table (tests, and a caller that already looked up). */\n canvas?: VideoOutputCanvas\n tolerance?: number\n}): FrameFitPlan | null {\n const { fit, sourceWidth, sourceHeight } = args\n if (fit === \"original\") return null\n if (!(sourceWidth > 0) || !(sourceHeight > 0)) return null\n\n const aspectToken = resolveFrameFitAspect({\n provider: args.provider,\n requestedAspect: args.aspect,\n sourceWidth,\n sourceHeight,\n })\n\n const canvas = fit === \"resolution\"\n ? args.canvas ?? resolveOutputCanvas(args.provider, args.resolution, aspectToken)\n : undefined\n\n const targetAspect = canvas ? canvas[0] / canvas[1] : parseAspectToken(aspectToken)\n if (targetAspect === undefined || !(targetAspect > 0)) return null\n\n const sourceAspect = sourceWidth / sourceHeight\n const gap = Math.abs(sourceAspect - targetAspect) / targetAspect\n const tolerance = args.tolerance ?? FRAME_FIT_STRETCH_TOLERANCE\n const crop = gap > tolerance ? centreCropToAspect(sourceWidth, sourceHeight, targetAspect) : undefined\n\n const target = canvas\n ? { width: canvas[0], height: canvas[1] }\n : minimalRatioDimensions(\n crop ? crop.width : sourceWidth,\n crop ? crop.height : sourceHeight,\n targetAspect,\n )\n\n const unchanged = target.width === sourceWidth && target.height === sourceHeight && !crop\n if (unchanged) return null\n\n return {\n width: target.width,\n height: target.height,\n ...(crop ? { crop } : {}),\n reason: canvas ? \"resolution\" : \"ratio\",\n }\n}\n\n/**\n * Frame or reference? `auto` reads the per-provider default measured above.\n * Reference delivery is only possible on models that accept reference images —\n * on the others `reference` collapses back to `frame` rather than dropping the\n * frame on the floor.\n */\nexport function resolveFrameDelivery(args: {\n provider: string | undefined\n requested: FrameDelivery | undefined\n supportsReferenceImages: boolean\n}): Exclude<FrameDelivery, \"auto\"> {\n const requested = args.requested ?? DEFAULT_FRAME_DELIVERY\n const wanted = requested === \"auto\"\n ? (args.provider ? FRAME_DELIVERY_BY_PROVIDER[args.provider] ?? \"frame\" : \"frame\")\n : requested\n if (wanted === \"reference\" && !args.supportsReferenceImages) return \"frame\"\n return wanted\n}\n"]}