@escapeaihq/client-core 0.8.0 → 0.42.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 (307) hide show
  1. package/README.md +48 -4
  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 +200 -0
  31. package/dist/admin.d.ts.map +1 -0
  32. package/dist/admin.js +124 -0
  33. package/dist/admin.js.map +1 -0
  34. package/dist/api.d.ts +1299 -3
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +683 -95
  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 +62 -0
  47. package/dist/conversation/binding.d.ts.map +1 -0
  48. package/dist/conversation/binding.js +51 -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 +342 -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 +260 -0
  103. package/dist/graphSchema.d.ts.map +1 -0
  104. package/dist/graphSchema.js +354 -0
  105. package/dist/graphSchema.js.map +1 -0
  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 +9 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +12 -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/abortUtils.d.ts +16 -0
  119. package/dist/reactor/abortUtils.d.ts.map +1 -0
  120. package/dist/reactor/abortUtils.js +26 -0
  121. package/dist/reactor/abortUtils.js.map +1 -0
  122. package/dist/reactor/applyScenePrompt.d.ts +75 -0
  123. package/dist/reactor/applyScenePrompt.d.ts.map +1 -0
  124. package/dist/reactor/applyScenePrompt.js +60 -0
  125. package/dist/reactor/applyScenePrompt.js.map +1 -0
  126. package/dist/reactor/chunkDistribution.d.ts +43 -0
  127. package/dist/reactor/chunkDistribution.d.ts.map +1 -0
  128. package/dist/reactor/chunkDistribution.js +85 -0
  129. package/dist/reactor/chunkDistribution.js.map +1 -0
  130. package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -1
  131. package/dist/reactor/heliosCommandDispatcher.js +10 -15
  132. package/dist/reactor/heliosCommandDispatcher.js.map +1 -1
  133. package/dist/reactor/index.d.ts +4 -0
  134. package/dist/reactor/index.d.ts.map +1 -1
  135. package/dist/reactor/index.js +7 -0
  136. package/dist/reactor/index.js.map +1 -1
  137. package/dist/reactor/longLiveCommandDispatcher.d.ts +103 -0
  138. package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -0
  139. package/dist/reactor/longLiveCommandDispatcher.js +87 -0
  140. package/dist/reactor/longLiveCommandDispatcher.js.map +1 -0
  141. package/dist/reactor/sceneEntry.d.ts +40 -6
  142. package/dist/reactor/sceneEntry.d.ts.map +1 -1
  143. package/dist/reactor/sceneEntry.js +63 -24
  144. package/dist/reactor/sceneEntry.js.map +1 -1
  145. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -1
  146. package/dist/reactor/scenesFromEnrichment.js +2 -66
  147. package/dist/reactor/scenesFromEnrichment.js.map +1 -1
  148. package/dist/reactor/seedImageOrchestrator.d.ts +42 -2
  149. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  150. package/dist/reactor/seedImageOrchestrator.js +173 -4
  151. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  152. package/dist/reactor/storyTimeline.d.ts +44 -0
  153. package/dist/reactor/storyTimeline.d.ts.map +1 -0
  154. package/dist/reactor/storyTimeline.js +95 -0
  155. package/dist/reactor/storyTimeline.js.map +1 -0
  156. package/dist/storyGraph.d.ts +70 -0
  157. package/dist/storyGraph.d.ts.map +1 -0
  158. package/dist/storyGraph.js +178 -0
  159. package/dist/storyGraph.js.map +1 -0
  160. package/dist/timeFormat.d.ts +10 -0
  161. package/dist/timeFormat.d.ts.map +1 -1
  162. package/dist/timeFormat.js +12 -0
  163. package/dist/timeFormat.js.map +1 -1
  164. package/dist/toolSchemas.d.ts +370 -0
  165. package/dist/toolSchemas.d.ts.map +1 -0
  166. package/dist/toolSchemas.js +182 -0
  167. package/dist/toolSchemas.js.map +1 -0
  168. package/dist/vision/VisionPublisher.d.ts +115 -0
  169. package/dist/vision/VisionPublisher.d.ts.map +1 -0
  170. package/dist/vision/VisionPublisher.js +475 -0
  171. package/dist/vision/VisionPublisher.js.map +1 -0
  172. package/dist/vision/VisionSourceController.d.ts +127 -0
  173. package/dist/vision/VisionSourceController.d.ts.map +1 -0
  174. package/dist/vision/VisionSourceController.js +284 -0
  175. package/dist/vision/VisionSourceController.js.map +1 -0
  176. package/dist/vision/credentials.d.ts +22 -0
  177. package/dist/vision/credentials.d.ts.map +1 -0
  178. package/dist/vision/credentials.js +34 -0
  179. package/dist/vision/credentials.js.map +1 -0
  180. package/dist/vision/index.d.ts +18 -0
  181. package/dist/vision/index.d.ts.map +1 -0
  182. package/dist/vision/index.js +13 -0
  183. package/dist/vision/index.js.map +1 -0
  184. package/dist/vision/sourceKinds.d.ts +65 -0
  185. package/dist/vision/sourceKinds.d.ts.map +1 -0
  186. package/dist/vision/sourceKinds.js +26 -0
  187. package/dist/vision/sourceKinds.js.map +1 -0
  188. package/dist/vision/startVisionPublisher.d.ts +38 -0
  189. package/dist/vision/startVisionPublisher.d.ts.map +1 -0
  190. package/dist/vision/startVisionPublisher.js +44 -0
  191. package/dist/vision/startVisionPublisher.js.map +1 -0
  192. package/dist/vision/types.d.ts +95 -0
  193. package/dist/vision/types.d.ts.map +1 -0
  194. package/dist/vision/types.js +12 -0
  195. package/dist/vision/types.js.map +1 -0
  196. package/dist/vision/visionScheduler.d.ts +63 -0
  197. package/dist/vision/visionScheduler.d.ts.map +1 -0
  198. package/dist/vision/visionScheduler.js +67 -0
  199. package/dist/vision/visionScheduler.js.map +1 -0
  200. package/dist/websocket.d.ts +195 -0
  201. package/dist/websocket.d.ts.map +1 -1
  202. package/dist/websocket.js +179 -1
  203. package/dist/websocket.js.map +1 -1
  204. package/package.json +11 -1
  205. package/src/__tests__/adapters-capabilities.test.ts +46 -0
  206. package/src/__tests__/adapters-chat.test.ts +172 -0
  207. package/src/__tests__/adapters-director.test.ts +95 -0
  208. package/src/__tests__/adapters-image.test.ts +133 -0
  209. package/src/__tests__/adapters-platform.test.ts +95 -0
  210. package/src/__tests__/adapters-registry.test.ts +189 -0
  211. package/src/__tests__/adapters-world.test.ts +296 -0
  212. package/src/__tests__/admin.test.ts +312 -0
  213. package/src/__tests__/adventures-party.test.ts +219 -0
  214. package/src/__tests__/adventures.test.ts +282 -0
  215. package/src/__tests__/api-pollers.test.ts +104 -0
  216. package/src/__tests__/api.clip-lookup.test.ts +64 -0
  217. package/src/__tests__/api.list-images-filters.test.ts +103 -0
  218. package/src/__tests__/api.test.ts +470 -0
  219. package/src/__tests__/audio.test.ts +65 -0
  220. package/src/__tests__/cast.test.ts +95 -0
  221. package/src/__tests__/castProjection.test.ts +167 -0
  222. package/src/__tests__/chat-auth.test.ts +91 -0
  223. package/src/__tests__/conversation/controller.test.ts +697 -0
  224. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  225. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  226. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  227. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  228. package/src/__tests__/conversation/roster.test.ts +100 -0
  229. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  230. package/src/__tests__/conversation/router.test.ts +81 -0
  231. package/src/__tests__/conversation/runtime.test.ts +206 -0
  232. package/src/__tests__/conversation/voice.test.ts +440 -0
  233. package/src/__tests__/documents.test.ts +360 -0
  234. package/src/__tests__/graphSchema.test.ts +326 -0
  235. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  236. package/src/__tests__/platformAssistant.test.ts +484 -0
  237. package/src/__tests__/reactor/applyScenePrompt.test.ts +192 -0
  238. package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +4 -3
  239. package/src/__tests__/reactor/sceneEntry.test.ts +134 -10
  240. package/src/__tests__/reactor/seedImageOrchestrator.test.ts +51 -16
  241. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  242. package/src/__tests__/regeneration.test.ts +486 -0
  243. package/src/__tests__/stories.test.ts +171 -0
  244. package/src/__tests__/storyGraph.test.ts +134 -0
  245. package/src/__tests__/timeFormat.test.ts +22 -1
  246. package/src/__tests__/toolSchemas.test.ts +57 -0
  247. package/src/__tests__/tools-wrappers.test.ts +272 -0
  248. package/src/__tests__/videoGraph.test.ts +94 -0
  249. package/src/__tests__/websocket-vision.test.ts +265 -0
  250. package/src/__tests__/websocket.test.ts +213 -0
  251. package/src/adapters/capabilities.ts +24 -0
  252. package/src/adapters/chatAdapter.ts +114 -0
  253. package/src/adapters/directorAdapter.ts +126 -0
  254. package/src/adapters/imageAdapter.ts +100 -0
  255. package/src/adapters/index.ts +67 -0
  256. package/src/adapters/registry.ts +159 -0
  257. package/src/adapters/worldAdapter.ts +272 -0
  258. package/src/admin.ts +310 -0
  259. package/src/api.ts +1890 -162
  260. package/src/audio.ts +35 -0
  261. package/src/castProjection.ts +95 -0
  262. package/src/conversation/binding.ts +81 -0
  263. package/src/conversation/controller.ts +439 -0
  264. package/src/conversation/effectiveModel.ts +111 -0
  265. package/src/conversation/index.ts +27 -0
  266. package/src/conversation/participant.ts +71 -0
  267. package/src/conversation/presence.ts +60 -0
  268. package/src/conversation/presenceBus.ts +109 -0
  269. package/src/conversation/presenceRegistry.ts +83 -0
  270. package/src/conversation/roster.ts +111 -0
  271. package/src/conversation/rosterProjection.ts +98 -0
  272. package/src/conversation/router.ts +96 -0
  273. package/src/conversation/runtime.ts +188 -0
  274. package/src/conversation/types.ts +100 -0
  275. package/src/conversation/voice.ts +402 -0
  276. package/src/graphSchema.ts +532 -0
  277. package/src/http.ts +72 -0
  278. package/src/index.ts +12 -0
  279. package/src/platformAssistant.ts +347 -0
  280. package/src/reactor/abortUtils.ts +22 -0
  281. package/src/reactor/applyScenePrompt.ts +136 -0
  282. package/src/reactor/chunkDistribution.ts +98 -0
  283. package/src/reactor/heliosCommandDispatcher.ts +10 -18
  284. package/src/reactor/index.ts +7 -0
  285. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  286. package/src/reactor/sceneEntry.ts +104 -33
  287. package/src/reactor/scenesFromEnrichment.ts +11 -76
  288. package/src/reactor/seedImageOrchestrator.ts +200 -4
  289. package/src/reactor/storyTimeline.ts +127 -0
  290. package/src/storyGraph.ts +298 -0
  291. package/src/timeFormat.ts +13 -0
  292. package/src/toolSchemas.ts +225 -0
  293. package/src/vision/VisionPublisher.ts +553 -0
  294. package/src/vision/VisionSourceController.ts +354 -0
  295. package/src/vision/__tests__/VisionPublisher.kvs.test.ts +244 -0
  296. package/src/vision/__tests__/VisionPublisher.test.ts +301 -0
  297. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  298. package/src/vision/__tests__/startVisionPublisher.test.ts +251 -0
  299. package/src/vision/__tests__/toVisionRtcCredentials.test.ts +113 -0
  300. package/src/vision/__tests__/visionScheduler.test.ts +149 -0
  301. package/src/vision/credentials.ts +39 -0
  302. package/src/vision/index.ts +44 -0
  303. package/src/vision/sourceKinds.ts +75 -0
  304. package/src/vision/startVisionPublisher.ts +64 -0
  305. package/src/vision/types.ts +101 -0
  306. package/src/vision/visionScheduler.ts +102 -0
  307. package/src/websocket.ts +334 -4
@@ -0,0 +1,354 @@
1
+ /**
2
+ * Framework-agnostic vision-SOURCE controller — the single source of truth
3
+ * for "turn a chosen local source into a published vision feed".
4
+ *
5
+ * R3a of the Platform Experience Restructure
6
+ * (`specs/platform-experience-restructure-phase-R3-vision-source-picker.md`).
7
+ *
8
+ * Today the two React call sites duplicate the same
9
+ * acquire→credentials→publish→teardown sequence and differ only in how the
10
+ * track is obtained (the fork `startVisionPublisher`'s header already calls
11
+ * out): the chat-ws page hardcodes `getUserMedia({ video: true })` and the
12
+ * watch hook hardcodes `<video>.captureStream()`. This controller owns the
13
+ * acquisition switch (webcam / playing-video / server-render) plus the full
14
+ * publisher lifecycle, and DELEGATES the publisher wiring to the existing
15
+ * `startVisionPublisher` helper — it does not duplicate it.
16
+ *
17
+ * Error discipline (matches the lifted call sites + this module's
18
+ * callbacks-not-throws convention): environmental/acquisition failures
19
+ * (no getUserMedia support, permission denied, captureStream unsupported,
20
+ * no video track, credential fetch failure) are reported via `onError` and
21
+ * `start()` RESOLVES with the controller back in the idle, restartable
22
+ * state. Programmer misuse (`start()` while a source is active or starting)
23
+ * THROWS fail-loud — use `switchSource()` to change sources.
24
+ *
25
+ * Zero React/DOM-query imports: descriptors carry any DOM element in, so a
26
+ * React hook (R3b) drives it today and a game-engine surface can later.
27
+ * Cross-device vision relay stays deferred — every source is local and the
28
+ * feed publishes over the caller's own authenticated `ChatWebSocket`
29
+ * exactly as today.
30
+ */
31
+
32
+ import type { ApiClient, ChatVisionRtcCredentialsResponse } from '../api';
33
+ import type { ChatWebSocket } from '../websocket';
34
+ import { startVisionPublisher } from './startVisionPublisher';
35
+ import type { VisionPublisherHandle } from './startVisionPublisher';
36
+ import type { VisionStatus } from './types';
37
+ import { VISION_SOURCE_KINDS } from './sourceKinds';
38
+ import type {
39
+ VisionCaptureElement,
40
+ VisionSourceDescriptor,
41
+ VisionSourceKind,
42
+ } from './sourceKinds';
43
+
44
+ /**
45
+ * The slice of `ApiClient` the controller needs (structural — a full
46
+ * `ApiClient` satisfies it; tests can pass a one-method stub).
47
+ */
48
+ export type VisionCredentialsClient = Pick<ApiClient, 'getVisionRtcCredentials'>;
49
+
50
+ export interface VisionSourceControllerOptions {
51
+ /**
52
+ * The SAME authenticated `ChatWebSocket` the user's chat turns use —
53
+ * vision frames are keyed to the WS session ID server-side, so a fresh
54
+ * socket would land in a different `FrameBuffer`. Callers must keep this
55
+ * reference stable for the controller's lifetime (the identity-stability
56
+ * requirement lifted from the watch hook).
57
+ */
58
+ ws: ChatWebSocket;
59
+ /** Mints vision-signaling credentials via
60
+ * `POST /api/v1/chat/vision-rtc/credentials`. */
61
+ apiClient: VisionCredentialsClient;
62
+ /** Frames-per-second cadence; clamped server-side to 0.5–3.0 fps. */
63
+ fps: number;
64
+ /** Publisher telemetry (drives the HUD line). */
65
+ onStatus?: (status: VisionStatus) => void;
66
+ /** Environmental/acquisition failures AND asynchronous publisher errors. */
67
+ onError?: (error: Error) => void;
68
+ /** Fired when `currentKind` changes: the new kind after a successful
69
+ * `start`, and `null` when an active source is stopped. */
70
+ onSourceChange?: (kind: VisionSourceKind | null) => void;
71
+ }
72
+
73
+ /** First `readyState` where the `<video>` has a real decoded image; tracks
74
+ * pulled before then publish a black buffer (the watch-page guard). */
75
+ const HAVE_CURRENT_DATA = 2;
76
+
77
+ type Phase = 'idle' | 'starting' | 'active';
78
+
79
+ const toError = (err: unknown): Error =>
80
+ err instanceof Error ? err : new Error(String(err));
81
+
82
+ /**
83
+ * Module-private sentinel thrown to unwind `acquire()` when `stop()`
84
+ * cancels a pending first-frame gate. Handled explicitly in `start()`'s
85
+ * catch — it never reaches `onError` and is never user-visible.
86
+ */
87
+ class StartCancelledError extends Error {
88
+ constructor() {
89
+ super('vision source start cancelled');
90
+ this.name = 'StartCancelledError';
91
+ }
92
+ }
93
+
94
+ /** Duck-typed captureStream lookup — `HTMLVideoElement.captureStream` /
95
+ * `HTMLCanvasElement.captureStream` aren't in all lib.dom versions, so we
96
+ * cast locally rather than widening global types (same pattern as the
97
+ * watch hook this lifts). */
98
+ const captureStreamOf = (
99
+ element: VisionCaptureElement,
100
+ ): (() => MediaStream) | undefined => {
101
+ const fn = (element as { captureStream?: () => MediaStream }).captureStream;
102
+ return typeof fn === 'function' ? fn.bind(element) : undefined;
103
+ };
104
+
105
+ export class VisionSourceController {
106
+ private readonly ws: ChatWebSocket;
107
+ private readonly apiClient: VisionCredentialsClient;
108
+ private readonly fps: number;
109
+ private readonly onStatus?: (status: VisionStatus) => void;
110
+ private readonly onError?: (error: Error) => void;
111
+ private readonly onSourceChange?: (kind: VisionSourceKind | null) => void;
112
+
113
+ /** Bumped by every `stop()`; in-flight `start()` work compares its
114
+ * captured epoch after each await and bails (releasing anything it
115
+ * acquired) when stale. */
116
+ private epoch = 0;
117
+ private phase: Phase = 'idle';
118
+ private kind: VisionSourceKind | null = null;
119
+ private stream: MediaStream | null = null;
120
+ private handle: VisionPublisherHandle | null = null;
121
+ /** Cancels a pending waitForFrame `loadeddata` listener. */
122
+ private cancelWaitForFrame: (() => void) | null = null;
123
+
124
+ constructor(opts: VisionSourceControllerOptions) {
125
+ this.ws = opts.ws;
126
+ this.apiClient = opts.apiClient;
127
+ this.fps = opts.fps;
128
+ this.onStatus = opts.onStatus;
129
+ this.onError = opts.onError;
130
+ this.onSourceChange = opts.onSourceChange;
131
+ }
132
+
133
+ /** The currently-published source kind, or `null` when idle/starting. */
134
+ get currentKind(): VisionSourceKind | null {
135
+ return this.kind;
136
+ }
137
+
138
+ /** True while a `start()` is in flight (acquisition / first-frame gate /
139
+ * credentials). Lets a UI adapter render a loading state without
140
+ * probing the lifecycle. */
141
+ get isStarting(): boolean {
142
+ return this.phase === 'starting';
143
+ }
144
+
145
+ /**
146
+ * Acquire the descriptor's track, mint credentials, and start publishing.
147
+ *
148
+ * Resolves when the publisher is started OR the attempt failed (failure
149
+ * reported via `onError`; controller back in the restartable idle state)
150
+ * OR a concurrent `stop()`/`switchSource()` cancelled it. Throws only on
151
+ * misuse: calling `start()` while a source is already active or starting.
152
+ */
153
+ async start(descriptor: VisionSourceDescriptor): Promise<void> {
154
+ if (this.phase !== 'idle') {
155
+ throw new Error(
156
+ `VisionSourceController.start() called while a source is ${this.phase} — ` +
157
+ 'use switchSource() to change sources',
158
+ );
159
+ }
160
+ this.phase = 'starting';
161
+ const epoch = this.epoch;
162
+
163
+ // 1. Acquire the source stream (the only step that differs per kind).
164
+ let stream: MediaStream;
165
+ try {
166
+ stream = await this.acquire(descriptor, epoch);
167
+ } catch (err) {
168
+ if (err instanceof StartCancelledError) return; // deliberate stop — not an error
169
+ this.failStart(epoch, toError(err));
170
+ return;
171
+ }
172
+ if (epoch !== this.epoch) {
173
+ // stop()/switchSource() raced the acquisition — release what we
174
+ // acquired (the camera light must not linger) and bail silently:
175
+ // a deliberate stop is not an error.
176
+ stream.getTracks().forEach((t) => t.stop());
177
+ return;
178
+ }
179
+
180
+ const track = stream.getVideoTracks()[0];
181
+ if (!track) {
182
+ // A live MediaStream with no video track: stop its tracks before
183
+ // bailing so we don't leak the capture (lifted verbatim from both
184
+ // call sites).
185
+ stream.getTracks().forEach((t) => t.stop());
186
+ this.failStart(
187
+ epoch,
188
+ new Error(
189
+ descriptor.kind === VISION_SOURCE_KINDS.WEBCAM
190
+ ? 'No video track available'
191
+ : 'No video track available from captureStream()',
192
+ ),
193
+ );
194
+ return;
195
+ }
196
+ // Safe to publish the stream onto the instance only now: the no-track
197
+ // check above ran synchronously since acquisition (no await between),
198
+ // so no stop() can have interleaved.
199
+ this.stream = stream;
200
+
201
+ // 2. Mint signaling credentials AFTER acquisition succeeds — keeps the
202
+ // AWS round-trip off the cold-toggle path until we can produce frames.
203
+ let credentialsResponse: ChatVisionRtcCredentialsResponse;
204
+ try {
205
+ credentialsResponse = await this.apiClient.getVisionRtcCredentials();
206
+ } catch (err) {
207
+ // Release unconditionally — if stop() raced this await it already
208
+ // stopped these tracks via this.stream, and double-stopping a
209
+ // MediaStreamTrack is a spec'd no-op. Either way the camera light
210
+ // goes off.
211
+ stream.getTracks().forEach((t) => t.stop());
212
+ if (epoch === this.epoch) this.stream = null;
213
+ this.failStart(epoch, toError(err));
214
+ return;
215
+ }
216
+ if (epoch !== this.epoch) {
217
+ // stop() already released this.stream; double-stopping a track is a
218
+ // spec'd no-op, so release unconditionally for safety.
219
+ stream.getTracks().forEach((t) => t.stop());
220
+ return;
221
+ }
222
+
223
+ // 3. Delegate the publisher wiring to the existing helper (DRY — the
224
+ // construct→subscribe→start sequence has exactly one implementation).
225
+ // Defensively wrapped: a synchronous throw here would otherwise leave
226
+ // the phase stuck at 'starting' (non-restartable) with no onError.
227
+ try {
228
+ this.handle = startVisionPublisher({
229
+ ws: this.ws,
230
+ track,
231
+ credentialsResponse,
232
+ fps: this.fps,
233
+ onStatus: this.onStatus,
234
+ onError: this.onError,
235
+ });
236
+ } catch (err) {
237
+ stream.getTracks().forEach((t) => t.stop());
238
+ this.stream = null;
239
+ this.failStart(epoch, toError(err));
240
+ return;
241
+ }
242
+ this.phase = 'active';
243
+ this.kind = descriptor.kind;
244
+ this.onSourceChange?.(descriptor.kind);
245
+ }
246
+
247
+ /**
248
+ * Stop the current source (publisher + every acquired track), then start
249
+ * the new one. The teardown completes synchronously BEFORE the next
250
+ * acquisition begins, so e.g. the webcam light is off before the video
251
+ * capture starts. This is the net-new capability the hardwired call
252
+ * sites couldn't do.
253
+ *
254
+ * Single-caller by design: the phase passes through `idle` between the
255
+ * stop and the start, so a concurrent `start()` issued in that window
256
+ * would win and make this call's deferred `start()` throw. The React
257
+ * adapter (R3b) holds the controller on a `useRef` and serializes calls
258
+ * through one effect, which guarantees a single caller.
259
+ */
260
+ async switchSource(descriptor: VisionSourceDescriptor): Promise<void> {
261
+ this.stop();
262
+ await this.start(descriptor);
263
+ }
264
+
265
+ /**
266
+ * Idempotent teardown: stops the publisher (via its handle), stops every
267
+ * acquired `MediaStreamTrack` (camera light off; no leaked captureStream
268
+ * tracks), cancels any pending first-frame gate, and aborts any in-flight
269
+ * `start()`.
270
+ */
271
+ stop(): void {
272
+ this.epoch += 1;
273
+ this.cancelWaitForFrame?.();
274
+ this.handle?.stop();
275
+ this.handle = null;
276
+ this.stream?.getTracks().forEach((t) => t.stop());
277
+ this.stream = null;
278
+ this.phase = 'idle';
279
+ if (this.kind !== null) {
280
+ this.kind = null;
281
+ this.onSourceChange?.(null);
282
+ }
283
+ }
284
+
285
+ // ── Internals ──────────────────────────────────────────────────────────
286
+
287
+ /** Report a failed start attempt and return to idle (unless a stop()
288
+ * superseded this attempt — then the user cancelled, not an error). */
289
+ private failStart(epoch: number, error: Error): void {
290
+ if (epoch !== this.epoch) return;
291
+ this.phase = 'idle';
292
+ this.onError?.(error);
293
+ }
294
+
295
+ /** Per-kind track acquisition. Throws environmental errors; the caller
296
+ * routes them through `failStart`. */
297
+ private async acquire(
298
+ descriptor: VisionSourceDescriptor,
299
+ epoch: number,
300
+ ): Promise<MediaStream> {
301
+ if (descriptor.kind === VISION_SOURCE_KINDS.WEBCAM) {
302
+ if (
303
+ typeof navigator === 'undefined' ||
304
+ !navigator.mediaDevices?.getUserMedia
305
+ ) {
306
+ throw new Error('Browser does not support webcam access');
307
+ }
308
+ return navigator.mediaDevices.getUserMedia(
309
+ descriptor.constraints ?? { video: true },
310
+ );
311
+ }
312
+
313
+ // playing-video / server-render: captureStream() off the supplied
314
+ // element, optionally gated on the first decoded frame for <video>.
315
+ const { element } = descriptor;
316
+ if (descriptor.waitForFrame) {
317
+ await this.waitForFirstFrame(element);
318
+ if (epoch !== this.epoch) {
319
+ // stop() cancelled the gate while we were waiting — unwind out of
320
+ // acquire(); start()'s catch swallows this sentinel explicitly.
321
+ throw new StartCancelledError();
322
+ }
323
+ }
324
+ const captureStream = captureStreamOf(element);
325
+ if (!captureStream) {
326
+ throw new Error('Browser does not support captureStream()');
327
+ }
328
+ return captureStream();
329
+ }
330
+
331
+ /** Resolve once the `<video>` has decoded its first frame (or
332
+ * immediately for canvases / already-decoded videos). Cancellable by
333
+ * `stop()` via `cancelWaitForFrame`. */
334
+ private waitForFirstFrame(element: VisionCaptureElement): Promise<void> {
335
+ const video = element as HTMLVideoElement;
336
+ // Canvas elements have no readyState — capture immediately.
337
+ if (typeof video.readyState !== 'number') return Promise.resolve();
338
+ if (video.readyState >= HAVE_CURRENT_DATA) return Promise.resolve();
339
+ return new Promise<void>((resolve) => {
340
+ const onReady = (): void => {
341
+ video.removeEventListener('loadeddata', onReady);
342
+ this.cancelWaitForFrame = null;
343
+ resolve();
344
+ };
345
+ video.addEventListener('loadeddata', onReady);
346
+ this.cancelWaitForFrame = (): void => {
347
+ video.removeEventListener('loadeddata', onReady);
348
+ this.cancelWaitForFrame = null;
349
+ // Resolve (not reject): the epoch check after the await bails out.
350
+ resolve();
351
+ };
352
+ });
353
+ }
354
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Tests for VisionPublisher KVS-mode signaling (`startKvsMode`).
3
+ *
4
+ * KVS mode only runs in deployment, so it had no coverage (Issue #177) —
5
+ * and that untested path shipped two deploy-only bugs:
6
+ * 1. the SDK import was unresolvable in the web build, and
7
+ * 2. the SignalingClient threw "credentials cannot be undefined" because
8
+ * we pass a backend-presigned URL instead of AWS credentials.
9
+ * These tests pin the fix: a no-op `requestSigner` that returns the
10
+ * presigned URL verbatim, plus the open → attach → offer lifecycle.
11
+ *
12
+ * The KVS SDK is mocked virtually so the suite doesn't depend on the
13
+ * optional peer being installed. RTCPeerConnection is stubbed (jsdom has
14
+ * no WebRTC), mirroring VisionPublisher.test.ts.
15
+ */
16
+
17
+ interface MockSignaling {
18
+ on: jest.Mock;
19
+ open: jest.Mock;
20
+ close: jest.Mock;
21
+ sendSdpOffer: jest.Mock;
22
+ sendIceCandidate: jest.Mock;
23
+ }
24
+
25
+ const mockSignaling: MockSignaling = {
26
+ on: jest.fn(),
27
+ open: jest.fn(),
28
+ close: jest.fn(),
29
+ sendSdpOffer: jest.fn(),
30
+ sendIceCandidate: jest.fn(),
31
+ };
32
+ const mockSignalingClientCtor = jest.fn(
33
+ (_config: Record<string, unknown>) => mockSignaling,
34
+ );
35
+
36
+ jest.mock(
37
+ 'amazon-kinesis-video-streams-webrtc',
38
+ () => ({
39
+ SignalingClient: mockSignalingClientCtor,
40
+ Role: { VIEWER: 'VIEWER', MASTER: 'MASTER' },
41
+ }),
42
+ { virtual: true },
43
+ );
44
+
45
+ import { VisionPublisher } from '../VisionPublisher';
46
+ import type { VisionRtcCredentials } from '../types';
47
+
48
+ interface MockPc {
49
+ addTrack: jest.Mock;
50
+ createOffer: jest.Mock;
51
+ setLocalDescription: jest.Mock;
52
+ setRemoteDescription: jest.Mock;
53
+ addIceCandidate: jest.Mock;
54
+ close: jest.Mock;
55
+ addEventListener: jest.Mock;
56
+ connectionState: RTCPeerConnectionState;
57
+ }
58
+
59
+ const makeMockPc = (): MockPc => ({
60
+ addTrack: jest.fn(),
61
+ createOffer: jest.fn().mockResolvedValue({ type: 'offer', sdp: 'kvs-offer-sdp' }),
62
+ setLocalDescription: jest.fn().mockResolvedValue(undefined),
63
+ setRemoteDescription: jest.fn().mockResolvedValue(undefined),
64
+ addIceCandidate: jest.fn().mockResolvedValue(undefined),
65
+ close: jest.fn(),
66
+ addEventListener: jest.fn(),
67
+ connectionState: 'new',
68
+ });
69
+
70
+ interface MockKvsWs {
71
+ sendVisionAttach: jest.Mock;
72
+ sendVisionDetach: jest.Mock;
73
+ sendVisionOffer: jest.Mock;
74
+ sendVisionIce: jest.Mock;
75
+ sendVisionClose: jest.Mock;
76
+ on: jest.Mock;
77
+ off: jest.Mock;
78
+ }
79
+
80
+ const makeMockWs = (): MockKvsWs => ({
81
+ sendVisionAttach: jest.fn(),
82
+ sendVisionDetach: jest.fn(),
83
+ sendVisionOffer: jest.fn(),
84
+ sendVisionIce: jest.fn(),
85
+ sendVisionClose: jest.fn(),
86
+ on: jest.fn(),
87
+ off: jest.fn(),
88
+ });
89
+
90
+ const PRESIGNED_URL =
91
+ 'wss://x.kinesisvideo.us-east-1.amazonaws.com/?X-Amz-ChannelARN=arn&X-Amz-ClientId=viewer-abc&X-Amz-Signature=sig';
92
+
93
+ const kvsCredentials = (): VisionRtcCredentials => ({
94
+ mode: 'kvs',
95
+ iceServers: [{ urls: 'stun:stun.kinesisvideo.us-east-1.amazonaws.com:443' }],
96
+ signedSignalingUrl: PRESIGNED_URL,
97
+ channelArn: 'arn:aws:kinesisvideo:us-east-1:123:channel/test/1',
98
+ clientId: 'viewer-0123456789abcdef0123456789abcdef',
99
+ region: 'us-east-1',
100
+ expiresIn: 300,
101
+ });
102
+
103
+ const originalRtc = (globalThis as unknown as { RTCPeerConnection?: unknown })
104
+ .RTCPeerConnection;
105
+ let mockRtcCtor: jest.Mock;
106
+
107
+ const getSignalingHandler = (event: string): ((arg?: unknown) => unknown) => {
108
+ const call = mockSignaling.on.mock.calls.find((c: unknown[]) => c[0] === event);
109
+ if (!call) throw new Error(`no signaling handler registered for '${event}'`);
110
+ return call[1] as (arg?: unknown) => unknown;
111
+ };
112
+
113
+ beforeEach(() => {
114
+ jest.clearAllMocks();
115
+ mockRtcCtor = jest.fn(() => makeMockPc());
116
+ (globalThis as unknown as { RTCPeerConnection: unknown }).RTCPeerConnection =
117
+ mockRtcCtor;
118
+ });
119
+
120
+ afterEach(() => {
121
+ if (originalRtc === undefined) {
122
+ delete (globalThis as unknown as { RTCPeerConnection?: unknown })
123
+ .RTCPeerConnection;
124
+ } else {
125
+ (globalThis as unknown as { RTCPeerConnection: unknown }).RTCPeerConnection =
126
+ originalRtc;
127
+ }
128
+ });
129
+
130
+ describe('VisionPublisher KVS mode', () => {
131
+ it('constructs SignalingClient with a requestSigner and NO credentials', async () => {
132
+ const ws = makeMockWs();
133
+ const pub = new VisionPublisher({
134
+ ws: ws as never,
135
+ track: {} as MediaStreamTrack,
136
+ credentials: kvsCredentials(),
137
+ });
138
+ await pub.start();
139
+
140
+ expect(mockSignalingClientCtor).toHaveBeenCalledTimes(1);
141
+ const config = mockSignalingClientCtor.mock.calls[0][0];
142
+ // The fix: a requestSigner is supplied (so the SDK does not require
143
+ // AWS credentials), and no raw credentials are sent to the browser.
144
+ expect(config.requestSigner).toBeDefined();
145
+ expect(config.credentials).toBeUndefined();
146
+ expect(config.role).toBe('VIEWER');
147
+ expect(config.clientId).toBe(kvsCredentials().clientId);
148
+ });
149
+
150
+ it('requestSigner.getSignedURL returns the backend presigned URL verbatim', async () => {
151
+ const ws = makeMockWs();
152
+ const pub = new VisionPublisher({
153
+ ws: ws as never,
154
+ track: {} as MediaStreamTrack,
155
+ credentials: kvsCredentials(),
156
+ });
157
+ await pub.start();
158
+
159
+ const config = mockSignalingClientCtor.mock.calls[0][0] as unknown as {
160
+ requestSigner: {
161
+ getSignedURL: (endpoint: string, qp: unknown, date?: Date) => Promise<string>;
162
+ };
163
+ };
164
+ // Whatever endpoint/queryParams the SDK passes, we hand back our
165
+ // already-signed URL (it carries ChannelARN + ClientId + signature).
166
+ const signed = await config.requestSigner.getSignedURL(
167
+ 'wss://ignored-endpoint',
168
+ { 'X-Amz-ChannelARN': 'ignored' },
169
+ new Date(),
170
+ );
171
+ expect(signed).toBe(PRESIGNED_URL);
172
+ });
173
+
174
+ it('on signaling open: sends vision_attach, creates offer, sends SDP offer', async () => {
175
+ const ws = makeMockWs();
176
+ const pub = new VisionPublisher({
177
+ ws: ws as never,
178
+ track: {} as MediaStreamTrack,
179
+ credentials: kvsCredentials(),
180
+ });
181
+ await pub.start();
182
+
183
+ expect(mockSignaling.open).toHaveBeenCalledTimes(1);
184
+ // Drive the 'open' event the SDK would emit once connected.
185
+ await getSignalingHandler('open')();
186
+
187
+ expect(ws.sendVisionAttach).toHaveBeenCalledWith({
188
+ action: 'vision_attach',
189
+ clientId: kvsCredentials().clientId,
190
+ });
191
+ expect(mockSignaling.sendSdpOffer).toHaveBeenCalledWith({
192
+ type: 'offer',
193
+ sdp: 'kvs-offer-sdp',
194
+ });
195
+ });
196
+
197
+ it('applies the SDP answer from the signaling channel', async () => {
198
+ const ws = makeMockWs();
199
+ const pub = new VisionPublisher({
200
+ ws: ws as never,
201
+ track: {} as MediaStreamTrack,
202
+ credentials: kvsCredentials(),
203
+ });
204
+ await pub.start();
205
+
206
+ await getSignalingHandler('sdpAnswer')({ type: 'answer', sdp: 'kvs-answer-sdp' });
207
+
208
+ const pc = mockRtcCtor.mock.results[0].value as MockPc;
209
+ expect(pc.setRemoteDescription).toHaveBeenCalledWith({
210
+ type: 'answer',
211
+ sdp: 'kvs-answer-sdp',
212
+ });
213
+ });
214
+
215
+ it('stop() closes the signaling client and sends vision_detach', async () => {
216
+ const ws = makeMockWs();
217
+ const pub = new VisionPublisher({
218
+ ws: ws as never,
219
+ track: {} as MediaStreamTrack,
220
+ credentials: kvsCredentials(),
221
+ });
222
+ await pub.start();
223
+ pub.stop();
224
+
225
+ expect(mockSignaling.close).toHaveBeenCalledTimes(1);
226
+ expect(ws.sendVisionDetach).toHaveBeenCalledTimes(1);
227
+ expect(ws.sendVisionClose).not.toHaveBeenCalled();
228
+ });
229
+
230
+ it('open handler is a no-op if stop() was called first (stop-race guard)', async () => {
231
+ const ws = makeMockWs();
232
+ const pub = new VisionPublisher({
233
+ ws: ws as never,
234
+ track: {} as MediaStreamTrack,
235
+ credentials: kvsCredentials(),
236
+ });
237
+ await pub.start();
238
+ pub.stop();
239
+ // 'open' arriving after stop() must not send a dangling vision_attach.
240
+ ws.sendVisionAttach.mockClear();
241
+ await getSignalingHandler('open')();
242
+ expect(ws.sendVisionAttach).not.toHaveBeenCalled();
243
+ });
244
+ });