@escapeaihq/client-core 0.12.0 → 0.49.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 (242) hide show
  1. package/README.md +32 -7
  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 +323 -0
  31. package/dist/admin.d.ts.map +1 -0
  32. package/dist/admin.js +198 -0
  33. package/dist/admin.js.map +1 -0
  34. package/dist/api.d.ts +1512 -4
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +820 -52
  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 +77 -0
  47. package/dist/conversation/binding.d.ts.map +1 -0
  48. package/dist/conversation/binding.js +57 -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 +350 -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 +92 -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 +553 -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/binding.test.ts +62 -0
  179. package/src/__tests__/conversation/controller.test.ts +732 -0
  180. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  181. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  182. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  183. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  184. package/src/__tests__/conversation/roster.test.ts +100 -0
  185. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  186. package/src/__tests__/conversation/router.test.ts +81 -0
  187. package/src/__tests__/conversation/runtime.test.ts +206 -0
  188. package/src/__tests__/conversation/voice.test.ts +440 -0
  189. package/src/__tests__/documents.test.ts +360 -0
  190. package/src/__tests__/graphSchema.test.ts +218 -9
  191. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  192. package/src/__tests__/monitoring.test.ts +162 -0
  193. package/src/__tests__/persona-generation.test.ts +352 -0
  194. package/src/__tests__/platformAssistant.test.ts +484 -0
  195. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  196. package/src/__tests__/regeneration.test.ts +486 -0
  197. package/src/__tests__/stories.test.ts +171 -0
  198. package/src/__tests__/storyGraph.test.ts +134 -0
  199. package/src/__tests__/tools-wrappers.test.ts +272 -0
  200. package/src/__tests__/videoGraph.test.ts +94 -0
  201. package/src/__tests__/websocket.test.ts +263 -0
  202. package/src/adapters/capabilities.ts +24 -0
  203. package/src/adapters/chatAdapter.ts +114 -0
  204. package/src/adapters/directorAdapter.ts +126 -0
  205. package/src/adapters/imageAdapter.ts +100 -0
  206. package/src/adapters/index.ts +67 -0
  207. package/src/adapters/registry.ts +159 -0
  208. package/src/adapters/worldAdapter.ts +272 -0
  209. package/src/admin.ts +517 -0
  210. package/src/api.ts +2215 -95
  211. package/src/audio.ts +35 -0
  212. package/src/castProjection.ts +95 -0
  213. package/src/conversation/binding.ts +100 -0
  214. package/src/conversation/controller.ts +447 -0
  215. package/src/conversation/effectiveModel.ts +111 -0
  216. package/src/conversation/index.ts +27 -0
  217. package/src/conversation/participant.ts +71 -0
  218. package/src/conversation/presence.ts +60 -0
  219. package/src/conversation/presenceBus.ts +109 -0
  220. package/src/conversation/presenceRegistry.ts +83 -0
  221. package/src/conversation/roster.ts +111 -0
  222. package/src/conversation/rosterProjection.ts +98 -0
  223. package/src/conversation/router.ts +96 -0
  224. package/src/conversation/runtime.ts +188 -0
  225. package/src/conversation/types.ts +100 -0
  226. package/src/conversation/voice.ts +402 -0
  227. package/src/graphSchema.ts +396 -13
  228. package/src/http.ts +72 -0
  229. package/src/index.ts +9 -0
  230. package/src/platformAssistant.ts +347 -0
  231. package/src/reactor/chunkDistribution.ts +98 -0
  232. package/src/reactor/index.ts +5 -0
  233. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  234. package/src/reactor/scenesFromEnrichment.ts +11 -76
  235. package/src/reactor/seedImageOrchestrator.ts +12 -13
  236. package/src/reactor/storyTimeline.ts +127 -0
  237. package/src/storyGraph.ts +298 -0
  238. package/src/vision/VisionSourceController.ts +354 -0
  239. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  240. package/src/vision/index.ts +13 -0
  241. package/src/vision/sourceKinds.ts +75 -0
  242. package/src/websocket.ts +99 -3
@@ -0,0 +1,484 @@
1
+ /**
2
+ * Tests for the R4c framework-agnostic `PlatformAssistantController`
3
+ * (`src/platformAssistant.ts`).
4
+ *
5
+ * The controller is a thin state holder over `ApiClient.streamAssistant`:
6
+ * it holds the running message list + the current `routeContext`, calls
7
+ * `streamAssistant` on `ask(prompt)`, parses the returned SSE
8
+ * `ReadableStreamDefaultReader` (the SAME `data: {…}\n\n` frame format the
9
+ * web chat page decodes), and fans the decoded `AssistantStreamEvent`
10
+ * variants out to the host callbacks:
11
+ * - `token` -> onTextDelta(content)
12
+ * - `suggestion` -> onSuggestion({ targetForm, fields, rationale? })
13
+ * - `error` -> onError(message)
14
+ * - `done` -> onDone()
15
+ * (`tool_use` / `tool_result` / `citation` are ignored — minimal surface.)
16
+ *
17
+ * The controller MUST stay framework-agnostic (React/Vue/PlayCanvas all
18
+ * consume it) — the final test reads the source file and asserts it imports
19
+ * no UI framework (the R2.1 ConversationController portability mandate).
20
+ *
21
+ * Mirrors the SSE-reader harness + global-fetch save/restore discipline in
22
+ * api.test.ts (a single UTF-8 chunk reader; `jest.restoreAllMocks` only
23
+ * unwinds spyOn, not direct assignment to globalThis.fetch).
24
+ */
25
+
26
+ import { readFileSync } from 'node:fs';
27
+ import path from 'node:path';
28
+ // jest-environment-jsdom does not expose TextEncoder/TextDecoder as globals.
29
+ // The controller decodes the SSE stream with the BROWSER-global `TextDecoder`
30
+ // (correct in browsers + modern Node — it must stay framework/runtime-agnostic,
31
+ // so it does NOT import from `node:util`). Pull both from Node's `util` here to
32
+ // polyfill the jsdom env (below) so the test exercises that same global path.
33
+ import { TextEncoder, TextDecoder } from 'node:util';
34
+
35
+ import { ApiClient } from '../api';
36
+ import type { AssistantRouteContext } from '../api';
37
+ import {
38
+ PlatformAssistantController,
39
+ type PlatformAssistantSuggestion,
40
+ } from '../platformAssistant';
41
+
42
+ // Install the polyfills onto globalThis BEFORE any test constructs the
43
+ // controller (module-eval time — runs once after the hoisted imports above).
44
+ const g = globalThis as { TextEncoder?: unknown; TextDecoder?: unknown };
45
+ if (g.TextEncoder === undefined) g.TextEncoder = TextEncoder;
46
+ if (g.TextDecoder === undefined) g.TextDecoder = TextDecoder;
47
+
48
+ const TEST_BASE_URL = 'http://test.local';
49
+ const TEST_CHAT_BASE_URL = 'http://test.local/chat';
50
+
51
+ const makeClient = (sessionToken: string = 'test-token') =>
52
+ new ApiClient(TEST_BASE_URL, sessionToken, TEST_CHAT_BASE_URL);
53
+
54
+ const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch;
55
+
56
+ afterEach(() => {
57
+ if (originalFetch === undefined) {
58
+ delete (globalThis as { fetch?: typeof fetch }).fetch;
59
+ } else {
60
+ (globalThis as { fetch?: typeof fetch }).fetch = originalFetch;
61
+ }
62
+ jest.restoreAllMocks();
63
+ });
64
+
65
+ /**
66
+ * Build a Response-like object whose `body.getReader()` streams the given
67
+ * SSE text as a single UTF-8 chunk then closes (the shape `fetch` returns for
68
+ * a `text/event-stream` response so `streamAssistant` hands back the reader).
69
+ */
70
+ const sseResponse = (sseText: string, init?: { ok?: boolean; status?: number }) => {
71
+ const encoder = new TextEncoder();
72
+ let sent = false;
73
+ const reader = {
74
+ read: async () => {
75
+ if (sent) return { done: true, value: undefined };
76
+ sent = true;
77
+ return { done: false, value: encoder.encode(sseText) };
78
+ },
79
+ releaseLock: () => undefined,
80
+ cancel: async () => undefined,
81
+ closed: Promise.resolve(undefined),
82
+ };
83
+
84
+ return {
85
+ ok: init?.ok ?? true,
86
+ status: init?.status ?? 200,
87
+ statusText: 'OK',
88
+ headers: {
89
+ get: (h: string) => (h.toLowerCase() === 'content-type' ? 'text/event-stream' : null),
90
+ },
91
+ body: { getReader: () => reader },
92
+ json: async () => ({}),
93
+ };
94
+ };
95
+
96
+ /** Serialize an SSE event frame the way the backend writes them. */
97
+ const frame = (event: Record<string, unknown>): string => `data: ${JSON.stringify(event)}\n\n`;
98
+
99
+ const ROUTE: AssistantRouteContext = {
100
+ surface: 'studio/cast',
101
+ formId: 'persona',
102
+ entityId: 'story-1',
103
+ };
104
+
105
+ describe('PlatformAssistantController.ask', () => {
106
+ it('streams token events into onTextDelta in order and fires onDone', async () => {
107
+ const sse =
108
+ frame({ type: 'token', content: 'A weary ' }) +
109
+ frame({ type: 'token', content: 'detective.' }) +
110
+ frame({ type: 'done', reason: 'stop' }) +
111
+ 'data: [DONE]\n\n';
112
+ const fetchMock = jest.fn().mockResolvedValue(sseResponse(sse));
113
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
114
+
115
+ const deltas: string[] = [];
116
+ let doneCount = 0;
117
+ const controller = new PlatformAssistantController({
118
+ apiClient: makeClient(),
119
+ routeContext: ROUTE,
120
+ callbacks: {
121
+ onTextDelta: (text) => deltas.push(text),
122
+ onDone: () => {
123
+ doneCount += 1;
124
+ },
125
+ },
126
+ });
127
+
128
+ await controller.ask('make a brooding detective');
129
+
130
+ expect(deltas).toEqual(['A weary ', 'detective.']);
131
+ expect(doneCount).toBe(1);
132
+ });
133
+
134
+ it('decodes a suggestion event into onSuggestion with targetForm + fields + rationale', async () => {
135
+ const sse =
136
+ frame({
137
+ type: 'suggestion',
138
+ targetForm: 'persona',
139
+ fields: { name: 'Cole Tarrant', systemPrompt: 'A weary, brooding detective.' },
140
+ rationale: 'Matches the noir brief.',
141
+ }) +
142
+ frame({ type: 'done' }) +
143
+ 'data: [DONE]\n\n';
144
+ const fetchMock = jest.fn().mockResolvedValue(sseResponse(sse));
145
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
146
+
147
+ const suggestions: PlatformAssistantSuggestion[] = [];
148
+ const controller = new PlatformAssistantController({
149
+ apiClient: makeClient(),
150
+ routeContext: ROUTE,
151
+ callbacks: { onSuggestion: (s) => suggestions.push(s) },
152
+ });
153
+
154
+ await controller.ask('propose persona fields');
155
+
156
+ expect(suggestions).toHaveLength(1);
157
+ expect(suggestions[0].targetForm).toBe('persona');
158
+ expect(suggestions[0].fields).toEqual({
159
+ name: 'Cole Tarrant',
160
+ systemPrompt: 'A weary, brooding detective.',
161
+ });
162
+ expect(suggestions[0].rationale).toBe('Matches the noir brief.');
163
+ });
164
+
165
+ it('surfaces an error event through onError', async () => {
166
+ const sse = frame({ type: 'error', message: 'model unavailable' }) + 'data: [DONE]\n\n';
167
+ const fetchMock = jest.fn().mockResolvedValue(sseResponse(sse));
168
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
169
+
170
+ const errors: string[] = [];
171
+ const controller = new PlatformAssistantController({
172
+ apiClient: makeClient(),
173
+ routeContext: ROUTE,
174
+ callbacks: { onError: (m) => errors.push(m) },
175
+ });
176
+
177
+ await controller.ask('anything');
178
+
179
+ expect(errors).toEqual(['model unavailable']);
180
+ });
181
+
182
+ it('surfaces a TRANSPORT error via onError and never rejects ask()', async () => {
183
+ // streamAssistant rejects (network/transport) — not an SSE `error` frame.
184
+ const fetchMock = jest.fn().mockRejectedValue(new Error('network down'));
185
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
186
+
187
+ const errors: string[] = [];
188
+ const controller = new PlatformAssistantController({
189
+ apiClient: makeClient(),
190
+ routeContext: ROUTE,
191
+ callbacks: { onError: (m) => errors.push(m) },
192
+ });
193
+
194
+ // ask() must RESOLVE (not reject) — the framework-agnostic contract.
195
+ await expect(controller.ask('anything')).resolves.toBeUndefined();
196
+ expect(errors).toEqual(['network down']);
197
+ });
198
+
199
+ it('threads the current routeContext + accumulated message history into streamAssistant', async () => {
200
+ const fetchMock = jest
201
+ .fn()
202
+ .mockResolvedValueOnce(
203
+ sseResponse(frame({ type: 'token', content: 'hi' }) + 'data: [DONE]\n\n'),
204
+ )
205
+ .mockResolvedValueOnce(sseResponse('data: [DONE]\n\n'));
206
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
207
+
208
+ const controller = new PlatformAssistantController({
209
+ apiClient: makeClient(),
210
+ routeContext: ROUTE,
211
+ callbacks: {},
212
+ });
213
+
214
+ await controller.ask('first');
215
+ // The second ask must carry the first user prompt + the streamed assistant
216
+ // reply as prior history (the running message list).
217
+ await controller.ask('second');
218
+
219
+ const secondBody = JSON.parse(fetchMock.mock.calls[1][1].body as string);
220
+ expect(secondBody.prompt).toBe('second');
221
+ expect(secondBody.routeContext).toEqual(ROUTE);
222
+ expect(secondBody.messages).toEqual([
223
+ { role: 'user', content: 'first' },
224
+ { role: 'assistant', content: 'hi' },
225
+ ]);
226
+ // No videoId — the assistant is out-of-world.
227
+ expect(secondBody).not.toHaveProperty('videoId');
228
+ });
229
+
230
+ it('threads ask() documentContext into the request only when supplied (R11.2)', async () => {
231
+ const fetchMock = jest
232
+ .fn()
233
+ .mockResolvedValue(sseResponse('data: [DONE]\n\n'));
234
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
235
+
236
+ const controller = new PlatformAssistantController({
237
+ apiClient: makeClient(),
238
+ routeContext: ROUTE,
239
+ callbacks: {},
240
+ });
241
+
242
+ // WITH documentContext: the large draft rides the dedicated field.
243
+ await controller.ask('Refine this prompt; return only the body.', {
244
+ documentContext: 'A 40 KB draft body the assistant should operate on…',
245
+ });
246
+ const withCtx = JSON.parse(fetchMock.mock.calls[0][1].body as string);
247
+ expect(withCtx.prompt).toBe('Refine this prompt; return only the body.');
248
+ expect(withCtx.documentContext).toBe(
249
+ 'A 40 KB draft body the assistant should operate on…',
250
+ );
251
+
252
+ // WITHOUT documentContext (plain ask): the key is ABSENT — the wire payload
253
+ // is byte-identical to the pre-R11.2 one (no empty/undefined documentContext).
254
+ await controller.ask('just a question');
255
+ const withoutCtx = JSON.parse(fetchMock.mock.calls[1][1].body as string);
256
+ expect(withoutCtx).not.toHaveProperty('documentContext');
257
+ });
258
+
259
+ it('omits documentContext when an empty string is passed (no empty wire field)', async () => {
260
+ const fetchMock = jest.fn().mockResolvedValue(sseResponse('data: [DONE]\n\n'));
261
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
262
+
263
+ const controller = new PlatformAssistantController({
264
+ apiClient: makeClient(),
265
+ routeContext: ROUTE,
266
+ callbacks: {},
267
+ });
268
+
269
+ await controller.ask('hi', { documentContext: '' });
270
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);
271
+ expect(body).not.toHaveProperty('documentContext');
272
+ });
273
+
274
+ it('setRouteContext updates the context sent on the next ask', async () => {
275
+ const fetchMock = jest.fn().mockResolvedValue(sseResponse('data: [DONE]\n\n'));
276
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
277
+
278
+ const controller = new PlatformAssistantController({
279
+ apiClient: makeClient(),
280
+ routeContext: ROUTE,
281
+ callbacks: {},
282
+ });
283
+
284
+ const next: AssistantRouteContext = { surface: 'settings/defaults', formId: 'prompt' };
285
+ controller.setRouteContext(next);
286
+ await controller.ask('improve this');
287
+
288
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);
289
+ expect(body.routeContext).toEqual(next);
290
+ });
291
+
292
+ it('abort() cancels the in-flight stream via the AbortSignal', async () => {
293
+ let capturedSignal: AbortSignal | undefined;
294
+ // A reader whose first read() blocks until the signal aborts (so the stream
295
+ // is genuinely IN FLIGHT when abort() is called — the real cancel path).
296
+ const blockingResponse = (signal?: AbortSignal) => {
297
+ const reader = {
298
+ read: () =>
299
+ new Promise<{ done: boolean; value: undefined }>((resolve) => {
300
+ const finish = () => resolve({ done: true, value: undefined });
301
+ // Resolve immediately if abort already fired before this read()
302
+ // subscribed; otherwise resolve when it does.
303
+ if (signal?.aborted) {
304
+ finish();
305
+ return;
306
+ }
307
+ signal?.addEventListener('abort', finish, { once: true });
308
+ }),
309
+ releaseLock: () => undefined,
310
+ cancel: async () => undefined,
311
+ closed: Promise.resolve(undefined),
312
+ };
313
+ return {
314
+ ok: true,
315
+ status: 200,
316
+ statusText: 'OK',
317
+ headers: { get: () => 'text/event-stream' },
318
+ body: { getReader: () => reader },
319
+ json: async () => ({}),
320
+ };
321
+ };
322
+ const fetchMock = jest.fn().mockImplementation((_url: string, init: RequestInit) => {
323
+ capturedSignal = init.signal ?? undefined;
324
+ return Promise.resolve(blockingResponse(init.signal ?? undefined));
325
+ });
326
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
327
+
328
+ const controller = new PlatformAssistantController({
329
+ apiClient: makeClient(),
330
+ routeContext: ROUTE,
331
+ callbacks: {},
332
+ });
333
+
334
+ // Do NOT await — the stream blocks until we abort it.
335
+ const pending = controller.ask('start');
336
+ // Let the fetch + getReader resolve so the controller is mid-stream.
337
+ await Promise.resolve();
338
+ await Promise.resolve();
339
+ expect(capturedSignal).toBeDefined();
340
+ expect(capturedSignal!.aborted).toBe(false);
341
+
342
+ controller.abort();
343
+ expect(capturedSignal!.aborted).toBe(true);
344
+ await pending; // resolves once the blocked read() unblocks on abort
345
+ });
346
+
347
+ it('ask() after dispose() surfaces onError and does NOT throw', async () => {
348
+ const errors: string[] = [];
349
+ const controller = new PlatformAssistantController({
350
+ apiClient: makeClient(),
351
+ routeContext: ROUTE,
352
+ callbacks: { onError: (m) => errors.push(m) },
353
+ });
354
+ controller.dispose();
355
+ // Honors the "never rejects" contract — disposed routes through onError.
356
+ await expect(controller.ask('after dispose')).resolves.toBeUndefined();
357
+ expect(errors.some((m) => /dispose/i.test(m))).toBe(true);
358
+ });
359
+
360
+ it('a turn that produces no reply commits no message (no dangling user turn)', async () => {
361
+ // Empty reply (just [DONE]) ⇒ the user turn is NOT committed, so a re-entrant
362
+ // ask() that aborts a reply-less turn never leaves a dangling user message.
363
+ const fetchMock = jest.fn().mockResolvedValue(sseResponse('data: [DONE]\n\n'));
364
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
365
+
366
+ const controller = new PlatformAssistantController({
367
+ apiClient: makeClient(),
368
+ routeContext: ROUTE,
369
+ callbacks: {},
370
+ });
371
+ await controller.ask('no reply expected');
372
+ expect(controller.getMessages()).toEqual([]);
373
+ });
374
+
375
+ it('fires onDone when the stream closes WITHOUT a [DONE] sentinel (server crash/timeout)', async () => {
376
+ // The reader closes mid-stream with NO done event / [DONE] sentinel — the
377
+ // turn is still over, so onDone MUST fire (else the overlay sticks streaming).
378
+ const sse = frame({ type: 'token', content: 'partial answer' }); // no [DONE]
379
+ const fetchMock = jest.fn().mockResolvedValue(sseResponse(sse));
380
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
381
+
382
+ const done = jest.fn();
383
+ const controller = new PlatformAssistantController({
384
+ apiClient: makeClient(),
385
+ routeContext: ROUTE,
386
+ callbacks: { onDone: done },
387
+ });
388
+ await controller.ask('x');
389
+ expect(done).toHaveBeenCalledTimes(1);
390
+ });
391
+
392
+ it('processes a final frame that arrives WITHOUT a trailing newline (server closed mid-frame)', async () => {
393
+ // The last frame has no terminating `\n\n`, so it sits in the line buffer when
394
+ // the reader closes. The close-time flush must still parse it (via the shared
395
+ // handleLine path) so the final token is not silently dropped.
396
+ const sse =
397
+ frame({ type: 'token', content: 'first ' }) +
398
+ 'data: {"type":"token","content":"last"}';
399
+ const fetchMock = jest.fn().mockResolvedValue(sseResponse(sse));
400
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
401
+
402
+ const deltas: string[] = [];
403
+ const controller = new PlatformAssistantController({
404
+ apiClient: makeClient(),
405
+ routeContext: ROUTE,
406
+ callbacks: { onTextDelta: (t) => deltas.push(t) },
407
+ });
408
+ await controller.ask('x');
409
+ expect(deltas).toEqual(['first ', 'last']);
410
+ });
411
+
412
+ it('releases the response-body reader lock when the stream closes', async () => {
413
+ // Hygiene (claude[bot] round-7): the consume() finally must releaseLock() on
414
+ // the normal-close path so the body reader does not stay locked.
415
+ const releaseLock = jest.fn();
416
+ const encoder = new TextEncoder();
417
+ let sent = false;
418
+ const reader = {
419
+ read: async () => {
420
+ if (sent) return { done: true, value: undefined };
421
+ sent = true;
422
+ return {
423
+ done: false,
424
+ value: encoder.encode(frame({ type: 'done' }) + 'data: [DONE]\n\n'),
425
+ };
426
+ },
427
+ releaseLock,
428
+ cancel: async () => undefined,
429
+ closed: Promise.resolve(undefined),
430
+ };
431
+ const response = {
432
+ ok: true,
433
+ status: 200,
434
+ statusText: 'OK',
435
+ headers: { get: () => 'text/event-stream' },
436
+ body: { getReader: () => reader },
437
+ json: async () => ({}),
438
+ };
439
+ const fetchMock = jest.fn().mockResolvedValue(response);
440
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
441
+
442
+ const controller = new PlatformAssistantController({
443
+ apiClient: makeClient(),
444
+ routeContext: ROUTE,
445
+ callbacks: {},
446
+ });
447
+ await controller.ask('x');
448
+ expect(releaseLock).toHaveBeenCalledTimes(1);
449
+ });
450
+
451
+ it('a self-abort (AbortError) fires onDone, not onError, and resolves', async () => {
452
+ // The reader THROWS AbortError (vs resolving {done:true}) — the turn is over,
453
+ // so onDone fires (a future Cancel button must not leave streaming stuck) and
454
+ // it is NOT surfaced as an error.
455
+ const abortErr = new Error('aborted');
456
+ abortErr.name = 'AbortError';
457
+ const fetchMock = jest.fn().mockRejectedValue(abortErr);
458
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
459
+
460
+ const done = jest.fn();
461
+ const errors: string[] = [];
462
+ const controller = new PlatformAssistantController({
463
+ apiClient: makeClient(),
464
+ routeContext: ROUTE,
465
+ callbacks: { onDone: done, onError: (m) => errors.push(m) },
466
+ });
467
+ await expect(controller.ask('x')).resolves.toBeUndefined();
468
+ expect(done).toHaveBeenCalledTimes(1);
469
+ expect(errors).toEqual([]);
470
+ });
471
+ });
472
+
473
+ describe('PlatformAssistantController portability', () => {
474
+ it('imports no UI framework (framework-agnostic — portable to Vue/PlayCanvas)', () => {
475
+ const source = readFileSync(
476
+ path.join(__dirname, '..', 'platformAssistant.ts'),
477
+ 'utf8',
478
+ );
479
+ // No import from react / react-dom / vue / next (or scoped variants).
480
+ expect(source).not.toMatch(/from\s+['"](react|react-dom|vue|next)(\/[^'"]*)?['"]/);
481
+ expect(source).not.toMatch(/from\s+['"]@(react|vue|next)\//);
482
+ expect(source).not.toMatch(/require\(\s*['"](react|react-dom|vue|next)['"]\s*\)/);
483
+ });
484
+ });
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Tests for `deriveStoryTimeline` — the collapsed-story-projection
3
+ * (`SceneView[]`) → world-model-timeline mapper (Platform Restructure R8.1).
4
+ *
5
+ * Coverage:
6
+ * - empty SceneView[] → [] (defensive contract, no throw)
7
+ * - 3 timed scenes → 3 beats, proportional chunks, first pinned to 0,
8
+ * monotonically increasing, clamped to maxChunks - 1
9
+ * - prompt contains the scene summary + featured-character names + location
10
+ * - styleHint prepended with a single space, no trailing punctuation
11
+ * - label carries the scene-id provenance tag
12
+ * - sourceStart/sourceEnd from startTime/endTime; null times omitted
13
+ * - maxChunks <= 0 → []
14
+ * - shares the SAME chunk distribution as mapEnrichmentToTimeline (untimed
15
+ * scenes → even distribution)
16
+ */
17
+
18
+ import {
19
+ deriveStoryTimeline,
20
+ type StoryTimelineOptions,
21
+ } from '../../reactor/storyTimeline';
22
+ import type { TimelineBeat } from '../../reactor/scenesFromEnrichment';
23
+ import { deriveScenes, type SceneView } from '../../storyGraph';
24
+ import type { VideoGraphResponse } from '../../api';
25
+
26
+ function makeScene(overrides: Partial<SceneView> = {}): SceneView {
27
+ return {
28
+ nodeId: 'n-scene',
29
+ sceneId: 'sc-1',
30
+ title: 'A Scene',
31
+ index: 1,
32
+ startTime: 0,
33
+ endTime: 10,
34
+ summary: 'Something happens.',
35
+ actNodeId: 'n-act',
36
+ actTitle: 'Act One',
37
+ actIndex: 1,
38
+ featuredCharacters: [],
39
+ location: null,
40
+ shots: [],
41
+ ...overrides,
42
+ };
43
+ }
44
+
45
+ describe('deriveStoryTimeline', () => {
46
+ it('returns [] for an empty scene list (no throw)', () => {
47
+ expect(deriveStoryTimeline([])).toEqual([]);
48
+ });
49
+
50
+ it('returns [] when maxChunks is non-positive', () => {
51
+ const scenes = [makeScene()];
52
+ expect(deriveStoryTimeline(scenes, { maxChunks: 0 })).toEqual([]);
53
+ expect(deriveStoryTimeline(scenes, { maxChunks: -5 })).toEqual([]);
54
+ });
55
+
56
+ it('maps 3 timed scenes to 3 monotonically-increasing beats, first pinned to chunk 0', () => {
57
+ const scenes: SceneView[] = [
58
+ makeScene({ sceneId: 'sc-1', index: 1, startTime: 0, endTime: 30, summary: 'Opening.' }),
59
+ makeScene({ sceneId: 'sc-2', index: 2, startTime: 30, endTime: 60, summary: 'Middle.' }),
60
+ makeScene({ sceneId: 'sc-3', index: 3, startTime: 60, endTime: 90, summary: 'Climax.' }),
61
+ ];
62
+ const beats = deriveStoryTimeline(scenes, { maxChunks: 30 });
63
+ expect(beats).toHaveLength(3);
64
+ expect(beats[0].chunk).toBe(0);
65
+ // monotonically increasing
66
+ expect(beats[1].chunk).toBeGreaterThan(beats[0].chunk);
67
+ expect(beats[2].chunk).toBeGreaterThan(beats[1].chunk);
68
+ // clamped to maxChunks - 1
69
+ for (const b of beats) {
70
+ expect(b.chunk).toBeGreaterThanOrEqual(0);
71
+ expect(b.chunk).toBeLessThanOrEqual(29);
72
+ }
73
+ // Proportional placement by scene START over the 0..90 span (same rule as
74
+ // mapEnrichmentToTimeline): scene-3 starts at 60 → round(60/90 * 29) = 19.
75
+ expect(beats[1].chunk).toBe(10);
76
+ expect(beats[2].chunk).toBe(19);
77
+ });
78
+
79
+ it('grounds each prompt in the scene summary + featured-character names + location', () => {
80
+ const scenes: SceneView[] = [
81
+ makeScene({
82
+ sceneId: 'sc-1',
83
+ summary: 'Alice confronts Bob in the bunker.',
84
+ featuredCharacters: [
85
+ { nodeId: 'n-a', entityId: 'c-alice', name: 'Alice' },
86
+ { nodeId: 'n-b', entityId: 'c-bob', name: 'Bob' },
87
+ ],
88
+ location: { nodeId: 'n-l', entityId: 'l-bunker', name: 'The Bunker' },
89
+ }),
90
+ ];
91
+ const [beat] = deriveStoryTimeline(scenes);
92
+ expect(beat.prompt).toContain('Alice confronts Bob in the bunker.');
93
+ expect(beat.prompt).toContain('Alice');
94
+ expect(beat.prompt).toContain('Bob');
95
+ expect(beat.prompt).toContain('The Bunker');
96
+ });
97
+
98
+ it('prepends styleHint with a single space and no trailing punctuation', () => {
99
+ const scenes = [makeScene({ summary: 'A quiet morning.' })];
100
+ const opts: StoryTimelineOptions = { styleHint: 'cinematic 16:9, golden hour' };
101
+ const [beat] = deriveStoryTimeline(scenes, opts);
102
+ expect(beat.prompt.startsWith('cinematic 16:9, golden hour A quiet morning.')).toBe(true);
103
+ // exactly one space between hint and body
104
+ expect(beat.prompt).not.toContain('golden hour A');
105
+ });
106
+
107
+ it('trims a styleHint and ignores a blank one', () => {
108
+ const scenes = [makeScene({ summary: 'Body.' })];
109
+ expect(deriveStoryTimeline(scenes, { styleHint: ' ' })[0].prompt).toBe('Body.');
110
+ expect(deriveStoryTimeline(scenes, { styleHint: ' neon ' })[0].prompt).toBe('neon Body.');
111
+ });
112
+
113
+ it('falls back to the scene title when the summary is empty', () => {
114
+ const scenes = [makeScene({ title: 'The Reckoning', summary: null, featuredCharacters: [] })];
115
+ expect(deriveStoryTimeline(scenes)[0].prompt).toContain('The Reckoning');
116
+ });
117
+
118
+ it('tags the beat label with the scene-id provenance', () => {
119
+ const scenes = [makeScene({ sceneId: 'sc-42', title: 'Finale' })];
120
+ expect(deriveStoryTimeline(scenes)[0].label).toBe('Finale (sc-42)');
121
+ });
122
+
123
+ it('carries sourceStart/sourceEnd from scene times; omits them when null', () => {
124
+ const timed = deriveStoryTimeline([makeScene({ startTime: 5, endTime: 15 })])[0];
125
+ expect(timed.sourceStart).toBe(5);
126
+ expect(timed.sourceEnd).toBe(15);
127
+
128
+ const untimed = deriveStoryTimeline([makeScene({ startTime: null, endTime: null })])[0];
129
+ expect(untimed.sourceStart).toBeUndefined();
130
+ expect(untimed.sourceEnd).toBeUndefined();
131
+ });
132
+
133
+ it('distributes untimed scenes evenly (shared distribution with mapEnrichmentToTimeline)', () => {
134
+ const scenes: SceneView[] = [
135
+ makeScene({ sceneId: 'a', startTime: null, endTime: null }),
136
+ makeScene({ sceneId: 'b', startTime: null, endTime: null }),
137
+ makeScene({ sceneId: 'c', startTime: null, endTime: null }),
138
+ ];
139
+ const beats = deriveStoryTimeline(scenes, { maxChunks: 30, minChunkSpacing: 1 });
140
+ expect(beats.map((b) => b.chunk)).toEqual([0, 15, 29]);
141
+ });
142
+
143
+ it('enforces minChunkSpacing — beats too close are dropped', () => {
144
+ // Two scenes whose proportional chunks would land within minChunkSpacing.
145
+ const scenes: SceneView[] = [
146
+ makeScene({ sceneId: 'a', startTime: 0, endTime: 1 }),
147
+ makeScene({ sceneId: 'b', startTime: 0.1, endTime: 1 }),
148
+ makeScene({ sceneId: 'c', startTime: 100, endTime: 110 }),
149
+ ];
150
+ const beats = deriveStoryTimeline(scenes, { maxChunks: 30, minChunkSpacing: 5 });
151
+ // First pinned, second too close to first → dropped, third kept.
152
+ expect(beats.map((b) => b.label)).toEqual(['A Scene (a)', 'A Scene (c)']);
153
+ });
154
+
155
+ it('produces a TimelineBeat[] assignable to the existing beat type', () => {
156
+ const beats: TimelineBeat[] = deriveStoryTimeline([makeScene()]);
157
+ expect(beats[0]).toHaveProperty('chunk');
158
+ expect(beats[0]).toHaveProperty('prompt');
159
+ });
160
+
161
+ it('end-to-end: a t0/t1 story graph → proportional, time-carrying beats', () => {
162
+ // The production path: get_video_graph(detail=story) Scene nodes carry
163
+ // t0/t1, deriveScenes reads them, deriveStoryTimeline places proportionally
164
+ // and carries sourceStart/sourceEnd. Regression for codex R8.1 P2 — before
165
+ // the t0/t1 fix this fell back to even distribution with no source times.
166
+ const graph: VideoGraphResponse = {
167
+ traceId: 't',
168
+ videoId: 'v',
169
+ nodes: [
170
+ { id: 'n-a', label: 'Act', properties: { actId: 'a1', title: 'Act', index: 1 } },
171
+ { id: 'n-s1', label: 'Scene', properties: { sceneId: 's1', title: 'One', index: 1, t0: 0, t1: 30 } },
172
+ { id: 'n-s2', label: 'Scene', properties: { sceneId: 's2', title: 'Two', index: 2, t0: 60, t1: 90 } },
173
+ ],
174
+ edges: [
175
+ { id: 'e1', source: 'n-a', target: 'n-s1', type: 'CONTAINS', properties: {} },
176
+ { id: 'e2', source: 'n-a', target: 'n-s2', type: 'CONTAINS', properties: {} },
177
+ ],
178
+ };
179
+ const beats = deriveStoryTimeline(deriveScenes(graph), { maxChunks: 30 });
180
+ expect(beats).toHaveLength(2);
181
+ expect(beats[0]).toMatchObject({ chunk: 0, sourceStart: 0, sourceEnd: 30 });
182
+ // scene-2 starts at 60 over a 0..90 span → round(60/90 * 29) = 19 (NOT the
183
+ // even-distribution 29 the broken null-times path would have produced).
184
+ expect(beats[1]).toMatchObject({ chunk: 19, sourceStart: 60, sourceEnd: 90 });
185
+ });
186
+ });