@nodaro/shared 3.69.0 → 3.71.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 (198) hide show
  1. package/dist/{chunk-25C2E2GI.cjs → chunk-4A3ITJJB.cjs} +6 -6
  2. package/dist/{chunk-25C2E2GI.cjs.map → chunk-4A3ITJJB.cjs.map} +1 -1
  3. package/dist/{chunk-5EQRIUGI.cjs → chunk-4HV3LY4A.cjs} +78 -78
  4. package/dist/chunk-4HV3LY4A.cjs.map +1 -0
  5. package/dist/{chunk-PERUFUVH.cjs → chunk-5B337MCI.cjs} +15 -15
  6. package/dist/{chunk-PERUFUVH.cjs.map → chunk-5B337MCI.cjs.map} +1 -1
  7. package/dist/{chunk-7EQJIGVT.js → chunk-6FUVGATF.js} +3 -3
  8. package/dist/{chunk-7EQJIGVT.js.map → chunk-6FUVGATF.js.map} +1 -1
  9. package/dist/{chunk-WML66SUV.cjs → chunk-6PEWM2B3.cjs} +18 -18
  10. package/dist/{chunk-WML66SUV.cjs.map → chunk-6PEWM2B3.cjs.map} +1 -1
  11. package/dist/{chunk-KLEKJUQI.js → chunk-BO6IKV24.js} +5 -5
  12. package/dist/{chunk-KLEKJUQI.js.map → chunk-BO6IKV24.js.map} +1 -1
  13. package/dist/{chunk-KSHAAPQF.cjs → chunk-BOCHNFDU.cjs} +4 -4
  14. package/dist/chunk-BOCHNFDU.cjs.map +1 -0
  15. package/dist/{chunk-AH6OQXLW.js → chunk-BQV6NV7E.js} +3 -3
  16. package/dist/{chunk-AH6OQXLW.js.map → chunk-BQV6NV7E.js.map} +1 -1
  17. package/dist/{chunk-BDW25A7Y.js → chunk-BVP4M5AK.js} +247 -11
  18. package/dist/chunk-BVP4M5AK.js.map +1 -0
  19. package/dist/{chunk-ML55U7WM.js → chunk-C2UHX7OF.js} +3 -3
  20. package/dist/{chunk-ML55U7WM.js.map → chunk-C2UHX7OF.js.map} +1 -1
  21. package/dist/{chunk-Q2LEJXLZ.cjs → chunk-C32IL6RD.cjs} +2 -2
  22. package/dist/{chunk-Q2LEJXLZ.cjs.map → chunk-C32IL6RD.cjs.map} +1 -1
  23. package/dist/{chunk-5WHU7CYE.js → chunk-CL7ECTK2.js} +52 -7
  24. package/dist/chunk-CL7ECTK2.js.map +1 -0
  25. package/dist/{chunk-FUYBUT65.js → chunk-COA2OJIH.js} +51 -28
  26. package/dist/chunk-COA2OJIH.js.map +1 -0
  27. package/dist/{chunk-PLANUXQL.cjs → chunk-CV2BEK52.cjs} +25 -3
  28. package/dist/chunk-CV2BEK52.cjs.map +1 -0
  29. package/dist/{chunk-HW6TLOK4.cjs → chunk-DRPHRE4J.cjs} +2 -2
  30. package/dist/{chunk-HW6TLOK4.cjs.map → chunk-DRPHRE4J.cjs.map} +1 -1
  31. package/dist/{chunk-LZPG4XHT.js → chunk-F3XG5J5V.js} +3 -3
  32. package/dist/{chunk-LZPG4XHT.js.map → chunk-F3XG5J5V.js.map} +1 -1
  33. package/dist/{chunk-I6TBKTW3.cjs → chunk-H52P7DD2.cjs} +73 -73
  34. package/dist/{chunk-I6TBKTW3.cjs.map → chunk-H52P7DD2.cjs.map} +1 -1
  35. package/dist/{chunk-AGIG5HUU.cjs → chunk-HUCGHMOI.cjs} +17 -17
  36. package/dist/{chunk-AGIG5HUU.cjs.map → chunk-HUCGHMOI.cjs.map} +1 -1
  37. package/dist/{chunk-3AB3YIFM.cjs → chunk-I4C6ZYU4.cjs} +6 -6
  38. package/dist/{chunk-3AB3YIFM.cjs.map → chunk-I4C6ZYU4.cjs.map} +1 -1
  39. package/dist/{chunk-UVUHVY7F.js → chunk-JCYTTTM2.js} +2 -2
  40. package/dist/{chunk-UVUHVY7F.js.map → chunk-JCYTTTM2.js.map} +1 -1
  41. package/dist/{chunk-7OSUEYZ4.js → chunk-JPSKVBYB.js} +3 -3
  42. package/dist/{chunk-7OSUEYZ4.js.map → chunk-JPSKVBYB.js.map} +1 -1
  43. package/dist/{chunk-TAPBDT47.js → chunk-JVYDKXGY.js} +4 -4
  44. package/dist/{chunk-TAPBDT47.js.map → chunk-JVYDKXGY.js.map} +1 -1
  45. package/dist/{chunk-YT4ZTJVC.js → chunk-K2P7KOIT.js} +11 -11
  46. package/dist/{chunk-YT4ZTJVC.js.map → chunk-K2P7KOIT.js.map} +1 -1
  47. package/dist/{chunk-YVQFYW2U.js → chunk-K3YGI5IW.js} +25 -4
  48. package/dist/chunk-K3YGI5IW.js.map +1 -0
  49. package/dist/{chunk-4IMEJQVQ.cjs → chunk-K5WRF2F3.cjs} +4 -4
  50. package/dist/{chunk-4IMEJQVQ.cjs.map → chunk-K5WRF2F3.cjs.map} +1 -1
  51. package/dist/{chunk-TDU45K6Z.js → chunk-KD4UUCMW.js} +5 -5
  52. package/dist/{chunk-TDU45K6Z.js.map → chunk-KD4UUCMW.js.map} +1 -1
  53. package/dist/{chunk-UJREE6EQ.cjs → chunk-LBKMQAXD.cjs} +9 -9
  54. package/dist/{chunk-UJREE6EQ.cjs.map → chunk-LBKMQAXD.cjs.map} +1 -1
  55. package/dist/{chunk-XZYZYWKG.cjs → chunk-MI4WEFJ4.cjs} +21 -21
  56. package/dist/{chunk-XZYZYWKG.cjs.map → chunk-MI4WEFJ4.cjs.map} +1 -1
  57. package/dist/{chunk-RURPG6IS.cjs → chunk-MN7BUGXF.cjs} +7 -7
  58. package/dist/{chunk-RURPG6IS.cjs.map → chunk-MN7BUGXF.cjs.map} +1 -1
  59. package/dist/{chunk-54E2JO4E.cjs → chunk-NNCHSLFD.cjs} +309 -26
  60. package/dist/chunk-NNCHSLFD.cjs.map +1 -0
  61. package/dist/{chunk-6Q4BS6AR.js → chunk-NT3ZFUNJ.js} +31 -3
  62. package/dist/chunk-NT3ZFUNJ.js.map +1 -0
  63. package/dist/{chunk-G6AOKNAY.js → chunk-PPXUSZJU.js} +3 -3
  64. package/dist/{chunk-G6AOKNAY.js.map → chunk-PPXUSZJU.js.map} +1 -1
  65. package/dist/{chunk-6QJHSN6J.cjs → chunk-QCGSL4CJ.cjs} +4 -4
  66. package/dist/{chunk-6QJHSN6J.cjs.map → chunk-QCGSL4CJ.cjs.map} +1 -1
  67. package/dist/{chunk-DE55SA2X.js → chunk-QME5O4NG.js} +8 -6
  68. package/dist/chunk-QME5O4NG.js.map +1 -0
  69. package/dist/{chunk-KL6GAYTT.js → chunk-S6DXSQCV.js} +5 -3
  70. package/dist/chunk-S6DXSQCV.js.map +1 -0
  71. package/dist/{chunk-LSX2OFNB.js → chunk-SAOIGWA2.js} +3 -3
  72. package/dist/{chunk-LSX2OFNB.js.map → chunk-SAOIGWA2.js.map} +1 -1
  73. package/dist/{chunk-PHQVAPSD.js → chunk-SHSDGAI4.js} +29 -17
  74. package/dist/chunk-SHSDGAI4.js.map +1 -0
  75. package/dist/{chunk-QNPYYSLT.cjs → chunk-SR7WH4FX.cjs} +33 -33
  76. package/dist/{chunk-QNPYYSLT.cjs.map → chunk-SR7WH4FX.cjs.map} +1 -1
  77. package/dist/{chunk-OZA4DE23.js → chunk-SZ7ALYPK.js} +3 -3
  78. package/dist/{chunk-OZA4DE23.js.map → chunk-SZ7ALYPK.js.map} +1 -1
  79. package/dist/{chunk-DNWFFVC6.js → chunk-T4YYUI5Q.js} +3 -3
  80. package/dist/{chunk-DNWFFVC6.js.map → chunk-T4YYUI5Q.js.map} +1 -1
  81. package/dist/{chunk-ZWEVRMFN.cjs → chunk-TOYWEF6E.cjs} +51 -28
  82. package/dist/chunk-TOYWEF6E.cjs.map +1 -0
  83. package/dist/{chunk-V24EPI5N.cjs → chunk-U4DIGIC3.cjs} +5 -3
  84. package/dist/chunk-U4DIGIC3.cjs.map +1 -0
  85. package/dist/{chunk-NTCSXKZ3.cjs → chunk-U6APV2PO.cjs} +5 -5
  86. package/dist/{chunk-NTCSXKZ3.cjs.map → chunk-U6APV2PO.cjs.map} +1 -1
  87. package/dist/{chunk-7PC2YHBN.cjs → chunk-UJIPIVTB.cjs} +48 -48
  88. package/dist/{chunk-7PC2YHBN.cjs.map → chunk-UJIPIVTB.cjs.map} +1 -1
  89. package/dist/{chunk-H5KHWTAE.js → chunk-UY6QZX7H.js} +4 -4
  90. package/dist/chunk-UY6QZX7H.js.map +1 -0
  91. package/dist/{chunk-DBD4BCGH.cjs → chunk-VDFQKLDG.cjs} +33 -2
  92. package/dist/chunk-VDFQKLDG.cjs.map +1 -0
  93. package/dist/{chunk-OEOOXL3F.js → chunk-VZIMLPDC.js} +5 -5
  94. package/dist/chunk-VZIMLPDC.js.map +1 -0
  95. package/dist/{chunk-TWUFC32F.cjs → chunk-W4CJ2P3F.cjs} +8 -8
  96. package/dist/{chunk-TWUFC32F.cjs.map → chunk-W4CJ2P3F.cjs.map} +1 -1
  97. package/dist/{chunk-HP3YIWNJ.js → chunk-WARGPM7P.js} +2 -2
  98. package/dist/{chunk-HP3YIWNJ.js.map → chunk-WARGPM7P.js.map} +1 -1
  99. package/dist/{chunk-3OHRFSQL.cjs → chunk-WHK3HTFY.cjs} +73 -60
  100. package/dist/chunk-WHK3HTFY.cjs.map +1 -0
  101. package/dist/{chunk-5ZCZL73I.js → chunk-X3YRSRHP.js} +3 -3
  102. package/dist/{chunk-5ZCZL73I.js.map → chunk-X3YRSRHP.js.map} +1 -1
  103. package/dist/{chunk-OOUJZR4K.js → chunk-XK75VOEH.js} +5 -5
  104. package/dist/{chunk-OOUJZR4K.js.map → chunk-XK75VOEH.js.map} +1 -1
  105. package/dist/{chunk-LY6IR5LL.cjs → chunk-YHZUTPZL.cjs} +26 -24
  106. package/dist/{chunk-DE55SA2X.js.map → chunk-YHZUTPZL.cjs.map} +1 -1
  107. package/dist/{chunk-MGSGLRHZ.cjs → chunk-ZJQ2L3MI.cjs} +72 -11
  108. package/dist/chunk-ZJQ2L3MI.cjs.map +1 -0
  109. package/dist/entries/apps.cjs +43 -43
  110. package/dist/entries/apps.js +8 -8
  111. package/dist/entries/credits.cjs +426 -238
  112. package/dist/entries/credits.d.cts +277 -1
  113. package/dist/entries/credits.d.ts +277 -1
  114. package/dist/entries/credits.js +11 -11
  115. package/dist/entries/edl.cjs +60 -60
  116. package/dist/entries/edl.d.cts +96 -1
  117. package/dist/entries/edl.d.ts +96 -1
  118. package/dist/entries/edl.js +1 -1
  119. package/dist/entries/llm-models.cjs +76 -72
  120. package/dist/entries/llm-models.d.cts +38 -4
  121. package/dist/entries/llm-models.d.ts +38 -4
  122. package/dist/entries/llm-models.js +2 -2
  123. package/dist/entries/media.cjs +87 -87
  124. package/dist/entries/media.js +1 -1
  125. package/dist/entries/model-catalog.cjs +133 -133
  126. package/dist/entries/model-catalog.js +4 -4
  127. package/dist/entries/models.cjs +431 -415
  128. package/dist/entries/models.d.cts +62 -27
  129. package/dist/entries/models.d.ts +62 -27
  130. package/dist/entries/models.js +7 -7
  131. package/dist/entries/nodes.cjs +215 -215
  132. package/dist/entries/nodes.js +11 -11
  133. package/dist/entries/pipeline.cjs +153 -153
  134. package/dist/entries/pipeline.js +3 -3
  135. package/dist/entries/social.cjs +241 -177
  136. package/dist/entries/social.d.cts +189 -6
  137. package/dist/entries/social.d.ts +189 -6
  138. package/dist/entries/social.js +2 -2
  139. package/dist/entries/ugc.cjs +71 -71
  140. package/dist/entries/ugc.js +4 -4
  141. package/dist/entries/video.cjs +153 -153
  142. package/dist/entries/video.js +7 -7
  143. package/dist/entries/workflow.cjs +152 -152
  144. package/dist/entries/workflow.js +4 -4
  145. package/dist/index.cjs +2203 -1931
  146. package/dist/index.d.cts +5 -5
  147. package/dist/index.d.ts +5 -5
  148. package/dist/index.js +27 -27
  149. package/package.json +1 -1
  150. package/src/__tests__/audio-isolation-pricing.test.ts +49 -0
  151. package/src/__tests__/cast-swap-limits.test.ts +54 -20
  152. package/src/__tests__/competitors.test.ts +69 -0
  153. package/src/__tests__/credit-identifiers.test.ts +9 -10
  154. package/src/__tests__/lip-sync-pricing.test.ts +29 -2
  155. package/src/__tests__/llm-models.test.ts +50 -7
  156. package/src/__tests__/motion-transfer-pricing.test.ts +252 -0
  157. package/src/__tests__/suno-separate.test.ts +32 -0
  158. package/src/__tests__/video-to-video-pricing.test.ts +151 -0
  159. package/src/audio-isolation-pricing.ts +80 -0
  160. package/src/cast-swap-limits.ts +43 -25
  161. package/src/competitors.ts +86 -8
  162. package/src/credit-identifiers.ts +6 -0
  163. package/src/entries/credits.ts +56 -0
  164. package/src/entries/edl.ts +2 -0
  165. package/src/entries/llm-models.ts +2 -0
  166. package/src/entries/models.ts +4 -0
  167. package/src/entries/social.ts +34 -0
  168. package/src/generated/unit-contracts.ts +1 -0
  169. package/src/lip-sync-pricing.ts +25 -0
  170. package/src/llm-models.ts +60 -4
  171. package/src/model-catalog.ts +46 -23
  172. package/src/motion-transfer-pricing.ts +239 -0
  173. package/src/node-runtime-keys.ts +2 -2
  174. package/src/producer-types.ts +2 -0
  175. package/src/suno-separate.ts +51 -0
  176. package/src/topics.ts +162 -0
  177. package/src/use-case-output.ts +102 -0
  178. package/src/video-face-mesh.ts +1 -1
  179. package/src/video-to-video-pricing.ts +248 -0
  180. package/dist/chunk-3OHRFSQL.cjs.map +0 -1
  181. package/dist/chunk-54E2JO4E.cjs.map +0 -1
  182. package/dist/chunk-5EQRIUGI.cjs.map +0 -1
  183. package/dist/chunk-5WHU7CYE.js.map +0 -1
  184. package/dist/chunk-6Q4BS6AR.js.map +0 -1
  185. package/dist/chunk-BDW25A7Y.js.map +0 -1
  186. package/dist/chunk-DBD4BCGH.cjs.map +0 -1
  187. package/dist/chunk-FUYBUT65.js.map +0 -1
  188. package/dist/chunk-H5KHWTAE.js.map +0 -1
  189. package/dist/chunk-KL6GAYTT.js.map +0 -1
  190. package/dist/chunk-KSHAAPQF.cjs.map +0 -1
  191. package/dist/chunk-LY6IR5LL.cjs.map +0 -1
  192. package/dist/chunk-MGSGLRHZ.cjs.map +0 -1
  193. package/dist/chunk-OEOOXL3F.js.map +0 -1
  194. package/dist/chunk-PHQVAPSD.js.map +0 -1
  195. package/dist/chunk-PLANUXQL.cjs.map +0 -1
  196. package/dist/chunk-V24EPI5N.cjs.map +0 -1
  197. package/dist/chunk-YVQFYW2U.js.map +0 -1
  198. package/dist/chunk-ZWEVRMFN.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/credit-conversion.ts","../src/film-pricing.ts","../src/credit-estimators/video-utils.ts","../src/credit-estimators/image-overlay.ts","../src/credit-estimators/video-sfx.ts","../src/credit-estimators/text-to-audio.ts","../src/credit-estimators/ltx-extend.ts","../src/credit-estimators/ltx-retake.ts","../src/credit-estimators/speech.ts","../src/credit-estimators/voice-changer-pro-quote.ts","../src/credit-estimators/pitch-tempo.ts","../src/credit-estimators/nemotron-transcribe.ts","../src/credit-estimators/add-captions-nemotron.ts","../src/credit-estimators/video-overlay.ts","../src/topaz-upscale.ts","../src/upscale-factors.ts","../src/monetization.ts","../src/lip-sync-pricing.ts","../src/motion-transfer-pricing.ts","../src/video-to-video-pricing.ts","../src/audio-isolation-pricing.ts","../src/seedance-lip-sync.ts","../src/ai-avatar-pricing.ts","../src/switchx-pricing.ts","../src/cinematic-avatar-pricing.ts","../src/avatar-payload-validators.ts","../src/effective-tier.ts","../src/video-analysis-pricing.ts","../src/content-recipe-ideas.ts"],"names":["known","output","FLOAT_NOISE_SEC","chargedSize","ALLOWED_RESOLUTIONS"],"mappings":";;;;;;;;;;;;AAoBO,IAAM,0BAAA,GAA6B;AAE1C,SAAS,gBAAgB,GAAA,EAAmB;AAC1C,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,QAAS,IAAI,KAAA,CAAM,CAAA,uCAAA,EAA0C,GAAG,CAAA,CAAE,CAAA;AAC1F,EAAA,IAAI,MAAM,CAAA,EAAG,MAAM,IAAI,KAAA,CAAM,CAAA,6CAAA,EAAgD,GAAG,CAAA,CAAE,CAAA;AACpF;AAGO,SAAS,aAAa,GAAA,EAAqB;AAChD,EAAA,eAAA,CAAgB,GAAG,CAAA;AACnB,EAAA,MAAM,YAAA,GAAe,IAAA,CAAK,KAAA,CAAO,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AAkC;AAAA,EAC7C,wBAAA;AAAA,EACA,gBAAA;AAAA,EACA,wBAAA;AAAA,EACA,+BAAA;AAAA,EACA,uBAAA;AAAA,EACA,eAAA;AAAA,EACA,uBAAA;AAAA,EACA,8BAAA;AAAA,EACA,0BAAA;AAAA,EACA,kBAAA;AAAA,EACA,0BAAA;AAAA,EACA;AACF","file":"chunk-BVP4M5AK.js","sourcesContent":["/**\n * The ONLY place credit⇄USD arithmetic is written.\n *\n * Every credit figure derives from {@link CREDIT_BASE_USD}. Dividing by a\n * hardcoded copy of that number instead makes the base impossible to change\n * without a multi-file hunt, so route conversions through here.\n *\n * MILLI-CREDIT GUARD — do not remove. `usd / base` is IEEE-754 division and\n * lands a hair above an integer for many exact-multiple inputs\n * (0.14 / 0.02 = 7.000000000000001), so a bare `Math.ceil` rounds up a whole\n * credit that was not owed. Rounding to milli-credits first absorbs that noise\n * at 1000x finer resolution than any credit-level decision.\n *\n * The guard matters at every base, not just the current one — a finer base does\n * not make it unnecessary, it only moves which inputs trip it. Do not\n * \"simplify\" it away if {@link CREDIT_BASE_USD} ever changes.\n */\nimport { CREDIT_BASE_USD } from \"./model-constants.js\"\n\n/** Milli-credits per credit — the intermediate rounding resolution. */\nexport const CREDIT_ROUNDING_RESOLUTION = 1000\n\nfunction assertUsableUsd(usd: number): void {\n if (!Number.isFinite(usd)) throw new Error(`usdToCredits: cost must be finite, got ${usd}`)\n if (usd < 0) throw new Error(`usdToCredits: cost must not be negative, got ${usd}`)\n}\n\n/** A USD amount → whole credits at the current base. Rounds up. */\nexport function usdToCredits(usd: number): number {\n assertUsableUsd(usd)\n const milliCredits = Math.round((usd / CREDIT_BASE_USD) * CREDIT_ROUNDING_RESOLUTION)\n return Math.ceil(milliCredits / CREDIT_ROUNDING_RESOLUTION)\n}\n\n/** Whole credits → their USD value at the current base. Display/reporting only. */\nexport function creditsToUsd(credits: number): number {\n if (!Number.isFinite(credits)) throw new Error(`creditsToUsd: credits must be finite, got ${credits}`)\n return credits * CREDIT_BASE_USD\n}\n","/**\n * Film cost ESTIMATION for the studio preview.\n *\n * This is display guidance only — it produces an approximate \"this film will\n * cost ≈ N credits\" number so the user can see cost before committing to a\n * length + model. The ACTUAL charge is still computed at generation time from\n * `STATIC_CREDIT_COSTS` / the `model_pricing` table per job; this module never\n * bills.\n *\n * Numbers are grounded in the KIE-calibrated per-clip credit costs in\n * `backend/src/ee/billing/credits.ts` (each entry there is annotated with its\n * KIE-credit + USD source). A backend test cross-checks `VIDEO_CLIP_CREDITS`\n * against that source so the estimate can't silently drift from reality.\n *\n * Cost structure of a Story→Video film:\n * total = BASE (duration-independent planning + assembly)\n * + perShot × shotCount (the variable, model-driven bulk)\n * where a shot = one keyframe image + one video clip + one video-critic pass,\n * and shotCount ≈ ceil(duration / clipSeconds) for the chosen model.\n */\n\n/**\n * Duration-independent overhead, in credits:\n * script/showrunner LLM chain ~30 · music timeline 4 · editor LLM 3 ·\n * final merge 3 · storyboard-cohesion critic 5 ≈ 45.\n * Mirrors the fixed line items in `estimateUpfrontCredits`\n * (backend/src/ee/pipelines/credits.ts).\n */\nexport const FILM_BASE_CREDITS = 45\n\n/** Per-shot keyframe image (nano-banana class) — see STATIC_CREDIT_COSTS. */\nexport const KEYFRAME_CREDITS_PER_SHOT = 2\n/** Per-shot Video Critic pass (first_last frame mode) — see credits.ts. */\nexport const VIDEO_CRITIC_CREDITS_PER_SHOT = 2\n\nexport interface VideoClipCost {\n /** Representative per-clip credit cost at the studio's default config\n * (720p; for the Seedance 2 family this is the ref-image variant the\n * studio uses for identity). Sourced from STATIC_CREDIT_COSTS. */\n readonly credits: number\n /** Representative clip length in seconds for shot-count estimation. */\n readonly clipSeconds: number\n}\n\n/**\n * Representative per-clip credit cost for each user-pinnable video model.\n * Values are the KIE-calibrated credits from STATIC_CREDIT_COSTS at the\n * studio's typical settings (720p; Seedance 2 = 8s 720p +ref). Keep in sync\n * with that table — the backend cross-check test guards drift.\n */\nexport const VIDEO_CLIP_CREDITS: Record<string, VideoClipCost> = {\n \"kling-turbo\": { credits: 11, clipSeconds: 5 }, // kling-turbo:5s\n \"kling\": { credits: 14, clipSeconds: 5 }, // kling:5s\n \"kling-3.0\": { credits: 31, clipSeconds: 5 },\n \"seedance-2\": { credits: 50, clipSeconds: 8 }, // seedance-2:8s:720p-ref\n \"seedance-2-fast\": { credits: 40, clipSeconds: 8 }, // seedance-2-fast:8s:720p-ref\n \"seedance-2-mini\": { credits: 25, clipSeconds: 8 }, // seedance-2-mini:8s:720p-ref\n \"seedance-2-5\": { credits: 76, clipSeconds: 8 }, // seedance-2-5:8s:720p-ref\n \"veo3\": { credits: 79, clipSeconds: 8 }, // flat per generation (VEO 3.1 Quality)\n \"veo3.1\": { credits: 19, clipSeconds: 6 }, // veo3.1 @ 720p\n \"veo3_lite\": { credits: 10, clipSeconds: 6 }, // veo3_lite @ 720p\n \"minimax\": { credits: 18, clipSeconds: 6 }, // fixed ~6s\n \"hailuo-standard\": { credits: 8, clipSeconds: 6 }, // hailuo-standard:6s\n \"wan-turbo\": { credits: 13, clipSeconds: 5 }, // 5s 480p\n \"bytedance-lite\": { credits: 6, clipSeconds: 5 },\n \"bytedance-pro\": { credits: 18, clipSeconds: 5 },\n}\n\n/**\n * Fallback when no model is pinned (Auto — the Scene Director picks per scene)\n * or the model isn't in the table. kling-turbo is the cheap, common default\n * the engine gravitates to, so it's a reasonable \"≈\" anchor.\n */\nexport const DEFAULT_VIDEO_CLIP_COST: VideoClipCost = VIDEO_CLIP_CREDITS[\"kling-turbo\"]!\n\nexport interface FilmCreditEstimate {\n /** Total estimated credits for the whole film. */\n readonly totalCredits: number\n /** Fixed base portion (planning + assembly). */\n readonly baseCredits: number\n /** Variable portion (shots × per-shot). */\n readonly variableCredits: number\n /** Estimated number of shots (clips) generated. */\n readonly shotCount: number\n /** Average credits per second of film (totalCredits / duration). */\n readonly creditsPerSecond: number\n /** Whether a known model drove the estimate (false = Auto/fallback). */\n readonly modelKnown: boolean\n}\n\n/**\n * Estimate the credit cost of a Story→Video film of `durationSeconds` rendered\n * with `videoModel`. Approximate, for the studio's cost preview only.\n */\nexport function estimateFilmCredits(\n durationSeconds: number,\n videoModel?: string,\n): FilmCreditEstimate {\n const seconds = Math.max(1, Math.round(durationSeconds))\n const known = !!videoModel && videoModel in VIDEO_CLIP_CREDITS\n const clip = known ? VIDEO_CLIP_CREDITS[videoModel!]! : DEFAULT_VIDEO_CLIP_COST\n\n const shotCount = Math.max(1, Math.ceil(seconds / clip.clipSeconds))\n const perShot =\n clip.credits + KEYFRAME_CREDITS_PER_SHOT + VIDEO_CRITIC_CREDITS_PER_SHOT\n const variableCredits = shotCount * perShot\n const totalCredits = FILM_BASE_CREDITS + variableCredits\n\n return {\n totalCredits,\n baseCredits: FILM_BASE_CREDITS,\n variableCredits,\n shotCount,\n creditsPerSecond: Math.round((totalCredits / seconds) * 10) / 10,\n modelKnown: known,\n }\n}\n","/**\n * Pure credit estimators for video-utility nodes (loop-video, trim-video,\n * combine-videos, assemble-narrated-video). Used by frontend (Run-button\n * display + API call) AND backend (creditGuard reservation, the workflow\n * run's reservation, the workflow estimate) so the displayed cost equals\n * what gets debited.\n *\n * Every estimate counts pricing UNITS and returns units × CREDIT_UNIT base\n * credits: a unit is 5 seconds of output, ~24 frames a smart loop cut\n * searches, each combine input beyond two, and each step of Assemble Narrated\n * Video (3 + 1 per 6 blocks).\n */\n\nexport const VIDEO_UTIL_PRICING = {\n /** Base credits per pricing unit. The node's own `model_pricing` row is one unit. */\n CREDIT_UNIT: 10,\n /** Base credits per 5 seconds of output (one unit), ceiling. */\n CREDITS_PER_5_SEC: 10,\n /** Smart-loop-cut work scales at one unit per ~24 frames searched. */\n FRAMES_PER_CREDIT: 24,\n /** Used when an upstream node hasn't produced a measurable duration yet. */\n FALLBACK_DURATION_SECONDS: 8,\n} as const\n\n/** Base credits for a count of pricing units, never below one unit. */\nfunction unitsToCredits(units: number): number {\n return VIDEO_UTIL_PRICING.CREDIT_UNIT * Math.max(1, units)\n}\n\nexport interface LoopVideoEstimatorInput {\n mode?: \"repeat\" | \"duration\"\n repeatCount?: number\n targetDuration?: number\n smartLoopCutBeforeRepeat?: boolean\n smartLoopCutLookback?: number\n}\n\nexport interface TrimVideoEstimatorInput {\n trimMode?: \"time\" | \"seconds\" | \"keep-first-seconds\" | \"keep-last-seconds\" | \"frames\" | \"smart-loop-cut\"\n startTime?: number\n endTime?: number\n /** Seconds-mirror of frames mode: trim N seconds from start AND/OR end. */\n trimStartSeconds?: number\n trimEndSeconds?: number\n /** Keep only the first/last N seconds (probes duration at runtime). */\n keepFirstSeconds?: number\n keepLastSeconds?: number\n trimStartFrames?: number\n trimEndFrames?: number\n smartLoopCutLookback?: number\n}\n\nexport interface CombineVideosEstimatorInput {\n /** Any id from `COMBINE_TRANSITIONS`. The estimator only branches on\n * `cut` vs non-cut, so accepting the full string keeps the catalog as\n * the single source of truth. */\n transition?: string\n transitionDuration?: number\n trimStartFrames?: number\n trimEndFrames?: number\n /**\n * The frame rate the clips' frame trims are cut at (the rate the join\n * conforms its clips to), when known. Absent, 24 fps, the estimate's\n * long-standing assumption. The trims come off at the joins only: the start\n * of every clip but the first, the end of every clip but the last.\n */\n trimFramesPerSecond?: number\n /**\n * Per-join transitions (Combine Videos' `transitions`): `index` k is the\n * join between clip k and clip k + 1. A join with an entry blends for its\n * own `duration` (a `\"cut\"`, or a duration of 0, overlaps nothing); every\n * other join keeps `transition` / `transitionDuration`. An index outside the\n * joins is ignored, and a later entry for the same join wins, as the join\n * renders them.\n */\n transitions?: ReadonlyArray<{ readonly index?: number; readonly transition?: string; readonly duration?: number }>\n}\n\n/** The most a join may overlap, as a share of the shortest clip it joins (the render's own clamp). */\nconst COMBINE_MAX_OVERLAP_SHARE = 0.9\n\n/** A length in seconds when it is a positive one, else 0 (a transition with no length overlaps nothing). */\nconst positiveSeconds = (v: unknown): number => (typeof v === \"number\" && Number.isFinite(v) && v > 0 ? v : 0)\n\nexport function estimateLoopVideoCredits(\n data: LoopVideoEstimatorInput,\n upstreamDuration?: number,\n): number {\n const fallback = VIDEO_UTIL_PRICING.FALLBACK_DURATION_SECONDS\n const inputDuration = upstreamDuration ?? fallback\n\n const output =\n data.mode === \"duration\"\n ? (data.targetDuration ?? fallback)\n : (data.repeatCount ?? 2) * inputDuration\n\n const base = Math.ceil(output / 5)\n const cut = data.smartLoopCutBeforeRepeat\n ? Math.ceil((data.smartLoopCutLookback ?? 16) / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT)\n : 0\n\n return unitsToCredits(base + cut)\n}\n\nexport function estimateTrimVideoCredits(\n data: TrimVideoEstimatorInput,\n upstreamDuration?: number,\n): number {\n const fallback = VIDEO_UTIL_PRICING.FALLBACK_DURATION_SECONDS\n const inputDuration = upstreamDuration ?? fallback\n\n if (data.trimMode === \"smart-loop-cut\") {\n const base = Math.ceil(inputDuration / 5)\n const cut = Math.ceil((data.smartLoopCutLookback ?? 16) / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT)\n return unitsToCredits(base + cut)\n }\n\n if (data.trimMode === \"frames\") {\n // Source fps unknown frontend-side; assume 24.\n const startSec = (data.trimStartFrames ?? 0) / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT\n const endSec = (data.trimEndFrames ?? 0) / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT\n const output = Math.max(0, inputDuration - startSec - endSec)\n return unitsToCredits(Math.ceil(output / 5))\n }\n\n if (data.trimMode === \"seconds\") {\n const output = Math.max(0, inputDuration - (data.trimStartSeconds ?? 0) - (data.trimEndSeconds ?? 0))\n return unitsToCredits(Math.ceil(output / 5))\n }\n\n if (data.trimMode === \"keep-first-seconds\") {\n const output = Math.min(inputDuration, Math.max(0, data.keepFirstSeconds ?? 0))\n return unitsToCredits(Math.ceil(output / 5))\n }\n\n if (data.trimMode === \"keep-last-seconds\") {\n const output = Math.min(inputDuration, Math.max(0, data.keepLastSeconds ?? 0))\n return unitsToCredits(Math.ceil(output / 5))\n }\n\n // \"time\" mode (default)\n const output = (data.endTime ?? 0) - (data.startTime ?? 0)\n return unitsToCredits(Math.ceil(output / 5))\n}\n\nexport function estimateCombineVideosCredits(\n data: CombineVideosEstimatorInput,\n upstreamDurations: ReadonlyArray<number | undefined>,\n): number {\n if (upstreamDurations.length === 0) return unitsToCredits(1)\n\n const fallback = VIDEO_UTIL_PRICING.FALLBACK_DURATION_SECONDS\n const n = upstreamDurations.length\n\n const trimFps =\n data.trimFramesPerSecond !== undefined && Number.isFinite(data.trimFramesPerSecond) && data.trimFramesPerSecond > 0\n ? data.trimFramesPerSecond\n : VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT\n const startSec = (data.trimStartFrames ?? 0) / trimFps\n const endSec = (data.trimEndFrames ?? 0) / trimFps\n // Each clip as the join cuts it: the trims come off only where two clips\n // meet — the start of every clip but the first, the end of every clip but\n // the last. The film's own first and last frames are kept.\n const clips = upstreamDurations.map((d, i) => {\n const sec = typeof d === \"number\" && Number.isFinite(d) && d >= 0 ? d : fallback\n return sec - (i > 0 ? startSec : 0) - (i < n - 1 ? endSec : 0)\n })\n let total = clips.reduce((sum, sec) => sum + sec, 0)\n\n // Each join's overlap, as the join renders it: its own transition where one\n // is set, else the global one; at most 90 % of the shortest clip.\n const globalOverlap = data.transition && data.transition !== \"cut\" ? Math.max(0, data.transitionDuration ?? 0.5) : 0\n const overrides = new Map<number, number>()\n for (const entry of data.transitions ?? []) {\n const index = entry?.index\n if (typeof index !== \"number\" || !Number.isInteger(index) || index < 0 || index >= n - 1) continue\n const overlap = positiveSeconds(entry.duration)\n overrides.set(index, entry.transition === \"cut\" ? 0 : overlap)\n }\n const maxOverlap = Math.max(0, Math.min(...clips) * COMBINE_MAX_OVERLAP_SHARE)\n for (let k = 0; k < n - 1; k++) total -= Math.min(overrides.get(k) ?? globalOverlap, maxOverlap)\n\n const base = Math.ceil(Math.max(0, total) / 5)\n const inputAdder = Math.max(0, n - 2)\n return unitsToCredits(base + inputAdder)\n}\n\nexport interface LoopTrimEstimatorInput {\n enabled?: boolean\n framesToTest?: number\n}\n\n/** Add-on credits charged for the smart-loop-cut post-process applied to an\n * image-to-video output. Returns 0 when loopTrim is undefined or disabled.\n * Formula: CREDIT_UNIT × (ceil(duration / 5) + ceil(framesToTest / 24)) —\n * the same units as Trim Video's smart loop cut, so 8 s at 16 frames → 30. */\nexport function estimateLoopTrimAddonCredits(\n loopTrim: LoopTrimEstimatorInput | undefined,\n outputDurationSeconds: number,\n): number {\n if (!loopTrim?.enabled) return 0\n const frames = Math.max(1, Math.min(loopTrim.framesToTest ?? 16, 64))\n return unitsToCredits(\n Math.ceil(outputDurationSeconds / 5) + Math.ceil(frames / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT),\n )\n}\n\n/** BASE credits for assemble-narrated-video: 3 units flat + 1 per 6\n * blocks. 6→40, 24→70, 60→130. Single source of truth shared by the backend\n * route/creditGuard (`backend/src/providers/video/narrated-block-fit.ts`\n * re-exports this), the workflow run's reservation and the frontend pre-run\n * estimate (`frontend/src/hooks/use-estimated-credits.ts`). */\nexport function assembleNarratedVideoCredits(blockCount: number): number {\n return unitsToCredits(3 + Math.ceil(blockCount / 6))\n}\n","import { overlayPlatformById } from \"../image-overlay-platforms.js\"\n\n/**\n * Image Overlay pricing — one formula shared by the backend route\n * (creditGuard computeCredits), the orchestrator's reservation override, the\n * workflow estimator and the canvas Run button, so every surface quotes and\n * charges the same number.\n *\n * credits = BASE + PER_VARIANT × (number of distinct, valid platform ids)\n *\n * The base covers the composite and its mask; every extra platform render is\n * one more resize + encode + upload. Worked examples (pinned by the tests and\n * repeated in docs/nodes/processing-video/image-overlay.md — keep them equal):\n * 0 variants → 10, 2 → 14, 12 (every platform) → 34.\n */\nexport const IMAGE_OVERLAY_BASE_CREDITS = 10\nexport const IMAGE_OVERLAY_VARIANT_CREDITS = 2\n\n/** Distinct platform ids the registry knows — the count the price is built from. */\nexport function imageOverlayBillableVariants(variants: ReadonlyArray<unknown> | undefined): string[] {\n const seen = new Set<string>()\n for (const v of variants ?? []) {\n if (typeof v === \"string\" && overlayPlatformById(v)) seen.add(v)\n }\n return [...seen]\n}\n\nexport function imageOverlayCredits(variants: ReadonlyArray<unknown> | undefined): number {\n return IMAGE_OVERLAY_BASE_CREDITS + IMAGE_OVERLAY_VARIANT_CREDITS * imageOverlayBillableVariants(variants).length\n}\n","/**\n * Video SFX pricing — which price row a run is charged from, by the length of\n * the input video. One mapping for every place that names the row: the route\n * (`POST /v1/video-sfx`), the workflow run's reservation, the node's Run\n * button and the workflow estimates.\n *\n * Each bucket is a `model_pricing` row (`replicate-mmaudio:<n>s`); the credit\n * amounts live there, never here. Worked examples (repeated in\n * docs/nodes/ai-video/video-sfx.md):\n * 5 s → `:8s`, 12 s → `:15s`, 31 s → `:60s`, 180 s → `:300s`.\n */\n\nimport { gracedMeasuredSec } from \"../priced-clip-seconds.js\"\n\nexport const VIDEO_SFX_PRICING = {\n /** The longest input video a run accepts, in seconds. */\n MAX_DURATION_SEC: 300,\n /** The length priced (and generated) when the input video cannot be measured. */\n FALLBACK_DURATION_SEC: 8,\n} as const\n\nconst VIDEO_SFX_BUCKETS: ReadonlyArray<{ readonly upToSec: number; readonly creditId: string }> = [\n { upToSec: 8, creditId: \"replicate-mmaudio:8s\" },\n { upToSec: 15, creditId: \"replicate-mmaudio:15s\" },\n { upToSec: 30, creditId: \"replicate-mmaudio:30s\" },\n { upToSec: 60, creditId: \"replicate-mmaudio:60s\" },\n { upToSec: 120, creditId: \"replicate-mmaudio:120s\" },\n { upToSec: 300, creditId: \"replicate-mmaudio:300s\" },\n]\n\n/**\n * The price row for an input video of `durationSec` seconds. An unknown or\n * non-positive length prices the fallback length; anything past the cap prices\n * the last bucket (the route refuses such a video before it gets here).\n */\nexport function videoSfxCreditId(durationSec: number | null | undefined): string {\n const seconds =\n typeof durationSec === \"number\" && Number.isFinite(durationSec) && durationSec > 0\n ? durationSec\n : VIDEO_SFX_PRICING.FALLBACK_DURATION_SEC\n const bucket = VIDEO_SFX_BUCKETS.find((b) => seconds <= b.upToSec) ?? VIDEO_SFX_BUCKETS[VIDEO_SFX_BUCKETS.length - 1]!\n return bucket.creditId\n}\n\n/**\n * The price row a run HOLDS and is CHARGED for an input video it measured at\n * `measuredSec` seconds: the row of the length less `CLIP_PRICE_GRACE_SEC`\n * (0.05 s, decided 2026-11-14), so a container a hair past a row's length (a\n * re-encoded 30 s cut measures 30.016 s) is charged that row, the one its\n * length is quoted at ({@link videoSfxQuoteCreditId}, which reads the length\n * exactly). Past the grace, the next row.\n */\nexport function videoSfxHeldCreditId(measuredSec: number): string {\n // Less a float-noise hair too (`gracedMeasuredSec`): 15.05 s less 0.05 s is 15.000000000000002, not past 15 s.\n return videoSfxCreditId(Math.max(Number.MIN_VALUE, gracedMeasuredSec(measuredSec)))\n}\n\n/**\n * The price row a QUOTE names for an input video of `durationSec` seconds —\n * every estimate before a run (the node's Run button, the workflow estimate,\n * the server's run estimate, a listing). A known length is the row its run is\n * charged ({@link videoSfxCreditId}). An UNKNOWN length is the last row, 300\n * seconds (decided 2026-10-13): a run measures the clip before it reserves and\n * refuses one over 300 s, so that row is the most any run can be charged —\n * the quote is never below the charge, as Video Mask and Video Depth quote an\n * unknown clip at their highest row.\n */\nexport function videoSfxQuoteCreditId(durationSec: number | null | undefined): string {\n const known = typeof durationSec === \"number\" && Number.isFinite(durationSec) && durationSec > 0\n return videoSfxCreditId(known ? durationSec : VIDEO_SFX_PRICING.MAX_DURATION_SEC)\n}\n","/**\n * Text to Audio (sound effects) pricing — which price row a run is charged\n * from, by the length of the clip it asks for. One mapping for every place\n * that names the row: the route (`POST /v1/text-to-audio`), the workflow run's\n * reservation, the node's Run button and the workflow estimates.\n *\n * `elevenlabs-sfx` is priced per second: one `model_pricing` row per whole\n * second (`elevenlabs-sfx:1s` … `elevenlabs-sfx:30s`); the credit amounts live\n * there, never here. The requested length is rounded UP to whole seconds, and\n * a request that names no length is priced as 5 seconds. Worked examples\n * (repeated in docs/nodes/ai-audio/text-to-audio.md):\n * 0.5 s → `:1s`, 6 s → `:6s`, 22.3 s → `:23s`, no duration → `:5s`.\n */\n\nimport { DEFAULT_TEXT_TO_AUDIO_PROVIDER } from \"../model-constants.js\"\n\nexport const TEXT_TO_AUDIO_PRICING = {\n /** The engine priced per second of requested audio. */\n PER_SECOND_PROVIDER: \"elevenlabs-sfx\",\n /** The longest clip a request may ask for, in seconds. */\n MAX_DURATION_SEC: 30,\n /** The length priced when a request names none (the model picks the length). */\n DEFAULT_BILLED_SEC: 5,\n} as const\n\n/** Every per-second price row, shortest first: `elevenlabs-sfx:1s` … `:30s`. */\nexport const TEXT_TO_AUDIO_SFX_CREDIT_IDS: readonly string[] = Array.from(\n { length: TEXT_TO_AUDIO_PRICING.MAX_DURATION_SEC },\n (_, i) => `${TEXT_TO_AUDIO_PRICING.PER_SECOND_PROVIDER}:${i + 1}s`,\n)\n\n/**\n * The whole seconds a request of `duration` seconds is billed for: rounded up,\n * at most the 30 s cap. No usable length (absent, empty, non-numeric, zero or\n * negative) bills the 5 s default. A numeric string counts — a field mapping\n * can deliver the length as text.\n */\nexport function textToAudioBilledSeconds(duration: unknown): number {\n const seconds =\n typeof duration === \"number\"\n ? duration\n : typeof duration === \"string\" && duration.trim() !== \"\"\n ? Number(duration)\n : Number.NaN\n if (!Number.isFinite(seconds) || seconds <= 0) return TEXT_TO_AUDIO_PRICING.DEFAULT_BILLED_SEC\n return Math.min(Math.ceil(seconds), TEXT_TO_AUDIO_PRICING.MAX_DURATION_SEC)\n}\n\n/**\n * The price row for a Text to Audio request. A request with no provider runs\n * (and is priced as) the default engine. An engine that is not priced per\n * second keeps its own flat row.\n */\nexport function textToAudioCreditId(provider: string | null | undefined, duration: unknown): string {\n const engine = provider || DEFAULT_TEXT_TO_AUDIO_PROVIDER\n if (engine !== TEXT_TO_AUDIO_PRICING.PER_SECOND_PROVIDER) return engine\n return `${engine}:${textToAudioBilledSeconds(duration)}s`\n}\n","/**\n * LTX 2.3 Pro Extend pricing — a per-second price row times the seconds added.\n *\n * `ltxExtendDurationSec` is the one reading of the requested length, and the\n * value it returns is the one SENT to the model: the route, the workflow run\n * and the worker all pass it on, so the seconds priced are the seconds\n * rendered. An absent length is the model's own default (6 seconds).\n *\n * The per-second amount lives in the `model_pricing` row, never here. Worked\n * examples at the row's listed price of 40 (repeated in\n * docs/nodes/ai-video/extend-video.md):\n * 2 s → 80, 6 s (or no length) → 240, 20 s → 800.\n */\n\nexport const LTX_EXTEND_PER_SECOND_CREDIT_ID = \"ltx-2.3-pro-extend:per-second\"\n\nexport const LTX_EXTEND_DURATION = {\n MIN_SEC: 1,\n MAX_SEC: 20,\n DEFAULT_SEC: 6,\n} as const\n\n/**\n * The seconds an LTX extend adds: a whole number from 1 to 20, the default\n * when none (or nothing readable) was given. Accepts a numeric string, which a\n * workflow field mapping can deliver.\n */\nexport function ltxExtendDurationSec(raw: unknown): number {\n const n =\n typeof raw === \"number\" ? raw : typeof raw === \"string\" && raw.trim() !== \"\" ? Number(raw) : Number.NaN\n if (!Number.isFinite(n)) return LTX_EXTEND_DURATION.DEFAULT_SEC\n return Math.min(LTX_EXTEND_DURATION.MAX_SEC, Math.max(LTX_EXTEND_DURATION.MIN_SEC, Math.round(n)))\n}\n","/**\n * LTX 2.3 Pro Retake pricing — a per-second price row times the seconds of\n * the replaced window.\n *\n * `ltxRetakeDurationSec` is the one reading of the window's length, and the\n * value it returns is the one SENT to the model: the route, the workflow run\n * and the worker all pass it on. The window is at least 2 seconds (the\n * route's own floor) and may be fractional — the editor's range picker sets\n * it to the frame.\n *\n * The per-second amount lives in the `model_pricing` row, never here; a run\n * is the row × these seconds, rounded up to a whole credit.\n */\n\nexport const LTX_RETAKE_PER_SECOND_CREDIT_ID = \"ltx-2.3-pro-retake:per-second\"\n\n/** The shortest window a retake replaces, in seconds. */\nexport const LTX_RETAKE_MIN_DURATION_SEC = 2\n\n/**\n * The seconds a retake replaces: the requested window, never below 2; 2 when\n * none (or nothing readable) was given. Accepts a numeric string, which a\n * workflow field mapping can deliver.\n */\nexport function ltxRetakeDurationSec(raw: unknown): number {\n const n =\n typeof raw === \"number\" ? raw : typeof raw === \"string\" && raw.trim() !== \"\" ? Number(raw) : Number.NaN\n if (!Number.isFinite(n) || n <= 0) return LTX_RETAKE_MIN_DURATION_SEC\n return Math.max(LTX_RETAKE_MIN_DURATION_SEC, n)\n}\n","/**\n * Length-based speech pricing — the shape of the price, not its value.\n *\n * A speech request (Text to Speech, Text to Dialogue, and the voiced-video\n * add-on) is priced per STARTED 100 characters of the text actually sent,\n * with a minimum number of units per request. The amount of one unit is a\n * `model_pricing` row per model — `<model id>:per-100-chars`, admin-editable\n * — and never lives here. `speechCredits(chars, row)` is the list price of a\n * request at a catalog row. An instance prices the WHOLE request and rounds it\n * once, so the price it serves for one unit times the units is only an upper\n * bound of what the request costs there. The exact charge of a\n * request of N units is served under its own id, `speechQuoteCreditId(model,\n * N)` (`<model>:per-100-chars:<N>u`), by the same price lookups that serve the\n * unit row (credits.model-costs, GET /v1/credits/model-cost): a client quotes\n * that answer rather than multiplying.\n *\n * Why 100 and not 1,000: the per-request error is at most one unit, and a\n * whole number of units times a charged unit price never under-quotes the\n * charge (the same property the per-second video rows rely on).\n *\n * A model whose rate is below one credit per 100 characters (a row holds\n * whole credits) quotes its row per 1,000 instead — `<model>:per-1k-chars`,\n * its sheet's `ratePer1kChars` (decided 2026-11-12). The count is the same\n * (started 100s, at least 8), and a request costs its hundreds × the row ÷ 10,\n * rounded up once (`speechRowCredits`). Its request quote keeps the one id\n * shape, `<model>:per-100-chars:<N>u`, N in started hundreds, so a client\n * that builds that id quotes every model alike.\n *\n * Decided 2026-10-06. Every name here is a published contract.\n */\nimport { canonicalTtsProvider, findTtsCapabilities } from \"../tts-capabilities.js\"\nimport { findDialogueCapabilities } from \"../dialogue-capabilities.js\"\nimport { unitQuoteCreditId } from \"./unit-quote.js\"\n\n/** Characters per price unit. */\nexport const SPEECH_PRICE_UNIT_CHARS = 100\n\n/** The minimum units a request is priced at, however short its text. */\nexport const SPEECH_FLOOR_UNITS = 8\n\n/** Appended to a speech model's id to name its per-unit price row. */\nexport const SPEECH_UNIT_CREDIT_SUFFIX = \":per-100-chars\"\n\n/** Appended to a speech model's id to name its rate row quoted per 1,000 characters (`TtsCapabilities.ratePer1kChars`). */\nexport const SPEECH_PER_1K_CREDIT_SUFFIX = \":per-1k-chars\"\n\n/**\n * How many units (started 100 characters) one rate row of the model prices:\n * 10 for a model whose row is quoted per 1,000 characters, else 1. The\n * legacy alias resolved; an id with no speech sheet is 1.\n */\nexport function speechRowUnits(modelId: string): 1 | 10 {\n const id = canonicalTtsProvider(modelId)\n return (findTtsCapabilities(id) ?? findDialogueCapabilities(id))?.ratePer1kChars ? 10 : 1\n}\n\n/**\n * The price-row id of the rate the model a request runs as is charged at:\n * `<model>:per-100-chars` (one unit), or `<model>:per-1k-chars` for a model\n * quoted per 1,000 characters ({@link speechRowUnits}). The legacy\n * `elevenlabs` alias prices on turbo's row, as it runs on turbo; any other id\n * (including the dialogue model) is used as given.\n */\nexport function speechUnitCreditId(modelId: string): string {\n const id = canonicalTtsProvider(modelId)\n return `${id}${speechRowUnits(id) === 10 ? SPEECH_PER_1K_CREDIT_SUFFIX : SPEECH_UNIT_CREDIT_SUFFIX}`\n}\n\n/**\n * Base credits of `units` (started hundreds) at a rate row of `rowCredits`\n * that prices `rowUnits` units: `ceil(units × row ÷ rowUnits)`, in whole\n * numbers so it never rounds a hair high. With `rowUnits` 1 it is exactly\n * units × the row (every per-100 row is a whole number).\n */\nexport function speechRowCredits(units: number, rowCredits: number, rowUnits: number = 1): number {\n return rowUnits === 1 ? units * rowCredits : Math.ceil((units * rowCredits) / rowUnits)\n}\n\n/**\n * Units a text of `chars` characters is priced at: every started 100, and\n * never fewer than the floor. A count that is not a finite non-negative\n * number (node data written straight into workflow JSON) is the floor.\n */\nexport function speechPriceUnits(chars: number): number {\n const started = Number.isFinite(chars) && chars > 0 ? Math.ceil(chars / SPEECH_PRICE_UNIT_CHARS) : 0\n return Math.max(SPEECH_FLOOR_UNITS, started)\n}\n\n/** Base credits for `chars` characters at `perUnitCredits` per unit (the model's `:per-100-chars` row). */\nexport function speechCredits(chars: number, perUnitCredits: number): number {\n return speechPriceUnits(chars) * perUnitCredits\n}\n\n/**\n * Base credits for `chars` characters on `modelId` at its rate row\n * (`speechUnitCreditId(modelId)`, read as `rowCredits`): per-100 or per-1K,\n * whichever the model is quoted in. What every seam that reserves speech, and\n * every client that quotes it, computes.\n */\nexport function speechCreditsFor(modelId: string, chars: number, rowCredits: number): number {\n return speechRowCredits(speechPriceUnits(chars), rowCredits, speechRowUnits(modelId))\n}\n\n/**\n * The id of the exact charge of a whole request of `units` units on `modelId`:\n * `<model>:per-100-chars:<N>u`. Never a row of its own — a price lookup prices\n * it from the model's unit row × N as one whole, exactly as a request of that\n * length is reserved. Served only while length pricing is on, like the unit\n * row it is priced from.\n */\nexport function speechQuoteCreditId(modelId: string, units: number): string {\n // Always the per-100 shape, whatever the model's rate row: N is started hundreds.\n return unitQuoteCreditId(`${canonicalTtsProvider(modelId)}${SPEECH_UNIT_CREDIT_SUFFIX}`, units)\n}\n\n/** A `<model>:per-100-chars:<N>u` id, read back. */\nexport interface SpeechQuoteCreditIdParts {\n /** The speech model (canonical id) the request runs as. */\n model: string\n /** Its rate row: `<model>:per-100-chars`, or `<model>:per-1k-chars` for a model quoted per 1,000. */\n unitId: string\n /** Units priced: at least the floor, at most the model's per-request cap in started hundreds. */\n units: number\n /** How many units one `unitId` row prices (10 for a per-1,000 row, else 1): the request is `speechRowCredits(units, row, rowUnits)`. */\n rowUnits: 1 | 10\n}\n\nconst SPEECH_QUOTE_ID = /^(.+):per-100-chars:(\\d{1,6})u$/\n\n/**\n * The parts of a `<model>:per-100-chars:<N>u` id, or undefined for any other id\n * — including a model that is not a speech model under its canonical id, and a\n * unit count no request on that model can be priced at (below the floor, or\n * above the model's cap in started hundreds).\n */\nexport function parseSpeechQuoteCreditId(id: string): SpeechQuoteCreditIdParts | undefined {\n if (typeof id !== \"string\") return undefined\n const m = SPEECH_QUOTE_ID.exec(id)\n if (!m) return undefined\n const model = m[1]!\n if (canonicalTtsProvider(model) !== model) return undefined\n const caps = findTtsCapabilities(model) ?? findDialogueCapabilities(model)\n if (!caps) return undefined\n const units = Number(m[2])\n if (!Number.isInteger(units) || units < SPEECH_FLOOR_UNITS || units > speechPriceUnits(caps.maxChars)) return undefined\n return { model, unitId: speechUnitCreditId(model), units, rowUnits: speechRowUnits(model) }\n}\n\n/**\n * Whether an id is a length price of speech — a `<model>:per-100-chars` unit\n * row, a `<model>:per-1k-chars` rate row or a `<model>:per-100-chars:<N>u`\n * request quote — by its shape alone. All are served only while the server\n * prices speech by length.\n */\nexport function isSpeechLengthPriceId(id: string): boolean {\n return typeof id === \"string\" && /(?::per-100-chars(?::\\d+u)?|:per-1k-chars)$/.test(id)\n}\n\n/**\n * The speech model a length price id is priced for — the id a request of\n * that model is reserved at, so the two are priced under the same id — or\n * undefined for any other id.\n */\nexport function speechLengthPriceModel(id: string): string | undefined {\n if (!isSpeechLengthPriceId(id)) return undefined\n return id.replace(/(?::per-100-chars(?::\\d+u)?|:per-1k-chars)$/, \"\")\n}\n","/**\n * The price of a whole Voice Changer Pro convert, as ONE id.\n *\n * A convert is charged as one whole: every changed speaker's slot is priced in\n * base credits (a recast slot by the length of its stem, a Re-speak slot by\n * its characters on its engine's row), the slots are summed, and the sum is\n * marked up ONCE at `voice-changer-pro`. A client that prices each slot on the\n * served (already marked-up, already rounded) rows and adds them up cannot\n * reach that figure: the rounding happens in a different place.\n *\n * `voiceChangerProQuoteCreditId(slots)` names the whole price:\n * `voice-changer-pro:<slot>,<slot>,…`, one slot per changed speaker, where a\n * slot is\n *\n * - `sts-<seconds>` — a recast (speech-to-speech) slot whose stem is that\n * many seconds long (the speaker's last utterance end); `sts` alone when\n * the length is unknown (priced as one minute, as the convert reserves it);\n * - `respeak-<chars>` — a Re-speak slot on the default engine (v3) that\n * re-speaks that many characters; `respeak` alone when the count is unknown;\n * - `respeak-v4-<chars>` — a Re-speak slot on the v4 engine (`respeak-v4`\n * when the count is unknown); `respeak-v3-<chars>` names v3 explicitly\n * and is the same price as `respeak-<chars>`;\n * - `respeak-v4t-<chars>` — a v4 slot speaking a TRANSLATION of its\n * `<chars>` transcript characters. The convert reserves such a slot for more\n * speech than its transcript holds (a line may be re-rendered once,\n * shorter); the server applies that allowance, so the client sends the\n * transcript's own count and never the arithmetic. Only v4 speaks a\n * translation, so there is no `v3t`.\n *\n * `POST /v1/credits/model-costs` and `GET /v1/credits/model-cost` answer it\n * with the figure the convert reserves; an id the server does not price\n * (a malformed slot, more slots than a convert takes, a count out of range)\n * lands in `missing`. Numbers are written exactly as JavaScript prints them,\n * so the server reads back the value the client priced.\n */\n\n/** The id a convert is reserved (and marked up) at. */\nexport const VOICE_CHANGER_PRO_QUOTE_RATE_ID = \"voice-changer-pro\"\n\n/** A Re-speak engine, as the quote names it. */\nexport type VoiceChangerProQuoteRespeakEngine = \"v3\" | \"v4\"\n\n/** One changed speaker of a convert, as the quote prices it. */\nexport type VoiceChangerProQuoteSlot =\n /** A recast slot: the stem's length in seconds; `null` (or not a positive number) = unknown. */\n | { readonly kind: \"sts\"; readonly seconds: number | null }\n /**\n * A Re-speak slot: the characters of its transcript; `null` (or not a\n * positive number) = unknown. `engine` absent = the default engine (v3).\n * `translated` = the slot speaks the plan's target language — read only on\n * v4, the one engine that speaks a translation (the convert route reads it\n * the same way).\n */\n | {\n readonly kind: \"respeak\"\n readonly chars: number | null\n readonly engine?: VoiceChangerProQuoteRespeakEngine\n readonly translated?: boolean\n }\n\n/** A `voice-changer-pro:<slots>` id, read back into the convert's pricing inputs (slot order kept per kind). */\nexport interface VoiceChangerProQuoteCreditIdParts {\n /** Stem seconds per recast slot; `null` = unknown. */\n readonly stsSlotSeconds: ReadonlyArray<number | null>\n /** Transcript characters per Re-speak slot; `null` = unknown. */\n readonly respeakChars: ReadonlyArray<number | null>\n /** The engine of each Re-speak slot, index-aligned with `respeakChars`; `null` = not named (the default engine). */\n readonly respeakEngines: ReadonlyArray<VoiceChangerProQuoteRespeakEngine | null>\n /** Whether each Re-speak slot speaks a translation, index-aligned with `respeakChars` (only ever true on v4). */\n readonly respeakTranslated: ReadonlyArray<boolean>\n}\n\nconst PREFIX = `${VOICE_CHANGER_PRO_QUOTE_RATE_ID}:`\nconst NUMBER = String.raw`\\d{1,7}(?:\\.\\d{1,20})?`\nconst STS_SLOT = new RegExp(`^sts(?:-(${NUMBER}))?$`)\nconst RESPEAK_SLOT = new RegExp(`^respeak(?:-(v3|v4|v4t))?(?:-(${NUMBER}))?$`)\n\nconst known = (n: number | null): n is number => n !== null && Number.isFinite(n) && n > 0\n\n/** The engine token of a Re-speak slot: none for the default engine (the id every client sent before engines were named). */\nfunction respeakEngineToken(slot: { readonly engine?: VoiceChangerProQuoteRespeakEngine; readonly translated?: boolean }): string {\n if (slot.engine !== \"v4\") return \"\"\n return slot.translated === true ? \"-v4t\" : \"-v4\"\n}\n\n/** `voice-changer-pro:<slot>,…` — the id of the whole price of a convert with these changed speakers. */\nexport function voiceChangerProQuoteCreditId(slots: ReadonlyArray<VoiceChangerProQuoteSlot>): string {\n return (\n PREFIX +\n slots\n .map((slot) => {\n if (slot.kind === \"sts\") return known(slot.seconds) ? `sts-${String(slot.seconds)}` : \"sts\"\n const head = `respeak${respeakEngineToken(slot)}`\n return known(slot.chars) ? `${head}-${String(slot.chars)}` : head\n })\n .join(\",\")\n )\n}\n\nfunction measureOf(text: string | undefined): number | null | undefined {\n if (text === undefined) return null\n const value = Number(text)\n return Number.isFinite(value) && value > 0 ? value : undefined\n}\n\n/**\n * The parts of a `voice-changer-pro:<slots>` id by its shape alone, or\n * undefined (not such an id, an empty or malformed slot). How many slots and\n * what counts the server prices is the server's to say: an id it does not\n * price lands in `missing`.\n */\nexport function parseVoiceChangerProQuoteCreditId(id: string): VoiceChangerProQuoteCreditIdParts | undefined {\n if (typeof id !== \"string\" || !id.startsWith(PREFIX)) return undefined\n const body = id.slice(PREFIX.length)\n if (body.length === 0) return undefined\n const stsSlotSeconds: Array<number | null> = []\n const respeakChars: Array<number | null> = []\n const respeakEngines: Array<VoiceChangerProQuoteRespeakEngine | null> = []\n const respeakTranslated: boolean[] = []\n for (const part of body.split(\",\")) {\n const sts = STS_SLOT.exec(part)\n if (sts) {\n const seconds = measureOf(sts[1])\n if (seconds === undefined) return undefined\n stsSlotSeconds.push(seconds)\n continue\n }\n const respeak = RESPEAK_SLOT.exec(part)\n if (!respeak) return undefined\n const chars = measureOf(respeak[2])\n if (chars === undefined) return undefined\n const token = respeak[1]\n respeakChars.push(chars)\n respeakEngines.push(token === undefined ? null : token === \"v3\" ? \"v3\" : \"v4\")\n respeakTranslated.push(token === \"v4t\")\n }\n return { stsSlotSeconds, respeakChars, respeakEngines, respeakTranslated }\n}\n","/**\n * Pitch & Tempo pricing — per STARTED minute of the input media (decided\n * 2026-10-12), at least one minute, at most 30.\n *\n * One `model_pricing` row, `pitch-tempo`, holds the credits per minute; a run\n * reserves `pitch-tempo:<N>m` (N = started minutes), which billing prices as\n * that row × N — never a row of its own, so a retune of the rate row moves the\n * route, the workflow run, the node's Run button and every estimate together.\n * The same id is built by the route (from the probed length), the workflow run\n * (the same probe) and the editor (the upstream length it knows).\n *\n * Worked examples at the row's listed rate of 20 (repeated in\n * docs/nodes/processing-audio/pitch-tempo.md):\n * 0:45 → 20, 1:00 → 20, 1:01 → 40, 3:10 → 80, 30:00 → 600.\n */\n\nimport { gracedMeasuredSec } from \"../priced-clip-seconds.js\"\n\nexport const PITCH_TEMPO_PRICING = {\n /** The rate row: credits per started minute. Never reserved by itself. */\n RATE_CREDIT_ID: \"pitch-tempo\",\n /** The longest input a run accepts, in seconds (the route refuses longer). */\n MAX_DURATION_SEC: 1800,\n /** The most minutes a `pitch-tempo:<N>m` id can carry. */\n MAX_MINUTES: 30,\n /** The rate row's launch value (admin-retunable in /admin/models). */\n CREDITS_PER_MINUTE_DEFAULT: 20,\n} as const\n\n/** The control ranges every surface validates against. */\nexport const PITCH_TEMPO_LIMITS = {\n SEMITONES_MIN: -12,\n SEMITONES_MAX: 12,\n TEMPO_MIN: 0.5,\n TEMPO_MAX: 2,\n} as const\n\n/**\n * Started minutes of an input of `durationSec` seconds: ceil(sec / 60), at\n * least 1, at most 30. An unknown or non-positive length counts as one minute\n * here; a quote of an unknown length names 30 instead\n * ({@link pitchTempoQuoteCreditId}), and a run always measures.\n */\nexport function pitchTempoStartedMinutes(durationSec: number | null | undefined): number {\n if (typeof durationSec !== \"number\" || !Number.isFinite(durationSec) || durationSec <= 0) return 1\n return Math.min(PITCH_TEMPO_PRICING.MAX_MINUTES, Math.max(1, Math.ceil(durationSec / 60)))\n}\n\n/** `pitch-tempo:<N>m` — the id a run on an input of `durationSec` seconds reserves. */\nexport function pitchTempoCreditId(durationSec: number | null | undefined): string {\n return `pitch-tempo:${pitchTempoStartedMinutes(durationSec)}m`\n}\n\n/**\n * `pitch-tempo:<N>m` — the id a run HOLDS and is CHARGED for an input it\n * measured at `measuredSec` seconds: the started minutes of the length less\n * `CLIP_PRICE_GRACE_SEC` (0.05 s, decided 2026-11-14), so a file a hair past a\n * minute is charged the minute its length is quoted at\n * ({@link pitchTempoQuoteCreditId} reads the length exactly).\n */\nexport function pitchTempoHeldCreditId(measuredSec: number): string {\n // Less a float-noise hair too (`gracedMeasuredSec`): 60.05 s less 0.05 s is 60.00000000000001, not past a minute.\n return pitchTempoCreditId(Math.max(Number.MIN_VALUE, gracedMeasuredSec(measuredSec)))\n}\n\n/**\n * The id a QUOTE names for an input of `durationSec` seconds — every estimate\n * before a run. A known length is the id its run reserves\n * ({@link pitchTempoCreditId}). An UNKNOWN length is the 30-minute id\n * (decided 2026-10-13): a run measures the file before it reserves and refuses\n * one it cannot measure or one over 30 minutes, so 30 minutes is the most any\n * run can be charged and the quote is never below the charge.\n */\nexport function pitchTempoQuoteCreditId(durationSec: number | null | undefined): string {\n const known = typeof durationSec === \"number\" && Number.isFinite(durationSec) && durationSec > 0\n return pitchTempoCreditId(known ? durationSec : PITCH_TEMPO_PRICING.MAX_DURATION_SEC)\n}\n\n/** The minutes of a `pitch-tempo:<N>m` id (1 ≤ N ≤ 30), or `undefined` for any other id. */\nexport function parsePitchTempoCreditId(id: string): { minutes: number } | undefined {\n const m = /^pitch-tempo:(\\d+)m$/.exec(id)\n if (!m) return undefined\n const minutes = Number(m[1])\n if (!Number.isInteger(minutes) || minutes < 1 || minutes > PITCH_TEMPO_PRICING.MAX_MINUTES) return undefined\n return { minutes }\n}\n\n/** rate × minutes, rounded up, at least 1 credit — what a `pitch-tempo:<N>m` id costs. */\nexport function pitchTempoBaseCredits(ratePerMinute: number, minutes: number): number {\n return Math.max(1, Math.ceil(ratePerMinute * minutes))\n}\n\n/** The frequency ratio for a shift of `semitones` (12 = one octave up = ×2). */\nexport function semitonesToPitchRatio(semitones: number): number {\n return 2 ** (semitones / 12)\n}\n","/**\n * Nemotron 3.5 Transcribe pricing — per STARTED minute of the file (decided\n * 2026-11-12): the same price with word timings or a translation.\n *\n * The base price is 0.75 credits a minute, which no whole-credit row can hold\n * (`model_pricing.credit_cost` is an integer), so the rate row prices FOUR\n * minutes — the same trick as Nodaro Video Upscale's four-second rows. A run\n * reserves `nemotron-3-5-transcribe:<N>m` (N = started minutes, 1..60; a\n * measured file's less the one second its charge forgives), which\n * billing prices as that row × N ÷ 4, rounded up once for the whole run, then\n * marked up once — never a row of its own, so a retune of the rate row moves\n * the route, the workflow run, the node's Run button and every estimate\n * together. The same id is built by the route (from the probed length), the\n * workflow run (the same probe) and the editor (the upstream length it knows).\n * That id is the HOLD: a run is then CHARGED for the minutes the provider\n * reports it decoded, up or down (decided 2026-11-12; backend\n * `lib/nemotron-transcribe-settle.ts`).\n *\n * Worked base prices at the row's launch value of 3 (per 4 minutes):\n * 0:45 → 1, 1:00 → 1, 1:05 → 2, 10:00 → 8, 60:00 → 45\n * (a length's started minutes; a measured file up to 1 s past a minute is\n * held and charged the minute below, {@link nemotronHeldMinutes}).\n * The listed (marked-up) price follows from those.\n */\n\n/** The engine's id — the Transcribe node's `provider`, and the bare price id. */\nexport const NEMOTRON_TRANSCRIBE_ID = \"nemotron-3-5-transcribe\"\n\nexport const NEMOTRON_TRANSCRIBE_PRICING = {\n /** The rate row: credits per {@link NEMOTRON_TRANSCRIBE_PRICING.RATE_MINUTES} minutes. Never reserved by itself. */\n RATE_CREDIT_ID: \"nemotron-3-5-transcribe:per-4m\",\n /** The minutes the rate row prices. */\n RATE_MINUTES: 4,\n /** The rate row's launch value (admin-retunable in /admin/models): 0.75 base credits a minute. */\n CREDITS_PER_RATE_DEFAULT: 3,\n /** The longest file a run accepts, in seconds (KIE's 60-minute limit; the route refuses longer). */\n MAX_DURATION_SEC: 3600,\n /** The most minutes a `nemotron-3-5-transcribe:<N>m` id can carry. */\n MAX_MINUTES: 60,\n /** The largest file a run accepts, in bytes (KIE's 200 MB limit). */\n MAX_BYTES: 200 * 1024 * 1024,\n} as const\n\n/**\n * Started minutes of a file of `durationSec` seconds: ceil(sec / 60), at least\n * 1, at most 60. An unknown or non-positive length counts as one minute here; a\n * quote of an unknown length names 60 instead ({@link nemotronTranscribeQuoteCreditId}),\n * as does a run whose file's length cannot be read (it holds 60 minutes and\n * settles at the provider's decoded length).\n */\nexport function nemotronTranscribeStartedMinutes(durationSec: number | null | undefined): number {\n if (typeof durationSec !== \"number\" || !Number.isFinite(durationSec) || durationSec <= 0) return 1\n return Math.min(NEMOTRON_TRANSCRIBE_PRICING.MAX_MINUTES, Math.max(1, Math.ceil(durationSec / 60)))\n}\n\n/** `nemotron-3-5-transcribe:<N>m` — the id of `durationSec` seconds' started minutes (the price of that length; a quote names it). */\nexport function nemotronTranscribeCreditId(durationSec: number | null | undefined): string {\n return `${NEMOTRON_TRANSCRIBE_ID}:${nemotronTranscribeStartedMinutes(durationSec)}m`\n}\n\n/**\n * How far past a whole minute a file may run and still be held and charged the\n * minute below it: one second (decided 2026-11-12 for the charge, which reads\n * KIE's decoded length; the hold reads it too, {@link nemotronHeldMinutes}).\n * Decoders and containers disagree by a few hundredths at a file's end — a\n * 60-second cut re-encoded with its sound measures 60.0004–60.011 s.\n */\nexport const NEMOTRON_UPWARD_GRACE_SEC = 1\n\n/**\n * The started minutes a run HOLDS for a file it measured at `measuredSec`\n * before it runs: those of the length less {@link NEMOTRON_UPWARD_GRACE_SEC},\n * at least 1, at most 60 — the minutes its charge settles at when KIE decodes\n * the file within the grace of them (backend `nemotronChargeId`, which forgives\n * only a length past the HELD minutes). So a quote of a length the graph knows\n * is never below the hold of a file that measures up to the grace past it, and\n * a file a hair past a minute is held and charged as that minute. The one rule\n * both holds read: the Transcribe node's (`nemotronTranscribeHeldCreditId`) and\n * Add Captions' on Nemotron (`addCaptionsNemotronHeldCreditId`).\n */\nexport function nemotronHeldMinutes(measuredSec: number): number {\n return nemotronTranscribeStartedMinutes(measuredSec - NEMOTRON_UPWARD_GRACE_SEC)\n}\n\n/** `nemotron-3-5-transcribe:<N>m` — the id a run on a file it measured at `measuredSec` seconds holds ({@link nemotronHeldMinutes}). */\nexport function nemotronTranscribeHeldCreditId(measuredSec: number): string {\n return `${NEMOTRON_TRANSCRIBE_ID}:${nemotronHeldMinutes(measuredSec)}m`\n}\n\n/**\n * The id a QUOTE names for a file of `durationSec` seconds — every estimate\n * before a run. A known length is the id its run reserves. An UNKNOWN length is\n * the 60-minute id: a run measures the file before it reserves, holds 60\n * minutes for one whose length cannot be read and refuses one over 60 minutes,\n * and the provider refuses longer audio, so 60 minutes is the most any run can\n * be charged and the quote is never below the charge (Pitch & Tempo's rule).\n */\nexport function nemotronTranscribeQuoteCreditId(durationSec: number | null | undefined): string {\n const known = typeof durationSec === \"number\" && Number.isFinite(durationSec) && durationSec > 0\n return nemotronTranscribeCreditId(known ? durationSec : NEMOTRON_TRANSCRIBE_PRICING.MAX_DURATION_SEC)\n}\n\n/** The minutes of a `nemotron-3-5-transcribe:<N>m` id (1 ≤ N ≤ 60), or `undefined` for any other id. */\nexport function parseNemotronTranscribeCreditId(id: string): { minutes: number } | undefined {\n const m = /^nemotron-3-5-transcribe:(\\d+)m$/.exec(id)\n if (!m) return undefined\n const minutes = Number(m[1])\n if (!Number.isInteger(minutes) || minutes < 1 || minutes > NEMOTRON_TRANSCRIBE_PRICING.MAX_MINUTES) return undefined\n return { minutes }\n}\n\n/**\n * The base of a run of `minutes` started minutes from the rate row's value\n * (`ratePerBlock` credits per {@link NEMOTRON_TRANSCRIBE_PRICING.RATE_MINUTES}\n * minutes): rate × minutes ÷ 4, rounded up once for the whole run, at least 1.\n */\nexport function nemotronTranscribeBaseCredits(ratePerBlock: number, minutes: number): number {\n return Math.max(1, Math.ceil((ratePerBlock * minutes) / NEMOTRON_TRANSCRIBE_PRICING.RATE_MINUTES))\n}\n","/**\n * Add Captions transcribing on Nemotron 3.5 Transcribe — ONE charge for the\n * render and its transcription (decided 2026-11-13).\n *\n * Every Add Captions render that transcribes is a Remotion render\n * (`captionRoutesToRemotion`), billed at the kinetic row. On the other engines\n * that flat row covers the transcription too. Nemotron is priced by the\n * video's length, so its caption run holds\n * `add-captions:kinetic:nemotron:<N>m` (N = started minutes of the video,\n * 1..60): the kinetic row plus Nemotron's own per-minute price (its four-minute\n * rate row × N ÷ 4, rounded up once), summed into one base and marked up once\n * — never a row of its own, so a retune of either row moves every price\n * together. The id keeps the `add-captions` prefix, so Add Captions' margin\n * applies to the whole charge.\n *\n * It is held only when a transcription will actually run on Nemotron; a\n * Nemotron node that brings its own captions, transcript or static text holds\n * the plain kinetic row. Like the Transcribe node's id it is the HOLD: the run\n * is charged for the minutes the provider reports it decoded, up or down\n * (backend `lib/nemotron-transcribe-settle.ts`).\n */\nimport {\n NEMOTRON_TRANSCRIBE_PRICING,\n nemotronHeldMinutes,\n nemotronTranscribeBaseCredits,\n nemotronTranscribeStartedMinutes,\n} from \"./nemotron-transcribe.js\"\n\n/** The Remotion render's row — every Add Captions render that transcribes. */\nexport const ADD_CAPTIONS_KINETIC_CREDIT_ID = \"add-captions:kinetic\"\n\n/** The prefix of the per-minute ids a Nemotron caption run holds. */\nexport const ADD_CAPTIONS_NEMOTRON_ID_PREFIX = `${ADD_CAPTIONS_KINETIC_CREDIT_ID}:nemotron`\n\n/** `add-captions:kinetic:nemotron:<N>m` for N started minutes (1..60, clamped). */\nexport function addCaptionsNemotronMinutesId(minutes: number): string {\n const n = Math.min(NEMOTRON_TRANSCRIBE_PRICING.MAX_MINUTES, Math.max(1, Math.ceil(minutes)))\n return `${ADD_CAPTIONS_NEMOTRON_ID_PREFIX}:${n}m`\n}\n\n/** The id of a Nemotron caption run on a video of `durationSec` seconds' started minutes (the price of that length; a quote names it). */\nexport function addCaptionsNemotronCreditId(durationSec: number | null | undefined): string {\n return addCaptionsNemotronMinutesId(nemotronTranscribeStartedMinutes(durationSec))\n}\n\n/**\n * The id a Nemotron caption run on a video it measured at `measuredSec`\n * seconds HOLDS: the started minutes less the one second its charge forgives\n * (`nemotronHeldMinutes`, the Transcribe node's own rule).\n */\nexport function addCaptionsNemotronHeldCreditId(measuredSec: number): string {\n return addCaptionsNemotronMinutesId(nemotronHeldMinutes(measuredSec))\n}\n\n/**\n * The id a QUOTE names for a video of `durationSec` seconds — every estimate\n * before a run. A known length is the id its run holds; an UNKNOWN length is\n * the 60-minute id, the most any run can be charged (a run measures the video\n * first, holds 60 minutes for one whose length cannot be read, and refuses one\n * over 60 minutes).\n */\nexport function addCaptionsNemotronQuoteCreditId(durationSec: number | null | undefined): string {\n const known = typeof durationSec === \"number\" && Number.isFinite(durationSec) && durationSec > 0\n return addCaptionsNemotronCreditId(known ? durationSec : NEMOTRON_TRANSCRIBE_PRICING.MAX_DURATION_SEC)\n}\n\n/** The minutes of an `add-captions:kinetic:nemotron:<N>m` id (1 ≤ N ≤ 60), or `undefined` for any other id. */\nexport function parseAddCaptionsNemotronCreditId(id: string): { minutes: number } | undefined {\n const m = /^add-captions:kinetic:nemotron:(\\d+)m$/.exec(id)\n if (!m) return undefined\n const minutes = Number(m[1])\n if (!Number.isInteger(minutes) || minutes < 1 || minutes > NEMOTRON_TRANSCRIBE_PRICING.MAX_MINUTES) return undefined\n return { minutes }\n}\n\n/**\n * The base of a Nemotron caption run of `minutes` started minutes: the kinetic\n * row's base plus Nemotron's per-minute base for those minutes (`ratePerBlock`\n * credits per four minutes, rounded up once). Marked up once, as one charge.\n */\nexport function addCaptionsNemotronBaseCredits(kineticBase: number, ratePerBlock: number, minutes: number): number {\n return kineticBase + nemotronTranscribeBaseCredits(ratePerBlock, minutes)\n}\n","/**\n * Video Overlay pricing — which row a run is charged from, and how many units\n * of it. One mapping for every place that names the price: the route\n * (`POST /v1/video-overlay`), the workflow run's reservation, the node's Run\n * button and the workflow estimates.\n *\n * An image-only run is the flat `video-overlay` row, whatever its layers or\n * the base's length; its base is never measured for the price. A run with any\n * video layer is charged the `video-overlay:video` row once per started 5\n * seconds of the output — the base's length, which is the output's — the unit\n * Mask Composite is charged by. The route and the workflow run measure the\n * base before anything is reserved, and refuse one they cannot read or one\n * past {@link VIDEO_OVERLAY_PRICING.MAX_BASE_SEC}. Before a run, a base whose\n * length is not known yet is quoted at that cap, so a quote is never below\n * what the run is charged.\n *\n * Worked examples, in units of the `video-overlay:video` row:\n * 10 s → 2, 23 s → 5, 60 s → 12, unknown → 12, 61 s → refused.\n */\nimport { pricedClipSeconds } from \"../priced-clip-seconds.js\"\nimport { VIDEO_OVERLAY_VIDEO_MAX_BASE_SEC } from \"../video-overlay.js\"\n\nexport const VIDEO_OVERLAY_PRICING = {\n /** An image-only run: one flat row. */\n IMAGE_CREDIT_ID: \"video-overlay\",\n /** A run with a video layer: one row per started {@link VIDEO_OVERLAY_PRICING.UNIT_SEC} seconds of the output. */\n VIDEO_CREDIT_ID: \"video-overlay:video\",\n /** Seconds of output one unit of the video row covers. */\n UNIT_SEC: 5,\n /** The longest base a run with a video layer accepts, in seconds. */\n MAX_BASE_SEC: VIDEO_OVERLAY_VIDEO_MAX_BASE_SEC,\n} as const\n\n/**\n * How much longer, in seconds, the base the worker downloads may run than the\n * base measured before the run was charged, before the worker refuses it as\n * changed: a re-measure can read a hair longer (a re-encode, a container's\n * rounding), and that is not a different file. Applied to the seconds, never\n * to the units: a base billed for 10 s renders at up to 10.5 s.\n */\nexport const VIDEO_OVERLAY_REMEASURE_SLACK_SEC = 0.5\n\n/** The row a run is charged from: the flat image row, or the per-5-second video row when any layer is a video. */\nexport function videoOverlayCreditId(hasVideoLayer: boolean): string {\n return hasVideoLayer ? VIDEO_OVERLAY_PRICING.VIDEO_CREDIT_ID : VIDEO_OVERLAY_PRICING.IMAGE_CREDIT_ID\n}\n\n/**\n * Units of the video row for a base `baseSec` long: one per started 5\n * seconds, at least one, after `pricedClipSeconds` (up to 0.05 s past a whole\n * second is ignored, so a 10.01 s base is 2 units). An unknown length counts\n * the cap — the pre-run quote for a base not measured yet — and so does a\n * length past it (such a base is refused before anything is reserved).\n */\nexport function videoOverlayVideoUnits(baseSec: number | null | undefined): number {\n const sec =\n typeof baseSec === \"number\" && Number.isFinite(baseSec) && baseSec > 0\n ? Math.min(baseSec, VIDEO_OVERLAY_PRICING.MAX_BASE_SEC)\n : VIDEO_OVERLAY_PRICING.MAX_BASE_SEC\n return Math.ceil(pricedClipSeconds(sec) / VIDEO_OVERLAY_PRICING.UNIT_SEC)\n}\n\n/**\n * Whether a measured base is past the cap for a run with a video layer. Read\n * on the priced seconds the units use, so a base the price counts as 60 s\n * (60.04 s, a whole-second cut of a 29.97 fps clip) is accepted at 12 units.\n */\nexport function videoOverlayBaseTooLong(baseSec: number): boolean {\n return pricedClipSeconds(baseSec) > VIDEO_OVERLAY_PRICING.MAX_BASE_SEC\n}\n","/**\n * Topaz image upscale — the single authority for \"which lever did the user\n * pull, what do we send, and what do we charge\".\n *\n * KIE's `topaz/image-upscale` takes exactly ONE quality lever:\n * upscale_factor: \"1\" | \"2\" | \"4\" (default \"2\")\n * There is no target-resolution parameter (docs.kie.ai/market/topaz/image-upscale,\n * verified 2026-09-02). The editor nevertheless shipped TWO controls — an\n * `upscaleFactor` select AND a `targetResolution` select (2K/4K/8K) — and billed\n * on the second one, which never reached the worker. Everyone who bought 4K or\n * 8K got a 2x render at 2x/4x the price (app-reports triage 2026-09-01 §4.3).\n *\n * So: the FACTOR is the lever. `targetResolution` survives only as a legacy\n * input (stored node data, old API/MCP callers) and is mapped forward here.\n * The credit tier is derived from the SAME resolution, which is why callers\n * must pass `creditTier` into `buildCreditModelIdentifier` rather than the raw\n * request value — that is what makes CHECK = DEBIT = SENT.\n *\n * The composite `topaz-image-upscale:4K` is retained as the id of the 4x tier\n * (migration 288 wrote that row; renaming it would need a pricing migration for\n * zero user-visible gain). Read it as \"the top Topaz tier\", not as a promise of\n * 4096 pixels. `topaz-image-upscale:8K` stays priced in STATIC_CREDIT_COSTS so\n * historical usage_logs still resolve, but nothing can reserve it any more.\n *\n * Resolution order (fix round 1, 2026-09-02 review):\n * 1. Resolve the WINNING factor first — a valid `upscaleFactor` always wins;\n * an invalid one falls through to `targetResolution` exactly as if it had\n * never been sent, rather than freezing the default before the legacy\n * tier gets a chance to raise it (an invalid factor + a stored 4K/8K tier\n * must still resolve — and bill — at the tier's factor, not the default).\n * 2. Only THEN build `adjustments`, so every `to` reflects the resolved\n * factor rather than an intermediate guess, and every `from` is the raw,\n * untransformed input string (never the trimmed/uppercased copy used\n * internally to match).\n * 3. A valid `upscaleFactor` alongside a `targetResolution` it disagrees\n * with emits an informational (not corrective) adjustment — the stored\n * legacy choice is being overridden, not silently dropped — with\n * `to: undefined` because nothing was actually sent for that field.\n * Agreement (they resolve to the same factor) is reported as nothing:\n * there is no override to disclose.\n */\n\nexport type TopazUpscaleFactor = \"1\" | \"2\" | \"4\"\n\nexport const TOPAZ_UPSCALE_FACTORS: readonly TopazUpscaleFactor[] = [\"1\", \"2\", \"4\"]\n\n/** KIE's own default when `upscale_factor` is omitted (providers/kie/models.ts). */\nexport const TOPAZ_DEFAULT_UPSCALE_FACTOR: TopazUpscaleFactor = \"2\"\n\nexport interface TopazUpscaleAdjustment {\n field: \"upscaleFactor\" | \"targetResolution\"\n /** The raw, untransformed value as received — never trimmed or case-normalized. */\n from: string\n /**\n * The resolved factor this adjustment corresponds to, or `undefined` for the\n * informational \"your stored targetResolution was overridden\" notice, which\n * names nothing to switch TO — `upscaleFactor` already won.\n */\n to: string | undefined\n reason: string\n}\n\nexport interface TopazUpscaleResolution {\n /** Sent to KIE as `upscale_factor`. Always set — never rely on the model default. */\n upscaleFactor: TopazUpscaleFactor\n /**\n * Passed VERBATIM as `buildCreditModelIdentifier`'s `targetResolution` arg.\n * `undefined` = the bare id (1x / 2x); `\"4K\"` = the 4x tier.\n */\n creditTier: \"4K\" | undefined\n /** Non-empty when a legacy or out-of-enum value was coerced or overridden. */\n adjustments: TopazUpscaleAdjustment[]\n}\n\n/** Legacy 2K/4K/8K tier → the factor the provider can actually deliver. */\nconst LEGACY_TIER_TO_FACTOR: Record<string, TopazUpscaleFactor> = {\n \"2K\": \"2\",\n \"4K\": \"4\",\n \"8K\": \"4\",\n}\n\nfunction isFactor(v: string): v is TopazUpscaleFactor {\n return (TOPAZ_UPSCALE_FACTORS as readonly string[]).includes(v)\n}\n\nexport function resolveTopazUpscale(input: {\n upscaleFactor?: string | null\n targetResolution?: string | null\n}): TopazUpscaleResolution {\n const adjustments: TopazUpscaleAdjustment[] = []\n\n // Raw, untransformed inputs — these are what every adjustment's `from` reports.\n const rawFactor = typeof input.upscaleFactor === \"string\" ? input.upscaleFactor : \"\"\n const rawTier = typeof input.targetResolution === \"string\" ? input.targetResolution : \"\"\n\n // Trimmed/normalized copies used ONLY for matching, never for display.\n const trimmedFactor = rawFactor.trim()\n const normalizedTier = rawTier.trim().toUpperCase()\n\n const factorGiven = trimmedFactor.length > 0\n const factorValid = factorGiven && isFactor(trimmedFactor)\n\n const tierGiven = normalizedTier.length > 0\n const tierMappedFactor = tierGiven ? LEGACY_TIER_TO_FACTOR[normalizedTier] : undefined\n\n // --- 1. Resolve the winning factor FIRST. ---\n // A valid factor always wins. An invalid (or absent) one falls through to\n // whatever the legacy tier maps to; only if that also comes up empty do we\n // land on the provider default.\n const finalFactor: TopazUpscaleFactor = factorValid\n ? (trimmedFactor as TopazUpscaleFactor)\n : (tierMappedFactor ?? TOPAZ_DEFAULT_UPSCALE_FACTOR)\n\n // --- 2. Emit adjustments LAST, against the already-resolved factor. ---\n if (factorGiven && !factorValid) {\n adjustments.push({\n field: \"upscaleFactor\",\n from: rawFactor,\n to: finalFactor,\n reason: `Topaz upscale accepts a factor of 1, 2 or 4 — \"${rawFactor}\" was replaced with ${finalFactor}.`,\n })\n }\n\n if (factorValid && tierGiven) {\n // The factor won outright. Say so if it disagrees with the stored legacy\n // tier — otherwise the tier silently vanishes with no record. Agreement\n // needs no note: nothing was overridden.\n if (tierMappedFactor !== finalFactor) {\n adjustments.push({\n field: \"targetResolution\",\n from: rawTier,\n to: undefined,\n reason: \"upscaleFactor takes precedence over the legacy targetResolution.\",\n })\n }\n } else if (!factorValid && tierGiven) {\n // No valid explicit factor — the legacy tier is the (partial) source of\n // the resolved factor, or was consulted and found unusable.\n if (tierMappedFactor) {\n if (normalizedTier === \"8K\") {\n adjustments.push({\n field: \"targetResolution\",\n from: rawTier,\n to: finalFactor,\n reason: \"Topaz upscale offers factors up to 4x — an 8K target renders and bills at the 4x tier.\",\n })\n }\n } else {\n adjustments.push({\n field: \"targetResolution\",\n from: rawTier,\n to: finalFactor,\n reason: `Unknown Topaz target \"${rawTier}\" — rendering at ${finalFactor}x.`,\n })\n }\n }\n\n return {\n upscaleFactor: finalFactor,\n creditTier: finalFactor === \"4\" ? \"4K\" : undefined,\n adjustments,\n }\n}\n","/**\n * The upscale FACTOR of the image upscalers that take one — which factors each\n * model accepts, and the factor a request renders at. One authority for the\n * route's enum, the editor's dropdown and its fail-safe snap, the workflow\n * payload, the worker, MCP and the SDK.\n *\n * Two models take a factor:\n * - `topaz-image-upscale`: 1, 2 or 4 — resolved by `resolveTopazUpscale`,\n * which also maps its legacy `targetResolution` (unchanged here).\n * - `nodaro-image-upscale`: 1, 2, 4 or 8. A factor multiplies both sides; 1\n * enhances the picture at its own size. Anything else is rendered at the\n * default, 2. It has no `targetResolution`: its price follows the output's\n * size (`@nodaro/render-rules` nodaro-image-upscale-pricing.ts), so a stored\n * tier from another model is never read.\n *\n * Every other model (Recraft, and the edit models) declares no factor list,\n * and a factor stored or mapped onto its node is passed on exactly as it\n * always was — \"1\", \"2\" and \"4\" are the values the route takes for it — except\n * a factor only the house model takes ({@link HOUSE_ONLY_UPSCALE_FACTORS}, \"8\"):\n * no other model takes it, so it is never sent to one, and the editor clears\n * it from a node switched away from Nodaro Image Upscale.\n */\nimport { resolveTopazUpscale, TOPAZ_UPSCALE_FACTORS } from \"./topaz-upscale.js\"\n\n/** Nodaro Image Upscale's model id. */\nexport const NODARO_IMAGE_UPSCALE_MODEL_ID = \"nodaro-image-upscale\"\n\nexport type NodaroImageUpscaleFactor = \"1\" | \"2\" | \"4\" | \"8\"\n\n/** The factors Nodaro Image Upscale renders at, smallest first. */\nexport const NODARO_IMAGE_UPSCALE_FACTORS: readonly NodaroImageUpscaleFactor[] = [\"1\", \"2\", \"4\", \"8\"]\n\n/** The factor a Nodaro Image Upscale request without a valid one renders at. */\nexport const NODARO_IMAGE_UPSCALE_DEFAULT_FACTOR: NodaroImageUpscaleFactor = \"2\"\n\n/** Every factor any image upscaler takes — the vocabulary the request enums carry. Each model's own list is {@link upscaleFactorsFor}. */\nexport const UPSCALE_FACTORS = [\"1\", \"2\", \"4\", \"8\"] as const\nexport type UpscaleFactor = (typeof UPSCALE_FACTORS)[number]\n\n/** The factor Nodaro Image Upscale renders `raw` at: a listed factor as given (trimmed), anything else the default. */\nexport function resolveNodaroImageUpscaleFactor(raw: unknown): NodaroImageUpscaleFactor {\n const trimmed = typeof raw === \"string\" ? raw.trim() : typeof raw === \"number\" ? String(raw) : \"\"\n return (NODARO_IMAGE_UPSCALE_FACTORS as readonly string[]).includes(trimmed)\n ? (trimmed as NodaroImageUpscaleFactor)\n : NODARO_IMAGE_UPSCALE_DEFAULT_FACTOR\n}\n\n/**\n * The factors only Nodaro Image Upscale takes: every other model's request\n * refuses them (Topaz's list, and the 1/2/4 the route takes for a model with\n * no list of its own), so none is ever sent to another model. \"8\".\n */\nexport const HOUSE_ONLY_UPSCALE_FACTORS: readonly UpscaleFactor[] = NODARO_IMAGE_UPSCALE_FACTORS.filter(\n (f) => !(TOPAZ_UPSCALE_FACTORS as readonly string[]).includes(f),\n)\n\n/** True when `value` is a factor only Nodaro Image Upscale takes ({@link HOUSE_ONLY_UPSCALE_FACTORS}). */\nfunction isHouseOnlyUpscaleFactor(value: string): boolean {\n return (HOUSE_ONLY_UPSCALE_FACTORS as readonly string[]).includes(value.trim())\n}\n\n/** The factors `provider` accepts, or undefined for a model that declares no factor list. */\nexport function upscaleFactorsFor(provider: unknown): readonly UpscaleFactor[] | undefined {\n if (provider === NODARO_IMAGE_UPSCALE_MODEL_ID) return NODARO_IMAGE_UPSCALE_FACTORS\n if (provider === \"topaz-image-upscale\") return TOPAZ_UPSCALE_FACTORS\n return undefined\n}\n\n/**\n * The factor a request to `provider` sends: Topaz's through `resolveTopazUpscale`\n * (its legacy `targetResolution` included), Nodaro Image Upscale's through\n * {@link resolveNodaroImageUpscaleFactor}, and any other model's value as\n * given — except a factor only the house model takes (\"8\"), which is not\n * sent. What the editor's panel snaps a stale value to, and what the editor's\n * Run and the workflow payload send.\n */\nexport function resolveUpscaleFactor(\n provider: unknown,\n input: { upscaleFactor?: unknown; targetResolution?: unknown },\n): string | undefined {\n if (provider === NODARO_IMAGE_UPSCALE_MODEL_ID) return resolveNodaroImageUpscaleFactor(input.upscaleFactor)\n if (provider === \"topaz-image-upscale\") {\n return resolveTopazUpscale({\n upscaleFactor: typeof input.upscaleFactor === \"string\" ? input.upscaleFactor : undefined,\n targetResolution: typeof input.targetResolution === \"string\" ? input.targetResolution : undefined,\n }).upscaleFactor\n }\n return typeof input.upscaleFactor === \"string\" && !isHouseOnlyUpscaleFactor(input.upscaleFactor) ? input.upscaleFactor : undefined\n}\n\n/**\n * The factor a node on `provider` must carry instead of its stored one — the\n * one the run would render ({@link resolveUpscaleFactor}) — `null` when it\n * must carry none, or undefined when the stored factor stands. What the editor\n * writes when a stale factor meets a model that does not take it: a Nodaro\n * Image Upscale 8x switched to Topaz runs, and is stored, at 2x; one switched\n * to a model with no factor list (Recraft) keeps no factor. Any other factor\n * on such a model stands exactly as it always did (a saved Recraft node's \"4\"\n * is never rewritten), as does none stored, or one the model takes.\n */\nexport function snappedUpscaleFactor(\n provider: unknown,\n input: { upscaleFactor?: unknown; targetResolution?: unknown },\n): string | null | undefined {\n const stored = typeof input.upscaleFactor === \"string\" ? input.upscaleFactor : undefined\n if (stored === undefined) return undefined\n const factors = upscaleFactorsFor(provider)\n if (!factors) return isHouseOnlyUpscaleFactor(stored) ? null : undefined\n if ((factors as readonly string[]).includes(stored)) return undefined\n return resolveUpscaleFactor(provider, input) ?? null\n}\n","/**\n * Calculate the creator's monetization markup on a base credit cost.\n * Returns the markup amount (not the total).\n */\nexport function calculateMonetizationMarkup(baseCost: number, flatFee: number, percent: number): number {\n if (flatFee <= 0 && percent <= 0) return 0\n return flatFee + Math.ceil(baseCost * percent / 100)\n}\n\n/**\n * Calculate the total cost a runner pays (base + markup).\n */\nexport function calculateMonetizedCost(baseCost: number, flatFee: number, percent: number): number {\n return baseCost + calculateMonetizationMarkup(baseCost, flatFee, percent)\n}\n","/**\n * Lip-sync per-second pricing helpers.\n *\n * KIE.ai Kling AI Avatar 2.0 (May 2026) raised the max input audio from 15s\n * to 5 minutes and bills per-second. We bucket the requested audio duration\n * into discrete tiers and use composite credit identifiers\n * (e.g. `kling-avatar:60s`) so credit reservation scales with input length.\n *\n * InfiniTalk still enforces a 15s upstream cap.\n *\n * A model listed in {@link LIP_SYNC_AUDIO_RATES} is priced differently: at a\n * per-second RATE times the seconds of its audio, never by bucket.\n */\n\nimport { unitQuoteCreditId } from \"./credit-estimators/unit-quote.js\"\nimport { gracedMeasuredSec } from \"./priced-clip-seconds.js\"\n\n/**\n * A lip-sync model charged at a per-second rate: the rate's one-second price\n * row times the seconds of the audio that drives it, rounded up once and marked\n * up once by the pricing chain that charges every per-unit rate.\n */\nexport interface LipSyncAudioRate {\n /** The one-second price row (`model_pricing`, else `STATIC_CREDIT_COSTS`). */\n readonly rateId: string\n /** The fewest seconds a run is charged. Shorter audio is padded with silence to this length before the model sees it. */\n readonly minSeconds: number\n /** The longest audio the model takes. Longer audio is refused before anything is held. */\n readonly maxSeconds: number\n}\n\n/** OmniHuman 2.0's one-second price row. */\nexport const OMNIHUMAN_2_0_PER_SECOND_CREDIT_ID = \"omnihuman-2-0:per-second\"\n\n/**\n * The lip-sync models charged per second of audio at a rate (decided\n * 2026-11-11 for OmniHuman 2.0). Every price of such a run, its quote and its\n * hold are the rate × {@link lipSyncBilledSeconds}.\n */\nexport const LIP_SYNC_AUDIO_RATES: Readonly<Record<string, LipSyncAudioRate>> = {\n // OmniHuman 2.0 (KIE): audio from 4 to 300 seconds; the output is as long as the audio.\n \"omnihuman-2-0\": { rateId: OMNIHUMAN_2_0_PER_SECOND_CREDIT_ID, minSeconds: 4, maxSeconds: 300 },\n}\n\n/** The per-second rate a lip-sync model is charged at, or undefined for every model priced another way. */\nexport function lipSyncAudioRateOf(provider: unknown): LipSyncAudioRate | undefined {\n return typeof provider === \"string\" && Object.prototype.hasOwnProperty.call(LIP_SYNC_AUDIO_RATES, provider)\n ? LIP_SYNC_AUDIO_RATES[provider]\n : undefined\n}\n\n/**\n * The seconds a run of a per-second-rate model is charged for audio measured at\n * `measuredSec`: rounded up to a whole second, and at least the rate's minimum.\n * THE one place this rounding happens — the route, the workflow run, the\n * estimates and the provider's own cost all read it. Pass the length of the\n * audio as it was given, never of a copy padded to the minimum (a padded clip\n * runs a hair past it and would round up a whole second more).\n */\nexport function lipSyncBilledSeconds(rate: LipSyncAudioRate, measuredSec: number): number {\n if (!Number.isFinite(measuredSec) || measuredSec <= 0) return rate.minSeconds\n return Math.max(rate.minSeconds, Math.ceil(measuredSec))\n}\n\n/**\n * The seconds a run of a per-second-rate model is HELD and CHARGED for audio\n * it measured at `measuredSec`: {@link lipSyncBilledSeconds} of the length less\n * `CLIP_PRICE_GRACE_SEC` (0.05 s, decided 2026-11-14), so audio a hair past a\n * whole second (a decoder's few hundredths at a file's end) is charged the\n * second its length is quoted at. A quote reads the length exactly\n * ({@link lipSyncEstimateSeconds}).\n */\nexport function lipSyncHeldSeconds(rate: LipSyncAudioRate, measuredSec: number): number {\n if (!Number.isFinite(measuredSec) || measuredSec <= 0) return rate.minSeconds\n return lipSyncBilledSeconds(rate, Math.max(Number.MIN_VALUE, gracedMeasuredSec(measuredSec)))\n}\n\n\n/**\n * The length the editor quotes a lip-sync run on while its audio's length is\n * not known yet — the 15 seconds every model priced by its audio shows then\n * (a bucketed model's `:15s` row), marked as an estimate.\n */\nexport const LIP_SYNC_UNMEASURED_ESTIMATE_SECONDS = 15\n\n/**\n * The seconds an ESTIMATE prices a per-second-rate run at: the billed seconds\n * of the audio when its length is known (at most the model's maximum, the most\n * a run can be charged), else `unknownSec` — by default the maximum, so a\n * server estimate never quotes below what the run may hold; the editor passes\n * {@link LIP_SYNC_UNMEASURED_ESTIMATE_SECONDS} and shows the figure as an estimate.\n */\nexport function lipSyncEstimateSeconds(rate: LipSyncAudioRate, knownSec: number | undefined, unknownSec: number = rate.maxSeconds): number {\n if (knownSec === undefined || !Number.isFinite(knownSec) || knownSec <= 0) return lipSyncBilledSeconds(rate, unknownSec)\n return lipSyncBilledSeconds(rate, Math.min(knownSec, rate.maxSeconds))\n}\n\nexport const LIP_SYNC_DURATION_BUCKETS = [15, 30, 60, 120, 300] as const\n\nexport type LipSyncDurationBucket = typeof LIP_SYNC_DURATION_BUCKETS[number]\n\n/** Round a measured audio duration up to the next supported bucket. */\nexport function pickLipSyncBucket(seconds: number): LipSyncDurationBucket {\n if (!Number.isFinite(seconds) || seconds <= 0) return LIP_SYNC_DURATION_BUCKETS[0]\n for (const b of LIP_SYNC_DURATION_BUCKETS) {\n if (seconds <= b) return b\n }\n return 300\n}\n\n/**\n * Upper audio-duration limit per lip-sync provider, in seconds.\n * Anything longer must be trimmed (server-side) before sending upstream.\n */\nexport const LIP_SYNC_MAX_AUDIO_SECONDS: Record<string, number> = {\n \"kling-avatar\": 300,\n \"kling-avatar-pro\": 300,\n \"infinitalk\": 15,\n // OmniHuman 1.5 — KIE hard limit is < 60s; audio is auto-trimmed to this cap.\n \"omnihuman-1-5\": 60,\n // HeyGen Lipsync Precision + Sync Lipsync 2 Pro — billed per output second.\n // 5-min ceiling for credit bucketing (mirrors kling-avatar). MUST be set:\n // the default fallback below is 15s, which would clamp every request to the\n // 15s bucket and silently under-charge long clips.\n \"heygen-lipsync-precision\": 300,\n \"lipsync-2-pro\": 300,\n // Sync Lipsync v3 (fal.ai) — per-second dubbing, 5-min ceiling for bucketing.\n \"sync-lipsync-v3\": 300,\n // Volcengine (KIE) — video-to-video dubbing, per-second, 5-min ceiling.\n \"volcengine-lipsync\": 300,\n // LatentSync — its output is as long as its audio, and its run time grows\n // with that length. 5-min ceiling: longer audio is priced at it and cut to it.\n \"latentsync\": 300,\n // The per-second-rate models: their own maximum (longer audio is refused; up to the 0.05 s its hold forgives past it, held at the maximum and cut to it).\n ...Object.fromEntries(Object.entries(LIP_SYNC_AUDIO_RATES).map(([provider, rate]) => [provider, rate.maxSeconds])),\n}\n\nexport function getLipSyncMaxAudioSeconds(provider: string): number {\n return LIP_SYNC_MAX_AUDIO_SECONDS[provider] ?? 15\n}\n\n/**\n * The id whose price is a 15-second run of a lip-sync model priced by the\n * length of its audio — the bucket row of a bucketed model (`<provider>:15s`),\n * the 15-second quote of a per-second-rate model — or undefined for a model\n * with one price. A model menu shows a per-second rate from it.\n */\nexport function lipSyncFifteenSecondCreditId(provider: string): string | undefined {\n const rate = lipSyncAudioRateOf(provider)\n if (rate) return unitQuoteCreditId(rate.rateId, LIP_SYNC_UNMEASURED_ESTIMATE_SECONDS)\n return isPerSecondLipSyncProvider(provider) ? `${provider}:${LIP_SYNC_UNMEASURED_ESTIMATE_SECONDS}s` : undefined\n}\n\n/**\n * Providers whose credit cost varies with audio duration, priced by BUCKET\n * (`<provider>:<bucket>s`). A model charged at a per-second rate\n * ({@link LIP_SYNC_AUDIO_RATES}) is never listed here: every caller that\n * branches on this set would bucket it.\n */\nconst PER_SECOND_LIP_SYNC_PROVIDERS = new Set([\n \"kling-avatar\",\n \"kling-avatar-pro\",\n // OmniHuman 1.5 — /sec, bucketed by audio length (60s cap).\n \"omnihuman-1-5\",\n \"heygen-lipsync-precision\",\n \"lipsync-2-pro\",\n // Sync Lipsync v3 (fal.ai) — billed per output second (/min).\n \"sync-lipsync-v3\",\n // Volcengine (KIE) — video-to-video dubbing, billed per output second.\n \"volcengine-lipsync\",\n // LatentSync — held by the bucket of its audio's length and charged what the\n // run used (LIP_SYNC_CHARGED_AT_RUN_COST below).\n \"latentsync\",\n])\n\nexport function isPerSecondLipSyncProvider(provider: string): boolean {\n return PER_SECOND_LIP_SYNC_PROVIDERS.has(provider)\n}\n\n/**\n * Bucketed lip-sync models whose bucket row is a HOLD, not the charge (decided\n * 2026-11-18): the run is charged what it used once it ends. Less than the\n * hold releases the rest; more is collected from the payer's balance. The\n * work such a model does grows with its audio's length AND with settings the\n * bucket cannot see (LatentSync's inference steps, the size of its video), so\n * one fixed row per bucket would be wrong for most runs. Every other bucketed\n * model is charged its bucket row as it is.\n *\n * A member MUST be a bucketed model (`isPerSecondLipSyncProvider`): the hold is\n * its bucket row. `lip-sync-pricing.test.ts` holds that.\n */\nexport const LIP_SYNC_CHARGED_AT_RUN_COST: ReadonlySet<string> = new Set([\"latentsync\"])\n\n/** Is this lip-sync model charged what its run used, with its bucket row as the hold? */\nexport function isLipSyncChargedAtRunCost(provider: unknown): boolean {\n return typeof provider === \"string\" && LIP_SYNC_CHARGED_AT_RUN_COST.has(provider)\n}\n\n/**\n * Build the credit identifier for a lip-sync request.\n *\n * For kling-avatar / kling-avatar-pro, returns `<provider>:<bucket>s`.\n * For other providers, returns the bare provider name (caller appends\n * any extra dimensions like resolution).\n *\n * If `audioDurationSec` is missing, defaults to the provider's max cap so\n * credit reservation covers the worst case and any overage is refunded\n * after the worker reconciles the actual KIE cost.\n */\nexport function buildLipSyncCreditId(\n provider: string,\n audioDurationSec: number | undefined,\n): string {\n if (!isPerSecondLipSyncProvider(provider)) return provider\n const cap = getLipSyncMaxAudioSeconds(provider)\n const requested = audioDurationSec === undefined || audioDurationSec <= 0\n ? cap\n : Math.min(audioDurationSec, cap)\n return `${provider}:${pickLipSyncBucket(requested)}s`\n}\n","/**\n * How a Motion Transfer run is priced (decided 2026-11-18): from the length of\n * its DRIVING video as the server reads it, never a length the caller\n * declares.\n *\n * - Every model is refused below {@link MOTION_TRANSFER_MIN_SEC} and past its\n * limit ({@link motionTransferMaxSec}: Kling 2.6 and Kling 3.0 take 10\n * seconds while the character keeps the image's orientation — the default —\n * and 30 while it follows the video's; Wan Animate takes 30). A clip up to\n * `CLIP_PRICE_GRACE_SEC` past a limit is accepted and priced at it.\n * - Every model and size is charged per second of that video\n * ({@link MOTION_TRANSFER_SECOND_RATES}): its rate row × the billed seconds\n * ÷ the seconds the row prices, rounded up once, marked up once — the hold\n * IS the charge.\n * - Wan Animate keeps its flat price by size as a FLOOR: a run is charged the\n * larger of its rate's figure and its floor row, compared as base credits\n * ({@link motionTransferChargedPrice}), and the run is\n * charged at the row that won — the floor row once, or the rate row × its\n * units — so the usage log, the whole-run quote id (`<rate>:<N>u`) and the\n * flat row's own price each name exactly what was charged.\n *\n * Billed seconds are the length rounded up to a whole second after the house\n * grace ({@link motionTransferBilledSeconds}). The route, the workflow run,\n * the MCP verb (which calls the route) and both estimates read this one\n * module. The old length-tier rows (`buildMotionCreditModelIdentifier`) are no\n * run's price any more; they stay for older code and saved quotes.\n */\nimport { motionTransferResolution } from \"./credit-identifiers.js\"\nimport { CLIP_PRICE_GRACE_SEC, gracedMeasuredSec } from \"./priced-clip-seconds.js\"\n\n/** Float noise: a length that is arithmetic can land a hair past a limit, and must not be refused for it. */\nconst FLOAT_NOISE_SEC = 1e-9\n\n/** The shortest driving video any Motion Transfer model takes. */\nexport const MOTION_TRANSFER_MIN_SEC = 3\n\n/** The longest driving video Kling 2.6 / Kling 3.0 take while the character keeps the image's orientation. */\nexport const MOTION_TRANSFER_IMAGE_ORIENTATION_MAX_SEC = 10\n\n/** The longest driving video any Motion Transfer model takes (Kling following the video's orientation, Wan Animate). */\nexport const MOTION_TRANSFER_MAX_SEC = 30\n\n/** The orientation a run uses: `\"video\"` only when it says so; anything else (absent included) is the default, `\"image\"`. */\nexport function motionTransferOrientation(characterOrientation: unknown): \"image\" | \"video\" {\n return characterOrientation === \"video\" ? \"video\" : \"image\"\n}\n\nconst isWanAnimate = (provider: string): boolean => provider === \"wan-animate-move\" || provider === \"wan-animate-replace\"\n\n/** The longest driving video a run of `provider` at `characterOrientation` takes. */\nexport function motionTransferMaxSec(provider: string, characterOrientation: unknown): number {\n if (isWanAnimate(provider)) return MOTION_TRANSFER_MAX_SEC\n return motionTransferOrientation(characterOrientation) === \"video\" ? MOTION_TRANSFER_MAX_SEC : MOTION_TRANSFER_IMAGE_ORIENTATION_MAX_SEC\n}\n\n/** A per-second rate: the row that prices `rateSeconds` seconds of driving video, and the floor a run of it never goes below. */\nexport interface MotionTransferSecondRate {\n readonly rateId: string\n readonly rateSeconds: number\n /**\n * The row a run of this model and size is never charged below (Wan Animate:\n * its flat price for the size the request names); absent when the rate\n * alone prices the run (Kling).\n */\n readonly floorId?: string\n}\n\n/** Every rate row prices four seconds, so its value stays a whole credit and dividing by 4 is exact in floating point. */\nconst PER_4S = 4\n\n/**\n * The rate of every model and size, keyed `<provider>:<charged size>`.\n * Wan Animate Move runs at 720p only (its catalog entry lists that one size,\n * so `motionTransferResolution` sends and charges any size it names as 720p).\n */\nexport const MOTION_TRANSFER_SECOND_RATES: Readonly<Record<string, MotionTransferSecondRate>> = {\n \"kling:720p\": { rateId: \"motion-transfer:720p:per-4s\", rateSeconds: PER_4S },\n \"kling:1080p\": { rateId: \"motion-transfer:1080p:per-4s\", rateSeconds: PER_4S },\n \"kling-3.0:720p\": { rateId: \"kling-3.0-motion:720p:per-4s\", rateSeconds: PER_4S },\n \"kling-3.0:1080p\": { rateId: \"kling-3.0-motion:1080p:per-4s\", rateSeconds: PER_4S },\n \"wan-animate-replace:480p\": { rateId: \"wan-animate-replace:480p:per-4s\", rateSeconds: PER_4S, floorId: \"wan-animate-replace\" },\n \"wan-animate-replace:580p\": { rateId: \"wan-animate-replace:580p:per-4s\", rateSeconds: PER_4S, floorId: \"wan-animate-replace:580p\" },\n \"wan-animate-replace:720p\": { rateId: \"wan-animate-replace:720p:per-4s\", rateSeconds: PER_4S, floorId: \"wan-animate-replace:720p\" },\n \"wan-animate-move:720p\": { rateId: \"wan-animate-move:720p:per-4s\", rateSeconds: PER_4S, floorId: \"wan-animate-move:720p\" },\n}\n\n/** Every per-second rate row, once each. */\nexport const MOTION_TRANSFER_RATE_IDS: readonly string[] = [...new Set(Object.values(MOTION_TRANSFER_SECOND_RATES).map((r) => r.rateId))]\n\n/** Every floor row a per-second rate names, once each. */\nexport const MOTION_TRANSFER_FLOOR_IDS: readonly string[] = [\n ...new Set(Object.values(MOTION_TRANSFER_SECOND_RATES).flatMap((r) => (r.floorId === undefined ? [] : [r.floorId]))),\n]\n\n/** The model a run of `provider` runs: a model Motion Transfer has, else its default (Kling 2.6), as the route and the workflow run resolve it. */\nfunction runProvider(provider: unknown): string {\n return typeof provider === \"string\" && Object.keys(MOTION_TRANSFER_SECOND_RATES).some((k) => k.startsWith(`${provider}:`)) ? provider : \"kling\"\n}\n\n/**\n * The size a run is CHARGED at: the size it runs at (`motionTransferResolution`),\n * and for Kling any size but 1080p is charged as 720p (its rows have no other).\n */\nfunction chargedSize(provider: string, resolution: unknown): string {\n const sized = motionTransferResolution(provider, typeof resolution === \"string\" && resolution !== \"\" ? resolution : \"720p\").resolution\n if (isWanAnimate(provider)) return sized\n return sized === \"1080p\" ? \"1080p\" : \"720p\"\n}\n\n/** The per-second rate a run of `provider` at `resolution` is charged at; a model Motion Transfer does not have is priced as its default (Kling 2.6). */\nexport function motionTransferRateOf(provider: unknown, resolution: unknown): MotionTransferSecondRate {\n const model = runProvider(provider)\n const key = `${model}:${chargedSize(model, resolution)}`\n // Every size `motionTransferResolution` answers has an entry (motion-transfer-pricing.test.ts); a size it does not is priced at the model's 720p.\n return MOTION_TRANSFER_SECOND_RATES[key] ?? MOTION_TRANSFER_SECOND_RATES[`${model}:720p`]!\n}\n\n/**\n * The whole seconds a driving video read at `measuredSec` is billed for:\n * rounded up after forgiving `CLIP_PRICE_GRACE_SEC` past a whole second, at\n * least one. THE one rounding every lane reads.\n */\nexport function motionTransferBilledSeconds(measuredSec: number): number {\n return Math.max(1, Math.ceil(gracedMeasuredSec(measuredSec)))\n}\n\n/** A Motion Transfer run's price: the row it is charged at and, for a rate row, the units of it. */\nexport interface MotionTransferPrice {\n /** The row the run reserves: a per-second rate row, or (once {@link motionTransferChargedPrice} chose it) a floor row. */\n readonly creditId: string\n /** Units of the rate row the run is charged (billed seconds ÷ the rate's seconds); undefined for a floor row, charged once. */\n readonly units?: number\n /** The floor row the rate is compared with (Wan Animate) before the run is charged; undefined once chosen, and for Kling. */\n readonly floorId?: string\n}\n\n/**\n * The rate price of a run of `provider` at `resolution` whose driving video is\n * billed for `billedSeconds` whole seconds: the rate row and its units, and\n * the floor row it is compared with ({@link motionTransferChargedPrice}).\n */\nexport function motionTransferPrice(provider: string, resolution: unknown, billedSeconds: number): MotionTransferPrice {\n const rate = motionTransferRateOf(provider, resolution)\n return { creditId: rate.rateId, units: billedSeconds / rate.rateSeconds, ...(rate.floorId !== undefined ? { floorId: rate.floorId } : {}) }\n}\n\n/**\n * The row a run is CHARGED at — THE floor rule every lane reads: a price with\n * no floor is its rate; one with a floor is charged its floor row when the\n * floor's figure is at least the rate's figure for the run (a tie goes to the\n * floor: the same credits, at today's row), else its rate row × the units.\n * `perSecond` and `floor` must be figures of the same kind — both base credits\n * (the server: the rate row × the units rounded up once, and the floor row)\n * or both charged credits (the editor, from the server's quotes). A figure\n * that is not known leaves the rate (whose own lookup refuses an unpriced\n * row).\n */\nexport function motionTransferChargedPrice(\n price: MotionTransferPrice,\n figures: { readonly perSecond: number | undefined; readonly floor: number | undefined },\n): MotionTransferPrice {\n const rate: MotionTransferPrice = { creditId: price.creditId, ...(price.units !== undefined ? { units: price.units } : {}) }\n if (price.floorId === undefined || figures.perSecond === undefined || figures.floor === undefined) return rate\n return figures.floor >= figures.perSecond ? { creditId: price.floorId } : rate\n}\n\n/**\n * {@link motionTransferChargedPrice} from base rows (`baseOf`: a row's base\n * credits, undefined when it is priced nowhere), with the base credits the\n * run is charged, as base credits: the rate row × the units rounded up once,\n * or the floor row.\n */\nexport function motionTransferBaseCharge(\n price: MotionTransferPrice,\n baseOf: (creditId: string) => number | undefined,\n): MotionTransferPrice & { readonly baseCredits: number | undefined } {\n const rateBase = baseOf(price.creditId)\n const perSecond = rateBase === undefined ? undefined : Math.ceil(rateBase * (price.units ?? 1))\n const floor = price.floorId === undefined ? undefined : baseOf(price.floorId)\n const charged = motionTransferChargedPrice(price, { perSecond, floor })\n return { ...charged, baseCredits: charged.units === undefined ? floor : perSecond }\n}\n\n/** What the length check answers for a measured driving video. */\nexport type MotionTransferLengthCheck =\n | { readonly ok: true; readonly billedSeconds: number }\n | { readonly ok: false; readonly code: \"video_too_short\" | \"video_too_long\"; readonly message: string }\n\n/**\n * Whether a driving video measured at `measuredSec` can run on `provider` at\n * `characterOrientation`, and the seconds it is billed for. Shorter than\n * {@link MOTION_TRANSFER_MIN_SEC} is refused; past the limit by more than\n * `CLIP_PRICE_GRACE_SEC` is refused; a clip within that grace is billed at the\n * limit.\n */\nexport function checkMotionTransferLength(provider: string, characterOrientation: unknown, measuredSec: number): MotionTransferLengthCheck {\n if (measuredSec < MOTION_TRANSFER_MIN_SEC) {\n return {\n ok: false,\n code: \"video_too_short\",\n message: `The motion video is ${measuredSec.toFixed(1)} seconds. Motion Transfer needs a motion video of at least ${MOTION_TRANSFER_MIN_SEC} seconds.`,\n }\n }\n const max = motionTransferMaxSec(provider, characterOrientation)\n if (measuredSec > max + CLIP_PRICE_GRACE_SEC + FLOAT_NOISE_SEC) {\n const followVideo = !isWanAnimate(provider) && motionTransferOrientation(characterOrientation) === \"image\"\n ? ` (or ${MOTION_TRANSFER_MAX_SEC} seconds with the character following the video's orientation)`\n : \"\"\n return {\n ok: false,\n code: \"video_too_long\",\n message: `The motion video is ${measuredSec.toFixed(1)} seconds. This model takes at most ${max} seconds${followVideo}. Trim the video first.`,\n }\n }\n return { ok: true, billedSeconds: Math.min(max, motionTransferBilledSeconds(measuredSec)) }\n}\n\n/**\n * The billed seconds an ESTIMATE quotes before the video is measured: the\n * length the graph gives, at most the limit, billed as a run bills it; a\n * length it does not know quotes the limit — the most the run can be charged\n * (decided 2026-11-18), marked as an estimate by the caller.\n */\nexport function motionTransferEstimateSeconds(provider: string, characterOrientation: unknown, knownSec?: number | null): number {\n const max = motionTransferMaxSec(provider, characterOrientation)\n if (knownSec == null || !Number.isFinite(knownSec) || knownSec <= 0) return max\n return Math.min(max, motionTransferBilledSeconds(Math.max(MOTION_TRANSFER_MIN_SEC, knownSec)))\n}\n\n/** The price an estimate quotes ({@link motionTransferEstimateSeconds}), and whether it stood in for an unknown length. */\nexport function motionTransferEstimatePrice(\n provider: string,\n resolution: unknown,\n characterOrientation: unknown,\n knownSec?: number | null,\n): MotionTransferPrice & { readonly lengthKnown: boolean } {\n const lengthKnown = knownSec != null && Number.isFinite(knownSec) && knownSec > 0\n return { ...motionTransferPrice(provider, resolution, motionTransferEstimateSeconds(provider, characterOrientation, knownSec)), lengthKnown }\n}\n","/**\n * How a Video to Video run on HappyHorse Edit or Wan 2.7 VideoEdit is priced\n * (decided 2026-11-18): from the length of the clip it edits, as the server\n * reads it from the file before anything is held. Every other Video to Video\n * model keeps its flat row and is never read.\n *\n * - HappyHorse Edit is charged per started half-second of the clip, at its\n * size's row (the price of four clip seconds): row × half-seconds ÷ 8,\n * rounded up once, marked up once. The size priced is the size sent\n * ({@link videoToVideoSentResolution}): 1080p only when the request says\n * so, else 720p. A clip shorter than 3 s or longer than 60 s is refused.\n * - Wan 2.7 VideoEdit is charged per second of the clip it delivers (the\n * clip's length, or the shorter `videoEditDuration` it is asked for),\n * rounded up to a whole second after the house grace — at its row (the price\n * of four seconds) × seconds ÷ 4, rounded up once — but never below its flat\n * row (`wan-videoedit`): a run is charged the LARGER of the two. A clip\n * shorter than 2 s or longer than 10 s (past `CLIP_PRICE_GRACE_SEC`) is\n * refused; a clip within the grace is priced at 10 s.\n *\n * The route, the workflow run, the MCP verb (which calls the route), `POST\n * /v1/quote` and both estimates read this one module.\n */\nimport { CLIP_PRICE_GRACE_SEC, gracedMeasuredSec } from \"./priced-clip-seconds.js\"\nimport { MODEL_CATALOG } from \"./model-catalog.js\"\n\n/** Float noise: a length that is arithmetic can land a hair past an edge, and must not be refused or rounded up for it. */\nconst FLOAT_NOISE_SEC = 1e-9\n\n/** The Video to Video models priced by the length of their clip. */\nexport const CLIP_PRICED_V2V_PROVIDERS = [\"happyhorse-edit\", \"wan-videoedit\"] as const\nexport type ClipPricedV2vProvider = (typeof CLIP_PRICED_V2V_PROVIDERS)[number]\n\n/** Whether a Video to Video run on `provider` is priced by its clip's length (and so reads the clip before it holds anything). */\nexport function isClipPricedV2vProvider(provider: unknown): provider is ClipPricedV2vProvider {\n return typeof provider === \"string\" && (CLIP_PRICED_V2V_PROVIDERS as readonly string[]).includes(provider)\n}\n\n/** The shortest and longest clip HappyHorse Edit takes, in seconds. */\nexport const HAPPYHORSE_EDIT_MIN_SEC = 3\nexport const HAPPYHORSE_EDIT_MAX_SEC = 60\n/** The shortest and longest clip Wan 2.7 VideoEdit takes, in seconds. */\nexport const WAN_VIDEOEDIT_MIN_SEC = 2\nexport const WAN_VIDEOEDIT_MAX_SEC = 10\n\n/** Wan 2.7 VideoEdit's flat row: what a run cost before it was priced by length, and the least it costs now. */\nexport const WAN_VIDEOEDIT_FLOOR_CREDIT_ID = \"wan-videoedit\"\n\n/** A rate: the row that prices `rateSeconds` seconds of clip. */\nexport interface V2vClipRate {\n readonly rateId: string\n readonly rateSeconds: number\n}\n\nconst WAN_VIDEOEDIT_1080P_RATE: V2vClipRate = { rateId: \"wan-videoedit:1080p:per-4s\", rateSeconds: 4 }\n\n/**\n * The rates, keyed `<provider>:<size priced>`. A row prices four seconds so\n * its value stays a whole credit, and dividing by 4 (or 8 half-seconds) is\n * exact in floating point. Wan 2.7 VideoEdit at 720p is charged at its 1080p\n * rate for now: giving it its own is this one entry (plus its row).\n */\nexport const V2V_CLIP_RATES: Readonly<Record<string, V2vClipRate>> = {\n \"happyhorse-edit:720p\": { rateId: \"happyhorse-edit:720p:per-4s\", rateSeconds: 4 },\n \"happyhorse-edit:1080p\": { rateId: \"happyhorse-edit:1080p:per-4s\", rateSeconds: 4 },\n \"wan-videoedit:1080p\": WAN_VIDEOEDIT_1080P_RATE,\n \"wan-videoedit:720p\": WAN_VIDEOEDIT_1080P_RATE,\n}\n\n/** Every rate row, once. */\nexport const V2V_CLIP_RATE_IDS: readonly string[] = [...new Set(Object.values(V2V_CLIP_RATES).map((r) => r.rateId))]\n\n/**\n * The seeded credits of one of these models' rows, from their catalog entries'\n * pricing (held to `STATIC_CREDIT_COSTS` by the catalog parity test): the rows\n * an estimate with no live price table of its own compares.\n */\nexport function v2vSeededRowCredits(id: string): number | undefined {\n for (const provider of CLIP_PRICED_V2V_PROVIDERS) {\n const row = MODEL_CATALOG[provider]?.pricing.find((p) => p.identifier === id)\n if (row) return row.credits\n }\n return undefined\n}\n\n/** The shortest clip `provider` takes. */\nexport function videoToVideoClipMinSec(provider: ClipPricedV2vProvider): number {\n return provider === \"happyhorse-edit\" ? HAPPYHORSE_EDIT_MIN_SEC : WAN_VIDEOEDIT_MIN_SEC\n}\n\n/** The longest clip `provider` takes. */\nexport function videoToVideoClipMaxSec(provider: ClipPricedV2vProvider): number {\n return provider === \"happyhorse-edit\" ? HAPPYHORSE_EDIT_MAX_SEC : WAN_VIDEOEDIT_MAX_SEC\n}\n\n/**\n * The resolution a Video to Video run SENDS. HappyHorse Edit: \"1080p\" only\n * when the request names it, else \"720p\" — what it is priced at too, so a\n * size left on the node by another model never reaches the model unpriced.\n * Every other model: the value as given (absent stays absent).\n */\nexport function videoToVideoSentResolution(provider: unknown, resolution: unknown): string | undefined {\n if (provider === \"happyhorse-edit\") return resolution === \"1080p\" ? \"1080p\" : \"720p\"\n return typeof resolution === \"string\" && resolution !== \"\" ? resolution : undefined\n}\n\n/** The size a clip-priced run is CHARGED at: HappyHorse Edit's sent size; Wan 2.7 VideoEdit 720p only when named (it renders 1080p otherwise). */\nfunction chargedSize(provider: ClipPricedV2vProvider, resolution: unknown): \"720p\" | \"1080p\" {\n if (provider === \"happyhorse-edit\") return videoToVideoSentResolution(provider, resolution) as \"720p\" | \"1080p\"\n return resolution === \"720p\" ? \"720p\" : \"1080p\"\n}\n\n/** The rate a run of `provider` at `resolution` is charged at, or undefined for a model not priced by its clip. */\nexport function videoToVideoClipRateOf(provider: unknown, resolution: unknown): V2vClipRate | undefined {\n if (!isClipPricedV2vProvider(provider)) return undefined\n return V2V_CLIP_RATES[`${provider}:${chargedSize(provider, resolution)}`]\n}\n\n/** The output length Wan 2.7 VideoEdit is asked for: `videoEditDuration` \"5\" / \"10\", else 0 (as long as the clip). */\nfunction wanAskedSeconds(videoEditDuration: unknown): number {\n const n = typeof videoEditDuration === \"number\" ? videoEditDuration : typeof videoEditDuration === \"string\" ? Number(videoEditDuration) : 0\n return Number.isFinite(n) && n > 0 ? n : 0\n}\n\n/**\n * The seconds a clip of `clipSec` is billed for. HappyHorse Edit: every\n * started half-second of the clip (float noise forgiven, nothing more): 3.00 s\n * is 3, 10.04 s is 10.5. Wan 2.7 VideoEdit: the clip it delivers — the clip's\n * length, or `videoEditDuration` when that is shorter — rounded up to a whole\n * second after `CLIP_PRICE_GRACE_SEC`, at least 1 and at most its limit. THE\n * one rounding every lane reads.\n */\nexport function videoToVideoBilledSeconds(provider: ClipPricedV2vProvider, clipSec: number, videoEditDuration?: unknown): number {\n if (provider === \"happyhorse-edit\") return Math.max(1, Math.ceil(2 * clipSec - FLOAT_NOISE_SEC)) / 2\n const asked = wanAskedSeconds(videoEditDuration)\n const output = asked > 0 ? Math.min(asked, clipSec) : clipSec\n return Math.min(WAN_VIDEOEDIT_MAX_SEC, Math.max(1, Math.ceil(gracedMeasuredSec(output))))\n}\n\n/** What the length check answers for a clip. */\nexport type V2vClipLengthCheck =\n | { readonly ok: true; readonly billedSeconds: number }\n | { readonly ok: false; readonly code: \"video_too_short\" | \"video_too_long\"; readonly message: string }\n\nconst LABEL: Readonly<Record<ClipPricedV2vProvider, string>> = {\n \"happyhorse-edit\": \"HappyHorse Edit\",\n \"wan-videoedit\": \"Wan 2.7 VideoEdit\",\n}\n\n/**\n * Whether a clip of `clipSec` can run on `provider`, and the seconds it is\n * billed for. Shorter than the model's minimum is refused; longer than its\n * maximum is refused — past float noise on HappyHorse Edit, past\n * `CLIP_PRICE_GRACE_SEC` on Wan 2.7 VideoEdit (a clip within it is billed at\n * the limit).\n */\nexport function checkVideoToVideoClipLength(provider: ClipPricedV2vProvider, clipSec: number, videoEditDuration?: unknown): V2vClipLengthCheck {\n const min = videoToVideoClipMinSec(provider)\n const max = videoToVideoClipMaxSec(provider)\n if (clipSec < min - FLOAT_NOISE_SEC) {\n return {\n ok: false,\n code: \"video_too_short\",\n message: `The video is ${clipSec.toFixed(1)} seconds. ${LABEL[provider]} needs a video of at least ${min} seconds.`,\n }\n }\n const grace = provider === \"wan-videoedit\" ? CLIP_PRICE_GRACE_SEC : 0\n if (clipSec > max + grace + FLOAT_NOISE_SEC) {\n return {\n ok: false,\n code: \"video_too_long\",\n message: `The video is ${clipSec.toFixed(1)} seconds. ${LABEL[provider]} takes at most ${max} seconds. Trim the video first.`,\n }\n }\n return { ok: true, billedSeconds: videoToVideoBilledSeconds(provider, Math.min(clipSec, max), videoEditDuration) }\n}\n\n/** A clip-priced run's price: the row it reserves and, for a rate, the units of that row. */\nexport interface V2vClipPrice {\n /** The row the run reserves: a rate row, or Wan 2.7 VideoEdit's flat row while it is the larger. */\n readonly creditId: string\n /** Units of the row the run is charged (billed seconds ÷ the rate's seconds); undefined for a row charged once. */\n readonly units?: number\n}\n\n/**\n * The price of a run of `provider` at `resolution` billed for `billedSeconds`.\n *\n * Wan 2.7 VideoEdit is charged the LARGER of its flat row and its rate for the\n * billed seconds (its rate row × seconds ÷ 4, rounded up), so a run never\n * costs less than the flat row and costs more once its length passes what\n * that row covers; a tie keeps the flat row. `rowOf` gives a row's credits —\n * the caller's own table (the server's live rows, an estimate's price table),\n * the same kind for both rows; a row it does not know never wins.\n */\nexport function videoToVideoClipPrice(\n provider: ClipPricedV2vProvider,\n resolution: unknown,\n billedSeconds: number,\n rowOf: (id: string) => number | undefined,\n): V2vClipPrice {\n const rate = videoToVideoClipRateOf(provider, resolution)!\n const units = billedSeconds / rate.rateSeconds\n if (provider === \"happyhorse-edit\") return { creditId: rate.rateId, units }\n const rateRow = rowOf(rate.rateId)\n const floorRow = rowOf(WAN_VIDEOEDIT_FLOOR_CREDIT_ID)\n const rateWins = rateRow !== undefined && (floorRow === undefined || Math.ceil(rateRow * units) > floorRow)\n return rateWins ? { creditId: rate.rateId, units } : { creditId: WAN_VIDEOEDIT_FLOOR_CREDIT_ID }\n}\n\n/**\n * The fewest billed seconds at which Wan 2.7 VideoEdit at `resolution` is\n * charged by its rate rather than its flat row, given `rowOf`; undefined when\n * the rate never passes the flat row inside the model's limit.\n */\nexport function wanVideoEditRateFromSeconds(resolution: unknown, rowOf: (id: string) => number | undefined): number | undefined {\n for (let s = 1; s <= WAN_VIDEOEDIT_MAX_SEC; s++) {\n if (videoToVideoClipPrice(\"wan-videoedit\", resolution, s, rowOf).units !== undefined) return s\n }\n return undefined\n}\n\n/**\n * The billed seconds an ESTIMATE quotes before the clip is read: the length\n * the graph gives, held to the model's limits, billed as a run bills it; a\n * length it does not know quotes the longest clip the model takes — the most\n * the run can be charged — marked as an estimate by the caller.\n */\nexport function videoToVideoEstimateSeconds(provider: ClipPricedV2vProvider, videoEditDuration: unknown, knownSec?: number | null): number {\n const min = videoToVideoClipMinSec(provider)\n const max = videoToVideoClipMaxSec(provider)\n const sec = knownSec == null || !Number.isFinite(knownSec) || knownSec <= 0 ? max : Math.min(max, Math.max(min, knownSec))\n return videoToVideoBilledSeconds(provider, sec, videoEditDuration)\n}\n\n/** The price an estimate quotes ({@link videoToVideoEstimateSeconds}), and whether it stood in for an unknown length. */\nexport function videoToVideoEstimatePrice(\n provider: ClipPricedV2vProvider,\n resolution: unknown,\n videoEditDuration: unknown,\n knownSec: number | null | undefined,\n rowOf: (id: string) => number | undefined,\n): V2vClipPrice & { readonly lengthKnown: boolean } {\n const lengthKnown = knownSec != null && Number.isFinite(knownSec) && knownSec > 0\n return {\n ...videoToVideoClipPrice(provider, resolution, videoToVideoEstimateSeconds(provider, videoEditDuration, knownSec), rowOf),\n lengthKnown,\n }\n}\n","/**\n * How an Audio Isolation run is priced (decided 2026-11-18): from the length\n * of its audio as the server reads it before anything is held, never a length\n * the caller declares.\n *\n * - The run is charged {@link AUDIO_ISOLATION_RATE_ID} once per started\n * {@link AUDIO_ISOLATION_RATE_SECONDS} seconds of the audio, at least once,\n * after forgiving `CLIP_PRICE_GRACE_SEC` past a mark. The hold IS the charge.\n * - Audio longer than {@link AUDIO_ISOLATION_MAX_SEC} (30 minutes, a hair past\n * it forgiven) is refused before anything is held; so is a file larger than\n * {@link AUDIO_ISOLATION_MAX_BYTES}.\n *\n * The route, the workflow run, the MCP verb (which calls the route) and both\n * estimates read this one module.\n */\nimport { CLIP_PRICE_GRACE_SEC, gracedMeasuredSec } from \"./priced-clip-seconds.js\"\n\n/** Float noise: a length that is arithmetic can land a hair past the limit, and must not be refused for it. */\nconst FLOAT_NOISE_SEC = 1e-9\n\n/** The row an Audio Isolation run reserves and is charged: the price of ten seconds of audio. */\nexport const AUDIO_ISOLATION_RATE_ID = \"elevenlabs-isolation:per-10s\"\n\n/** The seconds of audio one unit of {@link AUDIO_ISOLATION_RATE_ID} prices. */\nexport const AUDIO_ISOLATION_RATE_SECONDS = 10\n\n/** The longest audio a run takes: 30 minutes. */\nexport const AUDIO_ISOLATION_MAX_SEC = 1800\n\n/** The largest file a run takes (the provider's own limit): 500 MB. */\nexport const AUDIO_ISOLATION_MAX_BYTES = 500 * 1024 * 1024\n\n/** The most units a run can be charged: the 30-minute cap's. */\nexport const AUDIO_ISOLATION_MAX_UNITS = AUDIO_ISOLATION_MAX_SEC / AUDIO_ISOLATION_RATE_SECONDS\n\n/**\n * The units of {@link AUDIO_ISOLATION_RATE_ID} an audio of `seconds` is\n * charged: every started ten seconds after the grace, at least one, at most\n * the cap's. THE one rounding every lane reads.\n */\nexport function audioIsolationUnits(seconds: number): number {\n if (!Number.isFinite(seconds) || seconds <= 0) return 1\n const units = Math.ceil(gracedMeasuredSec(seconds) / AUDIO_ISOLATION_RATE_SECONDS)\n return Math.min(AUDIO_ISOLATION_MAX_UNITS, Math.max(1, units))\n}\n\n/** What the length check answers for an audio of a given length. */\nexport type AudioIsolationLengthCheck =\n | { readonly ok: true; readonly units: number }\n | { readonly ok: false; readonly code: \"audio_too_long\"; readonly message: string }\n\n/** The refusal of an audio past the 30-minute cap: how long it is, the limit, and what to do. */\nexport function audioIsolationTooLongMessage(seconds: number): string {\n const minutes = Math.floor(seconds / 60)\n const rest = Math.round(seconds - minutes * 60)\n const length = rest > 0 ? `${minutes} min ${rest} s` : `${minutes} min`\n return `The audio is ${length} long. Audio Isolation takes audio up to 30 minutes: split or trim it to 30 minutes or less first.`\n}\n\n/**\n * Whether an audio of `seconds` can run, and the units it is charged. Past\n * the 30-minute cap by more than `CLIP_PRICE_GRACE_SEC` is refused; within\n * that grace it is charged at the cap.\n */\nexport function checkAudioIsolationLength(seconds: number): AudioIsolationLengthCheck {\n if (seconds > AUDIO_ISOLATION_MAX_SEC + CLIP_PRICE_GRACE_SEC + FLOAT_NOISE_SEC) {\n return { ok: false, code: \"audio_too_long\", message: audioIsolationTooLongMessage(seconds) }\n }\n return { ok: true, units: audioIsolationUnits(seconds) }\n}\n\n/**\n * The units an ESTIMATE quotes before the run reads the audio: the length\n * the graph gives, at most the cap; a length it does not know quotes the cap\n * (the most a run can be charged), and the caller marks it as an estimate.\n */\nexport function audioIsolationEstimateUnits(knownSec?: number | null): number {\n if (knownSec == null || !Number.isFinite(knownSec) || knownSec <= 0) return AUDIO_ISOLATION_MAX_UNITS\n return audioIsolationUnits(knownSec)\n}\n","/**\n * What a Seedance Lip Sync run renders and is priced at — ONE rule for the\n * route, the workflow run, the editor's estimate and the worker (decided\n * 2026-11-16).\n *\n * A Seedance Lip Sync run (the Seedance 2 family on the Lip Sync node: one\n * portrait plus the voice line as reference AUDIO, no reference video) renders\n * a fixed {@link SEEDANCE_LIP_SYNC_SECONDS}-second clip. The provider bills it\n * at the model's plain per-second rate — a reference video is what moves a\n * Seedance run onto the `-ref` rate (input + output seconds), and this run has\n * none — so it is priced on the plain row `<model>:8s:<resolution>`.\n *\n * The resolution is the one asked when the model renders it, else the model's\n * top catalog tier (a 1080p asked of Seedance 2 Fast renders and bills 720p),\n * and 720p when none is asked. Every catalog tier of every family member has a\n * plain 8-second row. The worker sends this same resolution, so what renders is\n * what was priced.\n *\n * MiniMax Hailuo 3 rides the same Lip Sync lane but is no Seedance model: it is\n * priced and sent on its own rule (`minimax-h3:8s`), never here.\n */\nimport { MODEL_CATALOG } from \"./model-catalog.js\"\nimport { SEEDANCE_LIP_SYNC_PROVIDERS, isMinimaxH3Provider, isSeedance2Provider } from \"./model-constants.js\"\n\n/** The length, in seconds, a Seedance Lip Sync run renders and is priced at. */\nexport const SEEDANCE_LIP_SYNC_SECONDS = 8\n\n/** The resolution a Seedance Lip Sync run uses when none is asked. */\nconst SEEDANCE_LIP_SYNC_DEFAULT_RESOLUTION = \"720p\"\n\n/** Whether this Lip Sync model is a Seedance model priced by {@link seedanceLipSyncCreditId}. */\nexport function isSeedanceLipSyncProvider(provider: unknown): provider is string {\n return typeof provider === \"string\" && SEEDANCE_LIP_SYNC_PROVIDERS.has(provider) && isSeedance2Provider(provider)\n}\n\n/** The resolution a Seedance Lip Sync run renders and is priced at (see the file comment). */\nexport function seedanceLipSyncResolution(provider: string, resolution?: unknown): string {\n const supported = MODEL_CATALOG[provider]?.resolutions ?? []\n const want = typeof resolution === \"string\" && resolution !== \"\" ? resolution : SEEDANCE_LIP_SYNC_DEFAULT_RESOLUTION\n if (supported.includes(want)) return want\n return supported[supported.length - 1] ?? SEEDANCE_LIP_SYNC_DEFAULT_RESOLUTION\n}\n\n/** The credit id a Seedance Lip Sync run is held and charged on: its plain 8-second row. */\nexport function seedanceLipSyncCreditId(provider: string, resolution?: unknown): string {\n return `${provider}:${SEEDANCE_LIP_SYNC_SECONDS}s:${seedanceLipSyncResolution(provider, resolution)}`\n}\n\n/**\n * MiniMax Hailuo 3 on Lip Sync: the same portrait-plus-voice-line run, held on\n * its 8-second 2K row on every path (decided 2026-11-16). The Lip Sync\n * resolution never names H3's own 768P tier, and KIE renders 2K when none is\n * sent, so the row does not follow the resolution and nothing sent changes.\n */\nexport const MINIMAX_H3_LIP_SYNC_CREDIT_ID = `minimax-h3:${SEEDANCE_LIP_SYNC_SECONDS}s`\n\n/**\n * The credit id a Lip Sync run on a multimodal video model (the Seedance 2\n * family and MiniMax Hailuo 3: a portrait plus the voice line as reference\n * audio) is held and charged on — the ONE rule the route, the workflow run,\n * the film pipeline and both estimates read. Undefined for every other Lip\n * Sync model.\n */\nexport function referenceAudioLipSyncCreditId(provider: unknown, resolution?: unknown): string | undefined {\n if (isSeedanceLipSyncProvider(provider)) return seedanceLipSyncCreditId(provider, resolution)\n if (typeof provider === \"string\" && isMinimaxH3Provider(provider)) return MINIMAX_H3_LIP_SYNC_CREDIT_ID\n return undefined\n}\n","/**\n * AI Avatar (HeyGen) duration-bucketing + credit-identifier helpers.\n * Single source of truth for the NON-monetary side of ai-avatar billing\n * (duration estimation, bucket selection, composite credit-id construction) —\n * imported by the frontend node UI (to build the id it hands to the\n * `/v1/credits/model-cost` display lookup) AND the backend route/orchestrator\n * (to resolve the credit-guard reservation id pre-Zod).\n *\n * The provider-$ rate table and the USD/credit cost FORMULAS derived from it\n * live in `backend/src/lib/pricing/ai-avatar-cost.ts` (core, not ee/ — the\n * HeyGen provider integration needs them regardless of edition). They were\n * moved out of this package (published Apache-2.0 on npm — an irrevocable\n * grant) per the 2026-07-06 public-flip IP audit, S5.\n */\n\nexport type AiAvatarEngine = \"avatar-v\" | \"avatar-iv\"\nexport type AiAvatarResolution = \"720p\" | \"1080p\" | \"4k\"\n\n/**\n * Worst-case clip duration used as the credit-reserve ceiling.\n * A 5000-character script at voiceSpeed 0.5 ≈ 5000/12/0.5 ≈ 833s → top bucket 900s.\n */\nexport const AI_AVATAR_MAX_DURATION_SEC = 900\n\n/**\n * Duration buckets (seconds) used to pick a reserve ceiling at creditGuard\n * time, when the actual clip length is unknown (text-mode scripts) or only\n * known via a server-side ffprobe (audio mode).\n *\n * The low end is FINE-GRAINED (5/10/15/30/60s) so short clips — the common\n * case — don't over-reserve. A 15s clip lands in the 15s bucket, not the old\n * coarse 30s floor (which doubled the hold). The high end stays coarse because\n * long-form scripts are rare and the bucket-up is a one-time refundable surplus.\n *\n * Bucket selection:\n * - Text mode: bucket = pickAiAvatarBucket(ceil(scriptChars / 12 / voiceSpeed)).\n * - Audio mode: bucket = pickAiAvatarBucket(ceil(probedDurationSec)) when the\n * ffprobe preHandler stashed `__probedDurationSec` on the body; otherwise a\n * MODEST 120s default (NOT the 900s top bucket — that was the bug: it\n * reserved ~4000+ credits for a sub-minute clip).\n *\n * Worst-case derivation: 5000 chars at voiceSpeed=0.5 → ceil(5000/12/0.5) = 834s\n * → fits in 900s bucket. The 900s top bucket covers all legal text inputs.\n *\n * Note: audio >900s (no probe) would undercharge against the 120s default, but\n * the commit-time metered true-up CANNOT charge more than reserved — so a long\n * un-probed audio clip is a (small) revenue leak, not an over-charge. The probe\n * closes it for the normal path. The 900s bucket remains available for the\n * probed long-audio case.\n */\nexport const AI_AVATAR_DURATION_BUCKETS = [5, 10, 15, 30, 60, 120, 240, 360, 600, 900] as const\n\n/**\n * Modest fallback bucket (seconds) for AUDIO mode when the ffprobe preHandler\n * did NOT stash a probed duration. Replaces the old 900s top-bucket fallback\n * that over-reserved ~4000+ credits for short clips. The commit-time metered\n * true-up is refund-only, so this is a reserve ceiling, not a charge.\n */\nexport const AI_AVATAR_AUDIO_FALLBACK_SEC = 120\n\n/**\n * Hard cap (seconds) on AUDIO-mode clip length. HeyGen has no natural length\n * limit on an audio-driven avatar, so a long audio = an expensive / possibly\n * rejected generation and a bounded under-reserve window. We cap it here:\n * - The worker TRIMS incoming audio longer than this down to AI_AVATAR_MAX_AUDIO_SEC\n * (and warns the user, non-fatal).\n * - The credit RESERVE is capped at this bucket too: even a 30-min probed\n * audio buckets at 600s, never the 900s top bucket. Because the worker\n * trims the actual clip to ≤600s, the metered true-up can only refund.\n *\n * Text mode (5000-char script) and cinematic (4–15s) are bounded elsewhere and\n * are NOT affected by this cap.\n */\nexport const AI_AVATAR_MAX_AUDIO_SEC = 600\n\nexport type AiAvatarDurationBucket = (typeof AI_AVATAR_DURATION_BUCKETS)[number]\n\nconst ALLOWED_ENGINES = new Set<AiAvatarEngine>([\"avatar-v\", \"avatar-iv\"])\nconst ALLOWED_RESOLUTIONS = new Set<AiAvatarResolution>([\"720p\", \"1080p\", \"4k\"])\n\n/**\n * Estimate script duration in seconds from character count and voice speed.\n *\n * Uses ~12 chars/sec at normal speed (voiceSpeed=1) — deliberately generous\n * (biased high) so the credit hold covers TTS pacing variations. Slower speech\n * (voiceSpeed < 1) produces a longer clip and thus a higher estimate.\n * Minimum 1s.\n *\n * @param script Script text (undefined treated as empty).\n * @param voiceSpeed HeyGen voice speed parameter, range 0.5–1.5 (default 1).\n * Slower speed → more seconds → higher hold.\n */\nexport function estimateScriptDurationSec(script: string | undefined, voiceSpeed = 1): number {\n const speed = Math.min(1.5, Math.max(0.5, voiceSpeed || 1))\n return Math.max(1, Math.ceil((script?.length ?? 0) / 12 / speed))\n}\n\n/**\n * Pick the smallest duration bucket that is ≥ sec.\n * Falls back to the maximum bucket (900s) when sec exceeds all buckets.\n */\nexport function pickAiAvatarBucket(sec: number): AiAvatarDurationBucket {\n for (const b of AI_AVATAR_DURATION_BUCKETS) {\n if (sec <= b) return b\n }\n return 900\n}\n\n/**\n * Composite credit identifier for a duration-bucketed reserve.\n *\n * Format: `\"heygen-<engine>:<resolution>:<bucketSec>s\"`\n * e.g. `\"heygen-avatar-iv:720p:60s\"`.\n */\nexport function aiAvatarReserveCreditId(\n engine: AiAvatarEngine,\n resolution: AiAvatarResolution,\n bucketSec: number,\n): string {\n return `heygen-${engine}:${resolution}:${bucketSec}s`\n}\n\n/**\n * Resolve the credit identifier from a raw request body BEFORE Zod validation.\n * Called at creditGuard preHandler time — mirrors how `resolveLipSyncIdentifier`\n * reads the raw body in `backend/src/routes/lip-sync.ts`.\n *\n * - `speechMode === \"text\"`: bucket by estimated script duration, accounting for\n * voiceSpeed (slower → longer clip → larger bucket). Surplus is refunded at commit.\n * - Any other speechMode (audio / missing): bucket by `__probedDurationSec` when\n * the ffprobe preHandler stashed it on the raw body; otherwise a MODEST 120s\n * default (AI_AVATAR_AUDIO_FALLBACK_SEC) — NOT the 900s top bucket. Reserving\n * the 900s ceiling for a sub-minute audio clip was the over-reservation bug\n * (~4000+ credits held for a clip that costs ~40). The commit-time metered\n * true-up is refund-only, so a modest reserve never over-charges. The effective\n * seconds are ALSO capped at AI_AVATAR_MAX_AUDIO_SEC (600s) — the worker trims\n * audio longer than that, so a 30-min audio reserves the 600s bucket, never 900s.\n *\n * - `avatarSource === \"image\"`: image-source mode is IV-class (HeyGen's own\n * engine, no avatar_id) — bill at the avatar-iv rate regardless of the\n * (ignored) `engine` field, reusing the existing heygen-avatar-iv:* ids.\n *\n * Falls back to (\"avatar-iv\", \"720p\", 120s) when fields are missing or invalid.\n */\nexport function resolveAiAvatarCreditId(\n body: Record<string, unknown> | undefined,\n): string {\n const rawEngine = body?.engine as string | undefined\n const rawResolution = body?.resolution as string | undefined\n const speechMode = body?.speechMode as string | undefined\n const avatarSource = body?.avatarSource as string | undefined\n\n // Image-source mode is IV-class (its own engine, no IV/V lever) — pin the\n // rate engine to avatar-iv and reuse the existing heygen-avatar-iv:* ids.\n const engine: AiAvatarEngine =\n avatarSource === \"image\"\n ? \"avatar-iv\"\n : rawEngine !== undefined && ALLOWED_ENGINES.has(rawEngine as AiAvatarEngine)\n ? (rawEngine as AiAvatarEngine)\n : \"avatar-iv\"\n\n const resolution: AiAvatarResolution =\n rawResolution !== undefined && ALLOWED_RESOLUTIONS.has(rawResolution as AiAvatarResolution)\n ? (rawResolution as AiAvatarResolution)\n : \"720p\"\n\n let bucketSec: AiAvatarDurationBucket\n if (speechMode === \"text\") {\n // voiceSpeed is a float in [0.5, 1.5]; coerce to number, default 1.\n // Slower speed → more seconds → larger bucket → larger hold (no undercharge).\n const voiceSpeed = Number(body?.voiceSpeed) || 1\n bucketSec = pickAiAvatarBucket(\n estimateScriptDurationSec(body?.script as string | undefined, voiceSpeed),\n )\n } else {\n // Audio/unknown mode. The ffprobe preHandler (video-sfx pattern) stashes\n // the measured clip length on the raw body as `__probedDurationSec` so we\n // can bucket by the ACTUAL audio duration. When present, bucket by it;\n // otherwise fall back to a MODEST 120s default — NOT the 900s top bucket.\n // The old 900s fallback over-reserved ~4000+ credits for sub-minute clips.\n //\n // Effective seconds are capped at AI_AVATAR_MAX_AUDIO_SEC (600s): audio mode\n // has no natural length limit, so the worker TRIMS the actual clip to ≤600s\n // and we cap the RESERVE at the matching 600s bucket. A 30-min probed audio\n // thus reserves the 600s bucket, never the 900s top bucket. Since the worker\n // trims actual to ≤600s, the metered commit can only refund.\n const probed = Number(body?.__probedDurationSec)\n const effectiveSec = Math.min(\n Number.isFinite(probed) && probed > 0\n ? Math.ceil(probed)\n : AI_AVATAR_AUDIO_FALLBACK_SEC,\n AI_AVATAR_MAX_AUDIO_SEC,\n )\n bucketSec = pickAiAvatarBucket(effectiveSec)\n }\n\n return aiAvatarReserveCreditId(engine, resolution, bucketSec)\n}\n\n/**\n * All 60 reserve credit IDs — every (engine × resolution × bucket) combination.\n * 2 engines × 3 resolutions × 10 buckets (5/10/15/30/60/120/240/360/600/900s) = 60.\n * Seeded in STATIC_CREDIT_COSTS and the model_pricing migration so\n * getModelCreditBaseCost never hard-fails (503 price_not_configured) for any\n * legal creditGuard input.\n */\nexport const AI_AVATAR_RESERVE_IDS: string[] = [...ALLOWED_ENGINES].flatMap((engine) =>\n [...ALLOWED_RESOLUTIONS].flatMap((resolution) =>\n AI_AVATAR_DURATION_BUCKETS.map((bucketSec) =>\n aiAvatarReserveCreditId(engine, resolution, bucketSec),\n ),\n ),\n)\n","// Beeble SwitchX — Relight & Switch video node. Non-monetary tier bucketing\n// and credit-identifier helpers. Beeble bills per 30-frame block with no\n// per-job meter returned, so we reserve a block tier (the smallest tier that\n// covers the clip's frame count) and commit it verbatim — tiers are 30-frame\n// multiples, so a clip snaps to the exact number of blocks Beeble bills\n// (ceil(frames/30)); there is no tier over-charge.\n//\n// The $-per-block provider rate and the credits-per-block formula derived\n// from it live in `backend/src/lib/pricing/switchx-cost.ts` (core, not ee/).\n// They were moved out of this package (published Apache-2.0 on npm — an\n// irrevocable grant) per the 2026-07-06 public-flip IP audit, S5.\nexport const SWITCHX_FRAME_TIERS = [30, 60, 90, 120, 150, 180, 210, 240] as const\n\n/** Beeble's metering granularity: frames per billed block. */\nexport const SWITCHX_BLOCK_FRAMES = 30\n\nexport function pickSwitchXFrameTier(frames?: number): number {\n if (frames === undefined || !Number.isFinite(frames) || frames <= 0) return 240\n for (const t of SWITCHX_FRAME_TIERS) if (frames <= t) return t\n return 240\n}\n\nfunction readMaxResolution(body: Record<string, unknown>): 720 | 1080 {\n const r = Number(body.maxResolution ?? body.max_resolution)\n return r === 720 ? 720 : 1080 // default 1080\n}\n\n// Frames are stashed on the raw body by the route's ffprobe preHandler.\nexport function resolveSwitchXCreditId(body: Record<string, unknown>): string {\n const frames = Number(body.__probedFrameCount)\n const tier = pickSwitchXFrameTier(Number.isFinite(frames) ? frames : undefined)\n return `beeble-switchx:${tier}f:${readMaxResolution(body)}p`\n}\n","/**\n * Cinematic Avatar (HeyGen `type:\"cinematic_avatar\"`) duration-clamping +\n * credit-identifier helpers. Single source of truth for the NON-monetary side\n * of cinematic-avatar billing — imported by the frontend node UI and the\n * backend route/orchestrator.\n *\n * The provider-$ rate table and the USD/credit cost FORMULAS derived from it\n * live in `backend/src/lib/pricing/cinematic-avatar-cost.ts` (core, not ee/ —\n * the HeyGen provider integration needs them regardless of edition). They\n * were moved out of this package (published Apache-2.0 on npm — an\n * irrevocable grant) per the 2026-07-06 public-flip IP audit, S5.\n *\n * ─── How this differs from ai-avatar pricing ────────────────────────────────\n * Cinematic Avatar is a generative clip (Seedance-style pipeline) driven by a\n * prompt + 1–3 avatar look ids. Crucially, `duration` is a USER PARAMETER\n * (4–15s, clamped) and is therefore KNOWN at submit time — unlike ai-avatar's\n * text/audio script whose clip length is only estimated. So the reserve here is\n * EXACT (no duration-bucket estimation): the credit id encodes the exact\n * requested duration, and the metered true-up at commit refunds nothing in the\n * common case (provider returns the requested duration).\n * ────────────────────────────────────────────────────────────────────────────\n */\n\nexport type CinematicResolution = \"720p\" | \"1080p\"\n\n/** Minimum / maximum / default user-selectable duration (seconds). */\nexport const CINEMATIC_MIN_DURATION_SEC = 4\nexport const CINEMATIC_MAX_DURATION_SEC = 15\nexport const CINEMATIC_DEFAULT_DURATION_SEC = 10\nexport const CINEMATIC_DEFAULT_RESOLUTION: CinematicResolution = \"720p\"\n\nconst ALLOWED_RESOLUTIONS = new Set<CinematicResolution>([\"720p\", \"1080p\"])\n\n/**\n * Clamp a (possibly invalid) duration to the legal 4–15s range, rounding to a\n * whole second. Falls back to the default (10s) for non-finite input.\n */\nexport function clampCinematicDuration(durationSec: number | undefined): number {\n const n = Number(durationSec)\n if (!Number.isFinite(n)) return CINEMATIC_DEFAULT_DURATION_SEC\n const rounded = Math.round(n)\n return Math.min(\n CINEMATIC_MAX_DURATION_SEC,\n Math.max(CINEMATIC_MIN_DURATION_SEC, rounded),\n )\n}\n\n/**\n * Composite credit identifier for an EXACT-duration reserve.\n *\n * Format: `cinematic-avatar:<resolution>:<durationSec>s`\n * e.g. `cinematic-avatar:720p:10s`.\n */\nexport function cinematicCreditId(\n resolution: CinematicResolution,\n durationSec: number,\n): string {\n return `cinematic-avatar:${resolution}:${durationSec}s`\n}\n\n/**\n * Resolve the credit identifier from a raw request body BEFORE Zod validation.\n * Called at creditGuard preHandler time — mirrors resolveAiAvatarCreditId.\n *\n * Reads `resolution` (default 720p) and `duration` (default 10, clamped 4–15)\n * straight off the raw body. Because duration is a user parameter known at\n * submit time, the reserve id is EXACT — no bucketing.\n *\n * ─── autoDuration → reserve at the MAX-duration ceiling ──────────────────────\n * When `autoDuration` is true, the provider DROPS `duration` and HeyGen picks\n * the clip length itself, so the actual metered length is UNKNOWN at submit\n * time and can exceed the requested/default `duration`. The metered true-up at\n * commit (commit_credits) can ONLY refund a surplus — it never charges more\n * when the actual exceeds the reserved hold. Reserving under the default-10s\n * hold therefore silently undercharges any auto clip longer than 10s (a revenue\n * leak). To preserve the refund-only invariant, reserve under the MAXIMUM\n * possible hold (`cinematic-avatar:<res>:15s`) so the true-up can only refund.\n */\nexport function resolveCinematicCreditId(\n body: Record<string, unknown> | undefined,\n): string {\n const rawResolution = body?.resolution as string | undefined\n const resolution: CinematicResolution =\n rawResolution !== undefined && ALLOWED_RESOLUTIONS.has(rawResolution as CinematicResolution)\n ? (rawResolution as CinematicResolution)\n : CINEMATIC_DEFAULT_RESOLUTION\n\n // autoDuration → HeyGen-chosen length, unknown at submit time → reserve at the\n // 15s ceiling so the metered true-up can only ever refund (never charge more).\n if (body?.autoDuration === true) {\n return cinematicCreditId(resolution, CINEMATIC_MAX_DURATION_SEC)\n }\n\n const durationSec = clampCinematicDuration(body?.duration as number | undefined)\n return cinematicCreditId(resolution, durationSec)\n}\n\n/**\n * All 24 reserve credit IDs — every (resolution × duration) combination.\n * 2 resolutions × 12 durations (4..15s) = 24.\n * Seeded in STATIC_CREDIT_COSTS and the model_pricing migration so\n * getModelCreditBaseCost never hard-fails (503 price_not_configured) for any\n * legal creditGuard input.\n */\nexport const CINEMATIC_RESERVE_IDS: string[] = [...ALLOWED_RESOLUTIONS].flatMap((resolution) => {\n const ids: string[] = []\n for (let d = CINEMATIC_MIN_DURATION_SEC; d <= CINEMATIC_MAX_DURATION_SEC; d++) {\n ids.push(cinematicCreditId(resolution, d))\n }\n return ids\n})\n","/**\n * Shared structural validators for the ai-avatar and cinematic-avatar payloads.\n *\n * ─── Why this exists ─────────────────────────────────────────────────────────\n * The route Zod schemas (`aiAvatarBody` / `cinematicAvatarBody`) only protect the\n * single-node Run path. Workflow runs, published-app runs, MCP run_workflow, and\n * imported/crafted workflow JSON all assemble a payload in\n * `payload-builder.ts` and forward it straight to the worker → provider →\n * HeyGen with NO Zod parse in between. That structural gap is the root cause of\n * the avatar edge-case findings: missing/over-count avatarLooks, reference caps,\n * source/speech-conditional requireds, and voice-param ranges all reach HeyGen\n * unvalidated on those paths.\n *\n * These validators reproduce the route Zod's invariants (minus the userId /\n * workflow wrapper and minus the URL-host allowlist — orchestrated URLs come\n * from trusted upstream R2 outputs). They run inside the `ai-avatar` /\n * `cinematic-avatar` cases of `payload-builder.ts` on the ASSEMBLED payload,\n * throwing `AvatarPayloadError` BEFORE credit reservation + enqueue. The\n * node-executor catches the throw and deletes the orphaned pending job, so both\n * entry points are correct-by-construction rather than relying on the route as\n * the only gate.\n *\n * Keep these in sync with `backend/src/routes/ai-avatar.ts` and\n * `backend/src/routes/cinematic-avatar.ts`.\n */\n\n/** Thrown by the avatar payload validators on a structurally-invalid payload. */\nexport class AvatarPayloadError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"AvatarPayloadError\"\n }\n}\n\nconst AI_AVATAR_SOURCES = new Set([\"avatar\", \"image\"])\nconst AI_AVATAR_ENGINES = new Set([\"avatar-v\", \"avatar-iv\"])\nconst AI_AVATAR_SPEECH_MODES = new Set([\"text\", \"audio\"])\nconst AI_AVATAR_RESOLUTIONS = new Set([\"720p\", \"1080p\", \"4k\"])\nconst AI_AVATAR_ASPECT_RATIOS = new Set([\"16:9\", \"9:16\"])\n\nconst AI_AVATAR_SCRIPT_MAX = 5000\nconst AI_AVATAR_VOICE_SPEED_MIN = 0.5\nconst AI_AVATAR_VOICE_SPEED_MAX = 1.5\nconst AI_AVATAR_PITCH_MIN = -50\nconst AI_AVATAR_PITCH_MAX = 50\nconst AI_AVATAR_VOLUME_MIN = 0\nconst AI_AVATAR_VOLUME_MAX = 1\n\nfunction isNonEmptyString(v: unknown): v is string {\n return typeof v === \"string\" && v.length > 0\n}\n\n/**\n * Validate an assembled ai-avatar payload (post-default-application).\n * Mirrors `aiAvatarBody` (`backend/src/routes/ai-avatar.ts`): enum bounds,\n * source/speech-conditional requireds, script length, and voice-param ranges.\n *\n * @throws AvatarPayloadError on any violation.\n */\nexport function validateAiAvatarPayload(payload: Record<string, unknown>): void {\n const avatarSource = (payload.avatarSource as string | undefined) ?? \"avatar\"\n const speechMode = (payload.speechMode as string | undefined) ?? \"text\"\n const engine = (payload.engine as string | undefined) ?? \"avatar-iv\"\n const resolution = (payload.resolution as string | undefined) ?? \"720p\"\n const aspectRatio = (payload.aspectRatio as string | undefined) ?? \"16:9\"\n\n if (!AI_AVATAR_SOURCES.has(avatarSource)) {\n throw new AvatarPayloadError(`ai-avatar: invalid avatarSource \"${avatarSource}\" (expected avatar | image)`)\n }\n if (!AI_AVATAR_ENGINES.has(engine)) {\n throw new AvatarPayloadError(`ai-avatar: invalid engine \"${engine}\" (expected avatar-v | avatar-iv)`)\n }\n if (!AI_AVATAR_SPEECH_MODES.has(speechMode)) {\n throw new AvatarPayloadError(`ai-avatar: invalid speechMode \"${speechMode}\" (expected text | audio)`)\n }\n if (!AI_AVATAR_RESOLUTIONS.has(resolution)) {\n throw new AvatarPayloadError(`ai-avatar: invalid resolution \"${resolution}\" (expected 720p | 1080p | 4k)`)\n }\n if (!AI_AVATAR_ASPECT_RATIOS.has(aspectRatio)) {\n throw new AvatarPayloadError(`ai-avatar: invalid aspectRatio \"${aspectRatio}\" (expected 16:9 | 9:16)`)\n }\n\n // Source-conditional requireds: avatar mode needs avatarId; image mode needs imageUrl.\n if (avatarSource === \"image\") {\n if (!isNonEmptyString(payload.imageUrl)) {\n throw new AvatarPayloadError(\"ai-avatar: imageUrl is required when avatarSource is image\")\n }\n } else {\n if (!isNonEmptyString(payload.avatarId)) {\n throw new AvatarPayloadError(\"ai-avatar: avatarId is required when avatarSource is avatar\")\n }\n }\n\n // Speech-conditional requireds.\n if (speechMode === \"text\") {\n if (!isNonEmptyString(payload.script)) {\n throw new AvatarPayloadError(\"ai-avatar: script is required when speechMode is text\")\n }\n if ((payload.script as string).length > AI_AVATAR_SCRIPT_MAX) {\n throw new AvatarPayloadError(`ai-avatar: script exceeds ${AI_AVATAR_SCRIPT_MAX} characters`)\n }\n if (!isNonEmptyString(payload.voiceId)) {\n throw new AvatarPayloadError(\"ai-avatar: voiceId is required when speechMode is text\")\n }\n } else {\n if (!isNonEmptyString(payload.audioUrl)) {\n throw new AvatarPayloadError(\"ai-avatar: audioUrl is required when speechMode is audio\")\n }\n }\n\n // Voice-param ranges (optional fields — only checked when present).\n assertNumberInRange(payload.voiceSpeed, AI_AVATAR_VOICE_SPEED_MIN, AI_AVATAR_VOICE_SPEED_MAX, \"ai-avatar: voiceSpeed\")\n assertNumberInRange(payload.pitch, AI_AVATAR_PITCH_MIN, AI_AVATAR_PITCH_MAX, \"ai-avatar: pitch\")\n assertNumberInRange(payload.volume, AI_AVATAR_VOLUME_MIN, AI_AVATAR_VOLUME_MAX, \"ai-avatar: volume\")\n}\n\nfunction assertNumberInRange(v: unknown, min: number, max: number, label: string): void {\n if (v === undefined || v === null) return\n const n = Number(v)\n if (!Number.isFinite(n) || n < min || n > max) {\n throw new AvatarPayloadError(`${label} must be between ${min} and ${max} (got ${String(v)})`)\n }\n}\n\n// ---------------------------------------------------------------------------\n// cinematic-avatar\n// ---------------------------------------------------------------------------\n\nconst CINEMATIC_RESOLUTIONS = new Set([\"720p\", \"1080p\"])\nconst CINEMATIC_ASPECT_RATIOS = new Set([\"16:9\", \"9:16\", \"1:1\"])\nexport const CINEMATIC_PROMPT_MAX = 10000\n\n/** HeyGen combined reference caps: ≤3 videos and ≤9 images across avatar looks + references. */\nexport const CINEMATIC_MAX_REFERENCE_VIDEOS = 3\nexport const CINEMATIC_MAX_REFERENCE_IMAGES = 9\nexport const CINEMATIC_MIN_LOOKS = 1\nexport const CINEMATIC_MAX_LOOKS = 3\n\n/**\n * Validate an assembled cinematic-avatar payload.\n * Mirrors `cinematicAvatarBody` (`backend/src/routes/cinematic-avatar.ts`):\n * prompt presence/length, avatarLooks count (1–3), enum bounds, and the\n * combined reference caps (≤3 videos; avatarLooks + image refs ≤ 9).\n *\n * @throws AvatarPayloadError on any violation.\n */\nexport function validateCinematicAvatarPayload(payload: Record<string, unknown>): void {\n const prompt = payload.prompt\n if (!isNonEmptyString(prompt)) {\n throw new AvatarPayloadError(\"cinematic-avatar: prompt is required\")\n }\n if ((prompt as string).length > CINEMATIC_PROMPT_MAX) {\n throw new AvatarPayloadError(`cinematic-avatar: prompt exceeds ${CINEMATIC_PROMPT_MAX} characters`)\n }\n\n const avatarLooks = payload.avatarLooks\n if (!Array.isArray(avatarLooks)) {\n throw new AvatarPayloadError(\"cinematic-avatar: avatarLooks must be an array of 1–3 look ids\")\n }\n if (avatarLooks.length < CINEMATIC_MIN_LOOKS || avatarLooks.length > CINEMATIC_MAX_LOOKS) {\n throw new AvatarPayloadError(\n `cinematic-avatar: avatarLooks must contain ${CINEMATIC_MIN_LOOKS}–${CINEMATIC_MAX_LOOKS} look ids (got ${avatarLooks.length})`,\n )\n }\n if (!avatarLooks.every((l) => isNonEmptyString(l))) {\n throw new AvatarPayloadError(\"cinematic-avatar: every avatarLooks entry must be a non-empty string\")\n }\n\n const resolution = (payload.resolution as string | undefined) ?? \"720p\"\n const aspectRatio = (payload.aspectRatio as string | undefined) ?? \"16:9\"\n if (!CINEMATIC_RESOLUTIONS.has(resolution)) {\n throw new AvatarPayloadError(`cinematic-avatar: invalid resolution \"${resolution}\" (expected 720p | 1080p)`)\n }\n if (!CINEMATIC_ASPECT_RATIOS.has(aspectRatio)) {\n throw new AvatarPayloadError(`cinematic-avatar: invalid aspectRatio \"${aspectRatio}\" (expected 16:9 | 9:16 | 1:1)`)\n }\n\n // Combined reference caps. avatar looks are image looks → count toward the\n // 9-image budget (matches the route superRefine).\n const references = payload.references\n if (references !== undefined) {\n if (!Array.isArray(references)) {\n throw new AvatarPayloadError(\"cinematic-avatar: references must be an array\")\n }\n let videoCount = 0\n let imageRefCount = 0\n for (const r of references) {\n if (!r || typeof r !== \"object\") {\n throw new AvatarPayloadError(\"cinematic-avatar: each reference must be an object { type, url }\")\n }\n const type = (r as { type?: unknown }).type\n const url = (r as { url?: unknown }).url\n if (type !== \"video\" && type !== \"image\" && type !== \"audio\") {\n throw new AvatarPayloadError(`cinematic-avatar: invalid reference type \"${String(type)}\" (expected video | image | audio)`)\n }\n if (!isNonEmptyString(url)) {\n throw new AvatarPayloadError(\"cinematic-avatar: each reference must carry a non-empty url\")\n }\n if (type === \"video\") videoCount++\n else if (type === \"image\") imageRefCount++\n }\n if (videoCount > CINEMATIC_MAX_REFERENCE_VIDEOS) {\n throw new AvatarPayloadError(\n `cinematic-avatar: at most ${CINEMATIC_MAX_REFERENCE_VIDEOS} video references are allowed (got ${videoCount})`,\n )\n }\n const totalImages = avatarLooks.length + imageRefCount\n if (totalImages > CINEMATIC_MAX_REFERENCE_IMAGES) {\n throw new AvatarPayloadError(\n `cinematic-avatar: at most ${CINEMATIC_MAX_REFERENCE_IMAGES} images are allowed across avatar looks + image references (got ${totalImages})`,\n )\n }\n }\n}\n","/**\n * Effective-tier resolution — the payg derivation.\n *\n * \"payg\" is a DERIVED tier, never stored: a user whose stored tier resolves\n * to \"free\" but who has NET lifetime top-up credits (granted − refunded,\n * clamped ≥ 0 by every SQL writer) is treated as \"payg\" by entitlement\n * checks. Stored tier stays untouched, so subscription webhooks never learn\n * about payg and a cancel→free transition re-derives it automatically.\n *\n * Lives in @nodaro/shared because the pipeline tier maps already do, and\n * both backend (credit gates, workers) and read surfaces need one source.\n *\n * The profile fields are REQUIRED (non-optional) on purpose: a call site\n * whose SELECT forgot to fetch `lifetime_topup_credits` becomes a compile\n * error instead of a silent `?? 0` that quietly deactivates payg — that is\n * the failure mode this shape exists to prevent.\n */\n\n/** Stored-tier resolution — mirrors SQL COALESCE(tier, subscription_tier, 'free'). */\nexport function resolveStoredTier(p: {\n tier: string | null\n subscription_tier: string | null\n}): string {\n return p.tier ?? p.subscription_tier ?? \"free\"\n}\n\n/**\n * Effective tier: stored \"free\" with NET lifetime top-ups > 0 derives \"payg\".\n * Every other stored tier passes through untouched.\n */\nexport function resolveEffectiveTier(p: {\n tier: string | null\n subscription_tier: string | null\n lifetime_topup_credits: number\n}): string {\n const stored = resolveStoredTier(p)\n if (stored === \"free\" && p.lifetime_topup_credits > 0) return \"payg\"\n return stored\n}\n\n/** Media-retention activity window for payg users (design 2026-07-05 §4.6). */\nexport const PAYG_RETENTION_DAYS = 90\n\n/**\n * Is this payg user inside their retention-activity window?\n *\n * Activity = credit SPEND (callers supply MAX(usage_logs.created_at) — never\n * `last_daily_reset`, which read-only balance polls bump) OR a top-up\n * PURCHASE (`last_topup_at`). Within PAYG_RETENTION_DAYS of either → the\n * nightly reaper leaves their media alone; past it, the standard free-tier\n * reaper rules apply. A user with no lifetime purchases is never\n * retention-active (they are not payg).\n */\nexport function isPaygRetentionActive(\n p: {\n lifetimeTopupCredits: number\n lastTopupAt: string | Date | null\n lastSpendAt: string | Date | null\n },\n now: Date\n): boolean {\n if (p.lifetimeTopupCredits <= 0) return false\n const cutoff = now.getTime() - PAYG_RETENTION_DAYS * 24 * 60 * 60 * 1000\n const at = (v: string | Date | null): number | null => {\n if (v === null) return null\n const t = v instanceof Date ? v.getTime() : new Date(v).getTime()\n return Number.isFinite(t) ? t : null\n }\n const topup = at(p.lastTopupAt)\n const spend = at(p.lastSpendAt)\n return (topup !== null && topup >= cutoff) || (spend !== null && spend >= cutoff)\n}\n","/**\n * Video-analysis pricing — shared duration-bucket credit model.\n *\n * Single source of truth for the video-analysis node's NON-monetary credit\n * math: duration bucketing, the window-batching constants (also consumed by\n * the backend workers for real chunking, not just pricing), and the\n * composite credit-id builder. The route (charge at generate-time), the\n * worker (re-check + settle), and the frontend node UI (via\n * `buildVideoAnalysisCreditId` + `/v1/credits/model-cost`) all derive from\n * these.\n *\n * The rate constants and the formula that GENERATE these numbers live\n * PRIVATELY in the `@nodaroai/cloud-plugins` package — never in this public\n * repo. They were first moved out of this package (published Apache-2.0 on\n * npm), then out of the app repo entirely alongside the rest of the\n * video-analysis node. A cross-check test in that private package guards\n * this table so the public numbers can't silently drift from the formula.\n *\n * `VIDEO_ANALYSIS_BUCKET_CREDITS` below is the precomputed OUTPUT of that\n * private formula for every (model × bucket) combination — a plain credit\n * lookup table, not a formula, mirroring the same wire-contract pattern\n * `VIDEO_CLIP_CREDITS` uses in `film-pricing.ts`. It is what the frontend's\n * client-side cost preview (`estimateNodeCredits` in\n * workflow-editor/types.ts) reads instead of calling the formula directly.\n * The formula's own test in `@nodaroai/cloud-plugins` cross-checks this\n * table against it and fails on drift. There is deliberately NO app-side formula to\n * check against — it was moved private in 2026-07 and the old backend test\n * went with it.\n *\n * `VIDEO_AUDIT_BUCKET_CREDITS` further down is the sibling table for the\n * `video-audit` node (\"AI Audit\") — same module, same bucket ladder, same\n * generator-authoritative pattern, its own two credit families.\n */\n\nexport const VIDEO_ANALYSIS_DURATION_BUCKETS = [60, 180, 360, 600] as const\n/** Pricing grace: a clip at most this far past a bucket edge is priced at that\n * bucket. A part chosen as 1:00 in the Video URL chooser downloads at about\n * 1:03 (the cut lands on keyframes), and must cost a minute, not three. Read\n * by pickVideoAnalysisBucket — the ONE bucket picker every price reads (the\n * editor estimate, the orchestrator reserve, the cloud routes). */\nexport const VIDEO_ANALYSIS_BUCKET_GRACE_SEC = 3\n/** Worker re-check grace: route metadata is integer-rounded, provider durations nominal;\n * ffprobe floats run 0.05–2 s over. Zero tolerance fails legit videos at 1:00/3:00/6:00/10:00.\n * It sits ON TOP of the pricing grace: a clip the grace priced into a bucket\n * (probe 63 s → 60 s) must still pass the worker gate (bucket + tolerance) at\n * its float length (63.4 s). The cloud plugin reads this constant from the\n * host app at run time, so its gate moves with it. */\nexport const VIDEO_ANALYSIS_DURATION_TOLERANCE_SEC = VIDEO_ANALYSIS_BUCKET_GRACE_SEC + 3\nexport const VIDEO_ANALYSIS_MAX_DURATION_SEC = 600\nconst WINDOW_LEN = 150, WINDOW_STRIDE = 145, WINDOW_OVERLAP = 5\nexport const VIDEO_ANALYSIS_WINDOW = { LEN: WINDOW_LEN, STRIDE: WINDOW_STRIDE, OVERLAP: WINDOW_OVERLAP, SINGLE_MAX: 180 } as const\n\n/**\n * Precomputed credit cost per (model, bucket) — the OUTPUT of the private\n * `videoAnalysisBucketCredits` formula (in `@nodaroai/cloud-plugins`), not a\n * formula itself. Regenerate by running that function for every\n * `VIDEO_ANALYSIS_LLM_MODELS` × duration bucket combination whenever the\n * underlying rate/token constants change (the plugin's cost test guards drift).\n * Keep in sync with\n * `docs/nodes/processing-video/video-analysis.md`.\n */\n// EVERY row here is RE-DERIVED from the cloud-plugins formula at the current\n// credit base — never a mechanical x10 of an older table. The formula ceils USD\n// into credits, so a 10x finer base rounds LESS: the 60s flash bucket is 23,\n// where x10 of the old 3 would have been 30 (a ~30% over-charge).\n//\n// That applies to the SENTINEL rows (`mixed:*`, `smart:*`) exactly as much as to\n// the per-model rows. They were briefly shipped as a x10 on the reasoning that\n// they sit outside the plugin's cross-check loop — but being outside the loop\n// makes a row UNGUARDED, not exempt: `videoAnalysisBucketCredits` computes them\n// from the same roll plan, so they are formula-derived too (mixed:60s is 104,\n// not 110). The plugin's cost test now covers sentinels as well, so this class\n// of drift fails CI instead of shipping.\n// REGENERATED 2026-07-31 with the smart-tier re-base (formula inputs moved in\n// the plugin: sampling 24→6 fps, which proved equal on content and better on\n// cast stability; system-prompt and per-window output-token constants updated).\n// Net effect: smart drops 27–47% per bucket, and the economy rows tick up 3–6%.\n//\n// REGENERATED 2026-08-03 — V1 hybrid-smart reprice, from the plugin's own\n// generator. This is the V1 true-up of the earlier provisional\n// judge/refine/frame-judge constants (the constants themselves, like the rest\n// of the formula, stay private in the plugin repo — never in this public\n// package). `smart` is now a multi-roll plan that always refines its merged\n// result (`selectionMode` does not apply to it), and every multi-roll tier\n// now carries its own explicit judge/refine terms instead of an implicit\n// share of a single-pass budget.\n// The economy tiers rise too (fast 33->185 @180s).\n// Net effect, per bucket (every row rises):\n//\n// gemini-3-flash 60s 24->180 180s 33->185 360s 86-> 514 600s 143-> 846\n// gemini-3.6-flash 60s 65->203 180s 92->218 360s 237-> 598 600s 395-> 986\n// gemini-3.1-pro 60s 87->215 180s 116->231 360s 305-> 636 600s 509->1050\n// mixed 60s 110->228 180s 149->249 360s 390-> 684 600s 651->1129\n// mixed (2026-08-04) 60s 228->268 180s 249->289 360s 684-> 724 600s 1129->1169 (+40 flat: continuity pass joined the family)\n// smart 60s 333->410 180s 470->500 360s 1135->1259 600s 1868->2064\n//\n// Values are pasted verbatim from the plugin generator's output — never hand\n// computed. The plugin's cost test cross-checks every row, sentinels included.\n// REGENERATED 2026-08-28 — recast shot-craft Stage 1: the analyser's system\n// prompt grew (transition/on-screen-text doctrine + three required wire\n// fields), so the plugin's system-prompt token pin moved 8_203 → 8_482 and\n// 21 of 28 rows tick up by 1–4 credits (~0.1–0.3%). Output of the plugin's\n// `scripts/gen-va-buckets.mjs` on `feat/va-shot-craft`, pasted verbatim.\n//\n// REGENERATED 2026-08-29 — recast shot-craft Stage 1.3: the analyser's system\n// prompt grew again, moving the plugin's system-prompt token pin 8_482 → 8_706\n// (cloud-plugins 0.209.0). 12 of 20 analysis rows and 6 of 8 audit rows tick up\n// by 1–3 credits (~0.1–0.3%); the legacy `gemini-3-flash` family is unchanged.\n// Output of the plugin's `scripts/gen-va-buckets.mjs`, pasted verbatim.\n//\n// REGENERATED 2026-08-30 — transition vocabulary v2: the analyser's doctrine now\n// DEFINES twelve named transition values (and says an absent transition asserts\n// nothing), which grew the analyser's system prompt once more — the plugin's\n// system-prompt token pin moved 8_706 → 9_082 (cloud-plugins 0.212.0). 15 of 20\n// analysis rows and 6 of 8 audit rows tick up by 1–5 credits (~0.1–0.6%); unlike\n// the 8_482 → 8_706 round, the legacy `gemini-3-flash` family moves too.\n// Output of the plugin's `scripts/gen-va-buckets.mjs`, pasted verbatim.\n//\n// RESET 2026-10-14 to the DEPLOYED schedule (migration 357, the 9_082 pin). A\n// 2026-09-06 regeneration (the 9_434 pin) moved these rows up by 1–5 credits\n// but shipped no migration, so for five weeks every estimate, doc and tool\n// description quoted a price no run was charged. This table is what\n// `model_pricing` holds, not the generator's latest output: a regeneration\n// lands TOGETHER with the migration that seeds it —\n// `backend/src/ee/billing/__tests__/static-costs-match-migrations.test.ts`\n// fails the build on any row that differs from its latest migration.\n//\n// 2026-11-13 — the fast tier moved to gemini-3.8-flash (KIE dropped\n// gemini-3-flash's channel). Only the rows the model swap touches were\n// regenerated, on the deployed 9_082 basis: the new gemini-3.8-flash family,\n// and `mixed` / `smart`, whose plans roll the fast model too. Every other row\n// is exactly as deployed.\n//\n// 2026-11-13 — the `ultra` tier (gemini-4-carbon) joined. Its four rows are new\n// (migration 649); every other row is exactly as deployed. They are the decided\n// schedule, set between `mixed` and `smart` in every bucket; the plugin's\n// cost test holds its formula to them like every other row.\nexport const VIDEO_ANALYSIS_BUCKET_CREDITS: Record<string, number> = {\n // Current fast tier (VIDEO_ANALYSIS_TIERS.fast, since 2026-11-13).\n \"video-analysis:gemini-3.8-flash:60s\": 186,\n \"video-analysis:gemini-3.8-flash:180s\": 193,\n \"video-analysis:gemini-3.8-flash:360s\": 534,\n \"video-analysis:gemini-3.8-flash:600s\": 880,\n // Legacy fast-tier model (backed the fast tier 2026-07-29 → 2026-11-13, and\n // before 2026-07) — kept for stored raw-id configs, which the analysis engine\n // now serves with the current fast model; still ≤ pro per bucket.\n \"video-analysis:gemini-3-flash:60s\": 181,\n \"video-analysis:gemini-3-flash:180s\": 185,\n \"video-analysis:gemini-3-flash:360s\": 515,\n \"video-analysis:gemini-3-flash:600s\": 848,\n // Legacy fast-tier model (backed the fast tier 2026-07 → 2026-07-29) — kept\n // for stored raw-id configs; still ≤ pro per bucket.\n \"video-analysis:gemini-3.6-flash:60s\": 204,\n \"video-analysis:gemini-3.6-flash:180s\": 219,\n \"video-analysis:gemini-3.6-flash:360s\": 602,\n \"video-analysis:gemini-3.6-flash:600s\": 992,\n \"video-analysis:gemini-3.1-pro:60s\": 216,\n \"video-analysis:gemini-3.1-pro:180s\": 232,\n \"video-analysis:gemini-3.1-pro:360s\": 640,\n \"video-analysis:gemini-3.1-pro:600s\": 1056,\n // ULTRA (VIDEO_ANALYSIS_TIERS.ultra, since 2026-11-13) — the deepest-reasoning\n // model reading every window. Above `mixed` and below `smart` per bucket.\n \"video-analysis:gemini-4-carbon:60s\": 349,\n \"video-analysis:gemini-4-carbon:180s\": 375,\n \"video-analysis:gemini-4-carbon:360s\": 1054,\n \"video-analysis:gemini-4-carbon:600s\": 1745,\n // Mixed tiers (`mixed` + `mixed-fast`) share ONE credit family — they are\n // variants of the same engine plan (plan internals live in the private\n // analysis plugin). Admin-tunable via model_pricing like every other row.\n \"video-analysis:mixed:60s\": 275,\n \"video-analysis:mixed:180s\": 298,\n \"video-analysis:mixed:360s\": 748,\n \"video-analysis:mixed:600s\": 1209,\n // SMART — the accuracy tier, and since the 2026-08-03 re-plan a multi-roll\n // plan like the others, always refined (`selectionMode` does not apply\n // here — smart always refines; it never offers a cheaper \"choose\" path).\n // Priced above the economy tiers because it genuinely costs more to run;\n // the only tier whose accuracy is validated against a hand-counted edit\n // list, re-validated at the current plan before this schedule shipped.\n \"video-analysis:smart:60s\": 416,\n \"video-analysis:smart:180s\": 508,\n \"video-analysis:smart:360s\": 1280,\n \"video-analysis:smart:600s\": 2097,\n}\n\n/**\n * The credit-id MODEL SEGMENT for an engine identifier: both mixed-tier\n * sentinels share the `mixed` price family (same engine plan); everything\n * else prices under its own identifier. Single source of truth — used by\n * `buildVideoAnalysisCreditId` below, so route/orchestrator/UI callers can\n * never diverge on where a sentinel prices.\n */\nexport function videoAnalysisCreditSegment(modelOrSentinel: string): string {\n return modelOrSentinel === \"mixed-fast\" ? \"mixed\" : modelOrSentinel\n}\n\nexport function pickVideoAnalysisBucket(durationSec: number): number {\n for (const b of VIDEO_ANALYSIS_DURATION_BUCKETS) if (durationSec <= b + VIDEO_ANALYSIS_BUCKET_GRACE_SEC) return b\n return VIDEO_ANALYSIS_MAX_DURATION_SEC\n}\n\nexport function buildVideoAnalysisCreditId(model: string, durationSec?: number): string {\n const bucket = durationSec !== undefined && durationSec > 0\n ? pickVideoAnalysisBucket(Math.min(durationSec, VIDEO_ANALYSIS_MAX_DURATION_SEC))\n : VIDEO_ANALYSIS_MAX_DURATION_SEC // unknown → ceiling composite (the ONLY silent-ceiling path)\n return `video-analysis:${videoAnalysisCreditSegment(model)}:${bucket}s`\n}\n\nexport function bucketSecondsFromCreditId(creditId: string): number | null {\n const m = /^video-analysis:.+:(\\d+)s$/.exec(creditId)\n return m ? Number(m[1]) : null\n}\n\nexport function videoAnalysisNumWindows(bucketSec: number): number {\n return bucketSec <= VIDEO_ANALYSIS_WINDOW.SINGLE_MAX ? 1 : 1 + Math.ceil((bucketSec - WINDOW_LEN) / WINDOW_STRIDE)\n}\n\n/**\n * Precomputed credit cost for the `video-audit` node (\"AI Audit\") — the same\n * pattern as `VIDEO_ANALYSIS_BUCKET_CREDITS` above: the OUTPUT of the private\n * `videoAuditBucketCredits` formula in `@nodaroai/cloud-plugins`\n * (in the plugin repo), a plain lookup table never a\n * formula, cross-checked against that package's own cost test. Shares the\n * SAME duration-bucket ladder as video-analysis (`VIDEO_ANALYSIS_DURATION_BUCKETS`\n * / `pickVideoAnalysisBucket`) — the audit re-watches the same clip, so it\n * buckets identically.\n *\n * Two credit families, selected by whether an analysis was wired into the\n * node (see `buildVideoAuditCreditId`):\n * - `video-audit:<bucket>s` — an analysis was provided; the audit re-watches\n * the clip against it directly (native watcher roll + reasoner pass, at a\n * safety margin — internals stay private in the plugin).\n * - `video-audit:auto:<bucket>s` — no analysis wired; the node auto-runs a\n * fast-tier analysis first. Exactly the base family's price PLUS the\n * fast tier's row (`gemini-3.8-flash` since 2026-11-13) from `VIDEO_ANALYSIS_BUCKET_CREDITS`\n * at the SAME bucket — summed in the plugin's generator/formula, never\n * hand-added here (see the single-source assertion in\n * video-analysis-pricing.test.ts).\n *\n * Bare ids (`video-audit`, `video-audit:auto` — they live in\n * `model-catalog.ts`'s pricing rows, not as keys in this table) equal their\n * family's 600s ceiling, the same \"unknown duration → ceiling\" convention\n * `VIDEO_ANALYSIS_BUCKET_CREDITS`'s bare per-model catalog rows use.\n * `buildVideoAuditCreditId` never returns a bare id itself — an\n * unknown/invalid duration resolves to the bucketed 600s id, matching\n * `buildVideoAnalysisCreditId`.\n *\n * Values pasted verbatim from the plugin generator's output\n * (the plugin repo's bucket generator) —\n * never hand computed. The plugin's cost test cross-checks every row.\n */\nexport const VIDEO_AUDIT_BUCKET_CREDITS: Record<string, number> = {\n \"video-audit:60s\": 215,\n \"video-audit:180s\": 290,\n \"video-audit:360s\": 663,\n \"video-audit:600s\": 1073,\n // The auto family follows the fast row (2026-11-13: gemini-3.8-flash).\n \"video-audit:auto:60s\": 401,\n \"video-audit:auto:180s\": 483,\n \"video-audit:auto:360s\": 1197,\n \"video-audit:auto:600s\": 1953,\n}\n\n/**\n * Composite credit-id builder for `video-audit`. Mirrors\n * `buildVideoAnalysisCreditId`'s bucket selection and unknown/invalid-duration\n * ceiling fallback exactly (same ladder, same rounding — `durationSec <=\n * bucket`, clamped to the 600s max), but selects the FAMILY by whether an\n * analysis was already provided instead of by model: `analysisProvided:\n * true` prices under the cheaper `video-audit` family (re-audits an existing\n * analysis); `false` prices under `video-audit:auto` (the node auto-runs a\n * fast analysis first, hence that family's built-in fast-tier addition).\n */\nexport function buildVideoAuditCreditId(args: { analysisProvided: boolean; durationSec?: number }): string {\n const { analysisProvided, durationSec } = args\n const bucket = durationSec !== undefined && durationSec > 0\n ? pickVideoAnalysisBucket(Math.min(durationSec, VIDEO_ANALYSIS_MAX_DURATION_SEC))\n : VIDEO_ANALYSIS_MAX_DURATION_SEC // no/invalid duration → ceiling composite, same convention as buildVideoAnalysisCreditId\n const family = analysisProvided ? \"video-audit\" : \"video-audit:auto\"\n return `${family}:${bucket}s`\n}\n\n/**\n * Table lookup for a resolved bucket + family. Snaps `bucketSec` onto the\n * ladder via `pickVideoAnalysisBucket` first, so a raw duration (not just an\n * exact 60/180/360/600) is safe to pass — mirrors `buildVideoAuditCreditId`'s\n * own rounding rather than requiring the caller to pre-round.\n */\nexport function videoAuditCreditsForBucket(bucketSec: number, auto: boolean): number {\n const bucket = pickVideoAnalysisBucket(bucketSec)\n return VIDEO_AUDIT_BUCKET_CREDITS[`video-audit${auto ? \":auto\" : \"\"}:${bucket}s`]!\n}\n\n/**\n * Parses a `video-audit:*` credit id back to its bucket seconds — both\n * families (`video-audit:<n>s` and `video-audit:auto:<n>s`); null on\n * anything else (a bare id with no bucket, a `video-analysis:*` id, or\n * garbage). Deliberately a SEPARATE parser from `bucketSecondsFromCreditId`\n * (anchored to the `video-analysis:` prefix and a mandatory model segment) —\n * mirrors the plugin-local audit parser so app code can never mis-parse an\n * audit id with the VA-anchored parser, or vice versa.\n */\nexport function bucketSecondsFromAuditCreditId(id: string): number | null {\n const m = /^video-audit(?::auto)?:(\\d+)s$/.exec(id)\n return m ? Number(m[1]) : null\n}\n","import { buildLlmCreditIdentifier, getLlmModel, LLM_FEATURE_DEFAULTS } from \"./llm-models.js\"\n\n/**\n * Pricing vocabulary for the \"steal the format\" nodes — Content Recipe and\n * Content Ideas. Public prices only: the credit ids a run is billed under and\n * the count rule that picks between them. One copy for the editor's credit\n * badge, the workflow orchestrator's reservation and the pre-run estimate;\n * the cloud plugin that runs the nodes computes the same ids.\n *\n * Content Ideas is charged per batch of up to five ideas: a run of 1–5 ideas\n * bills `content-ideas[:economy|:premium|:premium-direct]`, a run of 6–10 bills\n * `content-ideas:10[:economy|:premium|:premium-direct]`, priced at two batches.\n */\n\nexport const CONTENT_IDEAS_MAX_COUNT = 10\nexport const CONTENT_IDEAS_DEFAULT_COUNT = 5\nexport const CONTENT_IDEAS_PER_CHARGE = 5\n\n/** Request limits the cloud routes enforce — the orchestrator trims to the\n * same bounds, since its payload never passes the route's validation. */\nexport const CONTENT_RECIPE_SOURCE_MAX = 300_000\nexport const CONTENT_IDEAS_MAX_RECIPE_INPUTS = 20\nexport const CONTENT_IDEAS_BRAND_MAX = 6_000\nexport const CONTENT_IDEAS_LANGUAGE_MAX = 40\n\n/** A whole number of ideas in 1..10; anything but a finite number is the\n * default. (The plugin reads `count` the same way — numbers only.) */\nexport function clampContentIdeasCount(raw: unknown): number {\n const n = typeof raw === \"number\" && Number.isFinite(raw) ? Math.floor(raw) : CONTENT_IDEAS_DEFAULT_COUNT\n return Math.min(CONTENT_IDEAS_MAX_COUNT, Math.max(1, n))\n}\n\n/** The billing feature for a run of `count` ideas. */\nexport function contentIdeasCreditFeature(count: number): \"content-ideas\" | \"content-ideas:10\" {\n return count > CONTENT_IDEAS_PER_CHARGE ? \"content-ideas:10\" : \"content-ideas\"\n}\n\n/** The model a node runs: its own pick when the registry can return\n * structured output, else the feature default. Billing uses THIS — a missing\n * model must never bill the bare (standard) id while running economy. */\nexport function effectiveContentModel(feature: \"content-recipe\" | \"content-ideas\", llmModel: unknown): string {\n if (typeof llmModel === \"string\" && getLlmModel(llmModel)?.structuredOutputMode != null) return llmModel\n return LLM_FEATURE_DEFAULTS[feature]\n}\n\nexport function contentRecipeCreditId(llmModel?: unknown, reasoningEffort?: string): string {\n return buildLlmCreditIdentifier(\"content-recipe\", effectiveContentModel(\"content-recipe\", llmModel), reasoningEffort)\n}\n\nexport function contentIdeasCreditId(count: unknown, llmModel?: unknown, reasoningEffort?: string): string {\n return buildLlmCreditIdentifier(\n contentIdeasCreditFeature(clampContentIdeasCount(count)),\n effectiveContentModel(\"content-ideas\", llmModel),\n reasoningEffort,\n )\n}\n\n/** Every credit id the two nodes can bill — for price tables and guards. */\nexport const CONTENT_RECIPE_IDEAS_CREDIT_IDS = [\n \"content-recipe:economy\",\n \"content-recipe\",\n \"content-recipe:premium\",\n \"content-recipe:premium-direct\",\n \"content-ideas:economy\",\n \"content-ideas\",\n \"content-ideas:premium\",\n \"content-ideas:premium-direct\",\n \"content-ideas:10:economy\",\n \"content-ideas:10\",\n \"content-ideas:10:premium\",\n \"content-ideas:10:premium-direct\",\n] as const\n"]}
@@ -1,4 +1,4 @@
1
- import { LLM_FEATURE_DEFAULTS } from './chunk-YVQFYW2U.js';
1
+ import { LLM_FEATURE_DEFAULTS } from './chunk-K3YGI5IW.js';
2
2
 
3
3
  // src/script-model.ts
4
4
  var SCRIPT_LEGACY_PROVIDER_MODELS = {
@@ -12,5 +12,5 @@ function resolveScriptModelId(provider, llmModel) {
12
12
  }
13
13
 
14
14
  export { SCRIPT_LEGACY_PROVIDER_MODELS, resolveScriptModelId };
15
- //# sourceMappingURL=chunk-ML55U7WM.js.map
16
- //# sourceMappingURL=chunk-ML55U7WM.js.map
15
+ //# sourceMappingURL=chunk-C2UHX7OF.js.map
16
+ //# sourceMappingURL=chunk-C2UHX7OF.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/script-model.ts"],"names":[],"mappings":";;;AAWO,IAAM,6BAAA,GAA0E;AAAA,EACrF,MAAA,EAAQ,kBAAA;AAAA,EACR,MAAA,EAAQ,mBAAA;AAAA,EACR,GAAA,EAAK;AACP;AAEO,SAAS,oBAAA,CAAqB,UAAmB,QAAA,EAA2B;AACjF,EAAA,MAAM,MAAA,GAAS,YAAY,MAAA,CAAO,MAAA,CAAO,+BAA+B,QAAQ,CAAA,GAAI,6BAAA,CAA8B,QAA0B,CAAA,GAAI,MAAA;AAChJ,EAAA,OAAO,QAAA,IAAY,MAAA,IAAU,oBAAA,CAAqB,iBAAiB,CAAA;AACrE","file":"chunk-ML55U7WM.js","sourcesContent":["/**\n * The model a Generate Script call runs on, in one place: an explicit\n * `llmModel`, else a legacy script `provider` alias (nodes saved before the\n * per-model picker), else the feature's default. The route validates against\n * it, the worker runs it, and the server's estimate and the editor's price it —\n * one rule, so none of them can name a different model.\n */\nimport { LLM_FEATURE_DEFAULTS } from \"./llm-models.js\"\nimport type { ScriptProvider } from \"./model-constants.js\"\n\n/** Legacy provider names → the LLM model ids they ran. */\nexport const SCRIPT_LEGACY_PROVIDER_MODELS: Readonly<Record<ScriptProvider, string>> = {\n gemini: \"gemini-3.6-flash\",\n claude: \"claude-sonnet-4.6\",\n gpt: \"gpt-5.2\",\n}\n\nexport function resolveScriptModelId(provider?: string, llmModel?: string): string {\n const legacy = provider && Object.hasOwn(SCRIPT_LEGACY_PROVIDER_MODELS, provider) ? SCRIPT_LEGACY_PROVIDER_MODELS[provider as ScriptProvider] : undefined\n return llmModel || legacy || LLM_FEATURE_DEFAULTS[\"generate-script\"]\n}\n"]}
1
+ {"version":3,"sources":["../src/script-model.ts"],"names":[],"mappings":";;;AAWO,IAAM,6BAAA,GAA0E;AAAA,EACrF,MAAA,EAAQ,kBAAA;AAAA,EACR,MAAA,EAAQ,mBAAA;AAAA,EACR,GAAA,EAAK;AACP;AAEO,SAAS,oBAAA,CAAqB,UAAmB,QAAA,EAA2B;AACjF,EAAA,MAAM,MAAA,GAAS,YAAY,MAAA,CAAO,MAAA,CAAO,+BAA+B,QAAQ,CAAA,GAAI,6BAAA,CAA8B,QAA0B,CAAA,GAAI,MAAA;AAChJ,EAAA,OAAO,QAAA,IAAY,MAAA,IAAU,oBAAA,CAAqB,iBAAiB,CAAA;AACrE","file":"chunk-C2UHX7OF.js","sourcesContent":["/**\n * The model a Generate Script call runs on, in one place: an explicit\n * `llmModel`, else a legacy script `provider` alias (nodes saved before the\n * per-model picker), else the feature's default. The route validates against\n * it, the worker runs it, and the server's estimate and the editor's price it —\n * one rule, so none of them can name a different model.\n */\nimport { LLM_FEATURE_DEFAULTS } from \"./llm-models.js\"\nimport type { ScriptProvider } from \"./model-constants.js\"\n\n/** Legacy provider names → the LLM model ids they ran. */\nexport const SCRIPT_LEGACY_PROVIDER_MODELS: Readonly<Record<ScriptProvider, string>> = {\n gemini: \"gemini-3.6-flash\",\n claude: \"claude-sonnet-4.6\",\n gpt: \"gpt-5.2\",\n}\n\nexport function resolveScriptModelId(provider?: string, llmModel?: string): string {\n const legacy = provider && Object.hasOwn(SCRIPT_LEGACY_PROVIDER_MODELS, provider) ? SCRIPT_LEGACY_PROVIDER_MODELS[provider as ScriptProvider] : undefined\n return llmModel || legacy || LLM_FEATURE_DEFAULTS[\"generate-script\"]\n}\n"]}
@@ -820,5 +820,5 @@ exports.videoFaceMeshPartsOfLayers = videoFaceMeshPartsOfLayers;
820
820
  exports.videoMaskBilledSeconds = videoMaskBilledSeconds;
821
821
  exports.videoMaskCreditId = videoMaskCreditId;
822
822
  exports.videoMaskCreditIds = videoMaskCreditIds;
823
- //# sourceMappingURL=chunk-Q2LEJXLZ.cjs.map
824
- //# sourceMappingURL=chunk-Q2LEJXLZ.cjs.map
823
+ //# sourceMappingURL=chunk-C32IL6RD.cjs.map
824
+ //# sourceMappingURL=chunk-C32IL6RD.cjs.map