@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,293 @@
1
+ /**
2
+ * Translate parsed Helios commands into `reactor.sendCommand` calls.
3
+ *
4
+ * Pure framework-agnostic helper: no React imports, no DOM globals
5
+ * beyond `Blob` / `File` (which Vue, Node 22+, and React all expose).
6
+ * Originally lived in `web/app/interactive/chat/heliosToolHandler.ts`
7
+ * for Phase 3; lifted to client-core so the Vue web-app and any other
8
+ * consumer can reuse the same dispatcher.
9
+ *
10
+ * Failure policy: every command is wrapped in a try/catch. A bad
11
+ * command (e.g. SWAP_SEED for an entity the user never showed) is
12
+ * logged and skipped — never propagates back to the chat loop. The
13
+ * chat session must keep working even if the world stream is
14
+ * unreachable or the entity catalogue doesn't match.
15
+ */
16
+
17
+ import type { ApiClient, ImageRecord } from '../api';
18
+ import { findEntityImageBySeedName } from './entitySearch';
19
+ import type { HeliosCommand } from './heliosTools';
20
+ import {
21
+ loadSeedImageFile,
22
+ sendSeedFileToReactor,
23
+ } from './seedImageOrchestrator';
24
+ import type { EntityContext, PersonaContext } from './types';
25
+
26
+ /**
27
+ * Minimal Reactor surface the dispatcher needs. We accept a structural
28
+ * type rather than the JS-SDK's concrete `useReactorStore` shapes so
29
+ * this stays trivially mockable AND so client-core doesn't take a
30
+ * runtime dependency on `@reactor-team/js-sdk`.
31
+ *
32
+ * `uploadFile`'s return is typed as `unknown` here — the dispatcher
33
+ * never inspects it, only threads it back into `sendCommand('set_image',
34
+ * { image: ref })`. Callers using the real SDK assign their
35
+ * `Promise<FileRef>` to this slot via structural subtyping.
36
+ */
37
+ export interface HeliosReactorBridge {
38
+ sendCommand: (command: string, data: unknown) => Promise<void>;
39
+ uploadFile: (
40
+ file: File | Blob,
41
+ options?: { name?: string },
42
+ ) => Promise<unknown>;
43
+ }
44
+
45
+ /**
46
+ * Inputs the dispatcher needs beyond the command itself: an
47
+ * authenticated API client (for SWAP_SEED entity lookups and seed-image
48
+ * bytes), the Reactor bridge (sendCommand / uploadFile), the active
49
+ * video so SWAP_SEED knows where to search, and the live `currentChunk`
50
+ * from the Reactor state so SET_SCENE schedules the prompt at chunk+2
51
+ * (the same convention `InteractiveController.tsx` uses).
52
+ */
53
+ export interface HeliosToolContext {
54
+ apiClient: ApiClient;
55
+ reactor: HeliosReactorBridge;
56
+ /** Currently selected source video — required for SWAP_SEED catalog
57
+ * lookups. SET_SCENE doesn't need it. */
58
+ videoId: string | null;
59
+ /** Live `current_chunk` from the Reactor state. Used to schedule
60
+ * SET_SCENE prompts at `currentChunk + 2`. Treated as 0 (= first
61
+ * prompt) when undefined. */
62
+ currentChunk?: number;
63
+ /** Whether the page has already issued a `start` command in this
64
+ * session. SET_SCENE at chunk 0 needs to know: if false, fire
65
+ * set_prompt + start (this is the first prompt); if true, fire
66
+ * set_prompt only (re-emitting start while running is undocumented
67
+ * Reactor behavior — defensive to skip it). Page clears this on
68
+ * RESET_WORLD. */
69
+ hasStarted?: boolean;
70
+ /** Optional context to thread into upsample requests for SET_SCENE. */
71
+ entityContext?: EntityContext;
72
+ personaContext?: PersonaContext;
73
+ /** Active seed image id — passed to upsample so it can ground the
74
+ * prompt on a thumbnail. Optional. */
75
+ imageId?: string;
76
+ /** Optional UI-feedback callback. The dispatcher calls this with a
77
+ * short human-readable message when a command fails in a way the
78
+ * user would benefit from seeing (e.g. SWAP_SEED entity not found).
79
+ * Silent (console-only) when omitted. */
80
+ onUserWarning?: (message: string) => void;
81
+ /** Optional callback fired after a successful SWAP_SEED so the page
82
+ * can keep its selection refs in sync with the live Helios stream.
83
+ * Without this, subsequent SET_SCENE upsample calls still ground
84
+ * on the OLD entity's context. */
85
+ onSeedSwapped?: (image: ImageRecord) => void;
86
+ /** Optional `AbortSignal` that cancels in-flight API requests when
87
+ * the caller no longer cares about the result (page unmount, new
88
+ * user message arriving mid-dispatch, etc.). Threaded into
89
+ * `upsampleReactorPrompt` (SET_SCENE) and `getSeedImageBlob`
90
+ * (SWAP_SEED). Reactor `sendCommand` / `uploadFile` are NOT aborted
91
+ * — the SDK has no signal surface today and rebuilding it would
92
+ * require an SDK wrapper. The pre-`sendCommand` portion is the
93
+ * expensive part anyway. */
94
+ signal?: AbortSignal;
95
+ }
96
+
97
+ /**
98
+ * Dispatch a single `HeliosCommand` to the live Reactor session.
99
+ * Resolves with no value on both success and failure — the caller
100
+ * just awaits the dispatch and continues to the next command.
101
+ */
102
+ /** True when `err` is an `AbortError` (or carries that name). Browsers
103
+ * emit `DOMException('AbortError')`; fetch + apiClient already pass
104
+ * this through unchanged. The `code === 'ABORT_ERR'` branch covers
105
+ * custom error classes some libraries use; the `name` check handles
106
+ * every browser DOMException + standard polyfill. */
107
+ function isAbortError(err: unknown): boolean {
108
+ return (
109
+ err instanceof Error &&
110
+ (err.name === 'AbortError' || (err as Error & { code?: string }).code === 'ABORT_ERR')
111
+ );
112
+ }
113
+
114
+ /**
115
+ * Dispatch a single `HeliosCommand` to the live Reactor session.
116
+ * Resolves with no value on both success and failure — the caller
117
+ * just awaits the dispatch and continues to the next command.
118
+ *
119
+ * When `ctx.signal` is provided and gets aborted (before or during
120
+ * dispatch), the function returns silently without invoking any further
121
+ * `apiClient` / `sendCommand` calls. Callers don't need to inspect the
122
+ * return value to distinguish abort from completion.
123
+ */
124
+ export async function dispatchHeliosCommand(
125
+ cmd: HeliosCommand,
126
+ ctx: HeliosToolContext,
127
+ ): Promise<void> {
128
+ if (ctx.signal?.aborted) return;
129
+ try {
130
+ switch (cmd.type) {
131
+ case 'set_scene':
132
+ await handleSetScene(cmd.prompt, ctx);
133
+ return;
134
+ case 'swap_seed':
135
+ await handleSwapSeed(cmd.entityName, ctx);
136
+ return;
137
+ case 'pause_world':
138
+ await ctx.reactor.sendCommand('pause', {});
139
+ return;
140
+ case 'resume_world':
141
+ await ctx.reactor.sendCommand('resume', {});
142
+ return;
143
+ case 'reset_world':
144
+ await ctx.reactor.sendCommand('reset', {});
145
+ return;
146
+ default: {
147
+ // Exhaustiveness check — TS will complain at compile time if a
148
+ // new HeliosCommand variant is added without updating this
149
+ // switch. The runtime branch is unreachable but keeps the
150
+ // narrowing honest.
151
+ const _exhaustive: never = cmd;
152
+ console.warn(
153
+ '[heliosCommandDispatcher] unknown command type',
154
+ _exhaustive,
155
+ );
156
+ return;
157
+ }
158
+ }
159
+ } catch (err) {
160
+ // Abort is a clean signal — silent and stop here.
161
+ if (isAbortError(err)) return;
162
+ console.warn(
163
+ '[heliosCommandDispatcher] command failed; skipping',
164
+ cmd,
165
+ err,
166
+ );
167
+ }
168
+ }
169
+
170
+ /**
171
+ * SET_SCENE: knowledge-grounded upsample then a prompt change.
172
+ *
173
+ * Mirrors `InteractiveController.handleSubmit`:
174
+ * - chunk 0 (no frames rendered yet) → `set_prompt`
175
+ * - mid-stream → `schedule_prompt` at `currentChunk + 2`
176
+ *
177
+ * Upsample failure falls back to the raw model-emitted prompt rather
178
+ * than aborting — the model is already doing the Helios prompt-guide
179
+ * shaping; upsample just adds knowledge-graph grounding.
180
+ */
181
+ async function handleSetScene(
182
+ modelPrompt: string,
183
+ ctx: HeliosToolContext,
184
+ ): Promise<void> {
185
+ let prompt = modelPrompt;
186
+ try {
187
+ const res = await ctx.apiClient.upsampleReactorPrompt(
188
+ {
189
+ prompt: modelPrompt,
190
+ imageId: ctx.imageId,
191
+ entityContext: ctx.entityContext,
192
+ personaContext: ctx.personaContext,
193
+ },
194
+ { signal: ctx.signal },
195
+ );
196
+ if (res?.upsampledPrompt) prompt = res.upsampledPrompt;
197
+ } catch (err) {
198
+ // Non-fatal: the model's prompt is already 80-120 word Helios-quality
199
+ // per the addon prose, so falling back is safe. Abort is also routed
200
+ // through this branch — that's intentional, we want abort to skip the
201
+ // rest of the dispatch.
202
+ if (isAbortError(err)) {
203
+ // Silent on abort — the caller asked for cancellation.
204
+ throw err;
205
+ }
206
+ console.warn(
207
+ '[heliosCommandDispatcher] set_scene upsample failed; using raw prompt',
208
+ err,
209
+ );
210
+ }
211
+
212
+ if (ctx.signal?.aborted) return;
213
+ const chunk = ctx.currentChunk ?? 0;
214
+ if (chunk === 0) {
215
+ await ctx.reactor.sendCommand('set_prompt', { prompt });
216
+ // Only emit `start` when the page hasn't fired it yet — re-emitting
217
+ // start while the model is already running is undocumented Reactor
218
+ // behavior and could in theory restart the stream from frame 0.
219
+ // Defensive guard: when ctx.hasStarted is true, we just refresh the
220
+ // prompt without a fresh start.
221
+ if (!ctx.hasStarted) {
222
+ await ctx.reactor.sendCommand('start', {});
223
+ }
224
+ } else {
225
+ await ctx.reactor.sendCommand('schedule_prompt', {
226
+ prompt,
227
+ chunk: chunk + 2,
228
+ });
229
+ }
230
+ }
231
+
232
+ /**
233
+ * SWAP_SEED: replace the active seed image with a different entity
234
+ * from the current video. Entity resolution is delegated to
235
+ * `findEntityImageBySeedName` (also in client-core) so the lookup
236
+ * logic is reusable on its own.
237
+ *
238
+ * If nothing matches: log a warning + invoke `onUserWarning` and exit.
239
+ * The chat keeps working; the user can ask the assistant for an exact
240
+ * entity name.
241
+ */
242
+ async function handleSwapSeed(
243
+ entityName: string,
244
+ ctx: HeliosToolContext,
245
+ ): Promise<void> {
246
+ if (!ctx.videoId) {
247
+ console.warn(
248
+ '[heliosCommandDispatcher] swap_seed requested but no video selected',
249
+ );
250
+ ctx.onUserWarning?.(
251
+ 'Cannot swap seed — no video selected. Pick a video first.',
252
+ );
253
+ return;
254
+ }
255
+ const trimmed = entityName.trim();
256
+ if (!trimmed) {
257
+ console.warn('[heliosCommandDispatcher] swap_seed has empty entity name');
258
+ return;
259
+ }
260
+
261
+ const match = await findEntityImageBySeedName(
262
+ ctx.apiClient,
263
+ ctx.videoId,
264
+ trimmed,
265
+ );
266
+ if (!match) {
267
+ console.warn(
268
+ `[heliosCommandDispatcher] swap_seed: no entity matching "${entityName}" ` +
269
+ `in video ${ctx.videoId}`,
270
+ );
271
+ ctx.onUserWarning?.(
272
+ `Couldn't find an entity named "${entityName}" in this video. ` +
273
+ 'Try the exact name from the entity picker.',
274
+ );
275
+ return;
276
+ }
277
+
278
+ // Use the shared orchestrator (#116) so PNG/JPEG extension handling
279
+ // and the upload→set_image sequence stay in one place. `swap-seed`
280
+ // stem distinguishes SWAP_SEED uploads from initial-seed uploads in
281
+ // server logs.
282
+ const file = await loadSeedImageFile(match.image_id, ctx.apiClient, {
283
+ signal: ctx.signal,
284
+ filenameStem: 'swap-seed',
285
+ });
286
+ if (ctx.signal?.aborted) return;
287
+ await sendSeedFileToReactor(file, ctx.reactor, { transition: 'blend' });
288
+ // Tell the page so subsequent SET_SCENE upsample calls see the
289
+ // RIGHT entity's context. Without this, the Helios stream visually
290
+ // swaps but the model continues grounding prompts on the previous
291
+ // entity.
292
+ ctx.onSeedSwapped?.(match);
293
+ }
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Helios world-steering command vocabulary.
3
+ *
4
+ * Phase 3 ships an "inline markers" implementation: the chat model emits
5
+ * bracket-style commands like `[SET_SCENE: "wide cinematic shot…"]`
6
+ * inline in its assistant turn, and the browser intercepts them with
7
+ * `parseHeliosCommands()` and dispatches `reactor.sendCommand(...)` for
8
+ * each one. `stripHeliosCommands()` then removes the markers from the
9
+ * user-facing transcript so the user only sees natural-language reply
10
+ * text.
11
+ *
12
+ * Why markers and not real Bedrock tool-use today? `shared/chat_dispatcher.py`
13
+ * and `agents/strands/tool_schemas.py` only register SERVER-SIDE tools
14
+ * (executed inline by the agent) — there is no per-request browser-tools
15
+ * pipe through the WS yet. Adding that is a substantial refactor that
16
+ * would dwarf the Phase 3 scope. Markers are a pragmatic bridge.
17
+ *
18
+ * Future Phase 3b: migrate to real Bedrock tool-use by threading
19
+ * browser-defined tools through the WS payload. The
20
+ * {@link BEDROCK_TOOL_SCHEMAS} export below already encodes the same
21
+ * vocabulary in Converse-tool-spec form, so the migration is mostly
22
+ * delete-marker-parser + add-toolUse-handler. Tracked in
23
+ * `specs/technical-debt.md` Issue #113.
24
+ */
25
+
26
+ /**
27
+ * Discriminated union of every world-steering action the chat model can
28
+ * trigger. Keep this in sync with both {@link parseHeliosCommands} (the
29
+ * marker grammar) and {@link BEDROCK_TOOL_SCHEMAS} (the future-tool-use
30
+ * grammar).
31
+ */
32
+ export type HeliosCommand =
33
+ | { type: 'set_scene'; prompt: string }
34
+ | { type: 'swap_seed'; entityName: string }
35
+ | { type: 'pause_world' }
36
+ | { type: 'resume_world' }
37
+ | { type: 'reset_world' };
38
+
39
+ /**
40
+ * Marker names recognised by {@link parseHeliosCommands}. Matched
41
+ * case-insensitively. Anything else is silently dropped — the model
42
+ * regularly invents marker names, and throwing would break the chat
43
+ * session for every typo.
44
+ */
45
+ const KNOWN_MARKERS: Record<string, 'set_scene' | 'swap_seed' | 'pause_world' | 'resume_world' | 'reset_world'> = {
46
+ set_scene: 'set_scene',
47
+ swap_seed: 'swap_seed',
48
+ pause_world: 'pause_world',
49
+ resume_world: 'resume_world',
50
+ reset_world: 'reset_world',
51
+ };
52
+
53
+ /**
54
+ * Markers that REQUIRE a string argument. The argument is captured from
55
+ * the `"…"` group in the grammar; missing-arg variants are dropped.
56
+ */
57
+ const MARKERS_REQUIRING_ARG = new Set<string>(['set_scene', 'swap_seed']);
58
+
59
+ /**
60
+ * Grammar (loose):
61
+ * - `[ NAME ]`
62
+ * - `[ NAME : "argument" ]`
63
+ *
64
+ * Whitespace around the name/colon is tolerated; the name is matched
65
+ * case-insensitively. Markers that look syntactically valid but don't
66
+ * match a known name are dropped (so the model can hallucinate
67
+ * `[ENGAGE_HYPERDRIVE: "warp 9"]` without crashing).
68
+ *
69
+ * The regex is non-greedy on the argument to handle multiple markers
70
+ * on one line, and forbids embedded brackets inside the name to avoid
71
+ * catastrophic backtracking on malformed input.
72
+ *
73
+ * Only the regex SOURCE + FLAGS are kept at module scope. Each call
74
+ * to `parseHeliosCommands` constructs a fresh `RegExp` instance from
75
+ * those constants so the `g`-flag's `lastIndex` state is never shared
76
+ * across calls. Browser is single-threaded so the difference is mostly
77
+ * theoretical, but it eliminates the shared-state concern for SSR or
78
+ * concurrent test workers and lets us drop a defensive reset line.
79
+ */
80
+ const MARKER_PATTERN =
81
+ /\[\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*"((?:[^"\\]|\\.)*)"\s*)?\]/g;
82
+ const MARKER_PATTERN_SOURCE = MARKER_PATTERN.source;
83
+ const MARKER_PATTERN_FLAGS = MARKER_PATTERN.flags;
84
+
85
+ /**
86
+ * Extract Helios commands from a streamed model response. Unknown
87
+ * marker names are silently dropped. Malformed markers (unclosed
88
+ * brackets, missing quotes when an arg is expected) are also dropped —
89
+ * tolerance over strictness because the model is the source of truth
90
+ * for whether a marker was intended.
91
+ *
92
+ * Returned commands preserve source order.
93
+ */
94
+ export function parseHeliosCommands(text: string): HeliosCommand[] {
95
+ if (!text) return [];
96
+ const commands: HeliosCommand[] = [];
97
+ // Fresh regex per call — no shared lastIndex state to worry about.
98
+ const regex = new RegExp(MARKER_PATTERN_SOURCE, MARKER_PATTERN_FLAGS);
99
+ for (const match of text.matchAll(regex)) {
100
+ const rawName = match[1]?.toLowerCase();
101
+ const arg = match[2]; // string | undefined
102
+ if (!rawName) continue;
103
+ const type = KNOWN_MARKERS[rawName];
104
+ if (!type) continue;
105
+ if (MARKERS_REQUIRING_ARG.has(type)) {
106
+ // Argument is required and must be a non-empty trimmed string.
107
+ const trimmed = arg?.trim();
108
+ if (!trimmed) continue;
109
+ if (type === 'set_scene') {
110
+ commands.push({ type: 'set_scene', prompt: trimmed });
111
+ } else if (type === 'swap_seed') {
112
+ commands.push({ type: 'swap_seed', entityName: trimmed });
113
+ }
114
+ } else {
115
+ // Zero-arg markers; any included arg is ignored.
116
+ if (type === 'pause_world') commands.push({ type: 'pause_world' });
117
+ else if (type === 'resume_world') commands.push({ type: 'resume_world' });
118
+ else if (type === 'reset_world') commands.push({ type: 'reset_world' });
119
+ }
120
+ }
121
+ return commands;
122
+ }
123
+
124
+ /**
125
+ * Remove every Helios marker from a text fragment so the user-facing
126
+ * transcript reads cleanly. The function:
127
+ * - Drops markers regardless of whether the name is recognised (the
128
+ * user shouldn't see `[FOO: "bar"]` either way).
129
+ * - Collapses runs of horizontal whitespace introduced by the
130
+ * deletion (so `Hello [PAUSE_WORLD] world` becomes `Hello world`,
131
+ * not `Hello world`).
132
+ * - Collapses 3+ consecutive newlines down to 2 (preserves paragraph
133
+ * breaks but doesn't leave huge gaps where markers used to sit).
134
+ * - Leaves the input's leading/trailing whitespace untouched. Streaming
135
+ * callers concatenate chunks, so trimming boundary whitespace would
136
+ * corrupt seams.
137
+ */
138
+ export function stripHeliosCommands(text: string): string {
139
+ if (!text) return text;
140
+ // Reuse the parser's grammar via MARKER_PATTERN_SOURCE so any future
141
+ // change to the marker syntax automatically applies here too. Fresh
142
+ // RegExp instance — no `lastIndex` state shared with the parser.
143
+ // (Stripping doesn't capture so we don't need the parentheses, but
144
+ // keeping the same source is cheaper than maintaining two regexes.)
145
+ const stripRegex = new RegExp(
146
+ MARKER_PATTERN_SOURCE,
147
+ MARKER_PATTERN_FLAGS,
148
+ );
149
+ const stripped = text.replace(stripRegex, '');
150
+ // Collapse whitespace introduced by deletion (multiple spaces, tabs,
151
+ // newlines that became adjacent). Preserve single newlines for
152
+ // paragraph structure: collapse runs of horizontal whitespace, then
153
+ // dedupe consecutive blank lines.
154
+ const collapsed = stripped
155
+ // Collapse runs of spaces/tabs.
156
+ .replace(/[ \t]{2,}/g, ' ')
157
+ // Remove trailing spaces before newlines.
158
+ .replace(/[ \t]+\n/g, '\n')
159
+ // Collapse 3+ newlines down to 2.
160
+ .replace(/\n{3,}/g, '\n\n');
161
+ return collapsed;
162
+ }
163
+
164
+ /**
165
+ * Bedrock Converse tool specs for the same vocabulary as the markers
166
+ * above. **NOT USED IN PHASE 3** — the chat dispatcher doesn't accept
167
+ * browser-defined tools yet (see Issue #113 in
168
+ * `specs/technical-debt.md`). Kept here so the future migration to real
169
+ * tool-use only needs to delete the marker parser and wire these into
170
+ * the WS send payload.
171
+ *
172
+ * Schema shape matches the AWS Bedrock Converse API:
173
+ * { toolSpec: { name, description, inputSchema: { json: {...} } } }
174
+ *
175
+ * NAMING NOTE: schemas use `snake_case` property names (`entity_name`,
176
+ * not `entityName`) because that's the convention Bedrock Converse
177
+ * tool-use expects in the inputSchema, and the LLM emits arguments
178
+ * keyed to the schema. The Phase 3b migration handler will need to
179
+ * translate snake_case tool-use args → camelCase `HeliosCommand`
180
+ * fields (e.g. `entity_name` → `entityName`). The marker parser does
181
+ * the same translation for the inline-marker path today.
182
+ */
183
+ export const BEDROCK_TOOL_SCHEMAS = [
184
+ {
185
+ toolSpec: {
186
+ name: 'set_scene',
187
+ description:
188
+ 'Change the live Helios scene to a new prompt. The prompt should ' +
189
+ 'be a detailed 80-120 word scene description following the Helios ' +
190
+ 'prompt-guide style: subject, environment, lighting, camera framing, ' +
191
+ 'mood. Use this when the user asks to change the world, the weather, ' +
192
+ 'the time of day, or the mood. The change applies on the next chunk.',
193
+ inputSchema: {
194
+ json: {
195
+ type: 'object',
196
+ properties: {
197
+ prompt: {
198
+ type: 'string',
199
+ description:
200
+ 'Detailed 80-120 word scene description for Helios.',
201
+ },
202
+ },
203
+ required: ['prompt'],
204
+ },
205
+ },
206
+ },
207
+ },
208
+ {
209
+ toolSpec: {
210
+ name: 'swap_seed',
211
+ description:
212
+ 'Replace the active seed image with a different entity from the ' +
213
+ 'current video. The entity name should match one of the ' +
214
+ "extracted entities (matching is case-insensitive on whitespace-trimmed " +
215
+ "names — `Leo`, `leo`, `LEO` all resolve to the same entity). Use when " +
216
+ 'the user asks to ' +
217
+ "swap or focus on a different character. Triggers a blended " +
218
+ 'transition rather than a hard cut.',
219
+ inputSchema: {
220
+ json: {
221
+ type: 'object',
222
+ properties: {
223
+ entity_name: {
224
+ type: 'string',
225
+ description:
226
+ 'Exact display name of the target entity (e.g. "Leo").',
227
+ },
228
+ },
229
+ required: ['entity_name'],
230
+ },
231
+ },
232
+ },
233
+ },
234
+ {
235
+ toolSpec: {
236
+ name: 'pause_world',
237
+ description:
238
+ 'Pause the live Helios stream at the current frame. Use when the ' +
239
+ 'user wants to freeze the action.',
240
+ inputSchema: { json: { type: 'object', properties: {} } },
241
+ },
242
+ },
243
+ {
244
+ toolSpec: {
245
+ name: 'resume_world',
246
+ description:
247
+ 'Resume a paused Helios stream from the current frame.',
248
+ inputSchema: { json: { type: 'object', properties: {} } },
249
+ },
250
+ },
251
+ {
252
+ toolSpec: {
253
+ name: 'reset_world',
254
+ description:
255
+ 'Reset the Helios stream back to frame 0 and clear the scheduled ' +
256
+ 'prompt buffer. Use when the user wants to start over.',
257
+ inputSchema: { json: { type: 'object', properties: {} } },
258
+ },
259
+ },
260
+ ] as const;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Barrel re-export for the framework-agnostic Reactor / Helios layer.
3
+ * Consumed from `src/index.ts` via `export * from './reactor'`.
4
+ */
5
+
6
+ export * from './types';
7
+ export * from './regenTemplate';
8
+ export * from './upsamplePrompt';
9
+ export * from './entityContext';
10
+ export * from './scenesFromEnrichment';
11
+ export * from './heliosTools';
12
+ export * from './toolPromptAddon';
13
+ export * from './entitySearch';
14
+ export * from './heliosCommandDispatcher';
15
+ export * from './seedImageOrchestrator';
16
+ export * from './promptAddonRegistry';
17
+ export * from './sceneEntry';
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Frontend-facing registry of known prompt addons.
3
+ *
4
+ * The persona-edit form (and any other UI that wants to expose addon
5
+ * toggles) imports `KNOWN_PROMPT_ADDONS` to render a multi-select
6
+ * without having to hardcode the addon ID list. Each entry carries the
7
+ * stable ID, a human label, and a short description that the UI shows
8
+ * as helper text.
9
+ *
10
+ * Source of truth for the addon BEHAVIOUR still lives in the addon's
11
+ * own module (`toolPromptAddon.ts` for `helios-world-steering`); this
12
+ * registry is just the metadata listing.
13
+ *
14
+ * When a new addon lands:
15
+ * 1. Add its ID constant in `<addon>AddonId.ts` (mirroring
16
+ * `toolPromptAddonId.ts`) AND the matching Python constant in
17
+ * `shared/persona_addon_ids.py`.
18
+ * 2. Add the addon-text builder.
19
+ * 3. Add one entry here so the persona UI picks it up automatically.
20
+ *
21
+ * Once this list grows past ~10 entries, consider moving to a DynamoDB
22
+ * registry surfaced via API (`shared/prompt_addon_store.py`) — see
23
+ * `specs/technical-debt.md` #118 for the migration plan.
24
+ */
25
+
26
+ import { HELIOS_WORLD_STEERING_ADDON_ID } from './toolPromptAddonId';
27
+
28
+ export interface PromptAddonDescriptor {
29
+ /** Stable ID matching `prompt_addon_ids` in `PersonaConfig`. */
30
+ id: string;
31
+ /** Short label for the multi-select option. */
32
+ label: string;
33
+ /** One-sentence description for helper text under the option. */
34
+ description: string;
35
+ }
36
+
37
+ export const KNOWN_PROMPT_ADDONS: readonly PromptAddonDescriptor[] = [
38
+ {
39
+ id: HELIOS_WORLD_STEERING_ADDON_ID,
40
+ label: 'Helios world steering',
41
+ description:
42
+ 'Lets this persona drive a live Helios scene from the /interactive/chat page by emitting inline scene-change markers ([SET_SCENE], [SWAP_SEED], etc.). Auto-enabled when the persona is bound to a source video or character image.',
43
+ },
44
+ ];
45
+
46
+ /** Look up a descriptor by ID. Returns `undefined` for unknown IDs —
47
+ * callers can fall back to rendering the raw ID string. */
48
+ export function getPromptAddonDescriptor(
49
+ id: string,
50
+ ): PromptAddonDescriptor | undefined {
51
+ return KNOWN_PROMPT_ADDONS.find(a => a.id === id);
52
+ }