@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,265 @@
1
+ /**
2
+ * Tests for the vision-signaling additions to `ChatWebSocket`:
3
+ * - `sendVisionOffer` / `sendVisionIce` / `sendVisionClose` outbound
4
+ * send methods.
5
+ * - `on(event, handler)` / `off(event, handler)` typed event dispatch
6
+ * for inbound `vision_answer` / `vision_ice` / `vision_status`.
7
+ *
8
+ * Mirrors the StubWebSocket pattern used by `websocket.test.ts` —
9
+ * jsdom's WebSocket actually dials, so we replace the constructor with
10
+ * a stub that records sends and lets each test drive open/message/close
11
+ * synchronously.
12
+ *
13
+ * Wire-shape source of truth: `shared/vision_protocol.py`. The outbound
14
+ * `vision_ice` payload converts camel-case (`sdpMid` / `sdpMLineIndex`)
15
+ * to snake_case (`sdp_mid` / `sdp_m_line_index`); the inbound dispatcher
16
+ * converts the reverse direction so listeners always see camel-case.
17
+ */
18
+
19
+ import { ChatWebSocket } from '../websocket';
20
+ import type {
21
+ VisionAnswerEvent,
22
+ VisionIceEvent,
23
+ VisionStatusEvent,
24
+ } from '../websocket';
25
+
26
+ interface FakeWebSocket {
27
+ url: string;
28
+ readyState: number;
29
+ binaryType: string;
30
+ sent: string[];
31
+ onopen?: () => void;
32
+ onerror?: (err: Event) => void;
33
+ onmessage?: (event: MessageEvent) => void;
34
+ onclose?: () => void;
35
+ close: () => void;
36
+ send: (data: string | ArrayBuffer | Uint8Array) => void;
37
+ simulateOpen: () => void;
38
+ simulateMessage: (data: string) => void;
39
+ }
40
+
41
+ const instances: FakeWebSocket[] = [];
42
+
43
+ class StubWebSocket {
44
+ static CONNECTING = 0;
45
+ static OPEN = 1;
46
+ static CLOSING = 2;
47
+ static CLOSED = 3;
48
+
49
+ url: string;
50
+ readyState = StubWebSocket.CONNECTING;
51
+ binaryType = 'blob';
52
+ sent: string[] = [];
53
+ onopen?: () => void;
54
+ onerror?: (err: Event) => void;
55
+ onmessage?: (event: MessageEvent) => void;
56
+ onclose?: () => void;
57
+
58
+ constructor(url: string) {
59
+ this.url = url;
60
+ const ref = this as unknown as FakeWebSocket;
61
+ ref.close = () => {
62
+ this.readyState = StubWebSocket.CLOSED;
63
+ };
64
+ ref.send = (data: string | ArrayBuffer | Uint8Array) => {
65
+ if (typeof data === 'string') {
66
+ this.sent.push(data);
67
+ }
68
+ };
69
+ ref.simulateOpen = () => {
70
+ this.readyState = StubWebSocket.OPEN;
71
+ this.onopen?.();
72
+ };
73
+ ref.simulateMessage = (data: string) => {
74
+ this.onmessage?.({ data } as MessageEvent);
75
+ };
76
+ instances.push(ref);
77
+ }
78
+ }
79
+
80
+ const originalWebSocket = globalThis.WebSocket;
81
+
82
+ const flushMicrotasks = async (): Promise<void> => {
83
+ await Promise.resolve();
84
+ await Promise.resolve();
85
+ };
86
+
87
+ const lastSocket = (): FakeWebSocket => {
88
+ const last = instances[instances.length - 1];
89
+ if (!last) throw new Error('No WebSocket has been constructed yet');
90
+ return last;
91
+ };
92
+
93
+ beforeEach(() => {
94
+ instances.length = 0;
95
+ (globalThis as unknown as { WebSocket: typeof StubWebSocket }).WebSocket =
96
+ StubWebSocket;
97
+ });
98
+
99
+ afterEach(() => {
100
+ jest.useRealTimers();
101
+ (globalThis as { WebSocket?: typeof WebSocket }).WebSocket = originalWebSocket;
102
+ });
103
+
104
+ const openSocket = async (): Promise<ChatWebSocket> => {
105
+ const ws = new ChatWebSocket({ url: 'ws://test/chat', authToken: 'tok' });
106
+ const connectPromise = ws.connect();
107
+ await flushMicrotasks();
108
+ lastSocket().simulateOpen();
109
+ await connectPromise;
110
+ return ws;
111
+ };
112
+
113
+ describe('ChatWebSocket — vision outbound signaling', () => {
114
+ it('sendVisionOffer serializes the exact wire shape', async () => {
115
+ const ws = await openSocket();
116
+ ws.sendVisionOffer({
117
+ action: 'vision_offer',
118
+ sdp: 'v=0\r\no=- 123 ...',
119
+ fps: 1.5,
120
+ });
121
+ expect(lastSocket().sent).toHaveLength(1);
122
+ expect(JSON.parse(lastSocket().sent[0])).toEqual({
123
+ action: 'vision_offer',
124
+ sdp: 'v=0\r\no=- 123 ...',
125
+ fps: 1.5,
126
+ });
127
+ });
128
+
129
+ it('sendVisionIce converts camelCase to snake_case on the wire', async () => {
130
+ const ws = await openSocket();
131
+ ws.sendVisionIce({
132
+ action: 'vision_ice',
133
+ candidate: 'candidate:1 1 udp 2113937151 192.0.2.1 50000 typ host',
134
+ sdpMid: '0',
135
+ sdpMLineIndex: 0,
136
+ });
137
+ expect(JSON.parse(lastSocket().sent[0])).toEqual({
138
+ action: 'vision_ice',
139
+ candidate: 'candidate:1 1 udp 2113937151 192.0.2.1 50000 typ host',
140
+ sdp_mid: '0',
141
+ sdp_m_line_index: 0,
142
+ });
143
+ });
144
+
145
+ it('sendVisionIce serializes the end-of-candidates sentinel as null', async () => {
146
+ const ws = await openSocket();
147
+ ws.sendVisionIce({ action: 'vision_ice', candidate: null });
148
+ expect(JSON.parse(lastSocket().sent[0])).toEqual({
149
+ action: 'vision_ice',
150
+ candidate: null,
151
+ sdp_mid: null,
152
+ sdp_m_line_index: null,
153
+ });
154
+ });
155
+
156
+ it('sendVisionClose sends the vision_close action', async () => {
157
+ const ws = await openSocket();
158
+ ws.sendVisionClose();
159
+ expect(JSON.parse(lastSocket().sent[0])).toEqual({ action: 'vision_close' });
160
+ });
161
+
162
+ it('vision sends drop silently when the socket is not OPEN', () => {
163
+ // No connect() — there's no underlying socket. All three send methods
164
+ // are best-effort; they must early-return rather than throw, mirroring
165
+ // sendPlaybackState semantics.
166
+ const ws = new ChatWebSocket({ url: 'ws://test/chat' });
167
+ expect(() =>
168
+ ws.sendVisionOffer({ action: 'vision_offer', sdp: 'x', fps: 1 }),
169
+ ).not.toThrow();
170
+ expect(() =>
171
+ ws.sendVisionIce({ action: 'vision_ice', candidate: null }),
172
+ ).not.toThrow();
173
+ expect(() => ws.sendVisionClose()).not.toThrow();
174
+ expect(instances).toHaveLength(0);
175
+ });
176
+ });
177
+
178
+ describe('ChatWebSocket — inbound vision event dispatch', () => {
179
+ it('routes vision_answer to listeners registered via on()', async () => {
180
+ const ws = await openSocket();
181
+ const handler = jest.fn();
182
+ ws.on('vision_answer', handler);
183
+ lastSocket().simulateMessage(
184
+ JSON.stringify({ type: 'vision_answer', sdp: 'fake-answer-sdp' }),
185
+ );
186
+ expect(handler).toHaveBeenCalledTimes(1);
187
+ const received = handler.mock.calls[0]?.[0] as VisionAnswerEvent;
188
+ expect(received).toEqual({ type: 'vision_answer', sdp: 'fake-answer-sdp' });
189
+ });
190
+
191
+ it('routes vision_ice and converts snake_case to camelCase for listeners', async () => {
192
+ const ws = await openSocket();
193
+ const handler = jest.fn();
194
+ ws.on('vision_ice', handler);
195
+ lastSocket().simulateMessage(
196
+ JSON.stringify({
197
+ action: 'vision_ice',
198
+ candidate: 'candidate:remote ...',
199
+ sdp_mid: '0',
200
+ sdp_m_line_index: 0,
201
+ }),
202
+ );
203
+ const received = handler.mock.calls[0]?.[0] as VisionIceEvent;
204
+ expect(received).toEqual({
205
+ action: 'vision_ice',
206
+ candidate: 'candidate:remote ...',
207
+ sdpMid: '0',
208
+ sdpMLineIndex: 0,
209
+ });
210
+ });
211
+
212
+ it('routes vision_status with camelCase shape ready for the HUD', async () => {
213
+ const ws = await openSocket();
214
+ const handler = jest.fn();
215
+ ws.on('vision_status', handler);
216
+ lastSocket().simulateMessage(
217
+ JSON.stringify({
218
+ type: 'vision_status',
219
+ buffered_frames: 2,
220
+
221
+ processing_paused: false,
222
+ }),
223
+ );
224
+ const received = handler.mock.calls[0]?.[0] as VisionStatusEvent;
225
+ expect(received).toEqual({
226
+ type: 'vision_status',
227
+ bufferedFrames: 2,
228
+
229
+ processingPaused: false,
230
+ });
231
+ });
232
+
233
+ it('off() removes the typed listener', async () => {
234
+ const ws = await openSocket();
235
+ const handler = jest.fn();
236
+ ws.on('vision_answer', handler);
237
+ ws.off('vision_answer', handler);
238
+ lastSocket().simulateMessage(
239
+ JSON.stringify({ type: 'vision_answer', sdp: 'x' }),
240
+ );
241
+ expect(handler).not.toHaveBeenCalled();
242
+ });
243
+
244
+ it('preserves back-compat: typed messages still reach onMessage handlers', async () => {
245
+ const ws = await openSocket();
246
+ const onMessageHandler = jest.fn();
247
+ ws.onMessage(onMessageHandler);
248
+ lastSocket().simulateMessage(
249
+ JSON.stringify({ type: 'vision_answer', sdp: 'x' }),
250
+ );
251
+ // The legacy onMessage path still fires so existing consumers
252
+ // observing every raw message keep working.
253
+ expect(onMessageHandler).toHaveBeenCalledTimes(1);
254
+ });
255
+
256
+ it('typed dispatch ignores messages that are not vision events', async () => {
257
+ const ws = await openSocket();
258
+ const visionHandler = jest.fn();
259
+ ws.on('vision_answer', visionHandler);
260
+ lastSocket().simulateMessage(
261
+ JSON.stringify({ type: 'token', content: 'hello' }),
262
+ );
263
+ expect(visionHandler).not.toHaveBeenCalled();
264
+ });
265
+ });
@@ -250,6 +250,81 @@ describe('ChatWebSocket — onReconnect hello payload', () => {
250
250
  });
251
251
  });
252
252
 
253
+ describe('ChatWebSocket — sendPlaybackState', () => {
254
+ it('serializes the playback_state action with stamped clientTs when OPEN', async () => {
255
+ const ws = new ChatWebSocket({ url: 'ws://test/chat', authToken: 'tok' });
256
+ const connectPromise = ws.connect();
257
+ await flushMicrotasks();
258
+ lastSocket().simulateOpen();
259
+ await connectPromise;
260
+
261
+ // Pin Date.now so the stamped clientTs is deterministic.
262
+ const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000);
263
+ ws.sendPlaybackState({
264
+ videoId: 'v-1',
265
+ currentTime: 12.5,
266
+ shotId: 'S014',
267
+ paused: false,
268
+ });
269
+
270
+ expect(lastSocket().sent).toHaveLength(1);
271
+ const sent = JSON.parse(lastSocket().sent[0] as string);
272
+ expect(sent).toEqual({
273
+ action: 'playback_state',
274
+ videoId: 'v-1',
275
+ currentTime: 12.5,
276
+ shotId: 'S014',
277
+ paused: false,
278
+ clientTs: 1_700_000_000,
279
+ });
280
+ nowSpy.mockRestore();
281
+ });
282
+
283
+ it('preserves sub-second clientTs precision', async () => {
284
+ const ws = new ChatWebSocket({ url: 'ws://test/chat', authToken: 'tok' });
285
+ const connectPromise = ws.connect();
286
+ await flushMicrotasks();
287
+ lastSocket().simulateOpen();
288
+ await connectPromise;
289
+
290
+ // 1_700_000_000_123 ms → 1_700_000_000.123 s — confirms `/ 1000` does
291
+ // not silently truncate to whole seconds.
292
+ const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1_700_000_000_123);
293
+ ws.sendPlaybackState({ videoId: 'v-1', currentTime: 0, paused: false });
294
+ const sent = JSON.parse(lastSocket().sent[0] as string);
295
+ expect(sent.clientTs).toBeCloseTo(1_700_000_000.123, 3);
296
+ nowSpy.mockRestore();
297
+ });
298
+
299
+ it('drops silently when the socket is not OPEN (no throw, no send)', () => {
300
+ // Construct a ChatWebSocket but never call connect() — there's no
301
+ // underlying socket. The method must early-return rather than
302
+ // throw, because the publisher is best-effort.
303
+ const ws = new ChatWebSocket({ url: 'ws://test/chat' });
304
+ expect(() =>
305
+ ws.sendPlaybackState({
306
+ videoId: 'v-1',
307
+ currentTime: 0,
308
+ paused: true,
309
+ }),
310
+ ).not.toThrow();
311
+ expect(instances).toHaveLength(0);
312
+ });
313
+
314
+ it('drops silently after the socket has closed', async () => {
315
+ const ws = new ChatWebSocket({ url: 'ws://test/chat', authToken: 'tok' });
316
+ const connectPromise = ws.connect();
317
+ await flushMicrotasks();
318
+ lastSocket().simulateOpen();
319
+ await connectPromise;
320
+
321
+ lastSocket().simulateClose();
322
+ ws.sendPlaybackState({ videoId: 'v-1', currentTime: 3, paused: false });
323
+ // Post-close socket should have no recorded sends.
324
+ expect(lastSocket().sent).toEqual([]);
325
+ });
326
+ });
327
+
253
328
  describe('ChatWebSocket — back-compat with static authToken', () => {
254
329
  it('builds the URL from authToken when fetchToken is absent', async () => {
255
330
  const ws = new ChatWebSocket({
package/src/api.ts CHANGED
@@ -3,12 +3,38 @@
3
3
  */
4
4
 
5
5
  import type { AudioFormat } from './audioProtocol';
6
+ import { isAbortError } from './reactor/abortUtils';
6
7
  import type {
7
8
  EntityContext as ReactorEntityContext,
8
9
  PersonaContext as ReactorPersonaContext,
9
10
  } from './reactor/types';
10
11
  import type { Citation } from './websocket';
11
12
 
13
+ /**
14
+ * Module-private helper: resolves after `ms` milliseconds, or rejects with
15
+ * an AbortError if the optional `signal` fires before the timer expires.
16
+ *
17
+ * Listener hygiene: the abort listener is removed explicitly on the normal
18
+ * (timer) path so it does not linger on the signal after resolution.
19
+ */
20
+ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
21
+ return new Promise<void>((resolve, reject) => {
22
+ // Declare `timer` with `let` first so `onAbort` can reference it in the
23
+ // closure without a use-before-define lint error (the closure is only
24
+ // invoked after `timer` is assigned below).
25
+ let timer: ReturnType<typeof setTimeout>;
26
+ const onAbort = () => {
27
+ clearTimeout(timer);
28
+ reject(new DOMException('Polling aborted', 'AbortError'));
29
+ };
30
+ timer = setTimeout(() => {
31
+ signal?.removeEventListener('abort', onAbort);
32
+ resolve();
33
+ }, ms);
34
+ signal?.addEventListener('abort', onAbort, { once: true });
35
+ });
36
+ }
37
+
12
38
  export interface IngestionJob {
13
39
  jobId: string;
14
40
  videoId: string;
@@ -148,6 +174,50 @@ export interface ChatStreamRequest {
148
174
  modelId?: string;
149
175
  }
150
176
 
177
+ /**
178
+ * Capability flags advertised by a chat model. Mirrors
179
+ * ``shared/model_config.py:CAPABILITY_*`` so frontends can decide which
180
+ * UI affordances (image upload, audio chat, tool selection) to enable
181
+ * per model.
182
+ */
183
+ export type ChatModelCapability = 'tools' | 'vision' | 'audio' | 'thinking';
184
+
185
+ /**
186
+ * Single entry from ``GET /api/v1/chat/models``. The ``provider`` field
187
+ * tells consumers whether the backend will route via Bedrock or an
188
+ * OpenAI-compatible local endpoint — affects only diagnostics; the chat
189
+ * WebSocket protocol is identical for both.
190
+ */
191
+ export interface ChatModelInfo {
192
+ id: string;
193
+ name: string;
194
+ displayName: string;
195
+ provider: 'bedrock' | 'ollama' | string;
196
+ contextWindow: number;
197
+ maxOutputTokens: number;
198
+ capabilities: ChatModelCapability[];
199
+ }
200
+
201
+ export interface ChatModelsResponse {
202
+ models: ChatModelInfo[];
203
+ defaultModelId?: string | null;
204
+ }
205
+
206
+ /**
207
+ * Default system prompt components returned by `GET /api/v1/chat/system-prompt`.
208
+ *
209
+ * @property film_qa - Base film analyst persona and instructions
210
+ * @property guardrails - Developer guidance and safety constraints
211
+ * @property audio_markup - Instructions for TTS-optimized responses
212
+ * @property full_default - Combined default prompt as used in chat sessions
213
+ */
214
+ export interface SystemPromptComponents {
215
+ film_qa: string;
216
+ guardrails: string;
217
+ audio_markup: string;
218
+ full_default: string;
219
+ }
220
+
151
221
  // Persona types matching backend shared/persona_models.py
152
222
 
153
223
  export interface PersonaConfig {
@@ -191,6 +261,16 @@ export interface PersonaConfig {
191
261
  status: 'pending' | 'approved';
192
262
  created_at: string;
193
263
  updated_at: string;
264
+ /** Phase 2: opt into live-vision frame attachment on chat turns. Default
265
+ * false. When true and the persona's ``chat_model_id`` supports the
266
+ * ``vision`` capability, the backend attaches the latest browser-side
267
+ * captured frame to each user message. */
268
+ vision_enabled?: boolean;
269
+ /** Phase 2: requested vision frame cadence in frames-per-second (0.5–3.0).
270
+ * Client-side preference for the publisher's encode rate; backend
271
+ * does not currently enforce this server-side (see specs/technical-debt.md
272
+ * Issue #161). */
273
+ vision_fps?: number;
194
274
  }
195
275
 
196
276
  // Viseme bundle types — see services/persona/ and shared/viseme_bundle_models.py
@@ -441,6 +521,10 @@ export interface CreatePersonaRequest {
441
521
  prompt_addon_ids?: string[];
442
522
  is_default?: boolean;
443
523
  status?: 'pending' | 'approved';
524
+ /** Phase 2: opt into live-vision frame attachment on chat turns. */
525
+ vision_enabled?: boolean;
526
+ /** Phase 2: requested vision frame cadence in fps (0.5–3.0). */
527
+ vision_fps?: number;
444
528
  }
445
529
 
446
530
  export interface UpdatePersonaRequest {
@@ -469,6 +553,10 @@ export interface UpdatePersonaRequest {
469
553
  prompt_addon_ids?: string[] | null;
470
554
  is_default?: boolean | null;
471
555
  status?: 'pending' | 'approved';
556
+ /** Phase 2: opt into / out of live-vision frame attachment. */
557
+ vision_enabled?: boolean | null;
558
+ /** Phase 2: vision frame cadence in fps (0.5–3.0). */
559
+ vision_fps?: number | null;
472
560
  }
473
561
 
474
562
  export interface PersonaListResponse {
@@ -536,6 +624,35 @@ export interface ChatWsTokenResponse {
536
624
  expiresIn: number;
537
625
  }
538
626
 
627
+ /**
628
+ * Response from `POST /api/v1/chat/vision-rtc/credentials` — mirrors
629
+ * the Pydantic `VisionRtcCredentialsResponse` on the backend. `mode`
630
+ * tells the publisher whether to use the chat-WS signaling protocol
631
+ * (`local`) or the KVS WebRTC SDK (`kvs`); the rest of the fields are
632
+ * the connection-establishment material for the chosen mode.
633
+ *
634
+ * Re-exported as `VisionRtcCredentials` from
635
+ * `@escapeaihq/client-core/vision` for convenience at the
636
+ * `VisionPublisher` callsite.
637
+ */
638
+ export interface ChatVisionRtcCredentialsResponse {
639
+ mode: 'local' | 'kvs';
640
+ iceServers: Array<{
641
+ urls: string[];
642
+ username?: string | null;
643
+ credential?: string | null;
644
+ }>;
645
+ signedSignalingUrl: string | null;
646
+ channelArn: string | null;
647
+ clientId: string | null;
648
+ /** kvs mode only: AWS region for SigV4-signing follow-up ICE
649
+ * candidate messages. Null in local mode. */
650
+ region: string | null;
651
+ expiresIn: number;
652
+ /** Opaque request id for log correlation — matches chat-API logs. */
653
+ traceId: string;
654
+ }
655
+
539
656
  // Session types matching backend shared/persona_models.py
540
657
  export interface SessionMessage {
541
658
  role: string;
@@ -754,20 +871,6 @@ export interface UpsampleReactorPromptResponse {
754
871
  upsampledPrompt: string;
755
872
  }
756
873
 
757
- /**
758
- * Detect an abort (controller.abort(), unmount, signal expiry) so callers
759
- * can stay silent on expected cancellations while still surfacing real
760
- * fetch errors (5xx / timeout / CORS). Native `fetch` rejects with a
761
- * `DOMException { name: 'AbortError' }`; the project's own pollers throw
762
- * the same shape; a polyfilled fetch may throw a plain `Error` with the
763
- * same name. Accept both so the warn-suppression survives a future
764
- * polyfill or SSR runtime swap.
765
- */
766
- function isAbortError(err: unknown): boolean {
767
- if (err instanceof DOMException && err.name === 'AbortError') return true;
768
- return err instanceof Error && err.name === 'AbortError';
769
- }
770
-
771
874
  export class ApiClient {
772
875
  private baseURL: string;
773
876
  private sessionToken?: string;
@@ -1077,6 +1180,15 @@ export class ApiClient {
1077
1180
  return reader;
1078
1181
  }
1079
1182
 
1183
+ /**
1184
+ * Fetch the chat-model registry from the backend. Returns Bedrock entries
1185
+ * plus any locally-discovered Ollama models. Public endpoint — works
1186
+ * before the user is authenticated.
1187
+ */
1188
+ async listChatModels(): Promise<ChatModelsResponse> {
1189
+ return this.chatRequest<ChatModelsResponse>('/api/v1/chat/models');
1190
+ }
1191
+
1080
1192
  // ==================== Persona API Methods ====================
1081
1193
  // Note: Personas are served by the Chat API, not the Tools API
1082
1194
 
@@ -1370,17 +1482,7 @@ export class ApiClient {
1370
1482
  if (Date.now() >= deadline) {
1371
1483
  throw new Error(`Image generation timed out after ${Math.round(timeoutMs / 1000)}s`);
1372
1484
  }
1373
- await new Promise<void>((resolve, reject) => {
1374
- const timer = setTimeout(() => {
1375
- options.signal?.removeEventListener('abort', onAbort);
1376
- resolve();
1377
- }, intervalMs);
1378
- const onAbort = () => {
1379
- clearTimeout(timer);
1380
- reject(new DOMException('Polling aborted', 'AbortError'));
1381
- };
1382
- options.signal?.addEventListener('abort', onAbort, { once: true });
1383
- });
1485
+ await abortableSleep(intervalMs, options.signal);
1384
1486
  }
1385
1487
  }
1386
1488
 
@@ -1400,6 +1502,25 @@ export class ApiClient {
1400
1502
  });
1401
1503
  }
1402
1504
 
1505
+ /**
1506
+ * Mint WebRTC signaling credentials for a vision-publisher session.
1507
+ *
1508
+ * Returns either `local`-mode config (STUN-only; existing chat-WS
1509
+ * signaling protocol) or `kvs`-mode config (SigV4-presigned wss://
1510
+ * URL + short-term STUN/TURN). The publisher branches on `mode` —
1511
+ * raw AWS credentials never reach the browser.
1512
+ *
1513
+ * Token TTL is short (~300s); callers running long-lived sessions
1514
+ * should re-call this method before `expiresIn` elapses. The current
1515
+ * VisionPublisher does NOT auto-refresh.
1516
+ */
1517
+ async getVisionRtcCredentials(): Promise<ChatVisionRtcCredentialsResponse> {
1518
+ return this.chatRequest<ChatVisionRtcCredentialsResponse>(
1519
+ '/api/v1/chat/vision-rtc/credentials',
1520
+ { method: 'POST' },
1521
+ );
1522
+ }
1523
+
1403
1524
  /**
1404
1525
  * List available TTS voices. Backed by `GET /api/voices` — server
1405
1526
  * caches Inworld results for 5 min; pass `refresh: true` to bypass.
@@ -1864,17 +1985,7 @@ export class ApiClient {
1864
1985
  if (Date.now() >= deadline) {
1865
1986
  throw new Error(`Regeneration timed out after ${Math.round(timeoutMs / 1000)}s`);
1866
1987
  }
1867
- await new Promise<void>((resolve, reject) => {
1868
- const timer = setTimeout(() => {
1869
- options.signal?.removeEventListener('abort', onAbort);
1870
- resolve();
1871
- }, intervalMs);
1872
- const onAbort = () => {
1873
- clearTimeout(timer);
1874
- reject(new DOMException('Polling aborted', 'AbortError'));
1875
- };
1876
- options.signal?.addEventListener('abort', onAbort, { once: true });
1877
- });
1988
+ await abortableSleep(intervalMs, options.signal);
1878
1989
  }
1879
1990
  }
1880
1991
 
@@ -1936,17 +2047,7 @@ export class ApiClient {
1936
2047
  `Bundle generation timed out after ${Math.round(timeoutMs / 1000)}s`,
1937
2048
  );
1938
2049
  }
1939
- await new Promise<void>((resolve, reject) => {
1940
- const timer = setTimeout(() => {
1941
- options.signal?.removeEventListener('abort', onAbort);
1942
- resolve();
1943
- }, intervalMs);
1944
- const onAbort = () => {
1945
- clearTimeout(timer);
1946
- reject(new DOMException('Polling aborted', 'AbortError'));
1947
- };
1948
- options.signal?.addEventListener('abort', onAbort, { once: true });
1949
- });
2050
+ await abortableSleep(intervalMs, options.signal);
1950
2051
  }
1951
2052
  }
1952
2053
 
@@ -2029,6 +2130,18 @@ export class ApiClient {
2029
2130
  return await response.blob();
2030
2131
  }
2031
2132
 
2133
+ /**
2134
+ * Fetch the default system prompt components from the Chat API.
2135
+ * Backed by `GET /api/v1/chat/system-prompt`.
2136
+ *
2137
+ * Authentication is required — the client must have a session token set.
2138
+ * Callers that need caching should wrap this in their own layer (see
2139
+ * `web/lib/systemPrompt.ts` which keeps a 5-minute in-memory cache).
2140
+ */
2141
+ async getSystemPrompt(): Promise<SystemPromptComponents> {
2142
+ return this.chatRequest<SystemPromptComponents>('/api/v1/chat/system-prompt');
2143
+ }
2144
+
2032
2145
  /**
2033
2146
  * Knowledge-grounded prompt upsample — expands a short user prompt
2034
2147
  * into a Helios-quality 80-120 word paragraph using Bedrock. Routes