@escapeaihq/client-core 0.5.0 → 0.6.1
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.
- package/dist/api.d.ts +129 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +69 -0
- package/dist/api.js.map +1 -1
- package/dist/visemeGeometry.d.ts +15 -0
- package/dist/visemeGeometry.d.ts.map +1 -1
- package/dist/visemeGeometry.js +26 -0
- package/dist/visemeGeometry.js.map +1 -1
- package/dist/visemeScheduler.d.ts +12 -0
- package/dist/visemeScheduler.d.ts.map +1 -1
- package/dist/visemeScheduler.js +24 -0
- package/dist/visemeScheduler.js.map +1 -1
- package/dist/websocket.d.ts +156 -4
- package/dist/websocket.d.ts.map +1 -1
- package/dist/websocket.js +52 -7
- package/dist/websocket.js.map +1 -1
- package/package.json +1 -1
- package/src/__tests__/chat-auth.test.ts +261 -0
- package/src/__tests__/tools-wrappers.test.ts +219 -0
- package/src/__tests__/websocket.test.ts +278 -0
- package/src/api.ts +179 -0
- package/src/visemeGeometry.ts +30 -0
- package/src/visemeScheduler.ts +25 -0
- package/src/websocket.ts +193 -8
package/src/websocket.ts
CHANGED
|
@@ -9,7 +9,11 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import type { HelloPayload } from './audio';
|
|
12
|
-
import type {
|
|
12
|
+
import type {
|
|
13
|
+
AudioMetadataMessage,
|
|
14
|
+
BargeInAckMessage,
|
|
15
|
+
WordPhonemeInfo,
|
|
16
|
+
} from './audioProtocol';
|
|
13
17
|
|
|
14
18
|
export interface Citation {
|
|
15
19
|
videoId: string;
|
|
@@ -38,6 +42,104 @@ export interface ToolResult {
|
|
|
38
42
|
*/
|
|
39
43
|
export type DoneReason = 'complete' | 'timeout' | (string & {});
|
|
40
44
|
|
|
45
|
+
/**
|
|
46
|
+
* Discriminated union of every event the chat WebSocket can emit.
|
|
47
|
+
*
|
|
48
|
+
* Prefer this over the legacy {@link WebSocketMessage} flat interface
|
|
49
|
+
* when writing new code — TypeScript narrows each `case` in a switch
|
|
50
|
+
* to exactly the fields that case carries, so missing cases surface
|
|
51
|
+
* as compile errors rather than silent undefineds. The legacy shape
|
|
52
|
+
* is retained for back-compat with existing consumers but is being
|
|
53
|
+
* phased out — both seer-agent's React `chat-ws/page.tsx` and the
|
|
54
|
+
* Vue `seer-ai-chat.vue` hand-rolled their own copies of this union
|
|
55
|
+
* before it lived here.
|
|
56
|
+
*
|
|
57
|
+
* **Timestamp asymmetry.** Most cases carry `timestamp?: number`
|
|
58
|
+
* because `api/chat/ws.py` injects one into the dict literal before
|
|
59
|
+
* sending. The two pydantic-modelled cases (`AudioMetadataMessage`,
|
|
60
|
+
* `BargeInAckMessage` from `audioProtocol.ts`) intentionally omit it
|
|
61
|
+
* — their pydantic models use `extra="forbid"` and don't declare a
|
|
62
|
+
* timestamp field, so the server cannot send one. Don't add
|
|
63
|
+
* `timestamp?` to those interfaces unless you also relax the pydantic
|
|
64
|
+
* schemas.
|
|
65
|
+
*
|
|
66
|
+
* Source of truth for field semantics: `api/chat/app.py:websocket_endpoint`
|
|
67
|
+
* docstring + `api/chat/ws.py`.
|
|
68
|
+
*/
|
|
69
|
+
export type ChatWsEvent =
|
|
70
|
+
| { type: 'token'; timestamp?: number; content: string }
|
|
71
|
+
| {
|
|
72
|
+
type: 'citation';
|
|
73
|
+
timestamp?: number;
|
|
74
|
+
citation: Citation;
|
|
75
|
+
span?: string;
|
|
76
|
+
}
|
|
77
|
+
| { type: 'done'; timestamp?: number; reason?: DoneReason }
|
|
78
|
+
| { type: 'error'; timestamp?: number; message: string }
|
|
79
|
+
| {
|
|
80
|
+
type: 'image';
|
|
81
|
+
timestamp?: number;
|
|
82
|
+
imageUrl: string;
|
|
83
|
+
entity?: string;
|
|
84
|
+
prompt?: string;
|
|
85
|
+
sourceTimestamp?: number;
|
|
86
|
+
}
|
|
87
|
+
| {
|
|
88
|
+
type: 'tool_use';
|
|
89
|
+
timestamp?: number;
|
|
90
|
+
tool: string;
|
|
91
|
+
toolUseId: string;
|
|
92
|
+
}
|
|
93
|
+
| {
|
|
94
|
+
type: 'tool_result';
|
|
95
|
+
timestamp?: number;
|
|
96
|
+
tool?: string;
|
|
97
|
+
toolUseId?: string;
|
|
98
|
+
result?: ToolResult;
|
|
99
|
+
}
|
|
100
|
+
| {
|
|
101
|
+
type: 'hello_ack';
|
|
102
|
+
timestamp?: number;
|
|
103
|
+
sessionId: string;
|
|
104
|
+
mode: 'hybrid' | 'sonic';
|
|
105
|
+
/** Negotiated audio format ('pcm16' or 'mp3'). Optional on the
|
|
106
|
+
* wire — the server only populates it when the negotiation
|
|
107
|
+
* actually picked a value. See `HelloAckMessage` in
|
|
108
|
+
* `shared/audio_protocol.py`. */
|
|
109
|
+
audioFormat?: string;
|
|
110
|
+
}
|
|
111
|
+
| {
|
|
112
|
+
type: 'transcript';
|
|
113
|
+
timestamp?: number;
|
|
114
|
+
text: string;
|
|
115
|
+
final: boolean;
|
|
116
|
+
resultId?: string;
|
|
117
|
+
}
|
|
118
|
+
| AudioMetadataMessage
|
|
119
|
+
| BargeInAckMessage
|
|
120
|
+
| {
|
|
121
|
+
type: 'audio_chunk';
|
|
122
|
+
timestamp?: number;
|
|
123
|
+
chunkId?: string;
|
|
124
|
+
audio: string;
|
|
125
|
+
format: 'mp3' | 'pcm16' | 'ogg_opus';
|
|
126
|
+
}
|
|
127
|
+
| {
|
|
128
|
+
type: 'metrics';
|
|
129
|
+
timestamp?: number;
|
|
130
|
+
llm_first_token_ms?: number;
|
|
131
|
+
tts_first_chunk_ms?: number;
|
|
132
|
+
transcript_to_first_audio_ms?: number;
|
|
133
|
+
}
|
|
134
|
+
| { type: 'heartbeat'; timestamp?: number }
|
|
135
|
+
| { type: 'pong'; timestamp?: number };
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* @deprecated Prefer {@link ChatWsEvent} — the flat-shape interface
|
|
139
|
+
* here defeats exhaustiveness checking in switch statements. Kept for
|
|
140
|
+
* back-compat with existing handler signatures; new code should consume
|
|
141
|
+
* `ChatWsEvent` instead.
|
|
142
|
+
*/
|
|
41
143
|
export interface WebSocketMessage {
|
|
42
144
|
type:
|
|
43
145
|
| 'token'
|
|
@@ -70,6 +172,10 @@ export interface WebSocketMessage {
|
|
|
70
172
|
reason?: DoneReason;
|
|
71
173
|
mode?: 'hybrid' | 'sonic';
|
|
72
174
|
sessionId?: string;
|
|
175
|
+
/** Negotiated audio format on `{type: 'hello_ack'}` — 'pcm16' or
|
|
176
|
+
* 'mp3'. See `HelloAckMessage.audioFormat` in
|
|
177
|
+
* `shared/audio_protocol.py`. */
|
|
178
|
+
audioFormat?: string;
|
|
73
179
|
// Image regeneration fields
|
|
74
180
|
imageUrl?: string;
|
|
75
181
|
entity?: string;
|
|
@@ -101,12 +207,45 @@ export type BinaryHandler = (data: ArrayBuffer) => void;
|
|
|
101
207
|
|
|
102
208
|
export interface ChatWebSocketOptions {
|
|
103
209
|
url: string;
|
|
210
|
+
/**
|
|
211
|
+
* Static token baked into the URL at construction time. Reused on
|
|
212
|
+
* every reconnect attempt — fine for tokens that don't expire, but
|
|
213
|
+
* stale for ephemeral tokens (e.g. seer-agent's 10-min `ws-token`).
|
|
214
|
+
* Prefer {@link ChatWebSocketOptions.fetchToken} for ephemeral tokens.
|
|
215
|
+
*/
|
|
104
216
|
authToken?: string;
|
|
217
|
+
/**
|
|
218
|
+
* Async supplier invoked once per connect attempt (initial + every
|
|
219
|
+
* reconnect). Takes precedence over `authToken` when both are
|
|
220
|
+
* provided. Typical wiring:
|
|
221
|
+
*
|
|
222
|
+
* ```ts
|
|
223
|
+
* fetchToken: () => apiClient.getChatWsToken().then(r => r.wsToken),
|
|
224
|
+
* ```
|
|
225
|
+
*
|
|
226
|
+
* If this throws on a reconnect attempt, the failure counts against
|
|
227
|
+
* `maxReconnectAttempts` and the loop schedules another attempt with
|
|
228
|
+
* the existing backoff. On the initial connect the rejection
|
|
229
|
+
* propagates to the caller of `connect()`.
|
|
230
|
+
*/
|
|
231
|
+
fetchToken?: () => Promise<string>;
|
|
105
232
|
onOpen?: () => void;
|
|
106
233
|
onClose?: () => void;
|
|
107
234
|
onError?: (error: Event) => void;
|
|
108
235
|
onReconnecting?: (attempt: number) => void;
|
|
109
236
|
onReconnected?: () => void;
|
|
237
|
+
/**
|
|
238
|
+
* Called after a successful reconnect, immediately before
|
|
239
|
+
* `onReconnected`. If the caller returns a {@link HelloPayload}, it
|
|
240
|
+
* is serialized and sent so the server can restore voice/session
|
|
241
|
+
* state; returning `null` skips the send (e.g. text-only sessions
|
|
242
|
+
* that don't need a hello).
|
|
243
|
+
*
|
|
244
|
+
* Synchronous on purpose — the payload is built from in-memory
|
|
245
|
+
* state, and we want to send it on the same tick the socket opens
|
|
246
|
+
* to avoid racing other queued messages.
|
|
247
|
+
*/
|
|
248
|
+
onReconnect?: () => HelloPayload | null;
|
|
110
249
|
}
|
|
111
250
|
|
|
112
251
|
export class ChatWebSocket {
|
|
@@ -115,11 +254,13 @@ export class ChatWebSocket {
|
|
|
115
254
|
private binaryHandlers: BinaryHandler[] = [];
|
|
116
255
|
private url: string;
|
|
117
256
|
private authToken?: string;
|
|
257
|
+
private fetchToken?: () => Promise<string>;
|
|
118
258
|
private onOpenCallback?: () => void;
|
|
119
259
|
private onCloseCallback?: () => void;
|
|
120
260
|
private onErrorCallback?: (error: Event) => void;
|
|
121
261
|
private onReconnectingCallback?: (attempt: number) => void;
|
|
122
262
|
private onReconnectedCallback?: () => void;
|
|
263
|
+
private onReconnectCallback?: () => HelloPayload | null;
|
|
123
264
|
|
|
124
265
|
// Reconnection state
|
|
125
266
|
private maxReconnectAttempts = 5;
|
|
@@ -131,11 +272,13 @@ export class ChatWebSocket {
|
|
|
131
272
|
constructor(options: ChatWebSocketOptions) {
|
|
132
273
|
this.url = options.url;
|
|
133
274
|
this.authToken = options.authToken;
|
|
275
|
+
this.fetchToken = options.fetchToken;
|
|
134
276
|
this.onOpenCallback = options.onOpen;
|
|
135
277
|
this.onCloseCallback = options.onClose;
|
|
136
278
|
this.onErrorCallback = options.onError;
|
|
137
279
|
this.onReconnectingCallback = options.onReconnecting;
|
|
138
280
|
this.onReconnectedCallback = options.onReconnected;
|
|
281
|
+
this.onReconnectCallback = options.onReconnect;
|
|
139
282
|
}
|
|
140
283
|
|
|
141
284
|
/**
|
|
@@ -146,15 +289,43 @@ export class ChatWebSocket {
|
|
|
146
289
|
return this._connect(false);
|
|
147
290
|
}
|
|
148
291
|
|
|
292
|
+
/**
|
|
293
|
+
* Resolve the auth token for the next connect attempt. `fetchToken`
|
|
294
|
+
* wins over `authToken` when both are set — the supplier is the
|
|
295
|
+
* forward-looking path; `authToken` is back-compat.
|
|
296
|
+
*/
|
|
297
|
+
private async _resolveToken(): Promise<string | undefined> {
|
|
298
|
+
if (this.fetchToken) {
|
|
299
|
+
return await this.fetchToken();
|
|
300
|
+
}
|
|
301
|
+
return this.authToken;
|
|
302
|
+
}
|
|
303
|
+
|
|
149
304
|
/**
|
|
150
305
|
* Internal connect method. When isReconnect is true, calls
|
|
151
|
-
* onReconnected
|
|
306
|
+
* onReconnected (and dispatches any onReconnect hello payload)
|
|
307
|
+
* instead of onOpen on success.
|
|
152
308
|
*/
|
|
153
|
-
private _connect(isReconnect: boolean): Promise<void> {
|
|
309
|
+
private async _connect(isReconnect: boolean): Promise<void> {
|
|
310
|
+
let token: string | undefined;
|
|
311
|
+
try {
|
|
312
|
+
token = await this._resolveToken();
|
|
313
|
+
} catch (err) {
|
|
314
|
+
// Token fetch failed before any socket was opened, so onclose
|
|
315
|
+
// can't fire to drive the next reconnect attempt. On a reconnect
|
|
316
|
+
// pass we explicitly schedule another attempt so transient
|
|
317
|
+
// token-fetch failures (network blip, brief 502 on the token
|
|
318
|
+
// endpoint) don't kill the loop. On the initial connect we let
|
|
319
|
+
// the caller see the failure.
|
|
320
|
+
if (isReconnect && !this.intentionalDisconnect) {
|
|
321
|
+
this._attemptReconnect();
|
|
322
|
+
}
|
|
323
|
+
throw err;
|
|
324
|
+
}
|
|
325
|
+
|
|
154
326
|
return new Promise((resolve, reject) => {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
? `${this.url}?token=${encodeURIComponent(this.authToken)}`
|
|
327
|
+
const urlWithAuth = token
|
|
328
|
+
? `${this.url}?token=${encodeURIComponent(token)}`
|
|
158
329
|
: this.url;
|
|
159
330
|
|
|
160
331
|
this.ws = new WebSocket(urlWithAuth);
|
|
@@ -164,6 +335,14 @@ export class ChatWebSocket {
|
|
|
164
335
|
console.log('WebSocket connected');
|
|
165
336
|
this.reconnectAttempts = 0;
|
|
166
337
|
if (isReconnect) {
|
|
338
|
+
// Re-send hello BEFORE onReconnected so the caller observes
|
|
339
|
+
// a fully restored session, not a half-open one. Skip when
|
|
340
|
+
// the caller returns null (text-only sessions don't need a
|
|
341
|
+
// hello to resume).
|
|
342
|
+
const helloPayload = this.onReconnectCallback?.();
|
|
343
|
+
if (helloPayload && this.ws) {
|
|
344
|
+
this.ws.send(JSON.stringify(helloPayload));
|
|
345
|
+
}
|
|
167
346
|
this.onReconnectedCallback?.();
|
|
168
347
|
}
|
|
169
348
|
this.onOpenCallback?.();
|
|
@@ -370,17 +549,23 @@ export class ChatWebSocket {
|
|
|
370
549
|
}
|
|
371
550
|
|
|
372
551
|
/**
|
|
373
|
-
* Example usage:
|
|
552
|
+
* Example usage with an ephemeral token + voice-session restore:
|
|
374
553
|
*
|
|
375
554
|
* ```typescript
|
|
376
555
|
* const ws = new ChatWebSocket({
|
|
377
556
|
* url: 'ws://localhost:8080/api/chat/ws',
|
|
378
|
-
*
|
|
557
|
+
* fetchToken: () => apiClient.getChatWsToken().then((r) => r.wsToken),
|
|
558
|
+
* onReconnect: () => (voiceModeActive ? buildHelloPayload(...) : null),
|
|
379
559
|
* onOpen: () => console.log('Connected!'),
|
|
380
560
|
* onClose: () => console.log('Disconnected'),
|
|
381
561
|
* onError: (error) => console.error('Error:', error),
|
|
382
562
|
* });
|
|
383
563
|
*
|
|
564
|
+
* // Back-compat: static-token sessions still work without `fetchToken`.
|
|
565
|
+
* const wsLegacy = new ChatWebSocket({
|
|
566
|
+
* url: 'ws://localhost:8080/api/chat/ws',
|
|
567
|
+
* authToken: 'Bearer xyz123',
|
|
568
|
+
*
|
|
384
569
|
* await ws.connect();
|
|
385
570
|
*
|
|
386
571
|
* ws.onMessage((message) => {
|