@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,251 @@
1
+ /**
2
+ * Tests for `startVisionPublisher`.
3
+ *
4
+ * Strategy: mock the `VisionPublisher` module so we can assert on
5
+ * construction arguments and lifecycle calls without standing up real
6
+ * RTCPeerConnections. The `toVisionRtcCredentials` helper is also mocked
7
+ * so we can confirm the helper threads the raw response through it and
8
+ * passes the converted credentials to VisionPublisher.
9
+ */
10
+
11
+ import { startVisionPublisher } from '../startVisionPublisher';
12
+ import type {
13
+ StartVisionPublisherOptions,
14
+ VisionPublisherHandle,
15
+ } from '../startVisionPublisher';
16
+ import type { VisionStatus } from '../types';
17
+ import type { ChatVisionRtcCredentialsResponse } from '../../api';
18
+
19
+ // ── Mocks ────────────────────────────────────────────────────────────────────
20
+
21
+ jest.mock('../VisionPublisher');
22
+ jest.mock('../credentials');
23
+
24
+ import { VisionPublisher } from '../VisionPublisher';
25
+ import { toVisionRtcCredentials } from '../credentials';
26
+
27
+ const MockVisionPublisher = VisionPublisher as jest.MockedClass<typeof VisionPublisher>;
28
+ const mockToVisionRtcCredentials = toVisionRtcCredentials as jest.MockedFunction<
29
+ typeof toVisionRtcCredentials
30
+ >;
31
+
32
+ // ── Helpers ──────────────────────────────────────────────────────────────────
33
+
34
+ /** Retrieve the most-recently created mock publisher instance. */
35
+ const lastInstance = (): jest.Mocked<VisionPublisher> =>
36
+ MockVisionPublisher.mock.instances[
37
+ MockVisionPublisher.mock.instances.length - 1
38
+ ] as jest.Mocked<VisionPublisher>;
39
+
40
+ const makeMockWs = () =>
41
+ ({
42
+ on: jest.fn(),
43
+ off: jest.fn(),
44
+ sendVisionOffer: jest.fn(),
45
+ sendVisionIce: jest.fn(),
46
+ sendVisionClose: jest.fn(),
47
+ }) as unknown as import('../../websocket').ChatWebSocket;
48
+
49
+ const baseCredentialsResponse: ChatVisionRtcCredentialsResponse = {
50
+ mode: 'local',
51
+ iceServers: [{ urls: ['stun:stun.l.google.com:19302'], username: null, credential: null }],
52
+ signedSignalingUrl: null,
53
+ channelArn: null,
54
+ clientId: null,
55
+ region: null,
56
+ expiresIn: 3600,
57
+ traceId: 'trace-test',
58
+ };
59
+
60
+ const fakeConvertedCredentials = {
61
+ mode: 'local' as const,
62
+ iceServers: [{ urls: ['stun:stun.l.google.com:19302'] }],
63
+ signedSignalingUrl: null,
64
+ channelArn: null,
65
+ clientId: null,
66
+ region: null,
67
+ expiresIn: 3600,
68
+ };
69
+
70
+ // ── Suite ────────────────────────────────────────────────────────────────────
71
+
72
+ describe('startVisionPublisher', () => {
73
+ beforeEach(() => {
74
+ jest.clearAllMocks();
75
+
76
+ // Mock toVisionRtcCredentials to return a known object.
77
+ mockToVisionRtcCredentials.mockReturnValue(fakeConvertedCredentials);
78
+
79
+ // Default mock: start() resolves immediately; onStatus/onError return
80
+ // unsubscribe functions; stop() is a no-op.
81
+ MockVisionPublisher.prototype.start = jest.fn().mockResolvedValue(undefined);
82
+ MockVisionPublisher.prototype.stop = jest.fn();
83
+ MockVisionPublisher.prototype.onStatus = jest.fn().mockReturnValue(jest.fn());
84
+ MockVisionPublisher.prototype.onError = jest.fn().mockReturnValue(jest.fn());
85
+ });
86
+
87
+ it('passes credentials through toVisionRtcCredentials and constructs VisionPublisher', () => {
88
+ const ws = makeMockWs();
89
+ const track = {} as MediaStreamTrack;
90
+ const opts: StartVisionPublisherOptions = {
91
+ ws,
92
+ track,
93
+ credentialsResponse: baseCredentialsResponse,
94
+ fps: 2.0,
95
+ };
96
+
97
+ startVisionPublisher(opts);
98
+
99
+ // toVisionRtcCredentials was called with the raw response.
100
+ expect(mockToVisionRtcCredentials).toHaveBeenCalledWith(baseCredentialsResponse);
101
+
102
+ // VisionPublisher was constructed with the converted credentials.
103
+ expect(MockVisionPublisher).toHaveBeenCalledWith({
104
+ ws,
105
+ track,
106
+ config: { fps: 2.0 },
107
+ credentials: fakeConvertedCredentials,
108
+ });
109
+ });
110
+
111
+ it('returns a handle whose publisher is the constructed VisionPublisher', () => {
112
+ const ws = makeMockWs();
113
+ const track = {} as MediaStreamTrack;
114
+ const handle: VisionPublisherHandle = startVisionPublisher({
115
+ ws,
116
+ track,
117
+ credentialsResponse: baseCredentialsResponse,
118
+ fps: 1.0,
119
+ });
120
+
121
+ expect(handle.publisher).toBe(lastInstance());
122
+ });
123
+
124
+ it('registers onStatus callback when provided', () => {
125
+ const ws = makeMockWs();
126
+ const track = {} as MediaStreamTrack;
127
+ const onStatus = jest.fn<void, [VisionStatus]>();
128
+
129
+ startVisionPublisher({
130
+ ws,
131
+ track,
132
+ credentialsResponse: baseCredentialsResponse,
133
+ fps: 1.0,
134
+ onStatus,
135
+ });
136
+
137
+ expect(lastInstance().onStatus).toHaveBeenCalledWith(onStatus);
138
+ });
139
+
140
+ it('registers onError callback when provided', () => {
141
+ const ws = makeMockWs();
142
+ const track = {} as MediaStreamTrack;
143
+ const onError = jest.fn<void, [Error]>();
144
+
145
+ startVisionPublisher({
146
+ ws,
147
+ track,
148
+ credentialsResponse: baseCredentialsResponse,
149
+ fps: 1.0,
150
+ onError,
151
+ });
152
+
153
+ expect(lastInstance().onError).toHaveBeenCalledWith(onError);
154
+ });
155
+
156
+ it('does not call onStatus/onError on the publisher when callbacks are omitted', () => {
157
+ const ws = makeMockWs();
158
+ const track = {} as MediaStreamTrack;
159
+
160
+ startVisionPublisher({
161
+ ws,
162
+ track,
163
+ credentialsResponse: baseCredentialsResponse,
164
+ fps: 1.0,
165
+ });
166
+
167
+ expect(lastInstance().onStatus).not.toHaveBeenCalled();
168
+ expect(lastInstance().onError).not.toHaveBeenCalled();
169
+ });
170
+
171
+ it('calls start() on the publisher', () => {
172
+ const ws = makeMockWs();
173
+ const track = {} as MediaStreamTrack;
174
+
175
+ startVisionPublisher({
176
+ ws,
177
+ track,
178
+ credentialsResponse: baseCredentialsResponse,
179
+ fps: 1.0,
180
+ });
181
+
182
+ expect(lastInstance().start).toHaveBeenCalled();
183
+ });
184
+
185
+ it('stop() calls publisher.stop() and both unsubscribers', () => {
186
+ const ws = makeMockWs();
187
+ const track = {} as MediaStreamTrack;
188
+ const offStatus = jest.fn();
189
+ const offError = jest.fn();
190
+ MockVisionPublisher.prototype.onStatus = jest.fn().mockReturnValue(offStatus);
191
+ MockVisionPublisher.prototype.onError = jest.fn().mockReturnValue(offError);
192
+ const onStatus = jest.fn<void, [VisionStatus]>();
193
+ const onError = jest.fn<void, [Error]>();
194
+
195
+ const handle = startVisionPublisher({
196
+ ws,
197
+ track,
198
+ credentialsResponse: baseCredentialsResponse,
199
+ fps: 1.0,
200
+ onStatus,
201
+ onError,
202
+ });
203
+
204
+ handle.stop();
205
+
206
+ expect(lastInstance().stop).toHaveBeenCalled();
207
+ expect(offStatus).toHaveBeenCalled();
208
+ expect(offError).toHaveBeenCalled();
209
+ });
210
+
211
+ it('forwards start() rejection to onError', async () => {
212
+ const ws = makeMockWs();
213
+ const track = {} as MediaStreamTrack;
214
+ const boom = new Error('peer connection exploded');
215
+ MockVisionPublisher.prototype.start = jest.fn().mockRejectedValue(boom);
216
+ const onError = jest.fn<void, [Error]>();
217
+
218
+ startVisionPublisher({
219
+ ws,
220
+ track,
221
+ credentialsResponse: baseCredentialsResponse,
222
+ fps: 1.0,
223
+ onError,
224
+ });
225
+
226
+ // Allow the promise microtask to settle.
227
+ await Promise.resolve();
228
+
229
+ expect(onError).toHaveBeenCalledWith(boom);
230
+ });
231
+
232
+ it('wraps non-Error start() rejections in an Error before forwarding', async () => {
233
+ const ws = makeMockWs();
234
+ const track = {} as MediaStreamTrack;
235
+ MockVisionPublisher.prototype.start = jest.fn().mockRejectedValue('string-error');
236
+ const onError = jest.fn<void, [Error]>();
237
+
238
+ startVisionPublisher({
239
+ ws,
240
+ track,
241
+ credentialsResponse: baseCredentialsResponse,
242
+ fps: 1.0,
243
+ onError,
244
+ });
245
+
246
+ await Promise.resolve();
247
+
248
+ expect(onError).toHaveBeenCalledWith(expect.any(Error));
249
+ expect(onError.mock.calls[0][0].message).toBe('string-error');
250
+ });
251
+ });
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Unit tests for `toVisionRtcCredentials`.
3
+ *
4
+ * Verifies:
5
+ * (a) null ICE `username` / `credential` are coerced to `undefined`
6
+ * (b) `traceId` (on the response type, NOT on VisionRtcCredentials) is dropped
7
+ * (c) all scalar fields pass through unchanged
8
+ */
9
+
10
+ import { toVisionRtcCredentials } from '../credentials';
11
+ import type { ChatVisionRtcCredentialsResponse } from '../../api';
12
+
13
+ const baseResponse: ChatVisionRtcCredentialsResponse = {
14
+ mode: 'kvs',
15
+ iceServers: [
16
+ {
17
+ urls: ['stun:stun.kinesisvideo.us-east-1.amazonaws.com:443'],
18
+ username: 'someuser',
19
+ credential: 'somepass',
20
+ },
21
+ ],
22
+ signedSignalingUrl: 'wss://example.com/signed',
23
+ channelArn: 'arn:aws:kinesisvideo:us-east-1:123:channel/test',
24
+ clientId: 'viewer-abc123',
25
+ region: 'us-east-1',
26
+ expiresIn: 300,
27
+ traceId: 'trace-xyz',
28
+ };
29
+
30
+ describe('toVisionRtcCredentials', () => {
31
+ it('(c) passes through scalar fields unchanged', () => {
32
+ const result = toVisionRtcCredentials(baseResponse);
33
+
34
+ expect(result.mode).toBe('kvs');
35
+ expect(result.signedSignalingUrl).toBe('wss://example.com/signed');
36
+ expect(result.channelArn).toBe(
37
+ 'arn:aws:kinesisvideo:us-east-1:123:channel/test',
38
+ );
39
+ expect(result.clientId).toBe('viewer-abc123');
40
+ expect(result.region).toBe('us-east-1');
41
+ expect(result.expiresIn).toBe(300);
42
+ });
43
+
44
+ it('(c) passes through present ICE username and credential unchanged', () => {
45
+ const result = toVisionRtcCredentials(baseResponse);
46
+
47
+ expect(result.iceServers).toHaveLength(1);
48
+ expect(result.iceServers[0].urls).toEqual([
49
+ 'stun:stun.kinesisvideo.us-east-1.amazonaws.com:443',
50
+ ]);
51
+ expect(result.iceServers[0].username).toBe('someuser');
52
+ expect(result.iceServers[0].credential).toBe('somepass');
53
+ });
54
+
55
+ it('(a) coerces null ICE username to undefined', () => {
56
+ const response: ChatVisionRtcCredentialsResponse = {
57
+ ...baseResponse,
58
+ iceServers: [
59
+ { urls: ['stun:stun.l.google.com:19302'], username: null, credential: null },
60
+ ],
61
+ };
62
+
63
+ const result = toVisionRtcCredentials(response);
64
+
65
+ expect(result.iceServers[0].username).toBeUndefined();
66
+ expect(result.iceServers[0].credential).toBeUndefined();
67
+ });
68
+
69
+ it('(a) coerces null ICE credential to undefined while keeping a present username', () => {
70
+ const response: ChatVisionRtcCredentialsResponse = {
71
+ ...baseResponse,
72
+ iceServers: [
73
+ { urls: ['stun:stun.l.google.com:19302'], username: 'u', credential: null },
74
+ ],
75
+ };
76
+
77
+ const result = toVisionRtcCredentials(response);
78
+
79
+ expect(result.iceServers[0].username).toBe('u');
80
+ expect(result.iceServers[0].credential).toBeUndefined();
81
+ });
82
+
83
+ it('(b) does NOT carry traceId over to VisionRtcCredentials', () => {
84
+ const result = toVisionRtcCredentials(baseResponse);
85
+
86
+ // TypeScript types would normally prevent accessing .traceId, but we cast
87
+ // to verify at runtime that the field is absent.
88
+ expect((result as unknown as Record<string, unknown>)['traceId']).toBeUndefined();
89
+ });
90
+
91
+ it('handles local mode with no kvs-specific fields', () => {
92
+ const localResponse: ChatVisionRtcCredentialsResponse = {
93
+ mode: 'local',
94
+ iceServers: [{ urls: ['stun:stun.l.google.com:19302'], username: null, credential: null }],
95
+ signedSignalingUrl: null,
96
+ channelArn: null,
97
+ clientId: null,
98
+ region: null,
99
+ expiresIn: 3600,
100
+ traceId: 'trace-local',
101
+ };
102
+
103
+ const result = toVisionRtcCredentials(localResponse);
104
+
105
+ expect(result.mode).toBe('local');
106
+ expect(result.signedSignalingUrl).toBeNull();
107
+ expect(result.channelArn).toBeNull();
108
+ expect(result.clientId).toBeNull();
109
+ expect(result.region).toBeNull();
110
+ expect(result.expiresIn).toBe(3600);
111
+ expect((result as unknown as Record<string, unknown>)['traceId']).toBeUndefined();
112
+ });
113
+ });
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Tests for the pure visionScheduler helper — a stateless backpressure
3
+ * loop that adjusts publisher fps in response to backend `vision_status`
4
+ * events.
5
+ *
6
+ * The scheduler is intentionally pure: no timers, no sockets, no
7
+ * RTCRtpSender plumbing. Hooks/publishers feed it state, get a new
8
+ * target fps back, and decide what to do with it. That keeps the
9
+ * heuristic testable without spinning up an RTCPeerConnection.
10
+ */
11
+
12
+ import {
13
+ computeNextFps,
14
+ createVisionScheduler,
15
+ } from '../visionScheduler';
16
+ import type { VisionStatus } from '../types';
17
+
18
+ describe('computeNextFps', () => {
19
+ it('halves fps when the backend reports processingPaused', () => {
20
+ const status: VisionStatus = {
21
+ bufferedFrames: 3,
22
+
23
+ processingPaused: true,
24
+ };
25
+ expect(
26
+ computeNextFps({ currentFps: 2.0, status, minFps: 0.5, maxFps: 3.0 }),
27
+ ).toBe(1.0);
28
+ });
29
+
30
+ it('clamps to minFps when halving would underflow', () => {
31
+ const status: VisionStatus = {
32
+ bufferedFrames: 3,
33
+
34
+ processingPaused: true,
35
+ };
36
+ expect(
37
+ computeNextFps({ currentFps: 0.6, status, minFps: 0.5, maxFps: 3.0 }),
38
+ ).toBe(0.5);
39
+ });
40
+
41
+ it('nudges fps upward when the buffer is empty and inference is fast', () => {
42
+ const status: VisionStatus = {
43
+ bufferedFrames: 0,
44
+
45
+ processingPaused: false,
46
+ };
47
+ const next = computeNextFps({
48
+ currentFps: 1.0,
49
+ status,
50
+ minFps: 0.5,
51
+ maxFps: 3.0,
52
+ });
53
+ expect(next).toBeGreaterThan(1.0);
54
+ expect(next).toBeLessThanOrEqual(3.0);
55
+ });
56
+
57
+ it('clamps the upward nudge at maxFps', () => {
58
+ const status: VisionStatus = {
59
+ bufferedFrames: 0,
60
+
61
+ processingPaused: false,
62
+ };
63
+ expect(
64
+ computeNextFps({ currentFps: 2.9, status, minFps: 0.5, maxFps: 3.0 }),
65
+ ).toBe(3.0);
66
+ });
67
+
68
+ it('leaves fps unchanged when the system is in steady-state', () => {
69
+ const status: VisionStatus = {
70
+ bufferedFrames: 1,
71
+
72
+ processingPaused: false,
73
+ };
74
+ expect(
75
+ computeNextFps({ currentFps: 1.0, status, minFps: 0.5, maxFps: 3.0 }),
76
+ ).toBe(1.0);
77
+ });
78
+ });
79
+
80
+ describe('createVisionScheduler', () => {
81
+ it('invokes the onFpsChange callback only when fps actually changes', () => {
82
+ const onFpsChange = jest.fn();
83
+ const scheduler = createVisionScheduler({
84
+ initialFps: 1.0,
85
+ minFps: 0.5,
86
+ maxFps: 3.0,
87
+ onFpsChange,
88
+ });
89
+
90
+ // Steady state — no callback.
91
+ scheduler.handleStatus({
92
+ bufferedFrames: 1,
93
+
94
+ processingPaused: false,
95
+ });
96
+ expect(onFpsChange).not.toHaveBeenCalled();
97
+
98
+ // Pause → halve to 0.5; callback fires once.
99
+ scheduler.handleStatus({
100
+ bufferedFrames: 3,
101
+
102
+ processingPaused: true,
103
+ });
104
+ expect(onFpsChange).toHaveBeenCalledTimes(1);
105
+ expect(onFpsChange).toHaveBeenCalledWith(0.5);
106
+ expect(scheduler.getFps()).toBe(0.5);
107
+
108
+ // Already at floor under pressure → no further callback.
109
+ scheduler.handleStatus({
110
+ bufferedFrames: 3,
111
+
112
+ processingPaused: true,
113
+ });
114
+ expect(onFpsChange).toHaveBeenCalledTimes(1);
115
+ });
116
+
117
+ it('reports the current fps via getFps()', () => {
118
+ const scheduler = createVisionScheduler({
119
+ initialFps: 1.5,
120
+ minFps: 0.5,
121
+ maxFps: 3.0,
122
+ onFpsChange: () => undefined,
123
+ });
124
+ expect(scheduler.getFps()).toBe(1.5);
125
+ scheduler.handleStatus({
126
+ bufferedFrames: 0,
127
+
128
+ processingPaused: false,
129
+ });
130
+ expect(scheduler.getFps()).toBeGreaterThan(1.5);
131
+ });
132
+
133
+ it('clamps an out-of-range initialFps into [minFps, maxFps]', () => {
134
+ const tooHigh = createVisionScheduler({
135
+ initialFps: 10,
136
+ minFps: 0.5,
137
+ maxFps: 3.0,
138
+ onFpsChange: () => undefined,
139
+ });
140
+ expect(tooHigh.getFps()).toBe(3.0);
141
+ const tooLow = createVisionScheduler({
142
+ initialFps: 0.1,
143
+ minFps: 0.5,
144
+ maxFps: 3.0,
145
+ onFpsChange: () => undefined,
146
+ });
147
+ expect(tooLow.getFps()).toBe(0.5);
148
+ });
149
+ });
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Pure mapping helper: API response → VisionPublisher credentials.
3
+ *
4
+ * The chat-API returns `ChatVisionRtcCredentialsResponse` whose ICE-server
5
+ * entries use `string | null` for optional fields (JSON can't carry
6
+ * `undefined`). `RTCIceServer` / `VisionRtcCredentials` want `string |
7
+ * undefined` instead, so we normalise here.
8
+ *
9
+ * `traceId` is a log-correlation field on the response; it is NOT part of
10
+ * `VisionRtcCredentials` and is intentionally dropped.
11
+ */
12
+
13
+ import type { ChatVisionRtcCredentialsResponse } from '../api';
14
+ import type { VisionRtcCredentials } from './types';
15
+
16
+ /**
17
+ * Convert a `ChatVisionRtcCredentialsResponse` (API wire shape) into the
18
+ * `VisionRtcCredentials` expected by `VisionPublisher`.
19
+ *
20
+ * - `null` ICE `username` / `credential` fields are coerced to `undefined`.
21
+ * - `traceId` (present on the response for log correlation) is dropped.
22
+ */
23
+ export function toVisionRtcCredentials(
24
+ response: ChatVisionRtcCredentialsResponse,
25
+ ): VisionRtcCredentials {
26
+ return {
27
+ mode: response.mode,
28
+ iceServers: response.iceServers.map((entry) => ({
29
+ urls: entry.urls,
30
+ username: entry.username ?? undefined,
31
+ credential: entry.credential ?? undefined,
32
+ })),
33
+ signedSignalingUrl: response.signedSignalingUrl,
34
+ channelArn: response.channelArn,
35
+ clientId: response.clientId,
36
+ region: response.region,
37
+ expiresIn: response.expiresIn,
38
+ };
39
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Public surface for the framework-agnostic vision publisher.
3
+ *
4
+ * Re-exported from `packages/client-core/src/index.ts` so consumers can
5
+ * `import { VisionPublisher } from '@escapeaihq/client-core'`.
6
+ */
7
+
8
+ export { VisionPublisher } from './VisionPublisher';
9
+ export {
10
+ computeNextFps,
11
+ createVisionScheduler,
12
+ } from './visionScheduler';
13
+ export type {
14
+ VisionPublisherConfig,
15
+ VisionPublisherOptions,
16
+ VisionRtcCredentials,
17
+ VisionStatus,
18
+ VisionStatusListener,
19
+ VisionErrorListener,
20
+ } from './types';
21
+ export type {
22
+ ComputeNextFpsInput,
23
+ VisionScheduler,
24
+ VisionSchedulerOptions,
25
+ } from './visionScheduler';
26
+ export { toVisionRtcCredentials } from './credentials';
27
+ export { startVisionPublisher } from './startVisionPublisher';
28
+ export type {
29
+ StartVisionPublisherOptions,
30
+ VisionPublisherHandle,
31
+ } from './startVisionPublisher';
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Framework-agnostic helper that constructs a `VisionPublisher`, wires up
3
+ * status/error callbacks, calls `start()`, and returns a handle whose
4
+ * `stop()` tears everything down in the correct order.
5
+ *
6
+ * Both React sites (`useVisionPublisher` and the chat-ws page) share the
7
+ * identical construct→subscribe→start→cleanup sequence; only the track
8
+ * source (captureStream vs getUserMedia) differs, which stays at the
9
+ * call site.
10
+ *
11
+ * Spec: `specs/2026-05-22-phase-2-multimodal-watch.md`.
12
+ */
13
+
14
+ import type { ChatVisionRtcCredentialsResponse } from '../api';
15
+ import type { ChatWebSocket } from '../websocket';
16
+ import { toVisionRtcCredentials } from './credentials';
17
+ import type { VisionStatus } from './types';
18
+ import { VisionPublisher } from './VisionPublisher';
19
+
20
+ export interface StartVisionPublisherOptions {
21
+ ws: ChatWebSocket;
22
+ track: MediaStreamTrack;
23
+ credentialsResponse: ChatVisionRtcCredentialsResponse;
24
+ fps: number;
25
+ onStatus?: (status: VisionStatus) => void;
26
+ onError?: (error: Error) => void;
27
+ }
28
+
29
+ export interface VisionPublisherHandle {
30
+ publisher: VisionPublisher;
31
+ stop: () => void;
32
+ }
33
+
34
+ /**
35
+ * Construct, wire, and start a `VisionPublisher` in one call.
36
+ *
37
+ * Returns a handle whose `stop()` calls both unsubscribers and
38
+ * `publisher.stop()`. The caller is still responsible for stopping
39
+ * the `MediaStream` tracks (since the stream may outlive the publisher)
40
+ * and for nulling any ref to `handle.publisher`.
41
+ */
42
+ export function startVisionPublisher(
43
+ opts: StartVisionPublisherOptions,
44
+ ): VisionPublisherHandle {
45
+ const publisher = new VisionPublisher({
46
+ ws: opts.ws,
47
+ track: opts.track,
48
+ config: { fps: opts.fps },
49
+ credentials: toVisionRtcCredentials(opts.credentialsResponse),
50
+ });
51
+ const offStatus = opts.onStatus ? publisher.onStatus(opts.onStatus) : (): void => {};
52
+ const offError = opts.onError ? publisher.onError(opts.onError) : (): void => {};
53
+ publisher
54
+ .start()
55
+ .catch((e) => opts.onError?.(e instanceof Error ? e : new Error(String(e))));
56
+ return {
57
+ publisher,
58
+ stop: () => {
59
+ offStatus();
60
+ offError();
61
+ publisher.stop();
62
+ },
63
+ };
64
+ }