@escapeaihq/client-core 0.6.0 → 0.7.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.
- package/README.md +27 -2
- package/dist/api.d.ts +180 -2
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +134 -0
- package/dist/api.js.map +1 -1
- package/dist/audio.d.ts +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/reactor/entityContext.d.ts +34 -0
- package/dist/reactor/entityContext.d.ts.map +1 -0
- package/dist/reactor/entityContext.js +119 -0
- package/dist/reactor/entityContext.js.map +1 -0
- package/dist/reactor/entitySearch.d.ts +71 -0
- package/dist/reactor/entitySearch.d.ts.map +1 -0
- package/dist/reactor/entitySearch.js +93 -0
- package/dist/reactor/entitySearch.js.map +1 -0
- package/dist/reactor/heliosCommandDispatcher.d.ts +98 -0
- package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -0
- package/dist/reactor/heliosCommandDispatcher.js +181 -0
- package/dist/reactor/heliosCommandDispatcher.js.map +1 -0
- package/dist/reactor/heliosTools.d.ts +156 -0
- package/dist/reactor/heliosTools.d.ts.map +1 -0
- package/dist/reactor/heliosTools.js +241 -0
- package/dist/reactor/heliosTools.js.map +1 -0
- package/dist/reactor/index.d.ts +17 -0
- package/dist/reactor/index.d.ts.map +1 -0
- package/dist/reactor/index.js +17 -0
- package/dist/reactor/index.js.map +1 -0
- package/dist/reactor/promptAddonRegistry.d.ts +37 -0
- package/dist/reactor/promptAddonRegistry.d.ts.map +1 -0
- package/dist/reactor/promptAddonRegistry.js +38 -0
- package/dist/reactor/promptAddonRegistry.js.map +1 -0
- package/dist/reactor/regenTemplate.d.ts +23 -0
- package/dist/reactor/regenTemplate.d.ts.map +1 -0
- package/dist/reactor/regenTemplate.js +103 -0
- package/dist/reactor/regenTemplate.js.map +1 -0
- package/dist/reactor/sceneEntry.d.ts +79 -0
- package/dist/reactor/sceneEntry.d.ts.map +1 -0
- package/dist/reactor/sceneEntry.js +177 -0
- package/dist/reactor/sceneEntry.js.map +1 -0
- package/dist/reactor/scenesFromEnrichment.d.ts +67 -0
- package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -0
- package/dist/reactor/scenesFromEnrichment.js +344 -0
- package/dist/reactor/scenesFromEnrichment.js.map +1 -0
- package/dist/reactor/seedImageOrchestrator.d.ts +81 -0
- package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -0
- package/dist/reactor/seedImageOrchestrator.js +79 -0
- package/dist/reactor/seedImageOrchestrator.js.map +1 -0
- package/dist/reactor/toolPromptAddon.d.ts +44 -0
- package/dist/reactor/toolPromptAddon.d.ts.map +1 -0
- package/dist/reactor/toolPromptAddon.js +129 -0
- package/dist/reactor/toolPromptAddon.js.map +1 -0
- package/dist/reactor/toolPromptAddonId.d.ts +10 -0
- package/dist/reactor/toolPromptAddonId.d.ts.map +1 -0
- package/dist/reactor/toolPromptAddonId.js +10 -0
- package/dist/reactor/toolPromptAddonId.js.map +1 -0
- package/dist/reactor/types.d.ts +149 -0
- package/dist/reactor/types.d.ts.map +1 -0
- package/dist/reactor/types.js +2 -0
- package/dist/reactor/types.js.map +1 -0
- package/dist/reactor/upsamplePrompt.d.ts +30 -0
- package/dist/reactor/upsamplePrompt.d.ts.map +1 -0
- package/dist/reactor/upsamplePrompt.js +118 -0
- package/dist/reactor/upsamplePrompt.js.map +1 -0
- package/dist/timeFormat.d.ts +28 -0
- package/dist/timeFormat.d.ts.map +1 -0
- package/dist/timeFormat.js +48 -0
- package/dist/timeFormat.js.map +1 -0
- package/dist/visemeGeometry.d.ts +15 -0
- package/dist/visemeGeometry.d.ts.map +1 -1
- package/dist/visemeGeometry.js +26 -0
- package/dist/visemeGeometry.js.map +1 -1
- package/dist/visemeScheduler.d.ts +12 -0
- package/dist/visemeScheduler.d.ts.map +1 -1
- package/dist/visemeScheduler.js +24 -0
- package/dist/visemeScheduler.js.map +1 -1
- package/dist/websocket.d.ts +51 -3
- package/dist/websocket.d.ts.map +1 -1
- package/dist/websocket.js +52 -7
- package/dist/websocket.js.map +1 -1
- package/package.json +1 -1
- package/src/__tests__/reactor/__snapshots__/regenTemplate.test.ts.snap +5 -0
- package/src/__tests__/reactor/__snapshots__/scenesFromEnrichment.test.ts.snap +34 -0
- package/src/__tests__/reactor/api-reactor.test.ts +253 -0
- package/src/__tests__/reactor/entityContext.test.ts +237 -0
- package/src/__tests__/reactor/entitySearch.test.ts +223 -0
- package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +438 -0
- package/src/__tests__/reactor/heliosTools.test.ts +164 -0
- package/src/__tests__/reactor/promptAddonRegistry.test.ts +40 -0
- package/src/__tests__/reactor/regenTemplate.test.ts +156 -0
- package/src/__tests__/reactor/sceneEntry.test.ts +342 -0
- package/src/__tests__/reactor/scenesFromEnrichment.test.ts +760 -0
- package/src/__tests__/reactor/seedImageOrchestrator.test.ts +139 -0
- package/src/__tests__/reactor/toolPromptAddon.test.ts +104 -0
- package/src/__tests__/reactor/upsamplePrompt.test.ts +245 -0
- package/src/__tests__/timeFormat.test.ts +80 -0
- package/src/__tests__/tools-wrappers.test.ts +219 -0
- package/src/__tests__/websocket.test.ts +278 -0
- package/src/api.ts +279 -2
- package/src/index.ts +2 -0
- package/src/reactor/entityContext.ts +147 -0
- package/src/reactor/entitySearch.ts +139 -0
- package/src/reactor/heliosCommandDispatcher.ts +293 -0
- package/src/reactor/heliosTools.ts +260 -0
- package/src/reactor/index.ts +17 -0
- package/src/reactor/promptAddonRegistry.ts +52 -0
- package/src/reactor/regenTemplate.ts +142 -0
- package/src/reactor/sceneEntry.ts +267 -0
- package/src/reactor/scenesFromEnrichment.ts +393 -0
- package/src/reactor/seedImageOrchestrator.ts +132 -0
- package/src/reactor/toolPromptAddon.ts +135 -0
- package/src/reactor/toolPromptAddonId.ts +9 -0
- package/src/reactor/types.ts +158 -0
- package/src/reactor/upsamplePrompt.ts +154 -0
- package/src/timeFormat.ts +57 -0
- package/src/visemeGeometry.ts +30 -0
- package/src/visemeScheduler.ts +25 -0
- package/src/websocket.ts +86 -7
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `mapEnrichmentToTimeline` — maps a Pegasus video-enrichment result into
|
|
3
|
+
* an ordered array of `TimelineBeat`s that can be scheduled onto a Helios
|
|
4
|
+
* session via `sendCommand("schedule_prompt", {prompt, chunk})`.
|
|
5
|
+
*
|
|
6
|
+
* Defensive by design. `EnrichmentRecord.result` is typed as
|
|
7
|
+
* `Record<string, unknown>` because Pegasus's output shape isn't locked
|
|
8
|
+
* at the client. We probe the shapes we've observed in practice and fall
|
|
9
|
+
* back to `[]` for anything we can't parse:
|
|
10
|
+
* - Shape A: `{scenes: [{start, end, description, title?}, ...]}` —
|
|
11
|
+
* the preferred per-scene timeline form.
|
|
12
|
+
* - Shape B: `{narrative: {acts: [{scenes: [...]}]}}` — alternate
|
|
13
|
+
* narrative-tree form. We flatten across acts in order.
|
|
14
|
+
* - Shape C: `{summary: "..."}` — degenerate; returns a single beat at
|
|
15
|
+
* chunk 0.
|
|
16
|
+
* - Anything else: `[]`.
|
|
17
|
+
*
|
|
18
|
+
* Chunk distribution rules:
|
|
19
|
+
* - When all scenes have valid `start`/`end` timings, beat chunks are
|
|
20
|
+
* scaled proportionally across `maxChunks` using each scene's `start`
|
|
21
|
+
* relative to the total video span (max scene `end`).
|
|
22
|
+
* - When scenes lack timings, beats are distributed evenly.
|
|
23
|
+
* - `minChunkSpacing` enforces a minimum chunk gap between consecutive
|
|
24
|
+
* beats — beats that would collide with the previous one are dropped.
|
|
25
|
+
* The first beat is always pinned to chunk 0.
|
|
26
|
+
* - `maxChunks` clamps the maximum chunk index. Beats whose computed
|
|
27
|
+
* chunk exceeds `maxChunks - 1` are clamped to `maxChunks - 1`, then
|
|
28
|
+
* deduplicated by the spacing rule.
|
|
29
|
+
*
|
|
30
|
+
* `styleHint` (when non-empty) is prepended to every beat's prompt with a
|
|
31
|
+
* single space separator. No trailing punctuation is added — the caller
|
|
32
|
+
* controls phrasing.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import type { EnrichmentRecord } from '../api';
|
|
36
|
+
import { ENRICHMENT_STATUS_SUCCEEDED } from '../api';
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A single beat on the director timeline. One beat = one
|
|
40
|
+
* `schedule_prompt` call at the indicated chunk.
|
|
41
|
+
*/
|
|
42
|
+
export interface TimelineBeat {
|
|
43
|
+
/** Chunk index where this prompt should fire (0-based, monotonically increasing). */
|
|
44
|
+
chunk: number;
|
|
45
|
+
/** Helios scene prompt for this beat (will be sent to `schedule_prompt`). */
|
|
46
|
+
prompt: string;
|
|
47
|
+
/** Source-video time range this beat corresponds to, for UI display. */
|
|
48
|
+
sourceStart?: number;
|
|
49
|
+
sourceEnd?: number;
|
|
50
|
+
/** Free-text label for the UI (typically the scene number or title). */
|
|
51
|
+
label?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Caller-tunable options for `mapEnrichmentToTimeline`. All have defaults
|
|
56
|
+
* picked to match the Helios prototype's chunk budget (~33 fpc, 30 chunks
|
|
57
|
+
* ≈ 16s of generated video).
|
|
58
|
+
*/
|
|
59
|
+
export interface MapEnrichmentOptions {
|
|
60
|
+
/** Total chunks to fit. Beats are distributed evenly when source timings
|
|
61
|
+
* aren't available, or scaled proportionally if they are. */
|
|
62
|
+
maxChunks?: number;
|
|
63
|
+
/** Skip beats shorter than this many chunks. Prevents the model getting
|
|
64
|
+
* whiplashed by sub-chunk scene transitions. */
|
|
65
|
+
minChunkSpacing?: number;
|
|
66
|
+
/** A free-text prefix the caller wants to inject into every beat
|
|
67
|
+
* (e.g. "cinematic 16:9, golden hour"). Empty by default. */
|
|
68
|
+
styleHint?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const DEFAULT_MAX_CHUNKS = 30;
|
|
72
|
+
const DEFAULT_MIN_CHUNK_SPACING = 2;
|
|
73
|
+
|
|
74
|
+
interface RawScene {
|
|
75
|
+
start?: number;
|
|
76
|
+
end?: number;
|
|
77
|
+
description?: string;
|
|
78
|
+
title?: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function asNumber(v: unknown): number | undefined {
|
|
82
|
+
return typeof v === 'number' && Number.isFinite(v) ? v : undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function asString(v: unknown): string | undefined {
|
|
86
|
+
return typeof v === 'string' && v.trim() ? v.trim() : undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Coerce a possible scene-shape value into our internal `RawScene`. Only
|
|
91
|
+
* accepts entries with a non-empty `description` string — other fields
|
|
92
|
+
* are optional and default to undefined.
|
|
93
|
+
*/
|
|
94
|
+
function coerceScene(raw: unknown): RawScene | undefined {
|
|
95
|
+
if (!raw || typeof raw !== 'object') return undefined;
|
|
96
|
+
const obj = raw as Record<string, unknown>;
|
|
97
|
+
const description = asString(obj.description);
|
|
98
|
+
if (!description) return undefined;
|
|
99
|
+
const out: RawScene = { description };
|
|
100
|
+
const start = asNumber(obj.start);
|
|
101
|
+
const end = asNumber(obj.end);
|
|
102
|
+
if (start !== undefined) out.start = start;
|
|
103
|
+
if (end !== undefined) out.end = end;
|
|
104
|
+
const title = asString(obj.title);
|
|
105
|
+
if (title) out.title = title;
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Coerce a production Pegasus `shots[]` entry (`{shotIndex, t0, t1,
|
|
111
|
+
* caption, ...}`) into our internal `RawScene`. Caption is mapped to
|
|
112
|
+
* `description`; `t0`/`t1` to `start`/`end`.
|
|
113
|
+
*
|
|
114
|
+
* Production enrichment writer:
|
|
115
|
+
* `services/enrichment/full_video_pegasus.py:NARRATIVE_SCHEMA`
|
|
116
|
+
*/
|
|
117
|
+
function coerceShot(raw: unknown): RawScene | undefined {
|
|
118
|
+
if (!raw || typeof raw !== 'object') return undefined;
|
|
119
|
+
const obj = raw as Record<string, unknown>;
|
|
120
|
+
const description = asString(obj.caption);
|
|
121
|
+
if (!description) return undefined;
|
|
122
|
+
const out: RawScene = { description };
|
|
123
|
+
const t0 = asNumber(obj.t0);
|
|
124
|
+
const t1 = asNumber(obj.t1);
|
|
125
|
+
if (t0 !== undefined) out.start = t0;
|
|
126
|
+
if (t1 !== undefined) out.end = t1;
|
|
127
|
+
const shotIndex = asNumber(obj.shotIndex);
|
|
128
|
+
if (shotIndex !== undefined) {
|
|
129
|
+
out.title = `Shot ${shotIndex}`;
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Parse a Pegasus act `timeRange` string into start/end seconds. The
|
|
136
|
+
* Pegasus schema doesn't pin a format, but in practice acts come back
|
|
137
|
+
* as `"0:00-1:30"`, `"1:30 - 3:00"`, or `"0-90"` (raw seconds). Returns
|
|
138
|
+
* undefined when the string doesn't parse — caller falls back to even
|
|
139
|
+
* distribution.
|
|
140
|
+
*/
|
|
141
|
+
function parseTimeRange(
|
|
142
|
+
raw: unknown,
|
|
143
|
+
): { start: number; end: number } | undefined {
|
|
144
|
+
if (typeof raw !== 'string') return undefined;
|
|
145
|
+
// Split on en-dash, em-dash, or ASCII hyphen surrounded by whitespace.
|
|
146
|
+
const parts = raw.split(/\s*[-–—]\s*/);
|
|
147
|
+
if (parts.length !== 2) return undefined;
|
|
148
|
+
const [a, b] = parts.map((s) => s.trim());
|
|
149
|
+
const start = parseTimestamp(a);
|
|
150
|
+
const end = parseTimestamp(b);
|
|
151
|
+
if (start === undefined || end === undefined) return undefined;
|
|
152
|
+
return { start, end };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function parseTimestamp(s: string): number | undefined {
|
|
156
|
+
if (!s) return undefined;
|
|
157
|
+
// mm:ss form
|
|
158
|
+
if (s.includes(':')) {
|
|
159
|
+
const [m, sec] = s.split(':');
|
|
160
|
+
const mNum = Number(m);
|
|
161
|
+
const sNum = Number(sec);
|
|
162
|
+
if (!Number.isFinite(mNum) || !Number.isFinite(sNum)) return undefined;
|
|
163
|
+
return mNum * 60 + sNum;
|
|
164
|
+
}
|
|
165
|
+
// raw seconds
|
|
166
|
+
const n = Number(s);
|
|
167
|
+
return Number.isFinite(n) ? n : undefined;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Coerce a Pegasus narrative act (`{act, timeRange, description}`) into
|
|
172
|
+
* a `RawScene`. Falls back to undefined start/end when the timeRange
|
|
173
|
+
* can't be parsed — the caller's distribution logic handles untimed
|
|
174
|
+
* scenes via even spread.
|
|
175
|
+
*
|
|
176
|
+
* Production enrichment writer:
|
|
177
|
+
* `services/enrichment/full_video_pegasus.py:NARRATIVE_SCHEMA` (acts
|
|
178
|
+
* are `{act: number, timeRange: string, description: string}` — note
|
|
179
|
+
* that acts do NOT carry nested `scenes` in production).
|
|
180
|
+
*/
|
|
181
|
+
function coerceAct(raw: unknown): RawScene | undefined {
|
|
182
|
+
if (!raw || typeof raw !== 'object') return undefined;
|
|
183
|
+
const obj = raw as Record<string, unknown>;
|
|
184
|
+
const description = asString(obj.description);
|
|
185
|
+
if (!description) return undefined;
|
|
186
|
+
const out: RawScene = { description };
|
|
187
|
+
const range = parseTimeRange(obj.timeRange);
|
|
188
|
+
if (range) {
|
|
189
|
+
out.start = range.start;
|
|
190
|
+
out.end = range.end;
|
|
191
|
+
}
|
|
192
|
+
const actNum = asNumber(obj.act);
|
|
193
|
+
if (actNum !== undefined) {
|
|
194
|
+
out.title = `Act ${actNum}`;
|
|
195
|
+
}
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Probe the Pegasus result shape and return a flat `RawScene[]` in
|
|
201
|
+
* timeline order, or `undefined` for the degenerate `{summary}` path
|
|
202
|
+
* (handled by the caller).
|
|
203
|
+
*
|
|
204
|
+
* Probe order, highest fidelity first — the first non-empty result wins:
|
|
205
|
+
* 1. `result.shots[]` — production shape, one beat per shot.
|
|
206
|
+
* Captures the highest temporal resolution; what real videos use.
|
|
207
|
+
* 2. `result.narrative.acts[]` (production acts shape — flat with
|
|
208
|
+
* `timeRange` strings, no nested scenes).
|
|
209
|
+
* 3. `result.scenes[]` — alternate explicit-scenes shape (test
|
|
210
|
+
* fixtures, hand-written enrichments).
|
|
211
|
+
* 4. `result.narrative.acts[].scenes[]` — alternate nested-scenes
|
|
212
|
+
* shape kept for back-compat.
|
|
213
|
+
*
|
|
214
|
+
* Returns `undefined` only when nothing parseable is found AND no
|
|
215
|
+
* `summary` is available — the caller's degenerate-path branch handles
|
|
216
|
+
* `{summary}` separately.
|
|
217
|
+
*/
|
|
218
|
+
function extractScenes(
|
|
219
|
+
result: Record<string, unknown>,
|
|
220
|
+
): RawScene[] | undefined {
|
|
221
|
+
// 1. Production: top-level `shots: [{shotIndex, t0, t1, caption, ...}]`.
|
|
222
|
+
const shots = result.shots;
|
|
223
|
+
if (Array.isArray(shots) && shots.length > 0) {
|
|
224
|
+
const collected = shots
|
|
225
|
+
.map(coerceShot)
|
|
226
|
+
.filter((s): s is RawScene => s !== undefined);
|
|
227
|
+
if (collected.length > 0) return collected;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// 2. Production: `narrative.acts[]` as flat `{act, timeRange, description}`.
|
|
231
|
+
const narrative = result.narrative;
|
|
232
|
+
if (narrative && typeof narrative === 'object') {
|
|
233
|
+
const acts = (narrative as Record<string, unknown>).acts;
|
|
234
|
+
if (Array.isArray(acts) && acts.length > 0) {
|
|
235
|
+
// First try the production flat-act shape.
|
|
236
|
+
const flatActs = acts
|
|
237
|
+
.map(coerceAct)
|
|
238
|
+
.filter((s): s is RawScene => s !== undefined);
|
|
239
|
+
if (flatActs.length > 0) return flatActs;
|
|
240
|
+
|
|
241
|
+
// Then back-compat nested-scenes form.
|
|
242
|
+
const nested: RawScene[] = [];
|
|
243
|
+
for (const actRaw of acts) {
|
|
244
|
+
if (!actRaw || typeof actRaw !== 'object') continue;
|
|
245
|
+
const actScenes = (actRaw as Record<string, unknown>).scenes;
|
|
246
|
+
if (!Array.isArray(actScenes)) continue;
|
|
247
|
+
for (const sceneRaw of actScenes) {
|
|
248
|
+
const scene = coerceScene(sceneRaw);
|
|
249
|
+
if (scene) nested.push(scene);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (nested.length > 0) return nested;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// 3. Alternate / test-fixture shape: explicit `scenes: [...]`.
|
|
257
|
+
const direct = result.scenes;
|
|
258
|
+
if (Array.isArray(direct)) {
|
|
259
|
+
const collected = direct
|
|
260
|
+
.map(coerceScene)
|
|
261
|
+
.filter((s): s is RawScene => s !== undefined);
|
|
262
|
+
if (collected.length > 0) return collected;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
return undefined;
|
|
266
|
+
}
|
|
267
|
+
|
|
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
|
+
export function mapEnrichmentToTimeline(
|
|
342
|
+
enrichment: EnrichmentRecord,
|
|
343
|
+
opts: MapEnrichmentOptions = {},
|
|
344
|
+
): TimelineBeat[] {
|
|
345
|
+
const maxChunks = opts.maxChunks ?? DEFAULT_MAX_CHUNKS;
|
|
346
|
+
const minChunkSpacing = opts.minChunkSpacing ?? DEFAULT_MIN_CHUNK_SPACING;
|
|
347
|
+
const styleHint = (opts.styleHint ?? '').trim();
|
|
348
|
+
|
|
349
|
+
// Guard rails — never emit beats from an unfinished or empty result.
|
|
350
|
+
if (enrichment.status !== ENRICHMENT_STATUS_SUCCEEDED) return [];
|
|
351
|
+
if (!enrichment.result) return [];
|
|
352
|
+
// Hard floor — a maxChunks of 0 or negative makes no sense; treat as no budget.
|
|
353
|
+
if (maxChunks <= 0) return [];
|
|
354
|
+
|
|
355
|
+
const result = enrichment.result;
|
|
356
|
+
const scenes = extractScenes(result);
|
|
357
|
+
|
|
358
|
+
// Degenerate shape — `{summary: "..."}` with no scenes array of any kind.
|
|
359
|
+
// Emit a single beat at chunk 0 so the user at least gets the summary
|
|
360
|
+
// on the timeline.
|
|
361
|
+
if (scenes === undefined) {
|
|
362
|
+
const summary = asString(result.summary);
|
|
363
|
+
if (summary) {
|
|
364
|
+
const prompt = styleHint ? `${styleHint} ${summary}` : summary;
|
|
365
|
+
return [
|
|
366
|
+
{
|
|
367
|
+
chunk: 0,
|
|
368
|
+
prompt,
|
|
369
|
+
label: 'Summary',
|
|
370
|
+
},
|
|
371
|
+
];
|
|
372
|
+
}
|
|
373
|
+
return [];
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
if (scenes.length === 0) return [];
|
|
377
|
+
|
|
378
|
+
const chunks = computeChunkIndices(scenes, maxChunks);
|
|
379
|
+
const kept = enforceSpacing(scenes, chunks, minChunkSpacing);
|
|
380
|
+
|
|
381
|
+
return kept.map(({ scene, chunk, index }) => {
|
|
382
|
+
const description = scene.description as string; // coerced non-empty
|
|
383
|
+
const prompt = styleHint ? `${styleHint} ${description}` : description;
|
|
384
|
+
const beat: TimelineBeat = {
|
|
385
|
+
chunk,
|
|
386
|
+
prompt,
|
|
387
|
+
label: scene.title ?? `Scene ${index + 1}`,
|
|
388
|
+
};
|
|
389
|
+
if (typeof scene.start === 'number') beat.sourceStart = scene.start;
|
|
390
|
+
if (typeof scene.end === 'number') beat.sourceEnd = scene.end;
|
|
391
|
+
return beat;
|
|
392
|
+
});
|
|
393
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure async orchestration of the "selected image → Reactor seed" flow.
|
|
3
|
+
*
|
|
4
|
+
* Lifted from three React copies (#116):
|
|
5
|
+
* - `web/app/interactive/InteractiveController.tsx` (Phase 1)
|
|
6
|
+
* - `web/app/interactive/director/useSeedImageEffect.ts` (Phase 2)
|
|
7
|
+
* - `web/app/interactive/chat/page.tsx` (Phase 3)
|
|
8
|
+
*
|
|
9
|
+
* The three copies were structurally identical:
|
|
10
|
+
* load blob from `apiClient.getSeedImageBlob`
|
|
11
|
+
* → wrap as `File` with extension derived from MIME (round 14 fix)
|
|
12
|
+
* → `reactor.uploadFile(file)` → `FileRef`
|
|
13
|
+
* → `reactor.sendCommand('set_image', { image: ref, transition })`
|
|
14
|
+
* → optionally await `waitForImageReady()` (model echoes `conditions_ready`)
|
|
15
|
+
*
|
|
16
|
+
* The pending-file queue (selected image arrived before the session was
|
|
17
|
+
* ready) lives in the React hook on top of this — it's UI-lifecycle
|
|
18
|
+
* state. The pure orchestrator just handles the "ready, go" case.
|
|
19
|
+
*
|
|
20
|
+
* Framework-free so the Vue web-app can drop the same orchestrator
|
|
21
|
+
* behind a composable.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { ApiClient } from '../api';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Minimal Reactor surface needed by the orchestrator. Same shape used
|
|
28
|
+
* by `HeliosReactorBridge` in `heliosCommandDispatcher.ts` — the
|
|
29
|
+
* dispatcher and orchestrator share the bridge by structural typing.
|
|
30
|
+
*/
|
|
31
|
+
export interface SeedImageReactorBridge {
|
|
32
|
+
sendCommand: (command: string, data: unknown) => Promise<void>;
|
|
33
|
+
uploadFile: (
|
|
34
|
+
file: File | Blob,
|
|
35
|
+
options?: { name?: string },
|
|
36
|
+
) => Promise<unknown>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ApplySeedImageOptions {
|
|
40
|
+
/** `'cut'` (default) for the first seed in a session, `'blend'` for
|
|
41
|
+
* subsequent swaps so the model smooths the visual transition.
|
|
42
|
+
* Callers decide based on whether `current_frame > 0`. */
|
|
43
|
+
transition?: 'cut' | 'blend';
|
|
44
|
+
/** Optional model-ready barrier — InteractiveController awaits
|
|
45
|
+
* `conditions_ready` so the UI doesn't let the user submit a prompt
|
|
46
|
+
* before Helios has processed the new image. Other consumers can
|
|
47
|
+
* omit it. */
|
|
48
|
+
waitForImageReady?: () => Promise<void>;
|
|
49
|
+
/** Cancellation signal threaded into `getSeedImageBlob`. The
|
|
50
|
+
* Reactor SDK has no signal surface today, so `uploadFile` and
|
|
51
|
+
* `sendCommand` are NOT abortable — but the pre-upload portion
|
|
52
|
+
* (the S3 fetch via our proxy) is the slow part, so this still
|
|
53
|
+
* catches the bulk of unmount races. */
|
|
54
|
+
signal?: AbortSignal;
|
|
55
|
+
/** Override the upload filename stem. The extension is always
|
|
56
|
+
* derived from the blob MIME (so PNG character images get `.png`,
|
|
57
|
+
* not whatever extension the caller guessed). Defaults to `seed`,
|
|
58
|
+
* producing `seed.<ext>`. Matches `loadSeedImageFile`'s option
|
|
59
|
+
* name and semantics. */
|
|
60
|
+
filenameStem?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Derive a filename extension from a blob MIME type. PNG character
|
|
64
|
+
* images shouldn't masquerade as JPEG (round 14 fix). Falls back to
|
|
65
|
+
* `jpg` for unknown / missing MIME. Normalises `jpeg → jpg` because
|
|
66
|
+
* every prior seed-image call site used the `.jpg` extension and we
|
|
67
|
+
* shouldn't change wire shape just because the MIME spells out
|
|
68
|
+
* "jpeg". */
|
|
69
|
+
function extensionForMime(mime: string | undefined): string {
|
|
70
|
+
const base = (mime || 'image/jpeg').split('/')[1];
|
|
71
|
+
const raw = base?.split(/[;+]/)[0] || 'jpg';
|
|
72
|
+
return raw === 'jpeg' ? 'jpg' : raw;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Fetch a seed image by id and wrap it as a `File` ready to hand to
|
|
77
|
+
* `reactor.uploadFile`. Useful on its own for the pending-queue path —
|
|
78
|
+
* the React hook stashes this `File` and flushes it via
|
|
79
|
+
* `sendSeedFileToReactor` once the session is ready.
|
|
80
|
+
*/
|
|
81
|
+
export async function loadSeedImageFile(
|
|
82
|
+
imageId: string,
|
|
83
|
+
apiClient: ApiClient,
|
|
84
|
+
options: { signal?: AbortSignal; filenameStem?: string } = {},
|
|
85
|
+
): Promise<File> {
|
|
86
|
+
const blob = await apiClient.getSeedImageBlob(imageId, {
|
|
87
|
+
signal: options.signal,
|
|
88
|
+
});
|
|
89
|
+
const mime = blob.type || 'image/jpeg';
|
|
90
|
+
const ext = extensionForMime(mime);
|
|
91
|
+
const stem = options.filenameStem ?? 'seed';
|
|
92
|
+
return new File([blob], `${stem}.${ext}`, { type: mime });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Upload an already-loaded seed file and apply it to the live Reactor
|
|
97
|
+
* session. Splits from `loadSeedImageFile` so the React hook can queue
|
|
98
|
+
* a file ahead of the `ready` transition and flush it later.
|
|
99
|
+
*/
|
|
100
|
+
export async function sendSeedFileToReactor(
|
|
101
|
+
file: File,
|
|
102
|
+
reactor: SeedImageReactorBridge,
|
|
103
|
+
options: Omit<ApplySeedImageOptions, 'signal' | 'filenameStem'> = {},
|
|
104
|
+
): Promise<void> {
|
|
105
|
+
const transition = options.transition ?? 'cut';
|
|
106
|
+
const ref = await reactor.uploadFile(file);
|
|
107
|
+
await reactor.sendCommand('set_image', { image: ref, transition });
|
|
108
|
+
if (options.waitForImageReady) await options.waitForImageReady();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Convenience wrapper: load + upload + set_image in one call. Throws
|
|
113
|
+
* `AbortError` if the signal aborts during the fetch. Use the split
|
|
114
|
+
* primitives (`loadSeedImageFile` + `sendSeedFileToReactor`) when the
|
|
115
|
+
* caller needs to queue pre-`ready`.
|
|
116
|
+
*/
|
|
117
|
+
export async function loadAndApplySeedImage(
|
|
118
|
+
imageId: string,
|
|
119
|
+
apiClient: ApiClient,
|
|
120
|
+
reactor: SeedImageReactorBridge,
|
|
121
|
+
options: ApplySeedImageOptions = {},
|
|
122
|
+
): Promise<void> {
|
|
123
|
+
const file = await loadSeedImageFile(imageId, apiClient, {
|
|
124
|
+
signal: options.signal,
|
|
125
|
+
filenameStem: options.filenameStem,
|
|
126
|
+
});
|
|
127
|
+
if (options.signal?.aborted) return;
|
|
128
|
+
await sendSeedFileToReactor(file, reactor, {
|
|
129
|
+
transition: options.transition,
|
|
130
|
+
waitForImageReady: options.waitForImageReady,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* System-prompt addon that teaches a chat model to emit Helios
|
|
3
|
+
* world-steering markers.
|
|
4
|
+
*
|
|
5
|
+
* Phase 3 hooks this addon up via `PersonaConfig.prompt_addon_ids`: when
|
|
6
|
+
* a persona declares `prompt_addon_ids: ['helios-world-steering']`, the
|
|
7
|
+
* browser-side `/interactive/chat` page looks up the addon text via
|
|
8
|
+
* `getHeliosSteeringAddonText()` and concatenates it onto the persona's
|
|
9
|
+
* `custom_system_prompt` before sending each chat turn via the WS
|
|
10
|
+
* `systemPrompt` field.
|
|
11
|
+
*
|
|
12
|
+
* The backend has no awareness of the addon ID's semantics — the field
|
|
13
|
+
* is just metadata on `PersonaConfig`. See
|
|
14
|
+
* `shared/persona_addon_ids.py` for the matching Python constant.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { HELIOS_WORLD_STEERING_ADDON_ID } from './toolPromptAddonId';
|
|
18
|
+
|
|
19
|
+
export { HELIOS_WORLD_STEERING_ADDON_ID } from './toolPromptAddonId';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Marker the addon uses to verify idempotent reapplication. The build
|
|
23
|
+
* function looks for this string in the base prompt before appending,
|
|
24
|
+
* so calling `buildHeliosSteeringSystemPrompt(buildHeliosSteeringSystemPrompt(p))`
|
|
25
|
+
* returns the same value as a single application. Choose something
|
|
26
|
+
* unique enough that a normal persona prompt would never include it
|
|
27
|
+
* verbatim.
|
|
28
|
+
*/
|
|
29
|
+
const ADDON_SENTINEL = '<!-- helios-world-steering-addon:v1 -->';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Stable, model-friendly addon text that teaches the marker grammar
|
|
33
|
+
* and the rules around when to emit each marker. Kept as a function
|
|
34
|
+
* (not a const) so callers don't accidentally share-and-mutate the
|
|
35
|
+
* underlying string.
|
|
36
|
+
*
|
|
37
|
+
* Update the version sentinel inside the function if the addon
|
|
38
|
+
* semantics change in a way the model needs to relearn — `prompt_addon_ids`
|
|
39
|
+
* is a stable identifier, but cached upstream chat history may have
|
|
40
|
+
* trained the model against the OLD prose. The sentinel doubles as a
|
|
41
|
+
* "did the LLM see the new version?" diagnostic.
|
|
42
|
+
*/
|
|
43
|
+
export function getHeliosSteeringAddonText(): string {
|
|
44
|
+
return [
|
|
45
|
+
ADDON_SENTINEL,
|
|
46
|
+
'## World Steering Capability',
|
|
47
|
+
'',
|
|
48
|
+
'This conversation is running alongside a live Helios video stream that ' +
|
|
49
|
+
"you can steer directly. When the user asks you to change the visible " +
|
|
50
|
+
'world — scene changes, atmospheric shifts, character swaps, pausing, ' +
|
|
51
|
+
'resetting — emit ONE of the following bracket-style markers at the ' +
|
|
52
|
+
'VERY END of your response, after your natural-language reply.',
|
|
53
|
+
'',
|
|
54
|
+
'### Markers',
|
|
55
|
+
'',
|
|
56
|
+
'- `[SET_SCENE: "<80-120 word Helios-quality scene prompt>"]` — change ' +
|
|
57
|
+
'the live world to a new scene. The prompt MUST follow the Helios ' +
|
|
58
|
+
"prompt-guide style: name the subject, the environment, the lighting, " +
|
|
59
|
+
'the camera framing (wide / medium / medium close-up / close-up), and ' +
|
|
60
|
+
'the mood. Target 80-120 words. Example argument: "wide cinematic ' +
|
|
61
|
+
'shot, a man in a red coat walks across a snowy bridge at dusk, soft ' +
|
|
62
|
+
"golden hour light streaming through wrought-iron railings, medium " +
|
|
63
|
+
'tracking shot following him from the right, his breath visible in the ' +
|
|
64
|
+
'cold air, distant city lights glowing behind him, mood: contemplative ' +
|
|
65
|
+
'and quietly hopeful, 35mm film grain, cinematic depth of field."',
|
|
66
|
+
'- `[SWAP_SEED: "<entity name>"]` — replace the active seed image ' +
|
|
67
|
+
'with a different entity from the current video. The entity name must ' +
|
|
68
|
+
'match one of the entities the user has shown you (matching is ' +
|
|
69
|
+
"case-insensitive). If you're not sure of the name, don't emit this " +
|
|
70
|
+
'marker — ask the user to clarify instead.',
|
|
71
|
+
'- `[PAUSE_WORLD]` — pause the live stream at the current frame. Use ' +
|
|
72
|
+
'when the user wants to freeze the action.',
|
|
73
|
+
'- `[RESUME_WORLD]` — resume a paused stream.',
|
|
74
|
+
'- `[RESET_WORLD]` — reset the stream to frame 0 and clear pending ' +
|
|
75
|
+
'prompts. Use only when the user explicitly asks to start over.',
|
|
76
|
+
'',
|
|
77
|
+
'### Critical Rules',
|
|
78
|
+
'',
|
|
79
|
+
'1. Emit AT MOST ONE marker per turn. If the user asks for a sequence ' +
|
|
80
|
+
'(e.g. "pause then change the scene"), pick the first action and tell ' +
|
|
81
|
+
'them you\'ll do the next one when they ask.',
|
|
82
|
+
'2. Markers go at the END of your response, after a blank line, never ' +
|
|
83
|
+
'mixed into the middle of prose.',
|
|
84
|
+
'3. SET_SCENE prompts must be detailed and ground in the established ' +
|
|
85
|
+
'world. Bland three-word prompts produce bland output.',
|
|
86
|
+
'4. For SET_SCENE, weave the existing entity / character continuity into ' +
|
|
87
|
+
"the prompt so identity is preserved across the cut. Don't invent a " +
|
|
88
|
+
'brand-new protagonist mid-scene unless the user explicitly asks for ' +
|
|
89
|
+
'one.',
|
|
90
|
+
'5. If the user asks something you can answer in words alone — describe ' +
|
|
91
|
+
"the world, recall a past moment, plan a beat — DON'T emit a marker. " +
|
|
92
|
+
'Markers are for actions, not exposition.',
|
|
93
|
+
'',
|
|
94
|
+
'### Example',
|
|
95
|
+
'',
|
|
96
|
+
'User: "Make it start raining and feel a bit lonelier."',
|
|
97
|
+
'',
|
|
98
|
+
'Assistant: Pulling the warmth out of the light and adding a slow grey ' +
|
|
99
|
+
'rain — give it a beat to settle in.',
|
|
100
|
+
'',
|
|
101
|
+
'[SET_SCENE: "wide cinematic shot, a man in a long coat stands alone on ' +
|
|
102
|
+
'a deserted cobblestone bridge in a slow grey downpour, single sodium ' +
|
|
103
|
+
"streetlamp casting a cone of amber light onto wet stone, distant city " +
|
|
104
|
+
'reflections rippling in puddles, medium tracking shot pulling back ' +
|
|
105
|
+
'slightly, his breath fogging in the cold air, mood: melancholy and ' +
|
|
106
|
+
'introspective, 35mm film grain, shallow depth of field, muted blue and ' +
|
|
107
|
+
'amber color palette, soft falling rain catching the lamp light."]',
|
|
108
|
+
'',
|
|
109
|
+
].join('\n');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Concatenate the Helios steering addon onto an arbitrary base system
|
|
114
|
+
* prompt. Idempotent: a prompt that already contains the addon sentinel
|
|
115
|
+
* is returned unchanged.
|
|
116
|
+
*
|
|
117
|
+
* An empty base prompt is allowed — the addon stands on its own and
|
|
118
|
+
* works without a persona backstory (the test suite covers this).
|
|
119
|
+
*
|
|
120
|
+
* @param baseSystemPrompt - persona's `custom_system_prompt` (may be
|
|
121
|
+
* empty string or whitespace).
|
|
122
|
+
* @returns concatenated prompt: `<base>\n\n<addon>` when the base is
|
|
123
|
+
* non-empty, just `<addon>` otherwise.
|
|
124
|
+
*/
|
|
125
|
+
export function buildHeliosSteeringSystemPrompt(
|
|
126
|
+
baseSystemPrompt: string,
|
|
127
|
+
): string {
|
|
128
|
+
if (baseSystemPrompt && baseSystemPrompt.includes(ADDON_SENTINEL)) {
|
|
129
|
+
return baseSystemPrompt;
|
|
130
|
+
}
|
|
131
|
+
const addon = getHeliosSteeringAddonText();
|
|
132
|
+
const trimmed = (baseSystemPrompt ?? '').trim();
|
|
133
|
+
if (!trimmed) return addon;
|
|
134
|
+
return `${trimmed}\n\n${addon}`;
|
|
135
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stable string ID for the Helios world-steering prompt addon.
|
|
3
|
+
*
|
|
4
|
+
* Lives in its own module so consumers that only need the ID (e.g. UI
|
|
5
|
+
* code that checks whether a persona has the addon enabled) don't pull
|
|
6
|
+
* in the entire addon-text module. Match the Python constant in
|
|
7
|
+
* `shared/persona_addon_ids.py` exactly.
|
|
8
|
+
*/
|
|
9
|
+
export const HELIOS_WORLD_STEERING_ADDON_ID = 'helios-world-steering';
|