@nodaro/shared 3.64.0 → 3.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/dist/{chunk-J6B7J73J.cjs → chunk-23IKLMRL.cjs} +49 -49
  2. package/dist/{chunk-J6B7J73J.cjs.map → chunk-23IKLMRL.cjs.map} +1 -1
  3. package/dist/chunk-27HA6YOL.cjs +377 -0
  4. package/dist/chunk-27HA6YOL.cjs.map +1 -0
  5. package/dist/{chunk-OOZW2MM6.cjs → chunk-37ZSFS6A.cjs} +9 -9
  6. package/dist/{chunk-OOZW2MM6.cjs.map → chunk-37ZSFS6A.cjs.map} +1 -1
  7. package/dist/{chunk-AZNZ5WNZ.cjs → chunk-3L7GMQ4M.cjs} +142 -45
  8. package/dist/chunk-3L7GMQ4M.cjs.map +1 -0
  9. package/dist/{chunk-SXHHLZ22.js → chunk-3QJ3UR5Z.js} +9 -9
  10. package/dist/{chunk-SXHHLZ22.js.map → chunk-3QJ3UR5Z.js.map} +1 -1
  11. package/dist/chunk-3YWZ5SOZ.js +164 -0
  12. package/dist/chunk-3YWZ5SOZ.js.map +1 -0
  13. package/dist/{chunk-TTGZ2L3O.js → chunk-5GG4CG4Y.js} +3 -3
  14. package/dist/{chunk-TTGZ2L3O.js.map → chunk-5GG4CG4Y.js.map} +1 -1
  15. package/dist/{chunk-3KTWYYCN.js → chunk-5IZHECUP.js} +3 -3
  16. package/dist/{chunk-3KTWYYCN.js.map → chunk-5IZHECUP.js.map} +1 -1
  17. package/dist/{chunk-Q2Y4JHF7.js → chunk-5J2LIQYU.js} +5 -5
  18. package/dist/{chunk-Q2Y4JHF7.js.map → chunk-5J2LIQYU.js.map} +1 -1
  19. package/dist/{chunk-SHH2T4CR.js → chunk-5LWYX4GV.js} +3 -3
  20. package/dist/{chunk-SHH2T4CR.js.map → chunk-5LWYX4GV.js.map} +1 -1
  21. package/dist/{chunk-7AJGUI7L.cjs → chunk-5NVGKXJV.cjs} +34 -17
  22. package/dist/chunk-5NVGKXJV.cjs.map +1 -0
  23. package/dist/{chunk-D4KWNDPH.cjs → chunk-66QSUUB4.cjs} +12 -12
  24. package/dist/{chunk-D4KWNDPH.cjs.map → chunk-66QSUUB4.cjs.map} +1 -1
  25. package/dist/{chunk-KHH54GRP.cjs → chunk-6ET3KDO4.cjs} +15 -338
  26. package/dist/chunk-6ET3KDO4.cjs.map +1 -0
  27. package/dist/{chunk-ZI3QDUHO.js → chunk-AT53ZQUC.js} +3 -3
  28. package/dist/{chunk-ZI3QDUHO.js.map → chunk-AT53ZQUC.js.map} +1 -1
  29. package/dist/chunk-BMDOPJBP.cjs +185 -0
  30. package/dist/chunk-BMDOPJBP.cjs.map +1 -0
  31. package/dist/{chunk-PJJAZQVZ.js → chunk-BNR5FKL5.js} +3 -3
  32. package/dist/{chunk-PJJAZQVZ.js.map → chunk-BNR5FKL5.js.map} +1 -1
  33. package/dist/{chunk-5OBTGNUQ.cjs → chunk-E62W5I6A.cjs} +298 -2
  34. package/dist/chunk-E62W5I6A.cjs.map +1 -0
  35. package/dist/{chunk-GTWUS6MQ.cjs → chunk-EFYWV2V5.cjs} +61 -61
  36. package/dist/{chunk-GTWUS6MQ.cjs.map → chunk-EFYWV2V5.cjs.map} +1 -1
  37. package/dist/chunk-F6XIH3TZ.cjs +168 -0
  38. package/dist/chunk-F6XIH3TZ.cjs.map +1 -0
  39. package/dist/{chunk-NIAFR5EE.js → chunk-FGBGKBML.js} +32 -3
  40. package/dist/chunk-FGBGKBML.js.map +1 -0
  41. package/dist/{chunk-YQV53HRR.cjs → chunk-G2G7XGFU.cjs} +7 -7
  42. package/dist/{chunk-YQV53HRR.cjs.map → chunk-G2G7XGFU.cjs.map} +1 -1
  43. package/dist/{chunk-7KQ6W5DS.js → chunk-GF7ZA26H.js} +4 -4
  44. package/dist/{chunk-7KQ6W5DS.js.map → chunk-GF7ZA26H.js.map} +1 -1
  45. package/dist/{chunk-SPAHI7DY.cjs → chunk-GNLA5NTT.cjs} +4 -4
  46. package/dist/{chunk-SPAHI7DY.cjs.map → chunk-GNLA5NTT.cjs.map} +1 -1
  47. package/dist/{chunk-VPTA4Z7G.js → chunk-GTBW2KAY.js} +5 -5
  48. package/dist/{chunk-VPTA4Z7G.js.map → chunk-GTBW2KAY.js.map} +1 -1
  49. package/dist/{chunk-CHS2SIP6.cjs → chunk-HTDKEYMY.cjs} +90 -76
  50. package/dist/chunk-HTDKEYMY.cjs.map +1 -0
  51. package/dist/{chunk-EXEVT6D2.cjs → chunk-IWUW3YPM.cjs} +5 -5
  52. package/dist/{chunk-EXEVT6D2.cjs.map → chunk-IWUW3YPM.cjs.map} +1 -1
  53. package/dist/{chunk-ACZZHHFZ.cjs → chunk-JTYCJ5OL.cjs} +44 -22
  54. package/dist/chunk-JTYCJ5OL.cjs.map +1 -0
  55. package/dist/{chunk-HDPJNNMF.cjs → chunk-M5QY464F.cjs} +21 -21
  56. package/dist/{chunk-HDPJNNMF.cjs.map → chunk-M5QY464F.cjs.map} +1 -1
  57. package/dist/{chunk-DZ4IOP3Q.js → chunk-MVXZP6VB.js} +281 -3
  58. package/dist/chunk-MVXZP6VB.js.map +1 -0
  59. package/dist/{chunk-Y4GCJJPF.cjs → chunk-NYZQOIXJ.cjs} +35 -2
  60. package/dist/chunk-NYZQOIXJ.cjs.map +1 -0
  61. package/dist/{chunk-KB2SQAR3.js → chunk-OFQ6CU6S.js} +3 -3
  62. package/dist/{chunk-KB2SQAR3.js.map → chunk-OFQ6CU6S.js.map} +1 -1
  63. package/dist/{chunk-36VWLB4J.js → chunk-OXBU5AGH.js} +3 -3
  64. package/dist/{chunk-36VWLB4J.js.map → chunk-OXBU5AGH.js.map} +1 -1
  65. package/dist/{chunk-CHTZZRAL.cjs → chunk-OXTF4Y3P.cjs} +6 -6
  66. package/dist/{chunk-CHTZZRAL.cjs.map → chunk-OXTF4Y3P.cjs.map} +1 -1
  67. package/dist/{chunk-3AYM47GW.js → chunk-PAUWEWTY.js} +99 -9
  68. package/dist/chunk-PAUWEWTY.js.map +1 -0
  69. package/dist/{chunk-FHGRKQVZ.cjs → chunk-PGDR7CO3.cjs} +8 -8
  70. package/dist/{chunk-FHGRKQVZ.cjs.map → chunk-PGDR7CO3.cjs.map} +1 -1
  71. package/dist/{chunk-W6VJAUGM.cjs → chunk-PJAJCFLP.cjs} +94 -37
  72. package/dist/chunk-PJAJCFLP.cjs.map +1 -0
  73. package/dist/{chunk-IYSOVS7O.js → chunk-RVQW623D.js} +31 -13
  74. package/dist/chunk-RVQW623D.js.map +1 -0
  75. package/dist/{chunk-TPQJKS7D.js → chunk-SCDE676D.js} +21 -7
  76. package/dist/{chunk-CHS2SIP6.cjs.map → chunk-SCDE676D.js.map} +1 -1
  77. package/dist/chunk-SW5ZD7BO.js +143 -0
  78. package/dist/chunk-SW5ZD7BO.js.map +1 -0
  79. package/dist/{chunk-T2OVDF2M.cjs → chunk-T4GIHHXY.cjs} +6 -6
  80. package/dist/{chunk-T2OVDF2M.cjs.map → chunk-T4GIHHXY.cjs.map} +1 -1
  81. package/dist/{chunk-QYU7J5EQ.js → chunk-V6OXSXIX.js} +29 -18
  82. package/dist/chunk-V6OXSXIX.js.map +1 -0
  83. package/dist/{chunk-W7KHHNZR.js → chunk-VBP4DH37.js} +61 -9
  84. package/dist/chunk-VBP4DH37.js.map +1 -0
  85. package/dist/{chunk-67CMMTLN.cjs → chunk-WZG6GZIL.cjs} +4 -4
  86. package/dist/{chunk-67CMMTLN.cjs.map → chunk-WZG6GZIL.cjs.map} +1 -1
  87. package/dist/{chunk-O4RPXBDZ.cjs → chunk-X2YHKP4D.cjs} +8 -8
  88. package/dist/{chunk-O4RPXBDZ.cjs.map → chunk-X2YHKP4D.cjs.map} +1 -1
  89. package/dist/{chunk-OBOOHG3N.js → chunk-XEPKONJC.js} +3 -3
  90. package/dist/{chunk-OBOOHG3N.js.map → chunk-XEPKONJC.js.map} +1 -1
  91. package/dist/{chunk-O7RZRUMZ.js → chunk-XJWED257.js} +14 -309
  92. package/dist/chunk-XJWED257.js.map +1 -0
  93. package/dist/chunk-XSSLNINL.js +346 -0
  94. package/dist/chunk-XSSLNINL.js.map +1 -0
  95. package/dist/{chunk-4IUE2JB7.js → chunk-Z77M7Q2R.js} +3 -3
  96. package/dist/{chunk-4IUE2JB7.js.map → chunk-Z77M7Q2R.js.map} +1 -1
  97. package/dist/entries/apps.cjs +42 -42
  98. package/dist/entries/apps.js +7 -7
  99. package/dist/entries/captions.d.cts +1 -1
  100. package/dist/entries/captions.d.ts +1 -1
  101. package/dist/entries/credits.cjs +230 -214
  102. package/dist/entries/credits.d.cts +51 -14
  103. package/dist/entries/credits.d.ts +51 -14
  104. package/dist/entries/credits.js +10 -10
  105. package/dist/entries/entities.cjs +202 -193
  106. package/dist/entries/entities.d.cts +44 -9
  107. package/dist/entries/entities.d.ts +44 -9
  108. package/dist/entries/entities.js +2 -1
  109. package/dist/entries/llm-models.cjs +86 -62
  110. package/dist/entries/llm-models.d.cts +46 -15
  111. package/dist/entries/llm-models.d.ts +46 -15
  112. package/dist/entries/llm-models.js +2 -2
  113. package/dist/entries/media.cjs +79 -63
  114. package/dist/entries/media.d.cts +154 -1
  115. package/dist/entries/media.d.ts +154 -1
  116. package/dist/entries/media.js +1 -1
  117. package/dist/entries/model-catalog.cjs +175 -119
  118. package/dist/entries/model-catalog.d.cts +4 -54
  119. package/dist/entries/model-catalog.d.ts +4 -54
  120. package/dist/entries/model-catalog.js +4 -4
  121. package/dist/entries/models.cjs +503 -358
  122. package/dist/entries/models.d.cts +86 -7
  123. package/dist/entries/models.d.ts +86 -7
  124. package/dist/entries/models.js +6 -5
  125. package/dist/entries/nodes.cjs +212 -212
  126. package/dist/entries/nodes.d.cts +1 -1
  127. package/dist/entries/nodes.d.ts +1 -1
  128. package/dist/entries/nodes.js +8 -8
  129. package/dist/entries/pipeline.cjs +153 -153
  130. package/dist/entries/pipeline.d.cts +3 -3
  131. package/dist/entries/pipeline.d.ts +3 -3
  132. package/dist/entries/pipeline.js +3 -3
  133. package/dist/entries/social.cjs +177 -177
  134. package/dist/entries/social.js +2 -2
  135. package/dist/entries/ugc.cjs +71 -71
  136. package/dist/entries/ugc.js +4 -4
  137. package/dist/entries/video.cjs +174 -145
  138. package/dist/entries/video.d.cts +119 -2
  139. package/dist/entries/video.d.ts +119 -2
  140. package/dist/entries/video.js +7 -6
  141. package/dist/entries/workflow.d.cts +1 -1
  142. package/dist/entries/workflow.d.ts +1 -1
  143. package/dist/index.cjs +2086 -1793
  144. package/dist/index.d.cts +10 -9
  145. package/dist/index.d.ts +10 -9
  146. package/dist/index.js +24 -23
  147. package/dist/{model-catalog-Cf9fkEUp.d.ts → model-catalog-B-aQnUS8.d.cts} +186 -2
  148. package/dist/{model-catalog-Cf9fkEUp.d.cts → model-catalog-B-aQnUS8.d.ts} +186 -2
  149. package/dist/{model-constants-C_Nyft_i.d.cts → model-constants-BstsUup6.d.cts} +105 -6
  150. package/dist/{model-constants-BxjiWVQ9.d.ts → model-constants-DZ3tPGFO.d.ts} +105 -6
  151. package/dist/tts-capabilities-BJ4N8MIB.d.ts +133 -0
  152. package/dist/tts-capabilities-Cf_4nu1Z.d.cts +133 -0
  153. package/package.json +1 -1
  154. package/src/__tests__/dialogue-capabilities.test.ts +167 -6
  155. package/src/__tests__/extend-providers.test.ts +87 -0
  156. package/src/__tests__/flux-3-klein.test.ts +51 -3
  157. package/src/__tests__/image-run-limit.test.ts +96 -0
  158. package/src/__tests__/kling4-catalog.test.ts +1 -1
  159. package/src/__tests__/llm-models.test.ts +41 -4
  160. package/src/__tests__/seedream-5-5.test.ts +17 -0
  161. package/src/__tests__/speech-pricing.test.ts +62 -1
  162. package/src/__tests__/tts-capabilities.test.ts +160 -4
  163. package/src/__tests__/video-analysis-pricing.test.ts +13 -1
  164. package/src/__tests__/video-subjects.test.ts +209 -0
  165. package/src/__tests__/wired-character-names.test.ts +142 -0
  166. package/src/credit-estimators/index.ts +4 -0
  167. package/src/credit-estimators/speech.ts +57 -9
  168. package/src/credit-identifiers.ts +48 -13
  169. package/src/dialogue-capabilities.ts +220 -3
  170. package/src/dubbing-structure.ts +186 -0
  171. package/src/entries/entities.ts +2 -0
  172. package/src/entries/llm-models.ts +7 -0
  173. package/src/entries/media.ts +3 -1
  174. package/src/entries/model-catalog.ts +17 -0
  175. package/src/entries/models.ts +43 -0
  176. package/src/entries/video.ts +8 -1
  177. package/src/gemini-tts.ts +144 -0
  178. package/src/llm-models.ts +71 -21
  179. package/src/model-catalog.ts +283 -2
  180. package/src/model-constants.ts +167 -8
  181. package/src/tts-capabilities.ts +193 -1
  182. package/src/video-analysis-pricing.ts +11 -0
  183. package/src/video-character-refs.ts +165 -3
  184. package/src/wired-character-names.ts +134 -18
  185. package/src/wired-character-video-subjects.ts +63 -0
  186. package/dist/chunk-3AYM47GW.js.map +0 -1
  187. package/dist/chunk-5OBTGNUQ.cjs.map +0 -1
  188. package/dist/chunk-6YIV37V7.js +0 -31
  189. package/dist/chunk-6YIV37V7.js.map +0 -1
  190. package/dist/chunk-7AJGUI7L.cjs.map +0 -1
  191. package/dist/chunk-ACZZHHFZ.cjs.map +0 -1
  192. package/dist/chunk-AZNZ5WNZ.cjs.map +0 -1
  193. package/dist/chunk-DZ4IOP3Q.js.map +0 -1
  194. package/dist/chunk-IYSOVS7O.js.map +0 -1
  195. package/dist/chunk-KHH54GRP.cjs.map +0 -1
  196. package/dist/chunk-NIAFR5EE.js.map +0 -1
  197. package/dist/chunk-O7RZRUMZ.js.map +0 -1
  198. package/dist/chunk-QYU7J5EQ.js.map +0 -1
  199. package/dist/chunk-S3UGLZSF.js +0 -42
  200. package/dist/chunk-S3UGLZSF.js.map +0 -1
  201. package/dist/chunk-TPQJKS7D.js.map +0 -1
  202. package/dist/chunk-TQW3R44P.cjs +0 -38
  203. package/dist/chunk-TQW3R44P.cjs.map +0 -1
  204. package/dist/chunk-VZ6TE23U.cjs +0 -54
  205. package/dist/chunk-VZ6TE23U.cjs.map +0 -1
  206. package/dist/chunk-W6VJAUGM.cjs.map +0 -1
  207. package/dist/chunk-W7KHHNZR.js.map +0 -1
  208. package/dist/chunk-Y4GCJJPF.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/featured-entities.ts","../src/keepers-limits.ts","../src/ancestor-refs.ts","../src/extra-refs.ts","../src/surround.ts","../src/object-aspect-defaults.ts","../src/location-mention-slug.ts","../src/mention-token-grammar.ts","../src/image-mention-slug.ts","../src/entity-mention-slug.ts","../src/to-connected-references.ts","../src/character-aspect-defaults.ts","../src/entity-aspect-defaults.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/reference-roles.ts"],"names":["t"],"mappings":";;;;AAqBO,IAAM,iBAAA,GAA+D;AAAA,EAC1E,SAAA,EAAW;AAAA,IACT;AAAA,MACE,EAAA,EAAI,WAAA;AAAA,MACJ,KAAA,EAAO,oBAAA;AAAA,MACP,WAAA,EACE;AAAA,KACJ;AAAA,IACA;AAAA,MACE,EAAA,EAAI,SAAA;AAAA,MACJ,KAAA,EAAO,kBAAA;AAAA,MACP,WAAA,EACE;AAAA,KACJ;AAAA,IACA;AAAA,MACE,EAAA,EAAI,OAAA;AAAA,MACJ,KAAA,EAAO,YAAA;AAAA,MACP,WAAA,EACE;AAAA,KACJ;AAAA,IACA;AAAA,MACE,EAAA,EAAI,YAAA;AAAA,MACJ,KAAA,EAAO,kBAAA;AAAA,MACP,WAAA,EACE;AAAA,KACJ;AAAA,IACA;AAAA,MACE,EAAA,EAAI,WAAA;AAAA,MACJ,KAAA,EAAO,mBAAA;AAAA,MACP,WAAA,EACE;AAAA,KACJ;AAAA,IACA;AAAA,MACE,EAAA,EAAI,OAAA;AAAA,MACJ,KAAA,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AAG,EAAE,CAAA,CACX,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAClB,OAAA,CAAQ,IAAA,EAAM,EAAE,CAAA;AACrB","file":"chunk-XJWED257.js","sourcesContent":["/**\n * Featured entity starter catalog (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","/**\n * Nodaro Keepers — the bounds of a shelf entry, shared by the route that\n * validates `PUT /v1/<kind>/:id/catalog`, the cursor it hands out and the\n * Studio dialog that writes through it, so the form refuses exactly what the\n * server would. Documented in the API and SDK references; a change here is\n * a change to the public contract.\n */\n\n/** `catalogSort` (the shelf order) is an integer within ±this. */\nexport const KEEPER_CATALOG_SORT_MAX = 1_000_000\n\n/** `catalogCategory` (the shelf heading) is at most this many characters. */\nexport const KEEPER_CATALOG_CATEGORY_MAX = 80\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 * 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 /**\n * Stable id of this extra reference, when the row has one. What a\n * `{ref:<id>}` token in the prompt names; passed through to the shared video\n * resolver's slot map by both the canvas and the orchestrator. Absent → the\n * row still numbers normally but cannot be addressed by id.\n */\n readonly id?: string\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 * Surround continuation — the shared WIRE CONTRACT.\n *\n * The Location 360° \"look-around\" builds each ring view (45°, 90°, …) as an\n * image-to-image continuation of the previous one.\n *\n * This module owns only what the route Zod schema, the SDK input type, and the\n * worker all need to agree on: the direction enum and the carried-fraction\n * defaults. The fill prompt lives in `@nodaro/prompts` (never published) and\n * the compositing/harmonization engine is private.\n */\n\n/**\n * The camera move a continuation represents: `right` / `left` pan the view\n * horizontally, `up` / `down` tilt it vertically.\n */\nexport const SURROUND_DIRECTIONS = [\"right\", \"left\", \"up\", \"down\"] as const\nexport type SurroundDirection = (typeof SURROUND_DIRECTIONS)[number]\n\n/** Default carried fraction for a horizontal pan. */\nexport const DEFAULT_CARRIED_FRACTION = 0.5\n/** Default carried fraction for a vertical tilt. */\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// 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 * 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 — OR (Variant + Role\n * Separation) a non-mode 4th segment coexisting with a bucket/variant\n * (`@lib:1:weather/rain:lighting` → rain image, lighting phrase). Absent\n * (undefined) for canonical / bare-variant / mode tokens. The hybrid\n * resolver + role pill map it back to the phrase key via `normalizeRoleSlug`\n * (custom slugs pass through). Optional so those tokens stay\n * shape-identical to the pre-Phase-D parser 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:X — X is EITHER a mode override\n // (today's shape, byte-identical) OR — Variant + Role Separation — any other\n // slug, parsed as a per-mention ROLE coexisting with the bucket/variant (the\n // variant picks the image, the role picks the phrase). The `role` key is\n // emitted only on the non-mode branch, mirroring the character parser.\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 (!/^[a-z][a-z0-9-]*$/.test(fourth)) return null\n if (isLocationUsageMode(fourth)) {\n return { locationSlug, imageIndex, bucket, variant, usageMode: fourth, ...lockField }\n }\n return { locationSlug, imageIndex, bucket, variant, usageMode: null, role: 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","/**\n * The SHORT `@-mention` grammar core — `@<name-slug>:<index>[:<role>][~lock|~nolock]`.\n *\n * ONE parser, ONE finder, ONE pair of collision guards, shared by every mention\n * kind whose token has NO variant/bucket slot:\n *\n * - `image-mention-slug.ts` — wired media (`wired-image` / `manual`)\n * - `entity-mention-slug.ts` — wired entities (`wired-creature` / `wired-object`)\n *\n * WHY EXTRACTED (and why the 5-line slugify precedent does NOT apply here). The\n * character/location/image modules each keep their own copy of the trivial\n * `characterMentionSlug` algorithm — duplication that is cheap because the\n * function is five obvious lines. What is shared HERE is the opposite: the\n * two-part collision guard (`(?![:a-z0-9-])`, which stops a 4-part CHARACTER\n * token being claimed as a 3-part one, and the post-match slash guard, which\n * stops a LOCATION bucket token being spliced as its own truncated prefix).\n * Those guards exist precisely to prevent prompt corruption, and a second\n * hand-copied edition of them is a drift surface with a corruption payload. So\n * the media and entity grammars converge on this module and the per-kind files\n * keep only what genuinely differs: WHICH refs contribute a slug.\n *\n * The character and location grammars do NOT use this core — their tokens carry\n * 2–4 segments with a variant/bucket/usage-mode slot, a materially different\n * shape, and their finders deliberately have NO trailing-reject lookahead.\n */\n\n/**\n * Grammar-valid slug shape — the exact shape `findMentionTokens`' regex can\n * produce, and therefore the gate on BOTH sides of the match.\n *\n * Emptiness is NOT the gate: `mentionNameSlug(\"3D Render\")` → `\"3d-render\"` is\n * non-empty yet UNPARSEABLE (a leading digit), so a ref named \"3D Render\" must\n * be dropped from a known-slug set even though its slug is truthy. This pattern\n * is what drops it.\n */\nexport const MENTION_SLUG_PATTERN = /^[a-z][a-z0-9-]*$/\n\n/**\n * Slugify a reference's display name for `@`-mention tokens. Byte-identical\n * algorithm to `characterMentionSlug` / `locationMentionSlug`; the per-kind\n * modules re-export it under their own name so each call site's intent stays\n * explicit.\n */\nexport function mentionNameSlug(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n}\n\n/** Kind-neutral parse result. The per-kind modules rename `slug` / `index`. */\nexport interface ParsedMentionToken {\n readonly slug: string\n readonly index: number\n /** Present ONLY for a 3-part token; omitted otherwise (shape rule). */\n readonly role?: string\n /** Present ONLY when a sentinel was found; omitted otherwise (shape rule). */\n readonly lock?: boolean\n}\n\n/** Kind-neutral finder result — a `ParsedMentionToken` plus its splice site. */\nexport interface FoundMentionToken extends ParsedMentionToken {\n /** The matched token text, verbatim — spliced out of the prompt at resolve time. */\n readonly token: string\n /** Byte offset into the source prompt — used to splice the token out. */\n readonly offset: number\n}\n\n/**\n * Parse a single `@<name-slug>:<index>[:<role>]` token. Returns null when the\n * token doesn't match a supported shape (the caller falls back to literal text).\n *\n * Segment count is 2 or 3 — NOT 2–4 like the character/location parsers. Neither\n * a media reference nor a wired entity has a variant/bucket slot, so there is\n * nothing for a 4th segment to mean, and claiming one would let this parser\n * swallow a character token.\n */\nexport function parseMentionToken(text: string): ParsedMentionToken | 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 // Strip a trailing `~nolock` (force OFF) or `~lock` (force ON) BEFORE splitting\n // so the segment grammar is untouched (a `~` never appears inside a segment).\n // Check `~nolock` FIRST — `~lock` is its suffix. A token with NEITHER sentinel\n // gains NO `lock` key.\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 > 3) return null\n\n const [slug, indexStr, third] = parts\n if (!MENTION_SLUG_PATTERN.test(slug)) return null\n if (!/^\\d+$/.test(indexStr)) return null\n const index = parseInt(indexStr, 10)\n if (!Number.isInteger(index) || index < 1) return null\n\n if (parts.length === 2) return { slug, index, ...lockField }\n if (!MENTION_SLUG_PATTERN.test(third)) return null\n return { slug, index, role: third, ...lockField }\n}\n\n// ONE optional segment (the role) — media refs and wired entities have no\n// variant/bucket slot.\n//\n// The trailing `(?![:a-z0-9-])` is the DELIBERATE divergence from the character\n// and location finders. Without it, a 4-part CHARACTER token that the character\n// pass failed to resolve (`@kira:1:smile:face`) would be captured here as the\n// 3-part `@kira:1:smile`, leaving `:face` dangling in the prompt. The lookahead\n// makes the regex backtrack and match nothing, so a 4-part token is NEVER a\n// short-grammar mention. `~lock` still matches (`~` is outside the class), and\n// its own `(?![a-z0-9-])` keeps `~locked` / `~nolockx` literal.\n//\n// Linear-scan shape (a fixed prefix then bounded optional groups, no nested\n// quantifiers) — matching the sibling finders, and ReDoS-free.\nconst MENTION_TOKEN_REGEX =\n /(?:^|[^a-zA-Z0-9])(@[a-z][a-z0-9-]*:\\d+(?::[a-z][a-z0-9-]*)?(?:~(?:no)?lock(?![a-z0-9-]))?)(?![:a-z0-9-])/g\n\n/**\n * Find every short-grammar `@-mention` in a prompt whose slug is in\n * `knownSlugs`.\n *\n * `knownSlugs` is what keeps one kind's parser off another kind's tokens — every\n * finder matches the same `@slug:N…` surface and only the known-slug set\n * separates them.\n */\nexport function findMentionTokens(\n prompt: string,\n knownSlugs: readonly string[],\n): FoundMentionToken[] {\n const tokens: FoundMentionToken[] = []\n // A module-level `g` regex carries `lastIndex` state; `matchAll` requires the\n // `g` flag but resets nothing, so re-create the scanner per call.\n const regex = new RegExp(MENTION_TOKEN_REGEX.source, \"g\")\n const knownSet = new Set(knownSlugs)\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 // SLASH GUARD — the second half of the collision guard, and the reason it\n // is a post-match check instead of another lookahead in the regex. `/` is\n // the LOCATION grammar's bucket/variant separator (`@lib:1:weather/rain`),\n // so a token immediately followed by `/<segment>` is a sibling-grammar\n // token, never a short-grammar mention. A lookahead cannot express this:\n // the engine would just BACKTRACK to a shorter prefix (`@lib:1:weather` →\n // `@lib:1`, or `@town:1~lock` → `@town:1`) and splice THAT, which is the\n // very corruption being prevented. Rejecting the whole match here leaves\n // the token literal, exactly as the character/location finders do.\n //\n // `/` alone is NOT the signal — `@town:1/@barn:2` (two mentions separated\n // by a slash) must keep matching, and a location segment always starts\n // `[a-z]`. So the guard is `/` + a segment start.\n if (/^\\/[a-z]/.test(prompt.slice(offset + token.length))) continue\n const parsed = parseMentionToken(token)\n if (parsed && knownSet.has(parsed.slug)) {\n tokens.push({ token, ...parsed, offset })\n }\n }\n return tokens\n}\n","/**\n * Named-image `@-mention` parser — `@<name-slug>:<index>[:<role>]`.\n *\n * The media analog of `character-mention-slug.ts` / `location-mention-slug.ts`,\n * for a wired image (`wired-image` / `manual` reference) addressed by the slug of\n * its NAME: an upload node's label on the canvas, or the name a thin client puts\n * on the reference. The grammar is the SHORT one — 2 or 3 segments, no buckets, no\n * variants, no usage-mode enum — because a media reference has no variant array to\n * select from and no identity mode to override. Every valid 3rd segment is a ROLE.\n * It is not unique to media: `entity-mention-slug.ts` (creatures/objects) speaks\n * the identical grammar off the shared core noted below.\n *\n * @town:3 — bare mention; renders the reference's binding\n * (\"reference image C\") at the typed position\n * @town:3:background — role phrase (\"the background from reference image C\")\n * @town:3:my-custom-role — custom roles pass through verbatim\n * @town:3~lock — additive identity-lock sentinel (also `~nolock`)\n * @town:1:a:b — NULL. A 4-part token is never an image mention.\n *\n * GRAMMAR CORE. The slug shape, the parser and the finder (including BOTH\n * collision guards) live in `mention-token-grammar.ts` and are shared verbatim\n * with `entity-mention-slug.ts` (creatures/objects), which speaks the identical\n * 2-or-3-segment grammar. This module is the MEDIA view of that core: the\n * per-kind field names, and the part that genuinely differs — WHICH refs\n * contribute a slug.\n *\n * NO WIRE FIELD. Unlike `characterSlug` / `locationSlug`, there is no `imageSlug`\n * on `ConnectedReference`: the slug is DERIVED from `defaultName` at resolve time\n * (`knownImageSlugsFromRefs`), so a client cannot drift from the grammar and the\n * reference schema is untouched.\n *\n * NO LEGACY RESOLVER. Only the hybrid reference format resolves these tokens;\n * under the legacy format an `@name:N` token stays literal text and the\n * reference auto-attaches exactly as it does today.\n */\n\nimport type { ConnectedReference } from \"./types.js\"\nimport {\n MENTION_SLUG_PATTERN,\n findMentionTokens,\n mentionNameSlug,\n parseMentionToken,\n} from \"./mention-token-grammar.js\"\n\n/**\n * Slugify an image reference's display name for `@`-mention tokens. Byte-\n * identical algorithm to `characterMentionSlug` / `locationMentionSlug`; kept as\n * a separate export to make the call site's intent explicit.\n */\nexport function imageMentionSlug(name: string): string {\n return mentionNameSlug(name)\n}\n\nexport interface ImageMentionTokenInfo {\n /** The matched token text, verbatim — spliced out of the prompt at resolve time. */\n readonly token: string\n readonly imageSlug: string\n /**\n * 1-based correlation index assigned at insertion by the autocomplete\n * (`nextMentionIndex` = max(existing N) + 1, unified across characters,\n * locations and images). The hybrid resolver binds by its own numbering walk,\n * so the index is CORRELATION ONLY — it is never echoed into the prompt.\n */\n readonly imageIndex: number\n /**\n * Per-mention ROLE from the 3rd segment (`@town:3:background`) — curated\n * (`REFERENCE_ROLE_PRESETS[\"wired-image\"]`) or custom, stored VERBATIM. Media\n * role presets are all single-word, so this never needs `normalizeRoleSlug`\n * (the location-only remapping for multi-word presets). OMITTED (undefined,\n * never null) for 2-part tokens, so those stay shape-identical to a parser\n * with no role support.\n */\n readonly role?: string\n /**\n * Additive `~lock` / `~nolock` sentinel. Tri-state: `true` (force ON) |\n * `false` (force OFF, suppressing a ref-level `identityLock.enabled`) |\n * ABSENT/undefined (inherit the ref default). Honored only by the hybrid\n * resolver — there is no legacy image resolver to make it inert on.\n */\n readonly lock?: boolean\n /** Byte offset into the source prompt — used to splice the token out. */\n readonly offset: number\n}\n\n/**\n * Parse a single `@<name-slug>:<index>[:<role>]` token. Returns null when the\n * token doesn't match a supported shape (the caller falls back to literal text).\n *\n * Segment count is 2 or 3 — NOT 2–4 like the character/location parsers. A media\n * reference has no variant/bucket slot, so there is nothing for a 4th segment to\n * mean, and claiming one would let this parser swallow a character token.\n *\n * Delegates to the shared `parseMentionToken` and renames its kind-neutral\n * `slug` / `index` to this module's `imageSlug` / `imageIndex`. The optional\n * `role` / `lock` keys are re-emitted CONDITIONALLY so the documented shape rule\n * survives the rename: a 2-part token has no `role` key at all.\n */\nexport function parseImageMentionToken(text: string): {\n imageSlug: string\n imageIndex: number\n /** Present ONLY for a 3-part token; omitted otherwise (shape rule). */\n role?: string\n /** Present ONLY when a sentinel was found; omitted otherwise (shape rule). */\n lock?: boolean\n} | null {\n const parsed = parseMentionToken(text)\n if (!parsed) return null\n return {\n imageSlug: parsed.slug,\n imageIndex: parsed.index,\n ...(parsed.role !== undefined ? { role: parsed.role } : {}),\n ...(parsed.lock !== undefined ? { lock: parsed.lock } : {}),\n }\n}\n\n/**\n * Find every image `@-mention` in a prompt whose slug is a known image slug.\n *\n * `knownImageSlugs` (from `knownImageSlugsFromRefs`) is what keeps this parser\n * off the other grammars' tokens — every finder matches the same `@slug:N…`\n * surface and only the known-slug set separates them.\n */\nexport function findImageMentionTokens(\n prompt: string,\n knownImageSlugs: readonly string[],\n): ImageMentionTokenInfo[] {\n return findMentionTokens(prompt, knownImageSlugs).map((t) => ({\n token: t.token,\n imageSlug: t.slug,\n imageIndex: t.index,\n ...(t.role !== undefined ? { role: t.role } : {}),\n ...(t.lock !== undefined ? { lock: t.lock } : {}),\n offset: t.offset,\n }))\n}\n\n/**\n * The mention slug a single reference contributes, or `null` when the ref\n * cannot carry a mention at all — the SINGLE gate, so every view of \"which\n * refs are mentionable\" is the same view.\n *\n * Shared by `knownImageSlugsFromRefs` (the finder's known-slug set) and the\n * prompt-builder's hybrid resolver (its slug → ref lookup map). Those two must\n * admit exactly the same refs: a slug the finder accepts but the resolver drops\n * would splice a token with nothing to bind, and a ref the resolver keys under\n * a slug no token can match is dead weight. Emptiness is NOT the gate (see\n * `MENTION_SLUG_PATTERN`).\n */\nexport function imageMentionSlugForRef(r: ConnectedReference): string | null {\n if (r.source !== \"wired-image\" && r.source !== \"manual\") return null\n if (r.isExtraRef === true) return null\n if (!r.url || !r.defaultName) return null\n const slug = imageMentionSlug(r.defaultName)\n return MENTION_SLUG_PATTERN.test(slug) ? slug : null\n}\n\n/**\n * The known-image-slug set for a reference list — the SINGLE source of truth for\n * the derivation, shared by `buildImagePrompt`'s Phase 0 and the backend\n * orchestrator's structured-branch gate so the two can never disagree about\n * whether a prompt carries a resolvable image mention.\n *\n * Only MEDIA refs (`wired-image` / `manual`) with a URL participate — the other\n * sources have their own mention grammars: characters, locations, and — since the\n * creature/object leg — wired entities via `knownEntitySlugsFromRefs`.\n *\n * `isExtraRef` refs are EXCLUDED: an extra renders through the extras path with\n * its own body line, so letting a mention also bind one would double-emit prose.\n *\n * Grammar-invalid slugs are DROPPED (see `MENTION_SLUG_PATTERN`) — a ref named\n * \"3D Render\" slugs to the non-empty but unparseable `\"3d-render\"`, and admitting\n * it would put a slug in the set that no token can ever match.\n *\n * All four of those gates live in `imageMentionSlugForRef`, which the hybrid\n * resolver's own lookup map uses too — one predicate, so the two views cannot\n * drift apart.\n */\nexport function knownImageSlugsFromRefs(\n refs: readonly ConnectedReference[],\n): string[] {\n const out = new Set<string>()\n for (const r of refs) {\n const slug = imageMentionSlugForRef(r)\n if (slug) out.add(slug)\n }\n return [...out]\n}\n","/**\n * Wired-entity `@-mention` parser — `@<name-slug>:<index>[:<role>][~lock|~nolock]`\n * for `wired-creature` and `wired-object` references.\n *\n * THE BUG THIS KILLS. Before this leg, creatures and objects were the only wired\n * sources with NO mention grammar. A user writing \"Nessie rises from the lake\"\n * with a creature node wired in got the creature's NAME as plain prose while its\n * binding dangled as a trailing \"the creature from reference image D\" line after\n * the style hints — two disconnected halves of one intent, which is exactly the\n * failure mode mentions exist to remove. With a mention, the binding renders\n * INLINE at the typed position and the trailing canonical fallback for that ref\n * is suppressed.\n *\n * @nessie:4 — bare mention; the source-default role phrase\n * (\"the creature from reference image D\")\n * @nessie:4:markings — role phrase (\"the markings from reference image D\")\n * @chair:2:material — objects use the `wired-object` presets\n * @nessie:4:my-custom-role — custom roles pass through verbatim\n * @nessie:4~lock — additive identity-lock sentinel (also `~nolock`)\n * @nessie:4:a:b — NULL. A 4-part token is never an entity mention.\n *\n * GRAMMAR CORE. Identical grammar to the named-image mention, so the slug shape,\n * the parser and the finder (with BOTH collision guards — the 4-part trailing\n * reject and the location slash guard) are the SHARED `mention-token-grammar.ts`,\n * not a second hand-copied edition. This module is the ENTITY view of that core:\n * the field names, and the part that genuinely differs — WHICH refs contribute a\n * slug.\n *\n * PRECEDENCE, across all five kinds:\n *\n * character → location → image → creature → object\n *\n * Enforced by RESOLUTION ORDER in `buildImagePrompt`'s Phase 0, not by anything\n * in this file: each pass splices its matched tokens out of the prompt before the\n * next pass runs its finder, so a slug claimed by an earlier kind never reaches a\n * later pass. A name shared by a character and a creature resolves as the\n * CHARACTER, and the creature token never fires. The creature-before-object half\n * of the tail is enforced inside the single entity pass, whose slug → ref map is\n * built creature-first (see `resolveEntityMentionsHybrid`).\n *\n * NO WIRE FIELD, matching the image grammar and unlike `characterSlug` /\n * `locationSlug`: the slug is DERIVED from `defaultName` at resolve time\n * (`knownEntitySlugsFromRefs`), so a client cannot drift from the grammar and the\n * reference schema is untouched.\n *\n * NO LEGACY RESOLVER — the image-grammar precedent. Only the hybrid reference\n * format resolves these tokens; under the legacy format an `@name:N` token stays\n * literal text and the entity auto-attaches with its trailing canonical phrase\n * exactly as it does today. Legacy assembly has no inline role-phrase machinery\n * at all (its object/creature rendering is the numbered-directive block), so\n * there is no clean seam to add one and no consumer asking for it.\n */\n\nimport type { ConnectedReference } from \"./types.js\"\nimport {\n MENTION_SLUG_PATTERN,\n findMentionTokens,\n mentionNameSlug,\n parseMentionToken,\n} from \"./mention-token-grammar.js\"\n\n/**\n * Slugify a wired entity's display name for `@`-mention tokens. Byte-identical\n * algorithm to `characterMentionSlug` / `imageMentionSlug`; kept as a separate\n * export to make the call site's intent explicit.\n */\nexport function entityMentionSlug(name: string): string {\n return mentionNameSlug(name)\n}\n\nexport interface EntityMentionTokenInfo {\n /** The matched token text, verbatim — spliced out of the prompt at resolve time. */\n readonly token: string\n readonly entitySlug: string\n /**\n * 1-based correlation index assigned at insertion by the autocomplete\n * (`nextMentionIndex` = max(existing N) + 1, unified across every mention\n * kind). The hybrid resolver binds by its own numbering walk, so the index is\n * CORRELATION ONLY — it is never echoed into the prompt.\n */\n readonly entityIndex: number\n /**\n * Per-mention ROLE from the 3rd segment (`@nessie:4:markings`) — curated\n * (`REFERENCE_ROLE_PRESETS[\"wired-creature\"]` / `[\"wired-object\"]`) or custom,\n * stored VERBATIM. Both preset lists are entirely single-word, so this never\n * needs `normalizeRoleSlug` (the location-only remapping for multi-word\n * presets). OMITTED (undefined, never null) for 2-part tokens.\n */\n readonly role?: string\n /**\n * Additive `~lock` / `~nolock` sentinel. Tri-state: `true` (force ON) |\n * `false` (force OFF, suppressing a ref-level `identityLock.enabled`) |\n * ABSENT/undefined (inherit the ref default). Honored only by the hybrid\n * resolver — there is no legacy entity resolver to make it inert on.\n */\n readonly lock?: boolean\n /** Byte offset into the source prompt — used to splice the token out. */\n readonly offset: number\n}\n\n/**\n * Parse a single `@<name-slug>:<index>[:<role>]` token. Returns null when the\n * token doesn't match a supported shape (the caller falls back to literal text).\n *\n * Segment count is 2 or 3 — NOT 2–4 like the character/location parsers. A wired\n * creature or object has no variant/bucket slot, so there is nothing for a 4th\n * segment to mean, and claiming one would let this parser swallow a character\n * token.\n */\nexport function parseEntityMentionToken(text: string): {\n entitySlug: string\n entityIndex: number\n /** Present ONLY for a 3-part token; omitted otherwise (shape rule). */\n role?: string\n /** Present ONLY when a sentinel was found; omitted otherwise (shape rule). */\n lock?: boolean\n} | null {\n const parsed = parseMentionToken(text)\n if (!parsed) return null\n return {\n entitySlug: parsed.slug,\n entityIndex: parsed.index,\n ...(parsed.role !== undefined ? { role: parsed.role } : {}),\n ...(parsed.lock !== undefined ? { lock: parsed.lock } : {}),\n }\n}\n\n/**\n * Find every entity `@-mention` in a prompt whose slug is a known entity slug.\n *\n * `knownEntitySlugs` (from `knownEntitySlugsFromRefs`) is what keeps this parser\n * off the other grammars' tokens — every finder matches the same `@slug:N…`\n * surface and only the known-slug set separates them. Cross-kind precedence is\n * additionally enforced by pass ORDER at the resolver (see the module header).\n */\nexport function findEntityMentionTokens(\n prompt: string,\n knownEntitySlugs: readonly string[],\n): EntityMentionTokenInfo[] {\n return findMentionTokens(prompt, knownEntitySlugs).map((t) => ({\n token: t.token,\n entitySlug: t.slug,\n entityIndex: t.index,\n ...(t.role !== undefined ? { role: t.role } : {}),\n ...(t.lock !== undefined ? { lock: t.lock } : {}),\n offset: t.offset,\n }))\n}\n\n/**\n * The mention slug a single reference contributes, or `null` when the ref cannot\n * carry an entity mention at all — the SINGLE gate, so every view of \"which refs\n * are entity-mentionable\" is the same view.\n *\n * Shared by `knownEntitySlugsFromRefs` (the finder's known-slug set) and the\n * prompt-builder's hybrid resolver (its slug → ref lookup map). Those two must\n * admit exactly the same refs: a slug the finder accepts but the resolver drops\n * would splice a token with nothing to bind, and a ref the resolver keys under a\n * slug no token can match is dead weight. Emptiness is NOT the gate (see\n * `MENTION_SLUG_PATTERN`) — a creature named \"3-Eyed Raven\" slugs to the truthy\n * but unparseable `\"3-eyed-raven\"`.\n *\n * `isExtraRef` refs are EXCLUDED, mirroring `imageMentionSlugForRef`: an extra\n * renders through the extras path with its own body line, so letting a mention\n * also bind one would double-emit prose.\n */\nexport function entityMentionSlugForRef(r: ConnectedReference): string | null {\n if (r.source !== \"wired-creature\" && r.source !== \"wired-object\") return null\n if (r.isExtraRef === true) return null\n if (!r.url || !r.defaultName) return null\n const slug = entityMentionSlug(r.defaultName)\n return MENTION_SLUG_PATTERN.test(slug) ? slug : null\n}\n\n/**\n * The known-entity-slug set for a reference list — the SINGLE source of truth for\n * the derivation, shared by `buildImagePrompt`'s Phase 0 and the backend\n * orchestrator's structured-branch gate so the two can never disagree about\n * whether a prompt carries a resolvable entity mention.\n *\n * UNFILTERED, exactly like `knownImageSlugsFromRefs` and the character/location\n * slug sets: every mentionable creature/object contributes its slug regardless of\n * what any OTHER kind may also claim. Cross-kind precedence is a property of the\n * resolver's pass order (character → location → image → creature → object), NOT\n * of this set — subtracting the earlier kinds' slugs here would put the\n * precedence rule in two places and let them drift.\n *\n * Creature and object share ONE set (and one resolver pass): the grammar, the\n * gate and the rendering are identical, and `defaultRoleForSource(r.source)`\n * already tells the two apart at phrase time. Their relative precedence is\n * settled where a tie can actually occur — the resolver's slug → ref map, built\n * creature-first.\n */\nexport function knownEntitySlugsFromRefs(\n refs: readonly ConnectedReference[],\n): string[] {\n const out = new Set<string>()\n for (const r of refs) {\n const slug = entityMentionSlugForRef(r)\n if (slug) out.add(slug)\n }\n return [...out]\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\" | \"image\"\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), image → `wired-image` (a plain media reference; it\n * AUTO-ATTACHES, and an `@<name-slug>:<index>[:<role>]` mention re-seats it at the\n * position it was typed). 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 === \"image\") {\n // No slug field — the resolver derives it from `defaultName` at prompt time\n // (`knownImageSlugsFromRefs`), so a client cannot drift from the grammar and\n // nothing changes on the wire.\n return {\n id: entity.id,\n defaultName: entity.name,\n source: \"wired-image\",\n url: entity.url ?? \"\",\n ...(entity.description ? { description: entity.description } : {}),\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 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 // Named composite reference boards (migration 250) — identity-collage\n // sheets auto-attached by the ffmpeg image-collage worker.\n \"boards\",\n] as const\nexport type CharacterAttachColumn = (typeof CHARACTER_ATTACH_COLUMNS)[number]\n\n/**\n * The narrower set `/v1/image-to-image`'s `attachToColumn` accepts (Character\n * Studio refining an existing asset): the four refinable buckets. A subset of\n * {@link CHARACTER_ATTACH_COLUMNS}, checked at compile time.\n */\nexport const IMAGE_TO_IMAGE_ATTACH_COLUMNS = [\n \"expressions\",\n \"poses\",\n \"angles\",\n \"lighting_variations\",\n] as const satisfies readonly CharacterAttachColumn[]\nexport type ImageToImageAttachColumn = (typeof IMAGE_TO_IMAGE_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 = [\n \"nano-banana-pro\",\n \"gpt-image-2\",\n \"gpt-image-2-5-flare\",\n \"gpt-image-2-5-sunburst\",\n \"gpt-image-2-6-flare\",\n \"gpt-image-2-6-sunburst\",\n] 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","// 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\": [\"ref-only\", \"person\", \"face\", \"clothes\", \"hair\", \"pose\", \"expression\", \"style\"],\n \"wired-face\": [\"face\", \"person\", \"expression\", \"style\"],\n // \"location\" sits second, mirroring wired-character's ref-only/person order —\n // it is this source's default. \"background\" keeps its place for the genuine\n // backdrop case (see DEFAULT_LABEL_BY_SOURCE for why it stopped being default).\n \"wired-location\": [\"ref-only\", \"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 \"ref-only\":\n // Bare reference pointer — no descriptive phrase. The label-less/default\n // state for media refs; an explicit pick for character/location assets.\n return binding\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"]}