@escapeaihq/client-core 0.7.0 → 0.12.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 (107) hide show
  1. package/README.md +22 -3
  2. package/dist/api.d.ts +114 -0
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/api.js +62 -47
  5. package/dist/api.js.map +1 -1
  6. package/dist/graphSchema.d.ts +72 -0
  7. package/dist/graphSchema.d.ts.map +1 -0
  8. package/dist/graphSchema.js +105 -0
  9. package/dist/graphSchema.js.map +1 -0
  10. package/dist/index.d.ts +3 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/reactor/abortUtils.d.ts +16 -0
  15. package/dist/reactor/abortUtils.d.ts.map +1 -0
  16. package/dist/reactor/abortUtils.js +26 -0
  17. package/dist/reactor/abortUtils.js.map +1 -0
  18. package/dist/reactor/applyScenePrompt.d.ts +75 -0
  19. package/dist/reactor/applyScenePrompt.d.ts.map +1 -0
  20. package/dist/reactor/applyScenePrompt.js +60 -0
  21. package/dist/reactor/applyScenePrompt.js.map +1 -0
  22. package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -1
  23. package/dist/reactor/heliosCommandDispatcher.js +10 -15
  24. package/dist/reactor/heliosCommandDispatcher.js.map +1 -1
  25. package/dist/reactor/index.d.ts +2 -0
  26. package/dist/reactor/index.d.ts.map +1 -1
  27. package/dist/reactor/index.js +2 -0
  28. package/dist/reactor/index.js.map +1 -1
  29. package/dist/reactor/sceneEntry.d.ts +40 -6
  30. package/dist/reactor/sceneEntry.d.ts.map +1 -1
  31. package/dist/reactor/sceneEntry.js +63 -24
  32. package/dist/reactor/sceneEntry.js.map +1 -1
  33. package/dist/reactor/seedImageOrchestrator.d.ts +45 -2
  34. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  35. package/dist/reactor/seedImageOrchestrator.js +174 -4
  36. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  37. package/dist/timeFormat.d.ts +10 -0
  38. package/dist/timeFormat.d.ts.map +1 -1
  39. package/dist/timeFormat.js +12 -0
  40. package/dist/timeFormat.js.map +1 -1
  41. package/dist/toolSchemas.d.ts +370 -0
  42. package/dist/toolSchemas.d.ts.map +1 -0
  43. package/dist/toolSchemas.js +182 -0
  44. package/dist/toolSchemas.js.map +1 -0
  45. package/dist/vision/VisionPublisher.d.ts +115 -0
  46. package/dist/vision/VisionPublisher.d.ts.map +1 -0
  47. package/dist/vision/VisionPublisher.js +475 -0
  48. package/dist/vision/VisionPublisher.js.map +1 -0
  49. package/dist/vision/credentials.d.ts +22 -0
  50. package/dist/vision/credentials.d.ts.map +1 -0
  51. package/dist/vision/credentials.js +34 -0
  52. package/dist/vision/credentials.js.map +1 -0
  53. package/dist/vision/index.d.ts +14 -0
  54. package/dist/vision/index.d.ts.map +1 -0
  55. package/dist/vision/index.js +11 -0
  56. package/dist/vision/index.js.map +1 -0
  57. package/dist/vision/startVisionPublisher.d.ts +38 -0
  58. package/dist/vision/startVisionPublisher.d.ts.map +1 -0
  59. package/dist/vision/startVisionPublisher.js +44 -0
  60. package/dist/vision/startVisionPublisher.js.map +1 -0
  61. package/dist/vision/types.d.ts +95 -0
  62. package/dist/vision/types.d.ts.map +1 -0
  63. package/dist/vision/types.js +12 -0
  64. package/dist/vision/types.js.map +1 -0
  65. package/dist/vision/visionScheduler.d.ts +63 -0
  66. package/dist/vision/visionScheduler.d.ts.map +1 -0
  67. package/dist/vision/visionScheduler.js +67 -0
  68. package/dist/vision/visionScheduler.js.map +1 -0
  69. package/dist/websocket.d.ts +153 -0
  70. package/dist/websocket.d.ts.map +1 -1
  71. package/dist/websocket.js +199 -1
  72. package/dist/websocket.js.map +1 -1
  73. package/package.json +11 -1
  74. package/src/__tests__/api-pollers.test.ts +100 -0
  75. package/src/__tests__/chat-auth.test.ts +91 -0
  76. package/src/__tests__/graphSchema.test.ts +117 -0
  77. package/src/__tests__/reactor/applyScenePrompt.test.ts +192 -0
  78. package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +4 -3
  79. package/src/__tests__/reactor/sceneEntry.test.ts +134 -10
  80. package/src/__tests__/reactor/seedImageOrchestrator.test.ts +51 -16
  81. package/src/__tests__/timeFormat.test.ts +22 -1
  82. package/src/__tests__/toolSchemas.test.ts +57 -0
  83. package/src/__tests__/websocket-vision.test.ts +265 -0
  84. package/src/__tests__/websocket.test.ts +75 -0
  85. package/src/api.ts +160 -47
  86. package/src/graphSchema.ts +149 -0
  87. package/src/index.ts +3 -0
  88. package/src/reactor/abortUtils.ts +22 -0
  89. package/src/reactor/applyScenePrompt.ts +136 -0
  90. package/src/reactor/heliosCommandDispatcher.ts +10 -18
  91. package/src/reactor/index.ts +2 -0
  92. package/src/reactor/sceneEntry.ts +104 -33
  93. package/src/reactor/seedImageOrchestrator.ts +201 -4
  94. package/src/timeFormat.ts +13 -0
  95. package/src/toolSchemas.ts +225 -0
  96. package/src/vision/VisionPublisher.ts +553 -0
  97. package/src/vision/__tests__/VisionPublisher.kvs.test.ts +244 -0
  98. package/src/vision/__tests__/VisionPublisher.test.ts +301 -0
  99. package/src/vision/__tests__/startVisionPublisher.test.ts +251 -0
  100. package/src/vision/__tests__/toVisionRtcCredentials.test.ts +113 -0
  101. package/src/vision/__tests__/visionScheduler.test.ts +149 -0
  102. package/src/vision/credentials.ts +39 -0
  103. package/src/vision/index.ts +31 -0
  104. package/src/vision/startVisionPublisher.ts +64 -0
  105. package/src/vision/types.ts +101 -0
  106. package/src/vision/visionScheduler.ts +102 -0
  107. package/src/websocket.ts +301 -1
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Graph-schema vocabulary mirrored from the backend single source of truth
3
+ * (`shared/graph_schema.py` + `shared/provenance.py`).
4
+ *
5
+ * These are framework-agnostic TypeScript string-literal unions and constant
6
+ * tuples. They let consumers (the React `web/` graph editor's `PropertyPanel`
7
+ * and the Vue Web-App) drop their hand-maintained whitelist mirrors and type
8
+ * against the same vocabulary the backend validates against.
9
+ *
10
+ * Scope discipline (mirrors the backend "no god-module" rule): this file
11
+ * describes the **graph schema only** — node labels, relationship types, and
12
+ * the two provenance vocabularies. It must NOT grow tool/MCP schemas or
13
+ * request/response DTOs.
14
+ *
15
+ * Keep this in lockstep with the Python module. The Python `NARRATIVE_NODE_LABELS`
16
+ * static extension point (for Story-Engine narrative nodes like `Act`) has no
17
+ * runtime equivalent here — a phase that adds a narrative label widens these
18
+ * unions in the same change.
19
+ */
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // Node + relationship vocabulary (the graph that exists today)
23
+ // ---------------------------------------------------------------------------
24
+
25
+ /** Every node label that exists in the video graph today. */
26
+ export type GraphNodeLabel = 'Video' | 'Shot' | 'Entity' | 'Event' | 'DialogLine';
27
+
28
+ /** Every relationship type that exists in the video graph today. */
29
+ export type GraphRelationshipType =
30
+ | 'HAS_SHOT'
31
+ | 'MENTIONS'
32
+ | 'HAS_EVENT'
33
+ | 'HAS_DIALOG'
34
+ | 'SPOKEN_BY'
35
+ | 'NEXT';
36
+
37
+ /** Runtime tuple of all node labels (mirrors `VALID_NODE_LABELS`). */
38
+ export const GRAPH_NODE_LABELS: readonly GraphNodeLabel[] = [
39
+ 'Video',
40
+ 'Shot',
41
+ 'Entity',
42
+ 'Event',
43
+ 'DialogLine',
44
+ ] as const;
45
+
46
+ /** Runtime tuple of all relationship types (mirrors `VALID_RELATIONSHIP_TYPES`). */
47
+ export const GRAPH_RELATIONSHIP_TYPES: readonly GraphRelationshipType[] = [
48
+ 'HAS_SHOT',
49
+ 'MENTIONS',
50
+ 'HAS_EVENT',
51
+ 'HAS_DIALOG',
52
+ 'SPOKEN_BY',
53
+ 'NEXT',
54
+ ] as const;
55
+
56
+ /**
57
+ * Primary-key property per node label (mirrors `PRIMARY_KEY`).
58
+ *
59
+ * NOTE: keyed on the CLOSED `GraphNodeLabel` union, unlike the Python
60
+ * `dict[str, str]`. A Story-Engine phase that adds a narrative label (e.g.
61
+ * `Act`) must widen BOTH `GraphNodeLabel` AND this `Record` key here, in the
62
+ * same change — TS will flag the gap as a type error until both are updated.
63
+ */
64
+ export const GRAPH_PRIMARY_KEY: Readonly<Record<GraphNodeLabel, string>> = {
65
+ Video: 'videoId',
66
+ Shot: 'shotId',
67
+ Entity: 'entityId',
68
+ Event: 'eventId',
69
+ DialogLine: 'dialogId',
70
+ } as const;
71
+
72
+ /** User-editable properties per node label (mirrors `EDITABLE_NODE_PROPERTIES`). */
73
+ export const GRAPH_EDITABLE_NODE_PROPERTIES: Readonly<
74
+ Record<GraphNodeLabel, readonly string[]>
75
+ > = {
76
+ Video: ['fileName', 'episodeTitle'],
77
+ Shot: ['caption'],
78
+ Entity: ['name', 'type'],
79
+ Event: ['label', 'category'],
80
+ DialogLine: ['text', 'speaker'],
81
+ } as const;
82
+
83
+ /**
84
+ * Editable relationship properties (mirrors `EDITABLE_RELATIONSHIP_PROPERTIES`).
85
+ * NOTE: the Python source is a `frozenset` (unordered, unique) — this array
86
+ * carries no ordering contract; treat it as a set (membership), not a sequence.
87
+ */
88
+ export const GRAPH_EDITABLE_RELATIONSHIP_PROPERTIES: readonly string[] = [
89
+ 'confidence',
90
+ ] as const;
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // Provenance — TWO SEPARATE unions (mirrors shared/provenance.py)
94
+ // ---------------------------------------------------------------------------
95
+
96
+ /**
97
+ * How a story-graph node/edge entered the graph. Separate from
98
+ * {@link MemoryFactProvenance} — do not merge them.
99
+ */
100
+ export type StoryGraphProvenance = 'pegasus' | 'user' | 'document' | 'regenerated';
101
+
102
+ /**
103
+ * How an agent-memory fact entered the `:Memory` plane. Separate from
104
+ * {@link StoryGraphProvenance} — do not merge them.
105
+ */
106
+ export type MemoryFactProvenance = 'chat' | 'document' | 'system' | 'regenerated';
107
+
108
+ /** Runtime tuple of story-graph provenance values. */
109
+ export const STORY_GRAPH_PROVENANCE_VALUES: readonly StoryGraphProvenance[] = [
110
+ 'pegasus',
111
+ 'user',
112
+ 'document',
113
+ 'regenerated',
114
+ ] as const;
115
+
116
+ /** Runtime tuple of memory-fact provenance values. */
117
+ export const MEMORY_FACT_PROVENANCE_VALUES: readonly MemoryFactProvenance[] = [
118
+ 'chat',
119
+ 'document',
120
+ 'system',
121
+ 'regenerated',
122
+ ] as const;
123
+
124
+ /**
125
+ * Authored-canon provenance — facts that chat extraction must NOT overwrite.
126
+ * Mirrors `AUTHORED_STORY_PROVENANCE` / `AUTHORED_MEMORY_PROVENANCE` in
127
+ * `shared/provenance.py`. Phase 6 (persona memory) is the first consumer; keep
128
+ * these mirrored so the frontend never re-declares the canon set or compares
129
+ * raw strings.
130
+ */
131
+ export const AUTHORED_STORY_PROVENANCE: ReadonlySet<StoryGraphProvenance> = new Set([
132
+ 'user',
133
+ 'document',
134
+ ]);
135
+
136
+ export const AUTHORED_MEMORY_PROVENANCE: ReadonlySet<MemoryFactProvenance> = new Set([
137
+ 'system',
138
+ 'document',
139
+ ]);
140
+
141
+ /** Type guard mirroring `is_story_graph_provenance` in `shared/provenance.py`. */
142
+ export function isStoryGraphProvenance(value: string): value is StoryGraphProvenance {
143
+ return (STORY_GRAPH_PROVENANCE_VALUES as readonly string[]).includes(value);
144
+ }
145
+
146
+ /** Type guard mirroring `is_memory_fact_provenance` in `shared/provenance.py`. */
147
+ export function isMemoryFactProvenance(value: string): value is MemoryFactProvenance {
148
+ return (MEMORY_FACT_PROVENANCE_VALUES as readonly string[]).includes(value);
149
+ }
package/src/index.ts CHANGED
@@ -28,3 +28,6 @@ export * from './websocket';
28
28
  export * from './api';
29
29
  export * from './reactor';
30
30
  export * from './timeFormat';
31
+ export * from './toolSchemas';
32
+ export * from './vision';
33
+ export * from './graphSchema';
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Shared abort-detection helper for the reactor submodule. Three call
3
+ * sites used to carry their own copy of this 6-liner — drift between
4
+ * them would silently change cancellation semantics (an abort being
5
+ * mistaken for a real error logs noise; a real error being mistaken
6
+ * for an abort silently swallows it), so we consolidate here.
7
+ *
8
+ * Accepts both `DOMException { name: 'AbortError' }` (native `fetch`
9
+ * + browser `AbortController`) and plain `Error { name: 'AbortError'
10
+ * }` (some polyfills, the project's own pollers). Also accepts
11
+ * `Error { code: 'ABORT_ERR' }` which some libraries use as their
12
+ * abort signal shape. Keep the union broad so a future polyfill or
13
+ * SSR runtime swap doesn't silently break cancellation handling.
14
+ */
15
+ export function isAbortError(err: unknown): boolean {
16
+ if (err instanceof DOMException && err.name === 'AbortError') return true;
17
+ if (err instanceof Error) {
18
+ if (err.name === 'AbortError') return true;
19
+ if ((err as Error & { code?: string }).code === 'ABORT_ERR') return true;
20
+ }
21
+ return false;
22
+ }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Submit a user-authored or model-authored scene prompt to a live
3
+ * Reactor session. Encapsulates the chunk-0-vs-running policy that
4
+ * previously lived inline in `InteractiveController.handleSubmit` and
5
+ * has now been extracted so the watch-page `HeliosWorldControls`
6
+ * reuses the same logic without duplication.
7
+ *
8
+ * `dispatchHeliosCommand.handleSetScene` (the chat-tool driver) does
9
+ * NOT call into this helper — it keeps its own copy because it needs
10
+ * a distinct `hasStarted` guard for the chat flow (see the comment
11
+ * at the top of `heliosCommandDispatcher.ts::handleSetScene`).
12
+ *
13
+ * Framework-agnostic — no React, no DOM beyond what Reactor's bridge
14
+ * surface already accepts. Errors propagate (unlike `dispatchHelios-
15
+ * Command`, which swallows them to keep the chat loop alive). UI
16
+ * consumers can wrap the call in try/catch to surface a banner.
17
+ *
18
+ * Upsample policy is identical to the prior inline implementation:
19
+ * a non-abort failure logs a warning and falls back to the raw prompt
20
+ * (`buildUpsamplePrompt` is best-effort grounding, not a hard
21
+ * dependency). Abort errors are re-thrown so callers stop awaiting.
22
+ */
23
+
24
+ import type { ApiClient } from '../api';
25
+ import { isAbortError } from './abortUtils';
26
+ import type { EntityContext, PersonaContext } from './types';
27
+
28
+ /** Minimal Reactor surface this helper needs. `applyScenePrompt` only
29
+ * ever issues `set_prompt`, `start`, and `schedule_prompt` — it never
30
+ * uploads a file. Kept narrow so callers don't have to thread an
31
+ * unused `uploadFile` reference; the broader `HeliosReactorBridge`
32
+ * (which adds `uploadFile`) is for the swap-seed / set-image paths. */
33
+ export interface ApplyScenePromptReactorBridge {
34
+ sendCommand: (command: string, data: unknown) => Promise<void>;
35
+ }
36
+
37
+ export interface ApplyScenePromptInput {
38
+ /** The prompt to apply. May be raw user text or a model-emitted
39
+ * Helios-shaped prompt; either way the upsampler is run as a
40
+ * grounding pass and its output (or the raw prompt on failure) is
41
+ * forwarded to Reactor. */
42
+ prompt: string;
43
+ apiClient: ApiClient;
44
+ reactor: ApplyScenePromptReactorBridge;
45
+ /** Live `current_chunk` from Reactor's `state` messages. */
46
+ currentChunk: number;
47
+ /** Whether the world is currently running (Reactor model state
48
+ * `current_frame > 0`). When false, this is the first prompt and
49
+ * we issue `set_prompt` + `start`. When true, we issue
50
+ * `schedule_prompt` at `currentChunk + 2` (the two-chunk lead is
51
+ * what Helios accepts mid-stream). */
52
+ isRunning: boolean;
53
+ /** Optional context plumbed into the upsampler. */
54
+ imageId?: string;
55
+ entityContext?: EntityContext;
56
+ personaContext?: PersonaContext;
57
+ /** Previous prompt for the upsampler's narrative-continuity heuristic. */
58
+ previousPrompt?: string;
59
+ /** When false, skip the upsample call and forward `prompt` to Reactor
60
+ * verbatim. Defaults to `true` so existing callers keep their current
61
+ * behavior. UIs that surface a user-facing upsample toggle (and run
62
+ * the upsample preview separately via `apiClient.upsampleReactorPrompt`
63
+ * to populate an editable textarea) should pass `false` on the
64
+ * send-step so the operator's exact text reaches Helios. */
65
+ shouldUpsample?: boolean;
66
+ signal?: AbortSignal;
67
+ }
68
+
69
+ export interface ApplyScenePromptResult {
70
+ /** The prompt actually sent to Reactor — either the upsampler's
71
+ * output or the raw input when upsample failed. */
72
+ appliedPrompt: string;
73
+ /** When non-null, the chunk index Helios will activate the prompt at
74
+ * (`schedule_prompt`). When null, the prompt was set via
75
+ * `set_prompt` and `start` was issued — this was the first prompt
76
+ * for the session. */
77
+ scheduledAtChunk: number | null;
78
+ }
79
+
80
+ export async function applyScenePrompt(
81
+ input: ApplyScenePromptInput,
82
+ ): Promise<ApplyScenePromptResult> {
83
+ const {
84
+ prompt: rawPrompt,
85
+ apiClient,
86
+ reactor,
87
+ currentChunk,
88
+ isRunning,
89
+ imageId,
90
+ entityContext,
91
+ personaContext,
92
+ previousPrompt,
93
+ shouldUpsample = true,
94
+ signal,
95
+ } = input;
96
+
97
+ let prompt = rawPrompt;
98
+ if (shouldUpsample) {
99
+ try {
100
+ const res = await apiClient.upsampleReactorPrompt(
101
+ {
102
+ prompt: rawPrompt,
103
+ ...(previousPrompt ? { previousPrompt } : {}),
104
+ ...(imageId ? { imageId } : {}),
105
+ ...(entityContext ? { entityContext } : {}),
106
+ ...(personaContext ? { personaContext } : {}),
107
+ },
108
+ { signal },
109
+ );
110
+ if (res?.upsampledPrompt) prompt = res.upsampledPrompt;
111
+ } catch (err) {
112
+ if (isAbortError(err)) throw err;
113
+ console.warn(
114
+ '[applyScenePrompt] upsample failed; falling back to raw prompt',
115
+ err,
116
+ );
117
+ }
118
+ }
119
+
120
+ if (signal?.aborted) {
121
+ throw new DOMException('Aborted', 'AbortError');
122
+ }
123
+
124
+ if (!isRunning) {
125
+ await reactor.sendCommand('set_prompt', { prompt });
126
+ await reactor.sendCommand('start', {});
127
+ return { appliedPrompt: prompt, scheduledAtChunk: null };
128
+ }
129
+
130
+ const targetChunk = currentChunk + 2;
131
+ await reactor.sendCommand('schedule_prompt', {
132
+ prompt,
133
+ chunk: targetChunk,
134
+ });
135
+ return { appliedPrompt: prompt, scheduledAtChunk: targetChunk };
136
+ }
@@ -15,6 +15,7 @@
15
15
  */
16
16
 
17
17
  import type { ApiClient, ImageRecord } from '../api';
18
+ import { isAbortError } from './abortUtils';
18
19
  import { findEntityImageBySeedName } from './entitySearch';
19
20
  import type { HeliosCommand } from './heliosTools';
20
21
  import {
@@ -94,23 +95,6 @@ export interface HeliosToolContext {
94
95
  signal?: AbortSignal;
95
96
  }
96
97
 
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
98
  /**
115
99
  * Dispatch a single `HeliosCommand` to the live Reactor session.
116
100
  * Resolves with no value on both success and failure — the caller
@@ -170,13 +154,21 @@ export async function dispatchHeliosCommand(
170
154
  /**
171
155
  * SET_SCENE: knowledge-grounded upsample then a prompt change.
172
156
  *
173
- * Mirrors `InteractiveController.handleSubmit`:
157
+ * Mirrors `InteractiveController.handleSubmit` and
158
+ * `applyScenePrompt` (the shared helper used by the React controls):
174
159
  * - chunk 0 (no frames rendered yet) → `set_prompt`
175
160
  * - mid-stream → `schedule_prompt` at `currentChunk + 2`
176
161
  *
177
162
  * Upsample failure falls back to the raw model-emitted prompt rather
178
163
  * than aborting — the model is already doing the Helios prompt-guide
179
164
  * shaping; upsample just adds knowledge-graph grounding.
165
+ *
166
+ * Not implemented in terms of `applyScenePrompt` because the chat-tool
167
+ * path has a distinct `hasStarted` guard: when SET_SCENE fires at
168
+ * chunk 0 against an already-running world, we skip the `start`
169
+ * re-emit. `applyScenePrompt`'s UI callers track running via
170
+ * `current_frame > 0` instead, which is authoritative for the
171
+ * operator-driven flow.
180
172
  */
181
173
  async function handleSetScene(
182
174
  modelPrompt: string,
@@ -15,3 +15,5 @@ export * from './heliosCommandDispatcher';
15
15
  export * from './seedImageOrchestrator';
16
16
  export * from './promptAddonRegistry';
17
17
  export * from './sceneEntry';
18
+ export * from './applyScenePrompt';
19
+ export * from './abortUtils';
@@ -21,6 +21,7 @@ import type {
21
21
  ImageRecord,
22
22
  PersonaConfig,
23
23
  } from '../api';
24
+ import { isAbortError } from './abortUtils';
24
25
  import {
25
26
  aggregateEntityContext,
26
27
  aggregatePersonaContext,
@@ -30,22 +31,39 @@ import {
30
31
  sendSeedFileToReactor,
31
32
  type SeedImageReactorBridge,
32
33
  } from './seedImageOrchestrator';
34
+ import type { EntityContext, PersonaContext } from './types';
33
35
 
34
36
  export interface SceneEntryInput {
35
37
  /** The Seer video the user is watching. */
36
38
  videoId: string;
37
39
  /** Playhead position at the moment Step Into Scene was clicked. */
38
40
  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. */
41
+ /** Caption for the bracketing shot, if enrichment is loaded. Only
42
+ * used when `includeCaption: true` — the default image-first path
43
+ * ignores it because Helios already sees the seed frame via
44
+ * `set_image`. */
43
45
  shotCaption?: string | null;
46
+ /** When `true`, the upsampler runs with `shotCaption` (or a fallback)
47
+ * as the input prompt and the resulting Helios paragraph is sent as
48
+ * `set_prompt`. Defaults to `false`, in which case the upsample step
49
+ * is bypassed entirely and `IMAGE_FIRST_DIRECTIVE` is sent as
50
+ * `set_prompt` instead — instructing Helios to continue the seed
51
+ * image faithfully with only natural motion. Ignored when
52
+ * `customPrompt` is also provided. */
53
+ includeCaption?: boolean;
54
+ /** Operator-authored prompt that overrides BOTH the IMAGE_FIRST_DIRECTIVE
55
+ * default and the caption-upsample path. When provided, this string is
56
+ * sent verbatim as the initial `set_prompt`. Enables the watch-page
57
+ * prompt-editor surface where the user previews and tweaks the prompt
58
+ * before stepping into a scene. Trim externally — empty / whitespace-only
59
+ * strings fall back to the includeCaption-driven defaults. */
60
+ customPrompt?: string | null;
44
61
  /** Most-recent SUCCEEDED Pegasus enrichment for the video, used to
45
- * derive `sceneContext` inside the entity grounding. */
62
+ * derive `sceneContext` inside the entity grounding. Only consulted
63
+ * on the caption-driven path. */
46
64
  enrichment: EnrichmentRecord | null;
47
65
  /** Active persona on the watch page. `null` means "no persona
48
- * grounding" — the upsample runs with entity-only context. */
66
+ * grounding". Only consulted on the caption-driven path. */
49
67
  persona: PersonaConfig | null;
50
68
  apiClient: ApiClient;
51
69
  signal?: AbortSignal;
@@ -63,13 +81,42 @@ export interface SceneEntryPayload {
63
81
  * (or any consumer) deep-link to `/images/{imageId}` for inspection
64
82
  * or wire a "View in gallery" affordance. */
65
83
  imageId: string;
84
+ /** Aggregated entity grounding for the extracted frame. Surfaced so
85
+ * in-modal prompt resubmits (via `applyScenePrompt`) ground on the
86
+ * same scene context that the initial upsample used. */
87
+ entityContext: EntityContext;
88
+ /** Persona grounding, when the operator had a persona selected.
89
+ * `null` means "no persona". Mirrors `prepareSceneEntry`'s
90
+ * internal calculation so consumers don't recompute it. */
91
+ personaContext: PersonaContext | null;
66
92
  }
67
93
 
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. */
94
+ /** Fallback shot caption when `includeCaption: true` is set but
95
+ * enrichment is absent or the playhead is outside any shot. Matches
96
+ * the cadence of the upsample's training prompts so the LLM doesn't
97
+ * reject a one-word input. */
71
98
  const FALLBACK_SHOT_CAPTION = 'Step into this moment';
72
99
 
100
+ /** Default `set_prompt` for the image-first path. The seed frame is
101
+ * already loaded into Helios via `set_image`, so this prompt only
102
+ * needs to (a) tell the model to continue what it sees and (b)
103
+ * preserve the visual specifics. Written as a Helios-quality dense
104
+ * paragraph (~95 words) so we can send it directly without the
105
+ * upsampler round-trip. Follows the same prompt-guide rules
106
+ * encoded in `upsamplePrompt.ts::BASE_SYSTEM_RULES`: camera framing
107
+ * named explicitly, light by its effect, behavior over emotion. */
108
+ export const IMAGE_FIRST_DIRECTIVE =
109
+ 'Static medium shot, matching the seed image exactly. Preserve the ' +
110
+ 'subject\'s identity, position, posture, and wardrobe. Preserve the ' +
111
+ 'environment, depth, palette, and the way light falls across surfaces — ' +
112
+ 'the same shadows, the same highlights, the same atmospheric texture. ' +
113
+ 'Hold the original camera framing and lens character; the operator ' +
114
+ 'chose this exact moment. Apply only subtle natural motion: gentle ' +
115
+ 'breathing, slight weight shifts, ambient air moving fabric or hair, ' +
116
+ 'soft eye movement. No new actions, no new objects, no scene cuts, no ' +
117
+ 'introduced characters. Let the world settle into the frame the way it ' +
118
+ 'was captured and continue from there.';
119
+
73
120
  /** Sentinel entity name for the `ExtractImageRequest`. The backend
74
121
  * endpoint requires this field but uses `timestamp` for the actual
75
122
  * frame extraction when both are provided — `entity` survives only as
@@ -89,11 +136,14 @@ export async function prepareSceneEntry(
89
136
  videoId,
90
137
  timestamp,
91
138
  shotCaption,
139
+ includeCaption = false,
140
+ customPrompt,
92
141
  enrichment,
93
142
  persona,
94
143
  apiClient,
95
144
  signal,
96
145
  } = input;
146
+ const customPromptTrimmed = customPrompt?.trim() || null;
97
147
 
98
148
  // Step 1 — extract the frame server-side. The endpoint uses ffmpeg
99
149
  // against the source video's presigned URL and persists an
@@ -114,28 +164,37 @@ export async function prepareSceneEntry(
114
164
  );
115
165
  }
116
166
 
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.
167
+ // Step 2 — build entity/persona context (cheap, always run so the
168
+ // returned payload carries them for follow-up prompts via
169
+ // HeliosWorldControls).
123
170
  const entityContext = aggregateEntityContext({
124
171
  imageRecord: synthesizeImageRecord(videoId, extract),
125
172
  enrichment: enrichment ?? undefined,
126
173
  });
127
174
  const personaContext = persona ? aggregatePersonaContext(persona) : null;
128
- const promptInput = shotCaption?.trim() || FALLBACK_SHOT_CAPTION;
129
175
 
130
- const [upsample, frameFile] = await Promise.all([
131
- apiClient.upsampleReactorPrompt(
132
- {
133
- prompt: promptInput,
134
- entityContext,
135
- ...(personaContext ? { personaContext } : {}),
136
- },
137
- { signal },
138
- ),
176
+ // Step 3 — fan out the frame-blob fetch alongside the prompt
177
+ // resolution. Three paths, in priority order:
178
+ // 1. customPrompt: operator-authored, sent verbatim. No upsample.
179
+ // 2. includeCaption: legacy caption-upsample (Bedrock round-trip).
180
+ // 3. default image-first: send IMAGE_FIRST_DIRECTIVE verbatim.
181
+ const promptPromise: Promise<string> = customPromptTrimmed
182
+ ? Promise.resolve(customPromptTrimmed)
183
+ : includeCaption
184
+ ? apiClient
185
+ .upsampleReactorPrompt(
186
+ {
187
+ prompt: shotCaption?.trim() || FALLBACK_SHOT_CAPTION,
188
+ entityContext,
189
+ ...(personaContext ? { personaContext } : {}),
190
+ },
191
+ { signal },
192
+ )
193
+ .then(res => res.upsampledPrompt)
194
+ : Promise.resolve(IMAGE_FIRST_DIRECTIVE);
195
+
196
+ const [upsampledPrompt, frameFile] = await Promise.all([
197
+ promptPromise,
139
198
  loadSeedImageFile(extract.imageId, apiClient, {
140
199
  signal,
141
200
  filenameStem: 'scene',
@@ -144,9 +203,11 @@ export async function prepareSceneEntry(
144
203
 
145
204
  return {
146
205
  frameFile,
147
- upsampledPrompt: upsample.upsampledPrompt,
206
+ upsampledPrompt,
148
207
  sourceTimestamp: extract.sourceTimestamp,
149
208
  imageId: extract.imageId,
209
+ entityContext,
210
+ personaContext,
150
211
  };
151
212
  }
152
213
 
@@ -171,7 +232,9 @@ export async function prepareSceneEntry(
171
232
  export async function bootstrapSceneInReactor(
172
233
  payload: SceneEntryPayload,
173
234
  bridge: SeedImageReactorBridge,
174
- options: { signal?: AbortSignal } = {},
235
+ options: {
236
+ signal?: AbortSignal;
237
+ } = {},
175
238
  ): Promise<void> {
176
239
  // Abort is an *expected* terminal state for this flow (user clicked
177
240
  // Back to video, modal unmounted, etc.). Internally we use exceptions
@@ -181,8 +244,21 @@ export async function bootstrapSceneInReactor(
181
244
  // shouldn't have to ALSO distinguish AbortError from real errors.
182
245
  try {
183
246
  if (options.signal?.aborted) return;
247
+ // Match the docs sample exactly (file-uploads.md:33,
248
+ // image-to-video-player.md:94): uploadFile → set_image →
249
+ // set_prompt → start back-to-back, no wait between commands.
250
+ // Per `scripts/spikes/helios_set_image_spike.py`, Helios emits
251
+ // `image_accepted` AFTER `start` fires (during chunk 0), so any
252
+ // wait between set_image and start deadlocks. Chunk 0 is
253
+ // text-only briefly; chunks 1+ render with the seed.
254
+ // No transition on the first seed of a session — matches the
255
+ // working JS spike (helios_set_image_spike.html) verbatim. The
256
+ // docs (helios-overview.md) say first-call transition is a no-op,
257
+ // and empirically including `'cut'` here correlated with the
258
+ // image never taking effect in the React app even though the
259
+ // spike (no transition) reliably loads the seed.
184
260
  await raceWithAbort(
185
- sendSeedFileToReactor(payload.frameFile, bridge, { transition: 'cut' }),
261
+ sendSeedFileToReactor(payload.frameFile, bridge, {}),
186
262
  options.signal,
187
263
  );
188
264
  if (options.signal?.aborted) return;
@@ -198,11 +274,6 @@ export async function bootstrapSceneInReactor(
198
274
  }
199
275
  }
200
276
 
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
277
  /**
207
278
  * Race a promise against an `AbortSignal`. When the signal fires, the
208
279
  * returned promise rejects with `AbortError` even if the underlying