@nodaro/shared 1.4.2
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.
- package/LICENSE +202 -0
- package/README.md +32 -0
- package/dist/index.cjs +12506 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +12269 -0
- package/dist/index.d.ts +12269 -0
- package/dist/index.js +11831 -0
- package/dist/index.js.map +1 -0
- package/package.json +54 -0
- package/src/__tests__/__snapshots__/prompt-builder-segments.test.ts.snap +65 -0
- package/src/__tests__/ai-avatar-pricing.test.ts +321 -0
- package/src/__tests__/apply-video-negative-prompt.test.ts +76 -0
- package/src/__tests__/attach-columns.test.ts +28 -0
- package/src/__tests__/audio-crossfade-curves.test.ts +33 -0
- package/src/__tests__/build-model-menu.test.ts +58 -0
- package/src/__tests__/character-aspect-defaults.test.ts +142 -0
- package/src/__tests__/character-mention-slug.test.ts +199 -0
- package/src/__tests__/character-reference-photo-kinds.test.ts +32 -0
- package/src/__tests__/character-usage-mode.test.ts +147 -0
- package/src/__tests__/character-variant-assets.test.ts +142 -0
- package/src/__tests__/character-voice.test.ts +130 -0
- package/src/__tests__/cinematic-avatar-pricing.test.ts +119 -0
- package/src/__tests__/combine-transitions.test.ts +137 -0
- package/src/__tests__/component-types.test.ts +87 -0
- package/src/__tests__/condition-variables.test.ts +98 -0
- package/src/__tests__/credit-identifiers.test.ts +811 -0
- package/src/__tests__/default-video-provider.test.ts +63 -0
- package/src/__tests__/entity-image-handle.test.ts +43 -0
- package/src/__tests__/entity-variants.test.ts +33 -0
- package/src/__tests__/fal-lip-sync-sets.test.ts +31 -0
- package/src/__tests__/featured-entities.test.ts +33 -0
- package/src/__tests__/film-pricing.test.ts +64 -0
- package/src/__tests__/filter-condition.test.ts +285 -0
- package/src/__tests__/freecut-protocol.test.ts +35 -0
- package/src/__tests__/generate-text-items.test.ts +19 -0
- package/src/__tests__/generated-results.test.ts +50 -0
- package/src/__tests__/graph-utils.test.ts +618 -0
- package/src/__tests__/group-aggregation.test.ts +83 -0
- package/src/__tests__/i18n-locale-completeness.test.ts +156 -0
- package/src/__tests__/image-critic-node.test.ts +86 -0
- package/src/__tests__/image-mask-mode.test.ts +16 -0
- package/src/__tests__/image-ref-limit.test.ts +78 -0
- package/src/__tests__/inpaint-region.test.ts +24 -0
- package/src/__tests__/input-field-map-parity.test.ts +30 -0
- package/src/__tests__/json-evaluator.test.ts +289 -0
- package/src/__tests__/json-path.test.ts +64 -0
- package/src/__tests__/lip-sync-pricing.test.ts +142 -0
- package/src/__tests__/list-merge.test.ts +96 -0
- package/src/__tests__/list-sort.test.ts +134 -0
- package/src/__tests__/llm-models.test.ts +445 -0
- package/src/__tests__/location-mention-slug.test.ts +246 -0
- package/src/__tests__/locations-coverage-critic-schema.test.ts +92 -0
- package/src/__tests__/loop-delimiter.test.ts +39 -0
- package/src/__tests__/lottie-slots.test.ts +245 -0
- package/src/__tests__/model-catalog-flux2-resolutions.test.ts +21 -0
- package/src/__tests__/model-constants-location.test.ts +20 -0
- package/src/__tests__/model-constants.test.ts +122 -0
- package/src/__tests__/model-tree.test.ts +86 -0
- package/src/__tests__/no-internal-imports.test.ts +25 -0
- package/src/__tests__/node-default-mappings.test.ts +175 -0
- package/src/__tests__/node-mappable-fields.test.ts +7 -0
- package/src/__tests__/node-preset-export.test.ts +46 -0
- package/src/__tests__/node-preset-extract.test.ts +166 -0
- package/src/__tests__/node-refs-canonical.test.ts +54 -0
- package/src/__tests__/node-refs-combine.test.ts +54 -0
- package/src/__tests__/node-refs.test.ts +187 -0
- package/src/__tests__/node-runtime-keys.test.ts +99 -0
- package/src/__tests__/object-aspect-defaults.test.ts +59 -0
- package/src/__tests__/parameter-node-value.test.ts +137 -0
- package/src/__tests__/pinterest-url.test.ts +35 -0
- package/src/__tests__/pipeline-chat.test.ts +110 -0
- package/src/__tests__/pipeline-validation.test.ts +98 -0
- package/src/__tests__/presentation-utils.test.ts +1137 -0
- package/src/__tests__/producer-types.test.ts +47 -0
- package/src/__tests__/prompt-length-limits.test.ts +156 -0
- package/src/__tests__/provider-directive-defaults.test.ts +46 -0
- package/src/__tests__/reduce-strategy-registry.test.ts +43 -0
- package/src/__tests__/reference-board-templates.test.ts +33 -0
- package/src/__tests__/reference-roles.test.ts +36 -0
- package/src/__tests__/resolve-field-mappings.test.ts +110 -0
- package/src/__tests__/resolve-pipeline-model.test.ts +76 -0
- package/src/__tests__/scene-node-types.test.ts +80 -0
- package/src/__tests__/scraper-actors.test.ts +67 -0
- package/src/__tests__/seedance-2-catalog.test.ts +18 -0
- package/src/__tests__/seedance-2-credit-id.test.ts +23 -0
- package/src/__tests__/seedance-aspects.test.ts +52 -0
- package/src/__tests__/selector.test.ts +1151 -0
- package/src/__tests__/settled-with-limit.test.ts +214 -0
- package/src/__tests__/social-media-specs.test.ts +129 -0
- package/src/__tests__/sub-workflow-validation.test.ts +88 -0
- package/src/__tests__/switchx-pricing.test.ts +28 -0
- package/src/__tests__/to-connected-references.test.ts +153 -0
- package/src/__tests__/utilities.test.ts +541 -0
- package/src/__tests__/video-analysis-pricing.test.ts +58 -0
- package/src/__tests__/video-analysis.test.ts +63 -0
- package/src/__tests__/video-audio-capability.test.ts +204 -0
- package/src/__tests__/video-gen-providers.test.ts +28 -0
- package/src/__tests__/video-mode-aliases.test.ts +150 -0
- package/src/__tests__/video-ref-limits.test.ts +72 -0
- package/src/__tests__/video-utils.test.ts +303 -0
- package/src/__tests__/voice-changer-models.test.ts +33 -0
- package/src/__tests__/workflow-export-strip.test.ts +46 -0
- package/src/ai-avatar-pricing.ts +213 -0
- package/src/ancestor-refs.ts +48 -0
- package/src/animals.ts +231 -0
- package/src/audio-crossfade-curves.ts +73 -0
- package/src/audio-fx-presets.ts +64 -0
- package/src/avatar-payload-validators.ts +214 -0
- package/src/caption-styles.ts +31 -0
- package/src/character-aspect-defaults.ts +102 -0
- package/src/character-facets.ts +37 -0
- package/src/character-mention-slug.ts +166 -0
- package/src/character-usage-mode.ts +109 -0
- package/src/character-variant-assets.ts +121 -0
- package/src/character-voice.ts +151 -0
- package/src/cinematic-avatar-pricing.ts +111 -0
- package/src/clone-utils.ts +46 -0
- package/src/combine-transitions.ts +482 -0
- package/src/community.ts +112 -0
- package/src/component-types.ts +127 -0
- package/src/condition-variables.ts +65 -0
- package/src/credit-estimators/index.ts +15 -0
- package/src/credit-estimators/video-utils.ts +165 -0
- package/src/credit-identifiers.ts +304 -0
- package/src/entity-approval-types.ts +31 -0
- package/src/entity-aspect-defaults.ts +82 -0
- package/src/entity-asset-types.ts +296 -0
- package/src/entity-image-handle.ts +36 -0
- package/src/extra-refs.ts +139 -0
- package/src/featured-entities.ts +136 -0
- package/src/film-pricing.ts +117 -0
- package/src/filter-condition.ts +250 -0
- package/src/flux2-pricing.ts +18 -0
- package/src/freecut-protocol.ts +52 -0
- package/src/furniture.ts +167 -0
- package/src/generate-text-items.ts +15 -0
- package/src/generated-results.ts +63 -0
- package/src/group-aggregation.ts +75 -0
- package/src/hint-graph-types.ts +18 -0
- package/src/i18n/action-fx.ar.ts +89 -0
- package/src/i18n/action-fx.de.ts +89 -0
- package/src/i18n/action-fx.es.ts +89 -0
- package/src/i18n/action-fx.fr.ts +89 -0
- package/src/i18n/action-fx.he.ts +89 -0
- package/src/i18n/action-fx.hi.ts +89 -0
- package/src/i18n/action-fx.ja.ts +89 -0
- package/src/i18n/action-fx.ko.ts +89 -0
- package/src/i18n/action-fx.pt-BR.ts +89 -0
- package/src/i18n/action-fx.ru.ts +89 -0
- package/src/i18n/action-fx.zh-CN.ts +89 -0
- package/src/i18n/aesthetic.ar.ts +170 -0
- package/src/i18n/aesthetic.de.ts +48 -0
- package/src/i18n/aesthetic.es.ts +169 -0
- package/src/i18n/aesthetic.fr.ts +52 -0
- package/src/i18n/aesthetic.he.ts +169 -0
- package/src/i18n/aesthetic.hi.ts +55 -0
- package/src/i18n/aesthetic.ja.ts +165 -0
- package/src/i18n/aesthetic.ko.ts +169 -0
- package/src/i18n/aesthetic.pt-BR.ts +148 -0
- package/src/i18n/aesthetic.ru.ts +155 -0
- package/src/i18n/aesthetic.zh-CN.ts +172 -0
- package/src/i18n/animals.ar.ts +145 -0
- package/src/i18n/animals.de.ts +144 -0
- package/src/i18n/animals.es.ts +158 -0
- package/src/i18n/animals.fr.ts +144 -0
- package/src/i18n/animals.he.ts +155 -0
- package/src/i18n/animals.hi.ts +157 -0
- package/src/i18n/animals.ja.ts +159 -0
- package/src/i18n/animals.ko.ts +159 -0
- package/src/i18n/animals.pt-BR.ts +157 -0
- package/src/i18n/animals.ru.ts +155 -0
- package/src/i18n/animals.zh-CN.ts +155 -0
- package/src/i18n/atmosphere.ar.ts +49 -0
- package/src/i18n/atmosphere.de.ts +47 -0
- package/src/i18n/atmosphere.es.ts +50 -0
- package/src/i18n/atmosphere.fr.ts +47 -0
- package/src/i18n/atmosphere.he.ts +47 -0
- package/src/i18n/atmosphere.hi.ts +49 -0
- package/src/i18n/atmosphere.ja.ts +49 -0
- package/src/i18n/atmosphere.ko.ts +49 -0
- package/src/i18n/atmosphere.pt-BR.ts +49 -0
- package/src/i18n/atmosphere.ru.ts +47 -0
- package/src/i18n/atmosphere.zh-CN.ts +152 -0
- package/src/i18n/backdrop.ar.ts +53 -0
- package/src/i18n/backdrop.de.ts +46 -0
- package/src/i18n/backdrop.es.ts +54 -0
- package/src/i18n/backdrop.fr.ts +52 -0
- package/src/i18n/backdrop.he.ts +51 -0
- package/src/i18n/backdrop.hi.ts +59 -0
- package/src/i18n/backdrop.ja.ts +61 -0
- package/src/i18n/backdrop.ko.ts +59 -0
- package/src/i18n/backdrop.pt-BR.ts +59 -0
- package/src/i18n/backdrop.ru.ts +57 -0
- package/src/i18n/backdrop.zh-CN.ts +57 -0
- package/src/i18n/camera-format.ar.ts +40 -0
- package/src/i18n/camera-format.de.ts +37 -0
- package/src/i18n/camera-format.es.ts +41 -0
- package/src/i18n/camera-format.fr.ts +37 -0
- package/src/i18n/camera-format.he.ts +37 -0
- package/src/i18n/camera-format.hi.ts +42 -0
- package/src/i18n/camera-format.ja.ts +37 -0
- package/src/i18n/camera-format.ko.ts +37 -0
- package/src/i18n/camera-format.pt-BR.ts +46 -0
- package/src/i18n/camera-format.ru.ts +42 -0
- package/src/i18n/camera-format.zh-CN.ts +42 -0
- package/src/i18n/camera-motions.ar.ts +86 -0
- package/src/i18n/camera-motions.de.ts +74 -0
- package/src/i18n/camera-motions.es.ts +86 -0
- package/src/i18n/camera-motions.fr.ts +86 -0
- package/src/i18n/camera-motions.he.ts +86 -0
- package/src/i18n/camera-motions.hi.ts +99 -0
- package/src/i18n/camera-motions.ja.ts +99 -0
- package/src/i18n/camera-motions.ko.ts +99 -0
- package/src/i18n/camera-motions.pt-BR.ts +99 -0
- package/src/i18n/camera-motions.ru.ts +99 -0
- package/src/i18n/camera-motions.zh-CN.ts +99 -0
- package/src/i18n/character-fx.ar.ts +72 -0
- package/src/i18n/character-fx.de.ts +72 -0
- package/src/i18n/character-fx.es.ts +72 -0
- package/src/i18n/character-fx.fr.ts +72 -0
- package/src/i18n/character-fx.he.ts +72 -0
- package/src/i18n/character-fx.hi.ts +72 -0
- package/src/i18n/character-fx.ja.ts +72 -0
- package/src/i18n/character-fx.ko.ts +72 -0
- package/src/i18n/character-fx.pt-BR.ts +72 -0
- package/src/i18n/character-fx.ru.ts +72 -0
- package/src/i18n/character-fx.zh-CN.ts +72 -0
- package/src/i18n/color-look.ar.ts +50 -0
- package/src/i18n/color-look.de.ts +47 -0
- package/src/i18n/color-look.es.ts +50 -0
- package/src/i18n/color-look.fr.ts +50 -0
- package/src/i18n/color-look.he.ts +49 -0
- package/src/i18n/color-look.hi.ts +52 -0
- package/src/i18n/color-look.ja.ts +54 -0
- package/src/i18n/color-look.ko.ts +54 -0
- package/src/i18n/color-look.pt-BR.ts +54 -0
- package/src/i18n/color-look.ru.ts +52 -0
- package/src/i18n/color-look.zh-CN.ts +53 -0
- package/src/i18n/composition-effects.ar.ts +26 -0
- package/src/i18n/composition-effects.de.ts +25 -0
- package/src/i18n/composition-effects.es.ts +27 -0
- package/src/i18n/composition-effects.fr.ts +25 -0
- package/src/i18n/composition-effects.he.ts +25 -0
- package/src/i18n/composition-effects.hi.ts +27 -0
- package/src/i18n/composition-effects.ja.ts +27 -0
- package/src/i18n/composition-effects.ko.ts +27 -0
- package/src/i18n/composition-effects.pt-BR.ts +25 -0
- package/src/i18n/composition-effects.ru.ts +82 -0
- package/src/i18n/composition-effects.zh-CN.ts +25 -0
- package/src/i18n/era.ar.ts +37 -0
- package/src/i18n/era.de.ts +34 -0
- package/src/i18n/era.es.ts +37 -0
- package/src/i18n/era.fr.ts +37 -0
- package/src/i18n/era.he.ts +36 -0
- package/src/i18n/era.hi.ts +39 -0
- package/src/i18n/era.ja.ts +41 -0
- package/src/i18n/era.ko.ts +39 -0
- package/src/i18n/era.pt-BR.ts +41 -0
- package/src/i18n/era.ru.ts +121 -0
- package/src/i18n/era.zh-CN.ts +39 -0
- package/src/i18n/exposure-settings.ar.ts +28 -0
- package/src/i18n/exposure-settings.de.ts +26 -0
- package/src/i18n/exposure-settings.es.ts +28 -0
- package/src/i18n/exposure-settings.fr.ts +29 -0
- package/src/i18n/exposure-settings.he.ts +28 -0
- package/src/i18n/exposure-settings.hi.ts +31 -0
- package/src/i18n/exposure-settings.ja.ts +31 -0
- package/src/i18n/exposure-settings.ko.ts +31 -0
- package/src/i18n/exposure-settings.pt-BR.ts +31 -0
- package/src/i18n/exposure-settings.ru.ts +31 -0
- package/src/i18n/exposure-settings.zh-CN.ts +31 -0
- package/src/i18n/framing.ar.ts +78 -0
- package/src/i18n/framing.de.ts +73 -0
- package/src/i18n/framing.es.ts +78 -0
- package/src/i18n/framing.fr.ts +78 -0
- package/src/i18n/framing.he.ts +77 -0
- package/src/i18n/framing.hi.ts +82 -0
- package/src/i18n/framing.ja.ts +84 -0
- package/src/i18n/framing.ko.ts +82 -0
- package/src/i18n/framing.pt-BR.ts +84 -0
- package/src/i18n/framing.ru.ts +82 -0
- package/src/i18n/framing.zh-CN.ts +82 -0
- package/src/i18n/furniture.ar.ts +92 -0
- package/src/i18n/furniture.de.ts +93 -0
- package/src/i18n/furniture.es.ts +101 -0
- package/src/i18n/furniture.fr.ts +93 -0
- package/src/i18n/furniture.he.ts +101 -0
- package/src/i18n/furniture.hi.ts +101 -0
- package/src/i18n/furniture.ja.ts +101 -0
- package/src/i18n/furniture.ko.ts +101 -0
- package/src/i18n/furniture.pt-BR.ts +101 -0
- package/src/i18n/furniture.ru.ts +101 -0
- package/src/i18n/furniture.zh-CN.ts +101 -0
- package/src/i18n/held-prop.ar.ts +74 -0
- package/src/i18n/held-prop.de.ts +65 -0
- package/src/i18n/held-prop.es.ts +83 -0
- package/src/i18n/held-prop.fr.ts +74 -0
- package/src/i18n/held-prop.he.ts +73 -0
- package/src/i18n/held-prop.hi.ts +82 -0
- package/src/i18n/held-prop.ja.ts +84 -0
- package/src/i18n/held-prop.ko.ts +84 -0
- package/src/i18n/held-prop.pt-BR.ts +84 -0
- package/src/i18n/held-prop.ru.ts +82 -0
- package/src/i18n/held-prop.zh-CN.ts +82 -0
- package/src/i18n/index.ts +208 -0
- package/src/i18n/instrumentation.ar.ts +195 -0
- package/src/i18n/instrumentation.de.ts +195 -0
- package/src/i18n/instrumentation.es.ts +195 -0
- package/src/i18n/instrumentation.fr.ts +195 -0
- package/src/i18n/instrumentation.he.ts +195 -0
- package/src/i18n/instrumentation.hi.ts +195 -0
- package/src/i18n/instrumentation.ja.ts +195 -0
- package/src/i18n/instrumentation.ko.ts +195 -0
- package/src/i18n/instrumentation.pt-BR.ts +195 -0
- package/src/i18n/instrumentation.ru.ts +195 -0
- package/src/i18n/instrumentation.zh-CN.ts +195 -0
- package/src/i18n/lens.ar.ts +24 -0
- package/src/i18n/lens.de.ts +24 -0
- package/src/i18n/lens.es.ts +24 -0
- package/src/i18n/lens.fr.ts +24 -0
- package/src/i18n/lens.he.ts +24 -0
- package/src/i18n/lens.hi.ts +24 -0
- package/src/i18n/lens.ja.ts +24 -0
- package/src/i18n/lens.ko.ts +24 -0
- package/src/i18n/lens.pt-BR.ts +24 -0
- package/src/i18n/lens.ru.ts +25 -0
- package/src/i18n/lens.zh-CN.ts +24 -0
- package/src/i18n/lighting.ar.ts +86 -0
- package/src/i18n/lighting.de.ts +84 -0
- package/src/i18n/lighting.es.ts +89 -0
- package/src/i18n/lighting.fr.ts +84 -0
- package/src/i18n/lighting.he.ts +88 -0
- package/src/i18n/lighting.hi.ts +90 -0
- package/src/i18n/lighting.ja.ts +90 -0
- package/src/i18n/lighting.ko.ts +90 -0
- package/src/i18n/lighting.pt-BR.ts +90 -0
- package/src/i18n/lighting.ru.ts +88 -0
- package/src/i18n/lighting.zh-CN.ts +92 -0
- package/src/i18n/loop-subject.ar.ts +39 -0
- package/src/i18n/loop-subject.de.ts +39 -0
- package/src/i18n/loop-subject.es.ts +39 -0
- package/src/i18n/loop-subject.fr.ts +39 -0
- package/src/i18n/loop-subject.he.ts +39 -0
- package/src/i18n/loop-subject.hi.ts +39 -0
- package/src/i18n/loop-subject.ja.ts +39 -0
- package/src/i18n/loop-subject.ko.ts +39 -0
- package/src/i18n/loop-subject.pt-BR.ts +39 -0
- package/src/i18n/loop-subject.ru.ts +39 -0
- package/src/i18n/loop-subject.zh-CN.ts +39 -0
- package/src/i18n/materials.ar.ts +80 -0
- package/src/i18n/materials.de.ts +80 -0
- package/src/i18n/materials.es.ts +87 -0
- package/src/i18n/materials.fr.ts +80 -0
- package/src/i18n/materials.he.ts +86 -0
- package/src/i18n/materials.hi.ts +86 -0
- package/src/i18n/materials.ja.ts +88 -0
- package/src/i18n/materials.ko.ts +88 -0
- package/src/i18n/materials.pt-BR.ts +88 -0
- package/src/i18n/materials.ru.ts +86 -0
- package/src/i18n/materials.zh-CN.ts +86 -0
- package/src/i18n/mood.ar.ts +61 -0
- package/src/i18n/mood.de.ts +61 -0
- package/src/i18n/mood.es.ts +66 -0
- package/src/i18n/mood.fr.ts +61 -0
- package/src/i18n/mood.he.ts +64 -0
- package/src/i18n/mood.hi.ts +66 -0
- package/src/i18n/mood.ja.ts +66 -0
- package/src/i18n/mood.ko.ts +66 -0
- package/src/i18n/mood.pt-BR.ts +64 -0
- package/src/i18n/mood.ru.ts +64 -0
- package/src/i18n/mood.zh-CN.ts +64 -0
- package/src/i18n/music-genre.ar.ts +302 -0
- package/src/i18n/music-genre.de.ts +302 -0
- package/src/i18n/music-genre.es.ts +302 -0
- package/src/i18n/music-genre.fr.ts +302 -0
- package/src/i18n/music-genre.he.ts +302 -0
- package/src/i18n/music-genre.hi.ts +302 -0
- package/src/i18n/music-genre.ja.ts +302 -0
- package/src/i18n/music-genre.ko.ts +302 -0
- package/src/i18n/music-genre.pt-BR.ts +302 -0
- package/src/i18n/music-genre.ru.ts +302 -0
- package/src/i18n/music-genre.zh-CN.ts +302 -0
- package/src/i18n/music-mood.ar.ts +75 -0
- package/src/i18n/music-mood.de.ts +75 -0
- package/src/i18n/music-mood.es.ts +75 -0
- package/src/i18n/music-mood.fr.ts +75 -0
- package/src/i18n/music-mood.he.ts +75 -0
- package/src/i18n/music-mood.hi.ts +75 -0
- package/src/i18n/music-mood.ja.ts +75 -0
- package/src/i18n/music-mood.ko.ts +75 -0
- package/src/i18n/music-mood.pt-BR.ts +75 -0
- package/src/i18n/music-mood.ru.ts +75 -0
- package/src/i18n/music-mood.zh-CN.ts +75 -0
- package/src/i18n/person.ar.ts +638 -0
- package/src/i18n/person.de.ts +629 -0
- package/src/i18n/person.es.ts +645 -0
- package/src/i18n/person.fr.ts +621 -0
- package/src/i18n/person.he.ts +656 -0
- package/src/i18n/person.hi.ts +654 -0
- package/src/i18n/person.ja.ts +662 -0
- package/src/i18n/person.ko.ts +662 -0
- package/src/i18n/person.pt-BR.ts +656 -0
- package/src/i18n/person.ru.ts +656 -0
- package/src/i18n/person.zh-CN.ts +656 -0
- package/src/i18n/photo-genre.ar.ts +58 -0
- package/src/i18n/photo-genre.de.ts +52 -0
- package/src/i18n/photo-genre.es.ts +64 -0
- package/src/i18n/photo-genre.fr.ts +58 -0
- package/src/i18n/photo-genre.he.ts +62 -0
- package/src/i18n/photo-genre.hi.ts +63 -0
- package/src/i18n/photo-genre.ja.ts +65 -0
- package/src/i18n/photo-genre.ko.ts +63 -0
- package/src/i18n/photo-genre.pt-BR.ts +65 -0
- package/src/i18n/photo-genre.ru.ts +63 -0
- package/src/i18n/photo-genre.zh-CN.ts +63 -0
- package/src/i18n/photographer.ar.ts +75 -0
- package/src/i18n/photographer.de.ts +74 -0
- package/src/i18n/photographer.es.ts +77 -0
- package/src/i18n/photographer.fr.ts +77 -0
- package/src/i18n/photographer.he.ts +78 -0
- package/src/i18n/photographer.hi.ts +80 -0
- package/src/i18n/photographer.ja.ts +84 -0
- package/src/i18n/photographer.ko.ts +84 -0
- package/src/i18n/photographer.pt-BR.ts +83 -0
- package/src/i18n/photographer.ru.ts +78 -0
- package/src/i18n/photographer.zh-CN.ts +78 -0
- package/src/i18n/pose.ar.ts +95 -0
- package/src/i18n/pose.de.ts +96 -0
- package/src/i18n/pose.es.ts +104 -0
- package/src/i18n/pose.fr.ts +96 -0
- package/src/i18n/pose.he.ts +104 -0
- package/src/i18n/pose.hi.ts +104 -0
- package/src/i18n/pose.ja.ts +104 -0
- package/src/i18n/pose.ko.ts +104 -0
- package/src/i18n/pose.pt-BR.ts +104 -0
- package/src/i18n/pose.ru.ts +104 -0
- package/src/i18n/pose.zh-CN.ts +104 -0
- package/src/i18n/post-process-effects.ar.ts +25 -0
- package/src/i18n/post-process-effects.de.ts +24 -0
- package/src/i18n/post-process-effects.es.ts +26 -0
- package/src/i18n/post-process-effects.fr.ts +24 -0
- package/src/i18n/post-process-effects.he.ts +24 -0
- package/src/i18n/post-process-effects.hi.ts +26 -0
- package/src/i18n/post-process-effects.ja.ts +26 -0
- package/src/i18n/post-process-effects.ko.ts +26 -0
- package/src/i18n/post-process-effects.pt-BR.ts +24 -0
- package/src/i18n/post-process-effects.ru.ts +24 -0
- package/src/i18n/post-process-effects.zh-CN.ts +24 -0
- package/src/i18n/render-quality.ar.ts +34 -0
- package/src/i18n/render-quality.de.ts +30 -0
- package/src/i18n/render-quality.es.ts +35 -0
- package/src/i18n/render-quality.fr.ts +34 -0
- package/src/i18n/render-quality.he.ts +33 -0
- package/src/i18n/render-quality.hi.ts +39 -0
- package/src/i18n/render-quality.ja.ts +39 -0
- package/src/i18n/render-quality.ko.ts +39 -0
- package/src/i18n/render-quality.pt-BR.ts +37 -0
- package/src/i18n/render-quality.ru.ts +37 -0
- package/src/i18n/render-quality.zh-CN.ts +37 -0
- package/src/i18n/seasons.ar.ts +10 -0
- package/src/i18n/seasons.de.ts +10 -0
- package/src/i18n/seasons.es.ts +10 -0
- package/src/i18n/seasons.fr.ts +10 -0
- package/src/i18n/seasons.he.ts +10 -0
- package/src/i18n/seasons.hi.ts +10 -0
- package/src/i18n/seasons.ja.ts +10 -0
- package/src/i18n/seasons.ko.ts +10 -0
- package/src/i18n/seasons.pt-BR.ts +10 -0
- package/src/i18n/seasons.ru.ts +10 -0
- package/src/i18n/seasons.zh-CN.ts +10 -0
- package/src/i18n/setting.ar.ts +73 -0
- package/src/i18n/setting.de.ts +73 -0
- package/src/i18n/setting.es.ts +77 -0
- package/src/i18n/setting.fr.ts +73 -0
- package/src/i18n/setting.he.ts +76 -0
- package/src/i18n/setting.hi.ts +76 -0
- package/src/i18n/setting.ja.ts +78 -0
- package/src/i18n/setting.ko.ts +76 -0
- package/src/i18n/setting.pt-BR.ts +78 -0
- package/src/i18n/setting.ru.ts +76 -0
- package/src/i18n/setting.zh-CN.ts +76 -0
- package/src/i18n/style.ar.ts +55 -0
- package/src/i18n/style.de.ts +54 -0
- package/src/i18n/style.es.ts +54 -0
- package/src/i18n/style.fr.ts +54 -0
- package/src/i18n/style.he.ts +54 -0
- package/src/i18n/style.hi.ts +54 -0
- package/src/i18n/style.ja.ts +54 -0
- package/src/i18n/style.ko.ts +54 -0
- package/src/i18n/style.pt-BR.ts +56 -0
- package/src/i18n/style.ru.ts +54 -0
- package/src/i18n/style.zh-CN.ts +54 -0
- package/src/i18n/styling.ar.ts +295 -0
- package/src/i18n/styling.de.ts +285 -0
- package/src/i18n/styling.es.ts +317 -0
- package/src/i18n/styling.fr.ts +285 -0
- package/src/i18n/styling.he.ts +307 -0
- package/src/i18n/styling.hi.ts +323 -0
- package/src/i18n/styling.ja.ts +317 -0
- package/src/i18n/styling.ko.ts +311 -0
- package/src/i18n/styling.pt-BR.ts +301 -0
- package/src/i18n/styling.ru.ts +301 -0
- package/src/i18n/styling.zh-CN.ts +307 -0
- package/src/i18n/temporal.ar.ts +31 -0
- package/src/i18n/temporal.de.ts +24 -0
- package/src/i18n/temporal.es.ts +27 -0
- package/src/i18n/temporal.fr.ts +28 -0
- package/src/i18n/temporal.he.ts +31 -0
- package/src/i18n/temporal.hi.ts +31 -0
- package/src/i18n/temporal.ja.ts +31 -0
- package/src/i18n/temporal.ko.ts +31 -0
- package/src/i18n/temporal.pt-BR.ts +31 -0
- package/src/i18n/temporal.ru.ts +31 -0
- package/src/i18n/temporal.zh-CN.ts +31 -0
- package/src/i18n/transitions.ar.ts +97 -0
- package/src/i18n/transitions.de.ts +97 -0
- package/src/i18n/transitions.es.ts +97 -0
- package/src/i18n/transitions.fr.ts +97 -0
- package/src/i18n/transitions.he.ts +97 -0
- package/src/i18n/transitions.hi.ts +97 -0
- package/src/i18n/transitions.ja.ts +97 -0
- package/src/i18n/transitions.ko.ts +97 -0
- package/src/i18n/transitions.pt-BR.ts +97 -0
- package/src/i18n/transitions.ru.ts +97 -0
- package/src/i18n/transitions.zh-CN.ts +97 -0
- package/src/i18n/types.ts +158 -0
- package/src/i18n/vehicles.ar.ts +137 -0
- package/src/i18n/vehicles.de.ts +125 -0
- package/src/i18n/vehicles.es.ts +138 -0
- package/src/i18n/vehicles.fr.ts +125 -0
- package/src/i18n/vehicles.he.ts +136 -0
- package/src/i18n/vehicles.hi.ts +138 -0
- package/src/i18n/vehicles.ja.ts +138 -0
- package/src/i18n/vehicles.ko.ts +138 -0
- package/src/i18n/vehicles.pt-BR.ts +136 -0
- package/src/i18n/vehicles.ru.ts +136 -0
- package/src/i18n/vehicles.zh-CN.ts +136 -0
- package/src/i18n/voice-character.ar.ts +126 -0
- package/src/i18n/voice-character.de.ts +126 -0
- package/src/i18n/voice-character.es.ts +126 -0
- package/src/i18n/voice-character.fr.ts +126 -0
- package/src/i18n/voice-character.he.ts +126 -0
- package/src/i18n/voice-character.hi.ts +126 -0
- package/src/i18n/voice-character.ja.ts +126 -0
- package/src/i18n/voice-character.ko.ts +126 -0
- package/src/i18n/voice-character.pt-BR.ts +126 -0
- package/src/i18n/voice-character.ru.ts +126 -0
- package/src/i18n/voice-character.zh-CN.ts +126 -0
- package/src/i18n/voice-delivery.ar.ts +77 -0
- package/src/i18n/voice-delivery.de.ts +77 -0
- package/src/i18n/voice-delivery.es.ts +77 -0
- package/src/i18n/voice-delivery.fr.ts +77 -0
- package/src/i18n/voice-delivery.he.ts +77 -0
- package/src/i18n/voice-delivery.hi.ts +77 -0
- package/src/i18n/voice-delivery.ja.ts +77 -0
- package/src/i18n/voice-delivery.ko.ts +77 -0
- package/src/i18n/voice-delivery.pt-BR.ts +77 -0
- package/src/i18n/voice-delivery.ru.ts +77 -0
- package/src/i18n/voice-delivery.zh-CN.ts +77 -0
- package/src/i18n/weapons.ar.ts +115 -0
- package/src/i18n/weapons.de.ts +114 -0
- package/src/i18n/weapons.es.ts +116 -0
- package/src/i18n/weapons.fr.ts +103 -0
- package/src/i18n/weapons.he.ts +114 -0
- package/src/i18n/weapons.hi.ts +116 -0
- package/src/i18n/weapons.ja.ts +116 -0
- package/src/i18n/weapons.ko.ts +116 -0
- package/src/i18n/weapons.pt-BR.ts +114 -0
- package/src/i18n/weapons.ru.ts +114 -0
- package/src/i18n/weapons.zh-CN.ts +114 -0
- package/src/image-critic-node.ts +61 -0
- package/src/image-critic-types.ts +40 -0
- package/src/index.ts +866 -0
- package/src/inject-upstream.ts +15 -0
- package/src/inpaint-region.ts +51 -0
- package/src/json-evaluator.ts +732 -0
- package/src/json-path.ts +52 -0
- package/src/lip-sync-pricing.ts +90 -0
- package/src/list-merge.ts +40 -0
- package/src/list-sort.ts +122 -0
- package/src/list-source-resolver.ts +50 -0
- package/src/llm-models.ts +245 -0
- package/src/location-mention-slug.ts +291 -0
- package/src/location-preset-catalog-map.ts +128 -0
- package/src/loop-delimiter.ts +73 -0
- package/src/lora-routing.ts +95 -0
- package/src/lottie-overlay-catalog.ts +175 -0
- package/src/lottie-slots.ts +309 -0
- package/src/model-catalog.ts +2386 -0
- package/src/model-constants.ts +1910 -0
- package/src/model-tree.ts +120 -0
- package/src/monetization.ts +15 -0
- package/src/multi-pick.ts +42 -0
- package/src/node-default-mappings.ts +262 -0
- package/src/node-mappable-fields.ts +70 -0
- package/src/node-preset-export.ts +56 -0
- package/src/node-preset-extract.ts +147 -0
- package/src/node-refs.ts +253 -0
- package/src/node-runtime-keys.ts +117 -0
- package/src/object-aspect-defaults.ts +72 -0
- package/src/object-picker-types.ts +22 -0
- package/src/parameter-node-value.ts +284 -0
- package/src/pinterest-url.ts +28 -0
- package/src/pipeline-chat.ts +72 -0
- package/src/pipeline-defaults.ts +318 -0
- package/src/pipeline-events.ts +162 -0
- package/src/pipeline-state-types.ts +196 -0
- package/src/pipeline-types.ts +647 -0
- package/src/pipeline-validation.ts +87 -0
- package/src/presentation-types.ts +23 -0
- package/src/presentation-utils.ts +397 -0
- package/src/producer-types.ts +188 -0
- package/src/progress-curve.ts +99 -0
- package/src/provider-directive-defaults.ts +69 -0
- package/src/reduce-strategy-registry.ts +121 -0
- package/src/reference-board-templates.ts +81 -0
- package/src/reference-roles.ts +153 -0
- package/src/reference-sheet/__tests__/board-to-column.test.ts +20 -0
- package/src/reference-sheet/__tests__/catalog.test.ts +50 -0
- package/src/reference-sheet/__tests__/cost.test.ts +38 -0
- package/src/reference-sheet/__tests__/no-drift.test.ts +28 -0
- package/src/reference-sheet/__tests__/panel-plan.test.ts +61 -0
- package/src/reference-sheet/__tests__/panel-prompts.test.ts +17 -0
- package/src/reference-sheet/__tests__/plan-generation.test.ts +72 -0
- package/src/reference-sheet/__tests__/presets.test.ts +54 -0
- package/src/reference-sheet/__tests__/types.test.ts +24 -0
- package/src/reference-sheet/catalog.ts +144 -0
- package/src/reference-sheet/cost.ts +37 -0
- package/src/reference-sheet/credit-id.ts +7 -0
- package/src/reference-sheet/index.ts +8 -0
- package/src/reference-sheet/panel-plan.ts +65 -0
- package/src/reference-sheet/panel-prompts.ts +14 -0
- package/src/reference-sheet/plan-generation.ts +79 -0
- package/src/reference-sheet/presets.ts +77 -0
- package/src/reference-sheet/types.ts +92 -0
- package/src/repeat-types.ts +97 -0
- package/src/resolve-field-mappings.ts +119 -0
- package/src/route-filter.ts +80 -0
- package/src/scene-helper-types.ts +249 -0
- package/src/scene-node-types.ts +281 -0
- package/src/scraper-actors.ts +57 -0
- package/src/scraper-output-schemas.ts +25 -0
- package/src/seasons.ts +45 -0
- package/src/selector.ts +864 -0
- package/src/settled-with-limit.ts +42 -0
- package/src/shot-element.ts +43 -0
- package/src/social-media-specs.ts +121 -0
- package/src/social-post.ts +24 -0
- package/src/sub-workflow-validation.ts +78 -0
- package/src/supported-fonts.ts +40 -0
- package/src/surround.ts +113 -0
- package/src/switchx-pricing.ts +33 -0
- package/src/text-separators.ts +59 -0
- package/src/to-connected-references.ts +77 -0
- package/src/types.ts +272 -0
- package/src/variant-job-id.ts +17 -0
- package/src/vehicles.ts +213 -0
- package/src/video-analysis-pricing.ts +74 -0
- package/src/video-analysis.ts +127 -0
- package/src/video-duration.ts +25 -0
- package/src/voice-changer-models.ts +36 -0
- package/src/voice-matcher-types.ts +37 -0
- package/src/voices.ts +92 -0
- package/src/weapons.ts +190 -0
- package/src/workflow-export.ts +153 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/freecut-protocol.ts","../src/model-catalog.ts","../src/model-constants.ts","../src/film-pricing.ts","../src/featured-entities.ts","../src/inpaint-region.ts","../src/ancestor-refs.ts","../src/character-usage-mode.ts","../src/extra-refs.ts","../src/flux2-pricing.ts","../src/credit-identifiers.ts","../src/credit-estimators/video-utils.ts","../src/video-duration.ts","../src/presentation-utils.ts","../src/clone-utils.ts","../src/group-aggregation.ts","../src/llm-models.ts","../src/progress-curve.ts","../src/route-filter.ts","../src/json-path.ts","../src/variant-job-id.ts","../src/pinterest-url.ts","../src/json-evaluator.ts","../src/node-refs.ts","../src/filter-condition.ts","../src/scraper-output-schemas.ts","../src/selector.ts","../src/repeat-types.ts","../src/settled-with-limit.ts","../src/surround.ts","../src/parameter-node-value.ts","../src/object-picker-types.ts","../src/object-aspect-defaults.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/loop-delimiter.ts","../src/generate-text-items.ts","../src/text-separators.ts","../src/list-sort.ts","../src/seasons.ts","../src/location-preset-catalog-map.ts","../src/component-types.ts","../src/social-post.ts","../src/node-default-mappings.ts","../src/node-mappable-fields.ts","../src/scraper-actors.ts","../src/condition-variables.ts","../src/generated-results.ts","../src/lottie-slots.ts","../src/lottie-overlay-catalog.ts","../src/inject-upstream.ts","../src/resolve-field-mappings.ts","../src/list-source-resolver.ts","../src/list-merge.ts","../src/social-media-specs.ts","../src/animals.ts","../src/furniture.ts","../src/character-facets.ts","../src/vehicles.ts","../src/weapons.ts","../src/multi-pick.ts","../src/caption-styles.ts","../src/i18n/types.ts","../src/i18n/index.ts","../src/node-runtime-keys.ts","../src/workflow-export.ts","../src/sub-workflow-validation.ts","../src/character-mention-slug.ts","../src/character-variant-assets.ts","../src/location-mention-slug.ts","../src/to-connected-references.ts","../src/character-aspect-defaults.ts","../src/entity-aspect-defaults.ts","../src/pipeline-defaults.ts","../src/scene-node-types.ts","../src/pipeline-types.ts","../src/pipeline-chat.ts","../src/pipeline-events.ts","../src/pipeline-state-types.ts","../src/pipeline-validation.ts","../src/voice-matcher-types.ts","../src/character-voice.ts","../src/entity-approval-types.ts","../src/image-critic-types.ts","../src/image-critic-node.ts","../src/scene-helper-types.ts","../src/provider-directive-defaults.ts","../src/lora-routing.ts","../src/reduce-strategy-registry.ts","../src/combine-transitions.ts","../src/audio-crossfade-curves.ts","../src/producer-types.ts","../src/voice-changer-models.ts","../src/node-preset-extract.ts","../src/node-preset-export.ts","../src/reference-sheet/types.ts","../src/entity-asset-types.ts","../src/reference-sheet/catalog.ts","../src/reference-sheet/panel-plan.ts","../src/reference-sheet/panel-prompts.ts","../src/reference-sheet/plan-generation.ts","../src/reference-sheet/credit-id.ts","../src/reference-sheet/presets.ts","../src/reference-sheet/cost.ts","../src/reference-board-templates.ts","../src/model-tree.ts","../src/audio-fx-presets.ts","../src/supported-fonts.ts","../src/entity-image-handle.ts","../src/reference-roles.ts","../src/video-analysis.ts","../src/video-analysis-pricing.ts"],"names":["clamp01","band","t","output","url","text","sec","ALLOWED_RESOLUTIONS","newRows","INPUT_FIELD_MAP","walk","copy","z"],"mappings":";;;AA8MO,IAAM,uBAAA,GAA2D;AAAA,EACtE,QAAA,EAAU,QAAA;AAAA,EACV,aAAA,EAAe,QAAA;AAAA,EACf,iBAAA,EAAmB,QAAA;AAAA,EACnB,YAAA,EAAc,MAAA;AAAA,EACd,cAAA,EAAgB,QAAA;AAAA;AAAA;AAAA;AAAA,EAIhB,gBAAA,EAAkB,UAAA;AAAA,EAClB,gBAAA,EAAkB;AACpB;;;ACnNO,IAAM,iBAAA,GAAoB;AAI1B,IAAM,oBAAA,GAAuB;AAC7B,IAAM,mBAAA,GAAsB;AAC5B,IAAM,oBAAA,GAAuB;AAG7B,IAAM,aAAA,GAAgB;AACtB,IAAM,uBAAA,GAA0B;AAChC,IAAM,uBAAA,GAA0B;AAChC,IAAM,sBAAA,GAAyB;;;AC6H/B,IAAM,qBAAA,GAAwD;AAAA;AAAA,EAEnE,EAAE,QAAQ,0CAAA,EAA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iC;AACzE,EAAA,MAAM,CAAA,GAAI,4BAAA,CAA6B,IAAA,CAAK,QAAQ,CAAA;AACpD,EAAA,OAAO,CAAA,GAAI,MAAA,CAAO,CAAA,CAAE,CAAC,CAAC,CAAA,GAAI,IAAA;AAC5B;AAEO,SAAS,wBAAwB,SAAA,EAA2B;AACjE,EAAA,OAAO,SAAA,IAAa,sBAAsB,UAAA,GAAa,CAAA,GAAI,IAAI,IAAA,CAAK,IAAA,CAAA,CAAM,SAAA,GAAY,UAAA,IAAc,aAAa,CAAA;AACnH","file":"index.js","sourcesContent":["/**\n * Generic node/edge interfaces for structural subtyping.\n * Both frontend WorkflowNode and backend SimpleNode satisfy these.\n */\n\nimport type { UsageMode } from \"./character-usage-mode.js\"\nimport type { LocationReferencePhotoKind } from \"./entity-asset-types.js\"\n\nexport interface GenericNode {\n id: string\n type: string\n /**\n * Canvas (React-Flow) position. The editor needs it to lay the node out —\n * without it React-Flow stacks every node at (0,0). Optional so non-canvas\n * callers (pure graph data) need not supply it.\n */\n position?: { x: number; y: number }\n /** Fixed canvas width the editor applies (e.g. 220 for generate-image/-video). */\n width?: number\n data: Record<string, unknown>\n hidden?: boolean\n}\n\nexport interface GenericEdge {\n /** Stable edge id — React-Flow requires one to render the connection. */\n id?: string\n source: string\n target: string\n sourceHandle?: string | null\n targetHandle?: string | null\n}\n\nexport interface CharacterDef {\n id: string\n name: string\n type: \"reference\" | \"description\"\n category?: string\n referenceImageUrl?: string\n description?: string\n}\n\n// ---------------------------------------------------------------------------\n// Reference image metadata.\n//\n// An \"identity\" = (imageIndex, label) — what role this image plays at a given\n// mention. The same image can appear under multiple identities (e.g. image 1\n// used both as `:dragon` and as `:background`). Tokens in the prompt are\n// `{image:N:label}`, with `{image:N}` as a backward-compat positional ref.\n// ---------------------------------------------------------------------------\n\nexport type IdentityFidelity = \"strict\" | \"balanced\" | \"loose\" | \"custom\"\n\nexport type ReferenceSource =\n | \"manual\"\n | \"wired-image\"\n | \"wired-character\"\n | \"wired-face\"\n | \"wired-object\"\n | \"wired-creature\"\n | \"wired-location\"\n\n/** Per-identity user override stored on the consumer node. */\nexport interface IdentityMeta {\n /** 1-based position of the source image. */\n imageIndex: number\n /** Role label this entry covers (e.g. \"object\", \"background\", \"person\"). */\n label: string\n fidelity?: IdentityFidelity\n /** Free-text directive used when fidelity === \"custom\" (replaces the preset). */\n customText?: string\n}\n\n/** Computed view of a single connected reference, ready for the prompt builder. */\nexport interface ConnectedReference {\n id: string\n defaultName: string\n source: ReferenceSource\n /** Optional rich text from upstream char/face/object/location node. */\n description?: string\n url: string\n /** Slug of the source character (e.g. \"kira\") when this entry came from a character node. */\n readonly characterSlug?: string\n /** Variant slug (e.g. \"smile\"). undefined = canonical/default. */\n readonly variantSlug?: string\n /** Character's canonical_description. Set on every entry from the same character (used for dedup). */\n readonly characterCanonicalDescription?: string | null\n /**\n * Resolved prompt-fragment for the elements (held-prop / styling / text /\n * pickers) wired into the SOURCE character node's Assets/Prompt handle. A\n * mode-INDEPENDENT sibling of `characterCanonicalDescription`: where the\n * canonical description is only emitted for identity-locking modes, this is\n * scene composition (\"holding a smartphone…\") and rides the character's\n * identity bullet in EVERY mode that emits one (only `none` — which emits no\n * bullet — drops it). Resolved at assembly time from the wiring (never stored\n * on the character record). Stamped onto every entry of the same character so\n * whichever entry produces the primary bullet carries it. Absent/empty →\n * byte-identical to the pre-elementInjection output.\n */\n readonly elementInjection?: string | null\n /**\n * Location's canonical_description. Set on every entry derived from a wired\n * Location node (canonical image + future per-variant entries from Phase 2 #2\n * @location:1:variant mention syntax). Mirrors `characterCanonicalDescription`\n * — the directive builder appends this to the `wired-location` ref's subject\n * line when the location's slug isn't in `suppressedCanonicalLocationIds`.\n */\n readonly locationCanonicalDescription?: string | null\n /** Slug of the source location (e.g. \"old-library\") when this entry came from a location node. Used by `suppressedCanonicalLocationIds` filtering. */\n readonly locationSlug?: string\n /**\n * Variant bucket for per-variant location entries (Phase 2 #2). One of the\n * 6 location asset buckets — \"timeOfDay\" / \"weather\" / \"seasons\" / \"angles\"\n * / \"lighting\" / \"atmosphereMotions\". `undefined` for the canonical\n * main-image entry.\n *\n * Used by `resolveLocationMentions` to find the entry matching a\n * `@oldlibrary:1:weather/rain` mention token (lookup key is\n * `${locationSlug}:${locationVariantBucket}/${locationVariantSlug}`).\n */\n readonly locationVariantBucket?: string\n /**\n * Variant slug for per-variant location entries (e.g. \"rain\", \"neon\"). The\n * raw variant `name` from the location node's bucket array, slugified via\n * `locationMentionSlug` so the resolver match is case-insensitive and\n * whitespace-tolerant (`\"light rain\"` ↔ `\"light-rain\"`). `undefined` for\n * the canonical main-image entry.\n */\n readonly locationVariantSlug?: string\n /** Display name for the variant in autocomplete UI (e.g. \"rain\", \"canonical\"). */\n readonly locationVariantDisplayName?: string\n /**\n * For user-uploaded reference photos on wired locations, the photo's\n * `kind` — one of the 6 `LocationReferencePhotoKind` values. Drives the\n * prompt-builder's subject-line annotation so the model knows the role\n * (wide-angle establishing shot vs. interior detail vs. mood-board\n * context). Mirrors `locationVariantBucket` but for user-uploaded refs\n * instead of generated per-variant assets.\n *\n * Reference-photo entries have THIS field set but `locationVariantBucket`\n * unset — that's how the connectedReferences filter at\n * `prompt-builder.ts` lines ~1011-1016 distinguishes them from\n * mention-only variant entries. Reference photos AUTO-ATTACH (they're\n * not gated by `@-mention`), so the filter must NOT drop them.\n */\n readonly locationReferencePhotoKind?: LocationReferencePhotoKind\n /** The asset's own description (per-variant). null for canonical entries. */\n readonly variantDescription?: string | null\n /** Display name for the variant in autocomplete UI (e.g. \"smile\", \"canonical\"). */\n readonly variantDisplayName?: string\n /**\n * Character node's `defaultUsageMode` propagated into every entry derived\n * from that node. Used by `resolveCharacterMentions` as the fallback when\n * the per-mention slug doesn't carry an explicit mode override. Absent for\n * non-character refs and for character entries built without a node context\n * (e.g. character-definition-only entries in legacy paths).\n */\n readonly defaultUsageMode?: UsageMode\n /**\n * Character node's HYBRID `defaultRole` (the role-dropdown pick: a\n * `REFERENCE_ROLE_PRESETS[\"wired-character\"]` value or a sanitized Custom\n * slug) propagated into every entry derived from that node. Read via\n * `resolveDefaultRole(defaultRole, defaultUsageMode, source)` at the hybrid\n * resolver sites — it takes precedence over `defaultUsageMode`. Absent for\n * non-character refs and for nodes that never set a role (fall back to the\n * `defaultUsageMode`-derived role, then the source default).\n */\n readonly defaultRole?: string\n /**\n * Marks an entry as a user-attached \"extra reference image\" (see the\n * `extraRefs` field on Generate/Modify/Image-to-Video/Text-to-Video/Video-to-Video\n * node data types in the frontend). Extras are auto-attached to the worker\n * `referenceImageUrls` AND get a dedicated directive line in the assembled\n * prompt:\n * - character-sourced extras of an already-emitted character →\n * \"Image N is the same subject as Image M, <description>.\"\n * - character-sourced extras of a previously-unseen character →\n * a canonical-style directive using the description as the descriptor\n * - manual-sourced extras →\n * \"Image N (reference): <description>.\"\n *\n * The `description` field carries the per-ref free-text the user typed.\n * Without this marker, character refs with a variantSlug are treated as\n * autocomplete-only (the legacy behavior — unmentioned variants don't\n * auto-attach), which is exactly what we DON'T want for explicit extras.\n */\n readonly isExtraRef?: boolean\n // ─── Character LoRA training (Cloud edition) ──────────────────────────────\n // Propagated from CharacterNodeData on the upstream character node. Used\n // by selectLoraRoutingForMentions (`@nodaro/shared` + backend mirror) to\n // decide whether to route generate-image through `flux-lora-character`\n // instead of reference-image injection.\n readonly loraReplicateVersion?: string | null\n readonly loraTriggerWord?: string | null\n readonly loraTrainingStatus?: string | null\n /**\n * Optional, opt-in identity-lock for this reference. When `enabled === true`,\n * a short fidelity line is prepended so the model preserves the subject's\n * exact identity. `text` overrides the built-in default (use `{ref}` as the\n * placeholder for the reference's binding, e.g. \"reference image A\"). Default\n * is OFF for EVERY source: absent or `enabled === false` emits no lock line.\n * The single new structured-shape field for external (API/MCP/SDK) parity.\n */\n readonly identityLock?: { enabled: boolean; text?: string }\n}\n\n/** Default label per source — used by `@` autocomplete and inventory fallback. */\nexport const DEFAULT_LABEL_BY_SOURCE: Record<ReferenceSource, string> = {\n \"manual\": \"object\",\n \"wired-image\": \"object\",\n \"wired-character\": \"person\",\n \"wired-face\": \"face\",\n \"wired-object\": \"object\",\n // A bound Creature (animal/beast/monster) — its directive reads as a living\n // subject (\"match anatomy, markings…\"), not a prop. See CREATURE_LABELS in\n // prompt-builder.ts.\n \"wired-creature\": \"creature\",\n \"wired-location\": \"background\",\n}\n\n// ---------------------------------------------------------------------------\n// Scene node data — minimal interface for buildScenePrompt.\n// Frontend SceneNodeDataType satisfies this via structural subtyping.\n// Backend casts Record<string, unknown> node data to this.\n// ---------------------------------------------------------------------------\n\nexport interface SceneCharacterEntry {\n readonly assetId: string\n readonly mood: string\n readonly action: string\n readonly positionInFrame?: \"left\" | \"center\" | \"right\" | \"foreground\" | \"background\"\n}\n\nexport interface SceneLocationEntry {\n readonly assetId: string\n readonly name?: string\n readonly isPrimary?: boolean\n readonly timeOfDay?: string\n readonly weather?: string\n readonly lighting?: string\n}\n\nexport interface SceneObjectEntry {\n readonly assetId: string\n readonly description?: string\n}\n\nexport interface SceneDialogueEntry {\n readonly characterName: string\n readonly text: string\n readonly emotion?: string\n}\n\nexport interface SceneData {\n readonly shotType: string\n readonly cameraAngle: string\n readonly aspectRatio: string\n readonly characters: readonly SceneCharacterEntry[]\n readonly locations?: readonly SceneLocationEntry[]\n readonly objects: readonly SceneObjectEntry[]\n readonly mood: readonly string[]\n readonly visualStyle: string\n readonly depthOfField: string\n readonly lensType: string\n readonly cameraMovement: string\n readonly colorPalette: readonly string[]\n readonly summary: string\n readonly dialogue?: readonly SceneDialogueEntry[]\n readonly directorNotes?: string\n readonly timeOfDay: string\n readonly weather: string\n readonly lighting: string\n}\n","// Single source of truth for the Nodaro <-> FreeCut iframe postMessage protocol.\n// Imported by app's freecut-editor-modal and Studio's ported modal so the wire\n// format cannot drift. The fork (Nodaro-ai/freecut-fork) mirrors these strings in\n// src/features/embedded/services/embedded-message-handler.ts + use-send-back.ts.\n\n// Nodaro (parent) -> FreeCut (iframe)\nexport const NODARO_LOAD_VIDEO = \"NODARO_LOAD_VIDEO\"\n// Multi-clip analog of NODARO_LOAD_VIDEO: lay N ordered urls on the timeline as\n// sequential clips (FreeCut fetches them itself). Used by Studio's production\n// \"Edit in FreeCut\" to assemble the whole cut.\nexport const NODARO_LOAD_TIMELINE = \"NODARO_LOAD_TIMELINE\"\nexport const NODARO_IMPORT_FILES = \"NODARO_IMPORT_FILES\"\nexport const NODARO_RESET_PROJECT = \"NODARO_RESET_PROJECT\"\n\n// FreeCut (iframe) -> Nodaro (parent)\nexport const FREECUT_READY = \"FREECUT_READY\"\nexport const FREECUT_EXPORT_COMPLETE = \"FREECUT_EXPORT_COMPLETE\"\nexport const FREECUT_EXPORT_PROGRESS = \"FREECUT_EXPORT_PROGRESS\" // reserved; fork emits it, v1 parents ignore it\nexport const FREECUT_REQUEST_IMPORT = \"FREECUT_REQUEST_IMPORT\"\n\nexport interface FreecutImportFile {\n readonly name: string\n readonly type: string\n readonly size: number\n readonly buffer: ArrayBuffer\n}\n\nexport interface NodaroLoadVideoPayload {\n readonly videoUrl: string\n readonly videoBuffer?: ArrayBuffer\n readonly projectJson?: unknown\n readonly additionalFiles?: ReadonlyArray<FreecutImportFile>\n}\n\nexport interface NodaroLoadTimelinePayload {\n // Ordered clip urls; FreeCut fetches each and lays them end-to-end on the timeline.\n readonly clips: ReadonlyArray<string>\n}\n\nexport interface FreecutExportCompletePayload {\n readonly videoBuffer: ArrayBuffer\n readonly projectJson?: unknown\n}\n\nexport interface FreecutExportProgressPayload {\n readonly percent: number\n}\n\nexport interface FreecutRequestImportPayload {\n readonly accept?: string\n readonly multiple?: boolean\n}\n","/**\n * Model catalog — single source of truth for what each Nodaro-exposed model\n * is, who made it, what it's good for, and which knobs it accepts.\n *\n * Consumed by:\n * - Backend MCP `list_models` tool (renders the nested per-kind / per-family\n * response so Claude can pick the right model for a user's intent)\n * - (future) Frontend config panels — today they read parallel registries\n * in `frontend/src/components/editor/config-panels/model-options.ts`; a\n * follow-up will migrate them to import from here.\n *\n * Authoring rules:\n * - Keep `description` to one line (≤120 chars). It's what Claude reads to\n * decide which model to use.\n * - `useCases` is a small set of short tags (1-3 words) — verbs/nouns Claude\n * can match against user intent (\"typography\", \"character\", \"fast\",\n * \"cinematic\"). Stay consistent across entries: don't write \"text\" in one\n * and \"typography\" in another.\n * - `aspectRatios` / `resolutions` / `qualities` only appear when the model\n * actually exposes that lever (e.g., Nano Banana base has no `resolution`).\n * - `durations` is in seconds.\n * - `pricing[0]` is ALWAYS the default variant (the bare id without a\n * composite suffix like `:4K` or `:high`).\n * - Costs are sourced from `STATIC_CREDIT_COSTS` (see backend\n * `src/billing/credits.ts`). Keep them in sync if the table changes.\n * - After editing `MODEL_CATALOG` or `MODEL_RECOMMENDATIONS`, run\n * `npm run gen:skills` (from `backend/`) to refresh the public\n * `docs/choosing-models.md` guide. CI (`gen:skills:check`) fails on drift.\n */\n\nexport type ModelKind = \"image\" | \"video\" | \"audio\"\n\nexport type ModelMode =\n // image\n | \"t2i\"\n | \"i2i\"\n | \"edit\"\n | \"upscale\"\n | \"remove-bg\"\n // video\n | \"i2v\"\n | \"t2v\"\n | \"v2v\"\n | \"extend\"\n | \"motion-transfer\"\n | \"lip-sync\"\n | \"video-upscale\"\n // audio\n | \"tts\"\n | \"music\"\n | \"sfx\"\n | \"stt\"\n | \"voice-clone\"\n | \"voice-design\"\n | \"voice-changer\"\n | \"isolation\"\n | \"dubbing\"\n | \"forced-alignment\"\n // video analysis\n | \"video-analysis\"\n\nexport interface PriceVariant {\n /** Composite identifier as it appears in `STATIC_CREDIT_COSTS`. */\n identifier: string\n /** Credits charged at reservation. */\n credits: number\n /** Short human-readable note describing this variant (\"1K default\", \"4K\", \"with audio\"). */\n note?: string\n}\n\nexport interface ModelCatalogEntry {\n id: string\n kind: ModelKind\n /**\n * Operations this model supports. Many video models (minimax, veo3,\n * seedance) support BOTH i2v AND t2v under the same id — the route handler\n * picks which KIE endpoint to hit based on whether an image was supplied.\n * For those, list both modes here so MCP filters and frontend pickers see\n * the model in either context.\n */\n modes: readonly ModelMode[]\n /** Vendor / lab that produced the model. Used for UI grouping. */\n family: string\n /** Display name (NOT the id — the id is the API enum value). */\n label: string\n /**\n * Model LINE for the add-node Models tab — the brand-agnostic product line a\n * user thinks in (\"Nano Banana\", \"Flux\", \"VEO\", \"Kling\", \"ElevenLabs\").\n * Distinct from `family` (the lab: Google covers Nano Banana + Imagen + VEO).\n * REQUIRED for every node-creatable model; a completeness guard in\n * `@nodaro/shared` (model-tree.test.ts) fails if one is missing.\n */\n series?: string\n /**\n * The value written into the creating node's data field when this model is\n * picked from the Models tab, for models whose catalog id differs from the\n * stored value. Only `suno-generate` diverges today (id `suno-v5` → `data.model`\n * \"V5\"). Omit when the id IS the stored value (the common case).\n */\n dataValue?: string\n /** One-liner. Visible to Claude in MCP `list_models` output. */\n description: string\n /** Short tags Claude matches against user intent. */\n useCases: readonly string[]\n /** Capabilities flags: \"reference-image\", \"end-frame\", \"audio\", etc. */\n features?: readonly string[]\n aspectRatios?: readonly string[]\n resolutions?: readonly string[]\n qualities?: readonly string[]\n durations?: readonly number[]\n pricing: readonly PriceVariant[]\n /** Editorial highlight — \"best in tier\". Surfaces in MCP output as a ⭐. */\n featured?: boolean\n /**\n * Per-model overrides for the global value label decorations (e.g. Hailuo\n * 2.3 Pro labels its 1080P resolution as \"1080P (6s max)\" because the\n * model caps long durations at lower resolution). Falls back to\n * `MODEL_VALUE_LABELS` for values not listed here.\n */\n valueLabels?: Record<string, string>\n /**\n * Hide from MCP `list_models` output and tool model enums. Used for legacy\n * model versions superseded by newer entries — they remain in the catalog\n * (and accessible via direct API / frontend pickers for back-compat) but\n * stop showing up in Claude.ai's model picker, which keeps the surface\n * tight and steers the agent to the current generation.\n *\n * Frontend pickers ignore this flag.\n */\n mcpHidden?: boolean\n}\n\n/**\n * Editorial recommendations — short \"best for X\" picks Claude can echo back\n * to the user when they don't know which model to use. Surfaces as a \"Quick\n * recommendations\" footer in MCP `list_models` output.\n */\nexport interface ModelRecommendation {\n intent: string\n modelIds: readonly string[]\n note: string\n}\n\nexport const MODEL_RECOMMENDATIONS: readonly ModelRecommendation[] = [\n // image\n { intent: \"best for typography / logos / text-heavy\", modelIds: [\"nano-banana-pro\", \"gpt-image-2\"], note: \"Nano Banana Pro for diagrams / complex text; GPT Image 2 for logos and short copy.\" },\n { intent: \"cheapest realistic image\", modelIds: [\"z-image\", \"qwen\", \"imagen4-fast\"], note: \"Z-Image is the cheapest at 1 credit. Qwen / Imagen4 Fast for slightly higher quality.\" },\n { intent: \"highest fidelity image\", modelIds: [\"nano-banana-pro\", \"imagen4-ultra\", \"flux-flex\"], note: \"Pick by family preference; all three are premium tiers.\" },\n { intent: \"image edit / restyle\", modelIds: [\"flux-kontext\", \"ideogram-remix\", \"seedream-5-lite-i2i\"], note: \"Flux Kontext preserves identity; Ideogram Remix is character-aware; Seedream 5 Lite for instruction-based edits.\" },\n { intent: \"highest-resolution image (4K / 8K)\", modelIds: [\"topaz-image-upscale\", \"nano-banana-pro\", \"gpt-image-2\"], note: \"Generate at native then Topaz upscale for 8K.\" },\n { intent: \"background removal / cutout\", modelIds: [\"recraft-remove-bg\"], note: \"1 credit, no prompt needed.\" },\n // video\n { intent: \"best cinematic video\", modelIds: [\"veo3\", \"kling-3.0\", \"seedance-2\"], note: \"VEO 3.1 Quality for premium narrative; Kling 3.0 for music-synced motion; Seedance 2 for reference-driven consistency.\" },\n { intent: \"cheap batch video clips\", modelIds: [\"veo3.1\", \"wan-turbo\", \"bytedance-lite\"], note: \"VEO 3.1 Fast is the best price/quality balance with native audio.\" },\n { intent: \"video with start + end frame\", modelIds: [\"veo3\", \"veo3.1\", \"kling-turbo\", \"minimax\", \"hailuo-standard\", \"seedance-2\"], note: \"All listed support an end frame; VEO uses imageUrls[start, end].\" },\n { intent: \"music / song generation\", modelIds: [\"suno-v5\", \"suno\"], note: \"Suno v5 has better vocal quality at the same price.\" },\n { intent: \"voice over / narration\", modelIds: [\"elevenlabs-v3\", \"elevenlabs-turbo\"], note: \"v3 supports [audio tags] for emotion; Turbo is cheaper for plain narration.\" },\n { intent: \"lip-sync a portrait to audio\", modelIds: [\"kling-avatar-pro\", \"kling-avatar\", \"infinitalk\"], note: \"Pro for best mouth shape; InfiniTalk for resolution control.\" },\n { intent: \"transcription / captions\", modelIds: [\"elevenlabs-stt\"], note: \"Word-level timestamps available.\" },\n { intent: \"motion transfer (drive a subject by another video)\", modelIds: [\"motion-transfer\", \"kling-3.0-motion\"], note: \"Kling 2.6 base is cheap; Kling 3.0 is premium.\" },\n] as const\n\n// =============================================================================\n// Aspect ratio presets (mirrored from frontend's model-options.ts so backend\n// can consume them. Keep in sync when adding a new ratio set.)\n// =============================================================================\nconst NANO_BANANA_RATIOS = [\"1:1\", \"16:9\", \"9:16\", \"4:3\", \"3:4\", \"3:2\", \"2:3\", \"4:5\", \"5:4\", \"21:9\"] as const\n// Note: these arrays are synchronized with the frontend's\n// `model-options.ts` constants of the same names. The frontend now imports\n// them via the `getAspectRatioOptions(modelId)` helper; if you update one\n// you no longer need to touch the other.\nconst FLUX_RATIOS = [\"1:1\", \"16:9\", \"9:16\", \"4:3\", \"3:4\", \"3:2\", \"2:3\"] as const\nconst KONTEXT_RATIOS = [\"1:1\", \"16:9\", \"9:16\", \"4:3\", \"3:4\", \"21:9\"] as const\nconst GROK_RATIOS = [\"1:1\", \"16:9\", \"9:16\", \"3:2\", \"2:3\"] as const\nconst GPT_IMAGE_RATIOS = [\"1:1\", \"3:2\", \"2:3\"] as const\nconst GPT_IMAGE_2_RATIOS = [\"auto\", \"1:1\", \"16:9\", \"9:16\", \"4:3\", \"3:4\"] as const\nconst IMAGEN4_RATIOS = [\"1:1\", \"16:9\", \"9:16\", \"4:3\", \"3:4\"] as const\nconst IDEOGRAM_RATIOS = [\"1:1\", \"16:9\", \"9:16\", \"4:3\", \"3:4\"] as const\nconst SEEDREAM_RATIOS = [\"1:1\", \"16:9\", \"9:16\", \"4:3\", \"3:4\", \"3:2\", \"2:3\", \"21:9\"] as const\nconst Z_IMAGE_RATIOS = [\"1:1\", \"16:9\", \"9:16\", \"4:3\", \"3:4\"] as const\n\nconst VIDEO_RATIOS_HV = [\"16:9\", \"9:16\"] as const\nconst VIDEO_RATIOS_HVS = [\"16:9\", \"9:16\", \"1:1\"] as const\nconst WAN_27_IMAGE_RATIOS = [\"1:1\", \"16:9\", \"9:16\", \"4:3\", \"3:4\", \"21:9\", \"8:1\", \"1:8\"] as const\nconst VIDEO_RATIOS_HVS345 = [\"16:9\", \"9:16\", \"1:1\", \"4:3\", \"3:4\"] as const\n// Seedance 2.x only — KIE accepts the full fixed-ratio set incl. 21:9\n// (docs.kie.ai/market/bytedance/seedance-2). Kept separate from HVS so the\n// wider set can't leak to models that don't support it.\nconst VIDEO_RATIOS_SEEDANCE_2 = [\"16:9\", \"9:16\", \"1:1\", \"4:3\", \"3:4\", \"21:9\", \"adaptive\"] as const\n\n// =============================================================================\n// IMAGE MODELS\n// =============================================================================\nconst IMAGE_MODELS: Record<string, ModelCatalogEntry> = {\n // ── Google Nano Banana ──\n \"nano-banana\": {\n id: \"nano-banana\",\n kind: \"image\",\n // Accepts a reference image via image_input — works as both t2i (no\n // ref) and i2i (with ref) under the same id, so list in both modes.\n modes: [\"t2i\", \"i2i\"] as const,\n family: \"Google\",\n label: \"Nano Banana\",\n series: \"Nano Banana\",\n description: \"Budget-friendly realistic generation. Wide aspect-ratio support up to 21:9.\",\n useCases: [\"realistic\", \"general\", \"fast\"],\n features: [\"reference-image\"],\n aspectRatios: NANO_BANANA_RATIOS,\n pricing: [{ identifier: \"nano-banana\", credits: 1, note: \"1K\" }],\n mcpHidden: true,\n },\n \"nano-banana-2\": {\n id: \"nano-banana-2\",\n kind: \"image\",\n // Accepts reference images via image_input — same as the rest of the\n // Nano Banana family — so reachable for both t2i and i2i.\n modes: [\"t2i\", \"i2i\"] as const,\n family: \"Google\",\n label: \"Nano Banana 2\",\n series: \"Nano Banana\",\n description: \"Newer Nano Banana with native resolution control (1K/2K/4K) and Google Search context.\",\n useCases: [\"realistic\", \"high-res\", \"factual\"],\n features: [\"reference-image\", \"google-search\"],\n aspectRatios: NANO_BANANA_RATIOS,\n resolutions: [\"1K\", \"2K\", \"4K\"],\n pricing: [\n { identifier: \"nano-banana-2\", credits: 4, note: \"1K default\" },\n { identifier: \"nano-banana-2:2K\", credits: 5, note: \"2K\" },\n { identifier: \"nano-banana-2:4K\", credits: 5, note: \"4K\" },\n ],\n },\n \"nano-banana-pro\": {\n id: \"nano-banana-pro\",\n kind: \"image\",\n modes: [\"t2i\", \"i2i\"] as const,\n family: \"Google\",\n label: \"Nano Banana Pro\",\n series: \"Nano Banana\",\n description: \"Top-tier Nano Banana — best for text rendering, diagrams, and complex compositions.\",\n useCases: [\"typography\", \"diagrams\", \"premium\", \"text-heavy\"],\n features: [\"reference-image\"],\n aspectRatios: NANO_BANANA_RATIOS,\n resolutions: [\"1K\", \"2K\", \"4K\"],\n pricing: [\n { identifier: \"nano-banana-pro\", credits: 5, note: \"1K / 2K\" },\n { identifier: \"nano-banana-pro:4K\", credits: 6, note: \"4K\" },\n ],\n featured: true,\n },\n \"nano-banana-edit\": {\n id: \"nano-banana-edit\",\n kind: \"image\",\n modes: [\"edit\"] as const,\n family: \"Google\",\n label: \"Nano Banana Edit\",\n series: \"Nano Banana\",\n description: \"Image-to-image edits via Google's Nano Banana family. Good general-purpose editor.\",\n useCases: [\"edit\", \"remix\", \"general\"],\n features: [\"reference-image\"],\n aspectRatios: NANO_BANANA_RATIOS,\n pricing: [{ identifier: \"nano-banana-edit\", credits: 2 }],\n },\n\n // ── Black Forest Labs (Flux) ──\n \"flux\": {\n id: \"flux\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Black Forest Labs\",\n label: \"Flux 2 Pro\",\n series: \"Flux\",\n description: \"Flux 2 Pro text-to-image. Strong realism, fast. Resolution lever to 2K.\",\n useCases: [\"realistic\", \"general\"],\n features: [\"reference-image\"],\n aspectRatios: FLUX_RATIOS,\n resolutions: [\"1K\", \"2K\"],\n pricing: [\n { identifier: \"flux\", credits: 2, note: \"1K default\" },\n { identifier: \"flux:2K\", credits: 2, note: \"2K\" },\n ],\n },\n \"flux-flex\": {\n id: \"flux-flex\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Black Forest Labs\",\n label: \"Flux 2 Flex\",\n series: \"Flux\",\n description: \"Flux 2 Flex — premium fidelity, more flexible composition. Pricier than Pro.\",\n useCases: [\"premium\", \"fidelity\", \"realistic\"],\n features: [\"reference-image\"],\n aspectRatios: FLUX_RATIOS,\n resolutions: [\"1K\", \"2K\"],\n pricing: [\n { identifier: \"flux-flex\", credits: 4, note: \"1K default\" },\n { identifier: \"flux-flex:2K\", credits: 6, note: \"2K\" },\n ],\n },\n \"flux-i2i\": {\n id: \"flux-i2i\",\n kind: \"image\",\n modes: [\"i2i\"] as const,\n family: \"Black Forest Labs\",\n label: \"Flux 2 Flex (I2I)\",\n series: \"Flux\",\n description: \"Image-to-image with Flux Flex. Honors source image structure while applying prompt.\",\n useCases: [\"edit\", \"restyle\", \"transform\"],\n features: [\"reference-image\"],\n aspectRatios: FLUX_RATIOS,\n resolutions: [\"1K\", \"2K\"],\n pricing: [\n { identifier: \"flux-i2i\", credits: 4, note: \"1K default\" },\n { identifier: \"flux-i2i:2K\", credits: 6, note: \"2K\" },\n ],\n },\n \"flux-pro-i2i\": {\n id: \"flux-pro-i2i\",\n kind: \"image\",\n modes: [\"i2i\"] as const,\n family: \"Black Forest Labs\",\n label: \"Flux 2 Pro (I2I)\",\n series: \"Flux\",\n description: \"Image-to-image with Flux Pro. Cheaper than Flex variant, good general edits.\",\n useCases: [\"edit\", \"restyle\"],\n features: [\"reference-image\"],\n aspectRatios: FLUX_RATIOS,\n resolutions: [\"1K\", \"2K\"],\n pricing: [\n { identifier: \"flux-pro-i2i\", credits: 2, note: \"1K default\" },\n { identifier: \"flux-pro-i2i:2K\", credits: 2, note: \"2K\" },\n ],\n },\n \"flux-kontext\": {\n id: \"flux-kontext\",\n kind: \"image\",\n // Kontext supports both pure t2i (no input image) and edit (with input).\n modes: [\"t2i\", \"edit\"] as const,\n family: \"Black Forest Labs\",\n label: \"Flux Kontext Pro\",\n series: \"Flux\",\n description: \"Context-aware editing and style transfer. Strong at preserving subject identity through edits.\",\n useCases: [\"edit\", \"style-transfer\", \"preserve-identity\"],\n features: [\"reference-image\"],\n aspectRatios: KONTEXT_RATIOS,\n pricing: [{ identifier: \"flux-kontext\", credits: 2 }],\n },\n \"flux-kontext-max\": {\n id: \"flux-kontext-max\",\n kind: \"image\",\n modes: [\"t2i\", \"edit\"] as const,\n family: \"Black Forest Labs\",\n label: \"Flux Kontext Max\",\n series: \"Flux\",\n description: \"Premium Kontext — highest fidelity context-aware edits.\",\n useCases: [\"edit\", \"style-transfer\", \"premium\"],\n features: [\"reference-image\"],\n aspectRatios: KONTEXT_RATIOS,\n pricing: [{ identifier: \"flux-kontext-max\", credits: 4 }],\n },\n // ── Replicate \"Open\" (uncensored) — run direct via Replicate, not KIE ──\n \"flux-2-klein\": {\n id: \"flux-2-klein\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Black Forest Labs\",\n label: \"Flux 2 Klein (Open)\",\n series: \"Flux\",\n description: \"Open Flux 2 9B from BFL — fast, no safety filter. Runs direct on Replicate.\",\n useCases: [\"realistic\", \"fast\", \"unfiltered\"],\n features: [\"reference-image\"],\n aspectRatios: FLUX_RATIOS,\n resolutions: [\"0.5 MP\", \"1 MP\", \"2 MP\", \"4 MP\"],\n pricing: [\n { identifier: \"flux-2-klein\", credits: 1 }, // 1MP 0ref (default)\n { identifier: \"flux-2-klein:1MP:0ref\", credits: 1 }, // min\n { identifier: \"flux-2-klein:4MP:8ref\", credits: 11 }, // max\n ],\n },\n \"kontext-multi\": {\n id: \"kontext-multi\",\n kind: \"image\",\n modes: [\"i2i\", \"edit\"] as const,\n family: \"Black Forest Labs\",\n label: \"Kontext Multi (Open)\",\n series: \"Flux\",\n description: \"Multi-image Flux Kontext Pro via Replicate — up to 4 input images, no safety filter.\",\n useCases: [\"edit\", \"multi-reference\", \"unfiltered\"],\n features: [\"reference-image\"],\n aspectRatios: KONTEXT_RATIOS,\n pricing: [{ identifier: \"kontext-multi\", credits: 3 }],\n },\n \"flux-2-pro\": {\n id: \"flux-2-pro\",\n kind: \"image\",\n modes: [\"t2i\", \"i2i\"] as const,\n family: \"Black Forest Labs\",\n label: \"Flux 2 Pro (Safety Tolerance)\",\n series: \"Flux\",\n description: \"BFL Flux 2 Pro flagship via Replicate — exposes the `safety_tolerance` lever pinned to 5 (max for Pro). Accepts up to 4 reference images.\",\n useCases: [\"realistic\", \"high-quality\", \"unfiltered\", \"reference\"],\n features: [\"reference-image\"],\n aspectRatios: FLUX_RATIOS,\n resolutions: [\"0.5 MP\", \"1 MP\", \"2 MP\", \"4 MP\"],\n pricing: [\n { identifier: \"flux-2-pro\", credits: 3 }, // 2MP 0ref (default)\n { identifier: \"flux-2-pro:0.5MP:0ref\", credits: 2 }, // min\n { identifier: \"flux-2-pro:4MP:8ref\", credits: 28 }, // max\n ],\n },\n \"flux-2-max\": {\n id: \"flux-2-max\",\n kind: \"image\",\n modes: [\"t2i\", \"i2i\"] as const,\n family: \"Black Forest Labs\",\n label: \"Flux 2 Max (Safety Tolerance)\",\n series: \"Flux\",\n description: \"BFL Flux 2 Max — even larger sibling of Pro via Replicate, safety_tolerance=5, up to 8 reference images. Variable pricing by MP and ref count.\",\n useCases: [\"realistic\", \"high-quality\", \"unfiltered\", \"multi-reference\"],\n features: [\"reference-image\"],\n aspectRatios: FLUX_RATIOS,\n resolutions: [\"0.5 MP\", \"1 MP\", \"2 MP\", \"4 MP\"],\n pricing: [\n { identifier: \"flux-2-max\", credits: 7 }, // 2MP 0ref (default)\n { identifier: \"flux-2-max:0.5MP:0ref\", credits: 2 }, // min\n { identifier: \"flux-2-max:4MP:8ref\", credits: 62 }, // max\n ],\n },\n\n // ── OpenAI (GPT Image) ──\n \"gpt-image\": {\n id: \"gpt-image\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"OpenAI\",\n label: \"GPT Image 1.5\",\n series: \"GPT Image\",\n description: \"Best for text rendering, typography, logos, and graphic design. Limited aspect ratios.\",\n useCases: [\"typography\", \"logo\", \"graphic-design\", \"text-heavy\"],\n features: [\"reference-image\"],\n aspectRatios: GPT_IMAGE_RATIOS,\n qualities: [\"medium\", \"high\"],\n pricing: [\n { identifier: \"gpt-image\", credits: 4, note: \"medium default\" },\n { identifier: \"gpt-image:high\", credits: 6, note: \"high quality\" },\n ],\n valueLabels: { \"3:2\": \"3:2 (Landscape)\", \"2:3\": \"2:3 (Portrait)\" },\n mcpHidden: true,\n },\n \"gpt-image-i2i\": {\n id: \"gpt-image-i2i\",\n kind: \"image\",\n modes: [\"i2i\"] as const,\n family: \"OpenAI\",\n label: \"GPT Image 1.5 (I2I)\",\n series: \"GPT Image\",\n description: \"Image-to-image with GPT Image 1.5. Good text-aware edits.\",\n useCases: [\"edit\", \"typography\", \"remix\"],\n features: [\"reference-image\"],\n aspectRatios: GPT_IMAGE_RATIOS,\n qualities: [\"medium\", \"high\"],\n pricing: [\n { identifier: \"gpt-image-i2i\", credits: 4, note: \"medium default\" },\n { identifier: \"gpt-image-i2i:high\", credits: 6, note: \"high quality\" },\n ],\n valueLabels: { \"3:2\": \"3:2 (Landscape)\", \"2:3\": \"2:3 (Portrait)\" },\n mcpHidden: true,\n },\n \"gpt-image-2\": {\n id: \"gpt-image-2\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"OpenAI\",\n label: \"GPT Image 2\",\n series: \"GPT Image\",\n description: \"Next-gen GPT Image — broader aspect ratios, resolution-based pricing (1K/2K/4K).\",\n useCases: [\"typography\", \"high-res\", \"general\"],\n features: [\"reference-image\"],\n aspectRatios: GPT_IMAGE_2_RATIOS,\n resolutions: [\"1K\", \"2K\", \"4K\"],\n pricing: [\n { identifier: \"gpt-image-2\", credits: 1, note: \"1K default\" },\n { identifier: \"gpt-image-2:2K\", credits: 3, note: \"2K\" },\n { identifier: \"gpt-image-2:4K\", credits: 6, note: \"4K\" },\n ],\n },\n \"gpt-image-2-i2i\": {\n id: \"gpt-image-2-i2i\",\n kind: \"image\",\n modes: [\"i2i\"] as const,\n family: \"OpenAI\",\n label: \"GPT Image 2 (I2I)\",\n series: \"GPT Image\",\n description: \"Image-to-image with GPT Image 2.\",\n useCases: [\"edit\", \"high-res\"],\n features: [\"reference-image\"],\n aspectRatios: GPT_IMAGE_2_RATIOS,\n resolutions: [\"1K\", \"2K\", \"4K\"],\n pricing: [\n { identifier: \"gpt-image-2-i2i\", credits: 1, note: \"1K default\" },\n { identifier: \"gpt-image-2-i2i:2K\", credits: 3, note: \"2K\" },\n { identifier: \"gpt-image-2-i2i:4K\", credits: 6, note: \"4K\" },\n ],\n },\n\n // ── Ideogram ──\n // Ideogram models use a `rendering_speed` (TURBO / BALANCED / QUALITY)\n // dimension that's distinct from the `quality` lever — frontend exposes\n // it via a separate dropdown — so we don't model it under `qualities`.\n // The composite pricing identifiers (`ideogram-v3:TURBO`, etc.) capture\n // the per-tier credit cost without claiming Claude can pick it from\n // the MCP tool's `quality` enum.\n \"ideogram-v3\": {\n id: \"ideogram-v3\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Ideogram\",\n label: \"Ideogram V3\",\n series: \"Ideogram\",\n description: \"Strong typography and stylized illustration. Speed/quality tiered (TURBO/BALANCED/QUALITY).\",\n useCases: [\"typography\", \"illustration\", \"stylized\"],\n aspectRatios: IDEOGRAM_RATIOS,\n pricing: [\n { identifier: \"ideogram-v3\", credits: 2, note: \"BALANCED default\" },\n { identifier: \"ideogram-v3:TURBO\", credits: 1, note: \"fastest\" },\n { identifier: \"ideogram-v3:QUALITY\", credits: 3, note: \"best quality\" },\n ],\n },\n \"ideogram-edit\": {\n id: \"ideogram-edit\",\n kind: \"image\",\n modes: [\"edit\"] as const,\n family: \"Ideogram\",\n label: \"Ideogram Edit\",\n series: \"Ideogram\",\n description: \"Inpainting / mask-based editing with Ideogram. Pair with a mask URL.\",\n useCases: [\"edit\", \"inpaint\", \"typography\"],\n features: [\"reference-image\", \"mask\"],\n // No aspectRatios — Ideogram Edit takes output dimensions from the input\n // image + mask. Backend strips aspect_ratio for this provider.\n pricing: [\n { identifier: \"ideogram-edit\", credits: 5, note: \"BALANCED default\" },\n { identifier: \"ideogram-edit:TURBO\", credits: 3, note: \"fastest\" },\n { identifier: \"ideogram-edit:QUALITY\", credits: 6, note: \"best quality\" },\n ],\n },\n \"ideogram-remix\": {\n id: \"ideogram-remix\",\n kind: \"image\",\n modes: [\"i2i\"] as const,\n family: \"Ideogram\",\n label: \"Ideogram Remix\",\n series: \"Ideogram\",\n description: \"Ideogram remix — character-aware restyling driven by reference images.\",\n useCases: [\"remix\", \"character\", \"stylized\"],\n features: [\"reference-image\"],\n aspectRatios: IDEOGRAM_RATIOS,\n pricing: [\n { identifier: \"ideogram-remix\", credits: 5, note: \"BALANCED default\" },\n { identifier: \"ideogram-remix:TURBO\", credits: 3, note: \"fastest\" },\n { identifier: \"ideogram-remix:QUALITY\", credits: 6, note: \"best quality\" },\n ],\n },\n \"ideogram-reframe\": {\n id: \"ideogram-reframe\",\n kind: \"image\",\n modes: [\"edit\"] as const,\n family: \"Ideogram\",\n label: \"Ideogram Reframe\",\n series: \"Ideogram\",\n description: \"Outpaint / reframe to a new aspect ratio while preserving subject.\",\n useCases: [\"outpaint\", \"reframe\"],\n features: [\"reference-image\"],\n aspectRatios: IDEOGRAM_RATIOS,\n pricing: [\n { identifier: \"ideogram-reframe\", credits: 2, note: \"BALANCED default\" },\n { identifier: \"ideogram-reframe:TURBO\", credits: 1, note: \"fastest\" },\n { identifier: \"ideogram-reframe:QUALITY\", credits: 3, note: \"best quality\" },\n ],\n },\n\n // ── Google Imagen ──\n \"imagen4\": {\n id: \"imagen4\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Google\",\n label: \"Imagen 4\",\n series: \"Imagen\",\n description: \"Google's Imagen 4 — strong photographic quality and prompt fidelity.\",\n useCases: [\"photographic\", \"realistic\"],\n aspectRatios: IMAGEN4_RATIOS,\n pricing: [{ identifier: \"imagen4\", credits: 2 }],\n },\n \"imagen4-fast\": {\n id: \"imagen4-fast\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Google\",\n label: \"Imagen 4 Fast\",\n series: \"Imagen\",\n description: \"Cheaper / quicker Imagen 4 tier.\",\n useCases: [\"fast\", \"realistic\", \"general\"],\n aspectRatios: IMAGEN4_RATIOS,\n pricing: [{ identifier: \"imagen4-fast\", credits: 1 }],\n },\n \"imagen4-ultra\": {\n id: \"imagen4-ultra\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Google\",\n label: \"Imagen 4 Ultra\",\n series: \"Imagen\",\n description: \"Premium Imagen 4 — highest fidelity, slower / more credits.\",\n useCases: [\"premium\", \"photographic\"],\n aspectRatios: IMAGEN4_RATIOS,\n pricing: [{ identifier: \"imagen4-ultra\", credits: 3 }],\n },\n\n // ── Bytedance Seedream ──\n \"seedream\": {\n id: \"seedream\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Bytedance\",\n label: \"Seedream 4.5\",\n series: \"Seedream\",\n description: \"Bytedance's Seedream 4.5 — precise control, high resolution at 4K via :high.\",\n useCases: [\"realistic\", \"high-res\", \"control\"],\n features: [\"reference-image\"],\n aspectRatios: SEEDREAM_RATIOS,\n qualities: [\"basic\", \"high\"],\n pricing: [\n { identifier: \"seedream\", credits: 2, note: \"basic / 2K default\" },\n { identifier: \"seedream:high\", credits: 4, note: \"high / 4K\" },\n ],\n mcpHidden: true,\n },\n \"seedream-edit\": {\n id: \"seedream-edit\",\n kind: \"image\",\n modes: [\"edit\"] as const,\n family: \"Bytedance\",\n label: \"Seedream 4.5 Edit\",\n series: \"Seedream\",\n description: \"Image editing / transforms via Seedream 4.5.\",\n useCases: [\"edit\", \"transform\"],\n features: [\"reference-image\"],\n aspectRatios: SEEDREAM_RATIOS,\n qualities: [\"basic\", \"high\"],\n pricing: [\n { identifier: \"seedream-edit\", credits: 2, note: \"basic default\" },\n { identifier: \"seedream-edit:high\", credits: 4, note: \"high quality\" },\n ],\n mcpHidden: true,\n },\n \"seedream-5-lite\": {\n id: \"seedream-5-lite\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Bytedance\",\n label: \"Seedream 5 Lite\",\n series: \"Seedream\",\n description: \"Newer Seedream 5 Lite — instruction-based generation, visual reasoning.\",\n useCases: [\"realistic\", \"instruction\"],\n features: [\"reference-image\"],\n aspectRatios: SEEDREAM_RATIOS,\n qualities: [\"basic\", \"high\"],\n pricing: [\n { identifier: \"seedream-5-lite\", credits: 2, note: \"basic default\" },\n { identifier: \"seedream-5-lite:high\", credits: 5, note: \"high quality\" },\n ],\n },\n \"seedream-5-lite-i2i\": {\n id: \"seedream-5-lite-i2i\",\n kind: \"image\",\n modes: [\"i2i\"] as const,\n family: \"Bytedance\",\n label: \"Seedream 5 Lite (I2I)\",\n series: \"Seedream\",\n description: \"Image-to-image with Seedream 5 Lite.\",\n useCases: [\"edit\", \"instruction\"],\n features: [\"reference-image\"],\n aspectRatios: SEEDREAM_RATIOS,\n qualities: [\"basic\", \"high\"],\n pricing: [\n { identifier: \"seedream-5-lite-i2i\", credits: 2, note: \"basic default\" },\n { identifier: \"seedream-5-lite-i2i:high\", credits: 5, note: \"high quality\" },\n ],\n },\n\n // ── Alibaba Qwen ──\n \"qwen\": {\n id: \"qwen\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Alibaba\",\n label: \"Qwen\",\n series: \"Qwen\",\n description: \"Cheap, fast, decent quality. Native negative-prompt support.\",\n useCases: [\"fast\", \"cheap\", \"general\"],\n features: [\"reference-image\"],\n aspectRatios: IDEOGRAM_RATIOS,\n pricing: [{ identifier: \"qwen\", credits: 1 }],\n },\n \"qwen-i2i\": {\n id: \"qwen-i2i\",\n kind: \"image\",\n modes: [\"i2i\"] as const,\n family: \"Alibaba\",\n label: \"Qwen (I2I)\",\n series: \"Qwen\",\n description: \"Image-to-image with Qwen.\",\n useCases: [\"edit\", \"fast\", \"cheap\"],\n features: [\"reference-image\"],\n aspectRatios: IDEOGRAM_RATIOS,\n pricing: [{ identifier: \"qwen-i2i\", credits: 1 }],\n },\n \"qwen-edit\": {\n id: \"qwen-edit\",\n kind: \"image\",\n modes: [\"edit\"] as const,\n family: \"Alibaba\",\n label: \"Qwen Edit\",\n series: \"Qwen\",\n description: \"Qwen image edit endpoint with native negative prompt.\",\n useCases: [\"edit\", \"cheap\"],\n features: [\"reference-image\"],\n aspectRatios: IDEOGRAM_RATIOS,\n pricing: [{ identifier: \"qwen-edit\", credits: 2 }],\n },\n\n // ── Tongyi-MAI Z-Image ──\n \"z-image\": {\n id: \"z-image\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Tongyi-MAI\",\n label: \"Z-Image\",\n series: \"Z-Image\",\n description: \"Cheapest model in catalog. Fast, stylized output. Limited aspect ratios.\",\n useCases: [\"cheap\", \"fast\", \"stylized\"],\n aspectRatios: Z_IMAGE_RATIOS,\n pricing: [{ identifier: \"z-image\", credits: 1 }],\n featured: true,\n },\n\n // ── xAI Grok ──\n \"grok\": {\n id: \"grok\",\n // Grok serves both t2i (image) and t2v (video) under the same id —\n // backend route resolves which by entry point. We classify the catalog\n // entry by primary kind (image) but list both modes so MCP filters and\n // frontend pickers find it under either context.\n kind: \"image\",\n modes: [\"t2i\", \"t2v\"] as const,\n family: \"xAI\",\n label: \"Grok Imagine\",\n series: \"Grok\",\n description: \"Expressive, high-contrast output. Supports both image and video.\",\n useCases: [\"stylized\", \"expressive\", \"general\"],\n features: [\"reference-image\"],\n aspectRatios: GROK_RATIOS,\n pricing: [{ identifier: \"grok\", credits: 1 }],\n },\n \"grok-i2i\": {\n id: \"grok-i2i\",\n kind: \"image\",\n modes: [\"i2i\"] as const,\n family: \"xAI\",\n label: \"Grok Imagine (I2I)\",\n series: \"Grok\",\n description: \"Image-to-image with Grok.\",\n useCases: [\"edit\", \"stylized\"],\n features: [\"reference-image\"],\n pricing: [{ identifier: \"grok-i2i\", credits: 1 }],\n },\n \"grok-upscale\": {\n id: \"grok-upscale\",\n kind: \"image\",\n modes: [\"upscale\"] as const,\n family: \"xAI\",\n label: \"Grok Upscale\",\n series: \"Grok\",\n description: \"Upscale a previously-generated Grok image. Requires the prior task id.\",\n useCases: [\"upscale\"],\n pricing: [{ identifier: \"grok-upscale\", credits: 3 }],\n },\n\n // ── Utilities ──\n \"recraft-remove-bg\": {\n id: \"recraft-remove-bg\",\n kind: \"image\",\n modes: [\"remove-bg\"] as const,\n family: \"Recraft\",\n label: \"Recraft Remove BG\",\n series: \"Recraft\",\n description: \"Remove image background. Cheap utility.\",\n useCases: [\"background-removal\", \"utility\"],\n features: [\"reference-image\"],\n pricing: [{ identifier: \"recraft-remove-bg\", credits: 1 }],\n },\n \"recraft-upscale\": {\n id: \"recraft-upscale\",\n kind: \"image\",\n modes: [\"upscale\"] as const,\n family: \"Recraft\",\n label: \"Recraft Crisp Upscale\",\n series: \"Recraft\",\n description: \"Light-weight image upscale (Recraft Crisp).\",\n useCases: [\"upscale\", \"utility\"],\n features: [\"reference-image\"],\n pricing: [{ identifier: \"recraft-upscale\", credits: 1 }],\n },\n \"topaz-image-upscale\": {\n id: \"topaz-image-upscale\",\n kind: \"image\",\n modes: [\"upscale\"] as const,\n family: \"Topaz\",\n label: \"Topaz Image Upscale\",\n series: \"Topaz\",\n description: \"High-quality image upscale up to 8K. Best for production-ready output.\",\n useCases: [\"upscale\", \"high-res\", \"premium\"],\n features: [\"reference-image\"],\n resolutions: [\"2K\", \"4K\", \"8K\"],\n pricing: [\n { identifier: \"topaz-image-upscale\", credits: 3, note: \"2K default\" },\n { identifier: \"topaz-image-upscale:4K\", credits: 5, note: \"4K\" },\n { identifier: \"topaz-image-upscale:8K\", credits: 10, note: \"8K\" },\n ],\n },\n}\n\n// =============================================================================\n// VIDEO MODELS\n// =============================================================================\nconst VIDEO_MODELS: Record<string, ModelCatalogEntry> = {\n // ── Hailuo / MiniMax ──\n \"minimax\": {\n id: \"minimax\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"MiniMax\",\n label: \"Hailuo 02 I2V Pro\",\n series: \"Hailuo\",\n description: \"Hailuo 02 Pro — strong photoreal motion, fixed 5-second clips. Supports end frame.\",\n useCases: [\"realistic\", \"motion\", \"narrative\"],\n features: [\"end-frame\"],\n durations: [5],\n pricing: [{ identifier: \"minimax\", credits: 15, note: \"5s, 1080p\" }],\n },\n \"hailuo-2.3-pro\": {\n id: \"hailuo-2.3-pro\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n family: \"MiniMax\",\n valueLabels: { \"1080P\": \"1080P (6s max)\" },\n label: \"Hailuo 2.3 Pro\",\n series: \"Hailuo\",\n description: \"Hailuo 2.3 Pro — newer Hailuo with 768P / 1080P resolutions.\",\n useCases: [\"realistic\", \"motion\"],\n durations: [6, 10],\n resolutions: [\"768P\", \"1080P\"],\n pricing: [\n { identifier: \"hailuo-2.3-pro\", credits: 20, note: \"10s default\" },\n { identifier: \"hailuo-2.3-pro:6s\", credits: 13, note: \"6s\" },\n { identifier: \"hailuo-2.3-pro:10s\", credits: 20, note: \"10s\" },\n ],\n },\n \"hailuo-2.3\": {\n id: \"hailuo-2.3\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n family: \"MiniMax\",\n resolutions: [\"768P\", \"1080P\"],\n valueLabels: { \"1080P\": \"1080P (6s max)\" },\n label: \"Hailuo 2.3 Standard\",\n series: \"Hailuo\",\n description: \"Cheaper Hailuo 2.3 tier — good baseline quality.\",\n useCases: [\"realistic\", \"cheap\"],\n durations: [6, 10],\n pricing: [\n { identifier: \"hailuo-2.3\", credits: 8, note: \"6s default\" },\n { identifier: \"hailuo-2.3:6s\", credits: 8, note: \"6s\" },\n { identifier: \"hailuo-2.3:10s\", credits: 13, note: \"10s\" },\n ],\n },\n \"hailuo-standard\": {\n id: \"hailuo-standard\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"MiniMax\",\n label: \"Hailuo 02 Standard\",\n series: \"Hailuo\",\n description: \"Hailuo 02 Standard — economical option with end-frame support.\",\n useCases: [\"cheap\", \"motion\"],\n features: [\"end-frame\"],\n durations: [6, 10],\n resolutions: [\"512P\", \"768P\"],\n pricing: [\n { identifier: \"hailuo-standard\", credits: 8, note: \"6s default\" },\n { identifier: \"hailuo-standard:6s\", credits: 8, note: \"6s\" },\n { identifier: \"hailuo-standard:10s\", credits: 13, note: \"10s\" },\n ],\n },\n\n // ── Google VEO ──\n \"veo3\": {\n id: \"veo3\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Google\",\n label: \"VEO 3.1 Quality\",\n series: \"VEO\",\n description: \"Google VEO 3.1 Quality — premium cinematic video. 4/6/8s clips, optional end frame, native audio. Flat per-generation pricing across durations.\",\n useCases: [\"cinematic\", \"premium\", \"narrative\"],\n features: [\"end-frame\", \"audio\", \"reference-image\"],\n durations: [4, 6, 8],\n aspectRatios: VIDEO_RATIOS_HV,\n // 720p (default) + 1080p inline. 4K generates the base at 1080p then chains\n // KIE's /api/v1/veo/get-4k-video endpoint (worker handleImageToVideo / handleTextToVideo).\n resolutions: [\"720p\", \"1080p\", \"4k\"],\n pricing: [\n { identifier: \"veo3\", credits: 63, note: \"4/6/8s with audio (flat per-generation)\" },\n { identifier: \"veo3:4k\", credits: 93, note: \"4K (base 1080p → get-4k-video)\" },\n ],\n featured: true,\n },\n \"veo3.1\": {\n id: \"veo3.1\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Google\",\n label: \"VEO 3.1 Fast\",\n series: \"VEO\",\n description: \"VEO 3.1 Fast — cheaper VEO 3.1 tier, 4/6/8s with audio. Good balance for most uses. Flat per-generation pricing across durations.\",\n useCases: [\"cinematic\", \"fast\", \"general\"],\n features: [\"end-frame\", \"audio\", \"reference-image\"],\n durations: [4, 6, 8],\n aspectRatios: VIDEO_RATIOS_HV,\n resolutions: [\"720p\", \"1080p\", \"4k\"],\n pricing: [\n { identifier: \"veo3.1\", credits: 15, note: \"4/6/8s with audio @ 720p (flat)\" },\n { identifier: \"veo3.1:1080p\", credits: 17, note: \"4/6/8s with audio @ 1080p (flat)\" },\n { identifier: \"veo3.1:4k\", credits: 45, note: \"4K (base 1080p → get-4k-video)\" },\n ],\n featured: true,\n },\n \"veo3_lite\": {\n id: \"veo3_lite\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Google\",\n label: \"VEO 3.1 Lite\",\n series: \"VEO\",\n description: \"VEO 3.1 Lite — most cost-effective VEO tier for high-volume generation. 4/6/8s with audio, supports first+last frame.\",\n useCases: [\"cinematic\", \"cheap\", \"high-volume\"],\n features: [\"end-frame\", \"audio\", \"reference-image\"],\n durations: [4, 6, 8],\n aspectRatios: VIDEO_RATIOS_HV,\n resolutions: [\"720p\", \"1080p\", \"4k\"],\n pricing: [\n { identifier: \"veo3_lite\", credits: 8, note: \"4/6/8s with audio @ 720p (flat)\" },\n { identifier: \"veo3_lite:1080p\", credits: 9, note: \"4/6/8s with audio @ 1080p (flat)\" },\n { identifier: \"veo3_lite:4k\", credits: 38, note: \"4K (base 1080p → get-4k-video)\" },\n ],\n featured: false,\n },\n \"gemini-omni-video\": {\n id: \"gemini-omni-video\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const, // V2V is served via the i2v handle, not a catalog mode\n family: \"Google\",\n label: \"Gemini Omni\",\n series: \"Gemini\",\n description: \"Google multimodal video with native audio; text/image-to-video + video-edit.\",\n useCases: [\"cinematic\", \"narrative\"],\n features: [\"audio\", \"reference-image\"],\n aspectRatios: VIDEO_RATIOS_HV,\n resolutions: [\"720p\", \"1080p\", \"4k\"],\n durations: [4, 6, 8, 10],\n pricing: [\n { identifier: \"gemini-omni-video\", credits: 23, note: \"default — 720p/1080p 4s\" },\n { identifier: \"gemini-omni-video:4\", credits: 23, note: \"720p/1080p 4s\" },\n { identifier: \"gemini-omni-video:6\", credits: 30, note: \"720p/1080p 6s\" },\n { identifier: \"gemini-omni-video:8\", credits: 38, note: \"720p/1080p 8s\" },\n { identifier: \"gemini-omni-video:10\", credits: 45, note: \"720p/1080p 10s\" },\n { identifier: \"gemini-omni-video:4k:4\", credits: 53, note: \"4K 4s\" },\n { identifier: \"gemini-omni-video:4k:6\", credits: 60, note: \"4K 6s\" },\n { identifier: \"gemini-omni-video:4k:8\", credits: 68, note: \"4K 8s\" },\n { identifier: \"gemini-omni-video:4k:10\", credits: 75, note: \"4K 10s\" },\n { identifier: \"gemini-omni-video:vref\", credits: 60, note: \"video-edit 720p/1080p\" },\n { identifier: \"gemini-omni-video:4k:vref\", credits: 90, note: \"video-edit 4K\" },\n ],\n },\n\n // ── Kling ──\n \"kling\": {\n id: \"kling\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Kuaishou\",\n label: \"Kling 2.6\",\n series: \"Kling\",\n description: \"Kling 2.6 I2V — strong motion realism. 5s/10s, optional native audio.\",\n useCases: [\"realistic\", \"motion\", \"dance\"],\n features: [\"audio\"],\n aspectRatios: VIDEO_RATIOS_HVS,\n durations: [5, 10],\n pricing: [\n { identifier: \"kling\", credits: 28, note: \"10s no audio default\" },\n { identifier: \"kling:5s\", credits: 14, note: \"5s no audio\" },\n { identifier: \"kling:10s\", credits: 28, note: \"10s no audio\" },\n { identifier: \"kling:5s:audio\", credits: 28, note: \"5s with audio\" },\n { identifier: \"kling:10s:audio\", credits: 55, note: \"10s with audio\" },\n ],\n },\n \"kling-turbo\": {\n id: \"kling-turbo\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Kuaishou\",\n label: \"Kling 2.5 Turbo Pro\",\n series: \"Kling\",\n description: \"Faster Kling — good quality at lower cost. Supports end frame.\",\n useCases: [\"fast\", \"motion\", \"cheap\"],\n features: [\"end-frame\"],\n durations: [5, 10],\n pricing: [\n { identifier: \"kling-turbo\", credits: 11, note: \"5s default\" },\n { identifier: \"kling-turbo:5s\", credits: 11 },\n { identifier: \"kling-turbo:10s\", credits: 21 },\n ],\n },\n \"kling-3.0\": {\n id: \"kling-3.0\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Kuaishou\",\n label: \"Kling 3.0\",\n series: \"Kling\",\n description: \"Premium Kling 3.0 — variable 3-15s duration, native audio, 720P/1080P.\",\n useCases: [\"premium\", \"narrative\", \"cinematic\"],\n features: [\"end-frame\", \"audio\"],\n durations: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"720P\", \"1080P\"],\n pricing: [\n { identifier: \"kling-3.0\", credits: 50, note: \"5s 1080p with audio\" },\n { identifier: \"kling-3.0:5s\", credits: 34, note: \"5s 1080p no audio\" },\n { identifier: \"kling-3.0:10s\", credits: 68, note: \"10s 1080p no audio\" },\n { identifier: \"kling-3.0:15s\", credits: 102, note: \"15s 1080p no audio\" },\n { identifier: \"kling-3.0:5s:audio\", credits: 50, note: \"5s 1080p with audio\" },\n { identifier: \"kling-3.0:10s:audio\", credits: 100, note: \"10s 1080p with audio\" },\n { identifier: \"kling-3.0:15s:audio\", credits: 150, note: \"15s 1080p with audio\" },\n ],\n featured: true,\n },\n \"kling-master\": {\n id: \"kling-master\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n family: \"Kuaishou\",\n label: \"Kling 2.1 Master\",\n series: \"Kling\",\n description: \"Master tier I2V — strong cinematic quality.\",\n useCases: [\"cinematic\", \"premium\"],\n durations: [5, 10],\n pricing: [\n { identifier: \"kling-master\", credits: 40, note: \"5s default\" },\n { identifier: \"kling-master:5s\", credits: 40 },\n { identifier: \"kling-master:10s\", credits: 80 },\n ],\n },\n \"kling-3-omni\": {\n id: \"kling-3-omni\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n family: \"Kuaishou\",\n label: \"Kling 3 Omni\",\n series: \"Kling\",\n description: \"Kling 3 Omni via Replicate — 3-15s, 720p/1080p, end frame + reference images, native audio.\",\n useCases: [\"motion\", \"cinematic\", \"reference\"],\n features: [\"end-frame\", \"reference-image\"],\n durations: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"720p\", \"1080p\"],\n aspectRatios: VIDEO_RATIOS_HVS,\n pricing: [\n { identifier: \"kling-3-omni\", credits: 25, note: \"5s 720p default\" },\n { identifier: \"kling-3-omni:5s\", credits: 25 },\n { identifier: \"kling-3-omni:10s\", credits: 50 },\n { identifier: \"kling-3-omni:15s\", credits: 75 },\n ],\n },\n\n // ── xAI Grok video ──\n \"grok-i2v\": {\n id: \"grok-i2v\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n features: [\"reference-image\"],\n family: \"xAI\",\n label: \"Grok Imagine (I2V)\",\n series: \"Grok\",\n description: \"Grok image-to-video — stylized motion. Up to 15s.\",\n useCases: [\"stylized\", \"motion\"],\n durations: [6, 10],\n resolutions: [\"480p\", \"720p\"],\n pricing: [\n { identifier: \"grok-i2v\", credits: 5, note: \"6s default\" },\n { identifier: \"grok-i2v:6s\", credits: 5 },\n { identifier: \"grok-i2v:10s\", credits: 8 },\n { identifier: \"grok-i2v:15s\", credits: 10 },\n ],\n },\n // xAI Grok Imagine Video 1.5 — KIE image-to-video (image required). True\n // per-second billing split 480p/720p. modes:[\"i2v\"] is the honest capability;\n // it's also surfaced in the text-to-video dropdown for the unified node, where\n // the t2v route returns a clean \"requires an input image\" 400.\n \"grok-imagine-video-1.5\": {\n id: \"grok-imagine-video-1.5\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n // No `reference-image` (locked by video-reference-features.test.ts, 2026-06-28\n // audit): KIE's grok-imagine endpoint accepts a single image_url (the i2v\n // start frame) only — there is no reference transport, so advertising the\n // feature let the editor attach refs that were silently dropped at the\n // provider. Also kept OUT of VIDEO_REF_LIMITS_BY_PROVIDER for the same reason.\n family: \"xAI\",\n label: \"Grok Imagine Video 1.5\",\n series: \"Grok\",\n description: \"Grok Imagine 1.5 image-to-video — 1–15s, 480p/720p, per-second pricing. Requires an input image.\",\n useCases: [\"stylized\", \"motion\"],\n aspectRatios: [\"16:9\", \"9:16\", \"1:1\", \"4:3\", \"3:4\"],\n durations: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"480p\", \"720p\"],\n pricing: [\n { identifier: \"grok-imagine-video-1.5\", credits: 30, note: \"default 8s 480p — see :Ns:res variants\" },\n { identifier: \"grok-imagine-video-1.5:8s:480p\", credits: 30, note: \"8s 480p\" },\n { identifier: \"grok-imagine-video-1.5:8s:720p\", credits: 51, note: \"8s 720p\" },\n { identifier: \"grok-imagine-video-1.5:15s:480p\", credits: 55, note: \"15s 480p (max)\" },\n { identifier: \"grok-imagine-video-1.5:15s:720p\", credits: 95, note: \"15s 720p (max)\" },\n ],\n },\n\n // ── Bytedance Seedance ──\n \"seedance\": {\n id: \"seedance\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Bytedance\",\n label: \"Seedance 1.5 Pro\",\n series: \"Seedance\",\n description: \"Bytedance Seedance 1.5 Pro — flexible duration (4/8/12s) with end-frame support.\",\n useCases: [\"motion\", \"narrative\"],\n features: [\"end-frame\"],\n durations: [4, 8, 12],\n resolutions: [\"480p\", \"720p\", \"1080p\"],\n pricing: [\n { identifier: \"seedance\", credits: 7, note: \"8s default\" },\n { identifier: \"seedance:4s\", credits: 4 },\n { identifier: \"seedance:8s\", credits: 7 },\n { identifier: \"seedance:12s\", credits: 15 },\n ],\n mcpHidden: true,\n },\n \"seedance-2\": {\n id: \"seedance-2\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Bytedance\",\n label: \"Seedance 2\",\n series: \"Seedance\",\n description: \"Seedance 2 — premium tier with native audio. Per-second pricing by resolution.\",\n useCases: [\"premium\", \"narrative\"],\n features: [\"end-frame\", \"audio\", \"reference-image\"],\n aspectRatios: VIDEO_RATIOS_SEEDANCE_2,\n durations: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"480p\", \"720p\", \"1080p\", \"4k\"],\n pricing: [\n { identifier: \"seedance-2\", credits: 38, note: \"default — see :NsR variants for exact\" },\n { identifier: \"seedance-2:8s:480p\", credits: 38, note: \"8s 480p\" },\n { identifier: \"seedance-2:8s:720p\", credits: 82, note: \"8s 720p\" },\n { identifier: \"seedance-2:8s:1080p\", credits: 204, note: \"8s 1080p\" },\n { identifier: \"seedance-2:8s:480p-ref\", credits: 23, note: \"8s 480p with reference\" },\n { identifier: \"seedance-2:8s:720p-ref\", credits: 50, note: \"8s 720p with reference\" },\n { identifier: \"seedance-2:8s:1080p-ref\", credits: 124, note: \"8s 1080p with reference\" },\n { identifier: \"seedance-2:8s:4k\", credits: 416, note: \"8s 4k\" },\n { identifier: \"seedance-2:8s:4k-ref\", credits: 256, note: \"8s 4k with reference\" },\n ],\n },\n \"seedance-2-fast\": {\n id: \"seedance-2-fast\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Bytedance\",\n label: \"Seedance 2 Fast\",\n series: \"Seedance\",\n description: \"Cheaper / quicker Seedance 2 tier.\",\n useCases: [\"fast\", \"motion\"],\n features: [\"end-frame\", \"audio\", \"reference-image\"],\n aspectRatios: VIDEO_RATIOS_SEEDANCE_2,\n durations: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"480p\", \"720p\"],\n pricing: [\n { identifier: \"seedance-2-fast\", credits: 31, note: \"default — see :NsR variants\" },\n { identifier: \"seedance-2-fast:8s:480p\", credits: 31 },\n { identifier: \"seedance-2-fast:8s:720p\", credits: 66 },\n { identifier: \"seedance-2-fast:8s:480p-ref\", credits: 18 },\n { identifier: \"seedance-2-fast:8s:720p-ref\", credits: 40 },\n ],\n },\n \"seedance-2-mini\": {\n id: \"seedance-2-mini\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Bytedance\",\n label: \"Seedance 2 Mini\",\n series: \"Seedance\",\n description: \"Budget Seedance 2 tier — 480p/720p only, per-second pricing by resolution.\",\n useCases: [\"fast\", \"motion\"],\n features: [\"end-frame\", \"audio\", \"reference-image\"],\n aspectRatios: VIDEO_RATIOS_SEEDANCE_2,\n durations: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"480p\", \"720p\"],\n pricing: [\n { identifier: \"seedance-2-mini\", credits: 19, note: \"default — see :NsR variants\" },\n { identifier: \"seedance-2-mini:8s:480p\", credits: 19 },\n { identifier: \"seedance-2-mini:8s:720p\", credits: 41 },\n { identifier: \"seedance-2-mini:8s:480p-ref\", credits: 12 },\n { identifier: \"seedance-2-mini:8s:720p-ref\", credits: 25 },\n ],\n },\n\n // ── Wan ──\n \"wan-i2v\": {\n id: \"wan-i2v\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n family: \"Alibaba\",\n label: \"Wan 2.6 I2V\",\n series: \"Wan\",\n description: \"Wan 2.6 image-to-video — 5/10/15s at 720p/1080p.\",\n useCases: [\"motion\", \"narrative\"],\n durations: [5, 10, 15],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [\n { identifier: \"wan-i2v\", credits: 18, note: \"5s 720p default\" },\n { identifier: \"wan-i2v:5s\", credits: 18 },\n { identifier: \"wan-i2v:10s\", credits: 35 },\n { identifier: \"wan-i2v:15s\", credits: 53 },\n ],\n },\n \"wan-turbo\": {\n id: \"wan-turbo\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Alibaba\",\n label: \"Wan 2.2 Turbo\",\n series: \"Wan\",\n description: \"Cheap, fast Wan turbo — 5s. Serves both i2v and t2v under one id.\",\n useCases: [\"cheap\", \"fast\"],\n aspectRatios: VIDEO_RATIOS_HVS,\n durations: [5],\n resolutions: [\"480p\", \"720p\"],\n // Different KIE endpoints (i2v vs t2v) → different costs under\n // composite ids. Route picks endpoint based on whether image was supplied.\n pricing: [\n { identifier: \"wan-turbo\", credits: 10, note: \"i2v 5s 480p\" },\n { identifier: \"wan-turbo-t2v\", credits: 20, note: \"t2v 5s 720p\" },\n ],\n },\n \"wan\": {\n id: \"wan\",\n kind: \"video\",\n // \"wan\" id covers v2v AND t2v under different KIE endpoints; the\n // pricing variants tag which mode each cost belongs to.\n modes: [\"v2v\", \"t2v\"] as const,\n family: \"Alibaba\",\n label: \"Wan 2.6\",\n series: \"Wan\",\n description: \"Wan 2.6 — text-to-video and video-to-video under a single id.\",\n useCases: [\"v2v\", \"t2v\", \"restyle\"],\n durations: [5],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [\n { identifier: \"wan\", credits: 18, note: \"v2v 5s 720p\" },\n { identifier: \"wan-t2v\", credits: 27, note: \"t2v 5s 1080p\" },\n ],\n },\n \"wan-flash\": {\n id: \"wan-flash\",\n kind: \"video\",\n modes: [\"v2v\"] as const,\n family: \"Alibaba\",\n label: \"Wan Flash V2V\",\n series: \"Wan\",\n description: \"Faster Wan V2V variant.\",\n useCases: [\"v2v\", \"fast\"],\n pricing: [{ identifier: \"wan-flash\", credits: 13 }],\n },\n \"wan-videoedit\": {\n id: \"wan-videoedit\",\n kind: \"video\",\n modes: [\"v2v\"] as const,\n family: \"Alibaba\",\n label: \"Wan 2.7 VideoEdit\",\n series: \"Wan\",\n description: \"Guided video editing with optional reference image, audio control, and prompt expansion.\",\n useCases: [\"v2v\", \"restyle\", \"reference\"],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [{ identifier: \"wan-videoedit\", credits: 32 }],\n },\n // ── Wan 2.7 ──\n \"wan-2.7\": {\n id: \"wan-2.7\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Alibaba\",\n label: \"Wan 2.7\",\n series: \"Wan\",\n description: \"Wan 2.7 text-to-image — 1K/2K/4K, up to 9 optional style/character reference images.\",\n useCases: [\"photorealistic\", \"stylized\", \"reference\"],\n features: [\"reference-image\"] as const,\n aspectRatios: WAN_27_IMAGE_RATIOS,\n resolutions: [\"1K\", \"2K\", \"4K\"],\n pricing: [\n { identifier: \"wan-2.7\", credits: 2, note: \"1K base\" },\n { identifier: \"wan-2.7:2K\", credits: 4, note: \"2K\" },\n { identifier: \"wan-2.7:4K\", credits: 8, note: \"4K\" },\n ],\n },\n \"wan-2.7-pro\": {\n id: \"wan-2.7-pro\",\n kind: \"image\",\n modes: [\"t2i\"] as const,\n family: \"Alibaba\",\n label: \"Wan 2.7 Pro\",\n series: \"Wan\",\n description: \"Wan 2.7 Pro text-to-image — higher quality, 1K/2K/4K, no image input.\",\n useCases: [\"photorealistic\", \"premium\"],\n aspectRatios: WAN_27_IMAGE_RATIOS,\n resolutions: [\"1K\", \"2K\", \"4K\"],\n pricing: [\n { identifier: \"wan-2.7-pro\", credits: 3, note: \"1K base\" },\n { identifier: \"wan-2.7-pro:2K\", credits: 6, note: \"2K\" },\n { identifier: \"wan-2.7-pro:4K\", credits: 12, note: \"4K\" },\n ],\n },\n \"wan-2.7-i2v\": {\n id: \"wan-2.7-i2v\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n family: \"Alibaba\",\n label: \"Wan 2.7 I2V\",\n series: \"Wan\",\n description: \"Wan 2.7 image-to-video — 2–15s at 720p/1080p, supports start+end frame.\",\n useCases: [\"motion\", \"narrative\"],\n durations: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"720p\", \"1080p\"],\n features: [\"end-frame\"],\n pricing: [\n { identifier: \"wan-2.7-i2v\", credits: 19, note: \"5s 720p default\" },\n ],\n },\n \"wan-2.7-t2v\": {\n id: \"wan-2.7-t2v\",\n kind: \"video\",\n modes: [\"t2v\"] as const,\n family: \"Alibaba\",\n label: \"Wan 2.7 T2V\",\n series: \"Wan\",\n description: \"Wan 2.7 text-to-video — 2–15s at 720p/1080p.\",\n useCases: [\"motion\", \"narrative\"],\n aspectRatios: VIDEO_RATIOS_HVS345,\n durations: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [\n { identifier: \"wan-2.7-t2v\", credits: 19, note: \"5s 720p default\" },\n ],\n },\n // ── HappyHorse ──\n \"happyhorse\": {\n id: \"happyhorse\",\n kind: \"video\",\n modes: [\"t2v\"] as const,\n family: \"HappyHorse\",\n label: \"HappyHorse\",\n series: \"HappyHorse\",\n description: \"HappyHorse text-to-video — 3–15s at 720p/1080p.\",\n useCases: [\"motion\", \"creative\"],\n aspectRatios: VIDEO_RATIOS_HVS345,\n durations: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [\n { identifier: \"happyhorse\", credits: 13, note: \"5s 720p default\" },\n ],\n },\n \"happyhorse-i2v\": {\n id: \"happyhorse-i2v\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n family: \"HappyHorse\",\n label: \"HappyHorse I2V\",\n series: \"HappyHorse\",\n description: \"HappyHorse image-to-video — 3–15s at 720p/1080p, aspect ratio inferred from input image.\",\n useCases: [\"motion\", \"creative\"],\n durations: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [\n { identifier: \"happyhorse-i2v\", credits: 13, note: \"5s 720p default\" },\n ],\n },\n \"happyhorse-ref2v\": {\n id: \"happyhorse-ref2v\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n family: \"HappyHorse\",\n label: \"HappyHorse Ref2V\",\n series: \"HappyHorse\",\n description: \"HappyHorse reference-to-video — 1–9 reference images, 3–15s at 720p/1080p.\",\n useCases: [\"motion\", \"reference\"],\n aspectRatios: VIDEO_RATIOS_HVS345,\n durations: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"720p\", \"1080p\"],\n features: [\"reference-image\"],\n pricing: [\n { identifier: \"happyhorse-ref2v\", credits: 15, note: \"5s 720p default\" },\n ],\n },\n \"happyhorse-edit\": {\n id: \"happyhorse-edit\",\n kind: \"video\",\n modes: [\"v2v\"] as const,\n family: \"HappyHorse\",\n label: \"HappyHorse Edit\",\n series: \"HappyHorse\",\n description: \"HappyHorse video-edit — video-to-video transformation, up to 60s input, 720p/1080p output.\",\n useCases: [\"v2v\", \"restyle\"],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [\n { identifier: \"happyhorse-edit\", credits: 20, note: \"720p default\" },\n ],\n },\n // ── Bytedance video lite/pro ──\n \"bytedance-lite\": {\n id: \"bytedance-lite\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Bytedance\",\n label: \"Bytedance Lite I2V\",\n series: \"Bytedance\",\n description: \"Cheapest Bytedance video tier with end-frame support.\",\n useCases: [\"cheap\", \"motion\"],\n features: [\"end-frame\"],\n aspectRatios: VIDEO_RATIOS_HVS,\n durations: [5, 10],\n resolutions: [\"480p\", \"720p\", \"1080p\"],\n pricing: [{ identifier: \"bytedance-lite\", credits: 6 }],\n },\n \"bytedance-pro\": {\n id: \"bytedance-pro\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Bytedance\",\n label: \"Bytedance Pro I2V\",\n series: \"Bytedance\",\n description: \"Pro Bytedance video tier — better quality.\",\n useCases: [\"motion\", \"narrative\"],\n aspectRatios: VIDEO_RATIOS_HVS,\n durations: [5, 10],\n resolutions: [\"480p\", \"720p\", \"1080p\"],\n pricing: [{ identifier: \"bytedance-pro\", credits: 18 }],\n },\n \"bytedance-pro-fast\": {\n id: \"bytedance-pro-fast\",\n kind: \"video\",\n modes: [\"i2v\"] as const,\n family: \"Bytedance\",\n label: \"Bytedance Pro Fast I2V\",\n series: \"Bytedance\",\n description: \"Faster Bytedance Pro variant.\",\n useCases: [\"fast\", \"motion\"],\n durations: [5, 10],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [{ identifier: \"bytedance-pro-fast\", credits: 9 }],\n },\n\n // ── OpenAI Sora ──\n // (Sora2 / Sora2-Pro are listed in KIE models but not in STATIC_CREDIT_COSTS;\n // they're priced at runtime via the per-second tracker, so we omit pricing\n // arrays with composite entries — `list_models` will fall back to whatever\n // base entry exists.)\n\n // ── Runway ──\n \"runway-kie\": {\n id: \"runway-kie\",\n kind: \"video\",\n modes: [\"i2v\", \"t2v\"] as const,\n family: \"Runway\",\n label: \"Runway (via KIE)\",\n series: \"Runway\",\n description: \"Runway Gen-3 routed through KIE. 5/10s at 720p/1080p.\",\n useCases: [\"motion\", \"narrative\"],\n durations: [5, 10],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [{ identifier: \"runway-kie\", credits: 3, note: \"5s 720p\" }],\n },\n \"runway-aleph\": {\n id: \"runway-aleph\",\n kind: \"video\",\n modes: [\"v2v\"] as const,\n family: \"Runway\",\n label: \"Runway Aleph V2V\",\n series: \"Runway\",\n description: \"Runway Aleph — video-to-video conversion.\",\n useCases: [\"v2v\", \"restyle\"],\n pricing: [{ identifier: \"runway-aleph\", credits: 35, note: \"5s clip\" }],\n },\n\n // ── Extend / Upscale ──\n \"veo-extend\": {\n id: \"veo-extend\",\n kind: \"video\",\n modes: [\"extend\"] as const,\n family: \"Google\",\n label: \"VEO Extend\",\n series: \"VEO\",\n description: \"Extend an existing VEO 3.1 clip by another segment.\",\n useCases: [\"extend\"],\n pricing: [\n { identifier: \"veo-extend\", credits: 19, note: \"VEO 3.1 Fast default\" },\n { identifier: \"veo-extend:quality\", credits: 79, note: \"VEO 3.1 Quality\" },\n ],\n },\n \"runway-extend\": {\n id: \"runway-extend\",\n kind: \"video\",\n modes: [\"extend\"] as const,\n family: \"Runway\",\n label: \"Runway Extend\",\n series: \"Runway\",\n description: \"Extend a Runway video by another clip.\",\n useCases: [\"extend\"],\n pricing: [{ identifier: \"runway-extend\", credits: 32 }],\n },\n \"seedance-2-extend\": {\n id: \"seedance-2-extend\",\n kind: \"video\",\n modes: [\"extend\"] as const,\n family: \"Bytedance\",\n label: \"Seedance 2 Extend\",\n series: \"Seedance\",\n description: \"Extend ANY video: generates the continuation (audio included) and trim-stitches it into one seamless clip.\",\n useCases: [\"extend\"],\n durations: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n resolutions: [\"480p\", \"720p\", \"1080p\"],\n pricing: [\n { identifier: \"seedance-2-extend\", credits: 53, note: \"default 8s 720p (ref-mode 50 + 3 stitch) — see :NsR variants\" },\n { identifier: \"seedance-2-extend:8s:480p\", credits: 26, note: \"8s 480p (23+3)\" },\n { identifier: \"seedance-2-extend:8s:720p\", credits: 53, note: \"8s 720p (50+3)\" },\n { identifier: \"seedance-2-extend:8s:1080p\", credits: 78, note: \"8s 1080p (75+3)\" },\n ],\n },\n \"veo-1080p\": {\n id: \"veo-1080p\",\n kind: \"video\",\n modes: [\"video-upscale\"] as const,\n family: \"Google\",\n label: \"VEO 1080p Upscale\",\n series: \"VEO\",\n description: \"Upscale VEO output to 1080p.\",\n useCases: [\"upscale\"],\n pricing: [{ identifier: \"veo-1080p\", credits: 2 }],\n },\n \"veo-4k\": {\n id: \"veo-4k\",\n kind: \"video\",\n modes: [\"video-upscale\"] as const,\n family: \"Google\",\n label: \"VEO 4K Upscale\",\n series: \"VEO\",\n description: \"Upscale VEO output to 4K.\",\n useCases: [\"upscale\", \"high-res\"],\n pricing: [{ identifier: \"veo-4k\", credits: 38 }],\n },\n \"topaz-video\": {\n id: \"topaz-video\",\n kind: \"video\",\n modes: [\"video-upscale\"] as const,\n family: \"Topaz\",\n label: \"Topaz Video Upscale\",\n series: \"Topaz\",\n description: \"High-quality video upscale and enhancement.\",\n useCases: [\"upscale\", \"premium\"],\n pricing: [{ identifier: \"topaz-video\", credits: 19, note: \"~5s clip\" }],\n },\n\n // ── Motion transfer ──\n \"motion-transfer\": {\n id: \"motion-transfer\",\n kind: \"video\",\n modes: [\"motion-transfer\"] as const,\n family: \"Kuaishou\",\n label: \"Kling 2.6 Motion Transfer\",\n series: \"Kling\",\n description: \"Transfer the motion from a driving video onto a still subject. Kling 2.6 base.\",\n useCases: [\"motion-transfer\"],\n durations: [5, 10, 15, 30],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [\n { identifier: \"motion-transfer\", credits: 15, note: \"10s 720p default\" },\n { identifier: \"motion-transfer:5s\", credits: 8 },\n { identifier: \"motion-transfer:10s\", credits: 15 },\n { identifier: \"motion-transfer:15s\", credits: 23 },\n { identifier: \"motion-transfer:30s\", credits: 45 },\n { identifier: \"motion-transfer:1080p:10s\", credits: 23 },\n ],\n },\n \"kling-3.0-motion\": {\n id: \"kling-3.0-motion\",\n kind: \"video\",\n modes: [\"motion-transfer\"] as const,\n family: \"Kuaishou\",\n label: \"Kling 3.0 Motion Transfer\",\n series: \"Kling\",\n description: \"Premium motion transfer via Kling 3.0.\",\n useCases: [\"motion-transfer\", \"premium\"],\n durations: [5, 10, 15, 30],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [\n { identifier: \"kling-3.0-motion\", credits: 30, note: \"10s 720p default\" },\n { identifier: \"kling-3.0-motion:5s\", credits: 15 },\n { identifier: \"kling-3.0-motion:10s\", credits: 30 },\n { identifier: \"kling-3.0-motion:1080p:10s\", credits: 50 },\n ],\n },\n\n // ── Lip sync / talking-head ──\n \"kling-avatar\": {\n id: \"kling-avatar\",\n kind: \"video\",\n modes: [\"lip-sync\"] as const,\n family: \"Kuaishou\",\n label: \"Kling Avatar Standard\",\n series: \"Kling\",\n description: \"Lip-sync a still portrait to driving audio. Standard quality.\",\n useCases: [\"lip-sync\", \"talking-head\"],\n pricing: [{ identifier: \"kling-avatar\", credits: 28, note: \"~14s default\" }],\n },\n \"kling-avatar-pro\": {\n id: \"kling-avatar-pro\",\n kind: \"video\",\n modes: [\"lip-sync\"] as const,\n family: \"Kuaishou\",\n label: \"Kling Avatar Pro\",\n series: \"Kling\",\n description: \"Premium lip-sync — better mouth shape and timing.\",\n useCases: [\"lip-sync\", \"talking-head\", \"premium\"],\n pricing: [{ identifier: \"kling-avatar-pro\", credits: 56 }],\n },\n \"infinitalk\": {\n id: \"infinitalk\",\n kind: \"video\",\n modes: [\"lip-sync\"] as const,\n family: \"InfiniTalk\",\n label: \"InfiniTalk\",\n series: \"InfiniTalk\",\n description: \"Audio-driven talking-head from a still image. 480p / 720p.\",\n useCases: [\"lip-sync\", \"talking-head\"],\n resolutions: [\"480p\", \"720p\"],\n pricing: [\n { identifier: \"infinitalk\", credits: 42, note: \"720p default\" },\n { identifier: \"infinitalk:480p\", credits: 11 },\n { identifier: \"infinitalk:720p\", credits: 42 },\n ],\n },\n \"omnihuman-1-5\": {\n id: \"omnihuman-1-5\",\n kind: \"video\",\n modes: [\"lip-sync\"] as const,\n family: \"ByteDance\",\n label: \"OmniHuman 1.5\",\n series: \"OmniHuman\",\n description: \"Premium prompt-directed talking avatar from a still image + audio. 720p / 1080p, up to 60s. People, pets, anime.\",\n useCases: [\"lip-sync\", \"talking-head\", \"premium\"],\n resolutions: [\"720p\", \"1080p\"],\n pricing: [\n { identifier: \"omnihuman-1-5\", credits: 405, note: \"60s ceiling (no duration given)\" },\n { identifier: \"omnihuman-1-5:15s\", credits: 102 },\n { identifier: \"omnihuman-1-5:30s\", credits: 203 },\n { identifier: \"omnihuman-1-5:60s\", credits: 405 },\n ],\n },\n \"hailuo-avatar\": {\n id: \"hailuo-avatar\",\n kind: \"video\",\n modes: [\"lip-sync\"] as const,\n family: \"MiniMax\",\n label: \"Hailuo Avatar\",\n series: \"Hailuo\",\n description: \"MiniMax avatar lip-sync.\",\n useCases: [\"lip-sync\", \"talking-head\"],\n pricing: [{ identifier: \"hailuo-avatar\", credits: 19 }],\n // Not wired in any provider / not in LIP_SYNC_PROVIDERS — hide from MCP\n // list_models so the lip_sync tool can't advertise a model its route\n // rejects with a 400. Re-expose when the provider lands.\n mcpHidden: true,\n },\n \"sync-lipsync-v3\": {\n id: \"sync-lipsync-v3\",\n kind: \"video\",\n modes: [\"lip-sync\"] as const,\n family: \"Sync\",\n label: \"Sync Lipsync v3\",\n series: \"Sync\",\n description: \"Dub existing footage — re-syncs lips to a new audio track. Video input, billed per second.\",\n useCases: [\"lip-sync\", \"dubbing\", \"video-to-video\"],\n pricing: [\n { identifier: \"sync-lipsync-v3\", credits: 2000, note: \"5-min ceiling (no duration given)\" },\n { identifier: \"sync-lipsync-v3:15s\", credits: 100 },\n { identifier: \"sync-lipsync-v3:30s\", credits: 200 },\n { identifier: \"sync-lipsync-v3:60s\", credits: 400 },\n { identifier: \"sync-lipsync-v3:120s\", credits: 800 },\n { identifier: \"sync-lipsync-v3:300s\", credits: 2000, note: \"5-min ceiling\" },\n ],\n },\n \"volcengine-lipsync\": {\n id: \"volcengine-lipsync\",\n kind: \"video\",\n modes: [\"lip-sync\"] as const,\n family: \"Volcengine\",\n label: \"Volcengine Lip Sync\",\n series: \"Volcengine\",\n description: \"Video-to-video AI dubbing — re-syncs lips to a new vocal track. Multi-speaker (scene detection + speaker ID) in basic mode. Video input, billed per second.\",\n useCases: [\"lip-sync\", \"dubbing\", \"video-to-video\"],\n pricing: [\n { identifier: \"volcengine-lipsync\", credits: 600, note: \"5-min ceiling (no duration given)\" },\n { identifier: \"volcengine-lipsync:15s\", credits: 30 },\n { identifier: \"volcengine-lipsync:30s\", credits: 60 },\n { identifier: \"volcengine-lipsync:60s\", credits: 120 },\n { identifier: \"volcengine-lipsync:120s\", credits: 240 },\n { identifier: \"volcengine-lipsync:300s\", credits: 600, note: \"5-min ceiling\" },\n ],\n },\n // ── Gemini video analysis ── (Gemini-only; billed per duration bucket — the\n // structural credit formula lives in video-analysis-pricing.ts. Composite id\n // shape `video-analysis:<model>:<bucket>s` mirrors volcengine-lipsync: bare\n // row = per-model namespace root at the 10-min ceiling, plus one row per bucket.)\n \"gemini-3-flash-video-analysis\": {\n id: \"gemini-3-flash-video-analysis\",\n kind: \"video\",\n modes: [\"video-analysis\"] as const,\n family: \"Google\",\n label: \"Video Analysis (Gemini 3 Flash)\",\n series: \"Gemini\",\n description: \"Analyze a video into a structured shot list (scenes, camera, audio) — fast Gemini tier. Billed per duration bucket.\",\n useCases: [\"video-analysis\", \"shot-list\", \"fast\"],\n pricing: [\n { identifier: \"video-analysis:gemini-3-flash\", credits: 3, note: \"10-min ceiling (no duration given)\" },\n { identifier: \"video-analysis:gemini-3-flash:60s\", credits: 1 },\n { identifier: \"video-analysis:gemini-3-flash:180s\", credits: 1 },\n { identifier: \"video-analysis:gemini-3-flash:360s\", credits: 2 },\n { identifier: \"video-analysis:gemini-3-flash:600s\", credits: 3, note: \"10-min ceiling\" },\n ],\n },\n \"gemini-3.1-pro-video-analysis\": {\n id: \"gemini-3.1-pro-video-analysis\",\n kind: \"video\",\n modes: [\"video-analysis\"] as const,\n family: \"Google\",\n label: \"Video Analysis (Gemini 3.1 Pro)\",\n series: \"Gemini\",\n description: \"Analyze a video into a structured shot list (scenes, camera, audio) — high-fidelity Gemini tier. Billed per duration bucket.\",\n useCases: [\"video-analysis\", \"shot-list\", \"cinematic\"],\n pricing: [\n { identifier: \"video-analysis:gemini-3.1-pro\", credits: 11, note: \"10-min ceiling (no duration given)\" },\n { identifier: \"video-analysis:gemini-3.1-pro:60s\", credits: 2 },\n { identifier: \"video-analysis:gemini-3.1-pro:180s\", credits: 3 },\n { identifier: \"video-analysis:gemini-3.1-pro:360s\", credits: 7 },\n { identifier: \"video-analysis:gemini-3.1-pro:600s\", credits: 11, note: \"10-min ceiling\" },\n ],\n },\n}\n\n// =============================================================================\n// AUDIO MODELS\n// =============================================================================\nconst AUDIO_MODELS: Record<string, ModelCatalogEntry> = {\n // ── ElevenLabs TTS ──\n \"elevenlabs-v3\": {\n id: \"elevenlabs-v3\",\n kind: \"audio\",\n modes: [\"tts\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs v3\",\n series: \"ElevenLabs\",\n description: \"Latest ElevenLabs TTS — supports [audio tags] for emotion / pacing. Direct API.\",\n useCases: [\"tts\", \"voice-over\", \"narration\", \"expressive\"],\n features: [\"audio-tags\", \"voice-cloning\"],\n pricing: [{ identifier: \"elevenlabs-v3\", credits: 3 }],\n featured: true,\n },\n \"elevenlabs-turbo\": {\n id: \"elevenlabs-turbo\",\n kind: \"audio\",\n modes: [\"tts\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs Turbo v2.5\",\n series: \"ElevenLabs\",\n description: \"Fast, cheap ElevenLabs TTS via the direct ElevenLabs API. Good for narration.\",\n useCases: [\"tts\", \"narration\", \"fast\"],\n pricing: [{ identifier: \"elevenlabs-turbo\", credits: 2, note: \"per 1K chars\" }],\n },\n \"elevenlabs-multilingual\": {\n id: \"elevenlabs-multilingual\",\n kind: \"audio\",\n modes: [\"tts\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs Multilingual v2\",\n series: \"ElevenLabs\",\n description: \"Multi-language ElevenLabs TTS via the direct ElevenLabs API.\",\n useCases: [\"tts\", \"multilingual\"],\n pricing: [{ identifier: \"elevenlabs-multilingual\", credits: 3, note: \"per 1K chars\" }],\n },\n \"elevenlabs-dialogue\": {\n id: \"elevenlabs-dialogue\",\n kind: \"audio\",\n modes: [\"tts\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs Dialogue v3\",\n series: \"ElevenLabs\",\n description: \"Multi-speaker dialogue TTS — give it a script, it voices each role.\",\n useCases: [\"tts\", \"dialogue\", \"multi-speaker\"],\n pricing: [{ identifier: \"elevenlabs-dialogue\", credits: 4, note: \"per 1K chars\" }],\n // Driven only via the dialogue/character-voice path (multi-speaker script\n // shape), NOT the single-text generate_speech verb. Hide from MCP\n // list_models so generate_speech (TTS_PROVIDERS) can't advertise it and\n // then 400. Re-expose if a dialogue-capable MCP verb is added.\n mcpHidden: true,\n },\n\n // ── ElevenLabs voice utilities ──\n \"voice-clone\": {\n id: \"voice-clone\",\n kind: \"audio\",\n modes: [\"voice-clone\"] as const,\n family: \"ElevenLabs\",\n label: \"Voice Clone (Instant)\",\n series: \"ElevenLabs\",\n description: \"Clone a voice from a short reference clip. Instant clone via direct ElevenLabs API.\",\n useCases: [\"voice-clone\", \"personalization\"],\n pricing: [{ identifier: \"voice-clone\", credits: 5 }],\n },\n \"elevenlabs-voice-design\": {\n id: \"elevenlabs-voice-design\",\n kind: \"audio\",\n modes: [\"voice-design\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs Voice Design\",\n series: \"ElevenLabs\",\n description: \"Design a synthetic voice from a description (no reference clip needed).\",\n useCases: [\"voice-design\", \"synthetic\"],\n pricing: [{ identifier: \"elevenlabs-voice-design\", credits: 5 }],\n },\n \"elevenlabs-voice-changer\": {\n id: \"elevenlabs-voice-changer\",\n kind: \"audio\",\n modes: [\"voice-changer\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs Voice Changer\",\n series: \"ElevenLabs\",\n description: \"Speech-to-speech: convert one voice to another while preserving prosody.\",\n useCases: [\"voice-conversion\", \"dubbing\"],\n pricing: [{ identifier: \"elevenlabs-voice-changer\", credits: 4 }],\n },\n \"elevenlabs-stt\": {\n id: \"elevenlabs-stt\",\n kind: \"audio\",\n modes: [\"stt\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs STT\",\n series: \"ElevenLabs\",\n description: \"Speech-to-text — transcribe audio with timestamps.\",\n useCases: [\"transcription\", \"stt\"],\n pricing: [{ identifier: \"elevenlabs-stt\", credits: 3 }],\n },\n \"elevenlabs-isolation\": {\n id: \"elevenlabs-isolation\",\n kind: \"audio\",\n modes: [\"isolation\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs Voice Isolation\",\n series: \"ElevenLabs\",\n description: \"Strip background noise / music from a vocal track.\",\n useCases: [\"cleanup\", \"isolation\"],\n pricing: [{ identifier: \"elevenlabs-isolation\", credits: 8, note: \"variable per second\" }],\n },\n \"elevenlabs-dubbing\": {\n id: \"elevenlabs-dubbing\",\n kind: \"audio\",\n modes: [\"dubbing\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs Dubbing\",\n series: \"ElevenLabs\",\n description: \"Translate + dub a video into a new language. Async.\",\n useCases: [\"dubbing\", \"multilingual\"],\n pricing: [{ identifier: \"elevenlabs-dubbing\", credits: 8 }],\n },\n \"elevenlabs-forced-alignment\": {\n id: \"elevenlabs-forced-alignment\",\n kind: \"audio\",\n modes: [\"forced-alignment\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs Forced Alignment\",\n series: \"ElevenLabs\",\n description: \"Align an existing transcript to audio with word-level timestamps.\",\n useCases: [\"alignment\", \"captions\"],\n pricing: [{ identifier: \"elevenlabs-forced-alignment\", credits: 3 }],\n },\n\n // ── ElevenLabs SFX ──\n \"elevenlabs-sfx\": {\n id: \"elevenlabs-sfx\",\n kind: \"audio\",\n modes: [\"sfx\"] as const,\n family: \"ElevenLabs\",\n label: \"ElevenLabs Sound Effects\",\n series: \"ElevenLabs\",\n description: \"Generate short sound effects from a text prompt.\",\n useCases: [\"sfx\", \"ambient\"],\n pricing: [{ identifier: \"elevenlabs-sfx\", credits: 1, note: \"~5s clip\" }],\n },\n\n // ── Suno music ──\n \"suno\": {\n id: \"suno\",\n kind: \"audio\",\n modes: [\"music\"] as const,\n family: \"Suno\",\n label: \"Suno v4\",\n series: \"Suno\",\n dataValue: \"V4\",\n description: \"Suno v4 music generation — full songs with vocals, multiple genres.\",\n useCases: [\"music\", \"song\", \"vocals\"],\n pricing: [{ identifier: \"suno\", credits: 3, note: \"per generation\" }],\n },\n \"suno-v5\": {\n id: \"suno-v5\",\n kind: \"audio\",\n modes: [\"music\"] as const,\n family: \"Suno\",\n label: \"Suno v5\",\n series: \"Suno\",\n dataValue: \"V5\",\n description: \"Newer Suno v5 — better vocal quality, more genres. Same price as v4.\",\n useCases: [\"music\", \"song\", \"vocals\", \"premium\"],\n pricing: [{ identifier: \"suno-v5\", credits: 3, note: \"per generation\" }],\n },\n \"suno-v5_5\": {\n id: \"suno-v5_5\",\n kind: \"audio\",\n modes: [\"music\"] as const,\n family: \"Suno\",\n label: \"Suno v5.5\",\n series: \"Suno\",\n dataValue: \"V5_5\",\n description: \"Suno v5.5 — latest model with improved audio quality and expressiveness.\",\n useCases: [\"music\", \"song\", \"vocals\", \"premium\"],\n pricing: [{ identifier: \"suno-v5_5\", credits: 3, note: \"per generation\" }],\n featured: true,\n },\n}\n\n// =============================================================================\n// COMBINED CATALOG\n// =============================================================================\nexport const MODEL_CATALOG: Record<string, ModelCatalogEntry> = {\n ...IMAGE_MODELS,\n ...VIDEO_MODELS,\n ...AUDIO_MODELS,\n}\n\n/**\n * Lookup helpers for MCP and the future frontend migration.\n */\nexport function listModels(filter?: {\n kind?: ModelKind\n mode?: ModelMode\n family?: string\n}): ModelCatalogEntry[] {\n const all = Object.values(MODEL_CATALOG)\n if (!filter) return all\n return all.filter((m) => {\n if (filter.kind && m.kind !== filter.kind) return false\n if (filter.mode && !m.modes.includes(filter.mode)) return false\n if (filter.family && m.family.toLowerCase() !== filter.family.toLowerCase()) return false\n return true\n })\n}\n\n/**\n * Group entries by family, returning a stable order.\n * Returns Array<{ family: string; models: ModelCatalogEntry[] }>.\n */\nexport function groupByFamily(\n entries: ModelCatalogEntry[],\n): Array<{ family: string; models: ModelCatalogEntry[] }> {\n const groups = new Map<string, ModelCatalogEntry[]>()\n for (const m of entries) {\n const list = groups.get(m.family)\n if (list) list.push(m)\n else groups.set(m.family, [m])\n }\n return Array.from(groups.entries()).map(([family, models]) => ({ family, models }))\n}\n\nexport function getModel(id: string): ModelCatalogEntry | undefined {\n return MODEL_CATALOG[id]\n}\n\n// =============================================================================\n// Per-model input validation\n// =============================================================================\nexport type ValidationField =\n | \"aspectRatio\"\n | \"resolution\"\n | \"quality\"\n | \"duration\"\n\nexport interface ModelValidationIssue {\n field: ValidationField\n message: string\n allowed: readonly (string | number)[] | null\n}\n\n/**\n * Validate that the user's lever values are supported by the chosen model.\n *\n * Returns null on success or the FIRST issue found. We surface a single issue\n * rather than collecting all so the agent doesn't get a wall of complaints —\n * fix one thing, retry. Order: aspectRatio → resolution → quality → duration.\n *\n * Semantics:\n * - If the field is undefined, it's never an issue.\n * - If the catalog entry doesn't list a corresponding lever (e.g. base\n * nano-banana has no `resolutions`), passing that field IS an issue —\n * silently dropping it has caused two bugs already.\n * - If the value is in the allow list, it's valid.\n *\n * Unknown model ids are NOT flagged here — the route handler / Zod model\n * enum is the right gate for that. We just skip validation.\n */\nexport function validateModelInput(\n modelId: string,\n input: {\n aspectRatio?: string\n resolution?: string\n quality?: string\n duration?: number\n },\n): ModelValidationIssue | null {\n const m = MODEL_CATALOG[modelId]\n if (!m) return null\n\n if (input.aspectRatio !== undefined) {\n if (!m.aspectRatios) {\n return {\n field: \"aspectRatio\",\n message: `Model \"${modelId}\" does not have an aspect_ratio lever — omit it.`,\n allowed: null,\n }\n }\n if (!m.aspectRatios.includes(input.aspectRatio)) {\n return {\n field: \"aspectRatio\",\n message: `Model \"${modelId}\" does not support aspect_ratio \"${input.aspectRatio}\". Supported: ${m.aspectRatios.join(\", \")}.`,\n allowed: m.aspectRatios,\n }\n }\n }\n\n if (input.resolution !== undefined) {\n if (!m.resolutions) {\n return {\n field: \"resolution\",\n message: `Model \"${modelId}\" does not have a resolution lever — omit it.`,\n allowed: null,\n }\n }\n if (!m.resolutions.includes(input.resolution)) {\n return {\n field: \"resolution\",\n message: `Model \"${modelId}\" does not support resolution \"${input.resolution}\". Supported: ${m.resolutions.join(\", \")}.`,\n allowed: m.resolutions,\n }\n }\n }\n\n if (input.quality !== undefined) {\n if (!m.qualities) {\n return {\n field: \"quality\",\n message: `Model \"${modelId}\" does not have a quality lever — omit it.`,\n allowed: null,\n }\n }\n if (!m.qualities.includes(input.quality)) {\n return {\n field: \"quality\",\n message: `Model \"${modelId}\" does not support quality \"${input.quality}\". Supported: ${m.qualities.join(\", \")}.`,\n allowed: m.qualities,\n }\n }\n }\n\n if (input.duration !== undefined) {\n if (!m.durations) {\n return {\n field: \"duration\",\n message: `Model \"${modelId}\" does not have a duration lever — omit it.`,\n allowed: null,\n }\n }\n if (!m.durations.includes(input.duration)) {\n return {\n field: \"duration\",\n message: `Model \"${modelId}\" does not support duration ${input.duration}s. Supported: ${m.durations.join(\", \")}s.`,\n allowed: m.durations,\n }\n }\n }\n\n return null\n}\n\n// =============================================================================\n// Frontend picker helpers — return `{value, label}[]` shapes that the\n// existing config-panel components expect, derived from the catalog so we\n// don't duplicate registries between backend and frontend.\n// =============================================================================\n\n/**\n * Global value-label decorations. Per-model overrides live on\n * `ModelCatalogEntry.valueLabels` (e.g. Hailuo's \"1080P (6s max)\").\n *\n * Add entries here when a value should render with a richer human label.\n * Plain values (3:2, 4:3, 720p, etc.) can stay undecorated — the value\n * itself is the label and we fall back to `value` automatically.\n */\nconst MODEL_VALUE_LABELS: Record<string, string> = {\n // aspect ratios\n \"1:1\": \"1:1 (Square)\",\n \"16:9\": \"16:9 (Landscape)\",\n \"9:16\": \"9:16 (Portrait)\",\n \"21:9\": \"21:9 (Ultra-wide)\",\n \"9:21\": \"9:21 (Tall ultra-wide)\",\n \"auto\": \"Auto\",\n \"adaptive\": \"Adaptive\",\n // image resolutions\n \"1K\": \"1K (Standard)\",\n \"2K\": \"2K (High)\",\n \"4K\": \"4K (Ultra)\",\n \"4k\": \"4K\",\n \"8K\": \"8K (Ultra)\",\n // qualities\n \"medium\": \"Medium (Balanced)\",\n \"high\": \"High (Detailed)\",\n \"basic\": \"Basic (2K)\",\n \"TURBO\": \"Turbo (fast)\",\n \"BALANCED\": \"Balanced\",\n \"QUALITY\": \"Quality (best)\",\n}\n\nfunction decorateLabel(model: ModelCatalogEntry, value: string): string {\n return model.valueLabels?.[value] ?? MODEL_VALUE_LABELS[value] ?? value\n}\n\nexport interface LabeledOption {\n value: string\n label: string\n}\n\n/** Return `{value, label}[]` for the model's aspect ratios, or `null` if none. */\nexport function getAspectRatioOptions(modelId: string): LabeledOption[] | null {\n const m = MODEL_CATALOG[modelId]\n if (!m?.aspectRatios) return null\n return m.aspectRatios.map((v) => ({ value: v, label: decorateLabel(m, v) }))\n}\n\n/** Return `{value, label}[]` for the model's resolution lever, or `null` if none. */\nexport function getResolutionOptions(modelId: string): LabeledOption[] | null {\n const m = MODEL_CATALOG[modelId]\n if (!m?.resolutions) return null\n return m.resolutions.map((v) => ({ value: v, label: decorateLabel(m, v) }))\n}\n\n/** Return `{value, label}[]` for the model's quality lever, or `null` if none. */\nexport function getQualityOptions(modelId: string): LabeledOption[] | null {\n const m = MODEL_CATALOG[modelId]\n if (!m?.qualities) return null\n return m.qualities.map((v) => ({ value: v, label: decorateLabel(m, v) }))\n}\n\n/** Return the model's allowed durations (in seconds), or `null` if none. */\nexport function getDurationsForModel(modelId: string): number[] | null {\n const m = MODEL_CATALOG[modelId]\n if (!m?.durations) return null\n return [...m.durations]\n}\n\n/**\n * Min/max credits across all pricing variants — used by the frontend's\n * \"5–8 cr\" range badge in the model dropdown. `null` for models with a\n * single price point.\n */\nexport function getCreditRange(modelId: string): { min: number; max: number } | null {\n const m = MODEL_CATALOG[modelId]\n if (!m || m.pricing.length < 2) return null\n let min = Infinity\n let max = -Infinity\n for (const p of m.pricing) {\n if (p.credits < min) min = p.credits\n if (p.credits > max) max = p.credits\n }\n return { min, max }\n}\n\n/** Whether the model declares a given capability flag in its `features` array. */\nexport function hasFeature(modelId: string, feature: string): boolean {\n return MODEL_CATALOG[modelId]?.features?.includes(feature) ?? false\n}\n\n/**\n * All ids in the catalog whose `features` includes the given flag. Used by\n * frontend to build PROVIDERS_WITH_END_FRAME / PROVIDERS_WITH_REFERENCES\n * lists derived from the catalog.\n */\nexport function modelsWithFeature(feature: string): string[] {\n return Object.values(MODEL_CATALOG)\n .filter((m) => m.features?.includes(feature))\n .map((m) => m.id)\n}\n\n/**\n * Map of `{modelId: durations[]}` for every catalog entry whose `modes`\n * includes the given mode. Used to derive KIE_VIDEO_DURATIONS (mode i2v)\n * and KIE_T2V_DURATIONS (mode t2v) on the frontend.\n */\nexport function durationsByMode(mode: ModelMode): Record<string, number[]> {\n const out: Record<string, number[]> = {}\n for (const m of Object.values(MODEL_CATALOG)) {\n if (!m.modes.includes(mode)) continue\n if (!m.durations) continue\n out[m.id] = [...m.durations]\n }\n return out\n}\n\n/**\n * Map of `{modelId: LabeledOption[]}` for every catalog entry of the given\n * kind that exposes a resolution lever. Used to derive\n * IMAGE_RESOLUTION_OPTIONS / VIDEO_RESOLUTION_OPTIONS on the frontend.\n */\nexport function resolutionOptionsByKind(kind: ModelKind): Record<string, LabeledOption[]> {\n const out: Record<string, LabeledOption[]> = {}\n for (const m of Object.values(MODEL_CATALOG)) {\n if (m.kind !== kind) continue\n if (!m.resolutions) continue\n out[m.id] = m.resolutions.map((v) => ({ value: v, label: decorateLabel(m, v) }))\n }\n return out\n}\n\n/**\n * Map of `{modelId: LabeledOption[]}` for every catalog entry of the given\n * kind that exposes an aspect_ratio lever.\n */\nexport function aspectRatioOptionsByKind(kind: ModelKind): Record<string, LabeledOption[]> {\n const out: Record<string, LabeledOption[]> = {}\n for (const m of Object.values(MODEL_CATALOG)) {\n if (m.kind !== kind) continue\n if (!m.aspectRatios) continue\n out[m.id] = m.aspectRatios.map((v) => ({ value: v, label: decorateLabel(m, v) }))\n }\n return out\n}\n\n/** Same shape as `aspectRatioOptionsByKind` but for `qualities`. */\nexport function qualityOptionsByKind(kind: ModelKind): Record<string, LabeledOption[]> {\n const out: Record<string, LabeledOption[]> = {}\n for (const m of Object.values(MODEL_CATALOG)) {\n if (m.kind !== kind) continue\n if (!m.qualities) continue\n out[m.id] = m.qualities.map((v) => ({ value: v, label: decorateLabel(m, v) }))\n }\n return out\n}\n\n/** One shaped model row for a picker — capabilities derived from the catalog. */\nexport interface ModelMenuOption {\n /** Catalog id (the API enum value). */\n id: string\n /** Human-readable display name from the catalog. */\n label: string\n /** Resolution levers, `[]` when the model exposes none. */\n resolutions: LabeledOption[]\n /** Aspect-ratio levers, `[]` when the model exposes none. */\n aspectRatios: LabeledOption[]\n /** Duration levers in seconds (union of i2v+t2v modes); `[]` for image / fixed-duration models. */\n durations: { value: number; label: string }[]\n}\n\n/**\n * Build shaped picker rows for one catalog `kind` from a caller-supplied id\n * allowlist (the curation — which ids, in what order, stays the caller's). Every\n * CAPABILITY is derived from the catalog accessors, never hardcoded, so the menu\n * can't drift as the catalog evolves. Ids absent from the catalog or of the\n * wrong kind are skipped (so a stale allowlist entry drops out cleanly). Pure;\n * returns fresh arrays (never aliases the accessor maps).\n */\nexport function buildModelMenu(\n kind: ModelKind,\n allowlist: readonly string[],\n): ModelMenuOption[] {\n const resByModel = resolutionOptionsByKind(kind)\n const arByModel = aspectRatioOptionsByKind(kind)\n const i2v = durationsByMode(\"i2v\")\n const t2v = durationsByMode(\"t2v\")\n const out: ModelMenuOption[] = []\n for (const id of allowlist) {\n const entry = MODEL_CATALOG[id]\n if (!entry || entry.kind !== kind) continue\n const durations = Array.from(new Set([...(i2v[id] ?? []), ...(t2v[id] ?? [])]))\n .sort((a, b) => a - b)\n .map((n) => ({ value: n, label: `${n}s` }))\n out.push({\n id: entry.id,\n label: entry.label,\n resolutions: [...(resByModel[id] ?? [])],\n aspectRatios: [...(arByModel[id] ?? [])],\n durations,\n })\n }\n return out\n}\n\n/** All `{modelId: {min, max}}` entries that have variable pricing (>1 variant). */\nexport function creditRangesAll(): Record<string, { min: number; max: number }> {\n const out: Record<string, { min: number; max: number }> = {}\n for (const m of Object.values(MODEL_CATALOG)) {\n const range = getCreditRange(m.id)\n if (range) out[m.id] = range\n }\n return out\n}\n\n/**\n * Tuple of model ids for a given kind + one or more modes. Built for use as\n * a Zod `z.enum()` argument so MCP tool input schemas stay in sync with the\n * catalog without manual maintenance.\n *\n * Filters out `mcpHidden: true` entries by default — pass `includeHidden`\n * to surface legacy versions (used internally by validators that still need\n * to recognize older ids forwarded by direct API callers).\n *\n * Pass `kind: null` to skip the kind filter — useful for cross-kind ids\n * like \"grok\" (catalog kind=image, modes include both t2i and t2v).\n */\nexport function modelIdsByKindMode(\n kind: ModelKind | null,\n modes: readonly ModelMode[],\n opts: { includeHidden?: boolean } = {},\n): [string, ...string[]] {\n const includeHidden = opts.includeHidden === true\n const ids = Object.values(MODEL_CATALOG)\n .filter((m) => (kind === null ? true : m.kind === kind))\n .filter((m) => m.modes.some((md) => modes.includes(md)))\n .filter((m) => includeHidden || !m.mcpHidden)\n .map((m) => m.id)\n .sort()\n if (ids.length === 0) {\n throw new Error(\n `modelIdsByKindMode: no models match kind=${kind ?? \"*\"} modes=[${modes.join(\",\")}]`,\n )\n }\n return ids as [string, ...string[]]\n}\n","/**\n * Model constants shared between frontend and backend.\n * Single source of truth for model capability sets and variable pricing rules.\n */\nimport { z } from \"zod\"\nimport { MODEL_CATALOG } from \"./model-catalog.js\"\n\n/** Base USD cost per 1 Nodaro credit, at cost. Used for cost→credit conversion. */\nexport const CREDIT_BASE_USD = 0.02\n\n/** Max characters for the (assembled) prompt accepted by the image-generation routes\n * (generate-image, image-to-image, edit-image). Single source of truth — the route Zod\n * schemas and the factory-preset guard test all read this. Prompt cap ONLY (not negativePrompt). */\nexport const IMAGE_PROMPT_MAX = 5000\n\n/**\n * Per-provider maximum ASSEMBLED image-prompt length (chars), VERIFIED against\n * each model's official docs.kie.ai schema (2026-06). Providers absent here use\n * {@link IMAGE_PROMPT_MAX} (the documented KIE \"standard\" of 5000). Read via\n * {@link getMaxImagePromptChars} by the prompt assembler's truncation AND the\n * frontend over-limit warning — the data-driven replacement for the old\n * hardcoded 2000 that silently severed appended cinematography hints + the\n * `Avoid:` negative on long prompts.\n *\n * Both directions matter: some models accept FAR MORE than 5000 (nano-banana-2 /\n * gpt-image-2-i2i = 20000) and some FAR LESS (seedream-5-lite = 1000) — sending\n * 5000 to a 1000-char model is a provider-side rejection. Only list a value you\n * can quote from the official schema; the t2i / i2i / edit siblings of one family\n * genuinely differ (verified: qwen t2i 3000 vs qwen-i2i 5000 vs qwen-edit 2000),\n * so never copy a sibling's number.\n *\n * Truncation is a graceful safety net, never a hard reject — the editor warns the\n * user BEFORE submit (switch model / trim) and the assembler truncates if they\n * proceed. So the image routes stay generous (a single high ceiling) and the\n * per-model enforcement lives here.\n */\nexport const MAX_IMAGE_PROMPT_CHARS_BY_PROVIDER: Record<string, number> = {\n // ── higher than the 5000 default ──\n \"nano-banana-2\": 20000, // docs.kie.ai/market/google/nano-banana-2\n \"nano-banana-pro\": 20000, // docs.kie.ai/market/google/pro-image-to-image\n \"gpt-image-2-i2i\": 20000, // docs.kie.ai/market/gpt/gpt-image-2-image-to-image\n // ── lower than the 5000 default (over-send risk if left at default) ──\n \"seedream\": 3000, // docs.kie.ai/market/seedream/4-5-text-to-image\n \"seedream-edit\": 3000, // docs.kie.ai/market/seedream/4-5-edit\n \"seedream-5-lite\": 1000, // docs.kie.ai/market/seedream/5-lite-text-to-image\n \"seedream-5-lite-i2i\": 3000, // docs.kie.ai/market/seedream-5-lite-image-to-image (NB: t2i sibling is 1000)\n \"qwen\": 3000, // docs.kie.ai/market/qwen/text-to-image\n \"qwen-edit\": 2000, // docs.kie.ai/market/qwen/image-edit\n // verified == 5000 default (no entry needed): imagen4(-fast/-ultra), nano-banana,\n // nano-banana-edit, flux, flux-flex, gpt-image-2, ideogram-v3/-edit/-remix,\n // z-image, grok, qwen-i2i.\n // grok-i2i: doc states 390000 (78× its t2i sibling) — treated as a KIE schema\n // typo and left at the 5000 default per the sanity-cap decision.\n // UNVERIFIED (no limit stated in schema) → 5000 default: flux-kontext(-max)\n // gpt-image, gpt-image-i2i, flux-i2i, flux-pro-i2i, ideogram-reframe.\n}\n\n/** Max assembled image-prompt length (chars) for a provider: its verified\n * override from {@link MAX_IMAGE_PROMPT_CHARS_BY_PROVIDER}, else the\n * {@link IMAGE_PROMPT_MAX} default. Single source of truth shared by the prompt\n * assembler, the over-limit warning, and the image-route ceiling. */\nexport function getMaxImagePromptChars(provider: string | undefined): number {\n return (provider && MAX_IMAGE_PROMPT_CHARS_BY_PROVIDER[provider]) || IMAGE_PROMPT_MAX\n}\n\n/**\n * Video prompt/negative cap shared by routes + editor (MCP verbs already use\n * 8000). Providers allow far more (KIE seedance-2: 20k chars) — the old\n * per-route 2500 was a false-positive blocker for legitimate multi-shot\n * Seedance prompts.\n */\nexport const VIDEO_PROMPT_MAX = 8000\n\n/**\n * Suno prompt / lyrics / content ceiling — the LARGEST any Suno version accepts\n * in custom mode (V4.5 / V4.5PLUS / V4.5ALL / V5 / V5.5 = 5000). The route Zod\n * uses this as a generous ceiling; the handler clamps to the per-version cap via\n * {@link getMaxSunoPromptChars} (V4/V3.5 = 3000, non-custom = 500). Shared with\n * the editor `maxLength` / counter (warn-don't-block at the per-version cap).\n * `style` and `title` have their own caps ({@link getMaxSunoStyleChars} /\n * {@link SUNO_TITLE_MAX}).\n */\nexport const SUNO_TEXT_MAX = 5000\n\n/**\n * Absolute ceiling for the `prompt` / `negativePrompt` fields on the image and\n * video routes' Zod schemas. The PER-MODEL limits below (and the editor warning)\n * do the real work; the routes stay generous so they never hard-reject a legit\n * long prompt — the assembler/payload truncates to the model cap as a graceful\n * safety net (warn-don't-block). 20000 = the largest verified per-model image/\n * video limit (seedance-2 / nano-banana-2 / gemini-omni). Anything past this is\n * abuse, not a real prompt.\n */\nexport const PROMPT_HARD_CEILING = 20000\n\n/**\n * Per-provider maximum VIDEO prompt length (chars), VERIFIED against each model's\n * official docs.kie.ai schema (2026-06). Absent → {@link VIDEO_PROMPT_MAX} (8000)\n * default (used for models whose schema states NO limit: veo3 family, kling-3.0,\n * kling-3-omni, runway-aleph). Read via {@link getMaxVideoPromptChars}.\n *\n * Most video models cap WELL BELOW the old flat 8000 (kling 2.6 = 1000!), so the\n * 8000 route value was over-sending to nearly every provider. A few accept much\n * more (seedance-2 = 20000). Mode note: where a model's t2v and i2v schemas\n * differ, the SMALLER is used so neither mode over-sends (hailuo-2.3-pro: t2v\n * 1500 / i2v 5000 → 1500).\n */\nexport const MAX_VIDEO_PROMPT_CHARS_BY_PROVIDER: Record<string, number> = {\n // Kling family — our `kling`→kling-2.6 (1000), `kling-turbo`→v2.5-turbo-pro (2500)\n \"kling\": 1000,\n \"kling-turbo\": 2500,\n \"kling-master\": 5000,\n // higher than the 8000 default\n \"seedance-2\": 20000,\n \"seedance-2-fast\": 20000,\n \"seedance-2-mini\": 20000,\n \"seedance-2-extend\": 20000,\n \"gemini-omni-video\": 20000,\n \"bytedance-lite\": 10000,\n \"bytedance-pro\": 10000,\n \"bytedance-pro-fast\": 10000,\n // lower than the 8000 default\n \"minimax\": 1500,\n \"hailuo-standard\": 1500,\n \"hailuo-2.3-pro\": 1500, // t2v 1500 / i2v 5000 → smaller, safe for both modes\n \"hailuo-2.3\": 5000,\n \"seedance\": 2500, // Seedance 1.5 Pro\n \"wan\": 5000,\n \"wan-i2v\": 5000,\n \"wan-turbo\": 5000,\n \"wan-flash\": 1500,\n \"wan-videoedit\": 5000,\n \"wan-2.7-i2v\": 5000,\n \"wan-2.7-t2v\": 5000,\n \"grok-i2v\": 5000,\n \"grok-imagine-video-1.5\": 4096,\n \"happyhorse\": 5000,\n \"happyhorse-i2v\": 5000,\n \"happyhorse-ref2v\": 5000,\n \"happyhorse-edit\": 5000,\n \"runway-kie\": 1800,\n // NB: `wan-2.7` / `wan-2.7-pro` are IMAGE models (see the image registry), not\n // video. The motion-transfer route's prompt is capped at the motion-control\n // limit (2500) inside the route itself — its provider values are the shared\n // `kling` (→1000 here, safely tighter) / `kling-3.0` ids, not a \"motion-*\" id.\n // UNVERIFIED (schema states no limit) → 8000 default: veo3, veo3.1, veo3_lite\n // kling-3.0, kling-3-omni, runway-aleph.\n}\n\n/** Max video-prompt length (chars) for a provider: verified override, else\n * {@link VIDEO_PROMPT_MAX}. Shared by the video routes/payload truncation and\n * the editor over-limit warning. */\nexport function getMaxVideoPromptChars(provider: string | undefined): number {\n return (provider && MAX_VIDEO_PROMPT_CHARS_BY_PROVIDER[provider]) || VIDEO_PROMPT_MAX\n}\n\n/** Default negative-prompt cap when a provider has no specific verified limit. */\nexport const NEGATIVE_PROMPT_MAX = 5000\n\n/**\n * Per-provider native `negative_prompt` cap (chars), VERIFIED from docs.kie.ai.\n * Only matters for providers that send the negative as a NATIVE param\n * ({@link NATIVE_NEGATIVE_PROMPT_MODELS} / {@link NATIVE_NEGATIVE_VIDEO_PROVIDERS});\n * everywhere else the negative is folded into the prompt as `Avoid: …` and rides\n * the prompt cap. Absent → {@link NEGATIVE_PROMPT_MAX}.\n */\nexport const MAX_NEGATIVE_PROMPT_CHARS_BY_PROVIDER: Record<string, number> = {\n // image\n \"imagen4\": 5000, \"imagen4-fast\": 5000, \"imagen4-ultra\": 5000,\n \"ideogram-v3\": 500, \"ideogram-remix\": 5000,\n \"qwen\": 500, \"qwen-i2i\": 500, \"qwen-edit\": 500,\n // video (native-negative families)\n \"kling-master\": 500,\n \"kling-turbo\": 500, // i2v 500 / t2v 2500 → smaller, safe for both modes\n \"wan-2.7-i2v\": 500, \"wan-2.7-t2v\": 500, \"wan-videoedit\": 500,\n}\n\n/** Max native negative-prompt length (chars) for a provider. */\nexport function getMaxNegativePromptChars(provider: string | undefined): number {\n return (provider && MAX_NEGATIVE_PROMPT_CHARS_BY_PROVIDER[provider]) || NEGATIVE_PROMPT_MAX\n}\n\n/** Default TTS text cap (legacy `elevenlabs`) when no per-model override. */\nexport const TTS_TEXT_MAX = 5000\n\n/**\n * Per-model Text-to-Speech character cap (PER REQUEST), from official ElevenLabs\n * docs. turbo/multilingual accept FAR more than the old flat 5000; v3 uses the\n * conservative 3000 (official pages say 5000 but the API is widely reported to\n * hard-limit v3 at 3000 — conservative avoids prod rejections). Absent →\n * {@link TTS_TEXT_MAX}.\n */\nexport const MAX_TTS_CHARS_BY_PROVIDER: Record<string, number> = {\n \"elevenlabs-turbo\": 40000, // == eleven_flash_v2_5 (functionally equivalent)\n \"elevenlabs-multilingual\": 10000, // eleven_multilingual_v2\n \"elevenlabs-v3\": 3000, // conservative (official 5000 / API-reported 3000)\n \"elevenlabs-dialogue\": 2000, // text-to-dialogue recommended per-request max\n}\n\n/** Max TTS text length (chars) for a provider: verified override, else {@link TTS_TEXT_MAX}. */\nexport function getMaxTtsChars(provider: string | undefined): number {\n return (provider && MAX_TTS_CHARS_BY_PROVIDER[provider]) || TTS_TEXT_MAX\n}\n\n/**\n * Suno per-version field caps (from docs.kie.ai/suno-api/generate-music). The old\n * flat {@link SUNO_TEXT_MAX} (3000) was simultaneously too low for V4.5+/V5\n * prompts (5000) and too high for `style` (1000) and `title` (80).\n * - prompt / lyrics: 500 in non-custom mode (all versions); in custom mode\n * 3000 for V4/V3.5 and 5000 for V4.5 / V4.5PLUS / V4.5ALL / V5 / V5.5.\n * - style: 200 for V4/V3.5, 1000 for V4.5+.\n * - title: 80 (all versions).\n */\nexport const SUNO_TITLE_MAX = 80\n\n/** Max Suno `prompt` (= lyrics in custom mode) length for a model version. */\nexport function getMaxSunoPromptChars(model: string | undefined, customMode: boolean): number {\n if (!customMode) return 500\n return model === \"V4\" || model === \"V3_5\" ? 3000 : 5000\n}\n\n/** Max Suno `style` length for a model version. */\nexport function getMaxSunoStyleChars(model: string | undefined): number {\n return model === \"V4\" || model === \"V3_5\" ? 200 : 1000\n}\n\n// Models that accept negative_prompt as a native API parameter.\n// All other models get negative prompt appended to the prompt text as \"Avoid: ...\".\nexport const NATIVE_NEGATIVE_PROMPT_MODELS = new Set([\n \"imagen4\", \"imagen4-fast\", \"imagen4-ultra\",\n \"ideogram-remix\", \"ideogram-v3\",\n \"qwen\", \"qwen-edit\",\n])\n\n/**\n * Video providers that accept `negative_prompt` natively in their KIE.ai\n * request payload. Everywhere else, the helper below appends `Avoid: <text>`\n * to the prompt instead so the negative intent still reaches the model.\n *\n * Sourced from inline comments in `backend/src/providers/kie/video.ts`\n * (Kling family + Wan family) plus the wan-s2v speech-to-video flow.\n *\n * NOT included (KIE will silently drop the param):\n * minimax / hailuo-* family, veo3.* family, sora2 / sora2-pro,\n * bytedance-* family, grok / grok-i2v, seedance-* family,\n * happyhorse-*, ltx-* family, runway-kie, wan-animate-move/replace\n * (Wan Animate is a separate model from regular Wan and doesn't take\n * negative_prompt — verified against KIE docs 2026-05-28).\n */\nexport const NATIVE_NEGATIVE_VIDEO_PROVIDERS = new Set<string>([\n // Kling family\n \"kling\", \"kling-turbo\", \"kling-master\", \"kling-3.0\", \"kling-3-omni\",\n // Wan family (regular Wan, NOT wan-animate)\n \"wan\", \"wan-flash\", \"wan-videoedit\",\n \"wan-i2v\", \"wan-turbo\",\n \"wan-2.7-i2v\", \"wan-2.7-t2v\",\n // Wan speech-to-video\n \"wan-s2v\",\n])\n\n/**\n * Apply the negative prompt to a video-provider request.\n *\n * If the provider natively accepts `negative_prompt` (Kling / Wan families),\n * the helper returns the original prompt and the trimmed negative as\n * `nativeNegativePrompt` — the caller should forward it as the API's\n * dedicated field.\n *\n * Otherwise, the helper appends `Avoid: <negativePrompt>` to the prompt\n * (consistent with `buildImagePrompt` in `prompt-builder.ts`) so the model\n * still sees the negative intent, and returns `nativeNegativePrompt = undefined`.\n *\n * Empty / missing negative is a no-op.\n *\n * Naming mirrors the established image-side pattern. Keep the wording\n * identical to `prompt-builder.ts` (\"Avoid: ...\") so users moving between\n * image and video nodes see consistent behavior.\n */\nexport function applyVideoNegativePrompt(\n prompt: string | undefined,\n negativePrompt: string | undefined,\n provider: string,\n): { prompt: string | undefined; nativeNegativePrompt: string | undefined } {\n // This is the universal \"finalize the video prompt for the provider\" chokepoint\n // (every KIE video method, the extend route, the orchestrator, and the editor\n // preview route through it). So it ALSO clamps to the model's verified caps —\n // a graceful safety net (the editor warns the user first; warn-don't-block).\n // Under-cap prompts (the common case) pass through byte-identical.\n const promptMax = getMaxVideoPromptChars(provider)\n const clamp = (p: string | undefined): string | undefined =>\n p != null && p.length > promptMax ? p.slice(0, promptMax) : p\n\n const neg = negativePrompt?.trim()\n if (!neg) return { prompt: clamp(prompt), nativeNegativePrompt: undefined }\n if (NATIVE_NEGATIVE_VIDEO_PROVIDERS.has(provider)) {\n // Native negative rides its own param → clamp each independently.\n return { prompt: clamp(prompt), nativeNegativePrompt: neg.slice(0, getMaxNegativePromptChars(provider)) }\n }\n // Non-native: fold the negative into the prompt as \"Avoid: …\". Reserve room for\n // the suffix so a long base prompt can't sever the negative (mirror the image\n // assembler), then clamp the whole to the model cap.\n const base = prompt && prompt.trim().length > 0 ? prompt : \"\"\n if (!base) return { prompt: `Avoid: ${neg}`.slice(0, promptMax), nativeNegativePrompt: undefined }\n const avoid = `\\nAvoid: ${neg}`\n const room = Math.max(0, promptMax - avoid.length)\n const injected = `${base.slice(0, room)}${avoid}`.slice(0, promptMax)\n return { prompt: injected, nativeNegativePrompt: undefined }\n}\n\n// Image providers that natively use reference images in their API.\n// Used by `buildImagePrompt` to filter referenceImageUrls before sending,\n// and by the frontend to warn when the user has `{image:N:label}` tokens\n// in a prompt for a provider that would silently ignore them.\n//\n// Verified against backend/src/providers/kie/models.ts (inputType +\n// imageParam) and the i2i flow in backend/src/providers/kie/image.ts.\n//\n// Image providers that natively use reference images in their API.\n//\n// Two categories included:\n// 1. Direct ref support: nano-banana family (multi-ref T2I) + flux-kontext\n// (single image edit) + all i2i/edit variants.\n// 2. Auto-switched: T2I models that have an i2i sibling — when the user\n// attaches refs to one of these in a generate-image node, the backend\n// route silently routes to the i2i sibling. See `T2I_TO_I2I_VARIANT`.\n// User-facing benefit: pick GPT Image / Grok / Qwen / Seedream / Flux at\n// the dropdown, attach refs, and they \"just work\".\n//\n// Excluded (no ref support and no i2i sibling — refs would be useless):\n// imagen4, imagen4-fast, imagen4-ultra, ideogram-v3, z-image\nexport const MODELS_WITH_REFERENCE_IMAGE_SUPPORT = new Set([\n // Multi-reference text-to-image\n \"nano-banana\",\n \"nano-banana-pro\",\n \"nano-banana-2\",\n // T2I providers that auto-route to their i2i sibling when refs are attached\n \"gpt-image\",\n \"gpt-image-2\",\n \"grok\",\n \"qwen\",\n \"seedream\",\n \"seedream-5-lite\",\n \"flux\",\n \"flux-flex\",\n // Image editing / image-to-image (reference = source image)\n \"nano-banana-edit\",\n \"gpt-image-i2i\",\n \"gpt-image-2-i2i\",\n \"flux-i2i\",\n \"flux-pro-i2i\",\n \"flux-kontext\",\n \"flux-kontext-max\",\n \"ideogram-edit\",\n \"ideogram-remix\",\n \"ideogram-reframe\",\n \"qwen-i2i\",\n \"qwen-edit\",\n \"seedream-edit\",\n \"seedream-5-lite-i2i\",\n \"grok-i2i\",\n // Upscale / background ops (source acts as the reference)\n \"recraft-remove-bg\",\n \"recraft-upscale\",\n \"topaz-image-upscale\",\n // Wan 2.7 — accepts up to 9 optional ref images via input_urls (pure T2I when omitted)\n \"wan-2.7\",\n // Replicate \"Open\" (uncensored) image models\n \"flux-2-klein\",\n \"kontext-multi\",\n \"flux-2-pro\",\n \"flux-2-max\",\n])\n\n/**\n * T2I provider → i2i sibling. When a generate-image node carries reference\n * images and the chosen provider is in this map, the backend route\n * transparently routes to the i2i variant so the refs are actually used.\n *\n * The user keeps seeing the T2I name in the UI; the warning component shows\n * an info hint that the i2i variant is being used under the hood.\n */\nexport const T2I_TO_I2I_VARIANT: Record<string, string> = {\n \"gpt-image\": \"gpt-image-i2i\",\n \"gpt-image-2\": \"gpt-image-2-i2i\",\n \"grok\": \"grok-i2i\",\n \"qwen\": \"qwen-i2i\",\n \"seedream\": \"seedream-edit\",\n \"seedream-5-lite\": \"seedream-5-lite-i2i\",\n \"flux\": \"flux-pro-i2i\",\n \"flux-flex\": \"flux-i2i\",\n}\n\n/**\n * Maximum number of reference images each provider accepts.\n * Sourced from the corresponding KIE.ai endpoint's documented input array\n * size, or from the model's natural input shape (single-source i2i = 1).\n *\n * Providers absent from this map default to `DEFAULT_REF_IMAGE_MAX` (4).\n * Providers absent from `MODELS_WITH_REFERENCE_IMAGE_SUPPORT` ignore\n * reference images entirely regardless of this value.\n */\nexport const REF_IMAGE_MAX_LIMITS: Record<string, number> = {\n // Multi-reference T2I (Nano Banana family is the only T2I family that\n // actually accepts ref URLs via the KIE wrapper's `image_input` param).\n \"nano-banana\": 8,\n \"nano-banana-pro\": 8,\n \"nano-banana-2\": 4,\n \"wan-2.7\": 9,\n // Image-to-image (multi-source array)\n \"nano-banana-edit\": 8,\n \"gpt-image-i2i\": 16,\n \"gpt-image-2-i2i\": 16,\n \"flux-i2i\": 4,\n \"flux-pro-i2i\": 4,\n \"seedream-edit\": 16,\n \"seedream-5-lite-i2i\": 16,\n // Single-source i2i (one input image)\n \"flux-kontext\": 1,\n \"flux-kontext-max\": 1,\n \"ideogram-edit\": 1,\n \"ideogram-remix\": 1,\n \"ideogram-reframe\": 1,\n \"qwen-i2i\": 1,\n \"qwen-edit\": 1,\n \"grok-i2i\": 1,\n \"recraft-remove-bg\": 1,\n \"recraft-upscale\": 1,\n \"topaz-image-upscale\": 1,\n // Replicate Open models — Klein takes an optional single ref; Kontext Multi\n // (multi-image-kontext-pro) is a two-image combiner (input_image_1/2 only);\n // Flux 2 Pro up to 4; Max up to 8.\n \"flux-2-klein\": 1,\n \"kontext-multi\": 2,\n \"flux-2-pro\": 4,\n \"flux-2-max\": 8,\n}\n\nexport const DEFAULT_REF_IMAGE_MAX = 4\n\n/**\n * Maximum reference images the UI should advertise for an IMAGE model — the\n * scalar image analogue of the video side's `videoReferenceLimits` (images have\n * a single reference kind, so a scalar suffices). Studio's Framing picker reads\n * this for its \"References\" chip; the editor's reference-handle popover reads it\n * too (via `getHandleConnectionLimit`).\n *\n * Returns 0 when the model accepts no reference images at all (so callers can\n * hide the chip / disable the handle), else the per-model cap from\n * {@link REF_IMAGE_MAX_LIMITS} (fallback {@link DEFAULT_REF_IMAGE_MAX}).\n * Therefore `imageReferenceLimit(p) > 0` is an exact \"supports references\" gate.\n *\n * Two behaviors keep the count matching what a user actually gets:\n * 1. T2I → i2i resolution. Pickers list text-to-image ids (grok, gpt-image-2,\n * seedream-5-lite, flux, …). When references are attached the generate-image\n * route silently routes to the i2i sibling ({@link T2I_TO_I2I_VARIANT}) —\n * the endpoint that actually consumes refs — so the advertised cap is the\n * SIBLING's (grok→grok-i2i = 1, gpt-image-2→gpt-image-2-i2i = 16), never the\n * t2i id's absent default. Mirrors the route's `resolveEffectiveProvider`.\n * 2. {@link REF_IMAGE_MAX_LIMITS} is the PRODUCT/UI cap, which may be\n * intentionally TIGHTER than the raw provider schema (e.g. flux-2-pro = 4\n * here though the BFL schema accepts 8; flux-2-klein = 1 though the array\n * slices at 5). The user-facing count must reflect the product cap, so the\n * reader reads this map verbatim — do NOT \"fix\" these to the schema maxima.\n */\nexport function imageReferenceLimit(provider: string | undefined): number {\n if (!provider || !MODELS_WITH_REFERENCE_IMAGE_SUPPORT.has(provider)) return 0\n const effective = T2I_TO_I2I_VARIANT[provider] ?? provider\n return REF_IMAGE_MAX_LIMITS[effective] ?? DEFAULT_REF_IMAGE_MAX\n}\n\n// Variable pricing: which setting type affects cost per provider\nexport const VARIABLE_PRICING_MODELS: Record<string, \"quality\" | \"resolution\" | \"rendering-speed\"> = {\n \"gpt-image\": \"quality\",\n \"gpt-image-i2i\": \"quality\",\n \"gpt-image-2\": \"resolution\",\n \"gpt-image-2-i2i\": \"resolution\",\n \"nano-banana-pro\": \"resolution\",\n \"nano-banana-2\": \"resolution\",\n \"flux\": \"resolution\",\n \"flux-flex\": \"resolution\",\n \"flux-i2i\": \"resolution\",\n \"flux-pro-i2i\": \"resolution\",\n \"seedream\": \"quality\",\n \"seedream-edit\": \"quality\",\n \"seedream-5-lite\": \"quality\",\n \"seedream-5-lite-i2i\": \"quality\",\n \"topaz-image-upscale\": \"resolution\",\n \"ideogram-edit\": \"rendering-speed\",\n \"ideogram-remix\": \"rendering-speed\",\n \"ideogram-reframe\": \"rendering-speed\",\n \"ideogram-v3\": \"rendering-speed\",\n \"wan-2.7\": \"resolution\",\n \"wan-2.7-pro\": \"resolution\",\n}\n\n\n// Models where quality=high triggers composite credit identifier\nexport const HIGH_QUALITY_PROVIDERS = new Set([\"gpt-image\", \"gpt-image-i2i\", \"seedream\", \"seedream-edit\", \"seedream-5-lite\", \"seedream-5-lite-i2i\"])\n\n// Models where resolution=2K triggers composite credit identifier\nexport const TWO_K_RESOLUTION_PROVIDERS = new Set([\"flux\", \"flux-pro-i2i\", \"flux-flex\", \"flux-i2i\"])\n\n// Models where both 2K and 4K resolutions trigger composite credit identifiers (1K is base)\nexport const RESOLUTION_2K_4K_TIERED_PROVIDERS = new Set([\n \"nano-banana-2\",\n \"gpt-image-2\",\n \"gpt-image-2-i2i\",\n \"wan-2.7\",\n \"wan-2.7-pro\",\n])\n\n// Ideogram family models with TURBO/QUALITY pricing variants\nexport const IDEOGRAM_PROVIDERS = new Set([\"ideogram-edit\", \"ideogram-remix\", \"ideogram-reframe\", \"ideogram-v3\"])\n\n// =====================================================================\n// Provider arrays (single source of truth for route Zod validation)\n// =====================================================================\n\n/** Text-to-image providers (no input image required) */\nexport const IMAGE_GEN_PROVIDERS = [\n \"nano-banana\",\n \"flux\",\n \"nano-banana-pro\",\n \"nano-banana-2\",\n \"grok\",\n \"gpt-image\",\n \"gpt-image-2\",\n \"imagen4\",\n \"imagen4-fast\",\n \"imagen4-ultra\",\n \"ideogram-v3\",\n \"qwen\",\n \"seedream\",\n \"seedream-5-lite\",\n \"flux-flex\",\n \"flux-kontext\",\n \"flux-kontext-max\",\n \"z-image\",\n \"wan-2.7\",\n \"wan-2.7-pro\",\n // Replicate Open (uncensored) — runs through Replicate, not KIE\n \"flux-2-klein\",\n \"flux-2-pro\",\n \"flux-2-max\",\n] as const\n\n/** Image-to-image providers (require input image) */\nexport const IMAGE_I2I_PROVIDERS = [\n \"nano-banana\",\n \"nano-banana-2\",\n \"nano-banana-pro\",\n \"grok-i2i\",\n \"flux-i2i\",\n \"flux-pro-i2i\",\n \"gpt-image-i2i\",\n \"gpt-image-2-i2i\",\n \"ideogram-edit\",\n \"ideogram-remix\",\n \"ideogram-reframe\",\n \"qwen-i2i\",\n \"qwen-edit\",\n \"seedream-edit\",\n \"seedream-5-lite-i2i\",\n \"flux-kontext\",\n \"flux-kontext-max\",\n // Replicate Open (uncensored) — multi-image Kontext via Replicate\n \"kontext-multi\",\n // BFL Flux 2 Pro — runs through Replicate with safety_tolerance=5 (max for Pro)\n \"flux-2-pro\",\n // BFL Flux 2 Max — runs through Replicate with safety_tolerance=5, up to 8 refs\n \"flux-2-max\",\n] as const\n\n/** Image editing providers (upscale, remove bg, etc.) */\nexport const IMAGE_EDIT_PROVIDERS = [\n \"recraft-upscale\",\n \"recraft-remove-bg\",\n \"nano-banana-edit\",\n \"topaz-image-upscale\",\n // grok-upscale takes a prior Grok generation's task_id (NOT an image URL) —\n // see edit-image route for the taskId-vs-imageUrl branching.\n \"grok-upscale\",\n] as const\n\n/** Modify image providers (I2I + edit-with-prompt) */\nexport const MODIFY_IMAGE_PROVIDERS = [\n ...IMAGE_I2I_PROVIDERS,\n \"nano-banana-edit\",\n] as const\nexport type ModifyImageProvider = typeof MODIFY_IMAGE_PROVIDERS[number]\n\n/** Image upscale providers */\nexport const UPSCALE_IMAGE_PROVIDERS = [\n \"recraft-upscale\",\n \"topaz-image-upscale\",\n] as const\nexport type UpscaleImageProvider = typeof UPSCALE_IMAGE_PROVIDERS[number]\n\n// Derived types from provider arrays\nexport type ImageGenProvider = typeof IMAGE_GEN_PROVIDERS[number]\nexport type ImageI2IProvider = typeof IMAGE_I2I_PROVIDERS[number]\nexport type ImageEditProvider = typeof IMAGE_EDIT_PROVIDERS[number]\n\n/** Image-to-video providers */\nexport const IMAGE_TO_VIDEO_PROVIDERS = [\n \"minimax\",\n \"veo3\",\n \"veo3.1\",\n \"veo3_lite\",\n \"kling\",\n \"kling-turbo\",\n \"kling-3.0\",\n \"kling-master\",\n \"seedance\",\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n \"hailuo-2.3-pro\",\n \"hailuo-2.3\",\n \"hailuo-standard\",\n \"wan-i2v\",\n \"wan-turbo\",\n \"bytedance-lite\",\n \"bytedance-pro\",\n \"bytedance-pro-fast\",\n \"grok-i2v\",\n \"wan-2.7-i2v\",\n \"happyhorse-i2v\",\n \"happyhorse-ref2v\",\n \"runway-kie\",\n \"kling-3-omni\",\n \"gemini-omni-video\",\n \"ltx-2.3-pro\",\n \"ltx-2.3-fast\",\n // xAI Grok Imagine Video 1.5 — KIE i2v (image_urls required). Also listed in\n // TEXT_TO_VIDEO_PROVIDERS so it's offered everywhere in the unified node; the\n // t2v route guards no-image runs via VIDEO_PROVIDERS_REQUIRING_IMAGE.\n \"grok-imagine-video-1.5\",\n // Replicate disabled\n // \"runway\",\n // \"pika\",\n // \"sora\",\n] as const\nexport type ImageToVideoProvider = typeof IMAGE_TO_VIDEO_PROVIDERS[number]\n\n/** Text-to-video providers */\nexport const TEXT_TO_VIDEO_PROVIDERS = [\n \"minimax\",\n \"veo3\",\n \"veo3.1\",\n \"veo3_lite\",\n \"kling\",\n \"kling-turbo\",\n \"kling-3.0\",\n \"grok\",\n \"seedance\",\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n \"wan\",\n \"hailuo-standard\",\n \"bytedance-lite\",\n \"bytedance-pro\",\n \"wan-turbo\",\n \"wan-2.7-t2v\",\n \"happyhorse\",\n \"runway-kie\",\n \"gemini-omni-video\",\n \"ltx-2.3-pro\",\n \"ltx-2.3-fast\",\n // ── i2v-only providers (image required) ──────────────────────────────────\n // These have NO text-to-video mode, but the unified Generate Video node can\n // dispatch ANY of its providers down the t2v path when no image is wired.\n // They must pass this enum so /v1/text-to-video can return the clean\n // \"requires an input image\" 400 (VIDEO_PROVIDERS_REQUIRING_IMAGE — derived\n // from MODEL_CATALOG modes) instead of an opaque Zod validation error.\n // They never reach a provider. Guarded by the dispatch-totality test in\n // __tests__/video-mode-aliases.test.ts.\n \"grok-imagine-video-1.5\",\n \"kling-3-omni\",\n \"kling-master\",\n \"hailuo-2.3\",\n \"hailuo-2.3-pro\",\n \"bytedance-pro-fast\",\n \"happyhorse-ref2v\",\n // Replicate disabled\n // \"runway\",\n // \"pika\",\n // \"sora\",\n] as const\nexport type TextToVideoProvider = typeof TEXT_TO_VIDEO_PROVIDERS[number]\n\n/** Unified video-generation providers (image-to-video ∪ text-to-video) for the generate-video node. */\nexport const VIDEO_GEN_PROVIDERS = [\n ...IMAGE_TO_VIDEO_PROVIDERS,\n ...TEXT_TO_VIDEO_PROVIDERS.filter(\n (p): p is typeof TEXT_TO_VIDEO_PROVIDERS[number] =>\n !(IMAGE_TO_VIDEO_PROVIDERS as readonly string[]).includes(p),\n ),\n] as const\nexport type VideoGenProvider = typeof VIDEO_GEN_PROVIDERS[number]\n\n/**\n * Video models that expose DISTINCT provider ids per mode (text-to-video vs\n * image-to-video) but represent ONE user-facing model. KIE keys i2v and t2v off\n * different ids in different maps (KIE_VIDEO_MODELS vs KIE_TEXT_TO_VIDEO_MODELS),\n * so each id only resolves to a real model in its native mode.\n *\n * The unified Generate Video node shows ONE picker row (the `base` id) and\n * auto-selects the mode by whether an input image is present; execution remaps\n * base→mode id via {@link resolveVideoProviderForMode}. This registry is the\n * single source of truth shared by the picker collapse (frontend\n * `model-options.ts`), the frontend DAG executor (`execute-node.ts`), and the\n * backend orchestrator (`payload-builder.ts`) so they can't drift.\n *\n * `base` MUST be one of the group's own mode ids (kept = the i2v id, since the\n * unified picker's i2v entries win on collision). Honesty invariants are guarded\n * in `__tests__/video-mode-aliases.test.ts`.\n */\nexport interface VideoModeAlias {\n /** Canonical id stored on the node + shown in the unified picker. */\n base: string\n /** KIE id to use when an input image is present (image-to-video). */\n i2v: string\n /** KIE id to use for pure text-to-video. */\n t2v: string\n}\n\nexport const VIDEO_MODE_ALIASES: readonly VideoModeAlias[] = [\n { base: \"grok-i2v\", i2v: \"grok-i2v\", t2v: \"grok\" },\n { base: \"wan-i2v\", i2v: \"wan-i2v\", t2v: \"wan\" },\n { base: \"wan-2.7-i2v\", i2v: \"wan-2.7-i2v\", t2v: \"wan-2.7-t2v\" },\n // HappyHorse: happyhorse/image-to-video + happyhorse/text-to-video are mode\n // twins of one KIE model family — previously TWO unified-picker rows, and the\n // i2v row crashed the t2v route when run without an image.\n { base: \"happyhorse-i2v\", i2v: \"happyhorse-i2v\", t2v: \"happyhorse\" },\n] as const\n\n/**\n * Resolve a (possibly base / cross-mode) video provider id to the concrete KIE\n * id for the given execution mode. Accepts any member id of an alias group\n * (base, i2v, or t2v) so existing workflows that stored either mode's id keep\n * working. Non-aliased providers (single-id models, VEO, Replicate, etc.) pass\n * through unchanged.\n */\nexport function resolveVideoProviderForMode(\n provider: string,\n mode: \"image-to-video\" | \"text-to-video\",\n): string {\n for (const g of VIDEO_MODE_ALIASES) {\n if (provider === g.base || provider === g.i2v || provider === g.t2v) {\n return mode === \"image-to-video\" ? g.i2v : g.t2v\n }\n }\n return provider\n}\n\n/**\n * t2v twin ids hidden from the unified Generate Video picker — the i2v/base\n * entry already represents both modes (execution remaps by image presence).\n * Only includes twins whose `base` is NOT the t2v id, so the surviving picker\n * entry is the base. Consumed by the frontend `VIDEO_GEN_MODELS` collapse.\n */\nexport const VIDEO_GEN_COLLAPSED_T2V_IDS: ReadonlySet<string> = new Set(\n VIDEO_MODE_ALIASES.filter((g) => g.t2v !== g.base).map((g) => g.t2v),\n)\n\n/** Video-to-video providers */\nexport const VIDEO_TO_VIDEO_PROVIDERS = [\n \"wan\",\n \"wan-flash\",\n \"wan-videoedit\",\n \"luma-modify\",\n \"runway-aleph\",\n \"happyhorse-edit\",\n] as const\nexport type VideoToVideoProvider = typeof VIDEO_TO_VIDEO_PROVIDERS[number]\n\n/** Face swap providers */\nexport const FACE_SWAP_PROVIDERS = [\n \"roop\",\n] as const\nexport type FaceSwapProvider = typeof FACE_SWAP_PROVIDERS[number]\n\n/** Video upscale providers */\nexport const VIDEO_UPSCALE_PROVIDERS = [\n \"topaz\",\n \"veo-1080p\",\n \"veo-4k\",\n] as const\nexport type VideoUpscaleProvider = typeof VIDEO_UPSCALE_PROVIDERS[number]\n\n/** Extend video providers */\nexport const EXTEND_VIDEO_PROVIDERS = [\n \"veo-extend\",\n \"runway-extend\",\n \"ltx-2.3-pro\",\n \"seedance-2-extend\",\n] as const\nexport type ExtendVideoProvider = typeof EXTEND_VIDEO_PROVIDERS[number]\n\n/** Lip sync providers */\nexport const LIP_SYNC_PROVIDERS = [\n \"kling-avatar\",\n \"kling-avatar-pro\",\n \"infinitalk\",\n // ByteDance OmniHuman 1.5 — KIE image+audio avatar, prompt-directed\n // performance, per-second billed, 60s audio cap. Routes the default KIE\n // path (not in any replicate/fal/seedance/video-input set).\n \"omnihuman-1-5\",\n \"latentsync\",\n \"wav2lip\",\n \"video-retalking\",\n \"sadtalker\",\n // HeyGen Lipsync Precision + Sync Lipsync 2 Pro — Replicate-hosted, video-input\n // dubbing models billed per second of output. Routed through replicateLipSync;\n // priced per-second via buildLipSyncCreditId (see lip-sync-pricing.ts).\n \"heygen-lipsync-precision\",\n \"lipsync-2-pro\",\n // Sync Lipsync v3 — fal.ai-hosted, video-input dubbing model billed per\n // second of output (/min). Routed through falLipSync (the worker's fal\n // branch); priced per-second via buildLipSyncCreditId (see lip-sync-pricing.ts).\n \"sync-lipsync-v3\",\n // Volcengine video-to-video lip sync — KIE-hosted, VIDEO-input AI dubbing\n // (mode lite/basic; multi-speaker scene-detection + speaker ID in basic).\n // Billed per-second via buildLipSyncCreditId; routed through the KIE\n // `lipSyncVideo` path (KieModelConfig.inputKind === \"video\"), NOT the\n // image+prompt `lipSync` path.\n \"volcengine-lipsync\",\n // Seedance 2 / 2 Fast — not \"lip-sync models\" per se, but ByteDance's\n // multimodal video models do native phoneme-level lip sync in 8+\n // languages when fed `reference_audio_urls` alongside a `first_frame_url`.\n // Routed through the i2v provider with the audio passed as a reference,\n // not the dedicated lip-sync flow.\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n] as const\nexport type LipSyncProvider = typeof LIP_SYNC_PROVIDERS[number]\n\n/** Seedance variants exposed via the lip-sync surface. They go through\n * the i2v provider with the audio plumbed as `reference_audio_urls`. */\nexport const SEEDANCE_LIP_SYNC_PROVIDERS = new Set<string>([\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n])\n\n/** Replicate-based lip-sync providers (video or image+audio via Replicate SDK) */\nexport const REPLICATE_LIP_SYNC_PROVIDERS = new Set([\n \"latentsync\",\n \"wav2lip\",\n \"video-retalking\",\n \"sadtalker\",\n \"heygen-lipsync-precision\",\n \"lipsync-2-pro\",\n] as const)\n\n/** fal.ai-based lip-sync providers (video+audio → video via the fal queue API).\n * Routed through `falLipSync` in the worker's `handleLipSync` fal branch. */\nexport const FAL_LIP_SYNC_PROVIDERS = new Set([\n \"sync-lipsync-v3\",\n] as const)\n\n/** Lip-sync providers that require video input (not image) */\nexport const VIDEO_INPUT_LIP_SYNC_PROVIDERS = new Set([\n \"latentsync\",\n \"video-retalking\",\n \"heygen-lipsync-precision\",\n \"lipsync-2-pro\",\n \"sync-lipsync-v3\",\n \"volcengine-lipsync\",\n] as const)\n\n/** Lip-sync providers that accept either video or image input */\nexport const FLEXIBLE_INPUT_LIP_SYNC_PROVIDERS = new Set([\n \"wav2lip\",\n] as const)\n\n/** Standard aspect ratio → pixel dimensions for composition nodes */\nexport const ASPECT_RATIO_DIMENSIONS: Record<string, { width: number; height: number }> = {\n \"16:9\": { width: 1920, height: 1080 },\n \"9:16\": { width: 1080, height: 1920 },\n \"1:1\": { width: 1080, height: 1080 },\n \"4:5\": { width: 1080, height: 1350 },\n}\n\n/** Motion transfer providers */\nexport const MOTION_TRANSFER_PROVIDERS = [\n \"kling\",\n \"kling-3.0\",\n \"wan-animate-move\",\n \"wan-animate-replace\",\n] as const\nexport type MotionTransferProviderType = typeof MOTION_TRANSFER_PROVIDERS[number]\n\n/** Text-to-speech providers */\nexport const TTS_PROVIDERS = [\n \"elevenlabs-v3\",\n \"elevenlabs-turbo\",\n \"elevenlabs-multilingual\",\n \"elevenlabs\",\n] as const\nexport type TtsProvider = typeof TTS_PROVIDERS[number]\n\n/** Text-to-audio providers */\nexport const TEXT_TO_AUDIO_PROVIDERS = [\n // Replicate disabled\n // \"tangoflux\",\n \"elevenlabs-sfx\",\n] as const\nexport type TextToAudioProvider = typeof TEXT_TO_AUDIO_PROVIDERS[number]\n\n/** Music generation providers */\nexport const MUSIC_PROVIDERS = [\n // Replicate disabled\n // \"musicgen\",\n \"minimax\",\n // TODO: surface Suno V5 here for discoverability — needs backend wiring\n // through suno-client.ts (Suno uses /api/v1/generate, NOT the standard\n // /api/v1/jobs/createTask path runKieTask uses). Tracked as a separate\n // follow-up PR. Until then, Suno is reachable via the standalone\n // `suno-generate` node.\n // Replicate disabled\n // \"lyria\",\n // \"bark\",\n] as const\nexport type MusicProvider = typeof MUSIC_PROVIDERS[number]\n\n/** Transcription providers */\nexport const TRANSCRIBE_PROVIDERS = [\n // Replicate disabled\n // \"whisper\",\n // \"incredibly-fast-whisper\",\n \"elevenlabs-stt\",\n] as const\nexport type TranscribeProvider = typeof TRANSCRIBE_PROVIDERS[number]\n\n/** Script generation providers */\nexport const SCRIPT_PROVIDERS = [\n \"gemini\",\n \"claude\",\n \"gpt\",\n] as const\nexport type ScriptProvider = typeof SCRIPT_PROVIDERS[number]\n\n/** AI writer providers */\nexport const AI_WRITER_PROVIDERS = [\n \"claude\",\n] as const\nexport type AiWriterProvider = typeof AI_WRITER_PROVIDERS[number]\n\n/** QA check providers */\nexport const QA_CHECK_PROVIDERS = [\n \"claude\",\n \"gpt\",\n] as const\nexport type QaCheckProvider = typeof QA_CHECK_PROVIDERS[number]\n\n/** Suno model versions */\nexport const SUNO_MODELS = [\n \"V4\",\n \"V4_5\",\n \"V4_5PLUS\",\n \"V4_5ALL\",\n \"V5\",\n \"V5_5\",\n] as const\nexport type SunoModel = typeof SUNO_MODELS[number]\n\n/** Suno models that support add-instrumental / add-vocals operations */\nexport const SUNO_ADD_TRACK_MODELS = [\"V4_5PLUS\", \"V5\", \"V5_5\"] as const\nexport type SunoAddTrackModel = typeof SUNO_ADD_TRACK_MODELS[number]\n\n/** Voice design models */\nexport const VOICE_DESIGN_MODELS = [\n \"eleven_ttv_v3\",\n \"eleven_multilingual_ttv_v2\",\n] as const\nexport type VoiceDesignModel = typeof VOICE_DESIGN_MODELS[number]\n\n/**\n * ElevenLabs' newest text-to-voice model (all languages) — the default when\n * a voice-design caller omits `model`. Single-sourced here so the route\n * (`backend/src/routes/voice-design.ts`) and the direct-API provider\n * (`backend/src/providers/elevenlabs/voice-design.ts`) can't drift.\n */\nexport const DEFAULT_VOICE_DESIGN_MODEL: VoiceDesignModel = \"eleven_ttv_v3\"\n\n/** I2I providers that support mask-based inpainting */\nexport const I2I_MASK_SUPPORT = new Set([\"ideogram-edit\"])\n\n/**\n * Mask edit tier per image-gen provider (single source of truth for inpaint).\n * - \"native\" → provider takes a real mask param (reserved for Phase 1.5; none today)\n * - \"prompt\" → strong instruction editor; inject a region descriptor into the prompt\n * - \"composite\" → rely on the always-on server-side composite floor only\n * Floor (B·(1−M)+E·M) applies to EVERY tier, so any provider is correct.\n */\nexport type ImageMaskMode = \"native\" | \"prompt\" | \"composite\"\n\nexport const IMAGE_MASK_MODE: Record<ImageGenProvider, ImageMaskMode> = {\n \"nano-banana\": \"prompt\",\n \"nano-banana-pro\": \"prompt\",\n \"nano-banana-2\": \"prompt\",\n \"gpt-image\": \"prompt\",\n \"gpt-image-2\": \"prompt\",\n \"seedream\": \"prompt\",\n \"seedream-5-lite\": \"prompt\",\n \"qwen\": \"prompt\",\n \"flux-kontext\": \"prompt\",\n \"flux-kontext-max\": \"prompt\",\n \"flux\": \"composite\",\n \"flux-flex\": \"composite\",\n \"grok\": \"composite\",\n \"imagen4\": \"composite\",\n \"imagen4-fast\": \"composite\",\n \"imagen4-ultra\": \"composite\",\n \"ideogram-v3\": \"composite\",\n \"z-image\": \"composite\",\n \"wan-2.7\": \"composite\",\n \"wan-2.7-pro\": \"composite\",\n \"flux-2-klein\": \"composite\",\n \"flux-2-pro\": \"composite\",\n \"flux-2-max\": \"composite\",\n}\n\n/** I2I providers that support a strength/denoising parameter */\nexport const I2I_STRENGTH_SUPPORT: Record<string, { min: number; max: number; step: number; default: number }> = {\n \"ideogram-remix\": { min: 0.01, max: 1, step: 0.01, default: 0.8 },\n \"qwen-i2i\": { min: 0, max: 1, step: 0.01, default: 0.8 },\n}\n\n/** Models that accept a seed parameter for reproducible generation */\nexport const SEED_SUPPORT = new Set([\n \"ideogram-remix\", \"ideogram-reframe\", \"ideogram-v3\",\n \"qwen\", \"qwen-i2i\", \"qwen-edit\",\n \"flux\", \"flux-flex\", \"flux-i2i\", \"flux-pro-i2i\", \"flux-kontext\", \"flux-kontext-max\",\n \"flux-2-klein\", \"kontext-multi\",\n])\n\n/** Ideogram models that support rendering_speed selection (TURBO/BALANCED/QUALITY) */\nexport const RENDERING_SPEED_SUPPORT = new Set([\n \"ideogram-remix\", \"ideogram-reframe\", \"ideogram-v3\",\n])\n\n/** Models that accept guidance_scale for controlling prompt adherence */\nexport const GUIDANCE_SCALE_SUPPORT: Record<string, { min: number; max: number; step: number; default: number }> = {\n \"qwen-i2i\": { min: 1, max: 20, step: 0.5, default: 7 },\n \"qwen-edit\": { min: 1, max: 20, step: 0.5, default: 7 },\n}\n\n// =====================================================================\n// Video variable pricing — duration-based and audio-addon pricing\n// =====================================================================\n\n/**\n * Video models where credit cost varies by duration.\n * Maps provider key → duration tier breakpoints.\n * Values are verified by the pricing verification script (backend/scripts/verify-kie-pricing.ts).\n * TODO: Run verification script and update costs after confirming actual KIE pricing.\n */\nexport const DURATION_PRICED_PROVIDERS = new Set([\n \"seedance-2-extend\",\n \"kling-3.0\",\n \"kling-3-omni\",\n \"kling\",\n \"kling-turbo\",\n \"kling-master\",\n \"grok-i2v\",\n \"wan-i2v\",\n \"hailuo-2.3-pro\",\n \"hailuo-2.3\",\n \"hailuo-standard\",\n \"seedance\",\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n \"grok-imagine-video-1.5\",\n])\n\n/**\n * Seedance 2.0 family — shared across UI gating, payload building, and pricing.\n * Expanded whenever a new Seedance 2.x variant ships.\n */\nexport const SEEDANCE_2_PROVIDERS = new Set<string>([\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n])\n\nexport function isSeedance2Provider(provider: string | undefined): boolean {\n return !!provider && SEEDANCE_2_PROVIDERS.has(provider)\n}\n\n/**\n * Default aspect ratio for a video provider when the node carries no explicit\n * `aspectRatio`. Seedance 2.x defaults to `\"adaptive\"` (output matches the\n * wired input — fits the unified-inputs model); every other provider keeps the\n * historical `\"16:9\"`. Single source of truth so every run-default / display-\n * fallback site stays in lock-step (preview = run). Applies to ALL Seedance\n * modes incl. text-to-video — KIE accepts `adaptive` there too.\n */\nexport function defaultVideoAspectRatio(provider: string | undefined): string {\n return isSeedance2Provider(provider) ? \"adaptive\" : \"16:9\"\n}\n\n/**\n * Google VEO family (Quality / Fast / Lite). VEO goes through its own KIE\n * endpoint and image-handling path, so callers branch on this in several places.\n */\nexport const VEO_PROVIDERS = new Set<string>([\n \"veo3\",\n \"veo3.1\",\n \"veo3_lite\",\n])\n\nexport function isVeoProvider(provider: string | undefined): boolean {\n return !!provider && VEO_PROVIDERS.has(provider)\n}\n\n/** KIE.ai limits for Seedance 2.0 multimodal reference arrays. */\nexport const SEEDANCE_2_REF_LIMITS = {\n images: 9,\n videos: 3,\n audio: 3,\n} as const\n\n/**\n * Trim-stitch parameters for the seedance-2-extend provider (spike-validated\n * 2026-06-11):\n * the model's extension output wobbles for its first ~3 frames and the source\n * tail's last ~4 frames lead into it; dropping both and butt-joining yields a\n * seam SMOOTHER than ordinary in-clip motion (PSNR 34.4dB vs 30.6dB\n * adjacent-frame baseline). The 0.15s timeline-anchored audio fades kill\n * boundary clicks without shifting sync (combineVideos cut+crossfade path).\n */\nexport const SEEDANCE_2_EXTEND_STITCH = {\n /** Frames dropped from the END of the source clip. */\n trimTailFrames: 4,\n /** Frames dropped from the START of the generated extension. */\n trimHeadFrames: 3,\n /** Boundary audio fade length (seconds), timeline-preserving. */\n audioFadeSec: 0.15,\n} as const\n\n/**\n * Per-provider max reference-audio duration (seconds) for Seedance 2.0 r2v\n * (audio-driven image-to-video). KIE rejects longer clips with a 400 BEFORE\n * generation (e.g. \"audio duration must be ≤ 15.2 for dreamina-seedance-2-0-fast\n * in r2v\"). Data-driven: only providers with a VERIFIED limit are listed, so an\n * unknown provider is never false-rejected.\n * - seedance-2-fast: 15.2s (verified against KIE).\n * - seedance-2 (non-fast): limit unverified → not enforced yet (add after\n * confirming via docs.kie.ai).\n */\nexport const SEEDANCE_2_R2V_MAX_AUDIO_SEC_BY_PROVIDER: Record<string, number> = {\n \"seedance-2-fast\": 15.2,\n}\n\n/** The verified r2v reference-audio cap (seconds) for a provider, or null when\n * none is enforced. */\nexport function seedance2AudioLimitSec(provider: string | undefined): number | null {\n if (!provider) return null\n return SEEDANCE_2_R2V_MAX_AUDIO_SEC_BY_PROVIDER[provider] ?? null\n}\n\n/**\n * First reference-audio duration (seconds) that exceeds the provider's r2v cap,\n * or null when all are within limit (or the provider has no enforced cap).\n * Non-finite durations (probe failures) are ignored. Used to reject over-long\n * audio BEFORE submitting to the provider — which would otherwise 400.\n */\nexport function findSeedance2AudioOverLimit(\n provider: string | undefined,\n durationsSec: readonly number[],\n): number | null {\n const limit = seedance2AudioLimitSec(provider)\n if (limit === null) return null\n for (const d of durationsSec) {\n if (Number.isFinite(d) && d > limit) return d\n }\n return null\n}\n\n/**\n * Per-provider connection caps for the typed reference handles on Generate Video\n * AND the cap for the server-side `connectedReferences` assembly (`imageCap`).\n *\n * The KEY SET is bound 1:1 to MODEL_CATALOG (kind:\"video\" + features:\n * [\"reference-image\"]) by the drift guard in `__tests__/video-ref-limits.test.ts`:\n * adding a ref-capable video model to the catalog without a cap here — or a cap\n * here without the catalog flag — fails CI. So the CATALOG is the single source\n * for \"is this model ref-capable\", and this map is the single source for the\n * NUMERIC caps (sourced from the provider configs, see per-line notes).\n * Providers absent from the map = 0 caps (the popover dims the handle with\n * \"Not supported by [Model]\"; the API assembly strips `{image:N}` tokens).\n */\nexport const VIDEO_REF_LIMITS_BY_PROVIDER: Record<\n string,\n { images?: number; videos?: number; audio?: number } | undefined\n> = {\n // Seedance 2 — full multimodal caps.\n \"seedance-2\": { ...SEEDANCE_2_REF_LIMITS },\n \"seedance-2-fast\": { ...SEEDANCE_2_REF_LIMITS },\n \"seedance-2-mini\": { ...SEEDANCE_2_REF_LIMITS },\n // Multi-image reference providers.\n \"gemini-omni-video\": { images: 7, videos: 1 },\n \"kling-3-omni\": { images: 7 }, // catalog/docs: \"end frame + up to 7 reference images\"\n \"grok-i2v\": { images: 7 }, // backend kie/models.ts maxRefImages: 7\n \"happyhorse-ref2v\": { images: 9 }, // backend kie/models.ts maxRefImages: 9\n // VEO 3.x — REFERENCE_2_VIDEO path caps refs at 3 (kie/video.ts slice(0, 3)).\n \"veo3\": { images: 3 },\n \"veo3.1\": { images: 3 },\n \"veo3_lite\": { images: 3 },\n // NOTE: wan-i2v / hailuo-2.3[-pro] / bytedance-pro[-fast] / grok-imagine-video-1.5\n // are deliberately ABSENT. The 2026-06-28 audit (video-reference-features.test.ts)\n // verified backend reference-forwarding paths and these i2v models have none —\n // a single image_url start frame only. Advertising a ref cap would silently drop\n // the user's references (the grok-imagine-video-1.5 bug). Add only with a\n // verified provider path + the catalog `reference-image` feature.\n}\n\n/**\n * Video models where credit cost depends on resolution AND whether a video\n * reference is connected. Identifier suffix: `:{resolution}[-ref]`.\n * Seedance 2.0 family uses per-second billing split 480p/720p × with-ref/no-ref.\n */\nexport const RESOLUTION_VIDEO_REF_PRICING = SEEDANCE_2_PROVIDERS\n\n/**\n * Video models priced by (duration × resolution) WITHOUT a video-ref dimension.\n * Identifier suffix: `:{resolution}`, appended after the duration tier; value =\n * the provider's PRICED resolution tiers. Any resolution outside the list\n * (or undefined) collapses to the FIRST entry — the provider's default tier —\n * so the builder can never emit an unpriced composite (the hard-fail guard\n * fuzzes the full resolution space). Distinct from\n * RESOLUTION_VIDEO_REF_PRICING (Seedance gen), which also adds `-ref` variants.\n */\nexport const RESOLUTION_DURATION_PRICING: Record<string, readonly string[]> = {\n // KIE supports only 480p/720p here; 480p is the default.\n \"grok-imagine-video-1.5\": [\"480p\", \"720p\"],\n // seedance-2-extend always uses a video ref, so pricing has no -ref\n // dimension — duration tier + \":res\" only (rates = seedance-2 -ref + stitch).\n \"seedance-2-extend\": [\"480p\", \"720p\", \"1080p\"],\n}\n\n/**\n * Video generation models whose provider API natively accepts a \"match the\n * visual input's aspect\" token, mapped to that provider's EXACT token.\n * Consumed by the backend's `resolveSourceMatchedAspect`: members get the\n * native token (no probe round-trip, exact match even for off-catalog ratios\n * like 4:5); everyone else falls back to ffprobe + closest catalog ratio.\n *\n * Only add entries whose match-the-input semantics are verified against the\n * provider's docs AND a live job — e.g. grok-imagine-video-1.5 accepts\n * \"auto\", but that means \"provider default\", NOT \"match input\", so it does\n * not belong here.\n *\n * seedance-2 family: `adaptive` per docs.kie.ai/market/bytedance/seedance-2\n * + seedance-2-fast (enum'd alongside the fixed ratios; default 16:9).\n */\nexport const NATIVE_ADAPTIVE_ASPECT: Record<string, string> = {\n \"seedance-2\": \"adaptive\",\n \"seedance-2-fast\": \"adaptive\",\n \"seedance-2-mini\": \"adaptive\",\n}\n\n/**\n * Video providers that REQUIRE an input image (image-to-video only) even though\n * they're listed in TEXT_TO_VIDEO_PROVIDERS for unified-node visibility. The\n * `/v1/text-to-video` route early-returns a clean 400 for these before any job\n * is created, instead of letting the prompt-only request fail at the provider.\n *\n * DERIVED from MODEL_CATALOG (the capability source of truth): every video\n * model whose `modes` lacks \"t2v\" and that isn't remapped to a t2v twin by\n * VIDEO_MODE_ALIASES. Hand-listing this set is what let kling-3-omni,\n * kling-master, hailuo-2.3(-pro), bytedance-pro-fast and happyhorse-ref2v\n * crash the t2v route with a raw Zod enum error — new i2v-only models now get\n * the friendly gate automatically when their catalog entry is added.\n */\nexport const VIDEO_PROVIDERS_REQUIRING_IMAGE: ReadonlySet<string> = new Set(\n Object.values(MODEL_CATALOG)\n .filter((m) =>\n m.kind === \"video\" &&\n m.modes.includes(\"i2v\") &&\n !m.modes.includes(\"t2v\") &&\n (VIDEO_GEN_PROVIDERS as readonly string[]).includes(m.id) &&\n resolveVideoProviderForMode(m.id, \"text-to-video\") === m.id,\n )\n .map((m) => m.id),\n)\n\n/** True when a video provider can only run image-to-video (image required). */\nexport function videoProviderRequiresImage(provider: string | undefined): boolean {\n return !!provider && VIDEO_PROVIDERS_REQUIRING_IMAGE.has(provider)\n}\n\n/**\n * Video models where enabling audio/sound incurs an additional cost.\n * The audio addon is expressed as a separate composite identifier suffix.\n */\nexport const AUDIO_ADDON_PROVIDERS = new Set([\n \"kling-3.0\",\n \"kling\",\n])\n\n/**\n * How a video model handles an audio track. Single source of truth for\n * audio/speech capability across the whole stack — the config-panel audio\n * toggle (show / lock / disable + warn), the Story→Video dialogue auto-pick\n * (revoice vs TTS + lip-sync), provider option wiring (`sound` vs\n * `generateAudio`), and the audio credit suffix.\n *\n * Consolidates signals that were previously scattered + inconsistent:\n * - `KIE_VIDEO_MODELS` / `KIE_TEXT_TO_VIDEO_MODELS` `extraParams.sound` (Kling)\n * - `…extraParams.generate_audio` (Seedance)\n * - VEO native audio (implicit, always on)\n * - `AUDIO_ADDON_PROVIDERS` (cost) + `SEEDANCE_2_PROVIDERS` (reference audio)\n *\n * \"none\" — silent model; no audio output. UI disables the audio\n * toggle with an explanatory note; the pipeline uses TTS +\n * lip-sync for any dialogue.\n * \"ambient\" — generates ambient sound / SFX matched to the scene, NOT\n * lip-synced spoken dialogue. Toggle is offered; the\n * pipeline still uses TTS + lip-sync for dialogue.\n * \"native_speech\" — bakes spoken dialogue + lip movement from the prompt\n * (VEO 3.x). The pipeline injects the dialogue line, enables\n * audio, and revoices the clip to the character's saved voice.\n * \"audio_driven\" — lip-syncs to a supplied reference-audio track (Seedance\n * 2.0 multimodal). The pipeline synthesises the character's\n * voice first, feeds it as reference audio, and skips the\n * separate lip-sync pass.\n */\nexport type VideoAudioMode = \"none\" | \"ambient\" | \"native_speech\" | \"audio_driven\"\n\nexport interface VideoAudioCapability {\n mode: VideoAudioMode\n /** Provider-option field carrying the on/off toggle, when user-controllable. */\n field?: \"generateAudio\" | \"sound\"\n /** Audio is always produced and can't be turned off by the user (VEO 3.x). */\n alwaysOn?: boolean\n /** Enabling audio raises the credit cost (Kling — see AUDIO_ADDON_PROVIDERS). */\n affectsCost?: boolean\n}\n\n/**\n * Per-model audio capability. Only models that produce SOME audio are listed;\n * anything absent defaults to `{ mode: \"none\" }` via `getVideoAudioCapability`,\n * so silent models (minimax, hailuo, wan, grok-i2v, gemini-omni-video, runway,\n * pika, …) need no entry. New audio-capable models MUST be added here — the\n * `video-audio-capability` guard test cross-checks this map against the model\n * configs' `extraParams.sound` / `generate_audio` + VEO/Seedance-2 sets so a\n * forgotten entry fails CI rather than silently disabling audio.\n */\nexport const VIDEO_AUDIO_CAPABILITY: Record<string, VideoAudioCapability> = {\n // VEO 3.x — native spoken dialogue + lip movement; always on (no toggle).\n veo3: { mode: \"native_speech\", alwaysOn: true },\n \"veo3.1\": { mode: \"native_speech\", alwaysOn: true },\n veo3_lite: { mode: \"native_speech\", alwaysOn: true },\n // Kling 2.6 / 3.0 — ambient sound/SFX toggle; not lip-synced speech. Cost-affecting.\n kling: { mode: \"ambient\", field: \"sound\", affectsCost: true },\n \"kling-3.0\": { mode: \"ambient\", field: \"sound\", affectsCost: true },\n // Seedance 1.x — optional ambient audio (generate_audio); not dialogue.\n seedance: { mode: \"ambient\", field: \"generateAudio\" },\n // Seedance 2.0 — multimodal; lip-syncs to a supplied reference-audio track.\n \"seedance-2\": { mode: \"audio_driven\", field: \"generateAudio\" },\n \"seedance-2-fast\": { mode: \"audio_driven\", field: \"generateAudio\" },\n \"seedance-2-mini\": { mode: \"audio_driven\", field: \"generateAudio\" },\n}\n\nconst VIDEO_AUDIO_NONE: VideoAudioCapability = { mode: \"none\" }\n\n/** Audio capability for a video model. Unlisted/undefined → silent (`none`). */\nexport function getVideoAudioCapability(\n model: string | undefined,\n): VideoAudioCapability {\n return (model ? VIDEO_AUDIO_CAPABILITY[model] : undefined) ?? VIDEO_AUDIO_NONE\n}\n\n/**\n * True when the model produces any audio track at all. Drives the config-panel\n * audio toggle: `false` → disable the toggle + show a \"this model has no audio\"\n * note (never restrict the model choice — just explain the limitation).\n */\nexport function videoModelSupportsAudio(model: string | undefined): boolean {\n return getVideoAudioCapability(model).mode !== \"none\"\n}\n\n/**\n * True when the model can produce lip-synced spoken DIALOGUE — either natively\n * (VEO) or driven by a supplied audio track (Seedance 2.0). Drives the Story→Video\n * dialogue auto-pick: in-model speech + character revoice (VEO) / character-voiced\n * reference audio (Seedance 2.0) vs. the TTS + separate-lip-sync fallback.\n * Ambient-only models (Kling, Seedance 1.x) return `false` — their audio is SFX,\n * not speech.\n */\nexport function videoModelCanSpeakDialogue(model: string | undefined): boolean {\n const mode = getVideoAudioCapability(model).mode\n return mode === \"native_speech\" || mode === \"audio_driven\"\n}\n\n/**\n * Write the caller's neutral \"enable native audio\" intent onto a KIE provider\n * `input` under whichever field the chosen model actually reads, per\n * `VIDEO_AUDIO_CAPABILITY.field`. This is the single dispatch point that fixes\n * the recurring \"sound toggle dropped on Seedance/VEO\" bug class: callers pass\n * the model-agnostic toggle ONCE and never need to know that Kling's lever is\n * `sound` while Seedance's is `generate_audio`.\n *\n * - `sound` is the canonical neutral name; `generateAudio` is accepted as a\n * legacy alias (the workflow node + some clients send that key). `sound` wins\n * if both are present.\n * - **Cost-affecting models (Kling) honour ONLY the canonical `sound` lever** —\n * the same field the `:audio` credit surcharge keys off (`AUDIO_ADDON_PROVIDERS`\n * in `credit-identifiers.ts`). This makes a billed-but-not-generated (or\n * generated-but-not-billed) divergence structurally impossible: the model and\n * the surcharge read the same flag. Free models accept the `generateAudio`\n * alias too, where mis-billing isn't possible.\n * - No-op for `alwaysOn` models (VEO — audio can't be toggled) and silent /\n * unlisted models (no `field`), and when the caller expressed no intent\n * (leaves the model's own default in place).\n *\n * Future audio models are covered automatically by adding a\n * `VIDEO_AUDIO_CAPABILITY` entry — already guarded by the\n * `video-audio-capability` drift test, so this never silently regresses.\n */\nexport function applyVideoAudioToggle(\n input: Record<string, unknown>,\n provider: string | undefined,\n opts: { sound?: boolean; generateAudio?: boolean } | undefined,\n): void {\n const cap = getVideoAudioCapability(provider)\n if (!cap.field) return // alwaysOn (VEO) or silent/unlisted model — nothing to toggle\n // Cost-affecting models stay on the canonical `sound` lever so the model and\n // the credit surcharge can never read different flags; free models also accept\n // the `generateAudio` alias. `sound` is canonical and wins when both are set.\n const enabled = cap.affectsCost ? opts?.sound : (opts?.sound ?? opts?.generateAudio)\n if (enabled === undefined) return // no intent — keep the model's own default\n if (cap.field === \"generateAudio\") input.generate_audio = enabled\n else input.sound = enabled\n}\n\n/**\n * Video models where a quality/mode parameter (e.g., videoSize \"high\") incurs higher cost.\n * When provider is in this set and mode is \"high\", \":high\" is appended to the identifier.\n */\nexport const MODE_ADDON_PROVIDERS = new Set<string>([\n])\n\n/**\n * VEO 3.x providers where credit cost depends on the requested output\n * resolution (720p default vs 1080p inline; 4K is via the separate\n * upgrade endpoint and isn't part of this set). When provider is in\n * this set and resolution !== \"720p\", `:1080p` is appended to the\n * identifier so the credit lookup hits the per-resolution rate.\n *\n * Per KIE pricing (verified 2026-05-06):\n * veo3.1 (Fast): 720p=60 KIE cr, 1080p=65 KIE cr\n * veo3_lite: 720p=30 KIE cr, 1080p=35 KIE cr\n * veo3 (Quality) is not in this set yet — pricing not in our reference data.\n */\nexport const VEO_RESOLUTION_TIERED_PROVIDERS = new Set<string>([\n \"veo3.1\",\n \"veo3_lite\",\n])\n\n/**\n * Video variable pricing config — which params affect credit cost per model.\n * \"duration\" = cost varies by video length\n * \"duration+audio\" = cost varies by length AND audio on/off\n */\nexport const VIDEO_VARIABLE_PRICING: Record<string, \"duration\" | \"duration+audio\" | \"duration+mode\" | \"duration+resolution+ref\" | \"duration+resolution\"> = {\n \"kling-3.0\": \"duration+audio\",\n \"kling-3-omni\": \"duration\",\n \"kling\": \"duration+audio\",\n \"kling-turbo\": \"duration\",\n \"kling-master\": \"duration\",\n \"grok-i2v\": \"duration\",\n \"wan-i2v\": \"duration\",\n \"hailuo-2.3-pro\": \"duration\",\n \"hailuo-2.3\": \"duration\",\n \"hailuo-standard\": \"duration\",\n \"seedance\": \"duration\",\n \"seedance-2\": \"duration+resolution+ref\",\n \"seedance-2-fast\": \"duration+resolution+ref\",\n \"seedance-2-mini\": \"duration+resolution+ref\",\n // Grok Imagine Video 1.5 — per-second billing split 480p/720p (no video-ref dimension).\n \"grok-imagine-video-1.5\": \"duration+resolution\",\n}\n\n/**\n * Duration tier breakpoints for variable-priced video models.\n * Maps provider → array of { maxSeconds, suffix } in ascending order.\n * The first tier whose maxSeconds >= requested duration is used.\n */\nexport const VIDEO_DURATION_TIERS: Record<string, Array<{ maxSeconds: number; suffix: string }>> = {\n \"kling-3.0\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"kling-3-omni\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"kling\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"kling-turbo\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"kling-master\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"grok-i2v\": [\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"wan-i2v\": [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"hailuo-2.3-pro\": [\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"hailuo-2.3\": [\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"hailuo-standard\": [\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n ],\n \"seedance\": [\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n ],\n \"seedance-2\": [\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"seedance-2-mini\": [\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"seedance-2-extend\": [\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n \"seedance-2-fast\": [\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n // Grok Imagine Video 1.5 — true per-second billing (KIE 14.5 cr/s @480p, 25 cr/s\n // @720p, +2 cr/image). One tier per allowed second (1–15s) so the composite\n // identifier maps 1:1 to the seeded price — no rounding/overcharge for any on-menu value.\n \"grok-imagine-video-1.5\": [\n { maxSeconds: 1, suffix: \"1s\" },\n { maxSeconds: 2, suffix: \"2s\" },\n { maxSeconds: 3, suffix: \"3s\" },\n { maxSeconds: 4, suffix: \"4s\" },\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 6, suffix: \"6s\" },\n { maxSeconds: 7, suffix: \"7s\" },\n { maxSeconds: 8, suffix: \"8s\" },\n { maxSeconds: 9, suffix: \"9s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 11, suffix: \"11s\" },\n { maxSeconds: 12, suffix: \"12s\" },\n { maxSeconds: 13, suffix: \"13s\" },\n { maxSeconds: 14, suffix: \"14s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n ],\n}\n\n/**\n * Maps composer node types to their plan type identifier and the node data field\n * where the plan is stored. Used by render-video payload building, plan syncing,\n * and the frontend DAG executor.\n */\nexport const COMPOSER_PLAN_MAP: Readonly<Record<string, { planType: string; planField: string }>> = {\n \"video-composer\": { planType: \"scene-graph\", planField: \"sceneGraph\" },\n \"after-effects\": { planType: \"after-effects\", planField: \"effectPlan\" },\n \"lottie-overlay\": { planType: \"lottie-overlay\", planField: \"overlayPlan\" },\n \"3d-title\": { planType: \"3d-title\", planField: \"titlePlan\" },\n \"motion-graphics\": { planType: \"motion-graphics\", planField: \"motionPlan\" },\n \"composite\": { planType: \"composite\", planField: \"compositePlan\" },\n}\n\n/** Every composer plan-field name, derived from COMPOSER_PLAN_MAP (single source\n * of truth — consumed by preset plan-state hygiene and job-output extraction). */\nexport const COMPOSER_PLAN_FIELDS: readonly string[] = [\n ...new Set(Object.values(COMPOSER_PLAN_MAP).map((m) => m.planField)),\n]\n\n/**\n * Duration tier breakpoints for motion control pricing (per-second billing).\n * Same shape as VIDEO_DURATION_TIERS entries but with 30s tier for long reference videos.\n */\nexport const MOTION_DURATION_TIERS: ReadonlyArray<{ maxSeconds: number; suffix: string }> = [\n { maxSeconds: 5, suffix: \"5s\" },\n { maxSeconds: 10, suffix: \"10s\" },\n { maxSeconds: 15, suffix: \"15s\" },\n { maxSeconds: 30, suffix: \"30s\" },\n]\n\n/** Curated i2v providers compatible with character portrait reference input.\n * Subset of IMAGE_TO_VIDEO_PROVIDERS — excludes text-to-video-only models. */\nexport const CHARACTER_MOTION_PROVIDERS = [\n \"kling\",\n \"kling-turbo\",\n \"kling-3.0\",\n \"wan-i2v\",\n \"wan-2.7-i2v\",\n] as const\nexport type CharacterMotionProvider = typeof CHARACTER_MOTION_PROVIDERS[number]\n\n/**\n * Atmospheric video providers available to the Location Studio's motion tab.\n *\n * Tuned for ambient camera moves (dolly, pan, drift, parallax) rather than\n * character-driven motion. Subset of registered i2v providers; `seedance-2`\n * added as the cinematic option for establishing shots.\n *\n * Mirrors `CHARACTER_MOTION_PROVIDERS` shape — see entity-prompts.ts for the\n * naming convention.\n */\nexport const LOCATION_ATMOSPHERE_PROVIDERS = [\n \"kling\",\n \"kling-turbo\",\n \"kling-3.0\",\n \"wan-i2v\",\n \"wan-2.7-i2v\",\n \"seedance-2\",\n] as const\nexport type LocationAtmosphereProvider =\n (typeof LOCATION_ATMOSPHERE_PROVIDERS)[number]\n\n/**\n * Subset of i2v providers tuned for short ambient object-motion clips (rotate,\n * hover, spin, parallax). Excludes premium models (Veo3, Veo3.1, Grok-i2v,\n * Sora2, Sora2-pro, Hailuo-2.3-pro) which are cost-prohibitive for the\n * product-loop use case (several times kling-turbo's per-clip cost).\n * Phase 2 candidate for adding veo3.1 if demand for premium hero shots\n * materializes.\n */\nexport const OBJECT_MOTION_PROVIDERS = [\n \"kling-turbo\", // 5s, fast, cheap (10 credits) — default\n \"kling\", // 5/10s\n \"kling-3.0\", // 3-15s, premium\n \"minimax\", // 5s, end-frame support\n \"hailuo-2.3\", // 6/10s\n \"wan-i2v\", // 5/10/15s\n \"seedance\", // 4/8/12s\n \"bytedance-lite\", // 5/10s\n] as const\nexport type ObjectMotionProvider = (typeof OBJECT_MOTION_PROVIDERS)[number]\n\n// =====================================================================\n// Scene Input Modes + Video Model Capability Registry (v4.0 + v4.1 spec §6.10)\n// =====================================================================\n\n/**\n * SceneInputMode — the input-shape contract a video model exposes to the\n * Scene Director. Gates which `video_model` values are valid for a given\n * scene's `shot_input_mode`. Consumed by Scene Director LLM prompting,\n * route Zod validation, and the frontend SceneNode config panel.\n *\n * See architecture spec §6.10 + v4.1 Methods 2/3/8/10 for per-mode semantics.\n */\nexport const SceneInputModeSchema = z.enum([\n \"text\", // text-to-video\n \"first_frame\", // i2v with start image only\n \"first_last_frame\", // i2v with paired start+end (v4.1 Method 2)\n \"ref_images\", // multi-ref consistency models\n \"multi_shot\", // native multi-shot models (Kling Omni, Seedance multi)\n \"video_continuation\", // v4.1 Method 3 — extend prior clip (VEO extend, Seedance video-ref)\n \"frame_interpolation\", // v4.1 Method 8 — N sparse keyframes → interpolated video\n \"camera_path\", // v4.1 Method 10 — parametric 3D camera path\n])\nexport type SceneInputMode = z.infer<typeof SceneInputModeSchema>\n\n/**\n * Prompting style each model expects from the Scene Director.\n * Veo-family wants comma-separated cinematic tags; Kling-family wants\n * natural-language prose; Hailuo-family wants compact single-sentence prompts.\n */\nexport type ModelPromptingStyle =\n | \"cinematic_tag_heavy\" // Veo-family — comma-separated tags\n | \"natural_language\" // Kling-family — prose descriptions\n | \"compact\" // Hailuo-family — single-sentence\n\nexport interface VideoModelCapabilities {\n inputModes: SceneInputMode[]\n maxShotsPerCall?: number // for multi_shot models\n supportsLipSyncIntegrated?: boolean // Kling Avatar / VEO-3 etc\n supportsVideoExtension?: boolean // v4.1 Method 3\n supportsCameraPath?: boolean // v4.1 Method 10\n maxInterpolationKeyframes?: number // v4.1 Method 8\n maxDurationSeconds: number\n prompting_style: ModelPromptingStyle\n /**\n * Maximum number of reference IMAGES the model accepts in one call,\n * including the start frame. Drives `allocateReferenceSlots` in\n * `backend/src/ee/pipelines/continuity.ts` (Phase 1C.1 §5.13.3) — when\n * the budget is 1, multi-shot/character/object refs are silently\n * dropped and the slot allocator emits a `pipeline:warning` event.\n * Defaults to 1 when omitted.\n */\n maxReferenceImages?: number\n}\n\n/**\n * VIDEO_MODEL_CAPS — single source of truth for what each video model supports.\n * Consumed by: Scene Director LLM (filters eligible models), route Zod validation\n * (rejects invalid video_model for the chosen shot_input_mode), frontend SceneNode\n * config panel (filters dropdown options).\n *\n * Adding a new video model: add an entry here, run audit-providers skill to verify\n * downstream wiring.\n */\nexport const VIDEO_MODEL_CAPS: Record<string, VideoModelCapabilities> = {\n \"kling\": {\n inputModes: [\"first_frame\", \"first_last_frame\", \"text\"],\n maxDurationSeconds: 10,\n prompting_style: \"natural_language\",\n maxReferenceImages: 1,\n },\n \"kling-3-omni\": {\n inputModes: [\"ref_images\", \"multi_shot\"],\n maxShotsPerCall: 5,\n maxDurationSeconds: 15,\n prompting_style: \"natural_language\",\n // Kling Omni accepts a strong multi-ref budget (start frame + up to\n // ~6 character/scene refs). Drives `allocateReferenceSlots` in\n // continuity.ts to surface all of them.\n maxReferenceImages: 7,\n },\n \"veo3.1\": {\n inputModes: [\"first_frame\", \"text\", \"video_continuation\"],\n supportsVideoExtension: true,\n maxDurationSeconds: 8,\n prompting_style: \"cinematic_tag_heavy\",\n maxReferenceImages: 1,\n },\n \"seedance-2\": {\n inputModes: [\"first_frame\", \"first_last_frame\", \"ref_images\", \"video_continuation\"],\n supportsVideoExtension: true,\n maxDurationSeconds: 10,\n prompting_style: \"natural_language\",\n // SEEDANCE_2_REF_LIMITS.images is the hard upper bound (9). 1C.1\n // caps to a more conservative 5 to leave headroom for primary\n // character + location + 3 secondary refs.\n maxReferenceImages: 5,\n },\n \"hailuo-2.3-pro\": {\n inputModes: [\"first_frame\", \"text\"],\n maxDurationSeconds: 10,\n prompting_style: \"compact\",\n maxReferenceImages: 1,\n },\n \"hailuo-standard\": {\n inputModes: [\"first_frame\", \"first_last_frame\"],\n maxDurationSeconds: 6,\n prompting_style: \"compact\",\n maxReferenceImages: 1,\n },\n \"minimax\": {\n inputModes: [\"first_frame\", \"first_last_frame\"],\n maxDurationSeconds: 6,\n prompting_style: \"compact\",\n maxReferenceImages: 1,\n },\n \"kling-turbo\": {\n inputModes: [\"first_frame\", \"first_last_frame\"],\n maxDurationSeconds: 10,\n prompting_style: \"natural_language\",\n maxReferenceImages: 1,\n },\n \"bytedance-lite\": {\n inputModes: [\"first_frame\", \"first_last_frame\"],\n maxDurationSeconds: 10,\n prompting_style: \"compact\",\n maxReferenceImages: 1,\n },\n // v4.1 Method 8 — Frame interpolation (sparse keyframes → interpolated video).\n // RIFE: Replicate-hosted, optical-flow-based interpolation, up to 8 keyframes.\n \"rife\": {\n inputModes: [\"frame_interpolation\"],\n maxInterpolationKeyframes: 8,\n maxDurationSeconds: 60,\n prompting_style: \"compact\",\n },\n // Topaz Apollo: cloud-hosted (Topaz.ai), higher keyframe budget.\n // Provider routing currently stubs as `provider_not_available:topaz-apollo`\n // pending KIE catalog check — entry kept so Shot List Critic surfaces it.\n \"topaz-apollo\": {\n inputModes: [\"frame_interpolation\"],\n maxInterpolationKeyframes: 16,\n maxDurationSeconds: 60,\n prompting_style: \"compact\",\n },\n // v4.1 Method 10 — Parametric 3D camera path (Stability AI SV3D via Replicate).\n // SV3D takes a single image + a camera path and renders a 3D-orbit video.\n \"stable-video-3d\": {\n inputModes: [\"camera_path\", \"first_frame\"],\n supportsCameraPath: true,\n maxDurationSeconds: 5,\n prompting_style: \"natural_language\",\n maxReferenceImages: 1,\n },\n}\n\n/**\n * modelsForInputMode — filter VIDEO_MODEL_CAPS to models that support the given mode.\n * Used at three call sites: Scene Director prompt construction, route Zod validation,\n * frontend config panel dropdown options.\n */\nexport const modelsForInputMode = (mode: SceneInputMode): string[] =>\n Object.entries(VIDEO_MODEL_CAPS)\n .filter(([, caps]) => caps.inputModes.includes(mode))\n .map(([model]) => model)\n\n/**\n * preferredInputModeForModel — pick the best `shot_input_mode` for a pinned\n * video model so the pipeline adapts its input wiring to the chosen model:\n *\n * - models that accept `ref_images` (Seedance 2, Kling Omni) → `\"ref_images\"`,\n * so the character/location reference portraits feed the video model\n * directly (strongest identity lock).\n * - otherwise models that accept a start frame → `\"first_frame\"`, so the\n * per-scene keyframe is connected as the opening frame.\n *\n * Returns `undefined` for unknown/unregistered models (not in VIDEO_MODEL_CAPS)\n * or models that expose neither mode, so the caller keeps its own default.\n *\n * `first_last_frame` is deliberately NOT auto-selected — the animate stage\n * does not yet implement paired start+end keyframes (Method 2), so a\n * first_last_frame-capable model still resolves to `first_frame` here.\n */\nexport function preferredInputModeForModel(\n model: string | undefined,\n): SceneInputMode | undefined {\n if (!model) return undefined\n const caps = VIDEO_MODEL_CAPS[model]\n if (!caps) return undefined\n if (caps.inputModes.includes(\"ref_images\")) return \"ref_images\"\n if (caps.inputModes.includes(\"first_frame\")) return \"first_frame\"\n return undefined\n}\n\n/* ────────────────────────────────────────────────────────────────────────────\n * Platform default video model (single source of truth)\n *\n * Applied wherever a video request omits `provider`: the generate-video and\n * text-to-video routes (credit resolution + dispatch), the DAG payload\n * builder, and the KIE provider's last-resort fallback. Chosen from usage\n * data (2026-07): most-selected video model with the highest completion rate.\n * ──────────────────────────────────────────────────────────────────────────── */\n\nexport const DEFAULT_VIDEO_PROVIDER = \"seedance-2-fast\"\n\n/**\n * Duration paired with the default provider when BOTH provider and duration\n * are omitted. Pins the nothing-specified request to the default model's\n * cheapest seeded tier (4s @ 480p — resolution omission already resolves to\n * 480p in buildVideoCreditModelIdentifier), so first-touch cost stays at\n * entry level and longer clips are an explicit choice.\n */\nexport const DEFAULT_VIDEO_DURATION_SEC = 4\n\n/**\n * Resolve the effective (provider, duration) for a video request.\n *\n * - provider omitted → DEFAULT_VIDEO_PROVIDER\n * - duration omitted AND provider was omitted → DEFAULT_VIDEO_DURATION_SEC\n * - an explicitly chosen provider keeps its own duration semantics (an\n * omitted duration falls through to that model's natural default)\n *\n * Used by both single-node routes AND the workflow payload builder so the\n * two execution paths cannot drift (the route/DAG default previously\n * disagreed: \"minimax\" vs \"kling\").\n */\nexport function applyDefaultVideoSelection<D>(input: {\n provider?: string | null\n duration?: D\n}): { provider: string; duration: D | number | undefined } {\n const providerOmitted = input.provider == null || input.provider === \"\"\n return {\n provider: providerOmitted ? DEFAULT_VIDEO_PROVIDER : (input.provider as string),\n duration: input.duration ?? (providerOmitted ? DEFAULT_VIDEO_DURATION_SEC : undefined),\n }\n}\n","/**\n * Film cost ESTIMATION for the studio preview.\n *\n * This is display guidance only — it produces an approximate \"this film will\n * cost ≈ N credits\" number so the user can see cost before committing to a\n * length + model. The ACTUAL charge is still computed at generation time from\n * `STATIC_CREDIT_COSTS` / the `model_pricing` table per job; this module never\n * bills.\n *\n * Numbers are grounded in the KIE-calibrated per-clip credit costs in\n * `backend/src/ee/billing/credits.ts` (each entry there is annotated with its\n * KIE-credit + USD source). A backend test cross-checks `VIDEO_CLIP_CREDITS`\n * against that source so the estimate can't silently drift from reality.\n *\n * Cost structure of a Story→Video film:\n * total = BASE (duration-independent planning + assembly)\n * + perShot × shotCount (the variable, model-driven bulk)\n * where a shot = one keyframe image + one video clip + one video-critic pass,\n * and shotCount ≈ ceil(duration / clipSeconds) for the chosen model.\n */\n\n/**\n * Duration-independent overhead, in credits:\n * script/showrunner LLM chain ~30 · music timeline 4 · editor LLM 3 ·\n * final merge 3 · storyboard-cohesion critic 5 ≈ 45.\n * Mirrors the fixed line items in `estimateUpfrontCredits`\n * (backend/src/ee/pipelines/credits.ts).\n */\nexport const FILM_BASE_CREDITS = 45\n\n/** Per-shot keyframe image (nano-banana class) — see STATIC_CREDIT_COSTS. */\nexport const KEYFRAME_CREDITS_PER_SHOT = 2\n/** Per-shot Video Critic pass (first_last frame mode) — see credits.ts. */\nexport const VIDEO_CRITIC_CREDITS_PER_SHOT = 2\n\nexport interface VideoClipCost {\n /** Representative per-clip credit cost at the studio's default config\n * (720p; for the Seedance 2 family this is the ref-image variant the\n * studio uses for identity). Sourced from STATIC_CREDIT_COSTS. */\n readonly credits: number\n /** Representative clip length in seconds for shot-count estimation. */\n readonly clipSeconds: number\n}\n\n/**\n * Representative per-clip credit cost for each user-pinnable video model.\n * Values are the KIE-calibrated credits from STATIC_CREDIT_COSTS at the\n * studio's typical settings (720p; Seedance 2 = 8s 720p +ref). Keep in sync\n * with that table — the backend cross-check test guards drift.\n */\nexport const VIDEO_CLIP_CREDITS: Record<string, VideoClipCost> = {\n \"kling-turbo\": { credits: 11, clipSeconds: 5 }, // kling-turbo:5s\n \"kling\": { credits: 14, clipSeconds: 5 }, // kling:5s\n \"kling-3.0\": { credits: 31, clipSeconds: 5 },\n \"seedance\": { credits: 7, clipSeconds: 8 }, // seedance:8s\n \"seedance-2\": { credits: 50, clipSeconds: 8 }, // seedance-2:8s:720p-ref\n \"seedance-2-fast\": { credits: 40, clipSeconds: 8 }, // seedance-2-fast:8s:720p-ref\n \"seedance-2-mini\": { credits: 25, clipSeconds: 8 }, // seedance-2-mini:8s:720p-ref\n \"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 * Featured entity starter catalog (north-star §6 ③ — the \"Featured\" tab of each\n * entity Library).\n *\n * These are app-provided starter presets: a curated visual description per\n * archetype that the user can drop into an entity's Generate field as a\n * head-start, instead of writing one from scratch. They are intentionally\n * ASSETLESS — they seed generation (the user still generates the image with\n * their chosen model + style), so no hosted sample images are required. The\n * \"Mine\" tab (reuse an already-saved image) and \"+ New\" (Upload / write your\n * own) cover the other two on-ramps.\n */\nexport interface FeaturedEntity {\n /** Stable id (unique within its type). */\n id: string\n /** Short name shown on the chip. */\n label: string\n /** Curated visual description dropped into the Generate field. */\n description: string\n}\n\nexport const FEATURED_ENTITIES: Record<string, readonly FeaturedEntity[]> = {\n character: [\n {\n id: \"detective\",\n label: \"Grizzled Detective\",\n description:\n \"A weathered private detective in his 50s, stubble, rumpled trench coat, tired but sharp eyes, film-noir presence\",\n },\n {\n id: \"barista\",\n label: \"Cheerful Barista\",\n description:\n \"A cheerful young barista with curly hair, apron over a casual shirt, warm welcoming smile, energetic and approachable\",\n },\n {\n id: \"elder\",\n label: \"Wise Elder\",\n description:\n \"A wise elderly mentor with long grey hair and beard, flowing robes, calm knowing expression, gentle authority\",\n },\n {\n id: \"adventurer\",\n label: \"Young Adventurer\",\n description:\n \"A young adventurer in practical travel gear with a worn backpack, determined expression, sun-weathered skin\",\n },\n {\n id: \"scientist\",\n label: \"Focused Scientist\",\n description:\n \"A focused scientist in a white lab coat, glasses, hair tied back, intelligent and intense demeanor\",\n },\n {\n id: \"child\",\n label: \"Curious Kid\",\n description:\n \"A curious 8-year-old child with bright eyes and colorful casual clothes, playful and full of wonder\",\n },\n ],\n location: [\n {\n id: \"alley\",\n label: \"Cyberpunk Alley\",\n description:\n \"A neon-lit cyberpunk alley at night, wet pavement reflecting signs, drifting steam, dense layered urban detail\",\n },\n {\n id: \"cafe\",\n label: \"Cozy Café\",\n description:\n \"A cozy coffee shop interior, warm wood surfaces, soft pendant lighting, hanging plants, a few relaxed patrons\",\n },\n {\n id: \"forest\",\n label: \"Misty Forest\",\n description:\n \"A misty ancient forest at dawn, tall trees, shafts of light through fog, ferns underfoot, ethereal stillness\",\n },\n {\n id: \"office\",\n label: \"Modern Office\",\n description:\n \"A sleek modern office with glass walls, a city skyline view, minimal furniture, bright natural daylight\",\n },\n {\n id: \"beach\",\n label: \"Golden Beach\",\n description:\n \"A tranquil tropical beach at golden hour, soft rolling waves, leaning palm trees, warm low sun\",\n },\n {\n id: \"bridge\",\n label: \"Spaceship Bridge\",\n description:\n \"A futuristic spaceship bridge, glowing control panels, a vast viewport onto a star field, cool blue light\",\n },\n ],\n object: [\n {\n id: \"watch\",\n label: \"Vintage Pocket Watch\",\n description:\n \"An ornate vintage gold pocket watch, intricate engraving, slightly worn, on a fine chain\",\n },\n {\n id: \"sword\",\n label: \"Enchanted Sword\",\n description:\n \"A glowing enchanted sword, faint runes etched along the blade, ornate hilt wrapped in leather\",\n },\n {\n id: \"robot\",\n label: \"Retro Robot\",\n description:\n \"A friendly retro-futuristic robot companion, rounded brushed-metal chassis, a single expressive lens eye\",\n },\n {\n id: \"book\",\n label: \"Ancient Spellbook\",\n description:\n \"An ancient leather-bound spellbook, gilded page edges, embossed cover, a faint mysterious glow\",\n },\n {\n id: \"car\",\n label: \"Classic Convertible\",\n description:\n \"A sleek classic convertible sports car, polished chrome trim, vivid glossy paint, whitewall tires\",\n },\n ],\n}\n\n/** Featured presets for an entity type (\"character\" | \"location\" | \"object\"). */\nexport function getFeaturedEntities(type: string): readonly FeaturedEntity[] {\n return FEATURED_ENTITIES[type] ?? []\n}\n","export interface PixelBox { x: number; y: number; width: number; height: number }\n\nexport interface MaskRegionDescriptor {\n /** bbox normalized to 0..1 against the image, clamped so x+width ≤ 1 and y+height ≤ 1. */\n normBbox: PixelBox\n /** Natural-language location, e.g. \"the upper-left region\" / \"the center\". */\n location: string\n /** Prompt fragment to PREPEND to the user instruction. */\n fragment: string\n}\n\nfunction band(center: number): \"low\" | \"mid\" | \"high\" {\n if (center < 1 / 3) return \"low\"\n if (center > 2 / 3) return \"high\"\n return \"mid\"\n}\n\nconst VERT = { low: \"upper\", mid: \"middle\", high: \"lower\" } as const\nconst HORZ = { low: \"left\", mid: \"center\", high: \"right\" } as const\n\n/**\n * Turn a pixel bounding box of the masked (edit) region into a normalized bbox\n * + natural-language location + a prompt fragment. Pure — no IO. This is the\n * Tier-B descriptor injected for strong instruction-following editors, and the\n * exact primitive Phase 2 (named regions) will reuse.\n */\nexport function describeMaskRegion(box: PixelBox, image: { width: number; height: number }): MaskRegionDescriptor {\n const clamp01 = (n: number) => Math.max(0, Math.min(1, n))\n const round2 = (n: number) => Math.round(n * 100) / 100\n const nx = clamp01(box.x / image.width)\n const ny = clamp01(box.y / image.height)\n const normBbox: PixelBox = {\n x: round2(nx),\n y: round2(ny),\n width: round2(Math.max(0, Math.min(1 - nx, box.width / image.width))),\n height: round2(Math.max(0, Math.min(1 - ny, box.height / image.height))),\n }\n\n const cx = (box.x + box.width / 2) / image.width\n const cy = (box.y + box.height / 2) / image.height\n const v = VERT[band(cy)]\n const h = HORZ[band(cx)]\n const location = v === \"middle\" && h === \"center\" ? \"the center\" : `the ${v}-${h} region`\n\n const fragment =\n `Apply the following change ONLY to ${location} of the image ` +\n `(normalized region x=${normBbox.x} y=${normBbox.y} w=${normBbox.width} h=${normBbox.height}), ` +\n `leaving everything else unchanged: `\n\n return { normBbox, location, fragment }\n}\n","/**\n * Ancestor reference image collection — traverses upstream nodes to find\n * image-producing ancestors, with passthrough for text/logic nodes.\n * Shared between frontend and backend via a callback for extracting image URLs.\n */\n\nimport type { GenericNode, GenericEdge } from \"./types.js\"\n\n// Node types that produce reference images\nexport const IMAGE_REF_TYPES = new Set([\n \"upload-image\", \"face\", \"character\", \"object\", \"creature\", \"location\",\n \"generate-image\", \"edit-image\", \"image-to-image\",\n])\n\n// Node types that pass through (don't produce images but connect to ancestors that do)\nexport const PASSTHROUGH_TYPES = new Set([\n \"ai-writer\", \"llm-chat\", \"split-text\", \"combine-text\", \"text-prompt\", \"list\",\n])\n\n/**\n * Collect reference image URLs from upstream ancestor nodes.\n * @param getImageUrl - Callback to extract an image URL from a node. Frontend uses\n * extractNodeOutput(), backend uses nodeStates[id]?.output?.imageUrl.\n */\nexport function collectAncestorRefs<N extends GenericNode, E extends GenericEdge>(\n nodeId: string,\n nodes: N[],\n edges: E[],\n getImageUrl: (node: N) => string | undefined,\n visited = new Set<string>(),\n): string[] {\n if (visited.has(nodeId)) return []\n visited.add(nodeId)\n const refs: string[] = []\n const incoming = edges.filter((e) => e.target === nodeId)\n for (const edge of incoming) {\n const src = nodes.find((n) => n.id === edge.source)\n if (!src) continue\n if (IMAGE_REF_TYPES.has(src.type)) {\n const url = getImageUrl(src)\n if (url?.trim()) refs.push(url.trim())\n }\n if (PASSTHROUGH_TYPES.has(src.type)) {\n refs.push(...collectAncestorRefs(src.id, nodes, edges, getImageUrl, visited))\n }\n }\n return refs\n}\n","/**\n * Character-mention usage modes — describe HOW the AI should consume a\n * referenced character image. The mode shapes the per-image directive in the\n * assembled prompt (see `usageModeDirective`) so the same character reference\n * can act as a full likeness replacement, a face-only crop, a style donor,\n * etc., without needing different upstream images.\n *\n * The mode source-of-truth lives in two places:\n *\n * 1. **Character node default** — `CharacterNodeData.defaultUsageMode`.\n * Set via the small dropdown in the character node's title row.\n * Propagates into every `ConnectedReference` derived from that node.\n *\n * 2. **Per-mention override** — optional 4th segment in the slug,\n * e.g. `@kira:1:smile:face` overrides the character's default for that\n * specific mention. Parsed by `parseCharacterMentionToken` in\n * `character-mention-slug.ts`.\n *\n * Mode resolution at prompt-build time (in `resolveCharacterMentions`):\n * token.usageMode ?? ref.defaultUsageMode ?? \"identical\"\n */\n\nexport const USAGE_MODES = [\n \"identical\",\n \"face\",\n \"face-pose\",\n \"pose\",\n \"emotion\",\n \"style\",\n \"name\",\n \"none\",\n] as const\n\nexport type UsageMode = (typeof USAGE_MODES)[number]\n\n/** Default mode when neither the slug nor the character node specifies one. */\nexport const DEFAULT_USAGE_MODE: UsageMode = \"identical\"\n\n/** Type guard — narrows an arbitrary string to `UsageMode` when valid. */\nexport function isUsageMode(s: string): s is UsageMode {\n return (USAGE_MODES as readonly string[]).includes(s)\n}\n\n/**\n * Return the natural-language directive appended to a per-image bullet for the\n * given mode. The text is intentionally explicit so the model knows exactly\n * which aspects of the reference to take and which to derive from the rest of\n * the prompt.\n *\n * `name` and `none` are minimal-intervention modes that return `null` — the\n * caller emits NO trailing directive for them. `name` still includes the\n * character name in the labeled subject (`Image A (shira)`); `none` suppresses\n * the name as well (bare `Image A`) and excludes the character entirely from\n * the top-level \"Use these characters:\" header when ALL of its mentions are\n * `none`. Use these when the user wants the visual reference to speak for\n * itself without textual bias.\n *\n * Calling sites: `resolveCharacterMentions` (shared/prompt-builder.ts) and the\n * per-character canonical fallback (also in prompt-builder.ts), plus the video\n * mention resolvers on frontend (execute-node.ts) and backend (payload-builder.ts)\n * which mirror the same directive shape.\n */\nexport function usageModeDirective(mode: UsageMode): string | null {\n switch (mode) {\n case \"identical\":\n return \"The subject must remain exactly the same person — preserve 100% facial identity, bone structure, skin tone, proportions, and all unique features. Do not alter eyes, nose, mouth, or facial shape. Maintain natural skin texture, including pores and imperfections.\"\n case \"face\":\n return \"Take ONLY the facial features and expression — preserve 100% facial identity, bone structure, skin tone, and all unique features. Do not alter eyes, nose, mouth, or facial shape. Maintain natural skin texture, including pores and imperfections. Adopt clothing, hair styling, and posture from the rest of the prompt.\"\n case \"face-pose\":\n return \"Take the facial features AND body pose — preserve 100% facial identity, bone structure, skin tone, and all unique features. Do not alter eyes, nose, mouth, or facial shape. Maintain natural skin texture. Adopt clothing and styling from the rest of the prompt.\"\n case \"pose\":\n return \"Take only the body pose and posture — do not copy facial identity, features, or skin. Adopt face, clothing, hair, and all other details from the rest of the prompt.\"\n case \"emotion\":\n return \"Take only the emotional expression — preserve 100% facial identity and all unique features unchanged. Adopt face shape, clothing, body, and pose from the rest of the prompt; transfer only the emotional cue.\"\n case \"style\":\n return \"Take only the visual style and tone (lighting, color grade, atmosphere). Do not copy the subject's identity, clothing, or pose.\"\n case \"name\":\n case \"none\":\n return null\n }\n}\n\n/** Human-readable label for the dropdown / badge UI. */\nexport function usageModeLabel(mode: UsageMode): string {\n switch (mode) {\n case \"identical\": return \"Identical\"\n case \"face\": return \"Face only\"\n case \"face-pose\": return \"Face + Pose\"\n case \"pose\": return \"Pose only\"\n case \"emotion\": return \"Emotion only\"\n case \"style\": return \"Style only\"\n case \"name\": return \"Name only\"\n case \"none\": return \"None\"\n }\n}\n\n/**\n * Whether the labeled subject for this mode should include the character name\n * in parens (e.g. `Image A (shira)`) or stay bare (`Image A`). Only `none`\n * returns false — every other mode (including `name`) keeps the name so the\n * model can correlate the bullet with a named entity in the rest of the\n * prompt. Used by `resolveCharacterMentions` to decide the subject form AND to\n * filter the top-level \"Use these characters:\" header (a character whose\n * mentions are ALL `none` is invisible textually — only the image is\n * attached).\n */\nexport function usageModeIncludesName(mode: UsageMode): boolean {\n return mode !== \"none\"\n}\n","/**\n * Shared helper for materializing user-attached \"extra reference images\" into\n * `ConnectedReference` entries.\n *\n * Used by both:\n * - frontend `execute-node.ts` (single-node Run + DAG executor path) and\n * - backend `payload-builder.ts` (orchestrator path)\n * so single-node frontend runs and orchestrator-driven runs produce identical\n * `referenceImageUrls` + assembled prompts. See `frontend/src/types/nodes.ts`\n * for the `ExtraRef` interface and `packages/shared/src/prompt-builder.ts`\n * for the directive emission contract (`buildExtraRefDirectives`).\n *\n * Field mapping:\n * - manual upload → source = \"manual\", description = ref.description\n * - char-variant → source = \"wired-character\", characterSlug + variantSlug\n * preserved, description = ref.description (used as the\n * bullet's per-image description in directives — overrides\n * `variantDescription` from the character node).\n *\n * Usage-mode resolution: per-ref `usageMode` override → upstream character\n * node's `defaultUsageMode` → global \"identical\". The resolved mode is stored\n * in `defaultUsageMode` on the resulting `ConnectedReference` so the existing\n * directive emission (`buildExtraRefDirectives`, `buildCanonicalFallback`,\n * `resolveCharacterMentions`) reads it uniformly.\n *\n * Character-node lookup: takes a `lookupCharacterNode` callback so each caller\n * can provide its own (frontend uses Zustand store + edges, backend uses\n * `PayloadBuildContext.nodes` + edges). The callback should return the\n * character node whose name slugifies to `characterSlug`, or undefined if\n * no such character is wired upstream.\n */\n\nimport { DEFAULT_USAGE_MODE, type UsageMode } from \"./character-usage-mode.js\"\nimport type { ConnectedReference } from \"./types.js\"\n\n/** Shape of an extra-ref entry on node data. Matches `ExtraRef` in the\n * frontend `types/nodes.ts`; duplicated here as a structural interface so\n * the backend (which sees node data as `Record<string, unknown>`) can pass\n * raw JSON through `expandExtraRefsToConnectedReferences`. */\nexport interface ExtraRefInput {\n readonly url?: string\n readonly description?: string\n readonly characterSlug?: string\n readonly variantSlug?: string\n readonly variantDisplayName?: string\n readonly usageMode?: UsageMode\n}\n\n/** Hook that returns extra metadata for the upstream Character node backing\n * a given character slug, if any. Used to resolve `defaultUsageMode` and\n * `characterCanonicalDescription`. */\nexport interface ExtraRefCharacterContext {\n readonly defaultUsageMode?: UsageMode\n readonly canonicalDescription?: string | null\n readonly displayName?: string\n /** Character node's hybrid `defaultRole` — stamped onto the extra's\n * `ConnectedReference.defaultRole` (only when the extra carries no per-ref\n * `usageMode` override, which would take precedence). */\n readonly defaultRole?: string\n /** Character node's `identityLock`, mapped to the per-reference lock shape\n * (`characterLockToRefLock`) — stamped onto the extra's\n * `ConnectedReference.identityLock`. */\n readonly identityLock?: { enabled: boolean; text?: string }\n}\n\n/**\n * Convert a list of `ExtraRef` entries into `ConnectedReference` entries that\n * append to the consumer node's existing `connectedReferences` list. The\n * resulting entries carry `isExtraRef: true` so the shared prompt-builder\n * routes them through the dedicated extra-ref directive emission (which\n * handles \"Image N is the same subject as Image M, …\" pairing).\n *\n * `lookupCharacterContext(slug)` is called for character-sourced extras to\n * resolve the upstream character node's `defaultUsageMode` and canonical\n * description. Returning `undefined` is safe — the helper falls back to the\n * per-ref `usageMode` override or the global default.\n */\nexport function expandExtraRefsToConnectedReferences(\n extras: ReadonlyArray<ExtraRefInput> | undefined,\n lookupCharacterContext?: (slug: string) => ExtraRefCharacterContext | undefined,\n): ConnectedReference[] {\n if (!extras || extras.length === 0) return []\n const out: ConnectedReference[] = []\n for (let i = 0; i < extras.length; i++) {\n const r = extras[i]\n if (!r || !r.url) continue\n const description = (r.description ?? \"\").trim()\n if (r.characterSlug) {\n // Character-sourced extra. Resolution chain for the effective mode:\n // per-ref override (r.usageMode) → upstream character node's default →\n // global identical. The character node lookup also gives us the\n // canonical description used by \"identical\"/\"face-pose\" mode displays.\n const ctx = lookupCharacterContext?.(r.characterSlug)\n const effectiveMode: UsageMode = r.usageMode ?? ctx?.defaultUsageMode ?? DEFAULT_USAGE_MODE\n const displayName = ctx?.displayName || r.characterSlug\n out.push({\n id: `extra_${i}`,\n defaultName: r.variantDisplayName\n ? `${displayName} / ${r.variantDisplayName}`\n : displayName,\n source: \"wired-character\",\n description,\n url: r.url,\n characterSlug: r.characterSlug,\n variantSlug: r.variantSlug,\n characterCanonicalDescription: ctx?.canonicalDescription ?? null,\n variantDescription: description.length > 0 ? description : null,\n variantDisplayName: r.variantDisplayName,\n defaultUsageMode: effectiveMode,\n // Node-default role (Character Node Role+Lock): stamped ONLY when the\n // extra carries no per-ref `usageMode` override — the override wins\n // (it's already folded into `defaultUsageMode` above, and\n // `resolveDefaultRole` would otherwise let the role beat it).\n defaultRole: r.usageMode ? undefined : ctx?.defaultRole,\n // Node's mapped identity-lock (`characterLockToRefLock`) — orthogonal\n // to the role; the hybrid renderers emit its line via\n // `buildIdentityLockLine`.\n identityLock: ctx?.identityLock,\n isExtraRef: true,\n })\n } else {\n // Manual upload extra. `description` is what the user typed in the\n // per-row textarea; usage mode override applies if set (drives the\n // directive's lock language even for manual refs — covers the \"use as\n // style/face only\" case for an uploaded photo).\n const effectiveMode: UsageMode | undefined = r.usageMode\n out.push({\n id: `extra_${i}`,\n defaultName: `Image ${i + 1}`,\n source: \"manual\",\n description,\n url: r.url,\n defaultUsageMode: effectiveMode,\n isExtraRef: true,\n })\n }\n }\n return out\n}\n","/**\n * Model-id enum + UI resolution options for Replicate Flux 2 image models.\n *\n * The provider-$ rate table and the cost/credit FORMULAS derived from it live\n * in `backend/src/lib/pricing/flux2-cost.ts` (core, not ee/ — the Replicate\n * provider integration needs them regardless of edition). They were moved\n * out of this package (published Apache-2.0 on npm — an irrevocable grant)\n * per the 2026-07-06 public-flip IP audit, S5.\n */\n\nexport type Flux2Model = \"flux-2-klein\" | \"flux-2-pro\" | \"flux-2-max\"\n\n/** Megapixel tiers offered in the UI (strings; the value space for data.resolution). */\nexport const FLUX2_RES_MP = [\"0.5\", \"1\", \"2\", \"4\"] as const\n\nexport function isFlux2Model(m: string): m is Flux2Model {\n return m === \"flux-2-klein\" || m === \"flux-2-pro\" || m === \"flux-2-max\"\n}\n","/**\n * Build composite credit model identifiers for variable pricing.\n * Shared between frontend and backend.\n */\n\nimport {\n HIGH_QUALITY_PROVIDERS,\n TWO_K_RESOLUTION_PROVIDERS,\n RESOLUTION_2K_4K_TIERED_PROVIDERS,\n IDEOGRAM_PROVIDERS,\n DURATION_PRICED_PROVIDERS,\n AUDIO_ADDON_PROVIDERS,\n MODE_ADDON_PROVIDERS,\n RESOLUTION_VIDEO_REF_PRICING,\n RESOLUTION_DURATION_PRICING,\n VEO_RESOLUTION_TIERED_PROVIDERS,\n VIDEO_DURATION_TIERS,\n MOTION_DURATION_TIERS,\n T2I_TO_I2I_VARIANT,\n isVeoProvider,\n} from \"./model-constants.js\"\nimport { isFlux2Model } from \"./flux2-pricing.js\"\nimport { MODEL_CATALOG } from \"./model-catalog.js\"\n\n/**\n * Compute composite model identifier for variable credit pricing.\n * Examples: \"gpt-image:high\", \"flux:2K\", \"nano-banana-pro:4K\", \"ideogram:TURBO\",\n * \"flux-2-pro:2MP\", \"flux-2-max:2MP:1ref\" (Flux 2 — billed per megapixel).\n *\n * For image models, uses quality/resolution/renderingSpeed and (Flux 2) the output\n * megapixel count plus (Flux 2 Max) the number of reference images attached at request time.\n * For video models, uses duration/sound params when the model has variable pricing.\n */\nexport function buildCreditModelIdentifier(\n provider: string,\n quality?: string,\n resolution?: string,\n renderingSpeed?: string,\n targetResolution?: string,\n referenceImageCount?: number,\n): string {\n // Flux 2 family: billed per output megapixel AND per reference image (each\n // ref counts as input megapixels). Resolution arrives as \"N MP\" strings (the\n // UI value space); strip the unit. ALL three models encode the ref count\n // (capped at 8): Pro/Klein i2i always carry the source image as a ref and\n // their cost formula charges per input MP, so the reserved identifier must\n // reflect refs (there is no metered true-up to correct an under-reserved tier).\n if (isFlux2Model(provider)) {\n const mp = (resolution ?? \"1 MP\").replace(/\\s*MP$/i, \"\").trim()\n return `${provider}:${mp}MP:${Math.min(referenceImageCount ?? 0, 8)}ref`\n }\n if (HIGH_QUALITY_PROVIDERS.has(provider) && quality === \"high\") {\n return `${provider}:high`\n }\n if (TWO_K_RESOLUTION_PROVIDERS.has(provider) && resolution === \"2K\") {\n return `${provider}:2K`\n }\n if (provider === \"nano-banana-pro\" && resolution === \"4K\") {\n return `${provider}:4K`\n }\n if (RESOLUTION_2K_4K_TIERED_PROVIDERS.has(provider) && (resolution === \"2K\" || resolution === \"4K\")) {\n return `${provider}:${resolution}`\n }\n // Topaz Image Upscale: 2K is default (no suffix), 4K/8K get composite identifiers\n if (provider === \"topaz-image-upscale\" && targetResolution && targetResolution !== \"2K\") {\n return `${provider}:${targetResolution}`\n }\n if (IDEOGRAM_PROVIDERS.has(provider)) {\n if (renderingSpeed === \"TURBO\") return `${provider}:TURBO`\n if (renderingSpeed === \"QUALITY\") return `${provider}:QUALITY`\n }\n return provider\n}\n\n/**\n * Reference-aware image-generation credit identifier — the SINGLE source of\n * truth shared by the single-node routes (`/v1/generate-image`,\n * `/v1/image-to-image`) and the workflow orchestrator\n * (`payload-builder.ts`). It centralises the two pricing dimensions that must\n * match across both paths or a Flux 2 generation is billed the wrong tier\n * (Flux 2 commits non-metered / has no upward true-up, so the reserved\n * identifier IS the final charge):\n * - `refCount`: the number of reference images sent to the provider (Flux 2\n * bills per ref). generate-image passes the assembled count (0 for pure\n * text-to-image); image-to-image passes 1 (the primary `imageUrl`) + extras.\n * - `swapToI2i`: generate-image auto-swaps a bare T2I provider to its i2i\n * sibling (`T2I_TO_I2I_VARIANT`) when refs are attached, so the credit id\n * matches the variant actually invoked. image-to-image is already an i2i\n * provider → pass `false`.\n *\n * The LoRA short-circuit (`flux-lora-character`) stays at the call site because\n * the routing decision needs a DB lookup the routes/orchestrator own.\n */\nexport function resolveImageGenCreditIdentifier(opts: {\n provider: string | undefined\n quality?: string\n resolution?: string\n renderingSpeed?: string\n refCount: number\n swapToI2i?: boolean\n}): string {\n const provider = opts.provider || \"nano-banana\"\n const effectiveProvider =\n opts.swapToI2i && opts.refCount > 0 ? (T2I_TO_I2I_VARIANT[provider] ?? provider) : provider\n return buildCreditModelIdentifier(\n effectiveProvider,\n opts.quality,\n opts.resolution,\n opts.renderingSpeed,\n undefined,\n opts.refCount,\n )\n}\n\n// T2V-specific credit overrides: some providers have different costs for T2V\n// vs I2V/V2V due to different default resolutions or colliding with image model names.\nconst T2V_CREDIT_OVERRIDES: Record<string, string> = {\n \"grok\": \"grok-i2v\", // T2V grok, same as I2V grok (not image grok = 4 cr)\n \"wan\": \"wan-t2v\", // T2V wan 1080p = (V2V wan 720p = 70 cr)\n \"wan-turbo\": \"wan-turbo-t2v\", // T2V wan-turbo 720p = (I2V wan-turbo 480p = 40 cr)\n}\n\n/**\n * Compute composite model identifier for video models with duration/audio-based pricing.\n * Examples: \"kling-3.0:5s\", \"kling-3.0:10s:audio\", \"seedance-2:8s:720p-ref\"\n *\n * @param provider - Video model key (e.g., \"kling-3.0\")\n * @param duration - Video duration in seconds\n * @param sound - Whether audio/sound is enabled\n * @param nodeType - Node type for T2V-specific cost overrides\n * @param mode - Quality variant that affects pricing\n * @param resolution - Output resolution (used by Seedance 2 for 480p/720p pricing)\n * @param hasVideoRef - Whether a reference video is connected (Seedance 2 uses a lower per-second rate when true)\n */\n/** Gemini Omni Video duration tiers (seconds). Mirrors `MODEL_CATALOG[\"gemini-omni-video\"].durations`\n * and `KIE_VIDEO_MODELS[\"gemini-omni-video\"].allowedDurations`. Hoisted to module scope so the\n * nearest-tier snap below doesn't reallocate on every (hot-path) call. */\nconst GEMINI_OMNI_DURATIONS = [4, 6, 8, 10]\n\n/**\n * LTX 2.3 (Lightricks via Replicate) credit tiers: priced by\n * (resolution-band × duration-seconds). Keys mirror STATIC_CREDIT_COSTS /\n * model_pricing EXACTLY (lowercase band + raw seconds + \"s\"), e.g.\n * \"ltx-2.3-pro:1080p:6s\". This map is the source of truth for the nearest-tier\n * snap below, so an off-catalog (resolution, duration) from a direct API/SDK\n * call maps to a SEEDED price instead of hard-failing (price_not_configured\n * 503). Pro: 6/8/10s at every band. Fast: up to 20s at 1080p, 6/8/10s at 2k/4k.\n */\nconst LTX_DURATION_TIERS: Record<string, Record<string, number[]>> = {\n \"ltx-2.3-pro\": { \"1080p\": [6, 8, 10], \"2k\": [6, 8, 10], \"4k\": [6, 8, 10] },\n \"ltx-2.3-fast\": { \"1080p\": [6, 8, 10, 12, 14, 16, 18, 20], \"2k\": [6, 8, 10], \"4k\": [6, 8, 10] },\n}\n\nexport function buildVideoCreditModelIdentifier(\n provider: string,\n duration?: number | string,\n sound?: boolean,\n nodeType?: \"image-to-video\" | \"text-to-video\",\n mode?: string,\n resolution?: string,\n hasVideoRef?: boolean,\n): string {\n // T2V overrides: some providers have different base costs for text-to-video\n let effectiveProvider = provider\n if (nodeType === \"text-to-video\") {\n const override = T2V_CREDIT_OVERRIDES[provider]\n if (override) {\n // If override target also has duration pricing, use it as effective provider\n if (DURATION_PRICED_PROVIDERS.has(override)) {\n effectiveProvider = override\n } else {\n return override\n }\n }\n }\n\n // VEO 3.x resolution-tiered pricing: 720p is the base (no suffix), 1080p gets\n // \":1080p\" (Fast/Lite only), and 4K gets \":4k\" for ALL three tiers — direct-4K\n // generation chains KIE's get-4k-video off the base generation (the base runs\n // at 1080p). Duration is fixed at 8s for VEO so the duration-tier path below\n // does not apply.\n if (isVeoProvider(effectiveProvider)) {\n if (resolution === \"4k\") return `${effectiveProvider}:4k`\n // 1080p tier is Fast/Lite only (Quality has no 1080p surcharge).\n if (resolution === \"1080p\" && VEO_RESOLUTION_TIERED_PROVIDERS.has(effectiveProvider)) return `${effectiveProvider}:1080p`\n return effectiveProvider\n }\n\n // Gemini Omni Video: priced by (resolution-band × duration), with a flat\n // per-generation rate when a source video is supplied (V2V). Lowercase \"4k\".\n if (effectiveProvider === \"gemini-omni-video\") {\n if (hasVideoRef) {\n return resolution === \"4k\" ? \"gemini-omni-video:4k:vref\" : \"gemini-omni-video:vref\"\n }\n // Snap to nearest allowed tier (NOT a min/max clamp) so off-tier durations\n // map to a SEEDED composite; default 8 when unset.\n const raw = parseInt(String(duration ?? 8), 10)\n const d = Number.isNaN(raw) ? 8 : GEMINI_OMNI_DURATIONS.reduce((b, a) => (Math.abs(a - raw) < Math.abs(b - raw) ? a : b))\n return resolution === \"4k\" ? `gemini-omni-video:4k:${d}` : `gemini-omni-video:${d}`\n }\n\n // LTX 2.3: priced by (resolution-band × duration-seconds). The RESERVE must be\n // the correct composite — commit_credits (migration 176) only refunds a surplus\n // (actual < reserved) and NEVER collects an upward delta, so an under-reserved\n // LTX run (the bare-id default = cheapest 1080p:6s tier) stays under-charged\n // even with meteredCost:true. Snap to a seeded tier so the id always prices.\n if (effectiveProvider === \"ltx-2.3-pro\" || effectiveProvider === \"ltx-2.3-fast\") {\n const bands = LTX_DURATION_TIERS[effectiveProvider]\n const band = bands[String(resolution)] ? String(resolution) : \"1080p\"\n const allowed = bands[band]\n const raw = typeof duration === \"string\" ? parseInt(duration, 10) : (duration ?? allowed[0])\n const want = Number.isNaN(raw) ? allowed[0] : raw\n const dur = allowed.reduce((b, a) => (Math.abs(a - want) < Math.abs(b - want) ? a : b))\n return `${effectiveProvider}:${band}:${dur}s`\n }\n\n if (!DURATION_PRICED_PROVIDERS.has(effectiveProvider)) {\n return effectiveProvider\n }\n\n const parsed = typeof duration === \"string\" ? parseInt(duration, 10) : (duration ?? 5)\n const durationSec = Number.isNaN(parsed) ? 5 : parsed\n const tiers = VIDEO_DURATION_TIERS[effectiveProvider]\n if (!tiers) return effectiveProvider\n\n // Find the matching duration tier\n const tier = tiers.find(t => durationSec <= t.maxSeconds) ?? tiers[tiers.length - 1]\n let identifier = `${effectiveProvider}:${tier.suffix}`\n\n // Append audio suffix if applicable\n if (AUDIO_ADDON_PROVIDERS.has(effectiveProvider) && sound) {\n identifier += \":audio\"\n }\n\n // Append mode suffix for providers with quality-tiered pricing\n // \"high\" comes from I2V videoSize field, \"pro\" comes from T2V mode field\n if (MODE_ADDON_PROVIDERS.has(effectiveProvider) && (mode === \"high\" || mode === \"pro\")) {\n identifier += \":high\"\n }\n\n // Seedance 2.0 family: per-second billing with resolution + video-ref dimensions.\n // KIE accepts 480p / 720p / 1080p natively; per-second rates rise non-linearly\n // so each tier gets its own composite identifier.\n if (RESOLUTION_VIDEO_REF_PRICING.has(effectiveProvider)) {\n // Clamp to the model's catalog resolutions (single source of truth): e.g.\n // seedance-2-mini exposes only 480p/720p, so a stale/explicit 1080p (or 4k)\n // maps to its top priced tier instead of emitting an unpriced composite\n // (which the hard-fail credit guard would 503 on at runtime).\n const supported = MODEL_CATALOG[effectiveProvider]?.resolutions ?? [\"480p\", \"720p\", \"1080p\"]\n const want = resolution === \"4k\" ? \"4k\" : resolution === \"1080p\" ? \"1080p\" : resolution === \"720p\" ? \"720p\" : \"480p\"\n // Unsupported (e.g. a stale 1080p on seedance-2-mini) clamps to the model's\n // top priced tier so the emitted composite is always seeded.\n const res = supported.includes(want) ? want : (supported[supported.length - 1] ?? \"480p\")\n identifier += `:${res}`\n if (hasVideoRef) identifier += \"-ref\"\n }\n\n // Duration × resolution pricing without a -ref dimension. Resolutions\n // outside the provider's priced tiers (or undefined) collapse to the first\n // (default) tier so the emitted composite is always seeded — the hard-fail\n // guard fuzzes the whole resolution space.\n const resTiers = RESOLUTION_DURATION_PRICING[effectiveProvider]\n if (resTiers) {\n const res = resolution && resTiers.includes(resolution) ? resolution : resTiers[0]!\n identifier += `:${res}`\n }\n\n return identifier\n}\n\n/**\n * Compute composite model identifier for motion control with duration-tiered pricing.\n * Examples: \"kling-3.0-motion:10s\", \"kling-3.0-motion:1080p:15s\", \"motion-transfer:5s\"\n *\n * Wan Animate providers use resolution-tiered pricing (not per-second):\n * \"wan-animate-move\" (480p default), \"wan-animate-move:580p\", \"wan-animate-move:720p\"\n *\n * @param provider - Motion control provider key (\"kling\" for 2.6, \"kling-3.0\", \"wan-animate-move\", \"wan-animate-replace\")\n * @param resolution - \"720p\" or \"1080p\" (Kling), \"480p\" or \"580p\" or \"720p\" (Wan Animate)\n * @param videoDuration - Reference video duration in seconds (defaults to 10s, unused for Wan Animate)\n */\nexport function buildMotionCreditModelIdentifier(\n provider: string,\n resolution: string,\n videoDuration?: number,\n): string {\n // Wan Animate providers use resolution-tiered pricing (not duration-based)\n if (provider === \"wan-animate-move\" || provider === \"wan-animate-replace\") {\n // 480p is the default (base identifier), 580p and 720p get composite suffix\n if (resolution === \"580p\" || resolution === \"720p\") {\n return `${provider}:${resolution}`\n }\n return provider\n }\n\n const raw = videoDuration ?? 10\n const durationSec = Math.floor(Number.isNaN(raw) ? 10 : raw) // default 10s; floor to match KIE per-second billing\n const tier = MOTION_DURATION_TIERS.find(t => durationSec <= t.maxSeconds)\n ?? MOTION_DURATION_TIERS[MOTION_DURATION_TIERS.length - 1]\n\n const base = provider === \"kling-3.0\" ? \"kling-3.0-motion\" : \"motion-transfer\"\n const resSuffix = resolution === \"1080p\" ? \":1080p\" : \"\"\n return `${base}${resSuffix}:${tier.suffix}`\n}\n","/**\n * Pure credit estimators for video-utility nodes (loop-video, trim-video,\n * combine-videos). Used by frontend (Run-button display + API call) AND\n * backend (creditGuard reservation) so the displayed cost equals what gets\n * debited.\n */\n\nexport const VIDEO_UTIL_PRICING = {\n /** 1 credit per 5 seconds of output, ceiling. */\n CREDITS_PER_5_SEC: 1,\n /** Smart-loop-cut work scales at 1 credit 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\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 Math.max(1, 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 Math.max(1, 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 Math.max(1, 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 Math.max(1, 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 Math.max(1, 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 Math.max(1, Math.ceil(output / 5))\n }\n\n // \"time\" mode (default)\n const output = (data.endTime ?? 0) - (data.startTime ?? 0)\n return Math.max(1, 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 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 Math.max(1, 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: ceil(duration / 5) + ceil(framesToTest / 24) — matches the\n * trim-video smart-loop-cut formula for consistency. */\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 Math.ceil(outputDurationSeconds / 5) +\n Math.ceil(frames / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT)\n}\n\n/** BASE credits (at-cost) for assemble-narrated-video: 3 flat + 1 per 6\n * blocks. 6→4, 24→7, 60→13. Single source of truth shared by the backend\n * route/creditGuard (`backend/src/providers/video/narrated-block-fit.ts`\n * re-exports this) and the frontend pre-run estimate\n * (`frontend/src/hooks/use-estimated-credits.ts`). */\nexport function assembleNarratedVideoCredits(blockCount: number): number {\n return 3 + Math.ceil(blockCount / 6)\n}\n","/** Read a video node's duration (in seconds) from its data shape.\n * Tries `generatedResults[activeResultIndex].duration` (post-execution\n * metadata) first, then `data.duration` (configured at design time on\n * generate-video / image-to-video / text-to-video nodes). Returns\n * undefined when neither is set — callers should fall back to a sensible\n * default (e.g. 8s).\n *\n * Lives in `@nodaro/shared` so frontend (store walks) and backend\n * (orchestrator input-resolver) can use one source of truth. */\nexport function extractVideoDurationFromNode(\n data: Record<string, unknown> | undefined,\n): number | undefined {\n if (!data) return undefined\n const results = data.generatedResults as Array<{ duration?: number }> | undefined\n const idx = (data.activeResultIndex as number | undefined) ?? 0\n const fromResult = results?.[idx]?.duration\n if (typeof fromResult === \"number\" && Number.isFinite(fromResult) && fromResult > 0) {\n return fromResult\n }\n const fromConfig = data.duration\n if (typeof fromConfig === \"number\" && Number.isFinite(fromConfig) && fromConfig > 0) {\n return fromConfig\n }\n return undefined\n}\n","/**\n * Presentation / API utilities — pure logic, no React deps.\n * Shared between frontend (presentation mode) and backend (API schema generation).\n */\n\nimport type { GenericNode, GenericEdge } from \"./types.js\"\nimport type { PresentationItem } from \"./presentation-types.js\"\n\n// ---------------------------------------------------------------------------\n// Node type sets\n// ---------------------------------------------------------------------------\n\nexport const INPUT_NODE_TYPES = new Set([\n \"text-prompt\",\n \"upload-image\",\n \"upload-video\",\n \"upload-audio\",\n \"tone\",\n \"style-guide\",\n \"provider\",\n \"scene-count\",\n \"duration\",\n \"aspect-ratio\",\n \"motion\",\n \"camera-motion\",\n \"framing\",\n \"lens\",\n \"camera-format\",\n \"lighting\",\n \"color-look\",\n \"atmosphere\",\n \"action-fx\",\n \"temporal\",\n \"reference-audio\",\n])\n\nconst TRIGGER_NODE_TYPES = new Set([\n \"webhook-trigger\",\n \"schedule-trigger\",\n])\n\nconst ALWAYS_EXCLUDED_TYPES = new Set([\n \"sticky-note\",\n \"webhook-trigger\",\n \"schedule-trigger\",\n \"sub-workflow-input\",\n \"sub-workflow-output\",\n])\n\nconst NON_OUTPUT_TYPES = new Set([\n \"text-prompt\",\n \"list\",\n \"upload-image\",\n \"upload-video\",\n \"upload-audio\",\n \"reference-audio\",\n \"rss-feed\",\n \"youtube-video\",\n \"tone\",\n \"style-guide\",\n \"provider\",\n \"scene-count\",\n \"duration\",\n \"aspect-ratio\",\n \"motion\",\n \"camera-motion\",\n \"framing\",\n \"lens\",\n \"camera-format\",\n \"lighting\",\n \"color-look\",\n \"atmosphere\",\n \"action-fx\",\n \"temporal\",\n \"sticky-note\",\n \"sub-workflow-input\",\n \"sub-workflow-output\",\n \"webhook-trigger\",\n \"schedule-trigger\",\n \"combine-text\",\n \"split-text\",\n \"save-to-storage\",\n \"webhook-output\",\n \"component\",\n])\n\nconst MEDIA_PRODUCING_TYPES = new Set([\n \"generate-image\",\n \"edit-image\",\n \"image-to-image\",\n \"image-to-video\",\n \"text-to-video\",\n \"video-to-video\",\n \"text-to-speech\",\n \"generate-music\",\n \"text-to-audio\",\n \"generate-script\",\n \"ai-writer\",\n \"llm-chat\",\n \"render-video\",\n \"video-composer\",\n \"after-effects\",\n \"lottie-overlay\",\n \"3d-title\",\n \"motion-graphics\",\n \"composite\",\n \"text-to-dialogue\",\n \"voice-changer\",\n \"dubbing\",\n \"voice-remix\",\n \"voice-design\",\n \"extend-video\",\n \"lip-sync\",\n \"motion-transfer\",\n \"video-upscale\",\n])\n\n// Output type categorizations\nconst IMAGE_OUTPUT_TYPES = new Set([\n \"generate-image\", \"edit-image\", \"image-to-image\",\n \"upload-image\",\n])\n\nconst VIDEO_OUTPUT_TYPES = new Set([\n \"image-to-video\", \"text-to-video\", \"video-to-video\", \"extend-video\",\n \"render-video\", \"video-composer\", \"after-effects\", \"lottie-overlay\",\n \"3d-title\", \"motion-graphics\", \"composite\",\n \"combine-videos\", \"merge-video-audio\", \"resize-video\", \"trim-video\",\n \"speed-ramp\", \"loop-video\", \"fade-video\", \"transcode-video\",\n \"upload-video\",\n \"lip-sync\", \"motion-transfer\", \"video-upscale\", \"add-captions\",\n \"social-media-format\",\n])\n\nconst AUDIO_OUTPUT_TYPES = new Set([\n \"text-to-speech\", \"generate-music\", \"text-to-audio\",\n \"text-to-dialogue\", \"voice-changer\", \"dubbing\", \"voice-remix\",\n \"voice-design\", \"mix-audio\", \"adjust-volume\", \"audio-fx\", \"trim-audio\",\n \"audio-isolation\",\n \"audio-separation\",\n \"upload-audio\",\n])\n\nconst TEXT_OUTPUT_TYPES = new Set([\n \"generate-script\", \"ai-writer\", \"llm-chat\", \"transcribe\", \"image-to-text\", \"qa-check\",\n \"text-prompt\",\n])\n\n// ---------------------------------------------------------------------------\n// Output type enum\n// ---------------------------------------------------------------------------\n\nexport type OutputType = \"image\" | \"video\" | \"audio\" | \"text\" | \"data\"\n\n// ---------------------------------------------------------------------------\n// Core functions\n// ---------------------------------------------------------------------------\n\n/** Get nodes that act as user inputs (text prompts, uploads, parameters). */\nexport function getInputNodes<T extends GenericNode>(nodes: T[], curatedOnly = true): T[] {\n return nodes.filter((n) => {\n if (!n.type || ALWAYS_EXCLUDED_TYPES.has(n.type)) return false\n if (n.hidden) return false\n if (curatedOnly) {\n // New explicit flag\n if (n.data.presentationInput === true) return true\n // Backwards compat: old flag on input-type nodes\n if (n.data.presentationVisible === true && INPUT_NODE_TYPES.has(n.type)) return true\n return false\n }\n return true\n })\n}\n\n/** Get leaf/media-producing nodes that represent workflow outputs. */\nexport function getOutputNodes<T extends GenericNode>(\n nodes: T[],\n edges: GenericEdge[],\n curatedOnly = true,\n): T[] {\n const nodesWithOutgoing = new Set(edges.map((e) => e.source))\n\n return nodes.filter((n) => {\n if (!n.type || ALWAYS_EXCLUDED_TYPES.has(n.type)) return false\n if (n.hidden) return false\n if (curatedOnly) {\n // New explicit flag\n if (n.data.presentationOutput === true) return true\n // Backwards compat: old flag on output-eligible nodes\n if (n.data.presentationVisible === true) {\n if (NON_OUTPUT_TYPES.has(n.type)) return false\n return !nodesWithOutgoing.has(n.id) || MEDIA_PRODUCING_TYPES.has(n.type)\n }\n return false\n }\n return true\n })\n}\n\n/** Map node type to its output media type. */\nexport function getOutputType(nodeType: string | undefined): OutputType {\n if (!nodeType) return \"data\"\n if (IMAGE_OUTPUT_TYPES.has(nodeType)) return \"image\"\n if (VIDEO_OUTPUT_TYPES.has(nodeType)) return \"video\"\n if (AUDIO_OUTPUT_TYPES.has(nodeType)) return \"audio\"\n if (TEXT_OUTPUT_TYPES.has(nodeType)) return \"text\"\n return \"data\"\n}\n\n/** Extract the result URL or text from a node's data. */\nexport function getNodeResult(\n nodeData: Record<string, unknown>,\n): { url?: string; text?: string } {\n // Preview node: extract first visible item from previewItems\n const previewItems = nodeData.previewItems as\n | Array<{ type: string; value: string; visible?: boolean }>\n | undefined\n if (previewItems && previewItems.length > 0) {\n const first = previewItems.find((item) => item.visible !== false) ?? previewItems[0]\n if (first) {\n if (first.type === \"image\" || first.type === \"video\" || first.type === \"audio\") {\n return { url: first.value }\n }\n return { text: first.value }\n }\n }\n\n const results = nodeData.generatedResults as\n | Array<Record<string, unknown>>\n | undefined\n\n if (results && results.length > 0) {\n const idx = (nodeData.activeResultIndex as number) ?? 0\n const active = results[idx] ?? results[0]\n const url = (active?.url ?? active?.imageUrl ?? active?.videoUrl ?? active?.audioUrl) as\n | string\n | undefined\n const text = (active?.text ?? active?.script) as string | undefined\n return { url, text }\n }\n\n // Fallback to individual generated fields\n const url = (nodeData.generatedImageUrl ??\n nodeData.generatedVideoUrl ??\n nodeData.generatedAudioUrl) as string | undefined\n const text = (nodeData.generatedScript ?? nodeData.generatedText) as\n | string\n | undefined\n\n return { url, text }\n}\n\n/** Human-readable label for a node. */\nexport function getNodeLabel(node: GenericNode): string {\n return (\n (node.data.label as string) ||\n node.type?.replace(/-/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase()) ||\n \"Node\"\n )\n}\n\n// ---------------------------------------------------------------------------\n// Input field schema (for API schema generation)\n// ---------------------------------------------------------------------------\n\nexport interface InputFieldSchema {\n key: string\n type: \"text\" | \"image-url\" | \"video-url\" | \"audio-url\" | \"select\" | \"number\"\n options?: string[]\n}\n\n// Override field per input-node type. The `key` for a parameter-picker MUST be\n// the field that `getParameterValue()` (parameter-node-value.ts) actually reads\n// — for multi-dimension pickers, its FIRST per-dimension field (the\n// \"representative key\"). A mismatch silently drops the curated app/MCP/SDK input\n// (the override lands on a field nothing reads). This map is the single source\n// of truth for app-input override fields (consumed by extract-app-inputs.ts,\n// api-tokens.ts, and the app-runner). Its parity with getParameterValue is\n// guarded by input-field-map-parity.test.ts so the two can't drift.\nexport const INPUT_FIELD_MAP: Record<string, InputFieldSchema> = {\n // --- Source / upload nodes (not parameter pickers) ---\n \"text-prompt\": { key: \"text\", type: \"text\" },\n \"upload-image\": { key: \"url\", type: \"image-url\" },\n \"upload-video\": { key: \"url\", type: \"video-url\" },\n \"upload-audio\": { key: \"url\", type: \"audio-url\" },\n \"reference-audio\": { key: \"extractedAudioUrl\", type: \"audio-url\" },\n // --- Classic parameters ---\n \"provider\": { key: \"provider\", type: \"select\" },\n \"style-guide\": { key: \"text\", type: \"text\" }, // reads data.text (was wrongly \"styleGuide\")\n \"scene-count\": { key: \"count\", type: \"number\" },\n \"duration\": { key: \"seconds\", type: \"number\" }, // reads data.seconds (was wrongly \"duration\")\n \"aspect-ratio\": { key: \"ratio\", type: \"select\" }, // reads data.ratio (was wrongly \"aspectRatio\")\n // --- Single-field parameter pickers ---\n \"tone\": { key: \"tone\", type: \"select\" },\n \"motion\": { key: \"motion\", type: \"select\" },\n \"camera-motion\": { key: \"cameraMotion\", type: \"select\" },\n \"lens\": { key: \"lens\", type: \"select\" },\n \"camera-format\": { key: \"cameraFormat\", type: \"select\" },\n \"color-look\": { key: \"colorLook\", type: \"select\" },\n \"atmosphere\": { key: \"atmosphere\", type: \"select\" },\n \"style\": { key: \"style\", type: \"select\" },\n \"setting\": { key: \"setting\", type: \"select\" },\n \"mood\": { key: \"mood\", type: \"select\" },\n \"photographer\": { key: \"photographer\", type: \"select\" },\n \"aesthetic\": { key: \"aesthetic\", type: \"select\" },\n \"era\": { key: \"era\", type: \"select\" },\n \"material\": { key: \"material\", type: \"select\" },\n \"animal\": { key: \"animal\", type: \"select\" },\n \"vehicle\": { key: \"vehicle\", type: \"select\" },\n \"weapon\": { key: \"weapon\", type: \"select\" },\n \"furniture\": { key: \"furniture\", type: \"select\" },\n \"photo-genre\": { key: \"photoGenre\", type: \"select\" },\n \"backdrop\": { key: \"backdrop\", type: \"select\" },\n \"held-prop\": { key: \"heldProp\", type: \"select\" },\n \"render-quality\": { key: \"renderQuality\", type: \"select\" },\n \"composition-effects\": { key: \"compositionEffect\", type: \"select\" },\n \"post-process-effects\": { key: \"postProcess\", type: \"select\" },\n \"action-fx\": { key: \"actionFx\", type: \"select\" },\n \"character-fx\": { key: \"characterFx\", type: \"select\" },\n \"transition\": { key: \"transition\", type: \"select\" },\n \"loop-subject\": { key: \"loopSubject\", type: \"select\" },\n // --- Multi-dimension pickers: representative (first) field. Overriding only\n // sets that dimension; full hint composition runs in the executors. ---\n \"framing\": { key: \"shotSize\", type: \"select\" },\n \"lighting\": { key: \"timeOfDay\", type: \"select\" },\n \"temporal\": { key: \"temporalSpeed\", type: \"select\" },\n \"person\": { key: \"type\", type: \"select\" },\n \"pose\": { key: \"pose\", type: \"select\" },\n \"styling\": { key: \"makeup\", type: \"select\" },\n \"exposure-settings\": { key: \"aperture\", type: \"select\" },\n \"music-genre\": { key: \"subgenre\", type: \"select\" },\n \"music-mood\": { key: \"emotion\", type: \"select\" },\n \"instrumentation\": { key: \"production\", type: \"select\" },\n \"voice-character\": { key: \"timbre\", type: \"select\" },\n \"voice-delivery\": { key: \"archetype\", type: \"select\" },\n}\n\n/** Get the overridable field schema for an input node type. */\nexport function getInputFieldSchema(nodeType: string): InputFieldSchema | undefined {\n return INPUT_FIELD_MAP[nodeType]\n}\n\n// ---------------------------------------------------------------------------\n// Migration & validation helpers (PresentationItem)\n// ---------------------------------------------------------------------------\n\n/** Migrate a legacy string[] order to PresentationItem[]. */\nexport function migrateToItems(order: string[] | undefined): PresentationItem[] | undefined {\n if (!order) return undefined\n return order.map((nodeId) => ({ type: \"node\" as const, nodeId }))\n}\n\n/** Strip nested groups — groups may only contain non-group items. */\nexport function validateNoNestedGroups(items: PresentationItem[]): PresentationItem[] {\n return items.map((item) => {\n if (item.type === \"group\") {\n return { ...item, items: item.items.filter((child) => child.type !== \"group\") }\n }\n return item\n })\n}\n\n/** Recursively flatten all items, unwrapping groups. */\nexport function flattenItems(items: PresentationItem[]): PresentationItem[] {\n const result: PresentationItem[] = []\n for (const item of items) {\n if (item.type === \"group\") {\n result.push(...flattenItems(item.items))\n } else {\n result.push(item)\n }\n }\n return result\n}\n\n/** Get the sortable/unique ID for a PresentationItem. */\nexport function getItemSortId(item: PresentationItem): string {\n return item.type === \"node\" ? item.nodeId : item.id\n}\n\n/** Remove items whose nodeId no longer exists in the workflow. */\nexport function cleanOrphanedItems(\n items: PresentationItem[],\n nodeIds: Set<string>\n): PresentationItem[] {\n return items\n .filter((item) => {\n if (item.type === \"node\" || item.type === \"field\" || item.type === \"output\") return nodeIds.has(item.nodeId)\n return true\n })\n .map((item) => {\n if (item.type === \"group\") {\n return { ...item, items: cleanOrphanedItems(item.items, nodeIds) }\n }\n return item\n })\n}\n","/**\n * Utilities for detecting and filtering expanded loop clones.\n * Shared between frontend (store, persistence, execution) and backend (orchestrator).\n */\n\nimport type { GenericNode, GenericEdge } from \"./types.js\"\n\n/** Matches node IDs like `node_7_iter_0`, `node_7_iter_1`, etc. */\nexport const ITER_CLONE_PATTERN = /_iter_\\d+$/\n\n/** Returns true if the node is an expanded loop clone (by flag or ID pattern). */\nexport function isExpandedClone(node: GenericNode): boolean {\n return !!(node.data as Record<string, unknown>).__expandedClone || ITER_CLONE_PATTERN.test(node.id)\n}\n\n/**\n * Filter out expanded clone nodes and edges that reference them.\n * Unhides original nodes that were hidden during loop expansion.\n * Optionally filters sub-workflow nodes (prefix `__sub_`).\n */\nexport function filterCloneNodes<N extends GenericNode, E extends GenericEdge>(\n nodes: N[],\n edges: E[],\n options?: { filterSubWorkflow?: boolean },\n): { nodes: N[]; edges: E[] } {\n const filterSub = options?.filterSubWorkflow ?? false\n\n const cloneIds = new Set(\n nodes.filter((n) => isExpandedClone(n)).map((n) => n.id),\n )\n\n const filteredNodes = nodes\n .filter((n) => {\n if (cloneIds.has(n.id)) return false\n if (filterSub && n.id.startsWith(\"__sub_\")) return false\n return true\n })\n .map((n) => (n.hidden ? { ...n, hidden: false } as N : n))\n\n const filteredEdges = edges.filter((e) => {\n if (filterSub && (e as { id?: string }).id?.startsWith(\"__sub_\")) return false\n return !cloneIds.has(e.source) && !cloneIds.has(e.target)\n })\n\n return { nodes: filteredNodes, edges: filteredEdges }\n}\n","import type { OutputType } from \"./presentation-utils.js\"\n\n// Intentional subset of OutputType (presentation-utils.ts:152) —\n// excludes \"data\" (multi-output / opaque types are skipped from aggregation).\nexport type AggregateableType = \"text\" | \"image\" | \"video\" | \"audio\"\n\n// Stable ordered tuple of aggregateable types — used for handle ordering + presentTypes.\nexport const AGGREGATEABLE_TYPES = [\"text\", \"image\", \"video\", \"audio\"] as const\n\nexport interface Member {\n nodeId: string\n type: AggregateableType\n value: string\n}\n\nexport interface AggregationBuckets {\n text: string[]\n image: string[]\n video: string[]\n audio: string[]\n}\n\nexport function aggregateByType(members: Member[]): AggregationBuckets {\n const buckets: AggregationBuckets = { text: [], image: [], video: [], audio: [] }\n for (const m of members) buckets[m.type].push(m.value)\n return buckets\n}\n\nexport function presentTypes(buckets: AggregationBuckets): AggregateableType[] {\n return AGGREGATEABLE_TYPES.filter((t) => buckets[t].length > 0)\n}\n\n// Type guard for narrowing OutputType to AggregateableType.\nexport function isAggregateableType(t: OutputType | undefined): t is AggregateableType {\n return t === \"text\" || t === \"image\" || t === \"video\" || t === \"audio\"\n}\n\n// Handle id naming conventions for Group / Collect dynamic output handles + Collect's single input handle.\nexport const GROUP_HANDLE_PREFIX = \"out-\" as const\nexport const COLLECT_IN_HANDLE = \"in\" as const\n\nexport function groupHandleId(t: AggregateableType): string {\n return `${GROUP_HANDLE_PREFIX}${t}`\n}\n\nexport function parseGroupHandle(h: string | null | undefined): AggregateableType | undefined {\n if (!h || !h.startsWith(GROUP_HANDLE_PREFIX)) return undefined\n const candidate = h.slice(GROUP_HANDLE_PREFIX.length) as OutputType\n return isAggregateableType(candidate) ? candidate : undefined\n}\n\n/**\n * Build a parent → children-ids map from a flat node array in a single pass.\n * Used by both engines' `buildExecutionLevels` to derive the implicit\n * child → group dependency edges in O(N+G) instead of O(N×G).\n */\nexport function buildChildrenByParent<N extends { id: string; parentId?: string }>(\n nodes: ReadonlyArray<N>,\n): Map<string, string[]> {\n const childrenByParent = new Map<string, string[]>()\n for (const n of nodes) {\n if (!n.parentId) continue\n const list = childrenByParent.get(n.parentId)\n if (list) list.push(n.id)\n else childrenByParent.set(n.parentId, [n.id])\n }\n return childrenByParent\n}\n\n// Whether an edge targets a Collect node's \"in\" handle. The default-\"in\" fallback\n// matches every other call site so legacy edges without an explicit targetHandle\n// keep working. Duck-typed input shape avoids a runtime dep on @xyflow/react.\nexport function isCollectInEdge(e: { targetHandle?: string | null }): boolean {\n return (e.targetHandle ?? COLLECT_IN_HANDLE) === COLLECT_IN_HANDLE\n}\n","/**\n * LLM Model Registry — shared between frontend and backend.\n *\n * Single source of truth for available chat/LLM models routed through KIE.ai,\n * with direct Anthropic SDK fallback for Claude models. This is the\n * NON-monetary side of the registry (model ids, capabilities, tiers,\n * feature defaults). The provider-$ per-token rate table and the\n * `calculateLlmCost` formula derived from it live in\n * `backend/src/lib/pricing/llm-cost.ts` (core, not ee/ — internal LLM cost\n * logging needs them regardless of edition). They were moved out of this\n * package (published Apache-2.0 on npm — an irrevocable grant) per the\n * 2026-07-06 public-flip IP audit, S5: \"Keep the model-id enum; strip prices\n * + measurement notes.\"\n */\n\nexport type LlmTier = \"economy\" | \"standard\" | \"premium\"\nexport type KieApiFormat = \"chat-completions\" | \"messages\" | \"responses\"\n\nexport interface LlmModelDef {\n id: string\n displayName: string\n desc: string\n tier: LlmTier\n kieFormat: KieApiFormat\n /** For chat-completions: the slug prefix (e.g. \"gemini-3-flash\").\n * For messages: the model id sent in the body (e.g. \"claude-haiku-4-5-v1messages\").\n * For responses: the model id sent in the body (e.g. \"gpt-5-4\"). */\n kieSlugOrModel: string\n vendor: \"anthropic\" | \"google\" | \"openai\"\n supportsImages: boolean\n maxOutputTokens: number\n /**\n * How this model can be forced into schema-valid structured output.\n * - \"anthropic-tool\" → direct Anthropic SDK forced tool_choice (guaranteed).\n * - \"kie-response-format\" → KIE chat-completions `response_format: json_schema`\n * (verified enforced for Gemini via KIE).\n * - undefined → no native structured mode (GPT-via-KIE doesn't honor\n * response_format); callers fall back to parse + retry.\n * Capability-driven so `llmCompleteStructured` never hardcodes provider ids.\n */\n structuredOutputMode?: \"anthropic-tool\" | \"kie-response-format\"\n /** If set, fallback to direct Anthropic SDK with this model ID when KIE.ai fails */\n directFallbackModel?: string\n}\n\nexport const LLM_MODELS: readonly LlmModelDef[] = [\n {\n id: \"gemini-3-flash\",\n displayName: \"Gemini 3 Flash\",\n desc: \"Fast and cheap, good for simple tasks\",\n tier: \"economy\",\n kieFormat: \"chat-completions\",\n kieSlugOrModel: \"gemini-3-flash\",\n vendor: \"google\",\n structuredOutputMode: \"kie-response-format\",\n supportsImages: true,\n maxOutputTokens: 8192,\n },\n {\n id: \"claude-haiku-4.5\",\n displayName: \"Claude Haiku 4.5\",\n desc: \"Fast economy, good reasoning\",\n tier: \"economy\",\n kieFormat: \"messages\",\n kieSlugOrModel: \"claude-haiku-4-5\",\n vendor: \"anthropic\",\n structuredOutputMode: \"anthropic-tool\",\n supportsImages: true,\n maxOutputTokens: 8192,\n directFallbackModel: \"claude-haiku-4-5-20251001\",\n },\n {\n id: \"claude-sonnet-4.6\",\n displayName: \"Claude Sonnet 4.6\",\n desc: \"Balanced quality and speed\",\n tier: \"standard\",\n kieFormat: \"messages\",\n kieSlugOrModel: \"claude-sonnet-4-6\",\n vendor: \"anthropic\",\n structuredOutputMode: \"anthropic-tool\",\n supportsImages: true,\n maxOutputTokens: 16384,\n directFallbackModel: \"claude-sonnet-4-6\",\n },\n {\n id: \"gpt-5.2\",\n displayName: \"GPT-5.2\",\n desc: \"Strong general purpose\",\n tier: \"standard\",\n kieFormat: \"chat-completions\",\n kieSlugOrModel: \"gpt-5-2\",\n vendor: \"openai\",\n supportsImages: true,\n maxOutputTokens: 16384,\n },\n {\n id: \"gemini-3.1-pro\",\n displayName: \"Gemini 3.1 Pro\",\n desc: \"Advanced reasoning, large context\",\n tier: \"premium\",\n kieFormat: \"chat-completions\",\n kieSlugOrModel: \"gemini-3.1-pro\",\n vendor: \"google\",\n structuredOutputMode: \"kie-response-format\",\n supportsImages: true,\n maxOutputTokens: 16384,\n },\n {\n id: \"claude-opus-4.7\",\n displayName: \"Claude Opus 4.7\",\n desc: \"Highest quality, complex tasks\",\n tier: \"premium\",\n kieFormat: \"messages\",\n kieSlugOrModel: \"claude-opus-4-7\",\n vendor: \"anthropic\",\n structuredOutputMode: \"anthropic-tool\",\n supportsImages: true,\n maxOutputTokens: 16384,\n directFallbackModel: \"claude-opus-4-7\",\n },\n {\n id: \"gpt-5.4\",\n displayName: \"GPT-5.4\",\n desc: \"Latest GPT, premium quality\",\n tier: \"premium\",\n kieFormat: \"responses\",\n kieSlugOrModel: \"gpt-5-4\",\n vendor: \"openai\",\n supportsImages: true,\n maxOutputTokens: 16384,\n },\n] as const\n\nexport const LLM_MODEL_IDS = LLM_MODELS.map((m) => m.id)\n\n/** Vision models that can return GUARANTEED structured output — the\n * describe-to-picker analyzer forces a schema over an image, so its model\n * pickers AND the backend route gate offer exactly these: Anthropic (forced\n * tool) + Gemini (KIE `response_format`). GPT-via-KIE has no native structured\n * mode (parse+retry only), so it's excluded. Single source of truth so the\n * picker, the config panel, and the route gate can't drift. */\nexport const STRUCTURED_VISION_MODELS = LLM_MODELS.filter(\n (m) => m.supportsImages && m.structuredOutputMode != null,\n)\n\nexport type LlmFeature =\n | \"ai-writer\"\n | \"llm-chat\"\n | \"prompt-helper\"\n | \"scene-graph-ai\"\n | \"after-effects\"\n | \"motion-graphics\"\n | \"motion-graphics-lottie\"\n | \"lottie-overlay\"\n | \"3d-title\"\n | \"image-to-text\"\n | \"describe-to-picker\"\n | \"qa-check\"\n | \"generate-script\"\n | \"translate\"\n | \"image-critic\"\n\n/** Engine-dependent LlmFeature for the motion-graphics node (design §8: every credit-id site must branch on engine). */\nexport function motionGraphicsFeature(engine?: string): LlmFeature {\n return engine === \"lottie\" ? \"motion-graphics-lottie\" : \"motion-graphics\"\n}\n\n/** Feature → default model when user hasn't selected one */\nexport const LLM_FEATURE_DEFAULTS: Record<LlmFeature, string> = {\n \"ai-writer\": \"claude-sonnet-4.6\",\n \"llm-chat\": \"gemini-3-flash\",\n \"prompt-helper\": \"gemini-3-flash\",\n \"scene-graph-ai\": \"claude-sonnet-4.6\",\n \"after-effects\": \"claude-sonnet-4.6\",\n \"motion-graphics\": \"claude-sonnet-4.6\",\n \"motion-graphics-lottie\": \"claude-sonnet-4.6\",\n \"lottie-overlay\": \"claude-sonnet-4.6\",\n \"3d-title\": \"claude-sonnet-4.6\",\n \"image-to-text\": \"claude-sonnet-4.6\",\n \"describe-to-picker\": \"claude-opus-4.7\",\n \"qa-check\": \"claude-sonnet-4.6\",\n \"generate-script\": \"gemini-3-flash\",\n \"translate\": \"gemini-3-flash\",\n \"image-critic\": \"claude-sonnet-4.6\",\n}\n\n/**\n * Per-model multimodal input capabilities. Drives both frontend UI gating\n * and backend route-level filtering for the LLM Chat node references.\n *\n * As of 2026-05: Claude Messages API supports text + image only (no audio,\n * no video). Gemini 2/3 family supports image + video + audio natively.\n * GPT-5.x via KIE chat-completions / responses supports image only — audio\n * input requires a separate audio-capable model we don't route to today.\n */\nexport const LLM_MODALITY_CAPS: Record<string, { image: boolean; video: boolean; audio: boolean }> = {\n \"gemini-3-flash\": { image: true, video: true, audio: true },\n \"gemini-3.1-pro\": { image: true, video: true, audio: true },\n \"claude-haiku-4.5\": { image: true, video: false, audio: false },\n \"claude-sonnet-4.6\": { image: true, video: false, audio: false },\n \"claude-opus-4.7\": { image: true, video: false, audio: false },\n \"gpt-5.2\": { image: true, video: false, audio: false },\n \"gpt-5.4\": { image: true, video: false, audio: false },\n}\n\n/** Capability lookup with safe default — unknown models get image-only. */\nexport function getLlmModalityCaps(modelId: string | undefined): { image: boolean; video: boolean; audio: boolean } {\n if (!modelId) return { image: true, video: false, audio: false }\n return LLM_MODALITY_CAPS[modelId] ?? { image: true, video: false, audio: false }\n}\n\nexport function getLlmModel(id: string): LlmModelDef | undefined {\n return LLM_MODELS.find((m) => m.id === id)\n}\n\nexport function getLlmTier(id: string): LlmTier {\n return getLlmModel(id)?.tier ?? \"standard\"\n}\n\n/**\n * Build a composite credit identifier for an LLM feature.\n * - economy tier → \"ai-writer:economy\"\n * - standard tier → \"ai-writer\" (no suffix — backward compatible)\n * - premium tier → \"ai-writer:premium\"\n */\nexport function buildLlmCreditIdentifier(feature: string, modelId?: string): string {\n if (!modelId) return feature\n const tier = getLlmTier(modelId)\n if (tier === \"standard\") return feature\n return `${feature}:${tier}`\n}\n\n/**\n * Resolve llmModel from raw body for creditGuard preHandler (before Zod parsing).\n * Returns the credit identifier for the given feature + optional model.\n */\nexport function resolveLlmCreditId(feature: string, body: unknown): string {\n const llmModel = (body as Record<string, unknown>)?.llmModel as string | undefined\n return buildLlmCreditIdentifier(feature, llmModel)\n}\n\n/** Models capable of video-analysis: capability-derived, never hand-listed (route-enum-sync convention). */\nexport const VIDEO_ANALYSIS_LLM_MODELS: string[] = LLM_MODELS\n .filter((m) => getLlmModalityCaps(m.id).video && getLlmModalityCaps(m.id).audio)\n .map((m) => m.id)\n","/**\n * Non-linear progress calculation using quadratic ease-out curve.\n * Returns 0–99 during execution, never reaching 100 (that's set on completion).\n *\n * Formula: progress = 99 * (1 - (1 - t)^exponent)\n * where t = clamp(elapsedMs / estimatedMs, 0, 1)\n */\nexport function calculateProgress(\n elapsedMs: number,\n estimatedMs: number,\n exponent: number = 2,\n): number {\n if (estimatedMs <= 0) return 0\n const t = Math.min(Math.max(elapsedMs / estimatedMs, 0), 1)\n return Math.round(99 * (1 - Math.pow(1 - t, exponent)))\n}\n\n/** Category-based fallback durations (ms) when no historical data exists. */\nexport const CATEGORY_DURATION_DEFAULTS: Record<string, number> = {\n image: 30_000,\n video: 120_000,\n \"audio-tts\": 15_000,\n music: 60_000,\n llm: 8_000,\n upscale: 30_000,\n inline: 500,\n}\n\n/**\n * Compute weighted progress segments for a multi-node flow.\n * Each node gets a proportional slice of 0–99% based on its estimated duration.\n *\n * Returns array of { nodeId, startPct, endPct, estimatedMs } in execution order.\n */\nexport interface ProgressSegment {\n nodeId: string\n startPct: number\n endPct: number\n estimatedMs: number\n}\n\nexport function buildProgressSegments(\n nodeEstimates: { nodeId: string; estimatedMs: number }[],\n): ProgressSegment[] {\n const totalMs = nodeEstimates.reduce((sum, n) => sum + n.estimatedMs, 0)\n if (totalMs <= 0) return []\n\n const segments: ProgressSegment[] = []\n let cursor = 0\n\n for (let i = 0; i < nodeEstimates.length; i++) {\n const { nodeId, estimatedMs } = nodeEstimates[i]\n const sliceWidth = (estimatedMs / totalMs) * 99\n const isLast = i === nodeEstimates.length - 1\n segments.push({\n nodeId,\n startPct: cursor,\n // Last segment always stretches to exactly 99\n endPct: isLast ? 99 : cursor + sliceWidth,\n estimatedMs,\n })\n cursor += sliceWidth\n }\n\n return segments\n}\n\n/**\n * Calculate combined progress for a multi-node flow given current node states.\n */\nexport function calculateCombinedProgress(\n segments: ProgressSegment[],\n nodeStatuses: Record<string, {\n status: \"pending\" | \"running\" | \"completed\" | \"failed\" | \"skipped\"\n startedAt?: string\n }>,\n now: number = Date.now(),\n): number {\n let progress = 0\n\n for (const seg of segments) {\n const state = nodeStatuses[seg.nodeId]\n if (!state) continue\n\n const sliceWidth = seg.endPct - seg.startPct\n\n if (state.status === \"completed\" || state.status === \"skipped\") {\n progress += sliceWidth\n } else if (state.status === \"running\" && state.startedAt) {\n const elapsed = now - new Date(state.startedAt).getTime()\n const nodeProgress = calculateProgress(elapsed, seg.estimatedMs)\n // Map node's 0–99% to this segment's slice\n progress += (nodeProgress / 99) * sliceWidth\n }\n // pending/failed contribute 0\n }\n\n return Math.round(Math.min(progress, 99))\n}\n","/**\n * Shared BFS utility for computing reachable node IDs along a route.\n * Used by both frontend (RunTargetSelector stale guard) and backend\n * (presentation.ts, app-runner.ts, sub-workflow-handler.ts).\n */\n\nexport interface MinimalNode {\n id: string\n type?: string\n data: Record<string, unknown>\n}\n\nexport interface MinimalEdge {\n source: string\n target: string\n}\n\n/**\n * BFS in one direction from a start node.\n */\nfunction bfs(\n startId: string,\n edges: readonly MinimalEdge[],\n direction: \"forward\" | \"backward\",\n): Set<string> {\n const visited = new Set<string>()\n const queue = [startId]\n\n while (queue.length > 0) {\n const current = queue.shift()!\n if (visited.has(current)) continue\n visited.add(current)\n\n for (const edge of edges) {\n if (direction === \"forward\" && edge.source === current && !visited.has(edge.target)) {\n queue.push(edge.target)\n } else if (direction === \"backward\" && edge.target === current && !visited.has(edge.source)) {\n queue.push(edge.source)\n }\n }\n }\n\n return visited\n}\n\n/**\n * Compute the set of node IDs reachable along a route.\n * 1. Finds the sub-workflow-input node with matching routeId\n * 2. Finds the sub-workflow-output node with matching routeId\n * 3. BFS forward from input, BFS backward from output, intersect\n * Returns empty set if input or output node not found (stale routeId).\n */\nexport function getRouteReachableNodeIds(\n nodes: readonly MinimalNode[],\n edges: readonly MinimalEdge[],\n routeId: string,\n): Set<string> {\n const inputNode = nodes.find(\n (n) => n.type === \"sub-workflow-input\" && (n.data as Record<string, unknown>).routeId === routeId,\n )\n const outputNode = nodes.find(\n (n) => n.type === \"sub-workflow-output\" && (n.data as Record<string, unknown>).routeId === routeId,\n )\n\n if (!inputNode || !outputNode) return new Set()\n\n const forwardReachable = bfs(inputNode.id, edges, \"forward\")\n const backwardReachable = bfs(outputNode.id, edges, \"backward\")\n\n const reachable = new Set<string>()\n for (const id of forwardReachable) {\n if (backwardReachable.has(id)) reachable.add(id)\n }\n\n // Always include input and output\n reachable.add(inputNode.id)\n reachable.add(outputNode.id)\n\n return reachable\n}\n","/**\n * Evaluate a dot-notation path against a JSON value.\n *\n * Auto-iterates arrays at any depth: if the current value is an array,\n * the evaluator iterates and applies the remaining path to each element,\n * flattening results. This lets simple paths like \"caption\" work on a\n * top-level array and \"pages.markdown\" work on a nested array without\n * any wildcard syntax.\n *\n * Returns an array of values. Missing properties are skipped (empty for\n * that branch). Null/undefined leaf values are included — callers coerce.\n * Empty path returns `[value]` (a single-element array wrapping the\n * value) when the value is scalar/object, or the array elements flat\n * when the root is an array.\n */\nexport function evaluateJsonPath(value: unknown, path: string): unknown[] {\n const segments = path.length === 0 ? [] : path.split(\".\")\n return walk(value, segments, 0)\n}\n\n/**\n * Coerce an array of unknown values (typically from evaluateJsonPath) to\n * strings, skipping null/undefined. Primitives are stringified; objects\n * are JSON-encoded.\n */\nexport function stringifyPathResults(raw: unknown[]): string[] {\n const out: string[] = []\n for (const v of raw) {\n if (v === null || v === undefined) continue\n if (typeof v === \"string\") out.push(v)\n else if (typeof v === \"number\" || typeof v === \"boolean\") out.push(String(v))\n else out.push(JSON.stringify(v))\n }\n return out\n}\n\nfunction walk(value: unknown, segments: string[], offset: number): unknown[] {\n if (Array.isArray(value)) {\n const results: unknown[] = []\n for (const item of value) {\n for (const v of walk(item, segments, offset)) results.push(v)\n }\n return results\n }\n if (offset >= segments.length) return [value]\n if (value !== null && typeof value === \"object\") {\n const head = segments[offset]\n if (!Object.hasOwn(value as object, head)) return []\n return walk((value as Record<string, unknown>)[head], segments, offset + 1)\n }\n return []\n}\n","/**\n * R2-key + result-id suffix for multi-variant jobs. Provider returns multiple\n * URLs from a single task (Grok = up to 6 images, Suno = 2 tracks); each\n * variant gets a deterministic suffix-keyed ID so primary stays at the original\n * jobId for backwards compat and extras land under `${jobId}-v1`, `${jobId}-v2`, …\n *\n * Used by:\n * - backend `uploadImageVariantsMaybeWatermark` (R2 key)\n * - backend Suno `uploadAllSunoTracks` (R2 key)\n * - frontend `poll-job.ts handleJobCompleted` (GeneratedResult.jobId)\n * - frontend `run-handlers.ts` orchestrator poll loop (GeneratedResult.jobId)\n *\n * Changing the suffix scheme requires updating every caller, hence the shared helper.\n */\nexport function variantJobId(baseJobId: string, index: number): string {\n return index === 0 ? baseJobId : `${baseJobId}-v${index}`\n}\n","/**\n * Auto-upgrade Pinterest CDN URLs to their highest-resolution variant.\n *\n * `i.pinimg.com` serves the same image at multiple sizes via a path-prefix\n * segment: `/236x/`, `/474x/`, `/564x/`, `/736x/`, `/1200x/`, `/originals/`.\n * The `originals` segment returns the source resolution — much better input\n * for `describe-image`, `image-to-image`, `face-swap`, etc.\n *\n * Returns the input unchanged when:\n * - the URL doesn't parse as a URL\n * - the host isn't `i.pinimg.com`\n * - the path doesn't start with a recognized size segment\n *\n * Used by the upload-image node when a user pastes a Pinterest URL, and by\n * any backend describe-image-style fetch that wants the highest-res input.\n */\nexport function normalizePinterestUrl(url: string): string {\n try {\n const u = new URL(url)\n if (u.hostname !== \"i.pinimg.com\") return url\n const next = u.pathname.replace(/^\\/(?:\\d+x|originals)\\//, \"/originals/\")\n if (next === u.pathname) return url\n u.pathname = next\n return u.toString()\n } catch {\n return url\n }\n}\n","// --- Types ---\n\nexport type FilterOperator =\n | \"equals\" | \"not_equals\"\n | \"contains\" | \"not_contains\"\n | \"starts_with\" | \"ends_with\"\n | \"greater_than\" | \"less_than\"\n | \"is_empty\" | \"is_not_empty\"\n | \"matches_regex\"\n | \"in_list\"\n\nexport interface JsonFilter {\n id: string\n field: string\n operator: FilterOperator\n value: string | string[]\n}\n\nexport type JsonEvalResult =\n | { ok: true; value: unknown }\n | { ok: false; error: string }\n\n// --- Helpers ---\n\nconst BARE_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/\n\nfunction escapeString(v: string): string {\n return v.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')\n}\n\nfunction fieldRef(field: string): string {\n return BARE_IDENT.test(field) ? `.${field}` : `.[\"${escapeString(field)}\"]`\n}\n\nfunction coerceValue(v: string): string {\n const trimmed = v.trim()\n if (trimmed === \"\" || trimmed === \"Infinity\" || trimmed === \"-Infinity\" || trimmed === \"NaN\") return `\"${trimmed}\"`\n const n = Number(trimmed)\n return Number.isFinite(n) ? String(n) : `\"${escapeString(trimmed)}\"`\n}\n\nfunction buildFilterExpr(f: JsonFilter): string {\n const ref = fieldRef(f.field)\n switch (f.operator) {\n case \"equals\": return `select(${ref} == ${coerceValue(f.value as string)})`\n case \"not_equals\": return `select(${ref} != ${coerceValue(f.value as string)})`\n case \"contains\": return `select(${ref} | contains(\"${escapeString(f.value as string)}\"))`\n case \"not_contains\": return `select(${ref} | contains(\"${escapeString(f.value as string)}\") | not)`\n case \"starts_with\": return `select(${ref} | startswith(\"${escapeString(f.value as string)}\"))`\n case \"ends_with\": return `select(${ref} | endswith(\"${escapeString(f.value as string)}\"))`\n case \"greater_than\": {\n const n = Number((f.value as string).trim())\n if (!Number.isFinite(n)) return `select(${ref} > 0)`\n return `select(${ref} > ${n})`\n }\n case \"less_than\": {\n const n = Number((f.value as string).trim())\n if (!Number.isFinite(n)) return `select(${ref} < 0)`\n return `select(${ref} < ${n})`\n }\n case \"is_empty\": return `select(${ref} == null or ${ref} == \"\")`\n case \"is_not_empty\": return `select(${ref} != null and ${ref} != \"\")`\n case \"matches_regex\": return `select(${ref} | test(\"${escapeString(f.value as string)}\"))`\n case \"in_list\": {\n // Tolerate string form: users can switch operator to \"in_list\" while the\n // previous operator's string value is still in place. Comma-split so the\n // config panel's \"a, b, c\" shape works before it's persisted as an array.\n const raw = Array.isArray(f.value)\n ? f.value\n : String(f.value ?? \"\").split(\",\").map((s) => s.trim()).filter(Boolean)\n if (raw.length === 0) return `select(false)`\n const items = raw.map((v) => `${ref} == ${coerceValue(v)}`)\n return `select(${items.join(\" or \")})`\n }\n default: return `select(true)`\n }\n}\n\n// --- Public API ---\n\nexport function buildExpressionFromVisual(config: {\n inputPath?: string\n filters?: JsonFilter[]\n projections?: string[]\n}): string {\n const { inputPath, filters = [], projections = [] } = config\n const hasFilters = filters.length > 0\n const hasProjections = projections.length > 0\n const hasPath = !!inputPath && inputPath.trim().length > 0\n\n // Stage 1: path\n let path = hasPath ? `.${inputPath}` : \".\"\n\n // Append [] if filters or projections exist\n if (hasFilters || hasProjections) {\n path += \"[]\"\n }\n\n // If nothing configured, return identity\n if (!hasPath && !hasFilters && !hasProjections) return \".\"\n\n const parts: string[] = [path]\n\n // Stage 2: filters (AND via separate select pipes)\n for (const f of filters) {\n parts.push(buildFilterExpr(f))\n }\n\n // Stage 3: projections\n if (hasProjections) {\n const fields = projections.map((p) => {\n if (BARE_IDENT.test(p)) return p\n return `\"${p}\": .[\"${p}\"]`\n })\n parts.push(`{${fields.join(\", \")}}`)\n }\n\n return parts.join(\" | \")\n}\n\n// --- Tokenizer ---\n\ntype TokType =\n | \"DOT\" | \"PIPE\" | \"LBRACE\" | \"RBRACE\" | \"LBRACKET\" | \"RBRACKET\"\n | \"LPAREN\" | \"RPAREN\" | \"COMMA\" | \"COLON\"\n | \"EMPTY_ITER\" // []\n | \"INDEX\" // [N] or [-N]\n | \"BRACKET_KEY\" // [\"str\"]\n | \"IDENT\" // bare identifier or keyword\n | \"STRING\" // \"...\"\n | \"NUMBER\" // 42 / 3.14\n | \"OP\" // == != > < >= <=\n\ninterface Token { type: TokType; value: string | number }\n\nfunction tokenize(expr: string): Token[] {\n const tokens: Token[] = []\n let i = 0\n\n while (i < expr.length) {\n // whitespace\n if (/\\s/.test(expr[i])) { i++; continue }\n\n const ch = expr[i]\n\n // single-char structural\n if (ch === \".\") { tokens.push({ type: \"DOT\", value: \".\" }); i++; continue }\n if (ch === \"|\") { tokens.push({ type: \"PIPE\", value: \"|\" }); i++; continue }\n if (ch === \"{\") { tokens.push({ type: \"LBRACE\", value: \"{\" }); i++; continue }\n if (ch === \"}\") { tokens.push({ type: \"RBRACE\", value: \"}\" }); i++; continue }\n if (ch === \"(\") { tokens.push({ type: \"LPAREN\", value: \"(\" }); i++; continue }\n if (ch === \")\") { tokens.push({ type: \"RPAREN\", value: \")\" }); i++; continue }\n if (ch === \",\") { tokens.push({ type: \"COMMA\", value: \",\" }); i++; continue }\n if (ch === \":\") { tokens.push({ type: \"COLON\", value: \":\" }); i++; continue }\n\n // bracket forms: [], [N], [-N], [\"str\"]\n if (ch === \"[\") {\n const rest = expr.slice(i)\n // [\"str\"]\n const bkStr = rest.match(/^\\[\"((?:[^\"\\\\]|\\\\.)*)\"\\]/)\n if (bkStr) {\n const unescaped = bkStr[1].replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\").replace(/\\\\n/g, \"\\n\").replace(/\\\\t/g, \"\\t\")\n tokens.push({ type: \"BRACKET_KEY\", value: unescaped })\n i += bkStr[0].length; continue\n }\n // []\n const bkEmpty = rest.match(/^\\[\\]/)\n if (bkEmpty) {\n tokens.push({ type: \"EMPTY_ITER\", value: \"[]\" })\n i += 2; continue\n }\n // [-N] or [N]\n const bkIdx = rest.match(/^\\[-?(\\d+)\\]/)\n if (bkIdx) {\n const raw = rest.match(/^\\[(-?\\d+)\\]/)!\n tokens.push({ type: \"INDEX\", value: parseInt(raw[1], 10) })\n i += raw[0].length; continue\n }\n // standalone [ (for parser completeness — treated as error later)\n tokens.push({ type: \"LBRACKET\", value: \"[\" }); i++; continue\n }\n\n // two-char operators\n if (i + 1 < expr.length) {\n const two = expr.slice(i, i + 2)\n if (two === \"==\" || two === \"!=\" || two === \">=\" || two === \"<=\") {\n tokens.push({ type: \"OP\", value: two }); i += 2; continue\n }\n }\n if (ch === \">\" || ch === \"<\") {\n tokens.push({ type: \"OP\", value: ch }); i++; continue\n }\n\n // string literal\n if (ch === '\"') {\n let s = \"\"\n i++ // skip opening \"\n while (i < expr.length && expr[i] !== '\"') {\n if (expr[i] === \"\\\\\") {\n i++\n const esc = expr[i]\n if (esc === '\"') s += '\"'\n else if (esc === \"\\\\\") s += \"\\\\\"\n else if (esc === \"n\") s += \"\\n\"\n else if (esc === \"t\") s += \"\\t\"\n else s += esc\n } else {\n s += expr[i]\n }\n i++\n }\n if (expr[i] !== '\"') throw new Error(\"Unterminated string literal\")\n i++ // skip closing \"\n tokens.push({ type: \"STRING\", value: s }); continue\n }\n\n // number\n if (/[0-9]/.test(ch) || (ch === \"-\" && /[0-9]/.test(expr[i + 1] ?? \"\"))) {\n const m = expr.slice(i).match(/^-?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?/)\n if (m) {\n const n = Number(m[0])\n if (!Number.isFinite(n)) throw new Error(`Invalid number: ${m[0]}`)\n tokens.push({ type: \"NUMBER\", value: n })\n i += m[0].length; continue\n }\n }\n\n // identifier / keyword\n const idm = expr.slice(i).match(/^[a-zA-Z_$][a-zA-Z0-9_$]*/)\n if (idm) {\n tokens.push({ type: \"IDENT\", value: idm[0] })\n i += idm[0].length; continue\n }\n\n throw new Error(`Unexpected character '${ch}' at position ${i}`)\n }\n\n return tokens\n}\n\n// --- AST Node Types ---\n\ntype AstNode =\n | { k: \"identity\" }\n | { k: \"dot\"; field: string }\n | { k: \"bracket\"; key: string }\n | { k: \"iterate\" }\n | { k: \"index\"; index: number }\n | { k: \"pipe\"; left: AstNode; right: AstNode }\n | { k: \"select\"; cond: AstNode }\n | { k: \"object\"; fields: Array<{ key: string; valueExpr: AstNode | null }> }\n | { k: \"compare\"; op: string; left: AstNode; right: AstNode }\n | { k: \"bool\"; op: \"and\" | \"or\"; left: AstNode; right: AstNode }\n | { k: \"not\" }\n | { k: \"func\"; name: string; arg: string }\n | { k: \"literal\"; value: string | number }\n | { k: \"path\"; steps: AstNode[] } // chained dot/bracket/iterate/index\n\n// --- Parser ---\n\nclass Parser {\n private pos = 0\n constructor(private tokens: Token[]) {}\n\n private peek(): Token | undefined { return this.tokens[this.pos] }\n private eat(): Token {\n const t = this.tokens[this.pos++]\n if (!t) throw new Error(\"Unexpected end of expression\")\n return t\n }\n private expect(type: TokType): Token {\n const t = this.eat()\n if (t.type !== type) throw new Error(`Expected ${type}, got ${t.type} ('${t.value}')`)\n return t\n }\n private at(type: TokType): boolean { return this.peek()?.type === type }\n private atIdent(v: string): boolean { return this.peek()?.type === \"IDENT\" && this.peek()?.value === v }\n private done(): boolean { return this.pos >= this.tokens.length }\n\n parse(): AstNode {\n const node = this.parsePipe()\n if (!this.done()) throw new Error(`Unexpected token '${this.peek()!.value}' at position ${this.pos}`)\n return node\n }\n\n private parsePipe(): AstNode {\n let left = this.parseBoolExpr()\n while (this.at(\"PIPE\")) {\n this.eat() // consume |\n const right = this.parseBoolExpr()\n left = { k: \"pipe\", left, right }\n }\n return left\n }\n\n private parseBoolExpr(): AstNode {\n let left = this.parseCompare()\n while (this.atIdent(\"and\") || this.atIdent(\"or\")) {\n const op = this.eat().value as \"and\" | \"or\"\n const right = this.parseCompare()\n left = { k: \"bool\", op, left, right }\n }\n return left\n }\n\n private parseCompare(): AstNode {\n const left = this.parseAtom()\n if (this.at(\"OP\")) {\n const op = this.eat().value as string\n const right = this.parseAtom()\n return { k: \"compare\", op, left, right }\n }\n return left\n }\n\n // parseAtom handles all leaf-level filter constructs\n private parseAtom(): AstNode {\n // select(...)\n if (this.atIdent(\"select\")) {\n this.eat()\n this.expect(\"LPAREN\")\n // Allow full pipe expressions inside select (e.g., select(.name | contains(\"x\")))\n const cond = this.parsePipe()\n this.expect(\"RPAREN\")\n return { k: \"select\", cond }\n }\n // not (postfix — standalone in pipe context)\n if (this.atIdent(\"not\")) {\n this.eat()\n return { k: \"not\" }\n }\n // object construction\n if (this.at(\"LBRACE\")) {\n return this.parseObjectCtor()\n }\n // string function calls (contains, startswith, endswith, test) with arg\n if (this.at(\"IDENT\")) {\n const name = this.peek()!.value as string\n if ([\"contains\", \"startswith\", \"endswith\", \"test\"].includes(name)) {\n // look ahead for (\n if (this.tokens[this.pos + 1]?.type === \"LPAREN\") {\n this.eat() // name\n this.eat() // (\n const argTok = this.eat()\n if (argTok.type !== \"STRING\") throw new Error(`${name}() argument must be a string`)\n this.expect(\"RPAREN\")\n return { k: \"func\", name, arg: argTok.value as string }\n }\n }\n }\n // parenthesised expression\n if (this.at(\"LPAREN\")) {\n this.eat()\n const inner = this.parseBoolExpr()\n this.expect(\"RPAREN\")\n return inner\n }\n // literals and paths\n if (this.at(\"STRING\")) {\n return { k: \"literal\", value: this.eat().value as string }\n }\n if (this.at(\"NUMBER\")) {\n return { k: \"literal\", value: this.eat().value as number }\n }\n return this.parsePath()\n }\n\n private parsePath(): AstNode {\n if (!this.at(\"DOT\")) throw new Error(`Expected path starting with '.', got '${this.peek()?.value ?? \"EOF\"}'`)\n this.eat() // consume .\n\n // bare \".\" — identity\n const steps: AstNode[] = []\n\n // after dot, there may be an identifier or a bracket form\n if (this.at(\"IDENT\") && ![\"select\",\"not\",\"contains\",\"startswith\",\"endswith\",\"test\",\"and\",\"or\",\"null\",\"true\",\"false\"].includes(this.peek()!.value as string)) {\n steps.push({ k: \"dot\", field: this.eat().value as string })\n } else if (this.at(\"BRACKET_KEY\")) {\n steps.push({ k: \"bracket\", key: this.eat().value as string })\n } else if (this.at(\"EMPTY_ITER\")) {\n this.eat()\n steps.push({ k: \"iterate\" })\n } else if (this.at(\"INDEX\")) {\n steps.push({ k: \"index\", index: this.eat().value as number })\n } else {\n // just \".\"\n if (steps.length === 0) return { k: \"identity\" }\n }\n\n // chain more accesses: .foo.bar, .foo[0], .foo[]\n while (true) {\n if (this.at(\"DOT\")) {\n this.eat()\n if (this.at(\"IDENT\") && ![\"select\",\"not\",\"contains\",\"startswith\",\"endswith\",\"test\",\"and\",\"or\"].includes(this.peek()!.value as string)) {\n steps.push({ k: \"dot\", field: this.eat().value as string })\n } else if (this.at(\"BRACKET_KEY\")) {\n steps.push({ k: \"bracket\", key: this.eat().value as string })\n } else if (this.at(\"EMPTY_ITER\")) {\n this.eat(); steps.push({ k: \"iterate\" })\n } else if (this.at(\"INDEX\")) {\n steps.push({ k: \"index\", index: this.eat().value as number })\n } else {\n // trailing dot — treat as identity at end (shouldn't normally happen)\n break\n }\n } else if (this.at(\"BRACKET_KEY\")) {\n steps.push({ k: \"bracket\", key: this.eat().value as string })\n } else if (this.at(\"EMPTY_ITER\")) {\n this.eat(); steps.push({ k: \"iterate\" })\n } else if (this.at(\"INDEX\")) {\n steps.push({ k: \"index\", index: this.eat().value as number })\n } else {\n break\n }\n }\n\n if (steps.length === 0) return { k: \"identity\" }\n if (steps.length === 1) return steps[0]\n return { k: \"path\", steps }\n }\n\n private parseObjectCtor(): AstNode {\n this.eat() // {\n const fields: Array<{ key: string; valueExpr: AstNode | null }> = []\n\n while (!this.at(\"RBRACE\") && !this.done()) {\n let key: string\n let valueExpr: AstNode | null = null\n\n if (this.at(\"IDENT\")) {\n key = this.eat().value as string\n if (this.at(\"COLON\")) {\n this.eat() // :\n valueExpr = this.parsePipe()\n }\n // else shorthand: {name} => {name: .name}\n } else if (this.at(\"STRING\")) {\n key = this.eat().value as string\n this.expect(\"COLON\")\n valueExpr = this.parsePipe()\n } else {\n throw new Error(`Expected field name in object constructor, got '${this.peek()?.value}'`)\n }\n\n fields.push({ key, valueExpr })\n if (this.at(\"COMMA\")) this.eat()\n }\n\n this.expect(\"RBRACE\")\n return { k: \"object\", fields }\n }\n}\n\n// --- Evaluator ---\n\n// Sentinel to represent \"this item was dropped by select\"\nconst DROPPED = Symbol(\"DROPPED\")\n// Sentinel to track that we're in iterate mode (stream of items)\ntype EvalValue = unknown | typeof DROPPED\n\nfunction isTruthy(v: unknown): boolean {\n if (v === null || v === undefined || v === false || v === 0 || v === \"\") return false\n return true\n}\n\n// --- Per-call evaluation context ---\n\ninterface EvalCtx {\n expandedArrays: WeakSet<object>\n objectSourcedArrays: WeakSet<object>\n regexCache: Map<string, RegExp>\n}\n\nfunction evalNode(node: AstNode, input: unknown, ctx: EvalCtx): EvalValue | EvalValue[] {\n switch (node.k) {\n case \"identity\":\n return input\n\n case \"dot\": {\n if (input === null || input === undefined) return null\n if (typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(`Cannot access field '.${node.field}' on ${Array.isArray(input) ? \"array\" : typeof input}`)\n }\n const obj = input as Record<string, unknown>\n if (!(node.field in obj)) {\n const available = Object.keys(obj).join(\", \")\n throw new Error(`Field '${node.field}' not found. Available fields: ${available || \"(none)\"}`)\n }\n return obj[node.field]\n }\n\n case \"bracket\": {\n if (input === null || input === undefined) return null\n if (typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(`Cannot bracket-access on ${Array.isArray(input) ? \"array\" : typeof input}`)\n }\n const obj = input as Record<string, unknown>\n if (!(node.key in obj)) {\n const available = Object.keys(obj).join(\", \")\n throw new Error(`Field '${node.key}' not found. Available fields: ${available || \"(none)\"}`)\n }\n return obj[node.key]\n }\n\n case \"index\": {\n if (!Array.isArray(input)) throw new Error(`Cannot index non-array with .[${node.index}]`)\n const idx = node.index < 0 ? input.length + node.index : node.index\n return idx >= 0 && idx < input.length ? input[idx] : null\n }\n\n case \"iterate\": {\n if (Array.isArray(input)) {\n return input // return as array — caller handles fan-out\n }\n if (typeof input === \"object\" && input !== null) {\n // treat object as single-item sequence per spec\n const arr = [input]\n ctx.objectSourcedArrays.add(arr)\n return arr\n }\n throw new Error(`Cannot iterate over ${typeof input}`)\n }\n\n case \"path\": {\n let cur: unknown = input\n for (let i = 0; i < node.steps.length; i++) {\n const step = node.steps[i]\n const res = evalNode(step, cur, ctx)\n // if a step returns an array (from iterate), fan out remaining steps\n if (step.k === \"iterate\" && Array.isArray(res)) {\n const wasObjSourced = ctx.objectSourcedArrays.has(res as object)\n // fan out remaining steps over each element\n const remaining = node.steps.slice(i + 1)\n if (remaining.length === 0) return res\n const fanned: unknown[] = []\n for (const item of res) {\n const subNode: AstNode = remaining.length === 1 ? remaining[0] : { k: \"path\", steps: remaining }\n const subRes = evalNode(subNode, item, ctx)\n if (Array.isArray(subRes)) fanned.push(...subRes)\n else if (subRes !== DROPPED) fanned.push(subRes)\n }\n return markExpanded(fanned, wasObjSourced, ctx)\n }\n cur = res\n }\n return cur\n }\n\n case \"pipe\": {\n // Evaluate left side; if it produces an array (from iterate), fan-out over right side\n const leftVal = evalNode(node.left, input, ctx)\n\n // Check if left side was an iterate that produced array expansion\n const leftIsExpanded = isExpandedArray(node.left, leftVal, ctx)\n\n if (leftIsExpanded && Array.isArray(leftVal)) {\n const wasObjectSourced = ctx.objectSourcedArrays.has(leftVal as object)\n const results: unknown[] = []\n for (const item of leftVal) {\n const r = evalNode(node.right, item, ctx)\n if (r === DROPPED) continue\n if (Array.isArray(r) && isExpandedArray(node.right, r, ctx)) {\n results.push(...r)\n } else if (r !== DROPPED) {\n results.push(r)\n }\n }\n // mark as expanded, preserving object-sourced flag\n return markExpanded(results, wasObjectSourced, ctx)\n }\n\n if (leftVal === DROPPED) return DROPPED\n\n // scalar left — apply right once\n return evalNode(node.right, leftVal, ctx)\n }\n\n case \"select\": {\n const condVal = evalNode(node.cond, input, ctx)\n // If condition is a pipe that produced an expanded array (e.g., select(.name | contains(\"x\"))),\n // the truthiness is based on the final scalar result (the pipe's output).\n // An expanded array here means the condition pipeline returned array results — use last item.\n if (Array.isArray(condVal) && ctx.expandedArrays.has(condVal)) {\n const last = condVal[condVal.length - 1]\n return isTruthy(last) ? input : DROPPED\n }\n return isTruthy(condVal as unknown) ? input : DROPPED\n }\n\n case \"not\": {\n return !isTruthy(input)\n }\n\n case \"object\": {\n const result: Record<string, unknown> = {}\n for (const { key, valueExpr } of node.fields) {\n let fieldVal: unknown\n if (valueExpr === null) {\n // shorthand: {name} => .name\n fieldVal = evalNode({ k: \"dot\", field: key }, input, ctx)\n } else {\n fieldVal = evalNode(valueExpr, input, ctx)\n }\n if (fieldVal === DROPPED) return DROPPED\n result[key] = fieldVal\n }\n return result\n }\n\n case \"compare\": {\n const lv = evalNode(node.left, input, ctx) as unknown\n const rv = evalNode(node.right, input, ctx) as unknown\n switch (node.op) {\n case \"==\": return lv === rv\n case \"!=\": return lv !== rv\n case \">\": return typeof lv === \"number\" && typeof rv === \"number\" ? lv > rv : false\n case \"<\": return typeof lv === \"number\" && typeof rv === \"number\" ? lv < rv : false\n case \">=\": return typeof lv === \"number\" && typeof rv === \"number\" ? lv >= rv : false\n case \"<=\": return typeof lv === \"number\" && typeof rv === \"number\" ? lv <= rv : false\n default: return false\n }\n }\n\n case \"bool\": {\n const lv = evalNode(node.left, input, ctx)\n if (node.op === \"and\") {\n if (!isTruthy(lv as unknown)) return false\n return isTruthy(evalNode(node.right, input, ctx) as unknown)\n } else {\n if (isTruthy(lv as unknown)) return true\n return isTruthy(evalNode(node.right, input, ctx) as unknown)\n }\n }\n\n case \"func\": {\n if (typeof input !== \"string\") throw new Error(`${node.name}() requires a string input`)\n switch (node.name) {\n case \"contains\": return input.includes(node.arg)\n case \"startswith\": return input.startsWith(node.arg)\n case \"endswith\": return input.endsWith(node.arg)\n case \"test\": {\n let re = ctx.regexCache.get(node.arg)\n if (!re) {\n if (/(\\([^)]*[+*][^)]*\\))[+*]/.test(node.arg)) {\n throw new Error(\"Regex pattern too complex — avoid nested quantifiers\")\n }\n re = new RegExp(node.arg)\n ctx.regexCache.set(node.arg, re)\n }\n return re.test(input.slice(0, 100000))\n }\n default: throw new Error(`Unknown function: ${node.name}`)\n }\n }\n\n case \"literal\":\n return node.value\n\n default: {\n const _exhaustive: never = node\n throw new Error(`Unknown AST node`)\n }\n }\n}\n\n// --- Expanded array tracking ---\n// expandedArrays: arrays produced by iterate fan-out (pipe needs to fan-out over them)\n// objectSourcedArrays: expanded arrays whose origin was object iteration (unwrap at output)\n\nfunction markExpanded(arr: unknown[], objectSourced: boolean, ctx: EvalCtx): unknown[] {\n ctx.expandedArrays.add(arr)\n if (objectSourced) ctx.objectSourcedArrays.add(arr)\n return arr\n}\n\nfunction isExpandedArray(node: AstNode, val: unknown, ctx: EvalCtx): boolean {\n if (!Array.isArray(val)) return false\n // If left side is an iterate node directly, it's always expanded\n if (node.k === \"iterate\") return true\n // If left side is a path ending in iterate, check the last step\n if (node.k === \"path\") {\n const last = node.steps[node.steps.length - 1]\n if (last?.k === \"iterate\") return true\n }\n // If left side is a pipe that produced an expanded array\n if (node.k === \"pipe\") return ctx.expandedArrays.has(val as object)\n // Check WeakSet\n return ctx.expandedArrays.has(val as object)\n}\n\n// --- Public API ---\n\nexport function jsonResultToList(value: unknown): string[] {\n if (Array.isArray(value)) {\n return value.map((v) => typeof v === \"string\" ? v : JSON.stringify(v))\n }\n if (value !== null && value !== undefined) {\n return [typeof value === \"string\" ? value : JSON.stringify(value)]\n }\n return []\n}\n\nexport function evaluateJsonExpression(input: unknown, expression: string): JsonEvalResult {\n try {\n const tokens = tokenize(expression)\n const ast = new Parser(tokens).parse()\n const ctx: EvalCtx = {\n expandedArrays: new WeakSet(),\n objectSourcedArrays: new WeakSet(),\n regexCache: new Map(),\n }\n const raw = evalNode(ast, input, ctx)\n\n // If result is an expanded array (from iterate fan-out):\n if (Array.isArray(raw) && isExpandedArray(ast, raw, ctx)) {\n // Object-sourced: spec says treat as single-element sequence — unwrap (0 items → null, 1 → item)\n // Array-sourced: always return as array (jq model)\n const isObjSourced = ctx.objectSourcedArrays.has(raw as object)\n if (isObjSourced) {\n if (raw.length === 0) return { ok: true, value: null }\n if (raw.length === 1) return { ok: true, value: raw[0] }\n }\n if (raw.length === 0) return { ok: true, value: [] }\n return { ok: true, value: raw }\n }\n // Non-expanded: return as-is\n return { ok: true, value: raw === DROPPED ? [] : raw }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { ok: false, error: msg }\n }\n}\n","/**\n * Node reference pattern and resolution for {Node Label} template syntax.\n * Shared between frontend and backend.\n */\n\n/** Matches {Node Label} references in text. */\nexport const NODE_REF_PATTERN = /\\{([^}]+)\\}/g\n\n/** Reserved template variable names that should NOT be resolved as node refs */\nexport const RESERVED_TEMPLATE_VARS = new Set([\n \"name\",\n \"description\",\n \"userPrompt\",\n \"assetDescriptions\",\n \"outputCount\",\n])\n\n/**\n * Split a `{...}` token body into its node name and optional fallback. Splits on the FIRST `||`\n * (a fallback may itself contain `||`); both sides are trimmed. `fallback` is null when there is\n * no `||`, preserving the legacy \"leave the literal token\" behavior.\n * \"person || man\" -> { name: \"person\", fallback: \"man\" }\n * \"person || \" -> { name: \"person\", fallback: \"\" } (resolves to empty when absent)\n * \"person\" -> { name: \"person\", fallback: null } (literal {person} when absent)\n */\nexport function parseNodeRef(raw: string): { name: string; fallback: string | null } {\n const i = raw.indexOf(\"||\")\n if (i === -1) return { name: raw.trim(), fallback: null }\n return { name: raw.slice(0, i).trim(), fallback: raw.slice(i + 2).trim() }\n}\n\n/**\n * Canonical form of a node-name variable: trimmed + lowercased. Node-name\n * variables are CASE-INSENSITIVE with lowercase as canonical, so nodes labeled\n * `TEXt`, `TEXT`, `text` all feed the one `{text}` variable and `{TEXT}` /\n * `{Text}` / `{text}` in a prompt all resolve to it.\n *\n * Reserved template vars (RESERVED_TEMPLATE_VARS, e.g. `userPrompt`) are matched\n * case-sensitively on the ORIGINAL token BEFORE canonicalization, so `{userPrompt}`\n * stays a reserved token rather than becoming a `userprompt` node ref.\n */\nexport function canonicalVarName(label: string): string {\n return label.trim().toLowerCase()\n}\n\n/**\n * The distinct `{label}` names referenced across the given texts. Mirrors the\n * canvas-side `referencedRefs`: strips the `|| fallback`, and ignores empty\n * tokens, image-ref tokens (`{image:N}`), and RESERVED_TEMPLATE_VARS. Used to\n * SUPPRESS auto-injection of a connected node the author already placed\n * explicitly via `{label}` (so it isn't injected twice). `matchAll` over the\n * global pattern does not mutate its lastIndex, so sharing the constant is safe.\n */\nexport function extractReferencedLabels(\n ...texts: ReadonlyArray<string | undefined | null>\n): Set<string> {\n const refs = new Set<string>()\n for (const text of texts) {\n if (typeof text !== \"string\" || text.length === 0) continue\n for (const m of text.matchAll(NODE_REF_PATTERN)) {\n const { name } = parseNodeRef(m[1] ?? \"\")\n if (name === \"\" || name.startsWith(\"image:\") || RESERVED_TEMPLATE_VARS.has(name)) continue\n refs.add(canonicalVarName(name)) // case-insensitive: {Foo} suppresses a `foo` node\n }\n }\n return refs\n}\n\n/** Handle → combine-order category for same-label `{label}` merging. Lower wins\n * first: prompt (0) → elements (1) → look family (2). Other handles are -1\n * (not combinable — they keep the per-engine last-wins/suffix behavior). */\nexport const REF_HANDLE_CATEGORY: Readonly<Record<string, number>> = {\n prompt: 0,\n elements: 1,\n look: 2,\n cinematography: 2,\n style: 2,\n}\n\n/** Combine-order category for a direct-parent edge's `targetHandle`; -1 when the\n * handle isn't one of the combinable prompt/elements/look handles. */\nexport function refHandleCategory(targetHandle: string | null | undefined): number {\n if (targetHandle != null && Object.prototype.hasOwnProperty.call(REF_HANDLE_CATEGORY, targetHandle)) {\n return REF_HANDLE_CATEGORY[targetHandle]\n }\n return -1\n}\n\n/**\n * Reference-handle id → resolved-input key. The SINGLE SOURCE OF TRUTH for which\n * `targetHandle` ids carry image / video / audio reference inputs. Shared by the\n * backend input-resolver (routes the wired URL into the matching\n * `referenceImageUrls` / `referenceVideoUrls` / `referenceAudioUrls` slot) AND\n * the positional `{image:N}` / `{video:N}` / `{audio:N}` body-token COUNTS in the\n * FE preview (`video-prompt-assembly.ts`), FE run (`execute-node.ts`), and BE\n * payload-builder.\n *\n * Two handle families map to the same keys:\n * - Legacy / i2v single-name ids (`references` / `reference-videos` /\n * `reference-audio`) — kept for un-migrated workflows.\n * - Canonical typed-handle ids the modern Generate Video node exposes\n * (`imageReferences` / `videoReferences` / `audioReferences`) — share the\n * resolved-input keys with the legacy ids so consumer code never forks.\n */\nexport const REFERENCE_HANDLE_MAP: Record<string, \"referenceImageUrls\" | \"referenceVideoUrls\" | \"referenceAudioUrls\"> = {\n // Legacy / i2v single-name handle ids (kept for un-migrated workflows)\n \"references\": \"referenceImageUrls\",\n \"reference-videos\": \"referenceVideoUrls\",\n \"reference-audio\": \"referenceAudioUrls\",\n // New canonical typed-handle ids (Generate Video) — share the resolved-input\n // keys with the legacy ids so payload-builder code doesn't fork.\n \"imageReferences\": \"referenceImageUrls\",\n \"videoReferences\": \"referenceVideoUrls\",\n \"audioReferences\": \"referenceAudioUrls\",\n}\n\n/** The three reference modalities a reference handle can carry. */\nexport type ReferenceModality = \"image\" | \"video\" | \"audio\"\n\n/**\n * The reference MODALITY a `targetHandle` carries, or null when the handle is\n * not a reference handle. Resolves BOTH the legacy single-name ids and the\n * canonical Generate Video ids (via REFERENCE_HANDLE_MAP), so positional\n * `{image:N}` / `{video:N}` / `{audio:N}` token counts cover every handle alias\n * — without this, the generate-video `imageReferences` handle was silently\n * uncounted and `{image:N}` tokens dropped to bare labels on the only creatable\n * video node.\n */\nexport function referenceModalityForHandle(targetHandle: string | null | undefined): ReferenceModality | null {\n if (targetHandle == null) return null\n const key = REFERENCE_HANDLE_MAP[targetHandle]\n return key === \"referenceImageUrls\" ? \"image\" : key === \"referenceVideoUrls\" ? \"video\" : key === \"referenceAudioUrls\" ? \"audio\" : null\n}\n\n/**\n * Frame target handles (start / end keyframes). An image wired into one of these\n * is a KEYFRAME, not an `{image:N}` reference: the backend appends frames at the\n * TAIL of `reference_image_urls` (`resolveSeedance2Inputs`), never numbered. The\n * editor MUST therefore exclude them from `{image:N}` numbering so editor token N\n * equals the worker reference slot N.\n *\n * The SINGLE source of truth for \"is this a frame handle,\" shared by the\n * config-panel autocomplete (`video-configs.tsx`) AND the inline/modal builder\n * (`connected-references.ts`) — without ONE definition those two surfaces drifted\n * and the inline editor numbered the frame as `{image:1}` (the C1 bug). Frames\n * are deliberately NOT in `REFERENCE_HANDLE_MAP`: they carry no reference\n * modality, so `referenceModalityForHandle` already returns `null` for them on\n * the count side — this set is the exclusion lever for the EDITOR-numbering side.\n */\nexport const FRAME_TARGET_HANDLES: ReadonlySet<string> = new Set([\"startFrame\", \"endFrame\"])\n\n/**\n * Minimal structural edge shape {@link countRefModalityEdges} reads — only the\n * two fields the count needs. Both the FE `WorkflowEdge` (xyflow `Edge`, whose\n * `target` is a non-null string) and the BE `SimpleEdge` satisfy it.\n */\nexport interface RefModalityEdge {\n target?: string | null\n targetHandle?: string | null\n}\n\n/**\n * Count the reference-handle edges of a given reference MODALITY wired into a\n * node — the ONE positional `{image:N}` / `{video:N}` / `{audio:N}` counter\n * shared by the FE preview (`video-prompt-assembly.ts`), the FE run\n * (`execute-node.ts`), and the BE orchestrator (`payload-builder.ts`). Counting\n * via `referenceModalityForHandle` (not a single handle string) covers BOTH the\n * legacy single-name ids (`references` / `reference-videos` / `reference-audio`)\n * AND the canonical Generate Video ids (`imageReferences` / `videoReferences` /\n * `audioReferences`), so editor token N maps 1:1 to the worker\n * `referenceImageUrls` / `referenceVideoUrls` / `referenceAudioUrls` slot N on\n * every handle alias. This is the EDGE count (not the resolved/list-expanded URL\n * count) so all three paths stay byte-identical; the edge-vs-resolved divergence\n * for a reference edge that fans out to >1 URL (a List producer) is a shared,\n * documented v1 limitation.\n */\nexport function countRefModalityEdges(\n edges: ReadonlyArray<RefModalityEdge>,\n nodeId: string,\n modality: ReferenceModality,\n): number {\n let n = 0\n for (const e of edges) {\n if (e.target === nodeId && referenceModalityForHandle(e.targetHandle) === modality) n += 1\n }\n return n\n}\n\n/** A candidate contribution to the `{label}` map: the node's label, its resolved\n * output, and its direct-parent handle category (-1 = not combinable / deeper). */\nexport interface RefCandidate {\n label: string\n output: string\n category: number\n}\n\n/**\n * Same-label COMBINE: when ≥2 direct-parent candidates (category ≥ 0) share a\n * label, `{label}` resolves to their values joined by \", \" ordered prompt →\n * elements → look, and within a category by candidate (edge) order. Returns a\n * Map of ONLY the combined labels; the caller fills the rest with its own\n * (FE suffix / BE last-wins) logic, skipping any label present here. Shared so\n * the frontend executor and backend orchestrator never drift.\n */\nexport function combineSameLabelRefs(candidates: ReadonlyArray<RefCandidate>): Map<string, string> {\n const byLabel = new Map<string, RefCandidate[]>()\n for (const c of candidates) {\n if (c.category < 0) continue\n const key = canonicalVarName(c.label) // TEXt + TEXT + text collapse into one {text}\n const arr = byLabel.get(key)\n if (arr) arr.push(c)\n else byLabel.set(key, [c])\n }\n const combined = new Map<string, string>()\n for (const [label, group] of byLabel) {\n if (group.length < 2) continue\n const ordered = group\n .map((c, i) => ({ c, i }))\n .sort((a, b) => a.c.category - b.c.category || a.i - b.i)\n .map((x) => x.c.output)\n combined.set(label, ordered.join(\", \"))\n }\n return combined\n}\n\n/**\n * Resolve {Node Label} references in text by replacing them with actual node outputs.\n * Skips reserved template variables used by applyTemplate().\n * Iterates until stable to handle nested refs (e.g. {List} → {Animal1} → \"dog\").\n */\nexport function resolveNodeRefs(\n text: string,\n labelToOutput: ReadonlyMap<string, string>,\n): string {\n const MAX_PASSES = 10\n let result = text\n for (let i = 0; i < MAX_PASSES; i++) {\n const next = result.replace(NODE_REF_PATTERN, (match, raw: string) => {\n const { name, fallback } = parseNodeRef(raw)\n if (RESERVED_TEMPLATE_VARS.has(name)) return match\n // Node-name vars are case-insensitive: try the literal key first (keeps\n // original-cased maps like condition-variables working), then the\n // lowercase-canonical key (node-ref maps are canonical-keyed).\n const output = labelToOutput.get(name) ?? labelToOutput.get(canonicalVarName(name))\n if (output !== undefined) return output // connected, non-empty output → its value\n if (fallback !== null) return fallback // absent/empty + fallback → default (\"\" for {name || })\n return match // absent + no || → literal {name}\n })\n if (next === result) break\n result = next\n }\n return result\n}\n","/** Pure condition evaluator shared by filter-list and router (conditional mode). */\n\nimport { evaluateJsonPath } from \"./json-path.js\"\nimport { resolveNodeRefs } from \"./node-refs.js\"\n\nexport type FilterListOperator =\n | \">\" | \"<\" | \">=\" | \"<=\"\n | \"=\" | \"!=\"\n | \"contains\" | \"not_contains\"\n | \"starts_with\" | \"ends_with\" | \"regex\"\n | \"exists\" | \"not_exists\"\n\nexport interface FilterListCondition {\n id?: string\n field?: string\n operator: FilterListOperator\n value?: string\n valueType?: \"static\" | \"variable\"\n /** UI-only hint on the config panel — irrelevant to evaluation. */\n mode?: \"dropdown\" | \"custom\"\n}\n\n/** AND/OR condition bundle used by the router's conditional mode. When a\n * group matches, every routeId is added to activeRoutes. Multiple groups\n * union (deduped). */\nexport interface RouterConditionGroup {\n id?: string\n conditions?: FilterListCondition[]\n conditionLogic?: \"AND\" | \"OR\"\n routeIds?: string[]\n}\n\n/**\n * Options for `evaluateCondition` / `evaluateConditionGroup`.\n */\nexport interface EvaluateConditionOptions {\n /** When `false`, text operators (`contains`, `not_contains`, `starts_with`,\n * `ends_with`, `=`, `!=`) compare case-insensitively using case-folded\n * string equality.\n *\n * Note: `=` and `!=` lose their default numeric-coercion semantics under\n * `caseSensitive: false`. Under the default (case-sensitive), `1 == \"1.0\"`\n * via `valuesEqual`; under `caseSensitive: false`, comparison is pure\n * case-folded string equality, so `\"1\" !== \"1.0\"`.\n *\n * Default (when undefined): `true` (case-sensitive) — preserves existing\n * behavior for all callers.\n *\n * Non-text operators (`>`, `<`, `>=`, `<=`, `exists`, `not_exists`,\n * `regex`) are unaffected by this flag. */\n caseSensitive?: boolean\n /** Label→output map for `{Node Label}` refs inside condition values.\n * Populated from a filter-list / router node's `\"variables\"` target\n * handle. Resolved via `resolveNodeRefs` — unknown labels preserve\n * the original `{...}` text, so JSON-literal values stay intact. */\n variables?: ReadonlyMap<string, string>\n}\n\nexport function tryParseJson(item: unknown): unknown {\n if (typeof item !== \"string\") return item\n const trimmed = item.trim()\n if (!trimmed) return item\n const first = trimmed[0]\n if (first !== \"{\" && first !== \"[\" && first !== \"\\\"\" && !/^-?\\d/.test(trimmed) && trimmed !== \"true\" && trimmed !== \"false\" && trimmed !== \"null\") {\n return item\n }\n try { return JSON.parse(trimmed) } catch { return item }\n}\n\nconst HOUR_MS = 60 * 60 * 1000\nconst DAY_MS = 24 * HOUR_MS\nconst WEEK_MS = 7 * DAY_MS\n\n/** Resolve a relative-window token like `last_N_hours:3` to an ISO timestamp\n * N units before `Date.now()`. Returns undefined for malformed tokens. */\nexport function resolveRelativeWindowToken(key: string): string | undefined {\n const m = /^last_N_(hours|days|weeks):(-?\\d+)$/.exec(key)\n if (!m) return undefined\n const n = parseInt(m[2], 10)\n if (!Number.isFinite(n)) return undefined\n const unitMs = m[1] === \"hours\" ? HOUR_MS : m[1] === \"days\" ? DAY_MS : WEEK_MS\n return new Date(Date.now() - n * unitMs).toISOString()\n}\n\n/**\n * Substitute `{{...}}` template tokens — `{{now}}`, `{{trigger.<path>}}`,\n * and relative-window tokens (`{{last_N_hours:N}}` / days / weeks). Reused\n * by `resolveConditionValue` (filter-list / router) and `resolveSelectorRefs`\n * (selector node) so token semantics stay identical across the workflow-engine\n * ref-resolution surface.\n *\n * Pure: returns a new string. Strings with no `{{...}}` tokens pass through\n * unchanged.\n */\nexport function substituteTriggerTokens(\n raw: string,\n triggerData?: Record<string, unknown>,\n): string {\n if (!/\\{\\{/.test(raw)) return raw\n return raw.replace(/\\{\\{\\s*([^}]+?)\\s*\\}\\}/g, (_m, expr) => {\n const key = String(expr).trim()\n if (key === \"now\") return new Date().toISOString()\n if (key === \"trigger.last_triggered_at\") {\n const v = triggerData?.last_triggered_at\n return v == null ? \"\" : String(v)\n }\n if (key.startsWith(\"trigger.\")) {\n const path = key.slice(\"trigger.\".length)\n const v = triggerData?.[path]\n return v == null ? \"\" : String(v)\n }\n const relative = resolveRelativeWindowToken(key)\n if (relative !== undefined) return relative\n return \"\"\n })\n}\n\nexport function resolveConditionValue(\n raw: string,\n valueType: string | undefined,\n triggerData?: Record<string, unknown>,\n variables?: ReadonlyMap<string, string>,\n): string {\n let value = raw\n if (variables && variables.size > 0) {\n value = resolveNodeRefs(value, variables)\n }\n const hasTemplate = /\\{\\{/.test(value)\n if (valueType !== \"variable\" && !hasTemplate) return value\n return substituteTriggerTokens(value, triggerData)\n}\n\nfunction asComparableNumber(v: unknown): number {\n if (typeof v === \"number\") return v\n if (typeof v === \"boolean\") return v ? 1 : 0\n if (typeof v === \"string\") {\n const trimmed = v.trim()\n if (trimmed === \"\") return NaN\n const n = Number(trimmed)\n if (!isNaN(n)) return n\n const d = Date.parse(trimmed)\n if (!isNaN(d)) return d\n }\n return NaN\n}\n\n// Numeric-first ordering compare used by >, <, >=, <=. Falls back to\n// localeCompare when either side can't be parsed as a number.\nfunction compareValues(a: unknown, b: unknown): number {\n const na = asComparableNumber(a)\n const nb = asComparableNumber(b)\n if (!isNaN(na) && !isNaN(nb)) return na - nb\n return String(a ?? \"\").localeCompare(String(b ?? \"\"))\n}\n\n// Numeric-first equality used by = and !=. So \"432\" == 432, and 432 == \"432\".\n// Falls back to strict string equality (null/undefined coerced to \"\") so\n// alpha values still work.\nfunction valuesEqual(a: unknown, b: unknown): boolean {\n const na = asComparableNumber(a)\n const nb = asComparableNumber(b)\n if (!isNaN(na) && !isNaN(nb)) return na === nb\n return String(a ?? \"\") === String(b ?? \"\")\n}\n\nfunction applyCase(s: string, caseSensitive: boolean): string {\n return caseSensitive ? s : s.toLowerCase()\n}\n\nexport function evaluateCondition(\n parsedItem: unknown,\n rawItem: string,\n condition: FilterListCondition,\n triggerData?: Record<string, unknown>,\n options?: EvaluateConditionOptions,\n): boolean {\n const path = (condition.field ?? \"\").trim()\n let fieldValue: unknown\n if (path === \"\") {\n fieldValue = parsedItem ?? rawItem\n } else {\n const matches = evaluateJsonPath(parsedItem ?? rawItem, path)\n fieldValue = matches.length > 0 ? matches[0] : undefined\n }\n\n const targetStr = resolveConditionValue(condition.value ?? \"\", condition.valueType, triggerData, options?.variables)\n // Default to case-sensitive when the flag is not explicitly set. This\n // preserves existing behavior for Router conditional mode and legacy\n // Filter List nodes that don't carry the new `caseSensitive` field.\n const cs = options?.caseSensitive ?? true\n const fieldStr = String(fieldValue ?? \"\")\n\n switch (condition.operator) {\n case \"exists\":\n return fieldValue !== undefined && fieldValue !== null\n case \"not_exists\":\n return fieldValue === undefined || fieldValue === null\n case \"contains\":\n return applyCase(fieldStr, cs).includes(applyCase(targetStr, cs))\n case \"not_contains\":\n return !applyCase(fieldStr, cs).includes(applyCase(targetStr, cs))\n case \"starts_with\":\n return applyCase(fieldStr, cs).startsWith(applyCase(targetStr, cs))\n case \"ends_with\":\n return applyCase(fieldStr, cs).endsWith(applyCase(targetStr, cs))\n case \"regex\": {\n if (!targetStr) return false\n try {\n return new RegExp(targetStr).test(fieldStr)\n } catch {\n return false\n }\n }\n case \"=\":\n return cs\n ? valuesEqual(fieldValue, targetStr)\n : applyCase(fieldStr, false) === applyCase(targetStr, false)\n case \"!=\":\n return cs\n ? !valuesEqual(fieldValue, targetStr)\n : applyCase(fieldStr, false) !== applyCase(targetStr, false)\n case \">\":\n return compareValues(fieldValue, targetStr) > 0\n case \"<\":\n return compareValues(fieldValue, targetStr) < 0\n case \">=\":\n return compareValues(fieldValue, targetStr) >= 0\n case \"<=\":\n return compareValues(fieldValue, targetStr) <= 0\n default:\n return false\n }\n}\n\n/** Evaluate a single AND/OR-joined group against one item. Empty condition\n * list evaluates to `true` — typical when the user has just added a group\n * and hasn't configured any conditions yet. */\nexport function evaluateConditionGroup(\n parsedItem: unknown,\n rawItem: string,\n conditions: readonly FilterListCondition[],\n logic: \"AND\" | \"OR\",\n triggerData?: Record<string, unknown>,\n options?: EvaluateConditionOptions,\n): boolean {\n const effective = conditions.filter((c) => c && c.operator)\n if (effective.length === 0) return true\n const results = effective.map((c) => evaluateCondition(parsedItem, rawItem, c, triggerData, options))\n return logic === \"OR\" ? results.some(Boolean) : results.every(Boolean)\n}\n","import type { ScraperActorId } from \"./scraper-actors.js\"\n\n/**\n * Scalar fields exposed in the Extract Field dropdown when the direct\n * upstream is a web-scrape node. Nested / non-scalar fields (authorMeta,\n * musicMeta) are intentionally omitted — users access them via the\n * \"Custom path...\" option.\n *\n * content-crawler paths are pre-dotted (`pages.url`, `pages.markdown`)\n * because its root shape is `{ pages: [...] }`, not a top-level array.\n */\nexport const SCRAPER_OUTPUT_FIELDS: Record<ScraperActorId, readonly string[]> = {\n \"content-crawler\": [\"pages.url\", \"pages.markdown\"],\n \"google-search\": [\"title\", \"url\", \"description\"],\n \"instagram\": [\n \"url\", \"shortCode\", \"caption\", \"displayUrl\", \"videoUrl\",\n \"timestamp\", \"likesCount\", \"commentsCount\", \"ownerUsername\", \"type\",\n \"childPosts\",\n ],\n \"tiktok\": [\n \"id\", \"webVideoUrl\", \"videoUrl\", \"text\", \"createTime\",\n \"diggCount\", \"shareCount\", \"playCount\", \"commentCount\",\n ],\n \"rss\": [\"title\", \"url\", \"description\", \"pubDate\", \"guid\"],\n} as const\n","/**\n * Edge range utilities for resolving 1-based index expressions\n * and applying range/step slicing to output lists.\n *\n * Used by both frontend DAG executor and backend orchestrator\n * to support edge-level range, step, and item selection.\n */\n\nimport { evaluateCondition, substituteTriggerTokens, tryParseJson } from \"./filter-condition.js\"\nimport { resolveNodeRefs } from \"./node-refs.js\"\n\n/** Selector tab on an edge — \"range\" (from/to/step) or \"list\" (expression). */\nexport type SelectorMode = \"range\" | \"list\"\n\n/** Per-edge output mode controlling how upstream results reach downstream. */\nexport type OutputMode = \"last\" | \"each\" | \"all\" | \"item\"\n\n/** Edge-data fields consumed by selectListItems / isDefaultSelectorConfig. */\nexport type SelectorFields = {\n selectorMode?: SelectorMode\n listExpression?: string\n rangeFrom?: string\n rangeTo?: string\n rangeStep?: number\n}\n\n/** Full selector mode set — extends the edge-selector modes with new operators. */\nexport type FullSelectorMode =\n | \"item\"\n | \"range\"\n | \"list\"\n | \"random\"\n | \"modulo\"\n | \"predicate\"\n | \"named-key\"\n\n/** Operator set for predicate mode — reused from filter-list. */\nexport type SelectorPredicateOp =\n | \">\" | \"<\" | \">=\" | \"<=\"\n | \"=\" | \"!=\"\n | \"contains\" | \"not_contains\"\n | \"starts_with\" | \"ends_with\"\n | \"regex\"\n | \"exists\" | \"not_exists\"\n\n/** Config consumed by `runSelector` and `resolveSelectorRefs`. */\nexport type SelectorConfig = {\n mode: FullSelectorMode\n // item\n itemIndex?: string\n // range\n rangeFrom?: string\n rangeTo?: string\n rangeStep?: number\n // list\n listExpression?: string\n // random\n seed?: string\n randomCount?: number\n // modulo\n moduloDivisor?: string\n // predicate\n predicateField?: string\n predicateOp?: SelectorPredicateOp\n predicateValue?: string\n predicateMatch?: \"first\" | \"all\"\n predicateCaseSensitive?: boolean\n // named-key\n namedKeyField?: string\n namedKeyValue?: string\n}\n\n/** Result of a selector run. `picked ∪ rest = items`, `picked ∩ rest = ∅`. */\nexport type SelectorResult = { picked: string[]; rest: string[] }\n\n/**\n * Resolves a 1-based index expression to a 0-based array index.\n *\n * Supported expressions:\n * - \"1\", \"2\", ... — absolute 1-based index\n * - \"last\" — last element\n * - \"last-1\", \"last-2\", ... — relative from end\n *\n * Out-of-bounds values are clamped. Malformed input falls back to `defaultExpr`.\n */\nexport function resolveIndex(\n expr: string,\n listLength: number,\n defaultExpr: string = \"1\",\n): number {\n if (listLength <= 0) return 0\n\n const trimmed = expr.trim()\n let index: number\n\n if (trimmed === \"last\") {\n index = listLength - 1\n } else if (trimmed.startsWith(\"last-\")) {\n const offset = parseInt(trimmed.slice(5), 10)\n if (isNaN(offset) || offset < 0) return resolveIndex(defaultExpr === expr ? \"1\" : defaultExpr, listLength)\n index = listLength - 1 - offset\n } else {\n const n = parseInt(trimmed, 10)\n if (isNaN(n)) return resolveIndex(defaultExpr === expr ? \"1\" : defaultExpr, listLength)\n index = n - 1\n }\n\n return Math.max(0, Math.min(index, listLength - 1))\n}\n\n/**\n * Applies range and step slicing to a list of strings.\n *\n * `from` and `to` are 1-based index expressions (see `resolveIndex`).\n * `step` controls iteration direction and stride:\n * - positive step: forward iteration (from must be <= to)\n * - negative step: reverse iteration (from must be >= to)\n * - step 0 is treated as step 1\n *\n * Returns empty array if direction mismatches (e.g., from < to with negative step).\n */\nexport function applyRange(\n list: string[],\n from?: string,\n to?: string,\n step?: number,\n): string[] {\n if (list.length === 0) return []\n\n const fromIdx = resolveIndex(from ?? \"1\", list.length, \"1\")\n const toIdx = resolveIndex(to ?? \"last\", list.length, \"last\")\n const effectiveStep = step === 0 || step === undefined ? 1 : step\n\n if (effectiveStep > 0 && fromIdx > toIdx) return []\n if (effectiveStep < 0 && fromIdx < toIdx) return []\n\n const result: string[] = []\n if (effectiveStep > 0) {\n for (let i = fromIdx; i <= toIdx; i += effectiveStep) result.push(list[i])\n } else {\n for (let i = fromIdx; i >= toIdx; i += effectiveStep) result.push(list[i])\n }\n return result\n}\n\n/**\n * Migrates legacy `item:N` (0-based) outputMode to structured format.\n *\n * Legacy: `{ outputMode: \"item:0\" }` — 0-based index baked into mode string\n * New: `{ outputMode: \"item\", itemIndex: \"1\" }` — 1-based expression\n *\n * Returns the data unchanged if not a legacy item mode.\n */\nexport function migrateEdgeOutputMode(\n data: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!data) return data\n\n const mode = data.outputMode as string | undefined\n if (!mode || !mode.startsWith(\"item:\")) return data\n\n const idx = parseInt(mode.split(\":\")[1], 10)\n return {\n ...data,\n outputMode: \"item\",\n itemIndex: String(isNaN(idx) ? 1 : idx + 1),\n }\n}\n\n/**\n * Builds the edge range label shown as a pill on the edge.\n * Examples:\n * - \"2..last-1 +2\" — range with step 2\n * - \"last..1 -1\" — reversed\n * - \"3\" — item mode, index 3\n * - undefined — \"last\" mode has no label\n */\nexport function buildRangeLabel(\n mode: string,\n rangeFrom?: string,\n rangeTo?: string,\n rangeStep?: number,\n itemIndex?: string,\n selectorMode?: SelectorMode,\n listExpression?: string,\n): string | undefined {\n return buildItemLabel(mode, rangeFrom, rangeTo, rangeStep, itemIndex, selectorMode, listExpression)\n}\n\n/** Internal: builds the item-side label (range / list / item / each). Mode \"last\" returns undefined. */\nfunction buildItemLabel(\n mode: string,\n rangeFrom?: string,\n rangeTo?: string,\n rangeStep?: number,\n itemIndex?: string,\n selectorMode?: SelectorMode,\n listExpression?: string,\n): string | undefined {\n if (mode === \"last\") return undefined\n\n if ((mode === \"each\" || mode === \"all\") && selectorMode === \"list\") {\n const trimmed = (listExpression ?? \"\").trim()\n if (trimmed === \"\") return undefined\n return truncateLabel(trimmed, 18)\n }\n\n if (mode === \"item\") return itemIndex || undefined\n\n const from = rangeFrom ?? \"1\"\n const to = rangeTo ?? \"last\"\n const step = rangeStep ?? 1\n const isDefaultRange = from === \"1\" && to === \"last\"\n const isDefaultStep = step === 1\n if (isDefaultRange && isDefaultStep) return undefined\n\n let label = `${from}..${to}`\n if ((mode === \"each\" || mode === \"all\") && !isDefaultStep) {\n label += step > 0 ? ` +${step}` : ` ${step}`\n }\n return label\n}\n\nfunction truncateLabel(s: string, maxLen: number): string {\n if (s.length <= maxLen) return s\n return s.slice(0, maxLen) + \"…\"\n}\n\n/**\n * Validates a list expression without resolving indices.\n * Used for live UI validation in the List tab input.\n *\n * Returns { ok: true } for empty/whitespace input — matches the\n * \"empty = all items\" runtime semantics.\n */\nexport function parseListExpression(\n expr: string,\n): { ok: true } | { ok: false; error: string } {\n const result = parseListTerms(expr.trim())\n return result.ok ? { ok: true } : { ok: false, error: result.error }\n}\n\n/** Internal: validates a single index token (\"1\", \"last\", \"last-3\"). */\nfunction isValidIndexToken(token: string): boolean {\n if (token === \"last\") return true\n if (/^[1-9]\\d*$/.test(token)) return true\n const m = /^last-(\\d+)$/.exec(token)\n if (m) return !isNaN(parseInt(m[1], 10))\n return false\n}\n\n/**\n * Parses a list expression and returns 0-based indices into the list,\n * in user-specified order. Preserves duplicates.\n *\n * Supported syntax:\n * <expr> := <term> (\",\" <term>)*\n * <term> := <index> | <index> \"..\" <index> (\":\" <step>)?\n * <index> := <number> | \"last\" | \"last-\" <number>\n * <step> := integer (0 coerced to 1)\n *\n * Clamps out-of-bounds indices. Malformed input logs a warning and\n * returns [0..listLength-1] (matches applyRange leniency).\n */\nexport function resolveListExpression(expr: string, listLength: number): number[] {\n if (listLength <= 0) return []\n const result = parseListTerms(expr.trim())\n if (!result.ok) {\n console.warn(\"[edge-range] invalid list expression:\", expr, \"—\", result.error)\n return indexRange(0, listLength - 1, 1)\n }\n if (result.terms.length === 0) return indexRange(0, listLength - 1, 1)\n\n const out: number[] = []\n for (const term of result.terms) {\n if (term.kind === \"index\") {\n out.push(resolveIndex(term.token, listLength))\n } else {\n const from = resolveIndex(term.from, listLength)\n const to = resolveIndex(term.to, listLength)\n for (const idx of indexRange(from, to, term.step)) out.push(idx)\n }\n }\n return out\n}\n\n/** Internal: inclusive index range with step. Returns [] if direction mismatches. */\nfunction indexRange(from: number, to: number, step: number): number[] {\n const out: number[] = []\n if (step > 0) {\n if (from > to) return []\n for (let i = from; i <= to; i += step) out.push(i)\n } else {\n if (from < to) return []\n for (let i = from; i >= to; i += step) out.push(i)\n }\n return out\n}\n\n/**\n * Dispatches to either applyRange() or resolveListExpression() based on\n * edgeData.selectorMode. Returns a new string[] containing the selected\n * subset of items — or `items` unchanged when the edge has no filter.\n */\nexport function selectListItems(\n items: string[],\n edgeData: SelectorFields | undefined,\n): string[] {\n if (items.length === 0) return []\n if (isDefaultSelectorConfig(edgeData)) return items\n if (edgeData?.selectorMode === \"list\") {\n const indices = resolveListExpression(edgeData.listExpression ?? \"\", items.length)\n return indices.map((i) => items[i])\n }\n return applyRange(items, edgeData?.rangeFrom, edgeData?.rangeTo, edgeData?.rangeStep)\n}\n\n/**\n * Returns true when edge data carries no active filter — empty/whitespace list\n * expression in list mode, or defaults (1..last, step 1) in range mode.\n * Callers can skip filtering entirely when this returns true.\n */\nexport function isDefaultSelectorConfig(edgeData: SelectorFields | undefined): boolean {\n if (!edgeData) return true\n if (edgeData.selectorMode === \"list\") {\n return ((edgeData.listExpression ?? \"\").trim()) === \"\"\n }\n const { from, to, step } = canonicalRange(edgeData)\n return from === \"1\" && to === \"last\" && step === 1\n}\n\nexport function describeEdgeBehavior(\n edgeData:\n | {\n outputMode?: string\n selectorMode?: SelectorMode\n listExpression?: string\n rangeFrom?: string\n rangeTo?: string\n rangeStep?: number\n itemIndex?: string\n }\n | undefined,\n): string {\n const mode = edgeData?.outputMode\n return buildBaseSentence(edgeData, mode)\n}\n\nfunction buildBaseSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n mode: string | undefined,\n): string {\n if (mode === \"last\") return \"Passes the selected result.\"\n if (mode === \"item\") return buildItemSentence(edgeData)\n if (mode === \"each\") return buildEachSentence(edgeData)\n if (mode === \"all\") return buildAllSentence(edgeData)\n return \"Passes all items at once.\"\n}\n\nfunction buildItemSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): string {\n const canonical = canonicalItemIndex(edgeData?.itemIndex)\n return `Passes only ${itemModeForm(canonical)}.`\n}\n\nfunction buildEachSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): string {\n if (isDefaultSelectorConfig(edgeData)) return \"Runs the next node one by one, per item.\"\n if (edgeData?.selectorMode === \"list\") {\n const result = parseListTerms((edgeData.listExpression ?? \"\").trim())\n if (!result.ok) return \"Runs the next node one by one, per item.\"\n }\n const phrase = buildSelectionPhrase(edgeData)\n if (phrase.kind === \"empty-result\") {\n return \"Nothing selected — the next node won't run.\"\n }\n if (phrase.kind === \"single-index\") {\n return `Runs the next node only on ${phrase.itemModeForm}.`\n }\n return `Runs the next node once for ${phrase.text}.`\n}\n\nfunction buildAllSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): string {\n if (isDefaultSelectorConfig(edgeData)) return \"Passes all items at once.\"\n if (edgeData?.selectorMode === \"list\") {\n const result = parseListTerms((edgeData.listExpression ?? \"\").trim())\n if (!result.ok) return \"Passes all items at once.\"\n }\n const phrase = buildSelectionPhrase(edgeData)\n if (phrase.kind === \"empty-result\") {\n return \"Nothing selected — the next node will get an empty bundle.\"\n }\n if (phrase.kind === \"single-index\") {\n return `Passes only ${phrase.itemModeForm}.`\n }\n return `Passes ${phrase.text} at once.`\n}\n\ntype CanonicalRange = { from: string; to: string; step: number }\n\nfunction canonicalItemIndex(raw: string | undefined): string {\n const trimmed = (raw ?? \"\").trim()\n if (trimmed === \"\") return \"1\"\n if (!isValidIndexToken(trimmed)) return \"1\"\n return trimmed\n}\n\nfunction canonicalRange(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): CanonicalRange {\n const from = ((edgeData?.rangeFrom ?? \"\").trim() || \"1\")\n const to = ((edgeData?.rangeTo ?? \"\").trim() || \"last\")\n const rawStep = edgeData?.rangeStep\n const step = rawStep === undefined || rawStep === 0 ? 1 : rawStep\n return { from, to, step }\n}\n\n\nfunction itemModeForm(canonical: string): string {\n if (canonical === \"1\") return \"the first item\"\n if (/^\\d+$/.test(canonical)) return `item ${canonical}`\n if (canonical === \"last\" || canonical === \"last-0\") return \"the last item\"\n const m = /^last-(\\d+)$/.exec(canonical)\n if (m) {\n const n = parseInt(m[1], 10)\n if (n === 1) return \"the second-to-last item\"\n if (n === 2) return \"the third-to-last item\"\n if (n === 3) return \"the fourth-to-last item\"\n return `the ${ordinal(n + 1)}-from-last item`\n }\n return \"the first item\"\n}\n\nfunction compactForm(canonical: string): string {\n if (/^\\d+$/.test(canonical)) return canonical\n if (canonical === \"last\" || canonical === \"last-0\") return \"the last one\"\n const m = /^last-(\\d+)$/.exec(canonical)\n if (m) {\n const n = parseInt(m[1], 10)\n if (n === 1) return \"the second-to-last\"\n if (n === 2) return \"the third-to-last\"\n if (n === 3) return \"the fourth-to-last\"\n return `the ${ordinal(n + 1)}-from-last`\n }\n return canonical\n}\n\nfunction ordinal(n: number): string {\n const absN = Math.abs(n)\n const lastTwo = absN % 100\n if (lastTwo >= 11 && lastTwo <= 13) return `${n}th`\n switch (absN % 10) {\n case 1: return `${n}st`\n case 2: return `${n}nd`\n case 3: return `${n}rd`\n default: return `${n}th`\n }\n}\n\ntype SelectionPhrase =\n | { kind: \"items\"; text: string }\n | { kind: \"single-index\"; itemModeForm: string }\n | { kind: \"empty-result\" }\n\nfunction buildSelectionPhrase(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): SelectionPhrase {\n if (edgeData?.selectorMode === \"list\") {\n return buildListSelectionPhrase((edgeData.listExpression ?? \"\").trim())\n }\n return buildRangeSelectionPhrase(canonicalRange(edgeData))\n}\n\nfunction indexKind(token: string): \"concrete\" | \"relative\" | \"invalid\" {\n if (/^[1-9]\\d*$/.test(token)) return \"concrete\"\n if (token === \"last\" || /^last-\\d+$/.test(token)) return \"relative\"\n return \"invalid\"\n}\n\nfunction relativeOffset(token: string): number {\n if (token === \"last\") return 0\n const m = /^last-(\\d+)$/.exec(token)\n return m ? parseInt(m[1], 10) : 0\n}\n\nfunction compareTokens(a: string, b: string): -1 | 0 | 1 | \"indeterminate\" {\n const ka = indexKind(a)\n const kb = indexKind(b)\n if (ka !== kb) return \"indeterminate\"\n if (ka === \"concrete\") {\n const na = parseInt(a, 10)\n const nb = parseInt(b, 10)\n return na < nb ? -1 : na > nb ? 1 : 0\n }\n if (ka === \"relative\") {\n const oa = relativeOffset(a)\n const ob = relativeOffset(b)\n return oa < ob ? 1 : oa > ob ? -1 : 0\n }\n return \"indeterminate\"\n}\n\nfunction buildRangeSelectionPhrase(r: CanonicalRange): SelectionPhrase {\n const { from, to, step } = r\n\n const cmp = compareTokens(from, to)\n if (cmp !== \"indeterminate\") {\n if (step > 0 && cmp === 1) return { kind: \"empty-result\" }\n if (step < 0 && cmp === -1) return { kind: \"empty-result\" }\n }\n\n if (cmp === 0) {\n return { kind: \"single-index\", itemModeForm: itemModeForm(from) }\n }\n\n const absStep = Math.abs(step)\n if (step === -1 && from === \"last\" && to === \"1\") {\n return { kind: \"items\", text: \"all items in reverse order\" }\n }\n\n let text = `items ${compactForm(from)} through ${compactForm(to)}`\n if (absStep === 1 && step < 0) {\n text += \" in reverse order\"\n } else if (absStep > 1 && step > 0) {\n text += ` (every ${ordinal(absStep)} item)`\n } else if (absStep > 1 && step < 0) {\n text += ` (every ${ordinal(absStep)} item, in reverse)`\n }\n return { kind: \"items\", text }\n}\n\ntype ListTerm =\n | { kind: \"index\"; token: string }\n | { kind: \"range\"; from: string; to: string; step: number }\n\ntype ParseResult =\n | { ok: true; terms: ListTerm[] }\n | { ok: false; error: string }\n\n/**\n * Core list-expression parser. Returns structured terms on success or a\n * specific error message on failure. Empty input → zero terms (not an error).\n * Error messages are surfaced unchanged in the edge-config tooltip, so they\n * must stay stable:\n * - \"Empty item between commas\"\n * - \"Invalid index: <token>\"\n * - \"Range missing endpoint: <term>\"\n * - \"Step must be an integer\"\n */\nfunction parseListTerms(expr: string): ParseResult {\n if (expr === \"\") return { ok: true, terms: [] }\n const terms: ListTerm[] = []\n const raw = expr.split(\",\")\n for (const rawTerm of raw) {\n const term = rawTerm.trim()\n if (term === \"\") return { ok: false, error: \"Empty item between commas\" }\n const rangeIdx = term.indexOf(\"..\")\n if (rangeIdx === -1) {\n if (!isValidIndexToken(term)) return { ok: false, error: `Invalid index: ${term}` }\n terms.push({ kind: \"index\", token: term })\n continue\n }\n const left = term.slice(0, rangeIdx).trim()\n const rightWithStep = term.slice(rangeIdx + 2).trim()\n if (left === \"\" || rightWithStep === \"\") {\n return { ok: false, error: `Range missing endpoint: ${term}` }\n }\n const colonIdx = rightWithStep.indexOf(\":\")\n const right = colonIdx === -1 ? rightWithStep : rightWithStep.slice(0, colonIdx).trim()\n const stepStr = colonIdx === -1 ? null : rightWithStep.slice(colonIdx + 1).trim()\n if (right === \"\") return { ok: false, error: `Range missing endpoint: ${term}` }\n if (!isValidIndexToken(left)) return { ok: false, error: `Invalid index: ${left}` }\n if (!isValidIndexToken(right)) return { ok: false, error: `Invalid index: ${right}` }\n let step = 1\n if (stepStr !== null) {\n if (!/^-?\\d+$/.test(stepStr)) return { ok: false, error: \"Step must be an integer\" }\n const parsed = parseInt(stepStr, 10)\n step = parsed === 0 ? 1 : parsed\n }\n terms.push({ kind: \"range\", from: left, to: right, step })\n }\n return { ok: true, terms }\n}\n\nfunction buildListSelectionPhrase(expr: string): SelectionPhrase {\n const result = parseListTerms(expr)\n if (!result.ok) return { kind: \"empty-result\" }\n if (result.terms.length === 0) return { kind: \"items\", text: \"items\" } // unreachable via callers; default-config catches empty\n\n const normalized = result.terms.map<ListTerm>((t) => {\n if (t.kind === \"range\") {\n const cmp = compareTokens(t.from, t.to)\n if (cmp === 0) return { kind: \"index\", token: t.from }\n }\n return t\n })\n\n if (normalized.length === 1 && normalized[0].kind === \"index\") {\n return { kind: \"single-index\", itemModeForm: itemModeForm(normalized[0].token) }\n }\n\n const rendered = normalized.map((t) => {\n if (t.kind === \"index\") return compactForm(t.token)\n let text = `${compactForm(t.from)} through ${compactForm(t.to)}`\n const absStep = Math.abs(t.step)\n if (absStep === 1 && t.step < 0) {\n if (t.from === \"last\" && t.to === \"1\") return \"all items in reverse\"\n text += \" in reverse\"\n } else if (absStep > 1 && t.step > 0) {\n text += ` (every ${ordinal(absStep)})`\n } else if (absStep > 1 && t.step < 0) {\n text += ` (every ${ordinal(absStep)}, in reverse)`\n }\n return text\n })\n\n let joined: string\n if (rendered.length === 1) {\n joined = rendered[0]\n } else if (rendered.length === 2) {\n joined = `${rendered[0]} and ${rendered[1]}`\n } else {\n const head = rendered.slice(0, -1).join(\", \")\n joined = `${head}, and ${rendered[rendered.length - 1]}`\n }\n return { kind: \"items\", text: `items ${joined}` }\n}\n\n/**\n * Run the selector against `items`. Returns the picked subset plus the\n * complement (`rest`). For modes that pick by index, `rest` is computed by\n * index exclusion (not value) so duplicate items are handled correctly.\n */\nexport function runSelector(items: string[], config: SelectorConfig): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n\n switch (config.mode) {\n case \"item\": {\n const idx = resolveIndex(config.itemIndex ?? \"1\", items.length, \"1\")\n return splitByIndices(items, [idx])\n }\n case \"range\": {\n const indices = applyRangeIndices(items.length, config.rangeFrom, config.rangeTo, config.rangeStep)\n return splitByIndices(items, indices)\n }\n case \"list\": {\n const indices = resolveListExpression(config.listExpression ?? \"\", items.length)\n return splitByIndices(items, indices)\n }\n case \"random\":\n return selectRandom(items, config.randomCount ?? 1, config.seed)\n case \"modulo\":\n return selectByModulo(items, config.moduloDivisor)\n case \"predicate\":\n return selectByPredicate(items, config)\n case \"named-key\":\n return selectByNamedKey(items, config.namedKeyField, config.namedKeyValue)\n default:\n return { picked: [], rest: items.slice() }\n }\n}\n\n/**\n * Partition `items` into picked (indices ∈ pickedIndices, in their original\n * order in the source list) and rest (everything else). Deduplicates\n * `pickedIndices` so passing the same index twice doesn't double-count.\n */\nfunction splitByIndices(items: string[], pickedIndices: number[]): SelectorResult {\n const pickedSet = new Set(pickedIndices.filter((i) => i >= 0 && i < items.length))\n const picked: string[] = []\n const rest: string[] = []\n for (let i = 0; i < items.length; i++) {\n if (pickedSet.has(i)) picked.push(items[i])\n else rest.push(items[i])\n }\n return { picked, rest }\n}\n\n/**\n * Returns the indices that `applyRange` would pick. Extracted so `runSelector`\n * range mode can compute the exact picked-index set (`items.indexOf(value)`\n * would return the wrong duplicate when the list contains repeated values).\n */\nexport function applyRangeIndices(\n length: number,\n from?: string,\n to?: string,\n step?: number,\n): number[] {\n if (length === 0) return []\n const fromIdx = resolveIndex(from ?? \"1\", length, \"1\")\n const toIdx = resolveIndex(to ?? \"last\", length, \"last\")\n const effectiveStep = step === 0 || step === undefined ? 1 : step\n if (effectiveStep > 0 && fromIdx > toIdx) return []\n if (effectiveStep < 0 && fromIdx < toIdx) return []\n const result: number[] = []\n if (effectiveStep > 0) {\n for (let i = fromIdx; i <= toIdx; i += effectiveStep) result.push(i)\n } else {\n for (let i = fromIdx; i >= toIdx; i += effectiveStep) result.push(i)\n }\n return result\n}\n\n/** mulberry32 PRNG — deterministic given a seed (any 32-bit signed integer). */\nfunction mulberry32(seed: number): () => number {\n let a = seed | 0\n return () => {\n a = (a + 0x6D2B79F5) | 0\n let t = a\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** Hash a seed string to a 32-bit integer (FNV-1a variant). */\nfunction hashSeed(s: string): number {\n let h = 2166136261 | 0\n for (let i = 0; i < s.length; i++) {\n h ^= s.charCodeAt(i)\n h = Math.imul(h, 16777619)\n }\n return h\n}\n\n/**\n * Pick `count` items uniformly at random without replacement.\n * If `seed` is non-empty, the PRNG is seeded deterministically.\n * Otherwise `Math.random` is used (fresh randomness per call).\n */\nexport function selectRandom(items: string[], count: number, seed?: string): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n const k = Math.max(0, Math.min(count, items.length))\n const rand = seed && seed.length > 0 ? mulberry32(hashSeed(seed)) : Math.random\n // Partial Fisher-Yates: shuffle the first k positions, pick those indices.\n const indices = items.map((_, i) => i)\n for (let i = 0; i < k; i++) {\n const j = i + Math.floor(rand() * (indices.length - i))\n ;[indices[i], indices[j]] = [indices[j], indices[i]]\n }\n return splitByIndices(items, indices.slice(0, k))\n}\n\n/**\n * Pick a single item at `divisor % items.length`. Non-numeric `divisor`\n * falls back to index 0. Caller is responsible for resolving any\n * `{NodeLabel}` template refs in `divisor` BEFORE calling this — see\n * `resolveSelectorRefs`.\n */\nexport function selectByModulo(items: string[], divisor: string | undefined): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n const n = divisor ? Number.parseInt(divisor.trim(), 10) : NaN\n const safeN = Number.isFinite(n) ? n : 0\n const idx = ((safeN % items.length) + items.length) % items.length\n return splitByIndices(items, [idx])\n}\n\n/**\n * Pick items whose parsed JSON satisfies the predicate. `match: \"first\"`\n * (default) stops at the first hit; `\"all\"` collects every hit.\n *\n * Reuses the filter-list condition evaluator so operator semantics\n * (numeric coercion on `=`/`!=`, locale-aware ordering, case-sensitive\n * text ops) stay identical to the Filter List node.\n */\nexport function selectByPredicate(\n items: string[],\n config: SelectorConfig,\n): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n // Default operator to \"=\" so the UI's visual default (selector-config.tsx\n // shows `op={config.predicateOp ?? \"=\"}`) matches runtime; first-time\n // predicate use without explicitly setting an operator used to silently\n // return picked=[].\n // predicateField is intentionally allowed to be empty/undefined —\n // evaluateCondition treats an empty path as \"compare against the whole\n // item\" (filter-condition.ts:161), matching the UI placeholder hint\n // \"blank = whole item\" on the field input.\n const op = config.predicateOp ?? \"=\"\n // Pass caseSensitive explicitly. evaluateCondition defaults undefined to\n // `true` (case-sensitive) to preserve legacy callers, but the selector\n // UI checkbox shows unchecked by default — so undefined config must map\n // to case-INsensitive at runtime to match what the user sees.\n const opts = { caseSensitive: config.predicateCaseSensitive ?? false }\n const matchAll = config.predicateMatch === \"all\"\n const cond = {\n id: \"selector-predicate\",\n field: config.predicateField ?? \"\",\n operator: op,\n value: config.predicateValue ?? \"\",\n valueType: \"static\" as const,\n }\n const matchedIndices: number[] = []\n for (let i = 0; i < items.length; i++) {\n const parsed = tryParseJson(items[i])\n const hit = evaluateCondition(parsed, items[i], cond, undefined, opts)\n if (hit) {\n matchedIndices.push(i)\n if (!matchAll) break\n }\n }\n return splitByIndices(items, matchedIndices)\n}\n\n/**\n * Shortcut for `predicate(op=\"=\", match=\"first\")` — pick the first item\n * whose `field` strictly equals `value`. Implemented as a thin wrapper\n * so the UI can offer a 2-field form (\"look up by name\") instead of the\n * full 4-field predicate form.\n */\nexport function selectByNamedKey(\n items: string[],\n field: string | undefined,\n value: string | undefined,\n): SelectorResult {\n return selectByPredicate(items, {\n mode: \"predicate\",\n predicateField: field,\n predicateOp: \"=\",\n predicateValue: value,\n predicateMatch: \"first\",\n })\n}\n\n/**\n * Returns a new SelectorConfig with `{NodeLabel}` refs and `{{trigger.*}}` /\n * `{{now}}` / `{{last_N_*:N}}` template tokens resolved in the four\n * template-aware fields: moduloDivisor, predicateValue, namedKeyValue, seed.\n * All other fields are passed through unchanged. Callers must build\n * `variables` via `buildConditionVariables` (or equivalent) BEFORE calling.\n *\n * Other selector fields (itemIndex, range/list expressions, randomCount, etc.)\n * are treated as literals — they have their own selector-lib syntax and are\n * not resolved against the variable space.\n *\n * Token resolution matches `resolveConditionValue` exactly (both reuse\n * `substituteTriggerTokens`) so the selector's `{{trigger.foo}}` semantics\n * stay in lockstep with filter-list / router conditions.\n *\n * Pure: returns a new object; the input config is not mutated.\n */\nexport function resolveSelectorRefs(\n config: SelectorConfig,\n triggerData: Record<string, unknown> | undefined,\n variables: ReadonlyMap<string, string>,\n): SelectorConfig {\n const resolve = (v: string | undefined): string | undefined => {\n if (v == null) return v\n const refsResolved = resolveNodeRefs(v, variables)\n return substituteTriggerTokens(refsResolved, triggerData)\n }\n return {\n ...config,\n moduloDivisor: resolve(config.moduloDivisor),\n predicateValue: resolve(config.predicateValue),\n namedKeyValue: resolve(config.namedKeyValue),\n seed: resolve(config.seed),\n }\n}\n","/** AI generation node types that support repeat-N execution.\n * Excludes deterministic nodes, FFmpeg, social, render, and utility nodes. */\nexport const REPEATABLE_NODE_TYPES = new Set([\n \"generate-image\", \"edit-image\", \"image-to-image\",\n \"image-to-video\", \"video-to-video\", \"text-to-video\",\n \"text-to-speech\", \"generate-music\", \"text-to-audio\", \"text-to-dialogue\",\n \"ai-writer\", \"llm-chat\", \"generate-script\",\n \"suno-generate\", \"suno-cover\", \"suno-extend\", \"suno-lyrics\",\n \"lip-sync\", \"speech-to-video\",\n \"motion-transfer\", \"extend-video\",\n \"video-composer\", \"after-effects\", \"lottie-overlay\", \"3d-title\", \"motion-graphics\",\n \"voice-changer\", \"dubbing\", \"voice-remix\", \"voice-design\",\n \"component\",\n])\n\n/** Sentinel value used as list item for repeat-only execution (no list fan-out input).\n * executeNodeForList skips the overridePrompt/overrideMediaUrl when it sees this. */\nexport const REPEAT_PLACEHOLDER = \"__repeat__\"\n\n/** Sentinel prefix for per-iteration provider override.\n * An item like `__provider:nano-banana__` tells executeNodeForList to clone the\n * node with `data.provider = \"nano-banana\"` for that iteration and otherwise\n * behave like REPEAT_PLACEHOLDER (no prompt/media override). */\nexport const PROVIDER_PLACEHOLDER_PREFIX = \"__provider:\"\nconst PROVIDER_PLACEHOLDER_SUFFIX = \"__\"\n\nexport function encodeProviderItem(provider: string): string {\n return `${PROVIDER_PLACEHOLDER_PREFIX}${provider}${PROVIDER_PLACEHOLDER_SUFFIX}`\n}\n\nexport function decodeProviderItem(item: string): string | undefined {\n if (!item.startsWith(PROVIDER_PLACEHOLDER_PREFIX)) return undefined\n if (!item.endsWith(PROVIDER_PLACEHOLDER_SUFFIX)) return undefined\n const inner = item.slice(\n PROVIDER_PLACEHOLDER_PREFIX.length,\n item.length - PROVIDER_PLACEHOLDER_SUFFIX.length,\n )\n return inner.length > 0 ? inner : undefined\n}\n\n/** Read repeatCount from node data, clamped to 1-20. Returns 1 if unset/invalid. */\nexport function getEffectiveRepeatCount(nodeData: Record<string, unknown>): number {\n const raw = nodeData.repeatCount as number | undefined\n if (!raw || raw <= 1) return 1\n return Math.min(Math.max(Math.floor(raw), 1), 20)\n}\n\n/** Read providers array from node data. Returns the array only when it has 2+\n * entries; one provider is equivalent to single-provider mode. */\nfunction getEffectiveProviders(nodeData: Record<string, unknown>): readonly string[] | undefined {\n const raw = nodeData.providers as readonly unknown[] | undefined\n if (!raw || raw.length < 2) return undefined\n const cleaned = raw.filter((p): p is string => typeof p === \"string\" && p.length > 0)\n return cleaned.length >= 2 ? cleaned : undefined\n}\n\n/**\n * Expand list items by repeatCount, or create synthetic repeat / provider items.\n *\n * Resolution order:\n * 1. If an upstream list exists, the list drives expansion (repeatCount multiplies).\n * 2. Else if `data.providers` has 2+ entries, emit `providers.length × repeatCount`\n * items — each provider runs `repeatCount` times consecutively.\n * 3. Else if repeatCount > 1, emit `repeatCount` synthetic items.\n * 4. Otherwise return null — single execution, no fan-out.\n */\nexport function expandItemsWithRepeat(\n listItems: string[] | undefined,\n nodeType: string,\n nodeData: Record<string, unknown>,\n): string[] | null {\n const repeatCount = REPEATABLE_NODE_TYPES.has(nodeType)\n ? getEffectiveRepeatCount(nodeData)\n : 1\n\n if (listItems && listItems.length > 1) {\n const expanded = repeatCount > 1\n ? listItems.flatMap(item => Array(repeatCount).fill(item) as string[])\n : listItems\n return expanded\n }\n\n const providers = getEffectiveProviders(nodeData)\n if (providers) {\n // Cross-product: each provider runs `repeatCount` times. Same provider's\n // iterations are grouped (better for UI progress + caching).\n return providers.flatMap(p =>\n Array(Math.max(repeatCount, 1)).fill(encodeProviderItem(p)) as string[],\n )\n }\n\n if (repeatCount > 1) {\n return Array(repeatCount).fill(REPEAT_PLACEHOLDER) as string[]\n }\n\n return null\n}\n","/**\n * Like Promise.allSettled but limits how many tasks run concurrently.\n * Uses a worker-pool pattern so a new task starts as soon as a slot frees up.\n * When `cancelledRef` is provided and becomes truthy, remaining un-started\n * tasks are skipped (already-running tasks continue to completion/rejection).\n */\nexport async function settledWithLimit<T>(\n tasks: (() => Promise<T>)[],\n limit: number,\n cancelledRef?: { cancelled: boolean },\n): Promise<PromiseSettledResult<T>[]> {\n const results: PromiseSettledResult<T>[] = new Array(tasks.length)\n let nextIndex = 0\n\n const cancelledError = new Error(\"Execution cancelled\")\n\n async function worker(): Promise<void> {\n while (nextIndex < tasks.length) {\n if (cancelledRef?.cancelled) break\n const idx = nextIndex++\n try {\n const value = await tasks[idx]()\n results[idx] = { status: \"fulfilled\", value }\n } catch (reason) {\n results[idx] = { status: \"rejected\", reason }\n }\n }\n }\n\n const workers = Array.from(\n { length: Math.min(limit, tasks.length) },\n () => worker(),\n )\n await Promise.all(workers)\n\n // Fill any un-started slots (from cancellation) with a shared rejection\n for (let i = 0; i < results.length; i++) {\n if (!results[i]) results[i] = { status: \"rejected\", reason: cancelledError }\n }\n\n return results\n}\n","/**\n * Surround continuation — shared single source of truth.\n *\n * The Location 360° \"look-around\" builds each ring view (45°, 90°, …) as an\n * image-to-image continuation of the previous view. The platform forces\n * geometric continuity by handing the model a half-done frame: one edge holds\n * the previous view's carried pixels, the rest is flat gray, and the model is\n * asked to paint the gray region.\n *\n * This module owns the bits that are pure and reused across the route Zod\n * schema, the SDK input type, and the worker: the direction enum, the carried\n * fraction defaults, and the fill prompt. The geometry math + sharp compositing\n * + color harmonization live backend-side (they need `sharp`).\n */\n\n/**\n * The carry/paint axis for a continuation.\n *\n * PAN (horizontal — half-carry continuation):\n * - `right` — turning right: the new frame's LEFT edge continues the previous\n * view's RIGHT edge, so the carried band sits on the LEFT, painted on the RIGHT.\n * - `left` — turning left: the new frame's RIGHT edge continues the previous\n * view's LEFT edge, so the carried band sits on the RIGHT, painted on the LEFT.\n * (Mirror of `right`. Lets studio chain BOTH ways from a keyframe, capping\n * chain depth so quality doesn't compound down a long one-way chain.)\n *\n * TILT (vertical — thin-strip, subject-driven re-render):\n * - `up` — tilting straight up: render the open SKY overhead. A thin strip of\n * the establishing shot's TOP edge is carried into the new frame's BOTTOM for\n * a soft horizon transition; the rest is painted as sky (NOT a mirrored\n * landscape).\n * - `down` — tilting straight down: render the GROUND below. A thin strip of the\n * BOTTOM edge is carried into the new frame's TOP.\n */\nexport const SURROUND_DIRECTIONS = [\"right\", \"left\", \"up\", \"down\"] as const\nexport type SurroundDirection = (typeof SURROUND_DIRECTIONS)[number]\n\n/** Half the frame is carried for a horizontal pan (matches studio's composite). */\nexport const DEFAULT_CARRIED_FRACTION = 0.5\n/**\n * Tilts carry only a thin horizon strip. Carrying half of a horizontal frame is\n * exactly what makes the model echo/mirror the landscape vertically instead of\n * rendering what's actually overhead/underfoot — so tilts keep the carry small\n * and let the tilt prompt drive the subject.\n */\nexport const TILT_CARRIED_FRACTION = 0.12\n\n/** True for the vertical tilt directions (up/down), false for the pans. */\nexport function isTiltDirection(direction: SurroundDirection): boolean {\n return direction === \"up\" || direction === \"down\"\n}\n\n/** The carried fraction the platform uses when the caller doesn't pin one. */\nexport function defaultCarriedFraction(direction: SurroundDirection): number {\n return isTiltDirection(direction) ? TILT_CARRIED_FRACTION : DEFAULT_CARRIED_FRACTION\n}\n\n/** Which edge of the NEW frame holds the carried pixels vs the painted region. */\nconst EDGE: Record<SurroundDirection, { carried: string; painted: string }> = {\n right: { carried: \"left\", painted: \"right\" },\n left: { carried: \"right\", painted: \"left\" },\n up: { carried: \"bottom\", painted: \"top\" },\n down: { carried: \"top\", painted: \"bottom\" },\n}\n\n/** What a tilt must actually render (NOT a continuation of the landscape). */\nconst TILT_SUBJECT: Record<\"up\" | \"down\", { word: string; subject: string; where: string }> = {\n up: {\n word: \"up\",\n subject: \"the open sky directly overhead — sky, clouds, or (for an interior) the canopy or ceiling\",\n where: \"overhead\",\n },\n down: {\n word: \"down\",\n subject: \"the ground directly below — terrain, floor, or water surface\",\n where: \"below\",\n },\n}\n\n/**\n * Build the fill prompt the model receives alongside the half-carry composite.\n *\n * `userPrompt` (an optional scene hint from the caller) is woven in front. PAN\n * directions get the seamless-continuation prompt (with the anti-golden-hour\n * negative that fights the documented warm-regrade drift). TILT directions get a\n * subject-forcing prompt — render the sky / ground overhead / below, explicitly\n * NOT a mirrored landscape — which is what stops the vertical echo.\n */\nexport function buildSurroundFillPrompt(direction: SurroundDirection, userPrompt?: string): string {\n const scene = userPrompt && userPrompt.trim() ? `${userPrompt.trim()}. ` : \"\"\n const { carried, painted } = EDGE[direction]\n\n if (direction === \"up\" || direction === \"down\") {\n const t = TILT_SUBJECT[direction]\n return (\n `${scene}` +\n `This is a camera tilted straight ${t.word} from the same scene. The ${carried} strip holds real, finished pixels from the edge of the horizon view; the ${painted} region is flat gray and MUST be painted as ${t.subject}. ` +\n `Render what is genuinely ${t.where} — do NOT repeat, mirror, or continue the landscape, and do NOT draw a horizon line or distant scenery in the painted region. ` +\n `CRITICAL: keep the ${carried} strip unchanged and match the scene's EXACT lighting, time of day, white balance, and color grade — the same light as the ${carried} strip; no golden hour, no sunset, no warm relight, no cinematic regrade. ` +\n `Blend smoothly into the ${carried} strip with no visible seam. No people, no text, no labels, no watermarks.`\n )\n }\n\n // pan (right / left)\n return (\n `${scene}` +\n `This is a partial frame: the ${carried} portion contains real, finished pixels and the ${painted} portion is flat gray that MUST be painted in. ` +\n `Paint ONLY the ${painted} gray region as a natural, seamless continuation of the ${carried} portion — same scene, same perspective, continuing the horizon, geometry, and content across the boundary with no break. ` +\n `Keep the ${carried} portion completely unchanged. ` +\n `CRITICAL: do NOT change the lighting, exposure, white balance, or time of day. Match the ${carried} portion's EXACT light, color temperature, and contrast across the whole frame — if it is flat overcast daylight, keep flat overcast daylight. No golden hour, no sunset, no warm relight, no cinematic regrade. ` +\n `The seam between the ${carried} and ${painted} portions must be invisible. No people, no text, no labels, no watermarks.`\n )\n}\n","/**\n * Read the \"primary value\" of a parameter node directly from its data.\n *\n * Parameter nodes (framing, camera-motion, motion, tone, etc.) are pickers on\n * canvas — they don't execute, so they produce no NodeExecutionState.output on\n * the backend. Both the frontend extractNodeOutput fallthrough and the backend\n * resolver adapter call this when a mapped source is a parameter node, so that\n * fieldMappings on non-text fields (framing, cameraMotion, etc.) resolve\n * correctly at execution time.\n */\n\nexport const PARAMETER_NODE_TYPES: ReadonlySet<string> = new Set([\n \"text-prompt\",\n \"tone\",\n \"style-guide\",\n \"motion\",\n \"camera-motion\",\n \"framing\",\n \"lens\",\n \"camera-format\",\n \"lighting\",\n \"color-look\",\n \"atmosphere\",\n \"style\",\n \"setting\",\n \"person\",\n \"mood\",\n \"photographer\",\n \"aesthetic\",\n \"era\",\n \"pose\",\n \"styling\",\n \"temporal\",\n \"material\",\n \"animal\",\n \"vehicle\",\n \"weapon\",\n \"furniture\",\n \"photo-genre\",\n \"backdrop\",\n \"held-prop\",\n \"exposure-settings\",\n \"render-quality\",\n \"composition-effects\",\n \"post-process-effects\",\n \"action-fx\",\n \"character-fx\",\n \"transition\",\n \"loop-subject\",\n \"scene-count\",\n \"duration\",\n \"aspect-ratio\",\n \"music-genre\",\n \"music-mood\",\n \"instrumentation\",\n \"voice-character\",\n \"voice-delivery\",\n])\n\nexport function getParameterValue(\n data: Record<string, unknown>,\n nodeType: string,\n): string | undefined {\n switch (nodeType) {\n case \"text-prompt\":\n return trim(data.text)\n case \"tone\":\n return trim(data.tone)\n case \"style-guide\":\n return trim(data.text)\n case \"motion\":\n return trim(data.motion)\n case \"camera-motion\":\n return trim(data.cameraMotion)\n case \"framing\":\n // Multi-category: return the first set per-category value (used for\n // single-string field-mapping resolution; full hint composition goes\n // through buildFramingHints in the executors).\n return (\n trim(data.shotSize) ??\n trim(data.angle) ??\n trim(data.coverage) ??\n trim(data.composition) ??\n trim(data.vantage)\n )\n case \"lens\":\n return trim(data.lens)\n case \"camera-format\":\n return trim(data.cameraFormat)\n case \"lighting\":\n // Multi-category: return the first set per-category value (used for\n // single-string field-mapping resolution; full hint composition goes\n // through buildLightingHints in the executors).\n return (\n trim(data.timeOfDay) ??\n trim(data.lightingStyle) ??\n trim(data.lightingDirection) ??\n trim(data.lightingRatio) ??\n trim(data.colorTemperature)\n )\n case \"color-look\":\n return trim(data.colorLook)\n case \"music-genre\":\n return trim(data.subgenre) ?? trim(data.genre) ?? trim(data.era)\n case \"music-mood\":\n return trim(data.emotion) ?? trim(data.energy) ?? trim(data.vibe)\n case \"instrumentation\":\n return (\n trim(data.production) ??\n trim(data.instruments) ??\n trim(data.vocalPresence) ??\n trim(data.singingStyle)\n )\n case \"voice-character\":\n return (\n trim(data.timbre) ??\n trim(data.accent) ??\n trim(data.language) ??\n trim(data.gender) ??\n trim(data.age)\n )\n case \"voice-delivery\":\n return trim(data.archetype) ?? trim(data.emotion) ?? trim(data.pace)\n case \"atmosphere\":\n return trim(data.atmosphere)\n case \"action-fx\":\n return trim(data.actionFx)\n case \"character-fx\":\n return trim(data.characterFx)\n case \"transition\":\n return trim(data.transition)\n case \"style\":\n return trim(data.style)\n case \"setting\":\n return trim(data.setting)\n case \"loop-subject\":\n return trim(data.loopSubject)\n case \"material\":\n return trim(data.material)\n case \"animal\":\n return trim(data.animal)\n case \"vehicle\":\n return trim(data.vehicle)\n case \"weapon\":\n return trim(data.weapon)\n case \"furniture\":\n return trim(data.furniture)\n case \"photo-genre\":\n return trim(data.photoGenre)\n case \"backdrop\":\n return trim(data.backdrop)\n case \"held-prop\":\n return trim(data.heldProp)\n case \"person\":\n // Multi-dimension: return the first set per-dimension value (used for\n // single-string field-mapping resolution; full hint composition goes\n // through buildPersonHints in the executors).\n return (\n trim(data.type) ??\n trim(data.age) ??\n trim(data.ethnicity) ??\n trim(data.regionalAesthetic) ??\n trim(data.frame) ??\n trim(data.bodyMass) ??\n trim(data.bust) ??\n trim(data.waist) ??\n trim(data.hips) ??\n trim(data.silhouette) ??\n trim(data.faceShape) ??\n trim(data.jawline) ??\n trim(data.cheekbones) ??\n trim(data.facialFullness) ??\n trim(data.eyeShape) ??\n trim(data.eyelidType) ??\n trim(data.canthalTilt) ??\n trim(data.eyeSpacing) ??\n trim(data.eyeSetBrow) ??\n trim(data.nose) ??\n trim(data.noseTip) ??\n trim(data.lipFullness) ??\n trim(data.lipShape) ??\n trim(data.lips) ??\n trim(data.hairColor) ??\n trim(data.hairBase) ??\n trim(data.eyebrows) ??\n trim(data.skinTone) ??\n trim(data.skinTexture) ??\n trim(data.eyeColor) ??\n trim(data.facialHair) ??\n trim(data.distinctiveFeature) ??\n trim(data.lipState) ??\n trim(data.eyeState)\n )\n case \"mood\":\n return trim(data.mood)\n case \"photographer\":\n return trim(data.photographer)\n case \"aesthetic\":\n return trim(data.aesthetic)\n case \"era\":\n return trim(data.era)\n case \"pose\":\n return (\n trim(data.pose) ??\n trim(data.handPosition) ??\n trim(data.bodyLean) ??\n trim(data.headTilt) ??\n trim(data.activity)\n )\n case \"styling\":\n // Multi-dimension: return the first set per-dimension value (used for\n // single-string field-mapping resolution; full hint composition goes\n // through buildStylingHints in the executors).\n return (\n trim(data.makeup) ??\n trim(data.hairCut) ??\n trim(data.hairTreatment) ??\n trim(data.hairState) ??\n trim(data.eyewear) ??\n trim(data.headwear) ??\n trim(data.jewelry) ??\n trim(data.nails) ??\n trim(data.facePaint) ??\n trim(data.outfit) ??\n trim(data.top) ??\n trim(data.bottom) ??\n trim(data.outerwear) ??\n trim(data.legwear) ??\n trim(data.footwear) ??\n trim(data.fabric) ??\n trim(data.wardrobeState)\n )\n case \"temporal\":\n // Multi-category: return the first set per-category value (used for\n // single-string field-mapping resolution; full hint composition goes\n // through buildTemporalHints in the executors).\n return (\n trim(data.temporalSpeed) ??\n trim(data.temporalFreeze) ??\n trim(data.temporalDirection) ??\n trim(data.temporalShutter)\n )\n case \"exposure-settings\":\n return (\n trim(data.aperture) ??\n trim(data.shutterSpeed) ??\n trim(data.isoValue)\n )\n case \"render-quality\":\n return trim(data.renderQuality)\n case \"composition-effects\":\n return trim(data.compositionEffect)\n case \"post-process-effects\":\n return trim(data.postProcess)\n case \"scene-count\":\n return data.count != null ? String(data.count) : undefined\n case \"duration\":\n return data.seconds != null ? String(data.seconds) : undefined\n case \"aspect-ratio\":\n return trim(data.ratio)\n default:\n return undefined\n }\n}\n\nfunction trim(v: unknown): string | undefined {\n if (typeof v === \"string\") {\n const s = v.trim()\n return s.length > 0 ? s : undefined\n }\n // Multi-pick fields (ethnicity, mood, aesthetic) may be a string[]. The\n // single-string field-mapping resolver only needs *some* value to indicate\n // the field is set — return the first non-empty entry.\n if (Array.isArray(v)) {\n for (const item of v) {\n if (typeof item === \"string\") {\n const s = item.trim()\n if (s.length > 0) return s\n }\n }\n }\n return undefined\n}\n\n","import { PARAMETER_NODE_TYPES } from \"./parameter-node-value.js\"\n\n/**\n * The 5 parameter-picker node types that can wire INTO the Object Studio's\n * `type` input handle as upstream identity providers (Material, Animal,\n * Vehicle, Weapon, Furniture). The resolver in\n * `backend/src/services/workflow-engine/input-resolver.ts` (and its frontend\n * mirror) reads this set to discriminate wired pickers from arbitrary source\n * nodes when composing the seedPromptHint.\n *\n * Defensive filter: if `PARAMETER_NODE_TYPES` doesn't yet contain `\"furniture\"`\n * (i.e., the Furniture prereq PR hasn't been deployed in this environment),\n * furniture silently drops from the set. The wired-picker resolver then\n * skips furniture pickers without error rather than firing a wrong prompt\n * fragment. Production deploy order is enforced as: Prereq PR (#2601, merged)\n * → Object Studio PRs; this defensive code is a safety net.\n */\nexport const OBJECT_PICKER_NODE_TYPES: ReadonlySet<string> = new Set(\n [\"material\", \"animal\", \"vehicle\", \"weapon\", \"furniture\"].filter((t) =>\n PARAMETER_NODE_TYPES.has(t),\n ),\n)\n","// ─────────────────────────────────────────────────────────────────────────────\n// Object aspect-ratio defaults\n// ─────────────────────────────────────────────────────────────────────────────\n//\n// Objects are isolated subjects — product-showcase framing. Unlike characters\n// (which have per-asset-type framing differences — head shots 3:4, full-body\n// 9:16), objects use 1:1 square framing for every asset type by default. This\n// matches the natural framing of the Object Studio's asset-card grid (square\n// tiles) and avoids cropping the subject regardless of which variant axis\n// (angles/materials/variations/motion) is being generated.\n//\n// Resolution precedence (low → high):\n// 1. Per-asset-type default (this table — all 1:1 currently)\n// 2. Object node's `defaultAssetAspectRatio` (user override, Phase E)\n// 3. Explicit `aspectRatio` on the API request (caller wins)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const OBJECT_ASPECT_OPTIONS = [\"1:1\", \"3:4\", \"16:9\", \"9:16\", \"4:3\"] as const\nexport type ObjectAspectRatio = (typeof OBJECT_ASPECT_OPTIONS)[number]\n\n/**\n * The asset categories with distinct natural framing. For objects, all bucket\n * defaults are currently `\"1:1\"`, but the per-asset-type table is kept (vs a\n * single flat constant) so future tuning (e.g., wider framing for motion clips\n * with camera-orbit moves) can be added without touching the resolver.\n */\nexport type ObjectAssetTypeForAspect = \"angles\" | \"materials\" | \"variations\" | \"motion\" | \"custom\"\n\nexport const OBJECT_ASPECT_DEFAULTS: Record<ObjectAssetTypeForAspect, ObjectAspectRatio> = {\n angles: \"1:1\",\n materials: \"1:1\",\n variations: \"1:1\",\n // Motion clips are 1:1 because objects rotate in place. Switch to \"16:9\" if\n // future motion variants pan through a scene (e.g., drone-orbit with horizon).\n motion: \"1:1\",\n custom: \"1:1\",\n}\n\nexport function isObjectAspectRatio(s: string): s is ObjectAspectRatio {\n return (OBJECT_ASPECT_OPTIONS as readonly string[]).includes(s)\n}\n\nexport interface ResolveObjectAspectOptions {\n /** Explicit `aspectRatio` on the request body — highest precedence. */\n readonly explicit?: string | null\n /**\n * The object node's `defaultAssetAspectRatio` — set per-canvas-node via the\n * 5-pill toggle on the object node (Phase E). Flows through the API as\n * `objectNodeAspectRatio`.\n */\n readonly nodeOverride?: string | null\n /** What's being generated. Drives the default when nothing else is set. */\n readonly assetType: ObjectAssetTypeForAspect\n}\n\n/**\n * Resolve the final aspect ratio for an object generation request.\n *\n * Precedence: explicit > node override > per-asset-type default. The two\n * \"soft\" inputs are tolerated as raw strings and only honored when they parse\n * to a value in OBJECT_ASPECT_OPTIONS — anything else falls through to the\n * next layer (so a stale enum value doesn't poison the generation).\n */\nexport function resolveObjectAspectRatio(opts: ResolveObjectAspectOptions): ObjectAspectRatio {\n if (opts.explicit && isObjectAspectRatio(opts.explicit)) {\n return opts.explicit\n }\n if (opts.nodeOverride && isObjectAspectRatio(opts.nodeOverride)) {\n return opts.nodeOverride\n }\n return OBJECT_ASPECT_DEFAULTS[opts.assetType]\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 * Sentinel value persisted by the \"None\" delimiter option in the UI. Distinct\n * from `undefined` (which means \"default to newline\") so we can tell the\n * difference between \"user actively chose not to split\" and \"field never set\".\n */\nexport const NO_SPLIT_DELIMITER = \"__none__\" as const\n\n/**\n * Split text using a loop node's column delimiter.\n *\n * Uses the first text-type column's `splitDelimiter` to determine\n * how to split upstream text. Falls back to newline when no delimiter\n * is configured. The \"first text column wins\" heuristic is intentional:\n * connected mode pipes a single text stream into the loop, so we use\n * the primary text column's delimiter as the split strategy.\n *\n * `splitDelimiter === NO_SPLIT_DELIMITER` (\"__none__\") returns the input as\n * a single-item array — the user explicitly opted out of splitting.\n */\nexport function splitByLoopDelimiter(\n text: string,\n columns: ReadonlyArray<{ type?: string; splitDelimiter?: string }> | undefined,\n): string[] {\n const firstTextCol = (columns ?? []).find((c) => (c.type ?? \"text\") === \"text\")\n const raw = firstTextCol?.splitDelimiter\n if (raw === NO_SPLIT_DELIMITER) {\n const trimmed = text.trim()\n return trimmed.length > 0 ? [trimmed] : []\n }\n const delimiter = raw ?? \"\\n\"\n return text.split(delimiter).map((s) => s.trim()).filter((s) => s.length > 0)\n}\n\n/**\n * Split pasted (or manually-triggered) text into rows, inserting below\n * the source row. Returns the new rows array and truncation metadata.\n *\n * Pure function — callers handle persisting the result and showing toasts.\n */\nexport function spliceDelimitedRows(\n rows: readonly (readonly string[])[],\n rowIndex: number,\n colIndex: number,\n pastedText: string,\n delimiter: string,\n columnCount: number,\n maxItems: number,\n): { newRows: string[][]; truncated: boolean; totalProduced: number } {\n const parts = pastedText.split(delimiter).map((s) => s.trim()).filter((s) => s.length > 0)\n if (parts.length <= 1) {\n // Nothing to split — return rows unchanged with first part (or original) in cell\n const newRows = rows.map((r) => [...r])\n if (parts.length === 1) newRows[rowIndex][colIndex] = parts[0]\n return { newRows, truncated: false, totalProduced: newRows.length }\n }\n\n const newRows = rows.map((r) => [...r])\n newRows[rowIndex][colIndex] = parts[0]\n const insertRows = parts.slice(1).map((part) => {\n const r = Array.from<string>({ length: columnCount }).fill(\"\")\n r[colIndex] = part\n return r\n })\n newRows.splice(rowIndex + 1, 0, ...insertRows)\n\n const truncated = newRows.length > maxItems\n const totalProduced = newRows.length\n return {\n newRows: truncated ? newRows.slice(0, maxItems) : newRows,\n truncated,\n totalProduced,\n }\n}\n","/** Delimiter the Generate Text templates instruct the LLM to emit between blocks. */\nexport const GENERATE_TEXT_DELIMITER = \"===NEXT===\"\n\n/**\n * Split a Generate Text result into fan-out items. Used by BOTH the frontend\n * extractNodeOutput and the backend output-extractor so single-node and DAG\n * execution produce identical `items`.\n */\nexport function splitGeneratedItems(text: string | null | undefined): string[] {\n if (!text) return []\n const parts = text.split(GENERATE_TEXT_DELIMITER).map((s) => s.trim()).filter(Boolean)\n if (parts.length > 0) return parts\n const trimmed = text.trim()\n return trimmed ? [trimmed] : []\n}\n","/**\n * Shared separator presets for the Combine Text and Split Text nodes.\n * Single source of truth for both the frontend DAG executor and backend orchestrator.\n */\n\nexport const SEPARATOR_PRESETS = [\n \"newline\",\n \"double-newline\",\n \"comma\",\n \"space\",\n \"stars\",\n \"custom\",\n] as const\n\nexport type SeparatorPreset = (typeof SEPARATOR_PRESETS)[number]\n\nconst SPLIT_MAP: Record<string, string> = {\n newline: \"\\n\",\n \"double-newline\": \"\\n\\n\",\n comma: \",\",\n space: \" \",\n stars: \"***\",\n}\n\nconst COMBINE_MAP: Record<string, string> = {\n ...SPLIT_MAP,\n comma: \", \",\n}\n\n/** Human-readable label for the node badge. */\nexport const SEPARATOR_DISPLAY: Record<string, string> = {\n newline: \"\\\\n\",\n \"double-newline\": \"\\\\n\\\\n\",\n comma: \",\",\n space: \"space\",\n stars: \"***\",\n}\n\nexport interface ResolveSeparatorOptions {\n /** Use combine-text spacing — e.g. \", \" for comma instead of \",\" */\n combineSpacing?: boolean\n}\n\n/**\n * Resolve a separator value to its actual string.\n * - Enum preset → mapped value (e.g. \"newline\" → \"\\n\")\n * - \"custom\" → customSeparator field\n * - Anything else → literal string (back-compat with legacy values like \"===NEXT===\")\n */\nexport function resolveSeparator(\n raw: string | undefined,\n customSeparator: string | undefined,\n opts?: ResolveSeparatorOptions,\n): string {\n const r = raw || \"newline\"\n if (r === \"custom\") return customSeparator ?? \"\"\n const map = opts?.combineSpacing ? COMBINE_MAP : SPLIT_MAP\n return map[r] ?? r\n}\n","/** Pure sort helper shared by the frontend DAG executor and the backend\n * orchestrator. Contract: reorder stringified list items (as produced by\n * `collectUpstreamListItems` peers) by an optional dot-path field, with\n * Auto/Text/Number/Date comparison and asc/desc direction. Items whose\n * key is missing, empty, or uncoerceable under the chosen type are always\n * appended last — regardless of direction. */\n\nimport { evaluateJsonPath } from \"./json-path.js\"\nimport { tryParseJson } from \"./filter-condition.js\"\n\nexport type SortType = \"auto\" | \"text\" | \"number\" | \"date\"\nexport type SortDirection = \"asc\" | \"desc\"\n\nexport interface SortListOptions {\n field: string\n sortType: SortType\n direction: SortDirection\n}\n\n// Natural numeric-aware, case-insensitive locale compare. Declared once so\n// both the Text branch and the Auto fallback reuse the same Collator.\nconst textCollator = new Intl.Collator(undefined, {\n sensitivity: \"base\",\n numeric: true,\n})\n\ninterface KeyedItem {\n item: string\n key: number | string\n keyKind: \"number\" | \"text\" | \"invalid\"\n}\n\nfunction extractRawKey(item: string, field: string): unknown {\n if (field === \"\") return item\n const parsed = tryParseJson(item)\n const matches = evaluateJsonPath(parsed, field)\n return matches.length > 0 ? matches[0] : undefined\n}\n\nfunction isMissing(v: unknown): boolean {\n if (v === undefined || v === null) return true\n if (typeof v === \"string\" && v.trim() === \"\") return true\n return false\n}\n\nfunction toNumberKey(v: unknown): number | undefined {\n if (typeof v === \"number\") return Number.isFinite(v) ? v : undefined\n if (typeof v === \"boolean\") return v ? 1 : 0\n if (typeof v === \"string\") {\n const trimmed = v.trim()\n if (trimmed === \"\") return undefined\n const n = Number(trimmed)\n return Number.isFinite(n) ? n : undefined\n }\n return undefined\n}\n\nfunction toDateKey(v: unknown): number | undefined {\n if (v instanceof Date) {\n const t = v.getTime()\n return Number.isFinite(t) ? t : undefined\n }\n if (typeof v === \"number\") return Number.isFinite(v) ? v : undefined\n if (typeof v === \"string\") {\n const t = Date.parse(v)\n return Number.isFinite(t) ? t : undefined\n }\n return undefined\n}\n\nfunction coerceKey(raw: unknown, sortType: SortType): Pick<KeyedItem, \"key\" | \"keyKind\"> {\n if (isMissing(raw)) return { key: \"\", keyKind: \"invalid\" }\n\n if (sortType === \"number\") {\n const n = toNumberKey(raw)\n return n === undefined\n ? { key: \"\", keyKind: \"invalid\" }\n : { key: n, keyKind: \"number\" }\n }\n\n if (sortType === \"date\") {\n const d = toDateKey(raw)\n return d === undefined\n ? { key: \"\", keyKind: \"invalid\" }\n : { key: d, keyKind: \"number\" }\n }\n\n if (sortType === \"text\") {\n return { key: typeof raw === \"string\" ? raw : JSON.stringify(raw), keyKind: \"text\" }\n }\n\n // auto: try number → date → text.\n const asNum = toNumberKey(raw)\n if (asNum !== undefined) return { key: asNum, keyKind: \"number\" }\n const asDate = toDateKey(raw)\n if (asDate !== undefined) return { key: asDate, keyKind: \"number\" }\n return { key: typeof raw === \"string\" ? raw : JSON.stringify(raw), keyKind: \"text\" }\n}\n\nexport function sortListItems(items: readonly string[], opts: SortListOptions): string[] {\n const { field, sortType, direction } = opts\n const keyed: KeyedItem[] = items.map((item) => {\n const raw = extractRawKey(item, field)\n const { key, keyKind } = coerceKey(raw, sortType)\n return { item, key, keyKind }\n })\n\n const sortable = keyed.filter((k) => k.keyKind !== \"invalid\")\n const invalid = keyed.filter((k) => k.keyKind === \"invalid\")\n\n const factor = direction === \"desc\" ? -1 : 1\n // Array.prototype.sort is guaranteed stable since ES2019 — equal keys\n // preserve their relative input order.\n sortable.sort((a, b) => {\n if (a.keyKind === \"number\" && b.keyKind === \"number\") {\n return ((a.key as number) - (b.key as number)) * factor\n }\n return textCollator.compare(String(a.key), String(b.key)) * factor\n })\n\n return [...sortable.map((k) => k.item), ...invalid.map((k) => k.item)]\n}\n","/**\n * Canonical catalog of seasons.\n *\n * 4 universal seasonal labels — used by the Location Studio's Seasons tab\n * and (in the future) by any season-picker parameter node. Independent of\n * lighting (time-of-day), atmosphere (weather), and color/look.\n *\n * Northern-hemisphere reference is implicit. Promp t hints describe the\n * visual hallmarks of each season so downstream generators reproduce them\n * faithfully across diverse settings (interior, exterior, character, etc.).\n */\n\nexport interface Season {\n readonly id: string\n readonly label: string\n readonly description: string\n readonly promptHint: string\n}\n\nexport const SEASONS: ReadonlyArray<Season> = [\n {\n id: \"spring\",\n label: \"Spring\",\n description: \"Fresh growth, blossoms, mild weather\",\n promptHint: \"spring season, fresh new growth with green buds and emerging foliage, blossoming flowers, mild fresh air, soft directional sunlight, occasional light rain, pastel color palette of pale greens and pinks\",\n },\n {\n id: \"summer\",\n label: \"Summer\",\n description: \"Full bloom, warm light, lush green\",\n promptHint: \"summer season, lush full foliage in deep saturated greens, warm bright sunlight with strong overhead sun, deep shadows, vibrant warm color palette, clear blue skies or scattered cumulus clouds\",\n },\n {\n id: \"autumn\",\n label: \"Autumn\",\n description: \"Falling leaves, warm amber palette\",\n promptHint: \"autumn season, foliage transitioning to warm amber tones — red, orange, yellow, and rust — falling leaves drifting on the breeze, soft golden directional light, crisp cool air with low sun angles\",\n },\n {\n id: \"winter\",\n label: \"Winter\",\n description: \"Bare branches, snow, cool palette\",\n promptHint: \"winter season, bare branches against a cold sky, snow accumulation on every surface, breath visible in cold air, desaturated cool color palette of blues and grays with isolated warm artificial light sources\",\n },\n]\n","/**\n * Adapter from the Location Studio's backend preset strings to canonical\n * picker-catalog entries.\n *\n * The Location Studio's tab presets ship 46 backend-stable variant strings\n * (e.g. \"wide\", \"golden hour\", \"drone fly-over\"). These strings are what the\n * frontend sends to `POST /v1/generate-location-asset` and what backend Zod\n * validates against the `VARIANTS` map in\n * `backend/src/routes/generate-location-asset.ts`. They MUST stay stable.\n *\n * For display, however, we want translated labels that match the rest of\n * the app. Instead of maintaining a parallel `location-variants` i18n\n * catalog (the duplication this file replaces), the Studio looks up each\n * preset against an existing canonical catalog — framing, lighting,\n * atmosphere, camera-motions, seasons — and uses the existing localized\n * label.\n *\n * Adding a new preset to a Location Studio tab: pick the closest entry in\n * the relevant canonical catalog and add a mapping here. If the closest\n * match is wrong, ADD a new entry to the canonical catalog (so the\n * camera-motion picker / framing picker / etc. all benefit), then map.\n */\nimport type { I18nCatalogId } from \"./i18n/types.js\"\n\nexport interface LocationCatalogRef {\n readonly catalogId: I18nCatalogId\n readonly entryId: string\n}\n\n/**\n * Backend variant string → canonical catalog reference.\n *\n * Keys MUST match the strings in `VARIANTS` in\n * `backend/src/routes/generate-location-asset.ts` AND the preset arrays in\n * the Location Studio tab wrappers\n * (`frontend/src/components/editor/location-studio/{time-of-day,weather,seasons,angles,lighting}-tab.tsx`)\n * AND `motion-tab.tsx`'s MOTION_PRESETS.\n */\nexport const LOCATION_PRESET_TO_CATALOG: Readonly<Record<string, LocationCatalogRef>> = {\n // ── timeOfDay (9) → lighting time-of-day category ────────────────────\n \"dawn\": { catalogId: \"lighting\", entryId: \"dawn\" },\n \"morning\": { catalogId: \"lighting\", entryId: \"morning\" },\n \"noon\": { catalogId: \"lighting\", entryId: \"noon\" },\n \"afternoon\": { catalogId: \"lighting\", entryId: \"afternoon\" },\n \"golden hour\": { catalogId: \"lighting\", entryId: \"golden-hour\" },\n \"dusk\": { catalogId: \"lighting\", entryId: \"dusk\" },\n \"blue hour\": { catalogId: \"lighting\", entryId: \"blue-hour\" },\n \"night\": { catalogId: \"lighting\", entryId: \"night\" },\n \"midnight\": { catalogId: \"lighting\", entryId: \"midnight\" },\n\n // ── weather (9) → atmosphere ─────────────────────────────────────────\n \"clear\": { catalogId: \"atmosphere\", entryId: \"clear\" },\n \"cloudy\": { catalogId: \"atmosphere\", entryId: \"cloudy\" },\n \"light rain\": { catalogId: \"atmosphere\", entryId: \"light-rain\" },\n \"heavy rain\": { catalogId: \"atmosphere\", entryId: \"heavy-rain\" },\n \"storm\": { catalogId: \"atmosphere\", entryId: \"storm\" },\n \"snow\": { catalogId: \"atmosphere\", entryId: \"snow\" },\n \"blizzard\": { catalogId: \"atmosphere\", entryId: \"blizzard\" },\n \"fog\": { catalogId: \"atmosphere\", entryId: \"fog\" },\n \"mist\": { catalogId: \"atmosphere\", entryId: \"mist\" },\n\n // ── seasons (4) → seasons (this catalog only exists to serve this tab) ─\n \"spring\": { catalogId: \"seasons\", entryId: \"spring\" },\n \"summer\": { catalogId: \"seasons\", entryId: \"summer\" },\n \"autumn\": { catalogId: \"seasons\", entryId: \"autumn\" },\n \"winter\": { catalogId: \"seasons\", entryId: \"winter\" },\n\n // ── angles (8) → framing ────────────────────────────────────────────\n \"wide\": { catalogId: \"framing\", entryId: \"wide-shot\" },\n \"medium\": { catalogId: \"framing\", entryId: \"medium-shot\" },\n \"closeup\": { catalogId: \"framing\", entryId: \"close-up\" },\n // `framing` has `birds-eye` and `overhead` but no plain `aerial`. The\n // semantic intent (\"view from above\") is `birds-eye`, so we route there.\n \"aerial\": { catalogId: \"framing\", entryId: \"birds-eye\" },\n \"low-angle\": { catalogId: \"framing\", entryId: \"low-angle\" },\n \"eye-level\": { catalogId: \"framing\", entryId: \"eye-level\" },\n \"bird's-eye\": { catalogId: \"framing\", entryId: \"birds-eye\" },\n \"dutch tilt\": { catalogId: \"framing\", entryId: \"dutch-angle\" },\n\n // ── lighting (8) → lighting non-time-of-day categories ───────────────\n // (`\"blue hour\"` is shared with timeOfDay above — same canonical entry.)\n \"soft natural\": { catalogId: \"lighting\", entryId: \"natural\" },\n \"harsh sunlight\": { catalogId: \"lighting\", entryId: \"harsh-midday\" },\n \"golden\": { catalogId: \"lighting\", entryId: \"golden-hour\" },\n \"neon\": { catalogId: \"lighting\", entryId: \"neon-night\" },\n \"candlelit\": { catalogId: \"lighting\", entryId: \"candlelight\" },\n \"cinematic\": { catalogId: \"lighting\", entryId: \"three-point\" },\n \"dramatic chiaroscuro\": { catalogId: \"lighting\", entryId: \"chiaroscuro\" },\n\n // ── motion (8) → camera-motions ──────────────────────────────────────\n // The \"slow\" / \"gentle\" qualifiers are dropped at lookup time — the\n // chip displays the canonical motion name (\"Dolly-In\", \"Pan Left\") with\n // the user's locale applied.\n \"slow dolly-in\": { catalogId: \"camera-motions\", entryId: \"dolly-in\" },\n \"slow pan-left\": { catalogId: \"camera-motions\", entryId: \"pan-left\" },\n \"slow pan-right\": { catalogId: \"camera-motions\", entryId: \"pan-right\" },\n \"push up\": { catalogId: \"camera-motions\", entryId: \"pedestal-up\" },\n \"drone fly-over\": { catalogId: \"camera-motions\", entryId: \"fly-over\" },\n \"gentle drift\": { catalogId: \"camera-motions\", entryId: \"gentle-drift\" },\n \"parallax\": { catalogId: \"camera-motions\", entryId: \"parallax\" },\n \"static atmospheric\": { catalogId: \"camera-motions\", entryId: \"static\" },\n}\n\n/**\n * Resolve a backend preset string to its canonical catalog reference, or\n * undefined if the preset is unknown (caller falls back to the raw\n * preset string as the display label).\n */\nexport function resolveLocationPresetCatalog(preset: string): LocationCatalogRef | undefined {\n return LOCATION_PRESET_TO_CATALOG[preset]\n}\n\n/**\n * Each Location Studio tab pulls all its localized labels from a single\n * canonical catalog (the tab's bucket → catalog mapping below). This lets\n * the tab call `useLocalizedCatalog(LOCATION_BUCKET_TO_CATALOG_ID[bucket])`\n * once and resolve every preset chip through the same catalog.\n *\n * Atmosphere motion (motion-tab.tsx) uses `camera-motions` directly — it's\n * a single-bucket tab so the mapping isn't needed there.\n */\nexport const LOCATION_BUCKET_TO_CATALOG_ID = {\n timeOfDay: \"lighting\",\n weather: \"atmosphere\",\n seasons: \"seasons\",\n angles: \"framing\",\n lighting: \"lighting\",\n} as const satisfies Record<string, I18nCatalogId>\n","import { INPUT_FIELD_MAP as PRESENTATION_INPUT_MAP } from \"./presentation-utils.js\"\n\nexport interface ComponentHandle {\n id: string\n name: string\n type: \"image\" | \"video\" | \"audio\" | \"text\"\n required: boolean\n mediaPreview?: boolean\n fieldKey: string\n}\n\nexport interface ExposedSetting {\n nodeId: string\n field: string\n label: string\n type: \"select\" | \"text\" | \"number\" | \"toggle\" | \"aspect-ratio\"\n allowedValues?: unknown[]\n /** Full option list with labels for select fields (preferred over allowedValues). */\n options?: Array<{ value: string; label: string }>\n defaultValue: unknown\n}\n\nexport interface ComponentMetadata {\n inputs: ComponentHandle[]\n outputs: ComponentHandle[]\n exposedSettings: ExposedSetting[]\n}\n\n/** Maps input node types to their data field key for inputOverrides (derived from presentation-utils) */\nexport const INPUT_FIELD_MAP: Record<string, string> = Object.fromEntries(\n Object.entries(PRESENTATION_INPUT_MAP).map(([k, v]) => [k, v.key]),\n)\n\n/** Separator used in component handle ids that target a specific port on a sub-workflow-input / sub-workflow-output node. */\nexport const HANDLE_PORT_SEPARATOR = \"::\"\n\n/**\n * Split a component handle id of the form `nodeId` or `nodeId::portId`.\n * Returns the literal nodeId when no separator is present.\n */\nexport function parseHandleId(handleId: string): { nodeId: string; portId?: string } {\n const sep = handleId.indexOf(HANDLE_PORT_SEPARATOR)\n if (sep < 0) return { nodeId: handleId }\n const portId = handleId.slice(sep + HANDLE_PORT_SEPARATOR.length)\n return { nodeId: handleId.slice(0, sep), portId: portId || undefined }\n}\n\n/**\n * Apply a value for a component input handle to the inputOverrides map.\n *\n * - Plain handles (id = nodeId) write to `inputOverrides[nodeId][fieldKey]`,\n * which the orchestrator shallow-merges into `node.data` at execution.\n * - Compound handles (id = nodeId::portId) write into\n * `inputOverrides[nodeId].__injectedPortValues[portId]`, the slot that\n * sub-workflow-input nodes read at runtime via output-extractor.\n *\n * Mutates the map in place so multi-port accumulation merges correctly when\n * iterating handles in a loop.\n */\nexport function applyHandleInputOverride(\n inputOverrides: Record<string, Record<string, unknown>>,\n handle: { id: string; fieldKey: string },\n value: unknown,\n): void {\n const { nodeId, portId } = parseHandleId(handle.id)\n if (portId) {\n const existing = (inputOverrides[nodeId]?.__injectedPortValues as Record<string, unknown> | undefined) ?? {}\n inputOverrides[nodeId] = {\n ...inputOverrides[nodeId],\n __injectedPortValues: { ...existing, [portId]: value },\n }\n } else {\n inputOverrides[nodeId] = { ...inputOverrides[nodeId], [handle.fieldKey]: value }\n }\n}\n\n/**\n * Has a value already been recorded for this handle in the inputOverrides map?\n * Used to skip fallback wiring when an upstream connection already supplied\n * the input.\n */\nexport function isHandleInputWired(\n inputOverrides: Record<string, Record<string, unknown>>,\n handle: { id: string; fieldKey: string },\n): boolean {\n const { nodeId, portId } = parseHandleId(handle.id)\n if (portId) {\n const injected = inputOverrides[nodeId]?.__injectedPortValues as Record<string, unknown> | undefined\n return injected?.[portId] !== undefined\n }\n return inputOverrides[nodeId]?.[handle.fieldKey] !== undefined\n}\n\n/** Maps output media types to NodeOutput field keys */\nexport const OUTPUT_FIELD_MAP: Record<string, string> = {\n image: \"imageUrl\",\n video: \"videoUrl\",\n audio: \"audioUrl\",\n text: \"text\",\n}\n\n/**\n * Merge exposed settings into inputOverrides format.\n * exposedSettings is keyed by \"nodeId:field\" -> value on the component node data.\n *\n * Connected inputs (already present in inputOverrides) always take priority\n * over exposed settings for the same node+field combination. This ensures\n * that mandatory upstream wires are never silently overwritten by stale\n * default / user-configured exposed-setting values.\n */\nexport function mergeExposedSettings(\n inputOverrides: Record<string, Record<string, unknown>>,\n exposedSettings: Record<string, unknown>,\n metadata: ComponentMetadata,\n): Record<string, Record<string, unknown>> {\n const merged = { ...inputOverrides }\n for (const setting of metadata.exposedSettings) {\n const key = `${setting.nodeId}:${setting.field}`\n const value = exposedSettings[key]\n if (value !== undefined) {\n // Skip if a connected input already provided this field\n if (merged[setting.nodeId]?.[setting.field] !== undefined) continue\n merged[setting.nodeId] = { ...merged[setting.nodeId], [setting.field]: value }\n }\n }\n return merged\n}\n","/**\n * Shared constants for social post nodes.\n *\n * Used by both the frontend DAG executor and backend orchestrator so input\n * routing + API validation agree on which node types are social posts and\n * on Instagram's carousel item limits.\n */\n\n/** Node types that publish to a social platform via POST /v1/social/publish. */\nexport const SOCIAL_POST_NODE_TYPES = new Set([\n \"instagram-post\",\n \"tiktok-post\",\n \"youtube-upload\",\n \"linkedin-post\",\n \"x-post\",\n \"facebook-post\",\n \"telegram-post\",\n])\n\n/** Instagram carousel limits per Meta Graph API.\n * Meta's documented limit is 10 items; sending >10 fails at container\n * creation with \"(#100) too little or too many attachments\". */\nexport const INSTAGRAM_CAROUSEL_MIN_ITEMS = 2\nexport const INSTAGRAM_CAROUSEL_MAX_ITEMS = 10\n","import {\n IMAGE_GEN_PROVIDERS,\n IMAGE_I2I_PROVIDERS,\n IMAGE_EDIT_PROVIDERS,\n UPSCALE_IMAGE_PROVIDERS,\n TEXT_TO_VIDEO_PROVIDERS,\n IMAGE_TO_VIDEO_PROVIDERS,\n VIDEO_GEN_PROVIDERS,\n LIP_SYNC_PROVIDERS,\n TTS_PROVIDERS,\n VOICE_DESIGN_MODELS,\n} from \"./model-constants.js\"\nimport { LLM_MODEL_IDS } from \"./llm-models.js\"\n\n// ──────────────────────────────────────────────────────────────────────────\n// Types\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type QualityLevel = \"low\" | \"mid\" | \"high\"\nexport type SemanticAspectRatio = \"auto\" | \"1:1\" | \"4:3\" | \"3:4\" | \"16:9\" | \"9:16\"\n\nexport const NODE_DEFAULT_TYPES = [\n // Image\n \"generate-image\",\n \"image-to-image\",\n \"edit-image\",\n \"upscale-image\",\n // Video\n \"text-to-video\",\n \"image-to-video\",\n \"generate-video\",\n // Composition\n \"lip-sync\",\n // Audio / Music\n \"text-to-speech\",\n \"generate-music\",\n \"voice-design\",\n // LLM-driven\n \"ai-writer\",\n \"llm-chat\",\n \"lottie-overlay\",\n \"3d-title\",\n \"motion-graphics\",\n \"image-to-text\",\n \"qa-check\",\n] as const\n\nexport type NodeDefaultType = (typeof NODE_DEFAULT_TYPES)[number]\n\nexport const QUALITY_LEVELS: readonly QualityLevel[] = [\"low\", \"mid\", \"high\"] as const\nexport const SEMANTIC_ASPECT_RATIOS: readonly SemanticAspectRatio[] = [\n \"auto\",\n \"1:1\",\n \"4:3\",\n \"3:4\",\n \"16:9\",\n \"9:16\",\n] as const\n\n// ──────────────────────────────────────────────────────────────────────────\n// Per-node-type registry\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Per-node-type metadata: which field on the node carries the admin-set value,\n * the valid value set, and which optional dimensions apply.\n *\n * `field` distinguishes nodes that use `data.provider` (image/video/audio)\n * from nodes that use `data.model` (LLM nodes, voice-design).\n */\ninterface NodeTypeMeta {\n field: \"provider\" | \"model\"\n validValues: readonly string[]\n hasQuality: boolean\n hasAspectRatio: boolean\n}\n\n// Music providers per the runtime: enum currently only lists \"minimax\", but\n// `generate-music.defaultData.provider` is \"suno\" with a separate `modelVersion`.\n// Until that mismatch is fixed, accept both values for admin defaults.\nconst MUSIC_PROVIDERS_FOR_VALIDATION = [\"suno\", \"minimax\"] as const\n\nconst META: Record<NodeDefaultType, NodeTypeMeta> = {\n \"generate-image\": { field: \"provider\", validValues: IMAGE_GEN_PROVIDERS, hasQuality: true, hasAspectRatio: true },\n \"image-to-image\": { field: \"provider\", validValues: IMAGE_I2I_PROVIDERS, hasQuality: true, hasAspectRatio: true },\n \"edit-image\": { field: \"provider\", validValues: IMAGE_EDIT_PROVIDERS, hasQuality: false, hasAspectRatio: false },\n \"upscale-image\": { field: \"provider\", validValues: UPSCALE_IMAGE_PROVIDERS, hasQuality: false, hasAspectRatio: false },\n \"text-to-video\": { field: \"provider\", validValues: TEXT_TO_VIDEO_PROVIDERS, hasQuality: true, hasAspectRatio: true },\n \"image-to-video\": { field: \"provider\", validValues: IMAGE_TO_VIDEO_PROVIDERS, hasQuality: true, hasAspectRatio: true },\n \"generate-video\": { field: \"provider\", validValues: VIDEO_GEN_PROVIDERS, hasQuality: true, hasAspectRatio: true },\n \"lip-sync\": { field: \"provider\", validValues: LIP_SYNC_PROVIDERS, hasQuality: false, hasAspectRatio: false },\n \"text-to-speech\": { field: \"provider\", validValues: TTS_PROVIDERS, hasQuality: false, hasAspectRatio: false },\n \"generate-music\": { field: \"provider\", validValues: MUSIC_PROVIDERS_FOR_VALIDATION, hasQuality: false, hasAspectRatio: false },\n \"voice-design\": { field: \"model\", validValues: VOICE_DESIGN_MODELS, hasQuality: false, hasAspectRatio: false },\n \"ai-writer\": { field: \"model\", validValues: LLM_MODEL_IDS, hasQuality: false, hasAspectRatio: false },\n \"llm-chat\": { field: \"model\", validValues: LLM_MODEL_IDS, hasQuality: false, hasAspectRatio: false },\n \"lottie-overlay\": { field: \"model\", validValues: LLM_MODEL_IDS, hasQuality: false, hasAspectRatio: false },\n \"3d-title\": { field: \"model\", validValues: LLM_MODEL_IDS, hasQuality: false, hasAspectRatio: false },\n \"motion-graphics\": { field: \"model\", validValues: LLM_MODEL_IDS, hasQuality: false, hasAspectRatio: false },\n \"image-to-text\": { field: \"model\", validValues: LLM_MODEL_IDS, hasQuality: false, hasAspectRatio: false },\n \"qa-check\": { field: \"model\", validValues: LLM_MODEL_IDS, hasQuality: false, hasAspectRatio: false },\n}\n\nexport function getTargetField(nodeType: NodeDefaultType): \"provider\" | \"model\" {\n return META[nodeType].field\n}\n\nexport function getValidValues(nodeType: NodeDefaultType): readonly string[] {\n return META[nodeType].validValues\n}\n\nexport function supportedDefaultDimensions(nodeType: NodeDefaultType): {\n quality: boolean\n aspectRatio: boolean\n} {\n const m = META[nodeType]\n return { quality: m.hasQuality, aspectRatio: m.hasAspectRatio }\n}\n\nexport function validateProviderForNodeType(\n nodeType: NodeDefaultType,\n value: string,\n): string | null {\n const valid = META[nodeType].validValues\n if (!valid.includes(value)) {\n return `value \"${value}\" is not valid for node type \"${nodeType}\"`\n }\n return null\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Semantic mappings — quality + aspect ratio per provider\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Each provider stores its quality lever on a different field of node data:\n * - `resolution` (1K/2K/4K, 720p/1080p, …) — most image + video providers\n * - `quality` (medium/high, basic/high) — gpt-image, seedream\n *\n * Mapping a semantic level (low/mid/high) to a concrete value is meaningless\n * without knowing WHICH field it belongs to, because writing \"medium\" into\n * `resolution` (or \"2K\" into `quality`) trips the route's Zod enum at\n * generate-time. Each entry pairs the field with the per-level values built\n * from frontend/src/components/editor/config-panels/model-options.ts.\n *\n * Providers absent from this table return `undefined` from `mapQuality`,\n * letting the caller fall back to the factory default value.\n *\n * When a provider has fewer than 3 levels, semantic levels collapse onto\n * the closest concrete value (e.g. gpt-image only has medium/high → low maps\n * to medium).\n */\nexport type QualityField = \"resolution\" | \"quality\"\n\ninterface QualityMapping {\n field: QualityField\n values: Partial<Record<QualityLevel, string>>\n}\n\nconst QUALITY_MAP: Record<string, QualityMapping> = {\n // Image gen — resolution-style (1K/2K/4K)\n \"nano-banana-pro\": { field: \"resolution\", values: { low: \"1K\", mid: \"2K\", high: \"4K\" } },\n \"nano-banana-2\": { field: \"resolution\", values: { low: \"1K\", mid: \"2K\", high: \"4K\" } },\n \"flux\": { field: \"resolution\", values: { low: \"1K\", mid: \"2K\", high: \"2K\" } },\n \"flux-flex\": { field: \"resolution\", values: { low: \"1K\", mid: \"2K\", high: \"2K\" } },\n \"flux-i2i\": { field: \"resolution\", values: { low: \"1K\", mid: \"2K\", high: \"2K\" } },\n \"flux-pro-i2i\": { field: \"resolution\", values: { low: \"1K\", mid: \"2K\", high: \"2K\" } },\n \"gpt-image-2\": { field: \"resolution\", values: { low: \"1K\", mid: \"2K\", high: \"4K\" } },\n \"gpt-image-2-i2i\": { field: \"resolution\", values: { low: \"1K\", mid: \"2K\", high: \"4K\" } },\n // Image gen — quality-style (medium/high or basic/high)\n \"gpt-image\": { field: \"quality\", values: { low: \"medium\", mid: \"medium\", high: \"high\" } },\n \"gpt-image-i2i\": { field: \"quality\", values: { low: \"medium\", mid: \"medium\", high: \"high\" } },\n \"seedream\": { field: \"quality\", values: { low: \"basic\", mid: \"basic\", high: \"high\" } },\n \"seedream-edit\": { field: \"quality\", values: { low: \"basic\", mid: \"basic\", high: \"high\" } },\n \"seedream-5-lite\": { field: \"quality\", values: { low: \"basic\", mid: \"basic\", high: \"high\" } },\n \"seedream-5-lite-i2i\": { field: \"quality\", values: { low: \"basic\", mid: \"basic\", high: \"high\" } },\n // Video gen — resolution-style (720p/1080p)\n \"veo3\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"veo3.1\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"kling\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"kling-3.0\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"seedance-2\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"seedance-2-fast\": { field: \"resolution\", values: { low: \"480p\", mid: \"720p\", high: \"720p\" } },\n \"seedance-2-mini\": { field: \"resolution\", values: { low: \"480p\", mid: \"720p\", high: \"720p\" } },\n \"wan-2.7-i2v\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"wan-2.7-t2v\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"happyhorse\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"happyhorse-i2v\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"happyhorse-ref2v\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"happyhorse-edit\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"kling-3-omni\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n \"wan-videoedit\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"1080p\" } },\n // Lightricks LTX 2.3 — 1080p / 2k / 4k (lowercase, matching VIDEO_RESOLUTION_OPTIONS).\n // `field: \"resolution\"` is mandatory — see Provider Enum Sync pitfall 4.\n \"ltx-2.3-pro\": { field: \"resolution\", values: { low: \"1080p\", mid: \"2k\", high: \"4k\" } },\n \"ltx-2.3-fast\": { field: \"resolution\", values: { low: \"1080p\", mid: \"2k\", high: \"4k\" } },\n \"gemini-omni-video\": { field: \"resolution\", values: { low: \"720p\", mid: \"1080p\", high: \"4k\" } },\n // Grok Imagine Video 1.5 — only 480p/720p (no 1080p tier); high clamps to 720p.\n \"grok-imagine-video-1.5\": { field: \"resolution\", values: { low: \"480p\", mid: \"720p\", high: \"720p\" } },\n // Replicate Flux 2 family — MP-based resolution (matching IMAGE_RESOLUTION_OPTIONS[\"flux-2-*\"]).\n // `field: \"resolution\"` is mandatory — see Provider Enum Sync pitfall 4.\n // mid = provider default: 1 MP for Klein, 2 MP for Pro/Max.\n \"flux-2-klein\": { field: \"resolution\", values: { low: \"0.5 MP\", mid: \"1 MP\", high: \"2 MP\" } },\n \"flux-2-pro\": { field: \"resolution\", values: { low: \"1 MP\", mid: \"2 MP\", high: \"4 MP\" } },\n \"flux-2-max\": { field: \"resolution\", values: { low: \"1 MP\", mid: \"2 MP\", high: \"4 MP\" } },\n}\n\nconst ASPECT_PASSTHROUGH_PROVIDERS = new Set([\n ...IMAGE_GEN_PROVIDERS,\n ...IMAGE_I2I_PROVIDERS,\n ...TEXT_TO_VIDEO_PROVIDERS,\n ...IMAGE_TO_VIDEO_PROVIDERS,\n])\n\nexport interface MappedQuality {\n field: QualityField\n value: string\n}\n\nexport function mapQuality(provider: string, level: QualityLevel): MappedQuality | undefined {\n const m = QUALITY_MAP[provider]\n const value = m?.values[level]\n return value === undefined ? undefined : { field: m!.field, value }\n}\n\nexport function mapAspectRatio(\n provider: string,\n ratio: SemanticAspectRatio,\n): string | undefined {\n if (ratio === \"auto\") return undefined\n if (!ASPECT_PASSTHROUGH_PROVIDERS.has(provider as never)) return ratio\n return ratio\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Linked field derivation\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * When admin sets `provider` for a node that has linked fields (e.g.\n * generate-image stores both `provider` AND `model`), derive the linked\n * fields so the resolver writes a coherent snapshot.\n *\n * For unmapped providers, returns `{}` — the runtime config panel applies\n * its own defaulting when needed.\n */\nconst GENERATE_IMAGE_PROVIDER_TO_MODEL: Record<string, string> = {\n \"nano-banana\": \"gemini-2.5-flash-image\",\n \"nano-banana-pro\": \"gemini-2.5-flash-image\",\n \"nano-banana-2\": \"gemini-2.5-flash-image\",\n}\n\nexport function deriveLinkedFields(\n nodeType: NodeDefaultType,\n value: string,\n): Record<string, unknown> {\n if (nodeType === \"generate-image\") {\n const model = GENERATE_IMAGE_PROVIDER_TO_MODEL[value]\n return model ? { model } : {}\n }\n return {}\n}\n","/**\n * Per-node-type list of field names eligible for fieldMappings resolution.\n * Text fields also participate in {} injection when the resolver sees a\n * string value containing {} markers; non-text fields just receive the\n * mapped source's value verbatim.\n */\nexport const NODE_MAPPABLE_FIELDS: Readonly<Record<string, readonly string[]>> = {\n \"generate-image\": [\"prompt\", \"style\", \"negativePrompt\"],\n \"edit-image\": [\"prompt\", \"style\", \"negativePrompt\"],\n \"image-to-image\": [\"prompt\", \"style\", \"negativePrompt\"],\n \"modify-image\": [\"prompt\", \"style\", \"negativePrompt\"],\n \"text-to-video\": [\"prompt\", \"negativePrompt\"],\n \"image-to-video\": [\"prompt\"],\n // Unified t2v/i2v node — replaced the two deprecated keys above (kept only\n // for back-compat with un-migrated workflow JSON). Mirrors text-to-video so\n // fieldMappings/{} injection AND missing-ref detection work on the live node.\n \"generate-video\": [\"prompt\", \"negativePrompt\"],\n \"video-analysis\": [\"analysisFocus\", \"youtubeUrl\"],\n \"video-to-video\": [\"prompt\"],\n \"text-to-speech\": [\"directText\"],\n \"lip-sync\": [\"prompt\"],\n \"generate-music\": [\"prompt\", \"lyrics\", \"genre\", \"mood\"],\n \"text-to-audio\": [\"prompt\"],\n \"suno-generate\": [\"prompt\", \"lyrics\", \"style\", \"title\", \"negativeStyle\"],\n \"suno-cover\": [\"prompt\", \"lyrics\", \"style\", \"title\", \"negativeStyle\"],\n \"suno-extend\": [\"prompt\", \"style\", \"title\"],\n \"suno-lyrics\": [\"prompt\"],\n \"suno-replace-section\":[\"prompt\", \"tags\", \"title\"],\n \"suno-style-boost\": [\"content\"],\n \"suno-upload-extend\": [\"prompt\", \"style\", \"title\"],\n \"suno-mashup\": [\"style\", \"title\", \"negativeStyle\"],\n \"voice-remix\": [\"voiceDescription\", \"text\"],\n \"voice-design\": [\"voiceDescription\", \"text\"],\n \"forced-alignment\": [\"transcript\"],\n \"ai-writer\": [\"systemPrompt\", \"userInput\"],\n \"llm-chat\": [\"systemPrompt\", \"userInput\"],\n \"video-composer\": [\"compositionPrompt\"],\n \"after-effects\": [\"effectPrompt\"],\n \"lottie-overlay\": [\"overlayPrompt\"],\n \"3d-title\": [\"titlePrompt\"],\n \"motion-graphics\": [\"motionPrompt\"],\n \"generate-script\": [\"styleGuide\"],\n \"speech-to-video\": [\"prompt\", \"negativePrompt\"],\n \"extend-video\": [\"prompt\"],\n \"motion-transfer\": [\"prompt\"],\n \"cinematic-avatar\": [\"prompt\"],\n \"image-to-text\": [\"customPrompt\"],\n \"instagram-post\": [\"caption\", \"title\"],\n \"tiktok-post\": [\"caption\", \"title\"],\n \"youtube-upload\": [\"caption\", \"title\"],\n \"linkedin-post\": [\"caption\", \"title\"],\n \"x-post\": [\"caption\", \"title\"],\n \"facebook-post\": [\"caption\", \"title\"],\n \"telegram-post\": [\"caption\", \"title\"],\n \"save-to-storage\": [\"filename\"],\n \"webhook-output\": [\"url\"],\n \"character\": [\"characterName\", \"description\", \"baseOutfit\"],\n \"face\": [\"faceName\", \"description\"],\n \"object\": [\"objectName\", \"description\"],\n \"creature\": [\"creatureName\", \"description\"],\n \"location\": [\"locationName\", \"description\"],\n \"web-scrape\": [\"query\", \"url\", \"target\"],\n}\n\n/** suno-generate secondary text fields exposed as `field-<key>` canvas handles. */\nexport const SUNO_FIELD_HANDLE_FIELDS = [\"style\", \"lyrics\", \"title\", \"negativeStyle\"] as const\n/** Map a `field-<key>` handle id to its data key, or null if not a field handle. */\nexport function fieldKeyFromHandle(handleId: string): string | null {\n return handleId.startsWith(\"field-\") ? handleId.slice(\"field-\".length) : null\n}\n","export const SCRAPER_ACTOR_IDS = [\n \"content-crawler\",\n \"google-search\",\n \"instagram\",\n \"tiktok\",\n \"rss\",\n] as const\n\nexport type ScraperActorId = (typeof SCRAPER_ACTOR_IDS)[number]\n\nexport const SCRAPER_ACTOR_LABELS: Record<ScraperActorId, string> = {\n \"content-crawler\": \"Website Content (Markdown)\",\n \"google-search\": \"Google Search\",\n \"instagram\": \"Instagram\",\n \"tiktok\": \"TikTok\",\n \"rss\": \"RSS Feed\",\n}\n\n/** Credit costs per composite SKU — must stay in sync with STATIC_CREDIT_COSTS in backend. */\nexport const SCRAPER_CREDIT_COSTS: Record<string, number> = {\n \"web-scrape\": 2,\n \"web-scrape:google-search\": 3,\n \"web-scrape:content-crawler\": 1,\n \"web-scrape:content-crawler:site\": 5,\n \"web-scrape:instagram\": 1,\n \"web-scrape:tiktok\": 1,\n \"web-scrape:rss\": 1,\n}\n\nexport function isScraperActor(value: unknown): value is ScraperActorId {\n return typeof value === \"string\" && (SCRAPER_ACTOR_IDS as readonly string[]).includes(value)\n}\n\nexport interface ScraperCreditInput {\n actor: ScraperActorId\n mode?: \"page\" | \"site\"\n}\n\nexport function buildScraperCreditId(input: ScraperCreditInput): string {\n if (input.actor === \"content-crawler\") {\n const mode = input.mode ?? \"page\"\n return mode === \"site\" ? \"web-scrape:content-crawler:site\" : \"web-scrape:content-crawler\"\n }\n return `web-scrape:${input.actor}`\n}\n\n/**\n * Resolve the credit identifier from an unvalidated request body.\n * Falls back to a fixed default SKU (google-search) on missing/invalid actor\n * so misrouted requests reserve a known mid-tier price, not the max-cost tier.\n */\nexport function resolveScraperCreditId(body: unknown): string {\n const raw = body as { actor?: unknown; mode?: unknown } | undefined\n if (!raw || !isScraperActor(raw.actor)) return \"web-scrape:google-search\"\n const mode = raw.mode === \"site\" ? \"site\" : \"page\"\n return buildScraperCreditId({ actor: raw.actor, mode })\n}\n","/**\n * Build a label→output map for `{Node Label}` refs inside condition values\n * on filter-list and router nodes.\n *\n * Only considers edges whose `targetHandle === VARIABLES_HANDLE_ID` — the\n * dedicated condition-variables input handle. Data-flow edges (targetHandle\n * `\"in\"`, column handles, etc.) are ignored, so variable sources never\n * influence the filtered/routed list.\n *\n * Duplicate labels are suffixed `Same`, `Same (2)`, `Same (3)` — matches\n * the convention in `buildNodeRefMap` (frontend) / `buildNodeRefsMap`\n * (backend) for text-prompt refs.\n */\n\nexport const VARIABLES_HANDLE_ID = \"variables\"\n\ntype EdgeShape = {\n source: string\n target: string\n sourceHandle?: string | null\n targetHandle?: string | null\n}\n\ntype NodeShape = {\n id: string\n type?: string\n data: Record<string, unknown>\n}\n\nexport function buildConditionVariables<\n E extends EdgeShape,\n N extends NodeShape,\n>(\n targetNodeId: string,\n edges: ReadonlyArray<E>,\n nodes: ReadonlyArray<N>,\n extractOutput: (node: N) => string | undefined,\n): Map<string, string> {\n const pairs: Array<{ label: string; output: string }> = []\n for (const edge of edges) {\n if (edge.target !== targetNodeId) continue\n if (edge.targetHandle !== VARIABLES_HANDLE_ID) continue\n const src = nodes.find((n) => n.id === edge.source)\n if (!src) continue\n const output = extractOutput(src)\n if (output === undefined || output === \"\") continue\n const label = (src.data.label as string) || src.type || src.id\n pairs.push({ label, output })\n }\n\n const map = new Map<string, string>()\n const counts = new Map<string, number>()\n for (const { label } of pairs) counts.set(label, (counts.get(label) ?? 0) + 1)\n const seen = new Map<string, number>()\n for (const { label, output } of pairs) {\n let key = label\n if ((counts.get(label) ?? 0) > 1) {\n const n = (seen.get(label) ?? 0) + 1\n seen.set(label, n)\n if (n > 1) key = `${label} (${n})`\n }\n map.set(key, output)\n }\n return map\n}\n","/**\n * Helpers for reading a node's accumulated `generatedResults` array.\n *\n * Used by both frontend DAG executor (`node-input-resolver.ts`) and backend\n * orchestrator (`output-extractor.ts`) so they agree on when a node has\n * upstream-consumable output.\n */\n\n/**\n * Extract all output values from a node's accumulated generatedResults.\n * Returns the full flat list (any length). Returns undefined only when empty.\n */\nexport function extractAllGeneratedResults(\n data: Record<string, unknown>,\n): string[] | undefined {\n const results = data.generatedResults as\n | Array<{ url?: string; text?: string }>\n | undefined\n if (!results || results.length === 0) return undefined\n const outputs = results\n .map((r) => r.url || r.text || \"\")\n .filter((v) => v.length > 0)\n return outputs.length > 0 ? outputs : undefined\n}\n\n/**\n * Extract a JSON array (e.g. web-scrape `generatedJson`) as a list of strings.\n * Each array element is stringified; already-string elements pass through.\n */\nexport function extractGeneratedJsonAsList(\n data: Record<string, unknown>,\n): string[] | undefined {\n const jsonArr = data.generatedJson\n if (!Array.isArray(jsonArr) || jsonArr.length === 0) return undefined\n return jsonArr.map((item: unknown) =>\n typeof item === \"string\" ? item : JSON.stringify(item),\n )\n}\n\n/**\n * If a collected item list has a single entry whose contents parse to a\n * non-empty JSON array, spread the array's elements into separate items.\n * Mirrors the `output.json` spread in the orchestrator so a list node with\n * one row holding a JSON array feeds filter-list / deduplicate / sort-list /\n * merge-lists per-element instead of as one giant stringified blob.\n */\nexport function spreadJsonArrayIfSingleton(items: string[]): string[] {\n if (items.length !== 1) return items\n const single = items[0]\n if (typeof single !== \"string\") return items\n const trimmed = single.trim()\n if (!trimmed.startsWith(\"[\")) return items\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch {\n return items\n }\n if (!Array.isArray(parsed) || parsed.length === 0) return items\n return parsed.map((el) =>\n typeof el === \"string\" ? el : JSON.stringify(el),\n )\n}\n","/**\n * Lottie slot substitution — single source of truth (design §5).\n *\n * A slotted property is an object containing a `sid` key (canonically exactly\n * `{\"sid\": \"name\"}`; tolerantly also the annotation form `{a, k, sid}`). The\n * slot manifest maps sid → { p: <whatever belongs at the reference position> }.\n * Overrides map sid → raw value (what UI controls write).\n *\n * KEY CONVENTION: a slot's `p` is, by design, EXACTLY what belongs at the\n * reference position — and we substitute it VERBATIM, never auto-wrapping it in\n * an `{a:0,k:...}` envelope. At a property position (a fill color, a shape size)\n * that means `p` is a property object like `{\"a\":0,\"k\":[1,0,0,1]}`. At a RAW\n * position inside a text document — `layers[].t.d.k[0].s.t`, where lottie-web's\n * `buildFinalText` iterates string characters — `p` is a BARE string, e.g.\n * `{ \"nameText\": { \"p\": \"John Smith\" } }` substitutes the string `\"John Smith\"`\n * straight onto `s.t`. (Auto-wrapping there produced `{a:0,k:\"John Smith\"}` and\n * broke text rendering — the defect this contract fixes.)\n *\n * An override is wrapped ONLY when it lands on a property-object default: the\n * `{...p, k: override}` form preserves the default's envelope (animated/static\n * flags). On a raw default (or a missing slot) the override is substituted\n * verbatim too — so a raw text override stays a bare string.\n *\n * Substitution is renderer-agnostic: we replace every sid node ourselves and\n * never rely on lottie-web's version-dependent native slot support.\n */\n\ntype JsonRecord = Record<string, unknown>\n\nfunction isPlainObject(v: unknown): v is JsonRecord {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\n/** True when `p` already looks like a lottie animated-property object. */\nfunction isPropertyObject(v: unknown): v is JsonRecord {\n return isPlainObject(v) && \"k\" in v\n}\n\nfunction resolveSlotNode(\n node: JsonRecord,\n slots: JsonRecord,\n overrides: JsonRecord,\n): unknown {\n const sid = node.sid as string\n const slot = slots[sid]\n const slotP = isPlainObject(slot) ? (slot as JsonRecord).p : undefined\n const override = overrides[sid]\n\n if (override !== undefined) {\n // Wrap into the default's property-object envelope when the default IS one\n // (preserves animated/static flags); otherwise substitute the raw override\n // verbatim — a raw text override must stay a bare string at `s.t`.\n if (isPropertyObject(slotP)) return { ...slotP, k: structuredClone(override) }\n return structuredClone(override)\n }\n if (slotP !== undefined) {\n // `p` is by convention exactly what belongs at the reference position —\n // substitute it verbatim, never auto-wrap (a bare string stays a string).\n return structuredClone(slotP)\n }\n // No slot, no override — leave the node as-is (validator rule #6 should\n // prevent this; belt-and-braces for hand-fed documents).\n return node\n}\n\nfunction walk(value: unknown, slots: JsonRecord, overrides: JsonRecord): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => walk(item, slots, overrides))\n }\n if (isPlainObject(value)) {\n if (typeof value.sid === \"string\") {\n const resolved = resolveSlotNode(value, slots, overrides)\n // The original node comes back only in the missing-slot case; replacements\n // are leaf property objects and need no further walking.\n if (resolved === value) {\n const copy: JsonRecord = {}\n for (const [k, v] of Object.entries(value)) copy[k] = walk(v, slots, overrides)\n return copy\n }\n return resolved\n }\n const copy: JsonRecord = {}\n for (const [k, v] of Object.entries(value)) copy[k] = walk(v, slots, overrides)\n return copy\n }\n return value\n}\n\n/** Pure: returns a new document; never mutates inputs. */\nexport function applySlots(\n lottie: JsonRecord,\n slots: JsonRecord | undefined,\n overrides: JsonRecord | undefined,\n): JsonRecord {\n return walk(lottie, slots ?? {}, overrides ?? {}) as JsonRecord\n}\n\n// ── Playback normalization ───────────────────────────────────────────────────\n//\n// lottie-web computes a layer's local time as `frame - layer.st` and gates the\n// layer on `local >= ip && local < op`. A layer missing `st` yields NaN, fails\n// the gate, and stays `display:none` forever — the document \"loads\" (DOMLoaded\n// fires) but every frame renders blank (prod incident 2026-06-12: all authored\n// lottie renders came out as empty frames in headless Chrome). `st` and `sr`\n// are spec-optional with defaults, so documents routinely omit them; complete\n// them at the playback boundary so any source — authored plan, baked export,\n// catalog asset, external URL — renders. Mutates `doc` in place and returns it\n// (callers pass freshly fetched or freshly copied documents).\n\nexport function normalizeLottieLayers<T>(doc: T): T {\n if (!isPlainObject(doc)) return doc\n const fix = (layers: unknown): void => {\n if (!Array.isArray(layers)) return\n for (const layer of layers) {\n if (!isPlainObject(layer)) continue\n if (typeof layer.st !== \"number\") layer.st = 0\n if (typeof layer.sr !== \"number\") layer.sr = 1\n }\n }\n fix((doc as JsonRecord).layers)\n const assets = (doc as JsonRecord).assets\n if (Array.isArray(assets)) {\n for (const asset of assets) {\n if (isPlainObject(asset)) fix(asset.layers)\n }\n }\n return doc\n}\n\n// ── Slot control descriptors (Phase 2 — UI mapping) ──────────────────────────\n//\n// A slot manifest entry is `{ p: <whatever belongs at the reference position> }`\n// (Amendment 1). `describeSlotControl` unwraps that envelope to the editable raw\n// value and classifies it into the control kind the config panel should render.\n// `p` is either a property object `{a, k}` (colors, sizes, scalars) whose `k`\n// holds the value, or a bare raw value (text strings live unwrapped at `s.t`).\n\nexport type SlotControlKind = \"color\" | \"text\" | \"number\" | \"point\"\nexport interface SlotControlDescriptor {\n kind: SlotControlKind\n value: unknown\n}\n\n/**\n * Unwraps a slot entry to its editable raw value and classifies it:\n * {p:{a:0,k:[1,0,0,1]}} → { kind:\"color\", value:[1,0,0,1] }\n * {p:\"John\"} → { kind:\"text\", value:\"John\" }\n * {p:{a:0,k:42}} → { kind:\"number\", value:42 }\n * {p:{a:0,k:[10,20]}} → { kind:\"point\", value:[10,20] }\n * Animated property objects (`a:1`) and anything that doesn't map to a known\n * control kind return null (no editable control).\n */\nexport function describeSlotControl(slot: unknown): SlotControlDescriptor | null {\n if (!isPlainObject(slot)) return null\n const p = (slot as JsonRecord).p\n let value: unknown = p\n if (isPropertyObject(p)) {\n if ((p as JsonRecord).a === 1) return null\n value = (p as JsonRecord).k\n }\n if (typeof value === \"string\") return { kind: \"text\", value }\n if (typeof value === \"number\") return { kind: \"number\", value }\n if (\n Array.isArray(value) &&\n value.length === 4 &&\n value.every((n) => typeof n === \"number\" && n >= 0 && n <= 1)\n ) {\n return { kind: \"color\", value }\n }\n if (Array.isArray(value) && value.length === 2 && value.every((n) => typeof n === \"number\")) {\n return { kind: \"point\", value }\n }\n return null\n}\n\nfunction clamp01(n: number): number {\n if (Number.isNaN(n)) return 0\n return n < 0 ? 0 : n > 1 ? 1 : n\n}\n\nfunction toHexByte(component: number): string {\n return Math.round(clamp01(component) * 255)\n .toString(16)\n .padStart(2, \"0\")\n}\n\n/**\n * RGBA array (components 0..1) → hex string. The alpha component is omitted\n * when it is exactly 1 (`[1,0,0,1]` → `\"#ff0000\"`); otherwise an 8-digit hex is\n * emitted (`[0,1,0,0.5]` → `\"#00ff0080\"`). Output is always lowercase.\n */\nexport function rgbaArrayToHex(rgba: number[]): string {\n const [r = 0, g = 0, b = 0, a = 1] = rgba\n const base = `#${toHexByte(r)}${toHexByte(g)}${toHexByte(b)}`\n return a >= 1 ? base : `${base}${toHexByte(a)}`\n}\n\n/**\n * Hex string → RGBA array (components 0..1). Accepts `#rgb`, `#rrggbb`, and\n * `#rrggbbaa`; alpha defaults to 1 when absent. Leading `#` is optional.\n */\nexport function hexToRgbaArray(hex: string): number[] {\n let h = hex.trim().replace(/^#/, \"\")\n if (h.length === 3) {\n h = h\n .split(\"\")\n .map((c) => c + c)\n .join(\"\")\n }\n const r = parseInt(h.slice(0, 2), 16) / 255\n const g = parseInt(h.slice(2, 4), 16) / 255\n const b = parseInt(h.slice(4, 6), 16) / 255\n const a = h.length >= 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1\n return [r, g, b, a]\n}\n\n/** Manifest sids in insertion order (drives the slot-control list ordering). */\nexport function listSlotSids(slots: Record<string, unknown>): string[] {\n return Object.keys(slots ?? {})\n}\n\n// ── Slot → app-field derivation (Phase 3 — single source of truth) ────────────\n//\n// `deriveLottieSlotFields` turns a lottie-graphic plan's slot manifest into\n// ExposableField-shaped descriptors. ONE function feeds three surfaces: the\n// editor's publish picker, the published-app runtime, and the backend MCP\n// schema extractor — so the set of slots an app exposes can never drift between\n// them. It deliberately mirrors `describeSlotControl`'s classification (the\n// editor's live slot controls use the same source of truth).\n\n/** Prefix for the synthetic field key of a derived slot field: `slot:<sid>`. */\nexport const LOTTIE_SLOT_FIELD_PREFIX = \"slot:\"\n\n/** \"primaryColor\" → \"Primary Color\"; \"bar_size\" → \"Bar Size\". */\nexport function humanizeSlotSid(sid: string): string {\n return sid\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[_-]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n .replace(/\\b\\w/g, (c) => c.toUpperCase())\n}\n\n/** ExposableField-shaped descriptor derived from one slot. */\nexport interface LottieSlotField {\n /** Synthetic field key: `slot:<sid>`. */\n key: string\n /** Humanized sid (camelCase / snake_case → Title Case). */\n label: string\n /** Maps onto the `ExposableField.type` members used in apps. */\n type: \"color\" | \"text\" | \"slider\"\n min?: number\n max?: number\n step?: number\n /** Hex string for color; raw value for text/number. */\n defaultValue?: unknown\n}\n\n/**\n * Derive ExposableField-shaped descriptors from a motion-graphics node's plan.\n *\n * Returns [] unless `motionPlan.planType === \"lottie-graphic\"` and `slots` is a\n * non-empty object — the elements engine and absent plans expose nothing.\n *\n * Per slot, via `describeSlotControl`:\n * - color → `{ type: \"color\", defaultValue: rgbaArrayToHex(value) }`\n * - text → `{ type: \"text\", defaultValue: value }`\n * - number → `{ type: \"slider\", min, max, step, defaultValue: value }`\n * (0–1 values → 0..1 step 0.01; larger → 0..ceil(value*2) step 1)\n * - point / null → SKIPPED. Point-kind slots are intentionally not exposed in\n * apps (no paired-number card; positions are rarely end-user-meaningful).\n */\nexport function deriveLottieSlotFields(\n motionPlan: Record<string, unknown> | undefined,\n): LottieSlotField[] {\n if (!motionPlan || motionPlan.planType !== \"lottie-graphic\") return []\n const slots = motionPlan.slots\n if (!isPlainObject(slots)) return []\n\n const fields: LottieSlotField[] = []\n for (const [sid, slot] of Object.entries(slots)) {\n const control = describeSlotControl(slot)\n if (!control) continue\n const base = { key: `${LOTTIE_SLOT_FIELD_PREFIX}${sid}`, label: humanizeSlotSid(sid) }\n\n if (control.kind === \"color\") {\n fields.push({\n ...base,\n type: \"color\",\n defaultValue: rgbaArrayToHex(control.value as number[]),\n })\n } else if (control.kind === \"text\") {\n fields.push({ ...base, type: \"text\", defaultValue: control.value })\n } else if (control.kind === \"number\") {\n const value = Number(control.value)\n const isUnit = value <= 1\n fields.push({\n ...base,\n type: \"slider\",\n min: 0,\n max: isUnit ? 1 : Math.ceil(value * 2) || 100,\n step: isUnit ? 0.01 : 1,\n defaultValue: control.value,\n })\n }\n // point / unrecognized kinds are intentionally not exposed.\n }\n return fields\n}\n","/**\n * Built-in Lottie Overlay catalog — single source of truth.\n *\n * The Lottie Overlay node ships a curated set of 12 animations the overlay LLM\n * can pick from. They were originally served from the third-party lottie.host\n * CDN, which went dead (origin returns 403) and broke every catalog-based\n * overlay render in production. The replacements were authored with our own\n * Lottie engine, baked (slots resolved, no `sid` refs), and are now self-hosted\n * on the Nodaro CDN at `https://cdn.nodaro.ai/lottie-catalog/<slug>.json`.\n *\n * This module is the ONE place the catalog lives:\n * - `LOTTIE_OVERLAY_CATALOG` feeds the overlay system prompt (the LLM's menu).\n * - `LEGACY_LOTTIE_HOST_REMAP` + `resolveLottieOverlaySrc` heal saved overlay\n * plans at render time — a plan authored before the cut-over still points at\n * a dead lottie.host URL, so the renderer rewrites it to its self-hosted\n * replacement before fetching.\n */\n\nexport interface LottieOverlayCatalogEntry {\n /** Stable system key — the R2 object is `lottie-catalog/<slug>.json`. */\n readonly slug: string\n /** Display name — mirrors the original prompt's catalog labels. */\n readonly name: string\n /** Catalog group (drives the grouped layout in the system prompt). */\n readonly group:\n | \"Celebration\"\n | \"Social / Reactions\"\n | \"UI / Indicators\"\n | \"Ambient / Decorative\"\n /** One placement-intent line for the overlay LLM. */\n readonly description: string\n /** Public CDN URL: `https://cdn.nodaro.ai/lottie-catalog/<slug>.json`. */\n readonly url: string\n /** Whether the animation is continuous (loop) or a one-shot effect. */\n readonly loop: boolean\n}\n\nconst CDN_BASE = \"https://cdn.nodaro.ai/lottie-catalog\"\n\nexport const LOTTIE_OVERLAY_CATALOG: readonly LottieOverlayCatalogEntry[] = [\n // ── Celebration ────────────────────────────────────────────────────────────\n {\n slug: \"confetti-burst\",\n name: \"Confetti burst\",\n group: \"Celebration\",\n description: \"Multicolor confetti shower — large coverage at a celebratory peak; one-shot.\",\n url: `${CDN_BASE}/confetti-burst.json`,\n loop: false,\n },\n {\n slug: \"fireworks\",\n name: \"Fireworks\",\n group: \"Celebration\",\n description: \"Bursting fireworks against the sky — big-moment payoff over the upper frame; one-shot.\",\n url: `${CDN_BASE}/fireworks.json`,\n loop: false,\n },\n {\n slug: \"party-popper\",\n name: \"Party popper\",\n group: \"Celebration\",\n description: \"Party popper streamers from a corner — a quick celebratory accent; one-shot.\",\n url: `${CDN_BASE}/party-popper.json`,\n loop: false,\n },\n {\n slug: \"stars-sparkle\",\n name: \"Stars sparkle\",\n group: \"Celebration\",\n description: \"Twinkling stars/sparkles — small accent over a highlight; loops.\",\n url: `${CDN_BASE}/stars-sparkle.json`,\n loop: true,\n },\n // ── Social / Reactions ──────────────────────────────────────────────────────\n {\n slug: \"heart-pulse\",\n name: \"Heart pulse\",\n group: \"Social / Reactions\",\n description: \"Pulsing heart reaction — medium size at a corner or edge; loops.\",\n url: `${CDN_BASE}/heart-pulse.json`,\n loop: true,\n },\n {\n slug: \"thumbs-up\",\n name: \"Thumbs up\",\n group: \"Social / Reactions\",\n description: \"Thumbs-up approval reaction — medium size, pops in once; one-shot.\",\n url: `${CDN_BASE}/thumbs-up.json`,\n loop: false,\n },\n {\n slug: \"fire-flame\",\n name: \"Fire emoji\",\n group: \"Social / Reactions\",\n description: \"Flickering flame reaction (“this is fire”) — small size at an edge; loops.\",\n url: `${CDN_BASE}/fire-flame.json`,\n loop: true,\n },\n // ── UI / Indicators ─────────────────────────────────────────────────────────\n {\n slug: \"loading-spinner\",\n name: \"Loading spinner\",\n group: \"UI / Indicators\",\n description: \"Circular loading spinner — small, centered, signals progress; loops.\",\n url: `${CDN_BASE}/loading-spinner.json`,\n loop: true,\n },\n {\n slug: \"checkmark-success\",\n name: \"Checkmark success\",\n group: \"UI / Indicators\",\n description: \"Animated success checkmark — small, marks a completed/correct moment; one-shot.\",\n url: `${CDN_BASE}/checkmark-success.json`,\n loop: false,\n },\n {\n slug: \"arrow-pointer\",\n name: \"Arrow pointer\",\n group: \"UI / Indicators\",\n description: \"Animated arrow drawing attention to a spot — small, timed to a key area; loops.\",\n url: `${CDN_BASE}/arrow-pointer.json`,\n loop: true,\n },\n // ── Ambient / Decorative ────────────────────────────────────────────────────\n {\n slug: \"floating-particles\",\n name: \"Floating particles\",\n group: \"Ambient / Decorative\",\n description: \"Soft drifting particles — large coverage, low opacity, full-duration ambience; loops.\",\n url: `${CDN_BASE}/floating-particles.json`,\n loop: true,\n },\n {\n slug: \"glowing-ring\",\n name: \"Glowing ring\",\n group: \"Ambient / Decorative\",\n description: \"Pulsing glowing ring/halo — decorative accent around a focal point; loops.\",\n url: `${CDN_BASE}/glowing-ring.json`,\n loop: true,\n },\n] as const\n\n/**\n * Dead lottie.host URLs (origin returns 403) → their replacement catalog URLs.\n * Heals saved plans at render time. The keys are copied EXACTLY from the\n * original `lottie-overlay-system.ts` prompt — they are the literal `src`\n * strings the overlay LLM emitted before the cut-over.\n */\nexport const LEGACY_LOTTIE_HOST_REMAP: Readonly<Record<string, string>> = {\n // Celebration\n \"https://lottie.host/d7313e87-e4c9-4e0d-8e03-c3a59e87d8fb/TjHnrCGBjI.json\": `${CDN_BASE}/confetti-burst.json`,\n \"https://lottie.host/d5cad0dd-4e93-4bbe-b023-e94a04bc1581/JHEZMrqfMk.json\": `${CDN_BASE}/fireworks.json`,\n \"https://lottie.host/0060c9cd-75da-42d5-af7c-1a191fa8a8fd/c1xHMRnGTO.json\": `${CDN_BASE}/party-popper.json`,\n \"https://lottie.host/c04a2758-a1d9-40a9-b81f-6f3e4e13a88c/xKCYDU2w0O.json\": `${CDN_BASE}/stars-sparkle.json`,\n // Social / Reactions\n \"https://lottie.host/44c9e8d1-856c-4641-bfbe-d0e2a5c9850e/GIBsMSIkkq.json\": `${CDN_BASE}/heart-pulse.json`,\n \"https://lottie.host/9a611d56-1f35-4f51-9fa4-6a4daa6b8714/EH71MjHKPD.json\": `${CDN_BASE}/thumbs-up.json`,\n \"https://lottie.host/66db1de9-c1a8-4d0b-bb03-47a8932a8a86/q5JBGQ8fxu.json\": `${CDN_BASE}/fire-flame.json`,\n // UI / Indicators\n \"https://lottie.host/b03d748c-3b4a-4c07-a10c-e9eb3c967349/eMVAVEnb5x.json\": `${CDN_BASE}/loading-spinner.json`,\n \"https://lottie.host/3ffaab4a-58b0-4a72-9f1c-5eaa484d8c88/g27v7IPaJc.json\": `${CDN_BASE}/checkmark-success.json`,\n \"https://lottie.host/6f831c6e-693a-4d1d-90a0-d7e2b3f00e68/PFj0MwSPrj.json\": `${CDN_BASE}/arrow-pointer.json`,\n // Ambient / Decorative\n \"https://lottie.host/9c8e1aef-f8e5-4ce8-bc80-1647ffb0724d/mNDClfKJVB.json\": `${CDN_BASE}/floating-particles.json`,\n \"https://lottie.host/b5d3e7e7-40bc-44fa-9a53-78b98ad66e80/pQVdNsVDmQ.json\": `${CDN_BASE}/glowing-ring.json`,\n}\n\n/**\n * Resolve an overlay `src` through the legacy remap: a dead lottie.host URL is\n * rewritten to its self-hosted replacement; everything else (already-migrated\n * catalog URLs, user-provided assets) passes through unchanged.\n */\nexport function resolveLottieOverlaySrc(src: string): string {\n return LEGACY_LOTTIE_HOST_REMAP[src] ?? src\n}\n","/**\n * Replace {} placeholders in a field value with upstream text.\n *\n * ONLY handles {} injection. Does NOT inject into empty fields.\n * Empty-field fallback (d.prompt || inputs.prompt) stays in per-node\n * execution code — the resolver doesn't decide which field is \"primary.\"\n */\nexport function injectUpstream(\n fieldValue: string | undefined,\n upstream: string | undefined,\n): string | undefined {\n if (!fieldValue || !upstream) return fieldValue\n if (fieldValue.includes(\"{}\")) return fieldValue.replaceAll(\"{}\", upstream)\n return fieldValue\n}\n","import { injectUpstream } from \"./inject-upstream.js\"\n\n/**\n * Resolve fieldMappings + {} injection for all text fields on a node.\n *\n * Three resolution mechanisms, in precedence order per field:\n * 1. edge source: a live edge into the field's handle → use that node's\n * output. Prefix-agnostic — the caller decides which edges map to which\n * field (e.g. FE/BE wrappers match `field-<key>` handles). Wins over both\n * fieldMappings and {} injection.\n * 2. fieldMappings: field mapped to source node → use that node's output\n * 3. {} injection: manual field contains {} → replace with upstreamText\n *\n * Does NOT inject upstream into empty unmapped fields — that stays in\n * per-node execution code (e.g., d.prompt || inputs.prompt).\n *\n * The `getSourceOutput` callback abstracts how source node output is\n * extracted — frontend reads from live React Flow state, backend reads\n * from NodeExecutionState.output. Same pattern as ancestor-refs.ts.\n *\n * `edgeSourceForField` is optional: when omitted, behaviour is identical to\n * the prior fieldMappings-only resolver (existing callers stay valid).\n */\nexport function resolveFieldMappings(\n data: Record<string, unknown>,\n upstreamText: string | undefined,\n mappableFieldNames: ReadonlyArray<string>,\n getSourceOutput: (sourceNodeId: string) => string | undefined,\n edgeSourceForField?: (field: string) => string | undefined,\n): Record<string, unknown> {\n const fm = data.fieldMappings as Record<string, { sourceNodeId: string }> | undefined\n const resolved = { ...data }\n\n for (const field of mappableFieldNames) {\n const sourceNodeId = edgeSourceForField?.(field) ?? fm?.[field]?.sourceNodeId\n\n if (sourceNodeId) {\n const output = getSourceOutput(sourceNodeId)\n if (output != null) resolved[field] = output\n } else {\n const current = resolved[field]\n if (typeof current === \"string\") {\n const injected = injectUpstream(current, upstreamText)\n if (injected !== current) resolved[field] = injected\n }\n }\n }\n\n return resolved\n}\n\n/**\n * Location buckets that may carry generated/uploaded variants. Mirrors the\n * full set of attachable buckets in `entity-prompts.ts::LOCATION_ATTACH_COLUMNS`,\n * but in camelCase (matching the in-memory location object and the\n * `WorkflowExportLocation` export shape).\n */\nconst LOCATION_BUCKETS = [\n \"timeOfDay\",\n \"weather\",\n \"seasons\",\n \"angles\",\n \"lighting\",\n \"atmosphereMotions\",\n] as const\n\ninterface LocationFieldEntry {\n /** Stable key — `sourceImageUrl` or `<bucket>[<index>]`. */\n key: string\n /** Human-readable label — `Main image` or `<bucket> / <variant.name>`. */\n label: string\n /** R2 URL of the image. */\n url: string\n}\n\n/**\n * Flatten a location's anchor image and every variant bucket into a single\n * ordered list of `{ key, label, url }` entries. Used by picker UIs and\n * ref-resolvers that need a stable, position-keyed view of every image\n * attached to a location.\n *\n * Bucket iteration order is fixed (see `LOCATION_BUCKETS`) so frontend and\n * backend produce identical lists from the same fixture. Missing buckets and\n * non-array values are treated as empty — the helper never throws.\n *\n * Mirrors the future character/object variants of this helper; same shape\n * (`key`, `label`, `url`) so callers can be polymorphic over entity kind.\n */\nexport function resolveLocationFields(\n loc: Record<string, unknown>,\n): LocationFieldEntry[] {\n const out: LocationFieldEntry[] = []\n\n if (typeof loc.sourceImageUrl === \"string\" && loc.sourceImageUrl.length > 0) {\n out.push({\n key: \"sourceImageUrl\",\n label: \"Main image\",\n url: loc.sourceImageUrl,\n })\n }\n\n for (const bucket of LOCATION_BUCKETS) {\n const raw = loc[bucket]\n if (!Array.isArray(raw)) continue\n raw.forEach((item, i) => {\n if (!item || typeof item !== \"object\") return\n const variant = item as { name?: unknown; url?: unknown }\n if (typeof variant.url !== \"string\" || variant.url.length === 0) return\n const name = typeof variant.name === \"string\" ? variant.name : \"\"\n out.push({\n key: `${bucket}[${i}]`,\n label: `${bucket} / ${name}`,\n url: variant.url,\n })\n })\n }\n\n return out\n}\n","/**\n * Follow a list node's `in` edge chain to its effective upstream source.\n *\n * When a `list` node has no manual rows but an incoming connection, the UI\n * renders its upstream's items (see list-node.tsx's `connectedItems ??\n * staticItems`). Without this helper, downstream readers would see an empty\n * list because `extractSourceNodeOutput` for `list` only reads `data.rows`.\n *\n * Shared between the frontend DAG executor (`node-input-resolver.ts`) and\n * the backend orchestrator (`inline-executor.ts`) so both paths resolve\n * list-connected-mode identically.\n */\n\ntype EdgeShape = {\n source: string\n target: string\n sourceHandle?: string | null\n targetHandle?: string | null\n}\n\ntype NodeShape = {\n id: string\n type?: string\n data: Record<string, unknown>\n}\n\nfunction hasAnyRow(rows: string[][]): boolean {\n return rows.some((r) => r.some((v) => v?.trim()))\n}\n\nexport function resolveSourceThroughConnectedList<\n E extends EdgeShape,\n N extends NodeShape,\n>(edge: E, nodes: ReadonlyArray<N>, edges: ReadonlyArray<E>): E {\n const visited = new Set<string>()\n let current = edge\n while (true) {\n const src = nodes.find((n) => n.id === current.source)\n if (!src || src.type !== \"list\") return current\n if (visited.has(src.id)) return current\n visited.add(src.id)\n const rows = (src.data.rows as string[][] | undefined) ?? []\n if (hasAnyRow(rows)) return current\n const inEdge = edges.find(\n (e) => e.target === src.id && e.targetHandle === \"in\",\n )\n if (!inEdge) return current\n current = inEdge\n }\n}\n","import { tryParseJson } from \"./filter-condition.js\"\n\n/**\n * Element-wise merge across upstream lists with modulo-wrap.\n *\n * Used by the `merge-lists` node's \"zip\" mode. Each output position i takes\n * `lists[j][i % lists[j].length]` from every input; JSON objects are spread\n * into a single object (later sources override earlier ones on key conflicts),\n * non-object items are stringified and concatenated.\n *\n * Length semantics mirror the DAG's existing fan-out behavior: the result\n * length equals `max(len)` across non-empty inputs. Shorter inputs cycle.\n * This means a single-item upstream (e.g. a JSON-process node emitting one\n * object, or a list with one row) is automatically injected into every\n * element of a longer list.\n */\nexport function zipMergeLists(lists: ReadonlyArray<ReadonlyArray<string>>): string[] {\n const nonEmpty = lists.filter((l) => l.length > 0)\n if (nonEmpty.length === 0) return []\n if (nonEmpty.length === 1) return [...nonEmpty[0]]\n\n const maxLen = Math.max(...nonEmpty.map((l) => l.length))\n const out: string[] = []\n for (let i = 0; i < maxLen; i++) {\n const merged: Record<string, unknown> = {}\n const rawItems: string[] = []\n let hasObject = false\n for (const list of nonEmpty) {\n const item = list[i % list.length]\n rawItems.push(item)\n const parsed = tryParseJson(item)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n hasObject = true\n Object.assign(merged, parsed as Record<string, unknown>)\n }\n }\n out.push(hasObject ? JSON.stringify(merged) : rawItems.join(\"\"))\n }\n return out\n}\n","export type SocialMediaPlatform = \"instagram\" | \"tiktok\" | \"x\" | \"youtube\" | \"facebook\" | \"linkedin\" | \"telegram\"\n\nexport type SocialMediaContentType =\n | \"feed-square\" | \"feed-portrait\" | \"feed-landscape\" | \"story-reel\" // Instagram\n | \"video\" // TikTok\n | \"image-landscape\" | \"image-square\" | \"x-video\" // X\n | \"short\" // YouTube\n | \"fb-feed-portrait\" | \"reel\" // Facebook\n | \"li-image-landscape\" | \"li-image-square\" | \"li-video\" // LinkedIn\n\nexport interface SocialMediaSpec {\n readonly platform: SocialMediaPlatform\n readonly contentType: SocialMediaContentType\n readonly label: string\n readonly width: number\n readonly height: number\n readonly maxDurationSeconds: number | null // null = image only (no duration limit)\n readonly textLimit: number\n readonly isVideo: boolean\n}\n\nexport const PLATFORM_SPECS: Record<string, SocialMediaSpec> = {\n \"instagram:feed-square\": {\n platform: \"instagram\", contentType: \"feed-square\", label: \"Feed Square\",\n width: 1080, height: 1080, maxDurationSeconds: 60, textLimit: 2200, isVideo: true,\n },\n \"instagram:feed-portrait\": {\n platform: \"instagram\", contentType: \"feed-portrait\", label: \"Feed Portrait\",\n width: 1080, height: 1350, maxDurationSeconds: 60, textLimit: 2200, isVideo: true,\n },\n \"instagram:feed-landscape\": {\n platform: \"instagram\", contentType: \"feed-landscape\", label: \"Feed Landscape\",\n width: 1080, height: 566, maxDurationSeconds: 60, textLimit: 2200, isVideo: true,\n },\n \"instagram:story-reel\": {\n platform: \"instagram\", contentType: \"story-reel\", label: \"Story / Reel\",\n width: 1080, height: 1920, maxDurationSeconds: 180, textLimit: 2200, isVideo: true,\n },\n \"tiktok:video\": {\n platform: \"tiktok\", contentType: \"video\", label: \"Video\",\n width: 1080, height: 1920, maxDurationSeconds: 600, textLimit: 4000, isVideo: true,\n },\n \"x:image-landscape\": {\n platform: \"x\", contentType: \"image-landscape\", label: \"Image Landscape\",\n width: 1200, height: 675, maxDurationSeconds: null, textLimit: 280, isVideo: false,\n },\n \"x:image-square\": {\n platform: \"x\", contentType: \"image-square\", label: \"Image Square\",\n width: 1080, height: 1080, maxDurationSeconds: null, textLimit: 280, isVideo: false,\n },\n \"x:x-video\": {\n platform: \"x\", contentType: \"x-video\", label: \"Video\",\n width: 1920, height: 1080, maxDurationSeconds: 140, textLimit: 280, isVideo: true,\n },\n \"youtube:short\": {\n platform: \"youtube\", contentType: \"short\", label: \"Short\",\n width: 1080, height: 1920, maxDurationSeconds: 180, textLimit: 5000, isVideo: true,\n },\n \"facebook:fb-feed-portrait\": {\n platform: \"facebook\", contentType: \"fb-feed-portrait\", label: \"Feed Portrait\",\n width: 1080, height: 1350, maxDurationSeconds: null, textLimit: 63206, isVideo: false,\n },\n \"facebook:reel\": {\n platform: \"facebook\", contentType: \"reel\", label: \"Reel\",\n width: 1080, height: 1920, maxDurationSeconds: 90, textLimit: 63206, isVideo: true,\n },\n \"linkedin:li-image-landscape\": {\n platform: \"linkedin\", contentType: \"li-image-landscape\", label: \"Image Landscape\",\n width: 1200, height: 627, maxDurationSeconds: null, textLimit: 3000, isVideo: false,\n },\n \"linkedin:li-image-square\": {\n platform: \"linkedin\", contentType: \"li-image-square\", label: \"Image Square\",\n width: 1080, height: 1080, maxDurationSeconds: null, textLimit: 3000, isVideo: false,\n },\n \"linkedin:li-video\": {\n platform: \"linkedin\", contentType: \"li-video\", label: \"Video\",\n width: 1920, height: 1080, maxDurationSeconds: 600, textLimit: 3000, isVideo: true,\n },\n}\n\nexport const CONTENT_TYPES_BY_PLATFORM: Record<SocialMediaPlatform, ReadonlyArray<{ key: string; label: string }>> = {\n instagram: [\n { key: \"instagram:feed-square\", label: \"Feed Square (1080×1080)\" },\n { key: \"instagram:feed-portrait\", label: \"Feed Portrait (1080×1350)\" },\n { key: \"instagram:feed-landscape\", label: \"Feed Landscape (1080×566)\" },\n { key: \"instagram:story-reel\", label: \"Story / Reel (1080×1920)\" },\n ],\n tiktok: [\n { key: \"tiktok:video\", label: \"Video (1080×1920)\" },\n ],\n x: [\n { key: \"x:image-landscape\", label: \"Image Landscape (1200×675)\" },\n { key: \"x:image-square\", label: \"Image Square (1080×1080)\" },\n { key: \"x:x-video\", label: \"Video (1920×1080)\" },\n ],\n youtube: [\n { key: \"youtube:short\", label: \"Short (1080×1920)\" },\n ],\n facebook: [\n { key: \"facebook:fb-feed-portrait\", label: \"Feed Portrait (1080×1350)\" },\n { key: \"facebook:reel\", label: \"Reel (1080×1920)\" },\n ],\n linkedin: [\n { key: \"linkedin:li-image-landscape\", label: \"Image Landscape (1200×627)\" },\n { key: \"linkedin:li-image-square\", label: \"Image Square (1080×1080)\" },\n { key: \"linkedin:li-video\", label: \"Video (1920×1080)\" },\n ],\n telegram: [\n { key: \"telegram:message\", label: \"Message (text)\" },\n ],\n}\n\nexport const PLATFORM_LABELS: Record<SocialMediaPlatform, string> = {\n instagram: \"Instagram\",\n tiktok: \"TikTok\",\n x: \"X (Twitter)\",\n youtube: \"YouTube\",\n facebook: \"Facebook\",\n linkedin: \"LinkedIn\",\n telegram: \"Telegram\",\n}\n","/**\n * Canonical catalog of animal presets for the Object entity node.\n *\n * When the Object category is \"animal\", users pick a specific animal from this\n * catalog. The picker auto-fills the object's `objectName` and `description`\n * so the existing `buildObjectPrompt` pipeline just works — no backend prompt\n * changes needed.\n *\n * Organized into everyday sub-categories: cats, dogs, transport animals (the\n * rideable / working ones like horse + camel + donkey), farm, wild, birds,\n * sea, small pets, reptiles, and mythical.\n */\n\nexport type AnimalSubcategory =\n | \"cats\"\n | \"dogs\"\n | \"transport\"\n | \"farm\"\n | \"wild\"\n | \"birds\"\n | \"sea\"\n | \"small-pets\"\n | \"reptiles\"\n | \"insects\"\n | \"dinosaurs\"\n | \"mythical\"\n\nexport interface Animal {\n readonly id: string\n readonly label: string\n readonly subcategory: AnimalSubcategory\n readonly description: string\n}\n\nexport const ANIMALS: ReadonlyArray<Animal> = [\n // -------------------- Cats --------------------\n { id: \"cat-persian\", label: \"Persian Cat\", subcategory: \"cats\", description: \"Long-haired cat with a flat face, stocky build and luxurious fluffy coat\" },\n { id: \"cat-siamese\", label: \"Siamese Cat\", subcategory: \"cats\", description: \"Sleek short-haired cat with a cream body, dark points on face, ears, paws and tail, and piercing blue almond-shaped eyes\" },\n { id: \"cat-maine-coon\", label: \"Maine Coon\", subcategory: \"cats\", description: \"Very large long-haired cat with a shaggy ruff, tufted ears and a bushy ringed tail\" },\n { id: \"cat-bengal\", label: \"Bengal Cat\", subcategory: \"cats\", description: \"Muscular athletic cat with a sleek leopard-like rosetted coat in gold and brown\" },\n { id: \"cat-sphynx\", label: \"Sphynx Cat\", subcategory: \"cats\", description: \"Hairless wrinkled cat with large bat-like ears, prominent cheekbones and an elegant muscular frame\" },\n { id: \"cat-ragdoll\", label: \"Ragdoll Cat\", subcategory: \"cats\", description: \"Large semi-long-haired cat with a soft silky coat, color points and vivid blue eyes\" },\n { id: \"cat-british-shorthair\",label: \"British Shorthair\", subcategory: \"cats\", description: \"Plush round-faced cat with a dense blue-grey coat, chubby cheeks and copper eyes\" },\n { id: \"cat-scottish-fold\", label: \"Scottish Fold\", subcategory: \"cats\", description: \"Round-faced cat with small folded ears, a stocky body and big round owl-like eyes\" },\n { id: \"cat-tabby\", label: \"Tabby Cat\", subcategory: \"cats\", description: \"Classic striped short-haired cat with an M mark on the forehead and alert green eyes\" },\n { id: \"cat-black\", label: \"Black Cat\", subcategory: \"cats\", description: \"Sleek all-black short-haired cat with bright yellow-green eyes and a glossy coat\" },\n\n // -------------------- Dogs --------------------\n { id: \"dog-labrador\", label: \"Labrador Retriever\", subcategory: \"dogs\", description: \"Friendly medium-large sporting dog with a short dense coat in yellow, black or chocolate and a thick otter tail\" },\n { id: \"dog-golden-retriever\", label: \"Golden Retriever\", subcategory: \"dogs\", description: \"Medium-large dog with a luxurious wavy golden coat, feathered tail and a warm friendly face\" },\n { id: \"dog-german-shepherd\", label: \"German Shepherd\", subcategory: \"dogs\", description: \"Strong alert working dog with a tan and black saddle coat, erect ears and a bushy tail\" },\n { id: \"dog-bulldog\", label: \"Bulldog\", subcategory: \"dogs\", description: \"Stocky muscular short-haired dog with a wrinkled flat face, wide jaw and loose jowls\" },\n { id: \"dog-poodle\", label: \"Poodle\", subcategory: \"dogs\", description: \"Elegant curly-coated dog with a proud posture and a classic groomed silhouette\" },\n { id: \"dog-husky\", label: \"Siberian Husky\", subcategory: \"dogs\", description: \"Thick double-coated dog with black and white markings, piercing blue or bi-colored eyes and erect triangular ears\" },\n { id: \"dog-beagle\", label: \"Beagle\", subcategory: \"dogs\", description: \"Small tri-color hound with long floppy ears, a short coat and a white-tipped tail\" },\n { id: \"dog-dachshund\", label: \"Dachshund\", subcategory: \"dogs\", description: \"Long low-slung dog with short legs, a deep chest and long drooping ears\" },\n { id: \"dog-chihuahua\", label: \"Chihuahua\", subcategory: \"dogs\", description: \"Tiny toy dog with an apple-shaped head, huge upright ears and big alert eyes\" },\n { id: \"dog-corgi\", label: \"Corgi\", subcategory: \"dogs\", description: \"Short-legged herding dog with a fox-like face, huge upright ears and a plush double coat in red and white\" },\n { id: \"dog-pug\", label: \"Pug\", subcategory: \"dogs\", description: \"Small stocky dog with a deeply wrinkled flat face, curly tail and a fawn coat with a black mask\" },\n { id: \"dog-border-collie\", label: \"Border Collie\", subcategory: \"dogs\", description: \"Agile medium-sized herding dog with a black and white coat, intense stare and feathered tail\" },\n { id: \"dog-rottweiler\", label: \"Rottweiler\", subcategory: \"dogs\", description: \"Powerful muscular dog with a short glossy black coat and distinctive mahogany markings on face, chest and legs\" },\n { id: \"dog-shiba-inu\", label: \"Shiba Inu\", subcategory: \"dogs\", description: \"Compact spitz-type dog with a red-orange coat, curled tail, erect triangular ears and a fox-like face\" },\n\n // -------------------- Transport / Working --------------------\n { id: \"horse\", label: \"Horse\", subcategory: \"transport\", description: \"Strong graceful horse with flowing mane and tail, sturdy hooves and a muscular frame\" },\n { id: \"camel\", label: \"Camel\", subcategory: \"transport\", description: \"Desert camel with a tall humped back, long legs, wide padded feet and a serene face\" },\n { id: \"donkey\", label: \"Donkey\", subcategory: \"transport\", description: \"Small sturdy donkey with long ears, a short upright mane and a gentle face\" },\n { id: \"mule\", label: \"Mule\", subcategory: \"transport\", description: \"Hardy pack mule with long ears, a short dark mane and a compact muscular frame\" },\n { id: \"ox\", label: \"Ox\", subcategory: \"transport\", description: \"Massive working ox with broad shoulders, curved horns and a patient stoic face\" },\n\n // -------------------- Farm --------------------\n { id: \"cow\", label: \"Cow\", subcategory: \"farm\", description: \"Dairy cow with a white and black patched hide, large udder and gentle brown eyes\" },\n { id: \"pig\", label: \"Pig\", subcategory: \"farm\", description: \"Stout pink farm pig with a curled tail, round snout and upright ears\" },\n { id: \"sheep\", label: \"Sheep\", subcategory: \"farm\", description: \"Fluffy woolly sheep with a thick cream fleece, dark face and short legs\" },\n { id: \"goat\", label: \"Goat\", subcategory: \"farm\", description: \"Nimble goat with a shaggy coat, curved horns, a tuft of beard and rectangular pupils\" },\n { id: \"chicken\", label: \"Chicken\", subcategory: \"farm\", description: \"Classic farm chicken with a red comb and wattles, feathered body and alert side-tilted head\" },\n { id: \"rooster\", label: \"Rooster\", subcategory: \"farm\", description: \"Proud rooster with a tall red comb, iridescent green-and-copper feathers and long arched tail plumes\" },\n { id: \"duck\", label: \"Duck\", subcategory: \"farm\", description: \"White-and-brown farm duck with an orange bill, webbed feet and a rounded rump\" },\n { id: \"rabbit\", label: \"Rabbit\", subcategory: \"farm\", description: \"Fluffy rabbit with long upright ears, a twitching nose and a cotton-ball tail\" },\n { id: \"turkey\", label: \"Turkey\", subcategory: \"farm\", description: \"Large turkey with a fan of dark iridescent tail feathers, a bare red head and a dangling snood\" },\n\n // -------------------- Wild --------------------\n { id: \"lion\", label: \"Lion\", subcategory: \"wild\", description: \"Powerful male lion with a thick golden mane framing a wide tawny face and a muscular frame\" },\n { id: \"tiger\", label: \"Tiger\", subcategory: \"wild\", description: \"Massive tiger with striking orange fur, bold black stripes and intense amber eyes\" },\n { id: \"bear\", label: \"Bear\", subcategory: \"wild\", description: \"Large brown bear with thick shaggy fur, a broad head, round ears and powerful clawed paws\" },\n { id: \"polar-bear\", label: \"Polar Bear\", subcategory: \"wild\", description: \"Massive arctic bear with thick cream-white fur, a long neck, black nose and huge padded paws\" },\n { id: \"wolf\", label: \"Wolf\", subcategory: \"wild\", description: \"Lean grey wolf with a thick double coat, upright ears, piercing yellow eyes and a bushy tail\" },\n { id: \"fox\", label: \"Fox\", subcategory: \"wild\", description: \"Slender red fox with a sharp pointed muzzle, upright ears and a long white-tipped bushy tail\" },\n { id: \"elephant\", label: \"Elephant\", subcategory: \"wild\", description: \"Massive elephant with a wrinkled grey hide, long trunk, wide flapping ears and curved ivory tusks\" },\n { id: \"zebra\", label: \"Zebra\", subcategory: \"wild\", description: \"Sturdy horse-like zebra with bold black and white stripes, a short upright mane and large dark eyes\" },\n { id: \"giraffe\", label: \"Giraffe\", subcategory: \"wild\", description: \"Tall graceful giraffe with an impossibly long neck, a golden patchwork coat and small ossicone horns\" },\n { id: \"panda\", label: \"Giant Panda\", subcategory: \"wild\", description: \"Roly-poly panda with a black-and-white coat, round ears, distinctive black eye patches and a gentle face\" },\n { id: \"leopard\", label: \"Leopard\", subcategory: \"wild\", description: \"Sleek spotted leopard with a tawny coat covered in rosettes, muscular shoulders and piercing pale eyes\" },\n { id: \"cheetah\", label: \"Cheetah\", subcategory: \"wild\", description: \"Slim fast-running cheetah with a golden coat of solid black spots and tear-track lines down the face\" },\n { id: \"monkey\", label: \"Monkey\", subcategory: \"wild\", description: \"Agile long-tailed monkey with expressive brown eyes, slender limbs and a soft brown-and-cream coat\" },\n { id: \"gorilla\", label: \"Gorilla\", subcategory: \"wild\", description: \"Massive silverback gorilla with broad shoulders, a prominent brow ridge and thick black fur\" },\n { id: \"kangaroo\", label: \"Kangaroo\", subcategory: \"wild\", description: \"Tall kangaroo with powerful hind legs, a thick muscular tail, small front paws and upright alert ears\" },\n { id: \"koala\", label: \"Koala\", subcategory: \"wild\", description: \"Fluffy grey marsupial with a round head, large fuzzy ears, a big black nose and a soft fluffy chest\" },\n { id: \"deer\", label: \"Deer\", subcategory: \"wild\", description: \"Graceful deer with a reddish-brown coat, slender legs, white throat patch and — on a stag — branched antlers\" },\n { id: \"raccoon\", label: \"Raccoon\", subcategory: \"wild\", description: \"Masked raccoon with a grey coat, a dark bandit mask across the eyes and a bushy ringed tail\" },\n { id: \"capybara\", label: \"Capybara\", subcategory: \"wild\", description: \"Large peaceful South American rodent with a barrel-shaped body, blunt muzzle and calm expression, often photographed soaking in a hot spring with citrus floating around it\" },\n { id: \"sloth\", label: \"Sloth\", subcategory: \"wild\", description: \"Slow-moving tree-dwelling mammal with shaggy fur, long curved claws and a permanent gentle smile, often hanging upside-down from a branch\" },\n { id: \"red-panda\", label: \"Red Panda\", subcategory: \"wild\", description: \"Small fox-faced bamboo eater with rich reddish-brown fur, white facial markings, ringed tail and tufted upright ears, distinct from the giant panda\" },\n { id: \"pangolin\", label: \"Pangolin\", subcategory: \"wild\", description: \"Scaly armored anteater, distinctive overlapping plates\" },\n { id: \"okapi\", label: \"Okapi\", subcategory: \"wild\", description: \"Forest giraffe with zebra-striped legs\" },\n { id: \"quokka\", label: \"Quokka\", subcategory: \"wild\", description: \"Smiling Australian marsupial, internet-famous selfie animal\" },\n { id: \"meerkat\", label: \"Meerkat\", subcategory: \"wild\", description: \"Standing African mongoose, sentinel posture\" },\n\n // -------------------- Birds --------------------\n { id: \"eagle\", label: \"Eagle\", subcategory: \"birds\", description: \"Majestic eagle with a dark brown body, white head and tail, curved yellow beak and sharp talons\" },\n { id: \"owl\", label: \"Owl\", subcategory: \"birds\", description: \"Round-faced owl with a mottled brown-and-white plumage, huge forward-facing yellow eyes and feathered ear tufts\" },\n { id: \"parrot\", label: \"Parrot\", subcategory: \"birds\", description: \"Vibrant tropical parrot with saturated red, green, yellow and blue plumage and a hooked beak\" },\n { id: \"peacock\", label: \"Peacock\", subcategory: \"birds\", description: \"Iridescent blue peacock with an enormous fanned tail of shimmering eye-patterned feathers\" },\n { id: \"flamingo\", label: \"Flamingo\", subcategory: \"birds\", description: \"Tall slender flamingo with bright pink plumage, a long curved neck and a bent beak dipping toward the water\" },\n { id: \"penguin\", label: \"Penguin\", subcategory: \"birds\", description: \"Upright tuxedoed penguin with a black back, white belly and small flipper-like wings\" },\n { id: \"swan\", label: \"Swan\", subcategory: \"birds\", description: \"Elegant white swan with a long curved neck, orange beak and delicately folded wings\" },\n { id: \"sparrow\", label: \"Sparrow\", subcategory: \"birds\", description: \"Small brown-and-grey sparrow with a streaked back, tidy round body and alert black eye\" },\n { id: \"crow\", label: \"Crow\", subcategory: \"birds\", description: \"Glossy all-black crow with a thick straight beak, intelligent dark eyes and sleek iridescent feathers\" },\n { id: \"hummingbird\", label: \"Hummingbird\", subcategory: \"birds\", description: \"Tiny jewel-toned hummingbird with iridescent emerald and ruby plumage and a long needle-like beak\" },\n { id: \"raven\", label: \"Raven\", subcategory: \"birds\", description: \"Large glossy all-black raven with a heavy wedge-shaped beak, shaggy throat hackles and an intelligent piercing gaze, often perched in a cinematic mysterious mood\" },\n { id: \"emu\", label: \"Emu\", subcategory: \"birds\", description: \"Large flightless Australian ratite bird\" },\n\n // -------------------- Sea --------------------\n { id: \"dolphin\", label: \"Dolphin\", subcategory: \"sea\", description: \"Sleek grey dolphin with a playful smiling face, curved dorsal fin and powerful tail flukes\" },\n { id: \"whale\", label: \"Whale\", subcategory: \"sea\", description: \"Massive humpback whale with a dark blue-grey body, long pectoral fins and barnacled knobby head\" },\n { id: \"shark\", label: \"Shark\", subcategory: \"sea\", description: \"Powerful great white shark with a torpedo-shaped grey body, white underside and rows of sharp teeth\" },\n { id: \"octopus\", label: \"Octopus\", subcategory: \"sea\", description: \"Curious octopus with a bulbous head, large intelligent eyes and eight long suckered arms\" },\n { id: \"sea-turtle\", label: \"Sea Turtle\", subcategory: \"sea\", description: \"Graceful sea turtle with a patterned green-and-brown shell, flipper-like limbs and a wise wrinkled face\" },\n { id: \"jellyfish\", label: \"Jellyfish\", subcategory: \"sea\", description: \"Translucent jellyfish with a glowing bell-shaped body and long trailing filamentous tentacles\" },\n { id: \"crab\", label: \"Crab\", subcategory: \"sea\", description: \"Red-shelled crab with a wide armored carapace, large pincer claws and skittering side-stepping legs\" },\n { id: \"seahorse\", label: \"Seahorse\", subcategory: \"sea\", description: \"Tiny seahorse with a curled prehensile tail, horse-like head and delicate dorsal fin\" },\n { id: \"axolotl\", label: \"Axolotl\", subcategory: \"sea\", description: \"Pink-fleshed aquatic salamander with feathery external gills fanning out from the head, tiny clawed limbs and a distinctive smiling face\" },\n\n // -------------------- Small Pets --------------------\n { id: \"hamster\", label: \"Hamster\", subcategory: \"small-pets\", description: \"Round fluffy hamster with chubby cheek pouches, tiny paws and bright black bead eyes\" },\n { id: \"guinea-pig\", label: \"Guinea Pig\", subcategory: \"small-pets\", description: \"Plump guinea pig with a soft tri-color coat, no visible tail and a sweet alert face\" },\n { id: \"ferret\", label: \"Ferret\", subcategory: \"small-pets\", description: \"Sleek long-bodied ferret with a cream-and-sable coat, a dark bandit mask and a playful posture\" },\n { id: \"parakeet\", label: \"Parakeet\", subcategory: \"small-pets\", description: \"Small bright green-and-yellow parakeet with a striped head, dark eye spots and a long tapered tail\" },\n { id: \"gerbil\", label: \"Gerbil\", subcategory: \"small-pets\", description: \"Slender sandy-brown gerbil with large dark eyes, upright ears and a long tufted tail\" },\n\n // -------------------- Reptiles --------------------\n { id: \"snake\", label: \"Snake\", subcategory: \"reptiles\", description: \"Coiled snake with a smooth scaled body, diamond-patterned skin, slit pupils and a flickering forked tongue\" },\n { id: \"lizard\", label: \"Lizard\", subcategory: \"reptiles\", description: \"Agile lizard with a slender scaled body, long whip-like tail, clawed feet and keen side-facing eyes\" },\n { id: \"turtle\", label: \"Turtle\", subcategory: \"reptiles\", description: \"Friendly land turtle with a domed patterned shell, stout scaly legs and a wise wrinkled face\" },\n { id: \"crocodile\", label: \"Crocodile\", subcategory: \"reptiles\", description: \"Massive crocodile with armored olive-green scales, a long toothy snout and powerful clawed limbs\" },\n { id: \"chameleon\", label: \"Chameleon\", subcategory: \"reptiles\", description: \"Color-shifting chameleon with a tall casqued head, independently swiveling eyes and a tightly curled prehensile tail\" },\n { id: \"gecko\", label: \"Gecko\", subcategory: \"reptiles\", description: \"Small gecko with a plump spotted body, large lidless eyes and wide sticky toe pads\" },\n\n // -------------------- Insects --------------------\n { id: \"butterfly\", label: \"Butterfly\", subcategory: \"insects\", description: \"Delicate butterfly with wide patterned wings in vivid colors, a slender body and long antennae\" },\n { id: \"bee\", label: \"Bee\", subcategory: \"insects\", description: \"Fuzzy honey bee with yellow and black stripes, translucent wings and pollen-dusted legs\" },\n { id: \"ant\", label: \"Ant\", subcategory: \"insects\", description: \"Busy ant with a segmented dark body, six thin legs, bent antennae and strong mandibles\" },\n { id: \"spider\", label: \"Spider\", subcategory: \"insects\", description: \"Eight-legged spider with a bulbous abdomen, clustered dark eyes and fine hairs across its body\" },\n { id: \"ladybug\", label: \"Ladybug\", subcategory: \"insects\", description: \"Tiny red ladybug with a glossy rounded shell, bold black spots and delicate legs peeking out\" },\n { id: \"dragonfly\", label: \"Dragonfly\", subcategory: \"insects\", description: \"Slender dragonfly with iridescent blue-green body, huge faceted eyes and four long transparent wings\" },\n { id: \"beetle\", label: \"Beetle\", subcategory: \"insects\", description: \"Armored beetle with a glossy hard shell, ridged wing covers, sturdy legs and short antennae\" },\n { id: \"grasshopper\", label: \"Grasshopper\", subcategory: \"insects\", description: \"Green grasshopper with long powerful hind legs, folded wings along its back and long whip-like antennae\" },\n { id: \"praying-mantis\", label: \"Praying Mantis\", subcategory: \"insects\", description: \"Elongated praying mantis with a triangular head, large compound eyes and spiked raptorial forelegs held in a prayer pose\" },\n { id: \"mosquito\", label: \"Mosquito\", subcategory: \"insects\", description: \"Slender mosquito with long thin legs, narrow transparent wings and a needle-like proboscis\" },\n { id: \"scorpion\", label: \"Scorpion\", subcategory: \"insects\", description: \"Desert scorpion with armored segments, large pincer claws and a curled stinger-tipped tail raised over its back\" },\n { id: \"caterpillar\", label: \"Caterpillar\", subcategory: \"insects\", description: \"Plump segmented caterpillar with soft tufts, tiny legs and a cheerful munching posture on a green leaf\" },\n { id: \"tarantula\", label: \"Tarantula\", subcategory: \"insects\", description: \"Large hairy hunting spider\" },\n\n // -------------------- Dinosaurs --------------------\n { id: \"t-rex\", label: \"Tyrannosaurus Rex\", subcategory: \"dinosaurs\", description: \"Massive T-Rex with powerful hind legs, tiny clawed arms, a huge jaw full of dagger teeth and thick scaly hide\" },\n { id: \"velociraptor\", label: \"Velociraptor\", subcategory: \"dinosaurs\", description: \"Lean feathered velociraptor with sickle claws, a long stiff tail and a predatory forward-lean posture\" },\n { id: \"triceratops\", label: \"Triceratops\", subcategory: \"dinosaurs\", description: \"Armored triceratops with a large bony frill, three sharp horns on its face and a heavy four-legged stance\" },\n { id: \"brachiosaurus\", label: \"Brachiosaurus\", subcategory: \"dinosaurs\", description: \"Towering brachiosaurus with an impossibly long neck reaching into treetops, a small head and pillar-like legs\" },\n { id: \"stegosaurus\", label: \"Stegosaurus\", subcategory: \"dinosaurs\", description: \"Hulking stegosaurus with two rows of tall diamond-shaped plates along its back and a spiked tail\" },\n { id: \"pterodactyl\", label: \"Pterodactyl\", subcategory: \"dinosaurs\", description: \"Flying pterodactyl with vast leathery wings, a long toothed beak and a swept-back head crest\" },\n { id: \"spinosaurus\", label: \"Spinosaurus\", subcategory: \"dinosaurs\", description: \"Predatory spinosaurus with a tall sail fin down its back, a long crocodile-like snout and powerful clawed arms\" },\n { id: \"diplodocus\", label: \"Diplodocus\", subcategory: \"dinosaurs\", description: \"Enormous long-bodied diplodocus with a whip-thin tail balancing an equally long neck, peg-like teeth and sturdy legs\" },\n { id: \"ankylosaurus\", label: \"Ankylosaurus\", subcategory: \"dinosaurs\", description: \"Tank-like ankylosaurus covered in thick armored plates and spikes, with a massive bony club at the end of its tail\" },\n { id: \"brontosaurus\", label: \"Brontosaurus\", subcategory: \"dinosaurs\", description: \"Gentle giant brontosaurus with a long sweeping neck, a small head, a thick body and a tapering whip tail\" },\n { id: \"parasaurolophus\", label: \"Parasaurolophus\", subcategory: \"dinosaurs\", description: \"Duck-billed parasaurolophus with a long curved tubular crest sweeping back from its head and a slender bipedal body\" },\n { id: \"allosaurus\", label: \"Allosaurus\", subcategory: \"dinosaurs\", description: \"Fierce allosaurus predator with a large head, small brow horns, serrated teeth and powerful grasping arms\" },\n\n // -------------------- Mythical --------------------\n { id: \"dragon\", label: \"Dragon\", subcategory: \"mythical\", description: \"Towering dragon with leathery wings, ridged scales, curved horns, glowing eyes and smoke curling from its nostrils\" },\n { id: \"unicorn\", label: \"Unicorn\", subcategory: \"mythical\", description: \"Pure white unicorn with a flowing pastel mane and tail and a single spiraling pearlescent horn on its forehead\" },\n { id: \"phoenix\", label: \"Phoenix\", subcategory: \"mythical\", description: \"Majestic phoenix with fiery red, orange and gold plumage, long trailing tail feathers and flames licking its wingtips\" },\n { id: \"griffin\", label: \"Griffin\", subcategory: \"mythical\", description: \"Hybrid griffin with the head, wings and taloned front legs of an eagle and the muscular hind body of a lion\" },\n { id: \"pegasus\", label: \"Pegasus\", subcategory: \"mythical\", description: \"Pure white winged horse with feathered wings, a flowing mane and an otherworldly presence\" },\n { id: \"kraken\", label: \"Kraken\", subcategory: \"mythical\", description: \"Colossal sea-beast kraken with a massive head, glowing eyes and enormous suckered tentacles writhing from the deep\" },\n] as const\n\nconst animalById = new Map<string, Animal>(ANIMALS.map((a) => [a.id, a]))\n\nexport function getAnimal(id: string | undefined | null): Animal | undefined {\n if (!id) return undefined\n return animalById.get(id)\n}\n\nexport function getAnimalLabel(id: string | undefined | null, fallback?: string): string {\n const a = getAnimal(id)\n if (a) return a.label\n if (fallback !== undefined) return fallback\n return (id ?? \"\").replace(/-/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase())\n}\n\nexport const ANIMAL_IDS: ReadonlyArray<string> = ANIMALS.map((a) => a.id)\n\nexport const ANIMAL_SUBCATEGORY_LABELS: Readonly<Record<AnimalSubcategory, string>> = {\n cats: \"Cats\",\n dogs: \"Dogs\",\n transport: \"Transport & Working\",\n farm: \"Farm\",\n wild: \"Wild\",\n birds: \"Birds\",\n sea: \"Sea Life\",\n \"small-pets\": \"Small Pets\",\n reptiles: \"Reptiles\",\n insects: \"Insects\",\n dinosaurs: \"Dinosaurs\",\n mythical: \"Mythical\",\n}\n\nexport const ANIMAL_SUBCATEGORY_ORDER: ReadonlyArray<AnimalSubcategory> = [\n \"cats\",\n \"dogs\",\n \"transport\",\n \"farm\",\n \"wild\",\n \"birds\",\n \"sea\",\n \"small-pets\",\n \"reptiles\",\n \"insects\",\n \"dinosaurs\",\n \"mythical\",\n]\n","/**\n * Canonical catalog of furniture presets for the Object entity node.\n *\n * When the Object category is \"furniture\", users pick a specific furniture\n * piece from this catalog. The picker auto-fills the object's `objectName`\n * and `description` so the existing `buildObjectPrompt` pipeline just works\n * — no backend prompt changes needed.\n *\n * Organized into everyday sub-categories: seating, tables, beds, storage,\n * lighting, kitchen & dining, outdoor, decorative, and bath.\n */\n\nexport type FurnitureSubcategory =\n | \"seating\"\n | \"tables\"\n | \"beds\"\n | \"storage\"\n | \"lighting\"\n | \"kitchen-dining\"\n | \"outdoor\"\n | \"decorative\"\n | \"bath\"\n\nexport interface Furniture {\n readonly id: string\n readonly label: string\n readonly subcategory: FurnitureSubcategory\n readonly description: string\n}\n\nexport const FURNITURE: ReadonlyArray<Furniture> = [\n // -------------------- Seating --------------------\n { id: \"sofa\", label: \"Sofa\", subcategory: \"seating\", description: \"Three-seater sofa with plush cushioned back and seat, low armrests and upholstery in a neutral tone\" },\n { id: \"sectional-sofa\", label: \"Sectional Sofa\", subcategory: \"seating\", description: \"L-shaped sectional sofa with deep seats, soft cushions, a chaise end and hidden storage or recline mechanisms\" },\n { id: \"loveseat\", label: \"Loveseat\", subcategory: \"seating\", description: \"Compact two-seat loveseat with rolled arms, tufted back and tapered wooden legs\" },\n { id: \"armchair\", label: \"Armchair\", subcategory: \"seating\", description: \"Upholstered armchair with a tall padded back, curved armrests and four slim wooden legs\" },\n { id: \"recliner\", label: \"Recliner\", subcategory: \"seating\", description: \"Padded recliner chair with a pull lever, extending footrest, thick leather upholstery and a reclined backrest\" },\n { id: \"office-chair\", label: \"Office Chair\", subcategory: \"seating\", description: \"Ergonomic office chair with a mesh back, adjustable armrests, gas-lift height and a five-point caster base\" },\n { id: \"rocking-chair\", label: \"Rocking Chair\", subcategory: \"seating\", description: \"Wooden rocking chair with curved rockers, a woven cane back and a padded seat cushion\" },\n { id: \"throne\", label: \"Throne\", subcategory: \"seating\", description: \"Ornate royal throne with a towering carved back, gilded trim, jeweled accents and a plush velvet cushion\" },\n { id: \"bean-bag\", label: \"Bean Bag\", subcategory: \"seating\", description: \"Oversized slouchy bean bag chair with soft fabric exterior and a pillowy squishy shape that molds to the body\" },\n { id: \"stool\", label: \"Stool\", subcategory: \"seating\", description: \"Simple backless stool with a round wooden seat, four splayed turned legs and a worn comfortable patina\" },\n { id: \"bench\", label: \"Bench\", subcategory: \"seating\", description: \"Long wooden bench with a flat seat, open slatted back and sturdy planked legs\" },\n { id: \"chaise-lounge\", label: \"Chaise Lounge\", subcategory: \"seating\", description: \"Elegant chaise lounge with a sloped headrest, elongated upholstered seat and turned wooden legs\" },\n { id: \"dining-chair\", label: \"Dining Chair\", subcategory: \"seating\", description: \"Formal dining chair with a high slatted back, upholstered seat cushion and tapered wooden legs\" },\n\n // -------------------- Tables --------------------\n { id: \"dining-table\", label: \"Dining Table\", subcategory: \"tables\", description: \"Large rectangular dining table with a polished wooden top, thick trestle base and seating for six to eight\" },\n { id: \"coffee-table\", label: \"Coffee Table\", subcategory: \"tables\", description: \"Low rectangular coffee table with a glass or wooden top, clean minimalist legs and a lower shelf for magazines\" },\n { id: \"side-table\", label: \"Side Table\", subcategory: \"tables\", description: \"Petite side table with a round top, single drawer and slim tapered legs\" },\n { id: \"console-table\", label: \"Console Table\", subcategory: \"tables\", description: \"Narrow console table with a long slim top, delicate legs and decorative scrollwork along the apron\" },\n { id: \"desk\", label: \"Desk\", subcategory: \"tables\", description: \"Writing desk with a flat work surface, drawer bank on the side and a cable management cutout at the back\" },\n { id: \"workbench\", label: \"Workbench\", subcategory: \"tables\", description: \"Heavy-duty workbench with a thick butcher-block top, pegboard back panel and a vice clamped to one edge\" },\n { id: \"vanity-table\", label: \"Vanity Table\", subcategory: \"tables\", description: \"Dressing vanity with a wide tri-fold mirror, small drawers on each side and a cushioned bench tucked underneath\" },\n { id: \"nightstand\", label: \"Nightstand\", subcategory: \"tables\", description: \"Small bedside nightstand with a single drawer, open lower shelf and a lamp-ready top surface\" },\n { id: \"picnic-table\", label: \"Picnic Table\", subcategory: \"tables\", description: \"Classic wooden picnic table with a plank top, attached bench seats and weathered outdoor finish\" },\n\n // -------------------- Beds --------------------\n { id: \"bed-single\", label: \"Single Bed\", subcategory: \"beds\", description: \"Narrow single bed with a padded headboard, tailored fitted sheet and a folded throw blanket at the foot\" },\n { id: \"bed-queen\", label: \"Queen Bed\", subcategory: \"beds\", description: \"Queen-size bed with a tall upholstered headboard, layered pillows, a crisp duvet and a runner across the foot\" },\n { id: \"bed-king\", label: \"King Bed\", subcategory: \"beds\", description: \"Grand king-size bed with a tufted headboard, multiple plush pillows, crisp white linens and a thick quilted duvet\" },\n { id: \"bunk-bed\", label: \"Bunk Bed\", subcategory: \"beds\", description: \"Sturdy wooden bunk bed with two stacked mattresses, side ladder, safety rails and matching kid-friendly bedding\" },\n { id: \"canopy-bed\", label: \"Canopy Bed\", subcategory: \"beds\", description: \"Four-poster canopy bed with tall carved posts, a fabric canopy draped overhead and flowing curtains at each corner\" },\n { id: \"four-poster-bed\", label: \"Four-Poster Bed\", subcategory: \"beds\", description: \"Four-poster bed with turned wooden columns at each corner rising unadorned to match the headboard's carved profile\" },\n { id: \"daybed\", label: \"Daybed\", subcategory: \"beds\", description: \"Daybed with a low frame, three upholstered sides acting as back and armrests and bolster cushions along the wall\" },\n { id: \"crib\", label: \"Baby Crib\", subcategory: \"beds\", description: \"Wooden baby crib with vertical slatted sides, a small fitted mattress and soft plush toys tucked inside\" },\n { id: \"futon\", label: \"Futon\", subcategory: \"beds\", description: \"Convertible futon with a slim padded mattress over a folding metal frame that converts from sofa to bed\" },\n { id: \"hammock\", label: \"Hammock\", subcategory: \"beds\", description: \"Woven rope hammock slung between two supports, gently sagging with an inviting curve and colorful tassels at each end\" },\n\n // -------------------- Storage --------------------\n { id: \"bookshelf\", label: \"Bookshelf\", subcategory: \"storage\", description: \"Tall freestanding bookshelf with multiple horizontal shelves, wooden sides and rows of neatly stacked books\" },\n { id: \"wardrobe\", label: \"Wardrobe\", subcategory: \"storage\", description: \"Large double-door wardrobe with a full-length hanging section, drawer bank and decorative paneled doors\" },\n { id: \"dresser\", label: \"Dresser\", subcategory: \"storage\", description: \"Wooden dresser with a wide top, six deep drawers in two columns, brass pull handles and short tapered legs\" },\n { id: \"cabinet\", label: \"Cabinet\", subcategory: \"storage\", description: \"Storage cabinet with paneled doors, interior adjustable shelves and brass hardware\" },\n { id: \"chest\", label: \"Storage Chest\", subcategory: \"storage\", description: \"Weathered wooden storage chest with iron banding, a hinged domed lid and a heavy clasp latch at the front\" },\n { id: \"trunk\", label: \"Steamer Trunk\", subcategory: \"storage\", description: \"Vintage steamer trunk with leather straps, brass corners, travel stickers and a latched lid revealing tray inserts\" },\n { id: \"filing-cabinet\", label: \"Filing Cabinet\", subcategory: \"storage\", description: \"Four-drawer metal filing cabinet with label slots on each drawer, recessed pull handles and a key lock at the top\" },\n { id: \"tv-stand\", label: \"TV Stand\", subcategory: \"storage\", description: \"Low entertainment TV stand with open shelves, glass-fronted cabinet doors and cable pass-throughs\" },\n { id: \"display-case\", label: \"Display Case\", subcategory: \"storage\", description: \"Tall glass display case with interior lighting, glass shelves and a lockable framed door\" },\n { id: \"hutch\", label: \"China Hutch\", subcategory: \"storage\", description: \"Two-part china hutch with a glass-fronted upper cabinet showing plates on edge and a buffet base with drawers and doors\" },\n { id: \"toy-chest\", label: \"Toy Chest\", subcategory: \"storage\", description: \"Painted wooden toy chest with cheerful decals, a soft-close hinged lid and stickers accumulated on the sides\" },\n\n // -------------------- Lighting --------------------\n { id: \"floor-lamp\", label: \"Floor Lamp\", subcategory: \"lighting\", description: \"Tall floor lamp with a slim metal stand, weighted base, pull-chain switch and a drum fabric shade at the top\" },\n { id: \"table-lamp\", label: \"Table Lamp\", subcategory: \"lighting\", description: \"Classic table lamp with a ceramic base, pleated fabric shade and a small pull-chain switch\" },\n { id: \"desk-lamp\", label: \"Desk Lamp\", subcategory: \"lighting\", description: \"Articulating desk lamp with an adjustable arm, hinged head and a small cone-shaped metal shade\" },\n { id: \"chandelier\", label: \"Chandelier\", subcategory: \"lighting\", description: \"Grand crystal chandelier with tiered cascading crystals, curved golden arms and multiple flame-shaped bulbs\" },\n { id: \"pendant-light\", label: \"Pendant Light\", subcategory: \"lighting\", description: \"Modern pendant light hanging from a long cord with a minimalist metal or glass shade\" },\n { id: \"sconce\", label: \"Wall Sconce\", subcategory: \"lighting\", description: \"Wall-mounted sconce with a decorative backplate, curved arm and a fabric or glass shade pointing upward\" },\n { id: \"lantern\", label: \"Lantern\", subcategory: \"lighting\", description: \"Classic lantern with a metal frame, glass panels, a candle or flickering bulb inside and a carrying ring on top\" },\n { id: \"candelabra\", label: \"Candelabra\", subcategory: \"lighting\", description: \"Ornate silver candelabra with multiple curved branching arms each holding a tall taper candle\" },\n { id: \"neon-sign\", label: \"Neon Sign\", subcategory: \"lighting\", description: \"Glowing neon sign with bent glass tubes shaped into cursive lettering or a retro icon, casting colored light on the wall\" },\n\n // -------------------- Kitchen & Dining --------------------\n { id: \"kitchen-island\", label: \"Kitchen Island\", subcategory: \"kitchen-dining\", description: \"Freestanding kitchen island with a thick butcher-block top, cabinet storage below, bar stool overhang and a rack above\" },\n { id: \"bar-counter\", label: \"Bar Counter\", subcategory: \"kitchen-dining\", description: \"Home bar counter with a polished wooden top, brass footrail, backlit glass shelving and rows of bottles displayed behind\" },\n { id: \"bar-stool\", label: \"Bar Stool\", subcategory: \"kitchen-dining\", description: \"Tall bar stool with a round swiveling seat, footrest ring, metal frame and an optional low backrest\" },\n { id: \"pot-rack\", label: \"Pot Rack\", subcategory: \"kitchen-dining\", description: \"Overhead hanging pot rack with a wrought-iron frame, S-hooks dangling pots and pans and shelving for spices on top\" },\n { id: \"spice-rack\", label: \"Spice Rack\", subcategory: \"kitchen-dining\", description: \"Wall-mounted spice rack with rows of small labeled glass jars, wooden shelves and a cheerful cluttered charm\" },\n { id: \"buffet\", label: \"Buffet\", subcategory: \"kitchen-dining\", description: \"Long dining-room buffet with a flat top for serving platters, drawers for linens and cabinet doors for dishware below\" },\n\n // -------------------- Outdoor --------------------\n { id: \"patio-chair\", label: \"Patio Chair\", subcategory: \"outdoor\", description: \"Outdoor patio chair with a weather-resistant woven wicker seat, aluminum frame and a weatherproof cushion\" },\n { id: \"adirondack-chair\", label: \"Adirondack Chair\", subcategory: \"outdoor\", description: \"Classic wooden Adirondack chair with a slanted slatted back, wide flat armrests and a seat that scoops gently back\" },\n { id: \"porch-swing\", label: \"Porch Swing\", subcategory: \"outdoor\", description: \"Wooden porch swing suspended on chains from the ceiling with a slatted seat and a row of colorful outdoor cushions\" },\n { id: \"gazebo\", label: \"Gazebo\", subcategory: \"outdoor\", description: \"Freestanding outdoor gazebo with a peaked shingled roof, six open wooden columns, railings and a raised wooden floor\" },\n { id: \"bistro-set\", label: \"Bistro Set\", subcategory: \"outdoor\", description: \"Compact outdoor bistro set with a round wrought-iron table and two matching chairs in a glossy weather-resistant finish\" },\n { id: \"sun-lounger\", label: \"Sun Lounger\", subcategory: \"outdoor\", description: \"Poolside sun lounger with an adjustable reclining back, white vinyl straps and a matching side table\" },\n { id: \"fire-pit\", label: \"Fire Pit\", subcategory: \"outdoor\", description: \"Round outdoor fire pit bowl with a rough-iron exterior, flickering flames and glowing embers beneath a protective mesh screen\" },\n\n // -------------------- Decorative --------------------\n { id: \"mirror\", label: \"Mirror\", subcategory: \"decorative\", description: \"Large wall mirror with an ornate gilded frame, carved scrollwork and slightly aged silvering in the glass\" },\n { id: \"rug\", label: \"Rug\", subcategory: \"decorative\", description: \"Large patterned area rug with intricate woven motifs, tasseled ends and a soft plush pile\" },\n { id: \"vase\", label: \"Vase\", subcategory: \"decorative\", description: \"Tall ceramic vase with a rounded body, narrow neck, glazed finish and a fresh bouquet of flowers arranged inside\" },\n { id: \"grandfather-clock\", label: \"Grandfather Clock\", subcategory: \"decorative\", description: \"Tall wooden grandfather clock with a glass pendulum door, brass clock face, roman numerals and a chime mechanism\" },\n { id: \"wall-art\", label: \"Framed Wall Art\", subcategory: \"decorative\", description: \"Large framed artwork in a gilded or minimalist frame with a gallery-style matte border and a single focal painting\" },\n { id: \"pillow\", label: \"Throw Pillow\", subcategory: \"decorative\", description: \"Decorative throw pillow with a patterned cover, piped edges, plush fill and an invisible zipper closure\" },\n { id: \"curtains\", label: \"Curtains\", subcategory: \"decorative\", description: \"Full-length curtains with thick draping fabric, pleated tops hanging from a metal rod and tie-backs on each side\" },\n { id: \"sculpture\", label: \"Sculpture\", subcategory: \"decorative\", description: \"Abstract sculpture on a pedestal with flowing organic forms in bronze or marble catching the light from multiple angles\" },\n\n // -------------------- Bath --------------------\n { id: \"bathtub\", label: \"Bathtub\", subcategory: \"bath\", description: \"Freestanding clawfoot bathtub with rolled rim, polished white enamel interior and four ornate cast-iron feet\" },\n { id: \"shower\", label: \"Walk-In Shower\", subcategory: \"bath\", description: \"Walk-in shower with frameless glass panels, tiled walls, a rainfall showerhead and a linear floor drain\" },\n { id: \"toilet\", label: \"Toilet\", subcategory: \"bath\", description: \"Standard white ceramic toilet with an oval bowl, elongated seat and a tank with a chrome flush handle\" },\n { id: \"sink-vanity\", label: \"Sink Vanity\", subcategory: \"bath\", description: \"Bathroom sink vanity with a stone countertop, undermount basin, wide mirror above and paneled cabinet doors below\" },\n { id: \"towel-rack\", label: \"Towel Rack\", subcategory: \"bath\", description: \"Wall-mounted heated towel rack with multiple horizontal bars and fluffy folded towels draped over each bar\" },\n] as const\n\nconst furnitureById = new Map<string, Furniture>(FURNITURE.map((f) => [f.id, f]))\n\nexport function getFurniture(id: string | undefined | null): Furniture | undefined {\n if (!id) return undefined\n return furnitureById.get(id)\n}\n\nexport function getFurnitureLabel(id: string | undefined | null, fallback?: string): string {\n const f = getFurniture(id)\n if (f) return f.label\n if (fallback !== undefined) return fallback\n return (id ?? \"\").replace(/-/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase())\n}\n\nexport const FURNITURE_IDS: ReadonlyArray<string> = FURNITURE.map((f) => f.id)\n\nexport const FURNITURE_SUBCATEGORY_LABELS: Readonly<Record<FurnitureSubcategory, string>> = {\n seating: \"Seating\",\n tables: \"Tables\",\n beds: \"Beds\",\n storage: \"Storage\",\n lighting: \"Lighting\",\n \"kitchen-dining\": \"Kitchen & Dining\",\n outdoor: \"Outdoor\",\n decorative: \"Decorative\",\n bath: \"Bath\",\n}\n\nexport const FURNITURE_SUBCATEGORY_ORDER: ReadonlyArray<FurnitureSubcategory> = [\n \"seating\",\n \"tables\",\n \"beds\",\n \"storage\",\n \"lighting\",\n \"kitchen-dining\",\n \"outdoor\",\n \"decorative\",\n \"bath\",\n]\n","/**\n * Facets of a source character/asset that can be selectively injected into a\n * consumer character via the Character node's Assets handle (element/asset\n * injection, P2). Single source of truth for the frontend facet chip options\n * AND the backend facet-extraction instructions.\n *\n * `full` injects the whole source description verbatim (no LLM call needed).\n * Every other facet is LLM-extracted on demand from the source's\n * `canonicalDescription` via `POST /v1/character/extract-facet`.\n */\nexport interface CharacterFacet {\n /** Stable id stored on the connection (`assetInjections[].facet`). */\n readonly id: string\n /** Human label shown in the facet chip. */\n readonly label: string\n /** What the extractor should pull from the source description. Phrased to\n * complete \"Extract {instruction} …\". Unused for `full`. */\n readonly instruction: string\n}\n\nexport const CHARACTER_FACETS: readonly CharacterFacet[] = [\n { id: \"full\", label: \"Full likeness\", instruction: \"the complete physical likeness and appearance\" },\n { id: \"hair\", label: \"Hair\", instruction: \"ONLY the hair — style, length, colour, and texture\" },\n { id: \"skin-tone\", label: \"Skin tone\", instruction: \"ONLY the skin tone / complexion\" },\n { id: \"face\", label: \"Face\", instruction: \"ONLY the facial features — face shape, eyes, nose, mouth, eyebrows, and any distinguishing marks\" },\n { id: \"style\", label: \"Style\", instruction: \"ONLY the overall visual style, aesthetic, and vibe — not specific garments\" },\n { id: \"outfit\", label: \"Outfit\", instruction: \"ONLY the clothing, outfit, and wardrobe\" },\n { id: \"personality\", label: \"Personality\", instruction: \"ONLY the personality, demeanour, and characteristic expression\" },\n] as const\n\nexport const DEFAULT_CHARACTER_FACET = \"full\"\n\nexport const CHARACTER_FACET_IDS: ReadonlySet<string> = new Set(CHARACTER_FACETS.map((f) => f.id))\n\nexport function getCharacterFacet(id: string): CharacterFacet | undefined {\n return CHARACTER_FACETS.find((f) => f.id === id)\n}\n","/**\n * Canonical catalog of vehicle presets for the Object entity node.\n *\n * When the Object category is \"vehicle\", users pick a specific vehicle from\n * this catalog. The picker auto-fills the object's `objectName` and\n * `description` so the existing `buildObjectPrompt` pipeline just works — no\n * backend prompt changes needed.\n *\n * Organized into everyday sub-categories: classic cars, everyday cars,\n * performance cars, motorcycles, bicycles (human-powered), trucks, transit\n * (buses + rail + horse-drawn), aircraft, watercraft, military, construction,\n * and sci-fi.\n */\n\nexport type VehicleSubcategory =\n | \"cars-classic\"\n | \"cars-everyday\"\n | \"cars-performance\"\n | \"motorcycles\"\n | \"bicycles\"\n | \"trucks\"\n | \"transit\"\n | \"aircraft\"\n | \"watercraft\"\n | \"military\"\n | \"construction\"\n | \"sci-fi\"\n\nexport interface Vehicle {\n readonly id: string\n readonly label: string\n readonly subcategory: VehicleSubcategory\n readonly description: string\n}\n\nexport const VEHICLES: ReadonlyArray<Vehicle> = [\n // -------------------- Classic Cars --------------------\n { id: \"muscle-car\", label: \"Muscle Car\", subcategory: \"cars-classic\", description: \"Aggressive American muscle car with a long hood, wide stance, dual chrome exhausts and a deep throaty V8 presence\" },\n { id: \"car-57-chevy\", label: \"'57 Chevy\", subcategory: \"cars-classic\", description: \"Iconic 1957 Chevrolet Bel Air with tail fins, chrome bumpers, two-tone paint and whitewall tires\" },\n { id: \"hot-rod\", label: \"Hot Rod\", subcategory: \"cars-classic\", description: \"Chopped and channeled hot rod with flame paint job, exposed chrome engine, fat rear tires and skinny fronts\" },\n { id: \"vintage-roadster\", label: \"Vintage Roadster\", subcategory: \"cars-classic\", description: \"Pre-war open-top roadster with sweeping fenders, running boards, wire-spoke wheels and a long polished hood\" },\n { id: \"model-t\", label: \"Ford Model T\", subcategory: \"cars-classic\", description: \"Early 20th-century black Model T with boxy upright body, brass headlamps, spoked wheels and a cranked engine\" },\n { id: \"vw-beetle\", label: \"VW Beetle\", subcategory: \"cars-classic\", description: \"Rounded pastel-colored Volkswagen Beetle with a curved hood, air-cooled rear engine and cheerful bug-like face\" },\n { id: \"checker-cab\", label: \"Checker Cab\", subcategory: \"cars-classic\", description: \"Classic yellow New York checker taxi with a boxy body, black-and-white checker band and roof light\" },\n { id: \"woody-wagon\", label: \"Woody Wagon\", subcategory: \"cars-classic\", description: \"Surf-era station wagon with wood-paneled side doors, chrome bumpers and a long tailgate\" },\n { id: \"lowrider\", label: \"Lowrider\", subcategory: \"cars-classic\", description: \"Candy-painted lowrider with hydraulic suspension, chrome spoke wheels, whitewall tires and airbrushed murals\" },\n\n // -------------------- Everyday Cars --------------------\n { id: \"sedan\", label: \"Sedan\", subcategory: \"cars-everyday\", description: \"Four-door midsize sedan with a streamlined silhouette, chrome accents and modern LED headlights\" },\n { id: \"suv\", label: \"SUV\", subcategory: \"cars-everyday\", description: \"Large sport utility vehicle with a tall stance, roof rails, big alloy wheels and a muscular squared-off body\" },\n { id: \"hatchback\", label: \"Hatchback\", subcategory: \"cars-everyday\", description: \"Compact hatchback with a short rear, lift-up tailgate, nimble proportions and bright paint\" },\n { id: \"minivan\", label: \"Minivan\", subcategory: \"cars-everyday\", description: \"Family minivan with sliding side doors, a tall spacious cabin, tinted rear windows and a roomy rear hatch\" },\n { id: \"station-wagon\", label: \"Station Wagon\", subcategory: \"cars-everyday\", description: \"Long-roof station wagon with extended cargo area, rear quarter windows and a family-oriented silhouette\" },\n { id: \"crossover\", label: \"Crossover\", subcategory: \"cars-everyday\", description: \"Mid-sized crossover SUV with a raised ride height, car-like styling and aerodynamic LED accents\" },\n { id: \"electric-car\", label: \"Electric Car\", subcategory: \"cars-everyday\", description: \"Sleek modern electric car with a smooth grille-less front, flush door handles and aerodynamic clean lines\" },\n { id: \"hatchback-econobox\", label: \"Econobox\", subcategory: \"cars-everyday\", description: \"Tiny affordable two-door city car with a stubby hood, small wheels and simple compact styling\" },\n { id: \"police-car\", label: \"Police Car\", subcategory: \"cars-everyday\", description: \"Black-and-white patrol car with a roof-mounted light bar flashing red and blue, push bar on the front bumper, agency decals on the doors and antenna whips on the trunk\" },\n\n // -------------------- Performance / Exotic --------------------\n { id: \"sports-car\", label: \"Sports Car\", subcategory: \"cars-performance\", description: \"Low-slung two-door sports car with a wide aggressive stance, aerodynamic bodywork and bright glossy paint\" },\n { id: \"supercar\", label: \"Supercar\", subcategory: \"cars-performance\", description: \"Exotic mid-engined supercar with scissor doors, an ultra-low hood, huge rear intakes and a carbon-fiber rear wing\" },\n { id: \"convertible\", label: \"Convertible\", subcategory: \"cars-performance\", description: \"Two-seat convertible with the soft top down, a long sculpted hood and wind streaming past low-cut doors\" },\n { id: \"grand-tourer\", label: \"Grand Tourer\", subcategory: \"cars-performance\", description: \"Elegant grand-touring coupe with a long flowing hood, four exhausts and luxurious proportions\" },\n { id: \"roadster\", label: \"Roadster\", subcategory: \"cars-performance\", description: \"Compact two-seat roadster with a wraparound windshield, soft top tucked away and classic top-down silhouette\" },\n { id: \"racing-car\", label: \"Racing Car\", subcategory: \"cars-performance\", description: \"Open-wheel formula racing car with slick tires, a large rear wing, halo cockpit and aerodynamic sidepods covered in sponsor logos\" },\n { id: \"rally-car\", label: \"Rally Car\", subcategory: \"cars-performance\", description: \"Dirt-splattered rally hatchback with knobby tires, huge mud flaps, roof-mounted lights and race liveries\" },\n { id: \"drift-car\", label: \"Drift Car\", subcategory: \"cars-performance\", description: \"Aggressive drift-tuned coupe with a wide body kit, oversized rear wing, neon underglow and tire smoke trailing behind\" },\n\n // -------------------- Motorcycles --------------------\n { id: \"sportbike\", label: \"Sportbike\", subcategory: \"motorcycles\", description: \"Aerodynamic sport motorcycle with a crouched riding stance, full fairings, sticky tires and bright race-style graphics\" },\n { id: \"cruiser\", label: \"Cruiser\", subcategory: \"motorcycles\", description: \"Low-slung cruiser motorcycle with a long teardrop tank, swept-back handlebars, chrome exhausts and fat rear tire\" },\n { id: \"chopper\", label: \"Chopper\", subcategory: \"motorcycles\", description: \"Stretched custom chopper with a raked-out front end, tall ape-hanger handlebars, skinny front wheel and chrome everywhere\" },\n { id: \"dirt-bike\", label: \"Dirt Bike\", subcategory: \"motorcycles\", description: \"Off-road dirt bike with knobby tires, tall suspension, plastic fairings in bright colors and high handlebars\" },\n { id: \"scooter\", label: \"Scooter\", subcategory: \"motorcycles\", description: \"Compact step-through scooter with a smooth body shell, small wheels, a flat footrest and an under-seat storage bump\" },\n { id: \"moped\", label: \"Moped\", subcategory: \"motorcycles\", description: \"Small pedal-start moped with a simple steel frame, basket up front and a tiny gas engine under the seat\" },\n { id: \"cafe-racer\", label: \"Cafe Racer\", subcategory: \"motorcycles\", description: \"Stripped-down cafe racer motorcycle with clip-on bars, a humped solo seat, exposed frame and minimalist tank\" },\n\n // -------------------- Bicycles & Human-Powered --------------------\n { id: \"road-bike\", label: \"Road Bike\", subcategory: \"bicycles\", description: \"Lightweight road bike with drop handlebars, skinny high-pressure tires and an aerodynamic carbon frame\" },\n { id: \"mountain-bike\", label: \"Mountain Bike\", subcategory: \"bicycles\", description: \"Rugged mountain bike with knobby tires, front suspension fork, flat handlebars and a mud-splattered frame\" },\n { id: \"bmx\", label: \"BMX Bike\", subcategory: \"bicycles\", description: \"Stunt BMX bike with a small frame, pegs on the axles, chunky tires and a cross-brace handlebar\" },\n { id: \"cruiser-bike\", label: \"Beach Cruiser\", subcategory: \"bicycles\", description: \"Relaxed beach cruiser bicycle with a curved frame, swept-back handlebars, wide seat and balloon tires\" },\n { id: \"penny-farthing\", label: \"Penny Farthing\", subcategory: \"bicycles\", description: \"Victorian penny-farthing bicycle with an enormous front wheel, tiny rear wheel and a perched leather saddle high above\" },\n { id: \"unicycle\", label: \"Unicycle\", subcategory: \"bicycles\", description: \"Single-wheeled unicycle with a tall seat post, simple pedals on the hub and a minimalist circus look\" },\n { id: \"skateboard\", label: \"Skateboard\", subcategory: \"bicycles\", description: \"Wooden skateboard deck with grip tape on top, four polyurethane wheels and colorful graphic art on the underside\" },\n { id: \"kick-scooter\", label: \"Kick Scooter\", subcategory: \"bicycles\", description: \"Two-wheeled kick scooter with a tall T-handle, narrow deck and small hard wheels\" },\n\n // -------------------- Trucks --------------------\n { id: \"pickup-truck\", label: \"Pickup Truck\", subcategory: \"trucks\", description: \"Full-size pickup truck with a tall crew cab, open rear bed, chrome grille and aggressive off-road tires\" },\n { id: \"semi-truck\", label: \"Semi Truck\", subcategory: \"trucks\", description: \"Long-haul semi truck with a sleeper cab, tall chrome exhaust stacks and a massive articulated trailer behind\" },\n { id: \"dump-truck\", label: \"Dump Truck\", subcategory: \"trucks\", description: \"Heavy-duty dump truck with a raised tipping bed, massive off-road tires and yellow construction livery\" },\n { id: \"tow-truck\", label: \"Tow Truck\", subcategory: \"trucks\", description: \"Tow truck with a hydraulic boom, hook and flat recovery bed, rotating amber warning lights and bold signage\" },\n { id: \"delivery-van\", label: \"Delivery Van\", subcategory: \"trucks\", description: \"White delivery van with a boxy cargo hold, sliding side door, roof racks and corporate livery decals\" },\n { id: \"ice-cream-truck\", label: \"Ice Cream Truck\", subcategory: \"trucks\", description: \"Cheerful ice cream truck with pastel paint, a window counter displaying treats, colorful decals and a cone-shaped rooftop ornament\" },\n { id: \"food-truck\", label: \"Food Truck\", subcategory: \"trucks\", description: \"Stylized food truck with a folding service window, chalkboard menu, string lights and a bright custom wrap\" },\n { id: \"box-truck\", label: \"Box Truck\", subcategory: \"trucks\", description: \"Medium box truck with a plain rectangular cargo box, roll-up rear door and a forward cab\" },\n { id: \"ambulance\", label: \"Ambulance\", subcategory: \"trucks\", description: \"Emergency medical ambulance with a tall white box body, red cross and EMS livery, flashing red-and-blue lightbar, side warning lights and a high-visibility chevron pattern across the rear doors\" },\n\n // -------------------- Transit (Bus / Rail / Horse-Drawn) --------------------\n { id: \"city-bus\", label: \"City Bus\", subcategory: \"transit\", description: \"Modern articulated city bus with a low floor, sliding doors, destination sign up front and an advertising wrap\" },\n { id: \"school-bus\", label: \"School Bus\", subcategory: \"transit\", description: \"Classic yellow American school bus with black trim, flashing red stop signs, stop-arm out and black stenciled numbers\" },\n { id: \"double-decker\", label: \"Double-Decker Bus\", subcategory: \"transit\", description: \"Iconic red double-decker bus with a rounded roof, open staircase inside and destination scroll up front\" },\n { id: \"coach-bus\", label: \"Coach Bus\", subcategory: \"transit\", description: \"Long-distance coach bus with tinted panoramic windows, luggage bays underneath and streamlined bodywork\" },\n { id: \"train\", label: \"Train\", subcategory: \"transit\", description: \"Modern passenger train with a sleek streamlined nose, panoramic windows and a line of gleaming cars\" },\n { id: \"steam-locomotive\", label: \"Steam Locomotive\", subcategory: \"transit\", description: \"Black steam locomotive with a tall smokestack puffing steam, a boiler, connecting rods and a coal tender behind\" },\n { id: \"bullet-train\", label: \"Bullet Train\", subcategory: \"transit\", description: \"High-speed bullet train with an aerodynamic pointed nose, smooth white-and-blue livery and narrow windows\" },\n { id: \"subway\", label: \"Subway Train\", subcategory: \"transit\", description: \"Stainless-steel subway car with graffiti-resistant panels, sliding doors and rows of fluorescent lights inside\" },\n { id: \"tram\", label: \"Tram\", subcategory: \"transit\", description: \"Classic city tram car with a boxy wooden-framed body, overhead pantograph and rails running beneath\" },\n { id: \"stagecoach\", label: \"Stagecoach\", subcategory: \"transit\", description: \"Wild-west stagecoach with a wooden body, leaf-spring suspension, roof luggage rack and a team of horses harnessed in front\" },\n { id: \"horse-carriage\", label: \"Horse-Drawn Carriage\", subcategory: \"transit\", description: \"Ornate horse-drawn carriage with polished wood panels, large spoked wheels and a velvet-upholstered cabin\" },\n\n // -------------------- Aircraft --------------------\n { id: \"airliner\", label: \"Airliner\", subcategory: \"aircraft\", description: \"Wide-body commercial airliner with twin jet engines under swept wings, rows of oval windows and a tall swept tail fin\" },\n { id: \"biplane\", label: \"Biplane\", subcategory: \"aircraft\", description: \"Vintage biplane with two stacked wings connected by struts and wire bracing, an open cockpit and a wooden propeller\" },\n { id: \"propeller-plane\", label: \"Propeller Plane\", subcategory: \"aircraft\", description: \"Small single-engine propeller plane with a spinning nose prop, high wings, fixed landing gear and a bubble cockpit\" },\n { id: \"helicopter\", label: \"Helicopter\", subcategory: \"aircraft\", description: \"Utility helicopter with a large main rotor on top, a slim tail boom, skids underneath and a bubble-front cockpit\" },\n { id: \"seaplane\", label: \"Seaplane\", subcategory: \"aircraft\", description: \"Seaplane with twin pontoon floats instead of wheels, high wings and a propeller, resting on calm water\" },\n { id: \"hot-air-balloon\", label: \"Hot Air Balloon\", subcategory: \"aircraft\", description: \"Giant hot-air balloon with a colorful rainbow-striped fabric envelope, a roaring flame burner flaring upward into the mouth and a wicker passenger basket suspended below by braided cables\" },\n { id: \"blimp\", label: \"Blimp\", subcategory: \"aircraft\", description: \"Sausage-shaped blimp airship with a sleek silver envelope, small rear fins and a slung gondola beneath\" },\n { id: \"airship\", label: \"Airship / Dirigible\", subcategory: \"aircraft\", description: \"Massive rigid lighter-than-air dirigible with a long cigar-shaped fabric-covered metal frame, large rear stabilizer fins, multiple slung engine gondolas and a long passenger cabin running underneath the hull\" },\n { id: \"glider\", label: \"Glider\", subcategory: \"aircraft\", description: \"Elegant sailplane glider with ultra-long narrow wings, no engine and a teardrop cockpit pod\" },\n { id: \"paraglider\", label: \"Paraglider\", subcategory: \"aircraft\", description: \"Foot-launched paraglider with a wide elliptical soft-fabric ram-air wing arched overhead, dozens of slender suspension lines converging into a tandem harness with a seated pilot\" },\n { id: \"microlight\", label: \"Microlight Aircraft\", subcategory: \"aircraft\", description: \"Lightweight single-pilot microlight aircraft with an exposed tubular metal frame, fabric-covered high wings, a small pusher propeller engine behind the open seat and tricycle landing gear\" },\n { id: \"drone\", label: \"Drone\", subcategory: \"aircraft\", description: \"Quadcopter camera drone with four spinning rotors on slim arms, a central body and a gimbaled camera underneath\" },\n\n // -------------------- Watercraft --------------------\n { id: \"yacht\", label: \"Yacht\", subcategory: \"watercraft\", description: \"Sleek luxury motor yacht with multiple decks, tinted windows, a radar mast and glossy white hull cutting through blue water\" },\n { id: \"sailboat\", label: \"Sailboat\", subcategory: \"watercraft\", description: \"Graceful sailboat with a tall mast, taut white sails catching the wind and a narrow fiberglass hull\" },\n { id: \"speedboat\", label: \"Speedboat\", subcategory: \"watercraft\", description: \"Fast powerboat with a pointed deep-V hull, low windshield and a roaring outboard motor kicking up a wake\" },\n { id: \"cruise-ship\", label: \"Cruise Ship\", subcategory: \"watercraft\", description: \"Massive cruise ship with multiple towering decks, rows of balconies, bright funnels and a pointed bow\" },\n { id: \"cargo-ship\", label: \"Cargo Ship\", subcategory: \"watercraft\", description: \"Giant container cargo ship stacked high with rainbow-colored shipping containers, a bridge tower at the stern\" },\n { id: \"canoe\", label: \"Canoe\", subcategory: \"watercraft\", description: \"Classic wooden canoe with a pointed bow and stern, a cedar-ribbed interior and a single paddle resting inside\" },\n { id: \"kayak\", label: \"Kayak\", subcategory: \"watercraft\", description: \"Slim plastic kayak with a low profile, enclosed cockpit opening and a double-bladed paddle\" },\n { id: \"rowboat\", label: \"Rowboat\", subcategory: \"watercraft\", description: \"Small wooden rowboat with flat-bottom planks, oarlocks on the gunwales and two wooden oars\" },\n { id: \"jet-ski\", label: \"Jet Ski\", subcategory: \"watercraft\", description: \"Stand-up personal watercraft with an aggressive fairing, handlebars, a single seat and a jet-propulsion nozzle\" },\n { id: \"submarine\", label: \"Submarine\", subcategory: \"watercraft\", description: \"Military submarine with a long cylindrical hull, a conning tower with periscopes and a bulbous bow diving through deep water\" },\n { id: \"pirate-ship\", label: \"Pirate Ship\", subcategory: \"watercraft\", description: \"Wooden pirate galleon with tall masts, square sails, a figurehead on the bow, cannons along the hull and a tattered black flag\" },\n { id: \"hovercraft\", label: \"Hovercraft\", subcategory: \"watercraft\", description: \"Air-cushion hovercraft riding on a thick inflated rubber skirt billowing outward, large rear ducted fans for propulsion, a flat boxy passenger cabin on top and capable of skimming over both water and land\" },\n\n // -------------------- Military --------------------\n { id: \"tank\", label: \"Tank\", subcategory: \"military\", description: \"Heavy battle tank with a long cannon barrel, rotating turret, thick sloped armor and wide continuous tracks\" },\n { id: \"humvee\", label: \"Humvee\", subcategory: \"military\", description: \"Military Humvee with a wide stance, armored angular bodywork, off-road tires and a roof-mounted turret\" },\n { id: \"armored-personnel-carrier\", label: \"Armored Personnel Carrier\", subcategory: \"military\", description: \"Tracked armored personnel carrier with a boxy hull, rear ramp and a small turret up top\" },\n { id: \"fighter-jet\", label: \"Fighter Jet\", subcategory: \"military\", description: \"Supersonic fighter jet with swept delta wings, a sharp pointed nose, twin tail fins and missiles on wing pylons\" },\n { id: \"stealth-bomber\", label: \"Stealth Bomber\", subcategory: \"military\", description: \"Flying-wing stealth bomber with a matte black triangular silhouette, no tail fins and faceted radar-absorbing surfaces\" },\n { id: \"destroyer\", label: \"Destroyer\", subcategory: \"military\", description: \"Sleek naval destroyer with a long grey hull, gun turrets, missile launchers and a radar-bristling superstructure\" },\n { id: \"aircraft-carrier\", label: \"Aircraft Carrier\", subcategory: \"military\", description: \"Massive aircraft carrier with a flat-top flight deck, island tower with radar arrays and fighter jets parked in rows\" },\n\n // -------------------- Construction --------------------\n { id: \"bulldozer\", label: \"Bulldozer\", subcategory: \"construction\", description: \"Yellow construction bulldozer with a huge push blade up front, heavy tracks and a tall exhaust stack\" },\n { id: \"excavator\", label: \"Excavator\", subcategory: \"construction\", description: \"Hydraulic excavator with an articulated arm, toothed bucket, rotating cab and heavy tracked base\" },\n { id: \"crane-truck\", label: \"Crane Truck\", subcategory: \"construction\", description: \"Mobile crane truck with a massive telescoping boom extended upward, stabilizer outriggers and a heavy counterweight\" },\n { id: \"cement-mixer\", label: \"Cement Mixer\", subcategory: \"construction\", description: \"Cement mixer truck with a large rotating drum, chute at the rear and a boxy cab\" },\n { id: \"forklift\", label: \"Forklift\", subcategory: \"construction\", description: \"Warehouse forklift with twin steel fork tines raised in front, a roll cage over the driver and a compact counterweight rear\" },\n { id: \"backhoe\", label: \"Backhoe\", subcategory: \"construction\", description: \"Backhoe loader with a front bucket for scooping and a rear articulated arm with a toothed digging bucket\" },\n { id: \"tractor\", label: \"Tractor\", subcategory: \"construction\", description: \"Farm tractor with large knobby rear tires, smaller front tires, a roof canopy and a towing hitch at the back\" },\n\n // -------------------- Sci-Fi / Fantasy --------------------\n { id: \"spaceship\", label: \"Spaceship\", subcategory: \"sci-fi\", description: \"Sleek interstellar spaceship with curved fuselage, glowing engine nozzles, antenna arrays and a command bridge window\" },\n { id: \"starfighter\", label: \"Starfighter\", subcategory: \"sci-fi\", description: \"Agile single-pilot starfighter with swept wings, laser cannons on the wingtips, a bubble cockpit and glowing thrusters\" },\n { id: \"hovercar\", label: \"Hovercar\", subcategory: \"sci-fi\", description: \"Futuristic hovercar floating above the ground with no wheels, glowing underside thrusters, seamless bodywork and a curved canopy\" },\n { id: \"mech\", label: \"Mech\", subcategory: \"sci-fi\", description: \"Giant bipedal mech robot with armored plating, hydraulic pistons, a cockpit in the torso and heavy weapons mounted on the arms\" },\n { id: \"flying-saucer\", label: \"Flying Saucer\", subcategory: \"sci-fi\", description: \"Classic UFO flying saucer with a metallic disc body, glowing porthole lights around the rim and a domed cockpit on top\" },\n { id: \"space-shuttle\", label: \"Space Shuttle\", subcategory: \"sci-fi\", description: \"Space shuttle orbiter with white delta wings, a black heat-shield underbelly and huge rocket nozzles at the rear\" },\n { id: \"rocket\", label: \"Rocket\", subcategory: \"sci-fi\", description: \"Tall cylindrical rocket with pointed nose cone, tail fins, booster stages and flames roaring from the engines on launch\" },\n { id: \"hoverboard\", label: \"Hoverboard\", subcategory: \"sci-fi\", description: \"Futuristic hoverboard floating inches above the ground with glowing underside jets and a sleek single-plank body\" },\n] as const\n\nconst vehicleById = new Map<string, Vehicle>(VEHICLES.map((v) => [v.id, v]))\n\nexport function getVehicle(id: string | undefined | null): Vehicle | undefined {\n if (!id) return undefined\n return vehicleById.get(id)\n}\n\nexport function getVehicleLabel(id: string | undefined | null, fallback?: string): string {\n const v = getVehicle(id)\n if (v) return v.label\n if (fallback !== undefined) return fallback\n return (id ?? \"\").replace(/-/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase())\n}\n\nexport const VEHICLE_IDS: ReadonlyArray<string> = VEHICLES.map((v) => v.id)\n\nexport const VEHICLE_SUBCATEGORY_LABELS: Readonly<Record<VehicleSubcategory, string>> = {\n \"cars-classic\": \"Classic Cars\",\n \"cars-everyday\": \"Everyday Cars\",\n \"cars-performance\": \"Performance Cars\",\n motorcycles: \"Motorcycles\",\n bicycles: \"Bicycles & Human-Powered\",\n trucks: \"Trucks\",\n transit: \"Bus / Rail / Carriage\",\n aircraft: \"Aircraft\",\n watercraft: \"Watercraft\",\n military: \"Military\",\n construction: \"Construction\",\n \"sci-fi\": \"Sci-Fi\",\n}\n\nexport const VEHICLE_SUBCATEGORY_ORDER: ReadonlyArray<VehicleSubcategory> = [\n \"cars-classic\",\n \"cars-everyday\",\n \"cars-performance\",\n \"motorcycles\",\n \"bicycles\",\n \"trucks\",\n \"transit\",\n \"aircraft\",\n \"watercraft\",\n \"military\",\n \"construction\",\n \"sci-fi\",\n]\n","/**\n * Canonical catalog of weapon presets for the Object entity node.\n *\n * When the Object category is \"weapon\", users pick a specific weapon from\n * this catalog. The picker auto-fills the object's `objectName` and\n * `description` so the existing `buildObjectPrompt` pipeline just works —\n * no backend prompt changes needed.\n *\n * Organized by weapon family: swords, daggers, axes, polearms, bows,\n * blunt/impact, throwing, modern firearms, historical firearms, explosives\n * & siege, sci-fi, and fantasy.\n */\n\nexport type WeaponSubcategory =\n | \"swords\"\n | \"daggers\"\n | \"axes\"\n | \"polearms\"\n | \"bows\"\n | \"blunt\"\n | \"throwing\"\n | \"firearms-modern\"\n | \"firearms-historical\"\n | \"explosives-siege\"\n | \"sci-fi\"\n | \"fantasy\"\n\nexport interface Weapon {\n readonly id: string\n readonly label: string\n readonly subcategory: WeaponSubcategory\n readonly description: string\n}\n\nexport const WEAPONS: ReadonlyArray<Weapon> = [\n // -------------------- Swords --------------------\n { id: \"katana\", label: \"Katana\", subcategory: \"swords\", description: \"Japanese katana with a single-edged gently curved blade, wrapped rayskin handle, disc-shaped tsuba guard and a polished mirror finish\" },\n { id: \"longsword\", label: \"Longsword\", subcategory: \"swords\", description: \"Medieval double-edged longsword with a straight tapering blade, cross guard, leather-wrapped grip and a round pommel\" },\n { id: \"broadsword\", label: \"Broadsword\", subcategory: \"swords\", description: \"Heavy broadsword with a wide straight double-edged blade, basket hilt guard and a sturdy leather-wrapped grip\" },\n { id: \"rapier\", label: \"Rapier\", subcategory: \"swords\", description: \"Slim rapier with a long narrow thrusting blade, ornate swept-hilt basket guard and a spherical pommel\" },\n { id: \"saber\", label: \"Saber\", subcategory: \"swords\", description: \"Cavalry saber with a single-edged curved blade, brass knuckle-bow guard and a ribbed leather grip\" },\n { id: \"scimitar\", label: \"Scimitar\", subcategory: \"swords\", description: \"Curved scimitar with a wide single-edged blade, ornate crossguard and a rounded metal pommel\" },\n { id: \"claymore\", label: \"Claymore\", subcategory: \"swords\", description: \"Massive two-handed Scottish claymore with a long straight blade, forward-angled crossguard and a large leather-bound grip\" },\n { id: \"zweihander\", label: \"Zweihänder\", subcategory: \"swords\", description: \"Two-handed German Renaissance greatsword with an enormous straight double-edged blade, leather-wrapped ricasso above the crossguard, parrying lugs partway up the blade and a long extended grip ending in a heavy pear-shaped pommel\" },\n { id: \"cutlass\", label: \"Cutlass\", subcategory: \"swords\", description: \"Pirate cutlass with a short curved single-edged blade, brass cup-shaped hand guard and a weathered wooden grip\" },\n { id: \"wakizashi\", label: \"Wakizashi\", subcategory: \"swords\", description: \"Short Japanese wakizashi companion blade with a gently curved edge, small tsuba and rayskin-wrapped handle\" },\n { id: \"falchion\", label: \"Falchion\", subcategory: \"swords\", description: \"Heavy single-edged falchion with a cleaver-like tapering blade, simple crossguard and a riveted leather grip\" },\n\n // -------------------- Daggers & Knives --------------------\n { id: \"dagger\", label: \"Dagger\", subcategory: \"daggers\", description: \"Classic double-edged dagger with a narrow pointed blade, crossguard and a wrapped leather grip\" },\n { id: \"bowie-knife\", label: \"Bowie Knife\", subcategory: \"daggers\", description: \"Large bowie knife with a clip-point blade, brass guard, stacked leather-washer handle and a crossguard\" },\n { id: \"kukri\", label: \"Kukri\", subcategory: \"daggers\", description: \"Nepalese kukri with a forward-curving broad blade, wooden handle and distinctive inwardly-angled recurve\" },\n { id: \"stiletto\", label: \"Stiletto\", subcategory: \"daggers\", description: \"Slim stiletto with a long needle-thin triangular blade, minimal crossguard and a tapered handle\" },\n { id: \"dirk\", label: \"Dirk\", subcategory: \"daggers\", description: \"Scottish dirk with a long straight single-edged blade, interwoven Celtic-knot handle and an ornate pommel\" },\n { id: \"tanto\", label: \"Tanto\", subcategory: \"daggers\", description: \"Japanese tanto dagger with an angular chisel-point tip, small tsuba and wrapped rayskin handle\" },\n { id: \"switchblade\", label: \"Switchblade\", subcategory: \"daggers\", description: \"Pocket switchblade with a spring-loaded folding blade, pearl or resin side panels and a polished release button\" },\n { id: \"trench-knife\", label: \"Trench Knife\", subcategory: \"daggers\", description: \"Military trench knife with a slim double-edged blade and a brass knuckle-duster handguard wrapping the grip\" },\n\n // -------------------- Axes --------------------\n { id: \"battle-axe\", label: \"Battle Axe\", subcategory: \"axes\", description: \"Heavy two-handed battle axe with a wide curved cutting edge, bearded profile and a long wooden haft bound with iron bands\" },\n { id: \"tomahawk\", label: \"Tomahawk\", subcategory: \"axes\", description: \"Light throwing tomahawk with a small single-bit iron head, straight wooden haft and leather wrapping near the grip\" },\n { id: \"hatchet\", label: \"Hatchet\", subcategory: \"axes\", description: \"Compact hatchet with a short wooden handle, small single-bit steel head and a hammered finish\" },\n { id: \"halberd\", label: \"Halberd\", subcategory: \"axes\", description: \"Long-pole halberd combining an axe blade, a thrusting spear point and a rear hook atop a tall wooden shaft\" },\n { id: \"greataxe\", label: \"Greataxe\", subcategory: \"axes\", description: \"Massive greataxe with a huge double-sided crescent head, iron reinforcing bands and a long heavy haft requiring two hands\" },\n { id: \"bearded-axe\", label: \"Bearded Axe\", subcategory: \"axes\", description: \"Viking bearded axe with an elongated lower blade edge, narrow iron head and a tall wooden haft wrapped with leather\" },\n\n // -------------------- Polearms --------------------\n { id: \"spear\", label: \"Spear\", subcategory: \"polearms\", description: \"Simple spear with a leaf-shaped iron spearhead lashed to a tall straight wooden shaft and a small butt cap at the base\" },\n { id: \"lance\", label: \"Lance\", subcategory: \"polearms\", description: \"Jousting lance with a long wooden shaft, conical steel tip and a flared hand guard protecting the grip\" },\n { id: \"pike\", label: \"Pike\", subcategory: \"polearms\", description: \"Very long pike with a small triangular spearhead mounted atop a towering wooden pole twice the height of a man\" },\n { id: \"glaive\", label: \"Glaive\", subcategory: \"polearms\", description: \"Glaive polearm with a long curved single-edged blade mounted on a wooden shaft, tapering to a small crossguard\" },\n { id: \"trident\", label: \"Trident\", subcategory: \"polearms\", description: \"Three-pronged trident with sharp barbed tines, a central shaft and a long wooden pole\" },\n { id: \"naginata\", label: \"Naginata\", subcategory: \"polearms\", description: \"Japanese naginata with a curved single-edged blade mounted on a long lacquered wooden pole with silk wrappings\" },\n\n // -------------------- Bows & Crossbows --------------------\n { id: \"longbow\", label: \"Longbow\", subcategory: \"bows\", description: \"Tall English longbow with a single piece of yew wood, waxed linen string and a leather-wrapped grip\" },\n { id: \"recurve-bow\", label: \"Recurve Bow\", subcategory: \"bows\", description: \"Traditional recurve bow with limbs that curve away from the archer, a leather-wrapped riser and a taut bowstring\" },\n { id: \"compound-bow\", label: \"Compound Bow\", subcategory: \"bows\", description: \"Modern compound bow with aluminum cams, pulley wheels at each tip, carbon-fiber arrow rest and a sighting pin array\" },\n { id: \"crossbow\", label: \"Crossbow\", subcategory: \"bows\", description: \"Medieval crossbow with a horizontal wooden stock, steel prod, taut string and a trigger mechanism under the rail\" },\n { id: \"short-bow\", label: \"Short Bow\", subcategory: \"bows\", description: \"Compact wooden short bow with a simple curved profile, a waxed string and a leather grip in the middle\" },\n\n // -------------------- Blunt & Impact --------------------\n { id: \"mace\", label: \"Mace\", subcategory: \"blunt\", description: \"Medieval flanged mace with a heavy crowned head bearing protruding iron flanges atop a short iron shaft\" },\n { id: \"war-hammer\", label: \"War Hammer\", subcategory: \"blunt\", description: \"Long-handled war hammer with a heavy iron head featuring a flat striking face on one side and a curved spike on the other\" },\n { id: \"club\", label: \"Club\", subcategory: \"blunt\", description: \"Simple wooden club with a thick knotted head, tapering shaft and a well-worn leather grip near the base\" },\n { id: \"morning-star\", label: \"Morning Star\", subcategory: \"blunt\", description: \"Morning star with a wooden shaft topped by a large iron ball bristling with tall spikes in every direction\" },\n { id: \"flail\", label: \"Flail\", subcategory: \"blunt\", description: \"Military flail with a spiked iron ball connected by a short chain to a wooden haft with an iron end cap\" },\n { id: \"nunchaku\", label: \"Nunchaku\", subcategory: \"blunt\", description: \"Martial-arts nunchaku with two polished wooden batons connected by a short length of braided cord or chain\" },\n\n // -------------------- Throwing --------------------\n { id: \"shuriken\", label: \"Shuriken\", subcategory: \"throwing\", description: \"Metal throwing star with multiple razor-sharp points radiating from a central hub and a blackened steel finish\" },\n { id: \"throwing-knife\", label: \"Throwing Knife\", subcategory: \"throwing\", description: \"Balanced throwing knife with a leaf-shaped double-edged blade, minimal handle and a polished steel finish\" },\n { id: \"boomerang\", label: \"Boomerang\", subcategory: \"throwing\", description: \"Curved wooden boomerang with an elbow bend, painted tribal patterns and a smooth aerodynamic profile\" },\n { id: \"javelin\", label: \"Javelin\", subcategory: \"throwing\", description: \"Lightweight throwing javelin with a slim steel tip, tapered wooden shaft and a leather grip wrap near the balance point\" },\n { id: \"bolas\", label: \"Bolas\", subcategory: \"throwing\", description: \"Three weighted stone or iron balls tied together by braided leather cords meeting at a central knot\" },\n { id: \"slingshot\", label: \"Slingshot\", subcategory: \"throwing\", description: \"Y-shaped wooden slingshot with a forked handle whittled from a tree branch, two thick rubber elastic bands stretched between the prongs and a small leather pouch in the middle for cradling stone projectiles\" },\n { id: \"blowgun\", label: \"Blowgun\", subcategory: \"throwing\", description: \"Long hollow blowpipe traditionally used by indigenous hunters, fashioned from a single piece of bamboo or carved hardwood with a small mouthpiece at one end and slender feather-fletched darts loaded for breath-launched shots\" },\n\n // -------------------- Modern Firearms --------------------\n { id: \"pistol\", label: \"Pistol\", subcategory: \"firearms-modern\", description: \"Modern semi-automatic pistol with a matte black polymer frame, ribbed slide, trigger guard and a flush magazine base\" },\n { id: \"revolver\", label: \"Revolver\", subcategory: \"firearms-modern\", description: \"Six-shooter revolver with a rotating cylinder, long barrel, hammer cocked back and a checkered wooden grip\" },\n { id: \"assault-rifle\", label: \"Assault Rifle\", subcategory: \"firearms-modern\", description: \"Military assault rifle with a long barrel, collapsible stock, optical sight on the rail and a curved detachable magazine\" },\n { id: \"shotgun\", label: \"Shotgun\", subcategory: \"firearms-modern\", description: \"Pump-action shotgun with a wide bore barrel, tactical fore-end, tube magazine underneath and a wooden or synthetic stock\" },\n { id: \"smg\", label: \"Submachine Gun\", subcategory: \"firearms-modern\", description: \"Compact submachine gun with a short barrel, side-mounted magazine, folding wire stock and an integral foregrip\" },\n { id: \"sniper-rifle\", label: \"Sniper Rifle\", subcategory: \"firearms-modern\", description: \"Bolt-action sniper rifle with a long barrel, high-magnification scope, bipod legs and an ergonomic polymer stock\" },\n { id: \"machine-gun\", label: \"Machine Gun\", subcategory: \"firearms-modern\", description: \"Heavy belt-fed machine gun with a long finned barrel, bipod, carry handle and an ammunition belt feeding from the side\" },\n { id: \"service-pistol\", label: \"Service Pistol\", subcategory: \"firearms-modern\", description: \"Modern semi-automatic service sidearm in the Glock or Beretta style with a matte black polymer frame, ribbed steel slide, accessory rail under the dust cover, three-dot iron sights and a flush double-stack magazine\" },\n { id: \"hunting-rifle\", label: \"Hunting Rifle\", subcategory: \"firearms-modern\", description: \"Bolt-action hunting rifle with a polished walnut wood stock, blued steel barrel, mounted variable-zoom scope on the receiver rail, leather sling and a checkered grip and forend for steady offhand shooting\" },\n\n // -------------------- Historical Firearms --------------------\n { id: \"musket\", label: \"Musket\", subcategory: \"firearms-historical\", description: \"Long flintlock musket with a smooth-bore iron barrel, walnut stock, brass fittings and a bayonet fixed near the muzzle\" },\n { id: \"flintlock-pistol\", label: \"Flintlock Pistol\", subcategory: \"firearms-historical\", description: \"Ornate flintlock pistol with a curved wooden grip, engraved brass fittings, a flint hammer and a single long barrel\" },\n { id: \"blunderbuss\", label: \"Blunderbuss\", subcategory: \"firearms-historical\", description: \"Short flintlock blunderbuss with a flared muzzle, brass fittings on a stout wooden stock and a pirate-era presence\" },\n { id: \"dueling-pistol\", label: \"Dueling Pistol\", subcategory: \"firearms-historical\", description: \"Elegant dueling pistol with a slim octagonal barrel, finely engraved lockwork and a polished walnut grip\" },\n\n // -------------------- Explosives & Siege --------------------\n { id: \"grenade\", label: \"Grenade\", subcategory: \"explosives-siege\", description: \"Pineapple-textured iron fragmentation grenade with a spoon lever held in place by a pulled safety pin\" },\n { id: \"stick-grenade\", label: \"Stick Grenade\", subcategory: \"explosives-siege\", description: \"Cylindrical stick grenade with an iron warhead mounted atop a long wooden handle and a pull-string fuse at the base\" },\n { id: \"dynamite\", label: \"Dynamite\", subcategory: \"explosives-siege\", description: \"Bundled sticks of red dynamite wrapped with twine and joined to a long sputtering fuse with a burning tip\" },\n { id: \"bomb\", label: \"Cartoon Bomb\", subcategory: \"explosives-siege\", description: \"Round black cartoon bomb with a smoking curled fuse coming out of the top and a shiny spherical iron shell\" },\n { id: \"rocket-launcher\", label: \"Rocket Launcher\", subcategory: \"explosives-siege\", description: \"Shoulder-fired rocket launcher with a long tube, forward grip, rear exhaust cone and optical targeting sight\" },\n { id: \"cannon\", label: \"Cannon\", subcategory: \"explosives-siege\", description: \"Cast-iron muzzle-loading cannon mounted on a wooden wheeled carriage with a long smooth-bore barrel and a smoking vent\" },\n { id: \"catapult\", label: \"Catapult\", subcategory: \"explosives-siege\", description: \"Wooden siege catapult with a long throwing arm cocked back, a counterweight or torsion bundle and a basket loaded with stone\" },\n { id: \"trebuchet\", label: \"Trebuchet\", subcategory: \"explosives-siege\", description: \"Tall medieval trebuchet with a massive counterweight, long throwing arm, braided sling and heavy timber frame\" },\n\n // -------------------- Sci-Fi --------------------\n { id: \"laser-pistol\", label: \"Laser Pistol\", subcategory: \"sci-fi\", description: \"Compact sci-fi laser pistol with glowing neon energy coils, a ridged metal body and a short emitter barrel\" },\n { id: \"plasma-rifle\", label: \"Plasma Rifle\", subcategory: \"sci-fi\", description: \"Futuristic plasma rifle with glowing blue energy cells, ventilated barrel shrouds and a holographic sight\" },\n { id: \"lightsaber\", label: \"Lightsaber\", subcategory: \"sci-fi\", description: \"Laser sword with a metallic ribbed handle emitting a tall glowing blade of saturated energy with a hazy plasma halo\" },\n { id: \"blaster\", label: \"Blaster\", subcategory: \"sci-fi\", description: \"Retro-futuristic blaster pistol with a chunky body, glowing energy chamber, cooling vents and a scope mounted on top\" },\n { id: \"phaser\", label: \"Phaser\", subcategory: \"sci-fi\", description: \"Sleek sci-fi phaser with a minimalist curved grip, glowing emitter tip and a smooth panel controlling intensity\" },\n { id: \"rail-gun\", label: \"Rail Gun\", subcategory: \"sci-fi\", description: \"Heavy electromagnetic rail gun with parallel metal rails, massive capacitors along the body and a glowing projectile chamber\" },\n { id: \"emp-grenade\", label: \"EMP Grenade\", subcategory: \"sci-fi\", description: \"Spherical electromagnetic pulse grenade with exposed coils, glowing blue indicator lights and a holographic arming dial\" },\n { id: \"plasma-sword\", label: \"Plasma Sword / Lightsaber\", subcategory: \"sci-fi\", description: \"Sci-fi energy blade with a metallic ridged hilt projecting a tall column of saturated plasma energy, surrounded by a bright halo of glowing light, casting colored reflections on the wielder and humming softly with contained power\" },\n { id: \"gravity-gun\", label: \"Gravity Gun\", subcategory: \"sci-fi\", description: \"Sci-fi physics-manipulating ranged weapon with a chunky metallic body, three articulated prongs at the muzzle that crackle with blue gravitational energy, exposed power conduits along the barrel and a heavy two-handed grip with a glowing trigger assembly\" },\n\n // -------------------- Fantasy / Magical --------------------\n { id: \"enchanted-sword\", label: \"Enchanted Sword\", subcategory: \"fantasy\", description: \"Enchanted sword with a glowing rune-etched blade, gold-inlaid crossguard and a gemstone embedded in the pommel\" },\n { id: \"magic-staff\", label: \"Magic Staff\", subcategory: \"fantasy\", description: \"Tall gnarled wizard's staff with a twisted wooden shaft ending in a crown of branches holding a glowing crystal\" },\n { id: \"runed-dagger\", label: \"Runed Dagger\", subcategory: \"fantasy\", description: \"Mystical dagger with a blade inscribed in glowing runes, a bone handle and dark energy swirling along the edge\" },\n { id: \"wizard-wand\", label: \"Wizard Wand\", subcategory: \"fantasy\", description: \"Slender wooden wand with knurled swirls, a leather grip and tiny sparks of magic leaking from the pointed tip\" },\n { id: \"war-horn\", label: \"War Horn\", subcategory: \"fantasy\", description: \"Massive curved war horn bound in leather and silver bands with a mouthpiece at one end and a flared bellowing opening at the other\" },\n { id: \"sorcerer-orb\", label: \"Sorcerer's Orb\", subcategory: \"fantasy\", description: \"Crystal sorcerer's orb held in a twisted silver claw-stand with swirling arcane mist suspended inside the glass sphere\" },\n] as const\n\nconst weaponById = new Map<string, Weapon>(WEAPONS.map((w) => [w.id, w]))\n\nexport function getWeapon(id: string | undefined | null): Weapon | undefined {\n if (!id) return undefined\n return weaponById.get(id)\n}\n\nexport function getWeaponLabel(id: string | undefined | null, fallback?: string): string {\n const w = getWeapon(id)\n if (w) return w.label\n if (fallback !== undefined) return fallback\n return (id ?? \"\").replace(/-/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase())\n}\n\nexport const WEAPON_IDS: ReadonlyArray<string> = WEAPONS.map((w) => w.id)\n\nexport const WEAPON_SUBCATEGORY_LABELS: Readonly<Record<WeaponSubcategory, string>> = {\n swords: \"Swords\",\n daggers: \"Daggers & Knives\",\n axes: \"Axes\",\n polearms: \"Polearms\",\n bows: \"Bows & Crossbows\",\n blunt: \"Blunt & Impact\",\n throwing: \"Throwing\",\n \"firearms-modern\": \"Firearms (Modern)\",\n \"firearms-historical\": \"Firearms (Historical)\",\n \"explosives-siege\": \"Explosives & Siege\",\n \"sci-fi\": \"Sci-Fi\",\n fantasy: \"Fantasy\",\n}\n\nexport const WEAPON_SUBCATEGORY_ORDER: ReadonlyArray<WeaponSubcategory> = [\n \"swords\",\n \"daggers\",\n \"axes\",\n \"polearms\",\n \"bows\",\n \"blunt\",\n \"throwing\",\n \"firearms-modern\",\n \"firearms-historical\",\n \"explosives-siege\",\n \"sci-fi\",\n \"fantasy\",\n]\n","/**\n * Multi-select helpers for parameter dimensions that allow up to N picks.\n *\n * A dimension's stored value can be:\n * - undefined / \"\" / [] → no pick\n * - string → single pick (back-compat with single-select fields)\n * - string[] → multi pick (1..N entries)\n *\n * `pickIds` normalizes any of those into a clean string[] (deduped, falsy\n * entries dropped). Pickers cap the array at `maxSelected` (FIFO replacement\n * is the picker's responsibility, not this helper's).\n *\n * Multi-select dimensions today: Person.ethnicity, Mood.mood, Aesthetic.aesthetic.\n */\n\nexport function pickIds(value: unknown): string[] {\n if (typeof value === \"string\") return value ? [value] : []\n if (!Array.isArray(value)) return []\n const seen = new Set<string>()\n const out: string[] = []\n for (const v of value) {\n if (typeof v !== \"string\" || !v || seen.has(v)) continue\n seen.add(v)\n out.push(v)\n }\n return out\n}\n\n/**\n * Cap a multi-pick array at `maxSelected`, FIFO-replacing the oldest entry\n * when the array is full and a new id is added. Returns a fresh array.\n */\nexport function togglePick(\n current: ReadonlyArray<string>,\n id: string,\n maxSelected: number,\n): string[] {\n if (current.includes(id)) return current.filter((v) => v !== id)\n if (current.length < maxSelected) return [...current, id]\n // FIFO replace: drop oldest, append new\n return [...current.slice(1), id]\n}\n","/**\n * Caption styles for the add-captions node. Static path uses FFmpeg drawtext;\n * kinetic styles render via Remotion (BurnCaptions composition).\n *\n * Single source of truth — imported by:\n * - backend route Zod (add-captions.ts)\n * - backend worker handler (ffmpeg.ts)\n * - backend MCP tool (verbs-video.ts)\n * - backend plan schema (plan-schemas.ts)\n * - frontend node config + cost helper\n * - packages/remotion overlay dispatcher\n */\nexport const STATIC_CAPTION_STYLES = [\"subtitle\"] as const\nexport const KINETIC_CAPTION_STYLES = [\n \"word-highlight\",\n \"karaoke\",\n \"tiktok-words\",\n \"word-pop\",\n \"bouncy\",\n] as const\nexport const ALL_CAPTION_STYLES = [...STATIC_CAPTION_STYLES, ...KINETIC_CAPTION_STYLES] as const\n\nexport type StaticCaptionStyle = (typeof STATIC_CAPTION_STYLES)[number]\nexport type KineticCaptionStyle = (typeof KINETIC_CAPTION_STYLES)[number]\nexport type CaptionStyle = (typeof ALL_CAPTION_STYLES)[number]\n\nconst KINETIC_SET = new Set<string>(KINETIC_CAPTION_STYLES)\n\nexport function isKineticCaptionStyle(style: string | undefined | null): style is KineticCaptionStyle {\n return style !== null && style !== undefined && KINETIC_SET.has(style)\n}\n","/**\n * i18n types and language registry for parameter-node pickers.\n *\n * Architecture:\n * - English is the canonical source — every catalog entry has its `label` and\n * `description` in English in the catalog file itself.\n * - Non-English translations live in sidecar files under\n * `packages/shared/src/i18n/<catalog>.<locale>.ts`.\n * - Each sidecar exports a `Record<id, LocalizedEntry>` keyed by entry id.\n * - Lazy-loaded per locale via dynamic import so users only download languages\n * they actually use.\n *\n * Translation rules (see picker-i18n design doc):\n * - `id` and `promptHint` are NEVER translated.\n * - `label` is translated when it's a common noun/adjective (e.g. \"Smoky Eye\"\n * → \"Ojo Ahumado\"). Proper names, brand names, model numbers, technical\n * units, and Latin/Italian/Japanese cinematography jargon stay in their\n * canonical form (e.g. Tim Walker, Sony A7III, chiaroscuro, anamorphic,\n * Y2K, ukiyo-e).\n * - `description` is translated freely, with proper nouns preserved inside.\n *\n * Search rule: pickers filter on the union of current-locale + English text,\n * so a French user typing \"soie\" finds \"Silk\" AND a French user typing \"silk\"\n * still finds it.\n */\n\n/** Canonical language code (BCP-47 or simplified two-letter). */\nexport type LocaleId =\n | \"en\"\n | \"es\"\n | \"fr\"\n | \"de\"\n | \"pt-BR\"\n | \"ru\"\n | \"hi\"\n | \"ja\"\n | \"ko\"\n | \"zh-CN\"\n | \"he\"\n | \"ar\"\n\n/** Reading direction. RTL languages need `dir=\"rtl\"` on the picker container. */\nexport type LocaleDirection = \"ltr\" | \"rtl\"\n\nexport interface LanguageDefinition {\n readonly id: LocaleId\n /** English name shown in language pickers when current locale is English. */\n readonly englishName: string\n /** Native name shown to native speakers (in their own script). */\n readonly nativeName: string\n /** Two-letter or short code displayed inside the small locale chip. */\n readonly shortCode: string\n /** Reading direction. */\n readonly dir: LocaleDirection\n /** Optional flag emoji for visual recognition. */\n readonly flag: string\n}\n\n/**\n * Master language registry. Order = display order in the language picker\n * dropdown. English first as canonical default, then mainstream LTR\n * languages, then RTL languages last.\n */\nexport const LANGUAGES: ReadonlyArray<LanguageDefinition> = [\n { id: \"en\", englishName: \"English\", nativeName: \"English\", shortCode: \"EN\", dir: \"ltr\", flag: \"🇬🇧\" },\n { id: \"es\", englishName: \"Spanish\", nativeName: \"Español\", shortCode: \"ES\", dir: \"ltr\", flag: \"🇪🇸\" },\n { id: \"fr\", englishName: \"French\", nativeName: \"Français\", shortCode: \"FR\", dir: \"ltr\", flag: \"🇫🇷\" },\n { id: \"de\", englishName: \"German\", nativeName: \"Deutsch\", shortCode: \"DE\", dir: \"ltr\", flag: \"🇩🇪\" },\n { id: \"pt-BR\", englishName: \"Portuguese (Brazil)\", nativeName: \"Português\", shortCode: \"PT\", dir: \"ltr\", flag: \"🇧🇷\" },\n { id: \"ru\", englishName: \"Russian\", nativeName: \"Русский\", shortCode: \"RU\", dir: \"ltr\", flag: \"🇷🇺\" },\n { id: \"hi\", englishName: \"Hindi\", nativeName: \"हिन्दी\", shortCode: \"HI\", dir: \"ltr\", flag: \"🇮🇳\" },\n { id: \"ja\", englishName: \"Japanese\", nativeName: \"日本語\", shortCode: \"JA\", dir: \"ltr\", flag: \"🇯🇵\" },\n { id: \"ko\", englishName: \"Korean\", nativeName: \"한국어\", shortCode: \"KO\", dir: \"ltr\", flag: \"🇰🇷\" },\n { id: \"zh-CN\", englishName: \"Chinese (Simplified)\", nativeName: \"简体中文\", shortCode: \"ZH\", dir: \"ltr\", flag: \"🇨🇳\" },\n { id: \"he\", englishName: \"Hebrew\", nativeName: \"עברית\", shortCode: \"HE\", dir: \"rtl\", flag: \"🇮🇱\" },\n { id: \"ar\", englishName: \"Arabic\", nativeName: \"العربية\", shortCode: \"AR\", dir: \"rtl\", flag: \"🇸🇦\" },\n] as const\n\nexport const LOCALE_IDS: ReadonlyArray<LocaleId> = LANGUAGES.map((l) => l.id)\nexport const NON_EN_LOCALE_IDS: ReadonlyArray<Exclude<LocaleId, \"en\">> = LANGUAGES\n .filter((l) => l.id !== \"en\")\n .map((l) => l.id) as ReadonlyArray<Exclude<LocaleId, \"en\">>\n\nconst languageById = new Map<LocaleId, LanguageDefinition>(LANGUAGES.map((l) => [l.id, l]))\n\nexport function getLanguage(id: string | undefined | null): LanguageDefinition | undefined {\n if (!id) return undefined\n return languageById.get(id as LocaleId)\n}\n\nexport function getLocaleDirection(id: string | undefined | null): LocaleDirection {\n return getLanguage(id)?.dir ?? \"ltr\"\n}\n\nexport function isRTL(id: string | undefined | null): boolean {\n return getLocaleDirection(id) === \"rtl\"\n}\n\n/**\n * A single localized entry. Either or both fields may be missing — the\n * resolver falls back to the canonical English `label` / `description` from\n * the catalog when a field is absent.\n */\nexport interface LocalizedEntry {\n readonly label?: string\n readonly description?: string\n}\n\n/** Map shape exported by every sidecar file (`<catalog>.<locale>.ts`). */\nexport type LocaleCatalogMap = Readonly<Record<string, LocalizedEntry>>\n\n/**\n * The catalogs that have i18n sidecar files. Each name corresponds to a\n * shared catalog file (e.g. \"mood\" → `packages/shared/src/mood.ts`).\n */\nexport const I18N_CATALOGS = [\n \"action-fx\",\n \"aesthetic\",\n \"animals\",\n \"atmosphere\",\n \"backdrop\",\n \"camera-format\",\n \"camera-motions\",\n \"character-fx\",\n \"color-look\",\n \"composition-effects\",\n \"era\",\n \"exposure-settings\",\n \"framing\",\n \"furniture\",\n \"held-prop\",\n \"instrumentation\",\n \"lens\",\n \"lighting\",\n \"loop-subject\",\n \"materials\",\n \"mood\",\n \"music-genre\",\n \"music-mood\",\n \"person\",\n \"photo-genre\",\n \"photographer\",\n \"pose\",\n \"post-process-effects\",\n \"render-quality\",\n \"seasons\",\n \"setting\",\n \"style\",\n \"styling\",\n \"temporal\",\n \"transitions\",\n \"vehicles\",\n \"voice-character\",\n \"voice-delivery\",\n \"weapons\",\n] as const\n\nexport type I18nCatalogId = (typeof I18N_CATALOGS)[number]\n","/**\n * i18n resolver + lazy loader for parameter-node picker labels/descriptions.\n *\n * Usage from a picker component:\n *\n * ```ts\n * const locale = useUserLocale() // current user-selected locale\n * await ensureLocaleCatalogLoaded(\"styling\", locale) // call once per (catalog, locale), cached\n * const localized = getLocalizedEntry(\"styling\", entry.id, locale)\n * const label = localized?.label ?? entry.label // fallback to canonical English\n * const description = localized?.description ?? entry.description\n * ```\n *\n * For search filtering, use `entryMatchesQuery(entry, locale, query)` which\n * filters across BOTH the canonical English text AND the localized text.\n */\n\nimport type { I18nCatalogId, LocaleCatalogMap, LocaleId, LocalizedEntry } from \"./types.js\"\n\nexport * from \"./types.js\"\n\n/**\n * In-memory cache of loaded locale catalogs. Key = `<catalog>:<locale>`.\n * `undefined` = never loaded; `null` = loaded but missing/empty.\n */\nconst cache = new Map<string, LocaleCatalogMap | null>()\nconst inflight = new Map<string, Promise<LocaleCatalogMap | null>>()\n\nfunction cacheKey(catalog: I18nCatalogId, locale: LocaleId): string {\n return `${catalog}:${locale}`\n}\n\n/**\n * Lazy-load a sidecar catalog. Returns `null` if the locale is `en` (no\n * sidecar — English lives in the canonical catalog file) or if no sidecar\n * file exists for that (catalog, locale) pair.\n *\n * Implementation note: the dynamic import string is constructed so that\n * Vite can statically analyze the glob and code-split each locale into its\n * own chunk. The `/* @vite-ignore *\\/` comment is required because the\n * locale variable defeats Vite's default static analysis; we accept the\n * runtime resolution and rely on the glob-discovery at module init.\n */\nexport async function ensureLocaleCatalogLoaded(\n catalog: I18nCatalogId,\n locale: LocaleId,\n): Promise<LocaleCatalogMap | null> {\n if (locale === \"en\") return null\n const key = cacheKey(catalog, locale)\n const cached = cache.get(key)\n if (cached !== undefined) return cached\n const existing = inflight.get(key)\n if (existing) return existing\n const promise = loadLocaleCatalog(catalog, locale).then(\n (map) => {\n cache.set(key, map)\n inflight.delete(key)\n return map\n },\n (err) => {\n inflight.delete(key)\n // Cache the failure as null so we don't retry forever\n cache.set(key, null)\n // Don't throw — missing sidecars are expected during gradual rollout;\n // the picker just falls back to English.\n console.warn(`[i18n] failed to load ${key}:`, err)\n return null\n },\n )\n inflight.set(key, promise)\n return promise\n}\n\n/**\n * Resolved value lookup. Reads from the in-memory cache; returns `undefined`\n * if the locale's catalog hasn't been loaded yet (caller should await\n * `ensureLocaleCatalogLoaded` first).\n */\nexport function getLocalizedEntry(\n catalog: I18nCatalogId,\n id: string,\n locale: LocaleId,\n): LocalizedEntry | undefined {\n if (locale === \"en\") return undefined\n const map = cache.get(cacheKey(catalog, locale))\n if (!map) return undefined\n return map[id]\n}\n\n/**\n * Synchronous resolver that returns the best label available right now.\n * Falls back to `englishLabel` when no translation exists (or the locale\n * sidecar isn't loaded yet).\n */\nexport function resolveLabel(\n catalog: I18nCatalogId,\n id: string,\n englishLabel: string,\n locale: LocaleId,\n): string {\n if (locale === \"en\") return englishLabel\n return getLocalizedEntry(catalog, id, locale)?.label ?? englishLabel\n}\n\n/**\n * Synchronous resolver that returns the best description available now.\n * Falls back to `englishDescription` when no translation exists.\n */\nexport function resolveDescription(\n catalog: I18nCatalogId,\n id: string,\n englishDescription: string,\n locale: LocaleId,\n): string {\n if (locale === \"en\") return englishDescription\n return getLocalizedEntry(catalog, id, locale)?.description ?? englishDescription\n}\n\n/**\n * Search predicate: returns true if `query` matches either the canonical\n * English label/description or the localized label/description for the\n * current locale.\n *\n * Empty query always matches.\n */\nexport function entryMatchesQuery(\n catalog: I18nCatalogId,\n id: string,\n englishLabel: string,\n englishDescription: string,\n locale: LocaleId,\n query: string,\n): boolean {\n const q = query.trim().toLowerCase()\n if (!q) return true\n if (englishLabel.toLowerCase().includes(q)) return true\n if (englishDescription.toLowerCase().includes(q)) return true\n if (locale === \"en\") return false\n const localized = getLocalizedEntry(catalog, id, locale)\n if (!localized) return false\n if (localized.label && localized.label.toLowerCase().includes(q)) return true\n if (localized.description && localized.description.toLowerCase().includes(q)) return true\n return false\n}\n\n/**\n * Sidecar loader registry. Populated by the consuming app via\n * `registerSidecarLoaders` at startup.\n *\n * Why externalised: this package is bundled by tsup for npm publish, and\n * `tsup` does NOT expand Vite's `import.meta.glob`. Calling it from inside\n * the bundled module yields an empty loader map at runtime → all pickers\n * silently fall back to English regardless of the user's locale.\n *\n * The frontend (which is processed by Vite) owns the glob — see\n * `frontend/src/lib/i18n-bootstrap.ts`. Backend / Node tests don't need\n * picker translations and simply skip registration.\n *\n * Keys are file paths relative to `packages/shared/src/i18n/`, e.g.\n * `\"./person.ja.ts\"`.\n */\ntype SidecarModule = { default?: LocaleCatalogMap } & Record<string, unknown>\nexport type SidecarLoader = () => Promise<unknown>\n\nlet sidecarLoaders: Record<string, SidecarLoader> = {}\n\n/**\n * Register the map of locale-sidecar loaders. Call once at app startup\n * before any picker mounts.\n *\n * In Vite-processed code:\n * ```ts\n * import { registerSidecarLoaders } from \"@nodaro/shared\"\n * registerSidecarLoaders(\n * import.meta.glob(\"../../packages/shared/src/i18n/*.*.ts\"),\n * )\n * ```\n */\nexport function registerSidecarLoaders(loaders: Record<string, SidecarLoader>): void {\n sidecarLoaders = loaders\n}\n\nasync function loadLocaleCatalog(\n catalog: I18nCatalogId,\n locale: LocaleId,\n): Promise<LocaleCatalogMap | null> {\n if (locale === \"en\") return null\n // Match by suffix so the registry survives different glob roots —\n // frontend's bootstrap globs from a different relative path than\n // this file lives at, so keys look like \".../i18n/person.ja.ts\".\n const suffix = `${catalog}.${locale}.ts`\n const matchKey = Object.keys(sidecarLoaders).find((k) =>\n k.endsWith(`/${suffix}`) || k === `./${suffix}`,\n )\n const loader = matchKey ? sidecarLoaders[matchKey] : undefined\n if (!loader) return null\n try {\n const mod = (await loader()) as SidecarModule\n if (mod.default && typeof mod.default === \"object\") return mod.default\n // Fallback: convention-named export (e.g. STYLING_FR)\n const conventional = `${catalog.toUpperCase().replace(/-/g, \"_\")}_${locale.toUpperCase().replace(/-/g, \"_\")}`\n const named = mod[conventional]\n if (named && typeof named === \"object\") return named as LocaleCatalogMap\n return null\n } catch {\n return null\n }\n}\n","/**\n * Field names on a node's `data` that hold runtime / result / transient execution\n * state (job ids, progress, generated outputs, fan-out bookkeeping). These are NEVER\n * part of a node's reusable configuration.\n *\n * Single source of truth, consumed by:\n * - the workflow store's undo logic (execution-only updates skip undo capture, so job\n * polling does not pollute undo history or flip `isDirty`)\n * - the node-preset extractor (presets must never capture runtime state)\n * - the backend defensive strip on preset writes\n *\n * When adding a new runtime/result field to a node's data, add its key here.\n */\nexport const EXECUTION_DATA_KEYS: ReadonlySet<string> = new Set([\n \"executionStatus\",\n \"currentJobId\",\n \"currentJobProgress\",\n \"errorMessage\",\n \"isStreaming\",\n \"generatedImageUrl\",\n \"generatedVideoUrl\",\n \"generatedAudioUrl\",\n \"generatedText\",\n \"generatedScript\",\n \"generatedItems\",\n \"generatedResults\",\n \"activeResultIndex\",\n \"sourceImageUrl\",\n \"__listTotal\",\n \"__listCompleted\",\n \"__listResults\",\n // List fan-out window flag (abandon-guard exemption). Set/cleared by\n // executeNodeForList — purely execution-related, never user-edited.\n \"__listRunning\",\n // Selector node dual-channel outputs (picked + rest). Server-side execution\n // output, not user-edited config.\n \"pickedResults\",\n \"restResults\",\n \"__pickedResults\",\n \"__restResults\",\n \"__pickedTotal\",\n \"__restTotal\",\n \"generatedJson\",\n \"subWorkflowProgress\",\n \"outputResults\",\n \"shots\",\n \"result\",\n \"processedResult\",\n \"activeRoutes\",\n \"routeOutputs\",\n \"_upstreamRefresh\",\n \"zoom\",\n // Character LoRA training status fields — written every 8s while training.\n \"loraReplicateVersion\",\n \"loraTriggerWord\",\n \"loraTrainingStatus\",\n // Collect (fan-in) execution snapshot.\n \"lastInputs\",\n \"lastMeta\",\n \"__upstreamCount\",\n])\n\n/**\n * The PURE RUN-STATE subset of EXECUTION_DATA_KEYS: per-tick values (status\n * flips, job ids, progress counters, fan-out bookkeeping) that must NEITHER\n * mark the workflow dirty NOR be persisted in the save payload. Everything\n * else in EXECUTION_DATA_KEYS is a RESULT the user expects to survive reload\n * (generated URLs/results, errorMessage, LoRA outputs, collect snapshots).\n *\n * Why this split exists: writing these keys used to set `isDirty`, so job\n * polling phantom-dirtied passive tabs → spurious autosaves → false\n * \"changed in another tab\" banners → the remote-ahead latch froze autosave\n * (the \"not saved for a long time\" report). Consumed by the workflow\n * store's dirty decision and the save-payload sanitizer below.\n *\n * Invariant (guarded by node-runtime-keys.test.ts): subset of\n * EXECUTION_DATA_KEYS — anything transient is also undo-exempt.\n */\nexport const TRANSIENT_RUNTIME_KEYS: ReadonlySet<string> = new Set([\n \"executionStatus\",\n \"currentJobId\",\n \"currentJobProgress\",\n \"isStreaming\",\n \"subWorkflowProgress\",\n \"__listTotal\",\n \"__listCompleted\",\n \"__listRunning\",\n \"_upstreamRefresh\",\n \"__upstreamCount\",\n])\n\n/**\n * Pure save-payload sanitizer: returns new node objects with the transient\n * run-state keys removed from `data`. Nodes without transient keys (or\n * without `data`) are returned by reference — cheap for the common case.\n */\nexport function stripTransientRuntimeData<\n T extends { data?: Record<string, unknown> | undefined },\n>(nodes: readonly T[]): T[] {\n return nodes.map((node) => {\n const data = node.data\n if (!data) return node\n let hasTransient = false\n for (const key of TRANSIENT_RUNTIME_KEYS) {\n if (key in data) {\n hasTransient = true\n break\n }\n }\n if (!hasTransient) return node\n const cleaned: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(data)) {\n if (!TRANSIENT_RUNTIME_KEYS.has(key)) cleaned[key] = value\n }\n return { ...node, data: cleaned }\n })\n}\n","import type { GenericNode, GenericEdge } from \"./types.js\"\nimport { EXECUTION_DATA_KEYS } from \"./node-runtime-keys.js\"\n\n/** A named media variant (expression, pose, angle, etc.) produced during entity generation. */\ninterface AssetVariant {\n name: string\n url: string\n}\n\n/** A mood-board / scrap photo attached to a location ({@link WorkflowExportLocation.referencePhotos}). */\ninterface ReferencePhoto {\n kind: string\n url: string\n}\n\nexport interface WorkflowExportCharacter {\n id: string\n nodeId: string\n name: string\n description?: string | null\n gender?: string | null\n style?: string | null\n baseOutfit?: string | null\n sourceImageUrl?: string | null\n expressions?: AssetVariant[]\n poses?: AssetVariant[]\n lightingVariations?: AssetVariant[]\n}\n\nexport interface WorkflowExportObject {\n id: string\n nodeId: string\n name: string\n description?: string | null\n style?: string | null\n sourceImageUrl?: string | null\n angles?: AssetVariant[]\n materials?: AssetVariant[]\n variations?: AssetVariant[]\n}\n\n/** Animal/Creature entity export shape. Structural clone of {@link WorkflowExportObject}\n * with the object→creature DELTA MAP: adds free-text `species`, and the `materials`\n * asset slot becomes `poses`. */\nexport interface WorkflowExportCreature {\n id: string\n nodeId: string\n name: string\n description?: string | null\n species?: string | null\n style?: string | null\n sourceImageUrl?: string | null\n angles?: AssetVariant[]\n poses?: AssetVariant[]\n variations?: AssetVariant[]\n}\n\nexport interface WorkflowExportLocation {\n id: string\n nodeId: string\n name: string\n description?: string | null\n style?: string | null\n sourceImageUrl?: string | null\n timeOfDay?: AssetVariant[]\n weather?: AssetVariant[]\n angles?: AssetVariant[]\n // Location Studio Phase 1 (migration 124).\n lighting?: AssetVariant[]\n seasons?: AssetVariant[]\n atmosphereMotions?: AssetVariant[]\n referencePhotos?: ReferencePhoto[]\n canonicalDescription?: string | null\n styleLock?: boolean | null\n}\n\nexport interface WorkflowExport {\n version: 1\n exportedAt: string\n name: string\n nodes: GenericNode[]\n edges: GenericEdge[]\n settings?: Record<string, unknown>\n assets?: {\n characters: WorkflowExportCharacter[]\n objects: WorkflowExportObject[]\n creatures?: WorkflowExportCreature[]\n locations: WorkflowExportLocation[]\n }\n}\n\n/**\n * Config keys that are (mis)classified inside EXECUTION_DATA_KEYS but are\n * actually USER CONFIG a template MUST keep — NOT runtime/result. `shots` is\n * the Kling-3.0 multi-shot storyboard (user-authored, route-accepted via\n * shotsSchema); stripping it on template export silently drops every shot's\n * prompt+duration while leaving `multiShot:true`, producing a broken template.\n * (`elements`, the sibling Kling-3 config, is correctly absent from\n * EXECUTION_DATA_KEYS — `shots` should arguably be too, but is kept there for\n * other run-state consumers, so we exclude it here rather than reclassify.)\n */\nconst TEMPLATE_KEEP_CONFIG_KEYS = new Set<string>([\"shots\"])\n\n/**\n * Top-level node data fields cleared on template export. Built from\n * EXECUTION_DATA_KEYS (the single source of truth for runtime/result keys),\n * minus the config keys above, so a new result field is stripped by default —\n * never re-leak generated media URLs, job ids, or trained-LoRA identity\n * (loraReplicateVersion / loraTriggerWord / outputResults / generatedVideoUrl\n * / …) into a shareable template — while preserving user config. `assetId` is\n * the one non-runtime extra (a library-asset pointer).\n */\nconst GENERATED_FIELDS: readonly string[] = [\n ...[...EXECUTION_DATA_KEYS].filter((k) => !TEMPLATE_KEEP_CONFIG_KEYS.has(k)),\n \"assetId\",\n]\n\n/** Per-node-type extra generated fields beyond GENERATED_FIELDS. Unknown types get no extras ([] default). */\nconst NODE_EXTRA_FIELDS: Record<string, string[]> = {\n character: [\"expressions\", \"poses\", \"lightingVariations\", \"angles\", \"customVariations\"],\n object: [\"angles\", \"materials\", \"variations\", \"customVariations\"],\n creature: [\"angles\", \"poses\", \"variations\", \"customVariations\"],\n location: [\n \"timeOfDay\",\n \"weather\",\n \"angles\",\n \"lighting\",\n \"seasons\",\n \"atmosphereMotions\",\n \"customVariations\",\n \"referencePhotos\",\n \"canonicalDescription\",\n ],\n // Strip the exporter's private face-row pointer + variants from templates\n // (faceDbId points at a row the importer doesn't own — see workflow-assets\n // import remap, which also clears it).\n face: [\"faceDbId\", \"expressions\", \"customVariations\"],\n // A template shouldn't carry a link to a specific child workflow id (it's\n // the exporter's, and unremapped on import). Strip it so the node lands\n // unlinked rather than dangling at the exporter's workflow.\n \"sub-workflow\": [\"referencedWorkflowId\"],\n}\n\n/** Strip generated/transient content from nodes for template export. Returns new node objects; inputs are not mutated. */\nexport function stripExportContent(nodes: GenericNode[]): GenericNode[] {\n return nodes.map((node) => {\n const data = { ...(node.data as Record<string, unknown>) }\n for (const field of GENERATED_FIELDS) delete data[field]\n const extras = NODE_EXTRA_FIELDS[node.type] ?? []\n for (const field of extras) delete data[field]\n return { ...node, data }\n })\n}\n","export interface SubWorkflowPort {\n readonly id: string\n readonly name: string\n readonly mediaType: \"text\" | \"image\" | \"video\" | \"audio\" | \"any\"\n}\n\ninterface BoundaryNode {\n readonly id: string\n readonly type: string\n readonly data: { readonly routeId?: string; readonly ports?: readonly SubWorkflowPort[] }\n}\n\nexport type ValidationError =\n | { code: \"missing_output_for_route\"; routeId: string; inputNodeId: string }\n | { code: \"missing_input_for_route\"; routeId: string; outputNodeId: string }\n | { code: \"route_has_no_output_ports\"; routeId: string; outputNodeId: string }\n | { code: \"duplicate_route_id\"; routeId: string; nodeIds: readonly string[] }\n\nexport type ValidationResult =\n | { ok: true }\n | { ok: false; errors: readonly ValidationError[] }\n\nexport function validateSubWorkflowRoutes(\n nodes: readonly BoundaryNode[],\n): ValidationResult {\n const inputs = nodes.filter((n) => n.type === \"sub-workflow-input\")\n const outputs = nodes.filter((n) => n.type === \"sub-workflow-output\")\n\n if (inputs.length === 0 && outputs.length === 0) return { ok: true }\n\n const errors: ValidationError[] = []\n\n // 1. Duplicate routeIds within input or output lists\n const groupByRoute = (list: readonly BoundaryNode[]) => {\n const map = new Map<string, BoundaryNode[]>()\n for (const n of list) {\n const r = n.data.routeId\n if (!r) continue\n const bucket = map.get(r) ?? []\n bucket.push(n)\n map.set(r, bucket)\n }\n return map\n }\n for (const [routeId, group] of groupByRoute(inputs)) {\n if (group.length > 1) errors.push({ code: \"duplicate_route_id\", routeId, nodeIds: group.map((g) => g.id) })\n }\n for (const [routeId, group] of groupByRoute(outputs)) {\n if (group.length > 1) errors.push({ code: \"duplicate_route_id\", routeId, nodeIds: group.map((g) => g.id) })\n }\n\n // 2. Every input routeId must have a matching output\n const outputByRoute = new Map(outputs.map((o) => [o.data.routeId, o] as const))\n for (const inputNode of inputs) {\n const routeId = inputNode.data.routeId\n if (!routeId) continue\n const matchingOutput = outputByRoute.get(routeId)\n if (!matchingOutput) {\n errors.push({ code: \"missing_output_for_route\", routeId, inputNodeId: inputNode.id })\n continue\n }\n if (!matchingOutput.data.ports || matchingOutput.data.ports.length === 0) {\n errors.push({ code: \"route_has_no_output_ports\", routeId, outputNodeId: matchingOutput.id })\n }\n }\n\n // 3. Every output routeId must have a matching input\n const inputByRoute = new Map(inputs.map((i) => [i.data.routeId, i] as const))\n for (const outputNode of outputs) {\n const routeId = outputNode.data.routeId\n if (!routeId) continue\n if (!inputByRoute.has(routeId)) {\n errors.push({ code: \"missing_input_for_route\", routeId, outputNodeId: outputNode.id })\n }\n }\n\n return errors.length === 0 ? { ok: true } : { ok: false, errors }\n}\n","import { isUsageMode, type UsageMode } from \"./character-usage-mode.js\"\n\n/**\n * Slugify a name (character or variant) for use in @-mention tokens.\n * Lowercase, strip non-alphanumeric, collapse runs of dashes.\n */\nexport function characterMentionSlug(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n}\n\nexport interface CharacterMentionTokenInfo {\n readonly token: string\n readonly characterSlug: string\n /**\n * 1-based positional index assigned at insertion time by the autocomplete.\n * Lets the user wire a literal-text mention (`@kira:1`) to a final-prompt\n * identity directive (`Image 1 (person) — match exactly…`) so the order in\n * the typed prompt matches the order in the assembled directive block.\n */\n readonly imageIndex: number\n readonly variantSlug: string | null\n /**\n * Optional per-mention usage-mode override (e.g. `:face`, `:style`). When\n * `null`, the assembled directive falls back to the source character node's\n * `defaultUsageMode`, then to the global `\"identical\"` default. Always one\n * of the entries in `USAGE_MODES` when non-null — the parser rejects any\n * other 4-part token.\n */\n readonly usageMode: UsageMode | null\n /**\n * Additive per-mention identity-lock sentinel (Unified Reference Roles,\n * Task 4 + F4). Tri-state: `true` (trailing `~lock`, force lock ON) |\n * `false` (trailing `~nolock`, force lock OFF — suppresses a ref-level\n * `identityLock.enabled = true`) | ABSENT/undefined (neither sentinel —\n * inherit the ref/source default; byte-identical to the pre-Task-4 shape).\n * Only ACTED UPON by the HYBRID resolvers; the LEGACY resolvers ignore it\n * entirely, so both `~lock` and `~nolock` are inert on the legacy path.\n */\n readonly lock?: boolean\n readonly offset: number\n}\n\n/**\n * Parse a single `@<character>:<index>(:<variant>)?(:<usageMode>)?` token.\n *\n * Supported shapes (each segment after `:` may contain internal dashes, so\n * `@young-kira:1:soft-smile` parses unambiguously as character + index +\n * variant):\n *\n * - `@kira:1` → canonical, default mode\n * - `@kira:1:smile` → variant smile, default mode\n * - `@kira:1:face` → canonical, mode \"face\" (mode is detected by\n * checking the 3rd segment against `USAGE_MODES`)\n * - `@kira:1:smile:face` → variant smile, mode \"face\"\n * - `@kira:1:smile:bogus` → null (4-part rejected when last segment is not\n * a valid usage mode — keeps the format strict)\n *\n * Format change: as of the index-in-slug update, the index segment is required.\n * Bare `@kira` is not a mention; the autocomplete always inserts at least\n * `@kira:N`.\n *\n * `knownCharacterSlugs` is no longer needed for parsing (the structure is\n * unambiguous given the closed `USAGE_MODES` enum) — it remains accepted for\n * API compatibility but ignored here. `findCharacterMentionTokens` still uses\n * it to filter unknown characters.\n */\nexport function parseCharacterMentionToken(\n text: string,\n _knownCharacterSlugs?: readonly string[],\n): { characterSlug: string; imageIndex: number; variantSlug: string | null; usageMode: UsageMode | null; lock?: boolean } | null {\n if (!text.startsWith(\"@\")) return null\n let rest = text.slice(1)\n if (rest.length === 0 || !/^[a-z]/.test(rest)) return null\n\n // Additive `~lock` / `~nolock` sentinels (Unified Reference Roles, Task 4 +\n // F4). Strip a trailing `~nolock` (force lock OFF) or `~lock` (force lock ON)\n // BEFORE splitting on \":\" so the segment grammar below is byte-identical to\n // pre-Task-4 (a `~` can never appear inside a segment — the shapes are\n // `[a-z][a-z0-9-]*`). Check `~nolock` FIRST: `\"x~nolock\".endsWith(\"~lock\")` is\n // false (last 5 chars \"olock\"), but the explicit ordering keeps intent clear.\n // A token with NEITHER sentinel is untouched here and gains NO `lock` key\n // (byte-identical). The parsed tri-state `lock` (true/false/undefined) is only\n // honored by the HYBRID resolvers — undefined inherits the ref default, true\n // forces the lock on, false forces it off.\n let lockField: { lock?: boolean } = {}\n if (rest.endsWith(\"~nolock\")) {\n rest = rest.slice(0, -\"~nolock\".length)\n lockField = { lock: false }\n } else if (rest.endsWith(\"~lock\")) {\n rest = rest.slice(0, -\"~lock\".length)\n lockField = { lock: true }\n }\n\n // Format: <character>:<index>(:<variant|mode>)?(:<mode>)?.\n // Splitting on \":\" requires 2–4 parts (no bare @character anymore).\n const parts = rest.split(\":\")\n if (parts.length < 2 || parts.length > 4) return null\n\n const [characterSlug, indexStr, third, fourth] = parts\n if (!/^[a-z][a-z0-9-]*$/.test(characterSlug)) return null\n if (!/^\\d+$/.test(indexStr)) return null\n const imageIndex = parseInt(indexStr, 10)\n if (!Number.isInteger(imageIndex) || imageIndex < 1) return null\n\n // 2-part: kira:1 — canonical, default mode.\n if (parts.length === 2) {\n return { characterSlug, imageIndex, variantSlug: null, usageMode: null, ...lockField }\n }\n\n // 3-part: kira:1:X — X is either a usage-mode keyword or a variant slug.\n // The closed `USAGE_MODES` enum + the variant-slug shape constraint\n // (`[a-z][a-z0-9-]*`) makes this unambiguous. A keyword like \"face\" wins\n // the mode interpretation; anything else is treated as a variant slug.\n if (parts.length === 3) {\n if (!/^[a-z][a-z0-9-]*$/.test(third)) return null\n if (isUsageMode(third)) {\n return { characterSlug, imageIndex, variantSlug: null, usageMode: third, ...lockField }\n }\n return { characterSlug, imageIndex, variantSlug: third, usageMode: null, ...lockField }\n }\n\n // 4-part: kira:1:smile:mode — variant + mode override. Both segments must\n // satisfy their respective shape; an unknown mode kills the token entirely\n // (callers fall back to literal text, matching unknown-character behavior).\n if (parts.length === 4) {\n if (!/^[a-z][a-z0-9-]*$/.test(third)) return null\n if (!isUsageMode(fourth)) return null\n return { characterSlug, imageIndex, variantSlug: third, usageMode: fourth, ...lockField }\n }\n\n return null\n}\n\n/** Find all @-mentions in a prompt that match a known character slug. */\nexport function findCharacterMentionTokens(\n prompt: string,\n knownCharacterSlugs: readonly string[],\n): CharacterMentionTokenInfo[] {\n const tokens: CharacterMentionTokenInfo[] = []\n // `@<character>:<index>(:<variant|mode>)?(:<mode>)?` preceded by\n // non-alphanumeric (or start of string) to prevent email-like matches.\n // The `\\d+` index segment is required — see `parseCharacterMentionToken`\n // for the rationale. The two optional trailing `:<slug>` groups absorb\n // either `:<variant>`, `:<mode>`, or `:<variant>:<mode>`; the parser\n // disambiguates which segment is which based on `USAGE_MODES`. The optional\n // trailing `(?:~(?:no)?lock)?` absorbs the additive Task-4/F4 identity-lock\n // sentinel (`~lock` force-on OR `~nolock` force-off) INTO the token (so it is\n // spliced out at resolve time); it is optional, so a lock-less token matches\n // byte-identically to before. The `(?![a-z0-9-])` word boundary keeps\n // `~locked` / `~nolockx` literal.\n const regex = /(?:^|[^a-zA-Z0-9])(@[a-z][a-z0-9-]*:\\d+(?::[a-z][a-z0-9-]*)?(?::[a-z][a-z0-9-]*)?(?:~(?:no)?lock(?![a-z0-9-]))?)/g\n const knownSet = new Set(knownCharacterSlugs)\n for (const match of prompt.matchAll(regex)) {\n const token = match[1]\n const offset = (match.index ?? 0) + (match[0].length - token.length)\n const parsed = parseCharacterMentionToken(token)\n if (parsed && knownSet.has(parsed.characterSlug)) {\n tokens.push({ token, ...parsed, offset })\n }\n }\n return tokens\n}\n","/**\n * Single source of truth for a character's `{name, url}[]` variant-asset buckets\n * — the image/video variants that are expandable into connected references and\n * therefore selectable in the reference picker AND `@`-mentionable in prompts.\n *\n * Historically the expansion list was hardcoded (6 copies across frontend\n * `connected-references.ts` / `connected-refs-builder.ts` / `execute-node.ts` and\n * backend `payload-builder.ts`), so when wardrobe (`outfitVariations`) and detail\n * close-ups (`detailCloseups`) were added — same `{name,url}[]` shape, written by\n * studio.nodaro.ai — they were silently dropped from the picker and `@` list.\n * Drive every expansion site off this constant so a new bucket can't drift again.\n *\n * NOT included (different shapes, handled elsewhere):\n * - `sheets` (`ReferenceSheet[]` — composited multi-panel boards)\n * - `referenceVideosByVariant` (`Record<variant, url[]>` — per-emotion video refs)\n */\nexport const CHARACTER_VARIANT_ASSET_BUCKETS = [\n \"expressions\",\n \"poses\",\n \"motions\",\n \"angles\",\n \"bodyAngles\",\n \"lightingVariations\",\n \"outfitVariations\",\n \"detailCloseups\",\n] as const\n\nexport type CharacterVariantAssetBucket = (typeof CHARACTER_VARIANT_ASSET_BUCKETS)[number]\n\nexport interface CharacterVariantAssetItem {\n readonly name: string\n readonly url: string\n readonly description?: string\n}\n\n/**\n * Build the `{ bucket: items[] }` map for every variant-asset bucket from a\n * character node's data. Missing / non-array buckets coerce to `[]`. One helper\n * for all six expansion sites so the bucket set is defined exactly once.\n */\nexport function characterVariantAssetArrays(\n data: Record<string, unknown> | null | undefined,\n): Record<CharacterVariantAssetBucket, readonly CharacterVariantAssetItem[]> {\n const out = {} as Record<CharacterVariantAssetBucket, readonly CharacterVariantAssetItem[]>\n for (const bucket of CHARACTER_VARIANT_ASSET_BUCKETS) {\n const value = data?.[bucket]\n out[bucket] = Array.isArray(value) ? (value as readonly CharacterVariantAssetItem[]) : []\n }\n return out\n}\n\n/**\n * Map a character's composite reference `sheets` (ReferenceSheet[] — a different\n * shape, with a composite board `url` + `type`/`skin`) into mentionable\n * `{name,url}` items so they too can be picked / `@`-mentioned. Each sheet → one\n * item named `\"<type> <skin>\"` (e.g. \"turnaround studio\"). Drops url-less sheets.\n */\nexport function characterSheetRefItems(sheets: unknown): CharacterVariantAssetItem[] {\n if (!Array.isArray(sheets)) return []\n return sheets.flatMap((s) => {\n const sheet = s as { url?: unknown; type?: unknown; skin?: unknown }\n if (!sheet || typeof sheet.url !== \"string\" || !sheet.url) return []\n const type = typeof sheet.type === \"string\" && sheet.type ? sheet.type : \"sheet\"\n const skin = typeof sheet.skin === \"string\" && sheet.skin ? ` ${sheet.skin}` : \"\"\n return [{ name: `${type}${skin}`, url: sheet.url }]\n })\n}\n\n/** Legacy `selected_asset_by_variant` keys that hold boards born before the\n * `boards` column existed (studio.nodaro.ai's reserved namespace). */\nconst BOARD_SHIM_KEY = \"studioBoard\"\nconst BOARD_SHIM_PREFIX = \"studioBoard:\"\n\n/**\n * Resolve a character's named reference boards from BOTH the `boards` column AND\n * the LEGACY `selected_asset_by_variant` shim (`studioBoard` / `studioBoard:<name>`)\n * — mirroring studio.nodaro.ai's read (entity-boards.ts), which merges both since\n * pre-column boards still live in the shim. Column wins on duplicate name; the\n * unnamed legacy board is named \"board\". Drops url-less entries.\n */\nexport function characterBoardItems(\n data: Record<string, unknown> | null | undefined,\n): CharacterVariantAssetItem[] {\n const column: CharacterVariantAssetItem[] = Array.isArray(data?.boards)\n ? (data!.boards as unknown[]).flatMap((b) => {\n const board = b as { name?: unknown; url?: unknown }\n if (!board || typeof board.url !== \"string\" || !board.url) return []\n return [{ name: typeof board.name === \"string\" && board.name ? board.name : \"board\", url: board.url }]\n })\n : []\n\n const map = (data?.selectedAssetByVariant ?? {}) as Record<string, unknown>\n const shim: CharacterVariantAssetItem[] = []\n const legacy = map[BOARD_SHIM_KEY]\n if (typeof legacy === \"string\" && legacy) shim.push({ name: \"board\", url: legacy })\n for (const [k, v] of Object.entries(map)) {\n if (k.startsWith(BOARD_SHIM_PREFIX) && typeof v === \"string\" && v) {\n shim.push({ name: k.slice(BOARD_SHIM_PREFIX.length) || \"board\", url: v })\n }\n }\n\n const haveNames = new Set(column.map((b) => b.name.toLowerCase()))\n return [...column, ...shim.filter((b) => !haveNames.has(b.name.toLowerCase()))]\n}\n\n/**\n * The COMPLETE set of mentionable character asset arrays: the `{name,url}[]`\n * variant buckets + derived `sheets` and `boards` buckets. This is what the\n * connected-reference / `@`-mention expansion sites iterate, so every\n * studio-produced asset (variants, composite sheets, AND boards — incl. legacy\n * shim boards) surfaces in the reference picker and `@` list.\n */\nexport function characterMentionableAssetArrays(\n data: Record<string, unknown> | null | undefined,\n): Record<string, readonly CharacterVariantAssetItem[]> {\n return {\n ...characterVariantAssetArrays(data),\n sheets: characterSheetRefItems(data?.sheets),\n boards: characterBoardItems(data),\n }\n}\n","/**\n * Location `@-mention` parser. Mirrors `character-mention-slug.ts` shape but\n * with two key differences:\n *\n * 1. **Bucketed variants:** the 3rd segment can be `bucket/variant` (slash-\n * separated, e.g. `weather/rain` or `lighting/cinematic`) in addition\n * to a bare usage-mode keyword. Locations carry their variants split\n * across 5 buckets (timeOfDay / weather / seasons / angles / lighting)\n * plus motion clips; the bucket prefix disambiguates which array to\n * pull from when two buckets happen to share a variant name.\n *\n * 2. **Smaller usage-mode set:** locations support 4 modes (\"identical\",\n * \"style\", \"layout\", \"none\") — a strict subset of the 8 character modes.\n * The character modes \"face\" / \"face-pose\" / \"pose\" / \"emotion\" / \"name\"\n * don't apply to scenes.\n *\n * The mention resolver (Phase 2 #2 follow-up) uses the parsed token to look\n * up the variant URL by walking the upstream Location node's `node.data`:\n * timeOfDay / weather / seasons / angles / lighting / atmosphereMotions\n * arrays, each `{name, url}`. Slug match is case-insensitive via the same\n * slugify helper used by character variants.\n *\n * Format reference (the parser accepts these shapes; everything else returns\n * null and the token falls through to literal-text in the final prompt):\n *\n * @oldlibrary:1 — canonical, default mode\n * @oldlibrary:1:weather/rain — rain variant from weather bucket\n * @oldlibrary:1:layout — canonical, mode \"layout\"\n * @oldlibrary:1:weather/rain:style — variant + mode override\n * @oldlibrary:1:weather/rain:bogus — null (4th segment must be a known\n * location usage mode)\n */\n\n/** Modes that apply to scenes/locations. Subset of character `USAGE_MODES`. */\nexport const LOCATION_USAGE_MODES = [\n \"identical\",\n \"style\",\n \"layout\",\n \"none\",\n] as const\n\nexport type LocationUsageMode = (typeof LOCATION_USAGE_MODES)[number]\n\n/** Default mode when neither the slug nor the location node specifies one. */\nexport const DEFAULT_LOCATION_USAGE_MODE: LocationUsageMode = \"identical\"\n\n/** Type guard — narrows an arbitrary string to `LocationUsageMode`. */\nexport function isLocationUsageMode(s: string): s is LocationUsageMode {\n return (LOCATION_USAGE_MODES as readonly string[]).includes(s)\n}\n\n/**\n * Human-readable label for the location usage-mode dropdown / badge UI.\n * Mirrors `usageModeLabel` for character modes but with location-specific\n * phrasing — locations don't have face/pose semantics, so the labels speak\n * about the scene as a whole (framing, layout, mood) instead of subject\n * features. Used by the location pill's mode menu (slice 4) and the\n * hierarchical drill in the `@`-autocomplete.\n *\n * Phrasing decisions:\n * - \"Match exactly\" — strongest possible directive; the scene should\n * reproduce the reference verbatim. Equivalent in role to character\n * \"Identical\".\n * - \"Style / mood only\" — atmospheric transfer (lighting, color grade,\n * mood) without locking the framing. Maps to character \"Style only\".\n * - \"Layout / framing only\" — keep the spatial composition (where things\n * are, where the camera sits) without copying the textures or palette.\n * No character-side equivalent.\n * - \"No textual bias\" — visual reference only, no top-level header\n * mention. Maps to character \"None\".\n */\nexport function locationUsageModeLabel(mode: LocationUsageMode): string {\n switch (mode) {\n case \"identical\": return \"Match exactly\"\n case \"style\": return \"Style / mood only\"\n case \"layout\": return \"Layout / framing only\"\n case \"none\": return \"No textual bias\"\n }\n}\n\n/**\n * Slugify a location name for use in @-mention tokens. Same algorithm as\n * `characterMentionSlug` — lowercase, strip non-alphanumeric, collapse runs.\n * Kept as a separate export to make the call site's intent explicit and to\n * allow future divergence (e.g., locations may need to preserve digits at\n * the start, characters may not).\n */\nexport function locationMentionSlug(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n}\n\nexport interface LocationMentionTokenInfo {\n readonly token: string\n readonly locationSlug: string\n readonly imageIndex: number\n /** \"weather\", \"lighting\", etc. — null when the mention targets the canonical\n * main image. */\n readonly bucket: string | null\n /** Variant name within the bucket (e.g. \"rain\"). null for canonical. */\n readonly variant: string | null\n /** Per-mention mode override; null falls back to the location node's default\n * (or the global \"identical\" default). */\n readonly usageMode: LocationUsageMode | null\n /** Bare-slug ROLE (Unified Reference Roles, Phase D + F2) — any slash-less,\n * non-mode 3rd segment (`background`, `empty-background`, `as-is`, … or a\n * CUSTOM slug), stored verbatim in slug form. Absent (undefined) for canonical /\n * bucket-variant / mode tokens. The hybrid resolver + role pill map it back to\n * the phrase key via `normalizeRoleSlug` (custom slugs pass through). Optional so\n * canonical/variant/mode tokens stay shape-identical to the pre-Phase-D parser\n * output. */\n readonly role?: string\n /**\n * Additive per-mention identity-lock sentinel (Unified Reference Roles,\n * Task 4 + F4). Tri-state: `true` (`~lock`, force ON) | `false` (`~nolock`,\n * force OFF — suppresses a ref-level `identityLock.enabled = true`) |\n * ABSENT/undefined (neither — inherit the ref default; byte-identical to the\n * pre-Task-4 shape). Only ACTED UPON by the HYBRID resolver; the LEGACY\n * resolver ignores it, so both sentinels are inert on the legacy path.\n */\n readonly lock?: boolean\n /** Byte offset into the source prompt — used to splice the token out at\n * resolve time. */\n readonly offset: number\n}\n\n/**\n * Parse a single `@<location>:<index>(:<bucket>/<variant>|<mode>)?(:<mode>)?`\n * token. Returns null when the token doesn't match any supported shape\n * (caller falls back to literal text).\n *\n * Disambiguation at the 3rd segment: presence of `/` indicates a\n * bucket/variant pair; absence indicates a bare mode keyword. The 4th\n * segment is always a mode override (and must be a valid `LocationUsageMode`).\n */\nexport function parseLocationMentionToken(\n text: string,\n): {\n locationSlug: string\n imageIndex: number\n bucket: string | null\n variant: string | null\n usageMode: LocationUsageMode | null\n /** Bare-slug role (slug form). Present for ANY bare, non-mode 3rd segment\n * (preset OR custom, F2); OMITTED (undefined) for every other shape so\n * canonical/variant/mode results stay byte-identical to the pre-Phase-D parser. */\n role?: string\n /** Additive per-mention identity-lock sentinel (Task 4 + F4). Tri-state:\n * `true` (`~lock`) | `false` (`~nolock`) | OMITTED (neither — byte-identical). */\n lock?: boolean\n} | null {\n if (!text.startsWith(\"@\")) return null\n let rest = text.slice(1)\n if (rest.length === 0 || !/^[a-z]/.test(rest)) return null\n\n // Additive `~lock` / `~nolock` sentinels (Task 4 + F4). Strip a trailing\n // `~nolock` (force lock OFF) or `~lock` (force lock ON) BEFORE splitting so\n // the segment grammar stays byte-identical (a `~` never appears inside a\n // bucket/variant/mode/role segment). Check `~nolock` FIRST. A token with\n // NEITHER sentinel is untouched and gains NO `lock` key (byte-identical).\n let lockField: { lock?: boolean } = {}\n if (rest.endsWith(\"~nolock\")) {\n rest = rest.slice(0, -\"~nolock\".length)\n lockField = { lock: false }\n } else if (rest.endsWith(\"~lock\")) {\n rest = rest.slice(0, -\"~lock\".length)\n lockField = { lock: true }\n }\n\n const parts = rest.split(\":\")\n if (parts.length < 2 || parts.length > 4) return null\n\n const [locationSlug, indexStr, third, fourth] = parts\n if (!/^[a-z][a-z0-9-]*$/.test(locationSlug)) return null\n if (!/^\\d+$/.test(indexStr)) return null\n const imageIndex = parseInt(indexStr, 10)\n if (!Number.isInteger(imageIndex) || imageIndex < 1) return null\n\n // 2-part: @oldlibrary:1 — canonical, default mode.\n if (parts.length === 2) {\n return {\n locationSlug,\n imageIndex,\n bucket: null,\n variant: null,\n usageMode: null,\n ...lockField,\n }\n }\n\n // 3-part: @oldlibrary:1:X — X is either bucket/variant or a mode keyword.\n if (parts.length === 3) {\n if (third.includes(\"/\")) {\n const slashAt = third.indexOf(\"/\")\n const bucket = third.slice(0, slashAt)\n const variant = third.slice(slashAt + 1)\n if (!/^[a-z][a-z0-9-]*$/.test(bucket)) return null\n if (!/^[a-z][a-z0-9-]*$/.test(variant)) return null\n return { locationSlug, imageIndex, bucket, variant, usageMode: null, ...lockField }\n }\n if (!/^[a-z][a-z0-9-]*$/.test(third)) return null\n if (isLocationUsageMode(third)) {\n return {\n locationSlug,\n imageIndex,\n bucket: null,\n variant: null,\n usageMode: third,\n ...lockField,\n }\n }\n // Additive (Unified Reference Roles, Phase D + F2 follow-up): a bare, non-\n // mode 3rd segment parses as a ROLE, stored verbatim in slug form\n // (`background`, `empty-background`, `as-is`, …, or a user's CUSTOM slug).\n // The F2 follow-up REMOVED the preset membership gate so custom location\n // roles behave like custom character roles — any valid slug (guaranteed\n // `[a-z][a-z0-9-]*` by the regex above, and not a `LocationUsageMode`, which\n // is caught first) is accepted. Legacy stays byte-identical NOT via this\n // parser but via the resolver's `if (t.role) continue` guard, which skips\n // ANY role token (preset or custom) → literal text with no bullet / phrase.\n // The slug round-trips through the pill's `renderText`; the hybrid resolver /\n // pill map it to a phrase via `normalizeRoleSlug` (custom slugs pass through\n // unchanged). (`layout`/`style` never reach this branch — usage modes above.)\n return {\n locationSlug,\n imageIndex,\n bucket: null,\n variant: null,\n usageMode: null,\n role: third,\n ...lockField,\n }\n }\n\n // 4-part: @oldlibrary:1:bucket/variant:mode.\n if (parts.length === 4) {\n if (!third.includes(\"/\")) return null\n const slashAt = third.indexOf(\"/\")\n const bucket = third.slice(0, slashAt)\n const variant = third.slice(slashAt + 1)\n if (!/^[a-z][a-z0-9-]*$/.test(bucket)) return null\n if (!/^[a-z][a-z0-9-]*$/.test(variant)) return null\n if (!isLocationUsageMode(fourth)) return null\n return { locationSlug, imageIndex, bucket, variant, usageMode: fourth, ...lockField }\n }\n\n return null\n}\n\n/**\n * Find all location @-mentions in a prompt that match a known location slug.\n *\n * The regex captures every `@<slug>:<index>(:<segment>)?(:<segment>)?` shape\n * where each segment is either `[a-z][a-z0-9-]*` (the character format —\n * shared with characters) or `[a-z][a-z0-9-]*\\/[a-z][a-z0-9-]*` (the\n * bucket/variant format — location-only). `knownLocationSlugs` filters to\n * only the user's wired locations so `@kira:1:smile` doesn't accidentally\n * trip the location parser.\n */\nexport function findLocationMentionTokens(\n prompt: string,\n knownLocationSlugs: readonly string[],\n): LocationMentionTokenInfo[] {\n const tokens: LocationMentionTokenInfo[] = []\n // Each optional segment is either a plain slug (`[a-z][a-z0-9-]*`) OR a\n // bucket/variant pair (`[a-z][a-z0-9-]*\\/[a-z][a-z0-9-]*`). The two are\n // disjoint at the regex level — bucket/variant requires the literal `/`.\n const segment = \"(?:[a-z][a-z0-9-]*\\\\/[a-z][a-z0-9-]*|[a-z][a-z0-9-]*)\"\n // The optional trailing `(?:~(?:no)?lock)?` absorbs the additive Task-4/F4\n // identity-lock sentinel (`~lock` force-on OR `~nolock` force-off) INTO the\n // captured token (spliced out at resolve time); optional, so a lock-less token\n // matches byte-identically to before. `(?![a-z0-9-])` keeps `~locked` /\n // `~nolockx` literal.\n const regex = new RegExp(\n `(?:^|[^a-zA-Z0-9])(@[a-z][a-z0-9-]*:\\\\d+(?::${segment})?(?::${segment})?(?:~(?:no)?lock(?![a-z0-9-]))?)`,\n \"g\",\n )\n const knownSet = new Set(knownLocationSlugs)\n for (const match of prompt.matchAll(regex)) {\n const token = match[1]\n const offset = (match.index ?? 0) + (match[0].length - token.length)\n const parsed = parseLocationMentionToken(token)\n if (parsed && knownSet.has(parsed.locationSlug)) {\n tokens.push({ token, ...parsed, offset })\n }\n }\n return tokens\n}\n","import type { ConnectedReference } from \"./types.js\"\nimport { characterMentionSlug } from \"./character-mention-slug.js\"\nimport { locationMentionSlug } from \"./location-mention-slug.js\"\n\n/**\n * A bound entity (a wired Character or Location) ready to convert into a\n * `ConnectedReference`. The minimal identity an app captures when a user binds\n * an entity — the SLUG (and thus the resolver match) is DERIVED from `name`\n * here, so callers can't drift from Nodaro's mention resolver. Apps own their\n * own binding UX (chips, pickers); this is just the contract mapping.\n */\nexport interface EntityReferenceInput {\n /** The entity row id. */\n readonly id: string\n readonly kind: \"character\" | \"location\" | \"creature\"\n /** Display name — the slug is derived from this. */\n readonly name: string\n /** Resolved thumbnail/source URL; null/undefined → \"\" (placeholder-safe). */\n readonly url?: string | null\n /** Variant slug (e.g. \"smile\", \"rain\"); undefined = canonical/default. */\n readonly variant?: string\n /** Optional free-text descriptor (creature bindings: species/appearance) —\n * folded into the auto-generated directive subject by the prompt builder. */\n readonly description?: string | null\n}\n\n/**\n * Map ONE bound entity to its `ConnectedReference`. character → `wired-character`\n * (slug via `characterMentionSlug`), location → `wired-location` (slug via\n * `locationMentionSlug`), creature → `wired-creature` (no mention-slug machinery\n * — like `wired-object`, a bound creature AUTO-ATTACHES and gets a canonical-style\n * creature/animal-subject directive with zero typing; `{image:N:creature}` tokens\n * also resolve against it). Canonical-description fields are null here (a binding\n * captures only name+variant; the picker/full-row path supplies descriptions).\n */\nexport function toConnectedReference(entity: EntityReferenceInput): ConnectedReference {\n if (entity.kind === \"character\") {\n return {\n id: entity.id,\n defaultName: entity.name,\n source: \"wired-character\",\n url: entity.url ?? \"\",\n characterSlug: characterMentionSlug(entity.name),\n variantSlug: entity.variant,\n characterCanonicalDescription: null,\n variantDescription: null,\n variantDisplayName: entity.variant ?? \"canonical\",\n }\n }\n if (entity.kind === \"creature\") {\n return {\n id: entity.id,\n defaultName: entity.name,\n source: \"wired-creature\",\n url: entity.url ?? \"\",\n ...(entity.description ? { description: entity.description } : {}),\n }\n }\n return {\n id: entity.id,\n defaultName: entity.name,\n source: \"wired-location\",\n url: entity.url ?? \"\",\n locationSlug: locationMentionSlug(entity.name),\n locationCanonicalDescription: null,\n locationVariantBucket: undefined,\n locationVariantSlug: entity.variant,\n locationVariantDisplayName: entity.variant ?? \"canonical\",\n }\n}\n\n/** Batch form — `entities.map(toConnectedReference)`. */\nexport function toConnectedReferences(\n entities: readonly EntityReferenceInput[],\n): ConnectedReference[] {\n return entities.map(toConnectedReference)\n}\n","// ─────────────────────────────────────────────────────────────────────────────\n// Character aspect-ratio defaults\n// ─────────────────────────────────────────────────────────────────────────────\n//\n// Characters are vertical subjects — the historical 16:9 default produced wide,\n// crop-unfriendly portraits. The per-asset-type table below picks the ratio\n// that fits each asset's natural framing:\n//\n// - Portrait / canonical head shot → 3:4\n// - Expressions (head-and-shoulders) → 1:1\n// - Poses (full-body) → 9:16\n// - Head angles → 3:4\n// - Body angles (full-body) → 9:16\n// - Lighting variations (full-body context) → 3:4\n// - Motions (vertical clip, full-body i2v) → 9:16\n//\n// Resolution precedence (low → high):\n// 1. Per-asset-type default (this table)\n// 2. Character node's `defaultAssetAspectRatio` (user override on the canvas\n// node — flows in as `characterNodeAspectRatio` in the request body)\n// 3. Explicit `aspectRatio` on the API request (caller wins)\n//\n// The character node's `defaultAssetAspectRatio` toggle (1:1 / 3:4 / 16:9 /\n// 9:16) drives BOTH the canvas thumbnail crop AND this override slot.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const CHARACTER_ASPECT_OPTIONS = [\"1:1\", \"3:4\", \"16:9\", \"9:16\"] as const\nexport type CharacterAspectRatio = (typeof CHARACTER_ASPECT_OPTIONS)[number]\n\n/**\n * The asset categories with distinct natural framing. Aliases:\n * - `angles` is the legacy single-surface key (now head-and-shoulders by\n * default). Use `headAngles` for clarity in new code.\n * - `bodyAngles` is the new full-body column added in migration 118.\n */\nexport type CharacterAssetTypeForAspect =\n | \"portrait\"\n | \"expressions\"\n | \"poses\"\n | \"angles\"\n | \"headAngles\"\n | \"bodyAngles\"\n | \"lighting\"\n | \"motions\"\n\nexport const CHARACTER_ASPECT_DEFAULTS: Record<\n CharacterAssetTypeForAspect,\n CharacterAspectRatio\n> = {\n portrait: \"3:4\",\n // Legacy `angles` was head angles — keep its default aligned with `headAngles`.\n angles: \"3:4\",\n headAngles: \"3:4\",\n // Full-body framings:\n poses: \"9:16\",\n bodyAngles: \"9:16\",\n motions: \"9:16\",\n // Expressions are head-and-shoulders — square framing matches the existing\n // expression card grid and avoids cutting off forehead/chin.\n expressions: \"1:1\",\n // Lighting variations are framed like portraits (3:4) — they're full-body in\n // the prompt but the user usually wants to see the lighting on the face.\n lighting: \"3:4\",\n}\n\nexport function isCharacterAspectRatio(s: string): s is CharacterAspectRatio {\n return (CHARACTER_ASPECT_OPTIONS as readonly string[]).includes(s)\n}\n\nexport interface ResolveCharacterAspectOptions {\n /** Explicit `aspectRatio` on the request body — highest precedence. */\n readonly explicit?: string | null\n /**\n * The character node's `defaultAssetAspectRatio` — set per-canvas-node via\n * the 4-pill toggle on the character node. Flows through the API as\n * `characterNodeAspectRatio`.\n */\n readonly nodeOverride?: string | null\n /** What's being generated. Drives the default when nothing else is set. */\n readonly assetType: CharacterAssetTypeForAspect\n}\n\n/**\n * Resolve the final aspect ratio for a character generation request.\n *\n * Precedence: explicit > node override > per-asset-type default. The two\n * \"soft\" inputs are tolerated as raw strings and only honored when they\n * parse to a value in `CHARACTER_ASPECT_OPTIONS` — anything else falls\n * through to the next layer (so a stale enum value doesn't poison the\n * generation).\n */\nexport function resolveCharacterAspectRatio(\n opts: ResolveCharacterAspectOptions,\n): CharacterAspectRatio {\n if (opts.explicit && isCharacterAspectRatio(opts.explicit)) {\n return opts.explicit\n }\n if (opts.nodeOverride && isCharacterAspectRatio(opts.nodeOverride)) {\n return opts.nodeOverride\n }\n return CHARACTER_ASPECT_DEFAULTS[opts.assetType]\n}\n","// ─────────────────────────────────────────────────────────────────────────────\n// Entity studio aspect-ratio defaults (location / creature / object)\n// ─────────────────────────────────────────────────────────────────────────────\n//\n// Character has its own table (`character-aspect-defaults.ts`); this is the\n// equivalent for the other three entity studios. It is the SINGLE source for:\n// 1. the generation request aspect sent to the provider (backend generate-*\n// routes), and\n// 2. the studio card's *fallback* container ratio (frontend), shown until the\n// real media aspect is probed.\n// Keeping both in one place means the framing a user sees can't drift from the\n// framing that was generated.\n//\n// Note: the frontend additionally sizes each card to the REAL decoded media\n// aspect (so a provider that returns a slightly different ratio still displays\n// uncropped). These per-type values are the deterministic placeholder + the\n// value requested at generation time.\n\nexport type EntityStudioKind = \"location\" | \"creature\" | \"object\"\n\n/** Provider \"W:H\" ratio strings (same vocabulary as the character table). */\nexport const ENTITY_ASPECT_DEFAULTS: Record<\n EntityStudioKind,\n Record<string, string>\n> = {\n // Locations are environments → landscape framing everywhere.\n location: {\n timeOfDay: \"16:9\",\n weather: \"16:9\",\n seasons: \"16:9\",\n angles: \"16:9\",\n lighting: \"16:9\",\n atmosphereMotions: \"16:9\",\n },\n // Creatures (animals): turnaround angles & condition variations read square;\n // full-body poses read taller (portrait); motion clips are vertical.\n creature: {\n angles: \"1:1\",\n poses: \"3:4\",\n variations: \"1:1\",\n motion: \"9:16\",\n },\n // Objects/props: product turnarounds, materials, and condition variants are\n // square; motion clips are vertical.\n object: {\n angles: \"1:1\",\n materials: \"1:1\",\n variations: \"1:1\",\n motion: \"9:16\",\n },\n}\n\nconst RATIO_RE = /^\\d+:\\d+$/\n\n/**\n * Resolve the provider aspect string for an entity asset generation.\n * Precedence: explicit > node override > per-asset-type default > \"1:1\".\n * The two \"soft\" inputs are honored only when they parse as a \"W:H\" ratio, so a\n * stale value falls through instead of poisoning the request.\n */\nexport function resolveEntityAspect(opts: {\n entity: EntityStudioKind\n assetType: string\n explicit?: string | null\n nodeOverride?: string | null\n}): string {\n if (opts.explicit && RATIO_RE.test(opts.explicit)) return opts.explicit\n if (opts.nodeOverride && RATIO_RE.test(opts.nodeOverride)) return opts.nodeOverride\n return ENTITY_ASPECT_DEFAULTS[opts.entity]?.[opts.assetType] ?? \"1:1\"\n}\n\n/**\n * \"9:16\" → 0.5625 (width / height) for a CSS `aspect-ratio` fallback value.\n * Anything that isn't a \"W:H\" ratio (or has a zero term) → 1 (square).\n */\nexport function aspectRatioToNumber(ratio: string): number {\n const m = /^(\\d+):(\\d+)$/.exec(ratio.trim())\n if (!m) return 1\n const w = Number(m[1])\n const h = Number(m[2])\n return w > 0 && h > 0 ? w / h : 1\n}\n","export const PIPELINE_TYPES = [\"story_to_video\", \"song_to_music_video\"] as const\nexport type PipelineType = (typeof PIPELINE_TYPES)[number]\n\nexport const PIPELINE_FORMATS = [\n \"trailer\",\n \"short_film\",\n \"music_video\",\n \"reel\",\n \"commercial\",\n] as const\nexport type PipelineFormat = (typeof PIPELINE_FORMATS)[number]\n\nexport const PIPELINE_MODES = [\"manual\", \"auto\", \"guided\"] as const\nexport type PipelineMode = (typeof PIPELINE_MODES)[number]\n\nexport const PIPELINE_ACTIVATION_MODES = [\"interactive\", \"programmatic\"] as const\nexport type PipelineActivationMode = (typeof PIPELINE_ACTIVATION_MODES)[number]\n\nexport const PIPELINE_OUTPUT_RESOLUTIONS = [\"480p\", \"720p\", \"1080p\", \"4K\"] as const\nexport type PipelineOutputResolution = (typeof PIPELINE_OUTPUT_RESOLUTIONS)[number]\n\nexport const PER_FORMAT_DURATION_BOUNDS: Record<\n PipelineFormat,\n { min: number; max: number }\n> = {\n reel: { min: 7, max: 90 },\n commercial: { min: 10, max: 90 },\n trailer: { min: 30, max: 180 },\n short_film: { min: 12, max: 600 },\n music_video: { min: 30, max: 600 },\n}\n\nexport const GLOBAL_MAX_DURATION_SECONDS = 600\n\nexport function validateDurationForFormat(\n format: PipelineFormat,\n seconds: number,\n): { ok: true } | { ok: false; reason: string } {\n if (seconds > GLOBAL_MAX_DURATION_SECONDS) {\n return { ok: false, reason: `target_duration_seconds must be <= ${GLOBAL_MAX_DURATION_SECONDS}` }\n }\n const bounds = PER_FORMAT_DURATION_BOUNDS[format]\n if (seconds < bounds.min || seconds > bounds.max) {\n return {\n ok: false,\n reason: `${format} requires duration in [${bounds.min}, ${bounds.max}] seconds`,\n }\n }\n return { ok: true }\n}\n\nexport function validateModeActivation(\n mode: PipelineMode,\n activation: PipelineActivationMode,\n): { ok: true } | { ok: false; reason: string } {\n if (activation === \"programmatic\" && mode === \"guided\") {\n return {\n ok: false,\n reason: \"Programmatic activation cannot use guided mode (no user for chat turns)\",\n }\n }\n return { ok: true }\n}\n\n// Tier → max parallel pipelines (Architecture §5.4)\nexport const TIER_PIPELINE_PARALLELISM: Record<string, number> = {\n free: 0,\n basic: 1,\n standard: 2,\n pro: 3,\n business: 5,\n}\n\n// Tier → default hard cost cap when max_cost_credits omitted (Architecture §6.6.3)\nexport const TIER_MAX_PIPELINE_COST_CREDITS: Record<string, number> = {\n free: 0,\n basic: 300,\n standard: 800,\n pro: 2000,\n business: 5000,\n}\n\n// Per-stage soft timeout (matches workflow-orchestration)\nexport const PIPELINE_STAGE_TIMEOUT_MS = 30 * 60 * 1000\n// Hard ceiling for a SINGLE orchestrator drive (pipeline-worker aborts the\n// in-flight drive when this fires). One drive runs a whole stage's work; the\n// heaviest is animate_audio_edit, which fans out every scene × every shot\n// (KIE video gen + per-shot critic + audio + merge). For a multi-scene film\n// that legitimately exceeds 90 min — the old value aborted such drives\n// mid-fan-out, and before the scene-level resume short-circuit landed each\n// retry restarted from scratch and tripped the resume cap (prod pipeline\n// 64b76ed9). 4 h gives a heavy drive room to finish in one pass while staying\n// well under the reconcile cron's 6 h abandon threshold. Worker concurrency is\n// 5, so even a pathological long drive leaves 4 slots free.\nexport const PIPELINE_HARD_TIMEOUT_MS = 4 * 60 * 60 * 1000\n\n/**\n * Per-stage hard retry caps applied to image-gen for that stage.\n * Pipeline-level credit cap (max_cost_credits) is the ultimate guard, but\n * these prevent a single stage from sucking all the budget.\n */\nexport const ENTITY_TOOL_RETRY_CAP = 3 // tool-level failure retries per entity\n\n/**\n * Default variant counts when ShowrunnerPlan doesn't suggest specifics.\n */\nexport const DEFAULT_CHARACTER_ANGLE_COUNT = 3 // main + 2 variants for non-protagonist\nexport const DEFAULT_CHARACTER_EXPRESSION_COUNT = 2 // baseline expression variants\n\n/**\n * Short-film lean reference set. A few-shot film can't meaningfully consume\n * 5-8 reference variants per character: each shot is animated from exactly ONE\n * reference image (the video providers accept a single reference and drop the\n * rest — see `allocateReferenceSlots`), so the extra angle/expression variants\n * are pure wall-clock + KIE load with ~no quality return. For films at or under\n * the threshold we generate only main + 1 angle + 1 expression; longer films\n * keep the full plan-driven variant set unchanged.\n *\n * Measured impact: the characters stage was the joint-largest time sink (≈27\n * min for a 40 s film — 23 character images at ~58 s each on KIE). Capping a\n * ≤2 min film to 2 variants/character cuts that to ~12 images.\n */\nexport const SHORT_FILM_VARIANT_THRESHOLD_SEC = 120\nexport const SHORT_FILM_ANGLE_COUNT = 2 // main + 1 angle variant\nexport const SHORT_FILM_EXPRESSION_COUNT = 1 // neutral only\n\n/**\n * Max location variants generated even if Showrunner suggests more — cost guard.\n */\nexport const MAX_LOCATION_VARIANTS = 4\n\n/**\n * Maximum user-turn count per stage for the chat refine flow. Enforced by\n * the chat POST route (counts existing `role='user'` rows and rejects when\n * the cap is reached). 1D.2b ships **Script chat only** per the LLM Spec\n * v4.0 narrowing — `shot_list` + `post_merge` caps are pre-declared so\n * adding their chat surfaces in 1D.2d only needs route+UI wiring, not a\n * type/constant change.\n */\nexport const CHAT_TURN_CAPS = {\n script: 20,\n shot_list: 15,\n post_merge: 8,\n} as const\n\n/**\n * Pipeline entity error code emitted by Phase 1D.2c-a image critics\n * (Stage 2 Characters + Stage 4 Locations) and any future image-level\n * validators. Constant lets the frontend compare equality (not substring)\n * and the backend writes a single canonical value.\n *\n * Written to `pipeline_entities.metadata.last_error` after the critic retry\n * cap exhausts. Auto-mode's failure-aggregator (`detectImageCriticFailures`\n * + `failPipelineForImageCriticUnresolvable`) reads this exact value.\n */\nexport const IMAGE_CRITIC_UNRESOLVABLE = \"image_critic_unresolvable\"\n\n/**\n * Maximum critic-feedback retry budget per entity in Phase 1D.2c-a image\n * critics. Each fail triggers a regeneration with critic suggestions injected\n * into the prompt; after this many retries the entity is marked failed and\n * surfaces in EntityCard with recovery buttons.\n */\nexport const IMAGE_CRITIC_MAX_RETRIES = 2\n\n/**\n * Score threshold below which the critic's verdict is overridden to \"fail\"\n * regardless of the verdict field. Defends against an overly lenient critic\n * that says verdict='pass' on a borderline image. The numeric score (0-10)\n * is enforced by the schema and the system prompt anchors the meaning.\n */\nexport const IMAGE_CRITIC_MIN_ADHERENCE_SCORE = 5\n\n/**\n * Metadata keys written by the image-critic retry loop (Phase 1D.2c-a)\n * onto `pipeline_entities.metadata` when an entity's critic budget is\n * exhausted. The retry-image-generation route clears these to reset the\n * entity to a fresh attempt; EntityCard reads them to render findings +\n * the failed image.\n *\n * Single source of truth so the writer (`_image-critic-loop.ts`) and the\n * clearer (`routes/pipelines.ts:retry-image-generation`) can't drift.\n */\nexport const IMAGE_CRITIC_METADATA_KEYS = [\n \"last_error\",\n \"last_error_at\",\n \"critic_findings\",\n \"last_attempted_image_url\",\n \"last_attempted_asset_id\",\n \"image_critic_retry_count\",\n] as const\n\nexport type ImageCriticMetadataKey = (typeof IMAGE_CRITIC_METADATA_KEYS)[number]\n\n/**\n * Removes every {@link IMAGE_CRITIC_METADATA_KEYS} entry from a metadata\n * blob, returning a shallow copy. Used by the retry-image-generation route\n * to wipe critic-only state while preserving everything else (`name`,\n * `voice_match`, `reject_count`, etc.).\n */\nexport function clearImageCriticMetadata(\n meta: Record<string, unknown> | null | undefined,\n): Record<string, unknown> {\n if (!meta) return {}\n const next: Record<string, unknown> = { ...meta }\n for (const key of IMAGE_CRITIC_METADATA_KEYS) {\n delete next[key]\n }\n return next\n}\n\n/**\n * Phase 1D.2c-b-ii — Video Critic frame extraction modes.\n * Each pipeline picks one via PipelineInput.video_critic_frame_count.\n * Default 'first_last' uses the input keyframe + extractLastFrame output\n * (both already produced by Stage 6 + extractLastFrame call), so no new\n * frame extractions are needed in the default case.\n */\nexport const VIDEO_CRITIC_FRAME_MODES = [\"first_last\", \"first_middle_last\", \"five_evenly\"] as const\nexport type VideoCriticFrameMode = (typeof VIDEO_CRITIC_FRAME_MODES)[number]\n\n/** Cap=1 retry per shot — cost-aware (every retry is a full paid video\n * generation, the priciest step in the loop). */\nexport const VIDEO_CRITIC_MAX_RETRIES = 1\n\n/** Auto-fail threshold for both prompt_adherence_score and continuity_score. */\nexport const VIDEO_CRITIC_MIN_ADHERENCE_SCORE = 5\n\n/**\n * Phase 1D.2c-b-ii — Video Critic ShotSpec sibling field names that get\n * persisted by the per-shot retry loop (`runVideoCriticLoopForShot` in\n * `scene-internal-pipeline.ts`) and stripped by the retry-video-generation\n * recovery route + the frontend Regenerate button.\n *\n * Single source of truth so the writer + clearer can't drift. Mirror of\n * {@link IMAGE_CRITIC_METADATA_KEYS} for the entity-level image critic.\n */\nexport const VIDEO_CRITIC_METADATA_KEYS = [\n \"video_critic_findings\",\n \"video_critic_score\",\n \"video_critic_continuity_score\",\n \"video_critic_identified_action\",\n \"video_critic_retry_count\",\n \"video_critic_last_attempted_url\",\n \"video_critic_failed\",\n \"video_critic_verdict\",\n] as const\n\nexport type VideoCriticMetadataKey = (typeof VIDEO_CRITIC_METADATA_KEYS)[number]\n\n/**\n * Returns a shallow copy of `shot` with all `video_critic_*` keys stripped.\n * Used by the retry-video-generation route + frontend Regenerate handler to\n * reset a shot to a fresh critic attempt while preserving everything else\n * (camera, action, motion_prompt, …).\n */\nexport function clearVideoCriticMetadata<T extends Record<string, unknown>>(\n shot: T,\n): Omit<T, VideoCriticMetadataKey> {\n const cleaned = { ...shot } as Record<string, unknown>\n for (const key of VIDEO_CRITIC_METADATA_KEYS) {\n delete cleaned[key]\n }\n return cleaned as Omit<T, VideoCriticMetadataKey>\n}\n\n/**\n * Phase 1D.2 — single source of truth for chat-stage configuration.\n *\n * `wired: true` = the route has a specialist implemented + the LLM emits\n * valid `ChatTurnResponse` for this stage's artifact.\n * `wired: false` = stage is in the v0.5 spec but not yet implemented\n * (the chat POST returns HTTP 501 `chat_not_wired_for_stage`).\n *\n * Per spec §5.12 v0.5: `script` + `shot_list` + `post_merge`.\n *\n * - `script`: wired in 1D.2b (chat-refine-showrunner)\n * - `post_merge`: wired in 1D.2c (chat-refine-postmerge; suggest_branch only)\n * - `shot_list`: pre-declared, ships in 1D.2d (blocked by v4.0 per-scene\n * architecture)\n *\n * Prefer reading `CHAT_STAGES[stage].wired` directly in new code; the\n * sibling `CHAT_ENABLED_STAGES` / `CHAT_WIRED_STAGES` exports below are\n * derived and remain for backward compatibility with existing call sites.\n */\nexport const CHAT_STAGES = {\n script: { wired: true },\n shot_list: { wired: false },\n post_merge: { wired: true },\n} as const\n\nexport type ChatEnabledStage = keyof typeof CHAT_STAGES\n\n/**\n * Ordered list of stages with chat enabled. Derived from {@link CHAT_STAGES}.\n * **In 1D.2c, `script` AND `post_merge` have chat code paths wired** —\n * post-merge ships with a dedicated `chat-refine-postmerge` specialist\n * (suggest_branch only — see {@link STAGE_PATCH_SCHEMA}, `post_merge` stays\n * `null` since the merged video isn't user-editable in place). `shot_list`\n * is pre-declared for 1D.2d. The route's chat dispatch checks\n * {@link CHAT_WIRED_STAGES} to decide which specialist to invoke (or 501\n * for unwired stages).\n */\nexport const CHAT_ENABLED_STAGES: readonly ChatEnabledStage[] = Object.keys(\n CHAT_STAGES,\n) as ChatEnabledStage[]\n\n/**\n * Per-stage boolean map of whether chat code paths are actually wired\n * end-to-end. Derived from {@link CHAT_STAGES}. The chat POST route reads\n * this to decide whether to invoke a specialist (true) or return 501\n * `chat_not_wired_for_stage` (false).\n */\nexport const CHAT_WIRED_STAGES: Record<ChatEnabledStage, boolean> = {\n script: CHAT_STAGES.script.wired,\n shot_list: CHAT_STAGES.shot_list.wired,\n post_merge: CHAT_STAGES.post_merge.wired,\n}\n","import { z } from \"zod\"\n\n// SceneInputMode lives in model-constants.ts — re-export so all SceneNodeData\n// consumers import from one place.\nimport { SceneInputModeSchema } from \"./model-constants.js\"\n\n/**\n * TransitionType — the set of allowed shot-to-shot transitions emitted by the\n * Editor LLM stage. Single source of truth shared across:\n * - ShotSpec.cut_decision.transition_to_next (this file)\n * - backend/src/ee/pipelines/llms/editor.ts (LLM result schema)\n * - backend/src/ee/pipelines/services/pipeline-final-merge.ts\n * - backend/src/ee/pipelines/freecut-export.ts\n */\nexport const TransitionTypeSchema = z.enum([\n \"hard_cut\",\n \"dissolve\",\n \"match_cut\",\n \"overlap\",\n])\nexport type TransitionType = z.infer<typeof TransitionTypeSchema>\n\n/**\n * ShotSpec — one shot inside a SceneNodeData.\n * Mirrors Architecture §6.9.1 + v4.1 Method-2/3/5/7/8/10 field additions.\n */\nexport const ShotSpecSchema = z.object({\n shot_id: z.string().regex(/^shot_\\d{2,3}$/, \"shot_id must be shot_NN or shot_NNN\"),\n camera: z.object({\n shot_type: z.enum([\n \"wide\", \"medium\", \"close_up\", \"extreme_close_up\", \"pov\", \"over_shoulder\",\n ]),\n angle: z.enum([\"eye_level\", \"low\", \"high\", \"dutch\", \"birds_eye\"]),\n motion: z.enum([\"static\", \"pan\", \"tilt\", \"dolly\", \"tracking\", \"handheld\"]),\n }),\n shot_intensity_kind: z.enum([\n \"establishing_shot\", \"action_shot\", \"dialogue_shot\",\n \"reaction_shot\", \"climactic_shot\", \"transition_shot\",\n ]),\n\n action: z.string().max(300),\n dialogue_line: z.string().max(200).nullable(),\n duration_seconds: z.number().min(0.3).max(8),\n\n motion_prompt: z.string().max(200),\n\n // Internal continuity within this scene\n start_state: z.string().max(200),\n end_state: z.string().max(200),\n continuity_with_previous: z.string().max(200).nullable(),\n\n // Provider-neutral intent — engine maps to provider-specific directives at call time\n shot_intent: z.object({\n needs_multishot_reference: z.boolean().default(false),\n is_loopable: z.boolean().default(false),\n needs_music_suppression: z.boolean().default(true),\n is_match_cut: z.boolean().default(false), // v4.1 Method 7\n }),\n\n visual_keyframe_prompt: z.string().min(1).max(1000),\n\n // v4.1 Method 2 — pre-planned paired keyframes (required when shot_input_mode='first_last_frame')\n end_keyframe_prompt: z.string().max(1000).optional(),\n\n // v4.1 Method 3 — video continuation (this shot extends extends_shot_id's clip)\n extends_shot_id: z.string().optional(),\n\n // v4.1 Method 5 — i2i bridge applied to prior last_frame before this shot animates\n bridge_image_prompt: z.string().max(500).optional(),\n\n // v4.1 Method 8 — sparse keyframes for interpolation models\n interpolation_keyframes: z\n .array(\n z.object({\n timestamp_sec: z.number().nonnegative(),\n prompt: z.string().min(10).max(1000),\n }),\n )\n .max(16)\n .optional(),\n\n // Phase 1C.3 Method 8 — generated R2 URLs of the sub-keyframes, one per\n // `interpolation_keyframes[N].prompt`. Stage 6 writes these BEFORE Stage 7\n // runs so the animate step can pass them to the interpolation provider.\n // Length MUST equal `interpolation_keyframes.length` when populated.\n interpolation_keyframe_urls: z.array(z.string().url()).max(16).optional(),\n\n // v4.1 Method 10 — parametric 3D camera path\n camera_path_directive: z\n .object({\n path_kind: z.enum([\"orbit\", \"dolly\", \"crane\", \"arc\", \"reveal\"]),\n parameters: z.record(z.unknown()).optional(),\n })\n .optional(),\n\n // ─── Execution state (engine writes; null on planning) ─────────────────────\n // Phase 1C.1: per-shot execution state lands directly on the shot record so\n // the SceneNode internal pipeline + continuity chain can read/write them in\n // one place. All optional — planning-time ShotSpec carries none of these.\n\n // Stage 6 (scene_images) writes these after keyframe generation.\n keyframe_asset_id: z.string().uuid().optional(),\n keyframe_url: z.string().url().optional(),\n\n // Stage 7 (animate_audio_edit) step 3 (animate) writes these after the\n // image-to-video / text-to-video call succeeds.\n video_asset_id: z.string().uuid().optional(),\n video_url: z.string().url().optional(),\n\n // Stage 7 step 3 (extract_frame chain — sequential mode only) writes these\n // after each shot's last frame is extracted at duration - 0.1s. Used by the\n // next shot's continuity chain (Method 1).\n last_frame_asset_id: z.string().uuid().optional(),\n last_frame_url: z.string().url().optional(),\n\n // Stage 7 step 4 (speech) writes these per shot with dialogue_line.\n audio_asset_id: z.string().uuid().optional(),\n audio_url: z.string().url().optional(),\n\n // Stage 7 step 5 (lip-sync) writes these when lipsync_enabled and the shot\n // has dialogue. The lipsynced clip replaces the shot's video_url in the\n // step-6 combine call.\n lipsynced_asset_id: z.string().uuid().optional(),\n lipsynced_url: z.string().url().optional(),\n\n // Phase 1C.3 — bridged frame (Method 5). Defensive placeholder; never set\n // in 1C.1 (continuity.applyContinuityToStartFrame already reads this).\n bridged_frame_url: z.string().url().optional(),\n\n // Phase 1D.1 Method 7 — set true when the user accepts a MatchCutCritic\n // 'break' verdict for this shot's pair. Stage 6 reads this to know the\n // break is resolved and the scene can advance to Stage 7.\n accepted_match_cut_break: z.boolean().optional(),\n\n // ─── Phase 1C.2 — dialogue + editor cut metadata ───────────────────────────\n // All optional; planning-time ShotSpec carries none of these. Populated by\n // the Editor LLM (Stage 7) and the silent-cut-preview sub-gate handler.\n\n // True when `dialogue_line` is non-null AND the speech generator produced\n // an audio track. The Editor LLM uses this to gate cut-in / cut-out into\n // the dialogue_no_cut_zone (Method 5.13.1 — never trim a syllable).\n has_dialogue: z.boolean().default(false),\n\n // Measured length of the per-shot speech audio (Stage 7 step 4 writes this).\n // Separate from `duration_seconds` (the planning intent) — the actual\n // recording can run longer/shorter than the spec.\n actual_audio_duration_sec: z.number().optional(),\n\n // Inclusive [start, end] window (seconds, relative to the shot's video clip)\n // during which the Editor LLM MUST NOT cut. Computed from\n // `actual_audio_duration_sec` + small padding by the Editor LLM stage.\n // null when has_dialogue=false (no zone to protect).\n dialogue_no_cut_zone: z\n .object({ start: z.number(), end: z.number() })\n .nullable()\n .optional(),\n\n // Editor LLM output (Phase 1C.2). Populated by the Editor LLM stage; the\n // silent-cut-preview sub-gate may patch it via user-applied overrides.\n // Mirrors the editor_decisions audit row shape (migration 135).\n cut_decision: z\n .object({\n in_offset_sec: z.number().min(0).max(2).default(0),\n out_offset_sec: z.number().min(0).max(2).default(0),\n transition_to_next: TransitionTypeSchema,\n transition_duration_sec: z.number().min(0).max(2).optional(),\n beat_snap_seconds: z.number().nullable().optional(),\n })\n .optional(),\n})\nexport type ShotSpec = z.infer<typeof ShotSpecSchema>\n\n/**\n * AssetRef — minimal asset reference shape for execution-state fields.\n * Phase 1B.2 doesn't populate these (Stage 6+ work) but the schema must accept them\n * for parse round-trips.\n */\nexport const AssetRefSchema = z.object({\n asset_id: z.string().uuid(),\n url: z.string().url(),\n})\nexport type AssetRef = z.infer<typeof AssetRefSchema>\n\n/**\n * SceneNodeData — what the Scene Director emits, what the SceneNode renders,\n * what the engine persists on `pipeline_entities.metadata` (for entity_type='scene').\n * Mirrors Architecture §6.9.1.\n */\nexport const SceneNodeDataSchema = z.object({\n // Plan fields (Scene Director fills; user editable)\n scene_index: z.number().int().min(1),\n description: z.string().max(500),\n emotional_beat: z.string(),\n duration_seconds: z.number().positive(),\n\n // Input mode — gates which video_model values are valid\n shot_input_mode: SceneInputModeSchema,\n\n // Echoed inputs (Scene Director copies from SceneSpec)\n cast_keys: z.array(z.string()),\n location_key: z.string(),\n object_keys: z.array(z.string()),\n continuity_from_prev: z.enum([\"hard_cut\", \"match_last_frame\", \"dissolve\"]),\n\n // Model picks\n image_model: z.string(),\n video_model: z.string(),\n\n // Shot list\n shots: z.array(ShotSpecSchema).min(1).max(8),\n\n // v4.1 Method 6 — pre-generated master keyframe (set in 1C; Phase 1B.2 always null)\n scene_anchor_keyframe: AssetRefSchema.nullable().default(null),\n\n // Optional per-scene style override\n style_directives: z\n .object({\n visualStyle: z.string().optional(),\n colorPalette: z.string().optional(),\n lighting: z.string().optional(),\n cameraLanguage: z.string().optional(),\n avoid: z.string().optional(),\n })\n .partial()\n .optional(),\n\n // Execution state (engine writes; null on planning — Phase 1C populates)\n generated_keyframes: z.array(AssetRefSchema).default([]),\n generated_clips: z.array(AssetRefSchema).default([]),\n composite_video: AssetRefSchema.nullable().default(null),\n last_frame: AssetRefSchema.nullable().default(null),\n scene_audio_track: AssetRefSchema.nullable().default(null),\n\n // Phase 1C.1 Stage 7 result — composite video assembled from the per-shot\n // clips inside this scene. Optional flat fields kept alongside\n // `composite_video` (AssetRefSchema) so consumers can read either shape.\n composite_video_asset_id: z.string().uuid().optional(),\n composite_video_url: z.string().url().optional(),\n})\nexport type SceneNodeData = z.infer<typeof SceneNodeDataSchema>\n\n/**\n * SceneMetadataSchema — what gets persisted on `pipeline_entities.metadata`\n * for entity_type='scene'. The discriminated union in pipeline-types.ts already has\n * Character/Object/Location entries from 1A; this Phase 1B.2 task extends it.\n */\nexport const SceneMetadataSchema = z.object({\n entity_type: z.literal(\"scene\"),\n scene_id: z.string(),\n shot_ids: z.array(z.string()),\n emotional_beat: z.string(),\n // Canonical pointer to the canvas SceneNode (workflows.nodes[i].id)\n scene_node_id: z.string(),\n // Opt-in Explode tracking (Phase 2 — null in 1B.2)\n exploded_to_workflow_id: z.string().uuid().nullable().default(null),\n // Phase 1B.2 stashes the full SceneNodeData here so the orchestrator + panel UI\n // don't have to re-resolve it from canvas state.\n // Optional because Stage 5 inserts the entity row BEFORE the Scene Director runs\n // (status='pending' / 'generating') — the field lands after the Scene Director succeeds.\n scene_node_data: SceneNodeDataSchema.optional(),\n})\nexport type SceneMetadata = z.infer<typeof SceneMetadataSchema>\n\n/**\n * MatchCutVerdictSchema — Phase 1D.1 Method 7.\n *\n * What Stage 6 persists in `pipeline_stages.output.match_cut_verdicts` for\n * each match-cut shot pair. Keyed by the TARGET shot_id (the shot with\n * `shot_intent.is_match_cut=true`). The pair is [target, next-shot].\n *\n * Stage 6 runs `runValidateMatchCut` for every eligible target and stores\n * one MatchCutVerdict per pair. The `pendingBreaks` list in the orchestrator\n * result identifies shots the user must explicitly accept before Stage 7 runs.\n */\nexport const MatchCutVerdictSchema = z.object({\n shot_pair: z.tuple([z.string(), z.string()]),\n match_strength: z.enum([\"strong\", \"moderate\", \"weak\", \"break\"]),\n suggested_adjustments: z.string().max(300),\n checked_at: z.string().datetime(),\n})\nexport type MatchCutVerdict = z.infer<typeof MatchCutVerdictSchema>\n","import { z } from \"zod\"\nimport {\n PIPELINE_FORMATS,\n PIPELINE_MODES,\n PIPELINE_OUTPUT_RESOLUTIONS,\n PIPELINE_TYPES,\n VIDEO_CRITIC_FRAME_MODES,\n} from \"./pipeline-defaults.js\"\nimport { SceneMetadataSchema } from \"./scene-node-types.js\"\n\n// ─── Input schema (POST /v1/pipelines body) ───────────────────────────────────\n\nexport const StyleDirectivesSchema = z.object({\n visualStyle: z.string().max(200).optional(),\n colorPalette: z.string().max(200).optional(),\n lighting: z.string().max(200).optional(),\n cameraLanguage: z.string().max(200).optional(),\n avoid: z.string().max(400).optional(),\n})\nexport type StyleDirectives = z.infer<typeof StyleDirectivesSchema>\n\n// User-configurable per-stage model overrides. Keys follow `<stage>_<kind>` so\n// the resolver can fall back to the global `<kind>_model` field below when a\n// stage key is absent. When neither stage nor global is set, downstream code\n// keeps its current \"LLM picks\" or \"hardcoded default\" behavior.\nexport const PIPELINE_MODEL_STAGES = [\n \"characters_image\",\n \"locations_image\",\n \"objects_image\",\n \"scene_keyframes_image\",\n \"shots_video\",\n \"script_llm\",\n] as const\nexport type PipelineModelStage = (typeof PIPELINE_MODEL_STAGES)[number]\nconst PipelineModelStageEnum = z.enum(PIPELINE_MODEL_STAGES)\n\n// User-pinnable model identifiers. Curated allowlists — both the Zod schema\n// AND the frontend dropdowns derive from these. Three reasons the allowlist\n// matters even with the `model_pricing` hard-fail guard downstream:\n// 1. Closes the unknown-ID oracle (an unknown id returns a 503 from the\n// route, an known-but-internal id would silently 500 mid-pipeline).\n// 2. Keeps internal-only synthetic ids (e.g. `flux-lora-character`) out of\n// the user-pinnable surface — those should ONLY be set by the\n// orchestrator at runtime.\n// 3. Prevents prompt injection via raw interpolation of the override string\n// into the Scene Director's LLM prompt — if it isn't in the enum it\n// can't reach the prompt.\n// Tier-restriction enforcement (free tier blocked from veo3 etc.) lives at\n// the route level via `canAffordCredits` — see `routes/pipelines.ts`.\nexport const PIPELINE_PINNABLE_IMAGE_MODELS = [\n \"nano-banana\",\n \"nano-banana-pro\",\n \"nano-banana-2\",\n \"flux\",\n \"gpt-image\",\n \"gpt-image-2\",\n] as const\nexport type PipelinePinnableImageModel = (typeof PIPELINE_PINNABLE_IMAGE_MODELS)[number]\n\nexport const PIPELINE_PINNABLE_VIDEO_MODELS = [\n \"kling-turbo\",\n \"kling\",\n \"kling-3.0\",\n \"seedance\",\n \"seedance-2\",\n \"seedance-2-fast\",\n \"seedance-2-mini\",\n \"veo3\",\n \"veo3.1\",\n \"veo3_lite\",\n \"minimax\",\n \"hailuo-standard\",\n \"wan-turbo\",\n \"bytedance-lite\",\n \"bytedance-pro\",\n] as const\nexport type PipelinePinnableVideoModel = (typeof PIPELINE_PINNABLE_VIDEO_MODELS)[number]\n\n// Script LLM — Anthropic-only. The pipeline's `callLLM` is hardwired to the\n// Anthropic SDK; picking a non-Anthropic model would 400 mid-stage and burn\n// the upfront credit reservation. Adding GPT/Gemini support requires routing\n// through `lib/llm-client.ts` first; until then, keep this list tight.\nexport const PIPELINE_PINNABLE_SCRIPT_LLMS = [\n \"claude-haiku-4-5\",\n \"claude-sonnet-4-6\",\n \"claude-opus-4-7\",\n] as const\nexport type PipelinePinnableScriptLlm = (typeof PIPELINE_PINNABLE_SCRIPT_LLMS)[number]\n\nconst ImageModelEnum = z.enum(PIPELINE_PINNABLE_IMAGE_MODELS)\nconst VideoModelEnum = z.enum(PIPELINE_PINNABLE_VIDEO_MODELS)\nconst ScriptLlmEnum = z.enum(PIPELINE_PINNABLE_SCRIPT_LLMS)\n\n// Per-stage override map. Each stage key maps to a model id valid for its\n// kind. Defined as a discriminated shape (instead of `Record<stage, string>`)\n// so the type system rejects `stage_models.shots_video = \"nano-banana\"`.\nconst StageModelsSchema = z\n .object({\n characters_image: ImageModelEnum.optional(),\n locations_image: ImageModelEnum.optional(),\n objects_image: ImageModelEnum.optional(),\n scene_keyframes_image: ImageModelEnum.optional(),\n shots_video: VideoModelEnum.optional(),\n script_llm: ScriptLlmEnum.optional(),\n })\n .optional()\n\nexport const PipelineConfigSchema = z.object({\n music_enabled: z.boolean().default(true),\n narration_enabled: z.boolean().default(true),\n lipsync_enabled: z.boolean().default(true),\n freecut_export_enabled: z.boolean().default(false),\n // Phase 1C.2.1 §H — when freecut_export_enabled, choose the serialization\n // format. JSON is the original Nodaro-flat-timeline-v1 shape; FCPXML emits\n // an FCPXML 1.10 timeline that Final Cut Pro / DaVinci Resolve / Premiere\n // can ingest directly. Both reuse the same in-memory timeline reduction.\n freecut_export_format: z.enum([\"json\", \"fcpxml\"]).default(\"json\"),\n shot_generation_mode: z.enum([\"parallel\", \"sequential\"]).default(\"parallel\"),\n silent_cut_review: z.boolean().default(true),\n // Phase 0 studio — when true, the script stage skips the critic + refine loop\n // and pauses for the user immediately after the first draft (\"critic off by\n // default; you decide\" — the user can Edit / Regenerate at the gate).\n skip_script_critic: z.boolean().default(false),\n // Studio — when true, the PRODUCTION stages (shot_list / scene_images) advance\n // automatically instead of pausing for per-scene / keyframe review. The\n // studio's control is the creative entities (script/cast/props/locations); the\n // engine then produces the film. The final cut (post_merge) still pauses for\n // review, and animate sub-gates (dialogue/silent-cut) still surface. Mirrors\n // auto-mode's advance for those stages without skipping the creative gates.\n auto_advance_production: z.boolean().default(false),\n // Studio speed — when true, the shot-list stage does NOT auto-force sequential\n // mode for shot continuity, so the animate stage renders all shots in parallel\n // (~minutes vs ~an hour for a multi-shot reel). Trades continuity chaining for\n // speed; per-shot keyframe identity still holds.\n force_parallel_animate: z.boolean().default(false),\n // Global model overrides — apply to every stage of the matching kind unless\n // a more-specific entry in `stage_models` overrides it. Constrained to the\n // pinnable allowlists above; the route handler still re-validates against\n // tier restrictions before pipeline creation.\n image_model: ImageModelEnum.optional(),\n video_model: VideoModelEnum.optional(),\n music_model: z.string().optional(),\n script_llm: ScriptLlmEnum.optional(),\n // Per-stage overrides. Each key is constrained to its kind's allowlist.\n // Empty/missing key = fall back to the global field.\n stage_models: StageModelsSchema,\n})\nexport type PipelineConfig = z.infer<typeof PipelineConfigSchema>\n\n/**\n * Resolve which model a given stage should use, following the precedence:\n * 1. `config.stage_models[stage]` — user's per-stage override\n * 2. `config.<kind>_model` (or `config.script_llm`) — user's global pick\n * 3. `undefined` — caller falls back to its own default (LLM picks, or hardcode)\n *\n * Returns `undefined` (not `null`) so callers can use `??` chains cleanly.\n */\nexport function resolvePipelineModel(\n config: PipelineConfig | Partial<PipelineConfig> | null | undefined,\n stage: PipelineModelStage,\n): string | undefined {\n if (!config) return undefined\n const override = config.stage_models?.[stage]\n if (override) return override\n if (stage === \"script_llm\") return config.script_llm\n if (stage.endsWith(\"_video\")) return config.video_model\n if (stage.endsWith(\"_image\")) return config.image_model\n return undefined\n}\n\nexport const PipelineInputSchema = z.object({\n pipeline_type: z.enum(PIPELINE_TYPES).default(\"story_to_video\"),\n workflow_id: z.string().uuid().optional(),\n root_node_id: z.string().min(1),\n story_prompt: z.string().min(1).max(4000),\n target_duration_seconds: z.number().int().min(5).max(3600),\n format: z.enum(PIPELINE_FORMATS),\n output_resolution: z.enum(PIPELINE_OUTPUT_RESOLUTIONS).default(\"720p\"),\n language: z.string().min(2).max(10).default(\"en\"),\n mode: z.enum(PIPELINE_MODES).default(\"manual\"),\n // Legacy back-compat — when both `mode` and `auto_mode` present, `mode` wins.\n auto_mode: z.boolean().optional(),\n style_directives: StyleDirectivesSchema.optional(),\n config: PipelineConfigSchema.partial().optional(),\n max_cost_credits: z.number().int().positive().optional(),\n video_critic_frame_count: z.enum(VIDEO_CRITIC_FRAME_MODES).default(\"first_last\"),\n})\nexport type PipelineInput = z.infer<typeof PipelineInputSchema>\n\n// ─── Detection LLM output (LLM spec §1) ───────────────────────────────────────\n\nexport const DetectionResultSchema = z.object({\n characters: z.array(\n z.object({\n key: z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),\n name: z.string(),\n visual_description: z.string(),\n role_hint: z.enum([\"protagonist\", \"antagonist\", \"supporting\", \"cameo\"]),\n has_dialogue_hint: z.boolean(),\n }),\n ),\n objects: z.array(\n z.object({\n key: z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),\n name: z.string(),\n visual_description: z.string(),\n narrative_significance: z.string(),\n }),\n ),\n locations: z.array(\n z.object({\n key: z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),\n name: z.string(),\n visual_description: z.string(),\n parent_location_key: z.string().nullable(),\n variant_kind: z\n .enum([\"main\", \"time_of_day\", \"weather\", \"aftermath\"])\n .nullable(),\n }),\n ),\n audio_intent: z.object({\n has_narrator: z.boolean(),\n narrator_profile_hint: z.string().nullable(),\n dialogue_speaker_keys: z.array(z.string()),\n music: z.object({\n mood_hint: z.string(),\n bpm_hint: z.number(),\n genre_hints: z.array(z.string()),\n }),\n sfx_hints: z.array(z.string()),\n }),\n})\nexport type DetectionResult = z.infer<typeof DetectionResultSchema>\n\n// ─── Showrunner output (LLM spec §2) ──────────────────────────────────────────\n\nexport const EMOTIONAL_BEAT = z.enum([\n \"setup\",\n \"inciting\",\n \"rising\",\n \"tension\",\n \"climax\",\n \"release\",\n \"denouement\",\n \"reveal\",\n \"shock\",\n \"release_humor\",\n \"reflection\",\n])\n\nexport const SceneSpecSchema = z.object({\n scene_index: z.number().int().min(1),\n description: z.string().max(500),\n emotional_beat: EMOTIONAL_BEAT,\n duration_seconds: z.number().positive(),\n cast_keys: z.array(z.string()),\n location_key: z.string(),\n object_keys: z.array(z.string()),\n dialogue: z\n .array(\n z.object({\n cast_key: z.string(),\n line: z.string().max(200),\n }),\n )\n .default([]),\n narration: z.string().nullable(),\n continuity_from_prev: z.enum([\"hard_cut\", \"match_last_frame\", \"dissolve\"]),\n shot_count_hint: z.number().int().min(1).max(8),\n})\n\nexport const ShowrunnerPlanSchema = z.object({\n title: z.string(),\n logline: z.string().max(200),\n target_duration_seconds: z.number().positive(),\n format: z.enum(PIPELINE_FORMATS),\n output_resolution: z.enum(PIPELINE_OUTPUT_RESOLUTIONS),\n language: z.string(),\n genre: z.enum([\n \"action\",\n \"drama\",\n \"thriller\",\n \"comedy\",\n \"horror\",\n \"sci-fi\",\n \"documentary\",\n ]),\n tone: z\n .array(\n z.enum([\n \"gritty\",\n \"hopeful\",\n \"tense\",\n \"melancholic\",\n \"playful\",\n \"epic\",\n \"intimate\",\n \"surreal\",\n \"nostalgic\",\n \"urgent\",\n \"dreamy\",\n \"cold\",\n \"warm\",\n \"menacing\",\n \"whimsical\",\n \"somber\",\n \"triumphant\",\n \"eerie\",\n ]),\n )\n .max(5),\n cast: z\n .array(\n z.object({\n key: z.string(),\n name: z.string(),\n role: z.enum([\"protagonist\", \"antagonist\", \"supporting\", \"cameo\"]),\n visual_description: z.string(),\n voice_profile: z.string(),\n has_dialogue: z.boolean(),\n angle_count_hint: z.number().int().min(1).max(8),\n expression_set_hint: z\n .array(\n z.enum([\n \"neutral\",\n \"smiling\",\n \"laughing\",\n \"angry\",\n \"scared\",\n \"determined\",\n \"sad\",\n \"surprised\",\n \"thoughtful\",\n \"crying\",\n ]),\n )\n .max(6)\n .default([]),\n }),\n )\n .max(8),\n locations: z\n .array(\n z.object({\n key: z.string(),\n name: z.string(),\n visual_description: z.string(),\n variants_needed: z.array(z.string()).default([]),\n }),\n )\n .max(8),\n objects: z\n .array(\n z.object({\n key: z.string(),\n name: z.string(),\n visual_description: z.string(),\n narrative_significance: z.string(),\n }),\n )\n .max(10),\n scenes: z.array(SceneSpecSchema).min(3).max(20),\n beats: z.array(\n z.object({\n type: z.enum([\"hook\", \"rising\", \"climax\", \"resolution\"]),\n scene_indices: z.array(z.number().int()),\n }),\n ),\n has_narrator: z.boolean(),\n narrator_profile: z.string().nullable(),\n /**\n * Phase 1C.2.1 §G — optional narration_script for omniscient narrator-style\n * formats (trailers, documentaries, retro storytelling). When present, Stage\n * 7 sub-step 7c synthesizes a single narration audio track that spans the\n * full pipeline duration and gets mixed over the music in the final merge\n * (music ducks to 60% volume per spec §G5). Leave undefined for dialogue-\n * driven scenes that don't benefit from narration.\n */\n narration_script: z\n .object({\n text: z.string().min(20).max(4000),\n voice_id: z.string().optional(),\n })\n .optional(),\n music_plan: z.object({\n mood: z.string(),\n bpm_target: z.number(),\n genre_hints: z.array(z.string()),\n }),\n global_style: z.object({\n visual_style: z.string(),\n color_palette: z.string(),\n lighting: z.string(),\n camera_language: z.string(),\n }),\n total_duration_seconds: z.number(),\n estimated_scene_count: z.number(),\n warnings: z.array(z.string()),\n})\nexport type ShowrunnerPlan = z.infer<typeof ShowrunnerPlanSchema>\n\n// ─── Critic output (LLM spec §4) ──────────────────────────────────────────────\n\nexport const CriticIssueSchema = z.object({\n severity: z.enum([\"blocking\", \"warning\"]),\n scene_index: z.number().int().nullable(),\n issue_type: z.string(),\n description: z.string(),\n suggested_fix: z.string(),\n})\n\nexport const ScriptCriticVerdictSchema = z.object({\n verdict: z.enum([\"pass\", \"fail\"]),\n issues: z.array(\n CriticIssueSchema.extend({\n issue_type: z.enum([\n \"duration\",\n \"consistency\",\n \"shot_count_hint\",\n \"generatability\",\n \"dialogue\",\n \"continuity\",\n \"arc\",\n ]),\n }),\n ),\n duration_analysis: z.object({\n target_seconds: z.number(),\n actual_sum_seconds: z.number(),\n deviation_percent: z.number(),\n within_tolerance: z.boolean(),\n }),\n improvement_suggestions: z.array(z.string()).optional(),\n})\nexport type ScriptCriticVerdict = z.infer<typeof ScriptCriticVerdictSchema>\n\nexport const CastCoverageCriticVerdictSchema = z.object({\n verdict: z.enum([\"pass\", \"fail\"]),\n issues: z.array(\n CriticIssueSchema.extend({\n issue_type: z.enum([\n \"orphan_cast\",\n \"unresolved_ref\",\n \"dialogue_load_skew\",\n \"role_completeness\",\n \"key_uniqueness\",\n ]),\n }),\n ),\n dialogue_distribution: z.array(\n z.object({\n cast_key: z.string(),\n line_count: z.number(),\n share_pct: z.number(),\n }),\n ),\n})\nexport type CastCoverageCriticVerdict = z.infer<typeof CastCoverageCriticVerdictSchema>\n\nexport const LocationsCoverageCriticIssueSchema = CriticIssueSchema.extend({\n issue_type: z.enum([\n \"orphan_location\",\n \"unresolved_scene_location_ref\",\n \"duplicate_key\",\n \"name_too_similar\",\n \"description_too_short\",\n \"redundant_location\",\n ]),\n // `nullish()` (= `.nullable().optional()`) instead of `.optional()` —\n // Sonnet routinely emits `\"location_key\": null` for issue_types like\n // `redundant_location` that flag a structural problem without pointing\n // at a specific key. `.optional()` only accepted `undefined`, so those\n // emits failed Zod validation, exhausted the critic retry budget, and\n // killed the whole Stage 1 with `locations_coverage validation failed\n // after 2 attempts: issues.N.location_key: Expected string, received\n // null`. Same fix already in place on `scene_index` below.\n location_key: z.string().nullish(),\n scene_index: z.number().int().nullish(),\n})\n\nexport const LocationsCoverageCriticVerdictSchema = z.object({\n verdict: z.enum([\"pass\", \"fail\"]),\n issues: z.array(LocationsCoverageCriticIssueSchema),\n})\nexport type LocationsCoverageCriticVerdict = z.infer<typeof LocationsCoverageCriticVerdictSchema>\n\n// Phase 1D.2c-a — image-level vision critics\n\nexport const CharacterImageCriticVerdictSchema = z.object({\n verdict: z.enum([\"pass\", \"fail\"]),\n prompt_adherence_score: z.number().int().min(0).max(10),\n identified_subject: z.string().min(1).max(500),\n issues: z.array(\n z.object({\n severity: z.enum([\"blocking\", \"warning\"]),\n category: z.enum([\n \"wrong_subject\",\n \"wrong_attributes\",\n \"visual_artifacts\",\n \"style_mismatch\",\n \"other\",\n ]),\n description: z.string().min(1).max(500),\n suggested_fix: z.string().min(1).max(300),\n }),\n ),\n approved_summary: z.string().min(1).max(500).optional(),\n})\nexport type CharacterImageCriticVerdict = z.infer<typeof CharacterImageCriticVerdictSchema>\n\nexport const LocationImageCriticVerdictSchema = z.object({\n verdict: z.enum([\"pass\", \"fail\"]),\n prompt_adherence_score: z.number().int().min(0).max(10),\n identified_subject: z.string().min(1).max(500),\n issues: z.array(\n z.object({\n severity: z.enum([\"blocking\", \"warning\"]),\n category: z.enum([\n \"wrong_location_type\",\n \"wrong_time_of_day\",\n \"wrong_attributes\",\n \"visual_artifacts\",\n \"style_mismatch\",\n \"other\",\n ]),\n description: z.string().min(1).max(500),\n suggested_fix: z.string().min(1).max(300),\n }),\n ),\n approved_summary: z.string().min(1).max(500).optional(),\n})\nexport type LocationImageCriticVerdict = z.infer<typeof LocationImageCriticVerdictSchema>\n\n// Phase 1D.2c-b-i — Storyboard Cohesion Critic (Stage 6, warn-only)\n\nexport const StoryboardCohesionCriticVerdictSchema = z.object({\n overall_assessment: z.enum([\"coherent\", \"minor_issues\", \"incoherent\"]),\n coherence_score: z.number().int().min(0).max(10),\n summary: z.string().min(1).max(500),\n findings: z.array(\n z.object({\n severity: z.enum([\"info\", \"warning\", \"blocking\"]),\n category: z.enum([\n \"character_inconsistency\",\n \"location_inconsistency\",\n \"lighting_mismatch\",\n \"style_drift\",\n \"missing_establishing_shot\",\n \"plot_jump\",\n \"other\",\n ]),\n affected_scenes: z.array(z.number().int().min(1)).max(20),\n description: z.string().min(1).max(500),\n suggested_action: z.string().min(1).max(300),\n }),\n ).max(30),\n})\nexport type StoryboardCohesionCriticVerdict = z.infer<typeof StoryboardCohesionCriticVerdictSchema>\n\n// Phase 1D.2c-b-ii — Video Critic (Stage 7)\n\nexport const VideoCriticVerdictSchema = z.object({\n verdict: z.enum([\"pass\", \"fail\"]),\n prompt_adherence_score: z.number().int().min(0).max(10),\n continuity_score: z.number().int().min(0).max(10).nullable(),\n identified_action: z.string().min(1).max(500),\n issues: z.array(\n z.object({\n severity: z.enum([\"blocking\", \"warning\"]),\n category: z.enum([\n \"wrong_action\",\n \"prompt_mismatch\",\n \"continuity_break\",\n \"visual_artifacts\",\n \"motion_glitch\",\n \"style_mismatch\",\n \"other\",\n ]),\n description: z.string().min(1).max(500),\n suggested_fix: z.string().min(1).max(300),\n }),\n ).max(20),\n approved_summary: z.string().min(1).max(500).optional(),\n})\nexport type VideoCriticVerdict = z.infer<typeof VideoCriticVerdictSchema>\n\n/**\n * Phase 1D.2c-b-ii — Video Critic ShotSpec sibling fields persisted by\n * Stage 7 (scene-internal-pipeline) directly on each ShotSpec record (NOT\n * under a nested `metadata` key). Persisting them as siblings lets the shot\n * recovery routes update them via a JSON-Patch-style path; the shared Zod\n * `ShotSpec` schema doesn't enumerate these because ShotSpec is an open\n * object on the persistence path, so this interface is the single source of\n * truth for backend + frontend consumers that need to read/write them.\n *\n * Persisted location:\n * `pipeline_entities.metadata.scene_node_data.shots[N].video_critic_*`\n *\n * Cleared by `clearVideoCriticMetadata` (see pipeline-defaults.ts) in the\n * retry-video-generation recovery route + the frontend Regenerate handler.\n */\nexport interface VideoCriticShotFields {\n video_critic_findings?: VideoCriticVerdict[\"issues\"]\n video_critic_score?: number\n video_critic_continuity_score?: number | null\n video_critic_identified_action?: string\n video_critic_retry_count?: number\n video_critic_last_attempted_url?: string\n video_critic_failed?: boolean\n video_critic_verdict?: \"pass\" | \"fail\"\n}\n\n// ─── Entity metadata (DB pipeline_entities.metadata) ──────────────────────────\n\nexport const CharacterMetadataSchema = z.object({\n entity_type: z.literal(\"character\"),\n name: z.string(),\n visual_description: z.string(),\n role: z.enum([\"protagonist\", \"antagonist\", \"supporting\", \"cameo\"]),\n estimated_screen_time_shots: z.number(),\n has_dialogue: z.boolean(),\n voice_profile: z.string().optional(),\n angle_count: z.number().int().min(1).max(8),\n})\n\nexport const ObjectMetadataSchema = z.object({\n entity_type: z.literal(\"object\"),\n name: z.string(),\n visual_description: z.string(),\n narrative_significance: z.string(),\n scenes_present: z.array(z.string()),\n})\n\nexport const LocationMetadataSchema = z.object({\n entity_type: z.literal(\"location\"),\n name: z.string(),\n visual_description: z.string(),\n variants_needed: z.array(z.string()),\n})\n\nexport const EntityMetadataSchema = z.discriminatedUnion(\"entity_type\", [\n CharacterMetadataSchema,\n ObjectMetadataSchema,\n LocationMetadataSchema,\n SceneMetadataSchema, // new in Phase 1B.2\n])\nexport type EntityMetadata = z.infer<typeof EntityMetadataSchema>\n","import { z } from \"zod\"\nimport type { Operation } from \"fast-json-patch\"\nimport type { PipelineStageName } from \"./pipeline-events.js\"\nimport { ShowrunnerPlanSchema } from \"./pipeline-types.js\"\n\n/** RFC 6902 JSON Patch operations. */\nexport type JsonPatch = Operation[]\n\n/**\n * Response from the chat-refine-showrunner LLM specialist. Either includes a\n * concrete proposed change the user can apply, or none (chat-only reply).\n *\n * Two variants:\n * - 'edit_artifact': JSON Patch operations to apply to the current stage\n * artifact (Script stage = ShowrunnerPlan).\n * - 'suggest_branch': the LLM thinks a deeper change is needed — recommend\n * the user use the Branch flow (1D.3) from this stage instead of trying\n * to patch inline.\n */\nexport const ChatTurnResponseSchema = z.object({\n reply: z.string().min(1).max(4000),\n proposed_change: z\n .discriminatedUnion(\"change_type\", [\n z.object({\n change_type: z.literal(\"edit_artifact\"),\n json_patch: z\n .array(\n z.object({\n op: z.enum([\"add\", \"remove\", \"replace\"]),\n path: z.string().min(1),\n value: z.unknown().optional(),\n }),\n )\n .min(1)\n .max(50),\n summary: z.string().min(1).max(200),\n }),\n z.object({\n change_type: z.literal(\"suggest_branch\"),\n from_stage: z.enum([\n \"script\",\n \"characters\",\n \"objects\",\n \"locations\",\n \"shot_list\",\n \"scene_images\",\n \"animate_audio_edit\",\n ]),\n reason: z.string().min(1).max(300),\n }),\n ])\n .nullable(),\n})\nexport type ChatTurnResponse = z.infer<typeof ChatTurnResponseSchema>\nexport type ProposedChange = NonNullable<ChatTurnResponse[\"proposed_change\"]>\n\n/**\n * Per-stage patch validation schema for `applyStageEdit`. Stages other than\n * `script` don't have chat enabled in 1D.2b (per LLM spec v4.0 narrowing) —\n * their entries are explicitly `null` to keep the type-check exhaustive when\n * future stages are added.\n */\nexport const STAGE_PATCH_SCHEMA: Record<PipelineStageName, z.ZodTypeAny | null> = {\n script: ShowrunnerPlanSchema,\n characters: null,\n objects: null,\n locations: null,\n shot_list: null,\n scene_images: null,\n animate_audio_edit: null,\n post_merge: null,\n}\n","import { z } from \"zod\"\nimport type { EntityStatus, EntityType } from \"./entity-approval-types.js\"\nimport type {\n EntityStateChangeEvent,\n EntityStaleEvent,\n PipelineForkedEvent,\n PipelineDriftSummary,\n PipelineCompletedEvent,\n StageAwaitingSubGateEvent,\n PipelineMusicReadyEvent,\n PipelineEditorDecisionsReadyEvent,\n} from \"./pipeline-state-types.js\"\n// Phase 1D.2b — Guided-mode chat. Type-only import to keep this file at the\n// root of the import graph (pipeline-chat.ts imports PipelineStageName from\n// here, so a value import would be circular).\nimport type { ProposedChange } from \"./pipeline-chat.js\"\n\n/**\n * Canonical pipeline stage order — Phase 1A→1C topology. The engine's\n * `runPipeline` walks this list in sequence; tests, the SSE event router,\n * and the admin-side stage timeline all consume this same tuple as the\n * source of truth for \"which stages exist + in what order\".\n */\nexport const PIPELINE_STAGE_NAMES = [\n \"script\",\n \"characters\",\n \"objects\",\n \"locations\",\n \"shot_list\",\n \"scene_images\",\n \"animate_audio_edit\",\n \"post_merge\",\n] as const\nexport const PipelineStageNameSchema = z.enum(PIPELINE_STAGE_NAMES)\nexport type PipelineStageName = (typeof PIPELINE_STAGE_NAMES)[number]\n\nexport const PipelineStatusSchema = z.enum([\n \"queued\",\n \"running\",\n \"awaiting_approval\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n \"forked\",\n])\nexport type PipelineStatus = z.infer<typeof PipelineStatusSchema>\n\nexport const PipelineStageStatusSchema = z.enum([\n \"pending\",\n \"running\",\n \"awaiting_approval\",\n \"approved\",\n \"rejected\",\n \"failed\",\n \"cancelled\",\n])\nexport type PipelineStageStatus = z.infer<typeof PipelineStageStatusSchema>\n\nexport type PipelineEvent =\n | { type: \"pipeline:status\"; pipelineId: string; status: PipelineStatus }\n | {\n type: \"stage:status\"\n pipelineId: string\n stageName: PipelineStageName\n status: PipelineStageStatus\n output?: unknown\n criticFeedback?: unknown\n }\n | {\n type: \"pipeline:warning\"\n pipelineId: string\n code: string\n message: string\n }\n | { type: \"pipeline:done\"; pipelineId: string }\n | {\n type: \"entity:status\"\n pipelineId: string\n entityId: string\n entityType: EntityType\n entityKey: string\n status: EntityStatus\n mainAssetUrl?: string\n }\n | {\n type: \"entity:variant:added\"\n pipelineId: string\n entityId: string\n variantKey: string\n assetUrl: string\n }\n | {\n type: \"scene:status\"\n pipelineId: string\n sceneEntityId: string\n sceneIndex: number\n status: EntityStatus\n shotCount?: number\n }\n // Phase 1B.4 lifecycle events — see pipeline-state-types.ts for full JSDoc\n // on when each fires. SSE forwarders in routes/pipelines.ts are\n // event-type-agnostic and pass all of these through unchanged.\n | EntityStateChangeEvent\n | EntityStaleEvent\n | PipelineForkedEvent\n | PipelineDriftSummary\n // Phase 1C.1 — final-MP4 ready event carries the merged asset id + URL.\n | PipelineCompletedEvent\n // Phase 1C.2 — Stage 7 sub-gate pause, music ready, editor decisions ready.\n | StageAwaitingSubGateEvent\n | PipelineMusicReadyEvent\n | PipelineEditorDecisionsReadyEvent\n // Phase 1D.2b — Guided-mode chat. `chat:turn` fires after each LLM round-\n // trip (user prompt → assistant reply with optional proposed_change). The\n // event carries the full turn record so the frontend chat history can\n // render it without an extra GET /chat roundtrip. `chat:proposal_applied`\n // fires when the user accepts a proposed_change — the turnId + attemptId\n // let the UI mark the source turn as applied and link to the resulting\n // stage attempt (re-run output) it produced.\n | {\n type: \"chat:turn\"\n pipelineId: string\n stageName: PipelineStageName\n turn: {\n id: string\n turn_n: number\n role: \"user\" | \"assistant\"\n content: string\n proposed_change: ProposedChange | null\n }\n }\n | {\n type: \"chat:proposal_applied\"\n pipelineId: string\n stageName: PipelineStageName\n turnId: string\n attemptId: string\n }\n // Phase 1D.2c-b-ii — per-shot status emitted by the Stage 7 Video Critic\n // retry loop. Fires once per shot after the critic finalises (pass or\n // cap-exhausted fail). The frontend per-shot UI subscribes to update each\n // shot's badge/banner without re-reading the scene entity.\n | {\n type: \"shot:status\"\n pipelineId: string\n sceneId: string\n shotId: string\n status: \"approved\" | \"failed\"\n }\n // LLM-stream narrative progress, emitted by callLLM when a caller passes\n // an `onProgress` callback. Currently used by the Stage 1 Showrunner so the\n // pipeline panel can show a live \"Drafting plan…\" banner instead of a 2-\n // minute spinner. The `message` is human-readable; `bytesSoFar` is a coarse\n // proxy for stream progress (cumulative tool-use JSON delta bytes) that the\n // frontend may format into a percent or just ignore.\n | {\n type: \"stage:progress\"\n pipelineId: string\n stageName: PipelineStageName\n message: string\n bytesSoFar?: number\n }\n","import { z } from \"zod\"\n\n/**\n * Phase 1B.4 — pipeline_state lifecycle + drift event types.\n *\n * `pipeline_state` lives on `pipeline_entity_nodes.pipeline_state` (migration\n * 131). Mirrors the four-value CHECK constraint there.\n *\n * `pipeline_owned_running` — node belongs to the pipeline, work in flight\n * `pipeline_owned_awaiting_approval` — node belongs to the pipeline, user is the gate\n * `pipeline_owned_approved` — node belongs to the pipeline, work locked in\n * `pipeline_orphaned` — pipeline released ownership (cancel / fork / fail);\n * node survives so the user keeps the work\n */\nexport const PipelineStateSchema = z.enum([\n \"pipeline_owned_running\",\n \"pipeline_owned_awaiting_approval\",\n \"pipeline_owned_approved\",\n \"pipeline_orphaned\",\n])\nexport type PipelineState = z.infer<typeof PipelineStateSchema>\n\n/**\n * Emitted when a pipeline_entity_nodes row transitions to a new\n * `pipeline_state`. Fires on:\n * - stage transitioning to 'awaiting_approval' (per-entity batch)\n * - approveEntity success\n * - rejectEntity regenerate path\n * - force-stop / fork orphaning (every entity at once)\n *\n * Frontend swaps node visuals (running glow → awaiting frame → approved chip)\n * based on the new state.\n */\nexport const EntityStateChangeEventSchema = z.object({\n type: z.literal(\"entity:state_change\"),\n pipelineId: z.string(),\n pipelineEntityId: z.string(),\n newState: PipelineStateSchema,\n})\nexport type EntityStateChangeEvent = z.infer<typeof EntityStateChangeEventSchema>\n\n/**\n * Emitted when a `pipeline_entities.is_stale` flag flips to true via the\n * cascade staleness trigger (migration 131). Triggered after a `main_asset_id`\n * update on an upstream entity; the trigger marks every transitive dependent\n * stale, and the engine emits one event per dependent.\n *\n * Frontend overlays a \"Stale — needs regenerate\" warning on the affected\n * canvas nodes.\n */\nexport const EntityStaleEventSchema = z.object({\n type: z.literal(\"entity:stale\"),\n pipelineId: z.string(),\n pipelineEntityId: z.string(),\n reason: z.enum([\"upstream_changed\", \"user_edit\", \"manual\"]).optional(),\n})\nexport type EntityStaleEvent = z.infer<typeof EntityStaleEventSchema>\n\n/**\n * Emitted when a pipeline is force-stopped / forked. Carries the prior status\n * (`forked_status`) so the UI can render \"Forked from approval\" vs \"Forked\n * mid-Stage-5\" copy. The companion `entity:state_change` flurry that orphans\n * every node lands in the same SSE batch.\n */\nexport const PipelineForkedEventSchema = z.object({\n type: z.literal(\"pipeline:forked\"),\n pipelineId: z.string(),\n forkedAt: z.string(), // ISO timestamp\n forkedStatus: z.string(),\n forkReason: z.string().optional(),\n})\nexport type PipelineForkedEvent = z.infer<typeof PipelineForkedEventSchema>\n\n/**\n * Section H drift summary — when the engine pauses a stage at\n * 'awaiting_approval' because user edits on the canvas diverged from the\n * pipeline's recorded state, this payload is attached to the\n * `pipeline_stages.awaiting_reason='canvas_drift'` row so the UI can render\n * the DriftBanner with actionable diffs.\n *\n * Carried inside a `stage:status` event (or a future dedicated event); kept\n * as a standalone schema so callers can validate the drift payload\n * independently.\n */\nexport const PipelineDriftSummarySchema = z.object({\n type: z.literal(\"pipeline:drift\"),\n pipelineId: z.string(),\n stageName: z.string(),\n driftedEntityIds: z.array(z.string()),\n summary: z.string().optional(),\n})\nexport type PipelineDriftSummary = z.infer<typeof PipelineDriftSummarySchema>\n\n/**\n * Phase 1C.1 — emitted by Stage 8 (post_merge) when the pipeline reaches the\n * `completed` terminal state. Carries the final merged-MP4 asset id + URL so\n * the SSE consumer can render the player without an extra round-trip.\n *\n * Distinct from the legacy `pipeline:done` lifecycle event (which carries no\n * payload). SSE forwarders close on either type.\n */\nexport const PipelineCompletedEventSchema = z.object({\n type: z.literal(\"pipeline:completed\"),\n pipelineId: z.string(),\n finalOutputAssetId: z.string().uuid().nullable(),\n finalOutputUrl: z.string(),\n})\nexport type PipelineCompletedEvent = z.infer<typeof PipelineCompletedEventSchema>\n\n/**\n * Phase 1C.2 — Sub-gate names. Stage 7 (animate_audio_edit) and Stage 6\n * (scene_images) can pause at one of these mid-stage gates before resuming\n * the rest of the stage; the gate name is persisted on\n * `pipeline_stages.output.current_sub_gate` (JSONB) so a resumed orchestrator\n * picks up at the right step.\n *\n * `silent_cut_preview` — Stage 7: Editor LLM has emitted cut_decisions;\n * user reviews the preview reel before the\n * per-shot trims commit.\n * `dialogue_recheck` — Stage 7: A re-recorded dialogue line shifted\n * the dialogue_no_cut_zone; user confirms the\n * new cuts still respect the zone.\n * `match_cut_break_pending` — Stage 6: MatchCutCritic found one or more\n * match-cut shot pairs with `match_strength =\n * \"break\"`. User must accept each break (sets\n * `accepted_match_cut_break=true` on the shot)\n * before Stage 7 can animate those pairs.\n */\nexport const SubGateNameSchema = z.enum([\n \"silent_cut_preview\",\n \"dialogue_recheck\",\n \"match_cut_break_pending\",\n])\nexport type SubGateName = z.infer<typeof SubGateNameSchema>\n\n/**\n * Phase 1C.2 — emitted when Stage 6 (scene_images) or Stage 7\n * (animate_audio_edit) pauses at a sub-gate. Carries an optional `payload`\n * (JSONB-shaped) for whatever the gate needs to render — e.g. the preview\n * reel URL, the affected shot ids, or the pending-break list.\n *\n * Distinct from `stage:status awaiting_approval` (which is the top-level\n * stage gate). Sub-gates stash `current_sub_gate` on the stage output AND\n * flip `status = \"awaiting_approval\"` so the pipeline engine waits.\n */\nexport const StageAwaitingSubGateEventSchema = z.object({\n type: z.literal(\"stage:awaiting_sub_gate\"),\n pipelineId: z.string().uuid(),\n stageName: z.enum([\"animate_audio_edit\", \"scene_images\"]),\n subGate: SubGateNameSchema,\n payload: z.record(z.unknown()).optional(),\n})\nexport type StageAwaitingSubGateEvent = z.infer<typeof StageAwaitingSubGateEventSchema>\n\n/**\n * Phase 1C.2 — emitted when the music_timeline build step (Stage 7 sibling)\n * has produced the merged music track + beat grid. The SSE consumer can\n * render the music waveform + beat markers without an extra round-trip.\n */\nexport const PipelineMusicReadyEventSchema = z.object({\n type: z.literal(\"pipeline:music_ready\"),\n pipelineId: z.string().uuid(),\n musicAssetUrl: z.string().url(),\n beatGridLength: z.number(),\n})\nexport type PipelineMusicReadyEvent = z.infer<typeof PipelineMusicReadyEventSchema>\n\n/**\n * Phase 1C.2 — emitted when the Editor LLM has produced cut_decisions for\n * every shot in the pipeline. Frontend can render the silent-cut-preview UI\n * (timeline + accept/reject) once this fires. Payload is intentionally\n * minimal — the decisions are persisted on the shots' `cut_decision` field\n * and the `editor_decisions` audit table.\n */\nexport const PipelineEditorDecisionsReadyEventSchema = z.object({\n type: z.literal(\"pipeline:editor_decisions_ready\"),\n pipelineId: z.string().uuid(),\n})\nexport type PipelineEditorDecisionsReadyEvent = z.infer<\n typeof PipelineEditorDecisionsReadyEventSchema\n>\n\n/**\n * Union of the Phase 1B.4 + 1C.1 + 1C.2 lifecycle event payloads. The broader\n * `PipelineEvent` union in `pipeline-events.ts` extends this so SSE\n * forwarders accept all of them transparently.\n */\nexport type PipelineLifecycleEvent =\n | EntityStateChangeEvent\n | EntityStaleEvent\n | PipelineForkedEvent\n | PipelineDriftSummary\n | PipelineCompletedEvent\n | StageAwaitingSubGateEvent\n | PipelineMusicReadyEvent\n | PipelineEditorDecisionsReadyEvent\n","import type { ShowrunnerPlan } from \"./pipeline-types\"\n\nexport interface ObjectsValidationIssue {\n severity: \"blocking\" | \"warning\"\n type:\n | \"duplicate_key\"\n | \"empty_significance\"\n | \"orphan_object\"\n | \"unresolved_scene_object_ref\"\n object_key?: string\n scene_index?: number\n message: string\n}\n\nexport interface ObjectsValidationResult {\n ok: boolean\n verdict: \"pass\" | \"fail\"\n issues: ObjectsValidationIssue[]\n}\n\nexport function validateObjects(\n objects: ShowrunnerPlan[\"objects\"],\n plan: ShowrunnerPlan,\n): ObjectsValidationResult {\n const issues: ObjectsValidationIssue[] = []\n\n // 1. Duplicate keys\n const seenKeys = new Map<string, number>()\n for (const obj of objects) {\n seenKeys.set(obj.key, (seenKeys.get(obj.key) ?? 0) + 1)\n }\n for (const [key, count] of seenKeys) {\n if (count > 1) {\n issues.push({\n severity: \"blocking\",\n type: \"duplicate_key\",\n object_key: key,\n message: `Object key \"${key}\" appears ${count} times — keys must be unique`,\n })\n }\n }\n\n // 2. Empty narrative_significance\n for (const obj of objects) {\n if (!obj.narrative_significance || obj.narrative_significance.trim() === \"\") {\n issues.push({\n severity: \"blocking\",\n type: \"empty_significance\",\n object_key: obj.key,\n message: `Object \"${obj.key}\" has empty narrative_significance`,\n })\n }\n }\n\n // 3. Unresolved scene → object refs\n const objectKeySet = new Set(objects.map((o) => o.key))\n const referencedKeys = new Set<string>()\n for (const sc of plan.scenes) {\n for (const k of sc.object_keys) {\n referencedKeys.add(k)\n if (!objectKeySet.has(k)) {\n issues.push({\n severity: \"blocking\",\n type: \"unresolved_scene_object_ref\",\n object_key: k,\n scene_index: sc.scene_index,\n message: `Scene ${sc.scene_index} references unknown object_key \"${k}\"`,\n })\n }\n }\n }\n\n // 4. Orphan objects (listed but never referenced) — warning only\n for (const obj of objects) {\n if (!referencedKeys.has(obj.key)) {\n issues.push({\n severity: \"warning\",\n type: \"orphan_object\",\n object_key: obj.key,\n message: `Object \"${obj.key}\" listed but no scene references it`,\n })\n }\n }\n\n const ok = !issues.some((i) => i.severity === \"blocking\")\n return { ok, verdict: ok ? \"pass\" : \"fail\", issues }\n}\n","import { z } from \"zod\"\n\n/**\n * Voice Matcher (LLM spec §7.1) picks an ElevenLabs voice per dialogue-bearing\n * cast member. Two variants discriminated by `voice_source`:\n * - 'premade' → uses a catalog voice_id\n * - 'custom' → emits a prompt for ElevenLabs voice_design (used when no\n * premade fits)\n *\n * **Schema shape note:** this was originally `z.discriminatedUnion(...)` but\n * Anthropic's tool input_schema validator rejects union-at-root JSON Schemas —\n * it requires `\"type\": \"object\"` at the top level (`tools.0.custom.input_schema.type:\n * Field required`). Flattening to a single object with both optional fields +\n * a `.refine()` produces a valid schema (root is an object) while still\n * enforcing the per-variant required-field rule at parse time. `callLLM`'s\n * schema.safeParse triggers a retry-with-feedback if the LLM emits an invalid\n * combination (e.g., 'premade' without voice_id), so the LLM converges on\n * correct output.\n */\nexport const VoiceMatchSchema = z\n .object({\n voice_source: z.enum([\"premade\", \"custom\"]),\n voice_id: z.string().min(1).optional(),\n voice_design_prompt: z.string().max(500).optional(),\n reasoning: z.string().max(500),\n })\n .refine(\n (v) =>\n v.voice_source === \"premade\"\n ? typeof v.voice_id === \"string\" && v.voice_id.length > 0\n : typeof v.voice_design_prompt === \"string\" && v.voice_design_prompt.length > 0,\n {\n message:\n \"voice_id is required when voice_source='premade'; voice_design_prompt is required when voice_source='custom'\",\n },\n )\nexport type VoiceMatch = z.infer<typeof VoiceMatchSchema>\n","import type { TtsProvider } from \"./model-constants.js\"\n\n/**\n * How the TTS layer resolves a voice id. Mirrors `CharacterVoice.voiceType` on\n * the frontend character node: `premade` voices resolve by NAME, `library` /\n * `custom` voices resolve by ID. Carry it alongside the id or premade-vs-library\n * resolution misroutes (see backend `direct-tts.ts`).\n */\nexport type VoiceType = \"premade\" | \"library\" | \"custom\"\n\n/**\n * A character's saved voice as supplied to the voiced-video orchestration on\n * `POST /v1/generate-video`. A deliberate subset of the frontend `CharacterVoice`:\n * only the fields the server needs to synthesise speech (no `voiceName` /\n * `traits` / `previewUrl`, which are display-only and never read server-side).\n *\n * `speaker` is the join key: it matches a {@link DialogueLine}.speaker so a\n * multi-speaker prompt routes each line to its own voice. Omit it for a\n * single-voice clip (one spec, no dialogue attribution needed).\n */\nexport interface CharacterVoiceSpec {\n /** ElevenLabs voice id, or the premade voice NAME when `voiceType === \"premade\"`. */\n readonly voiceId: string\n /** How the TTS layer resolves {@link voiceId}. Defaults to `\"premade\"` downstream. */\n readonly voiceType?: VoiceType\n /** Recommended TTS provider for this voice; forwarded as `provider` to TTS. */\n readonly ttsProvider?: TtsProvider\n /**\n * Speaker label this voice belongs to (e.g. \"Anna\"). Joined to\n * {@link DialogueLine}.speaker case-insensitively (trimmed). Omit for a\n * single-voice clip.\n */\n readonly speaker?: string\n}\n\n/** One attributed line of dialogue: who speaks (`speaker`) and what they say (`line`). */\nexport interface DialogueLine {\n readonly speaker: string\n readonly line: string\n}\n\n/**\n * A dialogue line resolved to a concrete voice, in the exact shape the\n * ElevenLabs Dialogue v3 primitive (`POST /v1/text-to-dialogue`) consumes:\n * `{ text, voice }` per line, in order. `voiceType` rides along so the TTS layer\n * resolves premade-by-name vs library/custom-by-id correctly.\n */\nexport interface ResolvedDialogueVoiceLine {\n readonly text: string\n readonly voice: string\n readonly voiceType?: VoiceType\n}\n\n// Quote characters built from code points so this file stays pure ASCII. The\n// published @nodaro/shared package must survive a re-save in any locale, and a\n// literal curly quote or em-dash here is exactly the CP1255 mojibake hazard that\n// has reached main before. RDQUO/LDQUO = curly double quotes, RAQUO/LAQUO =\n// guillemets, RSQUO = right single quote (apostrophe inside a name like O'Brien).\nconst RDQUO = String.fromCharCode(0x201d)\nconst LDQUO = String.fromCharCode(0x201c)\nconst RAQUO = String.fromCharCode(0x00bb)\nconst LAQUO = String.fromCharCode(0x00ab)\nconst RSQUO = String.fromCharCode(0x2019)\n\n/**\n * Matches one attributed, QUOTED line of dialogue. Built with `new RegExp` +\n * `String.raw` so the regex backslashes stay literal while the non-ASCII quote\n * characters are injected from the code-point consts above.\n *\n * - A leading boundary lookbehind (`^`, newline, sentence punctuation, or a\n * CLOSING quote) keeps the speaker capture from bridging a sentence: e.g.\n * \"...kitchen. Anna: \"hi\"\" yields speaker \"Anna\", not \"kitchen. Anna\", and the\n * speaker after a closing quote (\"hi\" Gordon: \"yo\") is still found.\n * - Speaker = 1 to 4 short words (names are short; no \".\" inside a token).\n * - Body = the first quoted run in straight, curly, or guillemet quotes.\n *\n * Requiring quotes is what stops cinematic direction (\"Setting: a forest\",\n * \"Camera: dolly in\") from being read as dialogue.\n */\nconst ATTRIBUTED_DIALOGUE_RE = new RegExp(\n String.raw`(?<=^|[\\n\\r.!?;,\"${RDQUO}${RAQUO}])\\s*([\\p{L}][\\p{L}\\p{N}'${RSQUO}-]*(?:\\s+[\\p{L}][\\p{L}\\p{N}'${RSQUO}-]*){0,3})\\s*:\\s*(?:\"([^\"]+)\"|${LDQUO}([^${RDQUO}]+)${RDQUO}|${LAQUO}([^${RAQUO}]+)${RAQUO})`,\n \"gu\",\n)\n\n/**\n * Extract attributed dialogue (`Speaker: \"line\"`) from a free-text prompt.\n *\n * Deterministic and intentionally conservative (see {@link ATTRIBUTED_DIALOGUE_RE}):\n * only QUOTED lines attributed to a short speaker label are matched. Callers that\n * already have structured dialogue (studio prompt chips) should pass it directly\n * and skip this parser. Order is preserved (it drives the stitched dialogue\n * track). Returns `[]` when no attributed quoted dialogue is found.\n */\nexport function parseAttributedDialogue(prompt: string): DialogueLine[] {\n if (!prompt) return []\n const out: DialogueLine[] = []\n for (const m of prompt.matchAll(ATTRIBUTED_DIALOGUE_RE)) {\n const speaker = m[1]?.trim() ?? \"\"\n const line = (m[2] ?? m[3] ?? m[4] ?? \"\").trim()\n if (speaker && line) out.push({ speaker, line })\n }\n return out\n}\n\n/**\n * Resolve each dialogue line to a concrete voice by joining `line.speaker` to\n * `voices[].speaker` (case-insensitive, trimmed) - the \"Speaker mapping\" model.\n *\n * Fallback order for an unmatched / unattributed line: the matched speaker's\n * voice -> `defaultVoiceId` -> the sole voice (when exactly one spec is given) ->\n * the first voice. A line resolves to nothing only when there are no voices and\n * no default, in which case it is dropped (the caller decides whether an empty\n * result means \"no dialogue to synthesise\"). This mirrors the pipeline's\n * non-fatal missing-voice behaviour (`allowDefaultVoiceFallback`).\n */\nexport function resolveDialogueVoices(\n dialogue: readonly DialogueLine[],\n voices: readonly CharacterVoiceSpec[],\n defaultVoiceId?: string,\n): ResolvedDialogueVoiceLine[] {\n const bySpeaker = new Map<string, CharacterVoiceSpec>()\n for (const v of voices) {\n const key = v.speaker?.trim().toLowerCase()\n if (key) bySpeaker.set(key, v)\n }\n const soleVoice = voices.length === 1 ? voices[0] : undefined\n const firstVoice = voices[0]\n\n const lineFor = (text: string, spec: CharacterVoiceSpec): ResolvedDialogueVoiceLine => ({\n text,\n voice: spec.voiceId,\n ...(spec.voiceType ? { voiceType: spec.voiceType } : {}),\n })\n\n const out: ResolvedDialogueVoiceLine[] = []\n for (const { speaker, line } of dialogue) {\n const text = line.trim()\n if (!text) continue\n const matched = bySpeaker.get(speaker.trim().toLowerCase())\n if (matched) {\n out.push(lineFor(text, matched))\n } else if (defaultVoiceId) {\n out.push({ text, voice: defaultVoiceId })\n } else if (soleVoice) {\n out.push(lineFor(text, soleVoice))\n } else if (firstVoice) {\n out.push(lineFor(text, firstVoice))\n }\n }\n return out\n}\n","import { z } from \"zod\"\n\n/**\n * Body for POST /v1/pipelines/:id/entities/:entity_id/reject.\n * Approve takes no body (optional `edits` future-deferred).\n */\nexport const EntityRejectInputSchema = z.object({\n feedback: z.string().min(1).max(2000),\n})\nexport type EntityRejectInput = z.infer<typeof EntityRejectInputSchema>\n\nexport const ENTITY_STATUSES = [\n \"pending\",\n \"generating\",\n \"awaiting_approval\",\n \"approved\",\n \"rejected\",\n \"failed\",\n // Phase 3 (granular-pipeline-control) — Stage 2 Character Wizard.\n // `pending_description` is the initial state for character entities in\n // manual/guided mode pipelines; the engine waits for the user's Step A\n // approval before generating the portrait. `skipped` is a terminal state\n // for entities the user explicitly opts out of (no generation, excluded\n // from stage-advance gating). Migration: 154_phase_1d3_character_wizard.sql.\n \"pending_description\",\n \"skipped\",\n] as const\nexport type EntityStatus = (typeof ENTITY_STATUSES)[number]\n\nexport const ENTITY_TYPES = [\"character\", \"object\", \"location\", \"scene\"] as const\nexport type EntityType = (typeof ENTITY_TYPES)[number]\n","import { z } from \"zod\"\n\n/**\n * Image Critic types — shared between backend (Sonnet vision call) and\n * frontend (helper result modal renderers). The schema lives in\n * `@nodaro/shared` so the helper-result schemas in `scene-helper-types.ts`\n * can compose it, and the frontend modal can render a typed\n * {@link ImageCriticVerdict} without a backend round-trip-only type.\n *\n * The runtime + persistence implementation lives in\n * `backend/src/ee/pipelines/llms/image-critic.ts` which re-exports these\n * schemas for callers that import from one place.\n */\n\n/**\n * Issue types the Image Critic can flag. `continuity_break` is the\n * Phase 1C.1 newcomer — fires when a prior-shot last_frame is supplied\n * and the new keyframe doesn't plausibly continue from it.\n */\nexport const ImageCriticIssueSchema = z.object({\n type: z.enum([\n \"continuity_break\",\n \"identity_mismatch\",\n \"composition_break\",\n \"wardrobe_inconsistency\",\n \"style_drift\",\n \"prompt_mismatch\",\n ]),\n severity: z.enum([\"blocking\", \"warning\", \"info\"]),\n message: z.string(),\n suggested_fix: z.string().optional(),\n})\nexport type ImageCriticIssue = z.infer<typeof ImageCriticIssueSchema>\n\nexport const ImageCriticVerdictSchema = z.object({\n ok: z.boolean(),\n issues: z.array(ImageCriticIssueSchema),\n notes: z.string().max(500),\n})\nexport type ImageCriticVerdict = z.infer<typeof ImageCriticVerdictSchema>\n","import { z } from \"zod\"\n\nexport const IMAGE_CRITIC_LEAF_MODES = [\n \"character-consistency\",\n \"realism\",\n \"prompt-adherence\",\n \"anatomy\",\n \"aesthetic\",\n \"style-match\",\n] as const\n\nexport const IMAGE_CRITIC_MODES = [\n ...IMAGE_CRITIC_LEAF_MODES,\n \"all\",\n] as const\n\nexport type ImageCriticLeafMode = (typeof IMAGE_CRITIC_LEAF_MODES)[number]\nexport type ImageCriticMode = (typeof IMAGE_CRITIC_MODES)[number]\n\nconst modeResult = z.object({\n score: z.number().min(0).max(1),\n feedback: z.string().min(1).max(300),\n})\n\nconst issue = z.object({\n category: z.string(),\n severity: z.enum([\"blocking\", \"warning\", \"info\"]),\n description: z.string().max(400),\n})\n\n// The critic LLM frequently emits `issues` as a bare string array even when the\n// prompt asks for objects. Coerce strings into the issue shape so an otherwise\n// well-formed critique isn't rejected as invalid_llm_output (which surfaced as\n// a 502 from the /v1/image-critic route). Objects pass through unchanged.\nconst issueLenient = z.preprocess(\n (v) =>\n typeof v === \"string\"\n ? { category: \"general\", severity: \"warning\", description: v.slice(0, 400) }\n : v,\n issue,\n)\n\nexport const ImageCriticResultSchema = z.object({\n score: z.number().min(0).max(1),\n feedback: z.string().min(1).max(600),\n issues: z.array(issueLenient).optional(),\n perMode: z\n .object({\n \"character-consistency\": modeResult.optional(),\n \"realism\": modeResult.optional(),\n \"prompt-adherence\": modeResult.optional(),\n \"anatomy\": modeResult.optional(),\n \"aesthetic\": modeResult.optional(),\n \"style-match\": modeResult.optional(),\n })\n .strict()\n .optional(),\n})\n\nexport type ImageCriticResult = z.infer<typeof ImageCriticResultSchema>\nexport type ImageCriticNodeIssue = z.infer<typeof issue>\n","import { z } from \"zod\"\nimport { ImageCriticVerdictSchema } from \"./image-critic-types.js\"\nimport { ShotSpecSchema } from \"./scene-node-types.js\"\n\n/**\n * All 10 helpers — 7 text/planning helpers shipped in Phase 1B.3 +\n * 3 vision-keyframe helpers activated in Phase 1C.1.\n * Names match the §6.11 spec sub-section labels (URL-safe form).\n */\nexport const SCENE_HELPER_NAMES = [\n // Text/planning-only — shipped in 1B.3\n \"audit_prompt\",\n \"improve_prompt\",\n \"generate_motion\",\n \"optimize_for_model\",\n \"add_broll\",\n \"bridge_to_next_scene\",\n \"anchor_scene_style\",\n // Vision-keyframe — activated in Phase 1C.1\n \"audit_images\",\n \"fix_continuity\",\n \"validate_match_cut\",\n] as const\n\nexport const SceneHelperNameSchema = z.enum(SCENE_HELPER_NAMES)\nexport type SceneHelperName = z.infer<typeof SceneHelperNameSchema>\n\n/**\n * UI-gating set used by `scene-helper-buttons.tsx` to render active vs disabled\n * buttons. Phase 1C.1 promoted the 3 vision-keyframe helpers from disabled →\n * active; the constant name is preserved for compat (it remains \"the set of\n * helpers currently shipped\"), and {@link ACTIVE_SCENE_HELPERS} is a clearer\n * alias for new code.\n */\nexport const HELPERS_SHIPPED_IN_1B3: ReadonlySet<SceneHelperName> = new Set([\n \"audit_prompt\",\n \"improve_prompt\",\n \"generate_motion\",\n \"optimize_for_model\",\n \"add_broll\",\n \"bridge_to_next_scene\",\n \"anchor_scene_style\",\n // Phase 1C.1 — activated\n \"audit_images\",\n \"fix_continuity\",\n \"validate_match_cut\",\n])\n\n/** Cleaner-named alias for {@link HELPERS_SHIPPED_IN_1B3}. */\nexport const ACTIVE_SCENE_HELPERS = HELPERS_SHIPPED_IN_1B3\n\n// ─── 6.11.2 Audit Prompt — Haiku, text-only ────────────────────────────────────\n\nexport const AuditPromptIssueSchema = z.object({\n shot_id: z.string(),\n severity: z.enum([\"blocking\", \"warning\", \"info\"]),\n issue_type: z.enum([\n \"contradiction\",\n \"missing_beat\",\n \"off_format\",\n \"camera_motion_mismatch\",\n ]),\n message: z.string(),\n suggested_fix: z.string(),\n})\n\nexport const AuditPromptResultSchema = z.object({\n scene_id: z.string(),\n ok: z.boolean(),\n issues_per_shot: z.array(AuditPromptIssueSchema),\n scene_level_notes: z.string().max(400),\n})\nexport type AuditPromptResult = z.infer<typeof AuditPromptResultSchema>\n\n// ─── 6.11.3 Improve Prompt — Sonnet, target enum ────────────────────────────────\n\nexport const ImprovePromptInputSchema = z.object({\n shot_ids: z.array(z.string()).min(1),\n field_targets: z.array(z.enum([\"action\", \"motion_prompt\", \"dialogue\"])).min(1),\n})\nexport type ImprovePromptInput = z.infer<typeof ImprovePromptInputSchema>\n\nexport const ImprovePromptResultSchema = z.object({\n scene_id: z.string(),\n shots: z.array(\n z.object({\n shot_id: z.string(),\n action: z.string().max(300).optional(),\n motion_prompt: z.string().max(200).optional(),\n dialogue_line: z.string().max(200).optional(),\n reasoning: z.string().max(300),\n }),\n ),\n})\nexport type ImprovePromptResult = z.infer<typeof ImprovePromptResultSchema>\n\n// ─── 6.11.5 Generate Motion — Haiku, fills motion_prompt ───────────────────────\n\nexport const GenerateMotionInputSchema = z.object({\n shot_ids: z.array(z.string()).min(1),\n})\n\nexport const GenerateMotionResultSchema = z.object({\n scene_id: z.string(),\n shots: z.array(\n z.object({\n shot_id: z.string(),\n motion_prompt: z.string().max(200),\n }),\n ),\n})\nexport type GenerateMotionResult = z.infer<typeof GenerateMotionResultSchema>\n\n// ─── 6.11.6 Optimize for Model — Sonnet, rewrites for new prompting_style ─────\n\nexport const OptimizeForModelInputSchema = z.object({\n target_model: z.string(),\n})\n\nexport const OptimizeForModelResultSchema = z.object({\n scene_id: z.string(),\n target_model: z.string(),\n shots: z.array(\n z.object({\n shot_id: z.string(),\n action: z.string().max(300),\n motion_prompt: z.string().max(200),\n }),\n ),\n rationale: z.string().max(300),\n})\nexport type OptimizeForModelResult = z.infer<typeof OptimizeForModelResultSchema>\n\n// ─── 6.11.7 Add B-Roll — Sonnet, proposes new shots ────────────────────────────\n\nexport const AddBRollResultSchema = z.object({\n scene_id: z.string(),\n candidates: z\n .array(\n z.object({\n proposed_insert_after_shot_id: z.string(),\n insert_kind: z.enum([\"reaction_shot\", \"cutaway\", \"establishing\", \"transition\"]),\n shot: ShotSpecSchema,\n rationale: z.string().max(200),\n }),\n )\n .min(1)\n .max(4),\n scene_duration_delta: z.number(),\n})\nexport type AddBRollResult = z.infer<typeof AddBRollResultSchema>\n\n// ─── 6.11.10 Bridge to Next Scene — Sonnet, generates bridge_image_prompt ──────\n\nexport const BridgeToNextSceneInputSchema = z.object({\n target_shot_id: z.string(),\n})\n\nexport const BridgeToNextSceneResultSchema = z.object({\n scene_id: z.string(),\n target_shot_id: z.string(),\n bridge_image_prompt: z.string().max(500),\n reasoning: z.string().max(300),\n})\nexport type BridgeToNextSceneResult = z.infer<typeof BridgeToNextSceneResultSchema>\n\n// ─── 6.11.11 Anchor Scene Style — Sonnet plans + image_model generates ─────────\n\nexport const AnchorSceneStyleResultSchema = z.object({\n scene_id: z.string(),\n anchor_prompt: z.string().max(800),\n asset_id: z.string().uuid(),\n asset_url: z.string().url(),\n credits_spent: z.number(),\n})\nexport type AnchorSceneStyleResult = z.infer<typeof AnchorSceneStyleResultSchema>\n\n// ─── 6.11.12 Audit Images — Sonnet vision, per-shot keyframe critic loop ──────\n//\n// Runs `runImageCritic` over every shot's keyframe_url in the scene (no body\n// inputs). Aggregates verdicts into a per-shot issue list. `ok` rolls up to\n// scene-level: false when any shot has a blocking issue.\n\nexport const AuditImagesShotEntrySchema = z.object({\n shot_id: z.string(),\n ok: z.boolean(),\n /** Verdict body — empty when the shot has no `keyframe_url` yet (skipped). */\n verdict: ImageCriticVerdictSchema.nullable(),\n /** True when the shot had no keyframe to audit. */\n skipped: z.boolean(),\n})\nexport type AuditImagesShotEntry = z.infer<typeof AuditImagesShotEntrySchema>\n\nexport const AuditImagesResultSchema = z.object({\n scene_id: z.string(),\n ok: z.boolean(),\n shot_issues: z.array(AuditImagesShotEntrySchema),\n /** Roll-up summary suitable for in-app display (\"3 of 5 shots have issues\"). */\n summary: z.string().max(400),\n})\nexport type AuditImagesResult = z.infer<typeof AuditImagesResultSchema>\n\n// ─── 6.11.13 Fix Continuity — Sonnet vision + i2i regen ──────────────────────\n//\n// Body: { target_shot_id }. Runs Image Critic against the target shot's\n// keyframe with its PRIOR shot's `last_frame_url`. If a `continuity_break`\n// blocking issue is found, regenerates the keyframe via\n// `pipelineGenerateImage` using the prior last_frame as a strong reference,\n// and persists the new keyframe_url back to the scene's shots[target].\n\nexport const FixContinuityInputSchema = z.object({\n target_shot_id: z.string(),\n})\nexport type FixContinuityInput = z.infer<typeof FixContinuityInputSchema>\n\nexport const FixContinuityResultSchema = z.object({\n scene_id: z.string(),\n target_shot_id: z.string(),\n action: z.enum([\"regenerated\", \"no_action_needed\"]),\n critic_verdict: ImageCriticVerdictSchema,\n /** Populated only when `action === \"regenerated\"`. */\n new_keyframe_url: z.string().url().optional(),\n new_keyframe_asset_id: z.string().uuid().optional(),\n})\nexport type FixContinuityResult = z.infer<typeof FixContinuityResultSchema>\n\n// ─── 6.11.14 Validate Match Cut — Sonnet vision ──────────────────────────────\n//\n// Body: { target_shot_id }. Loads the target shot's keyframe + the NEXT shot's\n// keyframe and asks the Image Critic to evaluate the match-cut quality.\n// Returns a `match_strength` summary + the critic's full verdict. Returns 400\n// `not_a_match_cut` from the route layer when `shot_intent.is_match_cut`\n// is false on the target shot (pre-flight check before credit reservation).\n\nexport const ValidateMatchCutInputSchema = z.object({\n target_shot_id: z.string(),\n})\nexport type ValidateMatchCutInput = z.infer<typeof ValidateMatchCutInputSchema>\n\nexport const ValidateMatchCutResultSchema = z.object({\n scene_id: z.string(),\n /** Tuple [shot_id_a, shot_id_b] — the target shot + the next shot. */\n shot_pair: z.tuple([z.string(), z.string()]),\n match_strength: z.enum([\"strong\", \"moderate\", \"weak\", \"break\"]),\n critic_verdict: ImageCriticVerdictSchema,\n /** Optional follow-up actions the user could take (free-form, ≤300 chars). */\n suggested_adjustments: z.string().max(300),\n})\nexport type ValidateMatchCutResult = z.infer<typeof ValidateMatchCutResultSchema>\n","import type { ShotSpec } from \"./scene-node-types.js\"\n\n/**\n * Provider-specific directive defaults. Architecture spec §5.14.\n *\n * Each video model can have side-effects the user usually wants (Seedance baking in\n * ambient music, VEO supporting loop seeds, etc.). The engine applies these defaults\n * at provider-call time, allowing them to be overridden by the Scene Director's\n * `shot_intent` field (provider-neutral) which we map below.\n *\n * Keys are canonical provider identifiers (matching VIDEO_MODEL_CAPS in\n * model-constants.ts). Non-canonical keys would silently break downstream\n * route validation + payload building.\n */\nexport const PROVIDER_DIRECTIVE_DEFAULTS = {\n seedance: { multishot: true, disable_internal_music: true, allow_sfx: true },\n \"seedance-2\": { multishot: true, disable_internal_music: true, allow_sfx: true },\n veo3: { reference_count: \"auto\" as const },\n \"veo3.1\": { reference_count: \"auto\" as const },\n kling: { reference_count: \"auto\" as const },\n \"kling-3-omni\": { reference_count: \"auto\" as const },\n \"kling-turbo\": { reference_count: \"auto\" as const },\n hailuo: {} as Record<string, never>,\n \"hailuo-2.3-pro\": {} as Record<string, never>,\n \"hailuo-standard\": {} as Record<string, never>,\n minimax: {} as Record<string, never>,\n \"bytedance-lite\": {} as Record<string, never>,\n} as const\n\n/**\n * Maps a Scene Director's provider-neutral shot_intent to provider-specific directives.\n * Architecture spec §5.14 mapping table.\n *\n * Unknown providers fall through to an empty object — the directive degrades to a text\n * hint in the motion_prompt (Scene Director includes it there as a fallback when\n * `needs_music_suppression: true`).\n */\nexport function mapShotIntentToProviderDirectives(\n provider: string,\n shotIntent: ShotSpec[\"shot_intent\"],\n): Record<string, unknown> {\n const directives: Record<string, unknown> = {\n ...(PROVIDER_DIRECTIVE_DEFAULTS[provider as keyof typeof PROVIDER_DIRECTIVE_DEFAULTS] ?? {}),\n }\n\n if (shotIntent.needs_multishot_reference) {\n if (provider.startsWith(\"seedance\")) {\n directives.multishot = true\n }\n // VEO + Kling: accepts reference_images array — engine attaches the refs separately.\n // Hailuo: only 1 ref — silently ignored at engine layer.\n }\n\n if (shotIntent.is_loopable) {\n if (provider.startsWith(\"veo\")) {\n directives.loop_seed = \"stable\"\n }\n // Other providers: no native loop_seed → degrade to motion_prompt frame-matching hint.\n }\n\n if (shotIntent.needs_music_suppression) {\n if (provider.startsWith(\"seedance\")) {\n directives.disable_internal_music = true\n }\n // VEO / Kling / Hailuo don't bake in music; no directive needed.\n }\n\n return directives\n}\n","/**\n * Character LoRA routing decision + identifier constants.\n *\n * Shared between backend (orchestrator's payload-builder) and frontend\n * (single-node Run's execute-node). MUST agree byte-for-byte — the backend\n * stamps the credit identifier and worker payload off this decision, the\n * frontend stamps the `_internalLora` body hint off it. Mismatches would\n * silently degrade trained-character generations to ref injection.\n */\n\n/**\n * Synthetic Replicate model id selected by the orchestrator (and the\n * single-node Run pre-Zod swap) when a single trained `@character` mention\n * is detected. Routes through `black-forest-labs/flux-dev-lora` with the\n * character's trained version under `extraParams.lora_version`. Never\n * appears in user-facing dropdowns.\n */\nexport const FLUX_LORA_CHARACTER_MODEL_ID = \"flux-lora-character\" as const\n\n/**\n * `jobs.job_type` discriminator + credit identifier for character LoRA\n * training jobs. Used for `STATIC_CREDIT_COSTS`/`model_pricing` lookup,\n * `creditGuard` reservation, refund flow, and webhook job lookup.\n */\nexport const CHARACTER_LORA_TRAINING_JOB_TYPE = \"character-lora-training\" as const\n\n/**\n * The three LoRA fields read off `CharacterNodeData` and stamped onto every\n * `ConnectedReference` produced from a wired character. Shared between the\n * backend's `expandWiredCharacterRefs` and the frontend's\n * `expandCharacterNodeIntoRefs` so both sides emit the same three fields\n * without copy-paste drift.\n */\nexport interface CharacterLoraFields {\n readonly loraReplicateVersion: string | null\n readonly loraTriggerWord: string | null\n readonly loraTrainingStatus: string | null\n}\n\n/**\n * Extract the three LoRA fields from a character node's `data`, normalized\n * to `null` for missing/undefined values so downstream type-checks (e.g.\n * `selectLoraRoutingForMentions`'s `=== \"succeeded\"`) are deterministic.\n */\nexport function extractCharacterLoraFields(charData: {\n loraReplicateVersion?: string | null\n loraTriggerWord?: string | null\n loraTrainingStatus?: string | null\n}): CharacterLoraFields {\n return {\n loraReplicateVersion: charData.loraReplicateVersion ?? null,\n loraTriggerWord: charData.loraTriggerWord ?? null,\n loraTrainingStatus: charData.loraTrainingStatus ?? null,\n }\n}\n\nexport interface LoraRouting {\n readonly characterSlug: string\n readonly triggerWord: string\n readonly loraVersion: string\n}\n\nexport interface LoraEligibleRef {\n readonly characterSlug?: string\n readonly loraReplicateVersion?: string | null\n readonly loraTriggerWord?: string | null\n readonly loraTrainingStatus?: string | null\n}\n\n/**\n * Returns a LoraRouting iff EXACTLY ONE distinct character is mentioned AND\n * that character has a successful LoRA. Returns null otherwise → caller\n * falls back to ref injection. Multi-character LoRA composition is Phase 2.\n */\nexport function selectLoraRoutingForMentions(\n refs: readonly LoraEligibleRef[],\n): LoraRouting | null {\n const distinct = new Set(refs.map((r) => r.characterSlug).filter(Boolean))\n if (distinct.size !== 1) return null\n const slug = [...distinct][0]!\n const match = refs.find((r) => r.characterSlug === slug)\n if (\n !match ||\n !match.loraReplicateVersion ||\n !match.loraTriggerWord ||\n match.loraTrainingStatus !== \"succeeded\"\n ) {\n return null\n }\n return {\n characterSlug: slug,\n triggerWord: match.loraTriggerWord,\n loraVersion: match.loraReplicateVersion,\n }\n}\n","import { z, type ZodType, type ZodTypeDef } from \"zod\"\n// Reuse the canonical `OutputType` from presentation-utils so a single union\n// is the source of truth across the package. Re-exporting it here would\n// collide with the explicit named re-export in `index.ts`.\nimport type { OutputType } from \"./presentation-utils.js\"\n\n// `ZodType<Output, Def, Input>` with `Input = any` lets us accept schemas\n// like `z.object({ x: z.string().default(\"\") })` where the parsed output is\n// `{ x: string }` but the input is `{ x?: string }`. Pinning Input to TConfig\n// would force input === output and reject `.default()` schemas.\nexport type ReduceStrategy<TConfig = unknown> = {\n readonly id: string\n readonly label: string\n readonly description: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly configSchema: ZodType<TConfig, ZodTypeDef, any>\n readonly defaultConfig: TConfig\n readonly outputType: OutputType\n readonly creditCostKey: string\n}\n\nconst PICK_BEST_LLM_STRATEGY = {\n id: \"pick-best-llm\",\n label: \"Pick best (LLM judge)\",\n description: \"Sonnet picks the best item against your criteria.\",\n configSchema: z.object({\n // Default to the sensible \"best quality\" criteria when omitted (matches\n // defaultConfig) so a reduce({strategyId:\"pick-best-llm\"}) call with no\n // criteria degrades gracefully instead of erroring. An explicit \"\" still\n // rejects via min(1).\n criteria: z.string().min(1, \"criteria cannot be empty\").default(\"Pick the highest-quality result.\"),\n inputKind: z.enum([\"text\", \"image-url\"]).default(\"text\"),\n }),\n defaultConfig: { criteria: \"Pick the highest-quality result.\", inputKind: \"text\" as const },\n outputType: \"text\" as OutputType,\n creditCostKey: \"reduce:pick-best-llm\",\n} as const satisfies ReduceStrategy<{ criteria: string; inputKind: \"text\" | \"image-url\" }>\n\nconst CONCAT_STRATEGY = {\n id: \"concat\",\n label: \"Concatenate\",\n description: \"Join all survivors with a separator.\",\n configSchema: z.object({ separator: z.string().default(\"\\n\\n\") }),\n defaultConfig: { separator: \"\\n\\n\" },\n outputType: \"text\" as OutputType,\n creditCostKey: \"reduce:concat\",\n} as const satisfies ReduceStrategy<{ separator: string }>\n\nconst FIRST_NON_EMPTY_STRATEGY = {\n id: \"first-non-empty\",\n label: \"First non-empty\",\n description: \"Return the first survivor (empty strings filtered).\",\n configSchema: z.object({}),\n defaultConfig: {},\n outputType: \"text\" as OutputType,\n creditCostKey: \"reduce:first-non-empty\",\n} as const satisfies ReduceStrategy<Record<string, never>>\n\nconst COUNT_STRATEGY = {\n id: \"count\",\n label: \"Count\",\n description: \"Return how many survivors came through.\",\n configSchema: z.object({}),\n defaultConfig: {},\n outputType: \"data\" as OutputType,\n creditCostKey: \"reduce:count\",\n} as const satisfies ReduceStrategy<Record<string, never>>\n\nconst VOTE_STRATEGY = {\n id: \"vote\",\n label: \"Majority vote\",\n description: \"Return the most common survivor (ties → first).\",\n configSchema: z.object({ caseSensitive: z.boolean().default(false) }),\n defaultConfig: { caseSensitive: false },\n outputType: \"text\" as OutputType,\n creditCostKey: \"reduce:vote\",\n} as const satisfies ReduceStrategy<{ caseSensitive: boolean }>\n\nconst MERGE_JSON_STRATEGY = {\n id: \"merge-json\",\n label: \"Merge JSON\",\n description: \"Parse each survivor as JSON and merge into one object.\",\n configSchema: z.object({ strategy: z.enum([\"deep\", \"shallow\"]).default(\"deep\") }),\n defaultConfig: { strategy: \"deep\" as const },\n outputType: \"data\" as OutputType,\n creditCostKey: \"reduce:merge-json\",\n} as const satisfies ReduceStrategy<{ strategy: \"deep\" | \"shallow\" }>\n\n/**\n * Result-meta shape returned by every reduce strategy. Shared between the\n * backend route, the SDK client, and the frontend node so all three layers\n * agree on field names. `selectedIndex` + `reasoning` are set by the\n * `pick-best-llm` and `vote` strategies (the former also fills `reasoning`);\n * `summary` is always populated.\n */\nexport type ReduceMeta = {\n readonly selectedIndex?: number\n readonly reasoning?: string\n readonly summary: string\n}\n\nexport const REDUCE_STRATEGIES = [\n PICK_BEST_LLM_STRATEGY,\n CONCAT_STRATEGY,\n FIRST_NON_EMPTY_STRATEGY,\n COUNT_STRATEGY,\n VOTE_STRATEGY,\n MERGE_JSON_STRATEGY,\n] as const\n\nexport const REDUCE_STRATEGY_IDS = REDUCE_STRATEGIES.map((s) => s.id) as readonly ReduceStrategyId[]\n\nexport type ReduceStrategyId = typeof REDUCE_STRATEGIES[number][\"id\"]\n\nconst BY_ID = new Map<string, ReduceStrategy>(REDUCE_STRATEGIES.map((s) => [s.id, s]))\n\nexport function getStrategy(id: ReduceStrategyId): ReduceStrategy {\n const s = BY_ID.get(id)\n if (!s) throw new Error(`unknown reduce strategy: ${id}`)\n return s\n}\n","/**\n * Catalog of every transition the combine-videos node supports.\n *\n * `id` is the stable identifier used in workflow JSON, Zod validation, and\n * the preview-CSS class suffix. `xfade` is the FFmpeg `xfade transition=`\n * name (or `null` for `cut`, which goes through the concat demuxer).\n *\n * The 5 original ids (`cut`, `fade`, `dissolve`, `dip-to-black`,\n * `dip-to-white`) are kept for back-compat with workflows saved before the\n * picker shipped.\n */\n\nexport type CombineTransitionGroup =\n | \"fades\"\n | \"wipes\"\n | \"slides\"\n | \"shapes\"\n | \"smooth\"\n | \"slices\"\n | \"reveals\"\n | \"covers\"\n | \"effects\"\n\nexport interface CombineTransition {\n readonly id: string\n readonly label: string\n /** FFmpeg `xfade transition=` name. `null` = special path (concat demuxer for cut). */\n readonly xfade: string | null\n readonly group: CombineTransitionGroup\n readonly common?: boolean\n readonly description: string\n}\n\nexport const COMBINE_TRANSITIONS: readonly CombineTransition[] = [\n // ===== Fades & Dips =====\n {\n id: \"cut\",\n label: \"Cut\",\n xfade: null,\n group: \"fades\",\n common: true,\n description: \"Hard cut — instant switch with no blend. Default, fastest.\",\n },\n {\n id: \"fade\",\n label: \"Fade\",\n xfade: \"fade\",\n group: \"fades\",\n common: true,\n description: \"Smooth alpha cross-fade between two clips. Classic clean blend.\",\n },\n {\n id: \"dissolve\",\n label: \"Dissolve\",\n xfade: \"dissolve\",\n group: \"fades\",\n common: true,\n description: \"Random-pixel dissolve. Grainy, organic feel — good for memory beats.\",\n },\n {\n id: \"dip-to-black\",\n label: \"Dip to Black\",\n xfade: \"fadeblack\",\n group: \"fades\",\n common: true,\n description: \"Fade through black. Use between scenes or time jumps.\",\n },\n {\n id: \"dip-to-white\",\n label: \"Dip to White\",\n xfade: \"fadewhite\",\n group: \"fades\",\n common: true,\n description: \"Fade through white. Bright, ethereal — flashbacks, dream beats.\",\n },\n {\n id: \"fadegrays\",\n label: \"Fade through Greys\",\n xfade: \"fadegrays\",\n group: \"fades\",\n description: \"Desaturates to grey at the midpoint, then re-saturates into B.\",\n },\n\n // ===== Wipes =====\n {\n id: \"wipe-left\",\n label: \"Wipe Left\",\n xfade: \"wipeleft\",\n group: \"wipes\",\n common: true,\n description: \"Hard edge sweeps from right to left, revealing the next clip.\",\n },\n {\n id: \"wipe-right\",\n label: \"Wipe Right\",\n xfade: \"wiperight\",\n group: \"wipes\",\n common: true,\n description: \"Hard edge sweeps from left to right.\",\n },\n {\n id: \"wipe-up\",\n label: \"Wipe Up\",\n xfade: \"wipeup\",\n group: \"wipes\",\n description: \"Edge sweeps from bottom to top.\",\n },\n {\n id: \"wipe-down\",\n label: \"Wipe Down\",\n xfade: \"wipedown\",\n group: \"wipes\",\n description: \"Edge sweeps from top to bottom.\",\n },\n {\n id: \"wipe-tl\",\n label: \"Wipe Top-Left\",\n xfade: \"wipetl\",\n group: \"wipes\",\n description: \"Diagonal wipe from top-left corner.\",\n },\n {\n id: \"wipe-tr\",\n label: \"Wipe Top-Right\",\n xfade: \"wipetr\",\n group: \"wipes\",\n description: \"Diagonal wipe from top-right corner.\",\n },\n {\n id: \"wipe-bl\",\n label: \"Wipe Bottom-Left\",\n xfade: \"wipebl\",\n group: \"wipes\",\n description: \"Diagonal wipe from bottom-left corner.\",\n },\n {\n id: \"wipe-br\",\n label: \"Wipe Bottom-Right\",\n xfade: \"wipebr\",\n group: \"wipes\",\n description: \"Diagonal wipe from bottom-right corner.\",\n },\n\n // ===== Slides =====\n {\n id: \"slide-left\",\n label: \"Slide Left\",\n xfade: \"slideleft\",\n group: \"slides\",\n common: true,\n description: \"Next clip pushes A off-screen, sliding in from the right.\",\n },\n {\n id: \"slide-right\",\n label: \"Slide Right\",\n xfade: \"slideright\",\n group: \"slides\",\n common: true,\n description: \"Next clip pushes A off-screen, sliding in from the left.\",\n },\n {\n id: \"slide-up\",\n label: \"Slide Up\",\n xfade: \"slideup\",\n group: \"slides\",\n description: \"Next clip pushes A upward off-screen.\",\n },\n {\n id: \"slide-down\",\n label: \"Slide Down\",\n xfade: \"slidedown\",\n group: \"slides\",\n description: \"Next clip pushes A downward off-screen.\",\n },\n\n // ===== Smooth (gradient-edge wipes) =====\n {\n id: \"smooth-left\",\n label: \"Smooth Left\",\n xfade: \"smoothleft\",\n group: \"smooth\",\n description: \"Soft-edged wipe sweeping leftward — gentler than a hard wipe.\",\n },\n {\n id: \"smooth-right\",\n label: \"Smooth Right\",\n xfade: \"smoothright\",\n group: \"smooth\",\n description: \"Soft-edged wipe sweeping rightward.\",\n },\n {\n id: \"smooth-up\",\n label: \"Smooth Up\",\n xfade: \"smoothup\",\n group: \"smooth\",\n description: \"Soft-edged wipe sweeping upward.\",\n },\n {\n id: \"smooth-down\",\n label: \"Smooth Down\",\n xfade: \"smoothdown\",\n group: \"smooth\",\n description: \"Soft-edged wipe sweeping downward.\",\n },\n\n // ===== Shapes (circles, rectangles, openings) =====\n {\n id: \"circle-open\",\n label: \"Circle Open\",\n xfade: \"circleopen\",\n group: \"shapes\",\n common: true,\n description: \"Circular iris opens to reveal next clip from the center.\",\n },\n {\n id: \"circle-close\",\n label: \"Circle Close\",\n xfade: \"circleclose\",\n group: \"shapes\",\n description: \"Circular iris closes inward over the current clip.\",\n },\n {\n id: \"circle-crop\",\n label: \"Circle Crop\",\n xfade: \"circlecrop\",\n group: \"shapes\",\n description: \"Circular mask crops A then expands as B.\",\n },\n {\n id: \"rect-crop\",\n label: \"Rectangle Crop\",\n xfade: \"rectcrop\",\n group: \"shapes\",\n description: \"Rectangular mask crops A then expands as B.\",\n },\n {\n id: \"horz-open\",\n label: \"Horizontal Open\",\n xfade: \"horzopen\",\n group: \"shapes\",\n description: \"Two horizontal bars split apart from the center to reveal B.\",\n },\n {\n id: \"horz-close\",\n label: \"Horizontal Close\",\n xfade: \"horzclose\",\n group: \"shapes\",\n description: \"Top and bottom bars meet at the center.\",\n },\n {\n id: \"vert-open\",\n label: \"Vertical Open\",\n xfade: \"vertopen\",\n group: \"shapes\",\n description: \"Two vertical bars split apart from the center to reveal B.\",\n },\n {\n id: \"vert-close\",\n label: \"Vertical Close\",\n xfade: \"vertclose\",\n group: \"shapes\",\n description: \"Left and right bars meet at the center.\",\n },\n {\n id: \"diag-tl\",\n label: \"Diagonal Top-Left\",\n xfade: \"diagtl\",\n group: \"shapes\",\n description: \"Diagonal slash sweep originating top-left.\",\n },\n {\n id: \"diag-tr\",\n label: \"Diagonal Top-Right\",\n xfade: \"diagtr\",\n group: \"shapes\",\n description: \"Diagonal slash sweep originating top-right.\",\n },\n {\n id: \"diag-bl\",\n label: \"Diagonal Bottom-Left\",\n xfade: \"diagbl\",\n group: \"shapes\",\n description: \"Diagonal slash sweep originating bottom-left.\",\n },\n {\n id: \"diag-br\",\n label: \"Diagonal Bottom-Right\",\n xfade: \"diagbr\",\n group: \"shapes\",\n description: \"Diagonal slash sweep originating bottom-right.\",\n },\n\n // ===== Slices =====\n {\n id: \"hl-slice\",\n label: \"Horizontal Left Slice\",\n xfade: \"hlslice\",\n group: \"slices\",\n description: \"Horizontal strips slice in from the left.\",\n },\n {\n id: \"hr-slice\",\n label: \"Horizontal Right Slice\",\n xfade: \"hrslice\",\n group: \"slices\",\n description: \"Horizontal strips slice in from the right.\",\n },\n {\n id: \"vu-slice\",\n label: \"Vertical Up Slice\",\n xfade: \"vuslice\",\n group: \"slices\",\n description: \"Vertical strips slice in from the bottom.\",\n },\n {\n id: \"vd-slice\",\n label: \"Vertical Down Slice\",\n xfade: \"vdslice\",\n group: \"slices\",\n description: \"Vertical strips slice in from the top.\",\n },\n\n // ===== Reveals =====\n {\n id: \"reveal-left\",\n label: \"Reveal Left\",\n xfade: \"revealleft\",\n group: \"reveals\",\n description: \"A slides leftward off-screen, revealing the static B underneath.\",\n },\n {\n id: \"reveal-right\",\n label: \"Reveal Right\",\n xfade: \"revealright\",\n group: \"reveals\",\n description: \"A slides rightward off-screen, revealing B.\",\n },\n {\n id: \"reveal-up\",\n label: \"Reveal Up\",\n xfade: \"revealup\",\n group: \"reveals\",\n description: \"A slides upward, revealing B.\",\n },\n {\n id: \"reveal-down\",\n label: \"Reveal Down\",\n xfade: \"revealdown\",\n group: \"reveals\",\n description: \"A slides downward, revealing B.\",\n },\n\n // ===== Covers =====\n {\n id: \"cover-left\",\n label: \"Cover Left\",\n xfade: \"coverleft\",\n group: \"covers\",\n description: \"B slides in from the right and covers A in place.\",\n },\n {\n id: \"cover-right\",\n label: \"Cover Right\",\n xfade: \"coverright\",\n group: \"covers\",\n description: \"B slides in from the left and covers A.\",\n },\n {\n id: \"cover-up\",\n label: \"Cover Up\",\n xfade: \"coverup\",\n group: \"covers\",\n description: \"B slides up from below and covers A.\",\n },\n {\n id: \"cover-down\",\n label: \"Cover Down\",\n xfade: \"coverdown\",\n group: \"covers\",\n description: \"B slides down from above and covers A.\",\n },\n\n // ===== Effects =====\n {\n id: \"pixelize\",\n label: \"Pixelize\",\n xfade: \"pixelize\",\n group: \"effects\",\n description: \"Both clips pixelate to chunky blocks at the midpoint, then sharpen into B.\",\n },\n {\n id: \"radial\",\n label: \"Radial Wipe\",\n xfade: \"radial\",\n group: \"effects\",\n description: \"Clock-hand sweep around the center.\",\n },\n {\n id: \"hblur\",\n label: \"Blur\",\n xfade: \"hblur\",\n group: \"effects\",\n description: \"Heavy horizontal blur at midpoint — dreamy speed-blur look.\",\n },\n {\n id: \"distance\",\n label: \"Distance\",\n xfade: \"distance\",\n group: \"effects\",\n description: \"Distance-field morph between A and B. Subtle dimensional warp.\",\n },\n {\n id: \"zoom-in\",\n label: \"Zoom In\",\n xfade: \"zoomin\",\n group: \"effects\",\n description: \"B zooms outward from a point in A.\",\n },\n {\n id: \"squeeze-h\",\n label: \"Squeeze Horizontal\",\n xfade: \"squeezeh\",\n group: \"effects\",\n description: \"A squeezes horizontally to a line, then B expands.\",\n },\n {\n id: \"squeeze-v\",\n label: \"Squeeze Vertical\",\n xfade: \"squeezev\",\n group: \"effects\",\n description: \"A squeezes vertically to a line, then B expands.\",\n },\n]\n\n/** All valid transition ids, sorted in catalog order. Use this for Zod enums. */\nexport const COMBINE_TRANSITION_IDS: readonly string[] = COMBINE_TRANSITIONS.map((t) => t.id)\n\n/** Ordered list of group tab keys. `common` is a virtual tab, prepended in UI. */\nexport const COMBINE_TRANSITION_GROUP_ORDER: readonly CombineTransitionGroup[] = [\n \"fades\",\n \"wipes\",\n \"slides\",\n \"smooth\",\n \"shapes\",\n \"slices\",\n \"reveals\",\n \"covers\",\n \"effects\",\n]\n\nexport const COMBINE_TRANSITION_GROUP_LABELS: Record<CombineTransitionGroup, string> = {\n fades: \"Fades & Dips\",\n wipes: \"Wipes\",\n slides: \"Slides\",\n smooth: \"Smooth\",\n shapes: \"Shapes\",\n slices: \"Slices\",\n reveals: \"Reveals\",\n covers: \"Covers\",\n effects: \"Effects\",\n}\n\nconst TRANSITIONS_BY_ID: ReadonlyMap<string, CombineTransition> = new Map(\n COMBINE_TRANSITIONS.map((t) => [t.id, t]),\n)\n\nexport function getCombineTransition(id: string): CombineTransition | undefined {\n return TRANSITIONS_BY_ID.get(id)\n}\n\n/**\n * Resolve the FFmpeg `xfade transition=` name for a given transition id.\n * Returns `null` for `cut` (handled via the concat demuxer instead of xfade).\n * Throws for unknown ids — callers validate input via Zod first.\n */\nexport function resolveXfadeName(id: string): string | null {\n const entry = TRANSITIONS_BY_ID.get(id)\n if (!entry) {\n throw new Error(`Unknown combine-videos transition: ${id}`)\n }\n return entry.xfade\n}\n","/**\n * Curated subset of FFmpeg `acrossfade=curve=...` options for combine-videos\n * audio crossfades. We expose 5 well-understood presets out of the ~21 raw\n * curves FFmpeg supports; the rest are either visually indistinguishable to\n * non-audio-engineers or rarely useful in this context.\n *\n * Default `linear` matches today's behavior — adding this catalog is a pure\n * additive change for existing workflows.\n */\n\nexport interface AudioCrossfadeCurve {\n readonly id: string\n /** FFmpeg `acrossfade=curve=...` name. */\n readonly ffmpeg: string\n readonly label: string\n readonly description: string\n}\n\nexport const AUDIO_CROSSFADE_CURVES: readonly AudioCrossfadeCurve[] = [\n {\n id: \"linear\",\n ffmpeg: \"tri\",\n label: \"Linear\",\n description: \"Straight-line fade. Default; predictable but can dip in the middle for music.\",\n },\n {\n id: \"equal-power\",\n ffmpeg: \"qsin\",\n label: \"Equal Power\",\n description: \"Quarter-sine. Keeps perceived loudness roughly constant across the crossfade — best for music.\",\n },\n {\n id: \"smooth\",\n ffmpeg: \"hsin\",\n label: \"Smooth (Sine)\",\n description: \"Half-sine. Gentler than equal-power; good for dialogue and ambient.\",\n },\n {\n id: \"logarithmic\",\n ffmpeg: \"log\",\n label: \"Logarithmic\",\n description: \"Compensates for the ear's logarithmic loudness response. Long, slow tails.\",\n },\n {\n id: \"exponential\",\n ffmpeg: \"exp\",\n label: \"Exponential\",\n description: \"Sharp out / slow in (or vice versa). Punchy — good for impact moments.\",\n },\n]\n\nexport const AUDIO_CROSSFADE_CURVE_IDS: readonly string[] =\n AUDIO_CROSSFADE_CURVES.map((c) => c.id)\n\nexport const DEFAULT_AUDIO_CROSSFADE_CURVE_ID = \"linear\"\n\nconst CURVES_BY_ID: ReadonlyMap<string, AudioCrossfadeCurve> = new Map(\n AUDIO_CROSSFADE_CURVES.map((c) => [c.id, c]),\n)\n\nexport function getAudioCrossfadeCurve(id: string): AudioCrossfadeCurve | undefined {\n return CURVES_BY_ID.get(id)\n}\n\n/**\n * Resolve a curve id to its FFmpeg `acrossfade=curve=` name. Unknown ids fall\n * back to `tri` (linear) — this matches the route's Zod default so callers\n * downstream of validation never see undefined.\n */\nexport function resolveAudioCrossfadeCurve(id: string | undefined): string {\n if (!id) return \"tri\"\n return CURVES_BY_ID.get(id)?.ffmpeg ?? \"tri\"\n}\n","/**\n * Producer-type sets — single source of truth for the node types whose\n * primary output is a video URL, audio URL, etc.\n *\n * Consumed by:\n * - backend/src/services/workflow-engine/execution-graph.ts (orchestrator\n * dispatch + asset-type tagging in payload-builder, output-extractor,\n * inline-executor — re-exported there as VIDEO_SOURCE_TYPES /\n * AUDIO_SOURCE_TYPES for backwards compatibility).\n * - frontend/src/lib/generate-video-handles.ts (handle connection\n * validation on the Generate Video node).\n *\n * Lifting these here ensures the frontend handle validator can never reject\n * a connection from a node type that the backend would happily route at\n * execution time (the prior drift bug, see issue 1 of the Task 4.1 review).\n */\n\n/**\n * Source node types whose primary output is a video URL.\n * Mirrors the backend execution-graph VIDEO_SOURCE_TYPES verbatim.\n */\nexport const VIDEO_PRODUCER_TYPES: ReadonlySet<string> = new Set([\n \"image-to-video\",\n \"video-to-video\",\n \"switchx\", // Beeble SwitchX relight/composite\n \"text-to-video\",\n // Unified video node — emits videoUrl identically to i2v/t2v (its payload-builder\n // case dispatches dynamically to \"image-to-video\" or \"text-to-video\" jobName based\n // on whether a start frame is wired). Without this, getPrimaryOutput would fall\n // through to the imageUrl/videoUrl/audioUrl/text default and downstream consumers\n // could silently misroute the output.\n \"generate-video\",\n \"upload-video\",\n \"youtube-video\",\n \"combine-videos\",\n \"lip-sync\",\n \"speech-to-video\",\n \"motion-transfer\",\n \"video-upscale\",\n \"extend-video\",\n // face-swap output is video (writes generatedVideoUrl, per-result `url`).\n // Frontend execution-graph already includes it in VIDEO_SOURCE_TYPES; this\n // entry brings the shared set in line so canvas typed-handle validation\n // doesn't reject face-swap → video-consumer edges that the orchestrator\n // would happily route at runtime.\n \"face-swap\",\n \"video-retake\",\n // video-sfx: adds an SFX track to a video → emits a video URL. Belongs here so\n // canvas handle validation accepts video-sfx → video-consumer edges and the\n // backend routes its output as video (it was previously relying on a fallback).\n \"video-sfx\",\n \"suno-music-video\",\n \"merge-video-audio\",\n \"add-captions\",\n \"resize-video\",\n \"social-media-format\",\n \"trim-video\",\n \"render-video\",\n \"speed-ramp\",\n \"loop-video\",\n \"fade-video\",\n \"transcode-video\",\n \"manual-edit\",\n // Remove Audio: strips the audio track, emits a silent video.\n \"remove-audio\",\n // AI Avatar (HeyGen): avatar + voice/audio → video.\n \"ai-avatar\",\n // Cinematic Avatar (HeyGen cinematic_avatar): prompt + 1–3 avatar looks → video.\n \"cinematic-avatar\",\n // Assemble Narrated Video: fits N (clip, voice) blocks into one MP4 → video.\n \"assemble-narrated-video\",\n])\n\n/**\n * Source node types whose output media-type cannot be classified\n * statically — iterators, dynamic dispatchers, sub-workflow wrappers.\n * The orchestrator decides their actual output type at execution time\n * based on what's wired upstream (loop iterates upstream column type;\n * sub-workflow emits its leaf node's type; adjust-volume passes through\n * video or audio based on its `lastInputType` runtime field;\n * voice-changer emits audio in audio mode, video+audio in video mode).\n *\n * Typed-handle validators (frontend/src/lib/{generate-image,generate-\n * video,ffmpeg}-handles.ts) must include these as acceptors on EVERY\n * media-typed input handle — otherwise the canvas validator hard-\n * rejects edges that the orchestrator would happily route at runtime.\n *\n * Lifted here from `frontend/src/lib/ffmpeg-handles.ts` (where the\n * escape hatch was first added) so the same set drives ALL handle\n * validators uniformly. Adding a new dynamic-output node type means\n * one edit here instead of N across sibling validator files.\n *\n * Intentionally OMITTED:\n * - `webhook-trigger` / `schedule-trigger` — their outputs are\n * user-defined JSON shapes, not media URLs. Accepting them as\n * media producers creates false-positive drops at the canvas\n * that fail at execution. Users wanting trigger → media flows\n * should wire through an upload node.\n */\nexport const DYNAMIC_PRODUCER_TYPES: ReadonlySet<string> = new Set([\n \"list\",\n \"sub-workflow\",\n \"adjust-volume\",\n // Dual-mode: audio in → audio out; video in → video out (+ revoiced audio).\n // Listed here so canvas validators accept its output on BOTH audio and video\n // input handles (it also stays in AUDIO_PRODUCER_TYPES as its default).\n \"voice-changer\",\n // voice-changer-pro (renamed from voice-recast in #3581) is a behavioral\n // twin of voice-changer — identical dual-mode output. Must mirror it in\n // EVERY producer set or its outputs can't connect (was the \"cannot connect\n // the outputs of voice-changer-pro\" bug). Guarded by producer-types.test.ts.\n \"voice-changer-pro\",\n \"reduce\",\n // Dual-output time chunker (UI label \"Split into Chunks\"; type id stays\n // \"split-media\"): video in → video chunks, audio in → audio chunks — two\n // independent lanes on two output handles. Like voice-changer, the canvas\n // validator only sees the source NODE type, not which handle a wire leaves,\n // so it lives here to be accepted on BOTH audio and video input handles. The\n // backend routes the correct lane by sourceHandle in getPrimaryOutput\n // (output-extractor.ts); the frontend does so in extractNodeOutput.\n \"split-media\",\n])\n\n/**\n * Source node types whose primary output is an audio URL.\n * Mirrors the backend execution-graph AUDIO_SOURCE_TYPES verbatim.\n */\nexport const AUDIO_PRODUCER_TYPES: ReadonlySet<string> = new Set([\n \"text-to-speech\",\n \"text-to-audio\",\n \"generate-music\",\n \"upload-audio\",\n \"suno-generate\",\n \"suno-cover\",\n \"suno-extend\",\n \"suno-separate\",\n \"audio-separation\",\n \"suno-mashup\",\n \"suno-replace-section\",\n \"suno-add-instrumental\",\n \"suno-add-vocals\",\n \"suno-convert-wav\",\n \"suno-upload-extend\",\n \"trim-audio\",\n \"mix-audio\",\n \"combine-audio\",\n \"adjust-volume\",\n \"audio-fx\",\n \"reference-audio\",\n \"audio-isolation\",\n \"text-to-dialogue\",\n \"voice-changer\",\n // Twin of voice-changer (see DYNAMIC_PRODUCER_TYPES note). Audio is its\n // default output mode; video mode is handled via DYNAMIC membership.\n \"voice-changer-pro\",\n \"dubbing\",\n \"voice-remix\",\n \"voice-design\",\n // Extract Audio: demuxes a video's audio track to a standalone MP3.\n \"extract-audio\",\n])\n\n/**\n * Source node types whose primary output is a LIST that, by default, fans out\n * one downstream execution per element when an edge leaves them WITHOUT an\n * explicit `outputMode` (all other edges default to \"last\"). `selector` is\n * included because its picked/rest channels are lists too.\n *\n * Single source of truth for the fan-out \"each\" default, consumed by:\n * - backend/src/services/workflow-engine/input-resolver.ts (DEFAULT_EACH_TYPES)\n * - frontend/src/components/editor/workflow-editor/types.ts (FAN_OUT_EACH_TYPES)\n * - frontend/src/components/editor/workflow-editor/node-input-resolver.ts\n *\n * These three previously kept independent copies; the backend copy drifted\n * (missing the four list-transform types), so server-side workflow runs\n * silently dropped all-but-the-first item for filter-list / deduplicate /\n * merge-lists / sort-list sources while the canvas fanned out N ways. Lifting\n * the set here makes that drift impossible.\n */\nexport const FAN_OUT_EACH_TYPES: ReadonlySet<string> = new Set([\n \"list\",\n \"split-text\",\n \"filter-list\",\n \"deduplicate\",\n \"merge-lists\",\n \"sort-list\",\n \"selector\",\n])\n","/**\n * ElevenLabs speech-to-speech (voice changer) models — single source of truth\n * for the Voice Changer node's model picker (frontend config panel) AND the\n * `/v1/voice-changer` route Zod enum (backend). Lifting the list here keeps the\n * dropdown and the validation enum from ever drifting apart.\n *\n * These are the two `model_id` values ElevenLabs' `/v1/speech-to-speech/{voiceId}`\n * endpoint accepts with `can_do_voice_conversion`. ElevenLabs' own docs\n * recommend Multilingual v2 even for English source audio (it often\n * outperforms the English-only model), and it's required for non-English\n * audio (e.g. Hebrew), so it's the default — English v2 stays selectable.\n */\nexport const VOICE_CHANGER_MODELS = [\n {\n value: \"eleven_multilingual_sts_v2\",\n label: \"Multilingual v2\",\n desc: \"29 languages; preserves emotion, cadence & timing. Default — ElevenLabs recommends this even for English audio.\",\n },\n {\n value: \"eleven_english_sts_v2\",\n label: \"English v2\",\n desc: \"English-optimized speech-to-speech.\",\n },\n] as const\n\nexport type VoiceChangerModel = (typeof VOICE_CHANGER_MODELS)[number][\"value\"]\n\n/** Plain id list for the route's `z.enum(...)`. */\nexport const VOICE_CHANGER_MODEL_IDS: VoiceChangerModel[] = VOICE_CHANGER_MODELS.map(\n (m) => m.value,\n)\n\n/** ElevenLabs recommends Multilingual v2 even for English source audio (it\n * often outperforms the English-only model), and it's required for\n * non-English audio — so it's the default. English v2 remains selectable. */\nexport const DEFAULT_VOICE_CHANGER_MODEL: VoiceChangerModel = \"eleven_multilingual_sts_v2\"\n","import { EXECUTION_DATA_KEYS } from \"./node-runtime-keys.js\"\nimport { COMPOSER_PLAN_FIELDS } from \"./model-constants.js\"\n\n/**\n * Generated-plan state on composer nodes that a preset must NEITHER capture NOR\n * carry, and that the dropdown must CLEAR when applying a preset:\n *\n * - every composer node's plan field (`COMPOSER_PLAN_MAP[*].planField` —\n * sceneGraph / effectPlan / overlayPlan / titlePlan / motionPlan /\n * compositePlan): a large LLM-authored plan blob, regenerated per run.\n * - `lottieUrl`: the R2 url of the authored Lottie JSON (motion-graphics'\n * `lottie` handle output) — a reapable generated artifact, not config.\n *\n * Derived from the single source of truth (COMPOSER_PLAN_MAP) so a new composer\n * node type is covered by construction — no per-type list to keep in sync.\n *\n * Two distinct hazards this closes (see motion-graphics-presets design §2a/§2b):\n * 1. Apply-time staleness: applying a preset over a node that already generated\n * a plan would leave the OLD animation showing under the NEW prompt (the\n * plan field is named by no patch, so it persists in the preview and on the\n * output handle). The dropdown spreads `{ ...clearPatch, ...preset.data }`\n * where clearPatch maps each key here to `undefined`.\n * 2. Capture pollution: a user-saved preset would otherwise capture the plan\n * blob (~tens of KB) + a stale url, re-injecting them on every apply and\n * bloating the preset row. These keys are in the capture-exclusion set below.\n */\nexport const PRESET_APPLY_CLEAR_KEYS: readonly string[] = [...COMPOSER_PLAN_FIELDS, \"lottieUrl\"]\n\n/**\n * Config fields that are intentionally NOT part of a preset, because they are not portable\n * configuration — they identify the node on the canvas, wire it into one specific graph, or point\n * at specific DB entities. Capturing them would make a preset silently wrong when applied to a\n * different node or workflow. This is the single place that defines that contract, so the system\n * stays correct-by-construction as new node types are added.\n *\n * Identity:\n * - `label`: the node's canvas identity. Presets carry their own name and must not rename the node.\n *\n * Graph wiring (reference specific upstream node / handle / tile ids — meaningless elsewhere):\n * - `fieldMappings`: field -> upstream node id.\n * - `referenceImageOrder` / `referenceOrder` / `connectedMediaOrder` / `connectedRefImageOrder`:\n * orderings keyed by the ids of wired upstream references.\n *\n * Structural identifiers (handle / port / route / channel ids that must stay unique per node and\n * that downstream edges target — copying them across nodes orphans edges or duplicates a channel):\n * - `routes` / `routeId` / `routeIds`: router routes + sub-workflow/condition route pairing ids.\n * - `ports` / `inputPorts` / `outputPorts`: sub-workflow port arrays (each port has a handle id).\n * - `channel` / `channelColor`: teleport send/receive pairing channel (auto-assigned per node).\n *\n * DB entity references / per-wiring identity state (tied to specific characters/locations):\n * - `characterDefinitionIds`, `suppressedCanonicalCharacterIds`, `suppressedCanonicalLocationIds`.\n * - `identityMeta`: per-identity overrides keyed by the wired identity's index/label.\n * - `extraRefs`: extra references carrying `characterSlug` + workflow-specific asset urls.\n *\n * Preset meta:\n * - `__activePresetId`: which preset is currently loaded onto the node (for the dropdown's\n * active-name + dirty `*`). Node-local UI state, never part of a preset's own config.\n * - `__promptFinalView`: field keys currently showing the final-prompt view (Edit ⇄ Final\n * per-field toggle). Node-local UI state, never part of a preset's own config.\n *\n * NOTE: manual reference image urls (`referenceImageUrl` / `referenceImageUrls`) are deliberately\n * KEPT — they are self-contained R2 urls a user set as input, and portable across nodes.\n *\n * Generated composer-plan state (`PRESET_APPLY_CLEAR_KEYS` — every COMPOSER_PLAN_MAP plan field +\n * `lottieUrl`): NOT portable config — a per-run LLM-authored plan blob / reapable artifact url.\n * Excluded here (preset-scoped, zero blast radius) rather than via EXECUTION_DATA_KEYS, whose\n * non-preset consumers (undo-skip in use-workflow-store, auto-execute IGNORE_KEYS) would then\n * treat a legitimately-persisted plan as transient runtime state.\n */\nexport const PRESET_EXCLUDED_KEYS: ReadonlySet<string> = new Set([\n \"label\",\n \"fieldMappings\",\n \"__activePresetId\",\n \"__promptFinalView\",\n \"referenceImageOrder\",\n \"referenceOrder\",\n \"connectedMediaOrder\",\n \"connectedRefImageOrder\",\n \"characterDefinitionIds\",\n \"suppressedCanonicalCharacterIds\",\n \"suppressedCanonicalLocationIds\",\n \"identityMeta\",\n \"extraRefs\",\n // structural identifiers\n \"routes\",\n \"routeId\",\n \"routeIds\",\n \"ports\",\n \"inputPorts\",\n \"outputPorts\",\n \"channel\",\n \"channelColor\",\n // generated composer-plan state (derived from COMPOSER_PLAN_MAP + lottieUrl)\n ...PRESET_APPLY_CLEAR_KEYS,\n])\n\n/**\n * Capture a node's reusable configuration from its `data`: a shallow copy minus runtime/result\n * state (EXECUTION_DATA_KEYS) and graph/identity fields (PRESET_EXCLUDED_KEYS). Pure; never mutates\n * the input. Node-type-agnostic — the node type is stored alongside the result by the caller.\n */\nexport function extractPresetData(\n data: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(data)) {\n if (EXECUTION_DATA_KEYS.has(key)) continue\n if (PRESET_EXCLUDED_KEYS.has(key)) continue\n out[key] = data[key]\n }\n return out\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (typeof a !== typeof b) return false\n if (a === null || b === null) return a === b\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false\n return a.every((v, i) => deepEqual(v, b[i]))\n }\n if (typeof a === \"object\" && typeof b === \"object\") {\n const ka = Object.keys(a as object)\n const kb = Object.keys(b as object)\n if (ka.length !== kb.length) return false\n return ka.every((k) =>\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n )\n }\n return false\n}\n\n/**\n * True iff the node's `data` still matches the preset — i.e. every key the preset defines\n * deep-equals the node's current value. Compares only preset-defined keys (the node may carry\n * extra keys the preset doesn't set, e.g. seed, which must NOT count as a mismatch). Used to drive\n * the dropdown's dirty `*` indicator.\n */\nexport function presetDataMatches(\n nodeData: Readonly<Record<string, unknown>>,\n presetData: Readonly<Record<string, unknown>>,\n): boolean {\n for (const key of Object.keys(presetData)) {\n if (!deepEqual(nodeData[key], presetData[key])) return false\n }\n return true\n}\n","import { z } from \"zod\"\nimport { extractPresetData } from \"./node-preset-extract.js\"\n\nexport const NODE_PRESET_EXPORT_KIND = \"nodaro.node-presets\" as const\n\nexport interface ExportedPreset {\n nodeType: string\n name: string\n description?: string\n data: Record<string, unknown>\n}\n\nexport interface NodePresetExport {\n kind: typeof NODE_PRESET_EXPORT_KIND\n version: 1\n exportedAt: string\n presets: ExportedPreset[]\n}\n\nconst exportedPresetSchema = z.object({\n nodeType: z.string().min(1).max(120),\n name: z.string().min(1).max(120),\n description: z.string().max(500).optional(),\n data: z.record(z.string(), z.unknown()),\n})\n\nconst envelopeSchema = z.object({\n kind: z.literal(NODE_PRESET_EXPORT_KIND),\n version: z.literal(1),\n exportedAt: z.string().optional().default(\"\"),\n presets: z.array(exportedPresetSchema).max(500),\n})\n\nexport function buildNodePresetExport(\n presets: ExportedPreset[],\n exportedAtIso: string,\n): NodePresetExport {\n return {\n kind: NODE_PRESET_EXPORT_KIND,\n version: 1,\n exportedAt: exportedAtIso,\n presets: presets.map((p) => ({ ...p, data: extractPresetData(p.data) })),\n }\n}\n\n/**\n * Validate an unknown parsed-JSON value as a preset export; throws on invalid. Defensively\n * re-strips runtime keys from each preset's data.\n */\nexport function parseNodePresetExport(input: unknown): NodePresetExport {\n const parsed = envelopeSchema.parse(input)\n return {\n ...parsed,\n presets: parsed.presets.map((p) => ({ ...p, data: extractPresetData(p.data) })),\n }\n}\n","export type EntityKind = \"character\" | \"object\" | \"location\"\n\nexport const SHEET_TYPES = [\"turnaround\", \"variation-board\", \"detail\", \"full-reference\"] as const\nexport type SheetType = (typeof SHEET_TYPES)[number]\n\nexport const SHEET_SKINS = [\"studio\", \"cinematic\", \"blueprint\", \"illustrated\"] as const\nexport type SheetSkin = (typeof SHEET_SKINS)[number]\n\nexport const SHEET_ASPECTS = [\"landscape\", \"square\", \"story\"] as const\nexport type SheetAspect = (typeof SHEET_ASPECTS)[number]\n\n/** Studio sheet presets (character only). Declared here so SheetFlavour can carry\n * it without a cycle (`presets.ts` re-exports it alongside the registry). */\nexport type SheetPresetId = \"studio-main\" | \"studio-extended\"\n\nexport const OUTPUT_FORMATS = [\"still\", \"motion\"] as const\nexport type OutputFormat = (typeof OUTPUT_FORMATS)[number]\n\nexport const SECTION_KINDS = [\n \"header\",\n \"head-turnaround\", \"body-turnaround\", \"turnaround\", \"coverage\",\n \"expression-board\", \"pose-board\", \"material-board\", \"variation-board\", \"environment-board\",\n \"detail-board\", \"wardrobe-board\",\n \"palette\", \"scale\", \"notes\",\n] as const\nexport type SectionKind = (typeof SECTION_KINDS)[number]\n\nexport const SHEET_BACKGROUNDS = [\"grey\", \"white\", \"transparent\", \"in-context\"] as const\nexport type SheetBackground = (typeof SHEET_BACKGROUNDS)[number]\n\n/** A board entry is either a catalog preset (by variant) or a user-authored custom panel. */\nexport interface PresetEntry { kind: \"preset\"; variant: string }\nexport interface CustomEntry { kind: \"custom\"; label: string; prompt: string }\nexport type SheetEntry = PresetEntry | CustomEntry\n\n/** One band in the sheet. `board` disambiguates kinds that map to several buckets (environment-board). */\nexport interface SheetSection {\n kind: SectionKind\n board?: string\n subtitle?: string\n panelCount?: number\n entries?: SheetEntry[] // omitted => planner fills the default preset set\n}\n\nexport interface SheetFlavour {\n outputFormat: OutputFormat\n withText: boolean\n showLabels: boolean\n aspect: SheetAspect\n background: SheetBackground\n sections?: SheetSection[] // explicit stack for `full-reference`; other types derive defaults\n presetId?: SheetPresetId // labels studio preset sheets; inert to pricing/composition\n}\n\n/** A single panel the planner says must exist (reused or generated). */\nexport interface PanelRequest {\n section: SectionKind\n board: string // logical board key (maps to a DB column via the backend adapter, Plan 04)\n variant: string // preset variant string, or the custom label\n label: string\n custom: boolean\n prompt?: string // present iff custom\n}\n\nexport interface Swatch { hex: string; label: string }\nexport interface PanelSource { board: string; variant: string; assetId?: string; url: string }\nexport interface SheetTextData {\n title?: string\n metadata?: Record<string, string>\n notes?: string\n sectionLabels?: Record<string, string>\n}\n\nexport interface ReferenceSheet {\n id: string\n type: SheetType\n skin: SheetSkin\n flavour: SheetFlavour\n source: \"studio\" | \"node\"\n url: string\n panelUrls: string[]\n panelSources: PanelSource[]\n sectionsSnapshot: SheetSection[]\n metadataSnapshot: SheetTextData\n paletteSnapshot: Swatch[]\n sourceImageUrlAtGen: string\n createdAt: string\n}\n\n/** Hard ceilings (also re-asserted in the route Zod schema, Plan 04). */\nexport const MAX_PANELS_PER_SHEET = 24\nexport const MAX_CUSTOM_ENTRIES_PER_BOARD = 12\n","/**\n * Structural entity vocabulary — asset-type/attach-column tuples, reference\n * photo kinds, styles, labels. Product data visible in the UI and required\n * by SDK consumers; deliberately part of the public Apache surface.\n * (The prompt-BUILDING craft lives in @nodaro/prompts.)\n */\n\n/**\n * Prompt builders for entity nodes (character, face, object, location).\n *\n * Single source of truth shared between:\n * - Route handlers: `backend/src/routes/generate-{character,face,object,location}.ts`\n * - Backend orchestrator: `backend/src/services/workflow-engine/payload-builder.ts`\n *\n * The route handlers call these when no client-supplied prompt is provided.\n * The orchestrator calls these to build the same prompt that a single-node\n * HTTP call would produce.\n */\n\n/**\n * Allowed style values for character / face / object / location entities.\n * Single source of truth: derive Zod enums + TS types from this tuple so the\n * Zod schema, the TS union, the SDK input types, and the CLI flag validator\n * never drift apart.\n */\nexport const CHARACTER_STYLES = [\"realistic\", \"anime\", \"3d-pixar\", \"illustration\"] as const\nexport type EntityStyle = (typeof CHARACTER_STYLES)[number]\n\n/**\n * Character asset-type enum — the kinds of variant a user can generate off a\n * character's anchor portrait. Mirrors the literal accepted by\n * `POST /v1/generate-character-asset` (`backend/src/routes/generate-character-asset.ts`)\n * and consumed by the MCP `generate_character` verb (kind=\"asset\") in\n * `backend/src/lib/mcp/tools/verbs-clo.ts`.\n *\n * `angles` is the legacy single-surface alias for `headAngles` — both produce\n * head-and-shoulders portrait framing. `bodyAngles` is the full-body variant.\n * `lighting` is the bucket key (the DB column is `lighting_variations`).\n */\nexport const CHARACTER_ASSET_TYPES = [\n \"expressions\",\n \"poses\",\n \"lighting\",\n \"angles\",\n \"headAngles\",\n \"bodyAngles\",\n \"custom\",\n] as const\nexport type CharacterAssetType = (typeof CHARACTER_ASSET_TYPES)[number]\n\n/**\n * DB columns the character-asset worker may auto-attach to. Required when\n * `assetType === \"custom\"` (the worker can't infer the bucket from the asset\n * type); for canonical asset types the column is derived automatically.\n *\n * Mirrors the literal accepted by the route's `attachToColumn` Zod field.\n */\nexport const CHARACTER_ATTACH_COLUMNS = [\n \"expressions\",\n \"poses\",\n \"angles\",\n \"body_angles\",\n \"lighting_variations\",\n // Reference-sheet buckets (migration 200). `sheets` holds composited\n // reference sheets; `detail_closeups` holds macro close-up panels;\n // `outfit_variations` holds wardrobe panels (character-only — objects and\n // locations don't have an outfit dimension).\n \"sheets\",\n \"detail_closeups\",\n \"outfit_variations\",\n] as const\nexport type CharacterAttachColumn = (typeof CHARACTER_ATTACH_COLUMNS)[number]\n\n/**\n * Canonical variant presets per character asset type — the SINGLE source of\n * truth shared by the `generate-character-asset` route (Zod validation rejects a\n * non-`custom` variant outside this list) and any client building the asset-set\n * UI (e.g. the Studio character creator), so the two can't drift. `custom` has no\n * preset list (free-form variant).\n */\nexport const CHARACTER_ASSET_VARIANTS = {\n expressions: [\n \"neutral\",\n \"smile\",\n \"angry\",\n \"surprised\",\n \"sad\",\n \"talking\",\n \"laughing\",\n \"disgusted\",\n \"fearful\",\n \"smirk\",\n \"crying\",\n ],\n poses: [\n \"standing\",\n \"walking\",\n \"sitting\",\n \"running\",\n \"crouching\",\n \"pointing\",\n \"fighting stance\",\n \"jumping\",\n \"turning\",\n ],\n lighting: [\"daylight\", \"night\", \"dramatic\"],\n angles: [\"front\", \"3/4 left\", \"left profile\", \"right profile\", \"3/4 right\", \"back\", \"above\", \"below\"],\n headAngles: [\"front\", \"3/4 left\", \"left profile\", \"right profile\", \"3/4 right\", \"above\", \"below\", \"back\"],\n bodyAngles: [\"front\", \"3/4 left\", \"left profile\", \"right profile\", \"3/4 right\", \"back\", \"above\", \"below\"],\n} as const satisfies Partial<Record<CharacterAssetType, readonly string[]>>\n\n/**\n * Location asset-type enum — the kinds of variant a user can generate off a\n * location's anchor establishing shot. Mirrors the literal accepted by\n * `POST /v1/generate-location-asset` (`backend/src/routes/generate-location-asset.ts`)\n * and consumed by the MCP `generate_location` verb (kind=\"asset\").\n *\n * `lighting` is the bucket key (the DB column is `lighting`). `custom` is the\n * free-form bucket where callers must supply `attachToColumn` explicitly since\n * the worker can't infer the destination from the asset type.\n */\nexport const LOCATION_ASSET_TYPES = [\n \"timeOfDay\",\n \"weather\",\n \"seasons\",\n \"angles\",\n \"lighting\",\n \"custom\",\n] as const\nexport type LocationAssetType = (typeof LOCATION_ASSET_TYPES)[number]\n\n/**\n * DB columns the location-asset worker may auto-attach to. Required when\n * `assetType === \"custom\"` (the worker can't infer the bucket from the asset\n * type); for canonical asset types the column is derived automatically.\n *\n * Mirrors the literal accepted by the route's `attachToColumn` Zod field.\n */\nexport const LOCATION_ATTACH_COLUMNS = [\n \"time_of_day\",\n \"weather\",\n \"seasons\",\n \"angles\",\n \"lighting\",\n \"atmosphere_motions\",\n // Reference-sheet buckets (migration 200). Locations get `sheets` +\n // `detail_closeups` (no `outfit_variations` — that's character-only).\n \"sheets\",\n \"detail_closeups\",\n] as const\nexport type LocationAttachColumn = (typeof LOCATION_ATTACH_COLUMNS)[number]\n\n/**\n * Canonical variant presets per LOCATION asset type — hoisted from\n * `backend/src/routes/generate-location-asset.ts` (single source of truth shared\n * with the reference-sheet catalog; Plan 04 switches the route to import this).\n */\nexport const LOCATION_ASSET_VARIANTS = {\n timeOfDay: [\"dawn\", \"morning\", \"noon\", \"afternoon\", \"golden hour\", \"dusk\", \"blue hour\", \"night\", \"midnight\"],\n weather: [\"clear\", \"cloudy\", \"light rain\", \"heavy rain\", \"storm\", \"snow\", \"blizzard\", \"fog\", \"mist\"],\n seasons: [\"spring\", \"summer\", \"autumn\", \"winter\"],\n angles: [\"wide\", \"medium\", \"closeup\", \"aerial\", \"low-angle\", \"eye-level\", \"bird's-eye\", \"dutch tilt\"],\n lighting: [\"soft natural\", \"harsh sunlight\", \"golden\", \"blue hour\", \"neon\", \"candlelit\", \"cinematic\", \"dramatic chiaroscuro\"],\n} as const satisfies Partial<Record<LocationAssetType, readonly string[]>>\n\n/**\n * Reference-photo kind discriminator — the mood-board roles a user can attach\n * to a location row. Single source of truth shared between:\n * - Backend route Zod enum (`backend/src/routes/locations.ts`)\n * - Backend export/import bundle schema (`backend/src/lib/workflow-assets.ts`)\n * - Frontend Studio picker (`reference-photos-section.tsx`)\n * - Frontend `LocationNodeData.referencePhotos.kind` union (`frontend/src/types/nodes.ts`)\n *\n * `other` is the free-form bucket; the rest are user-curated mood-board roles.\n */\nexport const LOCATION_REFERENCE_PHOTO_KINDS = [\n \"wide\",\n \"interior\",\n \"exterior\",\n \"detail\",\n \"moodBoard\",\n \"other\",\n] as const\nexport type LocationReferencePhotoKind = (typeof LOCATION_REFERENCE_PHOTO_KINDS)[number]\n\n/**\n * Human-friendly label for each photo kind, used in prompt subject lines\n * (`Image N (Old Library — wide-angle reference)`) so the model knows the\n * role of each reference photo at generate time. Kept as a separate map\n * from `LOCATION_REFERENCE_PHOTO_KINDS` so labels can be edited without\n * disturbing the kind enum (which is the schema-of-record).\n */\nexport const LOCATION_REFERENCE_PHOTO_KIND_LABELS: Record<LocationReferencePhotoKind, string> = {\n wide: \"wide-angle reference\",\n interior: \"interior reference\",\n exterior: \"exterior reference\",\n detail: \"detail reference\",\n moodBoard: \"mood-board reference\",\n other: \"reference\",\n}\n\nexport function locationReferencePhotoKindLabel(kind: LocationReferencePhotoKind): string {\n return LOCATION_REFERENCE_PHOTO_KIND_LABELS[kind]\n}\n\n/**\n * Reference-photo kinds captured in the Character Studio identity foundation —\n * the SINGLE schema-of-record for the 7 kinds. Previously duplicated across the\n * `generate-character` + `characters` route Zod enums, `character-reference-set.ts`\n * (backend ranking), and `frontend/src/lib/reference-photo-routing.ts` (UI\n * filtering). All of those now derive from this const (build a Zod enum via\n * `z.enum(CHARACTER_REFERENCE_PHOTO_KINDS)` at the backend edge — this package\n * stays zod-free). Also the shape of the DB `characters.reference_photos[].kind`.\n *\n * `other` is the free-form bucket; the rest are curated identity-foundation roles\n * (frontFace + the four rotation views + a full-body shot).\n */\nexport const CHARACTER_REFERENCE_PHOTO_KINDS = [\n \"frontFace\",\n \"sideLeft\",\n \"sideRight\",\n \"threeQuarterLeft\",\n \"threeQuarterRight\",\n \"frontBody\",\n \"other\",\n] as const\nexport type CharacterReferencePhotoKind = (typeof CHARACTER_REFERENCE_PHOTO_KINDS)[number]\n\n/** A single character reference photo: a URL plus its identity-foundation role. */\nexport interface CharacterReferencePhoto {\n url: string\n kind: CharacterReferencePhotoKind\n}\n\n/**\n * Reserved name the Character Studio auto-assigns when a user clicks Generate\n * before naming the character. Treated as \"no name\" by prompt builders so the\n * literal string \"Untitled character\" never leaks into a generation prompt.\n * Frontend stays in sync via `@nodaro/shared`.\n */\nexport const PLACEHOLDER_CHARACTER_NAME = \"Untitled character\"\n\n\nexport const OBJECT_ASSET_TYPES = [\n \"angles\",\n \"materials\",\n \"variations\",\n \"motion\",\n \"custom\",\n] as const\nexport type ObjectAssetType = (typeof OBJECT_ASSET_TYPES)[number]\n\n/**\n * DB columns the object-asset worker may auto-attach to. Aligns with the\n * `append_object_asset` RPC's CASE/WHEN whitelist (migration 147). Required\n * when `assetType === \"custom\"`; for canonical asset types the column is\n * derived automatically.\n */\nexport const OBJECT_ATTACH_COLUMNS = [\n \"angles\",\n \"materials\",\n \"variations\",\n \"motion_clips\",\n // Reference-sheet buckets (migration 200). Objects get `sheets` +\n // `detail_closeups` (no `outfit_variations` — that's character-only).\n \"sheets\",\n \"detail_closeups\",\n] as const\nexport type ObjectAttachColumn = (typeof OBJECT_ATTACH_COLUMNS)[number]\n\n/** Worker-attachable JSONB asset columns on `creatures` (mirrors OBJECT_ATTACH_COLUMNS;\n * `materials`→`poses`). The append_creature_asset RPC (migration 206) whitelists these. */\nexport const CREATURE_ATTACH_COLUMNS = [\n \"angles\", \"poses\", \"variations\", \"motion_clips\", \"sheets\", \"detail_closeups\",\n] as const\nexport type CreatureAttachColumn = (typeof CREATURE_ATTACH_COLUMNS)[number]\n\n/**\n * Canonical variant presets per OBJECT asset type — hoisted from\n * `backend/src/routes/generate-object-asset.ts` so the route, the reference-sheet\n * catalog, and any client share one list and can't drift. (Plan 04 switches the\n * route to import this.) `custom`/`motion` have no preset list.\n */\nexport const OBJECT_ASSET_VARIANTS = {\n angles: [\"front\", \"side\", \"top\", \"back\", \"three-quarter\"],\n materials: [\"wood\", \"metal\", \"glass\", \"plastic\", \"fabric\", \"stone\"],\n variations: [\"clean\", \"weathered\", \"damaged\", \"ornate\", \"minimal\"],\n} as const satisfies Partial<Record<ObjectAssetType, readonly string[]>>\n\n/**\n * Input shape for buildObjectMotionPrompt.\n *\n * Mirrors LocationMotionPromptInput's role. `canonicalDescription` is preferred\n * (LLM-authored from the approved main image) but the helper falls back to\n * category+name if not yet set, and to a generic placeholder if both are absent.\n */\n","import {\n CHARACTER_ASSET_VARIANTS, OBJECT_ASSET_VARIANTS, LOCATION_ASSET_VARIANTS,\n} from \"../entity-asset-types.js\"\nimport type { EntityKind, SectionKind, SheetType, SheetSection } from \"./types.js\"\n\n/** Starter presets for the NEW close-up bucket (per entity). Custom entries override. */\nexport const DETAIL_VARIANTS: Record<EntityKind, readonly string[]> = {\n character: [\"eyes\", \"hands\", \"hair detail\"],\n object: [\"texture\", \"material detail\", \"key part\"],\n location: [\"architectural detail\", \"material detail\", \"focal element\"],\n}\n\n/** Starter presets for the NEW wardrobe bucket (character only). Custom entries override. */\nexport const WARDROBE_VARIANTS = [\"base look\", \"alternate look\", \"sporty\"] as const\n\n/** Logical board → ordered canonical variants, per entity. Character/object/location\n * pull from the SoT lists; detail/wardrobe are the new buckets. */\nexport const BOARD_VARIANTS: Record<EntityKind, Record<string, readonly string[]>> = {\n character: {\n headAngles: CHARACTER_ASSET_VARIANTS.headAngles,\n bodyAngles: CHARACTER_ASSET_VARIANTS.bodyAngles,\n expressions: CHARACTER_ASSET_VARIANTS.expressions,\n poses: CHARACTER_ASSET_VARIANTS.poses,\n lighting: CHARACTER_ASSET_VARIANTS.lighting,\n detail: DETAIL_VARIANTS.character,\n wardrobe: WARDROBE_VARIANTS,\n },\n object: {\n angles: OBJECT_ASSET_VARIANTS.angles,\n materials: OBJECT_ASSET_VARIANTS.materials,\n variations: OBJECT_ASSET_VARIANTS.variations,\n detail: DETAIL_VARIANTS.object,\n },\n location: {\n angles: LOCATION_ASSET_VARIANTS.angles,\n timeOfDay: LOCATION_ASSET_VARIANTS.timeOfDay,\n weather: LOCATION_ASSET_VARIANTS.weather,\n seasons: LOCATION_ASSET_VARIANTS.seasons,\n lighting: LOCATION_ASSET_VARIANTS.lighting,\n detail: DETAIL_VARIANTS.location,\n },\n}\n\n/** Section kinds that NEVER produce panels (chrome/text bands). The single\n * source of truth for \"structural\" — the planner uses this to decide whether a\n * section with no resolvable board is intentionally panel-less (these) or a\n * misconfiguration (e.g. `environment-board` with no explicit `board`, which\n * must throw, not silently yield zero panels). */\nexport const STRUCTURAL_SECTIONS = new Set<SectionKind>([\"header\", \"palette\", \"scale\", \"notes\"])\n\n/** Default board for each board-typed section kind. `null` = no default board.\n * For the four structural kinds (`STRUCTURAL_SECTIONS`) that means \"no panels\".\n * For `environment-board` it means \"ambiguous (3 buckets) — the section MUST\n * carry an explicit `board`\" (the planner throws if it doesn't). */\nexport const SECTION_BOARD: Record<SectionKind, string | null> = {\n header: null, palette: null, scale: null, notes: null,\n \"head-turnaround\": \"headAngles\",\n \"body-turnaround\": \"bodyAngles\",\n turnaround: \"angles\",\n coverage: \"angles\",\n \"expression-board\": \"expressions\",\n \"pose-board\": \"poses\",\n \"material-board\": \"materials\",\n \"variation-board\": \"variations\",\n \"environment-board\": null, // requires explicit section.board (timeOfDay|weather|seasons)\n \"detail-board\": \"detail\",\n \"wardrobe-board\": \"wardrobe\",\n}\n\n/** Sections each entity supports (catalog gate for the config picker, Plan 06). */\nexport const ENTITY_SECTIONS: Record<EntityKind, readonly SectionKind[]> = {\n character: [\"header\", \"head-turnaround\", \"body-turnaround\", \"expression-board\", \"pose-board\",\n \"detail-board\", \"wardrobe-board\", \"palette\", \"scale\", \"notes\"],\n object: [\"header\", \"turnaround\", \"material-board\", \"variation-board\", \"detail-board\",\n \"palette\", \"scale\", \"notes\"],\n location: [\"header\", \"coverage\", \"environment-board\", \"detail-board\", \"palette\", \"scale\", \"notes\"],\n}\n\nconst sec = (kind: SectionKind, extra: Partial<SheetSection> = {}): SheetSection => ({ kind, ...extra })\n\n/** Preset section stacks per (entity, type). `full-reference` is the rich poster\n * (YUVAL order for character); other types are single-board presets. */\nexport const DEFAULT_SECTIONS: Record<EntityKind, Record<SheetType, readonly SheetSection[]>> = {\n character: {\n turnaround: [sec(\"header\"), sec(\"head-turnaround\")],\n \"variation-board\": [sec(\"header\"), sec(\"expression-board\")],\n detail: [sec(\"header\"), sec(\"detail-board\")],\n \"full-reference\": [\n sec(\"header\"), sec(\"head-turnaround\"), sec(\"expression-board\"), sec(\"body-turnaround\"),\n sec(\"pose-board\"), sec(\"detail-board\"), sec(\"wardrobe-board\"), sec(\"palette\"), sec(\"notes\"),\n ],\n },\n object: {\n turnaround: [sec(\"header\"), sec(\"turnaround\")],\n \"variation-board\": [sec(\"header\"), sec(\"material-board\")],\n detail: [sec(\"header\"), sec(\"detail-board\")],\n \"full-reference\": [\n sec(\"header\"), sec(\"turnaround\"), sec(\"material-board\"), sec(\"variation-board\"),\n sec(\"detail-board\"), sec(\"palette\"), sec(\"notes\"),\n ],\n },\n location: {\n turnaround: [sec(\"header\"), sec(\"coverage\")],\n \"variation-board\": [sec(\"header\"), sec(\"environment-board\", { board: \"timeOfDay\" })],\n detail: [sec(\"header\"), sec(\"detail-board\")],\n \"full-reference\": [\n sec(\"header\"), sec(\"coverage\"),\n sec(\"environment-board\", { board: \"timeOfDay\" }),\n sec(\"environment-board\", { board: \"weather\" }),\n sec(\"detail-board\"), sec(\"palette\"), sec(\"notes\"),\n ],\n },\n}\n\n/** Default number of panels drawn from a board when the section doesn't specify. */\nexport const DEFAULT_PANEL_COUNT = 4\n\n/** Logical board key → real entity DB column (headAngles→angles,\n * lighting→lighting_variations, timeOfDay→time_of_day, etc.). The worker uses\n * this to find a panel's asset in the entity's JSONB buckets. */\nexport const BOARD_TO_COLUMN: Record<EntityKind, Record<string, string>> = {\n character: { headAngles: \"angles\", bodyAngles: \"body_angles\", expressions: \"expressions\", poses: \"poses\", lighting: \"lighting_variations\", detail: \"detail_closeups\", wardrobe: \"outfit_variations\" },\n object: { angles: \"angles\", materials: \"materials\", variations: \"variations\", detail: \"detail_closeups\" },\n location: { angles: \"angles\", timeOfDay: \"time_of_day\", weather: \"weather\", seasons: \"seasons\", lighting: \"lighting\", detail: \"detail_closeups\" },\n}\n\n/** Flat per-entity DB column holding motion clips ({name,url} videos). Unlike\n * still panels (per-board columns via BOARD_TO_COLUMN), all of an entity's motion\n * clips live in ONE column, looked up by name===variant. Used by the motion\n * reference sheet to find the clip for each planned panel. */\nexport const MOTION_COLUMN: Record<EntityKind, string> = {\n character: \"motions\",\n object: \"motion_clips\",\n location: \"atmosphere_motions\",\n}\n\n/** Logical board → the `generate-*-asset` `assetType` to use. Standard boards map\n * to their own assetType; detail/wardrobe have no dedicated assetType so they go\n * through `custom` (with a built userPrompt). */\nexport const BOARD_TO_ASSET_TYPE: Record<EntityKind, Record<string, string>> = {\n character: { headAngles: \"headAngles\", bodyAngles: \"bodyAngles\", expressions: \"expressions\", poses: \"poses\", lighting: \"lighting\", detail: \"custom\", wardrobe: \"custom\" },\n object: { angles: \"angles\", materials: \"materials\", variations: \"variations\", detail: \"custom\" },\n location: { angles: \"angles\", timeOfDay: \"timeOfDay\", weather: \"weather\", seasons: \"seasons\", lighting: \"lighting\", detail: \"custom\" },\n}\n","import type { EntityKind, PanelRequest, SheetFlavour, SheetSection } from \"./types.js\"\nimport { MAX_PANELS_PER_SHEET, MAX_CUSTOM_ENTRIES_PER_BOARD } from \"./types.js\"\nimport { BOARD_VARIANTS, SECTION_BOARD, STRUCTURAL_SECTIONS, DEFAULT_PANEL_COUNT } from \"./catalog.js\"\n\n/** Resolve the logical board for a section, or null for structural sections.\n * A non-structural board section that can't resolve a board (e.g.\n * `environment-board` with no explicit `section.board`, or a board not valid\n * for this entity) throws — turning misconfiguration into a free rejection\n * instead of silently emitting zero panels. */\nfunction resolveBoard(entityKind: EntityKind, section: SheetSection): string | null {\n if (STRUCTURAL_SECTIONS.has(section.kind)) return null\n const board = section.board ?? SECTION_BOARD[section.kind]\n if (!board || !BOARD_VARIANTS[entityKind][board]) {\n throw new Error(\n `Section \"${section.kind}\" has no resolvable board for ${entityKind} (board=${board ?? \"?\"}) — ` +\n `board sections like environment-board require an explicit section.board valid for the entity`,\n )\n }\n return board\n}\n\n/**\n * Pure: given an entity kind, an ordered section list, and the flavour, return the\n * ordered panels the sheet needs. Reuse-vs-generate and pricing happen later\n * (Plan 04) — this only says WHAT panels must exist. Throws on bad config so the\n * route can 400 before any paid work.\n */\nexport function planSheetPanels(\n entityKind: EntityKind,\n sections: readonly SheetSection[],\n _flavour: SheetFlavour,\n): PanelRequest[] {\n const panels: PanelRequest[] = []\n for (const section of sections) {\n const board = resolveBoard(entityKind, section)\n if (board === null) continue // structural section, no panels\n\n const customs = (section.entries ?? []).filter((e) => e.kind === \"custom\")\n if (customs.length > MAX_CUSTOM_ENTRIES_PER_BOARD) {\n throw new Error(`Too many custom entries on ${section.kind} (${customs.length} > ${MAX_CUSTOM_ENTRIES_PER_BOARD})`)\n }\n\n if (section.entries && section.entries.length > 0) {\n for (const e of section.entries) {\n if (e.kind === \"custom\") {\n panels.push({ section: section.kind, board, variant: e.label, label: e.label, custom: true, prompt: e.prompt })\n } else {\n panels.push({ section: section.kind, board, variant: e.variant, label: e.variant, custom: false })\n }\n }\n } else {\n const available = BOARD_VARIANTS[entityKind][board]\n // Clamp both ends: a negative panelCount must not become a negative slice\n // bound (which would silently drop panels from the end of the board).\n const count = Math.max(0, Math.min(section.panelCount ?? DEFAULT_PANEL_COUNT, available.length))\n for (const variant of available.slice(0, count)) {\n panels.push({ section: section.kind, board, variant, label: variant, custom: false })\n }\n }\n }\n if (panels.length > MAX_PANELS_PER_SHEET) {\n throw new Error(`Sheet plan has too many panels (${panels.length} > MAX_PANELS_PER_SHEET=${MAX_PANELS_PER_SHEET})`)\n }\n return panels\n}\n","import type { EntityKind } from \"./types.js\"\n\n/** Build the `userPrompt` for a detail/wardrobe panel generated via the\n * `custom` assetType (these boards have no dedicated backend assetType). */\nexport function buildPanelPrompt(entityKind: EntityKind, board: string, variant: string, name: string): string {\n if (board === \"detail\") {\n return `Extreme close-up macro detail of ${name}'s ${variant}, sharp focus on the ${variant}, neutral background, no text.`\n }\n if (board === \"wardrobe\") {\n return `Full-body view of ${name} wearing the \"${variant}\" outfit, consistent character, neutral studio background, no text.`\n }\n // Generic passthrough for any other custom board.\n return `${name}, ${variant}. Consistent character, neutral background, no text.`\n}\n","import { planSheetPanels } from \"./panel-plan.js\"\nimport { BOARD_TO_COLUMN, BOARD_TO_ASSET_TYPE, DEFAULT_SECTIONS } from \"./catalog.js\"\nimport { buildPanelPrompt } from \"./panel-prompts.js\"\nimport type { EntityKind, SheetSection, SheetFlavour, SheetType } from \"./types.js\"\n\n/**\n * The section stack to actually compose for a sheet. The Studio \"Sheet\" tab\n * sends an explicit, user-chosen stack in `flavour.sections`; the canvas node,\n * workflow runs, and API/MCP callers send only `type`, so fall back to the\n * default stack for (entityKind, type). Always returns a fresh, mutable clone so\n * neither the caller nor the shared `DEFAULT_SECTIONS` constant is mutated.\n *\n * Single source of truth for \"type → sections\" — without this fallback a node\n * sheet composes with zero bands (a blank image). Every (entityKind, type) has a\n * non-empty default stack (guarded by the catalog invariant test).\n */\nexport function resolveSheetSections(\n entityKind: EntityKind,\n type: SheetType,\n sections?: readonly SheetSection[],\n): SheetSection[] {\n const base = sections?.length ? sections : (DEFAULT_SECTIONS[entityKind][type] ?? [])\n return base.map((s) => ({ ...s }))\n}\n\n/** A `generate-*-asset` request for one missing panel. */\nexport interface PanelGenRequest {\n assetType: string // e.g. \"headAngles\" | \"expressions\" | \"custom\"\n variant: string // preset variant or custom label (also the attachName)\n attachToColumn: string // DB column (snake_case) the worker appends to\n attachName: string // == variant\n userPrompt?: string // present for custom assetType / custom entries\n}\n\nexport interface SheetGenerationPlan {\n presentUrls: string[]\n missing: PanelGenRequest[]\n}\n\n/** Find the bucket item whose `name` equals `variant` and which carries a\n * non-empty `url` (single source of truth — the same predicate the still + motion\n * panel resolvers use to locate a planned panel in an entity's buckets). */\nexport function matchVariant(\n items: ReadonlyArray<{ name?: string; url?: string }>,\n variant: string,\n): { name?: string; url?: string } | undefined {\n return items.find((it) => it?.name === variant && typeof it?.url === \"string\" && it.url.length > 0)\n}\n\n/** Pure: given the entity's current buckets (keyed by DB column), split the\n * planned panels into already-present URLs and the generate-requests needed for\n * the rest. The surface fires each request, awaits, then calls the compose API. */\nexport function planSheetGeneration(\n entityKind: EntityKind,\n sections: readonly SheetSection[],\n flavour: SheetFlavour,\n bucketsByColumn: Record<string, ReadonlyArray<{ name?: string; url?: string }> | undefined>,\n name: string,\n): SheetGenerationPlan {\n const plan = planSheetPanels(entityKind, sections, flavour)\n const presentUrls: string[] = []\n const missing: PanelGenRequest[] = []\n for (const p of plan) {\n const column = BOARD_TO_COLUMN[entityKind][p.board]\n const items = (column ? bucketsByColumn[column] : undefined) ?? []\n const match = matchVariant(items, p.variant)\n if (match?.url) {\n presentUrls.push(match.url)\n continue\n }\n const assetType = BOARD_TO_ASSET_TYPE[entityKind][p.board] ?? \"custom\"\n const userPrompt =\n p.custom ? p.prompt :\n assetType === \"custom\" ? buildPanelPrompt(entityKind, p.board, p.variant, name) :\n undefined\n missing.push({ assetType, variant: p.variant, attachToColumn: column, attachName: p.variant, userPrompt })\n }\n return { presentUrls, missing }\n}\n","import type { OutputFormat } from \"./types.js\"\n/** The credit identifier for a sheet by output format (single source of truth —\n * mirrors resolveCinematicCreditId). Used by the route guard, the orchestrator\n * payload-builder, and the node's credit display. */\nexport function referenceSheetCreditId(flavour: { outputFormat?: OutputFormat | string } | undefined): string {\n return flavour?.outputFormat === \"motion\" ? \"reference-sheet:assembly-motion\" : \"reference-sheet:assembly\"\n}\n","import type { SheetSection, SheetEntry, SheetType, SheetSkin, SheetAspect, SheetPresetId } from \"./types.js\"\n\nexport type { SheetPresetId }\n\n/** Build ordered preset entries from a variant list (a curated board subset). */\nexport const presetEntries = (vs: readonly string[]): SheetEntry[] =>\n vs.map((variant) => ({ kind: \"preset\", variant }))\n\nexport interface SheetPreset {\n id: SheetPresetId\n label: string\n description: string\n /** Carrier for the route's required `type` enum; the layout comes from `baseSections`. */\n type: SheetType\n baseSections: SheetSection[]\n skin: SheetSkin\n aspect: SheetAspect\n}\n\n/**\n * Studio sheet presets (character only). Each bundles a curated head+body\n * turnaround (via `entries`) + a default skin/aspect + a carrier `type`. The\n * à-la-carte boards below layer optional extra bands on top.\n *\n * `studio-main` is the clean screenshot format (head: front, profiles, back-of-\n * head; body: front, side, back). `studio-extended` adds above/below + 3/4\n * angles for fuller coverage.\n */\nexport const SHEET_PRESETS: readonly SheetPreset[] = [\n {\n id: \"studio-main\",\n label: \"Studio · Main\",\n description: \"Clean turnaround for AI video reference — head (front, profiles, back) + body (front, side, back).\",\n type: \"turnaround\",\n skin: \"studio\",\n aspect: \"landscape\",\n baseSections: [\n { kind: \"head-turnaround\", entries: presetEntries([\"front\", \"left profile\", \"right profile\", \"back\"]) },\n { kind: \"body-turnaround\", entries: presetEntries([\"front\", \"left profile\", \"back\"]) },\n ],\n },\n {\n id: \"studio-extended\",\n label: \"Studio · Extended\",\n description: \"Full turnaround — adds above/below and 3/4 angles for maximum coverage.\",\n type: \"full-reference\",\n skin: \"studio\",\n aspect: \"landscape\",\n baseSections: [\n { kind: \"head-turnaround\", entries: presetEntries([\"front\", \"3/4 left\", \"left profile\", \"right profile\", \"3/4 right\", \"above\", \"below\", \"back\"]) },\n { kind: \"body-turnaround\", entries: presetEntries([\"front\", \"3/4 left\", \"left profile\", \"right profile\", \"back\", \"above\", \"below\"]) },\n ],\n },\n]\n\nexport const PRESET_LABELS: Record<SheetPresetId, string> = {\n \"studio-main\": \"Studio · Main\",\n \"studio-extended\": \"Studio · Extended\",\n}\n\nexport interface AlaCarteBoard {\n id: string\n label: string\n /** UI hint: panels this board adds (the board's default slice). Free boards are 0. */\n panelCount: number\n section: SheetSection\n}\n\n/** Optional boards layered on a base preset. No `entries` → the planner uses the\n * board's default slice (`min(4, board length)`). Palette is structural (free). */\nexport const ALA_CARTE_BOARDS: readonly AlaCarteBoard[] = [\n { id: \"expressions\", label: \"Expressions\", panelCount: 4, section: { kind: \"expression-board\" } },\n { id: \"poses\", label: \"Poses\", panelCount: 4, section: { kind: \"pose-board\" } },\n { id: \"wardrobe\", label: \"Wardrobe\", panelCount: 3, section: { kind: \"wardrobe-board\" } },\n { id: \"detail\", label: \"Detail\", panelCount: 3, section: { kind: \"detail-board\" } },\n { id: \"palette\", label: \"Palette\", panelCount: 0, section: { kind: \"palette\" } },\n]\n","import { planSheetGeneration, type PanelGenRequest } from \"./plan-generation.js\"\nimport type { EntityKind, SheetSection, SheetFlavour } from \"./types.js\"\n\nexport interface SheetCostEstimate {\n present: number\n missing: PanelGenRequest[]\n prepareCost: number\n assemblyCost: number\n total: number\n /** True when the plan exceeds MAX_PANELS_PER_SHEET (planSheetPanels throws). */\n overflow: boolean\n}\n\n/**\n * Pure cost estimate for a sheet plan. Wraps `planSheetGeneration` so a\n * MAX_PANELS overflow (which throws in the planner) becomes `overflow:true`\n * instead of crashing the caller's render. `perPanelCost`/`assemblyCost` are\n * injected by the UI (constants from the adapter) so the shared layer stays\n * pricing-agnostic.\n */\nexport function estimateSheetCost(\n entityKind: EntityKind,\n sections: readonly SheetSection[],\n flavour: SheetFlavour,\n buckets: Record<string, ReadonlyArray<{ name?: string; url?: string }> | undefined>,\n name: string,\n perPanelCost: number,\n assemblyCost: number,\n): SheetCostEstimate {\n try {\n const { presentUrls, missing } = planSheetGeneration(entityKind, sections, flavour, buckets, name)\n const prepareCost = missing.length * perPanelCost\n return { present: presentUrls.length, missing, prepareCost, assemblyCost, total: prepareCost + assemblyCost, overflow: false }\n } catch {\n return { present: 0, missing: [], prepareCost: 0, assemblyCost, total: assemblyCost, overflow: true }\n }\n}\n","/** Gen providers for the board: strict subset of IMAGE_GEN_PROVIDERS that\n * renders legible in-image text + accepts reference conditioning. */\nexport const REFERENCE_BOARD_PROVIDERS = [\"nano-banana-pro\", \"gpt-image-2\"] as const\nexport type ReferenceBoardProvider = (typeof REFERENCE_BOARD_PROVIDERS)[number]\n\nexport type BoardEntityKind = \"character\" | \"location\" | \"object\"\n\nexport interface BoardTemplate {\n /** \"<entityKind>/<slug>\" */\n readonly id: string\n readonly entityKind: BoardEntityKind\n readonly label: string\n readonly build: (ctx: BoardPromptContext) => string\n}\n\n/** Optional metadata the resolver supplies from a connected entity. All\n * optional — the prompt degrades gracefully (omits labels) when absent. */\nexport interface BoardPromptContext {\n readonly name?: string\n readonly description?: string\n}\n\n// ── Shared clauses (the three guide tricks) ──────────────────────────────\nconst ANTI_RIGID =\n \"Editorial reference-board layout, dark near-black background, thin yellow neon accent light, \" +\n \"faint film-grain overlay, production-grade design UI. Organized but not rigidly locked: panels may \" +\n \"shift position from generation to generation while staying readable, balanced and premium. Works \" +\n \"cleanly in different aspect ratios without depending on a fixed left-column structure. All on-image labels in ENGLISH.\"\nconst PALETTE = \"A COLOR PALETTE panel: 6 swatches with HEX codes derived from the dominant tones.\"\nconst CAPTION = (kind: string) =>\n `Bottom caption: \"Use this ${kind} board as a visual reference for consistent depiction across all generations.\" ` +\n `Bottom-right tags: STYLE · Modern · Realistic · Cinematic. Style: photorealistic, no illustration. 8K, fine grain, cinematic color grading.`\n\nconst subj = (ctx: BoardPromptContext, fallback: string) =>\n ctx.description?.trim() ? ctx.description.trim() : fallback\n\n// ── Character ────────────────────────────────────────────────────────────\nconst characterFullBoard = (ctx: BoardPromptContext): string =>\n `Create a single high-resolution, densely packed character reference sheet titled \"CHARACTER BOARD\" ` +\n `using the attached photo as the single source of truth for face, hair, eyes, skin tone and body proportions ` +\n `of ${subj(ctx, \"the attached person\")}. The same person appears in every panel — same age, same features. ${ANTI_RIGID} ` +\n `Include a large hero portrait + metadata block: NAME · AGE · HEIGHT · BUILD · HAIR · EYES · FEATURES · OUTFIT · CHARACTER · MOOD. ` +\n `Six panels: VIEWS (front · 3/4 · side · back) · EXPRESSIONS (5 headshots) · DETAILS (face/eyes, hand, outfit macro) · ` +\n `OUTFIT FLAT-LAYS (5 isolated product shots) · LIGHTING/MOOD (4 lighting setups) · ${PALETTE} ${CAPTION(\"character\")}`\n\n// ── Location ─────────────────────────────────────────────────────────────\nconst locationFullBoard = (ctx: BoardPromptContext): string =>\n `Create a single high-resolution, densely packed location reference sheet titled \"LOCATION BOARD\" ` +\n `using the attached photo as the single source of truth for architecture, atmosphere, lighting, materials and color ` +\n `of ${subj(ctx, \"the attached location\")}. The space is identical across every panel — same place, materials, era. ${ANTI_RIGID} ` +\n `Include a hero establishing shot + metadata block: NAME · TYPE · ERA · SCALE · ARCHITECTURE · MATERIALS · ATMOSPHERE · DEFAULT TIME · DEFAULT WEATHER · PURPOSE. ` +\n `Six panels: VIEWS (wide · mid · tight · alt · overhead) · TIME OF DAY (dawn · noon · dusk · night) · DETAILS (material, architectural) · ` +\n `SET DRESSING / PROPS (5 studies) · WEATHER/MOOD (clear · overcast · rain · fog) · ${PALETTE} ${CAPTION(\"location\")}`\n\n// ── Object ───────────────────────────────────────────────────────────────\nconst objectFullBoard = (ctx: BoardPromptContext): string =>\n `Create a single high-resolution, densely packed object reference sheet titled \"OBJECT BOARD\" ` +\n `using the attached photo as the single source of truth for shape, materials, finish and proportions ` +\n `of ${subj(ctx, \"the attached object\")}. The object is identical across every panel. ${ANTI_RIGID} ` +\n `Include a hero shot + metadata block: NAME · TYPE · SCALE · MATERIALS · FINISH · KEY FEATURES · FUNCTION · MOOD. ` +\n `Six panels: VIEWS (front · 3/4 · side · back · top) · MATERIALS (close studies) · DETAILS (key part macros) · ` +\n `VARIATIONS (color/finish options) · LIGHTING/MOOD (4 setups) · ${PALETTE} ${CAPTION(\"object\")}`\n\nconst t = (entityKind: BoardEntityKind, slug: string, label: string, build: BoardTemplate[\"build\"]): BoardTemplate =>\n ({ id: `${entityKind}/${slug}`, entityKind, label, build })\n\nexport const REFERENCE_BOARD_TEMPLATES: readonly BoardTemplate[] = [\n t(\"character\", \"full-board\", \"Full Board — hero + 6 panels + palette\", characterFullBoard),\n t(\"location\", \"full-board\", \"Full Board — hero + 6 panels + palette\", locationFullBoard),\n t(\"object\", \"full-board\", \"Full Board — hero + 6 panels + palette\", objectFullBoard),\n]\n\nexport function listBoardTemplates(kind: BoardEntityKind): BoardTemplate[] {\n return REFERENCE_BOARD_TEMPLATES.filter((x) => x.entityKind === kind)\n}\n\nexport function buildBoardPrompt(templateId: string, ctx: BoardPromptContext): string {\n const tpl = REFERENCE_BOARD_TEMPLATES.find((x) => x.id === templateId)\n if (!tpl) throw new Error(`Unknown reference-board template: ${templateId}`)\n return tpl.build(ctx)\n}\n","/**\n * Models-tab data source: maps each catalog model to the node it creates\n * (`modelToNodeTarget`) and groups node-creatable models into product lines\n * (`buildModelTree`). Consumed by the add-node popup's Models tab. Pure — derives\n * everything from `MODEL_CATALOG` + the provider enums, so models added to the\n * catalog/enums flow through automatically.\n */\nimport { MODEL_CATALOG, type ModelKind, type ModelMode } from \"./model-catalog.js\"\nimport {\n IMAGE_GEN_PROVIDERS, VIDEO_GEN_PROVIDERS, IMAGE_TO_VIDEO_PROVIDERS, TEXT_TO_VIDEO_PROVIDERS,\n UPSCALE_IMAGE_PROVIDERS, VIDEO_UPSCALE_PROVIDERS, MODIFY_IMAGE_PROVIDERS, IMAGE_EDIT_PROVIDERS,\n VIDEO_TO_VIDEO_PROVIDERS, EXTEND_VIDEO_PROVIDERS, MOTION_TRANSFER_PROVIDERS, LIP_SYNC_PROVIDERS,\n FACE_SWAP_PROVIDERS, TTS_PROVIDERS, TEXT_TO_AUDIO_PROVIDERS, TRANSCRIBE_PROVIDERS, MUSIC_PROVIDERS,\n} from \"./model-constants.js\"\n\nexport interface ModelNodeTarget {\n nodeType: string\n field?: \"provider\" | \"model\"\n value?: string\n}\nexport interface ModelTreeVariant extends ModelNodeTarget {\n id: string\n label: string\n kind: ModelKind\n}\nexport interface ModelTreeLine {\n series: string\n family: string\n kind: ModelKind\n models: ModelTreeVariant[]\n}\n\n// A model id that is a valid provider-enum value gets a node + provider preset.\nconst ENUM_TARGETS: ReadonlyArray<readonly [readonly string[], string]> = [\n [IMAGE_GEN_PROVIDERS, \"generate-image\"],\n [VIDEO_GEN_PROVIDERS, \"generate-video\"],\n [IMAGE_TO_VIDEO_PROVIDERS, \"generate-video\"],\n [TEXT_TO_VIDEO_PROVIDERS, \"generate-video\"],\n [UPSCALE_IMAGE_PROVIDERS, \"upscale-image\"],\n [VIDEO_UPSCALE_PROVIDERS, \"video-upscale\"],\n [MODIFY_IMAGE_PROVIDERS, \"modify-image\"],\n [IMAGE_EDIT_PROVIDERS, \"modify-image\"],\n [VIDEO_TO_VIDEO_PROVIDERS, \"video-to-video\"],\n [EXTEND_VIDEO_PROVIDERS, \"extend-video\"],\n [MOTION_TRANSFER_PROVIDERS, \"motion-transfer\"],\n [LIP_SYNC_PROVIDERS, \"lip-sync\"],\n [FACE_SWAP_PROVIDERS, \"face-swap\"],\n [TTS_PROVIDERS, \"text-to-speech\"],\n [TEXT_TO_AUDIO_PROVIDERS, \"text-to-audio\"],\n [TRANSCRIBE_PROVIDERS, \"transcribe\"],\n [MUSIC_PROVIDERS, \"suno-generate\"],\n]\n\n// Fallback by the catalog's own `modes`, for models whose id is NOT a provider-enum\n// value — single-provider utility nodes (voice-design, dubbing, …) and catalog models\n// that no node exposes as a provider option. These create a bare node of the right\n// type (no provider preset — the user picks the model inside the node).\nconst MODE_TO_NODE: Readonly<Partial<Record<ModelMode, string>>> = {\n \"t2i\": \"generate-image\", \"i2i\": \"modify-image\", \"edit\": \"modify-image\", \"remove-bg\": \"modify-image\",\n \"t2v\": \"generate-video\", \"i2v\": \"generate-video\", \"v2v\": \"video-to-video\", \"extend\": \"extend-video\",\n \"upscale\": \"upscale-image\", \"video-upscale\": \"video-upscale\", \"motion-transfer\": \"motion-transfer\",\n \"lip-sync\": \"lip-sync\", \"tts\": \"text-to-speech\", \"sfx\": \"text-to-audio\",\n \"music\": \"suno-generate\", \"voice-design\": \"voice-design\", \"voice-changer\": \"voice-changer\",\n \"isolation\": \"audio-isolation\", \"dubbing\": \"dubbing\", \"forced-alignment\": \"forced-alignment\", \"stt\": \"transcribe\",\n \"video-analysis\": \"video-analysis\",\n}\n\nexport function modelToNodeTarget(modelId: string): ModelNodeTarget | null {\n const entry = MODEL_CATALOG[modelId]\n if (!entry) return null\n // Resolve the target node: a valid provider-enum value wins, else the catalog's modes.\n const enumMatch = ENUM_TARGETS.find(([providers]) => providers.includes(modelId))\n const nodeType = enumMatch?.[1] ?? entry.modes.map((m) => MODE_TO_NODE[m]).find(Boolean)\n if (!nodeType) return null\n // suno-generate stores its model in `data.model` (a V-code carried on the catalog\n // entry as `dataValue`), not as a `provider` id. Every other node takes a `provider`\n // preset when the id is a valid enum value, and a bare node otherwise.\n if (nodeType === \"suno-generate\") {\n return entry.dataValue ? { nodeType, field: \"model\", value: entry.dataValue } : { nodeType }\n }\n return enumMatch ? { nodeType, field: \"provider\", value: modelId } : { nodeType }\n}\n\n/**\n * Flat, query-filtered model variants for the add-node search. The single source\n * of truth shared by the Models tab/category browser and every tab's search\n * (image/video/audio narrow by `kind`; models/all/common pass no kind). Filters\n * by label/id substring; a blank query returns `[]`. Derived from\n * `buildModelTree`, so only node-creatable models appear and new catalog entries\n * flow through automatically.\n */\n// MODEL_CATALOG + the provider enums are static module constants, so the tree\n// never changes at runtime — build it once and reuse for every search keystroke.\nlet _modelTree: ModelTreeLine[] | null = null\nfunction getModelTree(): ModelTreeLine[] {\n return (_modelTree ??= buildModelTree())\n}\n\nexport function searchModelVariants(query: string, kind?: ModelKind): ModelTreeVariant[] {\n const q = query.trim().toLowerCase()\n if (!q) return []\n return getModelTree()\n .flatMap((l) => l.models)\n .filter((m) => (!kind || m.kind === kind) && (m.label.toLowerCase().includes(q) || m.id.toLowerCase().includes(q)))\n}\n\nexport function buildModelTree(): ModelTreeLine[] {\n const bySeries = new Map<string, ModelTreeLine>()\n for (const entry of Object.values(MODEL_CATALOG)) {\n const target = modelToNodeTarget(entry.id)\n if (!target || !entry.series) continue\n let line = bySeries.get(entry.series)\n if (!line) {\n line = { series: entry.series, family: entry.family, kind: entry.kind, models: [] }\n bySeries.set(entry.series, line)\n }\n line.models.push({ id: entry.id, label: entry.label, kind: entry.kind, ...target })\n }\n return [...bySeries.values()].sort((a, b) => a.series.localeCompare(b.series))\n}\n","/**\n * Audio FX node — preset id union (single source of truth).\n *\n * Shared so the backend Zod route enum, the frontend config dropdown, and the\n * `AudioFxData` node type can't drift. The per-preset FFmpeg filter chains\n * (IR DUR/SHAPE, delay/EQ knobs) live in the backend provider's PRESET_CHAINS\n * map — this file only fixes the id set + their human labels.\n *\n * Reverb presets are named by ON-SCREEN SCENARIO (where the voice is happening\n * in the scene) rather than abstract size, so a creator picking \"Church\" or\n * \"Car\" gets a believable space for that shot.\n */\n\nexport const AUDIO_FX_PRESETS = [\n // — reverb / spaces (afir + inline-synth IR), ordered small → large —\n \"room\", // ordinary indoor room — bedroom / office dialogue\n \"bathroom\", // small, bright, tiled — hard early reflections\n \"car\", // tight, very damped cabin\n \"hall\", // lobby / corridor / large room\n \"concert-hall\", // big, lush, musical tail\n \"church\", // cathedral — long, dark, reverberant\n \"cave\", // dark, diffuse, long\n \"arena\", // stadium / PA — huge, bright tail\n \"outdoor\", // open air — almost dry, faint early reflections\n // — character / non-reverb —\n \"telephone\", // band-limited phone line\n \"megaphone\", // PA / bullhorn — mid-forward + light grit\n \"echo\", // discrete echo / slap-back\n \"custom\", // manual: reverb wet · delay · EQ\n] as const\n\nexport type AudioFxPreset = (typeof AUDIO_FX_PRESETS)[number]\n\nexport const AUDIO_FX_PRESET_SET: ReadonlySet<string> = new Set(AUDIO_FX_PRESETS)\n\n/** Display labels for the config dropdown. */\nexport const AUDIO_FX_PRESET_LABELS: Record<AudioFxPreset, string> = {\n room: \"Room (indoor)\",\n bathroom: \"Bathroom\",\n car: \"Car interior\",\n hall: \"Hall / Lobby\",\n \"concert-hall\": \"Concert Hall\",\n church: \"Church\",\n cave: \"Cave\",\n arena: \"Arena / Stadium\",\n outdoor: \"Outdoor (open air)\",\n telephone: \"Telephone\",\n megaphone: \"Megaphone / PA\",\n echo: \"Echo / Slap-back\",\n custom: \"Custom\",\n}\n\n/** Presets that apply convolution reverb (afir + inline-synth IR). */\nexport const AUDIO_FX_REVERB_PRESETS: ReadonlySet<AudioFxPreset> = new Set<AudioFxPreset>([\n \"room\",\n \"bathroom\",\n \"car\",\n \"hall\",\n \"concert-hall\",\n \"church\",\n \"cave\",\n \"arena\",\n \"outdoor\",\n])\n","/**\n * Canonical list of font display names supported by the Remotion renderer.\n *\n * Single source of truth shared by:\n * - the backend Zod schemas (`z.enum(SUPPORTED_FONT_NAMES)`), which CANNOT\n * import `@nodaro/remotion` (its font-registry pulls the render runtime +\n * `@remotion/google-fonts` side-effects into a validation path), and\n * - `packages/remotion/src/lib/font-registry.ts`, which loads each face and\n * is kept in lock-step with this tuple by a compile-time `satisfies` guard.\n *\n * Order/spelling MUST match the keys of the `fonts` object in font-registry.ts.\n */\nexport const SUPPORTED_FONT_NAMES = [\n \"Inter\",\n \"Roboto\",\n \"Open Sans\",\n \"Montserrat\",\n \"Poppins\",\n \"Raleway\",\n \"Nunito\",\n \"Lato\",\n \"Playfair Display\",\n \"Merriweather\",\n \"Lora\",\n \"EB Garamond\",\n \"Bebas Neue\",\n \"Oswald\",\n \"Anton\",\n \"Dancing Script\",\n \"Pacifico\",\n \"Caveat\",\n \"Roboto Mono\",\n \"Fira Code\",\n \"Rubik\",\n \"Heebo\",\n \"Cairo\",\n \"Tajawal\",\n] as const\n\nexport type SupportedFontName = (typeof SUPPORTED_FONT_NAMES)[number]\n","/**\n * Entity node types that expose a plain `image` source handle (emitting the\n * portrait URL) in addition to their identity `*Ref` handle. When a wire leaves\n * the `image` handle, the entity is treated as a plain image PRODUCER\n * (substituted to \"upload-image\") so it reaches image inputs and lists exactly\n * like generate-image / upload-image, while the `*Ref` handle stays identity.\n *\n * SINGLE SOURCE OF TRUTH — consumed by:\n * - frontend connection validation (drop validator, drag-glow, popover),\n * - frontend run assemblers (execute-node, video-prompt-assembly),\n * - frontend config-panel reference preview builders,\n * - backend payload-builder identity-injection guards.\n * Add future per-handle output-type remaps HERE so every surface inherits them.\n */\nexport const ENTITY_IMAGE_HANDLE_TYPES: ReadonlySet<string> = new Set([\n \"character\",\n \"location\",\n \"object\",\n \"creature\",\n])\n\n/**\n * The effective output TYPE a given source handle emits. Returns the raw node\n * type for every `(type, handle)` pair EXCEPT an entity `image` handle, which\n * resolves to `\"upload-image\"` (a plain image producer). Pure — safe for both\n * frontend and backend.\n */\nexport function resolveEffectiveSourceType(\n rawSourceType: string | undefined | null,\n sourceHandleId: string | undefined | null,\n): string {\n if (sourceHandleId === \"image\" && ENTITY_IMAGE_HANDLE_TYPES.has(rawSourceType ?? \"\")) {\n return \"upload-image\"\n }\n return rawSourceType ?? \"\"\n}\n","// packages/shared/src/reference-roles.ts\nimport { DEFAULT_LABEL_BY_SOURCE, type ReferenceSource } from \"./types.js\"\n\n/**\n * Per-source ORDERED preset role ids (most-useful first) for the editor's role\n * menu. The single source of truth for the curated vocabulary — every menu and\n * the resolver read from here. `Custom…` (free-form) is added by the UI, not\n * listed here. Each list MUST contain the source's `DEFAULT_LABEL_BY_SOURCE`\n * value (guarded by reference-roles.test.ts).\n */\nexport const REFERENCE_ROLE_PRESETS: Record<ReferenceSource, readonly string[]> = {\n \"wired-character\": [\"person\", \"face\", \"clothes\", \"hair\", \"pose\", \"expression\", \"style\"],\n \"wired-face\": [\"face\", \"person\", \"expression\", \"style\"],\n \"wired-location\": [\"background\", \"atmosphere\", \"as-is\", \"empty background\", \"layout\", \"lighting\", \"style\"],\n \"wired-object\": [\"object\", \"shape\", \"material\", \"color\", \"texture\", \"style\"],\n \"wired-creature\": [\"creature\", \"anatomy\", \"markings\", \"pose\", \"color\", \"style\"],\n \"wired-image\": [\"object\", \"person\", \"face\", \"clothes\", \"background\", \"style\", \"pose\", \"texture\"],\n \"manual\": [\"object\", \"person\", \"face\", \"clothes\", \"background\", \"style\", \"pose\", \"texture\"],\n}\n\n/** Canonical default role for a source — the value the editor pre-fills and the\n * resolver falls back to. Aliased to `DEFAULT_LABEL_BY_SOURCE` so the two never\n * drift. */\nexport function defaultRoleForSource(source: ReferenceSource): string {\n return DEFAULT_LABEL_BY_SOURCE[source]\n}\n\n/**\n * Render the inline reference phrase. `binding` is the caller-formatted slot\n * string: `\"reference image A\"` (image, lettered) or `\"@image_3\"` (video).\n * Most roles are nouns and slot into the default template; the two non-noun\n * specials get a hand-tuned phrasing so the prompt reads naturally.\n */\nexport function roleToPhrase(role: string, binding: string): string {\n const r = role.trim()\n if (!r) return binding\n switch (r) {\n case \"as-is\":\n return `${binding}, used as-is`\n case \"empty background\":\n return `the background from ${binding} (without its foreground objects)`\n default:\n return `the ${r} from ${binding}`\n }\n}\n\n/**\n * Map a location role SLUG — as it appears in a `@location:N:<slug>` mention\n * token (lowercase, dash-joined, no spaces) — back to its canonical phrase key\n * so `roleToPhrase` matches the non-noun specials. Only the multi-word\n * `wired-location` presets need remapping (`empty-background` → `empty\n * background`); single-token roles and `as-is` (whose phrase key keeps the\n * hyphen) and free-form custom slugs pass through unchanged.\n *\n * Data-driven from `REFERENCE_ROLE_PRESETS[\"wired-location\"]` (the single source\n * of truth for the location vocabulary): a preset whose space→dash slug equals\n * `slug` maps back to the preset's phrase form, so a future multi-word preset is\n * handled with no extra wiring. Mention tokens are slug-form (the grammar\n * segment is `[a-z][a-z0-9-]*`), so the role is stored verbatim on the token and\n * normalized HERE at the consumption points — the location mention resolver\n * (before `roleToPhrase`) and the location role pill (display label). The\n * character side never needs this: character role slugs are single tokens that\n * already equal their phrase key.\n */\nexport function normalizeRoleSlug(slug: string): string {\n const s = slug.trim()\n if (!s) return s\n for (const preset of REFERENCE_ROLE_PRESETS[\"wired-location\"]) {\n if (preset.toLowerCase().replace(/\\s+/g, \"-\") === s) return preset\n }\n return s\n}\n\n/**\n * Role for a FIRST-SIGHT character extra-ref in HYBRID assembly. The `segment`\n * is the role when it is a curated preset for `source`; otherwise the source\n * default. This mirrors the segment→role preset gate the mention-hybrid paths\n * use, minus their custom-role-survival relaxation (an extra has no parsed\n * `usageMode == null` signal to tell a role from a variant pick).\n *\n * Shared by BOTH the image (`renderExtraRefsHybrid` in `prompt-builder.ts`) and\n * video (`resolveVideoReferenceCore` extras first-sight in\n * `video-reference-resolver.ts`) resolvers — and, as of the Reference Roles\n * deferred-follow-up, they share the HELPER **and** its INPUT, so they are\n * fully converged:\n * - image passes the COALESCED `defaultUsageMode`\n * (`usageMode` → char-node default → \"identical\", folded by\n * `expandExtraRefsToConnectedReferences`).\n * - video passes its COALESCED `effectiveMode`\n * (`ex.usageMode` → char-node default (`lookupCharacterBySlug`) →\n * \"identical\") — the identical resolution chain, already computed for the\n * legacy directive path.\n * Both are always defined for a real character extra, so no `variantSlug`\n * fallback is needed on either side. A character whose node default is\n * Face/Pose/Style now resolves an un-overridden extra to that default on BOTH\n * image and video (and consistently with the video legacy path). The single\n * source of truth for the coalescing is the per-ref override → char-node\n * default → \"identical\" chain, applied at both call sites.\n */\nexport function firstSightExtraRole(\n segment: string | null | undefined,\n source: ReferenceSource,\n): string {\n const s = (segment ?? \"\").trim()\n return s && REFERENCE_ROLE_PRESETS[source].includes(s) ? s : defaultRoleForSource(source)\n}\n\n/**\n * The effective default role for a wired entity, given the node's explicit\n * hybrid `defaultRole` and its legacy `defaultUsageMode`. Single source of truth\n * for the node-default precedence, read at every hybrid resolver site (image +\n * video × extras / canonical / mention):\n *\n * 1. `defaultRole` (the hybrid dropdown pick) — used VERBATIM when non-blank,\n * so a Custom role like `earrings` survives (mirrors the pill's Custom\n * relaxation) and beats any legacy `defaultUsageMode`.\n * 2. else `firstSightExtraRole(defaultUsageMode, source)` — the back-compat\n * mapping (`face`/`pose`/`style` pass through; every other usage mode, and\n * an absent one, collapse to the source default, e.g. `\"person\"`).\n *\n * A per-mention token role (the pill / autocomplete) still wins over this at the\n * mention call sites; this is only the NODE-level fallback.\n */\nexport function resolveDefaultRole(\n defaultRole: string | null | undefined,\n defaultUsageMode: string | null | undefined,\n source: ReferenceSource,\n): string {\n const explicit = defaultRole?.trim()\n if (explicit) return explicit\n return firstSightExtraRole(defaultUsageMode, source)\n}\n\n/**\n * Sanitize a free-form Custom role into a character-variant-slug-safe token.\n * Hoisted to shared (was `config-panels/prompt-editor/character-ref-roles.ts`)\n * so BOTH the mention pill and the character node's role dropdown share one\n * source of truth. Grammar is `[a-z][a-z0-9-]*` (the `variantSlug` token slot):\n * lower-case, dash-join whitespace, drop out-of-grammar chars, force a leading\n * letter, cap at 32, collapse dash runs, drop a trailing dash — keeping the\n * emitted role re-parseable and matching `characterMentionSlug`'s slugification.\n */\nexport function sanitizeRole(raw: string): string {\n return raw\n .trim()\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/[^a-z0-9-]/g, \"\")\n .replace(/^[^a-z]+/, \"\") // grammar requires a leading [a-z]\n .slice(0, 32)\n .replace(/-+/g, \"-\") // collapse dash runs (matches characterMentionSlug)\n .replace(/-$/, \"\") // drop a trailing dash (incl. one left by the 32-cap)\n}\n","/**\n * Video-analysis node — shared data contract.\n *\n * Single source of truth for the video-analysis node: the backend worker, the\n * frontend, and a future generator all import from here. Two schema layers:\n * - `windowAnalysisSchema` — what the LLM emits per analysis window\n * (strict-JSON footer). `scenes` has NO min (a quiet window returning zero\n * scenes is a VALID result). Model-emitted `oversized`/`slotRefs` are\n * STRIPPED here — they are validator-computed later (z.object drops unknown\n * keys by default).\n * - `videoAnalysisResultSchema` — the merged, validator-computed result across\n * all windows; requires >=1 scene overall.\n *\n * Entity slots are referenced in scene `visual` text via `{slot:<id>}` tokens\n * (`SLOT_TOKEN_RE`) — a grammar distinct from `NODE_REF_PATTERN` and the\n * `{image:N}` reference tokens. Unresolved tokens UNWRAP to their literal id\n * text, never delete (spec invariant), so a downstream prompt never carries a\n * dangling `{slot:…}` placeholder.\n */\nimport { z } from \"zod\"\n\nexport const VIDEO_ANALYSIS_MAX_SCENE_SEC = 8\nexport const VIDEO_ANALYSIS_ENTITY_SOURCES = [\"wired-character\", \"wired-object\", \"wired-location\", \"wired-creature\"] as const\nexport type VideoAnalysisEntitySource = (typeof VIDEO_ANALYSIS_ENTITY_SOURCES)[number]\n/** Matches {slot:<id>} tokens. Distinct from NODE_REF_PATTERN / {image:N} grammars. */\nexport const SLOT_TOKEN_RE = /\\{slot:([a-z0-9-]+)\\}/g\n\nexport const entitySlotSchema = z.object({\n slotId: z.string().min(1).regex(/^[a-z0-9-]+$/),\n label: z.string().min(1),\n source: z.enum(VIDEO_ANALYSIS_ENTITY_SOURCES),\n role: z.string().min(1),\n description: z.string().min(1),\n})\nexport type EntitySlot = z.infer<typeof entitySlotSchema>\n\nconst audioSchema = z.object({\n mode: z.enum([\"speech\", \"music\", \"sfx\", \"silence\"]),\n content: z.string(), // speech: verbatim quote; music/sfx: gen-ready description; silence: \"\" allowed\n voice: z.string().optional(),\n})\n\nconst windowSceneBase = z.object({\n startSec: z.number().min(0),\n endSec: z.number().min(0),\n label: z.string().min(1),\n shotType: z.string().min(1),\n camera: z.string(),\n visual: z.string().min(1),\n transitionOut: z.enum([\"cut\", \"fade\", \"wipe\", \"whip\"]).optional(),\n audio: audioSchema,\n})\n// .strip() (default) drops model-emitted oversized/slotRefs — validator-computed only.\nconst windowSceneSchema = windowSceneBase.refine((s) => s.endSec > s.startSec, { message: \"endSec must be > startSec\" })\nexport type WindowScene = z.infer<typeof windowSceneSchema>\n\n/** What the MODEL emits per window (strict-JSON footer schema). scenes has NO min. */\nexport const windowAnalysisSchema = z.object({\n language: z.string().optional(),\n slots: z.array(entitySlotSchema),\n scenes: z.array(windowSceneSchema),\n})\nexport type WindowAnalysis = z.infer<typeof windowAnalysisSchema>\n\nexport const analyzedSceneSchema = windowSceneBase.extend({\n sceneNumber: z.number().int().min(1),\n visualResolved: z.string().min(1),\n oversized: z.boolean().optional(),\n slotRefs: z.array(z.string()),\n}).refine((s) => s.endSec > s.startSec, { message: \"endSec must be > startSec\" })\nexport type AnalyzedScene = z.infer<typeof analyzedSceneSchema>\n\nexport const videoAnalysisResultSchema = z.object({\n meta: z.object({\n durationSec: z.number().positive(),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n aspectRatio: z.string(),\n title: z.string().optional(),\n language: z.string().optional(),\n }),\n slots: z.array(entitySlotSchema),\n scenes: z.array(analyzedSceneSchema).min(1),\n})\nexport type VideoAnalysisResult = z.infer<typeof videoAnalysisResultSchema>\n\nexport function deriveSlotRefs(visual: string): string[] {\n const out: string[] = []\n for (const m of visual.matchAll(SLOT_TOKEN_RE)) if (!out.includes(m[1])) out.push(m[1])\n return out\n}\n\nexport function rewriteSlotTokens(visual: string, renames: Record<string, string>): string {\n return visual.replace(SLOT_TOKEN_RE, (whole, id: string) => (renames[id] ? `{slot:${renames[id]}}` : whole))\n}\n\n/** Unresolved tokens unwrap to their literal id text — never deleted (spec invariant). */\nexport function unwrapUnresolvedTokens(text: string, validIds: Set<string>): { text: string; unresolved: string[] } {\n const unresolved: string[] = []\n const out = text.replace(SLOT_TOKEN_RE, (whole, id: string) => {\n if (validIds.has(id)) return whole\n if (!unresolved.includes(id)) unresolved.push(id)\n return id\n })\n return { text: out, unresolved }\n}\n\n/** Substitute {slot:x}: castMap binding wins, else the slot's description, else literal id. */\nexport function renderAnalyzedScene(scene: { visual: string }, slots: EntitySlot[], castMap?: Record<string, string>): string {\n const byId = new Map(slots.map((s) => [s.slotId, s]))\n return scene.visual.replace(SLOT_TOKEN_RE, (_whole, id: string) => castMap?.[id] ?? byId.get(id)?.description ?? id)\n}\n\nexport function isOversizedScene(startSec: number, endSec: number): boolean {\n return endSec - startSec > VIDEO_ANALYSIS_MAX_SCENE_SEC\n}\n\nconst STANDARD_RATIOS: Array<[string, number]> = [\n [\"16:9\", 16 / 9], [\"9:16\", 9 / 16], [\"1:1\", 1], [\"4:3\", 4 / 3], [\"3:4\", 3 / 4], [\"21:9\", 21 / 9],\n]\nexport function aspectRatioFromDims(w: number, h: number): string {\n const r = w / h\n for (const [label, v] of STANDARD_RATIOS) if (Math.abs(r - v) / v < 0.03) return label\n const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b))\n const g = gcd(Math.round(w), Math.round(h))\n return `${Math.round(w) / g}:${Math.round(h) / g}`\n}\n","/**\n * 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 measured-rate constants and the $-derived `videoAnalysisBucketCredits`\n * formula live in `backend/src/lib/pricing/video-analysis-cost.ts` (core,\n * not ee/ — the MCP tool description builder needs them regardless of\n * edition). They were moved out of this package (published Apache-2.0 on\n * npm — an irrevocable grant) per the 2026-07-06 public-flip IP audit, S5.\n *\n * `VIDEO_ANALYSIS_BUCKET_CREDITS` below is the precomputed OUTPUT of that\n * backend 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 * A backend test (`video-analysis-cost.test.ts`) cross-checks this table\n * against the live formula so it can't silently drift.\n */\n\nexport const VIDEO_ANALYSIS_DURATION_BUCKETS = [60, 180, 360, 600] as const\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. */\nexport const VIDEO_ANALYSIS_DURATION_TOLERANCE_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 backend's\n * `videoAnalysisBucketCredits` formula, not a formula itself. Regenerate by\n * running that function for every `VIDEO_ANALYSIS_LLM_MODELS` × duration\n * bucket combination whenever the underlying rate/token constants change\n * (backend test guards drift). Keep in sync with\n * `docs/nodes/processing-video/video-analysis.md`.\n */\nexport const VIDEO_ANALYSIS_BUCKET_CREDITS: Record<string, number> = {\n \"video-analysis:gemini-3-flash:60s\": 1,\n \"video-analysis:gemini-3-flash:180s\": 1,\n \"video-analysis:gemini-3-flash:360s\": 2,\n \"video-analysis:gemini-3-flash:600s\": 3,\n \"video-analysis:gemini-3.1-pro:60s\": 2,\n \"video-analysis:gemini-3.1-pro:180s\": 3,\n \"video-analysis:gemini-3.1-pro:360s\": 7,\n \"video-analysis:gemini-3.1-pro:600s\": 11,\n}\n\nexport function pickVideoAnalysisBucket(durationSec: number): number {\n for (const b of VIDEO_ANALYSIS_DURATION_BUCKETS) if (durationSec <= b) 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:${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"]}
|