@escapeaihq/client-core 0.6.1 → 0.8.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 (109) hide show
  1. package/README.md +28 -3
  2. package/dist/api.d.ts +102 -2
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/api.js +92 -0
  5. package/dist/api.js.map +1 -1
  6. package/dist/audio.d.ts +1 -1
  7. package/dist/index.d.ts +2 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/reactor/entityContext.d.ts +34 -0
  12. package/dist/reactor/entityContext.d.ts.map +1 -0
  13. package/dist/reactor/entityContext.js +119 -0
  14. package/dist/reactor/entityContext.js.map +1 -0
  15. package/dist/reactor/entitySearch.d.ts +71 -0
  16. package/dist/reactor/entitySearch.d.ts.map +1 -0
  17. package/dist/reactor/entitySearch.js +93 -0
  18. package/dist/reactor/entitySearch.js.map +1 -0
  19. package/dist/reactor/heliosCommandDispatcher.d.ts +98 -0
  20. package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -0
  21. package/dist/reactor/heliosCommandDispatcher.js +181 -0
  22. package/dist/reactor/heliosCommandDispatcher.js.map +1 -0
  23. package/dist/reactor/heliosTools.d.ts +156 -0
  24. package/dist/reactor/heliosTools.d.ts.map +1 -0
  25. package/dist/reactor/heliosTools.js +241 -0
  26. package/dist/reactor/heliosTools.js.map +1 -0
  27. package/dist/reactor/index.d.ts +17 -0
  28. package/dist/reactor/index.d.ts.map +1 -0
  29. package/dist/reactor/index.js +17 -0
  30. package/dist/reactor/index.js.map +1 -0
  31. package/dist/reactor/promptAddonRegistry.d.ts +37 -0
  32. package/dist/reactor/promptAddonRegistry.d.ts.map +1 -0
  33. package/dist/reactor/promptAddonRegistry.js +38 -0
  34. package/dist/reactor/promptAddonRegistry.js.map +1 -0
  35. package/dist/reactor/regenTemplate.d.ts +23 -0
  36. package/dist/reactor/regenTemplate.d.ts.map +1 -0
  37. package/dist/reactor/regenTemplate.js +103 -0
  38. package/dist/reactor/regenTemplate.js.map +1 -0
  39. package/dist/reactor/sceneEntry.d.ts +79 -0
  40. package/dist/reactor/sceneEntry.d.ts.map +1 -0
  41. package/dist/reactor/sceneEntry.js +177 -0
  42. package/dist/reactor/sceneEntry.js.map +1 -0
  43. package/dist/reactor/scenesFromEnrichment.d.ts +67 -0
  44. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -0
  45. package/dist/reactor/scenesFromEnrichment.js +344 -0
  46. package/dist/reactor/scenesFromEnrichment.js.map +1 -0
  47. package/dist/reactor/seedImageOrchestrator.d.ts +81 -0
  48. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -0
  49. package/dist/reactor/seedImageOrchestrator.js +79 -0
  50. package/dist/reactor/seedImageOrchestrator.js.map +1 -0
  51. package/dist/reactor/toolPromptAddon.d.ts +44 -0
  52. package/dist/reactor/toolPromptAddon.d.ts.map +1 -0
  53. package/dist/reactor/toolPromptAddon.js +129 -0
  54. package/dist/reactor/toolPromptAddon.js.map +1 -0
  55. package/dist/reactor/toolPromptAddonId.d.ts +10 -0
  56. package/dist/reactor/toolPromptAddonId.d.ts.map +1 -0
  57. package/dist/reactor/toolPromptAddonId.js +10 -0
  58. package/dist/reactor/toolPromptAddonId.js.map +1 -0
  59. package/dist/reactor/types.d.ts +149 -0
  60. package/dist/reactor/types.d.ts.map +1 -0
  61. package/dist/reactor/types.js +2 -0
  62. package/dist/reactor/types.js.map +1 -0
  63. package/dist/reactor/upsamplePrompt.d.ts +30 -0
  64. package/dist/reactor/upsamplePrompt.d.ts.map +1 -0
  65. package/dist/reactor/upsamplePrompt.js +118 -0
  66. package/dist/reactor/upsamplePrompt.js.map +1 -0
  67. package/dist/timeFormat.d.ts +28 -0
  68. package/dist/timeFormat.d.ts.map +1 -0
  69. package/dist/timeFormat.js +48 -0
  70. package/dist/timeFormat.js.map +1 -0
  71. package/dist/websocket.d.ts +31 -0
  72. package/dist/websocket.d.ts.map +1 -1
  73. package/dist/websocket.js +20 -0
  74. package/dist/websocket.js.map +1 -1
  75. package/package.json +1 -1
  76. package/src/__tests__/reactor/__snapshots__/regenTemplate.test.ts.snap +5 -0
  77. package/src/__tests__/reactor/__snapshots__/scenesFromEnrichment.test.ts.snap +34 -0
  78. package/src/__tests__/reactor/api-reactor.test.ts +253 -0
  79. package/src/__tests__/reactor/entityContext.test.ts +237 -0
  80. package/src/__tests__/reactor/entitySearch.test.ts +223 -0
  81. package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +438 -0
  82. package/src/__tests__/reactor/heliosTools.test.ts +164 -0
  83. package/src/__tests__/reactor/promptAddonRegistry.test.ts +40 -0
  84. package/src/__tests__/reactor/regenTemplate.test.ts +156 -0
  85. package/src/__tests__/reactor/sceneEntry.test.ts +342 -0
  86. package/src/__tests__/reactor/scenesFromEnrichment.test.ts +760 -0
  87. package/src/__tests__/reactor/seedImageOrchestrator.test.ts +139 -0
  88. package/src/__tests__/reactor/toolPromptAddon.test.ts +104 -0
  89. package/src/__tests__/reactor/upsamplePrompt.test.ts +245 -0
  90. package/src/__tests__/timeFormat.test.ts +80 -0
  91. package/src/__tests__/websocket.test.ts +75 -0
  92. package/src/api.ts +170 -2
  93. package/src/index.ts +2 -0
  94. package/src/reactor/entityContext.ts +147 -0
  95. package/src/reactor/entitySearch.ts +139 -0
  96. package/src/reactor/heliosCommandDispatcher.ts +293 -0
  97. package/src/reactor/heliosTools.ts +260 -0
  98. package/src/reactor/index.ts +17 -0
  99. package/src/reactor/promptAddonRegistry.ts +52 -0
  100. package/src/reactor/regenTemplate.ts +142 -0
  101. package/src/reactor/sceneEntry.ts +267 -0
  102. package/src/reactor/scenesFromEnrichment.ts +393 -0
  103. package/src/reactor/seedImageOrchestrator.ts +132 -0
  104. package/src/reactor/toolPromptAddon.ts +135 -0
  105. package/src/reactor/toolPromptAddonId.ts +9 -0
  106. package/src/reactor/types.ts +158 -0
  107. package/src/reactor/upsamplePrompt.ts +154 -0
  108. package/src/timeFormat.ts +57 -0
  109. package/src/websocket.ts +42 -0
@@ -0,0 +1,142 @@
1
+ /**
2
+ * `buildRegenPrompt` — pure, deterministic prompt builder for the
3
+ * optional Gemini Flash Image regen step.
4
+ *
5
+ * Encodes the locked guarantees (16:9, identity preservation when
6
+ * requested, entity grounding) plus structured creative choices
7
+ * (framing, lighting, style) plus the user's free-form creative
8
+ * direction. The output is a single string suitable for
9
+ * `services/image_regeneration`'s `prompt` field.
10
+ *
11
+ * **Determinism matters.** The output of this function is shown
12
+ * verbatim in the RegenForm's live preview — a hidden non-determinism
13
+ * (e.g. `Date.now()` interpolation, randomization) would make the
14
+ * preview lie about the prompt that's actually generated.
15
+ *
16
+ * Throws `Error("customStyle required when styleFamily is 'custom'")`
17
+ * when the invariant is violated. The TS type can't express this
18
+ * cleanly without a discriminated union, so it's checked at runtime
19
+ * (the consuming UI also validates pre-submit).
20
+ */
21
+
22
+ import type { RegenTemplateInput } from './types';
23
+
24
+ const FRAMING_PHRASES: Record<RegenTemplateInput['framing'], string> = {
25
+ wide: 'wide shot capturing the full environment',
26
+ medium: 'medium shot framing the full figure',
27
+ 'medium-close-up': 'medium close-up framing the face and upper body',
28
+ 'close-up': 'close-up emphasising fine facial detail',
29
+ };
30
+
31
+ const LIGHTING_PHRASES: Record<RegenTemplateInput['lighting'], string> = {
32
+ cinematic:
33
+ 'cinematic lighting with deep shadows, sculpted key light, and a soft cool fill',
34
+ 'golden-hour':
35
+ 'warm golden-hour light, low sun raking across the subject, long soft shadows',
36
+ noir:
37
+ 'high-contrast noir lighting, hard key light from a single source, dramatic shadow falloff',
38
+ natural:
39
+ 'soft natural daylight, gentle directional shadows, balanced ambient fill',
40
+ studio:
41
+ 'clean three-point studio lighting, even exposure, controlled highlights',
42
+ };
43
+
44
+ const STYLE_PHRASES: Record<
45
+ Exclude<RegenTemplateInput['styleFamily'], 'custom'>,
46
+ string
47
+ > = {
48
+ photoreal:
49
+ 'photorealistic style, naturalistic textures and skin, lifelike depth of field',
50
+ anime:
51
+ 'modern cinematic anime style, clean line art, painterly cel-shaded colour, expressive eyes',
52
+ watercolor:
53
+ 'soft watercolour painting style, visible pigment edges, gentle paper texture',
54
+ pixar:
55
+ 'stylised Pixar-quality 3D animation, polished subsurface scattering, warm rendered look',
56
+ 'film-35mm':
57
+ '35mm film stock aesthetic, subtle grain, organic colour science, slight halation',
58
+ };
59
+
60
+ export function buildRegenPrompt(input: RegenTemplateInput): string {
61
+ if (input.styleFamily === 'custom') {
62
+ const custom = (input.customStyle ?? '').trim();
63
+ if (!custom) {
64
+ throw new Error("customStyle required when styleFamily is 'custom'");
65
+ }
66
+ }
67
+
68
+ const stylePhrase =
69
+ input.styleFamily === 'custom'
70
+ ? (input.customStyle ?? '').trim()
71
+ : STYLE_PHRASES[input.styleFamily];
72
+
73
+ const framingPhrase = FRAMING_PHRASES[input.framing];
74
+ const lightingPhrase = LIGHTING_PHRASES[input.lighting];
75
+
76
+ const segments: string[] = [];
77
+
78
+ // Opener — re-frame or reinterpret based on identity-preservation toggle.
79
+ // The 16:9 aspect ratio is always called out explicitly because the
80
+ // downstream Helios reference-image check rejects non-16:9 inputs.
81
+ if (input.preserveIdentity) {
82
+ segments.push(
83
+ `Reframe ${input.entity.name} as a wide 16:9 cinematic shot while preserving their distinctive features, proportions, and identity from the reference image.`,
84
+ );
85
+ } else {
86
+ segments.push(
87
+ `Reinterpret ${input.entity.name} as a wide 16:9 cinematic shot, taking creative liberties with appearance while keeping them recognisably the same character.`,
88
+ );
89
+ }
90
+
91
+ // 16:9 guarantee — restated as a hard requirement so the model
92
+ // doesn't drift to vertical or square outputs.
93
+ segments.push('16:9 framing required — the output must be a landscape composition.');
94
+
95
+ // Framing keyword.
96
+ segments.push(`Use a ${framingPhrase}.`);
97
+
98
+ // Lighting keyword.
99
+ segments.push(`Light the scene with ${lightingPhrase}.`);
100
+
101
+ // Style descriptor.
102
+ segments.push(`Render in ${stylePhrase}.`);
103
+
104
+ // Entity grounding — name + scene context if available. Trim the
105
+ // sceneContext and ensure it ends with terminal punctuation so the
106
+ // next segment (typically the persona backstory) doesn't run on into
107
+ // the previous sentence.
108
+ if (input.entity.sceneContext) {
109
+ const scene = input.entity.sceneContext.trim();
110
+ const punctuated = /[.!?]$/.test(scene) ? scene : `${scene}.`;
111
+ segments.push(
112
+ `Character context: ${input.entity.name} is grounded in the source scene — ${punctuated}`,
113
+ );
114
+ }
115
+
116
+ // Persona backstory — character grounding when provided. Same
117
+ // trailing-period treatment so creative direction (or any later
118
+ // segment) starts cleanly.
119
+ if (input.persona) {
120
+ const backstory = input.persona.backstory.trim();
121
+ const punctuated = /[.!?]$/.test(backstory) ? backstory : `${backstory}.`;
122
+ segments.push(
123
+ `Persona backstory for ${input.persona.name}: ${punctuated}`,
124
+ );
125
+ }
126
+
127
+ // Structured overrides — only included when populated.
128
+ if (input.clothingOverride && input.clothingOverride.trim()) {
129
+ segments.push(`Wardrobe: ${input.clothingOverride.trim()}.`);
130
+ }
131
+ if (input.poseOverride && input.poseOverride.trim()) {
132
+ segments.push(`Pose / action: ${input.poseOverride.trim()}.`);
133
+ }
134
+
135
+ // Creative direction — appended verbatim, last, so the human voice
136
+ // sits closest to the model's most-recent-tokens attention bias.
137
+ if (input.creativeDirection && input.creativeDirection.trim()) {
138
+ segments.push(input.creativeDirection.trim());
139
+ }
140
+
141
+ return segments.join(' ');
142
+ }
@@ -0,0 +1,267 @@
1
+ /**
2
+ * "Step Into Scene" orchestrator: turns a (videoId, timestamp) into a
3
+ * fully-bootstrapped Helios world seeded with the extracted frame and
4
+ * primed with a Pegasus-grounded scene prompt.
5
+ *
6
+ * Framework-agnostic. Consumed by:
7
+ * - seer-agent React `/watch/[videoId]` page (PR 1 + PR 2 of #200)
8
+ * - Vue web-app's existing video watching surface (post-tag, in web-app repo)
9
+ *
10
+ * The orchestrator is two pure functions split at the seam between
11
+ * "network work that produces a payload" (prepareSceneEntry) and
12
+ * "issue Reactor commands against a live session" (bootstrapSceneInReactor).
13
+ * Splitting at the seam lets the React modal render a "Materializing…"
14
+ * state while the payload is being prepared, *before* the ReactorProvider
15
+ * has connected — the bootstrap call then runs once the SDK reports ready.
16
+ */
17
+
18
+ import type {
19
+ ApiClient,
20
+ EnrichmentRecord,
21
+ ImageRecord,
22
+ PersonaConfig,
23
+ } from '../api';
24
+ import {
25
+ aggregateEntityContext,
26
+ aggregatePersonaContext,
27
+ } from './entityContext';
28
+ import {
29
+ loadSeedImageFile,
30
+ sendSeedFileToReactor,
31
+ type SeedImageReactorBridge,
32
+ } from './seedImageOrchestrator';
33
+
34
+ export interface SceneEntryInput {
35
+ /** The Seer video the user is watching. */
36
+ videoId: string;
37
+ /** Playhead position at the moment Step Into Scene was clicked. */
38
+ timestamp: number;
39
+ /** Caption for the bracketing shot, if enrichment is loaded. Feeds the
40
+ * upsample as the user-supplied prompt — Pegasus's narrative summary
41
+ * of THIS moment is a stronger upsample input than the entity name
42
+ * alone. Falls back to a generic seed when absent. */
43
+ shotCaption?: string | null;
44
+ /** Most-recent SUCCEEDED Pegasus enrichment for the video, used to
45
+ * derive `sceneContext` inside the entity grounding. */
46
+ enrichment: EnrichmentRecord | null;
47
+ /** Active persona on the watch page. `null` means "no persona
48
+ * grounding" — the upsample runs with entity-only context. */
49
+ persona: PersonaConfig | null;
50
+ apiClient: ApiClient;
51
+ signal?: AbortSignal;
52
+ }
53
+
54
+ export interface SceneEntryPayload {
55
+ /** The captured frame, wrapped as a `File` ready for `reactor.uploadFile`. */
56
+ frameFile: File;
57
+ /** Helios-quality scene paragraph from the upsample call. */
58
+ upsampledPrompt: string;
59
+ /** Pass-through for callers that want to render "from shot N at 0:42"
60
+ * in the modal header. */
61
+ sourceTimestamp: number;
62
+ /** Tracked `ImageRecord` id for the extracted frame. Lets the modal
63
+ * (or any consumer) deep-link to `/images/{imageId}` for inspection
64
+ * or wire a "View in gallery" affordance. */
65
+ imageId: string;
66
+ }
67
+
68
+ /** Fallback shot caption when enrichment is absent or the playhead is
69
+ * outside any shot. Matches the cadence of the upsample's training
70
+ * prompts so the LLM doesn't reject a one-word input. */
71
+ const FALLBACK_SHOT_CAPTION = 'Step into this moment';
72
+
73
+ /** Sentinel entity name for the `ExtractImageRequest`. The backend
74
+ * endpoint requires this field but uses `timestamp` for the actual
75
+ * frame extraction when both are provided — `entity` survives only as
76
+ * a label on the resulting ImageRecord. */
77
+ const SCENE_ENTITY_LABEL = 'scene';
78
+
79
+ /**
80
+ * Run the extract + upsample + frame-fetch pipeline. Resolves with a
81
+ * `SceneEntryPayload` ready to feed into `bootstrapSceneInReactor`. The
82
+ * `signal` is plumbed through both API calls AND the frame-blob fetch
83
+ * so an unmount mid-pipeline cancels cleanly.
84
+ */
85
+ export async function prepareSceneEntry(
86
+ input: SceneEntryInput,
87
+ ): Promise<SceneEntryPayload> {
88
+ const {
89
+ videoId,
90
+ timestamp,
91
+ shotCaption,
92
+ enrichment,
93
+ persona,
94
+ apiClient,
95
+ signal,
96
+ } = input;
97
+
98
+ // Step 1 — extract the frame server-side. The endpoint uses ffmpeg
99
+ // against the source video's presigned URL and persists an
100
+ // ImageRecord that shows up in the user's gallery (free bookmark).
101
+ const extract = await apiClient.extractImage(
102
+ { videoId, entity: SCENE_ENTITY_LABEL, timestamp },
103
+ { signal },
104
+ );
105
+
106
+ // The seed-image proxy is the only browser-safe path to the frame
107
+ // bytes (the raw S3 bucket has no CORS rules). If best-effort
108
+ // persistence failed and we got back an extract response with no
109
+ // imageId, we can't seed Reactor at all — fail loudly here rather
110
+ // than later, where the user has already seen "Materializing…".
111
+ if (!extract.imageId) {
112
+ throw new Error(
113
+ 'extract-image did not return an imageId — the ImageRecord write failed and the frame is unreachable from the browser.',
114
+ );
115
+ }
116
+
117
+ // Step 2 — fan out the upsample call, blob fetch (through the
118
+ // same-origin seed-image proxy), and the entity-grounding build in
119
+ // parallel. Upsample uses text-only grounding (Pegasus scene context
120
+ // is richer than single-frame visual would be); the blob proxy and
121
+ // upsample are independent so running them serially would add ~1.5s
122
+ // of round-trip latency for no benefit.
123
+ const entityContext = aggregateEntityContext({
124
+ imageRecord: synthesizeImageRecord(videoId, extract),
125
+ enrichment: enrichment ?? undefined,
126
+ });
127
+ const personaContext = persona ? aggregatePersonaContext(persona) : null;
128
+ const promptInput = shotCaption?.trim() || FALLBACK_SHOT_CAPTION;
129
+
130
+ const [upsample, frameFile] = await Promise.all([
131
+ apiClient.upsampleReactorPrompt(
132
+ {
133
+ prompt: promptInput,
134
+ entityContext,
135
+ ...(personaContext ? { personaContext } : {}),
136
+ },
137
+ { signal },
138
+ ),
139
+ loadSeedImageFile(extract.imageId, apiClient, {
140
+ signal,
141
+ filenameStem: 'scene',
142
+ }),
143
+ ]);
144
+
145
+ return {
146
+ frameFile,
147
+ upsampledPrompt: upsample.upsampledPrompt,
148
+ sourceTimestamp: extract.sourceTimestamp,
149
+ imageId: extract.imageId,
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Apply the prepared payload to a live Reactor session. Composes
155
+ * `sendSeedFileToReactor` (from #199's orchestrator) with the
156
+ * `set_prompt` + `start` commands that turn a seeded session into a
157
+ * generating world.
158
+ *
159
+ * Use `transition: 'cut'` because this is always the first seed of a
160
+ * new session (closing the modal disconnects, so re-opens are fresh).
161
+ *
162
+ * **Abort behaviour.** The Reactor SDK's `uploadFile` and `sendCommand`
163
+ * don't accept an `AbortSignal` today, so we can't actually *cancel*
164
+ * an in-flight upload. Instead we race each phase against the signal:
165
+ * if the user closes the modal mid-upload the awaiting promise
166
+ * rejects with `AbortError` immediately, leaving the bridge to finish
167
+ * (or fail when `<ReactorProvider>` unmounts and tears down the
168
+ * session). Without the race the modal would appear frozen for the
169
+ * full upload duration even though the user has clicked "Back".
170
+ */
171
+ export async function bootstrapSceneInReactor(
172
+ payload: SceneEntryPayload,
173
+ bridge: SeedImageReactorBridge,
174
+ options: { signal?: AbortSignal } = {},
175
+ ): Promise<void> {
176
+ // Abort is an *expected* terminal state for this flow (user clicked
177
+ // Back to video, modal unmounted, etc.). Internally we use exceptions
178
+ // for fast unwind, but the public contract is "returns void on
179
+ // success or abort, throws only on a real Reactor failure". Callers
180
+ // already check `signal.aborted` to decide what to render — they
181
+ // shouldn't have to ALSO distinguish AbortError from real errors.
182
+ try {
183
+ if (options.signal?.aborted) return;
184
+ await raceWithAbort(
185
+ sendSeedFileToReactor(payload.frameFile, bridge, { transition: 'cut' }),
186
+ options.signal,
187
+ );
188
+ if (options.signal?.aborted) return;
189
+ await raceWithAbort(
190
+ bridge.sendCommand('set_prompt', { prompt: payload.upsampledPrompt }),
191
+ options.signal,
192
+ );
193
+ if (options.signal?.aborted) return;
194
+ await raceWithAbort(bridge.sendCommand('start', {}), options.signal);
195
+ } catch (err) {
196
+ if (isAbortError(err)) return;
197
+ throw err;
198
+ }
199
+ }
200
+
201
+ function isAbortError(err: unknown): boolean {
202
+ if (err instanceof DOMException && err.name === 'AbortError') return true;
203
+ return err instanceof Error && err.name === 'AbortError';
204
+ }
205
+
206
+ /**
207
+ * Race a promise against an `AbortSignal`. When the signal fires, the
208
+ * returned promise rejects with `AbortError` even if the underlying
209
+ * promise hasn't resolved — useful when the underlying operation
210
+ * (Reactor SDK calls in this case) can't be cancelled directly. The
211
+ * underlying operation still runs to completion in the background;
212
+ * the race only lets the caller stop awaiting it.
213
+ */
214
+ function raceWithAbort<T>(
215
+ promise: Promise<T>,
216
+ signal: AbortSignal | undefined,
217
+ ): Promise<T> {
218
+ if (!signal) return promise;
219
+ if (signal.aborted) {
220
+ return Promise.reject(new DOMException('Aborted', 'AbortError'));
221
+ }
222
+ return new Promise<T>((resolve, reject) => {
223
+ const onAbort = () => {
224
+ reject(new DOMException('Aborted', 'AbortError'));
225
+ };
226
+ signal.addEventListener('abort', onAbort, { once: true });
227
+ promise.then(
228
+ value => {
229
+ signal.removeEventListener('abort', onAbort);
230
+ resolve(value);
231
+ },
232
+ err => {
233
+ signal.removeEventListener('abort', onAbort);
234
+ reject(err);
235
+ },
236
+ );
237
+ });
238
+ }
239
+
240
+ /**
241
+ * Build a minimal `ImageRecord` from an `ExtractImageResponse` so the
242
+ * existing `aggregateEntityContext` helper can compute scene grounding
243
+ * without us having to round-trip a `listImages` call for the new
244
+ * record's ID. Only `source_timestamp` and `source_video_id` are read
245
+ * by the aggregator; the other fields are filled with safe defaults so
246
+ * the resulting object satisfies the TypeScript shape.
247
+ */
248
+ function synthesizeImageRecord(
249
+ videoId: string,
250
+ extract: { imageS3Key: string; sourceTimestamp: number; entity: string },
251
+ ): ImageRecord {
252
+ const now = new Date().toISOString();
253
+ return {
254
+ image_id: '',
255
+ user_id: '',
256
+ s3_key: extract.imageS3Key,
257
+ s3_bucket: '',
258
+ category: 'extracted',
259
+ content_type: 'image/png',
260
+ source_video_id: videoId,
261
+ source_entity: extract.entity,
262
+ source_timestamp: extract.sourceTimestamp,
263
+ created_at: now,
264
+ updated_at: now,
265
+ };
266
+ }
267
+