@escapeaihq/client-core 0.4.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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -0
  3. package/dist/api.d.ts +836 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +781 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/audio.d.ts +278 -0
  8. package/dist/audio.d.ts.map +1 -0
  9. package/dist/audio.js +758 -0
  10. package/dist/audio.js.map +1 -0
  11. package/dist/audioProtocol.d.ts +101 -0
  12. package/dist/audioProtocol.d.ts.map +1 -0
  13. package/dist/audioProtocol.js +62 -0
  14. package/dist/audioProtocol.js.map +1 -0
  15. package/dist/index.d.ts +28 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +28 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/visemeGeometry.d.ts +198 -0
  20. package/dist/visemeGeometry.d.ts.map +1 -0
  21. package/dist/visemeGeometry.js +297 -0
  22. package/dist/visemeGeometry.js.map +1 -0
  23. package/dist/visemeScheduler.d.ts +28 -0
  24. package/dist/visemeScheduler.d.ts.map +1 -0
  25. package/dist/visemeScheduler.js +94 -0
  26. package/dist/visemeScheduler.js.map +1 -0
  27. package/dist/websocket.d.ts +196 -0
  28. package/dist/websocket.d.ts.map +1 -0
  29. package/dist/websocket.js +250 -0
  30. package/dist/websocket.js.map +1 -0
  31. package/package.json +40 -0
  32. package/src/__tests__/api-pollers.test.ts +524 -0
  33. package/src/__tests__/audio.test.ts +714 -0
  34. package/src/__tests__/visemeGeometry.test.ts +465 -0
  35. package/src/__tests__/visemeScheduler.test.ts +256 -0
  36. package/src/api.ts +1577 -0
  37. package/src/audio.ts +934 -0
  38. package/src/audioProtocol.ts +163 -0
  39. package/src/index.ts +28 -0
  40. package/src/visemeGeometry.ts +353 -0
  41. package/src/visemeScheduler.ts +133 -0
  42. package/src/websocket.ts +385 -0
@@ -0,0 +1,297 @@
1
+ /**
2
+ * Geometry helpers for viseme bundle rendering.
3
+ *
4
+ * Pure functions that derive clip / mask / inner-lip geometry from the
5
+ * existing `mouth_paths` data so the chat-ws UI doesn't need any new
6
+ * server-side fields. Kept side-effect-free so they can be unit tested
7
+ * without rendering a React tree.
8
+ */
9
+ /**
10
+ * Parse the (x, y) numeric pairs out of an SVG path `d` string.
11
+ *
12
+ * Our viseme paths are always M + 4×C with 13 explicit points (1 anchor +
13
+ * 4 segments × (2 controls + 1 endpoint)). Returning an array regardless
14
+ * of command structure keeps this useful for any of our paths — the bbox
15
+ * is conservative because it's the convex hull of *control points*, which
16
+ * always contains the rendered Bézier curve.
17
+ */
18
+ export function parsePathPoints(d) {
19
+ const numbers = d.match(/-?\d+(?:\.\d+)?/g) ?? [];
20
+ const points = [];
21
+ for (let i = 0; i + 1 < numbers.length; i += 2) {
22
+ points.push({ x: parseFloat(numbers[i]), y: parseFloat(numbers[i + 1]) });
23
+ }
24
+ return points;
25
+ }
26
+ export function pointsBBox(points) {
27
+ if (points.length === 0)
28
+ return null;
29
+ let minX = Infinity;
30
+ let maxX = -Infinity;
31
+ let minY = Infinity;
32
+ let maxY = -Infinity;
33
+ for (const p of points) {
34
+ if (p.x < minX)
35
+ minX = p.x;
36
+ if (p.x > maxX)
37
+ maxX = p.x;
38
+ if (p.y < minY)
39
+ minY = p.y;
40
+ if (p.y > maxY)
41
+ maxY = p.y;
42
+ }
43
+ return { minX, maxX, minY, maxY };
44
+ }
45
+ /**
46
+ * Union of all viseme paths' control-point bboxes.
47
+ *
48
+ * Returns null if the input is empty or no path produces any points
49
+ * (defensive — callers should fall back to the hand-authored geometry).
50
+ */
51
+ export function unionMouthPathsBBox(mouthPaths) {
52
+ let result = null;
53
+ for (const d of Object.values(mouthPaths)) {
54
+ const bb = pointsBBox(parsePathPoints(d));
55
+ if (!bb)
56
+ continue;
57
+ if (!result) {
58
+ result = { ...bb };
59
+ }
60
+ else {
61
+ result.minX = Math.min(result.minX, bb.minX);
62
+ result.maxX = Math.max(result.maxX, bb.maxX);
63
+ result.minY = Math.min(result.minY, bb.minY);
64
+ result.maxY = Math.max(result.maxY, bb.maxY);
65
+ }
66
+ }
67
+ return result;
68
+ }
69
+ /** Defaults for the mouth clip ellipse — exported so tuning UI sliders
70
+ * can label the slider middle and tests can verify edge cases without
71
+ * importing implementation magic numbers. */
72
+ export const DEFAULT_CLIP_MARGIN_X = 1.6;
73
+ export const DEFAULT_CLIP_MARGIN_Y = 1.8;
74
+ export const DEFAULT_FEATHER_FACTOR = 0.1;
75
+ /**
76
+ * Compute a feathered mouth-region clip ellipse from the union of all
77
+ * viseme outer-lip path bboxes.
78
+ *
79
+ * Default margin factors:
80
+ * - Horizontal: 1.6 (sqrt(2) ≈ 1.41 to inscribe corners + ~13% padding)
81
+ * - Vertical: 1.8 (more padding for `aei` / `o` which extend down)
82
+ *
83
+ * Feather: min(rx, ry) · 0.10 so the seam between body SVG and PNG is
84
+ * indiscernible. With normal alpha compositing the feather edge sums to
85
+ * 1.0 coverage at all points (PNG·α + body·(1-α) = 1).
86
+ *
87
+ * Optional overrides let the persona-tuner UI tweak these in real time.
88
+ */
89
+ export function computeMouthClipEllipse(mouthPaths, overrides) {
90
+ const bbox = unionMouthPathsBBox(mouthPaths);
91
+ if (!bbox)
92
+ return null;
93
+ const marginX = overrides?.marginX ?? DEFAULT_CLIP_MARGIN_X;
94
+ const marginY = overrides?.marginY ?? DEFAULT_CLIP_MARGIN_Y;
95
+ const featherFactor = overrides?.featherFactor ?? DEFAULT_FEATHER_FACTOR;
96
+ const cx = (bbox.minX + bbox.maxX) / 2;
97
+ const cy = (bbox.minY + bbox.maxY) / 2;
98
+ const halfWidth = (bbox.maxX - bbox.minX) / 2;
99
+ const halfHeight = (bbox.maxY - bbox.minY) / 2;
100
+ const rx = halfWidth * marginX;
101
+ const ry = halfHeight * marginY;
102
+ const featherStdDev = Math.max(1, Math.min(rx, ry) * featherFactor);
103
+ return { cx, cy, rx, ry, featherStdDev };
104
+ }
105
+ /**
106
+ * Lip thickness as a fraction of the outer mouth height. The inner lip
107
+ * ring is shrunk vertically by this much from each side, so the inner
108
+ * ring is `(1 - 2·LIP_THICKNESS_FRACTION)` of the outer height. With
109
+ * the current value (0.25) the inner ring is exactly half the outer
110
+ * ring's height.
111
+ */
112
+ export const LIP_THICKNESS_FRACTION = 0.25;
113
+ const TWO_DECIMALS = (n) => n.toFixed(2);
114
+ const formatPoint = (p) => `${TWO_DECIMALS(p.x)},${TWO_DECIMALS(p.y)}`;
115
+ /**
116
+ * Derive an inner-lip path from the outer-lip path that morphs
117
+ * synchronously with it (same M+4C topology, 13 points).
118
+ *
119
+ * The outer path's anchors are: Left (M start), Up (end of C1), Right
120
+ * (end of C2), Lo (end of C3), back to Left (end of C4). Mouth corners
121
+ * (Left, Right) are physical pinch points and don't move when the lip
122
+ * thickens or thins. Up/Lo midpoints DO move — they shift toward the
123
+ * vertical centroid by `LIP_THICKNESS_FRACTION · h` each, so the inner
124
+ * ring height is `h · (1 - 2·LIP_THICKNESS_FRACTION)`.
125
+ *
126
+ * Bezier control points are shifted vertically by linear interp along
127
+ * each segment so the inner curve preserves the bulge shape of the
128
+ * outer curve (rather than collapsing to straight diamond edges).
129
+ *
130
+ * Properties:
131
+ * - Topology unchanged (M + 4C → 13 points → 26 numbers). Required for
132
+ * WAAPI d-string interpolation between visemes.
133
+ * - At rest (h ≈ 1-3 px), inner ring is a thin sliver — visually a
134
+ * hairline shadow between lips. Anatomically correct.
135
+ * - At fully open (h ≈ 100 px for `aei`), inner ring opens to expose
136
+ * the inner-mouth backdrop + teeth + tongue.
137
+ *
138
+ * Defensive falls back to returning the outer path unchanged if the
139
+ * input doesn't have the expected 13-point topology or the height is
140
+ * non-positive (degenerate path).
141
+ */
142
+ export function deriveInnerLipPath(outerD, overrides) {
143
+ const points = parsePathPoints(outerD);
144
+ if (points.length !== 13)
145
+ return outerD;
146
+ const Left = points[0];
147
+ const Up = points[3];
148
+ const Right = points[6];
149
+ const Lo = points[9];
150
+ const h = Lo.y - Up.y;
151
+ if (h <= 0)
152
+ return outerD;
153
+ const fraction = overrides?.lipThicknessFraction ?? LIP_THICKNESS_FRACTION;
154
+ const shift = h * fraction;
155
+ // Inner anchors — corners stay, midpoints shift toward centroid.
156
+ const innerUp = { x: Up.x, y: Up.y + shift };
157
+ const innerLo = { x: Lo.x, y: Lo.y - shift };
158
+ // Bezier control shift: linear interp along each segment so the
159
+ // bulge shape is preserved relative to the (now-shorter) baseline.
160
+ // For a control at parametric position t along the segment, vertical
161
+ // shift = anchor_shift · (t at end-anchor side, 1-t at start side).
162
+ const c1_1 = { x: points[1].x, y: points[1].y + shift * (1 / 3) };
163
+ const c1_2 = { x: points[2].x, y: points[2].y + shift * (2 / 3) };
164
+ const c2_1 = { x: points[4].x, y: points[4].y + shift * (2 / 3) };
165
+ const c2_2 = { x: points[5].x, y: points[5].y + shift * (1 / 3) };
166
+ const c3_1 = { x: points[7].x, y: points[7].y - shift * (1 / 3) };
167
+ const c3_2 = { x: points[8].x, y: points[8].y - shift * (2 / 3) };
168
+ const c4_1 = { x: points[10].x, y: points[10].y - shift * (2 / 3) };
169
+ const c4_2 = { x: points[11].x, y: points[11].y - shift * (1 / 3) };
170
+ return (`M ${formatPoint(Left)} ` +
171
+ `C ${formatPoint(c1_1)} ${formatPoint(c1_2)} ${formatPoint(innerUp)} ` +
172
+ `C ${formatPoint(c2_1)} ${formatPoint(c2_2)} ${formatPoint(Right)} ` +
173
+ `C ${formatPoint(c3_1)} ${formatPoint(c3_2)} ${formatPoint(innerLo)} ` +
174
+ `C ${formatPoint(c4_1)} ${formatPoint(c4_2)} ${formatPoint(Left)}`);
175
+ }
176
+ /**
177
+ * Combine outer + inner lip paths into a donut path renderable with
178
+ * `fill-rule="evenodd"`. A point inside an odd number of subpaths is
179
+ * filled — so inside outer + outside inner = filled (lip flesh);
180
+ * inside both = unfilled (mouth opening).
181
+ *
182
+ * The combined string preserves both subpath topologies — for two
183
+ * M+4C paths that's 2M + 8C = 26 points = 52 numbers, identical
184
+ * across all visemes. WAAPI interpolates linearly.
185
+ */
186
+ export function combineDonutPath(outerD, innerD) {
187
+ return `${outerD} ${innerD}`;
188
+ }
189
+ /**
190
+ * Compute static teeth + tongue positions sized to fit inside the
191
+ * largest mouth opening across all visemes (the union bbox).
192
+ *
193
+ * These shapes are clipped at render time to the morphing inner lip
194
+ * ring. When the mouth is closed (inner ring degenerate), the clip
195
+ * reveals nothing. When open (`aei`/`o`), the clip exposes upper
196
+ * teeth → tongue → lower teeth from top to bottom.
197
+ *
198
+ * Layout proportions of the union bbox half-extents (hw, hh):
199
+ * - upper teeth: rectangle covering top 30% of the inner area
200
+ * (y range [cy-0.5hh, cy-0.2hh]), 70% of the width on each side
201
+ * - lower teeth: same width, bottom 30% (y [cy+0.2hh, cy+0.5hh])
202
+ * - tongue: ellipse centered slightly below center, 60% horizontal
203
+ * radius, 20% vertical radius
204
+ */
205
+ export function computeTeethTongueGeom(mouthPaths) {
206
+ const bbox = unionMouthPathsBBox(mouthPaths);
207
+ if (!bbox)
208
+ return null;
209
+ const cx = (bbox.minX + bbox.maxX) / 2;
210
+ const cy = (bbox.minY + bbox.maxY) / 2;
211
+ const hw = (bbox.maxX - bbox.minX) / 2;
212
+ const hh = (bbox.maxY - bbox.minY) / 2;
213
+ const teethWidth = hw * 1.4;
214
+ return {
215
+ upperTeeth: {
216
+ x: cx - hw * 0.7,
217
+ y: cy - hh * 0.5,
218
+ width: teethWidth,
219
+ height: hh * 0.3,
220
+ },
221
+ lowerTeeth: {
222
+ x: cx - hw * 0.7,
223
+ y: cy + hh * 0.2,
224
+ width: teethWidth,
225
+ height: hh * 0.3,
226
+ },
227
+ tongue: {
228
+ cx,
229
+ cy: cy + hh * 0.1,
230
+ rx: hw * 0.6,
231
+ ry: hh * 0.2,
232
+ },
233
+ };
234
+ }
235
+ /**
236
+ * Default inner-mouth color palette. Hardcoded for now to avoid a
237
+ * round-trip through bundle regeneration; can be replaced with sampled
238
+ * colors once we add a backend extraction step.
239
+ */
240
+ export const INNER_MOUTH_COLORS = {
241
+ interior: '#3d1a14', // dark reddish brown
242
+ teeth: '#f4ecd6', // off-white, slightly yellow
243
+ tongue: '#a44d52', // muted pink
244
+ };
245
+ /**
246
+ * Per-viseme "openness" — outer mouth height (Lo.y - Up.y) min/max
247
+ * normalized across all visemes in this bundle.
248
+ *
249
+ * The result is in [0, 1] where 0 means the most closed-mouth viseme
250
+ * (typically `bmp` or `rest`) and 1 means the most open (typically
251
+ * `aei`). Returns null for malformed inputs.
252
+ *
253
+ * Used to drive teeth/tongue visibility: closed visemes show no teeth
254
+ * even though the inner-lip-ring clip would technically reveal a thin
255
+ * sliver of them.
256
+ */
257
+ export function computeVisemeOpenness(mouthPaths) {
258
+ const heights = {};
259
+ for (const [v, d] of Object.entries(mouthPaths)) {
260
+ const points = parsePathPoints(d);
261
+ if (points.length !== 13)
262
+ continue;
263
+ const h = points[9].y - points[3].y;
264
+ if (h > 0)
265
+ heights[v] = h;
266
+ }
267
+ const values = Object.values(heights);
268
+ if (values.length === 0)
269
+ return null;
270
+ const minH = Math.min(...values);
271
+ const maxH = Math.max(...values);
272
+ const range = maxH - minH;
273
+ const result = {};
274
+ for (const [v, h] of Object.entries(heights)) {
275
+ result[v] = range > 0 ? (h - minH) / range : 0;
276
+ }
277
+ return result;
278
+ }
279
+ /**
280
+ * Map a per-viseme openness in [0, 1] to a teeth/tongue opacity in
281
+ * [0, 1] via a soft floor.
282
+ *
283
+ * Below `OPENNESS_FLOOR` (15% of the range), opacity is 0 — the closed
284
+ * visemes (`bmp`, `rest`, often `cdgknstxyz`) cleanly hide the teeth
285
+ * even though the morphing inner-lip clip alone would let a sliver
286
+ * through. Above the floor, opacity ramps linearly to 1 at full
287
+ * openness, with a steeper-than-linear slope so wide-open visemes
288
+ * (`aei`, `th`, `qw`) saturate visibly.
289
+ */
290
+ export const OPENNESS_FLOOR = 0.15;
291
+ export const OPENNESS_SLOPE = 1.5;
292
+ export function teethOpacityFromOpenness(openness, overrides) {
293
+ const floor = overrides?.floor ?? OPENNESS_FLOOR;
294
+ const slope = overrides?.slope ?? OPENNESS_SLOPE;
295
+ return Math.max(0, Math.min(1, (openness - floor) * slope));
296
+ }
297
+ //# sourceMappingURL=visemeGeometry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"visemeGeometry.js","sourceRoot":"","sources":["../src/visemeGeometry.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAOH;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAAC,CAAS;IACvC,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,kBAAkB,CAAC,IAAI,EAAE,CAAC;IAClD,MAAM,MAAM,GAAY,EAAE,CAAC;IAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QAC/C,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,UAAU,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC5E,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAUD,MAAM,UAAU,UAAU,CAAC,MAAe;IACxC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACrC,IAAI,IAAI,GAAG,QAAQ,CAAC;IACpB,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC;IACrB,IAAI,IAAI,GAAG,QAAQ,CAAC;IACpB,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC;IACrB,KAAK,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;QACvB,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI;YAAE,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC;QAC3B,IAAI,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9C,MAAM,KAAK,GAAG,SAAS,EAAE,KAAK,IAAI,cAAc,CAAC;IACjD,MAAM,KAAK,GAAG,SAAS,EAAE,KAAK,IAAI,cAAc,CAAC;IACjD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,QAAQ,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC;AAC9D,CAAC"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * VisemeScheduler — drives lip-sync animation from Inworld TTS 1.5 phoneme data.
3
+ *
4
+ * Receives phoneme timing from audio_metadata WebSocket messages and maps them
5
+ * to AudioContext.currentTime so mouth shapes stay in lockstep with audio output.
6
+ */
7
+ import type { WordPhonemeInfo } from './audioProtocol';
8
+ export type VisemeSymbol = 'rest' | 'aei' | 'o' | 'ee' | 'bmp' | 'fv' | 'l' | 'r' | 'th' | 'qw' | 'cdgknstxyz';
9
+ export declare class VisemeScheduler {
10
+ private queue;
11
+ private currentViseme;
12
+ private animationFrameId;
13
+ private onVisemeChange;
14
+ private audioContext;
15
+ constructor(audioContext: AudioContext, onVisemeChange: (viseme: string) => void);
16
+ /**
17
+ * Schedule visemes from an audio_metadata message.
18
+ * @param phonemes - WordPhonemeInfo[] from the audio_metadata message
19
+ * @param chunkAudioStartTime - AudioContext.currentTime when this chunk starts playing
20
+ */
21
+ scheduleChunk(phonemes: WordPhonemeInfo[], chunkAudioStartTime: number): void;
22
+ private tick;
23
+ /** Call on barge-in or when audio stops. */
24
+ clear(): void;
25
+ getCurrentViseme(): string;
26
+ destroy(): void;
27
+ }
28
+ //# sourceMappingURL=visemeScheduler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"visemeScheduler.d.ts","sourceRoot":"","sources":["../src/visemeScheduler.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEvD,MAAM,MAAM,YAAY,GACpB,MAAM,GACN,KAAK,GACL,GAAG,GACH,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,GAAG,GACH,GAAG,GACH,IAAI,GACJ,IAAI,GACJ,YAAY,CAAC;AAsBjB,qBAAa,eAAe;IAC1B,OAAO,CAAC,KAAK,CAAyB;IAEtC,OAAO,CAAC,aAAa,CAAU;IAE/B,OAAO,CAAC,gBAAgB,CAAuB;IAE/C,OAAO,CAAC,cAAc,CAA2B;IAEjD,OAAO,CAAC,YAAY,CAAe;gBAEvB,YAAY,EAAE,YAAY,EAAE,cAAc,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI;IAKhF;;;;OAIG;IACH,aAAa,CAAC,QAAQ,EAAE,eAAe,EAAE,EAAE,mBAAmB,EAAE,MAAM,GAAG,IAAI;IAkB7E,OAAO,CAAC,IAAI,CA6BV;IAEF,4CAA4C;IAC5C,KAAK,IAAI,IAAI;IAYb,gBAAgB,IAAI,MAAM;IAI1B,OAAO,IAAI,IAAI;CAGhB"}
@@ -0,0 +1,94 @@
1
+ /**
2
+ * VisemeScheduler — drives lip-sync animation from Inworld TTS 1.5 phoneme data.
3
+ *
4
+ * Receives phoneme timing from audio_metadata WebSocket messages and maps them
5
+ * to AudioContext.currentTime so mouth shapes stay in lockstep with audio output.
6
+ */
7
+ const VALID_VISEMES = new Set([
8
+ 'rest',
9
+ 'aei',
10
+ 'o',
11
+ 'ee',
12
+ 'bmp',
13
+ 'fv',
14
+ 'l',
15
+ 'r',
16
+ 'th',
17
+ 'qw',
18
+ 'cdgknstxyz',
19
+ ]);
20
+ export class VisemeScheduler {
21
+ queue = [];
22
+ currentViseme = 'rest';
23
+ animationFrameId = null;
24
+ onVisemeChange;
25
+ audioContext;
26
+ constructor(audioContext, onVisemeChange) {
27
+ this.audioContext = audioContext;
28
+ this.onVisemeChange = onVisemeChange;
29
+ }
30
+ /**
31
+ * Schedule visemes from an audio_metadata message.
32
+ * @param phonemes - WordPhonemeInfo[] from the audio_metadata message
33
+ * @param chunkAudioStartTime - AudioContext.currentTime when this chunk starts playing
34
+ */
35
+ scheduleChunk(phonemes, chunkAudioStartTime) {
36
+ for (const word of phonemes) {
37
+ for (const phone of word.phones) {
38
+ const symbol = VALID_VISEMES.has(phone.visemeSymbol) ? phone.visemeSymbol : 'rest';
39
+ this.queue.push({
40
+ startTime: chunkAudioStartTime + phone.startTime,
41
+ endTime: chunkAudioStartTime + phone.startTime + phone.duration,
42
+ visemeSymbol: symbol,
43
+ });
44
+ }
45
+ }
46
+ this.queue.sort((a, b) => a.startTime - b.startTime);
47
+ if (this.animationFrameId === null) {
48
+ this.tick();
49
+ }
50
+ }
51
+ tick = () => {
52
+ const now = this.audioContext.currentTime;
53
+ // Discard expired visemes from the front of the sorted queue
54
+ while (this.queue.length > 0 && this.queue[0].endTime <= now) {
55
+ this.queue.shift();
56
+ }
57
+ // The first remaining item whose startTime <= now is the active viseme
58
+ const active = this.queue.length > 0 && this.queue[0].startTime <= now ? this.queue[0] : undefined;
59
+ const newViseme = active?.visemeSymbol ?? 'rest';
60
+ if (newViseme !== this.currentViseme) {
61
+ this.currentViseme = newViseme;
62
+ this.onVisemeChange(newViseme);
63
+ }
64
+ // Stop the loop when idle to avoid CPU/battery leak. Safe to bail
65
+ // here because `scheduleChunk` re-arms requestAnimationFrame whenever
66
+ // `animationFrameId === null`. Removing that null-guard in
67
+ // `scheduleChunk` would make this idle-stop silently strand any
68
+ // newly-enqueued phonemes.
69
+ if (this.queue.length === 0 && this.currentViseme === 'rest') {
70
+ this.animationFrameId = null;
71
+ return;
72
+ }
73
+ this.animationFrameId = requestAnimationFrame(this.tick);
74
+ };
75
+ /** Call on barge-in or when audio stops. */
76
+ clear() {
77
+ this.queue = [];
78
+ if (this.currentViseme !== 'rest') {
79
+ this.currentViseme = 'rest';
80
+ this.onVisemeChange('rest');
81
+ }
82
+ if (this.animationFrameId !== null) {
83
+ cancelAnimationFrame(this.animationFrameId);
84
+ this.animationFrameId = null;
85
+ }
86
+ }
87
+ getCurrentViseme() {
88
+ return this.currentViseme;
89
+ }
90
+ destroy() {
91
+ this.clear();
92
+ }
93
+ }
94
+ //# sourceMappingURL=visemeScheduler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"visemeScheduler.js","sourceRoot":"","sources":["../src/visemeScheduler.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAiBH,MAAM,aAAa,GAAwB,IAAI,GAAG,CAAS;IACzD,MAAM;IACN,KAAK;IACL,GAAG;IACH,IAAI;IACJ,KAAK;IACL,IAAI;IACJ,GAAG;IACH,GAAG;IACH,IAAI;IACJ,IAAI;IACJ,YAAY;CACb,CAAC,CAAC;AAQH,MAAM,OAAO,eAAe;IAClB,KAAK,GAAsB,EAAE,CAAC;IAE9B,aAAa,GAAG,MAAM,CAAC;IAEvB,gBAAgB,GAAkB,IAAI,CAAC;IAEvC,cAAc,CAA2B;IAEzC,YAAY,CAAe;IAEnC,YAAY,YAA0B,EAAE,cAAwC;QAC9E,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;IAED;;;;OAIG;IACH,aAAa,CAAC,QAA2B,EAAE,mBAA2B;QACpE,KAAK,MAAM,IAAI,IAAI,QAAQ,EAAE,CAAC;YAC5B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAChC,MAAM,MAAM,GAAG,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC;gBACnF,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;oBACd,SAAS,EAAE,mBAAmB,GAAG,KAAK,CAAC,SAAS;oBAChD,OAAO,EAAE,mBAAmB,GAAG,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,QAAQ;oBAC/D,YAAY,EAAE,MAAM;iBACrB,CAAC,CAAC;YACL,CA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AC;YAC7B,OAAO;QACT,CAAC;QAED,IAAI,CAAC,gBAAgB,GAAG,qBAAqB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3D,CAAC,CAAC;IAEF,4CAA4C;IAC5C,KAAK;QACH,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;QAChB,IAAI,IAAI,CAAC,aAAa,KAAK,MAAM,EAAE,CAAC;YAClC,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC;YAC5B,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;QAC9B,CAAC;QACD,IAAI,IAAI,CAAC,gBAAgB,KAAK,IAAI,EAAE,CAAC;YACnC,oBAAoB,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;YAC5C,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAC/B,CAAC;IACH,CAAC;IAED,gBAAgB;QACd,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED,OAAO;QACL,IAAI,CAAC,KAAK,EAAE,CAAC;IACf,CAAC;CACF"}
@@ -0,0 +1,196 @@
1
+ /**
2
+ * WebSocket client for real-time chat
3
+ *
4
+ * Provides a wrapper around the native WebSocket API with:
5
+ * - Automatic reconnection
6
+ * - Message queueing during connection
7
+ * - Event-based message handling
8
+ * - Auth token forwarding
9
+ */
10
+ import type { HelloPayload } from './audio';
11
+ import type { WordPhonemeInfo } from './audioProtocol';
12
+ export interface Citation {
13
+ videoId: string;
14
+ t0: number;
15
+ t1: number;
16
+ shotId?: string;
17
+ }
18
+ export interface ToolResult {
19
+ results: Array<{
20
+ text?: string;
21
+ content?: string;
22
+ }>;
23
+ citations: Citation[];
24
+ }
25
+ export interface WebSocketMessage {
26
+ type: 'token' | 'tool_use' | 'tool_result' | 'citation' | 'image' | 'error' | 'done' | 'heartbeat' | 'pong' | 'hello_ack' | 'transcript' | 'audio_metadata' | 'barge_in_ack' | 'audio_chunk' | 'metrics';
27
+ timestamp?: number;
28
+ content?: string;
29
+ tool?: string;
30
+ toolUseId?: string;
31
+ result?: ToolResult;
32
+ citation?: Citation;
33
+ span?: string;
34
+ message?: string;
35
+ final?: boolean;
36
+ text?: string;
37
+ resultId?: string;
38
+ mode?: 'hybrid' | 'sonic';
39
+ sessionId?: string;
40
+ imageUrl?: string;
41
+ entity?: string;
42
+ prompt?: string;
43
+ sourceTimestamp?: number;
44
+ chunkId?: string;
45
+ wordTimestamps?: Array<{
46
+ word: string;
47
+ startTime: number;
48
+ endTime: number;
49
+ }>;
50
+ phonemes?: WordPhonemeInfo[];
51
+ processedChars?: number;
52
+ isFinal?: boolean;
53
+ cumulativeTime?: number;
54
+ spokenText?: string;
55
+ cancelledText?: string;
56
+ interruptionTime?: number;
57
+ wordsSpoken?: string[];
58
+ audio?: string;
59
+ format?: 'mp3' | 'pcm16' | 'ogg_opus';
60
+ llm_first_token_ms?: number;
61
+ tts_first_chunk_ms?: number;
62
+ transcript_to_first_audio_ms?: number;
63
+ }
64
+ export type MessageHandler = (message: WebSocketMessage) => void;
65
+ export type BinaryHandler = (data: ArrayBuffer) => void;
66
+ export interface ChatWebSocketOptions {
67
+ url: string;
68
+ authToken?: string;
69
+ onOpen?: () => void;
70
+ onClose?: () => void;
71
+ onError?: (error: Event) => void;
72
+ onReconnecting?: (attempt: number) => void;
73
+ onReconnected?: () => void;
74
+ }
75
+ export declare class ChatWebSocket {
76
+ private ws;
77
+ private messageHandlers;
78
+ private binaryHandlers;
79
+ private url;
80
+ private authToken?;
81
+ private onOpenCallback?;
82
+ private onCloseCallback?;
83
+ private onErrorCallback?;
84
+ private onReconnectingCallback?;
85
+ private onReconnectedCallback?;
86
+ private maxReconnectAttempts;
87
+ private reconnectDelay;
88
+ private reconnectAttempts;
89
+ private intentionalDisconnect;
90
+ private reconnectTimer;
91
+ constructor(options: ChatWebSocketOptions);
92
+ /**
93
+ * Connect to the WebSocket server
94
+ */
95
+ connect(): Promise<void>;
96
+ /**
97
+ * Internal connect method. When isReconnect is true, calls
98
+ * onReconnected instead of onOpen on success.
99
+ */
100
+ private _connect;
101
+ /**
102
+ * Attempt to reconnect with exponential backoff.
103
+ */
104
+ private _attemptReconnect;
105
+ /**
106
+ * Send a chat message
107
+ */
108
+ send(prompt: string, options?: {
109
+ videoId?: string;
110
+ modelId?: string;
111
+ messages?: Array<{
112
+ role: string;
113
+ content: string;
114
+ modelId?: string;
115
+ }>;
116
+ systemPrompt?: string;
117
+ systemPromptOverride?: boolean;
118
+ heartbeatInterval?: number;
119
+ idleTimeout?: number;
120
+ }): void;
121
+ /**
122
+ * Send an audio hello handshake for hybrid audio/text sessions.
123
+ * Serializes the payload as-is — all defaults are applied by buildHelloPayload().
124
+ */
125
+ sendHello(payload: HelloPayload): void;
126
+ /**
127
+ * Send a binary microphone frame (tagged with TAG_MIC)
128
+ */
129
+ sendAudioFrame(frame: ArrayBuffer | Uint8Array): void;
130
+ /**
131
+ * Send a ping keepalive
132
+ */
133
+ ping(): void;
134
+ /**
135
+ * Get the raw WebSocket instance for advanced operations (e.g., barge-in)
136
+ */
137
+ getRawSocket(): WebSocket | null;
138
+ /**
139
+ * Register a message handler
140
+ */
141
+ onMessage(handler: MessageHandler): void;
142
+ /**
143
+ * Register a binary message handler
144
+ */
145
+ onBinary(handler: BinaryHandler): void;
146
+ /**
147
+ * Remove a message handler
148
+ */
149
+ offMessage(handler: MessageHandler): void;
150
+ /**
151
+ * Remove a binary handler
152
+ */
153
+ offBinary(handler: BinaryHandler): void;
154
+ /**
155
+ * Disconnect from the WebSocket server.
156
+ * Marks the close as intentional so no reconnection is attempted.
157
+ */
158
+ disconnect(): void;
159
+ /**
160
+ * Get the current connection state
161
+ */
162
+ get readyState(): number;
163
+ /**
164
+ * Check if the WebSocket is connected
165
+ */
166
+ get isConnected(): boolean;
167
+ }
168
+ /**
169
+ * Example usage:
170
+ *
171
+ * ```typescript
172
+ * const ws = new ChatWebSocket({
173
+ * url: 'ws://localhost:8080/api/chat/ws',
174
+ * authToken: 'Bearer xyz123',
175
+ * onOpen: () => console.log('Connected!'),
176
+ * onClose: () => console.log('Disconnected'),
177
+ * onError: (error) => console.error('Error:', error),
178
+ * });
179
+ *
180
+ * await ws.connect();
181
+ *
182
+ * ws.onMessage((message) => {
183
+ * if (message.type === 'token') {
184
+ * console.log('Token:', message.content);
185
+ * } else if (message.type === 'done') {
186
+ * console.log('Chat complete');
187
+ * }
188
+ * });
189
+ *
190
+ * ws.send('What happens in the opening scene?', {
191
+ * videoId: 'video-001',
192
+ * modelId: 'amazon.nova-pro-v1:0',
193
+ * });
194
+ * ```
195
+ */
196
+ //# sourceMappingURL=websocket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../src/websocket.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEvD,MAAM,WAAW,QAAQ;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,KAAK,CAAC;QACb,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC,CAAC;IACH,SAAS,EAAE,QAAQ,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EACA,OAAO,GACP,UAAU,GACV,aAAa,GACb,UAAU,GACV,OAAO,GACP,OAAO,GACP,MAAM,GACN,WAAW,GACX,MAAM,GACN,WAAW,GACX,YAAY,GACZ,gBAAgB,GAChB,cAAc,GACd,aAAa,GACb,SAAS,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,C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