@elevenlabs/client 0.9.2 → 0.11.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/.turbo/turbo-build.log +9 -9
- package/.turbo/turbo-generate-version.log +1 -1
- package/README.md +30 -23
- package/dist/index.d.ts +1 -1
- package/dist/lib.cjs +1 -1
- package/dist/lib.cjs.map +1 -1
- package/dist/lib.modern.js +1 -1
- package/dist/lib.modern.js.map +1 -1
- package/dist/lib.module.js +1 -1
- package/dist/lib.module.js.map +1 -1
- package/dist/lib.umd.js +1 -1
- package/dist/lib.umd.js.map +1 -1
- package/dist/scribe/connection.d.ts +15 -13
- package/dist/scribe/index.d.ts +1 -1
- package/dist/scribe/scribe.d.ts +7 -2
- package/dist/version.d.ts +1 -1
- package/package.json +2 -2
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
|
|
2
|
-
> @elevenlabs/client@0.
|
|
2
|
+
> @elevenlabs/client@0.11.0 prebuild /home/runner/work/packages/packages/packages/client
|
|
3
3
|
> npm run generate-version && npm run generate-worklets
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
> @elevenlabs/client@0.
|
|
6
|
+
> @elevenlabs/client@0.11.0 generate-version
|
|
7
7
|
> printf "// This file is auto-generated during build\nexport const PACKAGE_VERSION = \"%s\";\n" "$npm_package_version" > src/version.ts
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
> @elevenlabs/client@0.
|
|
10
|
+
> @elevenlabs/client@0.11.0 generate-worklets
|
|
11
11
|
> node scripts/generateWorklets.js
|
|
12
12
|
|
|
13
13
|
Generating TypeScript worklet files...
|
|
@@ -16,15 +16,15 @@ Generated audioConcatProcessor.generated.ts from audioConcatProcessor.js
|
|
|
16
16
|
Generated scribeAudioProcessor.generated.ts from scribeAudioProcessor.js
|
|
17
17
|
Worklet generation complete!
|
|
18
18
|
|
|
19
|
-
> @elevenlabs/client@0.
|
|
19
|
+
> @elevenlabs/client@0.11.0 build /home/runner/work/packages/packages/packages/client
|
|
20
20
|
> BROWSERSLIST_ENV=modern microbundle --jsx React.createElement --jsxFragment React.Fragment --jsxImportSource react src/index.ts
|
|
21
21
|
|
|
22
22
|
Build "@elevenlabs/client" to dist:
|
|
23
23
|
13.6 kB: lib.cjs.gz
|
|
24
24
|
12.1 kB: lib.cjs.br
|
|
25
|
-
12.
|
|
25
|
+
12.3 kB: lib.modern.js.gz
|
|
26
26
|
11 kB: lib.modern.js.br
|
|
27
|
-
13.
|
|
28
|
-
|
|
29
|
-
13.
|
|
30
|
-
12.
|
|
27
|
+
13.6 kB: lib.module.js.gz
|
|
28
|
+
12.1 kB: lib.module.js.br
|
|
29
|
+
13.7 kB: lib.umd.js.gz
|
|
30
|
+
12.2 kB: lib.umd.js.br
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
|
|
2
|
-
> @elevenlabs/client@0.
|
|
2
|
+
> @elevenlabs/client@0.11.0 generate-version /home/runner/work/packages/packages/packages/client
|
|
3
3
|
> printf "// This file is auto-generated during build\nexport const PACKAGE_VERSION = \"%s\";\n" "$npm_package_version" > src/version.ts
|
|
4
4
|
|
package/README.md
CHANGED
|
@@ -445,8 +445,6 @@ await conversation.changeOutputDevice({
|
|
|
445
445
|
|
|
446
446
|
Scribe is ElevenLabs' real-time speech-to-text API that provides low-latency transcription with support for both streaming microphone input and pre-recorded audio files.
|
|
447
447
|
|
|
448
|
-
**Note:** Scribe Realtime v2 is currently in closed beta. For access please [contact sales](https://elevenlabs.io/contact-sales).
|
|
449
|
-
|
|
450
448
|
### Quick Start
|
|
451
449
|
|
|
452
450
|
```js
|
|
@@ -455,7 +453,7 @@ import { Scribe, RealtimeEvents } from "@elevenlabs/client";
|
|
|
455
453
|
// Connect with microphone streaming
|
|
456
454
|
const connection = Scribe.connect({
|
|
457
455
|
token: "your-token",
|
|
458
|
-
modelId: "
|
|
456
|
+
modelId: "scribe_v2_realtime",
|
|
459
457
|
microphone: {
|
|
460
458
|
echoCancellation: true,
|
|
461
459
|
noiseSuppression: true,
|
|
@@ -467,8 +465,8 @@ connection.on(RealtimeEvents.PARTIAL_TRANSCRIPT, (data) => {
|
|
|
467
465
|
console.log("Partial:", data.text);
|
|
468
466
|
});
|
|
469
467
|
|
|
470
|
-
connection.on(RealtimeEvents.
|
|
471
|
-
console.log("
|
|
468
|
+
connection.on(RealtimeEvents.COMMITTED_TRANSCRIPT, (data) => {
|
|
469
|
+
console.log("Committed:", data.text);
|
|
472
470
|
});
|
|
473
471
|
|
|
474
472
|
// Close connection when done
|
|
@@ -516,7 +514,7 @@ import { Scribe, RealtimeEvents } from "@elevenlabs/client";
|
|
|
516
514
|
|
|
517
515
|
const connection = Scribe.connect({
|
|
518
516
|
token: "your-token",
|
|
519
|
-
modelId: "
|
|
517
|
+
modelId: "scribe_v2_realtime",
|
|
520
518
|
microphone: {
|
|
521
519
|
deviceId: "optional-device-id", // Optional: specific microphone
|
|
522
520
|
echoCancellation: true,
|
|
@@ -538,7 +536,7 @@ import { Scribe, AudioFormat, RealtimeEvents } from "@elevenlabs/client";
|
|
|
538
536
|
|
|
539
537
|
const connection = Scribe.connect({
|
|
540
538
|
token: "your-token",
|
|
541
|
-
modelId: "
|
|
539
|
+
modelId: "scribe_v2_realtime",
|
|
542
540
|
audioFormat: AudioFormat.PCM_16000,
|
|
543
541
|
sampleRate: 16000,
|
|
544
542
|
});
|
|
@@ -591,20 +589,18 @@ connection.on(RealtimeEvents.SESSION_STARTED, () => {
|
|
|
591
589
|
// Partial transcripts (interim results)
|
|
592
590
|
connection.on(RealtimeEvents.PARTIAL_TRANSCRIPT, (data) => {
|
|
593
591
|
console.log("Partial:", data.text);
|
|
594
|
-
// { text: string, language_code?: string }
|
|
595
592
|
});
|
|
596
593
|
|
|
597
|
-
//
|
|
598
|
-
connection.on(RealtimeEvents.
|
|
599
|
-
console.log("
|
|
600
|
-
// { text: string, language_code?: string }
|
|
594
|
+
// Committed transcripts
|
|
595
|
+
connection.on(RealtimeEvents.COMMITTED_TRANSCRIPT, (data) => {
|
|
596
|
+
console.log("Committed:", data.text);
|
|
601
597
|
});
|
|
602
598
|
|
|
603
|
-
//
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
console.log("
|
|
607
|
-
|
|
599
|
+
// Committed transcripts with word-level timestamps
|
|
600
|
+
// Only received when `includeTimestamps = true`
|
|
601
|
+
connection.on(RealtimeEvents.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS, (data) => {
|
|
602
|
+
console.log("Committed:", data.text);
|
|
603
|
+
console.log("Timestamps:", data.words);
|
|
608
604
|
});
|
|
609
605
|
|
|
610
606
|
// Errors
|
|
@@ -626,6 +622,11 @@ connection.on(RealtimeEvents.OPEN, () => {
|
|
|
626
622
|
connection.on(RealtimeEvents.CLOSE, () => {
|
|
627
623
|
console.log("Connection closed");
|
|
628
624
|
});
|
|
625
|
+
|
|
626
|
+
// Quota exceeded
|
|
627
|
+
connection.on(RealtimeEvents.QUOTA_EXCEEDED, (data) => {
|
|
628
|
+
console.log("Quota exceeded:", data.error)
|
|
629
|
+
})
|
|
629
630
|
```
|
|
630
631
|
|
|
631
632
|
### Configuration Options
|
|
@@ -637,7 +638,7 @@ All connection modes support these options:
|
|
|
637
638
|
```js
|
|
638
639
|
const connection = await scribe.connect({
|
|
639
640
|
token: "your-token", // Required: Single-use token
|
|
640
|
-
modelId: "
|
|
641
|
+
modelId: "scribe_v2_realtime", // Required: Model ID
|
|
641
642
|
baseUri: "wss://api.elevenlabs.io", // Optional: Custom endpoint
|
|
642
643
|
|
|
643
644
|
// Voice Activity Detection (VAD) settings
|
|
@@ -648,6 +649,8 @@ const connection = await scribe.connect({
|
|
|
648
649
|
minSilenceDurationMs: 500, // Minimum silence to detect pause
|
|
649
650
|
|
|
650
651
|
languageCode: "en", // ISO 639-1 language code
|
|
652
|
+
|
|
653
|
+
includeTimestamps: true // Whether to receive the committed_transcript_with_timestamps event after committing
|
|
651
654
|
});
|
|
652
655
|
```
|
|
653
656
|
|
|
@@ -691,7 +694,7 @@ import { Scribe, CommitStrategy, RealtimeEvents } from "@elevenlabs/client";
|
|
|
691
694
|
|
|
692
695
|
const connection = Scribe.connect({
|
|
693
696
|
token: "your-token",
|
|
694
|
-
modelId: "
|
|
697
|
+
modelId: "scribe_v2_realtime",
|
|
695
698
|
commitStrategy: CommitStrategy.MANUAL,
|
|
696
699
|
audioFormat: AudioFormat.PCM_16000,
|
|
697
700
|
sampleRate: 16000,
|
|
@@ -712,7 +715,7 @@ import { Scribe, CommitStrategy, RealtimeEvents } from "@elevenlabs/client";
|
|
|
712
715
|
|
|
713
716
|
const connection = Scribe.connect({
|
|
714
717
|
token: "your-token",
|
|
715
|
-
modelId: "
|
|
718
|
+
modelId: "scribe_v2_realtime",
|
|
716
719
|
commitStrategy: CommitStrategy.VAD,
|
|
717
720
|
audioFormat: AudioFormat.PCM_16000,
|
|
718
721
|
sampleRate: 16000,
|
|
@@ -763,12 +766,12 @@ import {
|
|
|
763
766
|
type AudioOptions,
|
|
764
767
|
type MicrophoneOptions,
|
|
765
768
|
type PartialTranscriptMessage,
|
|
766
|
-
type
|
|
769
|
+
type CommittedTranscriptMessage,
|
|
767
770
|
} from "@elevenlabs/client";
|
|
768
771
|
|
|
769
772
|
const connection: RealtimeConnection = await scribe.connect({
|
|
770
773
|
token: "your-token",
|
|
771
|
-
modelId: "
|
|
774
|
+
modelId: "scribe_v2_realtime",
|
|
772
775
|
microphone: {
|
|
773
776
|
echoCancellation: true,
|
|
774
777
|
},
|
|
@@ -785,7 +788,7 @@ import { Scribe, RealtimeEvents } from "@elevenlabs/client";
|
|
|
785
788
|
try {
|
|
786
789
|
const connection = Scribe.connect({
|
|
787
790
|
token: "your-token",
|
|
788
|
-
modelId: "
|
|
791
|
+
modelId: "scribe_v2_realtime",
|
|
789
792
|
microphone: {},
|
|
790
793
|
});
|
|
791
794
|
|
|
@@ -796,6 +799,10 @@ try {
|
|
|
796
799
|
connection.on(RealtimeEvents.AUTH_ERROR, (data) => {
|
|
797
800
|
console.error("Authentication failed:", data.error);
|
|
798
801
|
});
|
|
802
|
+
|
|
803
|
+
connection.on(RealtimeEvents.QUOTA_EXCEEDED, (data) => {
|
|
804
|
+
console.error("Quota exceeded:", data.error);
|
|
805
|
+
});
|
|
799
806
|
} catch (error) {
|
|
800
807
|
console.error("Failed to connect:", error);
|
|
801
808
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ export { postOverallFeedback } from "./utils/postOverallFeedback";
|
|
|
13
13
|
export { VoiceConversation } from "./VoiceConversation";
|
|
14
14
|
export { TextConversation } from "./TextConversation";
|
|
15
15
|
export { Scribe, AudioFormat, CommitStrategy, RealtimeEvents, RealtimeConnection, } from "./scribe";
|
|
16
|
-
export type { AudioOptions, MicrophoneOptions, WebSocketMessage, PartialTranscriptMessage,
|
|
16
|
+
export type { AudioOptions, MicrophoneOptions, WebSocketMessage, PartialTranscriptMessage, CommittedTranscriptMessage, CommittedTranscriptWithTimestampsMessage, ScribeErrorMessage, ScribeAuthErrorMessage, ScribeQuotaExceededErrorMessage, } from "./scribe";
|
|
17
17
|
export declare class Conversation extends BaseConversation {
|
|
18
18
|
static startSession(options: PartialOptions): Promise<Conversation>;
|
|
19
19
|
}
|
package/dist/lib.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=require("livekit-client");function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)({}).hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},t.apply(null,arguments)}function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,o(e,t)}function o(e,t){return o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},o(e,t)}function r(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var i=new Uint8Array(0),a=/*#__PURE__*/function(){function e(e,t){var n=this,o=this,i=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode="listening",this.status="connecting",this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=function(e){try{return"connected"!==o.status&&"connecting"!==o.status?Promise.resolve():(o.updateStatus("disconnecting"),Promise.resolve(o.handleEndSession()).then(function(){o.updateStatus("disconnected"),o.options.onDisconnect&&o.options.onDisconnect(e)}))}catch(e){return Promise.reject(e)}},this.onMessage=function(e){try{switch(e.type){case"interruption":return i.handleInterruption(e),Promise.resolve();case"agent_response":return i.handleAgentResponse(e),Promise.resolve();case"user_transcript":return i.handleUserTranscript(e),Promise.resolve();case"internal_tentative_agent_response":return i.handleTentativeAgentResponse(e),Promise.resolve();case"client_tool_call":var t=r(function(){return Promise.resolve(i.handleClientToolCall(e)).then(function(){})},function(t){i.onError("Unexpected error in client tool call handling: "+(t instanceof Error?t.message:String(t)),{clientToolName:e.client_tool_call.tool_name,toolCallId:e.client_tool_call.tool_call_id})});return Promise.resolve(t&&t.then?t.then(function(){}):void 0);case"audio":return i.handleAudio(e),Promise.resolve();case"vad_score":return i.handleVadScore(e),Promise.resolve();case"ping":return i.connection.sendMessage({type:"pong",event_id:e.ping_event.event_id}),Promise.resolve();case"mcp_tool_call":return i.handleMCPToolCall(e),Promise.resolve();case"mcp_connection_status":return i.handleMCPConnectionStatus(e),Promise.resolve();case"agent_tool_response":return i.handleAgentToolResponse(e),Promise.resolve();case"conversation_initiation_metadata":return i.handleConversationMetadata(e),Promise.resolve();case"asr_initiation_metadata":return i.handleAsrInitiationMetadata(e),Promise.resolve();case"agent_chat_response_part":return i.handleAgentChatResponsePart(e),Promise.resolve();case"error":return i.handleErrorEvent(e),Promise.resolve();default:return i.options.onDebug&&i.options.onDebug(e),Promise.resolve()}}catch(e){return Promise.reject(e)}},this.setVolume=function(e){n.volume=e.volume},this.options=e,this.connection=t,this.options.onConnect&&this.options.onConnect({conversationId:t.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(function(e){return n.updateMode(e)}),this.updateStatus("connected")}e.getFullOptions=function(e){return t({clientTools:{},onConnect:function(){},onDebug:function(){},onDisconnect:function(){},onError:function(){},onMessage:function(){},onAudio:function(){},onModeChange:function(){},onStatusChange:function(){},onCanSendFeedbackChange:function(){},onInterruption:function(){}},e)};var n=e.prototype;return n.endSession=function(){return this.endSessionWithDetails({reason:"user"})},n.handleEndSession=function(){try{return this.connection.close(),Promise.resolve()}catch(e){return Promise.reject(e)}},n.updateMode=function(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))},n.updateStatus=function(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))},n.updateCanSendFeedback=function(){var e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))},n.handleInterruption=function(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))},n.handleAgentResponse=function(e){this.options.onMessage&&this.options.onMessage({source:"ai",message:e.agent_response_event.agent_response})},n.handleUserTranscript=function(e){this.options.onMessage&&this.options.onMessage({source:"user",message:e.user_transcription_event.user_transcript})},n.handleTentativeAgentResponse=function(e){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:e.tentative_agent_response_internal_event.tentative_agent_response})},n.handleVadScore=function(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})},n.handleClientToolCall=function(e){try{var t=this;return Promise.resolve(function(){if(Object.prototype.hasOwnProperty.call(t.options.clientTools,e.client_tool_call.tool_name)){var n=r(function(){return Promise.resolve(t.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters)).then(function(n){var o="object"==typeof n?JSON.stringify(n):String(n);t.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:o,is_error:!1})})},function(n){t.onError("Client tool execution failed with following error: "+(null==n?void 0:n.message),{clientToolName:e.client_tool_call.tool_name}),t.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:"Client tool execution failed: "+(null==n?void 0:n.message),is_error:!0})});if(n&&n.then)return n.then(function(){})}else{if(t.options.onUnhandledClientToolCall)return void t.options.onUnhandledClientToolCall(e.client_tool_call);t.onError("Client tool with name "+e.client_tool_call.tool_name+" is not defined on client",{clientToolName:e.client_tool_call.tool_name}),t.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:"Client tool with name "+e.client_tool_call.tool_name+" is not defined on client",is_error:!0})}}())}catch(e){return Promise.reject(e)}},n.handleAudio=function(e){},n.handleMCPToolCall=function(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)},n.handleMCPConnectionStatus=function(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)},n.handleAgentToolResponse=function(e){"end_call"===e.agent_tool_response.tool_name&&this.endSessionWithDetails({reason:"agent",context:new CloseEvent("end_call",{reason:"Agent ended the call"})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)},n.handleConversationMetadata=function(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)},n.handleAsrInitiationMetadata=function(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)},n.handleAgentChatResponsePart=function(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)},n.handleErrorEvent=function(e){var t=e.error_event.error_type,n=e.error_event.message||e.error_event.reason||"Unknown error";"max_duration_exceeded"!==t?this.onError("Server error: "+n,{errorType:t,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details}):this.endSessionWithDetails({reason:"error",message:n,context:new Event("max_duration_exceeded")})},n.onError=function(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)},n.getId=function(){return this.connection.conversationId},n.isOpen=function(){return"connected"===this.status},n.setMicMuted=function(e){this.connection.setMicMuted(e)},n.getInputByteFrequencyData=function(){return i},n.getOutputByteFrequencyData=function(){return i},n.getInputVolume=function(){return 0},n.getOutputVolume=function(){return 0},n.sendFeedback=function(e){this.canSendFeedback?(this.connection.sendMessage({type:"feedback",score:e?"like":"dislike",event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(0===this.lastFeedbackEventId?"Cannot send feedback: the conversation has not started yet.":"Cannot send feedback: feedback has already been sent for the current response.")},n.sendContextualUpdate=function(e){this.connection.sendMessage({type:"contextual_update",text:e})},n.sendUserMessage=function(e){this.connection.sendMessage({type:"user_message",text:e})},n.sendUserActivity=function(){this.connection.sendMessage({type:"user_activity"})},n.sendMCPToolApprovalResult=function(e,t){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:e,is_approved:t})},e}(),s=/*#__PURE__*/function(){function e(e){void 0===e&&(e={}),this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}var t=e.prototype;return t.debug=function(e){this.onDebug&&this.onDebug(e)},t.onMessage=function(e){this.onMessageCallback=e;var t=this.queue;this.queue=[],t.length>0&&queueMicrotask(function(){t.forEach(e)})},t.onDisconnect=function(e){this.onDisconnectCallback=e;var t=this.disconnectionDetails;t&&queueMicrotask(function(){e(t)})},t.onModeChange=function(e){this.onModeChangeCallback=e},t.updateMode=function(e){var t;null==(t=this.onModeChangeCallback)||t.call(this,e)},t.disconnect=function(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,null==(t=this.onDisconnectCallback)||t.call(this,e))},t.handleMessage=function(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)},e}();function c(e){var t=e.split("_"),n=t[0],o=t[1];if(!["pcm","ulaw"].includes(n))throw new Error("Invalid format: "+e);var r=Number.parseInt(o);if(Number.isNaN(r))throw new Error("Invalid sample rate: "+o);return{format:n,sampleRate:r}}var u="0.9.2";function l(e){return!!e.type}var d="conversation_initiation_client_data";function h(e){var t,n,o,r,i,a,s={type:d};return e.overrides&&(s.conversation_config_override={agent:{prompt:null==(n=e.overrides.agent)?void 0:n.prompt,first_message:null==(o=e.overrides.agent)?void 0:o.firstMessage,language:null==(r=e.overrides.agent)?void 0:r.language},tts:{voice_id:null==(i=e.overrides.tts)?void 0:i.voiceId},conversation:{text_only:null==(a=e.overrides.conversation)?void 0:a.textOnly}}),e.customLlmExtraBody&&(s.custom_llm_extra_body=e.customLlmExtraBody),e.dynamicVariables&&(s.dynamic_variables=e.dynamicVariables),e.userId&&(s.user_id=e.userId),null!=(t=e.overrides)&&t.client&&(s.source_info={source:e.overrides.client.source,version:e.overrides.client.version}),s}var p=/*#__PURE__*/function(e){function t(t,n,o,r){var i;return(i=e.call(this)||this).socket=void 0,i.conversationId=void 0,i.inputFormat=void 0,i.outputFormat=void 0,i.socket=t,i.conversationId=n,i.inputFormat=o,i.outputFormat=r,i.socket.addEventListener("error",function(e){setTimeout(function(){return i.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:e})},0)}),i.socket.addEventListener("close",function(e){i.disconnect(1e3===e.code?{reason:"agent",context:e}:{reason:"error",message:e.reason||"The connection was closed by the server.",context:e})}),i.socket.addEventListener("message",function(e){try{var t=JSON.parse(e.data);if(!l(t))return void i.debug({type:"invalid_event",message:"Received invalid socket event",data:e.data});i.handleMessage(t)}catch(t){i.debug({type:"parsing_error",message:"Failed to parse socket message",error:t instanceof Error?t.message:String(t),data:e.data})}}),i}n(t,e),t.create=function(e){try{var n=null;return Promise.resolve(function(o,r){try{var i=function(){var o,r,i,a,s=null!=(o=e.origin)?o:"wss://api.elevenlabs.io",d=(null==(r=e.overrides)||null==(r=r.client)?void 0:r.version)||u,p=(null==(i=e.overrides)||null==(i=i.client)?void 0:i.source)||"js_sdk";if(e.signedUrl){var f=e.signedUrl.includes("?")?"&":"?";a=""+e.signedUrl+f+"source="+p+"&version="+d}else a=s+"/v1/convai/conversation?agent_id="+e.agentId+"&source="+p+"&version="+d;var m=["convai"];return e.authorization&&m.push("bearer."+e.authorization),n=new WebSocket(a,m),Promise.resolve(new Promise(function(t,o){n.addEventListener("open",function(){var t,o=h(e);null==(t=n)||t.send(JSON.stringify(o))},{once:!0}),n.addEventListener("error",function(e){setTimeout(function(){return o(e)},0)}),n.addEventListener("close",o),n.addEventListener("message",function(e){var n=JSON.parse(e.data);l(n)&&("conversation_initiation_metadata"===n.type?t(n.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})})).then(function(e){var o=e.conversation_id,r=e.agent_output_audio_format,i=e.user_input_audio_format,a=c(null!=i?i:"pcm_16000"),s=c(r);return new t(n,o,a,s)})}()}catch(e){return r(e)}return i&&i.then?i.then(void 0,r):i}(0,function(e){var t;throw null==(t=n)||t.close(),e}))}catch(e){return Promise.reject(e)}};var o=t.prototype;return o.close=function(){this.socket.close()},o.sendMessage=function(e){this.socket.send(JSON.stringify(e))},o.setMicMuted=function(e){try{return console.warn("WebSocket connection setMicMuted called with "+e+", but this is handled by VoiceConversation"),Promise.resolve()}catch(e){return Promise.reject(e)}},t}(s);function f(e){var t=new Uint8Array(e);return window.btoa(String.fromCharCode.apply(String,t))}function m(e){for(var t=window.atob(e),n=t.length,o=new Uint8Array(n),r=0;r<n;r++)o[r]=t.charCodeAt(r);return o.buffer}function v(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var g=new Map;function _(e,t){return function(n,o){try{var r,i=function(o){var i;if(r)return o;function a(o){return i?o:v(function(){var o="data:application/javascript;base64,"+btoa(t);return Promise.resolve(n.addModule(o)).then(function(){g.set(e,o)})},function(){throw new Error("Failed to load the "+e+" worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.")})}var s=new Blob([t],{type:"application/javascript"}),c=URL.createObjectURL(s),u=v(function(){return Promise.resolve(n.addModule(c)).then(function(){g.set(e,c),i=1})},function(){URL.revokeObjectURL(c)});return u&&u.then?u.then(a):a(u)},a=g.get(e);if(a)return Promise.resolve(n.addModule(a));var s=function(){if(o)return v(function(){return Promise.resolve(n.addModule(o)).then(function(){g.set(e,o),r=1})},function(t){throw new Error("Failed to load the "+e+" worklet module from path: "+o+". Error: "+t)})}();return Promise.resolve(s&&s.then?s.then(i):i(s))}catch(e){return Promise.reject(e)}}}var b=_("rawAudioProcessor",'/*\n * ulaw encoding logic taken from the wavefile library\n * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js\n * USED BY @elevenlabs/client\n */\n\nconst BIAS = 0x84;\nconst CLIP = 32635;\nconst encodeTable = [\n 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,\n 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,\n 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,\n 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7\n];\n\nfunction encodeSample(sample) {\n let sign;\n let exponent;\n let mantissa;\n let muLawSample;\n sign = (sample >> 8) & 0x80;\n if (sign !== 0) sample = -sample;\n sample = sample + BIAS;\n if (sample > CLIP) sample = CLIP;\n exponent = encodeTable[(sample>>7) & 0xFF];\n mantissa = (sample >> (exponent+3)) & 0x0F;\n muLawSample = ~(sign | (exponent << 4) | mantissa);\n \n return muLawSample;\n}\n\nclass RawAudioProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n \n this.port.onmessage = ({ data }) => {\n switch (data.type) {\n case "setFormat":\n this.isMuted = false;\n this.buffer = []; // Initialize an empty buffer\n this.bufferSize = data.sampleRate / 4;\n this.format = data.format;\n\n if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) {\n globalThis.LibSampleRate.create(1, sampleRate, data.sampleRate).then(resampler => {\n this.resampler = resampler;\n });\n }\n break;\n case "setMuted":\n this.isMuted = data.isMuted;\n break;\n }\n };\n }\n process(inputs) {\n if (!this.buffer) {\n return true;\n }\n \n const input = inputs[0]; // Get the first input node\n if (input.length > 0) {\n let channelData = input[0]; // Get the first channel\'s data\n\n // Resample the audio if necessary\n if (this.resampler) {\n channelData = this.resampler.full(channelData);\n }\n\n // Add channel data to the buffer\n this.buffer.push(...channelData);\n // Get max volume \n let sum = 0.0;\n for (let i = 0; i < channelData.length; i++) {\n sum += channelData[i] * channelData[i];\n }\n const maxVolume = Math.sqrt(sum / channelData.length);\n // Check if buffer size has reached or exceeded the threshold\n if (this.buffer.length >= this.bufferSize) {\n const float32Array = this.isMuted \n ? new Float32Array(this.buffer.length)\n : new Float32Array(this.buffer);\n\n let encodedArray = this.format === "ulaw"\n ? new Uint8Array(float32Array.length)\n : new Int16Array(float32Array.length);\n\n // Iterate through the Float32Array and convert each sample to PCM16\n for (let i = 0; i < float32Array.length; i++) {\n // Clamp the value to the range [-1, 1]\n let sample = Math.max(-1, Math.min(1, float32Array[i]));\n\n // Scale the sample to the range [-32768, 32767]\n let value = sample < 0 ? sample * 32768 : sample * 32767;\n if (this.format === "ulaw") {\n value = encodeSample(Math.round(value));\n }\n\n encodedArray[i] = value;\n }\n\n // Send the buffered data to the main script\n this.port.postMessage([encodedArray, maxVolume]);\n\n // Clear the buffer after sending\n this.buffer = [];\n }\n }\n return true; // Continue processing\n }\n}\nregisterProcessor("rawAudioProcessor", RawAudioProcessor);\n');function y(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var P=/*#__PURE__*/function(t){function o(e,n,o,r,i){var a;return void 0===i&&(i={}),(a=t.call(this,i)||this).conversationId=void 0,a.inputFormat=void 0,a.outputFormat=void 0,a.room=void 0,a.isConnected=!1,a.audioEventId=1,a.audioCaptureContext=null,a.audioElements=[],a.outputDeviceId=null,a.outputAnalyser=null,a.outputFrequencyData=null,a.room=e,a.conversationId=n,a.inputFormat=o,a.outputFormat=r,a.setupRoomEventListeners(),a}n(o,t),o.create=function(t){try{var n,r=function(r){var i=new e.Room;return y(function(){var r="room_"+Date.now(),a=c("pcm_48000"),s=c("pcm_48000"),u=new o(i,r,a,s,t);return Promise.resolve(i.connect(t.livekitUrl||"wss://livekit.rtc.elevenlabs.io",n)).then(function(){return Promise.resolve(new Promise(function(t){if(u.isConnected)t();else{var n=function(){i.off(e.RoomEvent.Connected,n),t()};i.on(e.RoomEvent.Connected,n)}})).then(function(){var e;return i.name&&(u.conversationId=(null==(e=i.name.match(/(conv_[a-zA-Z0-9]+)/))?void 0:e[0])||i.name),Promise.resolve(i.localParticipant.setMicrophoneEnabled(!0)).then(function(){var e=h(t);return u.debug({type:d,message:e}),Promise.resolve(u.sendMessage(e)).then(function(){return u})})})})},function(e){return Promise.resolve(i.disconnect()).then(function(){throw e})})},i=function(){if(!("conversationToken"in t)||!t.conversationToken)return function(){if("agentId"in t&&t.agentId)return y(function(){var e,o,r,i=(null==(e=t.overrides)||null==(e=e.client)?void 0:e.version)||u,a=(null==(o=t.overrides)||null==(o=o.client)?void 0:o.source)||"js_sdk",s=function(e){return e.replace(/^wss:\/\//,"https://")}(null!=(r=t.origin)?r:"https://api.elevenlabs.io");return Promise.resolve(fetch(s+"/v1/convai/conversation/token?agent_id="+t.agentId+"&source="+a+"&version="+i)).then(function(e){if(!e.ok)throw new Error("ElevenLabs API returned "+e.status+" "+e.statusText);return Promise.resolve(e.json()).then(function(e){if(!(n=e.token))throw new Error("No conversation token received from API")})})},function(e){var n=e instanceof Error?e.message:String(e);throw e instanceof Error&&e.message.includes("401")&&(n="Your agent has authentication enabled, but no signed URL or conversation token was provided."),new Error("Failed to fetch conversation token for agent "+t.agentId+": "+n)});throw new Error("Either conversationToken or agentId is required for WebRTC connection")}();n=t.conversationToken}();return Promise.resolve(i&&i.then?i.then(r):r())}catch(e){return Promise.reject(e)}};var r=o.prototype;return r.setupRoomEventListeners=function(){var t=this,n=this,o=this,r=this;this.room.on(e.RoomEvent.Connected,function(){try{return n.isConnected=!0,console.info("WebRTC room connected"),Promise.resolve()}catch(e){return Promise.reject(e)}}),this.room.on(e.RoomEvent.Disconnected,function(e){t.isConnected=!1,t.disconnect({reason:"agent",context:new CloseEvent("close",{reason:null==e?void 0:e.toString()})})}),this.room.on(e.RoomEvent.ConnectionStateChanged,function(n){n===e.ConnectionState.Disconnected&&(t.isConnected=!1,t.disconnect({reason:"error",message:"LiveKit connection state changed to "+n,context:new Event("connection_state_changed")}))}),this.room.on(e.RoomEvent.DataReceived,function(e,n){try{var o=JSON.parse((new TextDecoder).decode(e));if("audio"===o.type)return;l(o)?t.handleMessage(o):console.warn("Invalid socket event received:",o)}catch(t){console.warn("Failed to parse incoming data message:",t),console.warn("Raw payload:",(new TextDecoder).decode(e))}}),this.room.on(e.RoomEvent.TrackSubscribed,function(t,n,r){try{var i=function(){if(t.kind===e.Track.Kind.Audio&&r.identity.includes("agent")){var n=function(){return a.style.display="none",document.body.appendChild(a),o.audioElements.push(a),1===o.audioElements.length&&(null==o.onDebug||o.onDebug({type:"audio_element_ready"})),Promise.resolve(o.setupAudioCapture(i)).then(function(){})},i=t,a=i.attach();a.autoplay=!0,a.controls=!1;var s=function(){if(o.outputDeviceId&&a.setSinkId){var e=y(function(){return Promise.resolve(a.setSinkId(o.outputDeviceId)).then(function(){})},function(e){console.warn("Failed to set output device for new audio element:",e)});if(e&&e.then)return e.then(function(){})}}();return s&&s.then?s.then(n):n()}}();return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),this.room.on(e.RoomEvent.ActiveSpeakersChanged,function(e){try{return r.updateMode(e.length>0&&e[0].identity.startsWith("agent")?"speaking":"listening"),Promise.resolve()}catch(e){return Promise.reject(e)}})},r.close=function(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(function(e){e.track&&e.track.stop()})}catch(e){console.warn("Error stopping local tracks:",e)}this.audioCaptureContext&&(this.audioCaptureContext.close().catch(function(e){console.warn("Error closing audio capture context:",e)}),this.audioCaptureContext=null),this.audioElements.forEach(function(e){e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}},r.sendMessage=function(e){try{var t=this;if(!t.isConnected||!t.room.localParticipant)return console.warn("Cannot send message: room not connected or no local participant"),Promise.resolve();if("user_audio_chunk"in e)return Promise.resolve();var n=y(function(){var n=(new TextEncoder).encode(JSON.stringify(e));return Promise.resolve(t.room.localParticipant.publishData(n,{reliable:!0})).then(function(){})},function(n){t.debug({type:"send_message_error",message:{message:e,error:n}}),console.error("Failed to send message via WebRTC:",n)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},r.getRoom=function(){return this.room},r.setMicMuted=function(t){try{var n=this;if(!n.isConnected||!n.room.localParticipant)return console.warn("Cannot set microphone muted: room not connected or no local participant"),Promise.resolve();var o=n.room.localParticipant.getTrackPublication(e.Track.Source.Microphone);return Promise.resolve(null!=o&&o.track?y(function(){var e=t?Promise.resolve(o.track.mute()).then(function(){}):Promise.resolve(o.track.unmute()).then(function(){});if(e&&e.then)return e.then(function(){})},function(){return Promise.resolve(n.room.localParticipant.setMicrophoneEnabled(!t)).then(function(){})}):Promise.resolve(n.room.localParticipant.setMicrophoneEnabled(!t)).then(function(){}))}catch(e){return Promise.reject(e)}},r.setupAudioCapture=function(e){try{var t=this,n=y(function(){var n=new AudioContext;t.audioCaptureContext=n,t.outputAnalyser=n.createAnalyser(),t.outputAnalyser.fftSize=2048,t.outputAnalyser.smoothingTimeConstant=.8;var o=new MediaStream([e.mediaStreamTrack]),r=n.createMediaStreamSource(o);return r.connect(t.outputAnalyser),Promise.resolve(b(n.audioWorklet)).then(function(){var e=new AudioWorkletNode(n,"rawAudioProcessor");t.outputAnalyser.connect(e),e.port.postMessage({type:"setFormat",format:t.outputFormat.format,sampleRate:t.outputFormat.sampleRate}),e.port.onmessage=function(e){var n=e.data;if(n[1]>.01){var o=f(n[0].buffer),r=t.audioEventId++;t.handleMessage({type:"audio",audio_event:{audio_base_64:o,event_id:r}})}},r.connect(e)})},function(e){console.warn("Failed to set up audio capture:",e)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},r.setAudioVolume=function(e){this.audioElements.forEach(function(t){t.volume=e})},r.setAudioOutputDevice=function(e){try{var t=this;if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");var n=t.audioElements.map(function(t){try{return Promise.resolve(y(function(){return Promise.resolve(t.setSinkId(e)).then(function(){})},function(e){throw console.error("Failed to set sink ID for audio element:",e),e}))}catch(e){return Promise.reject(e)}});return Promise.resolve(Promise.all(n)).then(function(){t.outputDeviceId=e})}catch(e){return Promise.reject(e)}},r.setAudioInputDevice=function(t){try{var n=this;if(!n.isConnected||!n.room.localParticipant)throw new Error("Cannot change input device: room not connected or no local participant");return Promise.resolve(y(function(){function o(){return Promise.resolve(e.createLocalAudioTrack({deviceId:{exact:t},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}})).then(function(t){return Promise.resolve(n.room.localParticipant.publishTrack(t,{name:"microphone",source:e.Track.Source.Microphone})).then(function(){})})}var r=n.room.localParticipant.getTrackPublication(e.Track.Source.Microphone),i=function(){if(null!=r&&r.track)return Promise.resolve(r.track.stop()).then(function(){return Promise.resolve(n.room.localParticipant.unpublishTrack(r.track)).then(function(){})})}();return i&&i.then?i.then(o):o()},function(e){function t(){throw e}console.error("Failed to change input device:",e);var o=y(function(){return Promise.resolve(n.room.localParticipant.setMicrophoneEnabled(!0)).then(function(){})},function(e){console.error("Failed to recover microphone after device switch error:",e)});return o&&o.then?o.then(t):t()}))}catch(e){return Promise.reject(e)}},r.getOutputByteFrequencyData=function(){return this.outputAnalyser?(null!=this.outputFrequencyData||(this.outputFrequencyData=new Uint8Array(this.outputAnalyser.frequencyBinCount)),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null},o}(s),w=function(e){try{var t=function(e){return e.connectionType?e.connectionType:"conversationToken"in e&&e.conversationToken?"webrtc":"websocket"}(e);switch(t){case"websocket":return Promise.resolve(p.create(e));case"webrtc":return Promise.resolve(P.create(e));default:throw new Error("Unknown connection type: "+t)}}catch(e){return Promise.reject(e)}};function S(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}var k=function(e){void 0===e&&(e={default:0,android:3e3});try{var t,n=e.default;if(/android/i.test(navigator.userAgent))n=null!=(t=e.android)?t:n;else if(S()){var o;n=null!=(o=e.ios)?o:n}var r=function(){if(n>0)return Promise.resolve(new Promise(function(e){return setTimeout(e,n)})).then(function(){})}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},C=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return n(t,e),t.startSession=function(e){try{var n=a.getFullOptions(e);n.onStatusChange&&n.onStatusChange({status:"connecting"}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1}),n.onModeChange&&n.onModeChange({mode:"listening"}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});var o=null;return Promise.resolve(function(r,i){try{var a=Promise.resolve(k(n.connectionDelay)).then(function(){return Promise.resolve(w(e)).then(function(e){return new t(n,o=e)})})}catch(e){return i(e)}return a&&a.then?a.then(void 0,i):a}(0,function(e){var t;throw n.onStatusChange&&n.onStatusChange({status:"disconnected"}),null==(t=o)||t.close(),e}))}catch(e){return Promise.reject(e)}},t}(a);function E(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var M={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},A=/*#__PURE__*/function(){function e(e,t,n,o,r){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=t,this.worklet=n,this.inputStream=o,this.mediaStreamSource=r}e.create=function(n){var o=n.sampleRate,r=n.format,i=n.preferHeadphonesForIosDevices,a=n.inputDeviceId,s=n.workletPaths,c=n.libsampleratePath;try{var u=null,l=null;return Promise.resolve(E(function(){function n(){function n(){return Promise.resolve(b(u.audioWorklet,null==s?void 0:s.rawAudioProcessor)).then(function(){var n=t({voiceIsolation:!0},d);return Promise.resolve(navigator.mediaDevices.getUserMedia({audio:n})).then(function(t){var n=u.createMediaStreamSource(l=t),i=new AudioWorkletNode(u,"rawAudioProcessor");return i.port.postMessage({type:"setFormat",format:r,sampleRate:o}),n.connect(h),h.connect(i),Promise.resolve(u.resume()).then(function(){return new e(u,h,i,l,n)})})})}a&&(d.deviceId={exact:a});var i=navigator.mediaDevices.getSupportedConstraints().sampleRate,h=(u=new window.AudioContext(i?{sampleRate:o}:{})).createAnalyser(),p=function(){if(!i)return Promise.resolve(u.audioWorklet.addModule(c||"https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js")).then(function(){})}();return p&&p.then?p.then(n):n()}var d=t({sampleRate:{ideal:o}},M),h=function(){if(S()&&i)return Promise.resolve(window.navigator.mediaDevices.enumerateDevices()).then(function(e){var t=e.find(function(e){return"audioinput"===e.kind&&["airpod","headphone","earphone"].find(function(t){return e.label.toLowerCase().includes(t)})});t&&(d.deviceId={ideal:t.deviceId})})}();return h&&h.then?h.then(n):n()},function(e){var t,n;throw null==(t=l)||t.getTracks().forEach(function(e){e.stop()}),null==(n=u)||n.close(),e}))}catch(e){return Promise.reject(e)}};var n=e.prototype;return n.close=function(){try{var e=this;return e.inputStream.getTracks().forEach(function(e){e.stop()}),e.mediaStreamSource.disconnect(),Promise.resolve(e.context.close()).then(function(){})}catch(e){return Promise.reject(e)}},n.setMuted=function(e){this.worklet.port.postMessage({type:"setMuted",isMuted:e})},n.setInputDevice=function(e){try{var n=this;return Promise.resolve(E(function(){var o=t({},M);e&&(o.deviceId={exact:e});var r=t({voiceIsolation:!0},o);return Promise.resolve(navigator.mediaDevices.getUserMedia({audio:r})).then(function(e){n.inputStream.getTracks().forEach(function(e){e.stop()}),n.mediaStreamSource.disconnect(),n.inputStream=e,n.mediaStreamSource=n.context.createMediaStreamSource(e),n.mediaStreamSource.connect(n.analyser)})},function(e){throw console.error("Failed to switch input device:",e),e}))}catch(e){return Promise.reject(e)}},e}(),I=_("audioConcatProcessor",'/*\n * ulaw decoding logic taken from the wavefile library\n * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js\n * USED BY @elevenlabs/client\n */\n\nconst decodeTable = [0,132,396,924,1980,4092,8316,16764];\n\nfunction decodeSample(muLawSample) {\n let sign;\n let exponent;\n let mantissa;\n let sample;\n muLawSample = ~muLawSample;\n sign = (muLawSample & 0x80);\n exponent = (muLawSample >> 4) & 0x07;\n mantissa = muLawSample & 0x0F;\n sample = decodeTable[exponent] + (mantissa << (exponent+3));\n if (sign !== 0) sample = -sample;\n\n return sample;\n}\n\nclass AudioConcatProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffers = []; // Initialize an empty buffer\n this.cursor = 0;\n this.currentBuffer = null;\n this.wasInterrupted = false;\n this.finished = false;\n \n this.port.onmessage = ({ data }) => {\n switch (data.type) {\n case "setFormat":\n this.format = data.format;\n break;\n case "buffer":\n this.wasInterrupted = false;\n this.buffers.push(\n this.format === "ulaw"\n ? new Uint8Array(data.buffer)\n : new Int16Array(data.buffer)\n );\n break;\n case "interrupt":\n this.wasInterrupted = true;\n break;\n case "clearInterrupted":\n if (this.wasInterrupted) {\n this.wasInterrupted = false;\n this.buffers = [];\n this.currentBuffer = null;\n }\n }\n };\n }\n process(_, outputs) {\n let finished = false;\n const output = outputs[0][0];\n for (let i = 0; i < output.length; i++) {\n if (!this.currentBuffer) {\n if (this.buffers.length === 0) {\n finished = true;\n break;\n }\n this.currentBuffer = this.buffers.shift();\n this.cursor = 0;\n }\n\n let value = this.currentBuffer[this.cursor];\n if (this.format === "ulaw") {\n value = decodeSample(value);\n }\n output[i] = value / 32768;\n this.cursor++;\n\n if (this.cursor >= this.currentBuffer.length) {\n this.currentBuffer = null;\n }\n }\n\n if (this.finished !== finished) {\n this.finished = finished;\n this.port.postMessage({ type: "process", finished });\n }\n\n return true; // Continue processing\n }\n}\n\nregisterProcessor("audioConcatProcessor", AudioConcatProcessor);\n'),D=/*#__PURE__*/function(){function e(e,t,n,o,r){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=t,this.gain=n,this.worklet=o,this.audioElement=r}e.create=function(t){var n=t.sampleRate,o=t.format,r=t.outputDeviceId,i=t.workletPaths;try{var a=null,s=null;return Promise.resolve(function(t,c){try{var u=function(){var t=(a=new AudioContext({sampleRate:n})).createAnalyser(),c=a.createGain();(s=new Audio).src="",s.load(),s.autoplay=!0,s.style.display="none",document.body.appendChild(s);var u=a.createMediaStreamDestination();return s.srcObject=u.stream,c.connect(t),t.connect(u),Promise.resolve(I(a.audioWorklet,null==i?void 0:i.audioConcatProcessor)).then(function(){var n=new AudioWorkletNode(a,"audioConcatProcessor");return n.port.postMessage({type:"setFormat",format:o}),n.connect(c),Promise.resolve(a.resume()).then(function(){function o(){return new e(a,t,c,n,s)}var i=function(){if(r&&s.setSinkId)return Promise.resolve(s.setSinkId(r)).then(function(){})}();return i&&i.then?i.then(o):o()})})}()}catch(e){return c(e)}return u&&u.then?u.then(void 0,c):u}(0,function(e){var t,n;function o(){throw e}null!=(t=s)&&t.parentNode&&s.parentNode.removeChild(s),null==(n=s)||n.pause();var r=function(){if(a&&"closed"!==a.state)return Promise.resolve(a.close()).then(function(){})}();return r&&r.then?r.then(o):o()}))}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.setOutputDevice=function(e){try{if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");return Promise.resolve(this.audioElement.setSinkId(e||"")).then(function(){})}catch(e){return Promise.reject(e)}},t.close=function(){try{var e=this;return e.audioElement.parentNode&&e.audioElement.parentNode.removeChild(e.audioElement),e.audioElement.pause(),Promise.resolve(e.context.close()).then(function(){})}catch(e){return Promise.reject(e)}},e}();function R(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var T,F=/*#__PURE__*/function(e){function o(t,n,o,r,i){var a;return(a=e.call(this,t,n)||this).input=void 0,a.output=void 0,a.wakeLock=void 0,a.inputFrequencyData=void 0,a.outputFrequencyData=void 0,a.onInputWorkletMessage=function(e){"connected"===a.status&&a.connection.sendMessage({user_audio_chunk:f(e.data[0].buffer)})},a.onOutputWorkletMessage=function(e){var t=e.data;"process"===t.type&&a.updateMode(t.finished?"listening":"speaking")},a.addAudioBase64Chunk=function(e){a.output.gain.gain.cancelScheduledValues(a.output.context.currentTime),a.output.gain.gain.value=a.volume,a.output.worklet.port.postMessage({type:"clearInterrupted"}),a.output.worklet.port.postMessage({type:"buffer",buffer:m(e)})},a.fadeOutAudio=function(){a.updateMode("listening"),a.output.worklet.port.postMessage({type:"interrupt"}),a.output.gain.gain.exponentialRampToValueAtTime(1e-4,a.output.context.currentTime+2),setTimeout(function(){a.output.gain.gain.value=a.volume,a.output.worklet.port.postMessage({type:"clearInterrupted"})},2e3)},a.calculateVolume=function(e){if(0===e.length)return 0;for(var t=0,n=0;n<e.length;n++)t+=e[n]/255;return(t/=e.length)<0?0:t>1?1:t},a.setVolume=function(e){var t=e.volume,n=Number.isFinite(t)?Math.min(1,Math.max(0,t)):1;a.volume=n,a.connection instanceof P?a.connection.setAudioVolume(n):a.output.gain.gain.value=n},a.input=o,a.output=r,a.wakeLock=i,a.input.worklet.port.onmessage=a.onInputWorkletMessage,a.output.worklet.port.onmessage=a.onOutputWorkletMessage,a}n(o,e),o.startSession=function(e){try{var n=function(){return R(function(){return Promise.resolve(navigator.mediaDevices.getUserMedia({audio:!0})).then(function(n){return u=n,Promise.resolve(k(r.connectionDelay)).then(function(){return Promise.resolve(w(e)).then(function(n){return s=n,Promise.resolve(Promise.all([A.create(t({},s.inputFormat,{preferHeadphonesForIosDevices:e.preferHeadphonesForIosDevices,inputDeviceId:e.inputDeviceId,workletPaths:e.workletPaths,libsampleratePath:e.libsampleratePath})),D.create(t({},s.outputFormat,{outputDeviceId:e.outputDeviceId,workletPaths:e.workletPaths}))])).then(function(e){var t;return i=e[0],c=e[1],null==(t=u)||t.getTracks().forEach(function(e){e.stop()}),u=null,new o(r,s,i,c,l)})})})})},function(e){var t,n,o;return r.onStatusChange&&r.onStatusChange({status:"disconnected"}),null==(t=u)||t.getTracks().forEach(function(e){e.stop()}),null==(n=s)||n.close(),Promise.resolve(null==(o=i)?void 0:o.close()).then(function(){var t;return Promise.resolve(null==(t=c)?void 0:t.close()).then(function(){function t(){throw e}var n=R(function(){var e;return Promise.resolve(null==(e=l)?void 0:e.release()).then(function(){l=null})},function(){});return n&&n.then?n.then(t):t()})})})},r=a.getFullOptions(e);r.onStatusChange&&r.onStatusChange({status:"connecting"}),r.onCanSendFeedbackChange&&r.onCanSendFeedbackChange({canSendFeedback:!1});var i=null,s=null,c=null,u=null,l=null,d=function(t){if(null==(t=e.useWakeLock)||t){var n=R(function(){return Promise.resolve(navigator.wakeLock.request("screen")).then(function(e){l=e})},function(){});if(n&&n.then)return n.then(function(){})}}();return Promise.resolve(d&&d.then?d.then(n):n())}catch(e){return Promise.reject(e)}};var r=o.prototype;return r.handleEndSession=function(){try{var t=this;return Promise.resolve(e.prototype.handleEndSession.call(t)).then(function(){function e(){return Promise.resolve(t.input.close()).then(function(){return Promise.resolve(t.output.close()).then(function(){})})}var n=R(function(){var e;return Promise.resolve(null==(e=t.wakeLock)?void 0:e.release()).then(function(){t.wakeLock=null})},function(){});return n&&n.then?n.then(e):e()})}catch(e){return Promise.reject(e)}},r.handleInterruption=function(t){e.prototype.handleInterruption.call(this,t),this.fadeOutAudio()},r.handleAudio=function(e){var t,n;this.lastInterruptTimestamp<=e.audio_event.event_id&&(null==(t=(n=this.options).onAudio)||t.call(n,e.audio_event.audio_base_64),this.connection instanceof P||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))},r.setMicMuted=function(e){this.connection instanceof P?this.connection.setMicMuted(e):this.input.setMuted(e)},r.getInputByteFrequencyData=function(){return null!=this.inputFrequencyData||(this.inputFrequencyData=new Uint8Array(this.input.analyser.frequencyBinCount)),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData},r.getOutputByteFrequencyData=function(){return this.connection instanceof P?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(null!=this.outputFrequencyData||(this.outputFrequencyData=new Uint8Array(this.output.analyser.frequencyBinCount)),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)},r.getInputVolume=function(){return this.calculateVolume(this.getInputByteFrequencyData())},r.getOutputVolume=function(){return this.calculateVolume(this.getOutputByteFrequencyData())},r.changeInputDevice=function(e){var t=e.sampleRate,n=e.format,o=e.preferHeadphonesForIosDevices,r=e.inputDeviceId;try{var i,a=this;return Promise.resolve(R(function(){function e(e){if(i)return e;function s(){return Promise.resolve(a.input.close()).then(function(){return Promise.resolve(A.create({sampleRate:null!=t?t:a.connection.inputFormat.sampleRate,format:null!=n?n:a.connection.inputFormat.format,preferHeadphonesForIosDevices:o,inputDeviceId:r,workletPaths:a.options.workletPaths,libsampleratePath:a.options.libsampleratePath})).then(function(e){return a.input=e,a.input.worklet.port.onmessage=a.onInputWorkletMessage,a.input})})}var c=function(){if(a.connection instanceof P)return Promise.resolve(a.connection.setAudioInputDevice(r||"")).then(function(){})}();return c&&c.then?c.then(s):s()}var s=function(){if(a.connection instanceof p)return R(function(){return Promise.resolve(a.input.setInputDevice(r)).then(function(){return i=1,a.input})},function(e){console.warn("Failed to change device on existing input, recreating:",e)})}();return s&&s.then?s.then(e):e(s)},function(e){throw console.error("Error changing input device",e),e}))}catch(e){return Promise.reject(e)}},r.changeOutputDevice=function(e){var t=e.sampleRate,n=e.format,o=e.outputDeviceId;try{var r,i=this;return Promise.resolve(R(function(){function e(e){if(r)return e;function a(){return Promise.resolve(i.output.close()).then(function(){return Promise.resolve(D.create({sampleRate:null!=t?t:i.connection.outputFormat.sampleRate,format:null!=n?n:i.connection.outputFormat.format,outputDeviceId:o,workletPaths:i.options.workletPaths})).then(function(e){return i.output=e,i.output})})}var s=function(){if(i.connection instanceof P)return Promise.resolve(i.connection.setAudioOutputDevice(o||"")).then(function(){})}();return s&&s.then?s.then(a):a()}var a=function(){if(i.connection instanceof p)return R(function(){return Promise.resolve(i.output.setOutputDevice(o)).then(function(){return r=1,i.output})},function(e){console.warn("Failed to change device on existing output, recreating:",e)})}();return a&&a.then?a.then(e):e(a)},function(e){throw console.error("Error changing output device",e),e}))}catch(e){return Promise.reject(e)}},o}(a),x=/*#__PURE__*/function(){function e(){this.listeners=new Map}var t=e.prototype;return t.on=function(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);var n=this.listeners.get(e);n&&n.add(t)},t.off=function(e,t){var n=this.listeners.get(e);n&&n.delete(t)},t.emit=function(e){var t=arguments,n=this.listeners.get(e);n&&n.forEach(function(e){e.apply(void 0,[].slice.call(t,1))})},e}();exports.RealtimeEvents=void 0,(T=exports.RealtimeEvents||(exports.RealtimeEvents={})).SESSION_STARTED="session_started",T.PARTIAL_TRANSCRIPT="partial_transcript",T.FINAL_TRANSCRIPT="final_transcript",T.FINAL_TRANSCRIPT_WITH_TIMESTAMPS="final_transcript_with_timestamps",T.AUTH_ERROR="auth_error",T.ERROR="error",T.OPEN="open",T.CLOSE="close";var O,L,j=/*#__PURE__*/function(){function e(e){this.websocket=null,this.eventEmitter=new x,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}var t=e.prototype;return t.setWebSocket=function(e){var t=this;this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(exports.RealtimeEvents.OPEN):this.websocket.addEventListener("open",function(){t.eventEmitter.emit(exports.RealtimeEvents.OPEN)}),this.websocket.addEventListener("message",function(e){try{var n=JSON.parse(e.data);switch(n.message_type){case"session_started":t.eventEmitter.emit(exports.RealtimeEvents.SESSION_STARTED,n);break;case"partial_transcript":t.eventEmitter.emit(exports.RealtimeEvents.PARTIAL_TRANSCRIPT,n);break;case"final_transcript":t.eventEmitter.emit(exports.RealtimeEvents.FINAL_TRANSCRIPT,n);break;case"final_transcript_with_timestamps":t.eventEmitter.emit(exports.RealtimeEvents.FINAL_TRANSCRIPT_WITH_TIMESTAMPS,n);break;case"auth_error":t.eventEmitter.emit(exports.RealtimeEvents.AUTH_ERROR,n);break;case"error":t.eventEmitter.emit(exports.RealtimeEvents.ERROR,n);break;default:console.warn("Unknown message type:",n)}}catch(n){console.error("Failed to parse WebSocket message:",n,e.data),t.eventEmitter.emit(exports.RealtimeEvents.ERROR,new Error("Failed to parse message: "+n))}}),this.websocket.addEventListener("error",function(e){console.error("WebSocket error:",e),t.eventEmitter.emit(exports.RealtimeEvents.ERROR,e)}),this.websocket.addEventListener("close",function(e){if(console.log("WebSocket closed: code="+e.code+', reason="'+e.reason+'", wasClean='+e.wasClean),!e.wasClean||1e3!==e.code&&1005!==e.code){var n="WebSocket closed unexpectedly: "+e.code+" - "+(e.reason||"No reason provided");console.error(n),t.eventEmitter.emit(exports.RealtimeEvents.ERROR,new Error(n))}t.eventEmitter.emit(exports.RealtimeEvents.CLOSE,e)})},t.on=function(e,t){this.eventEmitter.on(e,t)},t.off=function(e,t){this.eventEmitter.off(e,t)},t.send=function(e){var t,n;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");var o={message_type:"input_audio_chunk",audio_base_64:e.audioBase64,commit:null!=(t=e.commit)&&t,sample_rate:null!=(n=e.sampleRate)?n:this.currentSampleRate};this.websocket.send(JSON.stringify(o))},t.commit=function(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");this.websocket.send(JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:this.currentSampleRate}))},t.close=function(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close()},e}(),W=_("scribeAudioProcessor",'/*\n * Scribe Audio Processor for converting microphone audio to PCM16 format\n * USED BY @elevenlabs/client\n */\n\nclass ScribeAudioProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = [];\n this.bufferSize = 4096; // Buffer size for optimal chunk transmission\n }\n\n process(inputs) {\n const input = inputs[0];\n if (input.length > 0) {\n const channelData = input[0]; // Get first channel (mono)\n\n // Add incoming audio to buffer\n this.buffer.push(...channelData);\n\n // When buffer reaches threshold, convert and send\n if (this.buffer.length >= this.bufferSize) {\n const float32Array = new Float32Array(this.buffer);\n const int16Array = new Int16Array(float32Array.length);\n\n // Convert Float32 [-1, 1] to Int16 [-32768, 32767]\n for (let i = 0; i < float32Array.length; i++) {\n // Clamp the value to prevent overflow\n const sample = Math.max(-1, Math.min(1, float32Array[i]));\n // Scale to PCM16 range\n int16Array[i] = sample < 0 ? sample * 32768 : sample * 32767;\n }\n\n // Send to main thread as transferable ArrayBuffer\n this.port.postMessage(\n {\n audioData: int16Array.buffer\n },\n [int16Array.buffer]\n );\n\n // Clear buffer\n this.buffer = [];\n }\n }\n\n return true; // Continue processing\n }\n}\n\nregisterProcessor("scribeAudioProcessor", ScribeAudioProcessor);\n\n');exports.AudioFormat=void 0,(O=exports.AudioFormat||(exports.AudioFormat={})).PCM_8000="pcm_8000",O.PCM_16000="pcm_16000",O.PCM_22050="pcm_22050",O.PCM_24000="pcm_24000",O.PCM_44100="pcm_44100",O.PCM_48000="pcm_48000",O.ULAW_8000="ulaw_8000",exports.CommitStrategy=void 0,(L=exports.CommitStrategy||(exports.CommitStrategy={})).MANUAL="manual",L.VAD="vad";var U=/*#__PURE__*/function(){function e(){}return e.getWebSocketUri=function(t){return void 0===t&&(t=e.DEFAULT_BASE_URI),t+"/v1/speech-to-text/realtime-beta"},e.buildWebSocketUri=function(t){var n=e.getWebSocketUri(t.baseUri),o=new URLSearchParams;if(o.append("model_id",t.modelId),o.append("token",t.token),void 0!==t.commitStrategy&&o.append("commit_strategy",t.commitStrategy),void 0!==t.vadSilenceThresholdSecs){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw new Error("vadSilenceThresholdSecs must be between 0.3 and 3.0");o.append("vad_silence_threshold_secs",t.vadSilenceThresholdSecs.toString())}if(void 0!==t.vadThreshold){if(t.vadThreshold<.1||t.vadThreshold>.9)throw new Error("vadThreshold must be between 0.1 and 0.9");o.append("vad_threshold",t.vadThreshold.toString())}if(void 0!==t.minSpeechDurationMs){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw new Error("minSpeechDurationMs must be between 50 and 2000");o.append("min_speech_duration_ms",t.minSpeechDurationMs.toString())}if(void 0!==t.minSilenceDurationMs){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw new Error("minSilenceDurationMs must be between 50 and 2000");o.append("min_silence_duration_ms",t.minSilenceDurationMs.toString())}void 0!==t.languageCode&&o.append("language_code",t.languageCode);var r=o.toString();return r?n+"?"+r:n},e.connect=function(t){if(!t.modelId)throw new Error("modelId is required");var n=new j("microphone"in t&&t.microphone?16e3:t.sampleRate),o=e.buildWebSocketUri(t),r=new WebSocket(o);return"microphone"in t&&t.microphone&&r.addEventListener("open",function(){e.streamFromMicrophone(t,n)}),n.setWebSocket(r),n},e.streamFromMicrophone=function(e,t){try{return Promise.resolve(function(n,o){try{var r=Promise.resolve(navigator.mediaDevices.getUserMedia({audio:{deviceId:null==(i=e.microphone)?void 0:i.deviceId,echoCancellation:null==(a=null==(s=e.microphone)?void 0:s.echoCancellation)||a,noiseSuppression:null==(c=null==(u=e.microphone)?void 0:u.noiseSuppression)||c,autoGainControl:null==(l=null==(d=e.microphone)?void 0:d.autoGainControl)||l,channelCount:null!=(h=null==(p=e.microphone)?void 0:p.channelCount)?h:1,sampleRate:{ideal:16e3}}})).then(function(e){var n=new AudioContext({sampleRate:16e3});return Promise.resolve(W(n.audioWorklet)).then(function(){function o(){t._audioCleanup=function(){e.getTracks().forEach(function(e){e.stop()}),r.disconnect(),i.disconnect(),n.close()}}var r=n.createMediaStreamSource(e),i=new AudioWorkletNode(n,"scribeAudioProcessor");i.port.onmessage=function(e){for(var n=new Uint8Array(e.data.audioData),o="",r=0;r<n.length;r++)o+=String.fromCharCode(n[r]);var i=btoa(o);t.send({audioBase64:i})},r.connect(i);var a=function(){if("suspended"===n.state)return Promise.resolve(n.resume()).then(function(){})}();return a&&a.then?a.then(o):o()})})}catch(e){return o(e)}var i,a,s,c,u,l,d,h,p;return r&&r.then?r.then(void 0,o):r}(0,function(e){throw console.error("Failed to start microphone streaming:",e),e}))}catch(e){return Promise.reject(e)}},e}();U.DEFAULT_BASE_URI="wss://api.elevenlabs.io",exports.Conversation=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return n(t,e),t.startSession=function(e){return e.textOnly?C.startSession(e):F.startSession(e)},t}(a),exports.Input=A,exports.Output=D,exports.RealtimeConnection=j,exports.Scribe=U,exports.TextConversation=C,exports.VoiceConversation=F,exports.WebRTCConnection=P,exports.WebSocketConnection=p,exports.createConnection=w,exports.postOverallFeedback=function(e,t,n){void 0===n&&(n="https://api.elevenlabs.io");var o={};return"boolean"==typeof t?o.feedback=t?"like":"dislike":(o.rating=t.rating,o.comment=t.comment),fetch(n+"/v1/convai/conversations/"+e+"/feedback",{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})};
|
|
1
|
+
var e=require("livekit-client");function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)({}).hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},t.apply(null,arguments)}function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,o(e,t)}function o(e,t){return o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},o(e,t)}function r(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var i=new Uint8Array(0),a=/*#__PURE__*/function(){function e(e,t){var n=this,o=this,i=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode="listening",this.status="connecting",this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=function(e){try{return"connected"!==o.status&&"connecting"!==o.status?Promise.resolve():(o.updateStatus("disconnecting"),Promise.resolve(o.handleEndSession()).then(function(){o.updateStatus("disconnected"),o.options.onDisconnect&&o.options.onDisconnect(e)}))}catch(e){return Promise.reject(e)}},this.onMessage=function(e){try{switch(e.type){case"interruption":return i.handleInterruption(e),Promise.resolve();case"agent_response":return i.handleAgentResponse(e),Promise.resolve();case"user_transcript":return i.handleUserTranscript(e),Promise.resolve();case"internal_tentative_agent_response":return i.handleTentativeAgentResponse(e),Promise.resolve();case"client_tool_call":var t=r(function(){return Promise.resolve(i.handleClientToolCall(e)).then(function(){})},function(t){i.onError("Unexpected error in client tool call handling: "+(t instanceof Error?t.message:String(t)),{clientToolName:e.client_tool_call.tool_name,toolCallId:e.client_tool_call.tool_call_id})});return Promise.resolve(t&&t.then?t.then(function(){}):void 0);case"audio":return i.handleAudio(e),Promise.resolve();case"vad_score":return i.handleVadScore(e),Promise.resolve();case"ping":return i.connection.sendMessage({type:"pong",event_id:e.ping_event.event_id}),Promise.resolve();case"mcp_tool_call":return i.handleMCPToolCall(e),Promise.resolve();case"mcp_connection_status":return i.handleMCPConnectionStatus(e),Promise.resolve();case"agent_tool_response":return i.handleAgentToolResponse(e),Promise.resolve();case"conversation_initiation_metadata":return i.handleConversationMetadata(e),Promise.resolve();case"asr_initiation_metadata":return i.handleAsrInitiationMetadata(e),Promise.resolve();case"agent_chat_response_part":return i.handleAgentChatResponsePart(e),Promise.resolve();case"error":return i.handleErrorEvent(e),Promise.resolve();default:return i.options.onDebug&&i.options.onDebug(e),Promise.resolve()}}catch(e){return Promise.reject(e)}},this.setVolume=function(e){n.volume=e.volume},this.options=e,this.connection=t,this.options.onConnect&&this.options.onConnect({conversationId:t.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(function(e){return n.updateMode(e)}),this.updateStatus("connected")}e.getFullOptions=function(e){return t({clientTools:{},onConnect:function(){},onDebug:function(){},onDisconnect:function(){},onError:function(){},onMessage:function(){},onAudio:function(){},onModeChange:function(){},onStatusChange:function(){},onCanSendFeedbackChange:function(){},onInterruption:function(){}},e)};var n=e.prototype;return n.endSession=function(){return this.endSessionWithDetails({reason:"user"})},n.handleEndSession=function(){try{return this.connection.close(),Promise.resolve()}catch(e){return Promise.reject(e)}},n.updateMode=function(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))},n.updateStatus=function(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))},n.updateCanSendFeedback=function(){var e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))},n.handleInterruption=function(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))},n.handleAgentResponse=function(e){this.options.onMessage&&this.options.onMessage({source:"ai",message:e.agent_response_event.agent_response})},n.handleUserTranscript=function(e){this.options.onMessage&&this.options.onMessage({source:"user",message:e.user_transcription_event.user_transcript})},n.handleTentativeAgentResponse=function(e){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:e.tentative_agent_response_internal_event.tentative_agent_response})},n.handleVadScore=function(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})},n.handleClientToolCall=function(e){try{var t=this;return Promise.resolve(function(){if(Object.prototype.hasOwnProperty.call(t.options.clientTools,e.client_tool_call.tool_name)){var n=r(function(){return Promise.resolve(t.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters)).then(function(n){var o="object"==typeof n?JSON.stringify(n):String(n);t.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:o,is_error:!1})})},function(n){t.onError("Client tool execution failed with following error: "+(null==n?void 0:n.message),{clientToolName:e.client_tool_call.tool_name}),t.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:"Client tool execution failed: "+(null==n?void 0:n.message),is_error:!0})});if(n&&n.then)return n.then(function(){})}else{if(t.options.onUnhandledClientToolCall)return void t.options.onUnhandledClientToolCall(e.client_tool_call);t.onError("Client tool with name "+e.client_tool_call.tool_name+" is not defined on client",{clientToolName:e.client_tool_call.tool_name}),t.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:"Client tool with name "+e.client_tool_call.tool_name+" is not defined on client",is_error:!0})}}())}catch(e){return Promise.reject(e)}},n.handleAudio=function(e){},n.handleMCPToolCall=function(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)},n.handleMCPConnectionStatus=function(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)},n.handleAgentToolResponse=function(e){"end_call"===e.agent_tool_response.tool_name&&this.endSessionWithDetails({reason:"agent",context:new CloseEvent("end_call",{reason:"Agent ended the call"})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)},n.handleConversationMetadata=function(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)},n.handleAsrInitiationMetadata=function(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)},n.handleAgentChatResponsePart=function(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)},n.handleErrorEvent=function(e){var t=e.error_event.error_type,n=e.error_event.message||e.error_event.reason||"Unknown error";"max_duration_exceeded"!==t?this.onError("Server error: "+n,{errorType:t,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details}):this.endSessionWithDetails({reason:"error",message:n,context:new Event("max_duration_exceeded")})},n.onError=function(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)},n.getId=function(){return this.connection.conversationId},n.isOpen=function(){return"connected"===this.status},n.setMicMuted=function(e){this.connection.setMicMuted(e)},n.getInputByteFrequencyData=function(){return i},n.getOutputByteFrequencyData=function(){return i},n.getInputVolume=function(){return 0},n.getOutputVolume=function(){return 0},n.sendFeedback=function(e){this.canSendFeedback?(this.connection.sendMessage({type:"feedback",score:e?"like":"dislike",event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(0===this.lastFeedbackEventId?"Cannot send feedback: the conversation has not started yet.":"Cannot send feedback: feedback has already been sent for the current response.")},n.sendContextualUpdate=function(e){this.connection.sendMessage({type:"contextual_update",text:e})},n.sendUserMessage=function(e){this.connection.sendMessage({type:"user_message",text:e})},n.sendUserActivity=function(){this.connection.sendMessage({type:"user_activity"})},n.sendMCPToolApprovalResult=function(e,t){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:e,is_approved:t})},e}(),s=/*#__PURE__*/function(){function e(e){void 0===e&&(e={}),this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}var t=e.prototype;return t.debug=function(e){this.onDebug&&this.onDebug(e)},t.onMessage=function(e){this.onMessageCallback=e;var t=this.queue;this.queue=[],t.length>0&&queueMicrotask(function(){t.forEach(e)})},t.onDisconnect=function(e){this.onDisconnectCallback=e;var t=this.disconnectionDetails;t&&queueMicrotask(function(){e(t)})},t.onModeChange=function(e){this.onModeChangeCallback=e},t.updateMode=function(e){var t;null==(t=this.onModeChangeCallback)||t.call(this,e)},t.disconnect=function(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,null==(t=this.onDisconnectCallback)||t.call(this,e))},t.handleMessage=function(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)},e}();function c(e){var t=e.split("_"),n=t[0],o=t[1];if(!["pcm","ulaw"].includes(n))throw new Error("Invalid format: "+e);var r=Number.parseInt(o);if(Number.isNaN(r))throw new Error("Invalid sample rate: "+o);return{format:n,sampleRate:r}}var u="0.11.0";function l(e){return!!e.type}var d="conversation_initiation_client_data";function h(e){var t,n,o,r,i,a,s={type:d};return e.overrides&&(s.conversation_config_override={agent:{prompt:null==(n=e.overrides.agent)?void 0:n.prompt,first_message:null==(o=e.overrides.agent)?void 0:o.firstMessage,language:null==(r=e.overrides.agent)?void 0:r.language},tts:{voice_id:null==(i=e.overrides.tts)?void 0:i.voiceId},conversation:{text_only:null==(a=e.overrides.conversation)?void 0:a.textOnly}}),e.customLlmExtraBody&&(s.custom_llm_extra_body=e.customLlmExtraBody),e.dynamicVariables&&(s.dynamic_variables=e.dynamicVariables),e.userId&&(s.user_id=e.userId),null!=(t=e.overrides)&&t.client&&(s.source_info={source:e.overrides.client.source,version:e.overrides.client.version}),s}var p=/*#__PURE__*/function(e){function t(t,n,o,r){var i;return(i=e.call(this)||this).socket=void 0,i.conversationId=void 0,i.inputFormat=void 0,i.outputFormat=void 0,i.socket=t,i.conversationId=n,i.inputFormat=o,i.outputFormat=r,i.socket.addEventListener("error",function(e){setTimeout(function(){return i.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:e})},0)}),i.socket.addEventListener("close",function(e){i.disconnect(1e3===e.code?{reason:"agent",context:e}:{reason:"error",message:e.reason||"The connection was closed by the server.",context:e})}),i.socket.addEventListener("message",function(e){try{var t=JSON.parse(e.data);if(!l(t))return void i.debug({type:"invalid_event",message:"Received invalid socket event",data:e.data});i.handleMessage(t)}catch(t){i.debug({type:"parsing_error",message:"Failed to parse socket message",error:t instanceof Error?t.message:String(t),data:e.data})}}),i}n(t,e),t.create=function(e){try{var n=null;return Promise.resolve(function(o,r){try{var i=function(){var o,r,i,a,s=null!=(o=e.origin)?o:"wss://api.elevenlabs.io",d=(null==(r=e.overrides)||null==(r=r.client)?void 0:r.version)||u,p=(null==(i=e.overrides)||null==(i=i.client)?void 0:i.source)||"js_sdk";if(e.signedUrl){var m=e.signedUrl.includes("?")?"&":"?";a=""+e.signedUrl+m+"source="+p+"&version="+d}else a=s+"/v1/convai/conversation?agent_id="+e.agentId+"&source="+p+"&version="+d;var f=["convai"];return e.authorization&&f.push("bearer."+e.authorization),n=new WebSocket(a,f),Promise.resolve(new Promise(function(t,o){n.addEventListener("open",function(){var t,o=h(e);null==(t=n)||t.send(JSON.stringify(o))},{once:!0}),n.addEventListener("error",function(e){setTimeout(function(){return o(e)},0)}),n.addEventListener("close",o),n.addEventListener("message",function(e){var n=JSON.parse(e.data);l(n)&&("conversation_initiation_metadata"===n.type?t(n.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})})).then(function(e){var o=e.conversation_id,r=e.agent_output_audio_format,i=e.user_input_audio_format,a=c(null!=i?i:"pcm_16000"),s=c(r);return new t(n,o,a,s)})}()}catch(e){return r(e)}return i&&i.then?i.then(void 0,r):i}(0,function(e){var t;throw null==(t=n)||t.close(),e}))}catch(e){return Promise.reject(e)}};var o=t.prototype;return o.close=function(){this.socket.close()},o.sendMessage=function(e){this.socket.send(JSON.stringify(e))},o.setMicMuted=function(e){try{return console.warn("WebSocket connection setMicMuted called with "+e+", but this is handled by VoiceConversation"),Promise.resolve()}catch(e){return Promise.reject(e)}},t}(s);function m(e){var t=new Uint8Array(e);return window.btoa(String.fromCharCode.apply(String,t))}function f(e){for(var t=window.atob(e),n=t.length,o=new Uint8Array(n),r=0;r<n;r++)o[r]=t.charCodeAt(r);return o.buffer}function v(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var g=new Map;function _(e,t){return function(n,o){try{var r,i=function(o){var i;if(r)return o;function a(o){return i?o:v(function(){var o="data:application/javascript;base64,"+btoa(t);return Promise.resolve(n.addModule(o)).then(function(){g.set(e,o)})},function(){throw new Error("Failed to load the "+e+" worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.")})}var s=new Blob([t],{type:"application/javascript"}),c=URL.createObjectURL(s),u=v(function(){return Promise.resolve(n.addModule(c)).then(function(){g.set(e,c),i=1})},function(){URL.revokeObjectURL(c)});return u&&u.then?u.then(a):a(u)},a=g.get(e);if(a)return Promise.resolve(n.addModule(a));var s=function(){if(o)return v(function(){return Promise.resolve(n.addModule(o)).then(function(){g.set(e,o),r=1})},function(t){throw new Error("Failed to load the "+e+" worklet module from path: "+o+". Error: "+t)})}();return Promise.resolve(s&&s.then?s.then(i):i(s))}catch(e){return Promise.reject(e)}}}var b=_("rawAudioProcessor",'/*\n * ulaw encoding logic taken from the wavefile library\n * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js\n * USED BY @elevenlabs/client\n */\n\nconst BIAS = 0x84;\nconst CLIP = 32635;\nconst encodeTable = [\n 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,\n 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,\n 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,\n 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7\n];\n\nfunction encodeSample(sample) {\n let sign;\n let exponent;\n let mantissa;\n let muLawSample;\n sign = (sample >> 8) & 0x80;\n if (sign !== 0) sample = -sample;\n sample = sample + BIAS;\n if (sample > CLIP) sample = CLIP;\n exponent = encodeTable[(sample>>7) & 0xFF];\n mantissa = (sample >> (exponent+3)) & 0x0F;\n muLawSample = ~(sign | (exponent << 4) | mantissa);\n \n return muLawSample;\n}\n\nclass RawAudioProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n \n this.port.onmessage = ({ data }) => {\n switch (data.type) {\n case "setFormat":\n this.isMuted = false;\n this.buffer = []; // Initialize an empty buffer\n this.bufferSize = data.sampleRate / 4;\n this.format = data.format;\n\n if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) {\n globalThis.LibSampleRate.create(1, sampleRate, data.sampleRate).then(resampler => {\n this.resampler = resampler;\n });\n }\n break;\n case "setMuted":\n this.isMuted = data.isMuted;\n break;\n }\n };\n }\n process(inputs) {\n if (!this.buffer) {\n return true;\n }\n \n const input = inputs[0]; // Get the first input node\n if (input.length > 0) {\n let channelData = input[0]; // Get the first channel\'s data\n\n // Resample the audio if necessary\n if (this.resampler) {\n channelData = this.resampler.full(channelData);\n }\n\n // Add channel data to the buffer\n this.buffer.push(...channelData);\n // Get max volume \n let sum = 0.0;\n for (let i = 0; i < channelData.length; i++) {\n sum += channelData[i] * channelData[i];\n }\n const maxVolume = Math.sqrt(sum / channelData.length);\n // Check if buffer size has reached or exceeded the threshold\n if (this.buffer.length >= this.bufferSize) {\n const float32Array = this.isMuted \n ? new Float32Array(this.buffer.length)\n : new Float32Array(this.buffer);\n\n let encodedArray = this.format === "ulaw"\n ? new Uint8Array(float32Array.length)\n : new Int16Array(float32Array.length);\n\n // Iterate through the Float32Array and convert each sample to PCM16\n for (let i = 0; i < float32Array.length; i++) {\n // Clamp the value to the range [-1, 1]\n let sample = Math.max(-1, Math.min(1, float32Array[i]));\n\n // Scale the sample to the range [-32768, 32767]\n let value = sample < 0 ? sample * 32768 : sample * 32767;\n if (this.format === "ulaw") {\n value = encodeSample(Math.round(value));\n }\n\n encodedArray[i] = value;\n }\n\n // Send the buffered data to the main script\n this.port.postMessage([encodedArray, maxVolume]);\n\n // Clear the buffer after sending\n this.buffer = [];\n }\n }\n return true; // Continue processing\n }\n}\nregisterProcessor("rawAudioProcessor", RawAudioProcessor);\n');function y(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var P=/*#__PURE__*/function(t){function o(e,n,o,r,i){var a;return void 0===i&&(i={}),(a=t.call(this,i)||this).conversationId=void 0,a.inputFormat=void 0,a.outputFormat=void 0,a.room=void 0,a.isConnected=!1,a.audioEventId=1,a.audioCaptureContext=null,a.audioElements=[],a.outputDeviceId=null,a.outputAnalyser=null,a.outputFrequencyData=null,a.room=e,a.conversationId=n,a.inputFormat=o,a.outputFormat=r,a.setupRoomEventListeners(),a}n(o,t),o.create=function(t){try{var n,r=function(r){var i=new e.Room;return y(function(){var r="room_"+Date.now(),a=c("pcm_48000"),s=c("pcm_48000"),u=new o(i,r,a,s,t);return Promise.resolve(i.connect(t.livekitUrl||"wss://livekit.rtc.elevenlabs.io",n)).then(function(){return Promise.resolve(new Promise(function(t){if(u.isConnected)t();else{var n=function(){i.off(e.RoomEvent.Connected,n),t()};i.on(e.RoomEvent.Connected,n)}})).then(function(){var e;return i.name&&(u.conversationId=(null==(e=i.name.match(/(conv_[a-zA-Z0-9]+)/))?void 0:e[0])||i.name),Promise.resolve(i.localParticipant.setMicrophoneEnabled(!0)).then(function(){var e=h(t);return u.debug({type:d,message:e}),Promise.resolve(u.sendMessage(e)).then(function(){return u})})})})},function(e){return Promise.resolve(i.disconnect()).then(function(){throw e})})},i=function(){if(!("conversationToken"in t)||!t.conversationToken)return function(){if("agentId"in t&&t.agentId)return y(function(){var e,o,r,i=(null==(e=t.overrides)||null==(e=e.client)?void 0:e.version)||u,a=(null==(o=t.overrides)||null==(o=o.client)?void 0:o.source)||"js_sdk",s=function(e){return e.replace(/^wss:\/\//,"https://")}(null!=(r=t.origin)?r:"https://api.elevenlabs.io");return Promise.resolve(fetch(s+"/v1/convai/conversation/token?agent_id="+t.agentId+"&source="+a+"&version="+i)).then(function(e){if(!e.ok)throw new Error("ElevenLabs API returned "+e.status+" "+e.statusText);return Promise.resolve(e.json()).then(function(e){if(!(n=e.token))throw new Error("No conversation token received from API")})})},function(e){var n=e instanceof Error?e.message:String(e);throw e instanceof Error&&e.message.includes("401")&&(n="Your agent has authentication enabled, but no signed URL or conversation token was provided."),new Error("Failed to fetch conversation token for agent "+t.agentId+": "+n)});throw new Error("Either conversationToken or agentId is required for WebRTC connection")}();n=t.conversationToken}();return Promise.resolve(i&&i.then?i.then(r):r())}catch(e){return Promise.reject(e)}};var r=o.prototype;return r.setupRoomEventListeners=function(){var t=this,n=this,o=this,r=this;this.room.on(e.RoomEvent.Connected,function(){try{return n.isConnected=!0,console.info("WebRTC room connected"),Promise.resolve()}catch(e){return Promise.reject(e)}}),this.room.on(e.RoomEvent.Disconnected,function(e){t.isConnected=!1,t.disconnect({reason:"agent",context:new CloseEvent("close",{reason:null==e?void 0:e.toString()})})}),this.room.on(e.RoomEvent.ConnectionStateChanged,function(n){n===e.ConnectionState.Disconnected&&(t.isConnected=!1,t.disconnect({reason:"error",message:"LiveKit connection state changed to "+n,context:new Event("connection_state_changed")}))}),this.room.on(e.RoomEvent.DataReceived,function(e,n){try{var o=JSON.parse((new TextDecoder).decode(e));if("audio"===o.type)return;l(o)?t.handleMessage(o):console.warn("Invalid socket event received:",o)}catch(t){console.warn("Failed to parse incoming data message:",t),console.warn("Raw payload:",(new TextDecoder).decode(e))}}),this.room.on(e.RoomEvent.TrackSubscribed,function(t,n,r){try{var i=function(){if(t.kind===e.Track.Kind.Audio&&r.identity.includes("agent")){var n=function(){return a.style.display="none",document.body.appendChild(a),o.audioElements.push(a),1===o.audioElements.length&&(null==o.onDebug||o.onDebug({type:"audio_element_ready"})),Promise.resolve(o.setupAudioCapture(i)).then(function(){})},i=t,a=i.attach();a.autoplay=!0,a.controls=!1;var s=function(){if(o.outputDeviceId&&a.setSinkId){var e=y(function(){return Promise.resolve(a.setSinkId(o.outputDeviceId)).then(function(){})},function(e){console.warn("Failed to set output device for new audio element:",e)});if(e&&e.then)return e.then(function(){})}}();return s&&s.then?s.then(n):n()}}();return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),this.room.on(e.RoomEvent.ActiveSpeakersChanged,function(e){try{return r.updateMode(e.length>0&&e[0].identity.startsWith("agent")?"speaking":"listening"),Promise.resolve()}catch(e){return Promise.reject(e)}})},r.close=function(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(function(e){e.track&&e.track.stop()})}catch(e){console.warn("Error stopping local tracks:",e)}this.audioCaptureContext&&(this.audioCaptureContext.close().catch(function(e){console.warn("Error closing audio capture context:",e)}),this.audioCaptureContext=null),this.audioElements.forEach(function(e){e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}},r.sendMessage=function(e){try{var t=this;if(!t.isConnected||!t.room.localParticipant)return console.warn("Cannot send message: room not connected or no local participant"),Promise.resolve();if("user_audio_chunk"in e)return Promise.resolve();var n=y(function(){var n=(new TextEncoder).encode(JSON.stringify(e));return Promise.resolve(t.room.localParticipant.publishData(n,{reliable:!0})).then(function(){})},function(n){t.debug({type:"send_message_error",message:{message:e,error:n}}),console.error("Failed to send message via WebRTC:",n)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},r.getRoom=function(){return this.room},r.setMicMuted=function(t){try{var n=this;if(!n.isConnected||!n.room.localParticipant)return console.warn("Cannot set microphone muted: room not connected or no local participant"),Promise.resolve();var o=n.room.localParticipant.getTrackPublication(e.Track.Source.Microphone);return Promise.resolve(null!=o&&o.track?y(function(){var e=t?Promise.resolve(o.track.mute()).then(function(){}):Promise.resolve(o.track.unmute()).then(function(){});if(e&&e.then)return e.then(function(){})},function(){return Promise.resolve(n.room.localParticipant.setMicrophoneEnabled(!t)).then(function(){})}):Promise.resolve(n.room.localParticipant.setMicrophoneEnabled(!t)).then(function(){}))}catch(e){return Promise.reject(e)}},r.setupAudioCapture=function(e){try{var t=this,n=y(function(){var n=new AudioContext;t.audioCaptureContext=n,t.outputAnalyser=n.createAnalyser(),t.outputAnalyser.fftSize=2048,t.outputAnalyser.smoothingTimeConstant=.8;var o=new MediaStream([e.mediaStreamTrack]),r=n.createMediaStreamSource(o);return r.connect(t.outputAnalyser),Promise.resolve(b(n.audioWorklet)).then(function(){var e=new AudioWorkletNode(n,"rawAudioProcessor");t.outputAnalyser.connect(e),e.port.postMessage({type:"setFormat",format:t.outputFormat.format,sampleRate:t.outputFormat.sampleRate}),e.port.onmessage=function(e){var n=e.data;if(n[1]>.01){var o=m(n[0].buffer),r=t.audioEventId++;t.handleMessage({type:"audio",audio_event:{audio_base_64:o,event_id:r}})}},r.connect(e)})},function(e){console.warn("Failed to set up audio capture:",e)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},r.setAudioVolume=function(e){this.audioElements.forEach(function(t){t.volume=e})},r.setAudioOutputDevice=function(e){try{var t=this;if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");var n=t.audioElements.map(function(t){try{return Promise.resolve(y(function(){return Promise.resolve(t.setSinkId(e)).then(function(){})},function(e){throw console.error("Failed to set sink ID for audio element:",e),e}))}catch(e){return Promise.reject(e)}});return Promise.resolve(Promise.all(n)).then(function(){t.outputDeviceId=e})}catch(e){return Promise.reject(e)}},r.setAudioInputDevice=function(t){try{var n=this;if(!n.isConnected||!n.room.localParticipant)throw new Error("Cannot change input device: room not connected or no local participant");return Promise.resolve(y(function(){function o(){return Promise.resolve(e.createLocalAudioTrack({deviceId:{exact:t},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}})).then(function(t){return Promise.resolve(n.room.localParticipant.publishTrack(t,{name:"microphone",source:e.Track.Source.Microphone})).then(function(){})})}var r=n.room.localParticipant.getTrackPublication(e.Track.Source.Microphone),i=function(){if(null!=r&&r.track)return Promise.resolve(r.track.stop()).then(function(){return Promise.resolve(n.room.localParticipant.unpublishTrack(r.track)).then(function(){})})}();return i&&i.then?i.then(o):o()},function(e){function t(){throw e}console.error("Failed to change input device:",e);var o=y(function(){return Promise.resolve(n.room.localParticipant.setMicrophoneEnabled(!0)).then(function(){})},function(e){console.error("Failed to recover microphone after device switch error:",e)});return o&&o.then?o.then(t):t()}))}catch(e){return Promise.reject(e)}},r.getOutputByteFrequencyData=function(){return this.outputAnalyser?(null!=this.outputFrequencyData||(this.outputFrequencyData=new Uint8Array(this.outputAnalyser.frequencyBinCount)),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null},o}(s),w=function(e){try{var t=function(e){return e.connectionType?e.connectionType:"conversationToken"in e&&e.conversationToken?"webrtc":"websocket"}(e);switch(t){case"websocket":return Promise.resolve(p.create(e));case"webrtc":return Promise.resolve(P.create(e));default:throw new Error("Unknown connection type: "+t)}}catch(e){return Promise.reject(e)}};function S(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}var k=function(e){void 0===e&&(e={default:0,android:3e3});try{var t,n=e.default;if(/android/i.test(navigator.userAgent))n=null!=(t=e.android)?t:n;else if(S()){var o;n=null!=(o=e.ios)?o:n}var r=function(){if(n>0)return Promise.resolve(new Promise(function(e){return setTimeout(e,n)})).then(function(){})}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},C=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return n(t,e),t.startSession=function(e){try{var n=a.getFullOptions(e);n.onStatusChange&&n.onStatusChange({status:"connecting"}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1}),n.onModeChange&&n.onModeChange({mode:"listening"}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});var o=null;return Promise.resolve(function(r,i){try{var a=Promise.resolve(k(n.connectionDelay)).then(function(){return Promise.resolve(w(e)).then(function(e){return new t(n,o=e)})})}catch(e){return i(e)}return a&&a.then?a.then(void 0,i):a}(0,function(e){var t;throw n.onStatusChange&&n.onStatusChange({status:"disconnected"}),null==(t=o)||t.close(),e}))}catch(e){return Promise.reject(e)}},t}(a);function E(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var M={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},A=/*#__PURE__*/function(){function e(e,t,n,o,r){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=t,this.worklet=n,this.inputStream=o,this.mediaStreamSource=r}e.create=function(n){var o=n.sampleRate,r=n.format,i=n.preferHeadphonesForIosDevices,a=n.inputDeviceId,s=n.workletPaths,c=n.libsampleratePath;try{var u=null,l=null;return Promise.resolve(E(function(){function n(){function n(){return Promise.resolve(b(u.audioWorklet,null==s?void 0:s.rawAudioProcessor)).then(function(){var n=t({voiceIsolation:!0},d);return Promise.resolve(navigator.mediaDevices.getUserMedia({audio:n})).then(function(t){var n=u.createMediaStreamSource(l=t),i=new AudioWorkletNode(u,"rawAudioProcessor");return i.port.postMessage({type:"setFormat",format:r,sampleRate:o}),n.connect(h),h.connect(i),Promise.resolve(u.resume()).then(function(){return new e(u,h,i,l,n)})})})}a&&(d.deviceId={exact:a});var i=navigator.mediaDevices.getSupportedConstraints().sampleRate,h=(u=new window.AudioContext(i?{sampleRate:o}:{})).createAnalyser(),p=function(){if(!i)return Promise.resolve(u.audioWorklet.addModule(c||"https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js")).then(function(){})}();return p&&p.then?p.then(n):n()}var d=t({sampleRate:{ideal:o}},M),h=function(){if(S()&&i)return Promise.resolve(window.navigator.mediaDevices.enumerateDevices()).then(function(e){var t=e.find(function(e){return"audioinput"===e.kind&&["airpod","headphone","earphone"].find(function(t){return e.label.toLowerCase().includes(t)})});t&&(d.deviceId={ideal:t.deviceId})})}();return h&&h.then?h.then(n):n()},function(e){var t,n;throw null==(t=l)||t.getTracks().forEach(function(e){e.stop()}),null==(n=u)||n.close(),e}))}catch(e){return Promise.reject(e)}};var n=e.prototype;return n.close=function(){try{var e=this;return e.inputStream.getTracks().forEach(function(e){e.stop()}),e.mediaStreamSource.disconnect(),Promise.resolve(e.context.close()).then(function(){})}catch(e){return Promise.reject(e)}},n.setMuted=function(e){this.worklet.port.postMessage({type:"setMuted",isMuted:e})},n.setInputDevice=function(e){try{var n=this;return Promise.resolve(E(function(){var o=t({},M);e&&(o.deviceId={exact:e});var r=t({voiceIsolation:!0},o);return Promise.resolve(navigator.mediaDevices.getUserMedia({audio:r})).then(function(e){n.inputStream.getTracks().forEach(function(e){e.stop()}),n.mediaStreamSource.disconnect(),n.inputStream=e,n.mediaStreamSource=n.context.createMediaStreamSource(e),n.mediaStreamSource.connect(n.analyser)})},function(e){throw console.error("Failed to switch input device:",e),e}))}catch(e){return Promise.reject(e)}},e}(),I=_("audioConcatProcessor",'/*\n * ulaw decoding logic taken from the wavefile library\n * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js\n * USED BY @elevenlabs/client\n */\n\nconst decodeTable = [0,132,396,924,1980,4092,8316,16764];\n\nfunction decodeSample(muLawSample) {\n let sign;\n let exponent;\n let mantissa;\n let sample;\n muLawSample = ~muLawSample;\n sign = (muLawSample & 0x80);\n exponent = (muLawSample >> 4) & 0x07;\n mantissa = muLawSample & 0x0F;\n sample = decodeTable[exponent] + (mantissa << (exponent+3));\n if (sign !== 0) sample = -sample;\n\n return sample;\n}\n\nclass AudioConcatProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffers = []; // Initialize an empty buffer\n this.cursor = 0;\n this.currentBuffer = null;\n this.wasInterrupted = false;\n this.finished = false;\n \n this.port.onmessage = ({ data }) => {\n switch (data.type) {\n case "setFormat":\n this.format = data.format;\n break;\n case "buffer":\n this.wasInterrupted = false;\n this.buffers.push(\n this.format === "ulaw"\n ? new Uint8Array(data.buffer)\n : new Int16Array(data.buffer)\n );\n break;\n case "interrupt":\n this.wasInterrupted = true;\n break;\n case "clearInterrupted":\n if (this.wasInterrupted) {\n this.wasInterrupted = false;\n this.buffers = [];\n this.currentBuffer = null;\n }\n }\n };\n }\n process(_, outputs) {\n let finished = false;\n const output = outputs[0][0];\n for (let i = 0; i < output.length; i++) {\n if (!this.currentBuffer) {\n if (this.buffers.length === 0) {\n finished = true;\n break;\n }\n this.currentBuffer = this.buffers.shift();\n this.cursor = 0;\n }\n\n let value = this.currentBuffer[this.cursor];\n if (this.format === "ulaw") {\n value = decodeSample(value);\n }\n output[i] = value / 32768;\n this.cursor++;\n\n if (this.cursor >= this.currentBuffer.length) {\n this.currentBuffer = null;\n }\n }\n\n if (this.finished !== finished) {\n this.finished = finished;\n this.port.postMessage({ type: "process", finished });\n }\n\n return true; // Continue processing\n }\n}\n\nregisterProcessor("audioConcatProcessor", AudioConcatProcessor);\n'),D=/*#__PURE__*/function(){function e(e,t,n,o,r){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=t,this.gain=n,this.worklet=o,this.audioElement=r}e.create=function(t){var n=t.sampleRate,o=t.format,r=t.outputDeviceId,i=t.workletPaths;try{var a=null,s=null;return Promise.resolve(function(t,c){try{var u=function(){var t=(a=new AudioContext({sampleRate:n})).createAnalyser(),c=a.createGain();(s=new Audio).src="",s.load(),s.autoplay=!0,s.style.display="none",document.body.appendChild(s);var u=a.createMediaStreamDestination();return s.srcObject=u.stream,c.connect(t),t.connect(u),Promise.resolve(I(a.audioWorklet,null==i?void 0:i.audioConcatProcessor)).then(function(){var n=new AudioWorkletNode(a,"audioConcatProcessor");return n.port.postMessage({type:"setFormat",format:o}),n.connect(c),Promise.resolve(a.resume()).then(function(){function o(){return new e(a,t,c,n,s)}var i=function(){if(r&&s.setSinkId)return Promise.resolve(s.setSinkId(r)).then(function(){})}();return i&&i.then?i.then(o):o()})})}()}catch(e){return c(e)}return u&&u.then?u.then(void 0,c):u}(0,function(e){var t,n;function o(){throw e}null!=(t=s)&&t.parentNode&&s.parentNode.removeChild(s),null==(n=s)||n.pause();var r=function(){if(a&&"closed"!==a.state)return Promise.resolve(a.close()).then(function(){})}();return r&&r.then?r.then(o):o()}))}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.setOutputDevice=function(e){try{if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");return Promise.resolve(this.audioElement.setSinkId(e||"")).then(function(){})}catch(e){return Promise.reject(e)}},t.close=function(){try{var e=this;return e.audioElement.parentNode&&e.audioElement.parentNode.removeChild(e.audioElement),e.audioElement.pause(),Promise.resolve(e.context.close()).then(function(){})}catch(e){return Promise.reject(e)}},e}();function T(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var R,x=/*#__PURE__*/function(e){function o(t,n,o,r,i){var a;return(a=e.call(this,t,n)||this).input=void 0,a.output=void 0,a.wakeLock=void 0,a.inputFrequencyData=void 0,a.outputFrequencyData=void 0,a.onInputWorkletMessage=function(e){"connected"===a.status&&a.connection.sendMessage({user_audio_chunk:m(e.data[0].buffer)})},a.onOutputWorkletMessage=function(e){var t=e.data;"process"===t.type&&a.updateMode(t.finished?"listening":"speaking")},a.addAudioBase64Chunk=function(e){a.output.gain.gain.cancelScheduledValues(a.output.context.currentTime),a.output.gain.gain.value=a.volume,a.output.worklet.port.postMessage({type:"clearInterrupted"}),a.output.worklet.port.postMessage({type:"buffer",buffer:f(e)})},a.fadeOutAudio=function(){a.updateMode("listening"),a.output.worklet.port.postMessage({type:"interrupt"}),a.output.gain.gain.exponentialRampToValueAtTime(1e-4,a.output.context.currentTime+2),setTimeout(function(){a.output.gain.gain.value=a.volume,a.output.worklet.port.postMessage({type:"clearInterrupted"})},2e3)},a.calculateVolume=function(e){if(0===e.length)return 0;for(var t=0,n=0;n<e.length;n++)t+=e[n]/255;return(t/=e.length)<0?0:t>1?1:t},a.setVolume=function(e){var t=e.volume,n=Number.isFinite(t)?Math.min(1,Math.max(0,t)):1;a.volume=n,a.connection instanceof P?a.connection.setAudioVolume(n):a.output.gain.gain.value=n},a.input=o,a.output=r,a.wakeLock=i,a.input.worklet.port.onmessage=a.onInputWorkletMessage,a.output.worklet.port.onmessage=a.onOutputWorkletMessage,a}n(o,e),o.startSession=function(e){try{var n=function(){return T(function(){return Promise.resolve(navigator.mediaDevices.getUserMedia({audio:!0})).then(function(n){return u=n,Promise.resolve(k(r.connectionDelay)).then(function(){return Promise.resolve(w(e)).then(function(n){return s=n,Promise.resolve(Promise.all([A.create(t({},s.inputFormat,{preferHeadphonesForIosDevices:e.preferHeadphonesForIosDevices,inputDeviceId:e.inputDeviceId,workletPaths:e.workletPaths,libsampleratePath:e.libsampleratePath})),D.create(t({},s.outputFormat,{outputDeviceId:e.outputDeviceId,workletPaths:e.workletPaths}))])).then(function(e){var t;return i=e[0],c=e[1],null==(t=u)||t.getTracks().forEach(function(e){e.stop()}),u=null,new o(r,s,i,c,l)})})})})},function(e){var t,n,o;return r.onStatusChange&&r.onStatusChange({status:"disconnected"}),null==(t=u)||t.getTracks().forEach(function(e){e.stop()}),null==(n=s)||n.close(),Promise.resolve(null==(o=i)?void 0:o.close()).then(function(){var t;return Promise.resolve(null==(t=c)?void 0:t.close()).then(function(){function t(){throw e}var n=T(function(){var e;return Promise.resolve(null==(e=l)?void 0:e.release()).then(function(){l=null})},function(){});return n&&n.then?n.then(t):t()})})})},r=a.getFullOptions(e);r.onStatusChange&&r.onStatusChange({status:"connecting"}),r.onCanSendFeedbackChange&&r.onCanSendFeedbackChange({canSendFeedback:!1});var i=null,s=null,c=null,u=null,l=null,d=function(t){if(null==(t=e.useWakeLock)||t){var n=T(function(){return Promise.resolve(navigator.wakeLock.request("screen")).then(function(e){l=e})},function(){});if(n&&n.then)return n.then(function(){})}}();return Promise.resolve(d&&d.then?d.then(n):n())}catch(e){return Promise.reject(e)}};var r=o.prototype;return r.handleEndSession=function(){try{var t=this;return Promise.resolve(e.prototype.handleEndSession.call(t)).then(function(){function e(){return Promise.resolve(t.input.close()).then(function(){return Promise.resolve(t.output.close()).then(function(){})})}var n=T(function(){var e;return Promise.resolve(null==(e=t.wakeLock)?void 0:e.release()).then(function(){t.wakeLock=null})},function(){});return n&&n.then?n.then(e):e()})}catch(e){return Promise.reject(e)}},r.handleInterruption=function(t){e.prototype.handleInterruption.call(this,t),this.fadeOutAudio()},r.handleAudio=function(e){var t,n;this.lastInterruptTimestamp<=e.audio_event.event_id&&(null==(t=(n=this.options).onAudio)||t.call(n,e.audio_event.audio_base_64),this.connection instanceof P||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))},r.setMicMuted=function(e){this.connection instanceof P?this.connection.setMicMuted(e):this.input.setMuted(e)},r.getInputByteFrequencyData=function(){return null!=this.inputFrequencyData||(this.inputFrequencyData=new Uint8Array(this.input.analyser.frequencyBinCount)),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData},r.getOutputByteFrequencyData=function(){return this.connection instanceof P?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(null!=this.outputFrequencyData||(this.outputFrequencyData=new Uint8Array(this.output.analyser.frequencyBinCount)),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)},r.getInputVolume=function(){return this.calculateVolume(this.getInputByteFrequencyData())},r.getOutputVolume=function(){return this.calculateVolume(this.getOutputByteFrequencyData())},r.changeInputDevice=function(e){var t=e.sampleRate,n=e.format,o=e.preferHeadphonesForIosDevices,r=e.inputDeviceId;try{var i,a=this;return Promise.resolve(T(function(){function e(e){if(i)return e;function s(){return Promise.resolve(a.input.close()).then(function(){return Promise.resolve(A.create({sampleRate:null!=t?t:a.connection.inputFormat.sampleRate,format:null!=n?n:a.connection.inputFormat.format,preferHeadphonesForIosDevices:o,inputDeviceId:r,workletPaths:a.options.workletPaths,libsampleratePath:a.options.libsampleratePath})).then(function(e){return a.input=e,a.input.worklet.port.onmessage=a.onInputWorkletMessage,a.input})})}var c=function(){if(a.connection instanceof P)return Promise.resolve(a.connection.setAudioInputDevice(r||"")).then(function(){})}();return c&&c.then?c.then(s):s()}var s=function(){if(a.connection instanceof p)return T(function(){return Promise.resolve(a.input.setInputDevice(r)).then(function(){return i=1,a.input})},function(e){console.warn("Failed to change device on existing input, recreating:",e)})}();return s&&s.then?s.then(e):e(s)},function(e){throw console.error("Error changing input device",e),e}))}catch(e){return Promise.reject(e)}},r.changeOutputDevice=function(e){var t=e.sampleRate,n=e.format,o=e.outputDeviceId;try{var r,i=this;return Promise.resolve(T(function(){function e(e){if(r)return e;function a(){return Promise.resolve(i.output.close()).then(function(){return Promise.resolve(D.create({sampleRate:null!=t?t:i.connection.outputFormat.sampleRate,format:null!=n?n:i.connection.outputFormat.format,outputDeviceId:o,workletPaths:i.options.workletPaths})).then(function(e){return i.output=e,i.output})})}var s=function(){if(i.connection instanceof P)return Promise.resolve(i.connection.setAudioOutputDevice(o||"")).then(function(){})}();return s&&s.then?s.then(a):a()}var a=function(){if(i.connection instanceof p)return T(function(){return Promise.resolve(i.output.setOutputDevice(o)).then(function(){return r=1,i.output})},function(e){console.warn("Failed to change device on existing output, recreating:",e)})}();return a&&a.then?a.then(e):e(a)},function(e){throw console.error("Error changing output device",e),e}))}catch(e){return Promise.reject(e)}},o}(a),F=/*#__PURE__*/function(){function e(){this.listeners=new Map}var t=e.prototype;return t.on=function(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);var n=this.listeners.get(e);n&&n.add(t)},t.off=function(e,t){var n=this.listeners.get(e);n&&n.delete(t)},t.emit=function(e){var t=arguments,n=this.listeners.get(e);n&&n.forEach(function(e){e.apply(void 0,[].slice.call(t,1))})},e}();exports.RealtimeEvents=void 0,(R=exports.RealtimeEvents||(exports.RealtimeEvents={})).SESSION_STARTED="session_started",R.PARTIAL_TRANSCRIPT="partial_transcript",R.COMMITTED_TRANSCRIPT="committed_transcript",R.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",R.AUTH_ERROR="auth_error",R.ERROR="error",R.OPEN="open",R.CLOSE="close",R.QUOTA_EXCEEDED="quota_exceeded";var O,L,U=/*#__PURE__*/function(){function e(e){this.websocket=null,this.eventEmitter=new F,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}var t=e.prototype;return t.setWebSocket=function(e){var t=this;this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(exports.RealtimeEvents.OPEN):this.websocket.addEventListener("open",function(){t.eventEmitter.emit(exports.RealtimeEvents.OPEN)}),this.websocket.addEventListener("message",function(e){try{var n=JSON.parse(e.data);switch(n.message_type){case"session_started":t.eventEmitter.emit(exports.RealtimeEvents.SESSION_STARTED,n);break;case"partial_transcript":t.eventEmitter.emit(exports.RealtimeEvents.PARTIAL_TRANSCRIPT,n);break;case"committed_transcript":t.eventEmitter.emit(exports.RealtimeEvents.COMMITTED_TRANSCRIPT,n);break;case"committed_transcript_with_timestamps":t.eventEmitter.emit(exports.RealtimeEvents.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,n);break;case"auth_error":t.eventEmitter.emit(exports.RealtimeEvents.AUTH_ERROR,n);break;case"quota_exceeded":t.eventEmitter.emit(exports.RealtimeEvents.QUOTA_EXCEEDED,n);break;case"error":t.eventEmitter.emit(exports.RealtimeEvents.ERROR,n);break;default:console.warn("Unknown message type:",n)}}catch(n){console.error("Failed to parse WebSocket message:",n,e.data),t.eventEmitter.emit(exports.RealtimeEvents.ERROR,new Error("Failed to parse message: "+n))}}),this.websocket.addEventListener("error",function(e){console.error("WebSocket error:",e),t.eventEmitter.emit(exports.RealtimeEvents.ERROR,e)}),this.websocket.addEventListener("close",function(e){if(console.log("WebSocket closed: code="+e.code+', reason="'+e.reason+'", wasClean='+e.wasClean),!e.wasClean||1e3!==e.code&&1005!==e.code){var n="WebSocket closed unexpectedly: "+e.code+" - "+(e.reason||"No reason provided");console.error(n),t.eventEmitter.emit(exports.RealtimeEvents.ERROR,new Error(n))}t.eventEmitter.emit(exports.RealtimeEvents.CLOSE,e)})},t.on=function(e,t){this.eventEmitter.on(e,t)},t.off=function(e,t){this.eventEmitter.off(e,t)},t.send=function(e){var t,n;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");var o={message_type:"input_audio_chunk",audio_base_64:e.audioBase64,commit:null!=(t=e.commit)&&t,sample_rate:null!=(n=e.sampleRate)?n:this.currentSampleRate};this.websocket.send(JSON.stringify(o))},t.commit=function(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");this.websocket.send(JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:this.currentSampleRate}))},t.close=function(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close()},e}(),j=_("scribeAudioProcessor",'/*\n * Scribe Audio Processor for converting microphone audio to PCM16 format\n * USED BY @elevenlabs/client\n */\n\nclass ScribeAudioProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = [];\n this.bufferSize = 4096; // Buffer size for optimal chunk transmission\n }\n\n process(inputs) {\n const input = inputs[0];\n if (input.length > 0) {\n const channelData = input[0]; // Get first channel (mono)\n\n // Add incoming audio to buffer\n this.buffer.push(...channelData);\n\n // When buffer reaches threshold, convert and send\n if (this.buffer.length >= this.bufferSize) {\n const float32Array = new Float32Array(this.buffer);\n const int16Array = new Int16Array(float32Array.length);\n\n // Convert Float32 [-1, 1] to Int16 [-32768, 32767]\n for (let i = 0; i < float32Array.length; i++) {\n // Clamp the value to prevent overflow\n const sample = Math.max(-1, Math.min(1, float32Array[i]));\n // Scale to PCM16 range\n int16Array[i] = sample < 0 ? sample * 32768 : sample * 32767;\n }\n\n // Send to main thread as transferable ArrayBuffer\n this.port.postMessage(\n {\n audioData: int16Array.buffer\n },\n [int16Array.buffer]\n );\n\n // Clear buffer\n this.buffer = [];\n }\n }\n\n return true; // Continue processing\n }\n}\n\nregisterProcessor("scribeAudioProcessor", ScribeAudioProcessor);\n\n');exports.AudioFormat=void 0,(O=exports.AudioFormat||(exports.AudioFormat={})).PCM_8000="pcm_8000",O.PCM_16000="pcm_16000",O.PCM_22050="pcm_22050",O.PCM_24000="pcm_24000",O.PCM_44100="pcm_44100",O.PCM_48000="pcm_48000",O.ULAW_8000="ulaw_8000",exports.CommitStrategy=void 0,(L=exports.CommitStrategy||(exports.CommitStrategy={})).MANUAL="manual",L.VAD="vad";var W=/*#__PURE__*/function(){function e(){}return e.getWebSocketUri=function(t){return void 0===t&&(t=e.DEFAULT_BASE_URI),t+"/v1/speech-to-text/realtime"},e.buildWebSocketUri=function(t){var n=e.getWebSocketUri(t.baseUri),o=new URLSearchParams;if(o.append("model_id",t.modelId),o.append("token",t.token),void 0!==t.commitStrategy&&o.append("commit_strategy",t.commitStrategy),void 0!==t.vadSilenceThresholdSecs){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw new Error("vadSilenceThresholdSecs must be between 0.3 and 3.0");o.append("vad_silence_threshold_secs",t.vadSilenceThresholdSecs.toString())}if(void 0!==t.vadThreshold){if(t.vadThreshold<.1||t.vadThreshold>.9)throw new Error("vadThreshold must be between 0.1 and 0.9");o.append("vad_threshold",t.vadThreshold.toString())}if(void 0!==t.minSpeechDurationMs){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw new Error("minSpeechDurationMs must be between 50 and 2000");o.append("min_speech_duration_ms",t.minSpeechDurationMs.toString())}if(void 0!==t.minSilenceDurationMs){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw new Error("minSilenceDurationMs must be between 50 and 2000");o.append("min_silence_duration_ms",t.minSilenceDurationMs.toString())}void 0!==t.languageCode&&o.append("language_code",t.languageCode),void 0!==t.includeTimestamps&&o.append("include_timestamps",t.includeTimestamps?"true":"false");var r=o.toString();return r?n+"?"+r:n},e.connect=function(t){if(!t.modelId)throw new Error("modelId is required");var n=new U("microphone"in t&&t.microphone?16e3:t.sampleRate),o=e.buildWebSocketUri(t),r=new WebSocket(o);return"microphone"in t&&t.microphone&&r.addEventListener("open",function(){e.streamFromMicrophone(t,n)}),n.setWebSocket(r),n},e.streamFromMicrophone=function(e,t){try{return Promise.resolve(function(n,o){try{var r=Promise.resolve(navigator.mediaDevices.getUserMedia({audio:{deviceId:null==(i=e.microphone)?void 0:i.deviceId,echoCancellation:null==(a=null==(s=e.microphone)?void 0:s.echoCancellation)||a,noiseSuppression:null==(c=null==(u=e.microphone)?void 0:u.noiseSuppression)||c,autoGainControl:null==(l=null==(d=e.microphone)?void 0:d.autoGainControl)||l,channelCount:null!=(h=null==(p=e.microphone)?void 0:p.channelCount)?h:1,sampleRate:{ideal:16e3}}})).then(function(e){var n=new AudioContext({sampleRate:16e3});return Promise.resolve(j(n.audioWorklet)).then(function(){function o(){t._audioCleanup=function(){e.getTracks().forEach(function(e){e.stop()}),r.disconnect(),i.disconnect(),n.close()}}var r=n.createMediaStreamSource(e),i=new AudioWorkletNode(n,"scribeAudioProcessor");i.port.onmessage=function(e){for(var n=new Uint8Array(e.data.audioData),o="",r=0;r<n.length;r++)o+=String.fromCharCode(n[r]);var i=btoa(o);t.send({audioBase64:i})},r.connect(i);var a=function(){if("suspended"===n.state)return Promise.resolve(n.resume()).then(function(){})}();return a&&a.then?a.then(o):o()})})}catch(e){return o(e)}var i,a,s,c,u,l,d,h,p;return r&&r.then?r.then(void 0,o):r}(0,function(e){throw console.error("Failed to start microphone streaming:",e),e}))}catch(e){return Promise.reject(e)}},e}();W.DEFAULT_BASE_URI="wss://api.elevenlabs.io",exports.Conversation=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return n(t,e),t.startSession=function(e){return e.textOnly?C.startSession(e):x.startSession(e)},t}(a),exports.Input=A,exports.Output=D,exports.RealtimeConnection=U,exports.Scribe=W,exports.TextConversation=C,exports.VoiceConversation=x,exports.WebRTCConnection=P,exports.WebSocketConnection=p,exports.createConnection=w,exports.postOverallFeedback=function(e,t,n){void 0===n&&(n="https://api.elevenlabs.io");var o={};return"boolean"==typeof t?o.feedback=t?"like":"dislike":(o.rating=t.rating,o.comment=t.comment),fetch(n+"/v1/convai/conversations/"+e+"/feedback",{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})};
|
|
2
2
|
//# sourceMappingURL=lib.cjs.map
|