@escapeaihq/client-core 0.12.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (242) hide show
  1. package/README.md +32 -7
  2. package/dist/adapters/capabilities.d.ts +10 -0
  3. package/dist/adapters/capabilities.d.ts.map +1 -0
  4. package/dist/adapters/capabilities.js +2 -0
  5. package/dist/adapters/capabilities.js.map +1 -0
  6. package/dist/adapters/chatAdapter.d.ts +38 -0
  7. package/dist/adapters/chatAdapter.d.ts.map +1 -0
  8. package/dist/adapters/chatAdapter.js +88 -0
  9. package/dist/adapters/chatAdapter.js.map +1 -0
  10. package/dist/adapters/directorAdapter.d.ts +62 -0
  11. package/dist/adapters/directorAdapter.d.ts.map +1 -0
  12. package/dist/adapters/directorAdapter.js +71 -0
  13. package/dist/adapters/directorAdapter.js.map +1 -0
  14. package/dist/adapters/imageAdapter.d.ts +44 -0
  15. package/dist/adapters/imageAdapter.d.ts.map +1 -0
  16. package/dist/adapters/imageAdapter.js +73 -0
  17. package/dist/adapters/imageAdapter.js.map +1 -0
  18. package/dist/adapters/index.d.ts +47 -0
  19. package/dist/adapters/index.d.ts.map +1 -0
  20. package/dist/adapters/index.js +41 -0
  21. package/dist/adapters/index.js.map +1 -0
  22. package/dist/adapters/registry.d.ts +98 -0
  23. package/dist/adapters/registry.d.ts.map +1 -0
  24. package/dist/adapters/registry.js +106 -0
  25. package/dist/adapters/registry.js.map +1 -0
  26. package/dist/adapters/worldAdapter.d.ts +142 -0
  27. package/dist/adapters/worldAdapter.d.ts.map +1 -0
  28. package/dist/adapters/worldAdapter.js +164 -0
  29. package/dist/adapters/worldAdapter.js.map +1 -0
  30. package/dist/admin.d.ts +323 -0
  31. package/dist/admin.d.ts.map +1 -0
  32. package/dist/admin.js +198 -0
  33. package/dist/admin.js.map +1 -0
  34. package/dist/api.d.ts +1512 -4
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +820 -52
  37. package/dist/api.js.map +1 -1
  38. package/dist/audio.d.ts +33 -1
  39. package/dist/audio.d.ts.map +1 -1
  40. package/dist/audio.js +4 -1
  41. package/dist/audio.js.map +1 -1
  42. package/dist/castProjection.d.ts +35 -0
  43. package/dist/castProjection.d.ts.map +1 -0
  44. package/dist/castProjection.js +80 -0
  45. package/dist/castProjection.js.map +1 -0
  46. package/dist/conversation/binding.d.ts +77 -0
  47. package/dist/conversation/binding.d.ts.map +1 -0
  48. package/dist/conversation/binding.js +57 -0
  49. package/dist/conversation/binding.js.map +1 -0
  50. package/dist/conversation/controller.d.ts +209 -0
  51. package/dist/conversation/controller.d.ts.map +1 -0
  52. package/dist/conversation/controller.js +350 -0
  53. package/dist/conversation/controller.js.map +1 -0
  54. package/dist/conversation/effectiveModel.d.ts +62 -0
  55. package/dist/conversation/effectiveModel.d.ts.map +1 -0
  56. package/dist/conversation/effectiveModel.js +73 -0
  57. package/dist/conversation/effectiveModel.js.map +1 -0
  58. package/dist/conversation/index.d.ts +27 -0
  59. package/dist/conversation/index.d.ts.map +1 -0
  60. package/dist/conversation/index.js +27 -0
  61. package/dist/conversation/index.js.map +1 -0
  62. package/dist/conversation/participant.d.ts +66 -0
  63. package/dist/conversation/participant.d.ts.map +1 -0
  64. package/dist/conversation/participant.js +36 -0
  65. package/dist/conversation/participant.js.map +1 -0
  66. package/dist/conversation/presence.d.ts +56 -0
  67. package/dist/conversation/presence.d.ts.map +1 -0
  68. package/dist/conversation/presence.js +34 -0
  69. package/dist/conversation/presence.js.map +1 -0
  70. package/dist/conversation/presenceBus.d.ts +42 -0
  71. package/dist/conversation/presenceBus.d.ts.map +1 -0
  72. package/dist/conversation/presenceBus.js +81 -0
  73. package/dist/conversation/presenceBus.js.map +1 -0
  74. package/dist/conversation/presenceRegistry.d.ts +49 -0
  75. package/dist/conversation/presenceRegistry.d.ts.map +1 -0
  76. package/dist/conversation/presenceRegistry.js +59 -0
  77. package/dist/conversation/presenceRegistry.js.map +1 -0
  78. package/dist/conversation/roster.d.ts +72 -0
  79. package/dist/conversation/roster.d.ts.map +1 -0
  80. package/dist/conversation/roster.js +69 -0
  81. package/dist/conversation/roster.js.map +1 -0
  82. package/dist/conversation/rosterProjection.d.ts +52 -0
  83. package/dist/conversation/rosterProjection.d.ts.map +1 -0
  84. package/dist/conversation/rosterProjection.js +74 -0
  85. package/dist/conversation/rosterProjection.js.map +1 -0
  86. package/dist/conversation/router.d.ts +74 -0
  87. package/dist/conversation/router.d.ts.map +1 -0
  88. package/dist/conversation/router.js +58 -0
  89. package/dist/conversation/router.js.map +1 -0
  90. package/dist/conversation/runtime.d.ts +64 -0
  91. package/dist/conversation/runtime.d.ts.map +1 -0
  92. package/dist/conversation/runtime.js +172 -0
  93. package/dist/conversation/runtime.js.map +1 -0
  94. package/dist/conversation/types.d.ts +99 -0
  95. package/dist/conversation/types.d.ts.map +1 -0
  96. package/dist/conversation/types.js +13 -0
  97. package/dist/conversation/types.js.map +1 -0
  98. package/dist/conversation/voice.d.ts +185 -0
  99. package/dist/conversation/voice.d.ts.map +1 -0
  100. package/dist/conversation/voice.js +307 -0
  101. package/dist/conversation/voice.js.map +1 -0
  102. package/dist/graphSchema.d.ts +201 -13
  103. package/dist/graphSchema.d.ts.map +1 -1
  104. package/dist/graphSchema.js +258 -9
  105. package/dist/graphSchema.js.map +1 -1
  106. package/dist/http.d.ts +20 -0
  107. package/dist/http.d.ts.map +1 -0
  108. package/dist/http.js +57 -0
  109. package/dist/http.js.map +1 -0
  110. package/dist/index.d.ts +6 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +9 -0
  113. package/dist/index.js.map +1 -1
  114. package/dist/platformAssistant.d.ts +155 -0
  115. package/dist/platformAssistant.d.ts.map +1 -0
  116. package/dist/platformAssistant.js +256 -0
  117. package/dist/platformAssistant.js.map +1 -0
  118. package/dist/reactor/chunkDistribution.d.ts +43 -0
  119. package/dist/reactor/chunkDistribution.d.ts.map +1 -0
  120. package/dist/reactor/chunkDistribution.js +85 -0
  121. package/dist/reactor/chunkDistribution.js.map +1 -0
  122. package/dist/reactor/index.d.ts +2 -0
  123. package/dist/reactor/index.d.ts.map +1 -1
  124. package/dist/reactor/index.js +5 -0
  125. package/dist/reactor/index.js.map +1 -1
  126. package/dist/reactor/longLiveCommandDispatcher.d.ts +103 -0
  127. package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -0
  128. package/dist/reactor/longLiveCommandDispatcher.js +87 -0
  129. package/dist/reactor/longLiveCommandDispatcher.js.map +1 -0
  130. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -1
  131. package/dist/reactor/scenesFromEnrichment.js +2 -66
  132. package/dist/reactor/scenesFromEnrichment.js.map +1 -1
  133. package/dist/reactor/seedImageOrchestrator.d.ts +6 -9
  134. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  135. package/dist/reactor/seedImageOrchestrator.js +12 -13
  136. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  137. package/dist/reactor/storyTimeline.d.ts +44 -0
  138. package/dist/reactor/storyTimeline.d.ts.map +1 -0
  139. package/dist/reactor/storyTimeline.js +95 -0
  140. package/dist/reactor/storyTimeline.js.map +1 -0
  141. package/dist/storyGraph.d.ts +70 -0
  142. package/dist/storyGraph.d.ts.map +1 -0
  143. package/dist/storyGraph.js +178 -0
  144. package/dist/storyGraph.js.map +1 -0
  145. package/dist/vision/VisionSourceController.d.ts +127 -0
  146. package/dist/vision/VisionSourceController.d.ts.map +1 -0
  147. package/dist/vision/VisionSourceController.js +284 -0
  148. package/dist/vision/VisionSourceController.js.map +1 -0
  149. package/dist/vision/index.d.ts +4 -0
  150. package/dist/vision/index.d.ts.map +1 -1
  151. package/dist/vision/index.js +2 -0
  152. package/dist/vision/index.js.map +1 -1
  153. package/dist/vision/sourceKinds.d.ts +65 -0
  154. package/dist/vision/sourceKinds.d.ts.map +1 -0
  155. package/dist/vision/sourceKinds.js +26 -0
  156. package/dist/vision/sourceKinds.js.map +1 -0
  157. package/dist/websocket.d.ts +92 -0
  158. package/dist/websocket.d.ts.map +1 -1
  159. package/dist/websocket.js.map +1 -1
  160. package/package.json +1 -1
  161. package/src/__tests__/adapters-capabilities.test.ts +46 -0
  162. package/src/__tests__/adapters-chat.test.ts +172 -0
  163. package/src/__tests__/adapters-director.test.ts +95 -0
  164. package/src/__tests__/adapters-image.test.ts +133 -0
  165. package/src/__tests__/adapters-platform.test.ts +95 -0
  166. package/src/__tests__/adapters-registry.test.ts +189 -0
  167. package/src/__tests__/adapters-world.test.ts +296 -0
  168. package/src/__tests__/admin.test.ts +312 -0
  169. package/src/__tests__/adventures-party.test.ts +219 -0
  170. package/src/__tests__/adventures.test.ts +282 -0
  171. package/src/__tests__/api-pollers.test.ts +4 -0
  172. package/src/__tests__/api.clip-lookup.test.ts +64 -0
  173. package/src/__tests__/api.list-images-filters.test.ts +103 -0
  174. package/src/__tests__/api.test.ts +553 -0
  175. package/src/__tests__/audio.test.ts +65 -0
  176. package/src/__tests__/cast.test.ts +95 -0
  177. package/src/__tests__/castProjection.test.ts +167 -0
  178. package/src/__tests__/conversation/binding.test.ts +62 -0
  179. package/src/__tests__/conversation/controller.test.ts +732 -0
  180. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  181. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  182. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  183. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  184. package/src/__tests__/conversation/roster.test.ts +100 -0
  185. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  186. package/src/__tests__/conversation/router.test.ts +81 -0
  187. package/src/__tests__/conversation/runtime.test.ts +206 -0
  188. package/src/__tests__/conversation/voice.test.ts +440 -0
  189. package/src/__tests__/documents.test.ts +360 -0
  190. package/src/__tests__/graphSchema.test.ts +218 -9
  191. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  192. package/src/__tests__/monitoring.test.ts +162 -0
  193. package/src/__tests__/persona-generation.test.ts +352 -0
  194. package/src/__tests__/platformAssistant.test.ts +484 -0
  195. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  196. package/src/__tests__/regeneration.test.ts +486 -0
  197. package/src/__tests__/stories.test.ts +171 -0
  198. package/src/__tests__/storyGraph.test.ts +134 -0
  199. package/src/__tests__/tools-wrappers.test.ts +272 -0
  200. package/src/__tests__/videoGraph.test.ts +94 -0
  201. package/src/__tests__/websocket.test.ts +263 -0
  202. package/src/adapters/capabilities.ts +24 -0
  203. package/src/adapters/chatAdapter.ts +114 -0
  204. package/src/adapters/directorAdapter.ts +126 -0
  205. package/src/adapters/imageAdapter.ts +100 -0
  206. package/src/adapters/index.ts +67 -0
  207. package/src/adapters/registry.ts +159 -0
  208. package/src/adapters/worldAdapter.ts +272 -0
  209. package/src/admin.ts +517 -0
  210. package/src/api.ts +2215 -95
  211. package/src/audio.ts +35 -0
  212. package/src/castProjection.ts +95 -0
  213. package/src/conversation/binding.ts +100 -0
  214. package/src/conversation/controller.ts +447 -0
  215. package/src/conversation/effectiveModel.ts +111 -0
  216. package/src/conversation/index.ts +27 -0
  217. package/src/conversation/participant.ts +71 -0
  218. package/src/conversation/presence.ts +60 -0
  219. package/src/conversation/presenceBus.ts +109 -0
  220. package/src/conversation/presenceRegistry.ts +83 -0
  221. package/src/conversation/roster.ts +111 -0
  222. package/src/conversation/rosterProjection.ts +98 -0
  223. package/src/conversation/router.ts +96 -0
  224. package/src/conversation/runtime.ts +188 -0
  225. package/src/conversation/types.ts +100 -0
  226. package/src/conversation/voice.ts +402 -0
  227. package/src/graphSchema.ts +396 -13
  228. package/src/http.ts +72 -0
  229. package/src/index.ts +9 -0
  230. package/src/platformAssistant.ts +347 -0
  231. package/src/reactor/chunkDistribution.ts +98 -0
  232. package/src/reactor/index.ts +5 -0
  233. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  234. package/src/reactor/scenesFromEnrichment.ts +11 -76
  235. package/src/reactor/seedImageOrchestrator.ts +12 -13
  236. package/src/reactor/storyTimeline.ts +127 -0
  237. package/src/storyGraph.ts +298 -0
  238. package/src/vision/VisionSourceController.ts +354 -0
  239. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  240. package/src/vision/index.ts +13 -0
  241. package/src/vision/sourceKinds.ts +75 -0
  242. package/src/websocket.ts +99 -3
@@ -0,0 +1,307 @@
1
+ /**
2
+ * `VoiceSession` (R7.5) — the framework-agnostic voice pipeline for the
3
+ * Conversation overlay.
4
+ *
5
+ * The R2.3/R2.4 Conversation overlay was TEXT-only (the controller's hello is
6
+ * `mode:'text'`; tech-debt #441). R7.5 lifts the FOUR page-owned voice pieces
7
+ * that live inside the 3,000-line `web/app/chat-ws/page.tsx` — the voice-mode
8
+ * `tts_stt` hello, mic capture (STT), audio playback + barge-in (TTS), and
9
+ * viseme scheduling — into ONE module that drives the SAME `ChatWebSocket` the
10
+ * `ConversationController` owns/adopts.
11
+ *
12
+ * DRY: this is a THIN composition, not a re-implementation. The
13
+ * player/viseme/barge-in/sentence-anchoring machinery already lives in
14
+ * `AudioPipeline` (audio.ts) and the hello in the single `buildHelloPayload`.
15
+ * The mic is the existing `MicrophoneRecorder`. `VoiceSession` only owns the
16
+ * lifecycle (the iOS user-gesture priming order, the socket handler wiring, and
17
+ * the dispose contract). There is NO second viseme scheduler, NO second
18
+ * hello-construction site, and NO second sentence-anchoring loop.
19
+ *
20
+ * Viseme delivery: `onViseme` is the SINGLE viseme callback. The React panel
21
+ * routes it into the presence face, which is the React realisation of R7.3's
22
+ * `PresenceAdapter.applyViseme` — visemes reach a face through exactly one path.
23
+ *
24
+ * Socket ownership: `VoiceSession` NEVER closes the socket on `dispose()` — the
25
+ * `ConversationController` (or the surface that owns an adopted socket) manages
26
+ * the transport. This preserves the Watch shared-socket invariant: voice on an
27
+ * adopted socket must not tear down the one `FrameBuffer` vision rides.
28
+ *
29
+ * `/chat-ws` is the parity ORACLE and is NOT rewired by R7.5: its page-owned
30
+ * pipeline stays verbatim, and `buildHello()` here is fixture-diffed against
31
+ * `startVoiceChat()`'s payload so the overlay's `tts_stt` hello is byte-identical.
32
+ */
33
+ import { AudioPipeline, MicrophoneRecorder, buildHelloPayload, } from '../audio.js';
34
+ /**
35
+ * Drives a full voice round-trip (STT in, TTS + visemes out) over a shared
36
+ * `ChatWebSocket`. Construct one per conversation; dispose it with the
37
+ * conversation. The socket is NOT owned here.
38
+ */
39
+ export class VoiceSession {
40
+ socket;
41
+ getHelloArgs;
42
+ voiceOptions;
43
+ callbacks;
44
+ pipeline = null;
45
+ recorder = null;
46
+ /** True once `hello_ack` lands — gates outbound mic frames so they are never
47
+ * sent into a server that has not wired up its receive side yet (the page's
48
+ * `audioReadyRef` contract). */
49
+ audioReady = false;
50
+ /** True between `start()` and `stop()`/`dispose()`. Gates reconnect re-send. */
51
+ active = false;
52
+ disposed = false;
53
+ /** The last hello sent, so a reconnect can re-send it (the page's
54
+ * `lastHelloRef`). Exposed via {@link reconnectHello}. */
55
+ lastHello = null;
56
+ messageHandler = (message) => this.handleMessage(message);
57
+ binaryHandler = (data) => this.handleBinary(data);
58
+ constructor(config) {
59
+ this.socket = config.socket;
60
+ this.getHelloArgs = config.getHelloArgs;
61
+ this.voiceOptions = config.voiceOptions ?? {};
62
+ this.callbacks = {
63
+ onViseme: config.onViseme,
64
+ onTranscript: config.onTranscript,
65
+ onSpeakingChange: config.onSpeakingChange,
66
+ onError: config.onError,
67
+ onStatus: config.onStatus,
68
+ };
69
+ }
70
+ /**
71
+ * Build the voice (`tts_stt`) hello. The SINGLE hello-builder: the context +
72
+ * active-participant args come from `getHelloArgs()` (which itself flows
73
+ * through `toHelloArgs`), the voice knobs from `voiceOptions`, and `mode` is
74
+ * forced to `'tts_stt'` — fed to the one `buildHelloPayload`. NO second
75
+ * construction site. This is the parity oracle target: for identical inputs
76
+ * it is byte-identical to the page's `startVoiceChat()` payload.
77
+ */
78
+ buildHello() {
79
+ return buildHelloPayload({
80
+ ...this.getHelloArgs(),
81
+ mode: 'tts_stt',
82
+ ...this.voiceOptions,
83
+ });
84
+ }
85
+ /** True while a voice session is running (between `start()` and stop). */
86
+ get isActive() {
87
+ return this.active;
88
+ }
89
+ /**
90
+ * Start voice. Mirrors `startVoiceChat()` (page.tsx:1770-1873) EXACTLY,
91
+ * including the iOS Safari user-gesture audio-activation order: the
92
+ * `AudioPipeline` (which creates the player's AudioContext) and the
93
+ * `MicrophoneRecorder.prime()` run in the SYNCHRONOUS prefix BEFORE the first
94
+ * await — an async wrapper around these silently breaks Safari mic activation.
95
+ * Callers MUST invoke `start()` from the synchronous prefix of the overlay
96
+ * button's click handler.
97
+ */
98
+ async start() {
99
+ if (this.disposed) {
100
+ throw new Error('VoiceSession: start() after dispose().');
101
+ }
102
+ if (!this.socket.isConnected) {
103
+ this.callbacks.onError?.('WebSocket connection required before starting voice chat.');
104
+ return;
105
+ }
106
+ if (this.active)
107
+ return;
108
+ // ─── iOS Safari user-gesture audio activation (synchronous prefix) ───
109
+ // Both AudioContexts (player + recorder) MUST be created and resume()'d
110
+ // inside the synchronous prefix of the click handler — see page.tsx:1776.
111
+ if (!this.pipeline) {
112
+ this.pipeline = new AudioPipeline((viseme) => this.callbacks.onViseme(viseme));
113
+ }
114
+ void this.pipeline.resume();
115
+ const recorder = new MicrophoneRecorder((frame) => {
116
+ if (!this.audioReady)
117
+ return;
118
+ try {
119
+ this.socket.sendAudioFrame(frame);
120
+ }
121
+ catch (err) {
122
+ console.error('Failed to send audio frame', err);
123
+ this.callbacks.onError?.('Unable to stream audio frame to server.');
124
+ }
125
+ }, (message) => this.callbacks.onError?.(message));
126
+ recorder.prime();
127
+ this.recorder = recorder;
128
+ // Subscribe to the socket BEFORE the hello so no early frame is missed.
129
+ this.socket.onMessage(this.messageHandler);
130
+ this.socket.onBinary(this.binaryHandler);
131
+ try {
132
+ this.callbacks.onStatus?.('Requesting microphone permission...');
133
+ this.audioReady = false;
134
+ // Safety-net await for non-iOS browsers (page.tsx:1809-1811).
135
+ await this.pipeline.resume();
136
+ // Barge-in: attach the session against the raw socket + start the
137
+ // playback-position tracker (page.tsx:1813-1827). `attachSession`
138
+ // wires the player; tracking makes the server's barge-in arbitration
139
+ // work against the real playhead.
140
+ const rawWs = this.socket.getRawSocket();
141
+ if (rawWs) {
142
+ this.pipeline.attachSession(rawWs);
143
+ this.pipeline.sessionClient?.startPlaybackTracking();
144
+ }
145
+ const hello = this.buildHello();
146
+ this.lastHello = hello;
147
+ this.socket.sendHello(hello);
148
+ await recorder.start();
149
+ this.active = true;
150
+ this.callbacks.onStatus?.('Microphone streaming. Say something to begin transcription.');
151
+ }
152
+ catch (err) {
153
+ // A failed start (typically a denied mic permission from
154
+ // `recorder.start()`) must NOT resolve silently: the panel flips
155
+ // `isVoiceActive` true BEFORE calling start() and only reverts it on a
156
+ // rejection, so swallowing here would strand the UI showing Stop/Interrupt
157
+ // while no session runs (codex P2). Tear down + surface the error AND
158
+ // rethrow so the caller's `.catch()` clears its active state.
159
+ console.error('Failed to start voice chat', err);
160
+ this.callbacks.onError?.('Unable to start voice chat. Please check microphone permissions.');
161
+ this.resetAudio();
162
+ throw err;
163
+ }
164
+ }
165
+ /**
166
+ * Stop voice capture/playback but keep the session reusable. Mirrors the
167
+ * page's `stopVoiceChat()` + `resetAudioState()`. Detaches socket handlers
168
+ * and tears down the audio resources; the socket itself is left OPEN (the
169
+ * owner manages it).
170
+ */
171
+ stop() {
172
+ this.active = false;
173
+ this.lastHello = null;
174
+ this.resetAudio();
175
+ this.callbacks.onStatus?.('Voice capture paused.');
176
+ }
177
+ /**
178
+ * Barge-in: interrupt the assistant's current audio. Mirrors the page's
179
+ * `handleInterrupt()` — delegates to the pipeline's `bargeIn()` (which sends
180
+ * the server `barge_in`, clears the player queue + visemes) and flips the
181
+ * speaking flag off. No-op when nothing is playing.
182
+ */
183
+ async interrupt() {
184
+ if (!this.pipeline)
185
+ return;
186
+ try {
187
+ await this.pipeline.bargeIn();
188
+ this.callbacks.onSpeakingChange?.(false);
189
+ }
190
+ catch (err) {
191
+ console.error('Failed to interrupt playback', err);
192
+ }
193
+ }
194
+ /**
195
+ * Re-send the voice hello after a socket reconnect, IF a voice session is
196
+ * active. Returns the payload (so a host that owns socket construction can
197
+ * wire this into `ChatWebSocket`'s `onReconnect` option) or `null` when voice
198
+ * is inactive (text reconnect — nothing to re-send). NOTE: it does NOT
199
+ * re-prime the mic/AudioSession (the page does, but that path is iOS-gesture
200
+ * gapped on an event-loop reconnect and requires the host to own socket
201
+ * construction — tracked as a follow-up). The hello re-send alone restores
202
+ * the server-side voice routing for the existing recorder's frames.
203
+ */
204
+ reconnectHello() {
205
+ if (!this.active || !this.lastHello)
206
+ return null;
207
+ return this.lastHello;
208
+ }
209
+ /**
210
+ * Tear down. Stops audio + detaches handlers, then becomes inert. NEVER
211
+ * closes the socket — the controller / adopting surface owns the transport
212
+ * (the Watch shared-socket invariant). Idempotent.
213
+ */
214
+ dispose() {
215
+ if (this.disposed)
216
+ return;
217
+ this.disposed = true;
218
+ this.active = false;
219
+ this.lastHello = null;
220
+ this.resetAudio();
221
+ }
222
+ // ── internals ──────────────────────────────────────────────────────────
223
+ /** Tear down audio resources + detach socket handlers, leaving the socket
224
+ * open. Idempotent; mirrors the page's `resetAudioState`. */
225
+ resetAudio() {
226
+ this.socket.offMessage(this.messageHandler);
227
+ this.socket.offBinary(this.binaryHandler);
228
+ this.recorder?.stop();
229
+ this.recorder = null;
230
+ if (this.pipeline) {
231
+ void this.pipeline.destroy();
232
+ this.pipeline = null;
233
+ }
234
+ this.audioReady = false;
235
+ this.callbacks.onSpeakingChange?.(false);
236
+ }
237
+ /**
238
+ * Reset per-turn audio state for a new assistant reply. Mirrors the page's
239
+ * new-assistant-turn reset (page.tsx:1244-1251): the pipeline's barge-in /
240
+ * sentence-anchor state (`AudioPipeline.resetTurn`), the player's
241
+ * `playbackOrigin` (so playback positions for the next reply are 0-based), and
242
+ * the viseme scheduler (so a stale tail doesn't bleed into the new turn). The
243
+ * pipeline's `player`/`visemeScheduler` are public readonly handles. No-op
244
+ * before the first `start()` (no pipeline yet).
245
+ */
246
+ resetTurn() {
247
+ if (!this.pipeline)
248
+ return;
249
+ this.pipeline.resetTurn();
250
+ this.pipeline.player.playbackOrigin = 0;
251
+ this.pipeline.visemeScheduler.clear();
252
+ }
253
+ handleMessage(message) {
254
+ switch (message.type) {
255
+ case 'hello_ack': {
256
+ this.audioReady = true;
257
+ this.callbacks.onStatus?.('Audio handshake acknowledged. Streaming microphone frames.');
258
+ this.callbacks.onSpeakingChange?.(false);
259
+ return;
260
+ }
261
+ case 'transcript': {
262
+ this.audioReady = true;
263
+ const text = message.text?.trim() ?? '';
264
+ if (message.final) {
265
+ // A final transcript begins a NEW assistant turn. Reset the
266
+ // pipeline/player turn state BEFORE the new reply's audio is tracked
267
+ // — the backend resets its barge-in timestamps to 0 for every
268
+ // `_process_turn`, so without this the client keeps reporting
269
+ // playback positions relative to the FIRST audio frame of the whole
270
+ // session and a later-turn Interrupt makes the server think the reply
271
+ // was already fully spoken (codex P2; mirrors page.tsx:1244-1251).
272
+ this.resetTurn();
273
+ if (text)
274
+ this.callbacks.onTranscript?.(text, true);
275
+ }
276
+ else {
277
+ this.callbacks.onTranscript?.(text, false);
278
+ }
279
+ return;
280
+ }
281
+ case 'audio_metadata': {
282
+ // Visemes + word timestamps. The pipeline buffers metadata that races
283
+ // ahead of binary frames (Inworld ASYNC mode) and schedules visemes
284
+ // through the SINGLE scheduler → `onViseme`.
285
+ this.pipeline?.handleAudioMetadata(message);
286
+ this.callbacks.onSpeakingChange?.(true);
287
+ return;
288
+ }
289
+ case 'barge_in_ack': {
290
+ this.callbacks.onSpeakingChange?.(false);
291
+ return;
292
+ }
293
+ default:
294
+ // token/citation/image/done/error/turn_changed/tool_result/metrics —
295
+ // the panel's text consumer owns those; VoiceSession only handles the
296
+ // audio-pipeline frames.
297
+ return;
298
+ }
299
+ }
300
+ handleBinary(data) {
301
+ if (!this.pipeline)
302
+ return;
303
+ this.pipeline.handleBinaryFrame(data);
304
+ this.callbacks.onSpeakingChange?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AAgB,EAAE,CAAC,IAAI,CAAC,CAAC;IAC1C,CAAC;CACF"}
@@ -8,22 +8,58 @@
8
8
  * against the same vocabulary the backend validates against.
9
9
  *
10
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.
11
+ * describes the **graph schema only** — node labels, relationship types, the
12
+ * user-creation whitelists (M7 P3a: {@link userCreatableLabels} /
13
+ * {@link userCreatableEdges} / {@link allowedPairs}), and the two provenance
14
+ * vocabularies. It must NOT grow tool/MCP schemas or request/response DTOs.
14
15
  *
15
16
  * 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
- /** Every node label that exists in the video graph today. */
21
- export type GraphNodeLabel = 'Video' | 'Shot' | 'Entity' | 'Event' | 'DialogLine';
22
- /** Every relationship type that exists in the video graph today. */
23
- export type GraphRelationshipType = 'HAS_SHOT' | 'MENTIONS' | 'HAS_EVENT' | 'HAS_DIALOG' | 'SPOKEN_BY' | 'NEXT';
17
+ * static extension point (for Story-Engine narrative nodes like `Act` /
18
+ * `Scene` / `PlotBeat` / `CharacterArc`) has no runtime equivalent here — a
19
+ * phase that adds a narrative label widens these unions in the same change.
20
+ * M7 P3a added `Scene` / `PlotBeat` / `CharacterArc` to the node vocabulary and
21
+ * the six story edges to the relationship vocabulary.
22
+ *
23
+ * Read-surface vs create-surface (mirrors the backend split): the `GRAPH_*`
24
+ * unions/tuples are the READ-SURFACE — the full vocabulary a viewer can
25
+ * encounter (every node label, every edge type on `getVideoGraph` edges). The
26
+ * `userCreatable*` exports are the strict CREATE-SURFACE subset authorized by
27
+ * `POST /graph/{nodes,edges}`. Widening the read-surface is additive — the
28
+ * public exports are pinned by the sibling Vue Web-App and must never shrink.
29
+ */
30
+ /**
31
+ * Every node label in the video + story graph. The first five exist in the
32
+ * pipeline-produced video graph; `Scene` / `PlotBeat` / `CharacterArc` are the
33
+ * Story-Engine narrative labels added in M7 Phase 3a (creatable via
34
+ * `POST /graph/nodes` — see {@link userCreatableLabels}).
35
+ */
36
+ export type GraphNodeLabel = 'Video' | 'Shot' | 'Entity' | 'Event' | 'DialogLine' | 'Act' | 'Scene' | 'PlotBeat' | 'CharacterArc' | 'SourceDoc' | 'Persona';
37
+ /**
38
+ * READ-SURFACE: every relationship type a viewer can encounter on edges
39
+ * returned by `getVideoGraph`. This is the full graph vocabulary — the original
40
+ * pipeline edges (`HAS_SHOT` / `MENTIONS` / `HAS_EVENT` / `HAS_DIALOG` /
41
+ * `SPOKEN_BY` / `NEXT`), the M7 narrative-structural edges (`HAS_ACT` /
42
+ * `IN_ACT` / `CONTAINS` / `INCLUDES`), and the six M7 P3a user-creatable story
43
+ * edges (`RELATES_TO` / `CAUSES` / `SET_IN` / `FEATURES` / `ON_ARC` /
44
+ * `LEADS_TO`).
45
+ *
46
+ * This is a SUPERSET of the original pipeline union (additive, no removal — the
47
+ * frozen public contract pinned by the sibling Vue Web-App stays valid).
48
+ *
49
+ * The CREATE-SURFACE is the strict subset {@link userCreatableEdges} (the six
50
+ * story edges only); `POST /graph/edges` rejects everything else (422). Mirror
51
+ * of the backend split: `shared/graph_schema.py` widens the `RelationshipType`
52
+ * read vocabulary while `VALID_RELATIONSHIP_TYPES` / `user_creatable_edges`
53
+ * stay the six.
54
+ */
55
+ export type GraphRelationshipType = 'HAS_SHOT' | 'MENTIONS' | 'HAS_EVENT' | 'HAS_DIALOG' | 'SPOKEN_BY' | 'NEXT' | 'HAS_ACT' | 'IN_ACT' | 'CONTAINS' | 'INCLUDES' | 'RELATES_TO' | 'CAUSES' | 'SET_IN' | 'FEATURES' | 'ON_ARC' | 'LEADS_TO' | 'ANNOTATES' | 'PORTRAYS';
24
56
  /** Runtime tuple of all node labels (mirrors `VALID_NODE_LABELS`). */
25
57
  export declare const GRAPH_NODE_LABELS: readonly GraphNodeLabel[];
26
- /** Runtime tuple of all relationship types (mirrors `VALID_RELATIONSHIP_TYPES`). */
58
+ /**
59
+ * Runtime tuple of the READ-SURFACE relationship vocabulary — every edge type a
60
+ * viewer can encounter on `getVideoGraph` edges. SUPERSET of the original
61
+ * pipeline edges (additive). The create-surface subset is {@link userCreatableEdges}.
62
+ */
27
63
  export declare const GRAPH_RELATIONSHIP_TYPES: readonly GraphRelationshipType[];
28
64
  /**
29
65
  * Primary-key property per node label (mirrors `PRIMARY_KEY`).
@@ -34,7 +70,82 @@ export declare const GRAPH_RELATIONSHIP_TYPES: readonly GraphRelationshipType[];
34
70
  * same change — TS will flag the gap as a type error until both are updated.
35
71
  */
36
72
  export declare const GRAPH_PRIMARY_KEY: Readonly<Record<GraphNodeLabel, string>>;
37
- /** User-editable properties per node label (mirrors `EDITABLE_NODE_PROPERTIES`). */
73
+ /**
74
+ * Story Engine Phase 5 — the node label for graph entities. Single source for
75
+ * the ``'Entity'`` label string so call sites (e.g. the persona↔character
76
+ * binding affordance) don't hardcode it. Mirrors
77
+ * ``shared/neo4j_queries.py:LABEL_ENTITY``.
78
+ */
79
+ export declare const GRAPH_ENTITY_LABEL: GraphNodeLabel;
80
+ /**
81
+ * Story Engine Phase 5 — the ``Entity.type`` property value identifying a
82
+ * character (vs. location / object / organization). Mirrors backend
83
+ * ``shared/models.py:EntityType.CHARACTER``. Used to gate character-only UI
84
+ * without hardcoding the literal at call sites.
85
+ */
86
+ export declare const ENTITY_TYPE_CHARACTER: "character";
87
+ /** Node labels the studio read-surface (and `storyGraph`) match. */
88
+ export declare const STUDIO_NODE_LABELS: {
89
+ /** 'Act' — read-only at runtime; not in the create-surface union. */
90
+ readonly ACT: "Act";
91
+ readonly SCENE: "Scene";
92
+ readonly SHOT: "Shot";
93
+ readonly ENTITY: "Entity";
94
+ readonly CHARACTER_ARC: "CharacterArc";
95
+ };
96
+ /** Edge (relationship) types the studio read-surface (and `storyGraph`) traverse. */
97
+ export declare const STUDIO_EDGE_TYPES: {
98
+ /** Structural containment: Act→Scene and Scene→Shot. */
99
+ readonly CONTAINS: "CONTAINS";
100
+ /** Alternate structural containment used by some pipeline writers. */
101
+ readonly INCLUDES: "INCLUDES";
102
+ /** Scene⇄character feature edge. */
103
+ readonly FEATURES: "FEATURES";
104
+ /** Scene→location edge (the location an entity is set in). */
105
+ readonly SET_IN: "SET_IN";
106
+ /** Character→CharacterArc edge. */
107
+ readonly ON_ARC: "ON_ARC";
108
+ /** Character⇄character relationship edge. */
109
+ readonly RELATES_TO: "RELATES_TO";
110
+ };
111
+ /**
112
+ * Node `properties` keys as they appear in the `get_video_graph` payload's
113
+ * `properties` map (mirrors the backend MERGE_* SET clauses).
114
+ */
115
+ export declare const STUDIO_NODE_PROPERTIES: {
116
+ readonly TITLE: "title";
117
+ readonly INDEX: "index";
118
+ readonly SUMMARY: "summary";
119
+ readonly DESCRIPTION: "description";
120
+ /** Scene/Shot time bounds (numeric seconds) — MERGE_SCENE / MERGE_SHOT. */
121
+ readonly START_TIME: "startTime";
122
+ readonly END_TIME: "endTime";
123
+ /** Act time bounds (numeric seconds) — MERGE_ACT uses t0/t1, not start/endTime. */
124
+ readonly T0: "t0";
125
+ readonly T1: "t1";
126
+ readonly NAME: "name";
127
+ readonly ENTITY_TYPE: "type";
128
+ readonly ALIASES: "aliases";
129
+ readonly ENTITY_ID: "entityId";
130
+ readonly SCENE_ID: "sceneId";
131
+ readonly SHOT_ID: "shotId";
132
+ readonly ARC_ID: "arcId";
133
+ readonly CAPTION: "caption";
134
+ };
135
+ /** The `Entity.type` value identifying a character (single source). */
136
+ export declare const STUDIO_CHARACTER_TYPE: "character";
137
+ /**
138
+ * User-editable properties per node label (mirrors `EDITABLE_NODE_PROPERTIES`).
139
+ *
140
+ * RUNTIME SOURCE OF TRUTH: the graph editor's live editable-property /
141
+ * primary-key whitelists now come from the fetched `GET /graph/schema` payload
142
+ * (see {@link fetchGraphSchema} and `web/app/jobs/[videoId]/graph/page.tsx`), so
143
+ * a backend whitelist change auto-propagates with no TS edit. These static
144
+ * `GRAPH_*` constants remain as the COMPILE-TIME typed vocabulary and a
145
+ * back-compat fallback (used while the schema is in flight, and imported by the
146
+ * sibling Vue Web-App). Keep them mirrored with the backend; do not treat them
147
+ * as the runtime authority for the editor.
148
+ */
38
149
  export declare const GRAPH_EDITABLE_NODE_PROPERTIES: Readonly<Record<GraphNodeLabel, readonly string[]>>;
39
150
  /**
40
151
  * Editable relationship properties (mirrors `EDITABLE_RELATIONSHIP_PROPERTIES`).
@@ -42,6 +153,55 @@ export declare const GRAPH_EDITABLE_NODE_PROPERTIES: Readonly<Record<GraphNodeLa
42
153
  * carries no ordering contract; treat it as a set (membership), not a sequence.
43
154
  */
44
155
  export declare const GRAPH_EDITABLE_RELATIONSHIP_PROPERTIES: readonly string[];
156
+ /**
157
+ * Node labels a creator may instantiate via `POST /graph/nodes`
158
+ * (mirrors `user_creatable_labels`). `Act` is pipeline-only (creators edit but
159
+ * do not create it); `Video`/`Shot`/`Entity`/`Event`/`DialogLine` are never
160
+ * user-creatable.
161
+ */
162
+ export declare const userCreatableLabels: readonly GraphNodeLabel[];
163
+ /**
164
+ * CREATE-SURFACE relationship type — the strict subset of
165
+ * {@link GraphRelationshipType} a creator may instantiate via
166
+ * `POST /graph/edges`. Mirrors the backend `VALID_RELATIONSHIP_TYPES` /
167
+ * `user_creatable_edges`. The read-only pipeline / narrative-structural edges
168
+ * (`MENTIONS` / `HAS_*` / `CONTAINS` / `INCLUDES`, etc.) are part of the
169
+ * read-surface but NOT this create-surface.
170
+ */
171
+ export type UserCreatableEdge = 'RELATES_TO' | 'CAUSES' | 'SET_IN' | 'FEATURES' | 'ON_ARC' | 'LEADS_TO';
172
+ /**
173
+ * CREATE-SURFACE: relationship types a creator may instantiate via
174
+ * `POST /graph/edges` (mirrors `user_creatable_edges`, identical to the
175
+ * backend's `VALID_RELATIONSHIP_TYPES`). A strict subset of the read-surface
176
+ * {@link GRAPH_RELATIONSHIP_TYPES}: the read-only pipeline / narrative-structural
177
+ * edges (`MENTIONS` / `HAS_*` / `CONTAINS` / `INCLUDES`, etc.) are encounterable
178
+ * on `getVideoGraph` but NOT creatable — the backend 422s them.
179
+ */
180
+ export declare const userCreatableEdges: readonly UserCreatableEdge[];
181
+ /**
182
+ * Allowed `(sourceLabel, targetLabel)` endpoint pairs per user-creatable edge
183
+ * type (mirrors `_VALID_EDGE_PAIRS`). The backend rejects any edge whose
184
+ * endpoint labels are not listed here (422); for `SET_IN` / `FEATURES` the
185
+ * target `Entity.type` (location / character) is validated separately by a
186
+ * server-side read. Keyed by {@link UserCreatableEdge} (the create-surface only,
187
+ * not the full read-surface), valued by readonly `[GraphNodeLabel, GraphNodeLabel]`
188
+ * pairs.
189
+ */
190
+ export declare const allowedPairs: Readonly<Record<UserCreatableEdge, readonly (readonly [GraphNodeLabel, GraphNodeLabel])[]>>;
191
+ /**
192
+ * Allowed `kind` values for a user-created `RELATES_TO` edge — mirrors the
193
+ * backend single source of truth (`shared/models.py:RelationshipKind`
194
+ * StrEnum: `ally|rival|family|romantic|mentor|custom`). Exposed so the M7 P3b
195
+ * CreateEdgePopover `kind` dropdown does not hand-roll the string list (DRY):
196
+ * the create-surface UI imports this rather than re-declaring it.
197
+ *
198
+ * Additive (M7 P3b): widens the create-surface mirror only; no existing export
199
+ * is removed or renamed, so the frozen public contract (pinned by the sibling
200
+ * Vue Web-App) stays valid.
201
+ */
202
+ export type RelationshipKindValue = 'ally' | 'rival' | 'family' | 'romantic' | 'mentor' | 'custom';
203
+ /** Runtime tuple of {@link RelationshipKindValue} (mirrors `RelationshipKind`). */
204
+ export declare const RELATIONSHIP_KIND_VALUES: readonly RelationshipKindValue[];
45
205
  /**
46
206
  * How a story-graph node/edge entered the graph. Separate from
47
207
  * {@link MemoryFactProvenance} — do not merge them.
@@ -69,4 +229,32 @@ export declare const AUTHORED_MEMORY_PROVENANCE: ReadonlySet<MemoryFactProvenanc
69
229
  export declare function isStoryGraphProvenance(value: string): value is StoryGraphProvenance;
70
230
  /** Type guard mirroring `is_memory_fact_provenance` in `shared/provenance.py`. */
71
231
  export declare function isMemoryFactProvenance(value: string): value is MemoryFactProvenance;
232
+ import type { GraphSchemaResponse } from './api';
233
+ /** Re-export the wire type so consumers import it from one module. */
234
+ export type { GraphSchemaResponse } from './api';
235
+ /**
236
+ * Minimal client surface `fetchGraphSchema` depends on. Keeps this module
237
+ * framework-agnostic and decoupled from the concrete `ApiClient` class — any
238
+ * object exposing `getGraphSchema()` works (real client or a test fake).
239
+ */
240
+ export interface GraphSchemaClient {
241
+ getGraphSchema(): Promise<GraphSchemaResponse>;
242
+ }
243
+ /**
244
+ * Session-scoped memoized fetch of `GET /graph/schema`. The first call kicks
245
+ * off the request; every subsequent call (concurrent or later) awaits the same
246
+ * cached promise — so `client.getGraphSchema()` runs exactly once per session.
247
+ *
248
+ * On rejection the cache is cleared so the next call retries rather than
249
+ * permanently surfacing a stale error (a transient network blip must not brick
250
+ * the editor for the rest of the session).
251
+ *
252
+ * Call `__resetGraphSchemaCache()` in tests (or on logout) to drop the cache.
253
+ */
254
+ export declare function fetchGraphSchema(client: GraphSchemaClient): Promise<GraphSchemaResponse>;
255
+ /**
256
+ * Test hook: drop the memoized schema promise so the next `fetchGraphSchema`
257
+ * starts fresh. Also usable on logout / session reset.
258
+ */
259
+ export declare function __resetGraphSchemaCache(): void;
72
260
  //# sourceMappingURL=graphSchema.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"graphSchema.d.ts","sourceRoot":"","sources":["../src/graphSchema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAMH,6DAA6D;AAC7D,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,YAAY,CAAC;AAElF,oEAAoE;AACpE,MAAM,MAAM,qBAAqB,GAC7B,UAAU,GACV,UAAU,GACV,WAAW,GACX,YAAY,GACZ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