@escapeaihq/client-core 0.8.0 → 0.42.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 (307) hide show
  1. package/README.md +48 -4
  2. package/dist/adapters/capabilities.d.ts +10 -0
  3. package/dist/adapters/capabilities.d.ts.map +1 -0
  4. package/dist/adapters/capabilities.js +2 -0
  5. package/dist/adapters/capabilities.js.map +1 -0
  6. package/dist/adapters/chatAdapter.d.ts +38 -0
  7. package/dist/adapters/chatAdapter.d.ts.map +1 -0
  8. package/dist/adapters/chatAdapter.js +88 -0
  9. package/dist/adapters/chatAdapter.js.map +1 -0
  10. package/dist/adapters/directorAdapter.d.ts +62 -0
  11. package/dist/adapters/directorAdapter.d.ts.map +1 -0
  12. package/dist/adapters/directorAdapter.js +71 -0
  13. package/dist/adapters/directorAdapter.js.map +1 -0
  14. package/dist/adapters/imageAdapter.d.ts +44 -0
  15. package/dist/adapters/imageAdapter.d.ts.map +1 -0
  16. package/dist/adapters/imageAdapter.js +73 -0
  17. package/dist/adapters/imageAdapter.js.map +1 -0
  18. package/dist/adapters/index.d.ts +47 -0
  19. package/dist/adapters/index.d.ts.map +1 -0
  20. package/dist/adapters/index.js +41 -0
  21. package/dist/adapters/index.js.map +1 -0
  22. package/dist/adapters/registry.d.ts +98 -0
  23. package/dist/adapters/registry.d.ts.map +1 -0
  24. package/dist/adapters/registry.js +106 -0
  25. package/dist/adapters/registry.js.map +1 -0
  26. package/dist/adapters/worldAdapter.d.ts +142 -0
  27. package/dist/adapters/worldAdapter.d.ts.map +1 -0
  28. package/dist/adapters/worldAdapter.js +164 -0
  29. package/dist/adapters/worldAdapter.js.map +1 -0
  30. package/dist/admin.d.ts +200 -0
  31. package/dist/admin.d.ts.map +1 -0
  32. package/dist/admin.js +124 -0
  33. package/dist/admin.js.map +1 -0
  34. package/dist/api.d.ts +1299 -3
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +683 -95
  37. package/dist/api.js.map +1 -1
  38. package/dist/audio.d.ts +33 -1
  39. package/dist/audio.d.ts.map +1 -1
  40. package/dist/audio.js +4 -1
  41. package/dist/audio.js.map +1 -1
  42. package/dist/castProjection.d.ts +35 -0
  43. package/dist/castProjection.d.ts.map +1 -0
  44. package/dist/castProjection.js +80 -0
  45. package/dist/castProjection.js.map +1 -0
  46. package/dist/conversation/binding.d.ts +62 -0
  47. package/dist/conversation/binding.d.ts.map +1 -0
  48. package/dist/conversation/binding.js +51 -0
  49. package/dist/conversation/binding.js.map +1 -0
  50. package/dist/conversation/controller.d.ts +209 -0
  51. package/dist/conversation/controller.d.ts.map +1 -0
  52. package/dist/conversation/controller.js +342 -0
  53. package/dist/conversation/controller.js.map +1 -0
  54. package/dist/conversation/effectiveModel.d.ts +62 -0
  55. package/dist/conversation/effectiveModel.d.ts.map +1 -0
  56. package/dist/conversation/effectiveModel.js +73 -0
  57. package/dist/conversation/effectiveModel.js.map +1 -0
  58. package/dist/conversation/index.d.ts +27 -0
  59. package/dist/conversation/index.d.ts.map +1 -0
  60. package/dist/conversation/index.js +27 -0
  61. package/dist/conversation/index.js.map +1 -0
  62. package/dist/conversation/participant.d.ts +66 -0
  63. package/dist/conversation/participant.d.ts.map +1 -0
  64. package/dist/conversation/participant.js +36 -0
  65. package/dist/conversation/participant.js.map +1 -0
  66. package/dist/conversation/presence.d.ts +56 -0
  67. package/dist/conversation/presence.d.ts.map +1 -0
  68. package/dist/conversation/presence.js +34 -0
  69. package/dist/conversation/presence.js.map +1 -0
  70. package/dist/conversation/presenceBus.d.ts +42 -0
  71. package/dist/conversation/presenceBus.d.ts.map +1 -0
  72. package/dist/conversation/presenceBus.js +81 -0
  73. package/dist/conversation/presenceBus.js.map +1 -0
  74. package/dist/conversation/presenceRegistry.d.ts +49 -0
  75. package/dist/conversation/presenceRegistry.d.ts.map +1 -0
  76. package/dist/conversation/presenceRegistry.js +59 -0
  77. package/dist/conversation/presenceRegistry.js.map +1 -0
  78. package/dist/conversation/roster.d.ts +72 -0
  79. package/dist/conversation/roster.d.ts.map +1 -0
  80. package/dist/conversation/roster.js +69 -0
  81. package/dist/conversation/roster.js.map +1 -0
  82. package/dist/conversation/rosterProjection.d.ts +52 -0
  83. package/dist/conversation/rosterProjection.d.ts.map +1 -0
  84. package/dist/conversation/rosterProjection.js +74 -0
  85. package/dist/conversation/rosterProjection.js.map +1 -0
  86. package/dist/conversation/router.d.ts +74 -0
  87. package/dist/conversation/router.d.ts.map +1 -0
  88. package/dist/conversation/router.js +58 -0
  89. package/dist/conversation/router.js.map +1 -0
  90. package/dist/conversation/runtime.d.ts +64 -0
  91. package/dist/conversation/runtime.d.ts.map +1 -0
  92. package/dist/conversation/runtime.js +172 -0
  93. package/dist/conversation/runtime.js.map +1 -0
  94. package/dist/conversation/types.d.ts +99 -0
  95. package/dist/conversation/types.d.ts.map +1 -0
  96. package/dist/conversation/types.js +13 -0
  97. package/dist/conversation/types.js.map +1 -0
  98. package/dist/conversation/voice.d.ts +185 -0
  99. package/dist/conversation/voice.d.ts.map +1 -0
  100. package/dist/conversation/voice.js +307 -0
  101. package/dist/conversation/voice.js.map +1 -0
  102. package/dist/graphSchema.d.ts +260 -0
  103. package/dist/graphSchema.d.ts.map +1 -0
  104. package/dist/graphSchema.js +354 -0
  105. package/dist/graphSchema.js.map +1 -0
  106. package/dist/http.d.ts +20 -0
  107. package/dist/http.d.ts.map +1 -0
  108. package/dist/http.js +57 -0
  109. package/dist/http.js.map +1 -0
  110. package/dist/index.d.ts +9 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +12 -0
  113. package/dist/index.js.map +1 -1
  114. package/dist/platformAssistant.d.ts +155 -0
  115. package/dist/platformAssistant.d.ts.map +1 -0
  116. package/dist/platformAssistant.js +256 -0
  117. package/dist/platformAssistant.js.map +1 -0
  118. package/dist/reactor/abortUtils.d.ts +16 -0
  119. package/dist/reactor/abortUtils.d.ts.map +1 -0
  120. package/dist/reactor/abortUtils.js +26 -0
  121. package/dist/reactor/abortUtils.js.map +1 -0
  122. package/dist/reactor/applyScenePrompt.d.ts +75 -0
  123. package/dist/reactor/applyScenePrompt.d.ts.map +1 -0
  124. package/dist/reactor/applyScenePrompt.js +60 -0
  125. package/dist/reactor/applyScenePrompt.js.map +1 -0
  126. package/dist/reactor/chunkDistribution.d.ts +43 -0
  127. package/dist/reactor/chunkDistribution.d.ts.map +1 -0
  128. package/dist/reactor/chunkDistribution.js +85 -0
  129. package/dist/reactor/chunkDistribution.js.map +1 -0
  130. package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -1
  131. package/dist/reactor/heliosCommandDispatcher.js +10 -15
  132. package/dist/reactor/heliosCommandDispatcher.js.map +1 -1
  133. package/dist/reactor/index.d.ts +4 -0
  134. package/dist/reactor/index.d.ts.map +1 -1
  135. package/dist/reactor/index.js +7 -0
  136. package/dist/reactor/index.js.map +1 -1
  137. package/dist/reactor/longLiveCommandDispatcher.d.ts +103 -0
  138. package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -0
  139. package/dist/reactor/longLiveCommandDispatcher.js +87 -0
  140. package/dist/reactor/longLiveCommandDispatcher.js.map +1 -0
  141. package/dist/reactor/sceneEntry.d.ts +40 -6
  142. package/dist/reactor/sceneEntry.d.ts.map +1 -1
  143. package/dist/reactor/sceneEntry.js +63 -24
  144. package/dist/reactor/sceneEntry.js.map +1 -1
  145. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -1
  146. package/dist/reactor/scenesFromEnrichment.js +2 -66
  147. package/dist/reactor/scenesFromEnrichment.js.map +1 -1
  148. package/dist/reactor/seedImageOrchestrator.d.ts +42 -2
  149. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  150. package/dist/reactor/seedImageOrchestrator.js +173 -4
  151. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  152. package/dist/reactor/storyTimeline.d.ts +44 -0
  153. package/dist/reactor/storyTimeline.d.ts.map +1 -0
  154. package/dist/reactor/storyTimeline.js +95 -0
  155. package/dist/reactor/storyTimeline.js.map +1 -0
  156. package/dist/storyGraph.d.ts +70 -0
  157. package/dist/storyGraph.d.ts.map +1 -0
  158. package/dist/storyGraph.js +178 -0
  159. package/dist/storyGraph.js.map +1 -0
  160. package/dist/timeFormat.d.ts +10 -0
  161. package/dist/timeFormat.d.ts.map +1 -1
  162. package/dist/timeFormat.js +12 -0
  163. package/dist/timeFormat.js.map +1 -1
  164. package/dist/toolSchemas.d.ts +370 -0
  165. package/dist/toolSchemas.d.ts.map +1 -0
  166. package/dist/toolSchemas.js +182 -0
  167. package/dist/toolSchemas.js.map +1 -0
  168. package/dist/vision/VisionPublisher.d.ts +115 -0
  169. package/dist/vision/VisionPublisher.d.ts.map +1 -0
  170. package/dist/vision/VisionPublisher.js +475 -0
  171. package/dist/vision/VisionPublisher.js.map +1 -0
  172. package/dist/vision/VisionSourceController.d.ts +127 -0
  173. package/dist/vision/VisionSourceController.d.ts.map +1 -0
  174. package/dist/vision/VisionSourceController.js +284 -0
  175. package/dist/vision/VisionSourceController.js.map +1 -0
  176. package/dist/vision/credentials.d.ts +22 -0
  177. package/dist/vision/credentials.d.ts.map +1 -0
  178. package/dist/vision/credentials.js +34 -0
  179. package/dist/vision/credentials.js.map +1 -0
  180. package/dist/vision/index.d.ts +18 -0
  181. package/dist/vision/index.d.ts.map +1 -0
  182. package/dist/vision/index.js +13 -0
  183. package/dist/vision/index.js.map +1 -0
  184. package/dist/vision/sourceKinds.d.ts +65 -0
  185. package/dist/vision/sourceKinds.d.ts.map +1 -0
  186. package/dist/vision/sourceKinds.js +26 -0
  187. package/dist/vision/sourceKinds.js.map +1 -0
  188. package/dist/vision/startVisionPublisher.d.ts +38 -0
  189. package/dist/vision/startVisionPublisher.d.ts.map +1 -0
  190. package/dist/vision/startVisionPublisher.js +44 -0
  191. package/dist/vision/startVisionPublisher.js.map +1 -0
  192. package/dist/vision/types.d.ts +95 -0
  193. package/dist/vision/types.d.ts.map +1 -0
  194. package/dist/vision/types.js +12 -0
  195. package/dist/vision/types.js.map +1 -0
  196. package/dist/vision/visionScheduler.d.ts +63 -0
  197. package/dist/vision/visionScheduler.d.ts.map +1 -0
  198. package/dist/vision/visionScheduler.js +67 -0
  199. package/dist/vision/visionScheduler.js.map +1 -0
  200. package/dist/websocket.d.ts +195 -0
  201. package/dist/websocket.d.ts.map +1 -1
  202. package/dist/websocket.js +179 -1
  203. package/dist/websocket.js.map +1 -1
  204. package/package.json +11 -1
  205. package/src/__tests__/adapters-capabilities.test.ts +46 -0
  206. package/src/__tests__/adapters-chat.test.ts +172 -0
  207. package/src/__tests__/adapters-director.test.ts +95 -0
  208. package/src/__tests__/adapters-image.test.ts +133 -0
  209. package/src/__tests__/adapters-platform.test.ts +95 -0
  210. package/src/__tests__/adapters-registry.test.ts +189 -0
  211. package/src/__tests__/adapters-world.test.ts +296 -0
  212. package/src/__tests__/admin.test.ts +312 -0
  213. package/src/__tests__/adventures-party.test.ts +219 -0
  214. package/src/__tests__/adventures.test.ts +282 -0
  215. package/src/__tests__/api-pollers.test.ts +104 -0
  216. package/src/__tests__/api.clip-lookup.test.ts +64 -0
  217. package/src/__tests__/api.list-images-filters.test.ts +103 -0
  218. package/src/__tests__/api.test.ts +470 -0
  219. package/src/__tests__/audio.test.ts +65 -0
  220. package/src/__tests__/cast.test.ts +95 -0
  221. package/src/__tests__/castProjection.test.ts +167 -0
  222. package/src/__tests__/chat-auth.test.ts +91 -0
  223. package/src/__tests__/conversation/controller.test.ts +697 -0
  224. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  225. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  226. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  227. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  228. package/src/__tests__/conversation/roster.test.ts +100 -0
  229. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  230. package/src/__tests__/conversation/router.test.ts +81 -0
  231. package/src/__tests__/conversation/runtime.test.ts +206 -0
  232. package/src/__tests__/conversation/voice.test.ts +440 -0
  233. package/src/__tests__/documents.test.ts +360 -0
  234. package/src/__tests__/graphSchema.test.ts +326 -0
  235. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  236. package/src/__tests__/platformAssistant.test.ts +484 -0
  237. package/src/__tests__/reactor/applyScenePrompt.test.ts +192 -0
  238. package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +4 -3
  239. package/src/__tests__/reactor/sceneEntry.test.ts +134 -10
  240. package/src/__tests__/reactor/seedImageOrchestrator.test.ts +51 -16
  241. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  242. package/src/__tests__/regeneration.test.ts +486 -0
  243. package/src/__tests__/stories.test.ts +171 -0
  244. package/src/__tests__/storyGraph.test.ts +134 -0
  245. package/src/__tests__/timeFormat.test.ts +22 -1
  246. package/src/__tests__/toolSchemas.test.ts +57 -0
  247. package/src/__tests__/tools-wrappers.test.ts +272 -0
  248. package/src/__tests__/videoGraph.test.ts +94 -0
  249. package/src/__tests__/websocket-vision.test.ts +265 -0
  250. package/src/__tests__/websocket.test.ts +213 -0
  251. package/src/adapters/capabilities.ts +24 -0
  252. package/src/adapters/chatAdapter.ts +114 -0
  253. package/src/adapters/directorAdapter.ts +126 -0
  254. package/src/adapters/imageAdapter.ts +100 -0
  255. package/src/adapters/index.ts +67 -0
  256. package/src/adapters/registry.ts +159 -0
  257. package/src/adapters/worldAdapter.ts +272 -0
  258. package/src/admin.ts +310 -0
  259. package/src/api.ts +1890 -162
  260. package/src/audio.ts +35 -0
  261. package/src/castProjection.ts +95 -0
  262. package/src/conversation/binding.ts +81 -0
  263. package/src/conversation/controller.ts +439 -0
  264. package/src/conversation/effectiveModel.ts +111 -0
  265. package/src/conversation/index.ts +27 -0
  266. package/src/conversation/participant.ts +71 -0
  267. package/src/conversation/presence.ts +60 -0
  268. package/src/conversation/presenceBus.ts +109 -0
  269. package/src/conversation/presenceRegistry.ts +83 -0
  270. package/src/conversation/roster.ts +111 -0
  271. package/src/conversation/rosterProjection.ts +98 -0
  272. package/src/conversation/router.ts +96 -0
  273. package/src/conversation/runtime.ts +188 -0
  274. package/src/conversation/types.ts +100 -0
  275. package/src/conversation/voice.ts +402 -0
  276. package/src/graphSchema.ts +532 -0
  277. package/src/http.ts +72 -0
  278. package/src/index.ts +12 -0
  279. package/src/platformAssistant.ts +347 -0
  280. package/src/reactor/abortUtils.ts +22 -0
  281. package/src/reactor/applyScenePrompt.ts +136 -0
  282. package/src/reactor/chunkDistribution.ts +98 -0
  283. package/src/reactor/heliosCommandDispatcher.ts +10 -18
  284. package/src/reactor/index.ts +7 -0
  285. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  286. package/src/reactor/sceneEntry.ts +104 -33
  287. package/src/reactor/scenesFromEnrichment.ts +11 -76
  288. package/src/reactor/seedImageOrchestrator.ts +200 -4
  289. package/src/reactor/storyTimeline.ts +127 -0
  290. package/src/storyGraph.ts +298 -0
  291. package/src/timeFormat.ts +13 -0
  292. package/src/toolSchemas.ts +225 -0
  293. package/src/vision/VisionPublisher.ts +553 -0
  294. package/src/vision/VisionSourceController.ts +354 -0
  295. package/src/vision/__tests__/VisionPublisher.kvs.test.ts +244 -0
  296. package/src/vision/__tests__/VisionPublisher.test.ts +301 -0
  297. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  298. package/src/vision/__tests__/startVisionPublisher.test.ts +251 -0
  299. package/src/vision/__tests__/toVisionRtcCredentials.test.ts +113 -0
  300. package/src/vision/__tests__/visionScheduler.test.ts +149 -0
  301. package/src/vision/credentials.ts +39 -0
  302. package/src/vision/index.ts +44 -0
  303. package/src/vision/sourceKinds.ts +75 -0
  304. package/src/vision/startVisionPublisher.ts +64 -0
  305. package/src/vision/types.ts +101 -0
  306. package/src/vision/visionScheduler.ts +102 -0
  307. package/src/websocket.ts +334 -4
@@ -0,0 +1,347 @@
1
+ /**
2
+ * Headless Platform Assistant controller (R4c).
3
+ *
4
+ * The framework-agnostic owner of a Platform Assistant conversation: it holds
5
+ * the running message list + the current `routeContext`, calls
6
+ * `ApiClient.streamAssistant`, parses the returned SSE event stream, and fans
7
+ * the decoded `AssistantStreamEvent` variants out to host-provided callbacks.
8
+ * It has ZERO framework imports — React (R4c web overlay), Vue, and PlayCanvas
9
+ * all drive this same controller (mirrors the R2.1 `ConversationController`
10
+ * decoupling mandate). A test reads this source and asserts no UI-framework
11
+ * import.
12
+ *
13
+ * It does NOT re-implement transport or the SSE wire: it delegates the fetch +
14
+ * body-reader to `ApiClient.streamAssistant` (the single SSE plumbing shared
15
+ * with `streamChat`) and decodes each `data: {…}\n\n` frame exactly the way the
16
+ * existing chat consumer does (TextDecoder streaming + line buffering +
17
+ * `[DONE]` terminator) — no second decoder.
18
+ *
19
+ * It performs NO mutation: a `suggestion` event is surfaced verbatim to
20
+ * `onSuggestion`; the HOST page that owns the form decides whether to apply it.
21
+ */
22
+
23
+ import type {
24
+ ApiClient,
25
+ AssistantRouteContext,
26
+ AssistantStreamEvent,
27
+ ChatMessage,
28
+ } from './api';
29
+
30
+ /** Conversation roles the assistant history carries (derived from the single
31
+ * source of truth — `ChatMessage['role']` — so it cannot drift). */
32
+ type AssistantMessageRole = ChatMessage['role'];
33
+
34
+ /**
35
+ * A `propose_form_fields` suggestion surfaced to the host. Mirrors the
36
+ * `suggestion` variant of `AssistantStreamEvent` (the wire contract shared with
37
+ * `api/assistant`), re-exported as a named type so the host overlay imports it
38
+ * verbatim rather than re-deriving the `Extract<…>`.
39
+ */
40
+ export interface PlatformAssistantSuggestion {
41
+ /** The target form id the proposed fields belong to (e.g. `persona`). */
42
+ targetForm: string;
43
+ /** The proposed `{ fieldName: value }` map the host reviews + applies. */
44
+ fields: Record<string, string>;
45
+ /** Optional human-readable rationale for the proposal. */
46
+ rationale?: string;
47
+ }
48
+
49
+ /**
50
+ * Host callbacks the controller invokes as the corresponding
51
+ * `AssistantStreamEvent` variants arrive. All optional — a host wires only the
52
+ * variants it renders. `token` -> onTextDelta, `suggestion` -> onSuggestion,
53
+ * `error` -> onError, `done` -> onDone. The `tool_use` / `tool_result` /
54
+ * `citation` variants are intentionally not surfaced (minimal assistant
55
+ * surface); a future PR can add callbacks for them additively.
56
+ */
57
+ export interface PlatformAssistantCallbacks {
58
+ /** A streamed answer token (append to the in-flight assistant message). */
59
+ onTextDelta?: (text: string) => void;
60
+ /** A `propose_form_fields` suggestion the host maps onto its own form. */
61
+ onSuggestion?: (suggestion: PlatformAssistantSuggestion) => void;
62
+ /** A streamed error message (the turn failed server-side). */
63
+ onError?: (message: string) => void;
64
+ /**
65
+ * The turn ended. Fires once whenever the stream CLOSES — a `done`/`[DONE]`
66
+ * terminator, a self-abort, OR the connection simply dropping. So for a
67
+ * server-side SSE `error` frame, BOTH onError and onDone fire (error surfaced,
68
+ * then the stream closed); for a TRANSPORT error (the request itself throws)
69
+ * only onError fires. Treat onDone as "stop showing the spinner", not "success".
70
+ */
71
+ onDone?: () => void;
72
+ }
73
+
74
+ export interface PlatformAssistantControllerOptions {
75
+ /** The client-core API client whose `streamAssistant` the controller drives. */
76
+ apiClient: Pick<ApiClient, 'streamAssistant'>;
77
+ /** The route the assistant is summoned on (scopes its suggestions). */
78
+ routeContext: AssistantRouteContext;
79
+ /** Host callbacks for the streamed events. */
80
+ callbacks: PlatformAssistantCallbacks;
81
+ /**
82
+ * Optional explicit model pin. Omitted = the server resolves the model via
83
+ * the same `resolve_model_id` -> `shared/model_router.py` seam the chat uses.
84
+ */
85
+ modelId?: string;
86
+ }
87
+
88
+ /**
89
+ * Per-turn options for {@link PlatformAssistantController.ask} (R11.2). Optional
90
+ * + additive — `ask(prompt)` is unchanged. `documentContext` carries a large
91
+ * "operate on this document" draft (e.g. a long prompt to refine) that the
92
+ * server places in MODEL CONTEXT, never the user turn, so the small `prompt`
93
+ * cap keeps its prompt-injection floor.
94
+ */
95
+ export interface PlatformAssistantAskOptions {
96
+ /** A large document/draft for the assistant to operate ON (model context). */
97
+ documentContext?: string;
98
+ }
99
+
100
+ const ROLE_USER: AssistantMessageRole = 'user';
101
+ const ROLE_ASSISTANT: AssistantMessageRole = 'assistant';
102
+
103
+ /** SSE `data:` line prefix + the stream terminator sentinel. */
104
+ const SSE_DATA_PREFIX = 'data: ';
105
+ const SSE_DONE_SENTINEL = '[DONE]';
106
+
107
+ export class PlatformAssistantController {
108
+ private readonly apiClient: Pick<ApiClient, 'streamAssistant'>;
109
+ private readonly callbacks: PlatformAssistantCallbacks;
110
+ private readonly modelId?: string;
111
+ private routeContext: AssistantRouteContext;
112
+ /** The running conversation history threaded into each `ask`. */
113
+ private messages: ChatMessage[] = [];
114
+ /** Abort controller for the in-flight `ask` stream (so `abort()` cancels it). */
115
+ private inflight: AbortController | undefined;
116
+ /** Set by `dispose()` — guards against driving a new stream after teardown. */
117
+ private disposed = false;
118
+
119
+ constructor(opts: PlatformAssistantControllerOptions) {
120
+ this.apiClient = opts.apiClient;
121
+ this.routeContext = opts.routeContext;
122
+ this.callbacks = opts.callbacks;
123
+ this.modelId = opts.modelId;
124
+ }
125
+
126
+ /** Point the assistant at a new surface/form (the host re-binds on navigation). */
127
+ setRouteContext(routeContext: AssistantRouteContext): void {
128
+ this.routeContext = routeContext;
129
+ }
130
+
131
+ /** A defensive copy of the running message history (host-render convenience). */
132
+ getMessages(): ChatMessage[] {
133
+ return this.messages.map((m) => ({ ...m }));
134
+ }
135
+
136
+ /**
137
+ * Send a user prompt: append it to the history, stream the assistant reply
138
+ * via `ApiClient.streamAssistant` (threading the running history + the current
139
+ * `routeContext`), and fan the decoded events out to the host callbacks. The
140
+ * accumulated assistant text is appended to the history on completion so the
141
+ * NEXT `ask` carries the full transcript.
142
+ *
143
+ * Resolves when the stream completes (or aborts). A single `ask` is allowed
144
+ * in flight at a time — calling `ask` again before the previous resolves
145
+ * aborts the prior stream first (so only one stream owns the callbacks).
146
+ *
147
+ * NEVER rejects: a transport/network error is surfaced via the `onError`
148
+ * callback (the same channel as SSE `error` frames) and a self-abort resolves
149
+ * silently — so framework-agnostic callers need not wrap `ask` in try/catch.
150
+ *
151
+ * `options.documentContext` (R11.2, optional) threads a large draft into the
152
+ * request's `documentContext` field — the server places it in model context,
153
+ * not the user turn. Omitted ⇒ the request carries no `documentContext`
154
+ * (byte-identical to the pre-R11.2 wire payload).
155
+ */
156
+ async ask(prompt: string, options?: PlatformAssistantAskOptions): Promise<void> {
157
+ if (this.disposed) {
158
+ // Disposed is NOT thrown — honor the "never rejects" contract (a
159
+ // navigation may dispose() while a queued ask() is still pending). Surface
160
+ // it through onError so a framework-agnostic caller need not try/catch.
161
+ this.callbacks.onError?.('PlatformAssistantController: ask() after dispose().');
162
+ return;
163
+ }
164
+ // Abort any prior in-flight stream so only one stream drives the callbacks.
165
+ this.abort();
166
+
167
+ // The prior COMMITTED history threads into the request. The new user turn is
168
+ // NOT pushed yet — it commits (paired with the assistant reply) only once the
169
+ // stream produces a reply (see the finally), so a re-entrant ask() that
170
+ // aborts this one before any reply never leaves a dangling user turn.
171
+ const priorMessages = this.getMessages();
172
+
173
+ const abortController = new AbortController();
174
+ this.inflight = abortController;
175
+
176
+ let assistantText = '';
177
+ try {
178
+ const reader = await this.apiClient.streamAssistant(
179
+ {
180
+ prompt,
181
+ messages: priorMessages,
182
+ routeContext: this.routeContext,
183
+ ...(this.modelId ? { modelId: this.modelId } : {}),
184
+ // R11.2 — only include documentContext when a non-empty draft is
185
+ // supplied, so a plain ask() emits a wire payload byte-identical to
186
+ // the pre-R11.2 one (no `documentContext` key at all).
187
+ ...(options?.documentContext
188
+ ? { documentContext: options.documentContext }
189
+ : {}),
190
+ },
191
+ abortController.signal,
192
+ );
193
+ assistantText = await this.consume(reader);
194
+ } catch (err) {
195
+ // A self-abort (a re-entrant ask(), dispose(), or an explicit abort() —
196
+ // e.g. a future Cancel button) is a clean cancel, NOT an error: fire onDone
197
+ // so the turn ends and a host relying on it to flip "streaming" off isn't
198
+ // left stuck (when the reader THROWS AbortError, the terminal onDone below
199
+ // is skipped). Any other error (transport/network) surfaces through onError
200
+ // — the SAME channel SSE `error` frames use, so a consumer has ONE error
201
+ // channel and ask() NEVER rejects (the framework-agnostic seam: a
202
+ // Vue/PlayCanvas caller need not wrap ask() in try/catch).
203
+ if (err instanceof Error && err.name === 'AbortError') {
204
+ this.callbacks.onDone?.();
205
+ } else {
206
+ this.callbacks.onError?.(err instanceof Error ? err.message : String(err));
207
+ }
208
+ } finally {
209
+ // Commit the user turn + the assistant reply as a PAIR — but only if the
210
+ // turn produced a reply (a completed or partially-streamed one). An
211
+ // immediately self-aborted turn (empty reply) commits NOTHING, so a
212
+ // re-entrant ask() never leaves a dangling user turn with no assistant
213
+ // response. Then clear the in-flight handle if it is still ours.
214
+ if (assistantText) {
215
+ this.messages.push({ role: ROLE_USER, content: prompt });
216
+ this.messages.push({ role: ROLE_ASSISTANT, content: assistantText });
217
+ }
218
+ if (this.inflight === abortController) {
219
+ this.inflight = undefined;
220
+ }
221
+ }
222
+ }
223
+
224
+ /** Abort the in-flight stream (no-op when nothing is streaming). */
225
+ abort(): void {
226
+ this.inflight?.abort();
227
+ this.inflight = undefined;
228
+ }
229
+
230
+ /** Tear down: abort any in-flight stream and reject further `ask` calls. */
231
+ dispose(): void {
232
+ this.disposed = true;
233
+ this.abort();
234
+ this.messages = [];
235
+ }
236
+
237
+ // ── internals ──────────────────────────────────────────────────────────────
238
+
239
+ /**
240
+ * Drain the SSE reader, decoding each `data: {…}\n\n` frame into an
241
+ * `AssistantStreamEvent` and dispatching it to the host callbacks. Returns the
242
+ * concatenated `token` text so the caller can persist the assistant turn.
243
+ *
244
+ * Reuses the EXACT decode discipline the web chat consumer uses (TextDecoder
245
+ * with `{ stream: true }`, line buffering with a trailing-partial carry-over,
246
+ * `data: ` prefix slice, `[DONE]` terminator) — no second SSE decoder.
247
+ */
248
+ private async consume(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<string> {
249
+ const decoder = new TextDecoder();
250
+ let buffer = '';
251
+ let text = '';
252
+
253
+ try {
254
+ for (;;) {
255
+ const { done, value } = await reader.read();
256
+ if (done) break;
257
+ if (value) buffer += decoder.decode(value, { stream: true });
258
+
259
+ const lines = buffer.split('\n');
260
+ // Keep the trailing partial line in the buffer until its newline arrives.
261
+ buffer = lines.pop() ?? '';
262
+
263
+ // We never break on `done` (the reader closes right after) — the terminal
264
+ // onDone after the loop covers every exit path.
265
+ for (const line of lines) text += this.handleLine(line);
266
+ }
267
+
268
+ // Flush the streaming decoder's buffered multi-byte tail, then process any
269
+ // final UNTERMINATED frame left in the buffer. Well-formed SSE ends with
270
+ // `\n\n` so the buffer is normally empty here — but a server that closes
271
+ // mid-frame without a trailing newline would otherwise drop its last token,
272
+ // and a multi-byte char split across the final chunk would be corrupted.
273
+ buffer += decoder.decode();
274
+ if (buffer) text += this.handleLine(buffer);
275
+
276
+ // The reader closing IS the completion signal — fire `onDone` once here
277
+ // regardless of whether a `done` event / `[DONE]` sentinel arrived. A server
278
+ // that closes the connection mid-stream (crash, network drop, Lambda
279
+ // timeout) sends neither, but the turn IS over, so a host relying on `onDone`
280
+ // to flip "streaming" off must still get it (otherwise the UI sticks).
281
+ this.callbacks.onDone?.();
282
+ return text;
283
+ } finally {
284
+ // Release the response-body reader lock on EVERY exit path (normal close OR
285
+ // a thrown AbortError caught by ask()). The abort signal already tears the
286
+ // fetch down, but releasing explicitly is correct stream hygiene. Optional-
287
+ // chained so a hand-rolled reader mock (tests) without releaseLock no-ops.
288
+ reader.releaseLock?.();
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Decode one buffered SSE line into an `AssistantStreamEvent`, dispatch it to
294
+ * the host callbacks, and return the `token` text the line contributed (empty
295
+ * for a non-token frame, the `[DONE]` sentinel, a non-`data:` line, or a
296
+ * malformed frame — a single bad line is SKIPPED, never aborting the stream).
297
+ *
298
+ * The single line-parse path shared by the streaming loop and the final-buffer
299
+ * flush in `consume`, so the loop and the close-time tail can never decode a
300
+ * frame differently.
301
+ */
302
+ private handleLine(line: string): string {
303
+ if (!line.startsWith(SSE_DATA_PREFIX)) return '';
304
+ const data = line.slice(SSE_DATA_PREFIX.length);
305
+ if (data === SSE_DONE_SENTINEL) return '';
306
+ let event: AssistantStreamEvent;
307
+ try {
308
+ event = JSON.parse(data) as AssistantStreamEvent;
309
+ } catch {
310
+ return '';
311
+ }
312
+ this.dispatch(event);
313
+ return event.type === 'token' ? event.content : '';
314
+ }
315
+
316
+ /**
317
+ * Dispatch one decoded event to the matching host callback. `done` needs no
318
+ * handling here — `consume` fires `onDone` once when the reader closes (the
319
+ * close is the completion signal). `tool_use` / `tool_result` / `citation` are
320
+ * intentionally ignored (minimal surface).
321
+ */
322
+ private dispatch(event: AssistantStreamEvent): void {
323
+ switch (event.type) {
324
+ case 'token':
325
+ this.callbacks.onTextDelta?.(event.content);
326
+ return;
327
+ case 'suggestion':
328
+ this.callbacks.onSuggestion?.({
329
+ targetForm: event.targetForm,
330
+ // String-coerce each value: the event is a `JSON.parse` cast with no
331
+ // runtime guarantee, and an LLM may emit a non-string (e.g. a number)
332
+ // — the host expects `Record<string, string>`, so normalize here.
333
+ fields: Object.fromEntries(
334
+ Object.entries(event.fields ?? {}).map(([k, v]) => [k, String(v)]),
335
+ ),
336
+ ...(event.rationale !== undefined ? { rationale: event.rationale } : {}),
337
+ });
338
+ return;
339
+ case 'error':
340
+ this.callbacks.onError?.(event.message);
341
+ return;
342
+ default:
343
+ // done / tool_use / tool_result / citation — no per-event handling.
344
+ return;
345
+ }
346
+ }
347
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Shared abort-detection helper for the reactor submodule. Three call
3
+ * sites used to carry their own copy of this 6-liner — drift between
4
+ * them would silently change cancellation semantics (an abort being
5
+ * mistaken for a real error logs noise; a real error being mistaken
6
+ * for an abort silently swallows it), so we consolidate here.
7
+ *
8
+ * Accepts both `DOMException { name: 'AbortError' }` (native `fetch`
9
+ * + browser `AbortController`) and plain `Error { name: 'AbortError'
10
+ * }` (some polyfills, the project's own pollers). Also accepts
11
+ * `Error { code: 'ABORT_ERR' }` which some libraries use as their
12
+ * abort signal shape. Keep the union broad so a future polyfill or
13
+ * SSR runtime swap doesn't silently break cancellation handling.
14
+ */
15
+ export function isAbortError(err: unknown): boolean {
16
+ if (err instanceof DOMException && err.name === 'AbortError') return true;
17
+ if (err instanceof Error) {
18
+ if (err.name === 'AbortError') return true;
19
+ if ((err as Error & { code?: string }).code === 'ABORT_ERR') return true;
20
+ }
21
+ return false;
22
+ }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Submit a user-authored or model-authored scene prompt to a live
3
+ * Reactor session. Encapsulates the chunk-0-vs-running policy that
4
+ * previously lived inline in `InteractiveController.handleSubmit` and
5
+ * has now been extracted so the watch-page `HeliosWorldControls`
6
+ * reuses the same logic without duplication.
7
+ *
8
+ * `dispatchHeliosCommand.handleSetScene` (the chat-tool driver) does
9
+ * NOT call into this helper — it keeps its own copy because it needs
10
+ * a distinct `hasStarted` guard for the chat flow (see the comment
11
+ * at the top of `heliosCommandDispatcher.ts::handleSetScene`).
12
+ *
13
+ * Framework-agnostic — no React, no DOM beyond what Reactor's bridge
14
+ * surface already accepts. Errors propagate (unlike `dispatchHelios-
15
+ * Command`, which swallows them to keep the chat loop alive). UI
16
+ * consumers can wrap the call in try/catch to surface a banner.
17
+ *
18
+ * Upsample policy is identical to the prior inline implementation:
19
+ * a non-abort failure logs a warning and falls back to the raw prompt
20
+ * (`buildUpsamplePrompt` is best-effort grounding, not a hard
21
+ * dependency). Abort errors are re-thrown so callers stop awaiting.
22
+ */
23
+
24
+ import type { ApiClient } from '../api';
25
+ import { isAbortError } from './abortUtils';
26
+ import type { EntityContext, PersonaContext } from './types';
27
+
28
+ /** Minimal Reactor surface this helper needs. `applyScenePrompt` only
29
+ * ever issues `set_prompt`, `start`, and `schedule_prompt` — it never
30
+ * uploads a file. Kept narrow so callers don't have to thread an
31
+ * unused `uploadFile` reference; the broader `HeliosReactorBridge`
32
+ * (which adds `uploadFile`) is for the swap-seed / set-image paths. */
33
+ export interface ApplyScenePromptReactorBridge {
34
+ sendCommand: (command: string, data: unknown) => Promise<void>;
35
+ }
36
+
37
+ export interface ApplyScenePromptInput {
38
+ /** The prompt to apply. May be raw user text or a model-emitted
39
+ * Helios-shaped prompt; either way the upsampler is run as a
40
+ * grounding pass and its output (or the raw prompt on failure) is
41
+ * forwarded to Reactor. */
42
+ prompt: string;
43
+ apiClient: ApiClient;
44
+ reactor: ApplyScenePromptReactorBridge;
45
+ /** Live `current_chunk` from Reactor's `state` messages. */
46
+ currentChunk: number;
47
+ /** Whether the world is currently running (Reactor model state
48
+ * `current_frame > 0`). When false, this is the first prompt and
49
+ * we issue `set_prompt` + `start`. When true, we issue
50
+ * `schedule_prompt` at `currentChunk + 2` (the two-chunk lead is
51
+ * what Helios accepts mid-stream). */
52
+ isRunning: boolean;
53
+ /** Optional context plumbed into the upsampler. */
54
+ imageId?: string;
55
+ entityContext?: EntityContext;
56
+ personaContext?: PersonaContext;
57
+ /** Previous prompt for the upsampler's narrative-continuity heuristic. */
58
+ previousPrompt?: string;
59
+ /** When false, skip the upsample call and forward `prompt` to Reactor
60
+ * verbatim. Defaults to `true` so existing callers keep their current
61
+ * behavior. UIs that surface a user-facing upsample toggle (and run
62
+ * the upsample preview separately via `apiClient.upsampleReactorPrompt`
63
+ * to populate an editable textarea) should pass `false` on the
64
+ * send-step so the operator's exact text reaches Helios. */
65
+ shouldUpsample?: boolean;
66
+ signal?: AbortSignal;
67
+ }
68
+
69
+ export interface ApplyScenePromptResult {
70
+ /** The prompt actually sent to Reactor — either the upsampler's
71
+ * output or the raw input when upsample failed. */
72
+ appliedPrompt: string;
73
+ /** When non-null, the chunk index Helios will activate the prompt at
74
+ * (`schedule_prompt`). When null, the prompt was set via
75
+ * `set_prompt` and `start` was issued — this was the first prompt
76
+ * for the session. */
77
+ scheduledAtChunk: number | null;
78
+ }
79
+
80
+ export async function applyScenePrompt(
81
+ input: ApplyScenePromptInput,
82
+ ): Promise<ApplyScenePromptResult> {
83
+ const {
84
+ prompt: rawPrompt,
85
+ apiClient,
86
+ reactor,
87
+ currentChunk,
88
+ isRunning,
89
+ imageId,
90
+ entityContext,
91
+ personaContext,
92
+ previousPrompt,
93
+ shouldUpsample = true,
94
+ signal,
95
+ } = input;
96
+
97
+ let prompt = rawPrompt;
98
+ if (shouldUpsample) {
99
+ try {
100
+ const res = await apiClient.upsampleReactorPrompt(
101
+ {
102
+ prompt: rawPrompt,
103
+ ...(previousPrompt ? { previousPrompt } : {}),
104
+ ...(imageId ? { imageId } : {}),
105
+ ...(entityContext ? { entityContext } : {}),
106
+ ...(personaContext ? { personaContext } : {}),
107
+ },
108
+ { signal },
109
+ );
110
+ if (res?.upsampledPrompt) prompt = res.upsampledPrompt;
111
+ } catch (err) {
112
+ if (isAbortError(err)) throw err;
113
+ console.warn(
114
+ '[applyScenePrompt] upsample failed; falling back to raw prompt',
115
+ err,
116
+ );
117
+ }
118
+ }
119
+
120
+ if (signal?.aborted) {
121
+ throw new DOMException('Aborted', 'AbortError');
122
+ }
123
+
124
+ if (!isRunning) {
125
+ await reactor.sendCommand('set_prompt', { prompt });
126
+ await reactor.sendCommand('start', {});
127
+ return { appliedPrompt: prompt, scheduledAtChunk: null };
128
+ }
129
+
130
+ const targetChunk = currentChunk + 2;
131
+ await reactor.sendCommand('schedule_prompt', {
132
+ prompt,
133
+ chunk: targetChunk,
134
+ });
135
+ return { appliedPrompt: prompt, scheduledAtChunk: targetChunk };
136
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * chunkDistribution — the shared chunk-index distribution + minimum-spacing
3
+ * rules used by BOTH timeline mappers (`mapEnrichmentToTimeline` over raw
4
+ * Pegasus enrichment, and `deriveStoryTimeline` over the R5 story projection).
5
+ *
6
+ * Extracted in R8.1 so the two mappers share ONE distribution algorithm — a
7
+ * second copy could drift the chunk math silently (CLAUDE.md DRY). The rules
8
+ * are documented on `scenesFromEnrichment.ts` and unit-tested via both mappers.
9
+ *
10
+ * The helpers operate on the minimal {@link TimedItem} timing shape so any
11
+ * caller (raw scene, story scene) can reuse them without a shared scene type.
12
+ */
13
+
14
+ /** Shared default chunk budget (Helios prototype: ~33 fpc, 30 chunks ≈ 16s). */
15
+ export const DEFAULT_MAX_CHUNKS = 30;
16
+ /** Shared default minimum chunk gap between consecutive kept beats. */
17
+ export const DEFAULT_MIN_CHUNK_SPACING = 2;
18
+
19
+ /** The minimal timing shape the distribution rules read. */
20
+ export interface TimedItem {
21
+ start?: number;
22
+ end?: number;
23
+ }
24
+
25
+ /**
26
+ * Compute one chunk index per item.
27
+ *
28
+ * If every item carries numeric `start`/`end` with a positive total span, the
29
+ * chunk index is scaled proportionally from each item's start across
30
+ * `[0, maxChunks)` (first item pinned to chunk 0, clamped to `maxChunks - 1`).
31
+ * Otherwise distribute evenly across `[0, maxChunks)` (first at 0, last at
32
+ * `maxChunks - 1`, linear spacing between).
33
+ */
34
+ export function computeChunkIndices(items: readonly TimedItem[], maxChunks: number): number[] {
35
+ if (items.length === 0) return [];
36
+ if (items.length === 1) return [0];
37
+
38
+ const allTimed = items.every(
39
+ (s) => typeof s.start === 'number' && typeof s.end === 'number',
40
+ );
41
+
42
+ // If timings are present and meaningful (positive span), scale.
43
+ if (allTimed) {
44
+ const starts = items.map((s) => s.start as number);
45
+ const ends = items.map((s) => s.end as number);
46
+ const minStart = Math.min(...starts);
47
+ const maxEnd = Math.max(...ends);
48
+ const span = maxEnd - minStart;
49
+ if (span > 0) {
50
+ return items.map((s, i) => {
51
+ if (i === 0) return 0;
52
+ const start = s.start as number;
53
+ const frac = (start - minStart) / span;
54
+ const chunk = Math.round(frac * (maxChunks - 1));
55
+ // Clamp into [0, maxChunks - 1].
56
+ return Math.max(0, Math.min(maxChunks - 1, chunk));
57
+ });
58
+ }
59
+ }
60
+
61
+ // Fallback — even distribution. First item at 0, last item at
62
+ // maxChunks - 1, with linear spacing between.
63
+ return items.map((_, i) => {
64
+ if (i === 0) return 0;
65
+ const frac = i / (items.length - 1);
66
+ return Math.round(frac * (maxChunks - 1));
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Apply `minSpacing`. Walks in order, always keeps the first item (forced to
72
+ * chunk 0), drops any item whose chunk is closer than `minSpacing` to the
73
+ * previously-kept item. Returns the kept items paired with their final chunk
74
+ * and original index.
75
+ */
76
+ export function enforceSpacing<T extends TimedItem>(
77
+ items: readonly T[],
78
+ chunks: readonly number[],
79
+ minSpacing: number,
80
+ ): { item: T; chunk: number; index: number }[] {
81
+ const kept: { item: T; chunk: number; index: number }[] = [];
82
+ for (let i = 0; i < items.length; i++) {
83
+ const item = items[i];
84
+ let chunk = chunks[i];
85
+ if (kept.length === 0) {
86
+ // First item is always pinned to chunk 0.
87
+ chunk = 0;
88
+ kept.push({ item, chunk, index: i });
89
+ continue;
90
+ }
91
+ const prev = kept[kept.length - 1].chunk;
92
+ if (chunk - prev < minSpacing) {
93
+ continue;
94
+ }
95
+ kept.push({ item, chunk, index: i });
96
+ }
97
+ return kept;
98
+ }
@@ -15,6 +15,7 @@
15
15
  */
16
16
 
17
17
  import type { ApiClient, ImageRecord } from '../api';
18
+ import { isAbortError } from './abortUtils';
18
19
  import { findEntityImageBySeedName } from './entitySearch';
19
20
  import type { HeliosCommand } from './heliosTools';
20
21
  import {
@@ -94,23 +95,6 @@ export interface HeliosToolContext {
94
95
  signal?: AbortSignal;
95
96
  }
96
97
 
97
- /**
98
- * Dispatch a single `HeliosCommand` to the live Reactor session.
99
- * Resolves with no value on both success and failure — the caller
100
- * just awaits the dispatch and continues to the next command.
101
- */
102
- /** True when `err` is an `AbortError` (or carries that name). Browsers
103
- * emit `DOMException('AbortError')`; fetch + apiClient already pass
104
- * this through unchanged. The `code === 'ABORT_ERR'` branch covers
105
- * custom error classes some libraries use; the `name` check handles
106
- * every browser DOMException + standard polyfill. */
107
- function isAbortError(err: unknown): boolean {
108
- return (
109
- err instanceof Error &&
110
- (err.name === 'AbortError' || (err as Error & { code?: string }).code === 'ABORT_ERR')
111
- );
112
- }
113
-
114
98
  /**
115
99
  * Dispatch a single `HeliosCommand` to the live Reactor session.
116
100
  * Resolves with no value on both success and failure — the caller
@@ -170,13 +154,21 @@ export async function dispatchHeliosCommand(
170
154
  /**
171
155
  * SET_SCENE: knowledge-grounded upsample then a prompt change.
172
156
  *
173
- * Mirrors `InteractiveController.handleSubmit`:
157
+ * Mirrors `InteractiveController.handleSubmit` and
158
+ * `applyScenePrompt` (the shared helper used by the React controls):
174
159
  * - chunk 0 (no frames rendered yet) → `set_prompt`
175
160
  * - mid-stream → `schedule_prompt` at `currentChunk + 2`
176
161
  *
177
162
  * Upsample failure falls back to the raw model-emitted prompt rather
178
163
  * than aborting — the model is already doing the Helios prompt-guide
179
164
  * shaping; upsample just adds knowledge-graph grounding.
165
+ *
166
+ * Not implemented in terms of `applyScenePrompt` because the chat-tool
167
+ * path has a distinct `hasStarted` guard: when SET_SCENE fires at
168
+ * chunk 0 against an already-running world, we skip the `start`
169
+ * re-emit. `applyScenePrompt`'s UI callers track running via
170
+ * `current_frame > 0` instead, which is authoritative for the
171
+ * operator-driven flow.
180
172
  */
181
173
  async function handleSetScene(
182
174
  modelPrompt: string,
@@ -8,10 +8,17 @@ export * from './regenTemplate';
8
8
  export * from './upsamplePrompt';
9
9
  export * from './entityContext';
10
10
  export * from './scenesFromEnrichment';
11
+ // R8.1 — story-graph-driven timeline mapper (sibling of scenesFromEnrichment).
12
+ // The shared chunk-distribution helpers in `./chunkDistribution` stay internal
13
+ // (imported by both mappers); they are deliberately NOT re-exported here.
14
+ export * from './storyTimeline';
11
15
  export * from './heliosTools';
12
16
  export * from './toolPromptAddon';
13
17
  export * from './entitySearch';
14
18
  export * from './heliosCommandDispatcher';
19
+ export * from './longLiveCommandDispatcher';
15
20
  export * from './seedImageOrchestrator';
16
21
  export * from './promptAddonRegistry';
17
22
  export * from './sceneEntry';
23
+ export * from './applyScenePrompt';
24
+ export * from './abortUtils';