@nodaro/shared 3.41.0 → 3.43.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 (139) hide show
  1. package/dist/{chunk-N2KG5AMQ.cjs → chunk-3J6JYP4X.cjs} +4 -4
  2. package/dist/{chunk-N2KG5AMQ.cjs.map → chunk-3J6JYP4X.cjs.map} +1 -1
  3. package/dist/{chunk-YEZ2YUKK.js → chunk-3UAQVTIO.js} +3 -3
  4. package/dist/{chunk-YEZ2YUKK.js.map → chunk-3UAQVTIO.js.map} +1 -1
  5. package/dist/{chunk-ZXIP5T5V.js → chunk-4GYMWGUG.js} +3 -3
  6. package/dist/{chunk-ZXIP5T5V.js.map → chunk-4GYMWGUG.js.map} +1 -1
  7. package/dist/{chunk-DC5EYYVX.cjs → chunk-4URFSG3O.cjs} +38 -39
  8. package/dist/chunk-4URFSG3O.cjs.map +1 -0
  9. package/dist/{chunk-4LKEOIOT.cjs → chunk-4VDQFY27.cjs} +6 -6
  10. package/dist/{chunk-4LKEOIOT.cjs.map → chunk-4VDQFY27.cjs.map} +1 -1
  11. package/dist/{chunk-TUUEQ2WR.cjs → chunk-52IHBMTM.cjs} +8 -8
  12. package/dist/{chunk-TUUEQ2WR.cjs.map → chunk-52IHBMTM.cjs.map} +1 -1
  13. package/dist/{chunk-LOTL72UI.js → chunk-5C6WODPL.js} +4 -5
  14. package/dist/chunk-5C6WODPL.js.map +1 -0
  15. package/dist/{chunk-4IWVZR44.cjs → chunk-7TQRTEWG.cjs} +5 -5
  16. package/dist/{chunk-4IWVZR44.cjs.map → chunk-7TQRTEWG.cjs.map} +1 -1
  17. package/dist/{chunk-PYDZ7ZGH.js → chunk-BJGJXYGO.js} +3 -3
  18. package/dist/{chunk-PYDZ7ZGH.js.map → chunk-BJGJXYGO.js.map} +1 -1
  19. package/dist/{chunk-BOUEGYGI.cjs → chunk-CDEWNDBO.cjs} +33 -37
  20. package/dist/chunk-CDEWNDBO.cjs.map +1 -0
  21. package/dist/{chunk-IKCFSNNH.cjs → chunk-CLYX5WIS.cjs} +21 -21
  22. package/dist/{chunk-IKCFSNNH.cjs.map → chunk-CLYX5WIS.cjs.map} +1 -1
  23. package/dist/{chunk-ZAOBNW6Y.cjs → chunk-DFBWBEXO.cjs} +12 -20
  24. package/dist/chunk-DFBWBEXO.cjs.map +1 -0
  25. package/dist/{chunk-RLVZ3RLE.cjs → chunk-DUWBODKW.cjs} +8 -8
  26. package/dist/{chunk-RLVZ3RLE.cjs.map → chunk-DUWBODKW.cjs.map} +1 -1
  27. package/dist/{chunk-VNC5DNIQ.cjs → chunk-ESBO2KR7.cjs} +11 -13
  28. package/dist/chunk-ESBO2KR7.cjs.map +1 -0
  29. package/dist/chunk-GAPZHS2X.cjs +27 -0
  30. package/dist/{chunk-XOZIHGR5.cjs.map → chunk-GAPZHS2X.cjs.map} +1 -1
  31. package/dist/{chunk-E4MLBJKG.js → chunk-GBUHNZZU.js} +8 -8
  32. package/dist/{chunk-E4MLBJKG.js.map → chunk-GBUHNZZU.js.map} +1 -1
  33. package/dist/{chunk-5J5L26IZ.js → chunk-IAH67SHO.js} +5 -7
  34. package/dist/chunk-IAH67SHO.js.map +1 -0
  35. package/dist/{chunk-YEET2QGF.cjs → chunk-IHPDWGBN.cjs} +4 -4
  36. package/dist/{chunk-YEET2QGF.cjs.map → chunk-IHPDWGBN.cjs.map} +1 -1
  37. package/dist/{chunk-VSDJCJKP.cjs → chunk-J32WVEJH.cjs} +46 -45
  38. package/dist/chunk-J32WVEJH.cjs.map +1 -0
  39. package/dist/{chunk-MLB6YNLS.js → chunk-KUWE6E2E.js} +4 -4
  40. package/dist/{chunk-MLB6YNLS.js.map → chunk-KUWE6E2E.js.map} +1 -1
  41. package/dist/{chunk-LOWOJN65.js → chunk-KZGGUDAB.js} +45 -7
  42. package/dist/chunk-KZGGUDAB.js.map +1 -0
  43. package/dist/{chunk-CWQC6IGE.js → chunk-L6G6G5BB.js} +4 -5
  44. package/dist/chunk-L6G6G5BB.js.map +1 -0
  45. package/dist/{chunk-5CKTBGB6.js → chunk-LRJAGGKY.js} +5 -24
  46. package/dist/chunk-LRJAGGKY.js.map +1 -0
  47. package/dist/{chunk-DJIRIBKX.cjs → chunk-LZBJJ6TC.cjs} +5 -6
  48. package/dist/chunk-LZBJJ6TC.cjs.map +1 -0
  49. package/dist/{chunk-GNY2S63W.js → chunk-N5NT3WZD.js} +4 -4
  50. package/dist/{chunk-GNY2S63W.js.map → chunk-N5NT3WZD.js.map} +1 -1
  51. package/dist/{chunk-BWQRAQUD.cjs → chunk-NSTIHL5G.cjs} +43 -43
  52. package/dist/{chunk-BWQRAQUD.cjs.map → chunk-NSTIHL5G.cjs.map} +1 -1
  53. package/dist/{chunk-X7IRSO4L.js → chunk-O2VQLVKB.js} +3 -3
  54. package/dist/{chunk-X7IRSO4L.js.map → chunk-O2VQLVKB.js.map} +1 -1
  55. package/dist/{chunk-SYUY7GNT.js → chunk-OAAQG66Y.js} +7 -6
  56. package/dist/chunk-OAAQG66Y.js.map +1 -0
  57. package/dist/{chunk-YX5FW7ON.js → chunk-PLU7RIDO.js} +4 -12
  58. package/dist/chunk-PLU7RIDO.js.map +1 -0
  59. package/dist/{chunk-A4NDZBSJ.js → chunk-PVAOXI2W.js} +14 -20
  60. package/dist/chunk-PVAOXI2W.js.map +1 -0
  61. package/dist/{chunk-GXTWKAJF.js → chunk-PZE6WTA3.js} +3 -3
  62. package/dist/{chunk-GXTWKAJF.js.map → chunk-PZE6WTA3.js.map} +1 -1
  63. package/dist/{chunk-TGZJXCLL.cjs → chunk-QHODM5TS.cjs} +46 -6
  64. package/dist/chunk-QHODM5TS.cjs.map +1 -0
  65. package/dist/{chunk-JN3V33AN.cjs → chunk-QJ2VGB5J.cjs} +6 -6
  66. package/dist/{chunk-JN3V33AN.cjs.map → chunk-QJ2VGB5J.cjs.map} +1 -1
  67. package/dist/{chunk-ADYPAGQF.cjs → chunk-RPQ2KF6L.cjs} +5 -24
  68. package/dist/chunk-RPQ2KF6L.cjs.map +1 -0
  69. package/dist/{chunk-2BJADMEX.js → chunk-S4UAYQQV.js} +3 -3
  70. package/dist/{chunk-2BJADMEX.js.map → chunk-S4UAYQQV.js.map} +1 -1
  71. package/dist/{chunk-FVZMFDRO.js → chunk-TTD6MZAM.js} +4 -4
  72. package/dist/{chunk-FVZMFDRO.js.map → chunk-TTD6MZAM.js.map} +1 -1
  73. package/dist/entries/apps.cjs +42 -42
  74. package/dist/entries/apps.js +7 -7
  75. package/dist/entries/credits.cjs +150 -150
  76. package/dist/entries/credits.d.cts +1 -1
  77. package/dist/entries/credits.d.ts +1 -1
  78. package/dist/entries/credits.js +7 -7
  79. package/dist/entries/llm-models.d.cts +1 -1
  80. package/dist/entries/llm-models.d.ts +1 -1
  81. package/dist/entries/media.cjs +56 -48
  82. package/dist/entries/media.d.cts +65 -3
  83. package/dist/entries/media.d.ts +65 -3
  84. package/dist/entries/media.js +1 -1
  85. package/dist/entries/model-catalog.cjs +66 -66
  86. package/dist/entries/model-catalog.js +4 -4
  87. package/dist/entries/models.cjs +252 -244
  88. package/dist/entries/models.d.cts +2 -7
  89. package/dist/entries/models.d.ts +2 -7
  90. package/dist/entries/models.js +4 -4
  91. package/dist/entries/nodes.cjs +206 -206
  92. package/dist/entries/nodes.js +8 -8
  93. package/dist/entries/pipeline.cjs +149 -149
  94. package/dist/entries/pipeline.d.cts +10 -14
  95. package/dist/entries/pipeline.d.ts +10 -14
  96. package/dist/entries/pipeline.js +3 -3
  97. package/dist/entries/ugc.cjs +71 -71
  98. package/dist/entries/ugc.js +4 -4
  99. package/dist/entries/video.cjs +117 -117
  100. package/dist/entries/video.js +4 -4
  101. package/dist/index.cjs +1085 -1069
  102. package/dist/index.d.cts +2 -2
  103. package/dist/index.d.ts +2 -2
  104. package/dist/index.js +18 -18
  105. package/dist/{model-constants-B5ka4TQr.d.cts → model-constants-BL-Ae0OU.d.cts} +24 -7
  106. package/dist/{model-constants-B5ka4TQr.d.ts → model-constants-BL-Ae0OU.d.ts} +24 -7
  107. package/package.json +1 -1
  108. package/src/__tests__/credit-identifiers.test.ts +13 -32
  109. package/src/__tests__/pricing-default-duration.test.ts +0 -2
  110. package/src/__tests__/retired-video-provider.test.ts +42 -0
  111. package/src/__tests__/video-audio-capability.test.ts +4 -13
  112. package/src/__tests__/video-mask.test.ts +31 -0
  113. package/src/__tests__/video-mode-aliases.test.ts +10 -1
  114. package/src/credit-identifiers.ts +4 -1
  115. package/src/entries/models.ts +2 -0
  116. package/src/film-pricing.ts +0 -1
  117. package/src/model-catalog.ts +3 -22
  118. package/src/model-constants.ts +29 -15
  119. package/src/pipeline-types.ts +4 -2
  120. package/src/provider-directive-defaults.ts +0 -1
  121. package/src/video-mask.ts +69 -2
  122. package/src/video-output-canvas.ts +0 -8
  123. package/dist/chunk-5CKTBGB6.js.map +0 -1
  124. package/dist/chunk-5J5L26IZ.js.map +0 -1
  125. package/dist/chunk-A4NDZBSJ.js.map +0 -1
  126. package/dist/chunk-ADYPAGQF.cjs.map +0 -1
  127. package/dist/chunk-BOUEGYGI.cjs.map +0 -1
  128. package/dist/chunk-CWQC6IGE.js.map +0 -1
  129. package/dist/chunk-DC5EYYVX.cjs.map +0 -1
  130. package/dist/chunk-DJIRIBKX.cjs.map +0 -1
  131. package/dist/chunk-LOTL72UI.js.map +0 -1
  132. package/dist/chunk-LOWOJN65.js.map +0 -1
  133. package/dist/chunk-SYUY7GNT.js.map +0 -1
  134. package/dist/chunk-TGZJXCLL.cjs.map +0 -1
  135. package/dist/chunk-VNC5DNIQ.cjs.map +0 -1
  136. package/dist/chunk-VSDJCJKP.cjs.map +0 -1
  137. package/dist/chunk-XOZIHGR5.cjs +0 -27
  138. package/dist/chunk-YX5FW7ON.js.map +0 -1
  139. package/dist/chunk-ZAOBNW6Y.cjs.map +0 -1
@@ -1 +0,0 @@
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/topaz-upscale.ts","../src/monetization.ts","../src/lip-sync-pricing.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":["CREDIT_BASE_USD","known","output","overlayPlatformById","DEFAULT_TEXT_TO_AUDIO_PROVIDER","canonicalTtsProvider","unitQuoteCreditId","findTtsCapabilities","findDialogueCapabilities","ALLOWED_RESOLUTIONS","getLlmModel","LLM_FEATURE_DEFAULTS","buildLlmCreditIdentifier"],"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,GAAA,GAAMA,oCAAmB,0BAA0B,CAAA;AACpF,EAAA,OAAO,IAAA,CAAK,IAAA,CAAK,YAAA,GAAe,0BAA0B,CAAA;AAC5D;AAGO,SAAS,aAAa,OAAA,EAAyB;AACpD,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,OAAO,CAAA,QAAS,IAAI,KAAA,CAAM,CAAA,0C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AAA;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-VNC5DNIQ.cjs","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\": { credits: 7, clipSeconds: 8 }, // seedance:8s\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\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 let total = 0\n for (const d of upstreamDurations) {\n total += typeof d === \"number\" && Number.isFinite(d) && d >= 0 ? d : fallback\n }\n\n if (data.transition && data.transition !== \"cut\" && n > 1) {\n total -= (data.transitionDuration ?? 0.5) * (n - 1)\n }\n\n const trimSecPerClip =\n ((data.trimStartFrames ?? 0) + (data.trimEndFrames ?? 0)) /\n VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT\n total -= trimSecPerClip * n\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\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 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 * 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/**\n * The price-row id of one unit for the model a request runs as. 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 return `${canonicalTtsProvider(modelId)}${SPEECH_UNIT_CREDIT_SUFFIX}`\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 * 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 return unitQuoteCreditId(speechUnitCreditId(modelId), 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 `<model>:per-100-chars` unit row. */\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}\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 }\n}\n\n/**\n * Whether an id is a length price of speech — a `<model>:per-100-chars` unit\n * row or a `<model>:per-100-chars:<N>u` request quote — by its shape alone.\n * Both are served only while the server prices speech by length.\n */\nexport function isSpeechLengthPriceId(id: string): boolean {\n return typeof id === \"string\" && /:per-100-chars(?::\\d+u)?$/.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)?$/, \"\")\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\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 * 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 * 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 * 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\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}\n\nexport function getLipSyncMaxAudioSeconds(provider: string): number {\n return LIP_SYNC_MAX_AUDIO_SECONDS[provider] ?? 15\n}\n\n/** Providers whose credit cost varies with audio duration. */\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])\n\nexport function isPerSecondLipSyncProvider(provider: string): boolean {\n return PER_SECOND_LIP_SYNC_PROVIDERS.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 * 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.\nexport const VIDEO_ANALYSIS_BUCKET_CREDITS: Record<string, number> = {\n // Current fast tier (VIDEO_ANALYSIS_TIERS.fast; it was also the fast model\n // before 2026-07).\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 // 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\": 270,\n \"video-analysis:mixed:180s\": 291,\n \"video-analysis:mixed:360s\": 729,\n \"video-analysis:mixed:600s\": 1177,\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\": 413,\n \"video-analysis:smart:180s\": 503,\n \"video-analysis:smart:360s\": 1267,\n \"video-analysis:smart:600s\": 2076,\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 * `gemini-3-flash` (legacy fast tier) row 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 \"video-audit:auto:60s\": 396,\n \"video-audit:auto:180s\": 475,\n \"video-audit:auto:360s\": 1178,\n \"video-audit:auto:600s\": 1921,\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 +0,0 @@
1
- {"version":3,"sources":["../src/credit-identifiers.ts"],"names":["FLUX2_RES_MP","defaultResolutionFor","isFlux2Model","HIGH_QUALITY_PROVIDERS","TWO_K_RESOLUTION_PROVIDERS","RESOLUTION_2K_4K_TIERED_PROVIDERS","IDEOGRAM_PROVIDERS","T2I_TO_I2I_VARIANT","autoAspectNeedsSourceImage","normalizeModelInput","snapToNearestDuration","pricedOutputDurationSec","isWan3Provider","normalizeWan3Resolution","isViduQ4Provider","normalizeViduQ4Resolution","isKling4Provider","normalizeKling4Resolution","DURATION_PRICED_PROVIDERS","isVeoProvider","VEO_RESOLUTION_TIERED_PROVIDERS","isGeminiOmniProvider","VIDEO_DURATION_TIERS","getVideoAudioCapability","AUDIO_ADDON_PROVIDERS","MODE_ADDON_PROVIDERS","RESOLUTION_VIDEO_REF_PRICING","MODEL_CATALOG","PRICING_DEFAULT_RESOLUTION","RESOLUTION_DURATION_PRICING","VIDEO_REF_RATE_PROVIDERS","isMinimaxH3Provider","normalizeMinimaxH3Resolution","normalizeVideoRequestParams","uiResolutionFill","VIDEO_DURATION_AUTO","MOTION_DURATION_TIERS"],"mappings":";;;;;;;AAiEA,SAAS,kBAAA,CAAmB,OAAmB,UAAA,EAA6B;AAC1E,EAAA,MA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ACzF,EAAA,MAAM,QAAQ,OAAA,KAAY,OAAA;AAC1B,EAAA,IAAI,IAAA,KAAS,UAAA,EAAY,OAAO,KAAA,GAAQ,oBAAA,GAAuB,cAAA;AAC/D,EAAA,OAAO,QAAQ,4BAAA,GAA+B,sBAAA;AAChD;AAkBO,SAAS,cAAA,CAAe,OAA2B,SAAA,EAA2B;AACnF,EAAA,IAAI,CAAE,8BAAA,CAAqD,QAAA,CAAS,SAAS,CAAA,EAAG;AAC9E,IAAA,OAAO,SAAA;AAAA,EACT;AACA,EAAA,OAAQ,KAAA,IAAS,wBAAA,CAAyB,KAAK,CAAA,IAAM,SAAA;AACvD;AAUO,IAAM,wBAAA,GAA6D;AAAA,EACxE,EAAA,EAAI,SAAA;AAAA,EACJ,OAAA,EAAS,cAAA;AAAA,EACT,OAAA,EAAS,cAAA;AAAA,EACT,IAAA,EAAM,WAAA;AAAA,EACN,EAAA,EAAI;AACN","file":"chunk-VSDJCJKP.cjs","sourcesContent":["/**\n * Build composite credit model identifiers for variable pricing.\n * Shared between frontend and backend.\n */\n\nimport {\n HIGH_QUALITY_PROVIDERS,\n TWO_K_RESOLUTION_PROVIDERS,\n RESOLUTION_2K_4K_TIERED_PROVIDERS,\n IDEOGRAM_PROVIDERS,\n DURATION_PRICED_PROVIDERS,\n AUDIO_ADDON_PROVIDERS,\n MODE_ADDON_PROVIDERS,\n RESOLUTION_VIDEO_REF_PRICING,\n RESOLUTION_DURATION_PRICING,\n VEO_RESOLUTION_TIERED_PROVIDERS,\n VIDEO_DURATION_TIERS,\n pricedOutputDurationSec,\n snapToNearestDuration,\n PRICING_DEFAULT_RESOLUTION,\n MOTION_DURATION_TIERS,\n T2I_TO_I2I_VARIANT,\n isVeoProvider,\n isMinimaxH3Provider,\n isGeminiOmniProvider,\n isWan3Provider,\n isViduQ4Provider,\n isKling4Provider,\n normalizeKling4Resolution,\n VIDEO_REF_RATE_PROVIDERS,\n normalizeMinimaxH3Resolution,\n normalizeWan3Resolution,\n normalizeViduQ4Resolution,\n getVideoAudioCapability,\n} from \"./model-constants.js\"\nimport { isFlux2Model, FLUX2_RES_MP, type Flux2Model } from \"./flux2-pricing.js\"\nimport { VIDEO_DURATION_AUTO } from \"./video-duration-auto.js\"\nimport { uiResolutionFill } from \"./video-ui-defaults.js\"\nimport { MODEL_CATALOG, autoAspectNeedsSourceImage, normalizeModelInput, normalizeVideoRequestParams, defaultResolutionFor, type ModelInputAdjustment, type SourceImageSize } from \"./model-catalog.js\"\n\n/**\n * The megapixel tier a Flux 2 credit identifier is keyed on, for ANY incoming\n * `resolution` value.\n *\n * Flux 2 is the only family whose identifier INTERPOLATES the resolution\n * instead of matching it against a known set, and its callers are not\n * guaranteed to hand it a Flux 2 value:\n * - the multi-provider cost preview prices one node's data against EVERY\n * selected provider (`frontend/src/ee/hooks/use-providers-credits-sum.ts`),\n * so a node whose `resolution` is \"2K\" (the flux / nano-banana-pro value\n * space) reaches this branch verbatim;\n * - node data written straight into workflow JSON by an agent, an import or\n * a template never ran the config panel's provider-change fail-safe.\n * Interpolating that produced the off-grid id `flux-2-pro:2KMP:0ref`, which no\n * pricing row can answer — every cost badge 503'd `price_not_configured`\n * (18 production app-reports, 2026-09-07..14).\n *\n * A value off the grid snaps to the model's DEFAULT tier — the same `preferred`\n * value `normalizeModelInput` uses — so the preview asks for exactly the id the\n * route will reserve (both routes and the orchestrator normalize through\n * `resolveNormalizedImageGen` first, which makes this snap a no-op for them).\n * An ABSENT resolution keeps its long-standing meaning (\"this caller has no\n * resolution dimension at all\") and stays on 1 MP rather than moving to the\n * model default, which would silently re-price every resolution-less node.\n */\nfunction flux2MegapixelTier(model: Flux2Model, resolution?: string): string {\n const bare = (v: string) => v.replace(/\\s*MP$/i, \"\").trim()\n const raw = typeof resolution === \"string\" ? bare(resolution) : \"\"\n if (raw === \"\") return \"1\"\n // Numeric match so \"2.0\"/\" 2 MP\" land on the same grid point as \"2\", and the\n // GRID's own spelling is what gets emitted — returning the caller's \"2.0\"\n // would build \":2.0MP:\", another id no pricing row carries.\n const tier = FLUX2_RES_MP.find((t) => Number(t) === Number(raw))\n return tier ?? bare(defaultResolutionFor(model) ?? \"1 MP\")\n}\n\n/**\n * Compute composite model identifier for variable credit pricing.\n * Examples: \"gpt-image:high\", \"flux:2K\", \"nano-banana-pro:4K\", \"ideogram:TURBO\",\n * \"flux-2-pro:2MP\", \"flux-2-max:2MP:1ref\" (Flux 2 — billed per megapixel).\n *\n * For image models, uses quality/resolution/renderingSpeed and (Flux 2) the output\n * megapixel count plus (Flux 2 Max) the number of reference images attached at request time.\n * For video models, uses duration/sound params when the model has variable pricing.\n */\nexport function buildCreditModelIdentifier(\n provider: string,\n quality?: string,\n resolution?: string,\n renderingSpeed?: string,\n targetResolution?: string,\n referenceImageCount?: number,\n): string {\n // Flux 2 family: billed per output megapixel AND per reference image (each\n // ref counts as input megapixels). Resolution arrives as \"N MP\" strings (the\n // UI value space); strip the unit. ALL three models encode the ref count\n // (capped at 8): Pro/Klein i2i always carry the source image as a ref and\n // their cost formula charges per input MP, so the reserved identifier must\n // reflect refs (there is no metered true-up to correct an under-reserved tier).\n if (isFlux2Model(provider)) {\n return `${provider}:${flux2MegapixelTier(provider, resolution)}MP:${Math.min(referenceImageCount ?? 0, 8)}ref`\n }\n if (HIGH_QUALITY_PROVIDERS.has(provider) && quality === \"high\") {\n return `${provider}:high`\n }\n if (TWO_K_RESOLUTION_PROVIDERS.has(provider) && resolution === \"2K\") {\n return `${provider}:2K`\n }\n if (provider === \"nano-banana-pro\" && resolution === \"4K\") {\n return `${provider}:4K`\n }\n if (RESOLUTION_2K_4K_TIERED_PROVIDERS.has(provider) && (resolution === \"2K\" || resolution === \"4K\")) {\n return `${provider}:${resolution}`\n }\n // Topaz Image Upscale: 2K is default (no suffix), 4K/8K get composite identifiers\n if (provider === \"topaz-image-upscale\" && targetResolution && targetResolution !== \"2K\") {\n return `${provider}:${targetResolution}`\n }\n if (IDEOGRAM_PROVIDERS.has(provider)) {\n if (renderingSpeed === \"TURBO\") return `${provider}:TURBO`\n if (renderingSpeed === \"QUALITY\") return `${provider}:QUALITY`\n }\n return provider\n}\n\n/**\n * An image request's catalog-snapped parameters PLUS the credit identifier\n * priced off them.\n *\n * `adjustments` is the disclosure channel: every lever this changed, why, and\n * to what. Routes return it in the 200 body so a caller learns their value was\n * corrected instead of silently getting something else.\n */\nexport interface NormalizedImageGen {\n /** Credit identifier, priced off the SNAPPED `resolution` / `quality`. */\n identifier: string\n /** The catalog model id the params were snapped against (post T2I→I2I swap). */\n modelId: string\n aspectRatio?: string\n resolution?: string\n quality?: string\n /** Empty when the caller's values were already valid for `modelId`. */\n adjustments: ModelInputAdjustment[]\n}\n\n/**\n * The catalog model `resolveNormalizedImageGen` snaps against: the provider\n * (Nano Banana when none is named), or — with `swapToI2i` and references\n * attached — its i2i sibling, the model the generate-image route and the\n * workflow payload builder then send. That sibling has its OWN catalog entry\n * and lever lists. Exported so a caller that has to decide something about\n * those lists before the snap (whether a photo's size is worth reading) asks\n * about the same model the snap will use.\n */\nexport function normalizedImageGenModelId(opts: {\n provider: unknown\n refCount: number\n swapToI2i?: boolean\n}): string {\n const provider = typeof opts.provider === \"string\" && opts.provider.length > 0 ? opts.provider : \"nano-banana\"\n return opts.swapToI2i && opts.refCount > 0 ? (T2I_TO_I2I_VARIANT[provider] ?? provider) : provider\n}\n\n/**\n * Whether \"auto\" on a Generate Image request can need its photo's size: the\n * model the snap runs against (`normalizedImageGenModelId` with the swap on)\n * has no native auto. Given the ASSEMBLED reference count, it asks about exactly\n * that model; without one — a write boundary, or a run before its references\n * assemble — about both the provider and its i2i sibling, since references may\n * yet attach.\n */\nexport function imageGenAutoAspectNeedsSourceImage(opts: {\n provider: unknown\n aspectRatio: unknown\n refCount?: number\n}): boolean {\n const asks = (refCount: number) =>\n autoAspectNeedsSourceImage(normalizedImageGenModelId({ provider: opts.provider, refCount, swapToI2i: true }), opts.aspectRatio)\n return opts.refCount === undefined ? asks(0) || asks(1) : asks(opts.refCount)\n}\n\n/**\n * Snap an image request's catalog-governed levers to a combination the model\n * actually accepts, and price the credit identifier off the SNAPPED values.\n *\n * WHY THE SNAP LIVES HERE and not at the call site. Both image routes compute\n * their credit identifier TWICE — once in the `creditGuard` preHandler (the\n * CHECK) and once at the handler's `reserveCreditsForJob` (the DEBIT) — and a\n * dedicated test asserts the two stay byte-identical (see\n * `backend/src/routes/__tests__/generate-image.test.ts`, \"CHECK === DEBIT\").\n * `resolution` and `quality` are pricing dimensions, so a snap applied at only\n * one of those sites breaks that invariant, and `commit_credits` never collects\n * an upward delta — the reserve IS the charge. Putting the snap inside the\n * primitive makes CHECK, DEBIT and the workflow orchestrator agree by\n * construction rather than by everyone remembering to call a normalizer.\n *\n * Inputs are typed `unknown` on purpose: the preHandler runs BEFORE Zod, so a\n * caller can put a number or an object in `resolution`. Non-strings become\n * `undefined` rather than reaching `normalizeModelInput` as a lie.\n *\n * Unknown model ids pass through untouched (same contract as\n * `normalizeModelInput`) — the route's provider enum is the gate for those.\n *\n * `sourceImage` is the size of the photo the request transforms or is drawn\n * from (an image-to-image / edit source, or Generate Image's first wired\n * reference). It only decides \"auto\" on a model without a native auto, and the\n * ratio is not a pricing dimension on any such model (pinned across the catalog\n * by `auto-aspect-source.test.ts`), so a CHECK that runs before the size is\n * known prices the same identifier as the DEBIT that knows it.\n */\nexport function resolveNormalizedImageGen(opts: {\n provider: string | undefined\n aspectRatio?: unknown\n quality?: unknown\n resolution?: unknown\n renderingSpeed?: unknown\n refCount: number\n swapToI2i?: boolean\n sourceImage?: SourceImageSize\n}): NormalizedImageGen {\n const str = (v: unknown): string | undefined =>\n typeof v === \"string\" && v.length > 0 ? v : undefined\n\n const modelId = normalizedImageGenModelId(opts)\n\n const n = normalizeModelInput(\n modelId,\n {\n aspectRatio: str(opts.aspectRatio),\n resolution: str(opts.resolution),\n quality: str(opts.quality),\n },\n { sourceImage: opts.sourceImage },\n )\n\n return {\n identifier: buildCreditModelIdentifier(\n modelId,\n n.quality,\n n.resolution,\n str(opts.renderingSpeed),\n undefined,\n opts.refCount,\n ),\n modelId,\n aspectRatio: n.aspectRatio,\n resolution: n.resolution,\n quality: n.quality,\n adjustments: n.adjustments,\n }\n}\n\n/**\n * Reference-aware image-generation credit identifier — the SINGLE source of\n * truth shared by the single-node routes (`/v1/generate-image`,\n * `/v1/image-to-image`) and the workflow orchestrator\n * (`payload-builder.ts`). It centralises the two pricing dimensions that must\n * match across both paths or a Flux 2 generation is billed the wrong tier\n * (Flux 2 commits non-metered / has no upward true-up, so the reserved\n * identifier IS the final charge):\n * - `refCount`: the number of reference images sent to the provider (Flux 2\n * bills per ref). generate-image passes the assembled count (0 for pure\n * text-to-image); image-to-image passes 1 (the primary `imageUrl`) + extras.\n * - `swapToI2i`: generate-image auto-swaps a bare T2I provider to its i2i\n * sibling (`T2I_TO_I2I_VARIANT`) when refs are attached, so the credit id\n * matches the variant actually invoked. image-to-image is already an i2i\n * provider → pass `false`.\n *\n * The LoRA short-circuit (`flux-lora-character`) stays at the call site because\n * the routing decision needs a DB lookup the routes/orchestrator own.\n */\nexport function resolveImageGenCreditIdentifier(opts: {\n provider: string | undefined\n quality?: string\n resolution?: string\n renderingSpeed?: string\n refCount: number\n swapToI2i?: boolean\n}): string {\n return resolveNormalizedImageGen(opts).identifier\n}\n\n// T2V-specific credit overrides: some providers have different costs for T2V\n// vs I2V/V2V due to different default resolutions or colliding with image model names.\nconst T2V_CREDIT_OVERRIDES: Record<string, string> = {\n \"grok\": \"grok-i2v\", // T2V grok, same as I2V grok (not image grok = 4 cr)\n \"wan\": \"wan-t2v\", // T2V wan 1080p = (V2V wan 720p = 70 cr)\n \"wan-turbo\": \"wan-turbo-t2v\", // T2V wan-turbo 720p = (I2V wan-turbo 480p = 40 cr)\n}\n\n/**\n * Compute composite model identifier for video models with duration/audio-based pricing.\n * Examples: \"kling-3.0:5s\", \"kling-3.0:10s:audio\", \"seedance-2:8s:720p-ref\"\n *\n * @param provider - Video model key (e.g., \"kling-3.0\")\n * @param duration - Video duration in seconds\n * @param sound - Whether audio/sound is enabled\n * @param nodeType - Node type for T2V-specific cost overrides\n * @param mode - Quality variant that affects pricing\n * @param resolution - Output resolution (used by Seedance 2 for 480p/720p pricing)\n * @param hasVideoRef - Whether a reference video is connected (Seedance 2 uses a lower per-second rate when true)\n */\n/**\n * LTX 2.3 (Lightricks via Replicate) credit tiers: priced by\n * (resolution-band × duration-seconds). Keys mirror STATIC_CREDIT_COSTS /\n * model_pricing EXACTLY (lowercase band + raw seconds + \"s\"), e.g.\n * \"ltx-2.3-pro:1080p:6s\". This map is the source of truth for the nearest-tier\n * snap below, so an off-catalog (resolution, duration) from a direct API/SDK\n * call maps to a SEEDED price instead of hard-failing (price_not_configured\n * 503). Pro: 6/8/10s at every band. Fast: up to 20s at 1080p, 6/8/10s at 2k/4k.\n */\nconst LTX_DURATION_TIERS: Record<string, Record<string, number[]>> = {\n \"ltx-2.3-pro\": { \"1080p\": [6, 8, 10], \"2k\": [6, 8, 10], \"4k\": [6, 8, 10] },\n \"ltx-2.3-fast\": { \"1080p\": [6, 8, 10, 12, 14, 16, 18, 20], \"2k\": [6, 8, 10], \"4k\": [6, 8, 10] },\n}\n\n/**\n * The (band, duration) tier the LTX pricing ladder charges for a request, or\n * `undefined` for a non-LTX provider. Extracted so\n * `buildVideoCreditModelIdentifier` and `pricedVideoSelection` read the ladder\n * ONCE — the routes must send the tier they reserved, and a second copy of this\n * math is exactly how the two drift apart.\n *\n * An unknown/absent band falls back to 1080p (LTX's own default, and the band\n * `snapLtxInput` snaps to at the Replicate call), and an off-tier duration\n * snaps to the NEAREST seeded one so the emitted composite always prices.\n */\nfunction ltxPricedTier(\n provider: string,\n resolution?: string,\n duration?: number | string,\n): { band: string; duration: number } | undefined {\n const bands = LTX_DURATION_TIERS[provider]\n if (!bands) return undefined\n const band = bands[String(resolution)] ? String(resolution) : \"1080p\"\n const allowed = bands[band]!\n // The model's own default (catalog `defaultDuration`) when unset, then the\n // nearest rung of THIS band's ladder — the length LTX renders.\n const dur = snapToNearestDuration(pricedOutputDurationSec(provider, duration), allowed)\n return { band, duration: dur }\n}\n\n/**\n * The resolution a provider whose runner NORMALIZES the lever actually renders,\n * in the lowercase spelling of its credit composites — billing collapses\n * through the very normalizer the runner sends, so render == billed for every\n * spelling. `undefined` passes through untouched for every other provider.\n */\nfunction wireNormalizedResolution(provider: string, resolution: string | undefined): string | undefined {\n if (isWan3Provider(provider)) return normalizeWan3Resolution(resolution).toLowerCase()\n if (isViduQ4Provider(provider)) return normalizeViduQ4Resolution(resolution)\n if (isKling4Provider(provider)) return normalizeKling4Resolution(resolution)\n return resolution\n}\n\nexport function buildVideoCreditModelIdentifier(\n provider: string,\n duration?: number | string,\n sound?: boolean,\n nodeType?: \"image-to-video\" | \"text-to-video\",\n mode?: string,\n resolution?: string,\n hasVideoRef?: boolean,\n): string {\n // T2V overrides: some providers have different base costs for text-to-video\n let effectiveProvider = provider\n if (nodeType === \"text-to-video\") {\n const override = T2V_CREDIT_OVERRIDES[provider]\n if (override) {\n // If override target also has duration pricing, use it as effective provider\n if (DURATION_PRICED_PROVIDERS.has(override)) {\n effectiveProvider = override\n } else {\n return override\n }\n }\n }\n\n // VEO 3.x resolution-tiered pricing: 720p is the base (no suffix), 1080p gets\n // \":1080p\" (Fast/Lite only), and 4K gets \":4k\" for ALL three tiers — direct-4K\n // generation chains KIE's get-4k-video off the base generation (the base runs\n // at 1080p). Duration is fixed at 8s for VEO so the duration-tier path below\n // does not apply.\n if (isVeoProvider(effectiveProvider)) {\n if (resolution === \"4k\") return `${effectiveProvider}:4k`\n // 1080p tier is Fast/Lite only (Quality has no 1080p surcharge).\n if (resolution === \"1080p\" && VEO_RESOLUTION_TIERED_PROVIDERS.has(effectiveProvider)) return `${effectiveProvider}:1080p`\n return effectiveProvider\n }\n\n // Gemini Omni family (gemini-omni-video + gemini-omni-flash): priced by\n // (resolution-band × duration), with a flat per-generation rate when a source\n // video is supplied (V2V). Lowercase \"4k\". The prefix is TEMPLATED from the\n // provider id, so a further Omni SKU needs no edit here — it only has to join\n // GEMINI_OMNI_PROVIDERS and seed its rows. These models are deliberately NOT\n // in DURATION_PRICED_PROVIDERS; this branch early-returns before that gate.\n if (isGeminiOmniProvider(effectiveProvider)) {\n if (hasVideoRef) {\n return resolution === \"4k\" ? `${effectiveProvider}:4k:vref` : `${effectiveProvider}:vref`\n }\n // The rendered length through the catalog funnel (nearest legal tier, the\n // model's own default when unset) so the composite is always a SEEDED one.\n const d = pricedOutputDurationSec(effectiveProvider, duration)\n return resolution === \"4k\" ? `${effectiveProvider}:4k:${d}` : `${effectiveProvider}:${d}`\n }\n\n // LTX 2.3: priced by (resolution-band × duration-seconds). The RESERVE must be\n // the correct composite — commit_credits (migration 176) only refunds a surplus\n // (actual < reserved) and NEVER collects an upward delta, so an under-reserved\n // LTX run (the bare-id default = cheapest 1080p:6s tier) stays under-charged\n // even with meteredCost:true. Snap to a seeded tier so the id always prices.\n const ltxTier = ltxPricedTier(effectiveProvider, resolution, duration)\n if (ltxTier) {\n return `${effectiveProvider}:${ltxTier.band}:${ltxTier.duration}s`\n }\n\n if (!DURATION_PRICED_PROVIDERS.has(effectiveProvider)) {\n return effectiveProvider\n }\n\n // A named-provider request with NO duration renders the model's own default\n // (kie/models.ts extraParams), so price that default — not the global 5s —\n // for providers whose per-second tiers wouldn't snap 5 up to it\n // (minimax-h3, seedance-2-5). One helper, shared with the dynamic\n // reference-video reservations, so the tier and the scaled reserve agree.\n const durationSec = pricedOutputDurationSec(effectiveProvider, duration)\n const tiers = VIDEO_DURATION_TIERS[effectiveProvider]\n if (!tiers) return effectiveProvider\n\n // Find the matching duration tier\n const tier = tiers.find(t => durationSec <= t.maxSeconds) ?? tiers[tiers.length - 1]\n let identifier = `${effectiveProvider}:${tier.suffix}`\n\n // Append audio suffix if applicable. When the caller expressed no intent\n // (sound === undefined), fall back to the model's own default (capability\n // `defaultOn` — kling-3.0 generates audio unless explicitly disabled), so an\n // intent-less request is billed for the audio it actually produces instead\n // of reserving the cheaper no-audio tier against an audio-on generation.\n const soundOn = sound ?? (getVideoAudioCapability(effectiveProvider).defaultOn === true)\n if (AUDIO_ADDON_PROVIDERS.has(effectiveProvider) && soundOn) {\n identifier += \":audio\"\n }\n\n // Append mode suffix for providers with quality-tiered pricing\n // \"high\" comes from I2V videoSize field, \"pro\" comes from T2V mode field\n if (MODE_ADDON_PROVIDERS.has(effectiveProvider) && (mode === \"high\" || mode === \"pro\")) {\n identifier += \":high\"\n }\n\n // Seedance 2.0 family: per-second billing with resolution + video-ref dimensions.\n // KIE accepts 480p / 720p / 1080p natively; per-second rates rise non-linearly\n // so each tier gets its own composite identifier.\n if (RESOLUTION_VIDEO_REF_PRICING.has(effectiveProvider)) {\n // Clamp to the model's catalog resolutions (single source of truth): e.g.\n // seedance-2-mini exposes only 480p/720p, so a stale/explicit 1080p (or 4k)\n // maps to its top priced tier instead of emitting an unpriced composite\n // (which the hard-fail credit guard would 503 on at runtime).\n const supported = MODEL_CATALOG[effectiveProvider]?.resolutions ?? [\"480p\", \"720p\", \"1080p\"]\n // An OMITTED resolution renders the model's KIE-side default, so price that\n // default rather than the cheapest tier — otherwise an intent-less request\n // reserves 480p against a 720p render and commit_credits (refund-only) can\n // never collect the delta. Providers without an entry keep the historical\n // 480p fallback, so this cannot reprice anything already live.\n const requested = resolution ?? PRICING_DEFAULT_RESOLUTION[effectiveProvider]\n const want = requested === \"4k\" ? \"4k\" : requested === \"1080p\" ? \"1080p\" : requested === \"720p\" ? \"720p\" : \"480p\"\n // Unsupported (e.g. a stale 1080p on seedance-2-mini) clamps to the model's\n // top priced tier so the emitted composite is always seeded.\n const res = supported.includes(want) ? want : (supported[supported.length - 1] ?? \"480p\")\n identifier += `:${res}`\n if (hasVideoRef) identifier += \"-ref\"\n }\n\n // Duration × resolution pricing without a -ref dimension. Resolutions\n // outside the provider's priced tiers (or undefined) collapse to the first\n // (default) tier so the emitted composite is always seeded — the hard-fail\n // guard fuzzes the whole resolution space.\n const resTiers = RESOLUTION_DURATION_PRICING[effectiveProvider]\n if (resTiers) {\n // The \"default tier\" is the provider's DECLARED default when it has one\n // (PRICING_DEFAULT_RESOLUTION — wan-3 renders 720p, not the cheapest tier),\n // otherwise the first listed tier. Declaring it explicitly means a cosmetic\n // reorder of the tier list can never reprice a live model, and an OMITTED\n // *or* unsupported resolution both land on what actually renders instead of\n // on the cheapest row (commit_credits refunds a surplus but can never\n // collect a shortfall). Behaviour-neutral for every member without a\n // declared default.\n const declaredDefault = PRICING_DEFAULT_RESOLUTION[effectiveProvider]\n const fallback = declaredDefault && resTiers.includes(declaredDefault) ? declaredDefault : resTiers[0]!\n // Wan 3.0 renders through `normalizeWan3Resolution`, which is CASE-INSENSITIVE\n // (\"1080P\" — KIE's own OpenAPI enum spelling, and the natural value for an\n // integrator reading the provider docs — renders 1080P). The tier list here is\n // lowercase and `Array.includes` is case-sensitive, so without this the render\n // path and the billing path disagree: \"1080P\" rendered the top tier and billed\n // the 720p row, a shortfall `commit_credits` (refund-only) can never collect.\n // Collapsing through the SAME normalizer the runner uses makes render == billed\n // by construction for every spelling, including garbage (→ the declared 720p).\n // Scoped to the families whose runner normalizes on purpose (Wan 3.0, Vidu\n // Q4): the other RESOLUTION_DURATION_PRICING members pass `resolution` to\n // their wire verbatim, so case-folding their billing without probing their\n // wire would reprice live models.\n const requested = wireNormalizedResolution(effectiveProvider, resolution)\n const res = requested && resTiers.includes(requested) ? requested : fallback\n identifier += `:${res}`\n // A reference VIDEO bills at its own per-second rate (Kling 4.0).\n if (hasVideoRef && VIDEO_REF_RATE_PROVIDERS.has(effectiveProvider)) identifier += \"-ref\"\n }\n\n // MiniMax Hailuo 3 (768P lever, 2026-08-03): bare duration composites stay\n // the 2K (default) rate — byte-identical to the pre-lever seeded rows, so\n // existing workflows and admin overrides keep their ids — and only a\n // verified 768P selection appends \":768p\". normalizeMinimaxH3Resolution\n // collapses anything else to 2K, matching what KIE renders for an\n // omitted/unknown value, so billing can never undercut the render.\n if (isMinimaxH3Provider(effectiveProvider) && normalizeMinimaxH3Resolution(resolution) === \"768P\") {\n identifier += \":768p\"\n }\n\n return identifier\n}\n\n/**\n * The credit identifier a video GENERATION node is quoted at — Generate Video\n * (and the legacy Image/Text to Video nodes) and the Video to Video Seedance\n * edit lane, on every surface that quotes one: the node's cost pill, the\n * editor's run estimate, the prompt modal and the backend pre-run estimator.\n *\n * It applies the request levers the run applies BEFORE it prices\n * (payload-builder's `resolveVideoRequestNorm`): the model's UI resolution fill\n * when the node names none (`uiResolutionFill` — what the run sends), then the\n * catalog normalizer `normalizeVideoRequestParams`, which also owns the Seedance\n * Draft rule (a draft is priced AND sent at 480p whatever resolution came with\n * it). Without that, a node with no resolution was quoted at the identifier's\n * own default band (720p on Seedance 2.5) while the run sent and reserved 480p.\n *\n * `hasVideoRef` must come from the GRAPH (a wired reference-video edge, e.g.\n * `countRefModalityEdges(edges, id, \"video\") > 0`), never node data: nothing\n * writes `referenceVideoUrls` into a video node, so reading it there always\n * quoted the plain ladder for a run that reserves on the `-ref` one.\n */\nexport function videoGenerationCreditId(args: {\n provider: string\n duration?: number | string\n sound?: boolean\n nodeType?: \"image-to-video\" | \"text-to-video\"\n mode?: string\n resolution?: string\n draft?: boolean\n hasVideoRef?: boolean\n}): string {\n const { resolution } = normalizeVideoRequestParams(args.provider, {\n resolution: args.resolution ?? uiResolutionFill(args.provider),\n draft: args.draft === true,\n })\n return buildVideoCreditModelIdentifier(\n args.provider,\n args.duration,\n args.sound,\n args.nodeType ?? \"image-to-video\",\n args.mode,\n resolution,\n args.hasVideoRef === true,\n )\n}\n\n/**\n * The credit identifier a Video to Video node's Seedance EDIT lane reserves\n * under. Seedance has no v2v endpoint — the lane is a text-to-video job in edit\n * shape with the source clip as reference video 1 — so it prices on the\n * REFERENCE-VIDEO ladder at the model's LONGEST clip (Auto duration), and the\n * measured settlement refunds down to what was actually delivered.\n *\n * A thin call into {@link videoGenerationCreditId}, so a Generate Video node\n * making the same KIE call (Seedance, Auto, a wired reference video) is quoted\n * the same id. FOUR surfaces must agree on it exactly: the orchestrator's\n * reservation (payload-builder.ts), the backend pre-run estimator\n * (ee/billing/credits.ts), the node's cost pill, and the frontend run-level\n * estimate (config-panels/helpers.ts). A quote that disagrees with the reserve\n * is the documented `price_not_configured` / blank-pill trap.\n *\n * `resolution` is the node's one `v2vResolution` field; when unset the model's\n * own UI fill is priced, which is what the lane will send. `draft` is the\n * node's Seedance Draft toggle (priced at 480p).\n */\nexport function seedanceVideoEditCreditId(provider: string, resolution?: string, draft?: boolean): string {\n return videoGenerationCreditId({\n provider,\n duration: VIDEO_DURATION_AUTO,\n nodeType: \"text-to-video\",\n resolution,\n draft,\n hasVideoRef: true,\n })\n}\n\n/** What the video credit identifier PRICES for a request, for the levers whose\n * priced value must also be the value we SEND. */\nexport interface PricedVideoSelection {\n /** The resolution band the reservation is priced at when the request omitted\n * one — and only where the platform DECLARES that band as the provider's own\n * default. `undefined` means \"leave `resolution` exactly as the request had\n * it\": either the caller supplied one, or the provider's real default is not\n * known to be the band the identifier assumes. */\n resolution?: string\n /** The length the reservation is priced at and the wire carries, for a\n * provider whose price follows the clip length (LTX's seeded tier, the KIE\n * ladders, Gemini Omni). `undefined` for every other provider, and for Auto:\n * their duration passes through. */\n duration?: number\n /** Non-empty only for a lever the caller ASKED for and did not get (a 7s\n * request snapped to the 6s tier). Filling an omitted lever is a disclosure of\n * the price already being charged, not a correction, so it reports nothing. */\n adjustments: ModelInputAdjustment[]\n}\n\n/**\n * The other half of the video money path: `normalizeVideoRequestParams` snaps a\n * value the CATALOG governs; this returns the value the PRICE ladder governs.\n *\n * Two defects it closes, both of the same shape — the identifier prices one\n * thing and the wire carries another, and `commit_credits` (migration 176) only\n * ever refunds a surplus, so the reservation is the final charge:\n *\n * 1. **Absent resolution.** `buildVideoCreditModelIdentifier` prices an omitted\n * `resolution` as a concrete band (LTX → 1080p; a\n * {@link PRICING_DEFAULT_RESOLUTION} member → its declared default). Leaving\n * the key unset then lets the provider pick — documented for the KIE members\n * (their `extraParams` pin the same band) but UNDOCUMENTED for LTX on\n * Replicate. Sending the band we priced makes the two agree by construction.\n *\n * The fill is deliberately limited to providers with a DECLARED default.\n * `buildVideoCreditModelIdentifier` also has un-declared fallbacks — the\n * cheapest tier for a resolution-priced provider with no\n * `PRICING_DEFAULT_RESOLUTION` row — and those are a HEDGE, not a verified\n * provider default: seedance-2 / -fast / -mini pin `resolution: \"720p\"`\n * KIE-side while the identifier prices 480p, so filling 480p would downgrade\n * the render to match a price we already know is wrong. That mismatch is a\n * pre-existing identifier bug and is fixed by seeding the row, not here.\n *\n * 2. **Duration.** Every provider whose price follows the clip length is\n * charged at the length it RENDERS: its own default when the request named\n * none (catalog `defaultDuration`), the nearest length it offers otherwise\n * (`pricedOutputDurationSec` — the runners' own snap rule). The LTX ladder is\n * seeded per (band × seconds), so a 7s request snaps onto the 6s tier;\n * sending 7s would bill six and render seven. The same value is returned for\n * the other length-priced providers (the KIE ladders, Gemini Omni), so what\n * is priced is what is sent. Auto (-1) is the model's call and is untouched.\n *\n * Pure, and IDEMPOTENT against the identifier: feeding its output back in\n * cannot move the reserved tier. `video-request-normalize.test.ts` proves that\n * over every provider × resolution × duration.\n */\nexport function pricedVideoSelection(opts: {\n provider: string\n resolution?: string\n duration?: number | string\n}): PricedVideoSelection {\n const adjustments: ModelInputAdjustment[] = []\n const ltx = ltxPricedTier(opts.provider, opts.resolution, opts.duration)\n\n // The band the request will be priced AND rendered at. An explicit value\n // always wins — this only ever fills an omission.\n const resolution = opts.resolution\n ?? (ltx ? ltx.band : PRICING_DEFAULT_RESOLUTION[opts.provider])\n\n const requested = typeof opts.duration === \"string\" ? parseInt(opts.duration, 10) : opts.duration\n const asked = requested !== undefined && !Number.isNaN(requested)\n\n // Every provider whose price follows the clip length sends the length it is\n // CHARGED at (the catalog funnel: its own default when unset, the nearest\n // legal length otherwise). Auto (-1) is the model's call and is left alone.\n const lengthPriced = !!ltx || DURATION_PRICED_PROVIDERS.has(opts.provider) || isGeminiOmniProvider(opts.provider)\n if (!lengthPriced || (!ltx && asked && requested! <= 0)) return { resolution, adjustments }\n\n const duration = ltx ? ltx.duration : pricedOutputDurationSec(opts.provider, opts.duration)\n if (asked && requested !== duration) {\n adjustments.push({\n field: \"duration\",\n from: requested!,\n to: duration,\n reason: ltx\n ? `LTX renders ${ltx.band} in ${ltx.duration}s steps — using ${ltx.duration}s instead of ${requested}s.`\n : `${opts.provider} renders ${duration}s clips at the nearest length it offers — using ${duration}s instead of ${requested}s.`,\n })\n }\n return { resolution, duration, adjustments }\n}\n\n/**\n * Compute composite model identifier for motion control with duration-tiered pricing.\n * Examples: \"kling-3.0-motion:10s\", \"kling-3.0-motion:1080p:15s\", \"motion-transfer:5s\"\n *\n * Wan Animate providers use resolution-tiered pricing (not per-second):\n * \"wan-animate-move\" (480p default), \"wan-animate-move:580p\", \"wan-animate-move:720p\"\n *\n * @param provider - Motion control provider key (\"kling\" for 2.6, \"kling-3.0\", \"wan-animate-move\", \"wan-animate-replace\")\n * @param resolution - \"720p\" or \"1080p\" (Kling), \"480p\" or \"580p\" or \"720p\" (Wan Animate)\n * @param videoDuration - Reference video duration in seconds (defaults to 10s, unused for Wan Animate)\n */\nexport function buildMotionCreditModelIdentifier(\n provider: string,\n resolution: string,\n videoDuration?: number,\n): string {\n // Wan Animate providers use resolution-tiered pricing (not duration-based)\n if (provider === \"wan-animate-move\" || provider === \"wan-animate-replace\") {\n // 480p is the default (base identifier), 580p and 720p get composite suffix\n if (resolution === \"580p\" || resolution === \"720p\") {\n return `${provider}:${resolution}`\n }\n return provider\n }\n\n const raw = videoDuration ?? 10\n const durationSec = Math.floor(Number.isNaN(raw) ? 10 : raw) // default 10s; floor to match KIE per-second billing\n const tier = MOTION_DURATION_TIERS.find(t => durationSec <= t.maxSeconds)\n ?? MOTION_DURATION_TIERS[MOTION_DURATION_TIERS.length - 1]\n\n const base = provider === \"kling-3.0\" ? \"kling-3.0-motion\" : \"motion-transfer\"\n const resSuffix = resolution === \"1080p\" ? \":1080p\" : \"\"\n return `${base}${resSuffix}:${tier.suffix}`\n}\n\n/**\n * The Suno operations whose credit key depends on the model VERSION.\n *\n * `/v1/suno/generate`, `/cover` and `/extend` resolve their creditGuard\n * identifier through `sunoCreditType(model, <operation>)` (routes/suno.ts\n * :247-249, :335-337, :407-409). EVERY other Suno route charges a flat\n * per-operation key and ignores the version the node carries — mashup (:648),\n * add-instrumental (:852), add-vocals (:907), upload-extend (:1016),\n * replace-section (:710), style-boost (:771), convert-wav (:962),\n * lyrics (:482), music-video (:594), voice (:1218).\n *\n * Anything that QUOTES a Suno price — a dropdown row, a node badge, the\n * workflow-credit estimator — must follow the same split, or it displays a\n * credit key the route never charges.\n */\nexport const SUNO_VERSION_PRICED_OPERATIONS = [\n \"suno-generate\",\n \"suno-cover\",\n \"suno-extend\",\n] as const\n\n/**\n * The seven Suno operations that appear behind a select/dropdown UI (model\n * pickers, node badges, the credit estimator) — the three version-priced\n * operations above, plus the four flat-key operations exercised by\n * `sunoCreditType`'s own test suite. A readonly tuple so later tasks (the\n * model dropdowns, node badges) can iterate or count it without redeclaring\n * the list and drifting from this one.\n */\nexport const SUNO_SELECT_OPERATIONS = [\n \"suno-generate\",\n \"suno-cover\",\n \"suno-extend\",\n \"suno-mashup\",\n \"suno-add-instrumental\",\n \"suno-add-vocals\",\n \"suno-upload-extend\",\n] as const\n\n/**\n * Adjust Speed's price id: motion-compensated (\"smooth\") interpolation is its\n * own, dearer tier. The route, the workflow run, and the editor's badge and\n * run estimate all price through this, so none of them can quote the fast tier\n * for a smooth run.\n */\nexport function speedRampCreditId(quality: unknown): \"speed-ramp\" | \"speed-ramp:smooth\" {\n return quality === \"smooth\" ? \"speed-ramp:smooth\" : \"speed-ramp\"\n}\n\n/**\n * Apply EDL's price id: a `proxy` render (the 720p preview) is its own,\n * cheaper per-output-minute row; a `final` render keeps the bare id. One id per\n * QUALITY, for a video and an audio output alike (decided 2026-10-04). Anything\n * that is not exactly \"proxy\" is the final, as the route and the node default\n * it. The route, the workflow run, and the editor's badge and run estimate all\n * price through this; the job itself is always named `apply-edl`.\n */\nexport function applyEdlCreditId(quality: unknown): \"apply-edl\" | \"apply-edl:proxy\" {\n return quality === \"proxy\" ? \"apply-edl:proxy\" : \"apply-edl\"\n}\n\n/**\n * Speaker View's price tiers (decided 2026-10-10, C4): a render is priced by\n * how many speakers it composites at once. `standard` — at most two tiles on\n * any segment and no zoom; `complex` — three to six tiles, or any zoom. Which\n * tier a render is in is the render rule's to say (the app's\n * `@nodaro/render-rules`), never this vocabulary's.\n */\nexport const SPEAKER_VIEW_PRICE_TIERS = [\"standard\", \"complex\"] as const\nexport type SpeakerViewPriceTier = (typeof SPEAKER_VIEW_PRICE_TIERS)[number]\n\nexport type SpeakerViewCreditId = \"speaker-view\" | \"speaker-view:proxy\" | \"speaker-view:complex\" | \"speaker-view:complex:proxy\"\n\n/** Every id `speakerViewCreditId` can name. */\nexport const SPEAKER_VIEW_CREDIT_IDS: readonly SpeakerViewCreditId[] = Object.freeze([\n \"speaker-view\",\n \"speaker-view:proxy\",\n \"speaker-view:complex\",\n \"speaker-view:complex:proxy\",\n] as const)\n\n/**\n * The credit id of a Speaker View render (F4, decided 2026-09-23; tiers\n * decided 2026-10-10): a Preview (`quality` \"proxy\") reserves on its own row,\n * anything else on the final's, and each in its price tier — `standard` on\n * `speaker-view` / `speaker-view:proxy`, `complex` on `speaker-view:complex` /\n * `speaker-view:complex:proxy`. A tier that is not exactly `standard` (absent\n * included) names the `complex` row: a caller that cannot tell quotes high,\n * never low. The job is always named `speaker-view`; only its credit id\n * follows the quality and the tier.\n */\nexport function speakerViewCreditId(quality: unknown, tier?: unknown): SpeakerViewCreditId {\n const proxy = quality === \"proxy\"\n if (tier === \"standard\") return proxy ? \"speaker-view:proxy\" : \"speaker-view\"\n return proxy ? \"speaker-view:complex:proxy\" : \"speaker-view:complex\"\n}\n\n/**\n * OUR Nodaro credit key for a Suno operation, given the model version and the\n * operation (which is also the node type and the BullMQ job name).\n *\n * This is the single source of truth for the Suno pricing contract, shared by\n * the reservation path (routes/suno.ts creditGuard), the egress seam\n * (workers/handlers/suno.ts `modelKey`, which must match what was reserved),\n * both workflow-credit estimators (ee/billing/credits.ts and the frontend\n * config-panels/helpers.ts), the seven Suno model dropdowns and the three Suno\n * node badges. It is a billing key — NEVER a KIE provider id — which is what\n * satisfies the B3 egress invariant.\n *\n * The version → key map is {@link SUNO_VERSION_CREDIT_KEYS}; a version with no\n * entry (V4 / V4_5 / V4_5ALL / V4_5PLUS) falls back to the operation key, and a\n * non-version-priced operation is returned unchanged.\n */\nexport function sunoCreditType(model: string | undefined, operation: string): string {\n if (!(SUNO_VERSION_PRICED_OPERATIONS as readonly string[]).includes(operation)) {\n return operation\n }\n return (model && SUNO_VERSION_CREDIT_KEYS[model]) || operation\n}\n\n/**\n * Suno version → Nodaro credit key for the version-priced operations. One row\n * per version that has its own `model_pricing` row / `STATIC_CREDIT_COSTS`\n * entry / `MODEL_CATALOG` pricing row, so an admin can reprice one version\n * without touching code. Every ACTIVE version MUST have a row here — guarded\n * by `__tests__/suno-credit-type.test.ts` (a new active version with no key\n * would silently bill at the operation key).\n */\nexport const SUNO_VERSION_CREDIT_KEYS: Readonly<Record<string, string>> = {\n V6: \"suno-v6\",\n V6_WILD: \"suno-v6_wild\",\n V6_MINI: \"suno-v6_mini\",\n V5_5: \"suno-v5_5\",\n V5: \"suno-v5\",\n}\n"]}
@@ -1,27 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkBOUEGYGI_cjs = require('./chunk-BOUEGYGI.cjs');
4
- var chunkADYPAGQF_cjs = require('./chunk-ADYPAGQF.cjs');
5
-
6
- // src/video-ui-defaults.ts
7
- function uiAspectRatioFill(provider) {
8
- if (chunkBOUEGYGI_cjs.isSeedance2Provider(provider) || chunkBOUEGYGI_cjs.isMinimaxH3Provider(provider) || chunkBOUEGYGI_cjs.isWan3Provider(provider)) return "adaptive";
9
- if (chunkBOUEGYGI_cjs.isKling4Provider(provider)) return "auto";
10
- return void 0;
11
- }
12
- function uiResolutionFill(provider) {
13
- if (chunkBOUEGYGI_cjs.isWan3Provider(provider) || chunkBOUEGYGI_cjs.isViduQ4Provider(provider) || chunkBOUEGYGI_cjs.isKling4Provider(provider)) return chunkBOUEGYGI_cjs.PRICING_DEFAULT_RESOLUTION[provider];
14
- if (chunkBOUEGYGI_cjs.isSeedance2Provider(provider)) return chunkADYPAGQF_cjs.MODEL_CATALOG[provider]?.resolutions?.[0];
15
- return void 0;
16
- }
17
- function uiDurationFill(provider) {
18
- if (chunkBOUEGYGI_cjs.isWan3Provider(provider) || chunkBOUEGYGI_cjs.isViduQ4Provider(provider) || chunkBOUEGYGI_cjs.isKling4Provider(provider)) return 5;
19
- if (chunkBOUEGYGI_cjs.isGeminiOmniProvider(provider)) return 8;
20
- return void 0;
21
- }
22
-
23
- exports.uiAspectRatioFill = uiAspectRatioFill;
24
- exports.uiDurationFill = uiDurationFill;
25
- exports.uiResolutionFill = uiResolutionFill;
26
- //# sourceMappingURL=chunk-XOZIHGR5.cjs.map
27
- //# sourceMappingURL=chunk-XOZIHGR5.cjs.map