@escapeaihq/client-core 0.12.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 (239) hide show
  1. package/README.md +31 -6
  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 +1185 -3
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +624 -51
  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 +201 -13
  103. package/dist/graphSchema.d.ts.map +1 -1
  104. package/dist/graphSchema.js +258 -9
  105. package/dist/graphSchema.js.map +1 -1
  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 +6 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +9 -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/chunkDistribution.d.ts +43 -0
  119. package/dist/reactor/chunkDistribution.d.ts.map +1 -0
  120. package/dist/reactor/chunkDistribution.js +85 -0
  121. package/dist/reactor/chunkDistribution.js.map +1 -0
  122. package/dist/reactor/index.d.ts +2 -0
  123. package/dist/reactor/index.d.ts.map +1 -1
  124. package/dist/reactor/index.js +5 -0
  125. package/dist/reactor/index.js.map +1 -1
  126. package/dist/reactor/longLiveCommandDispatcher.d.ts +103 -0
  127. package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -0
  128. package/dist/reactor/longLiveCommandDispatcher.js +87 -0
  129. package/dist/reactor/longLiveCommandDispatcher.js.map +1 -0
  130. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -1
  131. package/dist/reactor/scenesFromEnrichment.js +2 -66
  132. package/dist/reactor/scenesFromEnrichment.js.map +1 -1
  133. package/dist/reactor/seedImageOrchestrator.d.ts +6 -9
  134. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  135. package/dist/reactor/seedImageOrchestrator.js +12 -13
  136. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  137. package/dist/reactor/storyTimeline.d.ts +44 -0
  138. package/dist/reactor/storyTimeline.d.ts.map +1 -0
  139. package/dist/reactor/storyTimeline.js +95 -0
  140. package/dist/reactor/storyTimeline.js.map +1 -0
  141. package/dist/storyGraph.d.ts +70 -0
  142. package/dist/storyGraph.d.ts.map +1 -0
  143. package/dist/storyGraph.js +178 -0
  144. package/dist/storyGraph.js.map +1 -0
  145. package/dist/vision/VisionSourceController.d.ts +127 -0
  146. package/dist/vision/VisionSourceController.d.ts.map +1 -0
  147. package/dist/vision/VisionSourceController.js +284 -0
  148. package/dist/vision/VisionSourceController.js.map +1 -0
  149. package/dist/vision/index.d.ts +4 -0
  150. package/dist/vision/index.d.ts.map +1 -1
  151. package/dist/vision/index.js +2 -0
  152. package/dist/vision/index.js.map +1 -1
  153. package/dist/vision/sourceKinds.d.ts +65 -0
  154. package/dist/vision/sourceKinds.d.ts.map +1 -0
  155. package/dist/vision/sourceKinds.js +26 -0
  156. package/dist/vision/sourceKinds.js.map +1 -0
  157. package/dist/websocket.d.ts +73 -0
  158. package/dist/websocket.d.ts.map +1 -1
  159. package/dist/websocket.js.map +1 -1
  160. package/package.json +1 -1
  161. package/src/__tests__/adapters-capabilities.test.ts +46 -0
  162. package/src/__tests__/adapters-chat.test.ts +172 -0
  163. package/src/__tests__/adapters-director.test.ts +95 -0
  164. package/src/__tests__/adapters-image.test.ts +133 -0
  165. package/src/__tests__/adapters-platform.test.ts +95 -0
  166. package/src/__tests__/adapters-registry.test.ts +189 -0
  167. package/src/__tests__/adapters-world.test.ts +296 -0
  168. package/src/__tests__/admin.test.ts +312 -0
  169. package/src/__tests__/adventures-party.test.ts +219 -0
  170. package/src/__tests__/adventures.test.ts +282 -0
  171. package/src/__tests__/api-pollers.test.ts +4 -0
  172. package/src/__tests__/api.clip-lookup.test.ts +64 -0
  173. package/src/__tests__/api.list-images-filters.test.ts +103 -0
  174. package/src/__tests__/api.test.ts +470 -0
  175. package/src/__tests__/audio.test.ts +65 -0
  176. package/src/__tests__/cast.test.ts +95 -0
  177. package/src/__tests__/castProjection.test.ts +167 -0
  178. package/src/__tests__/conversation/controller.test.ts +697 -0
  179. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  180. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  181. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  182. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  183. package/src/__tests__/conversation/roster.test.ts +100 -0
  184. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  185. package/src/__tests__/conversation/router.test.ts +81 -0
  186. package/src/__tests__/conversation/runtime.test.ts +206 -0
  187. package/src/__tests__/conversation/voice.test.ts +440 -0
  188. package/src/__tests__/documents.test.ts +360 -0
  189. package/src/__tests__/graphSchema.test.ts +218 -9
  190. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  191. package/src/__tests__/platformAssistant.test.ts +484 -0
  192. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  193. package/src/__tests__/regeneration.test.ts +486 -0
  194. package/src/__tests__/stories.test.ts +171 -0
  195. package/src/__tests__/storyGraph.test.ts +134 -0
  196. package/src/__tests__/tools-wrappers.test.ts +272 -0
  197. package/src/__tests__/videoGraph.test.ts +94 -0
  198. package/src/__tests__/websocket.test.ts +213 -0
  199. package/src/adapters/capabilities.ts +24 -0
  200. package/src/adapters/chatAdapter.ts +114 -0
  201. package/src/adapters/directorAdapter.ts +126 -0
  202. package/src/adapters/imageAdapter.ts +100 -0
  203. package/src/adapters/index.ts +67 -0
  204. package/src/adapters/registry.ts +159 -0
  205. package/src/adapters/worldAdapter.ts +272 -0
  206. package/src/admin.ts +310 -0
  207. package/src/api.ts +1731 -116
  208. package/src/audio.ts +35 -0
  209. package/src/castProjection.ts +95 -0
  210. package/src/conversation/binding.ts +81 -0
  211. package/src/conversation/controller.ts +439 -0
  212. package/src/conversation/effectiveModel.ts +111 -0
  213. package/src/conversation/index.ts +27 -0
  214. package/src/conversation/participant.ts +71 -0
  215. package/src/conversation/presence.ts +60 -0
  216. package/src/conversation/presenceBus.ts +109 -0
  217. package/src/conversation/presenceRegistry.ts +83 -0
  218. package/src/conversation/roster.ts +111 -0
  219. package/src/conversation/rosterProjection.ts +98 -0
  220. package/src/conversation/router.ts +96 -0
  221. package/src/conversation/runtime.ts +188 -0
  222. package/src/conversation/types.ts +100 -0
  223. package/src/conversation/voice.ts +402 -0
  224. package/src/graphSchema.ts +396 -13
  225. package/src/http.ts +72 -0
  226. package/src/index.ts +9 -0
  227. package/src/platformAssistant.ts +347 -0
  228. package/src/reactor/chunkDistribution.ts +98 -0
  229. package/src/reactor/index.ts +5 -0
  230. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  231. package/src/reactor/scenesFromEnrichment.ts +11 -76
  232. package/src/reactor/seedImageOrchestrator.ts +12 -13
  233. package/src/reactor/storyTimeline.ts +127 -0
  234. package/src/storyGraph.ts +298 -0
  235. package/src/vision/VisionSourceController.ts +354 -0
  236. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  237. package/src/vision/index.ts +13 -0
  238. package/src/vision/sourceKinds.ts +75 -0
  239. package/src/websocket.ts +75 -3
@@ -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,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
+ }
@@ -8,10 +8,15 @@ 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';
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Translate parsed LongLive-v2 commands into `reactor.sendCommand` calls.
3
+ *
4
+ * The {@link dispatchHeliosCommand} analogue for the Reactor LongLive-v2
5
+ * world model. SAME Reactor transport (JWT / `main_video` track) as Helios —
6
+ * only the `modelName` string differs on the bridge. The COMMAND VOCABULARY
7
+ * differs: LongLive is text-to-video with a hard `scene_cut` (a
8
+ * memory-purging transition Helios lacks) and NO image conditioning (there is
9
+ * NO `uploadFile` / `set_image` / `swap_seed` equivalent — text-only).
10
+ *
11
+ * Pure framework-agnostic helper: no React imports, no `@reactor-team/js-sdk`
12
+ * dependency. It reuses the structural {@link HeliosReactorBridge}
13
+ * `sendCommand` surface via `Pick` (no rename — additive-only) but takes NO
14
+ * `uploadFile` (LongLive has no image path).
15
+ *
16
+ * Failure policy mirrors the Helios dispatcher: every command is wrapped in a
17
+ * try/catch. A clean abort is silent; any other failure is logged and skipped
18
+ * so the chat session keeps working even when the world stream is unreachable.
19
+ */
20
+
21
+ import { isAbortError } from './abortUtils';
22
+ import type { HeliosReactorBridge } from './heliosCommandDispatcher';
23
+
24
+ /**
25
+ * Discriminated union of every LongLive-v2 world-steering action.
26
+ *
27
+ * Wire vocabulary (Reactor `sendCommand`):
28
+ * - `set_shot` — soft transition (also the OPENING shot before `start`).
29
+ * - `scene_cut` — HARD transition: purges memory + resets the per-scene chunk
30
+ * counter (Helios has no equivalent).
31
+ * - `schedule_shot` / `schedule_scene_cut` — schedule at a CUMULATIVE
32
+ * `session_chunk` index (snake_case `at_session_chunk` on the wire).
33
+ * Presumes a STARTED session (the dispatcher only emits `start` from the
34
+ * opening `set_shot`); Step 3's director schedules only after the opening
35
+ * shot, so a schedule before `start` is a caller error, not handled here.
36
+ * - `pause` / `resume` / `reset` — lifecycle.
37
+ * - `set_seed` — deterministic seed.
38
+ *
39
+ * NOTE: there is deliberately NO `swap_seed` variant — LongLive is
40
+ * text-to-video and has no image-conditioning surface.
41
+ */
42
+ export type LongLiveCommand =
43
+ | { type: 'set_shot'; prompt: string }
44
+ | { type: 'scene_cut'; prompt: string }
45
+ | { type: 'schedule_shot'; prompt: string; atSessionChunk: number }
46
+ | { type: 'schedule_scene_cut'; prompt: string; atSessionChunk: number }
47
+ | { type: 'pause' }
48
+ | { type: 'resume' }
49
+ | { type: 'reset' }
50
+ | { type: 'set_seed'; seed: number };
51
+
52
+ /**
53
+ * Inputs the LongLive dispatcher needs beyond the command itself.
54
+ *
55
+ * Reuses the structural {@link HeliosReactorBridge} `sendCommand` slot via
56
+ * `Pick` so client-core takes NO runtime SDK dependency and the same mockable
57
+ * bridge works for both dispatchers. Deliberately NARROWER than
58
+ * `HeliosToolContext`: no `apiClient` (no upsample/entity lookup here), no
59
+ * `uploadFile` (no image path), no `videoId` / `imageId` / `entityContext`
60
+ * (text-to-video, no `swap_seed`).
61
+ */
62
+ export interface LongLiveToolContext {
63
+ reactor: Pick<HeliosReactorBridge, 'sendCommand'>;
64
+ /** Whether the page has already issued a `start` command in this session.
65
+ * `set_shot` at the opening shot needs to know: if false, fire
66
+ * `set_shot` + `start` (this is the first shot); if true, fire `set_shot`
67
+ * only (re-emitting `start` while running is undocumented Reactor
68
+ * behavior — defensive to skip it). Mirrors the Helios `set_scene`
69
+ * chunk-0 + `hasStarted` guard.
70
+ *
71
+ * CALLER CONTRACT (the dispatcher does NOT mutate `ctx`): the caller MUST
72
+ * set this to `true` after the first `set_shot` dispatches, and clear it to
73
+ * `false` on `reset`. A caller that reuses one context object without
74
+ * updating `hasStarted` will re-fire `start` on every `set_shot`. (Step 3's
75
+ * director tracks this on its session state.) */
76
+ hasStarted?: boolean;
77
+ /** Optional `AbortSignal`: when aborted (before dispatch), the function
78
+ * returns silently without invoking `sendCommand`. Reactor `sendCommand`
79
+ * is NOT itself aborted (the SDK has no signal surface) — but a clean
80
+ * abort thrown from within is routed silently through `isAbortError`. */
81
+ signal?: AbortSignal;
82
+ }
83
+
84
+ /**
85
+ * Dispatch a single {@link LongLiveCommand} to the live Reactor session.
86
+ * Resolves with no value on both success and failure — the caller just awaits
87
+ * and continues to the next command (mirrors {@link dispatchHeliosCommand}).
88
+ *
89
+ * When `ctx.signal` is already aborted, returns silently without invoking
90
+ * `sendCommand`. A clean abort thrown mid-dispatch is also silent.
91
+ */
92
+ export async function dispatchLongLiveCommand(
93
+ cmd: LongLiveCommand,
94
+ ctx: LongLiveToolContext,
95
+ ): Promise<void> {
96
+ if (ctx.signal?.aborted) return;
97
+ try {
98
+ switch (cmd.type) {
99
+ case 'set_shot':
100
+ await ctx.reactor.sendCommand('set_shot', { prompt: cmd.prompt });
101
+ // Opening-shot-then-start: only emit `start` when the page hasn't
102
+ // fired it yet (re-emitting `start` while running is undocumented
103
+ // Reactor behavior). Mirrors the Helios set_scene chunk-0 guard.
104
+ if (!ctx.hasStarted) {
105
+ await ctx.reactor.sendCommand('start', {});
106
+ }
107
+ return;
108
+ case 'scene_cut':
109
+ await ctx.reactor.sendCommand('scene_cut', { prompt: cmd.prompt });
110
+ return;
111
+ case 'schedule_shot':
112
+ await ctx.reactor.sendCommand('schedule_shot', {
113
+ prompt: cmd.prompt,
114
+ at_session_chunk: cmd.atSessionChunk,
115
+ });
116
+ return;
117
+ case 'schedule_scene_cut':
118
+ await ctx.reactor.sendCommand('schedule_scene_cut', {
119
+ prompt: cmd.prompt,
120
+ at_session_chunk: cmd.atSessionChunk,
121
+ });
122
+ return;
123
+ case 'pause':
124
+ await ctx.reactor.sendCommand('pause', {});
125
+ return;
126
+ case 'resume':
127
+ await ctx.reactor.sendCommand('resume', {});
128
+ return;
129
+ case 'reset':
130
+ await ctx.reactor.sendCommand('reset', {});
131
+ return;
132
+ case 'set_seed':
133
+ await ctx.reactor.sendCommand('set_seed', { seed: cmd.seed });
134
+ return;
135
+ default: {
136
+ // Exhaustiveness check — TS complains at compile time if a new
137
+ // LongLiveCommand variant is added without updating this switch. The
138
+ // runtime branch is unreachable but keeps the narrowing honest.
139
+ const _exhaustive: never = cmd;
140
+ console.warn(
141
+ '[longLiveCommandDispatcher] unknown command type',
142
+ _exhaustive,
143
+ );
144
+ return;
145
+ }
146
+ }
147
+ } catch (err) {
148
+ // Abort is a clean signal — silent and stop here.
149
+ if (isAbortError(err)) return;
150
+ console.warn(
151
+ '[longLiveCommandDispatcher] command failed; skipping',
152
+ cmd,
153
+ err,
154
+ );
155
+ }
156
+ }