@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
@@ -34,6 +34,12 @@
34
34
 
35
35
  import type { EnrichmentRecord } from '../api';
36
36
  import { ENRICHMENT_STATUS_SUCCEEDED } from '../api';
37
+ import {
38
+ DEFAULT_MAX_CHUNKS,
39
+ DEFAULT_MIN_CHUNK_SPACING,
40
+ computeChunkIndices,
41
+ enforceSpacing,
42
+ } from './chunkDistribution';
37
43
 
38
44
  /**
39
45
  * A single beat on the director timeline. One beat = one
@@ -68,8 +74,10 @@ export interface MapEnrichmentOptions {
68
74
  styleHint?: string;
69
75
  }
70
76
 
71
- const DEFAULT_MAX_CHUNKS = 30;
72
- const DEFAULT_MIN_CHUNK_SPACING = 2;
77
+ // DEFAULT_MAX_CHUNKS / DEFAULT_MIN_CHUNK_SPACING and the chunk-distribution
78
+ // helpers (computeChunkIndices / enforceSpacing) now live in
79
+ // `./chunkDistribution` so `deriveStoryTimeline` shares the SAME algorithm (R8.1
80
+ // DRY — one place can break). They are imported above.
73
81
 
74
82
  interface RawScene {
75
83
  start?: number;
@@ -265,79 +273,6 @@ function extractScenes(
265
273
  return undefined;
266
274
  }
267
275
 
268
- /**
269
- * Compute the chunk index for each scene. When all scenes have valid
270
- * `start` timings and the time span is positive, scale proportionally.
271
- * Otherwise distribute evenly across `[0, maxChunks)`.
272
- */
273
- function computeChunkIndices(
274
- scenes: RawScene[],
275
- maxChunks: number,
276
- ): number[] {
277
- if (scenes.length === 0) return [];
278
- if (scenes.length === 1) return [0];
279
-
280
- const allTimed = scenes.every(
281
- (s) => typeof s.start === 'number' && typeof s.end === 'number',
282
- );
283
-
284
- // If timings are present and meaningful (positive span), scale.
285
- if (allTimed) {
286
- const starts = scenes.map((s) => s.start as number);
287
- const ends = scenes.map((s) => s.end as number);
288
- const minStart = Math.min(...starts);
289
- const maxEnd = Math.max(...ends);
290
- const span = maxEnd - minStart;
291
- if (span > 0) {
292
- return scenes.map((s, i) => {
293
- if (i === 0) return 0;
294
- const start = s.start as number;
295
- const frac = (start - minStart) / span;
296
- const chunk = Math.round(frac * (maxChunks - 1));
297
- // Clamp into [0, maxChunks - 1].
298
- return Math.max(0, Math.min(maxChunks - 1, chunk));
299
- });
300
- }
301
- }
302
-
303
- // Fallback — even distribution. First beat at 0, last beat at
304
- // maxChunks - 1, with linear spacing between.
305
- return scenes.map((_, i) => {
306
- if (i === 0) return 0;
307
- const frac = i / (scenes.length - 1);
308
- return Math.round(frac * (maxChunks - 1));
309
- });
310
- }
311
-
312
- /**
313
- * Apply `minChunkSpacing`. Walks in order, always keeps the first beat
314
- * (forced to chunk 0), drops any beat whose chunk is closer than
315
- * `minChunkSpacing` to the previously-kept beat.
316
- */
317
- function enforceSpacing(
318
- scenes: RawScene[],
319
- chunks: number[],
320
- minSpacing: number,
321
- ): { scene: RawScene; chunk: number; index: number }[] {
322
- const kept: { scene: RawScene; chunk: number; index: number }[] = [];
323
- for (let i = 0; i < scenes.length; i++) {
324
- const scene = scenes[i];
325
- let chunk = chunks[i];
326
- if (kept.length === 0) {
327
- // First beat is always pinned to chunk 0.
328
- chunk = 0;
329
- kept.push({ scene, chunk, index: i });
330
- continue;
331
- }
332
- const prev = kept[kept.length - 1].chunk;
333
- if (chunk - prev < minSpacing) {
334
- continue;
335
- }
336
- kept.push({ scene, chunk, index: i });
337
- }
338
- return kept;
339
- }
340
-
341
276
  export function mapEnrichmentToTimeline(
342
277
  enrichment: EnrichmentRecord,
343
278
  opts: MapEnrichmentOptions = {},
@@ -378,7 +313,7 @@ export function mapEnrichmentToTimeline(
378
313
  const chunks = computeChunkIndices(scenes, maxChunks);
379
314
  const kept = enforceSpacing(scenes, chunks, minChunkSpacing);
380
315
 
381
- return kept.map(({ scene, chunk, index }) => {
316
+ return kept.map(({ item: scene, chunk, index }) => {
382
317
  const description = scene.description as string; // coerced non-empty
383
318
  const prompt = styleHint ? `${styleHint} ${description}` : description;
384
319
  const beat: TimelineBeat = {
@@ -7,17 +7,14 @@
7
7
  * cheap reference. The command channel only carries the reference, so
8
8
  * image size is decoupled from the 64KB-per-message data channel cap.
9
9
  *
10
- * Authoritative docs:
11
- * - `ai_docs/reference/reactor/helios-overview.md:217` — set_image
12
- * parameter table
10
+ * Authoritative docs (anchors are stable; line numbers rot):
11
+ * - `ai_docs/reference/reactor/helios-schema.md` `#set_image` — set_image
12
+ * parameter table and behavior notes
13
13
  * - `ai_docs/reference/reactor/file-uploads.md:33-54` — canonical
14
14
  * uploadFile + set_image pattern
15
- * - `ai_docs/reference/reactor/image-to-video-player.md:94` — full
16
- * image-to-video example
17
- *
18
- * The shorter `ai_docs/reference/reactor/llms.txt:558` summary line
19
- * lists `image_b64: string` for this command — that is misleading /
20
- * out of date; the detailed reference pages above are authoritative.
15
+ * - `ai_docs/reference/reactor/helios-schema.md` `#complete-example-image-to-video`
16
+ * — full image-to-video flow (now uses atomic `set_conditioning` to avoid
17
+ * a first-chunk race; `set_image`-then-`set_prompt` remains valid)
21
18
  *
22
19
  * Lifted from three React copies (#116):
23
20
  * - `web/app/interactive/InteractiveController.tsx` (Phase 1)
@@ -263,7 +260,7 @@ export async function sendSeedFileToReactor(
263
260
  options: Omit<ApplySeedImageOptions, 'signal' | 'filenameStem'> = {},
264
261
  ): Promise<void> {
265
262
  // Canonical Helios image-to-video pattern (file-uploads.md:33,
266
- // image-to-video-player.md:94): uploadFile → FileRef → set_image
263
+ // helios-schema.md#set_image): uploadFile → FileRef → set_image
267
264
  // with `{ image: ref, transition? }`. Bytes go via HTTP to Reactor's
268
265
  // object store; the command channel carries only the ref.
269
266
  //
@@ -276,9 +273,11 @@ export async function sendSeedFileToReactor(
276
273
  //
277
274
  // **Do not wait for an ack here.** The standalone Python spike
278
275
  // (`scripts/spikes/helios_set_image_spike.py`) confirmed that the
279
- // success event is `image_accepted` (NOT `image_set` as
280
- // helios-overview.md:441 claims — those docs are wrong) and it
281
- // only fires AFTER `start` is issued, during chunk 0 generation.
276
+ // success event is `image_accepted` (see `helios-schema.md` Messages
277
+ // table) and it only fires AFTER `start` is issued, during chunk 0
278
+ // generation. (Older docs called this `image_set`; upstream has since
279
+ // corrected this — keep this comment as the historical reason we
280
+ // don't gate on a pre-start ack.)
282
281
  // Any wait between set_image and the subsequent set_prompt+start
283
282
  // therefore deadlocks for `waitForImageReady`-timeout milliseconds
284
283
  // and produces no value. Match the docs sample's back-to-back
@@ -0,0 +1,127 @@
1
+ /**
2
+ * storyTimeline — maps the COLLAPSED story projection (`SceneView[]`, the R5
3
+ * `detail=story` view shaped by `deriveScenes`) into an ordered array of
4
+ * `TimelineBeat`s ready to schedule onto a world model (Platform Restructure
5
+ * R8.1).
6
+ *
7
+ * This is the STORY-GRAPH-driven sibling of `mapEnrichmentToTimeline` (which
8
+ * maps raw Pegasus enrichment shapes). Both share ONE chunk-distribution
9
+ * algorithm (`./chunkDistribution`) so the chunk math can only break in one
10
+ * place. `mapEnrichmentToTimeline` stays the labelled FALLBACK for stories with
11
+ * no graph scenes (degenerate Pegasus-only videos) — R8.1 does not delete it.
12
+ *
13
+ * One beat per `SceneView`, ordered by the scene's natural `deriveScenes`
14
+ * ordering (act.index, then scene.index — already applied by the projection).
15
+ * The beat `prompt` is composed from the scene `summary` + featured-character
16
+ * names + location label; `sourceStart`/`sourceEnd` from `startTime`/`endTime`;
17
+ * `label` from the scene `title`, tagged with the source scene id so a Timeline
18
+ * UI (and a PlayCanvas renderer) can mark story-derived vs operator-added beats.
19
+ */
20
+
21
+ import type { SceneView } from '../storyGraph';
22
+ import type { TimelineBeat } from './scenesFromEnrichment';
23
+ import {
24
+ DEFAULT_MAX_CHUNKS,
25
+ DEFAULT_MIN_CHUNK_SPACING,
26
+ computeChunkIndices,
27
+ enforceSpacing,
28
+ type TimedItem,
29
+ } from './chunkDistribution';
30
+
31
+ /**
32
+ * Caller-tunable options for `deriveStoryTimeline`. Mirrors
33
+ * `MapEnrichmentOptions` so both mappers share one tunable surface. Defaults
34
+ * pull from the DIRECTOR adapter's chunk budget (R1) at the call site — pass
35
+ * `maxChunks` explicitly from the adapter; the constants here are the shared
36
+ * fallback, not a re-declared page literal.
37
+ */
38
+ export interface StoryTimelineOptions {
39
+ /** Total chunks to fit. Beats distributed proportionally by scene timing. */
40
+ maxChunks?: number;
41
+ /** Skip beats closer than this many chunks to the previous kept beat. */
42
+ minChunkSpacing?: number;
43
+ /** Free-text prefix injected into every beat prompt (e.g. a style hint). */
44
+ styleHint?: string;
45
+ }
46
+
47
+ /**
48
+ * Prefix the scene-id provenance tag onto a beat label so a Timeline UI can
49
+ * distinguish story-derived beats from operator-added ones. Kept as a single
50
+ * helper so the tag format has one source.
51
+ */
52
+ function labelFor(scene: SceneView): string {
53
+ const title = scene.title.trim() || scene.sceneId;
54
+ return `${title} (${scene.sceneId})`;
55
+ }
56
+
57
+ /**
58
+ * Compose the beat prompt from the collapsed scene: summary first, then the
59
+ * featured-character names and the location label appended as grounding
60
+ * context. A `styleHint` (when non-empty) is prepended with a single space and
61
+ * no trailing punctuation — the IDENTICAL rule `mapEnrichmentToTimeline` uses.
62
+ */
63
+ function promptFor(scene: SceneView, styleHint: string): string {
64
+ const parts: string[] = [];
65
+
66
+ const summary = (scene.summary ?? '').trim();
67
+ if (summary) parts.push(summary);
68
+ else if (scene.title.trim()) parts.push(scene.title.trim());
69
+
70
+ const names = scene.featuredCharacters.map((c) => c.name.trim()).filter((n) => n.length > 0);
71
+ if (names.length > 0) parts.push(`Featuring ${names.join(', ')}.`);
72
+
73
+ const location = scene.location?.name.trim();
74
+ if (location) parts.push(`Location: ${location}.`);
75
+
76
+ const body = parts.join(' ');
77
+ return styleHint ? `${styleHint} ${body}` : body;
78
+ }
79
+
80
+ /**
81
+ * Map a collapsed story projection (`SceneView[]`) to scheduling beats.
82
+ *
83
+ * Defensive contract (matches `mapEnrichmentToTimeline`): an empty `scenes`
84
+ * array — or a non-positive `maxChunks` budget — returns `[]` (never throws).
85
+ */
86
+ export function deriveStoryTimeline(
87
+ scenes: readonly SceneView[],
88
+ options: StoryTimelineOptions = {},
89
+ ): TimelineBeat[] {
90
+ const maxChunks = options.maxChunks ?? DEFAULT_MAX_CHUNKS;
91
+ const minChunkSpacing = options.minChunkSpacing ?? DEFAULT_MIN_CHUNK_SPACING;
92
+ const styleHint = (options.styleHint ?? '').trim();
93
+
94
+ if (scenes.length === 0) return [];
95
+ // Hard floor — a maxChunks of 0 or negative makes no sense; treat as no budget.
96
+ if (maxChunks <= 0) return [];
97
+
98
+ // Project to the minimal timing shape the distribution rules read. A scene
99
+ // with a null startTime/endTime is left untimed (undefined) so the mapper
100
+ // falls back to even distribution when not every scene is timed — matching
101
+ // `mapEnrichmentToTimeline`'s behaviour.
102
+ const timed: TimedItem[] = scenes.map((s) => {
103
+ const item: TimedItem = {};
104
+ if (s.startTime !== null) item.start = s.startTime;
105
+ if (s.endTime !== null) item.end = s.endTime;
106
+ return item;
107
+ });
108
+
109
+ const chunks = computeChunkIndices(timed, maxChunks);
110
+ const kept = enforceSpacing(
111
+ scenes.map((scene, i) => ({ scene, ...timed[i] })),
112
+ chunks,
113
+ minChunkSpacing,
114
+ );
115
+
116
+ return kept.map(({ item, chunk }) => {
117
+ const { scene } = item;
118
+ const beat: TimelineBeat = {
119
+ chunk,
120
+ prompt: promptFor(scene, styleHint),
121
+ label: labelFor(scene),
122
+ };
123
+ if (scene.startTime !== null) beat.sourceStart = scene.startTime;
124
+ if (scene.endTime !== null) beat.sourceEnd = scene.endTime;
125
+ return beat;
126
+ });
127
+ }
@@ -0,0 +1,298 @@
1
+ /**
2
+ * storyGraph — pure, framework-agnostic projections over a get_video_graph
3
+ * payload (VideoGraphResponse), shared by the studio Scene inspector, Cast
4
+ * grid, AND the Director story-timeline mapper (Platform Restructure R8.1) so
5
+ * those read-only surfaces never drift.
6
+ *
7
+ * Composition-only: reads the EXISTING `GET /api/v1/tools/graph/{videoId}`
8
+ * payload and projects it into scene/cast view-models. No new endpoints, no
9
+ * mutations, no new graph machinery — only filtering + edge traversal.
10
+ *
11
+ * Edge direction is treated AGNOSTICALLY: get_video_graph emits real Cypher
12
+ * direction (source = startNode, target = endNode), but the structural
13
+ * relationships (CONTAINS/INCLUDES/FEATURES/SET_IN/RELATES_TO/ON_ARC) are
14
+ * matched by EITHER endpoint, so a future direction change in the writer cannot
15
+ * silently break these read-only views.
16
+ *
17
+ * Lifted verbatim from `web/app/components/studio/storyGraph.ts` (R8.1): the
18
+ * web module is now a thin re-export shim. Do NOT re-add logic to the web file.
19
+ */
20
+ import type { GraphNode, GraphEdge, VideoGraphResponse } from './api';
21
+ import {
22
+ STUDIO_NODE_LABELS,
23
+ STUDIO_EDGE_TYPES,
24
+ STUDIO_NODE_PROPERTIES,
25
+ STUDIO_CHARACTER_TYPE,
26
+ } from './graphSchema';
27
+
28
+ // Note: character detection reads `Entity.type` directly against the studio
29
+ // read-surface constants (single-sourced in `graphSchema.ts`), so this pure
30
+ // module takes NO dependency on the heavy cytoscape-backed graph editor
31
+ // (`GraphCanvas`) — keeping the helper testable in isolation. The match is
32
+ // identical to the editor's `entityTypeOf(node) === 'character'`.
33
+
34
+ // ---------- view models ----------
35
+
36
+ export interface ShotView {
37
+ shotId: string;
38
+ caption: string;
39
+ index: number;
40
+ startTime: number | null;
41
+ endTime: number | null;
42
+ }
43
+
44
+ export interface CharacterRef {
45
+ nodeId: string;
46
+ entityId: string;
47
+ name: string;
48
+ }
49
+
50
+ export interface LocationRef {
51
+ nodeId: string;
52
+ entityId: string;
53
+ name: string;
54
+ }
55
+
56
+ export interface SceneView {
57
+ nodeId: string;
58
+ sceneId: string;
59
+ title: string;
60
+ index: number;
61
+ startTime: number | null;
62
+ endTime: number | null;
63
+ summary: string | null;
64
+ actNodeId: string | null;
65
+ actTitle: string | null;
66
+ actIndex: number;
67
+ featuredCharacters: CharacterRef[];
68
+ location: LocationRef | null;
69
+ shots: ShotView[];
70
+ }
71
+
72
+ export interface ArcView {
73
+ arcId: string;
74
+ title: string;
75
+ description: string | null;
76
+ index: number;
77
+ }
78
+
79
+ export interface CharacterView {
80
+ nodeId: string;
81
+ entityId: string;
82
+ name: string;
83
+ aliases: string[];
84
+ sceneIds: string[];
85
+ arcs: ArcView[];
86
+ relatedCharacterIds: string[];
87
+ }
88
+
89
+ // ---------- property readers (constant-driven, no literals) ----------
90
+
91
+ function str(node: GraphNode, key: string): string | null {
92
+ const v = node.properties[key];
93
+ return typeof v === 'string' ? v : null;
94
+ }
95
+
96
+ function num(node: GraphNode, key: string): number | null {
97
+ const v = node.properties[key];
98
+ if (typeof v === 'number') return v;
99
+ if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) {
100
+ return Number(v);
101
+ }
102
+ return null;
103
+ }
104
+
105
+ function strList(node: GraphNode, key: string): string[] {
106
+ const v = node.properties[key];
107
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
108
+ }
109
+
110
+ /** First numeric value across `keys` (in order), or null. */
111
+ function numCoalesce(node: GraphNode, keys: readonly string[]): number | null {
112
+ for (const key of keys) {
113
+ const v = num(node, key);
114
+ if (v !== null) return v;
115
+ }
116
+ return null;
117
+ }
118
+
119
+ function isCharacter(node: GraphNode): boolean {
120
+ return (
121
+ node.label === STUDIO_NODE_LABELS.ENTITY &&
122
+ str(node, STUDIO_NODE_PROPERTIES.ENTITY_TYPE) === STUDIO_CHARACTER_TYPE
123
+ );
124
+ }
125
+
126
+ function isLocation(node: GraphNode): boolean {
127
+ // A location entity is any non-character Entity reached by a SET_IN edge; we
128
+ // do not over-constrain on the exact `type` value (location vs place) — the
129
+ // SET_IN edge is the authoritative signal.
130
+ return node.label === STUDIO_NODE_LABELS.ENTITY && !isCharacter(node);
131
+ }
132
+
133
+ function businessIdOf(node: GraphNode, key: string): string {
134
+ return str(node, key) ?? node.id;
135
+ }
136
+
137
+ // ---------- traversal helpers ----------
138
+
139
+ interface GraphIndex {
140
+ byId: Map<string, GraphNode>;
141
+ edges: GraphEdge[];
142
+ }
143
+
144
+ function indexGraph(graph: VideoGraphResponse): GraphIndex {
145
+ const byId = new Map<string, GraphNode>();
146
+ for (const node of graph.nodes) byId.set(node.id, node);
147
+ return { byId, edges: graph.edges };
148
+ }
149
+
150
+ /**
151
+ * For a node id and a set of edge types, return the OTHER endpoint nodes of
152
+ * every matching edge, regardless of which side `nodeId` sits on.
153
+ */
154
+ function neighbours(
155
+ index: GraphIndex,
156
+ nodeId: string,
157
+ edgeTypes: readonly string[],
158
+ ): GraphNode[] {
159
+ const types = new Set(edgeTypes);
160
+ const out: GraphNode[] = [];
161
+ const seen = new Set<string>();
162
+ for (const edge of index.edges) {
163
+ if (!types.has(edge.type)) continue;
164
+ let otherId: string | null = null;
165
+ if (edge.source === nodeId) otherId = edge.target;
166
+ else if (edge.target === nodeId) otherId = edge.source;
167
+ if (otherId === null || seen.has(otherId)) continue;
168
+ const other = index.byId.get(otherId);
169
+ if (other) {
170
+ seen.add(otherId);
171
+ out.push(other);
172
+ }
173
+ }
174
+ return out;
175
+ }
176
+
177
+ /** Act→Scene and Scene→Shot containment is CONTAINS or INCLUDES. */
178
+ const CONTAINMENT_EDGES = [STUDIO_EDGE_TYPES.CONTAINS, STUDIO_EDGE_TYPES.INCLUDES] as const;
179
+
180
+ // ---------- scene derivation ----------
181
+
182
+ export function deriveScenes(graph: VideoGraphResponse): SceneView[] {
183
+ const index = indexGraph(graph);
184
+ const P = STUDIO_NODE_PROPERTIES;
185
+ const sceneNodes = graph.nodes.filter((n) => n.label === STUDIO_NODE_LABELS.SCENE);
186
+
187
+ const scenes: SceneView[] = sceneNodes.map((scene) => {
188
+ // Parent act (containment edge whose other endpoint is an Act node).
189
+ const actNode =
190
+ neighbours(index, scene.id, CONTAINMENT_EDGES).find(
191
+ (n) => n.label === STUDIO_NODE_LABELS.ACT,
192
+ ) ?? null;
193
+
194
+ // Shots in this scene (containment edges to Shot nodes), sorted by index.
195
+ const shots: ShotView[] = neighbours(index, scene.id, CONTAINMENT_EDGES)
196
+ .filter((n) => n.label === STUDIO_NODE_LABELS.SHOT)
197
+ .map((sh) => ({
198
+ shotId: businessIdOf(sh, P.SHOT_ID),
199
+ caption: str(sh, P.CAPTION) ?? '',
200
+ index: num(sh, P.INDEX) ?? 0,
201
+ startTime: num(sh, P.START_TIME),
202
+ endTime: num(sh, P.END_TIME),
203
+ }))
204
+ .sort((a, b) => a.index - b.index);
205
+
206
+ // Featured characters (FEATURES edges to character entities).
207
+ const featuredCharacters: CharacterRef[] = neighbours(index, scene.id, [
208
+ STUDIO_EDGE_TYPES.FEATURES,
209
+ ])
210
+ .filter(isCharacter)
211
+ .map((c) => ({
212
+ nodeId: c.id,
213
+ entityId: businessIdOf(c, P.ENTITY_ID),
214
+ name: str(c, P.NAME) ?? businessIdOf(c, P.ENTITY_ID),
215
+ }))
216
+ .sort((a, b) => a.name.localeCompare(b.name));
217
+
218
+ // Location (SET_IN edge to a non-character entity).
219
+ const locNode = neighbours(index, scene.id, [STUDIO_EDGE_TYPES.SET_IN]).find(isLocation);
220
+ const location: LocationRef | null = locNode
221
+ ? {
222
+ nodeId: locNode.id,
223
+ entityId: businessIdOf(locNode, P.ENTITY_ID),
224
+ name: str(locNode, P.NAME) ?? businessIdOf(locNode, P.ENTITY_ID),
225
+ }
226
+ : null;
227
+
228
+ return {
229
+ nodeId: scene.id,
230
+ sceneId: businessIdOf(scene, P.SCENE_ID),
231
+ title: str(scene, P.TITLE) ?? businessIdOf(scene, P.SCENE_ID),
232
+ index: num(scene, P.INDEX) ?? 0,
233
+ // Scene nodes store their time bounds as t0/t1 (MERGE_SCENE — the
234
+ // get_video_graph `detail=story` reader annotates `t0`/`t1`, NOT
235
+ // start/endTime; Shots use start/endTime). Read t0/t1 first, falling back
236
+ // to start/endTime defensively. Without this, every production SceneView
237
+ // had null times and deriveStoryTimeline (R8.1) lost proportional chunk
238
+ // placement (codex R8.1 P2).
239
+ startTime: numCoalesce(scene, [P.T0, P.START_TIME]),
240
+ endTime: numCoalesce(scene, [P.T1, P.END_TIME]),
241
+ summary: str(scene, P.SUMMARY),
242
+ actNodeId: actNode?.id ?? null,
243
+ actTitle: actNode ? str(actNode, P.TITLE) : null,
244
+ actIndex: actNode ? (num(actNode, P.INDEX) ?? 0) : Number.MAX_SAFE_INTEGER,
245
+ featuredCharacters,
246
+ location,
247
+ shots,
248
+ };
249
+ });
250
+
251
+ // Sort by act.index, then scene.index. Scenes with no act sort last.
252
+ scenes.sort((a, b) => a.actIndex - b.actIndex || a.index - b.index);
253
+ return scenes;
254
+ }
255
+
256
+ // ---------- cast derivation ----------
257
+
258
+ export function deriveCast(graph: VideoGraphResponse): CharacterView[] {
259
+ const index = indexGraph(graph);
260
+ const P = STUDIO_NODE_PROPERTIES;
261
+ const characterNodes = graph.nodes.filter(isCharacter);
262
+
263
+ const cast: CharacterView[] = characterNodes.map((char) => {
264
+ // Scenes this character is featured in (FEATURES edges to Scene nodes).
265
+ const sceneIds = neighbours(index, char.id, [STUDIO_EDGE_TYPES.FEATURES])
266
+ .filter((n) => n.label === STUDIO_NODE_LABELS.SCENE)
267
+ .map((s) => businessIdOf(s, P.SCENE_ID));
268
+
269
+ // Character arcs (ON_ARC edges to CharacterArc nodes), sorted by index.
270
+ const arcs: ArcView[] = neighbours(index, char.id, [STUDIO_EDGE_TYPES.ON_ARC])
271
+ .filter((n) => n.label === STUDIO_NODE_LABELS.CHARACTER_ARC)
272
+ .map((a) => ({
273
+ arcId: businessIdOf(a, P.ARC_ID),
274
+ title: str(a, P.TITLE) ?? businessIdOf(a, P.ARC_ID),
275
+ description: str(a, P.DESCRIPTION) ?? str(a, P.SUMMARY),
276
+ index: num(a, P.INDEX) ?? 0,
277
+ }))
278
+ .sort((x, y) => x.index - y.index);
279
+
280
+ // Related characters (RELATES_TO edges to other character entities).
281
+ const relatedCharacterIds = neighbours(index, char.id, [STUDIO_EDGE_TYPES.RELATES_TO])
282
+ .filter(isCharacter)
283
+ .map((c) => businessIdOf(c, P.ENTITY_ID));
284
+
285
+ return {
286
+ nodeId: char.id,
287
+ entityId: businessIdOf(char, P.ENTITY_ID),
288
+ name: str(char, P.NAME) ?? businessIdOf(char, P.ENTITY_ID),
289
+ aliases: strList(char, P.ALIASES),
290
+ sceneIds,
291
+ arcs,
292
+ relatedCharacterIds,
293
+ };
294
+ });
295
+
296
+ cast.sort((a, b) => a.name.localeCompare(b.name));
297
+ return cast;
298
+ }