@nodaro/shared 3.40.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 (154) 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-25PAKSMK.cjs → chunk-4URFSG3O.cjs} +57 -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-NRSYWQKM.js → chunk-L6G6G5BB.js} +17 -6
  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-GLON7ANZ.cjs → chunk-P4QT7JGD.cjs} +7 -2
  58. package/dist/chunk-P4QT7JGD.cjs.map +1 -0
  59. package/dist/{chunk-YX5FW7ON.js → chunk-PLU7RIDO.js} +4 -12
  60. package/dist/chunk-PLU7RIDO.js.map +1 -0
  61. package/dist/{chunk-A4NDZBSJ.js → chunk-PVAOXI2W.js} +14 -20
  62. package/dist/chunk-PVAOXI2W.js.map +1 -0
  63. package/dist/{chunk-GXTWKAJF.js → chunk-PZE6WTA3.js} +3 -3
  64. package/dist/{chunk-GXTWKAJF.js.map → chunk-PZE6WTA3.js.map} +1 -1
  65. package/dist/{chunk-TGZJXCLL.cjs → chunk-QHODM5TS.cjs} +46 -6
  66. package/dist/chunk-QHODM5TS.cjs.map +1 -0
  67. package/dist/{chunk-JN3V33AN.cjs → chunk-QJ2VGB5J.cjs} +6 -6
  68. package/dist/{chunk-JN3V33AN.cjs.map → chunk-QJ2VGB5J.cjs.map} +1 -1
  69. package/dist/{chunk-ADYPAGQF.cjs → chunk-RPQ2KF6L.cjs} +5 -24
  70. package/dist/chunk-RPQ2KF6L.cjs.map +1 -0
  71. package/dist/{chunk-2BJADMEX.js → chunk-S4UAYQQV.js} +3 -3
  72. package/dist/{chunk-2BJADMEX.js.map → chunk-S4UAYQQV.js.map} +1 -1
  73. package/dist/{chunk-R6B2UDFR.js → chunk-T4EBNTKT.js} +7 -2
  74. package/dist/chunk-T4EBNTKT.js.map +1 -0
  75. package/dist/{chunk-FVZMFDRO.js → chunk-TTD6MZAM.js} +4 -4
  76. package/dist/{chunk-FVZMFDRO.js.map → chunk-TTD6MZAM.js.map} +1 -1
  77. package/dist/entries/apps.cjs +42 -42
  78. package/dist/entries/apps.js +7 -7
  79. package/dist/entries/credits.cjs +150 -150
  80. package/dist/entries/credits.d.cts +1 -1
  81. package/dist/entries/credits.d.ts +1 -1
  82. package/dist/entries/credits.js +7 -7
  83. package/dist/entries/llm-models.d.cts +1 -1
  84. package/dist/entries/llm-models.d.ts +1 -1
  85. package/dist/entries/media.cjs +56 -48
  86. package/dist/entries/media.d.cts +65 -3
  87. package/dist/entries/media.d.ts +65 -3
  88. package/dist/entries/media.js +1 -1
  89. package/dist/entries/model-catalog.cjs +66 -66
  90. package/dist/entries/model-catalog.js +4 -4
  91. package/dist/entries/models.cjs +273 -237
  92. package/dist/entries/models.d.cts +38 -8
  93. package/dist/entries/models.d.ts +38 -8
  94. package/dist/entries/models.js +4 -4
  95. package/dist/entries/nodes.cjs +206 -206
  96. package/dist/entries/nodes.js +8 -8
  97. package/dist/entries/pipeline.cjs +149 -149
  98. package/dist/entries/pipeline.d.cts +10 -14
  99. package/dist/entries/pipeline.d.ts +10 -14
  100. package/dist/entries/pipeline.js +3 -3
  101. package/dist/entries/types.d.cts +8 -0
  102. package/dist/entries/types.d.ts +8 -0
  103. package/dist/entries/ugc.cjs +71 -71
  104. package/dist/entries/ugc.js +4 -4
  105. package/dist/entries/video.cjs +117 -117
  106. package/dist/entries/video.js +4 -4
  107. package/dist/entries/workflow.cjs +98 -98
  108. package/dist/entries/workflow.js +1 -1
  109. package/dist/index.cjs +1204 -1160
  110. package/dist/index.d.cts +3 -3
  111. package/dist/index.d.ts +3 -3
  112. package/dist/index.js +19 -19
  113. package/dist/{model-constants-B5ka4TQr.d.cts → model-constants-BL-Ae0OU.d.cts} +24 -7
  114. package/dist/{model-constants-B5ka4TQr.d.ts → model-constants-BL-Ae0OU.d.ts} +24 -7
  115. package/package.json +1 -1
  116. package/src/__tests__/cast-swap-limits.test.ts +27 -0
  117. package/src/__tests__/credit-identifiers.test.ts +13 -32
  118. package/src/__tests__/pricing-default-duration.test.ts +0 -2
  119. package/src/__tests__/retired-video-provider.test.ts +42 -0
  120. package/src/__tests__/video-audio-capability.test.ts +4 -13
  121. package/src/__tests__/video-mask.test.ts +31 -0
  122. package/src/__tests__/video-mode-aliases.test.ts +10 -1
  123. package/src/__tests__/workflow-export-strip.test.ts +14 -0
  124. package/src/cast-swap-limits.ts +46 -0
  125. package/src/catalog-projection.ts +8 -0
  126. package/src/credit-identifiers.ts +4 -1
  127. package/src/entries/models.ts +10 -0
  128. package/src/film-pricing.ts +0 -1
  129. package/src/model-catalog.ts +3 -22
  130. package/src/model-constants.ts +29 -15
  131. package/src/pipeline-types.ts +4 -2
  132. package/src/provider-directive-defaults.ts +0 -1
  133. package/src/video-mask.ts +69 -2
  134. package/src/video-output-canvas.ts +0 -8
  135. package/src/workflow-export.ts +7 -0
  136. package/dist/chunk-25PAKSMK.cjs.map +0 -1
  137. package/dist/chunk-5CKTBGB6.js.map +0 -1
  138. package/dist/chunk-5J5L26IZ.js.map +0 -1
  139. package/dist/chunk-A4NDZBSJ.js.map +0 -1
  140. package/dist/chunk-ADYPAGQF.cjs.map +0 -1
  141. package/dist/chunk-BOUEGYGI.cjs.map +0 -1
  142. package/dist/chunk-DJIRIBKX.cjs.map +0 -1
  143. package/dist/chunk-GLON7ANZ.cjs.map +0 -1
  144. package/dist/chunk-LOTL72UI.js.map +0 -1
  145. package/dist/chunk-LOWOJN65.js.map +0 -1
  146. package/dist/chunk-NRSYWQKM.js.map +0 -1
  147. package/dist/chunk-R6B2UDFR.js.map +0 -1
  148. package/dist/chunk-SYUY7GNT.js.map +0 -1
  149. package/dist/chunk-TGZJXCLL.cjs.map +0 -1
  150. package/dist/chunk-VNC5DNIQ.cjs.map +0 -1
  151. package/dist/chunk-VSDJCJKP.cjs.map +0 -1
  152. package/dist/chunk-XOZIHGR5.cjs +0 -27
  153. package/dist/chunk-YX5FW7ON.js.map +0 -1
  154. package/dist/chunk-ZAOBNW6Y.cjs.map +0 -1
@@ -1,9 +1,9 @@
1
1
  import { unitQuoteCreditId } from './chunk-M7G66F6H.js';
2
2
  import { overlayPlatformById } from './chunk-5THUHJ3E.js';
3
- import { canonicalTtsProvider, findTtsCapabilities } from './chunk-ZXIP5T5V.js';
4
- import { findDialogueCapabilities } from './chunk-GNY2S63W.js';
3
+ import { canonicalTtsProvider, findTtsCapabilities } from './chunk-4GYMWGUG.js';
4
+ import { findDialogueCapabilities } from './chunk-N5NT3WZD.js';
5
5
  import { getLlmModel, LLM_FEATURE_DEFAULTS, buildLlmCreditIdentifier } from './chunk-2BHOAYZW.js';
6
- import { CREDIT_BASE_USD, DEFAULT_TEXT_TO_AUDIO_PROVIDER } from './chunk-A4NDZBSJ.js';
6
+ import { CREDIT_BASE_USD, DEFAULT_TEXT_TO_AUDIO_PROVIDER } from './chunk-PVAOXI2W.js';
7
7
 
8
8
  // src/credit-conversion.ts
9
9
  var CREDIT_ROUNDING_RESOLUTION = 1e3;
@@ -31,8 +31,6 @@ var VIDEO_CLIP_CREDITS = {
31
31
  "kling": { credits: 14, clipSeconds: 5 },
32
32
  // kling:5s
33
33
  "kling-3.0": { credits: 31, clipSeconds: 5 },
34
- "seedance": { credits: 7, clipSeconds: 8 },
35
- // seedance:8s
36
34
  "seedance-2": { credits: 50, clipSeconds: 8 },
37
35
  // seedance-2:8s:720p-ref
38
36
  "seedance-2-fast": { credits: 40, clipSeconds: 8 },
@@ -903,5 +901,5 @@ var CONTENT_RECIPE_IDEAS_CREDIT_IDS = [
903
901
  ];
904
902
 
905
903
  export { AI_AVATAR_DURATION_BUCKETS, AI_AVATAR_MAX_AUDIO_SEC, AI_AVATAR_MAX_DURATION_SEC, AI_AVATAR_RESERVE_IDS, AvatarPayloadError, CINEMATIC_DEFAULT_DURATION_SEC, CINEMATIC_DEFAULT_RESOLUTION, CINEMATIC_MAX_DURATION_SEC, CINEMATIC_MAX_LOOKS, CINEMATIC_MAX_REFERENCE_IMAGES, CINEMATIC_MAX_REFERENCE_VIDEOS, CINEMATIC_MIN_DURATION_SEC, CINEMATIC_MIN_LOOKS, CINEMATIC_PROMPT_MAX, CINEMATIC_RESERVE_IDS, CONTENT_IDEAS_BRAND_MAX, CONTENT_IDEAS_DEFAULT_COUNT, CONTENT_IDEAS_LANGUAGE_MAX, CONTENT_IDEAS_MAX_COUNT, CONTENT_IDEAS_MAX_RECIPE_INPUTS, CONTENT_IDEAS_PER_CHARGE, CONTENT_RECIPE_IDEAS_CREDIT_IDS, CONTENT_RECIPE_SOURCE_MAX, CREDIT_ROUNDING_RESOLUTION, DEFAULT_VIDEO_CLIP_COST, FILM_BASE_CREDITS, IMAGE_OVERLAY_BASE_CREDITS, IMAGE_OVERLAY_VARIANT_CREDITS, KEYFRAME_CREDITS_PER_SHOT, LIP_SYNC_DURATION_BUCKETS, LIP_SYNC_MAX_AUDIO_SECONDS, LTX_EXTEND_DURATION, LTX_EXTEND_PER_SECOND_CREDIT_ID, LTX_RETAKE_MIN_DURATION_SEC, LTX_RETAKE_PER_SECOND_CREDIT_ID, PAYG_RETENTION_DAYS, PITCH_TEMPO_LIMITS, PITCH_TEMPO_PRICING, SPEECH_FLOOR_UNITS, SPEECH_PRICE_UNIT_CHARS, SPEECH_UNIT_CREDIT_SUFFIX, SWITCHX_BLOCK_FRAMES, SWITCHX_FRAME_TIERS, TEXT_TO_AUDIO_PRICING, TEXT_TO_AUDIO_SFX_CREDIT_IDS, TOPAZ_DEFAULT_UPSCALE_FACTOR, TOPAZ_UPSCALE_FACTORS, VIDEO_ANALYSIS_BUCKET_CREDITS, VIDEO_ANALYSIS_BUCKET_GRACE_SEC, VIDEO_ANALYSIS_DURATION_BUCKETS, VIDEO_ANALYSIS_DURATION_TOLERANCE_SEC, VIDEO_ANALYSIS_MAX_DURATION_SEC, VIDEO_ANALYSIS_WINDOW, VIDEO_AUDIT_BUCKET_CREDITS, VIDEO_CLIP_CREDITS, VIDEO_CRITIC_CREDITS_PER_SHOT, VIDEO_SFX_PRICING, VIDEO_UTIL_PRICING, VOICE_CHANGER_PRO_QUOTE_RATE_ID, aiAvatarReserveCreditId, assembleNarratedVideoCredits, bucketSecondsFromAuditCreditId, bucketSecondsFromCreditId, buildLipSyncCreditId, buildVideoAnalysisCreditId, buildVideoAuditCreditId, calculateMonetizationMarkup, calculateMonetizedCost, cinematicCreditId, clampCinematicDuration, clampContentIdeasCount, contentIdeasCreditFeature, contentIdeasCreditId, contentRecipeCreditId, creditsToUsd, effectiveContentModel, estimateCombineVideosCredits, estimateFilmCredits, estimateLoopTrimAddonCredits, estimateLoopVideoCredits, estimateScriptDurationSec, estimateTrimVideoCredits, getLipSyncMaxAudioSeconds, imageOverlayBillableVariants, imageOverlayCredits, isPaygRetentionActive, isPerSecondLipSyncProvider, isSpeechLengthPriceId, ltxExtendDurationSec, ltxRetakeDurationSec, parsePitchTempoCreditId, parseSpeechQuoteCreditId, parseVoiceChangerProQuoteCreditId, pickAiAvatarBucket, pickLipSyncBucket, pickSwitchXFrameTier, pickVideoAnalysisBucket, pitchTempoBaseCredits, pitchTempoCreditId, pitchTempoQuoteCreditId, pitchTempoStartedMinutes, resolveAiAvatarCreditId, resolveCinematicCreditId, resolveEffectiveTier, resolveStoredTier, resolveSwitchXCreditId, resolveTopazUpscale, semitonesToPitchRatio, speechCredits, speechLengthPriceModel, speechPriceUnits, speechQuoteCreditId, speechUnitCreditId, textToAudioBilledSeconds, textToAudioCreditId, usdToCredits, validateAiAvatarPayload, validateCinematicAvatarPayload, videoAnalysisCreditSegment, videoAnalysisNumWindows, videoAuditCreditsForBucket, videoSfxCreditId, videoSfxQuoteCreditId, voiceChangerProQuoteCreditId };
906
- //# sourceMappingURL=chunk-5J5L26IZ.js.map
907
- //# sourceMappingURL=chunk-5J5L26IZ.js.map
904
+ //# sourceMappingURL=chunk-IAH67SHO.js.map
905
+ //# sourceMappingURL=chunk-IAH67SHO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/credit-conversion.ts","../src/film-pricing.ts","../src/credit-estimators/video-utils.ts","../src/credit-estimators/image-overlay.ts","../src/credit-estimators/video-sfx.ts","../src/credit-estimators/text-to-audio.ts","../src/credit-estimators/ltx-extend.ts","../src/credit-estimators/ltx-retake.ts","../src/credit-estimators/speech.ts","../src/credit-estimators/voice-changer-pro-quote.ts","../src/credit-estimators/pitch-tempo.ts","../src/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":["known","output","ALLOWED_RESOLUTIONS"],"mappings":";;;;;;;;AAoBO,IAAM,0BAAA,GAA6B;AAE1C,SAAS,gBAAgB,GAAA,EAAmB;AAC1C,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,QAAS,IAAI,KAAA,CAAM,CAAA,uCAAA,EAA0C,GAAG,CAAA,CAAE,CAAA;AAC1F,EAAA,IAAI,MAAM,CAAA,EAAG,MAAM,IAAI,KAAA,CAAM,CAAA,6CAAA,EAAgD,GAAG,CAAA,CAAE,CAAA;AACpF;AAGO,SAAS,aAAa,GAAA,EAAqB;AAChD,EAAA,eAAA,CAAgB,GAAG,CAAA;AAC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AAK,CAAC,CAAA;AAAA,IACvD,qBAAA,CAAsB,iBAAiB,QAAQ,CAAA;AAAA,IAC/C;AAAA,GACF;AACF;AAGO,IAAM,+BAAA,GAAkC;AAAA,EAC7C,wBAAA;AAAA,EACA,gBAAA;AAAA,EACA,wBAAA;AAAA,EACA,+BAAA;AAAA,EACA,uBAAA;AAAA,EACA,eAAA;AAAA,EACA,uBAAA;AAAA,EACA,8BAAA;AAAA,EACA,0BAAA;AAAA,EACA,kBAAA;AAAA,EACA,0BAAA;AAAA,EACA;AACF","file":"chunk-IAH67SHO.js","sourcesContent":["/**\n * The ONLY place credit⇄USD arithmetic is written.\n *\n * Every credit figure derives from {@link CREDIT_BASE_USD}. Dividing by a\n * hardcoded copy of that number instead makes the base impossible to change\n * without a multi-file hunt, so route conversions through here.\n *\n * MILLI-CREDIT GUARD — do not remove. `usd / base` is IEEE-754 division and\n * lands a hair above an integer for many exact-multiple inputs\n * (0.14 / 0.02 = 7.000000000000001), so a bare `Math.ceil` rounds up a whole\n * credit that was not owed. Rounding to milli-credits first absorbs that noise\n * at 1000x finer resolution than any credit-level decision.\n *\n * The guard matters at every base, not just the current one — a finer base does\n * not make it unnecessary, it only moves which inputs trip it. Do not\n * \"simplify\" it away if {@link CREDIT_BASE_USD} ever changes.\n */\nimport { CREDIT_BASE_USD } from \"./model-constants.js\"\n\n/** Milli-credits per credit — the intermediate rounding resolution. */\nexport const CREDIT_ROUNDING_RESOLUTION = 1000\n\nfunction assertUsableUsd(usd: number): void {\n if (!Number.isFinite(usd)) throw new Error(`usdToCredits: cost must be finite, got ${usd}`)\n if (usd < 0) throw new Error(`usdToCredits: cost must not be negative, got ${usd}`)\n}\n\n/** A USD amount → whole credits at the current base. Rounds up. */\nexport function usdToCredits(usd: number): number {\n assertUsableUsd(usd)\n const milliCredits = Math.round((usd / CREDIT_BASE_USD) * CREDIT_ROUNDING_RESOLUTION)\n return Math.ceil(milliCredits / CREDIT_ROUNDING_RESOLUTION)\n}\n\n/** Whole credits → their USD value at the current base. Display/reporting only. */\nexport function creditsToUsd(credits: number): number {\n if (!Number.isFinite(credits)) throw new Error(`creditsToUsd: credits must be finite, got ${credits}`)\n return credits * CREDIT_BASE_USD\n}\n","/**\n * Film cost ESTIMATION for the studio preview.\n *\n * This is display guidance only — it produces an approximate \"this film will\n * cost ≈ N credits\" number so the user can see cost before committing to a\n * length + model. The ACTUAL charge is still computed at generation time from\n * `STATIC_CREDIT_COSTS` / the `model_pricing` table per job; this module never\n * bills.\n *\n * Numbers are grounded in the KIE-calibrated per-clip credit costs in\n * `backend/src/ee/billing/credits.ts` (each entry there is annotated with its\n * KIE-credit + USD source). A backend test cross-checks `VIDEO_CLIP_CREDITS`\n * against that source so the estimate can't silently drift from reality.\n *\n * Cost structure of a Story→Video film:\n * total = BASE (duration-independent planning + assembly)\n * + perShot × shotCount (the variable, model-driven bulk)\n * where a shot = one keyframe image + one video clip + one video-critic pass,\n * and shotCount ≈ ceil(duration / clipSeconds) for the chosen model.\n */\n\n/**\n * Duration-independent overhead, in credits:\n * script/showrunner LLM chain ~30 · music timeline 4 · editor LLM 3 ·\n * final merge 3 · storyboard-cohesion critic 5 ≈ 45.\n * Mirrors the fixed line items in `estimateUpfrontCredits`\n * (backend/src/ee/pipelines/credits.ts).\n */\nexport const FILM_BASE_CREDITS = 45\n\n/** Per-shot keyframe image (nano-banana class) — see STATIC_CREDIT_COSTS. */\nexport const KEYFRAME_CREDITS_PER_SHOT = 2\n/** Per-shot Video Critic pass (first_last frame mode) — see credits.ts. */\nexport const VIDEO_CRITIC_CREDITS_PER_SHOT = 2\n\nexport interface VideoClipCost {\n /** Representative per-clip credit cost at the studio's default config\n * (720p; for the Seedance 2 family this is the ref-image variant the\n * studio uses for identity). Sourced from STATIC_CREDIT_COSTS. */\n readonly credits: number\n /** Representative clip length in seconds for shot-count estimation. */\n readonly clipSeconds: number\n}\n\n/**\n * Representative per-clip credit cost for each user-pinnable video model.\n * Values are the KIE-calibrated credits from STATIC_CREDIT_COSTS at the\n * studio's typical settings (720p; Seedance 2 = 8s 720p +ref). Keep in sync\n * with that table — the backend cross-check test guards drift.\n */\nexport const VIDEO_CLIP_CREDITS: Record<string, VideoClipCost> = {\n \"kling-turbo\": { credits: 11, clipSeconds: 5 }, // kling-turbo:5s\n \"kling\": { credits: 14, clipSeconds: 5 }, // kling:5s\n \"kling-3.0\": { credits: 31, clipSeconds: 5 },\n \"seedance-2\": { credits: 50, clipSeconds: 8 }, // seedance-2:8s:720p-ref\n \"seedance-2-fast\": { credits: 40, clipSeconds: 8 }, // seedance-2-fast:8s:720p-ref\n \"seedance-2-mini\": { credits: 25, clipSeconds: 8 }, // seedance-2-mini:8s:720p-ref\n \"seedance-2-5\": { credits: 76, clipSeconds: 8 }, // seedance-2-5:8s:720p-ref\n \"veo3\": { credits: 79, clipSeconds: 8 }, // flat per generation (VEO 3.1 Quality)\n \"veo3.1\": { credits: 19, clipSeconds: 6 }, // veo3.1 @ 720p\n \"veo3_lite\": { credits: 10, clipSeconds: 6 }, // veo3_lite @ 720p\n \"minimax\": { credits: 18, clipSeconds: 6 }, // fixed ~6s\n \"hailuo-standard\": { credits: 8, clipSeconds: 6 }, // hailuo-standard:6s\n \"wan-turbo\": { credits: 13, clipSeconds: 5 }, // 5s 480p\n \"bytedance-lite\": { credits: 6, clipSeconds: 5 },\n \"bytedance-pro\": { credits: 18, clipSeconds: 5 },\n}\n\n/**\n * Fallback when no model is pinned (Auto — the Scene Director picks per scene)\n * or the model isn't in the table. kling-turbo is the cheap, common default\n * the engine gravitates to, so it's a reasonable \"≈\" anchor.\n */\nexport const DEFAULT_VIDEO_CLIP_COST: VideoClipCost = VIDEO_CLIP_CREDITS[\"kling-turbo\"]!\n\nexport interface FilmCreditEstimate {\n /** Total estimated credits for the whole film. */\n readonly totalCredits: number\n /** Fixed base portion (planning + assembly). */\n readonly baseCredits: number\n /** Variable portion (shots × per-shot). */\n readonly variableCredits: number\n /** Estimated number of shots (clips) generated. */\n readonly shotCount: number\n /** Average credits per second of film (totalCredits / duration). */\n readonly creditsPerSecond: number\n /** Whether a known model drove the estimate (false = Auto/fallback). */\n readonly modelKnown: boolean\n}\n\n/**\n * Estimate the credit cost of a Story→Video film of `durationSeconds` rendered\n * with `videoModel`. Approximate, for the studio's cost preview only.\n */\nexport function estimateFilmCredits(\n durationSeconds: number,\n videoModel?: string,\n): FilmCreditEstimate {\n const seconds = Math.max(1, Math.round(durationSeconds))\n const known = !!videoModel && videoModel in VIDEO_CLIP_CREDITS\n const clip = known ? VIDEO_CLIP_CREDITS[videoModel!]! : DEFAULT_VIDEO_CLIP_COST\n\n const shotCount = Math.max(1, Math.ceil(seconds / clip.clipSeconds))\n const perShot =\n clip.credits + KEYFRAME_CREDITS_PER_SHOT + VIDEO_CRITIC_CREDITS_PER_SHOT\n const variableCredits = shotCount * perShot\n const totalCredits = FILM_BASE_CREDITS + variableCredits\n\n return {\n totalCredits,\n baseCredits: FILM_BASE_CREDITS,\n variableCredits,\n shotCount,\n creditsPerSecond: Math.round((totalCredits / seconds) * 10) / 10,\n modelKnown: known,\n }\n}\n","/**\n * Pure credit estimators for video-utility nodes (loop-video, trim-video,\n * combine-videos, assemble-narrated-video). Used by frontend (Run-button\n * display + API call) AND backend (creditGuard reservation, the workflow\n * run's reservation, the workflow estimate) so the displayed cost equals\n * what gets debited.\n *\n * Every estimate counts pricing UNITS and returns units × CREDIT_UNIT base\n * credits: a unit is 5 seconds of output, ~24 frames a smart loop cut\n * searches, each combine input beyond two, and each step of Assemble Narrated\n * Video (3 + 1 per 6 blocks).\n */\n\nexport const VIDEO_UTIL_PRICING = {\n /** Base credits per pricing unit. The node's own `model_pricing` row is one unit. */\n CREDIT_UNIT: 10,\n /** Base credits per 5 seconds of output (one unit), ceiling. */\n CREDITS_PER_5_SEC: 10,\n /** Smart-loop-cut work scales at one unit per ~24 frames searched. */\n FRAMES_PER_CREDIT: 24,\n /** Used when an upstream node hasn't produced a measurable duration yet. */\n FALLBACK_DURATION_SECONDS: 8,\n} as const\n\n/** Base credits for a count of pricing units, never below one unit. */\nfunction unitsToCredits(units: number): number {\n return VIDEO_UTIL_PRICING.CREDIT_UNIT * Math.max(1, units)\n}\n\nexport interface LoopVideoEstimatorInput {\n mode?: \"repeat\" | \"duration\"\n repeatCount?: number\n targetDuration?: number\n smartLoopCutBeforeRepeat?: boolean\n smartLoopCutLookback?: number\n}\n\nexport interface TrimVideoEstimatorInput {\n trimMode?: \"time\" | \"seconds\" | \"keep-first-seconds\" | \"keep-last-seconds\" | \"frames\" | \"smart-loop-cut\"\n startTime?: number\n endTime?: number\n /** Seconds-mirror of frames mode: trim N seconds from start AND/OR end. */\n trimStartSeconds?: number\n trimEndSeconds?: number\n /** Keep only the first/last N seconds (probes duration at runtime). */\n keepFirstSeconds?: number\n keepLastSeconds?: number\n trimStartFrames?: number\n trimEndFrames?: number\n smartLoopCutLookback?: number\n}\n\nexport interface CombineVideosEstimatorInput {\n /** Any id from `COMBINE_TRANSITIONS`. The estimator only branches on\n * `cut` vs non-cut, so accepting the full string keeps the catalog as\n * the single source of truth. */\n transition?: string\n transitionDuration?: number\n trimStartFrames?: number\n trimEndFrames?: number\n}\n\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,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkADYPAGQF_cjs = require('./chunk-ADYPAGQF.cjs');
3
+ var chunkRPQ2KF6L_cjs = require('./chunk-RPQ2KF6L.cjs');
4
4
 
5
5
  // src/image-model-roles.ts
6
6
  var IMAGE_MODEL_ROLE_DEFAULTS = {
@@ -17,7 +17,7 @@ var IMAGE_MODEL_RATIO_FALLBACKS = {
17
17
  };
18
18
  function imageModelDrawsRatio(modelId, aspectRatio) {
19
19
  if (!aspectRatio) return true;
20
- const ratios = chunkADYPAGQF_cjs.MODEL_CATALOG[modelId]?.aspectRatios;
20
+ const ratios = chunkRPQ2KF6L_cjs.MODEL_CATALOG[modelId]?.aspectRatios;
21
21
  return ratios === void 0 || ratios.includes(aspectRatio);
22
22
  }
23
23
  function defaultImageModel(role, aspectRatio) {
@@ -30,5 +30,5 @@ exports.IMAGE_MODEL_RATIO_FALLBACKS = IMAGE_MODEL_RATIO_FALLBACKS;
30
30
  exports.IMAGE_MODEL_ROLE_DEFAULTS = IMAGE_MODEL_ROLE_DEFAULTS;
31
31
  exports.defaultImageModel = defaultImageModel;
32
32
  exports.imageModelDrawsRatio = imageModelDrawsRatio;
33
- //# sourceMappingURL=chunk-YEET2QGF.cjs.map
34
- //# sourceMappingURL=chunk-YEET2QGF.cjs.map
33
+ //# sourceMappingURL=chunk-IHPDWGBN.cjs.map
34
+ //# sourceMappingURL=chunk-IHPDWGBN.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/image-model-roles.ts"],"names":["MODEL_CATALOG"],"mappings":";;;;;AAsBO,IAAM,yBAAA,GAA4B;AAAA,EACvC,SAAA,EAAW,aAAA;AAAA,EACX,OAAA,EAAS,aAAA;AAAA,EACT,MAAA,EAAQ,aAAA;AAAA,EACR,IAAA,EAAM;AACR;AAUO,IAAM,2BAAA,GAAmF;AAAA,EAC9F,SAAA,EAAW,CAAC,wBAAA,EAA0B,iBAAiB,CAAA;AAAA,EACvD,OAAA,EAAS,CAAC,wBAAA,EAA0B,iBAAiB,CAAA;AAAA,EACrD,MAAA,EAAQ,CAAC,wBAAA,EAA0B,iBAAiB,CAAA;AAAA,EACpD,IAAA,EAAM,CAAC,4BAAA,EAA8B,iBAAiB;AACxD;AAGO,SAAS,oBAAA,CAAqB,SAAiB,WAAA,EAAsC;AAC1F,EAAA,IAAI,CAAC,aAAa,OAAO,IAAA;AACzB,EAAA,MAAM,MAAA,GAASA,+BAAA,CAAc,OAAO,CAAA,EAAG,YAAA;AACvC,EAAA,OAAO,MAAA,KAAW,MAAA,IAAa,MAAA,CAAO,QAAA,CAAS,WAAW,CAAA;AAC5D;AAQO,SAAS,iBAAA,CAAkB,MAAsB,WAAA,EAAqC;AAC3F,EAAA,MAAM,OAAA,GAAU,0BAA0B,IAAI,CAAA;AAC9C,EAAA,IAAI,oBAAA,CAAqB,OAAA,EAAS,WAAW,CAAA,EAAG,OAAO,OAAA;AACvD,EAAA,OAAO,2BAAA,CAA4B,IAAI,CAAA,CAAE,IAAA,CAAK,CAAC,OAAO,oBAAA,CAAqB,EAAA,EAAI,WAAW,CAAC,CAAA,IAAK,OAAA;AAClG","file":"chunk-YEET2QGF.cjs","sourcesContent":["import { MODEL_CATALOG } from \"./model-catalog.js\"\n\n/**\n * The platform's answer to \"which image model, when the caller names none\".\n *\n * One table by ROLE, so every surface that picks for the user (node defaults,\n * route and workflow fallbacks, MCP tools, studios, pipelines) reads the same\n * model instead of keeping its own literal. Before this table those literals\n * had drifted apart: the Generate Image node started on Nano Banana Pro, the\n * routes fell back to the original Nano Banana, and MCP used Nano Banana 2.1.\n *\n * Decided on 2026-10-08 from a blind five-model comparison, quality\n * first and price second:\n * - characters, general text-to-image and video anchors on GPT Image 2;\n * - edits on GPT Image 2.5 Flare.\n * With reference images attached, GPT Image 2 runs as its i2i sibling (the\n * provider swaps it), so `character` covers identity-from-reference too.\n *\n * Nano Banana Pro is no longer a default. It remains a FALLBACK only: last in\n * the ratio chain below (it is the one model here that draws 4:5 and 5:4), the\n * GPT-family safety-block retry, and the swimwear dressing model.\n */\nexport const IMAGE_MODEL_ROLE_DEFAULTS = {\n character: \"gpt-image-2\",\n general: \"gpt-image-2\",\n anchor: \"gpt-image-2\",\n edit: \"gpt-image-2-5-flare-i2i\",\n} as const\n\nexport type ImageModelRole = keyof typeof IMAGE_MODEL_ROLE_DEFAULTS\n\n/**\n * Where a role's model goes when it cannot draw the requested aspect ratio.\n * GPT Image 2 draws only auto / 1:1 / 16:9 / 9:16 / 4:3 / 3:4, so 21:9, 3:2,\n * 2:3 and the other wide or in-between ratios move to GPT Image 2.5 Sunburst,\n * and 4:5 / 5:4 (which neither GPT generation draws) to Nano Banana Pro.\n */\nexport const IMAGE_MODEL_RATIO_FALLBACKS: Readonly<Record<ImageModelRole, readonly string[]>> = {\n character: [\"gpt-image-2-5-sunburst\", \"nano-banana-pro\"],\n general: [\"gpt-image-2-5-sunburst\", \"nano-banana-pro\"],\n anchor: [\"gpt-image-2-5-sunburst\", \"nano-banana-pro\"],\n edit: [\"gpt-image-2-5-sunburst-i2i\", \"nano-banana-pro\"],\n}\n\n/** True when the model's catalog entry lists the ratio (or no ratio was asked for). */\nexport function imageModelDrawsRatio(modelId: string, aspectRatio?: string | null): boolean {\n if (!aspectRatio) return true\n const ratios = MODEL_CATALOG[modelId]?.aspectRatios\n return ratios === undefined || ratios.includes(aspectRatio)\n}\n\n/**\n * The default image model for a role at the requested aspect ratio: the role's\n * model when it draws the ratio, else the first fallback that does, else the\n * role's model (whose own ratio normalization then snaps the ratio). Read from\n * the catalog, so widening a model's documented ratios moves this with it.\n */\nexport function defaultImageModel(role: ImageModelRole, aspectRatio?: string | null): string {\n const primary = IMAGE_MODEL_ROLE_DEFAULTS[role]\n if (imageModelDrawsRatio(primary, aspectRatio)) return primary\n return IMAGE_MODEL_RATIO_FALLBACKS[role].find((id) => imageModelDrawsRatio(id, aspectRatio)) ?? primary\n}\n"]}
1
+ {"version":3,"sources":["../src/image-model-roles.ts"],"names":["MODEL_CATALOG"],"mappings":";;;;;AAsBO,IAAM,yBAAA,GAA4B;AAAA,EACvC,SAAA,EAAW,aAAA;AAAA,EACX,OAAA,EAAS,aAAA;AAAA,EACT,MAAA,EAAQ,aAAA;AAAA,EACR,IAAA,EAAM;AACR;AAUO,IAAM,2BAAA,GAAmF;AAAA,EAC9F,SAAA,EAAW,CAAC,wBAAA,EAA0B,iBAAiB,CAAA;AAAA,EACvD,OAAA,EAAS,CAAC,wBAAA,EAA0B,iBAAiB,CAAA;AAAA,EACrD,MAAA,EAAQ,CAAC,wBAAA,EAA0B,iBAAiB,CAAA;AAAA,EACpD,IAAA,EAAM,CAAC,4BAAA,EAA8B,iBAAiB;AACxD;AAGO,SAAS,oBAAA,CAAqB,SAAiB,WAAA,EAAsC;AAC1F,EAAA,IAAI,CAAC,aAAa,OAAO,IAAA;AACzB,EAAA,MAAM,MAAA,GAASA,+BAAA,CAAc,OAAO,CAAA,EAAG,YAAA;AACvC,EAAA,OAAO,MAAA,KAAW,MAAA,IAAa,MAAA,CAAO,QAAA,CAAS,WAAW,CAAA;AAC5D;AAQO,SAAS,iBAAA,CAAkB,MAAsB,WAAA,EAAqC;AAC3F,EAAA,MAAM,OAAA,GAAU,0BAA0B,IAAI,CAAA;AAC9C,EAAA,IAAI,oBAAA,CAAqB,OAAA,EAAS,WAAW,CAAA,EAAG,OAAO,OAAA;AACvD,EAAA,OAAO,2BAAA,CAA4B,IAAI,CAAA,CAAE,IAAA,CAAK,CAAC,OAAO,oBAAA,CAAqB,EAAA,EAAI,WAAW,CAAC,CAAA,IAAK,OAAA;AAClG","file":"chunk-IHPDWGBN.cjs","sourcesContent":["import { MODEL_CATALOG } from \"./model-catalog.js\"\n\n/**\n * The platform's answer to \"which image model, when the caller names none\".\n *\n * One table by ROLE, so every surface that picks for the user (node defaults,\n * route and workflow fallbacks, MCP tools, studios, pipelines) reads the same\n * model instead of keeping its own literal. Before this table those literals\n * had drifted apart: the Generate Image node started on Nano Banana Pro, the\n * routes fell back to the original Nano Banana, and MCP used Nano Banana 2.1.\n *\n * Decided on 2026-10-08 from a blind five-model comparison, quality\n * first and price second:\n * - characters, general text-to-image and video anchors on GPT Image 2;\n * - edits on GPT Image 2.5 Flare.\n * With reference images attached, GPT Image 2 runs as its i2i sibling (the\n * provider swaps it), so `character` covers identity-from-reference too.\n *\n * Nano Banana Pro is no longer a default. It remains a FALLBACK only: last in\n * the ratio chain below (it is the one model here that draws 4:5 and 5:4), the\n * GPT-family safety-block retry, and the swimwear dressing model.\n */\nexport const IMAGE_MODEL_ROLE_DEFAULTS = {\n character: \"gpt-image-2\",\n general: \"gpt-image-2\",\n anchor: \"gpt-image-2\",\n edit: \"gpt-image-2-5-flare-i2i\",\n} as const\n\nexport type ImageModelRole = keyof typeof IMAGE_MODEL_ROLE_DEFAULTS\n\n/**\n * Where a role's model goes when it cannot draw the requested aspect ratio.\n * GPT Image 2 draws only auto / 1:1 / 16:9 / 9:16 / 4:3 / 3:4, so 21:9, 3:2,\n * 2:3 and the other wide or in-between ratios move to GPT Image 2.5 Sunburst,\n * and 4:5 / 5:4 (which neither GPT generation draws) to Nano Banana Pro.\n */\nexport const IMAGE_MODEL_RATIO_FALLBACKS: Readonly<Record<ImageModelRole, readonly string[]>> = {\n character: [\"gpt-image-2-5-sunburst\", \"nano-banana-pro\"],\n general: [\"gpt-image-2-5-sunburst\", \"nano-banana-pro\"],\n anchor: [\"gpt-image-2-5-sunburst\", \"nano-banana-pro\"],\n edit: [\"gpt-image-2-5-sunburst-i2i\", \"nano-banana-pro\"],\n}\n\n/** True when the model's catalog entry lists the ratio (or no ratio was asked for). */\nexport function imageModelDrawsRatio(modelId: string, aspectRatio?: string | null): boolean {\n if (!aspectRatio) return true\n const ratios = MODEL_CATALOG[modelId]?.aspectRatios\n return ratios === undefined || ratios.includes(aspectRatio)\n}\n\n/**\n * The default image model for a role at the requested aspect ratio: the role's\n * model when it draws the ratio, else the first fallback that does, else the\n * role's model (whose own ratio normalization then snaps the ratio). Read from\n * the catalog, so widening a model's documented ratios moves this with it.\n */\nexport function defaultImageModel(role: ImageModelRole, aspectRatio?: string | null): string {\n const primary = IMAGE_MODEL_ROLE_DEFAULTS[role]\n if (imageModelDrawsRatio(primary, aspectRatio)) return primary\n return IMAGE_MODEL_RATIO_FALLBACKS[role].find((id) => imageModelDrawsRatio(id, aspectRatio)) ?? primary\n}\n"]}