@m4trix/core 0.5.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,2670 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+ var socket_ioClient = require('socket.io-client');
5
+ var lit = require('lit');
6
+ var decorators_js = require('lit/decorators.js');
7
+ var ref_js = require('lit/directives/ref.js');
8
+ var animejs = require('animejs');
9
+ var messages = require('@langchain/core/messages');
10
+ var effect = require('effect');
11
+
12
+ var __defProp = Object.defineProperty;
13
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
+ var __decorateClass = (decorators, target, key, kind) => {
15
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
16
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
17
+ if (decorator = decorators[i])
18
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
19
+ if (kind && result)
20
+ __defProp(target, key, result);
21
+ return result;
22
+ };
23
+
24
+ // src/utility/Logger.ts
25
+ var _Logger = class _Logger {
26
+ constructor(namespace = "") {
27
+ this.namespace = namespace;
28
+ }
29
+ static enableGlobalLogging() {
30
+ _Logger.globalEnabled = true;
31
+ }
32
+ static disableGlobalLogging() {
33
+ _Logger.globalEnabled = false;
34
+ }
35
+ formatPrefix() {
36
+ return this.namespace ? `[${this.namespace}]` : "";
37
+ }
38
+ logIfEnabled(level, ...args) {
39
+ if (!_Logger.globalEnabled)
40
+ return;
41
+ const prefix = this.formatPrefix();
42
+ if (prefix) {
43
+ console[level](prefix, ...args);
44
+ } else {
45
+ console[level](...args);
46
+ }
47
+ }
48
+ log(...args) {
49
+ this.logIfEnabled("log", ...args);
50
+ }
51
+ debug(...args) {
52
+ this.logIfEnabled("debug", ...args);
53
+ }
54
+ info(...args) {
55
+ this.logIfEnabled("info", ...args);
56
+ }
57
+ warn(...args) {
58
+ this.logIfEnabled("warn", ...args);
59
+ }
60
+ error(...args) {
61
+ this.logIfEnabled("error", ...args);
62
+ }
63
+ };
64
+ _Logger.globalEnabled = false;
65
+ var Logger = _Logger;
66
+
67
+ // src/react/adapter/VoiceEndpointAdapter.ts
68
+ var VoiceEndpointAdapter = class {
69
+ constructor(config) {
70
+ this.logger = new Logger("SuTr > EndpointAdapter");
71
+ this.config = config;
72
+ }
73
+ };
74
+ var BaseVoiceEndpointAdapter = class extends VoiceEndpointAdapter {
75
+ constructor(config) {
76
+ super(config);
77
+ }
78
+ /**
79
+ * Send a voice file to the API endpoint and return a Pump stream of audio chunks
80
+ */
81
+ async sendVoiceFile({
82
+ blob,
83
+ metadata
84
+ }) {
85
+ const formData = new FormData();
86
+ formData.append("audio", blob);
87
+ if (metadata) {
88
+ formData.append("metadata", JSON.stringify(metadata));
89
+ }
90
+ this.logger.debug("Sending voice file to", this.config.endpoint, formData);
91
+ const response = await fetch(
92
+ `${this.config.baseUrl || ""}${this.config.endpoint}`,
93
+ {
94
+ method: "POST",
95
+ headers: this.config.headers,
96
+ body: formData
97
+ }
98
+ );
99
+ if (!response.ok) {
100
+ throw new Error(`API error: ${response.status} ${await response.text()}`);
101
+ }
102
+ if (!response.body) {
103
+ throw new Error("No response body");
104
+ }
105
+ return response;
106
+ }
107
+ };
108
+
109
+ // src/react/utility/audio/InputAudioController.ts
110
+ var InputAudioController = class {
111
+ constructor() {
112
+ this.logger = new Logger("@m4trix/core > InputAudioController");
113
+ }
114
+ };
115
+
116
+ // src/react/utility/audio/WebAudioInputAudioController.ts
117
+ var DEFAULT_SLICING_INTERVAL = 3e3;
118
+ var WebAudioInputAudioController = class extends InputAudioController {
119
+ constructor(audioConfig = {}) {
120
+ super();
121
+ this.audioConfig = audioConfig;
122
+ // ─── Recording state ─────────────────────────────────────────────────────
123
+ this.audioContextState = {
124
+ context: null,
125
+ source: null,
126
+ analyser: null
127
+ };
128
+ this.mediaRecorder = null;
129
+ this.recordedChunks = [];
130
+ this.recordingStream = null;
131
+ }
132
+ get audioContext() {
133
+ return this.audioContextState.context;
134
+ }
135
+ async createAudioContext() {
136
+ const context = new AudioContext({
137
+ sampleRate: this.audioConfig.sampleRate || 16e3,
138
+ latencyHint: "interactive"
139
+ });
140
+ const analyser = context.createAnalyser();
141
+ analyser.fftSize = 2048;
142
+ return { context, source: null, analyser };
143
+ }
144
+ async cleanupAudioContext() {
145
+ this.logger.debug("Cleaning up audio context");
146
+ const { source, context } = this.audioContextState;
147
+ if (source)
148
+ source.disconnect();
149
+ if (context)
150
+ await context.close();
151
+ this.audioContextState = { context: null, source: null, analyser: null };
152
+ }
153
+ async startRecording({
154
+ onRecordedChunk,
155
+ onError
156
+ } = {}) {
157
+ try {
158
+ this.logger.debug("Starting recording");
159
+ this.recordedChunks = [];
160
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
161
+ this.recordingStream = stream;
162
+ if (!this.audioContextState.context) {
163
+ this.audioContextState = await this.createAudioContext();
164
+ }
165
+ this.mediaRecorder = new MediaRecorder(stream, {
166
+ mimeType: "audio/webm;codecs=opus"
167
+ });
168
+ this.mediaRecorder.ondataavailable = (e) => {
169
+ if (e.data.size > 0) {
170
+ this.recordedChunks.push(e.data);
171
+ onRecordedChunk?.(e.data);
172
+ this.logger.debug("Recorded chunk", e.data.size);
173
+ }
174
+ };
175
+ this.mediaRecorder.start(DEFAULT_SLICING_INTERVAL);
176
+ this.logger.debug("MediaRecorder started");
177
+ } catch (err) {
178
+ const error = err instanceof Error ? err : new Error("Failed to start recording");
179
+ this.logger.error(error);
180
+ onError?.(error);
181
+ }
182
+ }
183
+ async stopRecording({
184
+ onRecordingCompleted
185
+ } = {}) {
186
+ this.logger.debug("Stopping recording");
187
+ if (!this.mediaRecorder || this.mediaRecorder.state === "inactive")
188
+ return;
189
+ await new Promise((resolve) => {
190
+ this.mediaRecorder.onstop = async () => {
191
+ if (this.recordedChunks.length) {
192
+ const blob = new Blob(this.recordedChunks, { type: "audio/webm" });
193
+ onRecordingCompleted?.(blob);
194
+ this.logger.debug("Recording completed", blob.size);
195
+ }
196
+ this.recordingStream?.getTracks().forEach((t) => t.stop());
197
+ this.recordingStream = null;
198
+ await this.cleanupAudioContext();
199
+ resolve();
200
+ };
201
+ this.mediaRecorder.stop();
202
+ });
203
+ }
204
+ /**
205
+ * Cleans up all audio recording resources.
206
+ */
207
+ cleanup() {
208
+ this.cleanupAudioContext();
209
+ if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
210
+ this.mediaRecorder.stop();
211
+ }
212
+ if (this.recordingStream) {
213
+ this.recordingStream.getTracks().forEach((t) => t.stop());
214
+ this.recordingStream = null;
215
+ }
216
+ }
217
+ };
218
+
219
+ // src/react/utility/audio/OutputAudioController.ts
220
+ var OutputAudioController = class {
221
+ constructor(loggerName) {
222
+ this.logger = new Logger(loggerName);
223
+ }
224
+ };
225
+
226
+ // src/react/utility/audio/AudioElementOutputAudioController.ts
227
+ var AudioElementOutputAudioController = class extends OutputAudioController {
228
+ constructor() {
229
+ super("@m4trix/core > WebApiOutputAudioController");
230
+ // ─── Playback state ──────────────────────────────────────────────────────
231
+ this.currentHtmlAudio = null;
232
+ this.currentAudioUrl = null;
233
+ }
234
+ // ─── One-shot playback ────────────────────────────────────────────────────
235
+ /**
236
+ * Play either a Blob or a URL string.
237
+ * Uses <audio> under the hood for maximum browser compatibility.
238
+ */
239
+ async playAudio({
240
+ source,
241
+ onComplete
242
+ }) {
243
+ if (this.currentHtmlAudio) {
244
+ this.currentHtmlAudio.pause();
245
+ this.currentHtmlAudio.src = "";
246
+ if (this.currentAudioUrl && source instanceof Blob) {
247
+ URL.revokeObjectURL(this.currentAudioUrl);
248
+ }
249
+ }
250
+ const audio = new Audio();
251
+ this.currentHtmlAudio = audio;
252
+ let url;
253
+ if (source instanceof Blob) {
254
+ url = URL.createObjectURL(source);
255
+ this.currentAudioUrl = url;
256
+ audio.onended = () => {
257
+ URL.revokeObjectURL(url);
258
+ onComplete?.();
259
+ };
260
+ } else {
261
+ url = source;
262
+ }
263
+ audio.src = url;
264
+ try {
265
+ await audio.play();
266
+ } catch (err) {
267
+ this.logger.error("Playback failed, user gesture may be required", err);
268
+ }
269
+ }
270
+ // ─── Streaming playback ──────────────────────────────────────────────────
271
+ /**
272
+ * Stream audio from a Response via MediaSource Extensions.
273
+ * @param params.response The fetch Response whose body is an audio stream
274
+ * @param params.mimeCodec MIME type+codec string, e.g. 'audio/mpeg'
275
+ * @param params.onComplete Optional callback once the stream ends
276
+ */
277
+ async playAudioStream({
278
+ response,
279
+ mimeCodec = "audio/mpeg",
280
+ onComplete
281
+ }) {
282
+ if (!response.ok || !response.body) {
283
+ throw new Error(`Invalid response (${response.status})`);
284
+ }
285
+ if (typeof MediaSource === "undefined" || !MediaSource.isTypeSupported(mimeCodec)) {
286
+ throw new Error(`Unsupported MIME type or codec: ${mimeCodec}`);
287
+ }
288
+ await this.stopPlayback();
289
+ const mediaSource = new MediaSource();
290
+ const url = URL.createObjectURL(mediaSource);
291
+ this.currentAudioUrl = url;
292
+ const audio = new Audio(url);
293
+ this.currentHtmlAudio = audio;
294
+ audio.autoplay = true;
295
+ audio.onended = () => {
296
+ URL.revokeObjectURL(url);
297
+ this.currentAudioUrl = null;
298
+ onComplete?.();
299
+ };
300
+ mediaSource.addEventListener(
301
+ "sourceopen",
302
+ () => {
303
+ const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
304
+ const reader = response.body.getReader();
305
+ const pump = async () => {
306
+ const { done, value } = await reader.read();
307
+ if (done) {
308
+ mediaSource.endOfStream();
309
+ return;
310
+ }
311
+ if (value) {
312
+ sourceBuffer.appendBuffer(value);
313
+ }
314
+ if (sourceBuffer.updating) {
315
+ sourceBuffer.addEventListener("updateend", pump, { once: true });
316
+ } else {
317
+ pump();
318
+ }
319
+ };
320
+ pump();
321
+ },
322
+ { once: true }
323
+ );
324
+ try {
325
+ await audio.play();
326
+ } catch (err) {
327
+ this.logger.error(
328
+ "Streaming playback failed, user gesture may be required",
329
+ err
330
+ );
331
+ }
332
+ }
333
+ // ─── Chunk-based streaming playback ─────────────────────────────────────
334
+ /**
335
+ * Initialize a streaming audio context for chunk-based playback.
336
+ * This creates the necessary MediaSource and SourceBuffer for subsequent chunk additions.
337
+ * Returns functions to add chunks and end the stream, encapsulated in a closure.
338
+ *
339
+ * @param mimeCodec MIME type+codec string, e.g. 'audio/mpeg'
340
+ * @param onComplete Optional callback once the stream ends
341
+ * @returns Object containing functions to add chunks and end the stream
342
+ */
343
+ async initializeChunkStream({
344
+ onComplete,
345
+ mimeCodec = "audio/mpeg"
346
+ }) {
347
+ this.logger.debug(`Initializing chunk stream with codec: ${mimeCodec}`);
348
+ if (typeof MediaSource === "undefined") {
349
+ throw new Error("MediaSource API is not supported in this browser");
350
+ }
351
+ if (!MediaSource.isTypeSupported(mimeCodec)) {
352
+ this.logger.warn(
353
+ `Codec ${mimeCodec} not supported, falling back to standard audio/mpeg`
354
+ );
355
+ mimeCodec = "audio/mpeg";
356
+ if (!MediaSource.isTypeSupported(mimeCodec)) {
357
+ throw new Error(
358
+ "Neither the specified codec nor the fallback codec are supported"
359
+ );
360
+ }
361
+ }
362
+ await this.stopPlayback();
363
+ const mediaSource = new MediaSource();
364
+ let sourceBuffer = null;
365
+ const url = URL.createObjectURL(mediaSource);
366
+ this.currentAudioUrl = url;
367
+ const audio = new Audio(url);
368
+ this.currentHtmlAudio = audio;
369
+ audio.autoplay = false;
370
+ audio.controls = true;
371
+ audio.style.display = "none";
372
+ document.body.appendChild(audio);
373
+ let playbackStarted = false;
374
+ let hasReceivedFirstChunk = false;
375
+ let receivedChunksCount = 0;
376
+ const pendingChunks = [];
377
+ let isProcessingQueue = false;
378
+ this.logger.debug("Waiting for MediaSource to open...");
379
+ await new Promise((resolve, reject) => {
380
+ const timeout = setTimeout(() => {
381
+ reject(new Error("MediaSource failed to open (timeout)"));
382
+ }, 5e3);
383
+ mediaSource.addEventListener(
384
+ "sourceopen",
385
+ () => {
386
+ clearTimeout(timeout);
387
+ this.logger.debug("MediaSource open event received");
388
+ try {
389
+ sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
390
+ if (mediaSource.duration === Infinity || isNaN(mediaSource.duration)) {
391
+ mediaSource.duration = 1e3;
392
+ }
393
+ this.logger.debug("SourceBuffer created successfully");
394
+ resolve();
395
+ } catch (err) {
396
+ reject(new Error(`Failed to create SourceBuffer: ${err}`));
397
+ }
398
+ },
399
+ { once: true }
400
+ );
401
+ });
402
+ const logger = this.logger;
403
+ const processQueue = async () => {
404
+ if (!sourceBuffer || pendingChunks.length === 0 || isProcessingQueue) {
405
+ return;
406
+ }
407
+ isProcessingQueue = true;
408
+ try {
409
+ while (pendingChunks.length > 0) {
410
+ if (sourceBuffer.updating) {
411
+ await new Promise((resolve) => {
412
+ sourceBuffer.addEventListener("updateend", () => resolve(), {
413
+ once: true
414
+ });
415
+ });
416
+ }
417
+ const nextChunk = pendingChunks.shift();
418
+ if (!nextChunk)
419
+ continue;
420
+ try {
421
+ sourceBuffer.appendBuffer(nextChunk);
422
+ logger.debug(
423
+ `Processed queued chunk of size ${nextChunk.byteLength}`
424
+ );
425
+ if (!playbackStarted && hasReceivedFirstChunk) {
426
+ await tryStartPlayback();
427
+ }
428
+ await new Promise((resolve) => {
429
+ sourceBuffer.addEventListener("updateend", () => resolve(), {
430
+ once: true
431
+ });
432
+ });
433
+ } catch (err) {
434
+ logger.error("Error appending queued chunk to source buffer", err);
435
+ }
436
+ }
437
+ } finally {
438
+ isProcessingQueue = false;
439
+ }
440
+ };
441
+ const tryStartPlayback = async () => {
442
+ if (playbackStarted)
443
+ return;
444
+ playbackStarted = true;
445
+ logger.debug("Attempting to start audio playback...");
446
+ if (receivedChunksCount < 3 && audio.buffered.length > 0 && audio.buffered.end(0) < 0.5) {
447
+ logger.debug("Not enough data buffered yet, delaying playback");
448
+ return;
449
+ }
450
+ try {
451
+ if (audio.readyState === 0) {
452
+ logger.debug(
453
+ "Audio element not ready yet, waiting for canplay event"
454
+ );
455
+ await new Promise((resolve) => {
456
+ audio.addEventListener("canplay", () => resolve(), { once: true });
457
+ });
458
+ }
459
+ await audio.play();
460
+ logger.debug("Successfully started audio playback");
461
+ } catch (err) {
462
+ logger.error("Failed to start playback", err);
463
+ document.addEventListener(
464
+ "click",
465
+ async () => {
466
+ try {
467
+ await audio.play();
468
+ logger.debug("Started playback after user interaction");
469
+ } catch (innerErr) {
470
+ logger.error(
471
+ "Still failed to play after user interaction",
472
+ innerErr
473
+ );
474
+ }
475
+ },
476
+ { once: true }
477
+ );
478
+ }
479
+ };
480
+ const addChunkToStream = async (chunk) => {
481
+ if (!sourceBuffer) {
482
+ throw new Error(
483
+ "Streaming context was closed or not properly initialized."
484
+ );
485
+ }
486
+ let arrayBufferChunk;
487
+ if (chunk instanceof Blob) {
488
+ logger.debug("Converting Blob to ArrayBuffer");
489
+ arrayBufferChunk = await chunk.arrayBuffer();
490
+ } else {
491
+ arrayBufferChunk = chunk;
492
+ }
493
+ if (!arrayBufferChunk || arrayBufferChunk.byteLength === 0) {
494
+ logger.warn("Received empty chunk, skipping");
495
+ return;
496
+ }
497
+ if (!hasReceivedFirstChunk) {
498
+ hasReceivedFirstChunk = true;
499
+ logger.debug(
500
+ `First chunk received, size: ${arrayBufferChunk.byteLength} bytes`
501
+ );
502
+ }
503
+ receivedChunksCount++;
504
+ pendingChunks.push(arrayBufferChunk);
505
+ logger.debug(
506
+ `Added chunk #${receivedChunksCount} to queue (size: ${arrayBufferChunk.byteLength} bytes)`
507
+ );
508
+ await processQueue();
509
+ if (!playbackStarted && hasReceivedFirstChunk && receivedChunksCount >= 3) {
510
+ await tryStartPlayback();
511
+ }
512
+ };
513
+ const endChunkStream = () => {
514
+ if (mediaSource && mediaSource.readyState === "open") {
515
+ try {
516
+ if (pendingChunks.length > 0 || sourceBuffer && sourceBuffer.updating) {
517
+ logger.debug("Waiting for pending chunks before ending stream");
518
+ setTimeout(() => endChunkStream(), 200);
519
+ return;
520
+ }
521
+ if (hasReceivedFirstChunk) {
522
+ mediaSource.endOfStream();
523
+ logger.debug("MediaSource stream ended successfully");
524
+ } else {
525
+ logger.warn("Stream ended without receiving any chunks");
526
+ }
527
+ } catch (err) {
528
+ logger.error("Error ending MediaSource stream", err);
529
+ }
530
+ }
531
+ audio.onended = null;
532
+ if (audio.parentNode) {
533
+ audio.parentNode.removeChild(audio);
534
+ }
535
+ if (this.currentAudioUrl === url) {
536
+ this.currentAudioUrl = null;
537
+ URL.revokeObjectURL(url);
538
+ }
539
+ sourceBuffer = null;
540
+ };
541
+ audio.onended = () => {
542
+ logger.debug("Audio playback completed");
543
+ endChunkStream();
544
+ onComplete?.();
545
+ };
546
+ return {
547
+ addChunkToStream,
548
+ endChunkStream
549
+ };
550
+ }
551
+ /**
552
+ * Stop any ongoing HTMLAudioElement playback.
553
+ */
554
+ async stopPlayback() {
555
+ if (this.currentHtmlAudio) {
556
+ try {
557
+ this.currentHtmlAudio.pause();
558
+ this.currentHtmlAudio.src = "";
559
+ } catch (err) {
560
+ this.logger.error("Error stopping playback", err);
561
+ }
562
+ this.currentHtmlAudio = null;
563
+ }
564
+ if (this.currentAudioUrl) {
565
+ URL.revokeObjectURL(this.currentAudioUrl);
566
+ this.currentAudioUrl = null;
567
+ }
568
+ }
569
+ /**
570
+ * Cleans up all audio playback resources.
571
+ */
572
+ cleanup() {
573
+ this.stopPlayback();
574
+ }
575
+ };
576
+
577
+ // src/react/hooks/use-conversation/useConversation.ts
578
+ Logger.enableGlobalLogging();
579
+ function useConversation(endpoint, {
580
+ onStartRecording,
581
+ onStopRecording,
582
+ onReceive,
583
+ autoPlay = true,
584
+ downstreamMode = "STREAM",
585
+ onError,
586
+ audioConfig = {},
587
+ requestData = {},
588
+ endpointConfig = {}
589
+ }) {
590
+ const { current: logger } = react.useRef(
591
+ new Logger("@m4trix/core > useConversation")
592
+ );
593
+ const inputAudioControllerRef = react.useRef(void 0);
594
+ const outputAudioControllerRef = react.useRef(
595
+ void 0
596
+ );
597
+ const endpointAdapterRef = react.useRef(
598
+ void 0
599
+ );
600
+ const [voiceAgentState, setVoiceAgentState] = react.useState("READY");
601
+ const [error, setError] = react.useState(null);
602
+ const handleError = react.useCallback(
603
+ (state2, err) => {
604
+ setError(err);
605
+ logger.error(`Error during ${state2}:`, err);
606
+ onError?.(state2, err);
607
+ },
608
+ [onError]
609
+ );
610
+ const startRecording = react.useCallback(() => {
611
+ if (inputAudioControllerRef.current) {
612
+ try {
613
+ logger.debug("Starting recording");
614
+ setVoiceAgentState("RECORDING");
615
+ inputAudioControllerRef.current.startRecording({
616
+ onError: (err) => {
617
+ handleError("RECORDING", err);
618
+ }
619
+ });
620
+ onStartRecording?.();
621
+ } catch (err) {
622
+ if (err instanceof Error) {
623
+ handleError("RECORDING", err);
624
+ }
625
+ }
626
+ }
627
+ }, [onStartRecording, handleError]);
628
+ const stopRecording = react.useCallback(async () => {
629
+ if (inputAudioControllerRef.current) {
630
+ try {
631
+ logger.debug("Stopping recording");
632
+ await inputAudioControllerRef.current.stopRecording({
633
+ onRecordingCompleted: async (allData) => {
634
+ setVoiceAgentState("PROCESSING");
635
+ try {
636
+ const response = await endpointAdapterRef.current?.sendVoiceFile({
637
+ blob: allData,
638
+ metadata: requestData
639
+ });
640
+ if (!response) {
641
+ throw new Error("No response received from endpoint");
642
+ }
643
+ setVoiceAgentState("RESPONDING");
644
+ if (autoPlay) {
645
+ if (downstreamMode === "STREAM") {
646
+ await outputAudioControllerRef.current?.playAudioStream({
647
+ response,
648
+ onComplete: () => {
649
+ setVoiceAgentState("READY");
650
+ }
651
+ });
652
+ } else if (downstreamMode === "DOWNLOAD") {
653
+ const responseBlob = await response.blob();
654
+ await outputAudioControllerRef.current?.playAudio({
655
+ source: responseBlob,
656
+ onComplete: () => {
657
+ setVoiceAgentState("READY");
658
+ }
659
+ });
660
+ }
661
+ } else {
662
+ setVoiceAgentState("READY");
663
+ }
664
+ onReceive?.(
665
+ allData,
666
+ async () => {
667
+ if (outputAudioControllerRef.current) {
668
+ if (downstreamMode === "STREAM") {
669
+ return outputAudioControllerRef.current.playAudioStream({
670
+ response,
671
+ onComplete: () => {
672
+ setVoiceAgentState("READY");
673
+ }
674
+ });
675
+ } else {
676
+ const responseBlob = await response.blob();
677
+ return outputAudioControllerRef.current.playAudio({
678
+ source: responseBlob,
679
+ onComplete: () => {
680
+ setVoiceAgentState("READY");
681
+ }
682
+ });
683
+ }
684
+ }
685
+ },
686
+ async () => {
687
+ if (outputAudioControllerRef.current) {
688
+ return outputAudioControllerRef.current.stopPlayback();
689
+ }
690
+ }
691
+ );
692
+ } catch (err) {
693
+ if (err instanceof Error) {
694
+ handleError("PROCESSING", err);
695
+ }
696
+ setVoiceAgentState("READY");
697
+ }
698
+ }
699
+ });
700
+ onStopRecording?.();
701
+ } catch (err) {
702
+ if (err instanceof Error) {
703
+ handleError("RECORDING", err);
704
+ }
705
+ }
706
+ }
707
+ }, [
708
+ onStopRecording,
709
+ requestData,
710
+ autoPlay,
711
+ downstreamMode,
712
+ handleError,
713
+ onReceive
714
+ ]);
715
+ react.useEffect(() => {
716
+ if (endpointAdapterRef.current) {
717
+ return;
718
+ }
719
+ try {
720
+ const endpointAdapter = endpointConfig.endpointAdapter ? endpointConfig.endpointAdapter : new BaseVoiceEndpointAdapter({
721
+ baseUrl: endpointConfig.baseUrl,
722
+ endpoint,
723
+ headers: endpointConfig.headers
724
+ });
725
+ endpointAdapterRef.current = endpointAdapter;
726
+ if (!inputAudioControllerRef.current) {
727
+ inputAudioControllerRef.current = new WebAudioInputAudioController(
728
+ audioConfig
729
+ );
730
+ }
731
+ if (!outputAudioControllerRef.current) {
732
+ outputAudioControllerRef.current = new AudioElementOutputAudioController();
733
+ }
734
+ } catch (err) {
735
+ if (err instanceof Error) {
736
+ handleError("READY", err);
737
+ }
738
+ }
739
+ }, [endpoint, endpointConfig, audioConfig, handleError]);
740
+ react.useEffect(() => {
741
+ return () => {
742
+ inputAudioControllerRef.current?.cleanup();
743
+ outputAudioControllerRef.current?.cleanup();
744
+ };
745
+ }, []);
746
+ return {
747
+ startRecording,
748
+ stopRecording,
749
+ voiceAgentState,
750
+ error,
751
+ audioContext: inputAudioControllerRef.current?.audioContext || null
752
+ };
753
+ }
754
+
755
+ // src/react/adapter/socket/VoiceSocketAdapter.ts
756
+ var VoiceSocketAdapter = class {
757
+ constructor(config) {
758
+ this._isConnected = false;
759
+ this.logger = new Logger("@m4trix/core > VoiceSocketAdapter");
760
+ this.emitter = new Emitter();
761
+ this.config = config;
762
+ }
763
+ on(event, listener) {
764
+ this.emitter.on(event, listener);
765
+ }
766
+ off(event, listener) {
767
+ this.emitter.off(event, listener);
768
+ }
769
+ once(event, listener) {
770
+ this.emitter.once(event, listener);
771
+ }
772
+ emit(event, data) {
773
+ this.emitter.emit(event, data);
774
+ }
775
+ isConnected() {
776
+ return this._isConnected;
777
+ }
778
+ };
779
+ var Emitter = class {
780
+ constructor() {
781
+ this.target = new EventTarget();
782
+ }
783
+ on(type, listener) {
784
+ this.target.addEventListener(type, listener);
785
+ }
786
+ off(type, listener) {
787
+ this.target.removeEventListener(type, listener);
788
+ }
789
+ once(type, listener) {
790
+ const wrapper = (event) => {
791
+ this.off(type, wrapper);
792
+ listener(event.detail);
793
+ };
794
+ this.on(type, wrapper);
795
+ }
796
+ emit(type, detail) {
797
+ this.target.dispatchEvent(new CustomEvent(type, { detail }));
798
+ }
799
+ };
800
+ var VoiceSocketIOAdapter = class extends VoiceSocketAdapter {
801
+ constructor(config) {
802
+ super(config);
803
+ this.socket = null;
804
+ }
805
+ async connect() {
806
+ return new Promise((resolve, reject) => {
807
+ if (!this.socket) {
808
+ this.socket = socket_ioClient.io(this.config.baseUrl, {
809
+ extraHeaders: this.config.headers,
810
+ autoConnect: true
811
+ });
812
+ }
813
+ this.socket.on("connect", () => {
814
+ this._isConnected = true;
815
+ this.logger.debug("Connected to socket");
816
+ this.emit("connect");
817
+ resolve();
818
+ });
819
+ this.socket.on("disconnect", () => {
820
+ this._isConnected = false;
821
+ this.emit("disconnect");
822
+ this.logger.debug("Disconnected from socket");
823
+ if (this.config.autoReconnect)
824
+ this.connect();
825
+ });
826
+ this.socket.on("connect_error", (error) => {
827
+ this.logger.error("Error connecting to socket", error);
828
+ this.emit("error", error);
829
+ reject(error);
830
+ });
831
+ this.socket.on("voice:chunk_received", (chunk) => {
832
+ this.logger.debug("Received voice chunk", chunk.byteLength);
833
+ this.onVoiceChunkReceived(chunk);
834
+ });
835
+ this.socket.on("voice:received_end_of_response_stream", () => {
836
+ this.logger.debug("Received end of response stream");
837
+ this.onReceivedEndOfResponseStream();
838
+ });
839
+ this.socket.on("voice:file_received", (blob) => {
840
+ this.logger.debug("Received voice file");
841
+ this.onVoiceFileReceived(blob);
842
+ });
843
+ this.socket.on("control-message", (message) => {
844
+ this.logger.debug("Received control message", message);
845
+ this.emit("control-message", message);
846
+ });
847
+ });
848
+ }
849
+ disconnect() {
850
+ this.socket?.disconnect();
851
+ this.socket = null;
852
+ this._isConnected = false;
853
+ }
854
+ exposeSocket() {
855
+ return this.socket;
856
+ }
857
+ async sendVoiceChunk(chunk, metadata) {
858
+ this.logger.debug(
859
+ "Sending voice chunk %i",
860
+ chunk instanceof Blob ? chunk.size : chunk.byteLength
861
+ );
862
+ if (!this.socket || !this.isConnected)
863
+ throw new Error("Socket not connected");
864
+ let chunkToSend;
865
+ if (chunk instanceof Blob) {
866
+ chunkToSend = await chunk.arrayBuffer();
867
+ } else {
868
+ chunkToSend = chunk;
869
+ }
870
+ this.logger.debug("[Socket] Sending voice chunk", chunkToSend.byteLength);
871
+ this.socket.emit("voice:send_chunk", chunkToSend, metadata);
872
+ this.emit("chunk_sent", chunk);
873
+ }
874
+ sendVoiceFile(blob, metadata) {
875
+ this.logger.debug("Sending voice file", blob, metadata);
876
+ if (!this.socket || !this.isConnected)
877
+ throw new Error("Socket not connected");
878
+ this.socket.emit("voice:send_file", blob, metadata);
879
+ this.emit("file-sent", blob);
880
+ }
881
+ commitVoiceMessage() {
882
+ if (!this.socket || !this.isConnected)
883
+ throw new Error("Socket not connected");
884
+ this.socket.emit("voice:commit");
885
+ }
886
+ onVoiceChunkReceived(chunk) {
887
+ this.emit("chunk-received", chunk);
888
+ }
889
+ onVoiceFileReceived(blob) {
890
+ this.emit("file-received", blob);
891
+ }
892
+ onReceivedEndOfResponseStream() {
893
+ this.emit("received-end-of-response-stream");
894
+ }
895
+ };
896
+
897
+ // src/react/utility/audio/WebAudioOutputAudioController.ts
898
+ var STREAM_SAMPLE_RATE = 24e3;
899
+ var CHANNELS = 1;
900
+ var SLICE_DURATION_S = 0.25;
901
+ var FRAMES_PER_SLICE = Math.floor(STREAM_SAMPLE_RATE * SLICE_DURATION_S);
902
+ var BYTES_PER_SLICE = FRAMES_PER_SLICE * 2;
903
+ var SCHED_TOLERANCE = 0.05;
904
+ var WebAudioOutputAudioController = class extends OutputAudioController {
905
+ constructor() {
906
+ super("@m4trix/core > WebAudioOutputAudioController");
907
+ this.audioCtx = new AudioContext();
908
+ this.gain = this.audioCtx.createGain();
909
+ this.nextPlayTime = 0;
910
+ this.activeSources = /* @__PURE__ */ new Set();
911
+ this.userGestureHookAttached = false;
912
+ this.gain.connect(this.audioCtx.destination);
913
+ this.resetScheduler();
914
+ }
915
+ // ─────────────────────────────────────────────────────────────────────
916
+ // One‑shot playback
917
+ // ─────────────────────────────────────────────────────────────────────
918
+ async playAudio({
919
+ source,
920
+ onComplete
921
+ }) {
922
+ await this.stopPlayback();
923
+ const buf = await this.sourceToArrayBuffer(source);
924
+ const decoded = await this.decode(buf);
925
+ await this.ensureContextRunning();
926
+ const src = this.createSource(decoded, this.audioCtx.currentTime);
927
+ src.onended = () => {
928
+ this.activeSources.delete(src);
929
+ onComplete?.();
930
+ };
931
+ }
932
+ async playAudioStream() {
933
+ }
934
+ // ─────────────────────────────────────────────────────────────────────
935
+ // PCM streaming
936
+ // ─────────────────────────────────────────────────────────────────────
937
+ async initializeChunkStream({
938
+ onComplete
939
+ }) {
940
+ await this.stopPlayback();
941
+ await this.ensureContextRunning();
942
+ this.resetScheduler();
943
+ let streamEnded = false;
944
+ let pending = new Uint8Array(0);
945
+ const addChunkToStream = async (pkt) => {
946
+ if (streamEnded) {
947
+ this.logger.warn("Attempt to add chunk after stream ended \u2013 ignoring.");
948
+ return;
949
+ }
950
+ const bytes = new Uint8Array(
951
+ pkt instanceof Blob ? await pkt.arrayBuffer() : pkt
952
+ );
953
+ if (bytes.length === 0)
954
+ return;
955
+ const merged = new Uint8Array(pending.length + bytes.length);
956
+ merged.set(pending);
957
+ merged.set(bytes, pending.length);
958
+ pending = merged;
959
+ if (pending.length % 2 === 1)
960
+ return;
961
+ while (pending.length >= BYTES_PER_SLICE) {
962
+ const sliceBytes = pending.slice(0, BYTES_PER_SLICE);
963
+ pending = pending.slice(BYTES_PER_SLICE);
964
+ const aligned = sliceBytes.buffer.slice(
965
+ sliceBytes.byteOffset,
966
+ sliceBytes.byteOffset + sliceBytes.byteLength
967
+ );
968
+ const int16 = new Int16Array(aligned);
969
+ const buf = this.audioCtx.createBuffer(
970
+ CHANNELS,
971
+ int16.length,
972
+ STREAM_SAMPLE_RATE
973
+ );
974
+ const data = buf.getChannelData(0);
975
+ for (let i = 0; i < int16.length; i++)
976
+ data[i] = int16[i] / 32768;
977
+ this.scheduleBuffer(buf);
978
+ }
979
+ };
980
+ const endChunkStream = () => {
981
+ if (streamEnded)
982
+ return;
983
+ streamEnded = true;
984
+ if (onComplete) {
985
+ if (this.activeSources.size === 0)
986
+ onComplete();
987
+ else {
988
+ const last = Array.from(this.activeSources).pop();
989
+ if (last) {
990
+ const prev = last.onended;
991
+ last.onended = (e) => {
992
+ if (prev)
993
+ prev.call(last, e);
994
+ onComplete();
995
+ };
996
+ }
997
+ }
998
+ }
999
+ };
1000
+ return { addChunkToStream, endChunkStream };
1001
+ }
1002
+ // ─────────────────────────────────────────────────────────────────────
1003
+ // Buffer scheduling helpers
1004
+ // ─────────────────────────────────────────────────────────────────────
1005
+ scheduleBuffer(buf) {
1006
+ if (this.nextPlayTime < this.audioCtx.currentTime + SCHED_TOLERANCE) {
1007
+ this.nextPlayTime = this.audioCtx.currentTime + SCHED_TOLERANCE;
1008
+ }
1009
+ this.createSource(buf, this.nextPlayTime);
1010
+ this.nextPlayTime += buf.duration;
1011
+ }
1012
+ createSource(buf, when) {
1013
+ const src = this.audioCtx.createBufferSource();
1014
+ src.buffer = buf;
1015
+ src.connect(this.gain);
1016
+ src.start(when);
1017
+ this.activeSources.add(src);
1018
+ src.onended = () => {
1019
+ this.activeSources.delete(src);
1020
+ };
1021
+ return src;
1022
+ }
1023
+ resetScheduler() {
1024
+ this.nextPlayTime = this.audioCtx.currentTime;
1025
+ }
1026
+ // ─── External resource helpers ───────────────────────────────────────
1027
+ sourceToArrayBuffer(src) {
1028
+ return typeof src === "string" ? fetch(src).then((r) => {
1029
+ if (!r.ok)
1030
+ throw new Error(`${r.status}`);
1031
+ return r.arrayBuffer();
1032
+ }) : src.arrayBuffer();
1033
+ }
1034
+ decode(buf) {
1035
+ return new Promise(
1036
+ (res, rej) => this.audioCtx.decodeAudioData(buf, res, rej)
1037
+ );
1038
+ }
1039
+ // ─── Lifecycle methods ───────────────────────────────────────────────
1040
+ async stopPlayback() {
1041
+ for (const src of this.activeSources) {
1042
+ try {
1043
+ src.stop();
1044
+ } catch {
1045
+ }
1046
+ src.disconnect();
1047
+ }
1048
+ this.activeSources.clear();
1049
+ this.resetScheduler();
1050
+ }
1051
+ cleanup() {
1052
+ this.stopPlayback();
1053
+ if (this.audioCtx.state !== "closed")
1054
+ this.audioCtx.close();
1055
+ }
1056
+ // ─── Autoplay‑policy helper ──────────────────────────────────────────
1057
+ async ensureContextRunning() {
1058
+ if (this.audioCtx.state !== "suspended")
1059
+ return;
1060
+ try {
1061
+ await this.audioCtx.resume();
1062
+ } catch {
1063
+ }
1064
+ if (this.audioCtx.state === "running")
1065
+ return;
1066
+ if (!this.userGestureHookAttached) {
1067
+ this.userGestureHookAttached = true;
1068
+ const resume = async () => {
1069
+ try {
1070
+ await this.audioCtx.resume();
1071
+ } catch {
1072
+ }
1073
+ if (this.audioCtx.state === "running")
1074
+ document.removeEventListener("click", resume);
1075
+ };
1076
+ document.addEventListener("click", resume);
1077
+ }
1078
+ }
1079
+ };
1080
+
1081
+ // src/react/hooks/use-conversation/useSocketConversation.ts
1082
+ Logger.enableGlobalLogging();
1083
+ function useSocketConversation({
1084
+ scope,
1085
+ onStartRecording,
1086
+ onStopRecording,
1087
+ onReceive,
1088
+ upstreamMode = "STREAM_WHILE_TALK",
1089
+ onError,
1090
+ audioConfig = {},
1091
+ socketConfig = {}
1092
+ }) {
1093
+ const { current: logger } = react.useRef(
1094
+ new Logger("SuTr > useSocketConversation")
1095
+ );
1096
+ const inputAudioControllerRef = react.useRef(void 0);
1097
+ const outputAudioControllerRef = react.useRef(
1098
+ void 0
1099
+ );
1100
+ const socketAdapterRef = react.useRef(void 0);
1101
+ const [socket, setSocket] = react.useState(null);
1102
+ const [voiceAgentState, setVoiceAgentState] = react.useState("READY");
1103
+ const [error, setError] = react.useState(null);
1104
+ const shouldStreamWhileTalk = upstreamMode === "STREAM_WHILE_TALK";
1105
+ const handleError = react.useCallback(
1106
+ (state2, err) => {
1107
+ setError(err);
1108
+ logger.error(`Error during ${state2}:`, err);
1109
+ onError?.(state2, err);
1110
+ },
1111
+ [onError]
1112
+ );
1113
+ const subscribeToSocketEventsForChunkDownstreaming = react.useCallback(
1114
+ async (socketAdapter) => {
1115
+ logger.debug("Setting up audio stream for receiving chunks");
1116
+ try {
1117
+ const { addChunkToStream, endChunkStream } = await outputAudioControllerRef.current.initializeChunkStream({
1118
+ mimeCodec: "audio/mpeg",
1119
+ onComplete: () => {
1120
+ logger.debug("Audio stream playback completed");
1121
+ setVoiceAgentState("READY");
1122
+ }
1123
+ });
1124
+ let chunkCount = 0;
1125
+ const chunkReceivedEmitter = async (chunk) => {
1126
+ if (chunk instanceof ArrayBuffer) {
1127
+ chunkCount++;
1128
+ logger.debug(
1129
+ `Received voice chunk #${chunkCount} from socket, size: ${chunk.byteLength} bytes`
1130
+ );
1131
+ if (!chunk || chunk.byteLength === 0) {
1132
+ logger.warn("Received empty chunk, skipping");
1133
+ return;
1134
+ }
1135
+ try {
1136
+ await addChunkToStream(chunk);
1137
+ logger.debug(
1138
+ `Successfully added chunk #${chunkCount} to audio stream`
1139
+ );
1140
+ } catch (err) {
1141
+ logger.error(
1142
+ `Failed to add chunk #${chunkCount} to audio stream`,
1143
+ err
1144
+ );
1145
+ if (err instanceof Error) {
1146
+ handleError("DOWNSTREAMING", err);
1147
+ }
1148
+ }
1149
+ }
1150
+ };
1151
+ socketAdapter.on("chunk-received", chunkReceivedEmitter);
1152
+ const endOfStreamEmitter = () => {
1153
+ logger.debug(
1154
+ `Received end of stream signal after ${chunkCount} chunks, ending chunk stream`
1155
+ );
1156
+ endChunkStream();
1157
+ setVoiceAgentState("READY");
1158
+ };
1159
+ socketAdapter.on("received-end-of-response-stream", endOfStreamEmitter);
1160
+ return () => {
1161
+ logger.debug("Cleaning up socket event listeners");
1162
+ socketAdapter.off("chunk-received", chunkReceivedEmitter);
1163
+ socketAdapter.off(
1164
+ "received-end-of-response-stream",
1165
+ endOfStreamEmitter
1166
+ );
1167
+ endChunkStream();
1168
+ };
1169
+ } catch (err) {
1170
+ if (err instanceof Error) {
1171
+ handleError("DOWNSTREAMING", err);
1172
+ }
1173
+ return () => {
1174
+ };
1175
+ }
1176
+ },
1177
+ [handleError]
1178
+ );
1179
+ const hookupSocketAdapter = react.useCallback(
1180
+ async (socketAdapter) => {
1181
+ logger.debug("Connecting to socket...");
1182
+ try {
1183
+ await socketAdapter.connect();
1184
+ socketAdapter.on("connect", () => {
1185
+ logger.debug("Socket adapter connected");
1186
+ setVoiceAgentState("READY");
1187
+ });
1188
+ socketAdapter.on("disconnect", () => {
1189
+ logger.debug("Socket adapter disconnected");
1190
+ });
1191
+ socketAdapter.on("error", (err) => {
1192
+ if (err instanceof Error) {
1193
+ handleError(voiceAgentState, err);
1194
+ } else {
1195
+ handleError(voiceAgentState, new Error("Unknown error"));
1196
+ }
1197
+ });
1198
+ setSocket(socketAdapter.exposeSocket());
1199
+ } catch (err) {
1200
+ if (err instanceof Error) {
1201
+ handleError("READY", err);
1202
+ }
1203
+ }
1204
+ },
1205
+ [handleError, voiceAgentState]
1206
+ );
1207
+ const startRecording = react.useCallback(() => {
1208
+ if (inputAudioControllerRef.current) {
1209
+ try {
1210
+ logger.debug("Starting recording");
1211
+ setVoiceAgentState("RECORDING");
1212
+ inputAudioControllerRef.current.startRecording({
1213
+ onRecordedChunk: async (chunk) => {
1214
+ if (shouldStreamWhileTalk) {
1215
+ try {
1216
+ await socketAdapterRef.current?.sendVoiceChunk(chunk);
1217
+ } catch (err) {
1218
+ if (err instanceof Error) {
1219
+ handleError("RECORDING", err);
1220
+ }
1221
+ }
1222
+ }
1223
+ }
1224
+ });
1225
+ onStartRecording?.();
1226
+ } catch (err) {
1227
+ if (err instanceof Error) {
1228
+ handleError("RECORDING", err);
1229
+ }
1230
+ }
1231
+ }
1232
+ }, [onStartRecording, shouldStreamWhileTalk, handleError]);
1233
+ const stopRecording = react.useCallback(async () => {
1234
+ if (inputAudioControllerRef.current) {
1235
+ try {
1236
+ logger.debug("Stopping recording");
1237
+ await inputAudioControllerRef.current.stopRecording({
1238
+ onRecordingCompleted: async (allData) => {
1239
+ setVoiceAgentState("PROCESSING");
1240
+ try {
1241
+ if (shouldStreamWhileTalk) {
1242
+ logger.debug("Committing voice message");
1243
+ await socketAdapterRef.current?.commitVoiceMessage();
1244
+ } else {
1245
+ await socketAdapterRef.current?.sendVoiceFile(allData);
1246
+ }
1247
+ setVoiceAgentState("DOWNSTREAMING");
1248
+ await subscribeToSocketEventsForChunkDownstreaming(
1249
+ socketAdapterRef.current
1250
+ );
1251
+ onReceive?.(
1252
+ allData,
1253
+ async () => {
1254
+ if (outputAudioControllerRef.current) {
1255
+ return outputAudioControllerRef.current.stopPlayback();
1256
+ }
1257
+ },
1258
+ async () => {
1259
+ if (outputAudioControllerRef.current) {
1260
+ return outputAudioControllerRef.current.stopPlayback();
1261
+ }
1262
+ }
1263
+ );
1264
+ } catch (err) {
1265
+ if (err instanceof Error) {
1266
+ handleError("PROCESSING", err);
1267
+ }
1268
+ }
1269
+ }
1270
+ });
1271
+ onStopRecording?.();
1272
+ } catch (err) {
1273
+ if (err instanceof Error) {
1274
+ handleError("RECORDING", err);
1275
+ }
1276
+ }
1277
+ }
1278
+ }, [
1279
+ onStopRecording,
1280
+ handleError,
1281
+ subscribeToSocketEventsForChunkDownstreaming,
1282
+ onReceive
1283
+ ]);
1284
+ react.useEffect(() => {
1285
+ if (socketAdapterRef.current) {
1286
+ return;
1287
+ }
1288
+ try {
1289
+ const socketAdapter = socketConfig.socketAdapter ? socketConfig.socketAdapter : new VoiceSocketIOAdapter({
1290
+ scope,
1291
+ baseUrl: socketConfig.baseUrl || "",
1292
+ headers: socketConfig.headers
1293
+ });
1294
+ socketAdapterRef.current = socketAdapter;
1295
+ if (!socketAdapter.isConnected()) {
1296
+ hookupSocketAdapter(socketAdapter);
1297
+ }
1298
+ if (!inputAudioControllerRef.current) {
1299
+ inputAudioControllerRef.current = new WebAudioInputAudioController(
1300
+ audioConfig
1301
+ );
1302
+ }
1303
+ if (!outputAudioControllerRef.current) {
1304
+ outputAudioControllerRef.current = new WebAudioOutputAudioController();
1305
+ }
1306
+ } catch (err) {
1307
+ if (err instanceof Error) {
1308
+ handleError("READY", err);
1309
+ }
1310
+ }
1311
+ }, [scope, socketConfig, hookupSocketAdapter, audioConfig, handleError]);
1312
+ react.useEffect(() => {
1313
+ return () => {
1314
+ inputAudioControllerRef.current?.cleanup();
1315
+ outputAudioControllerRef.current?.cleanup();
1316
+ if (socketAdapterRef.current) {
1317
+ socketAdapterRef.current.disconnect();
1318
+ socketAdapterRef.current = void 0;
1319
+ }
1320
+ };
1321
+ }, []);
1322
+ return {
1323
+ startRecording,
1324
+ stopRecording,
1325
+ voiceAgentState,
1326
+ error,
1327
+ audioContext: inputAudioControllerRef.current?.audioContext || null,
1328
+ socket
1329
+ };
1330
+ }
1331
+ var AiCursorComponentStyle = lit.css`
1332
+ :host {
1333
+ --ai-local-cursor-size: var(--sk-ai-cursor-size, 1rem);
1334
+ --ai-local-cursor-label-padding: var(
1335
+ --sk-ai-cursor-label-padding,
1336
+ 0.25rem 0.25rem
1337
+ );
1338
+ --ai-local-cursor-border-radius: var(--sk-ai-cursor-border-radius, 0.25rem);
1339
+ --ai-local-label-offset: var(--sk-ai-cursor-label-offset, 1rem);
1340
+
1341
+ --ai-local-label-font-size: var(--sk-ai-cursor-label-font-size, 12px);
1342
+ --ai-local-label-font-weight: var(--sk-ai-cursor-label-font-weight, bold);
1343
+ --ai-local-label-color: var(--sk-ai-cursor-label-color, white);
1344
+ --ai-local-label-background-color: var(
1345
+ --sk-ai-cursor-label-background-color,
1346
+ black
1347
+ );
1348
+ --ai-local-label-border-color: var(
1349
+ --sk-ai-cursor-label-border-color,
1350
+ white
1351
+ );
1352
+ --ai-local-label-border-width: var(
1353
+ --sk-ai-cursor-label-border-width,
1354
+ 0.1rem
1355
+ );
1356
+
1357
+ color: black;
1358
+ stroke: white;
1359
+ position: absolute;
1360
+ /* Insetting in the parent element (body) */
1361
+ top: 0;
1362
+ left: 0;
1363
+ bottom: 0;
1364
+ right: 0;
1365
+ pointer-events: none;
1366
+ width: var(--ai-local-cursor-size);
1367
+ height: var(--ai-local-cursor-size);
1368
+ }
1369
+
1370
+ #cursor-graphic-parent {
1371
+ position: absolute;
1372
+ top: 0;
1373
+ left: 0;
1374
+ }
1375
+
1376
+ #label-text {
1377
+ position: absolute;
1378
+ color: white;
1379
+ font-size: 12px;
1380
+ font-weight: bold;
1381
+ padding: var(--ai-local-cursor-label-padding);
1382
+ border-radius: var(--ai-local-cursor-border-radius);
1383
+
1384
+ white-space: nowrap;
1385
+ overflow: hidden;
1386
+ text-overflow: ellipsis;
1387
+
1388
+ width: fit-content;
1389
+ min-width: fit-content;
1390
+ top: var(--ai-local-label-offset);
1391
+ left: var(--ai-local-label-offset);
1392
+
1393
+ border: var(--ai-local-label-border-width) solid
1394
+ var(--ai-local-label-border-color);
1395
+ background-color: var(--ai-local-label-background-color);
1396
+ color: var(--ai-local-label-color);
1397
+ font-size: var(--ai-local-label-font-size);
1398
+ font-weight: var(--ai-local-label-font-weight);
1399
+ }
1400
+ `;
1401
+
1402
+ // src/ui/ai-cursor/rendering/AiCursorComponent.ts
1403
+ var AiCursorComponent = class extends lit.LitElement {
1404
+ constructor() {
1405
+ super();
1406
+ this.eventHooks = {
1407
+ defineSetPosition: () => {
1408
+ },
1409
+ defineAddPositionToQueue: () => {
1410
+ },
1411
+ definePlayQueue: () => {
1412
+ },
1413
+ defineSetShowCursor: () => {
1414
+ }
1415
+ };
1416
+ this.isShowingCursor = true;
1417
+ this.labelText = "AI Cursor";
1418
+ this.cursorPosition = [0, 0];
1419
+ this._cursorRef = ref_js.createRef();
1420
+ this._labelRef = ref_js.createRef();
1421
+ }
1422
+ updated(_changedProperties) {
1423
+ if (_changedProperties.has("_cursorRef")) {
1424
+ if (this._cursorRef.value) {
1425
+ this.hookUpCallbacks();
1426
+ } else {
1427
+ this._timeline?.pause();
1428
+ this._timeline?.refresh();
1429
+ }
1430
+ }
1431
+ super.updated(_changedProperties);
1432
+ }
1433
+ render() {
1434
+ const cursorSvg = lit.html`
1435
+ <svg
1436
+ width=${24}
1437
+ height=${24}
1438
+ viewBox="0 0 100 100"
1439
+ fill="none"
1440
+ xmlns="http://www.w3.org/2000/svg"
1441
+ >
1442
+ <g clip-path="url(#clip0_3576_285)">
1443
+ <path
1444
+ class="cursor-path"
1445
+ d="M2.14849 7.04749C1.35153 4.07321 4.07319 1.35155 7.04747 2.14851L77.3148 20.9766C80.2891 21.7735 81.2853 25.4914 79.108 27.6687L27.6687 79.108C25.4914 81.2853 21.7735 80.2891 20.9766 77.3149L2.14849 7.04749Z"
1446
+ fill="currentColor"
1447
+ />
1448
+ </g>
1449
+ <defs>
1450
+ <clipPath id="clip0_3576_285">
1451
+ <rect width="100" height="100" fill="white" />
1452
+ </clipPath>
1453
+ </defs>
1454
+ </svg>
1455
+ `;
1456
+ return lit.html`
1457
+ <span
1458
+ id="cursor-graphic-parent"
1459
+ ${ref_js.ref(this._cursorRef)}
1460
+ ?hidden=${!this.isShowingCursor}
1461
+ >
1462
+ ${cursorSvg}
1463
+ <span
1464
+ ${ref_js.ref(this._labelRef)}
1465
+ id="label-text"
1466
+ ?hidden=${!this.isShowingCursor}
1467
+ >${this.labelText}</span
1468
+ >
1469
+ </span>
1470
+ `;
1471
+ }
1472
+ // private methods
1473
+ /**
1474
+ * The primary way to control the cursor is using an external API.
1475
+ * This interface exposes controlling methods. The Lit Component itself is
1476
+ * intended to be a controlled component.
1477
+ */
1478
+ hookUpCallbacks() {
1479
+ const animationTarget = this._cursorRef.value;
1480
+ if (!animationTarget) {
1481
+ return;
1482
+ }
1483
+ this._timeline = animejs.createTimeline({ defaults: { duration: 750 } });
1484
+ if (!this._timeline) {
1485
+ return;
1486
+ }
1487
+ this.eventHooks.defineSetPosition((position) => {
1488
+ this._timeline?.add(animationTarget, {
1489
+ translateX: position[0],
1490
+ translateY: position[1],
1491
+ duration: 1
1492
+ });
1493
+ this._timeline?.play();
1494
+ });
1495
+ this.eventHooks.defineAddPositionToQueue((position) => {
1496
+ this._timeline?.add(animationTarget, {
1497
+ translateX: position[0],
1498
+ translateY: position[1],
1499
+ duration: 1e3
1500
+ });
1501
+ });
1502
+ this.eventHooks.defineSetShowCursor((show) => {
1503
+ this.isShowingCursor = show;
1504
+ });
1505
+ this.eventHooks.definePlayQueue(() => {
1506
+ this._timeline?.play();
1507
+ });
1508
+ }
1509
+ // Getters
1510
+ get cursorRef() {
1511
+ return this._cursorRef.value;
1512
+ }
1513
+ get labelRef() {
1514
+ return this._labelRef.value;
1515
+ }
1516
+ };
1517
+ // Define scoped styles right with your component, in plain CSS
1518
+ AiCursorComponent.styles = AiCursorComponentStyle;
1519
+ __decorateClass([
1520
+ decorators_js.property({
1521
+ type: Object
1522
+ })
1523
+ ], AiCursorComponent.prototype, "eventHooks", 2);
1524
+ __decorateClass([
1525
+ decorators_js.property({ type: Boolean })
1526
+ ], AiCursorComponent.prototype, "isShowingCursor", 2);
1527
+ __decorateClass([
1528
+ decorators_js.property({ type: String })
1529
+ ], AiCursorComponent.prototype, "labelText", 2);
1530
+ __decorateClass([
1531
+ decorators_js.property({ type: Array })
1532
+ ], AiCursorComponent.prototype, "cursorPosition", 2);
1533
+ __decorateClass([
1534
+ decorators_js.state()
1535
+ ], AiCursorComponent.prototype, "_cursorRef", 2);
1536
+ __decorateClass([
1537
+ decorators_js.state()
1538
+ ], AiCursorComponent.prototype, "_labelRef", 2);
1539
+ AiCursorComponent = __decorateClass([
1540
+ decorators_js.customElement("ai-cursor")
1541
+ ], AiCursorComponent);
1542
+
1543
+ // src/ui/ai-cursor/rendering/index.ts
1544
+ var mountAiCursor = (aiCursorProps) => {
1545
+ const root = document.body;
1546
+ const cursor = document.createElement("ai-cursor");
1547
+ cursor.eventHooks = aiCursorProps.eventHooks;
1548
+ root.appendChild(cursor);
1549
+ };
1550
+
1551
+ // src/ui/ai-cursor/AiCursor.ts
1552
+ var AiCursor = class _AiCursor {
1553
+ constructor() {
1554
+ }
1555
+ // Static constructors
1556
+ static spawn() {
1557
+ const newCursor = new _AiCursor();
1558
+ newCursor.mount();
1559
+ return newCursor;
1560
+ }
1561
+ jumpTo(target) {
1562
+ const position = targetToPosition(target);
1563
+ if (position) {
1564
+ this.setPosition?.(position);
1565
+ }
1566
+ }
1567
+ moveTo(target) {
1568
+ const position = targetToPosition(target);
1569
+ if (position) {
1570
+ this.addPositionToQueue?.(position);
1571
+ this.playQueue?.();
1572
+ }
1573
+ }
1574
+ scheduleMoves(targets) {
1575
+ targets.forEach((target) => {
1576
+ const position = targetToPosition(target);
1577
+ if (position) {
1578
+ this.addPositionToQueue?.(position);
1579
+ }
1580
+ });
1581
+ this.playQueue?.();
1582
+ }
1583
+ show() {
1584
+ this.setShowCursor?.(true);
1585
+ }
1586
+ hide() {
1587
+ this.setShowCursor?.(false);
1588
+ }
1589
+ mount() {
1590
+ mountAiCursor({
1591
+ eventHooks: {
1592
+ defineSetPosition: (callback) => {
1593
+ this.setPosition = callback;
1594
+ },
1595
+ defineAddPositionToQueue: (callback) => {
1596
+ this.addPositionToQueue = callback;
1597
+ },
1598
+ definePlayQueue: (callback) => {
1599
+ this.playQueue = callback;
1600
+ },
1601
+ defineSetShowCursor: (callback) => {
1602
+ this.setShowCursor = callback;
1603
+ }
1604
+ }
1605
+ });
1606
+ }
1607
+ };
1608
+ function calculateClickPositionFromElement(element) {
1609
+ const rect = element.getBoundingClientRect();
1610
+ return [rect.left + rect.width / 2, rect.top + rect.height / 2];
1611
+ }
1612
+ function targetToPosition(target) {
1613
+ if (Array.isArray(target) && target.length === 2 && typeof target[0] === "number" && typeof target[1] === "number") {
1614
+ return target;
1615
+ } else if (target instanceof HTMLElement) {
1616
+ return calculateClickPositionFromElement(target);
1617
+ } else if (typeof target === "string") {
1618
+ const element = document.querySelector(target);
1619
+ if (element) {
1620
+ return calculateClickPositionFromElement(element);
1621
+ }
1622
+ }
1623
+ return void 0;
1624
+ }
1625
+
1626
+ // src/stream/Pump.ts
1627
+ var Pump = class _Pump {
1628
+ constructor(src) {
1629
+ this.src = src;
1630
+ }
1631
+ /**
1632
+ * Wrap an existing AsyncIterable or Readable stream into a Pump
1633
+ *
1634
+ * @template U The type of data in the source stream
1635
+ * @param source The source stream to convert to a Pump (AsyncIterable, ReadableStream, or NodeJS.ReadableStream)
1636
+ * @returns A new Pump instance that wraps the source
1637
+ */
1638
+ static from(source) {
1639
+ async function* gen() {
1640
+ let seq = 0;
1641
+ function isAsyncIterable(obj) {
1642
+ return Symbol.asyncIterator in obj;
1643
+ }
1644
+ function isWebReadableStream(obj) {
1645
+ return "getReader" in obj && typeof obj.getReader === "function";
1646
+ }
1647
+ function isNodeReadableStream(obj) {
1648
+ return "pipe" in obj && "on" in obj && typeof obj.pipe === "function" && typeof obj.on === "function";
1649
+ }
1650
+ if (isAsyncIterable(source)) {
1651
+ const iterator = source[Symbol.asyncIterator]();
1652
+ try {
1653
+ while (true) {
1654
+ const result = await iterator.next();
1655
+ if (result.done)
1656
+ break;
1657
+ yield {
1658
+ sequence: seq++,
1659
+ data: result.value,
1660
+ done: false
1661
+ };
1662
+ }
1663
+ } finally {
1664
+ }
1665
+ } else if (isWebReadableStream(source)) {
1666
+ const reader = source.getReader();
1667
+ try {
1668
+ while (true) {
1669
+ const result = await reader.read();
1670
+ if (result.done)
1671
+ break;
1672
+ yield {
1673
+ sequence: seq++,
1674
+ data: result.value,
1675
+ done: false
1676
+ };
1677
+ }
1678
+ } finally {
1679
+ reader.releaseLock();
1680
+ }
1681
+ } else if (isNodeReadableStream(source)) {
1682
+ try {
1683
+ for await (const chunk of source) {
1684
+ yield {
1685
+ sequence: seq++,
1686
+ data: chunk,
1687
+ done: false
1688
+ };
1689
+ }
1690
+ } catch (error) {
1691
+ console.error("Error reading from Node.js stream:", error);
1692
+ throw error;
1693
+ }
1694
+ }
1695
+ yield { sequence: seq, data: void 0, done: true };
1696
+ }
1697
+ return new _Pump(gen());
1698
+ }
1699
+ /**
1700
+ * Sync or async map over the data portion of each chunk
1701
+ *
1702
+ * @template U The output type after transformation
1703
+ * @param fn The mapping function that transforms each chunk
1704
+ * @returns A new Pump instance with the transformed data
1705
+ */
1706
+ map(fn) {
1707
+ async function* gen() {
1708
+ for await (const { sequence, data, done } of this.src) {
1709
+ if (done) {
1710
+ const out2 = data !== void 0 ? await fn(data) : void 0;
1711
+ yield { sequence, data: out2, done };
1712
+ break;
1713
+ }
1714
+ const out = await fn(data);
1715
+ yield { sequence, data: out, done };
1716
+ }
1717
+ }
1718
+ return new _Pump(gen.call(this));
1719
+ }
1720
+ /**
1721
+ * Stateful map allows processing stream chunks with a persistent context object.
1722
+ *
1723
+ * The context is initialized when the first chunk arrives and can be updated with each chunk.
1724
+ * This is useful for maintaining state across the stream processing.
1725
+ *
1726
+ * If you plan to use sockets you should rather opt for asyncStatefulMap.
1727
+ *
1728
+ * The pipe closes only after all processing is complete, including any final operations in onClose.
1729
+ *
1730
+ * TODO: Un-tested
1731
+ *
1732
+ * @param handlers Object containing callback functions for stream processing
1733
+ * @param handlers.onFirstChunk Function called when the first chunk arrives, initializes the context
1734
+ * @param handlers.onChunk Function called for each subsequent chunk, updates the context
1735
+ * @param handlers.onClose Optional function called when the stream closes, allows final processing
1736
+ * @returns A new Pump instance with transformed data
1737
+ */
1738
+ statefulMap(handlers) {
1739
+ const { src } = this;
1740
+ const gen = async function* () {
1741
+ let context;
1742
+ let initialized = false;
1743
+ let lastChunk;
1744
+ let seq = 0;
1745
+ const queue = [];
1746
+ const yieldData = (data) => {
1747
+ queue.push(data);
1748
+ };
1749
+ for await (const { data, done } of src) {
1750
+ if (done) {
1751
+ if (context && handlers.onClose) {
1752
+ await handlers.onClose(lastChunk, context, yieldData);
1753
+ }
1754
+ while (queue.length > 0) {
1755
+ yield { sequence: seq++, data: queue.shift(), done: false };
1756
+ }
1757
+ yield {
1758
+ sequence: seq++,
1759
+ data: void 0,
1760
+ done: true
1761
+ };
1762
+ break;
1763
+ }
1764
+ if (!initialized) {
1765
+ context = await handlers.onFirstChunk(data, yieldData);
1766
+ initialized = true;
1767
+ } else if (context) {
1768
+ context = await handlers.onChunk(data, context, yieldData);
1769
+ }
1770
+ lastChunk = data;
1771
+ while (queue.length > 0) {
1772
+ yield { sequence: seq++, data: queue.shift(), done: false };
1773
+ }
1774
+ }
1775
+ };
1776
+ return new _Pump(gen());
1777
+ }
1778
+ /**
1779
+ * Async map means that each incoming chunk is causing an async operation that when it completes
1780
+ * should yield a new chunk.
1781
+ * The pipe closes only after you unlock the pipe by using the unlockCloseEvent callback.
1782
+ *
1783
+ * Stateful refers to the fact that you can create your own small context object that is passed in the subsequent callbacks.
1784
+ * This allows you to keep track of things like a socket connection.
1785
+ *
1786
+ * Why is this nice? Well if you use things like a socket the pipe might have received the close event,
1787
+ * before you got any or all of your socket responses. Sockets don't fit into the standard promise pattern,
1788
+ * which makes it harder to wait for them.
1789
+ *
1790
+ * TODO: Un-tested
1791
+ *
1792
+ * @param handlers Object containing callback functions for stream processing
1793
+ * @param handlers.onFirstChunk Function called when the first chunk arrives, initializes the context
1794
+ * @param handlers.onChunk Function called for each subsequent chunk, updates the context
1795
+ * @param handlers.onClose Optional function called when the stream closes, allows final processing
1796
+ * @returns A new Pump instance with transformed data
1797
+ */
1798
+ asyncStatefulMap(handlers) {
1799
+ const { src } = this;
1800
+ const gen = async function* () {
1801
+ let context;
1802
+ let initialized = false;
1803
+ let lastChunk;
1804
+ let seq = 0;
1805
+ let lockedCloseEvent = true;
1806
+ const queue = [];
1807
+ const yieldData = (data) => {
1808
+ queue.push(data);
1809
+ };
1810
+ const unlockCloseEvent = () => {
1811
+ lockedCloseEvent = false;
1812
+ };
1813
+ for await (const { data, done } of src) {
1814
+ if (done) {
1815
+ if (context && handlers.onClose) {
1816
+ await handlers.onClose(
1817
+ lastChunk,
1818
+ context,
1819
+ yieldData,
1820
+ unlockCloseEvent
1821
+ );
1822
+ }
1823
+ const timestamp = Date.now();
1824
+ while (lockedCloseEvent && Date.now() - timestamp < 1e4) {
1825
+ while (queue.length > 0) {
1826
+ yield { sequence: seq++, data: queue.shift(), done: false };
1827
+ }
1828
+ await new Promise((resolve) => setTimeout(resolve, 5));
1829
+ }
1830
+ while (queue.length > 0) {
1831
+ yield { sequence: seq++, data: queue.shift(), done: false };
1832
+ }
1833
+ yield {
1834
+ sequence: seq++,
1835
+ data: void 0,
1836
+ done: true
1837
+ };
1838
+ break;
1839
+ }
1840
+ if (!initialized) {
1841
+ context = await handlers.onFirstChunk(
1842
+ data,
1843
+ yieldData,
1844
+ unlockCloseEvent
1845
+ );
1846
+ initialized = true;
1847
+ } else if (context) {
1848
+ context = await handlers.onChunk(
1849
+ data,
1850
+ context,
1851
+ yieldData,
1852
+ unlockCloseEvent
1853
+ );
1854
+ }
1855
+ lastChunk = data;
1856
+ while (queue.length > 0) {
1857
+ yield { sequence: seq++, data: queue.shift(), done: false };
1858
+ }
1859
+ }
1860
+ };
1861
+ return new _Pump(gen());
1862
+ }
1863
+ /**
1864
+ * Filter items based on a predicate
1865
+ *
1866
+ * @param predicate A function that determines whether to keep each chunk
1867
+ * @returns A new Pump instance containing only chunks that passed the predicate
1868
+ */
1869
+ filter(predicate) {
1870
+ async function* gen() {
1871
+ for await (const { sequence, data, done } of this.src) {
1872
+ if (done) {
1873
+ yield { sequence, data, done: true };
1874
+ break;
1875
+ }
1876
+ const keep = await predicate(data);
1877
+ if (keep) {
1878
+ yield { sequence, data, done: false };
1879
+ }
1880
+ }
1881
+ }
1882
+ return new _Pump(gen.call(this));
1883
+ }
1884
+ /**
1885
+ * Bundles (accumulates) chunks together based on a condition rather than a fixed size.
1886
+ *
1887
+ * This is useful when you need to group chunks dynamically based on their content or other criteria.
1888
+ *
1889
+ * Example: Bundling text chunks with a maximum character limit
1890
+ *
1891
+ * Input chunks: ["Hello", " this", " is", " a few", " chunks", " of text"]
1892
+ * With max size of 10 characters:
1893
+ * - First bundle: ["Hello", " this"] (10 chars)
1894
+ * - Second bundle: [" is", " a few"] (8 chars)
1895
+ * - Third bundle: [" chunks", " of text"] (13 chars)
1896
+ *
1897
+ * @param closeBundleCondition - Function that determines when to close the current bundle
1898
+ * Returns true when the current bundle should be emitted
1899
+ * Parameters:
1900
+ * - chunk: The current chunk being processed
1901
+ * - accumulatedChunks: Array of chunks in the current bundle
1902
+ *
1903
+ * @returns A pump that emits arrays of bundled items
1904
+ */
1905
+ bundle(closeBundleCondition) {
1906
+ async function* gen() {
1907
+ let buffer = [];
1908
+ let lastSequence = 0;
1909
+ for await (const { sequence, data, done } of this.src) {
1910
+ lastSequence = sequence;
1911
+ if (done) {
1912
+ if (buffer.length > 0) {
1913
+ yield { sequence, data: [...buffer], done: false };
1914
+ }
1915
+ yield {
1916
+ sequence: lastSequence,
1917
+ data: void 0,
1918
+ done: true
1919
+ };
1920
+ break;
1921
+ }
1922
+ const shouldClose = await closeBundleCondition(data, buffer);
1923
+ buffer.push(data);
1924
+ if (shouldClose) {
1925
+ yield {
1926
+ sequence: lastSequence,
1927
+ data: [...buffer],
1928
+ done: false
1929
+ };
1930
+ buffer = [];
1931
+ }
1932
+ }
1933
+ }
1934
+ return new _Pump(gen.call(this));
1935
+ }
1936
+ /**
1937
+ * Tap into each chunk without altering it
1938
+ *
1939
+ * @param fn A function that receives each chunk but doesn't affect the stream
1940
+ * @returns The same pump instance with unmodified data
1941
+ */
1942
+ onChunk(fn) {
1943
+ async function* gen() {
1944
+ for await (const chunk of this.src) {
1945
+ if (chunk.data === void 0 && chunk.done) {
1946
+ yield chunk;
1947
+ }
1948
+ await fn(chunk.data);
1949
+ yield chunk;
1950
+ }
1951
+ }
1952
+ return new _Pump(gen.call(this));
1953
+ }
1954
+ /**
1955
+ * Collect all chunks in the stream and run a callback when the stream is done.
1956
+ * The callback receives an array of all chunks that passed through.
1957
+ *
1958
+ * This is useful for analytics, logging, or processing the complete stream history
1959
+ * after all chunks have been received.
1960
+ *
1961
+ * @param fn - Callback function that receives the array of all chunks when the stream is complete
1962
+ * @returns The same pump, for chaining
1963
+ */
1964
+ onClose(fn) {
1965
+ async function* gen() {
1966
+ const history = [];
1967
+ for await (const chunk of this.src) {
1968
+ if (chunk.data !== void 0) {
1969
+ history.push(chunk.data);
1970
+ }
1971
+ if (chunk.done) {
1972
+ await fn(history);
1973
+ }
1974
+ yield chunk;
1975
+ }
1976
+ }
1977
+ return new _Pump(gen.call(this));
1978
+ }
1979
+ /**
1980
+ * Batch `n` chunks into arrays before emitting
1981
+ *
1982
+ * @param n The number of chunks to batch together
1983
+ * @returns A new Pump instance that emits arrays of batched chunks
1984
+ */
1985
+ batch(n) {
1986
+ async function* gen() {
1987
+ let buffer = [];
1988
+ for await (const chunk of this.src) {
1989
+ if (chunk.done) {
1990
+ if (chunk.data === void 0) {
1991
+ yield {
1992
+ sequence: buffer[0].sequence,
1993
+ data: buffer.map((c) => c.data),
1994
+ done: false
1995
+ };
1996
+ yield {
1997
+ sequence: chunk.sequence,
1998
+ data: void 0,
1999
+ done: true
2000
+ };
2001
+ buffer = [];
2002
+ } else {
2003
+ buffer.push(chunk);
2004
+ yield {
2005
+ sequence: buffer[0].sequence,
2006
+ data: buffer.map((c) => c.data),
2007
+ done: true
2008
+ };
2009
+ }
2010
+ break;
2011
+ }
2012
+ buffer.push(chunk);
2013
+ if (buffer.length === n) {
2014
+ yield {
2015
+ sequence: buffer[0].sequence,
2016
+ data: buffer.map((c) => c.data),
2017
+ done: chunk.done
2018
+ };
2019
+ buffer = [];
2020
+ }
2021
+ }
2022
+ }
2023
+ return new _Pump(gen.call(this));
2024
+ }
2025
+ /**
2026
+ * If you want to prevent chunk starvation, you can buffer the chunks.
2027
+ * Chunks will not be bundled into arrays or object but kept as is,
2028
+ * but the pipeline will not progress at that segment until the buffer is filled up.
2029
+ * Once a buffer is filled up it will drain and never buffer again.
2030
+ *
2031
+ * @param n The number of chunks to buffer before processing continues
2032
+ * @returns A new Pump instance with buffering behavior
2033
+ */
2034
+ buffer(n) {
2035
+ async function* gen() {
2036
+ let buffer = [];
2037
+ let bufferFilled = false;
2038
+ for await (const chunk of this.src) {
2039
+ if (!bufferFilled) {
2040
+ if (!chunk.done) {
2041
+ buffer.push(chunk);
2042
+ }
2043
+ if (buffer.length >= n || chunk.done) {
2044
+ bufferFilled = true;
2045
+ for (const bufferedChunk of buffer) {
2046
+ yield bufferedChunk;
2047
+ }
2048
+ if (chunk.done) {
2049
+ yield {
2050
+ sequence: chunk.sequence,
2051
+ data: void 0,
2052
+ done: true
2053
+ };
2054
+ break;
2055
+ }
2056
+ buffer = [];
2057
+ }
2058
+ } else {
2059
+ yield chunk;
2060
+ }
2061
+ }
2062
+ for (const bufferedChunk of buffer) {
2063
+ yield bufferedChunk;
2064
+ }
2065
+ }
2066
+ return new _Pump(gen.call(this));
2067
+ }
2068
+ /**
2069
+ * Rechunk the stream: transform one chunk into zero, one, or many output chunks.
2070
+ * The handler function receives the current buffer of chunks, a push function to emit new chunks,
2071
+ * and a flag indicating if this is the last chunk in the stream.
2072
+ *
2073
+ * @param handler Function that transforms chunks and pushes new ones
2074
+ * @returns A new Pump instance with rechunked data
2075
+ */
2076
+ rechunk(handler) {
2077
+ async function* gen() {
2078
+ let buffer = [];
2079
+ let seq = 0;
2080
+ const pending = [];
2081
+ const push = (chunk) => {
2082
+ pending.push(chunk);
2083
+ };
2084
+ for await (const { data, done } of this.src) {
2085
+ if (!done) {
2086
+ if (data !== void 0) {
2087
+ buffer.push(data);
2088
+ }
2089
+ await handler({
2090
+ buffer,
2091
+ push,
2092
+ lastChunk: false,
2093
+ setBuffer: (b) => {
2094
+ buffer = b;
2095
+ }
2096
+ });
2097
+ } else {
2098
+ await handler({
2099
+ buffer,
2100
+ push,
2101
+ lastChunk: true,
2102
+ setBuffer: (b) => {
2103
+ buffer = b;
2104
+ }
2105
+ });
2106
+ }
2107
+ while (pending.length > 0) {
2108
+ const out = pending.shift();
2109
+ yield { sequence: seq++, data: out, done: false };
2110
+ }
2111
+ if (done) {
2112
+ break;
2113
+ }
2114
+ }
2115
+ yield { sequence: seq, data: void 0, done: true };
2116
+ }
2117
+ return new _Pump(gen.call(this));
2118
+ }
2119
+ slidingWindow(size, step, fn) {
2120
+ async function* gen() {
2121
+ const history = [];
2122
+ let offset = 0;
2123
+ let lastSeq = 0;
2124
+ function buildWindow(_offset, _size, _history) {
2125
+ const window = Array(_size).fill(void 0);
2126
+ let windowIndex = 0;
2127
+ for (let i = _offset; i > _offset - _size; i -= step) {
2128
+ if (i >= history.length) {
2129
+ windowIndex++;
2130
+ continue;
2131
+ }
2132
+ if (i < 0) {
2133
+ break;
2134
+ }
2135
+ window[windowIndex] = _history[i];
2136
+ windowIndex++;
2137
+ }
2138
+ return window;
2139
+ }
2140
+ for await (const { sequence, data, done } of this.src) {
2141
+ if (done) {
2142
+ for (let i = 0; i < size - 1; i++) {
2143
+ const window2 = buildWindow(offset + i, size, history);
2144
+ yield { sequence: lastSeq, data: window2, done: false };
2145
+ }
2146
+ if (data === void 0) {
2147
+ yield {
2148
+ sequence: lastSeq,
2149
+ data: void 0,
2150
+ done: true
2151
+ };
2152
+ } else {
2153
+ yield {
2154
+ sequence: lastSeq,
2155
+ data: [
2156
+ history[history.length - 2] ?? void 0,
2157
+ history[history.length - 3] ?? void 0,
2158
+ history[history.length - 1]
2159
+ ],
2160
+ done: true
2161
+ };
2162
+ }
2163
+ break;
2164
+ }
2165
+ lastSeq = sequence;
2166
+ history.push(data);
2167
+ const window = buildWindow(offset, size, history);
2168
+ yield { sequence, data: window, done: false };
2169
+ offset++;
2170
+ }
2171
+ }
2172
+ const base = new _Pump(gen.call(this));
2173
+ return fn ? base.map(fn) : base;
2174
+ }
2175
+ /**
2176
+ * Sequentially flatten inner stream sources emitted by the pipeline.
2177
+ * Works with any Source type (AsyncIterable or ReadableStream).
2178
+ * This method is only available when the current Pump contains Source elements.
2179
+ *
2180
+ * @template U The type of data in the inner streams
2181
+ * @template F The type of inner stream source (extends Source<U>)
2182
+ * @returns A Pump instance with flattened stream data
2183
+ */
2184
+ sequenceStreams() {
2185
+ async function* gen() {
2186
+ let seq = 0;
2187
+ for await (const { data: innerSource, done: outerDone } of this.src) {
2188
+ if (outerDone)
2189
+ break;
2190
+ const innerPump = _Pump.from(innerSource);
2191
+ for await (const { data, done } of innerPump.src) {
2192
+ if (done)
2193
+ break;
2194
+ yield { sequence: seq++, data, done: false };
2195
+ }
2196
+ }
2197
+ yield { sequence: seq, data: void 0, done: true };
2198
+ }
2199
+ return new _Pump(gen.call(this));
2200
+ }
2201
+ /**
2202
+ * Fork the stream: two independent Pump<T> consumers
2203
+ * Both resulting Pumps will receive the same data, allowing for divergent processing paths.
2204
+ *
2205
+ * @returns An array containing two independent Pump instances with the same source data
2206
+ */
2207
+ fork() {
2208
+ const buffers = [[], []];
2209
+ let done = false;
2210
+ const srcIter = this.src[Symbol.asyncIterator]();
2211
+ async function fill() {
2212
+ const { value, done: streamDone } = await srcIter.next();
2213
+ if (streamDone) {
2214
+ done = true;
2215
+ return;
2216
+ }
2217
+ buffers.forEach((q) => q.push(value));
2218
+ if (value.done)
2219
+ done = true;
2220
+ }
2221
+ function makeStream(buf) {
2222
+ return {
2223
+ [Symbol.asyncIterator]() {
2224
+ return {
2225
+ async next() {
2226
+ while (buf.length === 0 && !done) {
2227
+ await fill();
2228
+ }
2229
+ if (buf.length === 0)
2230
+ return {
2231
+ done: true,
2232
+ value: void 0
2233
+ };
2234
+ return { done: false, value: buf.shift() };
2235
+ }
2236
+ };
2237
+ }
2238
+ };
2239
+ }
2240
+ return [new _Pump(makeStream(buffers[0])), new _Pump(makeStream(buffers[1]))];
2241
+ }
2242
+ /**
2243
+ * Drain the pipeline, consuming all chunks.
2244
+ * Returns a Promise that resolves when all chunks have been consumed.
2245
+ *
2246
+ * @returns A Promise that resolves when all chunks have been consumed
2247
+ */
2248
+ drain() {
2249
+ return (async () => {
2250
+ for await (const { done } of this.src) {
2251
+ if (done)
2252
+ break;
2253
+ }
2254
+ })();
2255
+ }
2256
+ /**
2257
+ * Drain the pipeline to a StreamTransformer.
2258
+ * Applies transform() to each data chunk, then closes the transformer,
2259
+ * and returns its response (which can be of any type defined by the transformer).
2260
+ *
2261
+ * Example with httpStreamResponse:
2262
+ * ```
2263
+ * const { transform, response, close } = httpStreamResponse(options);
2264
+ * return Pump.from(messageStream).drainTo({ transform, close, response });
2265
+ * ```
2266
+ *
2267
+ * @template U The type of data expected by the transformer (extends T)
2268
+ * @template R The response type produced by the transformer
2269
+ * @param transformer The StreamTransformer to drain to
2270
+ * @returns The response from the transformer
2271
+ */
2272
+ drainTo(transformer) {
2273
+ (async () => {
2274
+ for await (const { data, done } of this.src) {
2275
+ if (done)
2276
+ break;
2277
+ transformer.transform(data);
2278
+ }
2279
+ transformer.close();
2280
+ })();
2281
+ return transformer.response;
2282
+ }
2283
+ };
2284
+
2285
+ // src/stream/utility/pipe-transformers/response.ts
2286
+ function httpStreamResponse(options = {}) {
2287
+ const { init, encoder } = options;
2288
+ const encodeFn = encoder ?? ((d) => {
2289
+ if (d instanceof Uint8Array)
2290
+ return d;
2291
+ if (typeof d === "string")
2292
+ return d;
2293
+ return JSON.stringify(d);
2294
+ });
2295
+ const { readable, writable } = new TransformStream();
2296
+ const writer = writable.getWriter();
2297
+ const response = new Response(readable, init);
2298
+ const transform = (chunk) => {
2299
+ const encoded = encodeFn(chunk);
2300
+ const bytes = typeof encoded === "string" ? new TextEncoder().encode(encoded) : encoded;
2301
+ writer.write(bytes);
2302
+ return chunk;
2303
+ };
2304
+ const close = () => {
2305
+ writer.close();
2306
+ };
2307
+ return { transform, response, close };
2308
+ }
2309
+
2310
+ // src/stream/utility/rechunker/ensure-full-words.ts
2311
+ async function ensureFullWords({
2312
+ buffer,
2313
+ push,
2314
+ lastChunk
2315
+ }) {
2316
+ const combined = buffer.join("");
2317
+ const lastBoundary = Math.max(
2318
+ combined.lastIndexOf(" "),
2319
+ combined.lastIndexOf("\n"),
2320
+ combined.lastIndexOf(" ")
2321
+ );
2322
+ if (lastBoundary !== -1 || lastChunk) {
2323
+ const emitPart = lastBoundary !== -1 ? combined.slice(0, lastBoundary + 1) : combined;
2324
+ const leftoverPart = lastBoundary !== -1 ? combined.slice(lastBoundary + 1) : "";
2325
+ if (emitPart.trim().length > 0) {
2326
+ push(emitPart);
2327
+ }
2328
+ buffer.length = 0;
2329
+ if (leftoverPart.length > 0) {
2330
+ buffer.push(leftoverPart);
2331
+ }
2332
+ }
2333
+ }
2334
+
2335
+ // src/api/socket-handler/SocketIoFactory.ts
2336
+ var SocketIoFactory = class _SocketIoFactory {
2337
+ constructor(socket, prefix, hooks) {
2338
+ this.socket = socket;
2339
+ this.prefix = prefix;
2340
+ this.hooks = hooks;
2341
+ }
2342
+ static setupSocketHandlers({
2343
+ enableVoiceEvents,
2344
+ enableChatEvents,
2345
+ enableTranscriptEvents,
2346
+ prefix = "",
2347
+ socket,
2348
+ hooks
2349
+ }) {
2350
+ const factory = new _SocketIoFactory(socket, prefix, hooks);
2351
+ if (enableVoiceEvents) {
2352
+ factory.setupVoiceEvents();
2353
+ }
2354
+ if (enableChatEvents) {
2355
+ factory.setupChatEvents(socket);
2356
+ }
2357
+ if (enableTranscriptEvents) {
2358
+ factory.setupTranscriptEvents(socket);
2359
+ }
2360
+ }
2361
+ setupVoiceEvents() {
2362
+ const {
2363
+ onVoiceInputFile,
2364
+ onVoiceInputChunk,
2365
+ onVoiceInputCommit,
2366
+ onVoiceOutputDelta,
2367
+ onVoiceOutputCommit,
2368
+ onVoiceOutputFile,
2369
+ onVoiceOutputTranscriptDelta,
2370
+ onVoiceOutputTranscriptFull
2371
+ } = this.hooks;
2372
+ const prefix = this.prefixEvent;
2373
+ if (onVoiceInputFile) {
2374
+ this.socket.on(prefix("voice:input_file"), onVoiceInputFile);
2375
+ }
2376
+ if (onVoiceInputChunk) {
2377
+ this.socket.on(prefix("voice:input_chunk"), onVoiceInputChunk);
2378
+ }
2379
+ if (onVoiceInputCommit) {
2380
+ this.socket.on(prefix("voice:input_commit"), onVoiceInputCommit);
2381
+ }
2382
+ if (onVoiceOutputDelta) {
2383
+ this.socket.on(prefix("voice:output_delta"), onVoiceOutputDelta);
2384
+ }
2385
+ if (onVoiceOutputCommit) {
2386
+ this.socket.on(prefix("voice:output_commit"), onVoiceOutputCommit);
2387
+ }
2388
+ if (onVoiceOutputFile) {
2389
+ this.socket.on(prefix("voice:output_file"), onVoiceOutputFile);
2390
+ }
2391
+ if (onVoiceOutputTranscriptDelta) {
2392
+ this.socket.on(
2393
+ prefix("voice:output_transcript_delta"),
2394
+ onVoiceOutputTranscriptDelta
2395
+ );
2396
+ }
2397
+ if (onVoiceOutputTranscriptFull) {
2398
+ this.socket.on(
2399
+ prefix("voice:output_transcript_full"),
2400
+ onVoiceOutputTranscriptFull
2401
+ );
2402
+ }
2403
+ }
2404
+ setupChatEvents(_socket) {
2405
+ }
2406
+ setupTranscriptEvents(_socket) {
2407
+ }
2408
+ prefixEvent(event) {
2409
+ return this.prefix ? `${this.prefix}:${event}` : event;
2410
+ }
2411
+ };
2412
+ var humanAndAI = (message) => message instanceof messages.HumanMessage || message instanceof messages.AIMessage;
2413
+ var humanOnly = (message) => message instanceof messages.HumanMessage;
2414
+ var aiOnly = (message) => message instanceof messages.AIMessage;
2415
+ var includingTags = (message, tags) => {
2416
+ if (tags) {
2417
+ return tags.some(
2418
+ (tag) => Array.isArray(message.additional_kwargs?.tags) ? message.additional_kwargs?.tags.includes(tag) : false
2419
+ );
2420
+ }
2421
+ return true;
2422
+ };
2423
+ var excludingTags = (message, tags) => {
2424
+ if (tags) {
2425
+ return !tags.some(
2426
+ (tag) => Array.isArray(message.additional_kwargs?.tags) ? message.additional_kwargs?.tags.includes(tag) : false
2427
+ );
2428
+ }
2429
+ return true;
2430
+ };
2431
+ var typeOnFilter = {
2432
+ ["HumanAndAI" /* HumanAndAI */]: humanAndAI,
2433
+ ["HumanOnly" /* HumanOnly */]: humanOnly,
2434
+ ["AIOnly" /* AIOnly */]: aiOnly,
2435
+ ["IncludingTags" /* IncludingTags */]: includingTags,
2436
+ ["ExcludingTags" /* ExcludingTags */]: excludingTags
2437
+ };
2438
+ function concise(messages$1) {
2439
+ return messages$1.map((message) => {
2440
+ const prefix = message instanceof messages.AIMessage ? "AI" : "Human";
2441
+ return `${prefix}: ${message.content}`;
2442
+ }).join("\n");
2443
+ }
2444
+ function verbose(messages$1) {
2445
+ return messages$1.map((message) => {
2446
+ const prefix = message instanceof messages.AIMessage ? "AI" : "Human";
2447
+ return `${prefix}:
2448
+ ${message.content}`;
2449
+ }).join("\n-------------------\n");
2450
+ }
2451
+ function redactAi(messages$1) {
2452
+ return messages$1.map((message) => {
2453
+ const prefix = message instanceof messages.AIMessage ? "AI" : "Human";
2454
+ const content = message instanceof messages.AIMessage ? "[...]" : message.content;
2455
+ return `${prefix}: ${content}`;
2456
+ }).join("\n");
2457
+ }
2458
+ function redactHuman(messages$1) {
2459
+ return messages$1.map((message) => {
2460
+ const prefix = message instanceof messages.AIMessage ? "AI" : "Human";
2461
+ const content = message instanceof messages.AIMessage ? "[...]" : message.content;
2462
+ return `${prefix}: ${content}`;
2463
+ }).join("\n");
2464
+ }
2465
+ var typeOnFormatter = {
2466
+ ["concise" /* Concise */]: concise,
2467
+ ["verbose" /* Verbose */]: verbose,
2468
+ ["redact-ai" /* RedactAi */]: redactAi,
2469
+ ["redact-human" /* RedactHuman */]: redactHuman
2470
+ };
2471
+
2472
+ // src/helper/transform-messages/TransformMessages.ts
2473
+ var TransformMessages = class _TransformMessages {
2474
+ constructor(effect) {
2475
+ this.effect = effect;
2476
+ }
2477
+ /**
2478
+ * Create a new TransformMessages from an array of messages.
2479
+ */
2480
+ static from(messages) {
2481
+ return new _TransformMessages(effect.Effect.succeed(messages));
2482
+ }
2483
+ /**
2484
+ * Filter messages based on a predicate function
2485
+ */
2486
+ filter(predicate, tags) {
2487
+ let finalPredicate;
2488
+ if (typeof predicate === "string") {
2489
+ finalPredicate = typeOnFilter[predicate];
2490
+ } else {
2491
+ finalPredicate = predicate;
2492
+ }
2493
+ return new _TransformMessages(
2494
+ effect.pipe(
2495
+ this.effect,
2496
+ effect.Effect.map(
2497
+ (messages) => messages.filter((message) => finalPredicate(message, tags))
2498
+ )
2499
+ )
2500
+ );
2501
+ }
2502
+ /**
2503
+ * Take only the last n messages, but safely.
2504
+ * Tool calls should not be separated from the last human message.
2505
+ * Ensures all tool call conversations in the last n messages are complete.
2506
+ */
2507
+ safelyTakeLast(n, pruneAfterNOvershootingMessages = 0) {
2508
+ return new _TransformMessages(
2509
+ effect.pipe(
2510
+ this.effect,
2511
+ effect.Effect.map((messages$1) => {
2512
+ const total = messages$1.length;
2513
+ if (n <= 0 || total === 0)
2514
+ return [];
2515
+ const start = Math.max(0, total - n);
2516
+ const end = total;
2517
+ const lastSlice = messages$1.slice(start, end);
2518
+ if (lastSlice[0] instanceof messages.ToolMessage && lastSlice[0].tool_call_id) {
2519
+ let messagesToInclude = [];
2520
+ const remainingMessages = messages$1.slice(0, start);
2521
+ for (let i = remainingMessages.length - 1; i >= 0; i--) {
2522
+ const msg = remainingMessages[i];
2523
+ if (pruneAfterNOvershootingMessages > 0 && messagesToInclude.length - 1 >= pruneAfterNOvershootingMessages) {
2524
+ messagesToInclude = [];
2525
+ const filteredSlice = [];
2526
+ let foundFirstNonToolMessage = false;
2527
+ for (let i2 = 0; i2 < lastSlice.length; i2++) {
2528
+ const msg2 = lastSlice[i2];
2529
+ if (msg2 instanceof messages.ToolMessage) {
2530
+ if (foundFirstNonToolMessage) {
2531
+ filteredSlice.push(msg2);
2532
+ }
2533
+ } else {
2534
+ foundFirstNonToolMessage = true;
2535
+ filteredSlice.push(msg2);
2536
+ }
2537
+ }
2538
+ return filteredSlice;
2539
+ }
2540
+ if (msg instanceof messages.AIMessage && Array.isArray(msg.tool_calls)) {
2541
+ messagesToInclude.push(msg);
2542
+ break;
2543
+ } else if (msg instanceof messages.ToolMessage) {
2544
+ messagesToInclude.push(msg);
2545
+ } else {
2546
+ throw new Error(
2547
+ "Messages array invalid no adjacent AI message found"
2548
+ );
2549
+ }
2550
+ }
2551
+ return [...messagesToInclude.reverse(), ...lastSlice];
2552
+ } else {
2553
+ return lastSlice;
2554
+ }
2555
+ })
2556
+ )
2557
+ );
2558
+ }
2559
+ /**
2560
+ * Take only the last n messages
2561
+ */
2562
+ last(n) {
2563
+ return new _TransformMessages(
2564
+ effect.pipe(
2565
+ this.effect,
2566
+ effect.Effect.map((messages) => messages.slice(-n))
2567
+ )
2568
+ );
2569
+ }
2570
+ /**
2571
+ * Take only the first n messages
2572
+ */
2573
+ first(n) {
2574
+ return new _TransformMessages(
2575
+ effect.pipe(
2576
+ this.effect,
2577
+ effect.Effect.map((messages) => messages.slice(0, n))
2578
+ )
2579
+ );
2580
+ }
2581
+ /**
2582
+ * Skip the first n messages
2583
+ */
2584
+ skip(n) {
2585
+ return new _TransformMessages(
2586
+ effect.pipe(
2587
+ this.effect,
2588
+ effect.Effect.map((messages) => messages.slice(n))
2589
+ )
2590
+ );
2591
+ }
2592
+ /**
2593
+ * Reverse the order of messages
2594
+ */
2595
+ reverse() {
2596
+ return new _TransformMessages(
2597
+ effect.pipe(
2598
+ this.effect,
2599
+ effect.Effect.map((messages) => [...messages].reverse())
2600
+ )
2601
+ );
2602
+ }
2603
+ /**
2604
+ * Map over messages with a transformation function
2605
+ */
2606
+ map(fn) {
2607
+ return new _TransformMessages(
2608
+ effect.pipe(
2609
+ this.effect,
2610
+ effect.Effect.map((messages) => messages.map(fn))
2611
+ )
2612
+ );
2613
+ }
2614
+ /**
2615
+ * Format messages according to the specified format type
2616
+ */
2617
+ format(formatType) {
2618
+ return effect.pipe(
2619
+ this.effect,
2620
+ effect.Effect.map((messages) => {
2621
+ if (formatType === "json" /* JSON */) {
2622
+ return JSON.stringify(messages, null, 2);
2623
+ }
2624
+ const formatter = typeOnFormatter[formatType];
2625
+ return formatter(messages);
2626
+ })
2627
+ );
2628
+ }
2629
+ // Sink methods
2630
+ /**
2631
+ * Convert to array - runs the effect and returns the result
2632
+ */
2633
+ toArray() {
2634
+ return this.effect;
2635
+ }
2636
+ /**
2637
+ * Convert to string - runs the effect and returns JSON string
2638
+ */
2639
+ toString() {
2640
+ return effect.pipe(
2641
+ this.effect,
2642
+ effect.Effect.map((messages) => JSON.stringify(messages, null, 2))
2643
+ );
2644
+ }
2645
+ /**
2646
+ * Get the count of messages
2647
+ */
2648
+ count() {
2649
+ return effect.pipe(
2650
+ this.effect,
2651
+ effect.Effect.map((messages) => messages.length)
2652
+ );
2653
+ }
2654
+ };
2655
+
2656
+ exports.AiCursor = AiCursor;
2657
+ exports.BaseVoiceEndpointAdapter = BaseVoiceEndpointAdapter;
2658
+ exports.Emitter = Emitter;
2659
+ exports.InputAudioController = InputAudioController;
2660
+ exports.Pump = Pump;
2661
+ exports.SocketIoFactory = SocketIoFactory;
2662
+ exports.TransformMessages = TransformMessages;
2663
+ exports.VoiceEndpointAdapter = VoiceEndpointAdapter;
2664
+ exports.VoiceSocketAdapter = VoiceSocketAdapter;
2665
+ exports.ensureFullWords = ensureFullWords;
2666
+ exports.httpStreamResponse = httpStreamResponse;
2667
+ exports.useConversation = useConversation;
2668
+ exports.useSocketConversation = useSocketConversation;
2669
+ //# sourceMappingURL=out.js.map
2670
+ //# sourceMappingURL=index.cjs.map