@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,553 @@
1
+ /**
2
+ * Framework-agnostic WebRTC vision publisher.
3
+ *
4
+ * Lifecycle:
5
+ * - `start()` opens an `RTCPeerConnection`, attaches the video track,
6
+ * creates an SDP offer, ships it to the backend over the
7
+ * authenticated `ChatWebSocket`, and listens for the answer + ICE.
8
+ * - `stop()` closes the peer connection, removes WS event listeners,
9
+ * and notifies the backend with a `vision_close` so it can free
10
+ * its `FrameBuffer` and aiortc receiver.
11
+ *
12
+ * Auto-restart: if `pc.connectionState` transitions to `'failed'`, the
13
+ * publisher emits an error and tears down. Restart-on-failure is the
14
+ * caller's responsibility (React hook / Vue composable) — that keeps
15
+ * this class free of timer/retry state and easy to test in isolation.
16
+ *
17
+ * Wire-shape source of truth: `shared/vision_protocol.py`. Camel-case
18
+ * field names live here; the `ChatWebSocket` boundary converts to
19
+ * snake_case before sending and back to camel-case on receive.
20
+ *
21
+ * Spec: `specs/2026-05-22-phase-2-multimodal-watch.md`.
22
+ */
23
+
24
+ import type { ChatWebSocket, ChatWsTypedEvent } from '../websocket';
25
+ import type {
26
+ VisionErrorListener,
27
+ VisionPublisherOptions,
28
+ VisionRtcCredentials,
29
+ VisionStatus,
30
+ VisionStatusListener,
31
+ } from './types';
32
+
33
+ interface InboundVisionAnswer {
34
+ type: 'vision_answer';
35
+ sdp: string;
36
+ }
37
+
38
+ interface InboundVisionIce {
39
+ action: 'vision_ice';
40
+ candidate: string | null;
41
+ sdpMid?: string | null;
42
+ sdpMLineIndex?: number | null;
43
+ }
44
+
45
+ interface InboundVisionStatus extends VisionStatus {
46
+ type: 'vision_status';
47
+ }
48
+
49
+ type WsEventHandler = (msg: unknown) => void | Promise<void>;
50
+
51
+ /**
52
+ * Subset of the KVS WebRTC SDK's `SignalingClient` we depend on.
53
+ * Declaring it as a local interface (rather than importing the type
54
+ * from `amazon-kinesis-video-streams-webrtc`) keeps client-core
55
+ * type-checkable without a hard build-time dep on the optional peer.
56
+ */
57
+ interface KvsSignalingClientLike {
58
+ open(): void;
59
+ close(): void;
60
+ on(event: 'open', handler: () => void): void;
61
+ on(event: 'sdpAnswer', handler: (answer: RTCSessionDescriptionInit) => void): void;
62
+ on(event: 'iceCandidate', handler: (candidate: RTCIceCandidateInit) => void): void;
63
+ on(event: 'close', handler: () => void): void;
64
+ on(event: 'error', handler: (err: unknown) => void): void;
65
+ sendSdpOffer(offer: RTCSessionDescriptionInit): void;
66
+ sendIceCandidate(candidate: RTCIceCandidateInit): void;
67
+ }
68
+
69
+ const DEFAULT_FPS = 1.0;
70
+
71
+ export class VisionPublisher {
72
+ private readonly ws: ChatWebSocket;
73
+ private readonly track: MediaStreamTrack;
74
+ private readonly fps: number;
75
+ private readonly iceServers: RTCIceServer[];
76
+ private readonly credentials: VisionRtcCredentials | null;
77
+ private pc: RTCPeerConnection | null = null;
78
+ private kvsSignalingClient: KvsSignalingClientLike | null = null;
79
+ private statusListeners: VisionStatusListener[] = [];
80
+ private errorListeners: VisionErrorListener[] = [];
81
+ private wsHandlers: Array<{ event: ChatWsTypedEvent; handler: WsEventHandler }> = [];
82
+ private stopped = false;
83
+
84
+ constructor(opts: VisionPublisherOptions) {
85
+ this.ws = opts.ws;
86
+ this.track = VisionPublisher.resolveTrack(opts.track);
87
+ this.fps = opts.config?.fps ?? DEFAULT_FPS;
88
+ this.credentials = opts.credentials ?? null;
89
+ // Prefer KVS-provided ICE servers when credentials carry them;
90
+ // fall back to the caller's explicit override, then the public
91
+ // STUN default for legacy callers.
92
+ this.iceServers =
93
+ this.credentials?.iceServers ??
94
+ opts.config?.iceServers ??
95
+ VisionPublisher.DEFAULT_ICE_SERVERS;
96
+ }
97
+
98
+ /**
99
+ * Default ICE server set when neither `credentials.iceServers` nor
100
+ * `config.iceServers` is provided.
101
+ *
102
+ * Includes a single public STUN server so the browser can generate
103
+ * server-reflexive (`srflx`) candidates. This is required for
104
+ * connectivity in local-dev (browser ↔ Python on the same host) where
105
+ * aiortc may not advertise a candidate the browser can route to
106
+ * directly. In production, `credentials.iceServers` returned by the
107
+ * `/vision-rtc/credentials` endpoint carries KVS-managed STUN + TURN
108
+ * URIs, so this default is only the fallback path. Privacy-sensitive
109
+ * callers can still pass `iceServers: []` via `config` to skip STUN
110
+ * entirely.
111
+ */
112
+ static readonly DEFAULT_ICE_SERVERS: RTCIceServer[] = [
113
+ { urls: 'stun:stun.l.google.com:19302' },
114
+ ];
115
+
116
+ /**
117
+ * Open the peer connection. Routing is mode-aware:
118
+ *
119
+ * - **No credentials passed OR `credentials.mode === 'local'`**: the
120
+ * publisher uses the existing chat-WS protocol (`vision_offer` /
121
+ * `vision_ice` / `vision_close`). No AWS dependency. Default for
122
+ * local-dev (`WEBRTC_SIGNALING_MODE=local`).
123
+ * - **`credentials.mode === 'kvs'`**: the publisher dynamically
124
+ * imports the Amazon KVS WebRTC SDK and opens the signed wss:// URL
125
+ * from `credentials.signedSignalingUrl`. Used in deployed
126
+ * environments.
127
+ *
128
+ * The two paths share the same `RTCPeerConnection` setup, status /
129
+ * error event surface, and `stop()` teardown. Only signaling differs.
130
+ */
131
+ async start(): Promise<void> {
132
+ // Re-entry guard: a second start() without an intervening stop()
133
+ // would replace `this.pc` and `this.wsHandlers` without tearing
134
+ // down the prior PC/listeners — those would leak permanently on
135
+ // the long-lived ChatWebSocket. Force a clean slate first.
136
+ if (this.pc || this.wsHandlers.length > 0 || this.kvsSignalingClient) {
137
+ this.stop();
138
+ }
139
+ this.stopped = false;
140
+ if (this.credentials?.mode === 'kvs') {
141
+ await this.startKvsMode();
142
+ return;
143
+ }
144
+ await this.startLocalMode();
145
+ }
146
+
147
+ /**
148
+ * Local-mode signaling: SDP offer/answer + ICE trickle go through the
149
+ * authenticated chat-WS. The backend's `ws.py` `_handle_vision_offer`
150
+ * etc. accept them.
151
+ */
152
+ private async startLocalMode(): Promise<void> {
153
+ // Defensive clear in case a prior session left handlers attached.
154
+ // ``stop()`` already unsubscribes them, but a socket that closes
155
+ // between ``stop()`` calling ``ws.off()`` and the off taking
156
+ // effect could leave stale listeners alive. Re-clearing here
157
+ // ensures a fresh ``start()`` never doubles up on dispatches.
158
+ this.wsHandlers = [];
159
+ const pc = new RTCPeerConnection({ iceServers: this.iceServers });
160
+ this.pc = pc;
161
+
162
+ pc.addEventListener('icecandidate', (ev) => {
163
+ const candidate = (ev as RTCPeerConnectionIceEvent).candidate;
164
+ if (!candidate) {
165
+ // End-of-candidates sentinel. The backend expects an explicit
166
+ // `null` candidate to know trickle ICE is finished.
167
+ this.ws.sendVisionIce({ action: 'vision_ice', candidate: null });
168
+ return;
169
+ }
170
+ this.ws.sendVisionIce({
171
+ action: 'vision_ice',
172
+ candidate: candidate.candidate,
173
+ sdpMid: candidate.sdpMid ?? null,
174
+ sdpMLineIndex: candidate.sdpMLineIndex ?? null,
175
+ });
176
+ });
177
+
178
+ pc.addEventListener('connectionstatechange', () => {
179
+ if (!this.pc) return;
180
+ if (this.pc.connectionState === 'failed' && !this.stopped) {
181
+ this.emitError(new Error('VisionPublisher peer connection failed'));
182
+ this.stop();
183
+ }
184
+ });
185
+
186
+ pc.addTrack(this.track);
187
+
188
+ const onAnswer: WsEventHandler = async (msg) => {
189
+ if (!this.pc) return;
190
+ const { sdp } = msg as InboundVisionAnswer;
191
+ try {
192
+ await this.pc.setRemoteDescription({ type: 'answer', sdp });
193
+ } catch (err) {
194
+ // setRemoteDescription failure leaves the PC in an invalid
195
+ // signaling state — subsequent ICE/SDP calls would fail with
196
+ // cryptic "wrong state" errors that obscure the real cause.
197
+ // Force a clean teardown so the next start() builds a fresh PC.
198
+ this.emitError(err instanceof Error ? err : new Error(String(err)));
199
+ this.stop();
200
+ }
201
+ };
202
+
203
+ const onIce: WsEventHandler = async (msg) => {
204
+ if (!this.pc) return;
205
+ const ice = msg as InboundVisionIce;
206
+ if (!ice.candidate) {
207
+ // null candidate = end-of-candidates from the server; nothing to add.
208
+ return;
209
+ }
210
+ try {
211
+ await this.pc.addIceCandidate({
212
+ candidate: ice.candidate,
213
+ sdpMid: ice.sdpMid ?? undefined,
214
+ sdpMLineIndex: ice.sdpMLineIndex ?? undefined,
215
+ });
216
+ } catch (err) {
217
+ // ICE candidate failure is recoverable (other candidates may
218
+ // succeed) — emit but don't tear down the connection.
219
+ this.emitError(err instanceof Error ? err : new Error(String(err)));
220
+ }
221
+ };
222
+
223
+ const onStatus: WsEventHandler = (msg) => {
224
+ const status = msg as InboundVisionStatus;
225
+ const payload: VisionStatus = {
226
+ bufferedFrames: status.bufferedFrames,
227
+ processingPaused: status.processingPaused,
228
+ };
229
+ for (const listener of this.statusListeners) listener(payload);
230
+ };
231
+
232
+ this.ws.on('vision_answer', onAnswer);
233
+ this.ws.on('vision_ice', onIce);
234
+ this.ws.on('vision_status', onStatus);
235
+ this.wsHandlers = [
236
+ { event: 'vision_answer', handler: onAnswer },
237
+ { event: 'vision_ice', handler: onIce },
238
+ { event: 'vision_status', handler: onStatus },
239
+ ];
240
+
241
+ // Mirror the KVS-mode stop-race guards: if stop() is called while
242
+ // createOffer/setLocalDescription are in flight (rapid React HMR,
243
+ // unmount+remount in dev, or a fast vision-toggle cycle), the
244
+ // awaits continue against a closed PC and throw InvalidStateError.
245
+ // The guards short-circuit cleanly instead.
246
+ const offer = await pc.createOffer();
247
+ if (this.stopped) return;
248
+ await pc.setLocalDescription(offer);
249
+ if (this.stopped) return;
250
+
251
+ this.ws.sendVisionOffer({
252
+ action: 'vision_offer',
253
+ sdp: offer.sdp ?? '',
254
+ fps: this.fps,
255
+ });
256
+ }
257
+
258
+ /**
259
+ * KVS-mode signaling: SDP offer/answer + ICE trickle flow through
260
+ * an Amazon KVS WebRTC signaling channel. The SDK is dynamically
261
+ * imported so local-only builds (which never set `credentials.mode
262
+ * === 'kvs'`) don't pay the bundle cost.
263
+ *
264
+ * The signed wss:// URL the backend mints is what the SDK opens —
265
+ * raw AWS credentials never reach the browser. ICE servers in
266
+ * `credentials.iceServers` include the KVS-managed STUN entry plus
267
+ * any short-term TURN entries (`expiresIn` seconds). Callers must
268
+ * re-fetch credentials before that elapses if a session outlives
269
+ * the TTL; this publisher does not auto-refresh.
270
+ *
271
+ * **Async timing note:** the SDP offer is NOT sent inline with
272
+ * `start()`. The KVS SignalingClient uses an EventEmitter pattern —
273
+ * we subscribe to its `open` event and send the offer from inside
274
+ * that handler. So `start()` returns to the caller before the offer
275
+ * has been created or sent (an event loop tick or two later). Code
276
+ * that calls `start()` and synchronously checks `pc.signalingState`
277
+ * will see `"stable"` (no offer yet). This is observable but
278
+ * intentional — chat turns fired in the window between `start()`
279
+ * and `open` correctly resolve to "no vision frame this turn" via
280
+ * `session.kvs_client_id === None` server-side.
281
+ */
282
+ private async startKvsMode(): Promise<void> {
283
+ if (!this.credentials || this.credentials.mode !== 'kvs') {
284
+ throw new Error(
285
+ 'VisionPublisher.startKvsMode called without kvs credentials',
286
+ );
287
+ }
288
+ if (!this.credentials.signedSignalingUrl) {
289
+ throw new Error('VisionPublisher: kvs mode credentials missing signedSignalingUrl');
290
+ }
291
+ if (!this.credentials.channelArn || !this.credentials.clientId) {
292
+ throw new Error('VisionPublisher: kvs mode credentials missing channelArn/clientId');
293
+ }
294
+
295
+ // Dynamic import keeps the SDK out of the local-mode bundle. Errors
296
+ // here usually mean the optional peer dep is uninstalled; surface
297
+ // them clearly so deploy misconfigurations are obvious.
298
+ let sdkModule: unknown;
299
+ try {
300
+ sdkModule = await import(
301
+ // Keep the literal specifier so the bundler can statically
302
+ // discover the chunk. Resolution is layered:
303
+ // - Bundler (Turbopack): resolved via the host app's
304
+ // `turbopack.resolveAlias` entry, which anchors the lookup
305
+ // at the web project (web/node_modules) — needed because
306
+ // client-core is transpiled from source and its realpath
307
+ // (packages/client-core) can't see web/node_modules.
308
+ // - Type-checker (tsc): the host's web-rooted install does not
309
+ // place the SDK on client-core's realpath, so tsc can't find
310
+ // the types here; @ts-ignore suppresses that. (The SDK is an
311
+ // optional peer; it may also be genuinely absent at RUNTIME
312
+ // for a published consumer that didn't install it — handled
313
+ // by the surrounding try/catch.)
314
+ // Result is treated as ``unknown`` and narrowed below.
315
+ /* webpackChunkName: "kvs-webrtc" */
316
+ // @ts-ignore — optional peer dep; types/module may be unresolvable
317
+ // from client-core's realpath in a host's web-rooted install
318
+ 'amazon-kinesis-video-streams-webrtc'
319
+ );
320
+ } catch (err) {
321
+ this.emitError(
322
+ new Error(
323
+ 'VisionPublisher: failed to load amazon-kinesis-video-streams-webrtc; ' +
324
+ 'install it as a peer dep to enable kvs signaling mode',
325
+ ),
326
+ );
327
+ // Don't re-throw: callers that float the start() promise (the
328
+ // React hook does this) would get an unhandled rejection on top
329
+ // of the error event we just emitted. The onError channel is
330
+ // the contract; the throw would be a redundant second signal.
331
+ return;
332
+ }
333
+ const KvsCtors = sdkModule as {
334
+ SignalingClient: new (config: Record<string, unknown>) => KvsSignalingClientLike;
335
+ Role: { VIEWER: string };
336
+ };
337
+
338
+ const pc = new RTCPeerConnection({ iceServers: this.iceServers });
339
+ this.pc = pc;
340
+
341
+ pc.addEventListener('connectionstatechange', () => {
342
+ if (!this.pc) return;
343
+ if (this.pc.connectionState === 'failed' && !this.stopped) {
344
+ this.emitError(new Error('VisionPublisher peer connection failed (kvs)'));
345
+ this.stop();
346
+ }
347
+ });
348
+
349
+ pc.addTrack(this.track);
350
+
351
+ // The backend mints a fully SigV4-presigned wss:// URL — it bakes in
352
+ // X-Amz-ChannelARN, X-Amz-ClientId, and the signature
353
+ // (shared/kvs_webrtc._sign_wss_url). Supply a no-op requestSigner that
354
+ // returns that URL verbatim. Without a requestSigner the SDK builds a
355
+ // SigV4 signer from `config.credentials` and throws "credentials
356
+ // cannot be undefined" — and providing real credentials would mean
357
+ // shipping AWS keys to the browser, exactly what the presigned-URL
358
+ // design exists to avoid. getSignedURL is the ONLY place the SDK
359
+ // signs; follow-up SDP/ICE messages ride the already-authenticated
360
+ // WebSocket unsigned, so the no-op signer fully covers the contract.
361
+ const presignedUrl = this.credentials.signedSignalingUrl;
362
+ const signaling = new KvsCtors.SignalingClient({
363
+ channelARN: this.credentials.channelArn,
364
+ channelEndpoint: this.credentials.signedSignalingUrl,
365
+ clientId: this.credentials.clientId,
366
+ role: KvsCtors.Role.VIEWER,
367
+ // Region is stored by the SDK but not used for signing here (we
368
+ // bypass its signer); kept consistent with the channel's region.
369
+ region: this.credentials.region ?? 'us-east-1',
370
+ systemClockOffset: 0,
371
+ requestSigner: {
372
+ getSignedURL: async () => presignedUrl,
373
+ },
374
+ });
375
+ this.kvsSignalingClient = signaling;
376
+
377
+ pc.addEventListener('icecandidate', (ev) => {
378
+ const candidate = (ev as RTCPeerConnectionIceEvent).candidate;
379
+ if (!candidate) return; // end-of-candidates
380
+ signaling.sendIceCandidate({
381
+ candidate: candidate.candidate,
382
+ sdpMid: candidate.sdpMid ?? undefined,
383
+ sdpMLineIndex: candidate.sdpMLineIndex ?? undefined,
384
+ });
385
+ });
386
+
387
+ // Track whether we've notified the chat-WS of our ClientId so
388
+ // stop() knows whether to send detach.
389
+ //
390
+ // The `vision_attach` send waits for KVS's `open` event (rather
391
+ // than firing immediately at start()) because we want to send
392
+ // ClientId only after the signaling channel is actually live —
393
+ // otherwise a chat turn fired in the window between start() and
394
+ // open might race against a still-empty session. The window is
395
+ // sub-second in practice; a chat turn during that window correctly
396
+ // resolves to "no vision frame yet" (the dispatcher reads
397
+ // session.kvs_client_id = None) and the user just gets a frameless
398
+ // answer for that one turn. The next turn picks up the buffer.
399
+ const clientId = this.credentials.clientId;
400
+ signaling.on('open', async () => {
401
+ // Stop-race guard: if stop() was called between `start()` and
402
+ // this handler firing, the local peer is already closed and
403
+ // sending vision_attach would leave the server with a kvs_client_id
404
+ // binding but no receiver. Bail before any state-mutating call.
405
+ if (this.stopped) return;
406
+ try {
407
+ // Tell the chat-WS our KVS ClientId BEFORE the offer is sent
408
+ // — the backend dispatcher needs the ClientId on session state
409
+ // by the time the first chat turn looks up the FrameBuffer.
410
+ // Skipping this is the bug that left KVS-mode silently broken
411
+ // (router had the buffer; chat-WS session didn't know about it).
412
+ this.ws.sendVisionAttach({ action: 'vision_attach', clientId });
413
+ const offer = await pc.createOffer();
414
+ if (this.stopped) return;
415
+ await pc.setLocalDescription(offer);
416
+ if (this.stopped) return;
417
+ signaling.sendSdpOffer({ type: 'offer', sdp: offer.sdp ?? '' });
418
+ } catch (err) {
419
+ this.emitError(err instanceof Error ? err : new Error(String(err)));
420
+ }
421
+ });
422
+
423
+ signaling.on('sdpAnswer', async (answer) => {
424
+ try {
425
+ await pc.setRemoteDescription(answer);
426
+ } catch (err) {
427
+ // Same rationale as local-mode onAnswer: a failed remote
428
+ // description leaves the PC unrecoverable. Tear down so the
429
+ // hook can construct a fresh publisher on retry.
430
+ this.emitError(err instanceof Error ? err : new Error(String(err)));
431
+ this.stop();
432
+ }
433
+ });
434
+
435
+ signaling.on('iceCandidate', async (candidate) => {
436
+ try {
437
+ await pc.addIceCandidate(candidate);
438
+ } catch (err) {
439
+ // ICE failures are per-candidate and survivable.
440
+ this.emitError(err instanceof Error ? err : new Error(String(err)));
441
+ }
442
+ });
443
+
444
+ signaling.on('error', (err) => {
445
+ this.emitError(
446
+ err instanceof Error ? err : new Error(`KVS signaling: ${String(err)}`),
447
+ );
448
+ });
449
+
450
+ signaling.on('close', () => {
451
+ if (!this.stopped) {
452
+ this.emitError(new Error('VisionPublisher: KVS signaling closed unexpectedly'));
453
+ this.stop();
454
+ }
455
+ });
456
+
457
+ signaling.open();
458
+ }
459
+
460
+ /**
461
+ * Tear down the peer connection, unsubscribe from WS events, and let
462
+ * the backend know via `vision_close` so it can free its receiver.
463
+ * Idempotent — safe to call from `finally` blocks or auto-restart
464
+ * paths.
465
+ */
466
+ stop(): void {
467
+ if (
468
+ this.stopped &&
469
+ !this.pc &&
470
+ this.wsHandlers.length === 0 &&
471
+ this.kvsSignalingClient === null
472
+ ) {
473
+ return;
474
+ }
475
+ this.stopped = true;
476
+
477
+ if (this.pc) {
478
+ this.pc.close();
479
+ this.pc = null;
480
+ }
481
+
482
+ const wasKvs = this.kvsSignalingClient !== null;
483
+ if (this.kvsSignalingClient) {
484
+ try {
485
+ this.kvsSignalingClient.close();
486
+ } catch {
487
+ // KVS SDK occasionally throws during close; idempotent teardown.
488
+ }
489
+ this.kvsSignalingClient = null;
490
+ }
491
+
492
+ for (const { event, handler } of this.wsHandlers) {
493
+ this.ws.off(event, handler);
494
+ }
495
+ this.wsHandlers = [];
496
+
497
+ // Local mode: vision_close frees the per-session aiortc receiver
498
+ // server-side. KVS mode: vision_detach releases the receiver +
499
+ // FrameBuffer in VisionSessionRouter keyed by ClientId.
500
+ // Both are fire-and-forget — the backend also cleans up on WS
501
+ // disconnect, so a swallow-and-return is safe.
502
+ try {
503
+ if (wasKvs) {
504
+ this.ws.sendVisionDetach();
505
+ } else {
506
+ this.ws.sendVisionClose();
507
+ }
508
+ } catch {
509
+ // Socket may already be closed; the backend will GC on disconnect.
510
+ }
511
+ }
512
+
513
+ /** Subscribe to backend `vision_status` updates (HUD telemetry). Returns
514
+ * an unsubscribe function so React effects can clean up. */
515
+ onStatus(listener: VisionStatusListener): () => void {
516
+ this.statusListeners.push(listener);
517
+ return () => {
518
+ this.statusListeners = this.statusListeners.filter((l) => l !== listener);
519
+ };
520
+ }
521
+
522
+ /** Subscribe to publisher-level errors (peer-connection failure, SDP /
523
+ * ICE rejection). Returns an unsubscribe function. */
524
+ onError(listener: VisionErrorListener): () => void {
525
+ this.errorListeners.push(listener);
526
+ return () => {
527
+ this.errorListeners = this.errorListeners.filter((l) => l !== listener);
528
+ };
529
+ }
530
+
531
+ private emitError(err: Error): void {
532
+ for (const listener of this.errorListeners) listener(err);
533
+ }
534
+
535
+ private static resolveTrack(
536
+ input: MediaStreamTrack | MediaStream,
537
+ ): MediaStreamTrack {
538
+ // jsdom < 25 doesn't ship MediaStream, so guard the `instanceof`
539
+ // check on a truthy global. When the global isn't installed we
540
+ // assume the caller passed a track directly.
541
+ const MediaStreamCtor: typeof MediaStream | undefined = (
542
+ globalThis as unknown as { MediaStream?: typeof MediaStream }
543
+ ).MediaStream;
544
+ if (MediaStreamCtor && input instanceof MediaStreamCtor) {
545
+ const track = input.getVideoTracks()[0];
546
+ if (!track) {
547
+ throw new Error('VisionPublisher: MediaStream has no video tracks');
548
+ }
549
+ return track;
550
+ }
551
+ return input as MediaStreamTrack;
552
+ }
553
+ }