@escapeaihq/client-core 0.52.0 → 0.139.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 (782) hide show
  1. package/README.md +445 -153
  2. package/dist/adapters/capabilities.d.ts +20 -3
  3. package/dist/adapters/capabilities.d.ts.map +1 -1
  4. package/dist/adapters/directorAdapter.d.ts +5 -4
  5. package/dist/adapters/directorAdapter.d.ts.map +1 -1
  6. package/dist/adapters/directorAdapter.js +5 -4
  7. package/dist/adapters/directorAdapter.js.map +1 -1
  8. package/dist/adapters/experienceModelCatalog.d.ts +382 -0
  9. package/dist/adapters/experienceModelCatalog.d.ts.map +1 -0
  10. package/dist/adapters/experienceModelCatalog.js +401 -0
  11. package/dist/adapters/experienceModelCatalog.js.map +1 -0
  12. package/dist/adapters/extractionAdapter.d.ts +81 -0
  13. package/dist/adapters/extractionAdapter.d.ts.map +1 -0
  14. package/dist/adapters/extractionAdapter.js +98 -0
  15. package/dist/adapters/extractionAdapter.js.map +1 -0
  16. package/dist/adapters/imageAdapter.d.ts +5 -1
  17. package/dist/adapters/imageAdapter.d.ts.map +1 -1
  18. package/dist/adapters/imageAdapter.js +5 -1
  19. package/dist/adapters/imageAdapter.js.map +1 -1
  20. package/dist/adapters/index.d.ts +54 -16
  21. package/dist/adapters/index.d.ts.map +1 -1
  22. package/dist/adapters/index.js +62 -11
  23. package/dist/adapters/index.js.map +1 -1
  24. package/dist/adapters/momentDirective.d.ts +66 -0
  25. package/dist/adapters/momentDirective.d.ts.map +1 -0
  26. package/dist/adapters/momentDirective.js +78 -0
  27. package/dist/adapters/momentDirective.js.map +1 -0
  28. package/dist/adapters/momentPolicy.d.ts +132 -0
  29. package/dist/adapters/momentPolicy.d.ts.map +1 -0
  30. package/dist/adapters/momentPolicy.js +165 -0
  31. package/dist/adapters/momentPolicy.js.map +1 -0
  32. package/dist/adapters/registry.d.ts +1 -1
  33. package/dist/adapters/registry.d.ts.map +1 -1
  34. package/dist/adapters/videoGenAdapter.d.ts +55 -0
  35. package/dist/adapters/videoGenAdapter.d.ts.map +1 -0
  36. package/dist/adapters/videoGenAdapter.js +78 -0
  37. package/dist/adapters/videoGenAdapter.js.map +1 -0
  38. package/dist/adapters/worldAdapter.d.ts +132 -11
  39. package/dist/adapters/worldAdapter.d.ts.map +1 -1
  40. package/dist/adapters/worldAdapter.js +127 -11
  41. package/dist/adapters/worldAdapter.js.map +1 -1
  42. package/dist/adapters/worldModelPreference.d.ts +173 -0
  43. package/dist/adapters/worldModelPreference.d.ts.map +1 -0
  44. package/dist/adapters/worldModelPreference.js +209 -0
  45. package/dist/adapters/worldModelPreference.js.map +1 -0
  46. package/dist/adapters/worldModelTradeoffs.d.ts +120 -0
  47. package/dist/adapters/worldModelTradeoffs.d.ts.map +1 -0
  48. package/dist/adapters/worldModelTradeoffs.js +154 -0
  49. package/dist/adapters/worldModelTradeoffs.js.map +1 -0
  50. package/dist/admin.d.ts +545 -0
  51. package/dist/admin.d.ts.map +1 -1
  52. package/dist/admin.js +230 -16
  53. package/dist/admin.js.map +1 -1
  54. package/dist/api.d.ts +10295 -2216
  55. package/dist/api.d.ts.map +1 -1
  56. package/dist/api.js +4187 -1240
  57. package/dist/api.js.map +1 -1
  58. package/dist/arcBoardJoin.d.ts +38 -0
  59. package/dist/arcBoardJoin.d.ts.map +1 -0
  60. package/dist/arcBoardJoin.js +37 -0
  61. package/dist/arcBoardJoin.js.map +1 -0
  62. package/dist/arcPreview.d.ts +49 -0
  63. package/dist/arcPreview.d.ts.map +1 -0
  64. package/dist/arcPreview.js +65 -0
  65. package/dist/arcPreview.js.map +1 -0
  66. package/dist/audio.d.ts +259 -16
  67. package/dist/audio.d.ts.map +1 -1
  68. package/dist/audio.js +605 -114
  69. package/dist/audio.js.map +1 -1
  70. package/dist/audioDsp.d.ts +45 -0
  71. package/dist/audioDsp.d.ts.map +1 -0
  72. package/dist/audioDsp.js +108 -0
  73. package/dist/audioDsp.js.map +1 -0
  74. package/dist/audioProtocol.d.ts +160 -0
  75. package/dist/audioProtocol.d.ts.map +1 -1
  76. package/dist/audioProtocol.js +99 -0
  77. package/dist/audioProtocol.js.map +1 -1
  78. package/dist/beatTitles.d.ts +33 -0
  79. package/dist/beatTitles.d.ts.map +1 -0
  80. package/dist/beatTitles.js +39 -0
  81. package/dist/beatTitles.js.map +1 -0
  82. package/dist/castProjection.d.ts +204 -1
  83. package/dist/castProjection.d.ts.map +1 -1
  84. package/dist/castProjection.js +202 -0
  85. package/dist/castProjection.js.map +1 -1
  86. package/dist/characterGrounding.d.ts +369 -0
  87. package/dist/characterGrounding.d.ts.map +1 -0
  88. package/dist/characterGrounding.js +408 -0
  89. package/dist/characterGrounding.js.map +1 -0
  90. package/dist/conversation/binding.d.ts +13 -0
  91. package/dist/conversation/binding.d.ts.map +1 -1
  92. package/dist/conversation/binding.js.map +1 -1
  93. package/dist/conversation/chatSessionStore.d.ts +178 -0
  94. package/dist/conversation/chatSessionStore.d.ts.map +1 -0
  95. package/dist/conversation/chatSessionStore.js +196 -0
  96. package/dist/conversation/chatSessionStore.js.map +1 -0
  97. package/dist/conversation/controller.d.ts +44 -0
  98. package/dist/conversation/controller.d.ts.map +1 -1
  99. package/dist/conversation/controller.js +82 -3
  100. package/dist/conversation/controller.js.map +1 -1
  101. package/dist/conversation/index.d.ts +2 -0
  102. package/dist/conversation/index.d.ts.map +1 -1
  103. package/dist/conversation/index.js +2 -0
  104. package/dist/conversation/index.js.map +1 -1
  105. package/dist/conversation/participant.d.ts +16 -0
  106. package/dist/conversation/participant.d.ts.map +1 -1
  107. package/dist/conversation/readSequencer.d.ts +38 -0
  108. package/dist/conversation/readSequencer.d.ts.map +1 -0
  109. package/dist/conversation/readSequencer.js +42 -0
  110. package/dist/conversation/readSequencer.js.map +1 -0
  111. package/dist/conversation/roster.d.ts +5 -1
  112. package/dist/conversation/roster.d.ts.map +1 -1
  113. package/dist/conversation/roster.js.map +1 -1
  114. package/dist/conversation/rosterProjection.d.ts +74 -1
  115. package/dist/conversation/rosterProjection.d.ts.map +1 -1
  116. package/dist/conversation/rosterProjection.js +135 -1
  117. package/dist/conversation/rosterProjection.js.map +1 -1
  118. package/dist/conversation/runtime.d.ts +20 -3
  119. package/dist/conversation/runtime.d.ts.map +1 -1
  120. package/dist/conversation/runtime.js +66 -7
  121. package/dist/conversation/runtime.js.map +1 -1
  122. package/dist/conversation/types.d.ts +43 -4
  123. package/dist/conversation/types.d.ts.map +1 -1
  124. package/dist/conversation/voice.d.ts +290 -13
  125. package/dist/conversation/voice.d.ts.map +1 -1
  126. package/dist/conversation/voice.js +565 -42
  127. package/dist/conversation/voice.js.map +1 -1
  128. package/dist/creatorCuration.d.ts +134 -0
  129. package/dist/creatorCuration.d.ts.map +1 -0
  130. package/dist/creatorCuration.js +228 -0
  131. package/dist/creatorCuration.js.map +1 -0
  132. package/dist/creatorDashboard.d.ts +155 -0
  133. package/dist/creatorDashboard.d.ts.map +1 -0
  134. package/dist/creatorDashboard.js +237 -0
  135. package/dist/creatorDashboard.js.map +1 -0
  136. package/dist/creatorUniverse.d.ts +95 -0
  137. package/dist/creatorUniverse.d.ts.map +1 -0
  138. package/dist/creatorUniverse.js +136 -0
  139. package/dist/creatorUniverse.js.map +1 -0
  140. package/dist/curationWrite.d.ts +76 -0
  141. package/dist/curationWrite.d.ts.map +1 -0
  142. package/dist/curationWrite.js +106 -0
  143. package/dist/curationWrite.js.map +1 -0
  144. package/dist/designTokens.d.ts +64 -0
  145. package/dist/designTokens.d.ts.map +1 -0
  146. package/dist/designTokens.js +117 -0
  147. package/dist/designTokens.js.map +1 -0
  148. package/dist/dialogAttribution.d.ts +79 -0
  149. package/dist/dialogAttribution.d.ts.map +1 -0
  150. package/dist/dialogAttribution.js +144 -0
  151. package/dist/dialogAttribution.js.map +1 -0
  152. package/dist/dmRunWorldReadiness.d.ts +605 -0
  153. package/dist/dmRunWorldReadiness.d.ts.map +1 -0
  154. package/dist/dmRunWorldReadiness.js +775 -0
  155. package/dist/dmRunWorldReadiness.js.map +1 -0
  156. package/dist/domains/access.d.ts +32 -0
  157. package/dist/domains/access.d.ts.map +1 -0
  158. package/dist/domains/access.js +43 -0
  159. package/dist/domains/access.js.map +1 -0
  160. package/dist/domains/adventureDefinitions.d.ts +159 -0
  161. package/dist/domains/adventureDefinitions.d.ts.map +1 -0
  162. package/dist/domains/adventureDefinitions.js +168 -0
  163. package/dist/domains/adventureDefinitions.js.map +1 -0
  164. package/dist/domains/adventures.d.ts +329 -0
  165. package/dist/domains/adventures.d.ts.map +1 -0
  166. package/dist/domains/adventures.js +359 -0
  167. package/dist/domains/adventures.js.map +1 -0
  168. package/dist/domains/arcs.d.ts +146 -0
  169. package/dist/domains/arcs.d.ts.map +1 -0
  170. package/dist/domains/arcs.js +202 -0
  171. package/dist/domains/arcs.js.map +1 -0
  172. package/dist/domains/artifacts.d.ts +259 -0
  173. package/dist/domains/artifacts.d.ts.map +1 -0
  174. package/dist/domains/artifacts.js +125 -0
  175. package/dist/domains/artifacts.js.map +1 -0
  176. package/dist/domains/chat.d.ts +158 -0
  177. package/dist/domains/chat.d.ts.map +1 -0
  178. package/dist/domains/chat.js +224 -0
  179. package/dist/domains/chat.js.map +1 -0
  180. package/dist/domains/decisions.d.ts +31 -0
  181. package/dist/domains/decisions.d.ts.map +1 -0
  182. package/dist/domains/decisions.js +42 -0
  183. package/dist/domains/decisions.js.map +1 -0
  184. package/dist/domains/documents.d.ts +218 -0
  185. package/dist/domains/documents.d.ts.map +1 -0
  186. package/dist/domains/documents.js +252 -0
  187. package/dist/domains/documents.js.map +1 -0
  188. package/dist/domains/enhancements.d.ts +106 -0
  189. package/dist/domains/enhancements.d.ts.map +1 -0
  190. package/dist/domains/enhancements.js +160 -0
  191. package/dist/domains/enhancements.js.map +1 -0
  192. package/dist/domains/graph.d.ts +454 -0
  193. package/dist/domains/graph.d.ts.map +1 -0
  194. package/dist/domains/graph.js +648 -0
  195. package/dist/domains/graph.js.map +1 -0
  196. package/dist/domains/images.d.ts +220 -0
  197. package/dist/domains/images.d.ts.map +1 -0
  198. package/dist/domains/images.js +307 -0
  199. package/dist/domains/images.js.map +1 -0
  200. package/dist/domains/ingestion.d.ts +312 -0
  201. package/dist/domains/ingestion.d.ts.map +1 -0
  202. package/dist/domains/ingestion.js +495 -0
  203. package/dist/domains/ingestion.js.map +1 -0
  204. package/dist/domains/me.d.ts +21 -0
  205. package/dist/domains/me.d.ts.map +1 -0
  206. package/dist/domains/me.js +23 -0
  207. package/dist/domains/me.js.map +1 -0
  208. package/dist/domains/orgs.d.ts +47 -0
  209. package/dist/domains/orgs.d.ts.map +1 -0
  210. package/dist/domains/orgs.js +75 -0
  211. package/dist/domains/orgs.js.map +1 -0
  212. package/dist/domains/personas.d.ts +138 -0
  213. package/dist/domains/personas.d.ts.map +1 -0
  214. package/dist/domains/personas.js +322 -0
  215. package/dist/domains/personas.js.map +1 -0
  216. package/dist/domains/projects.d.ts +53 -0
  217. package/dist/domains/projects.d.ts.map +1 -0
  218. package/dist/domains/projects.js +94 -0
  219. package/dist/domains/projects.js.map +1 -0
  220. package/dist/domains/quests.d.ts +431 -0
  221. package/dist/domains/quests.d.ts.map +1 -0
  222. package/dist/domains/quests.js +61 -0
  223. package/dist/domains/quests.js.map +1 -0
  224. package/dist/domains/reactor.d.ts +98 -0
  225. package/dist/domains/reactor.d.ts.map +1 -0
  226. package/dist/domains/reactor.js +131 -0
  227. package/dist/domains/reactor.js.map +1 -0
  228. package/dist/domains/showcase.d.ts +28 -0
  229. package/dist/domains/showcase.d.ts.map +1 -0
  230. package/dist/domains/showcase.js +28 -0
  231. package/dist/domains/showcase.js.map +1 -0
  232. package/dist/domains/storyboards.d.ts +1253 -0
  233. package/dist/domains/storyboards.d.ts.map +1 -0
  234. package/dist/domains/storyboards.js +781 -0
  235. package/dist/domains/storyboards.js.map +1 -0
  236. package/dist/domains/studioSettings.d.ts +39 -0
  237. package/dist/domains/studioSettings.d.ts.map +1 -0
  238. package/dist/domains/studioSettings.js +80 -0
  239. package/dist/domains/studioSettings.js.map +1 -0
  240. package/dist/domains/universes.d.ts +191 -0
  241. package/dist/domains/universes.d.ts.map +1 -0
  242. package/dist/domains/universes.js +276 -0
  243. package/dist/domains/universes.js.map +1 -0
  244. package/dist/domains/userDefaults.d.ts +18 -0
  245. package/dist/domains/userDefaults.d.ts.map +1 -0
  246. package/dist/domains/userDefaults.js +27 -0
  247. package/dist/domains/userDefaults.js.map +1 -0
  248. package/dist/domains/visemeBundles.d.ts +262 -0
  249. package/dist/domains/visemeBundles.d.ts.map +1 -0
  250. package/dist/domains/visemeBundles.js +373 -0
  251. package/dist/domains/visemeBundles.js.map +1 -0
  252. package/dist/domains/workflows.d.ts +142 -0
  253. package/dist/domains/workflows.d.ts.map +1 -0
  254. package/dist/domains/workflows.js +245 -0
  255. package/dist/domains/workflows.js.map +1 -0
  256. package/dist/enhancementDiff.d.ts +56 -0
  257. package/dist/enhancementDiff.d.ts.map +1 -0
  258. package/dist/enhancementDiff.js +110 -0
  259. package/dist/enhancementDiff.js.map +1 -0
  260. package/dist/generated/contract.d.ts +372 -0
  261. package/dist/generated/contract.d.ts.map +1 -0
  262. package/dist/generated/contract.js +395 -0
  263. package/dist/generated/contract.js.map +1 -0
  264. package/dist/graphSchema.d.ts +36 -5
  265. package/dist/graphSchema.d.ts.map +1 -1
  266. package/dist/graphSchema.js +88 -2
  267. package/dist/graphSchema.js.map +1 -1
  268. package/dist/http.d.ts +70 -1
  269. package/dist/http.d.ts.map +1 -1
  270. package/dist/http.js +263 -11
  271. package/dist/http.js.map +1 -1
  272. package/dist/identity.d.ts +81 -0
  273. package/dist/identity.d.ts.map +1 -0
  274. package/dist/identity.js +65 -0
  275. package/dist/identity.js.map +1 -0
  276. package/dist/index.d.ts +35 -0
  277. package/dist/index.d.ts.map +1 -1
  278. package/dist/index.js +118 -0
  279. package/dist/index.js.map +1 -1
  280. package/dist/messageContent.d.ts +174 -0
  281. package/dist/messageContent.d.ts.map +1 -0
  282. package/dist/messageContent.js +405 -0
  283. package/dist/messageContent.js.map +1 -0
  284. package/dist/mutationEpoch.d.ts +83 -0
  285. package/dist/mutationEpoch.d.ts.map +1 -0
  286. package/dist/mutationEpoch.js +109 -0
  287. package/dist/mutationEpoch.js.map +1 -0
  288. package/dist/obo.d.ts +144 -0
  289. package/dist/obo.d.ts.map +1 -0
  290. package/dist/obo.js +135 -0
  291. package/dist/obo.js.map +1 -0
  292. package/dist/opusTransport.d.ts +113 -0
  293. package/dist/opusTransport.d.ts.map +1 -0
  294. package/dist/opusTransport.js +170 -0
  295. package/dist/opusTransport.js.map +1 -0
  296. package/dist/pagination.d.ts +18 -0
  297. package/dist/pagination.d.ts.map +1 -0
  298. package/dist/pagination.js +26 -0
  299. package/dist/pagination.js.map +1 -0
  300. package/dist/platformAssistant.d.ts +55 -1
  301. package/dist/platformAssistant.d.ts.map +1 -1
  302. package/dist/platformAssistant.js +39 -1
  303. package/dist/platformAssistant.js.map +1 -1
  304. package/dist/pollUtils.d.ts +19 -0
  305. package/dist/pollUtils.d.ts.map +1 -0
  306. package/dist/pollUtils.js +35 -0
  307. package/dist/pollUtils.js.map +1 -0
  308. package/dist/questLog.d.ts +232 -0
  309. package/dist/questLog.d.ts.map +1 -0
  310. package/dist/questLog.js +522 -0
  311. package/dist/questLog.js.map +1 -0
  312. package/dist/reactor/dmDirectiveToExperience.d.ts +300 -0
  313. package/dist/reactor/dmDirectiveToExperience.d.ts.map +1 -0
  314. package/dist/reactor/dmDirectiveToExperience.js +401 -0
  315. package/dist/reactor/dmDirectiveToExperience.js.map +1 -0
  316. package/dist/reactor/dmSceneControlPrompt.d.ts.map +1 -1
  317. package/dist/reactor/dmSceneControlPrompt.js +64 -2
  318. package/dist/reactor/dmSceneControlPrompt.js.map +1 -1
  319. package/dist/reactor/dmWorldEntry.d.ts +1278 -0
  320. package/dist/reactor/dmWorldEntry.d.ts.map +1 -0
  321. package/dist/reactor/dmWorldEntry.js +1396 -0
  322. package/dist/reactor/dmWorldEntry.js.map +1 -0
  323. package/dist/reactor/framePromptCompaction.d.ts +223 -0
  324. package/dist/reactor/framePromptCompaction.d.ts.map +1 -0
  325. package/dist/reactor/framePromptCompaction.js +393 -0
  326. package/dist/reactor/framePromptCompaction.js.map +1 -0
  327. package/dist/reactor/frameWorldBind.d.ts +86 -0
  328. package/dist/reactor/frameWorldBind.d.ts.map +1 -0
  329. package/dist/reactor/frameWorldBind.js +79 -0
  330. package/dist/reactor/frameWorldBind.js.map +1 -0
  331. package/dist/reactor/happyOysterSeed.d.ts +166 -0
  332. package/dist/reactor/happyOysterSeed.d.ts.map +1 -0
  333. package/dist/reactor/happyOysterSeed.js +233 -0
  334. package/dist/reactor/happyOysterSeed.js.map +1 -0
  335. package/dist/reactor/happyOysterWalk.d.ts +274 -0
  336. package/dist/reactor/happyOysterWalk.d.ts.map +1 -0
  337. package/dist/reactor/happyOysterWalk.js +407 -0
  338. package/dist/reactor/happyOysterWalk.js.map +1 -0
  339. package/dist/reactor/happyOysterWorld.d.ts +718 -0
  340. package/dist/reactor/happyOysterWorld.d.ts.map +1 -0
  341. package/dist/reactor/happyOysterWorld.js +826 -0
  342. package/dist/reactor/happyOysterWorld.js.map +1 -0
  343. package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -1
  344. package/dist/reactor/heliosCommandDispatcher.js +5 -2
  345. package/dist/reactor/heliosCommandDispatcher.js.map +1 -1
  346. package/dist/reactor/hiddenWorldLifecycle.d.ts +101 -0
  347. package/dist/reactor/hiddenWorldLifecycle.d.ts.map +1 -0
  348. package/dist/reactor/hiddenWorldLifecycle.js +119 -0
  349. package/dist/reactor/hiddenWorldLifecycle.js.map +1 -0
  350. package/dist/reactor/imageCanvas.d.ts +15 -0
  351. package/dist/reactor/imageCanvas.d.ts.map +1 -0
  352. package/dist/reactor/imageCanvas.js +33 -0
  353. package/dist/reactor/imageCanvas.js.map +1 -0
  354. package/dist/reactor/index.d.ts +19 -0
  355. package/dist/reactor/index.d.ts.map +1 -1
  356. package/dist/reactor/index.js +78 -0
  357. package/dist/reactor/index.js.map +1 -1
  358. package/dist/reactor/longLiveCommandDispatcher.d.ts +23 -8
  359. package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -1
  360. package/dist/reactor/longLiveCommandDispatcher.js +16 -4
  361. package/dist/reactor/longLiveCommandDispatcher.js.map +1 -1
  362. package/dist/reactor/longLiveSceneEntry.d.ts +203 -0
  363. package/dist/reactor/longLiveSceneEntry.d.ts.map +1 -0
  364. package/dist/reactor/longLiveSceneEntry.js +280 -0
  365. package/dist/reactor/longLiveSceneEntry.js.map +1 -0
  366. package/dist/reactor/momentCut.d.ts +153 -0
  367. package/dist/reactor/momentCut.d.ts.map +1 -0
  368. package/dist/reactor/momentCut.js +142 -0
  369. package/dist/reactor/momentCut.js.map +1 -0
  370. package/dist/reactor/promptAddonRegistry.d.ts +39 -3
  371. package/dist/reactor/promptAddonRegistry.d.ts.map +1 -1
  372. package/dist/reactor/promptAddonRegistry.js +42 -3
  373. package/dist/reactor/promptAddonRegistry.js.map +1 -1
  374. package/dist/reactor/promptTemplatePreview.d.ts +97 -0
  375. package/dist/reactor/promptTemplatePreview.d.ts.map +1 -0
  376. package/dist/reactor/promptTemplatePreview.js +185 -0
  377. package/dist/reactor/promptTemplatePreview.js.map +1 -0
  378. package/dist/reactor/reactorAvailability.d.ts +80 -0
  379. package/dist/reactor/reactorAvailability.d.ts.map +1 -0
  380. package/dist/reactor/reactorAvailability.js +121 -0
  381. package/dist/reactor/reactorAvailability.js.map +1 -0
  382. package/dist/reactor/reactorSessionRefusal.d.ts +125 -0
  383. package/dist/reactor/reactorSessionRefusal.d.ts.map +1 -0
  384. package/dist/reactor/reactorSessionRefusal.js +197 -0
  385. package/dist/reactor/reactorSessionRefusal.js.map +1 -0
  386. package/dist/reactor/reactorTokenScope.d.ts +47 -0
  387. package/dist/reactor/reactorTokenScope.d.ts.map +1 -0
  388. package/dist/reactor/reactorTokenScope.js +64 -0
  389. package/dist/reactor/reactorTokenScope.js.map +1 -0
  390. package/dist/reactor/resolveDirectorBeats.d.ts +65 -0
  391. package/dist/reactor/resolveDirectorBeats.d.ts.map +1 -0
  392. package/dist/reactor/resolveDirectorBeats.js +86 -0
  393. package/dist/reactor/resolveDirectorBeats.js.map +1 -0
  394. package/dist/reactor/sanaLiveEdit.d.ts +117 -0
  395. package/dist/reactor/sanaLiveEdit.d.ts.map +1 -0
  396. package/dist/reactor/sanaLiveEdit.js +105 -0
  397. package/dist/reactor/sanaLiveEdit.js.map +1 -0
  398. package/dist/reactor/sceneEntry.d.ts +66 -9
  399. package/dist/reactor/sceneEntry.d.ts.map +1 -1
  400. package/dist/reactor/sceneEntry.js +59 -66
  401. package/dist/reactor/sceneEntry.js.map +1 -1
  402. package/dist/reactor/sceneSeedImage.d.ts +199 -0
  403. package/dist/reactor/sceneSeedImage.d.ts.map +1 -0
  404. package/dist/reactor/sceneSeedImage.js +239 -0
  405. package/dist/reactor/sceneSeedImage.js.map +1 -0
  406. package/dist/reactor/seedImageOrchestrator.d.ts +70 -3
  407. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  408. package/dist/reactor/seedImageOrchestrator.js +92 -28
  409. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  410. package/dist/reactor/toolPromptAddon.d.ts.map +1 -1
  411. package/dist/reactor/toolPromptAddon.js +16 -2
  412. package/dist/reactor/toolPromptAddon.js.map +1 -1
  413. package/dist/reactor/worldMintLoop.d.ts +286 -0
  414. package/dist/reactor/worldMintLoop.d.ts.map +1 -0
  415. package/dist/reactor/worldMintLoop.js +381 -0
  416. package/dist/reactor/worldMintLoop.js.map +1 -0
  417. package/dist/reactor/worldSteerOutcome.d.ts +98 -0
  418. package/dist/reactor/worldSteerOutcome.d.ts.map +1 -0
  419. package/dist/reactor/worldSteerOutcome.js +81 -0
  420. package/dist/reactor/worldSteerOutcome.js.map +1 -0
  421. package/dist/retryAfter.d.ts +15 -0
  422. package/dist/retryAfter.d.ts.map +1 -0
  423. package/dist/retryAfter.js +75 -0
  424. package/dist/retryAfter.js.map +1 -0
  425. package/dist/seriesKey.d.ts +31 -0
  426. package/dist/seriesKey.d.ts.map +1 -0
  427. package/dist/seriesKey.js +33 -0
  428. package/dist/seriesKey.js.map +1 -0
  429. package/dist/sessionRefresh.d.ts +135 -0
  430. package/dist/sessionRefresh.d.ts.map +1 -0
  431. package/dist/sessionRefresh.js +215 -0
  432. package/dist/sessionRefresh.js.map +1 -0
  433. package/dist/sharedAudioContext.d.ts +39 -0
  434. package/dist/sharedAudioContext.d.ts.map +1 -0
  435. package/dist/sharedAudioContext.js +63 -0
  436. package/dist/sharedAudioContext.js.map +1 -0
  437. package/dist/singleFlight.d.ts +51 -0
  438. package/dist/singleFlight.d.ts.map +1 -0
  439. package/dist/singleFlight.js +87 -0
  440. package/dist/singleFlight.js.map +1 -0
  441. package/dist/storyGraph.d.ts +83 -0
  442. package/dist/storyGraph.d.ts.map +1 -1
  443. package/dist/storyGraph.js +169 -4
  444. package/dist/storyGraph.js.map +1 -1
  445. package/dist/storyboardMask.d.ts +343 -0
  446. package/dist/storyboardMask.d.ts.map +1 -0
  447. package/dist/storyboardMask.js +505 -0
  448. package/dist/storyboardMask.js.map +1 -0
  449. package/dist/storyboardTimeline.d.ts +93 -0
  450. package/dist/storyboardTimeline.d.ts.map +1 -0
  451. package/dist/storyboardTimeline.js +131 -0
  452. package/dist/storyboardTimeline.js.map +1 -0
  453. package/dist/studioAutomation.d.ts +104 -0
  454. package/dist/studioAutomation.d.ts.map +1 -0
  455. package/dist/studioAutomation.js +178 -0
  456. package/dist/studioAutomation.js.map +1 -0
  457. package/dist/tenantClaim.d.ts +86 -0
  458. package/dist/tenantClaim.d.ts.map +1 -0
  459. package/dist/tenantClaim.js +164 -0
  460. package/dist/tenantClaim.js.map +1 -0
  461. package/dist/timeFormat.d.ts +25 -0
  462. package/dist/timeFormat.d.ts.map +1 -1
  463. package/dist/timeFormat.js +56 -0
  464. package/dist/timeFormat.js.map +1 -1
  465. package/dist/toolSchemas.d.ts +58 -10
  466. package/dist/toolSchemas.d.ts.map +1 -1
  467. package/dist/toolSchemas.js +37 -9
  468. package/dist/toolSchemas.js.map +1 -1
  469. package/dist/transport.d.ts +120 -0
  470. package/dist/transport.d.ts.map +1 -0
  471. package/dist/transport.js +282 -0
  472. package/dist/transport.js.map +1 -0
  473. package/dist/videoGenFacade.d.ts +63 -0
  474. package/dist/videoGenFacade.d.ts.map +1 -0
  475. package/dist/videoGenFacade.js +49 -0
  476. package/dist/videoGenFacade.js.map +1 -0
  477. package/dist/visemeScheduler.d.ts +24 -2
  478. package/dist/visemeScheduler.d.ts.map +1 -1
  479. package/dist/visemeScheduler.js +31 -2
  480. package/dist/visemeScheduler.js.map +1 -1
  481. package/dist/vision/VisionPublisher.d.ts +88 -0
  482. package/dist/vision/VisionPublisher.d.ts.map +1 -1
  483. package/dist/vision/VisionPublisher.js +196 -13
  484. package/dist/vision/VisionPublisher.js.map +1 -1
  485. package/dist/vision/VisionSourceController.d.ts +67 -1
  486. package/dist/vision/VisionSourceController.d.ts.map +1 -1
  487. package/dist/vision/VisionSourceController.js +147 -5
  488. package/dist/vision/VisionSourceController.js.map +1 -1
  489. package/dist/vision/index.d.ts +2 -1
  490. package/dist/vision/index.d.ts.map +1 -1
  491. package/dist/vision/index.js +2 -1
  492. package/dist/vision/index.js.map +1 -1
  493. package/dist/vision/sourceKinds.d.ts +18 -5
  494. package/dist/vision/sourceKinds.d.ts.map +1 -1
  495. package/dist/vision/sourceKinds.js +15 -2
  496. package/dist/vision/sourceKinds.js.map +1 -1
  497. package/dist/vision/types.d.ts +7 -4
  498. package/dist/vision/types.d.ts.map +1 -1
  499. package/dist/vision/visionErrors.d.ts +45 -0
  500. package/dist/vision/visionErrors.d.ts.map +1 -0
  501. package/dist/vision/visionErrors.js +66 -0
  502. package/dist/vision/visionErrors.js.map +1 -0
  503. package/dist/voiceCloneCaption.d.ts +33 -0
  504. package/dist/voiceCloneCaption.d.ts.map +1 -0
  505. package/dist/voiceCloneCaption.js +69 -0
  506. package/dist/voiceCloneCaption.js.map +1 -0
  507. package/dist/websocket.d.ts +273 -10
  508. package/dist/websocket.d.ts.map +1 -1
  509. package/dist/websocket.js +79 -0
  510. package/dist/websocket.js.map +1 -1
  511. package/dist/workflowAuthoring.d.ts +139 -0
  512. package/dist/workflowAuthoring.d.ts.map +1 -0
  513. package/dist/workflowAuthoring.js +557 -0
  514. package/dist/workflowAuthoring.js.map +1 -0
  515. package/package.json +15 -5
  516. package/src/__tests__/adapters-director.test.ts +9 -6
  517. package/src/__tests__/adapters-extraction.test.ts +175 -0
  518. package/src/__tests__/adapters-image.test.ts +66 -0
  519. package/src/__tests__/adapters-momentPolicy.test.ts +218 -0
  520. package/src/__tests__/adapters-platform.test.ts +110 -4
  521. package/src/__tests__/adapters-videogen.test.ts +53 -0
  522. package/src/__tests__/adapters-world.test.ts +117 -7
  523. package/src/__tests__/admin.enhancement-defaults.test.ts +115 -0
  524. package/src/__tests__/admin.test.ts +282 -0
  525. package/src/__tests__/adventures-world-state.test.ts +156 -0
  526. package/src/__tests__/adventures.test.ts +111 -1
  527. package/src/__tests__/api-pollers.test.ts +113 -23
  528. package/src/__tests__/api.adventure-definitions.test.ts +312 -0
  529. package/src/__tests__/api.anchor-beat.test.ts +75 -0
  530. package/src/__tests__/api.arc-approval.test.ts +171 -0
  531. package/src/__tests__/api.arc-beats-floor.test.ts +56 -0
  532. package/src/__tests__/api.arc-generation.test.ts +168 -0
  533. package/src/__tests__/api.arc-templates.test.ts +78 -0
  534. package/src/__tests__/api.assignVideoSeries.test.ts +81 -0
  535. package/src/__tests__/api.cast-frame-choices.test.ts +141 -0
  536. package/src/__tests__/api.cutscene-registry.test.ts +148 -0
  537. package/src/__tests__/api.enhancement-addition-actions.test.ts +137 -0
  538. package/src/__tests__/api.enrichVideo-serialization.test.ts +116 -0
  539. package/src/__tests__/api.extraction-base.test.ts +87 -0
  540. package/src/__tests__/api.generateVideo-cutscene.test.ts +148 -0
  541. package/src/__tests__/api.job-pipeline-stages.test.ts +128 -0
  542. package/src/__tests__/api.list-images-filters.test.ts +6 -3
  543. package/src/__tests__/api.quest-curation.test.ts +169 -0
  544. package/src/__tests__/api.reprocessVideo.test.ts +71 -0
  545. package/src/__tests__/api.scene-split-merge.test.ts +129 -0
  546. package/src/__tests__/api.session-quests.test.ts +184 -0
  547. package/src/__tests__/api.test.ts +122 -0
  548. package/src/__tests__/api.transferSeries.test.ts +114 -0
  549. package/src/__tests__/api.unknown-clusters.test.ts +225 -0
  550. package/src/__tests__/api.uploadVideo-options.test.ts +156 -0
  551. package/src/__tests__/arcPreview.test.ts +71 -0
  552. package/src/__tests__/arcStyleProfile.test.ts +204 -0
  553. package/src/__tests__/artifacts-delete.test.ts +109 -0
  554. package/src/__tests__/audio.test.ts +864 -5
  555. package/src/__tests__/audioDsp.test.ts +196 -0
  556. package/src/__tests__/audioUnavailable.test.ts +43 -0
  557. package/src/__tests__/cast.test.ts +10 -1
  558. package/src/__tests__/castCurationProjection.test.ts +84 -0
  559. package/src/__tests__/castFramePipelinePending.test.ts +171 -0
  560. package/src/__tests__/castProjection.test.ts +497 -5
  561. package/src/__tests__/characterGrounding.test.ts +357 -0
  562. package/src/__tests__/contract.test.ts +97 -0
  563. package/src/__tests__/conversation/chatSessionStore.test.ts +243 -0
  564. package/src/__tests__/conversation/controller.test.ts +211 -0
  565. package/src/__tests__/conversation/readSequencer.test.ts +52 -0
  566. package/src/__tests__/conversation/rosterProjection.test.ts +204 -3
  567. package/src/__tests__/conversation/runtime.test.ts +118 -1
  568. package/src/__tests__/conversation/voice.test.ts +741 -7
  569. package/src/__tests__/creatorCuration.test.ts +256 -0
  570. package/src/__tests__/creatorDashboard.test.ts +444 -0
  571. package/src/__tests__/creatorUniverse.test.ts +138 -0
  572. package/src/__tests__/curationWrite.test.ts +179 -0
  573. package/src/__tests__/decisions.test.ts +89 -0
  574. package/src/__tests__/designTokens.test.ts +72 -0
  575. package/src/__tests__/dialogAttribution.test.ts +187 -0
  576. package/src/__tests__/dmDirectiveToExperience.test.ts +198 -0
  577. package/src/__tests__/dmWorldEntry.test.ts +2102 -0
  578. package/src/__tests__/enhancementDiff.test.ts +132 -0
  579. package/src/__tests__/experienceModelCatalog.test.ts +292 -0
  580. package/src/__tests__/extractionStageState.test.ts +67 -0
  581. package/src/__tests__/getVideo.test.ts +95 -0
  582. package/src/__tests__/graphReadAfterWrite.test.ts +211 -0
  583. package/src/__tests__/graphSchema.test.ts +55 -4
  584. package/src/__tests__/happyOysterSeed.test.ts +208 -0
  585. package/src/__tests__/happyOysterWorld.test.ts +1241 -0
  586. package/src/__tests__/happyOysterWorldRefusal.test.ts +224 -0
  587. package/src/__tests__/hiddenWorldLifecycle.test.ts +203 -0
  588. package/src/__tests__/http.session-refresh.test.ts +424 -0
  589. package/src/__tests__/http.test.ts +316 -0
  590. package/src/__tests__/identity.test.ts +132 -0
  591. package/src/__tests__/loadBundleManifest.test.ts +192 -22
  592. package/src/__tests__/longLiveSceneEntry.test.ts +371 -0
  593. package/src/__tests__/me.test.ts +74 -0
  594. package/src/__tests__/messageContent.test.ts +395 -0
  595. package/src/__tests__/momentCut.test.ts +229 -0
  596. package/src/__tests__/mutationEpoch.test.ts +218 -0
  597. package/src/__tests__/obo.test.ts +159 -0
  598. package/src/__tests__/opusTransport.test.ts +182 -0
  599. package/src/__tests__/opusTransportLibopus.test.ts +125 -0
  600. package/src/__tests__/orgs.test.ts +229 -0
  601. package/src/__tests__/persona-generation.test.ts +208 -1
  602. package/src/__tests__/platformAssistant.test.ts +140 -0
  603. package/src/__tests__/projects.test.ts +338 -0
  604. package/src/__tests__/promptTemplatePreview.test.ts +160 -0
  605. package/src/__tests__/reactor/__fixtures__/realFramePromptText.ts +23 -0
  606. package/src/__tests__/reactor/api-reactor.test.ts +60 -21
  607. package/src/__tests__/reactor/framePromptCompaction.test.ts +300 -0
  608. package/src/__tests__/reactor/promptAddonRegistry.test.ts +79 -0
  609. package/src/__tests__/reactor/reactorTokenScope.test.ts +50 -0
  610. package/src/__tests__/reactor/resolveDirectorBeats.test.ts +156 -0
  611. package/src/__tests__/reactor/sceneEntry.test.ts +3 -0
  612. package/src/__tests__/reactor/sceneSeedImage.test.ts +361 -0
  613. package/src/__tests__/reactor/seedImageOrchestrator.test.ts +43 -5
  614. package/src/__tests__/reactor-happyOysterWalk.test.ts +294 -0
  615. package/src/__tests__/reactorAvailability.test.ts +217 -0
  616. package/src/__tests__/reactorSessionRefusal.test.ts +189 -0
  617. package/src/__tests__/regeneration.test.ts +9 -9
  618. package/src/__tests__/reprocessBlockedReason.test.ts +30 -0
  619. package/src/__tests__/retryAfter.test.ts +65 -0
  620. package/src/__tests__/roleClaim.test.ts +102 -0
  621. package/src/__tests__/sanaLiveEdit.test.ts +84 -0
  622. package/src/__tests__/seriesKey.test.ts +24 -0
  623. package/src/__tests__/settings-set9.test.ts +238 -0
  624. package/src/__tests__/singleFlight.test.ts +348 -0
  625. package/src/__tests__/storyGraph.test.ts +111 -1
  626. package/src/__tests__/storyboardFrameCutscene.test.ts +115 -0
  627. package/src/__tests__/storyboardMask.test.ts +527 -0
  628. package/src/__tests__/storyboardTimeline.test.ts +228 -0
  629. package/src/__tests__/storyboards.test.ts +639 -0
  630. package/src/__tests__/studioAutomation.test.ts +325 -0
  631. package/src/__tests__/toolSchemas.test.ts +11 -18
  632. package/src/__tests__/transport.test.ts +312 -0
  633. package/src/__tests__/videoGenFacade.test.ts +141 -0
  634. package/src/__tests__/videoGraph.test.ts +43 -1
  635. package/src/__tests__/visemeScheduler.test.ts +55 -1
  636. package/src/__tests__/visibility.test.ts +143 -0
  637. package/src/__tests__/voiceCloneCaption.test.ts +80 -0
  638. package/src/__tests__/voiceFallback.test.ts +55 -0
  639. package/src/__tests__/websocket-error-turn-ended.test.ts +49 -0
  640. package/src/__tests__/websocket-vision.test.ts +141 -0
  641. package/src/__tests__/websocket.test.ts +75 -1
  642. package/src/__tests__/workflowAuthoring.test.ts +187 -0
  643. package/src/__tests__/workflows.test.ts +640 -0
  644. package/src/__tests__/worldMintLoop.test.ts +448 -0
  645. package/src/__tests__/worldModelPreference.test.ts +302 -0
  646. package/src/__tests__/worldModelTradeoffs.test.ts +89 -0
  647. package/src/__tests__/worldSteerOutcome.test.ts +62 -0
  648. package/src/adapters/capabilities.ts +39 -3
  649. package/src/adapters/directorAdapter.ts +5 -4
  650. package/src/adapters/experienceModelCatalog.ts +538 -0
  651. package/src/adapters/extractionAdapter.ts +150 -0
  652. package/src/adapters/imageAdapter.ts +5 -1
  653. package/src/adapters/index.ts +104 -17
  654. package/src/adapters/momentDirective.ts +109 -0
  655. package/src/adapters/momentPolicy.ts +209 -0
  656. package/src/adapters/registry.ts +1 -1
  657. package/src/adapters/videoGenAdapter.ts +124 -0
  658. package/src/adapters/worldAdapter.ts +221 -16
  659. package/src/adapters/worldModelPreference.ts +247 -0
  660. package/src/adapters/worldModelTradeoffs.ts +247 -0
  661. package/src/admin.ts +842 -16
  662. package/src/api.ts +12687 -3446
  663. package/src/arcBoardJoin.ts +46 -0
  664. package/src/arcPreview.ts +103 -0
  665. package/src/audio.ts +691 -130
  666. package/src/audioDsp.ts +132 -0
  667. package/src/audioProtocol.ts +235 -0
  668. package/src/beatTitles.ts +51 -0
  669. package/src/castProjection.ts +311 -0
  670. package/src/characterGrounding.ts +491 -0
  671. package/src/conversation/binding.ts +13 -0
  672. package/src/conversation/chatSessionStore.ts +281 -0
  673. package/src/conversation/controller.ts +96 -3
  674. package/src/conversation/index.ts +2 -0
  675. package/src/conversation/participant.ts +16 -0
  676. package/src/conversation/readSequencer.ts +55 -0
  677. package/src/conversation/roster.ts +5 -1
  678. package/src/conversation/rosterProjection.ts +166 -2
  679. package/src/conversation/runtime.ts +66 -7
  680. package/src/conversation/types.ts +43 -4
  681. package/src/conversation/voice.ts +655 -51
  682. package/src/creatorCuration.ts +316 -0
  683. package/src/creatorDashboard.ts +344 -0
  684. package/src/creatorUniverse.ts +222 -0
  685. package/src/curationWrite.ts +108 -0
  686. package/src/designTokens.ts +157 -0
  687. package/src/dialogAttribution.ts +182 -0
  688. package/src/dmRunWorldReadiness.ts +1168 -0
  689. package/src/domains/access.ts +92 -0
  690. package/src/domains/adventureDefinitions.ts +313 -0
  691. package/src/domains/adventures.ts +557 -0
  692. package/src/domains/arcs.ts +350 -0
  693. package/src/domains/artifacts.ts +349 -0
  694. package/src/domains/chat.ts +338 -0
  695. package/src/domains/decisions.ts +62 -0
  696. package/src/domains/documents.ts +389 -0
  697. package/src/domains/enhancements.ts +259 -0
  698. package/src/domains/graph.ts +959 -0
  699. package/src/domains/images.ts +451 -0
  700. package/src/domains/ingestion.ts +695 -0
  701. package/src/domains/me.ts +27 -0
  702. package/src/domains/orgs.ts +168 -0
  703. package/src/domains/personas.ts +440 -0
  704. package/src/domains/projects.ts +177 -0
  705. package/src/domains/quests.ts +587 -0
  706. package/src/domains/reactor.ts +163 -0
  707. package/src/domains/showcase.ts +35 -0
  708. package/src/domains/storyboards.ts +1698 -0
  709. package/src/domains/studioSettings.ts +149 -0
  710. package/src/domains/universes.ts +433 -0
  711. package/src/domains/userDefaults.ts +37 -0
  712. package/src/domains/visemeBundles.ts +541 -0
  713. package/src/domains/workflows.ts +376 -0
  714. package/src/enhancementDiff.ts +171 -0
  715. package/src/generated/contract.ts +1016 -0
  716. package/src/graphSchema.ts +154 -6
  717. package/src/http.ts +295 -11
  718. package/src/identity.ts +123 -0
  719. package/src/index.ts +131 -0
  720. package/src/messageContent.ts +500 -0
  721. package/src/mutationEpoch.ts +107 -0
  722. package/src/obo.ts +201 -0
  723. package/src/opusTransport.ts +268 -0
  724. package/src/pagination.ts +29 -0
  725. package/src/platformAssistant.ts +97 -1
  726. package/src/pollUtils.ts +35 -0
  727. package/src/questLog.ts +704 -0
  728. package/src/reactor/dmDirectiveToExperience.ts +636 -0
  729. package/src/reactor/dmSceneControlPrompt.ts +69 -2
  730. package/src/reactor/dmWorldEntry.ts +2226 -0
  731. package/src/reactor/framePromptCompaction.ts +544 -0
  732. package/src/reactor/frameWorldBind.ts +133 -0
  733. package/src/reactor/happyOysterSeed.ts +329 -0
  734. package/src/reactor/happyOysterWalk.ts +541 -0
  735. package/src/reactor/happyOysterWorld.ts +1270 -0
  736. package/src/reactor/heliosCommandDispatcher.ts +5 -1
  737. package/src/reactor/hiddenWorldLifecycle.ts +182 -0
  738. package/src/reactor/imageCanvas.ts +38 -0
  739. package/src/reactor/index.ts +78 -0
  740. package/src/reactor/longLiveCommandDispatcher.ts +23 -8
  741. package/src/reactor/longLiveSceneEntry.ts +409 -0
  742. package/src/reactor/momentCut.ts +219 -0
  743. package/src/reactor/promptAddonRegistry.ts +81 -3
  744. package/src/reactor/promptTemplatePreview.ts +240 -0
  745. package/src/reactor/reactorAvailability.ts +155 -0
  746. package/src/reactor/reactorSessionRefusal.ts +260 -0
  747. package/src/reactor/reactorTokenScope.ts +69 -0
  748. package/src/reactor/resolveDirectorBeats.ts +140 -0
  749. package/src/reactor/sanaLiveEdit.ts +158 -0
  750. package/src/reactor/sceneEntry.ts +106 -88
  751. package/src/reactor/sceneSeedImage.ts +338 -0
  752. package/src/reactor/seedImageOrchestrator.ts +116 -34
  753. package/src/reactor/toolPromptAddon.ts +16 -2
  754. package/src/reactor/worldMintLoop.ts +545 -0
  755. package/src/reactor/worldSteerOutcome.ts +132 -0
  756. package/src/retryAfter.ts +71 -0
  757. package/src/seriesKey.ts +42 -0
  758. package/src/sessionRefresh.ts +237 -0
  759. package/src/sharedAudioContext.ts +67 -0
  760. package/src/singleFlight.ts +91 -0
  761. package/src/storyGraph.ts +247 -4
  762. package/src/storyboardMask.ts +756 -0
  763. package/src/storyboardTimeline.ts +220 -0
  764. package/src/studioAutomation.ts +208 -0
  765. package/src/tenantClaim.ts +170 -0
  766. package/src/timeFormat.ts +51 -0
  767. package/src/toolSchemas.ts +40 -10
  768. package/src/transport.ts +327 -0
  769. package/src/videoGenFacade.ts +90 -0
  770. package/src/visemeScheduler.ts +36 -3
  771. package/src/vision/VisionPublisher.ts +204 -14
  772. package/src/vision/VisionSourceController.ts +187 -6
  773. package/src/vision/__tests__/VisionPublisher.kvs.test.ts +50 -0
  774. package/src/vision/__tests__/VisionPublisher.test.ts +291 -0
  775. package/src/vision/__tests__/VisionSourceController.test.ts +376 -6
  776. package/src/vision/index.ts +5 -1
  777. package/src/vision/sourceKinds.ts +19 -5
  778. package/src/vision/types.ts +7 -4
  779. package/src/vision/visionErrors.ts +70 -0
  780. package/src/voiceCloneCaption.ts +77 -0
  781. package/src/websocket.ts +361 -12
  782. package/src/workflowAuthoring.ts +664 -0
@@ -0,0 +1,2226 @@
1
+ /**
2
+ * DM world entry — the client half of §Q `DM.1`: a DM `[SCENE:enter_world]`
3
+ * directive opens a HappyOyster world SEEDED FROM THE RATIFIED STORYBOARD
4
+ * FRAME for the beat the party is standing on.
5
+ *
6
+ * Nothing here is a new mechanism. `happyOysterWorld.ts` already owns the
7
+ * lifecycle, the permanent `{encryptedWorldId, mode}` handle and the error
8
+ * taxonomy; `happyOysterSeed.ts` already owns crop-then-encode; the directive
9
+ * pipeline already parses the tag. This module owns only the decisions that
10
+ * stand between an LLM-emitted tag and a PERMANENT, BILLED, UNLISTABLE asset,
11
+ * and it owns them in ONE place so no surface can re-derive them differently.
12
+ *
13
+ * ## The owner's ruling: OPT-IN AUTO-FIRE WITH RAILS, not a blanket gate
14
+ *
15
+ * (Owner, 2026-07-28: *"user should be able to allow dm to auto-fire (as long
16
+ * as there aren't any hidden sessions or lost sessions and they can easily be
17
+ * stopped. And they timeout after an interval … default to 30 seconds)"*.) The
18
+ * four rails, and where each one lives:
19
+ *
20
+ * 1. **Opt-in.** {@link DmWorldEntryPlanInput.autoFireEnabled} defaults to
21
+ * `false` ({@link DM_WORLD_AUTO_FIRE_DEFAULT}). With it off, every create
22
+ * is `confirm_required` and {@link launchDmWorldEntry} REFUSES to run one
23
+ * without an explicit operator confirmation.
24
+ * 2. **No hidden or lost sessions.** Every handle a launch produces goes to
25
+ * `onWorldHandle`, at THREE points (§Q `DM.43`): at MINT time, the instant
26
+ * the vendor returns a world id and BEFORE `startTravel`; on success; and
27
+ * from `HappyOysterLaunchError.handle`, i.e. including a world that was
28
+ * created and billed but whose `startTravel` failed. The mint-time offer
29
+ * is the load-bearing one — `startTravel` can occupy minutes, and the two
30
+ * settle-time offers only fire once it is over.
31
+ * {@link rememberDmWorldEntry} keeps the session's
32
+ * list so a surface can show what it opened and reattach to it, and
33
+ * {@link collectDmWorldRecords} (§Q `DM.24`) is the DURABLE-FIRST read of
34
+ * it: the board's `StoryboardFrame.worldId` bindings, which survive a
35
+ * reload, plus whatever the session knows that the board does not yet.
36
+ * 3. **Easily stopped.** Auto-fired plans carry
37
+ * {@link DmWorldEntryPlan.autoStopAfterMs}; the pane arms that deadline and
38
+ * the existing "Back to the party" exit is the manual stop.
39
+ * 4. **Timeout, default 30 s** — {@link DM_WORLD_AUTO_STOP_MS_DEFAULT},
40
+ * overridable per call by the studio setting once that store exists.
41
+ *
42
+ * **What actually bounds vendor cost is CREATION FREQUENCY, not run time.** A
43
+ * timeout stops a world streaming; it cannot un-bill a world already created.
44
+ * So auto-fire rides the owner's `DM.12` ruling — *"regenerate the world at
45
+ * scene changes, have the DM issue instruct commands based on the storyboard
46
+ * and user choices otherwise"*: a live world whose scene has not changed is
47
+ * STEERED (`'steer'` ⇒ `instruct`, free), a frame that already owns a world is
48
+ * REOPENED (`'reopen'` ⇒ `attachWorld`, free), and `createWorld` fires only on
49
+ * a genuine scene change. That caps creation at one per scene rather than one
50
+ * per LLM emission, which was the real hazard.
51
+ *
52
+ * ## Two things that are NOT relaxed by any of the above
53
+ *
54
+ * - **The seed is BYTES, never a URL.** `createWorld({firstFrameImageUrl})` is
55
+ * forwarded verbatim with no client guard, frames are stored PNG with no
56
+ * byte guarantee, and the presigned frame URL expires — each of those fails
57
+ * AFTER the world is billed. `prepareHappyOysterSeedFromUrl` converts all
58
+ * three into PRE-billing throws for the cost of one client-side fetch, and
59
+ * the launcher refuses to create without prepared bytes in hand.
60
+ * - **The frame is resolved DETERMINISTICALLY, never from the tag.**
61
+ * {@link resolveDmWorldEntryFrame} joins the ACTIVE BEAT to a board frame
62
+ * through `StoryboardFrame.beatId` (the documented join to quests'
63
+ * `sourceBeatId`). The tag's free text is ATMOSPHERE ONLY, appended to the
64
+ * frame's server-compiled prompt. A hallucinated id can never select,
65
+ * replace or mis-address the seed — a risk that goes UP, not down, with
66
+ * auto-fire on.
67
+ *
68
+ * Framework- and SDK-agnostic, like the rest of `reactor/`: pure data plus the
69
+ * structural {@link HappyOysterBridge}.
70
+ *
71
+ * PARKED, deliberately not decided here: §Q `DM.1` Q3 (are DM worlds always
72
+ * `adventure`?) stays open on `SB-W.4`, so `mode` is a REQUIRED input the host
73
+ * supplies rather than a default this module picks.
74
+ */
75
+
76
+ import {
77
+ frameImageUrl,
78
+ frameRenderFailed,
79
+ frameRenderFailure,
80
+ orderStoryboardFrames,
81
+ promptFrameVariant,
82
+ type StoryboardFrame,
83
+ } from '../domains/storyboards';
84
+ import { beatHeadline } from '../beatTitles';
85
+ import type { BeatView } from '../storyGraph';
86
+ import { compactFramePromptText } from './framePromptCompaction';
87
+ import type { PreparedHappyOysterSeed } from './happyOysterSeed';
88
+ import {
89
+ HAPPY_OYSTER_BUILD_FAST_MS,
90
+ HAPPY_OYSTER_BUILD_OBSERVED_MAX_MS,
91
+ HAPPY_OYSTER_PROMPT_MAX_CHARS,
92
+ HAPPY_OYSTER_STREAM_START_TIMEOUT_MS,
93
+ HappyOysterLaunchError,
94
+ happyOysterPromptIssue,
95
+ launchHappyOysterWorld,
96
+ type HappyOysterBridge,
97
+ type HappyOysterFailureReason,
98
+ type HappyOysterLaunchResult,
99
+ type HappyOysterMode,
100
+ type HappyOysterWorldHandle,
101
+ } from './happyOysterWorld';
102
+ import {
103
+ reactorSessionRefusalDetail,
104
+ reactorSessionRefusalTitle,
105
+ type ReactorSessionRefusal,
106
+ } from './reactorSessionRefusal';
107
+
108
+ /**
109
+ * Whether the DM may open a world WITHOUT asking, when the host supplies no
110
+ * setting. `false` — the rail is opt-IN (owner 2026-07-28), so an unconfigured
111
+ * host never lets an LLM-emitted tag mint a permanent, billed asset on its own.
112
+ */
113
+ export const DM_WORLD_AUTO_FIRE_DEFAULT = false;
114
+
115
+ /**
116
+ * §Q `WORLD.1-A` — THE MODE EVERY PLAYER SURFACE OPENS A WORLD ON.
117
+ *
118
+ * `DM.23` decided this for the DM play episode and held the constant in that
119
+ * file: **on a player surface a world is always `adventure`** — the party steps
120
+ * into it while the DM narrates, and `directing` is the authoring experience
121
+ * (the World Explorer demo and, later, `SB-W.4`'s storyboard director keep
122
+ * their own picker). `DM.1` Q3 stays PARKED at the client-core level: this is a
123
+ * shared HOST default, not a decision `planDmWorldEntry` makes — `mode` is
124
+ * still a REQUIRED input there.
125
+ *
126
+ * It moved here the moment a SECOND player surface needed it. The viewer
127
+ * (`WatchShell`) reopens the very worlds the episode created, and the vendor
128
+ * fails a cross-mode reattach with `MODE_MISMATCH` — so two surfaces holding
129
+ * their own literal is a world that is permanently unreachable from one of
130
+ * them, and `planDmWorldEntry`'s `world_mode_mismatch` refusal would be the
131
+ * only warning.
132
+ */
133
+ export const DM_WORLD_MODE: HappyOysterMode = 'adventure';
134
+
135
+ /**
136
+ * How long an AUTO-FIRED world runs before the surface stops it, in ms. Owner
137
+ * default: 30 s. Studio-configurable once that setting store exists — the value
138
+ * rides {@link DmWorldEntryPlanInput.autoStopAfterMs} so the host passes the
139
+ * configured number and nothing here needs to change.
140
+ *
141
+ * This bounds RUN TIME, not spend: the world is already billed by the time it
142
+ * streams. The spend rail is the scene-change condition on `'create'`.
143
+ */
144
+ export const DM_WORLD_AUTO_STOP_MS_DEFAULT = 30_000;
145
+
146
+ /**
147
+ * Separator between the frame's server-compiled prompt and the DM tag's
148
+ * atmosphere text. The label is part of the contract: it keeps the atmosphere
149
+ * legible as a modifier of the frame rather than as a second scene description.
150
+ */
151
+ export const DM_WORLD_ATMOSPHERE_PREFIX = '\n\nAtmosphere: ';
152
+
153
+ /**
154
+ * Shortest atmosphere worth appending. If the frame's own prompt leaves less
155
+ * room than this under {@link HAPPY_OYSTER_PROMPT_MAX_CHARS}, the atmosphere is
156
+ * dropped entirely rather than shipped as a truncated fragment — the frame is
157
+ * the authority, so it is never the thing that gets cut.
158
+ */
159
+ export const DM_WORLD_ATMOSPHERE_MIN_CHARS = 24;
160
+
161
+ /**
162
+ * §Q `DM.17` — WHAT A REOPEN ACTUALLY RETURNS, in the one place every surface
163
+ * reads it from.
164
+ *
165
+ * Measured live 2026-07-28 on world `dHpmaEU0…EihKgVEbA1ghvbKh20QDdU4`: after an
166
+ * `instruct` visibly moved the world, TWO separate reattaches minutes apart both
167
+ * came back to the world as CREATED. `attachWorld` restores the seeded scene;
168
+ * the vendor persists no steered state and exposes no checkpoint API.
169
+ *
170
+ * The `DM.17` ruling is to SAY SO, not to replay. Replay cannot serve the
171
+ * affordance this notice guards —
172
+ * `↻ relive` mints a NEW session (`reliveFromSavePoint`), so a client-held steer
173
+ * log dies with the session it was kept in, and the quest ledger has no steer
174
+ * event to rebuild one from (`QUEST_EVENT_TYPES` carries none). Replaying only
175
+ * where a log happens to survive would make continuity INTERMITTENT, which is a
176
+ * worse lie than a uniform, stated limit. Durable replay is a backend row.
177
+ */
178
+ export const DM_WORLD_REOPEN_NOTICE =
179
+ 'Reopening returns this world to the scene it was created from. Steering issued while it ran is not carried over — the vendor stores no steered state.';
180
+
181
+ /**
182
+ * The continuity notice a surface must show for `action`, or `null` when the
183
+ * action carries no continuity claim to correct.
184
+ *
185
+ * Only `'reopen'` re-enters an existing world, so only `'reopen'` can silently
186
+ * imply a continuity that does not exist. `'create'`/`'confirm_required'` mint
187
+ * the scene they show, and `'steer'` re-aims the world that is already running —
188
+ * neither loses anything. Derived here so no surface re-decides it.
189
+ */
190
+ export function dmWorldReopenNotice(action: DmWorldEntryAction): string | null {
191
+ return action === 'reopen' ? DM_WORLD_REOPEN_NOTICE : null;
192
+ }
193
+
194
+ /**
195
+ * §Q `DM.42` — WHICH OF THE TWO LONG WAITS A LAUNCH IS IN.
196
+ *
197
+ * They look identical from the outside and mean opposite things:
198
+ *
199
+ * - `'building'` — `createWorld`/`attachWorld` has not returned. Measured at
200
+ * 105–240 s and entirely normal; the answer is to wait.
201
+ * - `'entering'` — the world is BUILT and `startTravel` is waiting for the
202
+ * live stream, which the vendor bounds at
203
+ * {@link HAPPY_OYSTER_STREAM_START_TIMEOUT_MS}. Waiting past that does not
204
+ * help: the SDK ends the travel itself.
205
+ *
206
+ * Collapsing them is what made a dead travel read as a slow build. Measured
207
+ * 2026-08-01 on staging: the pane held *"Reopening this world…"* for the full
208
+ * 60 s while the world's own phase was already `traveling`, then the travel
209
+ * was torn down.
210
+ */
211
+ export type DmWorldLaunchStage =
212
+ /** Fetching + cropping the seed bytes. Nothing is billed yet. */
213
+ | 'preparing'
214
+ | 'building'
215
+ | 'entering';
216
+
217
+ /**
218
+ * The SDK client phase that means "the world is done; we are opening the
219
+ * stream". `HappyOysterModel.doStartTravel` sets it on the line immediately
220
+ * before `startTravel`, so it is the exact boundary — not an inference from
221
+ * elapsed time, which is what a host would otherwise have to guess with.
222
+ */
223
+ export const HAPPY_OYSTER_PHASE_STARTING_STREAM = 'starting_stream';
224
+
225
+ /** Resolve the stage from the SDK's own phase. `preparingSeed` wins because it
226
+ * runs before any session state exists to read. */
227
+ export function dmWorldLaunchStage(input: {
228
+ preparingSeed: boolean;
229
+ /** `HappyOysterModel.phase`. */
230
+ clientPhase: string | null | undefined;
231
+ }): DmWorldLaunchStage {
232
+ if (input.preparingSeed) return 'preparing';
233
+ return input.clientPhase === HAPPY_OYSTER_PHASE_STARTING_STREAM
234
+ ? 'entering'
235
+ : 'building';
236
+ }
237
+
238
+ /** What a surface renders while a launch is in flight. */
239
+ export interface DmWorldLaunchProgress {
240
+ title: string;
241
+ /** The honest expectation for THIS stage, or `null` when there is none worth
242
+ * stating (a reopen's attach is fast and unbounded by anything useful). */
243
+ detail: string | null;
244
+ }
245
+
246
+ const seconds = (ms: number): number => Math.round(ms / 1000);
247
+
248
+ /**
249
+ * The progress copy for a stage — the ONLY place a surface gets it, so the
250
+ * build's 105–240 s expectation can never be shown over the stream-start wait
251
+ * again.
252
+ */
253
+ export function dmWorldLaunchProgress(
254
+ stage: DmWorldLaunchStage,
255
+ action: DmWorldEntryAction,
256
+ ): DmWorldLaunchProgress {
257
+ if (stage === 'preparing') {
258
+ return { title: 'Preparing the starting frame…', detail: null };
259
+ }
260
+ if (stage === 'entering') {
261
+ return {
262
+ title: 'Opening the live stream…',
263
+ detail:
264
+ `The world is built. Video has ${seconds(HAPPY_OYSTER_STREAM_START_TIMEOUT_MS)} seconds to arrive before the ` +
265
+ 'vendor ends the travel — waiting longer does not help.',
266
+ };
267
+ }
268
+ return action === 'reopen'
269
+ ? { title: 'Reopening this world…', detail: null }
270
+ : {
271
+ title: 'Building the world…',
272
+ detail:
273
+ `World builds have taken ${seconds(HAPPY_OYSTER_BUILD_FAST_MS)}–${seconds(HAPPY_OYSTER_BUILD_OBSERVED_MAX_MS)} seconds. ` +
274
+ 'Leaving abandons a world that is already being billed.',
275
+ };
276
+ }
277
+
278
+ /**
279
+ * §Q `DM.42` — what to SAY when a launch dies after the world was already
280
+ * built and the stream never came.
281
+ *
282
+ * Measured on staging 2026-08-01, on the free reopen path and independently in
283
+ * the World Explorer host, which shares no episode code: the vendor's
284
+ * `travels/status` reports `rtcStatus: STREAMING`, the AliRTC peer reaches ICE
285
+ * `connected` with both transceivers delivered — and `getStats()` records ZERO
286
+ * `inbound-rtp` for the whole window, so the world publisher never sends a
287
+ * packet. The client then hits the vendor's stream-start bound and the SDK ends
288
+ * the travel.
289
+ *
290
+ * Why this text exists rather than the vendor's own error: the SDK retries a
291
+ * stream-start timeout (its transient-error regex matches the word "timeout"),
292
+ * so the error that finally surfaces is the RETRY's — on a reopen that is
293
+ * `[TRAVELING] a travel is live`, which describes the wreckage of the first
294
+ * attempt and not the failure. Reporting it verbatim sends the reader after
295
+ * the wrong cause.
296
+ */
297
+ export const DM_WORLD_STREAM_STALL_TITLE = 'The world never started streaming';
298
+ export const DM_WORLD_STREAM_STALL_MESSAGE =
299
+ 'The world is built and the vendor reports it as streaming, but no video ever reached this browser, ' +
300
+ `so the vendor ended the travel after ${seconds(HAPPY_OYSTER_STREAM_START_TIMEOUT_MS)} seconds. ` +
301
+ 'This is a fault on the world-model side, not something retrying from here fixes.';
302
+
303
+ /** Everything a surface renders for a failed launch. */
304
+ export interface DmWorldLaunchFailure {
305
+ title: string;
306
+ detail: string;
307
+ /**
308
+ * The permanent world this launch already paid for, when one exists. Shown
309
+ * because a billed world that reaches a dead end WITHOUT its id on screen is
310
+ * exactly the loss `DM.43` is about — worlds cannot be listed.
311
+ */
312
+ worldId: string | null;
313
+ /**
314
+ * Whether this is the stream-start stall rather than an ordinary failure.
315
+ * Carried on the result so a surface can address the state (a test id, a
316
+ * probe) without re-deriving it by comparing the rendered title to a
317
+ * constant — the copy is allowed to change; the classification is not.
318
+ */
319
+ streamStalled: boolean;
320
+ /**
321
+ * §Q `WORLD.17` — the vendor's refusal of the session, when that is what
322
+ * failed. Carried so a surface can publish it (a test id, a probe) without
323
+ * re-parsing the rendered copy.
324
+ */
325
+ vendorRefusal?: ReactorSessionRefusal | null;
326
+ }
327
+
328
+ /**
329
+ * Build a {@link DmWorldLaunchFailure}. `streamStalled` takes precedence over
330
+ * the vendor's reason for the reason in {@link DM_WORLD_STREAM_STALL_MESSAGE};
331
+ * the vendor's own text is kept as the detail's tail so nothing is hidden.
332
+ */
333
+ export function dmWorldLaunchFailure(input: {
334
+ reason: HappyOysterFailureReason | string;
335
+ message: string;
336
+ worldId?: string | null;
337
+ streamStalled?: boolean;
338
+ /**
339
+ * §Q `WORLD.17` — set when the vendor refused the SESSION. Takes precedence
340
+ * over everything else: the reason a refused session carries is `unknown`,
341
+ * and rendering that word as the headline is what left the 2026-10-09 402
342
+ * nameless.
343
+ */
344
+ vendorRefusal?: ReactorSessionRefusal | null;
345
+ }): DmWorldLaunchFailure {
346
+ const worldId = input.worldId ?? null;
347
+ if (input.vendorRefusal != null) {
348
+ return {
349
+ title: reactorSessionRefusalTitle(input.vendorRefusal),
350
+ detail: reactorSessionRefusalDetail(input.vendorRefusal),
351
+ worldId,
352
+ streamStalled: false,
353
+ vendorRefusal: input.vendorRefusal,
354
+ };
355
+ }
356
+ if (input.streamStalled === true) {
357
+ return {
358
+ title: DM_WORLD_STREAM_STALL_TITLE,
359
+ detail: `${DM_WORLD_STREAM_STALL_MESSAGE} (The SDK reported: ${input.message})`,
360
+ worldId,
361
+ streamStalled: true,
362
+ };
363
+ }
364
+ return { title: input.reason, detail: input.message, worldId, streamStalled: false };
365
+ }
366
+
367
+ /** Why a world entry cannot proceed, AS DECIDED BY THE PLANNER — i.e. the board
368
+ * was in hand, {@link planDmWorldEntry} ran, and it refused. Every one of these
369
+ * is decided BEFORE any session is opened, i.e. before anything can be billed.
370
+ *
371
+ * ⛔ DO NOT WIDEN THIS ALIAS. It is published, and a consumer's exhaustive
372
+ * `switch` or `Record<DmWorldEntryBlockReason, …>` breaks the moment a member
373
+ * is added (codex on #1681). New RENDERABLE reasons go on
374
+ * {@link DmWorldEntryHostBlockReason} and reach the copy tables through
375
+ * {@link DmWorldEntryRenderBlockReason}. */
376
+ export type DmWorldEntryBlockReason =
377
+ /** The session reports no active beat, so there is nothing to join on. */
378
+ | 'no_active_beat'
379
+ /** No board frame carries that beat id. */
380
+ | 'no_frame_for_beat'
381
+ /** The frame exists and is still generating — there is no seed YET. */
382
+ | 'frame_not_rendered'
383
+ /**
384
+ * §Q `SB.34` — the frame exists, is fully described, and its render FAILED.
385
+ * Split out of `frame_not_rendered` because the two need opposite responses:
386
+ * one resolves by waiting, the other never does.
387
+ */
388
+ | 'frame_render_failed'
389
+ /** The frame carries no server-compiled prompt text on any variant. */
390
+ | 'prompt_unavailable'
391
+ /** The composed prompt is unusable (empty / over the vendor cap). */
392
+ | 'prompt_invalid'
393
+ /**
394
+ * §Q `DM.30` — the frame IS bound to a world, but to the OTHER mode's model.
395
+ * HappyOyster worlds are mode-fixed, so this can never resolve by retrying
396
+ * here; the world has to be opened from the surface that minted it. Decided
397
+ * from the frame's STORED `worldMode`, which is why DM.30 had to persist it:
398
+ * a bare id looks bound and fails at `attachWorld` with `[MODE_MISMATCH]`.
399
+ */
400
+ | 'world_mode_mismatch';
401
+
402
+ /**
403
+ * §Q `DM.73` — why a HOST cannot even reach the planner.
404
+ *
405
+ * The planner is pure and needs the board in hand, so a host that has not got
406
+ * one has no `DmWorldEntryBlockReason` to report. It used to report NOTHING
407
+ * — `reason: null`, which {@link dmWorldEntryBlockTitle} renders as
408
+ * {@link DM_WORLD_ENTRY_NO_BOARD_TITLE} — and that collapsed three different
409
+ * situations into the single claim *"this story has no ratified storyboard"*:
410
+ * the read had not landed yet, the read FAILED, and the story genuinely has no
411
+ * board. Only the third is what the copy says. See the DM.73 section at the
412
+ * bottom of this module for the measurement.
413
+ */
414
+ export type DmWorldEntryHostBlockReason =
415
+ /** The board read has not settled yet (first attempt or a scheduled retry). */
416
+ | 'board_read_pending'
417
+ /** Every attempt at the board read failed. The story's board state is
418
+ * UNKNOWN — emphatically not known to be absent. */
419
+ | 'board_read_failed'
420
+ /**
421
+ * §Q `WORLD.1-A` — the surface has a board and NO beat, so the player has to
422
+ * name which world to open and has not yet.
423
+ *
424
+ * The DM episode can never reach it: a session always stands on a beat (or
425
+ * reports `no_active_beat`, which is a different claim — the story has not
426
+ * started). The VIEWER has no session at all, so its entry is a pick from the
427
+ * story's frame-bound worlds, and stepping into the world source before
428
+ * picking one is a real, reachable state that would otherwise render as a
429
+ * black pane.
430
+ */
431
+ | 'world_not_chosen';
432
+
433
+ /**
434
+ * Every reason a surface can render a block for: the planner's refusals plus
435
+ * the host's own pre-planner states.
436
+ *
437
+ * A NEW name rather than a widening of {@link DmWorldEntryBlockReason}, so the
438
+ * published planner alias keeps exactly the members it shipped with and only
439
+ * the copy tables and {@link DmWorldEntryBlock} see the wider set.
440
+ * {@link DmWorldEntryPlanResult} keeps the PLANNER half, so no planner branch
441
+ * can ever return a host reason, while the Records below cover the whole union —
442
+ * a new member of either half fails to compile until it has a headline.
443
+ */
444
+ export type DmWorldEntryRenderBlockReason =
445
+ | DmWorldEntryBlockReason
446
+ | DmWorldEntryHostBlockReason;
447
+
448
+ /**
449
+ * §Q `SB.34` — the HEADLINE a surface shows for each block reason.
450
+ *
451
+ * The messages below already differed per reason; the headline did not, so
452
+ * every block read as the same dead end — *"No world for this beat"* on a beat
453
+ * whose frame merely failed looks exactly like a beat nobody storyboarded, and
454
+ * the owner's `star-wars` board (1 rendered frame, 5 refused) presented as
455
+ * having no board at all. The headline is the line that gets read first, so it
456
+ * is the line that has to carry the difference.
457
+ *
458
+ * A `Record` rather than a `switch` so a new {@link DmWorldEntryBlockReason}
459
+ * member fails to compile here instead of silently falling back to generic copy.
460
+ * It lives beside the reasons — the messages already do — so no surface invents
461
+ * its own vocabulary for a state the planner owns.
462
+ */
463
+ export const DM_WORLD_ENTRY_BLOCK_TITLES: Record<
464
+ DmWorldEntryRenderBlockReason,
465
+ string
466
+ > = {
467
+ // §Q DM.61(a) — "No beat is active yet" describes the DATA and reads as a
468
+ // fault. On the happy path it is not one: a definition spawn starts with
469
+ // `current_beat_id=None` (25 of 88 live sessions on 2026-08-02), so a player
470
+ // who launches and immediately asks for the world hits this BY DESIGN. The
471
+ // headline now names the situation the player is in, and the recourse below
472
+ // names the one move that leaves it.
473
+ no_active_beat: 'The story has not started yet',
474
+ no_frame_for_beat: 'This beat has no storyboard frame',
475
+ frame_not_rendered: "This beat's frame is still rendering",
476
+ frame_render_failed: "This beat's frame failed to render",
477
+ prompt_unavailable: "This beat's frame has no prompt to build from",
478
+ prompt_invalid: "This beat's prompt cannot open a world",
479
+ world_mode_mismatch: "This beat's world belongs to another experience",
480
+ // §Q DM.73 — neither of these says anything about whether a board EXISTS,
481
+ // because neither host state knows. That is the whole point of the row.
482
+ board_read_pending: "Loading this story's storyboard…",
483
+ board_read_failed: "This story's storyboard could not be loaded",
484
+ // §Q WORLD.1-A — nothing is wrong; the surface is waiting on a choice only
485
+ // the player can make. The headline says so rather than borrowing an absence.
486
+ world_not_chosen: 'Pick a world to step into',
487
+ };
488
+
489
+ /**
490
+ * The headline for a block, or the generic one when the planner was never
491
+ * reached at all (no board on the story, so there is no reason object).
492
+ */
493
+ export const DM_WORLD_ENTRY_NO_BOARD_TITLE = 'No world for this beat';
494
+
495
+ /**
496
+ * §Q `DM.61(a)` — THE ONE MOVE THAT LEAVES THE BLOCK, when one exists.
497
+ *
498
+ * A refusal that states only what is missing is a dead end even when the way
499
+ * out is one click away. `no_active_beat` is the case that made this worth a
500
+ * field: it is reachable on the HAPPY path (a definition spawn starts with no
501
+ * beat until the DM's first `advance_story`), it resolves ENTIRELY by playing
502
+ * the first turn, and nothing on the block said so.
503
+ *
504
+ * The value is the action LABEL a surface puts on the way back, so the copy
505
+ * lives beside the reason it belongs to rather than in whichever pane renders
506
+ * it. `null` means there is genuinely nothing the player can do from here — do
507
+ * NOT invent one to fill the field:
508
+ *
509
+ * · `no_frame_for_beat` / `frame_not_rendered` / `frame_render_failed` /
510
+ * `prompt_unavailable` / `prompt_invalid` resolve on the STORYBOARD, which
511
+ * is a different surface and a different person's job.
512
+ * · `world_mode_mismatch` has no client recourse at all. The frame holds ONE
513
+ * world slot and the bound world lives on the other mode-fixed model, so
514
+ * nothing the player clicks here can rebind it — per-mode slots (or an
515
+ * unbind) is a server change. Faking a button would be worse than the
516
+ * honest dead end.
517
+ */
518
+ export const DM_WORLD_ENTRY_BLOCK_RECOURSE: Record<
519
+ DmWorldEntryRenderBlockReason,
520
+ string | null
521
+ > = {
522
+ // codex P3 on #1663 — the label names what the CONTROL does and what it is
523
+ // for, in that order. "Take your first turn" alone would overstate it: the
524
+ // control returns to the chat, it does not send a turn.
525
+ no_active_beat: 'Back to chat to take your first turn',
526
+ no_frame_for_beat: null,
527
+ frame_not_rendered: null,
528
+ frame_render_failed: null,
529
+ prompt_unavailable: null,
530
+ prompt_invalid: null,
531
+ world_mode_mismatch: null,
532
+ // §Q DM.73 — nothing to offer while the read is still in flight; the surface
533
+ // is already doing the only thing that resolves it.
534
+ board_read_pending: null,
535
+ // The one host block with a real move: the read is retryable BY DEFINITION
536
+ // (the host exhausted its automatic attempts to get here), so asking again is
537
+ // not a guess. `dmWorldEntryBlockIsRetryable` is what a surface branches on —
538
+ // this label must NOT be hung on an exit control.
539
+ board_read_failed: 'Try loading the storyboard again',
540
+ // §Q WORLD.1-A — the list of this story's worlds is on the surface BEHIND
541
+ // this pane, so leaving the pane IS the move. Named for the viewer, which is
542
+ // the only surface that can produce this reason.
543
+ world_not_chosen: 'Back to the video',
544
+ };
545
+
546
+ /**
547
+ * §Q `DM.73` — whether this block's recourse is a RETRY of the thing that
548
+ * failed, rather than a way out of the surface.
549
+ *
550
+ * `HappyOysterWorldPane` renders `DmWorldEntryBlock.recourse` as the label of
551
+ * its EXIT control, which is right for `no_active_beat` ("Back to chat to take
552
+ * your first turn" genuinely leaves the pane) and would be a lie for
553
+ * `board_read_failed` — a button reading *"Try loading the storyboard again"*
554
+ * that instead closes the world pane. Derived here so no surface re-decides
555
+ * which recourses are exits and which are actions.
556
+ */
557
+ export function dmWorldEntryBlockIsRetryable(
558
+ reason: DmWorldEntryRenderBlockReason | null,
559
+ ): boolean {
560
+ return reason === 'board_read_failed';
561
+ }
562
+
563
+ /** {@link DM_WORLD_ENTRY_BLOCK_RECOURSE} with the no-reason case folded in. */
564
+ export function dmWorldEntryBlockRecourse(
565
+ reason: DmWorldEntryRenderBlockReason | null,
566
+ ): string | null {
567
+ return reason === null ? null : DM_WORLD_ENTRY_BLOCK_RECOURSE[reason];
568
+ }
569
+
570
+ /** {@link DM_WORLD_ENTRY_BLOCK_TITLES} with the no-reason case folded in, so a
571
+ * surface never repeats the `?? generic` tail. */
572
+ export function dmWorldEntryBlockTitle(
573
+ reason: DmWorldEntryRenderBlockReason | null,
574
+ ): string {
575
+ return reason === null
576
+ ? DM_WORLD_ENTRY_NO_BOARD_TITLE
577
+ : DM_WORLD_ENTRY_BLOCK_TITLES[reason];
578
+ }
579
+
580
+ /**
581
+ * Everything a surface renders for a block, in ONE object: the reason (for
582
+ * test/telemetry addressing), the headline, and the planner's own message.
583
+ *
584
+ * Carried as a pair rather than two loose props because they must always agree —
585
+ * a headline paired with a message from a different reason is the exact class of
586
+ * drift that let a failed frame read as a missing one.
587
+ */
588
+ export interface DmWorldEntryBlock {
589
+ /** `null` when the planner was never reached AND the host has nothing of its
590
+ * own to say — i.e. the story genuinely has no board (§Q `DM.73`). */
591
+ reason: DmWorldEntryRenderBlockReason | null;
592
+ title: string;
593
+ message: string;
594
+ /**
595
+ * §Q `DM.61(a)` — the label for the one move that resolves this block, or
596
+ * `null` when nothing the player does here can. See
597
+ * {@link DM_WORLD_ENTRY_BLOCK_RECOURSE}.
598
+ */
599
+ recourse: string | null;
600
+ }
601
+
602
+ /** Build a {@link DmWorldEntryBlock}; the ONLY way a surface should mint one. */
603
+ export function dmWorldEntryBlock(
604
+ reason: DmWorldEntryRenderBlockReason | null,
605
+ message: string,
606
+ ): DmWorldEntryBlock {
607
+ return {
608
+ reason,
609
+ title: dmWorldEntryBlockTitle(reason),
610
+ message,
611
+ recourse: dmWorldEntryBlockRecourse(reason),
612
+ };
613
+ }
614
+
615
+ /** What the plan authorises. Only `'create'` costs anything. */
616
+ export type DmWorldEntryAction =
617
+ /** A world is live and the scene has not changed — `instruct` it (DM.12). */
618
+ | 'steer'
619
+ /** The frame already owns a permanent world — reopen it. Free and instant. */
620
+ | 'reopen'
621
+ /** Auto-fire is on and this is a scene change: create without asking. */
622
+ | 'create'
623
+ /** Create ONLY after an explicit operator confirmation. */
624
+ | 'confirm_required';
625
+
626
+ /** What is streaming right now, so the planner can prefer steering/reuse over a
627
+ * new billed world (owner `DM.12`). */
628
+ export interface DmLiveWorld {
629
+ handle: HappyOysterWorldHandle;
630
+ /** The `sequenceId` of the frame the live world was seeded from. A change is
631
+ * a CUT — that, and only that, is what justifies a new world. */
632
+ sequenceId?: string | null;
633
+ /**
634
+ * §Q `DM.62` — the FRAME the live world was seeded from. Optional and
635
+ * additive (client-core is published and `../Web-App` is pinned), but it is
636
+ * what makes scene identity decidable when the sequence anchor is null: 8 of
637
+ * 21 live frames carry no `sequenceId` and the ENDINGS are among them, so
638
+ * `sequenceId`-only identity collapsed every unanchored beat into one scene.
639
+ */
640
+ frameId?: string | null;
641
+ /** The beat that frame was resolved from — the fallback identity for a host
642
+ * that knows the beat but not the frame id. */
643
+ beatId?: string | null;
644
+ }
645
+
646
+ /** One world this session opened — rail 2's "nothing hidden, nothing lost". */
647
+ export interface DmWorldSessionEntry {
648
+ handle: HappyOysterWorldHandle;
649
+ /** The frame it was seeded from, so a surface can show WHICH moment it is. */
650
+ frameId: string;
651
+ beatId: string | null;
652
+ /** How it came to exist — an auto-fired world is the one a player did not
653
+ * ask for by hand, so a surface can label it as such. */
654
+ trigger: 'auto' | 'confirmed' | 'reopen';
655
+ /** `Date.now()` at the launch attempt. */
656
+ openedAt: number;
657
+ }
658
+
659
+ /**
660
+ * Add a world to the session's list, de-duplicated by `encryptedWorldId`.
661
+ *
662
+ * Pure and returning a new array so a host can hold it in ordinary state. It is
663
+ * NOT the world-explorer demo's `worldHandleStore.saveStoredWorld` — that one
664
+ * PERSISTS a capped, newest-first list to `localStorage` for a dev host; this is
665
+ * the DM session's in-order record of what THIS session opened, and the durable
666
+ * home for a DM world is `StoryboardFrame.world_id`. Only the
667
+ * dedupe-on-encrypted-id rule is shared, and it is three lines.
668
+ *
669
+ * This is rail 2's data half: a world that is billed and permanent must be VISIBLE
670
+ * (the list is what a surface renders) and REACHABLE afterwards (the handle
671
+ * reopens it via `attachWorld`), including one whose `startTravel` failed.
672
+ *
673
+ * §Q `DM.24` — this list ALONE is not that rail: it is React state, so it is
674
+ * gone on reload while the worlds stay billed. A surface renders
675
+ * {@link collectDmWorldRecords}, which reads the durable frame bindings first
676
+ * and folds this list in; an entry that appears ONLY here is flagged with
677
+ * {@link DM_WORLD_UNRECORDED_NOTICE}.
678
+ */
679
+ export function rememberDmWorldEntry(
680
+ entries: readonly DmWorldSessionEntry[],
681
+ entry: DmWorldSessionEntry,
682
+ ): DmWorldSessionEntry[] {
683
+ const existing = entries.findIndex(
684
+ e => e.handle.encryptedWorldId === entry.handle.encryptedWorldId,
685
+ );
686
+ if (existing === -1) return [...entries, entry];
687
+ const next = [...entries];
688
+ next[existing] = entry;
689
+ return next;
690
+ }
691
+
692
+ /**
693
+ * §Q `DM.24` — WHERE THE KNOWLEDGE OF A WORLD ACTUALLY LIVES.
694
+ *
695
+ * `'frame'` — read back off `StoryboardFrame.worldId`. DURABLE: it survives a
696
+ * reload, a different browser and a different operator, because the board is
697
+ * server state.
698
+ *
699
+ * `'session'` — present only in {@link rememberDmWorldEntry}'s in-memory list.
700
+ * The world EXISTS and IS BILLED, but no frame records it, so the id dies with
701
+ * the tab. This is the state {@link DM_WORLD_UNRECORDED_NOTICE} warns about and
702
+ * the reason this projection exists at all.
703
+ */
704
+ export type DmWorldRecordSource =
705
+ | 'frame'
706
+ | 'session'
707
+ /**
708
+ * §Q `MOMENT.8` — read back off `StoryboardFrame.supersededWorldIds`. The
709
+ * frame USED to open into it and a sibling replaced it. Just as DURABLE and
710
+ * just as BILLED as `'frame'`: HappyOyster exposes no delete, so a superseded
711
+ * world is permanent, and the id in the ledger is the only thing that can
712
+ * still reach it. It is listed for exactly that reason — the alternative,
713
+ * dropping it on replacement, is the orphaned-paid-world failure the
714
+ * supersede design exists to prevent.
715
+ */
716
+ | 'superseded';
717
+
718
+ /**
719
+ * One world this story is known to own, from the DURABLE board first and the
720
+ * session's memory second.
721
+ *
722
+ * A projection, never storage: `collectDmWorldRecords` rebuilds it from the two
723
+ * inputs on every read, so no surface can hold a stale copy of which worlds
724
+ * exist.
725
+ */
726
+ export interface DmWorldRecord {
727
+ /** The permanent HappyOyster `encryptedWorldId`. */
728
+ worldId: string;
729
+ /**
730
+ * The mode-fixed model that owns it, or `null` when NOTHING recorded it — a
731
+ * pre-`DM.30` binding, or a session entry (whose handle mode is what the
732
+ * session launched with, which is a fact, so it is carried).
733
+ *
734
+ * `null` is UNKNOWN, never a default. A reader that substitutes its own mode
735
+ * here re-creates the `[MODE_MISMATCH]` bug DM.30 fixed.
736
+ */
737
+ mode: HappyOysterMode | null;
738
+ /** The frame that owns it. Always set — every record is anchored to a frame,
739
+ * including a session-only one (the launch resolved one to seed from). */
740
+ frameId: string;
741
+ beatId: string | null;
742
+ source: DmWorldRecordSource;
743
+ /** How it came to exist, when THIS session opened it; `null` for a world read
744
+ * back off the board that this session did not open. */
745
+ trigger: DmWorldSessionEntry['trigger'] | null;
746
+ /** `Date.now()` at this session's launch, or `null` as above. */
747
+ openedAt: number | null;
748
+ }
749
+
750
+ /**
751
+ * What a surface must say about a `'session'`-source record.
752
+ *
753
+ * HappyOyster worlds are permanent, billed and UNLISTABLE — there is no
754
+ * vendor-side list to recover an id from. So a world whose frame binding never
755
+ * landed is reachable ONLY through the string on screen, and only until the page
756
+ * reloads. That is not a warning about a future risk; it is the current state.
757
+ */
758
+ export const DM_WORLD_UNRECORDED_NOTICE =
759
+ 'This world exists and is billed, but no storyboard frame records it — copy the id now. HappyOyster worlds cannot be listed, so once this page reloads nothing can reach it again.';
760
+
761
+ /**
762
+ * Every world this story owns, DURABLE-FIRST — the data half of §Q `DM.24`.
763
+ *
764
+ * The problem it solves: `DmWorldSessionEntry[]` lives in React state, so a
765
+ * surface built on it alone shows nothing after a reload while the worlds it
766
+ * listed are still permanent and still billed. `StoryboardFrame.worldId` is the
767
+ * durable home (written by `DM.27`, mode-stamped by `DM.30`), so the board — not
768
+ * the session — is the primary source here and the session list only ADDS what
769
+ * the board does not yet know.
770
+ *
771
+ * Order: board order (`orderStoryboardFrames`) for durable records, then
772
+ * session-only records in the order they were opened. Durable first because
773
+ * that is the list that is still true tomorrow.
774
+ *
775
+ * A session entry whose world IS on the board enriches that durable record with
776
+ * `trigger`/`openedAt` rather than appearing twice — one world, one row, and the
777
+ * row still says it is safely recorded.
778
+ */
779
+ export function collectDmWorldRecords(input: {
780
+ /** The board's ordering source of truth (`Storyboard.frameIds`). */
781
+ frameIds: readonly string[];
782
+ /** The detail read's frames, in any order. */
783
+ frames: readonly StoryboardFrame[];
784
+ /** This session's in-memory list (`rememberDmWorldEntry`). */
785
+ entries?: readonly DmWorldSessionEntry[];
786
+ }): DmWorldRecord[] {
787
+ const entries = input.entries ?? [];
788
+ const records: DmWorldRecord[] = [];
789
+ const byWorldId = new Map<string, DmWorldRecord>();
790
+
791
+ for (const frame of orderStoryboardFrames(input.frameIds, input.frames)) {
792
+ const worldId = frame.worldId?.trim() ?? '';
793
+ if (worldId === '' || byWorldId.has(worldId)) continue;
794
+ const record: DmWorldRecord = {
795
+ worldId,
796
+ mode: frame.worldMode ?? null,
797
+ frameId: frame.frameId,
798
+ beatId: frame.beatId ?? null,
799
+ source: 'frame',
800
+ trigger: null,
801
+ openedAt: null,
802
+ };
803
+ records.push(record);
804
+ byWorldId.set(worldId, record);
805
+ }
806
+
807
+ // §Q MOMENT.8 — the supersede ledger, AFTER the current bindings so a world
808
+ // that is current on one frame is never demoted to "superseded" by another
809
+ // frame's history. Listed at all because these are still permanent and still
810
+ // billed; the row is what keeps them reachable.
811
+ for (const frame of orderStoryboardFrames(input.frameIds, input.frames)) {
812
+ for (const supersededId of frame.supersededWorldIds ?? []) {
813
+ const worldId = supersededId.trim();
814
+ if (worldId === '' || byWorldId.has(worldId)) continue;
815
+ const record: DmWorldRecord = {
816
+ worldId,
817
+ // The mode is UNKNOWN for a superseded id and is never substituted: the
818
+ // frame's `worldMode` describes the world that REPLACED it, and
819
+ // assuming it here re-creates the `[MODE_MISMATCH]` bug DM.30 fixed.
820
+ mode: null,
821
+ frameId: frame.frameId,
822
+ beatId: frame.beatId ?? null,
823
+ source: 'superseded',
824
+ trigger: null,
825
+ openedAt: null,
826
+ };
827
+ records.push(record);
828
+ byWorldId.set(worldId, record);
829
+ }
830
+ }
831
+
832
+ for (const entry of entries) {
833
+ const worldId = entry.handle.encryptedWorldId;
834
+ const durable = byWorldId.get(worldId);
835
+ if (durable !== undefined) {
836
+ // The board already owns it; the session only knows HOW and WHEN.
837
+ durable.trigger = entry.trigger;
838
+ durable.openedAt = entry.openedAt;
839
+ continue;
840
+ }
841
+ const record: DmWorldRecord = {
842
+ worldId,
843
+ // The handle's mode is what the session launched against, i.e. the mode
844
+ // the world was created on — a recorded fact, not a substitution.
845
+ mode: entry.handle.mode,
846
+ frameId: entry.frameId,
847
+ beatId: entry.beatId,
848
+ source: 'session',
849
+ trigger: entry.trigger,
850
+ openedAt: entry.openedAt,
851
+ };
852
+ records.push(record);
853
+ byWorldId.set(worldId, record);
854
+ }
855
+
856
+ return records;
857
+ }
858
+
859
+ /**
860
+ * §Q `MOMENT.6b` — "N of M prepared", from the board alone.
861
+ *
862
+ * `preparedBeats` counts BEATS whose deterministic anchor frame already owns a
863
+ * permanent world, so play-time entry resolves to `'reopen'` (`attachWorld`,
864
+ * instant) instead of a 105-240 s cold build. `totalBeats` is every beat the
865
+ * board covers.
866
+ *
867
+ * Counted per BEAT and not per FRAME because that is the grain the world is
868
+ * minted at (design R3) and the grain play-time entry joins on: a board with 12
869
+ * frames over 6 beats and 6 worlds is FULLY prepared, and a frame-grain count
870
+ * would report it half done.
871
+ */
872
+ export interface DmWorldPreparationSummary {
873
+ preparedBeats: number;
874
+ totalBeats: number;
875
+ /** `'4 of 6 prepared'` — one wording, so two surfaces cannot drift. */
876
+ label: string;
877
+ }
878
+
879
+ export function summarizeDmWorldPreparation(input: {
880
+ /** The board's ordering source of truth (`Storyboard.frameIds`). */
881
+ frameIds: readonly string[];
882
+ /** The detail read's frames, in any order. */
883
+ frames: readonly StoryboardFrame[];
884
+ }): DmWorldPreparationSummary {
885
+ const ordered = orderStoryboardFrames(input.frameIds, input.frames);
886
+ const beatIds: string[] = [];
887
+ for (const frame of ordered) {
888
+ const beatId = frame.beatId?.trim() ?? '';
889
+ if (beatId !== '' && !beatIds.includes(beatId)) beatIds.push(beatId);
890
+ }
891
+ const preparedBeats = beatIds.filter(beatId => {
892
+ // The SAME anchor rule play-time entry uses — a beat counts as prepared
893
+ // only when the frame entry will actually resolve to owns a world. A plain
894
+ // "any frame on this beat has a worldId" would report a beat prepared whose
895
+ // entry then cold-builds, which is precisely the promise this label makes.
896
+ const anchor = resolveDmWorldEntryFrame({
897
+ frameIds: input.frameIds,
898
+ frames: input.frames,
899
+ activeBeatId: beatId,
900
+ });
901
+ return (anchor?.worldId?.trim() ?? '') !== '';
902
+ }).length;
903
+ return {
904
+ preparedBeats,
905
+ totalBeats: beatIds.length,
906
+ label: `${preparedBeats} of ${beatIds.length} prepared`,
907
+ };
908
+ }
909
+
910
+ /**
911
+ * §Q `DM.24` — the reopen affordance's own refusal.
912
+ *
913
+ * The row's reopen button plans through {@link planDmWorldEntry} rather than
914
+ * building a handle by hand, so the plan is checked to be a `'reopen'` OF THE
915
+ * CLICKED WORLD before it runs. It can legitimately not be: several frames may
916
+ * carry the same `beatId` and {@link resolveDmWorldEntryFrame} prefers a
917
+ * RENDERED one, so the beat can resolve to a frame that owns a DIFFERENT world
918
+ * (or none). Opening the resolver's choice anyway would mean opening the wrong
919
+ * PAID asset, so this says so instead.
920
+ */
921
+ export const DM_WORLD_REOPEN_UNRESOLVED_MESSAGE =
922
+ "This world's beat now resolves to a different storyboard frame, so reopening from here could open the wrong world. Open it from that frame on the board instead.";
923
+
924
+ /**
925
+ * §Q `WORLD.1-A` — what a surface tells a player who reached the world pane
926
+ * without naming a world. Paired with the `world_not_chosen` block reason.
927
+ */
928
+ export const DM_WORLD_NOT_CHOSEN_MESSAGE =
929
+ 'HappyOyster worlds belong to a storyboard frame, so this surface opens one you pick rather than guessing. Choose a world from the list beside the video.';
930
+
931
+ /**
932
+ * §Q `WORLD.1-A` — THE ONE DECISION BEHIND A "REOPEN THIS WORLD" CLICK.
933
+ *
934
+ * Pure, and shared by every surface that lists {@link collectDmWorldRecords}:
935
+ * the DM play episode and the viewer both offer the same button and both must
936
+ * refuse the same way. It was written once in `DmExperienceLayout` and copied
937
+ * nowhere — this exists so it stays that way now the viewer has the affordance
938
+ * too.
939
+ *
940
+ * The guard is two conditions, and dropping either one turns a free reattach
941
+ * into a paid mistake: the plan must be a `'reopen'` (a `'create'` would mint a
942
+ * SECOND permanent world for a button labelled "reopen"), and its handle must be
943
+ * THE CLICKED WORLD (the beat can resolve to a frame owning a different one).
944
+ *
945
+ * `planned === null` means the host could not reach the planner at all — no
946
+ * board in hand — which is a refusal like any other here, not a licence to open.
947
+ */
948
+ export function dmWorldReopenDecision(
949
+ record: DmWorldRecord,
950
+ planned: DmWorldEntryPlanResult | null,
951
+ ): { plan: DmWorldEntryPlan; blocked: null } | { plan: null; blocked: DmWorldEntryBlock } {
952
+ if (
953
+ planned !== null &&
954
+ planned.ok &&
955
+ planned.plan.action === 'reopen' &&
956
+ planned.plan.handle?.encryptedWorldId === record.worldId
957
+ ) {
958
+ return { plan: planned.plan, blocked: null };
959
+ }
960
+ return {
961
+ plan: null,
962
+ blocked:
963
+ planned !== null && !planned.ok
964
+ ? dmWorldEntryBlock(planned.reason, planned.message)
965
+ : dmWorldEntryBlock(null, DM_WORLD_REOPEN_UNRESOLVED_MESSAGE),
966
+ };
967
+ }
968
+
969
+ /* ==========================================================================
970
+ * §Q `DM.67` — A CONTENT-REFUSED BEAT IS NOT A DEAD END
971
+ * ========================================================================== */
972
+
973
+ /**
974
+ * WHAT WAS MEASURED. CHECKPOINT-3 (2026-08-02,
975
+ * `~/.seer-e2e/checkpoint3-0802-verdicts.md` §B3-residual): beat 1's world was
976
+ * refused `content_rejected [403004]` by HappyOyster moderation and the pane
977
+ * rendered the vendor's *"Please try something else"* with NO control on it.
978
+ * Beat 2 then opened and played — so the refusal is PER BEAT, the recourse
979
+ * existed, and nothing on screen said so.
980
+ *
981
+ * The route out is the story's OTHER beats whose entry the planner would
982
+ * authorise. Each route is decided by {@link planDmWorldEntry} itself, never by
983
+ * a second reading of the frame here, so a route can never promise an entry the
984
+ * click then refuses.
985
+ */
986
+ const HAPPY_OYSTER_FAILURE_CONTENT_REJECTED: HappyOysterFailureReason =
987
+ 'content_rejected';
988
+
989
+ /**
990
+ * Whether a failed launch was the vendor's CONTENT refusal of this beat's scene
991
+ * (403004 moderation / 403005 copyright — `classifyHappyOysterError` collapses
992
+ * both). That refusal is about the seed and prompt, so a different beat's world
993
+ * can still open, which is what makes {@link dmWorldContentRefusalRoutes} the
994
+ * recourse. No other launch failure gets those routes: a transport fault or a
995
+ * credits refusal fails the next beat exactly the same way.
996
+ */
997
+ export function dmWorldLaunchIsContentRefusal(
998
+ reason: HappyOysterFailureReason | string | null | undefined,
999
+ ): boolean {
1000
+ return reason === HAPPY_OYSTER_FAILURE_CONTENT_REJECTED;
1001
+ }
1002
+
1003
+ /** One beat a content-refused entry can go to instead. */
1004
+ export interface DmWorldRefusalRoute {
1005
+ /** The board-space beat id — what `planDmWorldEntry` joins on. */
1006
+ beatId: string;
1007
+ /** The frame the planner resolved for it. */
1008
+ frameId: string;
1009
+ /**
1010
+ * What the planner authorised: `'reopen'` (the frame already owns a world —
1011
+ * free, and nothing new is submitted to moderation) or `'confirm_required'`
1012
+ * (a NEW, billed world, which still asks before anything is spent).
1013
+ */
1014
+ action: DmWorldEntryAction;
1015
+ /** `Beat 3 — the vault`, or `Beat <raw id>` when the graph lacks the beat. */
1016
+ label: string;
1017
+ /** What choosing it does, in one clause. */
1018
+ hint: string;
1019
+ }
1020
+
1021
+ export const DM_WORLD_REFUSAL_ROUTE_REOPEN_HINT =
1022
+ 'reopens the world this beat already owns';
1023
+ export const DM_WORLD_REFUSAL_ROUTE_BUILD_HINT =
1024
+ 'builds this beat’s world — asks you first';
1025
+
1026
+ /** The sentence above the routes. */
1027
+ export const DM_WORLD_CONTENT_REFUSAL_ROUTES_LEAD =
1028
+ 'The world model refused this beat’s scene on content grounds. That refusal is about this beat only — another beat’s world can still open:';
1029
+
1030
+ /**
1031
+ * What the card says when no other beat can be entered. Said in words, because
1032
+ * an empty list under a refusal is the same dead end this row removes.
1033
+ */
1034
+ export const DM_WORLD_CONTENT_REFUSAL_NO_ROUTE =
1035
+ 'The world model refused this beat’s scene on content grounds, and no other beat on this story’s board has a world or a drawn frame to open one from yet. Carry on in the chat — the refusal is about this beat, not the story.';
1036
+
1037
+ /**
1038
+ * The control under {@link DM_WORLD_CONTENT_REFUSAL_NO_ROUTE}. The routes are
1039
+ * planned from the board the episode read when it opened, and a session board
1040
+ * is still drawing frames for minutes after launch — so "nothing else can open
1041
+ * yet" from that read is exactly when re-reading the board is the way out.
1042
+ */
1043
+ export const DM_WORLD_CONTENT_REFUSAL_RECHECK_LABEL = 'Check the board again';
1044
+
1045
+ /**
1046
+ * §Q `DM.67` — the beats a content-refused entry can go to instead.
1047
+ *
1048
+ * Every beat on the board other than the refused ones, in board order, kept
1049
+ * only when {@link planDmWorldEntry} authorises an entry for it. Reopens come
1050
+ * first: they are free, and attaching an existing world submits nothing new to
1051
+ * the moderation that just refused. Planned WITHOUT auto-fire, so a route that
1052
+ * would mint a world arrives as `'confirm_required'` and the pane still parks
1053
+ * it on the consent card.
1054
+ */
1055
+ export function dmWorldContentRefusalRoutes(input: {
1056
+ /** The board's ordering source of truth (`Storyboard.frameIds`). */
1057
+ frameIds: readonly string[];
1058
+ /** The detail read's frames, in any order. */
1059
+ frames: readonly StoryboardFrame[];
1060
+ /** The mode-fixed model this session runs on. */
1061
+ mode: HappyOysterMode;
1062
+ /** Every beat the vendor refused on content grounds in this pane so far. */
1063
+ refusedBeatIds: readonly string[];
1064
+ /** The story-graph beats, for the label. Absent ⇒ `Beat <raw id>`. */
1065
+ beatById?: ReadonlyMap<string, BeatView>;
1066
+ }): DmWorldRefusalRoute[] {
1067
+ const refused = new Set(input.refusedBeatIds.map(id => id.trim()));
1068
+ const beatById = input.beatById ?? new Map<string, BeatView>();
1069
+ const seen = new Set<string>();
1070
+ const routes: DmWorldRefusalRoute[] = [];
1071
+ for (const frame of orderStoryboardFrames(input.frameIds, input.frames)) {
1072
+ const beatId = frame.beatId?.trim() ?? '';
1073
+ if (beatId === '' || refused.has(beatId) || seen.has(beatId)) continue;
1074
+ seen.add(beatId);
1075
+ const planned = planDmWorldEntry({
1076
+ frameIds: input.frameIds,
1077
+ frames: input.frames,
1078
+ activeBeatId: beatId,
1079
+ mode: input.mode,
1080
+ });
1081
+ if (!planned.ok) continue;
1082
+ const { action } = planned.plan;
1083
+ routes.push({
1084
+ beatId,
1085
+ frameId: planned.plan.frame.frameId,
1086
+ action,
1087
+ label: beatHeadline(beatId, beatById),
1088
+ hint:
1089
+ action === 'reopen'
1090
+ ? DM_WORLD_REFUSAL_ROUTE_REOPEN_HINT
1091
+ : DM_WORLD_REFUSAL_ROUTE_BUILD_HINT,
1092
+ });
1093
+ }
1094
+ // Stable: board order within each group.
1095
+ return [
1096
+ ...routes.filter(route => route.action === 'reopen'),
1097
+ ...routes.filter(route => route.action !== 'reopen'),
1098
+ ];
1099
+ }
1100
+
1101
+ /** A resolved, authorised world entry. Produced ONLY by
1102
+ * {@link planDmWorldEntry}; {@link launchDmWorldEntry} takes nothing else. */
1103
+ export interface DmWorldEntryPlan {
1104
+ action: DmWorldEntryAction;
1105
+ /** The deterministically resolved seed frame. */
1106
+ frame: StoryboardFrame;
1107
+ /** The mode-fixed model this entry runs on (host-supplied — see the module
1108
+ * docblock's PARKED note). */
1109
+ mode: HappyOysterMode;
1110
+ /** The permanent world to reopen/steer — non-null on `'reopen'`/`'steer'`. */
1111
+ handle: HappyOysterWorldHandle | null;
1112
+ /**
1113
+ * The composed prompt (frame prompt + atmosphere), inside the vendor cap. The
1114
+ * create prompt on `'create'`/`'confirm_required'`; the `instruct` text on
1115
+ * `'steer'`. Empty on `'reopen'`, which sends no prompt.
1116
+ */
1117
+ prompt: string;
1118
+ /** The frame image to fetch BYTES from — never handed to the vendor as a
1119
+ * URL. Null on `'reopen'`/`'steer'`, which create nothing. */
1120
+ seedImageUrl: string | null;
1121
+ /**
1122
+ * Rail 3/4 — how long the surface should let an AUTO-FIRED world run before
1123
+ * stopping it, in ms. Null when the entry was not auto-fired: a player who
1124
+ * asked for the world by hand is not yanked out of it on a timer.
1125
+ */
1126
+ autoStopAfterMs: number | null;
1127
+ }
1128
+
1129
+ /**
1130
+ * Whether an action would MINT a new permanent, billed world (`'create'` now,
1131
+ * `'confirm_required'` once an operator confirms). Derived from the action
1132
+ * rather than stored on the plan, so no plan can carry a stale flag.
1133
+ */
1134
+ export function dmWorldEntryWouldCreateWorld(
1135
+ action: DmWorldEntryAction,
1136
+ ): boolean {
1137
+ return action === 'create' || action === 'confirm_required';
1138
+ }
1139
+
1140
+ /** A plan, or the reason there is none. */
1141
+ export type DmWorldEntryPlanResult =
1142
+ | { ok: true; plan: DmWorldEntryPlan }
1143
+ | { ok: false; reason: DmWorldEntryBlockReason; message: string };
1144
+
1145
+ export interface DmWorldEntryPlanInput {
1146
+ /** The board's ordering source of truth (`Storyboard.frameIds`). */
1147
+ frameIds: readonly string[];
1148
+ /** The detail read's frames, in any order. */
1149
+ frames: readonly StoryboardFrame[];
1150
+ /** The beat the party is standing on — the deterministic join key. */
1151
+ activeBeatId: string | null | undefined;
1152
+ /**
1153
+ * The DM tag's free-text `prompt`. **Atmosphere only**: it is appended to the
1154
+ * frame's compiled prompt and can never select or replace the seed.
1155
+ */
1156
+ atmosphere?: string | null;
1157
+ /** The mode-fixed HappyOyster model the host will connect to. */
1158
+ mode: HappyOysterMode;
1159
+ /** Rail 1 — the player's "let the DM open worlds on its own" setting.
1160
+ * Defaults to {@link DM_WORLD_AUTO_FIRE_DEFAULT} (`false`). */
1161
+ autoFireEnabled?: boolean;
1162
+ /** The world currently streaming, if any (owner `DM.12` — steer it instead of
1163
+ * minting a new one unless the scene changed). */
1164
+ liveWorld?: DmLiveWorld | null;
1165
+ /** Rail 4 — the studio-configured auto-stop interval. Defaults to
1166
+ * {@link DM_WORLD_AUTO_STOP_MS_DEFAULT} (30 s). */
1167
+ autoStopAfterMs?: number;
1168
+ }
1169
+
1170
+ /**
1171
+ * Resolve the ACTIVE BEAT to its board frame, deterministically.
1172
+ *
1173
+ * Board order (`frameIds`) is the tie-break, so the same beat always resolves
1174
+ * to the same frame for every player of the story. A beat with several frames
1175
+ * prefers the first that has actually RENDERED — an unrendered frame has no
1176
+ * seed, and silently seeding from a later beat would be worse than reporting
1177
+ * nothing.
1178
+ *
1179
+ * Returns `null` when the beat is absent or no frame carries it.
1180
+ */
1181
+ export function resolveDmWorldEntryFrame(input: {
1182
+ frameIds: readonly string[];
1183
+ frames: readonly StoryboardFrame[];
1184
+ activeBeatId: string | null | undefined;
1185
+ }): StoryboardFrame | null {
1186
+ const beatId = input.activeBeatId?.trim() ?? '';
1187
+ if (beatId === '') return null;
1188
+ const matches = orderStoryboardFrames(input.frameIds, input.frames).filter(
1189
+ frame => frame.beatId === beatId,
1190
+ );
1191
+ return matches.find(frame => frameImageUrl(frame) !== null) ?? matches[0] ?? null;
1192
+ }
1193
+
1194
+ /**
1195
+ * How many characters {@link composeDmWorldPrompt} holds back from the frame's
1196
+ * compacted prompt so the DM tag's atmosphere survives (§Q `DM.21`).
1197
+ *
1198
+ * The prefix plus enough of the atmosphere to be worth appending —
1199
+ * {@link DM_WORLD_ATMOSPHERE_MIN_CHARS}, the floor the module already used to
1200
+ * decide a stub was not worth shipping — or the WHOLE atmosphere when it is
1201
+ * shorter than that floor, because reserving more ceremony than the text needs
1202
+ * would shed board context for nothing.
1203
+ *
1204
+ * `0` for an empty atmosphere: nothing to seat, so the frame gets the full cap.
1205
+ */
1206
+ export function dmWorldAtmosphereReservation(atmosphere: string): number {
1207
+ if (atmosphere === '') return 0;
1208
+ return (
1209
+ DM_WORLD_ATMOSPHERE_PREFIX.length +
1210
+ Math.min(atmosphere.length, DM_WORLD_ATMOSPHERE_MIN_CHARS)
1211
+ );
1212
+ }
1213
+
1214
+ /**
1215
+ * Compose the prompt: the frame's SERVER-COMPILED prompt text, COMPACTED to
1216
+ * the vendor cap, plus the DM tag's atmosphere.
1217
+ *
1218
+ * The base is `FrameVariant.promptText` — the exact string the storyboard
1219
+ * worker sent for this frame — deliberately NOT a client-side re-flattening of
1220
+ * `FramePrompt`. `compiled_text()` is server-side by design (`FramePrompt`'s
1221
+ * docblock) and a second flattener here would be a second source of truth for
1222
+ * what a frame looks like.
1223
+ *
1224
+ * §Q `SB.34` — read through `promptFrameVariant`, NOT `displayFrameVariant`.
1225
+ * The latter is succeeded-only (correctly, for images), which meant a frame
1226
+ * whose render was refused reported no prompt at all and blocked the beat as if
1227
+ * it had never been storyboarded. The prompt is composed BEFORE the image call
1228
+ * and is not what failed, so a failed variant's text is a real answer here even
1229
+ * though its (absent) image is not. This is the accessor split the row calls
1230
+ * for: image display keeps the succeeded-only rule untouched.
1231
+ *
1232
+ * §Q `DM.18` — `compiled_text` is budgeted against `PROMPT_TEXT_MAX_LEN * 4`
1233
+ * and a real frame compiles past {@link HAPPY_OYSTER_PROMPT_MAX_CHARS}, so the
1234
+ * base runs through {@link compactFramePromptText} first. That sheds whole
1235
+ * semantic units (reference addressing, arc stakes, themes) in a fixed
1236
+ * ceremony-first order and NEVER touches the `Action` line — see that module
1237
+ * for why truncation is not an option here. A base already inside the cap comes
1238
+ * back byte-identical.
1239
+ *
1240
+ * A frame whose `Action` alone exceeds the cap stays over it: this returns the
1241
+ * fully-shed text and `planDmWorldEntry`'s `happyOysterPromptIssue` check
1242
+ * reports `prompt_invalid` with the real overflow, rather than launching a
1243
+ * world built from half a beat.
1244
+ *
1245
+ * §Q `DM.21` — DM.18 left the real frame at 1999 of 2000, so the DM tag's own
1246
+ * text no longer fit and was dropped. `DM.19` established that the world tracks
1247
+ * the storyboard's PROSE, which makes that drop the loss of the INTERACTIVE
1248
+ * half of the entry: the world gets built from the board alone and the DM's
1249
+ * live scene intent is silently discarded. So the atmosphere's room is now
1250
+ * RESERVED before compaction — and taken from CEREMONY only
1251
+ * (`shedTiers: ['ceremony']`), never from the cast, the setting or the action.
1252
+ * That honours the ratified "the frame is never the thing that gets cut"
1253
+ * precedence rather than inverting it: ceremony is not the frame's substance.
1254
+ * When ceremony alone cannot free the reservation, the reservation is abandoned
1255
+ * and the full-cap compaction stands — the frame still wins.
1256
+ *
1257
+ * Returns `null` when the frame carries no compiled prompt.
1258
+ */
1259
+ export function composeDmWorldPrompt(
1260
+ frame: StoryboardFrame,
1261
+ atmosphere?: string | null,
1262
+ ): string | null {
1263
+ const compiled = promptFrameVariant(frame)?.promptText?.trim() ?? '';
1264
+ if (compiled === '') return null;
1265
+ // The frame's STRUCTURED cast, so the cast rung keeps every name exactly
1266
+ // instead of re-deriving the roster from the flattened `Characters:` line.
1267
+ const castInWords = frame.prompt?.charactersInWords;
1268
+ const extra = atmosphere?.trim() ?? '';
1269
+
1270
+ // §Q DM.21 — reserve the atmosphere's room out of CEREMONY before compacting.
1271
+ // A ceremony-only pass that cannot reach the reduced target comes back over
1272
+ // it; the full-cap compaction below is then the answer and the atmosphere
1273
+ // takes whatever is left, exactly as before.
1274
+ const reservation = dmWorldAtmosphereReservation(extra);
1275
+ if (reservation > 0) {
1276
+ const target = HAPPY_OYSTER_PROMPT_MAX_CHARS - reservation;
1277
+ const reserved = compactFramePromptText(compiled, target, {
1278
+ castInWords,
1279
+ shedTiers: ['ceremony'],
1280
+ });
1281
+ if (reserved.text.length <= target) {
1282
+ return appendDmWorldAtmosphere(reserved.text, extra);
1283
+ }
1284
+ }
1285
+
1286
+ const base = compactFramePromptText(compiled, HAPPY_OYSTER_PROMPT_MAX_CHARS, {
1287
+ castInWords,
1288
+ }).text;
1289
+ return extra === '' ? base : appendDmWorldAtmosphere(base, extra);
1290
+ }
1291
+
1292
+ /**
1293
+ * Append the atmosphere to an already-compacted base, inside the vendor cap.
1294
+ *
1295
+ * The frame text is never cut here — the base arrives compacted and this only
1296
+ * decides how much of the ATMOSPHERE fits. Three outcomes, in order: the whole
1297
+ * atmosphere when it fits; a trimmed one when at least
1298
+ * {@link DM_WORLD_ATMOSPHERE_MIN_CHARS} of it does; nothing when even that
1299
+ * would be a stub.
1300
+ */
1301
+ function appendDmWorldAtmosphere(base: string, extra: string): string {
1302
+ const room =
1303
+ HAPPY_OYSTER_PROMPT_MAX_CHARS -
1304
+ base.length -
1305
+ DM_WORLD_ATMOSPHERE_PREFIX.length;
1306
+ if (extra.length <= room) {
1307
+ return `${base}${DM_WORLD_ATMOSPHERE_PREFIX}${extra}`;
1308
+ }
1309
+ if (room < DM_WORLD_ATMOSPHERE_MIN_CHARS) return base;
1310
+ return `${base}${DM_WORLD_ATMOSPHERE_PREFIX}${extra.slice(0, room).trimEnd()}`;
1311
+ }
1312
+
1313
+ /**
1314
+ * §Q `DM.62` — is the live world's scene the SAME scene as this frame's?
1315
+ *
1316
+ * The steer-vs-create decision hangs on this one predicate, and it used to be
1317
+ * `(liveWorld.sequenceId ?? null) === (frame.sequenceId ?? null)`. A null
1318
+ * sequence anchor is not an identity: it means "this frame is not anchored to a
1319
+ * sequence", and TWO of those compared EQUAL. Measured 2026-08-02: 8 of 21 live
1320
+ * frames have a null `sequenceId` and every ENDING is one of them, so a world
1321
+ * opened on any unanchored beat was re-aimed at the ending's prompt instead of
1322
+ * the ending getting its own world — permanently, for the rest of the session.
1323
+ *
1324
+ * The rule, in order, so DM.12's spend rail survives intact:
1325
+ *
1326
+ * 1. **Same frame ⇒ `'same'`.** An exact identity, and the case that must
1327
+ * never mint a second world for one frame.
1328
+ * 2. **Both anchored ⇒ compare the anchors.** This is DM.12 unchanged: two
1329
+ * different frames of the same sequence are one scene and get a steer.
1330
+ * 3. **Unanchored and the frame ids differ ⇒ `'changed'`.** This is the row.
1331
+ * 4. **Neither anchored, no frame id ⇒ compare the beat**, when the host
1332
+ * recorded one.
1333
+ * 5. **Otherwise `'unknown'`** — NOT `'changed'`. The third value is the
1334
+ * point (codex P1 on #1663): a host that records no identity at all
1335
+ * cannot be said to have changed scene either, and collapsing that into
1336
+ * "changed" would let an explicit `autoFireEnabled: true` MINT A BILLED
1337
+ * WORLD for a scene that may already be streaming. `planDmWorldEntry`
1338
+ * routes `'unknown'` to `confirm_required` — a question, never a bill.
1339
+ */
1340
+ export type DmWorldSceneRelation = 'same' | 'changed' | 'unknown';
1341
+
1342
+ export function dmWorldEntrySceneRelation(
1343
+ liveWorld: DmLiveWorld,
1344
+ frame: StoryboardFrame,
1345
+ ): DmWorldSceneRelation {
1346
+ const liveFrameId = liveWorld.frameId?.trim() ?? '';
1347
+ if (liveFrameId !== '' && liveFrameId === frame.frameId) return 'same';
1348
+
1349
+ // Deliberately NOT `return liveFrameId === frame.frameId` above: a DIFFERENT
1350
+ // frame of the SAME sequence is still one scene, and short-circuiting on the
1351
+ // frame id would have turned DM.12's steer into a create for every anchored
1352
+ // pan across a scene — a spend regression dressed up as a correctness fix.
1353
+ const liveSequenceId = liveWorld.sequenceId?.trim() ?? '';
1354
+ const frameSequenceId = frame.sequenceId?.trim() ?? '';
1355
+ if (liveSequenceId !== '' && frameSequenceId !== '') {
1356
+ return liveSequenceId === frameSequenceId ? 'same' : 'changed';
1357
+ }
1358
+
1359
+ // Unanchored, and the frame ids are known to differ: a change.
1360
+ if (liveFrameId !== '') return 'changed';
1361
+
1362
+ const liveBeatId = liveWorld.beatId?.trim() ?? '';
1363
+ const frameBeatId = frame.beatId?.trim() ?? '';
1364
+ if (liveBeatId !== '' && frameBeatId !== '') {
1365
+ return liveBeatId === frameBeatId ? 'same' : 'changed';
1366
+ }
1367
+
1368
+ return 'unknown';
1369
+ }
1370
+
1371
+ /**
1372
+ * Decide what a DM world entry may do, from deterministic state only.
1373
+ *
1374
+ * Every failure path lands here — BEFORE `connect`, before `createWorld`, so
1375
+ * before anything is billed. Exactly one branch mints a billed world
1376
+ * (`'create'`), and it requires BOTH the player's auto-fire setting AND a
1377
+ * genuine scene change; everything else steers, reopens, or asks.
1378
+ */
1379
+ export function planDmWorldEntry(
1380
+ input: DmWorldEntryPlanInput,
1381
+ ): DmWorldEntryPlanResult {
1382
+ const frame = resolveDmWorldEntryFrame(input);
1383
+ if (frame === null) {
1384
+ const beatId = input.activeBeatId?.trim() ?? '';
1385
+ return beatId === ''
1386
+ ? {
1387
+ ok: false,
1388
+ reason: 'no_active_beat',
1389
+ // §Q DM.61(a) — this is the PRE-FIRST-TURN state, not a fault, and
1390
+ // the old copy ("No beat is active in this session yet — the world is
1391
+ // seeded from the storyboard frame for the current beat.") described
1392
+ // the join key instead of the situation. A definition spawn starts
1393
+ // with no beat until the DM's first `advance_story`, so a player who
1394
+ // launches and immediately asks for the world lands here on the happy
1395
+ // path. Say what has to happen, and let the block carry the action.
1396
+ message:
1397
+ 'The DM has not opened the scene yet, so the party is not standing on a beat — and a ' +
1398
+ "world is seeded from the storyboard frame for the beat you're on. Take your first turn " +
1399
+ 'in the chat; the world opens on the beat the DM moves you to.',
1400
+ }
1401
+ : {
1402
+ ok: false,
1403
+ reason: 'no_frame_for_beat',
1404
+ // §Q ARC.6k — the old copy read "storyboard this beat before
1405
+ // entering its world", and for a FORK-approved arc that instruction
1406
+ // is impossible to follow: a board is only ever minted in the
1407
+ // canonical story's id space, so no amount of re-storyboarding can
1408
+ // ever produce a frame carrying a fork-scoped beat id. The owner
1409
+ // followed it on 2026-08-02 and it could not have worked. The
1410
+ // caller-side scope translation (`storyboardJoinBeatId`) fixes the
1411
+ // JOIN; this fixes the advice for the residual cases where the join
1412
+ // still finds nothing, without prescribing an action that cannot
1413
+ // succeed.
1414
+ message:
1415
+ `No storyboard frame is anchored to beat "${beatId}" — a world is seeded from a ratified ` +
1416
+ "board frame and this story's board has none for it. Storyboard the beat to give it one; if " +
1417
+ 'this adventure came from a FORK-approved arc, storyboarding cannot reach it (boards are ' +
1418
+ 'minted only in the canonical story\'s id space) — re-approve the arc as a merge instead.',
1419
+ };
1420
+ }
1421
+
1422
+ const liveWorld = input.liveWorld ?? null;
1423
+
1424
+ // Owner DM.12 — a live world whose scene has NOT changed is steered, never
1425
+ // rebuilt. This is the rail that actually bounds spend: it caps `createWorld`
1426
+ // at one per scene instead of one per LLM emission.
1427
+ const sceneRelation =
1428
+ liveWorld === null ? null : dmWorldEntrySceneRelation(liveWorld, frame);
1429
+ if (liveWorld !== null && sceneRelation === 'same') {
1430
+ const steerPrompt = composeDmWorldPrompt(frame, input.atmosphere);
1431
+ if (steerPrompt === null) {
1432
+ return {
1433
+ ok: false,
1434
+ reason: 'prompt_unavailable',
1435
+ message:
1436
+ 'The storyboard frame carries no compiled prompt, so there is nothing to re-aim the world with.',
1437
+ };
1438
+ }
1439
+ return {
1440
+ ok: true,
1441
+ plan: {
1442
+ action: 'steer',
1443
+ frame,
1444
+ mode: input.mode,
1445
+ handle: liveWorld.handle,
1446
+ prompt: steerPrompt,
1447
+ seedImageUrl: null,
1448
+ autoStopAfterMs: null,
1449
+ },
1450
+ };
1451
+ }
1452
+
1453
+ // Owner ruling Q2 — world ownership is PER FRAME: a frame that already owns a
1454
+ // world reopens it. Free, instant, and it is preferred over any create.
1455
+ const worldId = frame.worldId?.trim() ?? '';
1456
+ if (worldId !== '') {
1457
+ // §Q DM.30 — the STORED mode, never the session's. This line used to read
1458
+ // `mode: input.mode`, which fabricated the handle's mode from whichever
1459
+ // session happened to be open: `launchHappyOysterWorld`'s pre-flight then
1460
+ // compared the session mode with itself and could never fire, so a world
1461
+ // belonging to the OTHER mode reached the vendor and came back
1462
+ // `[MODE_MISMATCH]` — with the world already paid for.
1463
+ const storedMode = frame.worldMode ?? null;
1464
+ if (storedMode !== null && storedMode !== input.mode) {
1465
+ return {
1466
+ ok: false,
1467
+ reason: 'world_mode_mismatch',
1468
+ message:
1469
+ `This beat's world belongs to the "${storedMode}" experience, but this session is "${input.mode}" — ` +
1470
+ 'HappyOyster worlds live on the mode-fixed model that created them and cannot be opened from the other one. ' +
1471
+ `Reopen it from the ${storedMode} surface.`,
1472
+ };
1473
+ }
1474
+ return {
1475
+ ok: true,
1476
+ plan: {
1477
+ action: 'reopen',
1478
+ frame,
1479
+ // A frame bound before DM.30 carries no mode. Falling back to the
1480
+ // session's keeps those (DM-created, therefore adventure) worlds
1481
+ // reopenable — the milestone run's `9b838d88…` frame among them —
1482
+ // rather than dead-ending every pre-DM.30 binding.
1483
+ handle: { encryptedWorldId: worldId, mode: storedMode ?? input.mode },
1484
+ mode: input.mode,
1485
+ prompt: '',
1486
+ seedImageUrl: null,
1487
+ autoStopAfterMs: null,
1488
+ },
1489
+ };
1490
+ }
1491
+
1492
+ const seedImageUrl = frameImageUrl(frame);
1493
+ if (seedImageUrl === null) {
1494
+ // §Q SB.34 — a REFUSED frame and a still-generating one are both "no image",
1495
+ // and telling the player to wait for one that will never arrive is the
1496
+ // failure the row is about. A world still cannot be created either way (the
1497
+ // seed is bytes), so this changes what the player is TOLD, not what is spent.
1498
+ if (frameRenderFailed(frame)) {
1499
+ const why = frameRenderFailure(frame);
1500
+ return {
1501
+ ok: false,
1502
+ reason: 'frame_render_failed',
1503
+ message:
1504
+ 'This beat IS storyboarded — its frame is written and waiting — but the image model refused or failed to draw it, so there is no starting image to seed the world with.' +
1505
+ (why === null ? '' : ` The model reported: ${why}`),
1506
+ };
1507
+ }
1508
+ return {
1509
+ ok: false,
1510
+ reason: 'frame_not_rendered',
1511
+ message:
1512
+ 'The storyboard frame for this beat has not rendered yet, so there is no starting image to seed the world with.',
1513
+ };
1514
+ }
1515
+ const prompt = composeDmWorldPrompt(frame, input.atmosphere);
1516
+ if (prompt === null) {
1517
+ return {
1518
+ ok: false,
1519
+ reason: 'prompt_unavailable',
1520
+ message:
1521
+ 'The storyboard frame carries no compiled prompt, so the world has nothing to build from.',
1522
+ };
1523
+ }
1524
+ const promptIssue = happyOysterPromptIssue(prompt);
1525
+ if (promptIssue !== null) {
1526
+ return { ok: false, reason: 'prompt_invalid', message: promptIssue };
1527
+ }
1528
+
1529
+ // Rail 1 — auto-fire is the player's setting, and reaching here means the
1530
+ // scene DID change (the steer branch above returns for an unchanged scene).
1531
+ //
1532
+ // §Q DM.62 / codex P1 on #1663 — EXCEPT when a world IS streaming and its
1533
+ // identity is unrecorded. That is not a scene change, it is an unanswered
1534
+ // question, and auto-firing it bills a second permanent world for a scene
1535
+ // that may already be on screen. Auto-fire is consent to skip the prompt on a
1536
+ // KNOWN cut, not consent to guess. An operator confirmation is the honest
1537
+ // resolution, and it is exactly one click.
1538
+ const autoFire =
1539
+ (input.autoFireEnabled ?? DM_WORLD_AUTO_FIRE_DEFAULT) && sceneRelation !== 'unknown';
1540
+ return {
1541
+ ok: true,
1542
+ plan: {
1543
+ action: autoFire ? 'create' : 'confirm_required',
1544
+ frame,
1545
+ mode: input.mode,
1546
+ handle: null,
1547
+ prompt,
1548
+ seedImageUrl,
1549
+ autoStopAfterMs: autoFire
1550
+ ? (input.autoStopAfterMs ?? DM_WORLD_AUTO_STOP_MS_DEFAULT)
1551
+ : null,
1552
+ },
1553
+ };
1554
+ }
1555
+
1556
+ export interface DmWorldEntryLaunchOptions {
1557
+ /**
1558
+ * The prepared seed BYTES. REQUIRED for any create — the launcher never falls
1559
+ * back to `firstFrameImageUrl` (see the module docblock).
1560
+ */
1561
+ seed?: PreparedHappyOysterSeed;
1562
+ /**
1563
+ * Explicit operator confirmation. The ONLY thing that unlocks a
1564
+ * `confirm_required` plan, i.e. the only way a world is created while the
1565
+ * player's auto-fire setting is off. A directive can never set this.
1566
+ */
1567
+ operatorConfirmed?: boolean;
1568
+ /**
1569
+ * Rail 2 — persist/record the permanent handle.
1570
+ *
1571
+ * Called at THREE points (§Q `DM.43`), de-duplicated so ONE world is written
1572
+ * once: at MINT time (the instant `createWorld` yields an id, before
1573
+ * `startTravel`), on success, and on a failure that nevertheless created a
1574
+ * world (`HappyOysterLaunchError.handle`). Worlds are permanent with no
1575
+ * listing API, and `startTravel` can occupy minutes, so waiting for either
1576
+ * settle-time offer leaves a long window in which a reload orphans a billed
1577
+ * asset.
1578
+ *
1579
+ * Return `false` ({@link DmWorldHandleRecorded}) when the write did NOT land,
1580
+ * so a later offer retries it; returning nothing means recorded. A throw is
1581
+ * treated the same as `false`, and is additionally swallowed on the failure
1582
+ * path so the ORIGINAL launch error still reaches the caller.
1583
+ */
1584
+ onWorldHandle?: (
1585
+ handle: HappyOysterWorldHandle,
1586
+ entry: DmWorldSessionEntry,
1587
+ ) => DmWorldHandleRecorded | void | Promise<DmWorldHandleRecorded | void>;
1588
+ jwt?: string;
1589
+ }
1590
+
1591
+ /**
1592
+ * §Q `DM.43` — whether a handle offer actually LANDED somewhere durable.
1593
+ *
1594
+ * `false` means the write failed and the world is still unrecorded, so the
1595
+ * launcher must offer the handle again at its next opportunity. Returning
1596
+ * nothing means "recorded", which keeps every pre-existing caller behaving
1597
+ * exactly as before.
1598
+ *
1599
+ * This exists because the DM host's `bindWorldToFrame` reports a failed write
1600
+ * by RESOLVING with `{status: 'unavailable'}` rather than throwing — so a
1601
+ * launcher that treated "did not throw" as "recorded" would mark the world done
1602
+ * on a transient API outage and never retry it. A 409 conflict is NOT such a
1603
+ * case: it is a durable answer (the frame already owns another world) that
1604
+ * retrying cannot improve.
1605
+ */
1606
+ export type DmWorldHandleRecorded = boolean;
1607
+
1608
+ /**
1609
+ * Execute a {@link planDmWorldEntry} plan. This is the ONLY place a DM world
1610
+ * entry reaches `createWorld`, and it refuses three things outright:
1611
+ *
1612
+ * - a `confirm_required` plan without `operatorConfirmed: true` (i.e. auto-fire
1613
+ * off and nobody confirmed);
1614
+ * - a create with no prepared seed bytes;
1615
+ * - anything the underlying launcher already refuses (prompt cap, mode
1616
+ * mismatch, …).
1617
+ *
1618
+ * All three throw a {@link HappyOysterLaunchError} before a session is opened.
1619
+ * A `'steer'` plan is NOT launched here, and no second executor is owed: the
1620
+ * adapter-agnostic steer path already shipped as §Q DM.14 — the pane registers
1621
+ * a steer closure (`useExperienceSource.registerWorldSteer`) and client-core's
1622
+ * `resolveWorldSteerCommand(adapterId)` maps it to the live model's verb
1623
+ * (HappyOyster → `instruct`). A steer plan feeds that, not this launcher.
1624
+ */
1625
+ export async function launchDmWorldEntry(
1626
+ plan: DmWorldEntryPlan,
1627
+ bridge: HappyOysterBridge,
1628
+ options: DmWorldEntryLaunchOptions = {},
1629
+ ): Promise<HappyOysterLaunchResult> {
1630
+ if (plan.action === 'steer') {
1631
+ throw new HappyOysterLaunchError({
1632
+ reason: 'invalid_request',
1633
+ message:
1634
+ 'A steer plan re-aims the live world through the pane, it does not launch one.',
1635
+ retryable: false,
1636
+ });
1637
+ }
1638
+ if (plan.action === 'confirm_required' && options.operatorConfirmed !== true) {
1639
+ throw new HappyOysterLaunchError({
1640
+ reason: 'invalid_request',
1641
+ message:
1642
+ 'Creating this world needs an explicit confirmation — a HappyOyster world is paid and permanent, so with auto-fire off a DM directive alone never creates one.',
1643
+ retryable: false,
1644
+ });
1645
+ }
1646
+
1647
+ // Exhaustive by construction: a new `DmWorldEntryAction` member fails to
1648
+ // compile here rather than falling through a ternary into 'confirmed'.
1649
+ const TRIGGERS: Record<
1650
+ Exclude<DmWorldEntryAction, 'steer'>,
1651
+ DmWorldSessionEntry['trigger']
1652
+ > = { reopen: 'reopen', create: 'auto', confirm_required: 'confirmed' };
1653
+ const trigger = TRIGGERS[plan.action];
1654
+ const launchOptions = { jwt: options.jwt };
1655
+ /**
1656
+ * §Q `DM.43` — worlds already recorded by THIS launch. The handle is now
1657
+ * offered at three points (created, succeeded, failed-but-created), and they
1658
+ * describe ONE world, so the frame is written once. Recorded only AFTER the
1659
+ * write resolves, so a failed create-time write is retried by the later
1660
+ * offers rather than being swallowed by its own bookkeeping.
1661
+ */
1662
+ const persisted = new Set<string>();
1663
+ const persist = async (handle: HappyOysterWorldHandle): Promise<void> => {
1664
+ if (persisted.has(handle.encryptedWorldId)) return;
1665
+ const recorded = await options.onWorldHandle?.(handle, {
1666
+ handle,
1667
+ frameId: plan.frame.frameId,
1668
+ beatId: plan.frame.beatId ?? null,
1669
+ trigger,
1670
+ openedAt: Date.now(),
1671
+ });
1672
+ // `false` is the host telling us the write did not land — see
1673
+ // {@link DmWorldHandleRecorded}. A throw is handled the same way, by never
1674
+ // reaching this line. Anything else (including `undefined`) is recorded.
1675
+ if (recorded !== false) persisted.add(handle.encryptedWorldId);
1676
+ };
1677
+
1678
+ if (plan.action === 'reopen') {
1679
+ // Non-null by construction — `planDmWorldEntry` sets `handle` on a reopen.
1680
+ const handle = plan.handle as HappyOysterWorldHandle;
1681
+ const result = await launchHappyOysterWorld(
1682
+ { kind: 'reopen', handle },
1683
+ bridge,
1684
+ plan.mode,
1685
+ launchOptions,
1686
+ );
1687
+ // Recorded like a create: rail 2 is about what the SESSION opened, and a
1688
+ // reopened world is just as visible and just as reachable.
1689
+ await persist(result.handle);
1690
+ return result;
1691
+ }
1692
+
1693
+ if (options.seed === undefined) {
1694
+ throw new HappyOysterLaunchError({
1695
+ reason: 'invalid_request',
1696
+ message:
1697
+ 'The starting frame has not been prepared — a DM world is always seeded from prepared image bytes, never from a frame URL.',
1698
+ retryable: false,
1699
+ });
1700
+ }
1701
+
1702
+ try {
1703
+ const result = await launchHappyOysterWorld(
1704
+ {
1705
+ kind: 'create',
1706
+ prompt: plan.prompt,
1707
+ firstFrameImage: options.seed.blob,
1708
+ },
1709
+ bridge,
1710
+ plan.mode,
1711
+ // §Q DM.43 — the handle goes to the frame the moment the vendor mints it,
1712
+ // BEFORE `startTravel`. Persisting only on success (or only from the
1713
+ // error's `handle`) leaves the whole 60 s stream-start window — and the
1714
+ // vendor's 3-attempt ladder behind it, up to ~3 minutes — as a period in
1715
+ // which a reload orphans a permanent, billed, unlistable world.
1716
+ { ...launchOptions, onWorldCreated: persist },
1717
+ );
1718
+ await persist(result.handle);
1719
+ return result;
1720
+ } catch (error) {
1721
+ if (error instanceof HappyOysterLaunchError && error.handle !== null) {
1722
+ // A world EXISTS and is already billed even though the launch failed.
1723
+ // Persist it before rethrowing, and never let a persistence failure
1724
+ // replace the error the caller needs to see.
1725
+ try {
1726
+ await persist(error.handle);
1727
+ } catch {
1728
+ /* the launch error below is the one that matters */
1729
+ }
1730
+ }
1731
+ throw error;
1732
+ }
1733
+ }
1734
+
1735
+ /* ==========================================================================
1736
+ * §Q `DM.66` — THE WORLD STOPPED STREAMING, AND THE SURFACE HAS TO SAY SO
1737
+ * ========================================================================== */
1738
+
1739
+ /**
1740
+ * WHAT WAS MEASURED. CHECKPOINT-2 (2026-08-02,
1741
+ * `~/.seer-e2e/checkpoint2-0802-verdicts.md` §B5) sampled the SAME world
1742
+ * `<video>` every 10 s with no user action in between:
1743
+ *
1744
+ * ```
1745
+ * s8 {readyState: 4, 864x480, currentTime: 55.893, paused: false}
1746
+ * s9 {readyState: 0, 0x0, currentTime: 0, paused: true }
1747
+ * ```
1748
+ *
1749
+ * and `checkpoint2-0802-worldplay-final-1440.png`, taken after that drop, still
1750
+ * shows the `● You're in the world` badge, *"The DM is narrating"*, and the
1751
+ * transport bar over a black pane. No error, no ended state, no way back in.
1752
+ *
1753
+ * WHY THE VENDOR'S OWN EVENT IS NOT ENOUGH. The SDK receives the RTC
1754
+ * `streamStop` and DELIBERATELY DISCARDS IT — its bundle logs *"Travel RTC
1755
+ * event: streamStop ignored, rely on status heartbeat"* — and its runtime
1756
+ * monitor answers a dead `<video>` by asking the backend for a status, which
1757
+ * reaches the client as `statusChanged('completed')` only if that request
1758
+ * agrees. In the measured failure the badge was still live and the transport
1759
+ * button still enabled, i.e. the client phase never left `streaming`. **So the
1760
+ * render element is the signal that is always present**, and the two facade
1761
+ * signals corroborate rather than lead.
1762
+ *
1763
+ * WHAT THIS SECTION DECIDES, and what it deliberately does not. It decides
1764
+ * whether the stream a surface is CLAIMING is still there, and what to say when
1765
+ * it is not. It decides NOTHING about *why* the vendor stops at ~t+68 s —
1766
+ * whether that is the travel's natural end or a duration limit is `DM.57`'s
1767
+ * open measurement and belongs to the vendor thread.
1768
+ */
1769
+ export type DmWorldStreamEndReason =
1770
+ /** The SDK reported the travel `completed` — authoritative, vendor-side. */
1771
+ | 'travel_completed'
1772
+ /** The client left the `streaming` phase without a completed travel: the
1773
+ * session dropped, or the SDK tore the travel down itself. */
1774
+ | 'session_ended'
1775
+ /** The render element is at `HAVE_NOTHING` while a live world is claimed. A
1776
+ * rebuffering stream sits at 2/3 and fires `waiting`/`stalled`; it does not
1777
+ * drop to 0. This is the reading CHECKPOINT-2 captured. */
1778
+ | 'video_gone'
1779
+ /** The element still holds media but no new frame has arrived for
1780
+ * {@link DM_WORLD_STREAM_SILENCE_MS}. */
1781
+ | 'video_silent';
1782
+
1783
+ /** Every reason, for runtime validation by a probe or a coherence check. */
1784
+ export const DM_WORLD_STREAM_END_REASONS: readonly DmWorldStreamEndReason[] = [
1785
+ 'travel_completed',
1786
+ 'session_ended',
1787
+ 'video_gone',
1788
+ 'video_silent',
1789
+ ];
1790
+
1791
+ /**
1792
+ * `HTMLMediaElement.HAVE_NOTHING`. Named because the whole `video_gone` verdict
1793
+ * turns on it and a bare `0` at a comparison site reads as a placeholder.
1794
+ */
1795
+ export const HTML_MEDIA_HAVE_NOTHING = 0;
1796
+
1797
+ /**
1798
+ * How long the render may go without a new frame before the stream is called
1799
+ * dead, in ms.
1800
+ *
1801
+ * DELIBERATELY LONGER THAN THE SDK'S OWN CONFIRM DELAY. The SDK's runtime
1802
+ * monitor debounces a `waiting`/`stalled`/`suspend` by
1803
+ * `DEFAULT_VIDEO_ISSUE_CONFIRM_DELAY_MS = 3000` and then re-checks whether the
1804
+ * element became playable again — i.e. the vendor treats sub-3 s silence as
1805
+ * ordinary rebuffering. A host bound at or below that would paint "the stream
1806
+ * ended" over a stream the SDK is about to recover, which is the same
1807
+ * dishonest surface this row exists to remove, pointing the other way. 15 s is
1808
+ * five times the vendor's own tolerance and still well inside the 10 s
1809
+ * sampling interval that caught the real failure.
1810
+ */
1811
+ export const DM_WORLD_STREAM_SILENCE_MS = 15_000;
1812
+
1813
+ /**
1814
+ * What a host reads off the world render element.
1815
+ *
1816
+ * Deliberately NOT the element's own `paused`: it is `true` under the player's
1817
+ * own Pause, under an autoplay refusal and under a dead stream alike, so it
1818
+ * decides nothing this reducer does not already decide better. A paused
1819
+ * element that is not the player's doing stops `currentTime`, which the silence
1820
+ * bound catches.
1821
+ */
1822
+ export interface DmWorldStreamSample {
1823
+ /** `HTMLMediaElement.readyState`. */
1824
+ readyState: number;
1825
+ currentTime: number;
1826
+ }
1827
+
1828
+ /**
1829
+ * How long an INFERRED end must persist before a surface may state it, in ms.
1830
+ *
1831
+ * Longer than the SDK's own `DEFAULT_VIDEO_ISSUE_CONFIRM_DELAY_MS = 3000`
1832
+ * rebuffer-confirm delay, for the same reason the silence bound is: a single
1833
+ * sample at `HAVE_NOTHING` — a source swap, a reload, a brief rebuffer — is not
1834
+ * yet a dead stream, and painting the ended notice on it is the mirror of the
1835
+ * defect this row removes.
1836
+ */
1837
+ export const DM_WORLD_STREAM_DEAD_CONFIRM_MS = 4_000;
1838
+
1839
+ /**
1840
+ * Whether a reason may be stated the moment it is first seen.
1841
+ *
1842
+ * Only the vendor-reported end is authoritative enough: `travel_completed` is
1843
+ * the SDK folding a server-side status into its own facade, so there is nothing
1844
+ * to confirm and nothing to recover from. Everything else is INFERRED from the
1845
+ * client's own view and must persist for {@link DM_WORLD_STREAM_DEAD_CONFIRM_MS}
1846
+ * before a surface says it out loud.
1847
+ */
1848
+ export function dmWorldStreamEndIsImmediate(
1849
+ reason: DmWorldStreamEndReason,
1850
+ ): boolean {
1851
+ return reason === 'travel_completed';
1852
+ }
1853
+
1854
+ /** The SDK client phase that means the live stream is up. */
1855
+ export const HAPPY_OYSTER_PHASE_STREAMING = 'streaming';
1856
+
1857
+ /**
1858
+ * The `onTravelStatusChanged` value the SDK folds into its own facade state —
1859
+ * it is the one status on which `HappyOysterModel.handleTravelCompleted` runs.
1860
+ * Named here so a host compares against vendor vocabulary in one place instead
1861
+ * of spelling the literal at each call site.
1862
+ */
1863
+ export const HAPPY_OYSTER_TRAVEL_STATUS_COMPLETED = 'completed';
1864
+
1865
+ export interface DmWorldStreamHealthInput {
1866
+ /** The SDK's `onTravelStatusChanged` reached `completed`. */
1867
+ travelCompleted: boolean;
1868
+ /** `HappyOysterModel.phase`. {@link HAPPY_OYSTER_PHASE_STREAMING} is the only
1869
+ * healthy value while a live world is claimed; `null`/`undefined` means the
1870
+ * host could not read one and the phase decides nothing. */
1871
+ clientPhase: string | null | undefined;
1872
+ /** The player pressed Pause. A paused world is HELD, not dead, so no
1873
+ * element-derived reason may fire while this is true. */
1874
+ userPaused: boolean;
1875
+ /** The render element's reading, or `null` when it could not be read. */
1876
+ sample: DmWorldStreamSample | null;
1877
+ /** Milliseconds since `currentTime` last advanced, or `null` when there is no
1878
+ * baseline yet (the first sample of a launch). */
1879
+ msSinceAdvance: number | null;
1880
+ }
1881
+
1882
+ /**
1883
+ * Why the claimed-live world is not streaming, or `null` while it is fine.
1884
+ *
1885
+ * Pure, so a host can call it on a timer and a check can call it on a fixture.
1886
+ * Order is authority: a vendor-reported end outranks the client phase, which
1887
+ * outranks anything inferred from the element. Reversible BY CONSTRUCTION —
1888
+ * it reads only the current observation, so an element that starts advancing
1889
+ * again returns `null` and the surface goes back to claiming the world.
1890
+ */
1891
+ export function dmWorldStreamEndReason(
1892
+ input: DmWorldStreamHealthInput,
1893
+ ): DmWorldStreamEndReason | null {
1894
+ if (input.travelCompleted) return 'travel_completed';
1895
+ if (
1896
+ typeof input.clientPhase === 'string' &&
1897
+ input.clientPhase !== HAPPY_OYSTER_PHASE_STREAMING
1898
+ ) {
1899
+ return 'session_ended';
1900
+ }
1901
+ // A held world is not a dead one. The player's own Pause stops `currentTime`
1902
+ // and sets the element's `paused`, so every element-derived reason below
1903
+ // would otherwise fire on it.
1904
+ if (input.userPaused) return null;
1905
+ if (input.sample === null) return null;
1906
+ if (input.sample.readyState === HTML_MEDIA_HAVE_NOTHING) return 'video_gone';
1907
+ if (
1908
+ input.msSinceAdvance !== null &&
1909
+ input.msSinceAdvance >= DM_WORLD_STREAM_SILENCE_MS
1910
+ ) {
1911
+ return 'video_silent';
1912
+ }
1913
+ return null;
1914
+ }
1915
+
1916
+ /** What a surface renders when the stream is gone. */
1917
+ export interface DmWorldStreamEndedNotice {
1918
+ title: string;
1919
+ detail: string;
1920
+ /** The label for the re-entry affordance, or `null` when there is no recorded
1921
+ * world to go back to and the only honest offer is to leave. */
1922
+ action: string | null;
1923
+ }
1924
+
1925
+ export const DM_WORLD_STREAM_ENDED_TITLE = 'The world stopped streaming';
1926
+ export const DM_WORLD_REENTER_ACTION = 'Re-enter the world';
1927
+
1928
+ const DM_WORLD_STREAM_END_DETAIL: Record<DmWorldStreamEndReason, string> = {
1929
+ travel_completed: 'The world model ended this run, so no more video is coming.',
1930
+ session_ended: 'The session carrying this world closed, so the video stopped.',
1931
+ video_gone:
1932
+ 'No video is reaching this browser any more — the stream is gone rather than buffering.',
1933
+ video_silent: `No new frames have arrived for ${seconds(
1934
+ DM_WORLD_STREAM_SILENCE_MS,
1935
+ )} seconds, so this run has stopped.`,
1936
+ };
1937
+
1938
+ /**
1939
+ * The permanence claim, appended ONLY when a handle exists to reopen.
1940
+ *
1941
+ * It used to be on every reason unconditionally, which overclaims: on a launch
1942
+ * whose world id never reached this surface, "the world is still recorded" is
1943
+ * exactly the thing that is not known (codex on #1669).
1944
+ */
1945
+ const DM_WORLD_STREAM_END_PERMANENCE =
1946
+ 'The world itself is permanent and is still recorded.';
1947
+
1948
+ /**
1949
+ * The copy for a dead stream — one place, so no surface can keep claiming a
1950
+ * live world.
1951
+ *
1952
+ * The re-entry half is NOT decoration: a stream that stopped with no way back
1953
+ * leaves a black pane, which is the state this row was filed against. When a
1954
+ * handle exists the detail carries {@link DM_WORLD_REOPEN_NOTICE} verbatim,
1955
+ * because re-entering IS a reopen and `DM.17` already measured what a reopen
1956
+ * does — it returns to the opening scene. Restating that in different words
1957
+ * here would be a second source of truth for it.
1958
+ */
1959
+ export function dmWorldStreamEndedNotice(
1960
+ reason: DmWorldStreamEndReason,
1961
+ options: { canReenter: boolean },
1962
+ ): DmWorldStreamEndedNotice {
1963
+ const base = DM_WORLD_STREAM_END_DETAIL[reason];
1964
+ return {
1965
+ title: DM_WORLD_STREAM_ENDED_TITLE,
1966
+ detail: options.canReenter
1967
+ ? `${base} ${DM_WORLD_STREAM_END_PERMANENCE} ${DM_WORLD_REOPEN_NOTICE}`
1968
+ : base,
1969
+ action: options.canReenter ? DM_WORLD_REENTER_ACTION : null,
1970
+ };
1971
+ }
1972
+
1973
+ /**
1974
+ * The plan a re-entry runs — ALWAYS a `'reopen'`, never a mint.
1975
+ *
1976
+ * ⛔ THE SPEND RAIL LIVES HERE, NOT IN THE SURFACE. The obvious re-entry is
1977
+ * "run the plan again", and on a `'create'` / `'confirm_required'` plan that
1978
+ * CREATES A SECOND PERMANENT BILLED WORLD every time the vendor stops the
1979
+ * stream — a charge for a fault the player did not cause. This builder is
1980
+ * structurally incapable of returning a minting action:
1981
+ * {@link dmWorldEntryWouldCreateWorld} is `false` for every plan it can return,
1982
+ * and it returns `null` (⇒ the surface offers only the exit) when no permanent
1983
+ * handle exists to reopen.
1984
+ *
1985
+ * `prompt` and `seedImageUrl` are cleared because a reopen sends neither, and
1986
+ * `autoStopAfterMs` is cleared because a re-entry is an explicit player action
1987
+ * — the auto-stop rail exists for worlds the player did not ask for.
1988
+ */
1989
+ export function dmWorldReentryPlan(
1990
+ plan: DmWorldEntryPlan | null,
1991
+ handle: HappyOysterWorldHandle | null,
1992
+ ): DmWorldEntryPlan | null {
1993
+ if (plan === null || handle === null) return null;
1994
+ return {
1995
+ ...plan,
1996
+ action: 'reopen',
1997
+ handle,
1998
+ prompt: '',
1999
+ seedImageUrl: null,
2000
+ autoStopAfterMs: null,
2001
+ };
2002
+ }
2003
+
2004
+ /* ==========================================================================
2005
+ * §Q `DM.73` — A FAILED BOARD READ IS NOT AN ABSENT BOARD
2006
+ * ========================================================================== */
2007
+
2008
+ /**
2009
+ * WHAT WAS MEASURED. On the 2026-08-03 GP.21 walk
2010
+ * (`~/.seer-e2e/gp21-0803-walk.log`), `GET /stories/{id}/storyboards` returned
2011
+ * **429** inside the episode's opening request burst. The host's board effect
2012
+ * caught it, set only its settled flag, and left `board` null — on an effect
2013
+ * keyed `[apiClient, storyId, enabled]`, so nothing ever read again for the
2014
+ * lifetime of the mount. `planEntry` then returned null on every one of three
2015
+ * world-entry attempts and the pane rendered *"This story has no ratified
2016
+ * storyboard yet"* over storyboard `1f18e56a3f784a46a840e8d883e1b2b3`, which
2017
+ * was `succeeded` with 14/14 frames and returned 200 on a re-read minutes later.
2018
+ *
2019
+ * THE DEFECT IS THE CLAIM, NOT THE 429. One transient rate-limit told the player
2020
+ * a FALSE FACT, permanently, with no way to correct it short of a reload — and
2021
+ * the same false fact reached the harness, which reported it as GP.20 substrate
2022
+ * absence. (The burst itself is §Q `DM.74` and is not fixed here.)
2023
+ *
2024
+ * WHAT THIS SECTION OWNS: the vocabulary and the policy, pure and testable —
2025
+ * which read failures are worth retrying, how long to wait between attempts, and
2026
+ * what a surface says for each unsettled state. The timer and the effect stay in
2027
+ * the host, because they are React.
2028
+ */
2029
+
2030
+ /**
2031
+ * Where the host's board read has got to.
2032
+ *
2033
+ * `'absent'` and `'failed'` are the two that must never be collapsed: the first
2034
+ * is a read that SUCCEEDED and found no board, the second is a read that did not
2035
+ * succeed at all, so the story's board state is unknown.
2036
+ */
2037
+ export type DmWorldBoardReadStatus =
2038
+ /** The first attempt is in flight. */
2039
+ | 'loading'
2040
+ /** An attempt failed retryably and another is scheduled or in flight. */
2041
+ | 'retrying'
2042
+ /** A board is in hand. */
2043
+ | 'loaded'
2044
+ /** The read SUCCEEDED and the story has no storyboard. */
2045
+ | 'absent'
2046
+ /** Every permitted attempt failed. The board state is UNKNOWN. */
2047
+ | 'failed';
2048
+
2049
+ /** Every status, for runtime validation by a probe or a coherence check. */
2050
+ export const DM_WORLD_BOARD_READ_STATUSES: readonly DmWorldBoardReadStatus[] = [
2051
+ 'loading',
2052
+ 'retrying',
2053
+ 'loaded',
2054
+ 'absent',
2055
+ 'failed',
2056
+ ];
2057
+
2058
+ /** `429 Too Many Requests` — the status this row was filed against. Named
2059
+ * because a bare `429` at a comparison site reads as a placeholder. */
2060
+ export const HTTP_STATUS_TOO_MANY_REQUESTS = 429;
2061
+
2062
+ /** The floor of the 5xx range: everything at or above it is a server-side
2063
+ * fault, i.e. not something this client asked for wrongly. */
2064
+ export const HTTP_STATUS_SERVER_ERROR_FLOOR = 500;
2065
+
2066
+ /**
2067
+ * How many times the board read may be attempted in total, including the first.
2068
+ *
2069
+ * Three, not more: the read sits on the episode's own mount, so every extra
2070
+ * attempt is latency a player waits through before the DM can ground anything —
2071
+ * and the burst that produced the 429 is itself the thing more attempts would
2072
+ * feed. Exhausting these leaves a RETRYABLE block, so the ceiling costs the
2073
+ * player a click rather than the answer.
2074
+ */
2075
+ export const DM_WORLD_BOARD_READ_MAX_ATTEMPTS = 3;
2076
+
2077
+ /**
2078
+ * The wait before attempt N+1, in ms — one entry per retry, so its length is
2079
+ * {@link DM_WORLD_BOARD_READ_MAX_ATTEMPTS} minus the first attempt.
2080
+ *
2081
+ * Backed off rather than flat because the failure mode being retried is a rate
2082
+ * limit produced by a burst this read is part of; retrying immediately re-enters
2083
+ * the burst. Short in absolute terms because the whole schedule runs BEFORE the
2084
+ * player can be told anything true about the board.
2085
+ */
2086
+ export const DM_WORLD_BOARD_READ_RETRY_DELAYS_MS: readonly number[] = [
2087
+ 600, 1_800,
2088
+ ];
2089
+
2090
+ /**
2091
+ * Whether an HTTP status is worth another attempt.
2092
+ *
2093
+ * `null`/`undefined` — a transport failure with no response at all — IS
2094
+ * retryable: that is the offline blip and the aborted connection, neither of
2095
+ * which says anything about the board.
2096
+ *
2097
+ * A `404`/`403` is deliberately NOT retryable. Those are answers: retrying them
2098
+ * would spin a story that legitimately has no board (or that this viewer may not
2099
+ * read) through the full schedule before settling, which is latency bought for
2100
+ * nothing.
2101
+ */
2102
+ export function isRetryableBoardReadStatus(
2103
+ status: number | null | undefined,
2104
+ ): boolean {
2105
+ if (status === null || status === undefined) return true;
2106
+ return (
2107
+ status === HTTP_STATUS_TOO_MANY_REQUESTS ||
2108
+ status >= HTTP_STATUS_SERVER_ERROR_FLOOR
2109
+ );
2110
+ }
2111
+
2112
+ /**
2113
+ * {@link isRetryableBoardReadStatus} against a thrown error.
2114
+ *
2115
+ * `http.ts` enriches every thrown request error with `.status` (§Q `AA.5c`), so
2116
+ * this branches on the status rather than pattern-matching a message — an error
2117
+ * carrying no status at all is a transport failure and retryable.
2118
+ */
2119
+ export function dmWorldBoardReadIsRetryable(err: unknown): boolean {
2120
+ if (typeof err !== 'object' || err === null) return true;
2121
+ const status = (err as { status?: unknown }).status;
2122
+ return isRetryableBoardReadStatus(
2123
+ typeof status === 'number' ? status : undefined,
2124
+ );
2125
+ }
2126
+
2127
+ /**
2128
+ * How long to wait before the attempt that follows `attemptsMade`, or `null`
2129
+ * when no attempt is left.
2130
+ *
2131
+ * Takes the number of attempts ALREADY made, so a caller counting from 1 asks
2132
+ * the same question the schedule answers and there is no off-by-one to get
2133
+ * wrong at the call site.
2134
+ */
2135
+ export function dmWorldBoardReadRetryDelayMs(
2136
+ attemptsMade: number,
2137
+ ): number | null {
2138
+ if (attemptsMade < 1) return null;
2139
+ if (attemptsMade >= DM_WORLD_BOARD_READ_MAX_ATTEMPTS) return null;
2140
+ return (
2141
+ DM_WORLD_BOARD_READ_RETRY_DELAYS_MS[attemptsMade - 1] ??
2142
+ DM_WORLD_BOARD_READ_RETRY_DELAYS_MS[
2143
+ DM_WORLD_BOARD_READ_RETRY_DELAYS_MS.length - 1
2144
+ ] ??
2145
+ null
2146
+ );
2147
+ }
2148
+
2149
+ /** The message for a board read that has not settled yet. It states the state
2150
+ * and claims nothing about whether a board exists. */
2151
+ export const DM_WORLD_BOARD_READ_PENDING_MESSAGE =
2152
+ "The storyboard this world would be seeded from is still loading. Whether this story has a ratified board is not known yet — nothing has been decided against it.";
2153
+
2154
+ /**
2155
+ * The message for a board read this session has stopped attempting — the
2156
+ * schedule was exhausted, or the failure was one retrying cannot resolve.
2157
+ *
2158
+ * It must say UNKNOWN, not absent: the whole row exists because a 429 was
2159
+ * rendered as *"this story has no ratified storyboard yet"* over a board that
2160
+ * was succeeded and 14/14. Deliberately claims no ATTEMPT COUNT — a
2161
+ * non-retryable failure settles here on the first one, and a message asserting
2162
+ * three would be its own small lie.
2163
+ */
2164
+ export const DM_WORLD_BOARD_READ_FAILED_MESSAGE =
2165
+ 'The storyboard could not be read, so it is unknown whether this story has one. This is a failed read, not a missing board — the story may well have a ratified storyboard that this session could not fetch.';
2166
+
2167
+ /**
2168
+ * The host block for a board-read status, or `null` when the status carries no
2169
+ * block at all.
2170
+ *
2171
+ * `'loaded'` has a board, so the PLANNER decides and this must not speak over
2172
+ * it. `'absent'` is the one status that genuinely means no board — it keeps the
2173
+ * `reason: null` / {@link DM_WORLD_ENTRY_NO_BOARD_TITLE} rendering, which is now
2174
+ * true wherever it appears, because the two states that used to borrow it have
2175
+ * their own.
2176
+ */
2177
+ /**
2178
+ * Whether a block came from the BOARD READ rather than from the planner.
2179
+ *
2180
+ * A host holds a block in state, so a block minted while the read was in flight
2181
+ * outlives the read unless something re-decides it. This is the predicate that
2182
+ * says which blocks are worth re-deciding when the read's status moves: a
2183
+ * planner refusal is a decision about the beat and does not become stale when a
2184
+ * board arrives, but a board-read block is nothing BUT a statement about the
2185
+ * read.
2186
+ */
2187
+ export function dmWorldEntryBlockIsBoardRead(
2188
+ reason: DmWorldEntryRenderBlockReason | null,
2189
+ ): boolean {
2190
+ return reason === 'board_read_pending' || reason === 'board_read_failed';
2191
+ }
2192
+
2193
+ /**
2194
+ * §Q `DM.76` — whether this block is still IN FLIGHT rather than settled.
2195
+ *
2196
+ * Every other block reason is an ANSWER: the planner refused, the read failed,
2197
+ * the story has no board. `board_read_pending` is the one that says only *"ask
2198
+ * again in a moment"* — the read has not decided anything yet and the surface is
2199
+ * already doing the one thing that resolves it.
2200
+ *
2201
+ * That difference has to be readable by a surface, because a surface that
2202
+ * renders pending under the same handle as the settled blocks teaches every
2203
+ * reader — human and probe — that the entry is over. `golden-path.mjs` races
2204
+ * three TERMINAL selectors after a world directive, `dm-world-blocked` among
2205
+ * them, so a directive landing mid-read resolved that race on a state that was
2206
+ * about to become a live world and recorded the attempt as blocked. The
2207
+ * predicate lives here, beside the reasons, so no surface re-derives "is this
2208
+ * one still in flight" from a string literal of its own.
2209
+ */
2210
+ export function dmWorldEntryBlockIsPending(
2211
+ reason: DmWorldEntryRenderBlockReason | null,
2212
+ ): boolean {
2213
+ return reason === 'board_read_pending';
2214
+ }
2215
+
2216
+ export function dmWorldBoardBlock(
2217
+ status: DmWorldBoardReadStatus,
2218
+ ): DmWorldEntryBlock | null {
2219
+ if (status === 'loaded' || status === 'absent') return null;
2220
+ return dmWorldEntryBlock(
2221
+ status === 'failed' ? 'board_read_failed' : 'board_read_pending',
2222
+ status === 'failed'
2223
+ ? DM_WORLD_BOARD_READ_FAILED_MESSAGE
2224
+ : DM_WORLD_BOARD_READ_PENDING_MESSAGE,
2225
+ );
2226
+ }