@vox-ai/react 0.3.0 → 0.3.2

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.
File without changes
@@ -15,7 +15,7 @@ export interface FunctionCallInfo {
15
15
  id: string;
16
16
  type: string;
17
17
  call_id: string;
18
- arguments: string;
18
+ arguments: Record<string, any>;
19
19
  name: string;
20
20
  }
21
21
  export interface FunctionCallResult {
@@ -51,12 +51,14 @@ export interface VoxAIOptions {
51
51
  /**
52
52
  * ConnectParams
53
53
  * @param agentId - The agent ID
54
+ * @param agentVersion - The agent version, if not provided, the current version will be used
54
55
  * @param apiKey - The API key
55
56
  * @param dynamicVariables - The dynamic variables
56
57
  * @param metadata - 이 메타데이터는 아웃바운드 웹훅, 통화 기록에 포함됩니다.
57
58
  */
58
59
  export interface ConnectParams {
59
60
  agentId: string;
61
+ agentVersion?: number;
60
62
  apiKey: string;
61
63
  dynamicVariables?: Record<string, any>;
62
64
  metadata?: Record<string, any>;
package/dist/index.d.ts CHANGED
File without changes
package/dist/lib.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e=require("react/jsx-runtime"),t=require("@livekit/components-react"),n=require("livekit-client"),r=require("react"),o=require("react-dom/client");function a(e){let{port:o,initialConfig:a}=e;const{agent:s,state:c}=t.useVoiceAssistant(),{send:i}=t.useChat(),[u,l]=r.useState({speaker:a.speaker||"agent",barCount:a.barCount,updateInterval:a.updateInterval}),p=t.useParticipantTracks([n.Track.Source.Microphone],null==s?void 0:s.identity)[0],d=t.useTrackTranscription(p),m=t.useAudioWaveform(p,{barCount:"agent"===u.speaker?u.barCount:120,updateInterval:"agent"===u.speaker?u.updateInterval:20}),f=t.useLocalParticipant(),g=t.useTrackTranscription({publication:f.microphoneTrack,source:n.Track.Source.Microphone,participant:f.localParticipant}),v=t.useParticipantTracks([n.Track.Source.Microphone],f.localParticipant.identity)[0],y=t.useAudioWaveform(v,{barCount:"user"===u.speaker?u.barCount:120,updateInterval:"user"===u.speaker?u.updateInterval:20});return r.useEffect(()=>{o&&m&&m.bars&&o.postMessage({type:"waveform_update",waveformData:m.bars,speaker:"agent"})},[o,m]),r.useEffect(()=>{o&&y&&y.bars&&o.postMessage({type:"waveform_update",waveformData:y.bars,speaker:"user"})},[o,y]),r.useEffect(()=>{if(!o)return;const e=e=>{const t=e.data;if("waveform_config"===t.type&&t.config)"number"==typeof t.config.barCount&&"number"==typeof t.config.updateInterval&&l(t.config);else if("send_text"===t.type)i?i(t.text):console.error("sendChat function is not available");else if("send_dtmf"===t.type)f.localParticipant?f.localParticipant.publishDtmf(101,t.digit):console.error("Local participant is not available for DTMF");else if("toggle_mic"===t.type&&"boolean"==typeof t.enabled)f.localParticipant?f.localParticipant.setMicrophoneEnabled(t.enabled).catch(e=>{console.error("Failed to toggle microphone:",e)}):console.error("Local participant is not available for mic toggle");else if("set_volume"===t.type&&"number"==typeof t.volume)if(s)try{s.setVolume(t.volume),console.log("Set agent volume to "+t.volume)}catch(e){console.error("Failed to set agent volume:",e)}else console.error("Agent is not available for volume control")};return o.start(),o.addEventListener("message",e),()=>{o.removeEventListener("message",e)}},[o,i,f,s]),r.useEffect(()=>{o&&o.postMessage({type:"state_update",state:c})},[c,o]),r.useEffect(()=>{if(o&&d.segments.length>0){const e=d.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"agent"}));o.postMessage({type:"transcription_update",transcriptions:e})}},[d.segments,o]),r.useEffect(()=>{if(o&&g.segments.length>0){const e=g.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"user"}));o.postMessage({type:"transcription_update",transcriptions:e})}},[g.segments,o]),t.useDataChannel("function_tools_executed",e=>{if(!o)return;const t=new TextDecoder,n=e.payload instanceof Uint8Array?t.decode(e.payload):String(e.payload);let r;try{r=JSON.parse(n),o.postMessage({type:"function_tools_executed",tool:r})}catch(e){console.error("Failed to parse function call log:",e)}}),null}exports.useVoxAI=function(n){void 0===n&&(n={});const[s,c]=r.useState(null),[i,u]=r.useState("disconnected"),l=r.useRef(Date.now()),[p,d]=r.useState(new Map),[m,f]=r.useState([]),g=r.useRef(""),v=r.useRef(new Set),y=r.useRef(null),b=r.useRef(null),h=r.useRef(null),k=r.useRef(null),[w,C]=r.useState({agent:[],user:[]}),M=r.useRef(null),[E,_]=r.useState(!0);r.useEffect(()=>{const e=Array.from(p.values()).sort((e,t)=>e.timestamp-t.timestamp),t=JSON.stringify(e);t!==g.current&&(g.current=t,f(e),n.onMessage&&e.filter(e=>e.isFinal&&e.id&&!v.current.has(e.id)).forEach(e=>{e.id&&(v.current.add(e.id),null==n.onMessage||n.onMessage(e))}))},[p,n.onMessage]),r.useEffect(()=>{const e=new MessageChannel;return e.port1.onmessage=e=>{const t=e.data;if("state_update"===t.type)u(t.state);else if("transcription_update"===t.type)x(t.transcriptions);else if("waveform_update"===t.type&&t.speaker)C(e=>({...e,[t.speaker]:t.waveformData}));else if("function_tools_executed"===t.type&&t.tool){const e="function-calls-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"tool",tool:t.tool,timestamp:Date.now(),isFinal:!0}),r})}},e.port1.start(),h.current=e,()=>{var e,t;null==(e=h.current)||e.port1.close(),null==(t=h.current)||t.port2.close(),h.current=null}},[]);const x=r.useCallback(e=>{d(t=>{const n=new Map(t);return e.forEach(e=>{var r;if(e.timestamp<l.current)return;const o="agent"===e.speaker?"agent":"user",a=(null==(r=t.get(e.id))?void 0:r.timestamp)||e.timestamp;n.set(e.id,{id:e.id,name:o,message:e.text,timestamp:a,isFinal:e.isFinal})}),n})},[]);r.useEffect(()=>{const e=document.createElement("div");return e.style.display="none",document.body.appendChild(e),y.current=e,b.current=o.createRoot(e),()=>{b.current&&b.current.unmount(),y.current&&document.body.removeChild(y.current)}},[]);const D=r.useCallback(function(e){let{agentId:t,apiKey:r,dynamicVariables:o,metadata:a}=e;try{return Promise.resolve(function(e,s){try{var p=function(){if("disconnected"!==i){const e="Connection attempt rejected: Already in a connection state ("+i+")";return console.warn(e),n.onError&&n.onError(new Error(e)),Promise.reject(new Error(e))}return l.current=Date.now(),u("connecting"),Promise.resolve(fetch("https://www.tryvox.co/api/agent/sdk",{method:"POST",headers:{Authorization:"Bearer "+r,"Content-Type":"application/json"},body:JSON.stringify({agent_id:t,metadata:{runtime_context:{source:{type:"react-sdk",version:"0.3.0"}},call_web:{dynamic_variables:o||{},metadata:a||{}}}})})).then(function(e){function t(t){return Promise.resolve(e.json()).then(function(e){c(e),n.onConnect&&n.onConnect()})}const r=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(t){throw new Error("Connection failed ("+e.status+"): "+t)})}();return r&&r.then?r.then(t):t()})}()}catch(e){return s(e)}return p&&p.then?p.then(void 0,s):p}(0,function(e){c(null),d(new Map),f([]),u("disconnected");const t=e instanceof Error?e:new Error(String(e));n.onError&&n.onError(t)}))}catch(e){return Promise.reject(e)}},[n,i]),S=r.useCallback(()=>{l.current=Date.now(),c(null),d(new Map),f([]),u("disconnected"),n.onDisconnect&&n.onDisconnect()},[n]),P=r.useCallback(e=>{let{message:t,digit:n}=e;if("disconnected"!==i){if(t){const e="user-text-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"user",message:t,timestamp:Date.now(),isFinal:!0}),r}),h.current?h.current.port1.postMessage({type:"send_text",text:t}):console.error("No message channel available to send message")}void 0!==n&&(h.current?h.current.port1.postMessage({type:"send_dtmf",digit:n}):console.error("No message channel available to send DTMF"))}else console.warn("Cannot send message: Not connected to a conversation")},[i]),T=r.useCallback(e=>{let{speaker:t="agent",barCount:n=10,updateInterval:r=20}=e;M.current={speaker:t,barCount:n,updateInterval:r},h.current&&h.current.port1.postMessage({type:"waveform_config",config:{speaker:t,barCount:n,updateInterval:r}});const o=w[t]||[];return o.length>0?o.slice(0,n):Array(n).fill(0)},[w]),F=r.useCallback(e=>{_(e),h.current?h.current.port1.postMessage({type:"toggle_mic",enabled:e}):console.error("No message channel available to toggle microphone")},[]),I=r.useCallback(e=>{const t=Math.min(Math.max(e,0),1);h.current?h.current.port1.postMessage({type:"set_volume",volume:t}):console.error("No message channel available to set volume")},[]);return r.useEffect(()=>{b.current&&(s?(k.current||(h.current&&h.current.port2.start(),k.current=e.jsxs(t.LiveKitRoom,{serverUrl:s.serverUrl,token:s.participantToken,audio:!0,video:!1,connect:!0,onDisconnected:S,onError:e=>{console.error("LiveKit connection error:",e),S(),n.onError&&n.onError(new Error("LiveKit connection error: "+e.message))},children:[e.jsx(t.RoomAudioRenderer,{}),h.current&&e.jsx(a,{port:h.current.port2,initialConfig:M.current||{barCount:10,updateInterval:20}})]})),b.current.render(k.current)):(k.current=null,b.current.render(e.jsx(e.Fragment,{}))))},[s,S,n.onError]),{connect:D,disconnect:S,state:i,messages:m,send:P,audioWaveform:T,toggleMic:F,setVolume:I}};
1
+ var e=require("react/jsx-runtime"),t=require("@livekit/components-react"),n=require("livekit-client"),r=require("react"),o=require("react-dom/client");function a(e){let{port:o,initialConfig:a}=e;const{agent:s,state:c}=t.useVoiceAssistant(),{send:i}=t.useChat(),[u,l]=r.useState({speaker:a.speaker||"agent",barCount:a.barCount,updateInterval:a.updateInterval}),p=t.useParticipantTracks([n.Track.Source.Microphone],null==s?void 0:s.identity)[0],d=t.useTrackTranscription(p),m=t.useAudioWaveform(p,{barCount:"agent"===u.speaker?u.barCount:120,updateInterval:"agent"===u.speaker?u.updateInterval:20}),f=t.useLocalParticipant(),g=t.useTrackTranscription({publication:f.microphoneTrack,source:n.Track.Source.Microphone,participant:f.localParticipant}),v=t.useParticipantTracks([n.Track.Source.Microphone],f.localParticipant.identity)[0],y=t.useAudioWaveform(v,{barCount:"user"===u.speaker?u.barCount:120,updateInterval:"user"===u.speaker?u.updateInterval:20});return r.useEffect(()=>{o&&m&&m.bars&&o.postMessage({type:"waveform_update",waveformData:m.bars,speaker:"agent"})},[o,m]),r.useEffect(()=>{o&&y&&y.bars&&o.postMessage({type:"waveform_update",waveformData:y.bars,speaker:"user"})},[o,y]),r.useEffect(()=>{if(!o)return;const e=e=>{const t=e.data;if("waveform_config"===t.type&&t.config)"number"==typeof t.config.barCount&&"number"==typeof t.config.updateInterval&&l(t.config);else if("send_text"===t.type)i?i(t.text):console.error("sendChat function is not available");else if("send_dtmf"===t.type)f.localParticipant?f.localParticipant.publishDtmf(101,t.digit):console.error("Local participant is not available for DTMF");else if("toggle_mic"===t.type&&"boolean"==typeof t.enabled)f.localParticipant?f.localParticipant.setMicrophoneEnabled(t.enabled).catch(e=>{console.error("Failed to toggle microphone:",e)}):console.error("Local participant is not available for mic toggle");else if("set_volume"===t.type&&"number"==typeof t.volume)if(s)try{s.setVolume(t.volume),console.log("Set agent volume to "+t.volume)}catch(e){console.error("Failed to set agent volume:",e)}else console.error("Agent is not available for volume control")};return o.start(),o.addEventListener("message",e),()=>{o.removeEventListener("message",e)}},[o,i,f,s]),r.useEffect(()=>{o&&o.postMessage({type:"state_update",state:c})},[c,o]),r.useEffect(()=>{if(o&&d.segments.length>0){const e=d.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"agent"}));o.postMessage({type:"transcription_update",transcriptions:e})}},[d.segments,o]),r.useEffect(()=>{if(o&&g.segments.length>0){const e=g.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"user"}));o.postMessage({type:"transcription_update",transcriptions:e})}},[g.segments,o]),t.useDataChannel("function_tools_executed",e=>{if(!o)return;const t=new TextDecoder,n=e.payload instanceof Uint8Array?t.decode(e.payload):String(e.payload);let r;try{r=JSON.parse(n),o.postMessage({type:"function_tools_executed",tool:r})}catch(e){console.error("Failed to parse function call log:",e)}}),null}exports.useVoxAI=function(n){void 0===n&&(n={});const[s,c]=r.useState(null),[i,u]=r.useState("disconnected"),l=r.useRef(Date.now()),[p,d]=r.useState(new Map),[m,f]=r.useState([]),g=r.useRef(""),v=r.useRef(new Set),y=r.useRef(null),b=r.useRef(null),h=r.useRef(null),k=r.useRef(null),[w,C]=r.useState({agent:[],user:[]}),M=r.useRef(null),[E,_]=r.useState(!0);r.useEffect(()=>{const e=Array.from(p.values()).sort((e,t)=>e.timestamp-t.timestamp),t=JSON.stringify(e);t!==g.current&&(g.current=t,f(e),n.onMessage&&e.filter(e=>e.isFinal&&e.id&&!v.current.has(e.id)).forEach(e=>{e.id&&(v.current.add(e.id),null==n.onMessage||n.onMessage(e))}))},[p,n.onMessage]),r.useEffect(()=>{const e=new MessageChannel;return e.port1.onmessage=e=>{const t=e.data;if("state_update"===t.type)u(t.state);else if("transcription_update"===t.type)x(t.transcriptions);else if("waveform_update"===t.type&&t.speaker)C(e=>({...e,[t.speaker]:t.waveformData}));else if("function_tools_executed"===t.type&&t.tool){const e="function-calls-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"tool",tool:t.tool,timestamp:Date.now(),isFinal:!0}),r})}},e.port1.start(),h.current=e,()=>{var e,t;null==(e=h.current)||e.port1.close(),null==(t=h.current)||t.port2.close(),h.current=null}},[]);const x=r.useCallback(e=>{d(t=>{const n=new Map(t);return e.forEach(e=>{var r;if(e.timestamp<l.current)return;const o="agent"===e.speaker?"agent":"user",a=(null==(r=t.get(e.id))?void 0:r.timestamp)||e.timestamp;n.set(e.id,{id:e.id,name:o,message:e.text,timestamp:a,isFinal:e.isFinal})}),n})},[]);r.useEffect(()=>{const e=document.createElement("div");return e.style.display="none",document.body.appendChild(e),y.current=e,b.current=o.createRoot(e),()=>{b.current&&b.current.unmount(),y.current&&document.body.removeChild(y.current)}},[]);const D=r.useCallback(function(e){let{agentId:t,apiKey:r,dynamicVariables:o,metadata:a}=e;try{return Promise.resolve(function(e,s){try{var p=function(){if("disconnected"!==i){const e="Connection attempt rejected: Already in a connection state ("+i+")";return console.warn(e),n.onError&&n.onError(new Error(e)),Promise.reject(new Error(e))}return l.current=Date.now(),u("connecting"),Promise.resolve(fetch("https://www.tryvox.co/api/agent/sdk",{method:"POST",headers:{Authorization:"Bearer "+r,"Content-Type":"application/json"},body:JSON.stringify({agent_id:t,metadata:{runtime_context:{source:{type:"react-sdk",version:"0.3.2"}},call_web:{dynamic_variables:o||{},metadata:a||{}}}})})).then(function(e){function t(t){return Promise.resolve(e.json()).then(function(e){c(e),n.onConnect&&n.onConnect()})}const r=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(t){throw new Error("Connection failed ("+e.status+"): "+t)})}();return r&&r.then?r.then(t):t()})}()}catch(e){return s(e)}return p&&p.then?p.then(void 0,s):p}(0,function(e){c(null),d(new Map),f([]),u("disconnected");const t=e instanceof Error?e:new Error(String(e));n.onError&&n.onError(t)}))}catch(e){return Promise.reject(e)}},[n,i]),S=r.useCallback(()=>{l.current=Date.now(),c(null),d(new Map),f([]),u("disconnected"),n.onDisconnect&&n.onDisconnect()},[n]),P=r.useCallback(e=>{let{message:t,digit:n}=e;if("disconnected"!==i){if(t){const e="user-text-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"user",message:t,timestamp:Date.now(),isFinal:!0}),r}),h.current?h.current.port1.postMessage({type:"send_text",text:t}):console.error("No message channel available to send message")}void 0!==n&&(h.current?h.current.port1.postMessage({type:"send_dtmf",digit:n}):console.error("No message channel available to send DTMF"))}else console.warn("Cannot send message: Not connected to a conversation")},[i]),T=r.useCallback(e=>{let{speaker:t="agent",barCount:n=10,updateInterval:r=20}=e;M.current={speaker:t,barCount:n,updateInterval:r},h.current&&h.current.port1.postMessage({type:"waveform_config",config:{speaker:t,barCount:n,updateInterval:r}});const o=w[t]||[];return o.length>0?o.slice(0,n):Array(n).fill(0)},[w]),F=r.useCallback(e=>{_(e),h.current?h.current.port1.postMessage({type:"toggle_mic",enabled:e}):console.error("No message channel available to toggle microphone")},[]),I=r.useCallback(e=>{const t=Math.min(Math.max(e,0),1);h.current?h.current.port1.postMessage({type:"set_volume",volume:t}):console.error("No message channel available to set volume")},[]);return r.useEffect(()=>{b.current&&(s?(k.current||(h.current&&h.current.port2.start(),k.current=e.jsxs(t.LiveKitRoom,{serverUrl:s.serverUrl,token:s.participantToken,audio:!0,video:!1,connect:!0,onDisconnected:S,onError:e=>{console.error("LiveKit connection error:",e),S(),n.onError&&n.onError(new Error("LiveKit connection error: "+e.message))},children:[e.jsx(t.RoomAudioRenderer,{}),h.current&&e.jsx(a,{port:h.current.port2,initialConfig:M.current||{barCount:10,updateInterval:20}})]})),b.current.render(k.current)):(k.current=null,b.current.render(e.jsx(e.Fragment,{}))))},[s,S,n.onError]),{connect:D,disconnect:S,state:i,messages:m,send:P,audioWaveform:T,toggleMic:F,setVolume:I}};
2
2
  //# sourceMappingURL=lib.cjs.map
package/dist/lib.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lib.cjs","sources":["../src/hooks/useVoxAI.tsx","../src/utils/constants.ts"],"sourcesContent":["import {\n LiveKitRoom,\n RoomAudioRenderer,\n useAudioWaveform,\n useChat,\n useDataChannel,\n useLocalParticipant,\n useParticipantTracks,\n useTrackTranscription,\n useVoiceAssistant,\n} from \"@livekit/components-react\";\nimport { Track } from \"livekit-client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport { HTTPS_API_ORIGIN, SDK_VERSION } from \"../utils/constants\";\n\ntype VoxConnectionDetail = {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n};\n\n/**\n * VoxAgentState\n * @description The state of the agent\n */\nexport type VoxAgentState =\n | \"disconnected\"\n | \"connecting\"\n | \"initializing\"\n | \"listening\"\n | \"thinking\"\n | \"speaking\";\n\n/**\n * Function call related types\n */\nexport interface FunctionToolsExecuted {\n type: \"function_tools_executed\";\n function_calls: FunctionCallInfo[];\n function_call_outputs: FunctionCallResult[];\n}\n\nexport interface FunctionCallInfo {\n id: string;\n type: string;\n call_id: string;\n arguments: string;\n name: string;\n}\n\nexport interface FunctionCallResult {\n id: string;\n name: string;\n type: string;\n call_id: string;\n output: string;\n is_error: boolean;\n}\n\n/**\n * VoxMessage\n * @description The message type between the agent and the user\n */\nexport type VoxMessage = {\n id?: string;\n name: \"agent\" | \"user\" | \"tool\";\n message?: string;\n timestamp: number;\n isFinal?: boolean;\n tool?: FunctionToolsExecuted;\n};\n\n/**\n * VoxAIOptions\n * @description The callback functions for the useVoxAI hook\n */\nexport interface VoxAIOptions {\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onMessage?: (message: VoxMessage) => void;\n}\n\n// Message channel event types\ntype MessageChannelEvent =\n | { type: \"state_update\"; state: VoxAgentState }\n | { type: \"transcription_update\"; transcriptions: TranscriptionSegment[] }\n | {\n type: \"waveform_update\";\n waveformData: number[];\n speaker: \"agent\" | \"user\";\n }\n | { type: \"function_tools_executed\"; tool: FunctionToolsExecuted };\n\ntype TranscriptionSegment = {\n id: string;\n text: string;\n isFinal: boolean;\n timestamp: number;\n speaker: \"agent\" | \"user\";\n};\n\n/**\n * ConnectParams\n * @param agentId - The agent ID\n * @param apiKey - The API key\n * @param dynamicVariables - The dynamic variables\n * @param metadata - 이 메타데이터는 아웃바운드 웹훅, 통화 기록에 포함됩니다.\n */\nexport interface ConnectParams {\n agentId: string;\n apiKey: string;\n dynamicVariables?: Record<string, any>;\n metadata?: Record<string, any>;\n}\n\n/**\n * useVoxAI\n * @description The hook for integrating with vox.ai voice assistant\n * @param options - The options for the useVoxAI hook\n * @returns The useVoxAI hook\n * @example\n * const { connect, disconnect, state, messages, send } = useVoxAI({\n * onConnect: () => console.log(\"Connected\"),\n * onDisconnect: () => console.log(\"Disconnected\"),\n * onError: (error) => console.error(\"Error:\", error),\n * onMessage: (message) => console.log(\"Message:\", message),\n * });\n */\nexport function useVoxAI(options: VoxAIOptions = {}) {\n // Connection state\n const [connectionDetail, setConnectionDetail] =\n useState<VoxConnectionDetail | null>(null);\n const [state, setState] = useState<VoxAgentState>(\"disconnected\");\n\n // Session timestamp to filter out stale asynchronous events\n const sessionTimestampRef = useRef<number>(Date.now());\n\n // Message handling\n const [transcriptMap, setTranscriptMap] = useState<Map<string, VoxMessage>>(\n new Map()\n );\n const [messages, setMessages] = useState<VoxMessage[]>([]);\n const prevMessagesRef = useRef<string>(\"\");\n\n // Track which messages we've already sent to the onMessage callback\n const processedMessageIdsRef = useRef<Set<string>>(new Set());\n\n // DOM manipulation for LiveKit portal\n const portalRootRef = useRef<HTMLDivElement | null>(null);\n const rootRef = useRef<Root | null>(null);\n\n // Communication channel\n const channelRef = useRef<MessageChannel | null>(null);\n\n // Add this near the start of your useVoxAI hook\n const livekitComponentRef = useRef<React.ReactNode>(null);\n\n // Replace the single waveform state with a map for multiple speakers\n const [waveformDataMap, setWaveformDataMap] = useState<\n Record<string, number[]>\n >({\n agent: [],\n user: [],\n });\n\n // Add back the waveform config reference\n const waveformConfigRef = useRef<{\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n } | null>(null);\n\n // Add a new state to track microphone status\n const [isMicEnabled, setIsMicEnabled] = useState<boolean>(true);\n\n // Update messages whenever transcriptMap changes\n useEffect(() => {\n const allMessages = Array.from(transcriptMap.values()).sort(\n (a, b) => a.timestamp - b.timestamp\n );\n\n // Only update if the messages have actually changed\n const messagesString = JSON.stringify(allMessages);\n if (messagesString !== prevMessagesRef.current) {\n prevMessagesRef.current = messagesString;\n setMessages(allMessages);\n\n // Only trigger onMessage for new final messages that haven't been processed yet\n if (options.onMessage) {\n allMessages\n .filter(\n (msg) =>\n msg.isFinal &&\n msg.id &&\n !processedMessageIdsRef.current.has(msg.id)\n )\n .forEach((msg) => {\n if (msg.id) {\n // Mark this message as processed\n processedMessageIdsRef.current.add(msg.id);\n // Call the callback\n options.onMessage?.(msg);\n }\n });\n }\n }\n }, [transcriptMap, options.onMessage]);\n\n // Initialize message channel - ensure ports are properly connected\n useEffect(() => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (e) => {\n const data = e.data as MessageChannelEvent;\n\n if (data.type === \"state_update\") {\n setState(data.state);\n } else if (data.type === \"transcription_update\") {\n handleTranscriptionUpdate(data.transcriptions);\n } else if (data.type === \"waveform_update\" && data.speaker) {\n // Store the waveform data for the specific speaker\n setWaveformDataMap((prevMap) => ({\n ...prevMap,\n [data.speaker]: data.waveformData,\n }));\n } else if (data.type === \"function_tools_executed\" && data.tool) {\n // Handle function calls\n const functionCallsId = `function-calls-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(functionCallsId, {\n id: functionCallsId,\n name: \"tool\",\n tool: data.tool,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n }\n };\n\n // Start the port\n channel.port1.start();\n\n // Store the channel reference\n channelRef.current = channel;\n\n return () => {\n channelRef.current?.port1.close();\n channelRef.current?.port2.close();\n channelRef.current = null;\n };\n }, []);\n\n // Process incoming transcriptions and filter out stale events\n const handleTranscriptionUpdate = useCallback(\n (transcriptions: TranscriptionSegment[]) => {\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n\n transcriptions.forEach((t) => {\n // Only process transcriptions generated after the current session timestamp\n if (t.timestamp < sessionTimestampRef.current) {\n return;\n }\n const messageType = t.speaker === \"agent\" ? \"agent\" : \"user\";\n // Use existing timestamp if we already have this segment\n const existingTimestamp = prevMap.get(t.id)?.timestamp || t.timestamp;\n\n newMap.set(t.id, {\n id: t.id,\n name: messageType,\n message: t.text,\n timestamp: existingTimestamp,\n isFinal: t.isFinal,\n });\n });\n\n return newMap;\n });\n },\n []\n );\n\n // Set up DOM portal for LiveKit\n useEffect(() => {\n const div = document.createElement(\"div\");\n div.style.display = \"none\";\n document.body.appendChild(div);\n portalRootRef.current = div;\n rootRef.current = createRoot(div);\n\n return () => {\n if (rootRef.current) {\n rootRef.current.unmount();\n }\n if (portalRootRef.current) {\n document.body.removeChild(portalRootRef.current);\n }\n };\n }, []);\n\n // Connect to VoxAI service - updated to include dynamicVariables\n const connect = useCallback(\n async ({ agentId, apiKey, dynamicVariables, metadata }: ConnectParams) => {\n try {\n // Prevent connecting if already in a connection state\n if (state !== \"disconnected\") {\n const errorMessage = `Connection attempt rejected: Already in a connection state (${state})`;\n console.warn(errorMessage);\n\n if (options.onError) {\n options.onError(new Error(errorMessage));\n }\n return Promise.reject(new Error(errorMessage));\n }\n\n // Update session timestamp for new connection\n sessionTimestampRef.current = Date.now();\n setState(\"connecting\");\n\n const response = await fetch(HTTPS_API_ORIGIN, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agent_id: agentId,\n metadata: {\n runtime_context: {\n source: {\n type: \"react-sdk\",\n version: SDK_VERSION,\n },\n },\n call_web: {\n dynamic_variables: dynamicVariables || {},\n metadata: metadata || {},\n },\n },\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Connection failed (${response.status}): ${errorText}`\n );\n }\n\n const data = await response.json();\n setConnectionDetail(data);\n\n if (options.onConnect) {\n options.onConnect();\n }\n } catch (err) {\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n if (options.onError) {\n options.onError(error);\n }\n }\n },\n [options, state]\n );\n\n // Disconnect from VoxAI service, updating the session timestamp to ignore stale events\n const disconnect = useCallback(() => {\n // Update session timestamp on disconnect\n sessionTimestampRef.current = Date.now();\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n if (options.onDisconnect) {\n options.onDisconnect();\n }\n }, [options]);\n\n // Update the send function with debugging and error checking\n const send = useCallback(\n ({ message, digit }: { message?: string; digit?: number }) => {\n if (state === \"disconnected\") {\n console.warn(\"Cannot send message: Not connected to a conversation\");\n return;\n }\n\n if (message) {\n const messageId = `user-text-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(messageId, {\n id: messageId,\n name: \"user\",\n message: message,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_text\",\n text: message,\n });\n } else {\n console.error(\"No message channel available to send message\");\n }\n }\n\n if (digit !== undefined) {\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_dtmf\",\n digit: digit,\n });\n } else {\n console.error(\"No message channel available to send DTMF\");\n }\n }\n },\n [state]\n );\n\n // Update the audioWaveform function to return data for the requested speaker\n const audioWaveform = useCallback(\n ({\n speaker = \"agent\",\n barCount = 10,\n updateInterval = 20,\n }: {\n speaker?: \"agent\" | \"user\";\n barCount?: number;\n updateInterval?: number;\n }): number[] => {\n waveformConfigRef.current = { speaker, barCount, updateInterval };\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"waveform_config\",\n config: { speaker, barCount, updateInterval },\n });\n }\n\n const speakerData = waveformDataMap[speaker] || [];\n return speakerData.length > 0\n ? speakerData.slice(0, barCount)\n : Array(barCount).fill(0);\n },\n [waveformDataMap]\n );\n\n // Add toggleMic function that will be exposed in the hook's return value\n const toggleMic = useCallback((value: boolean) => {\n setIsMicEnabled(value);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"toggle_mic\",\n enabled: value,\n });\n } else {\n console.error(\"No message channel available to toggle microphone\");\n }\n }, []);\n\n // Add setVolume function that will be exposed in the hook's return value\n const setVolume = useCallback((volume: number) => {\n const validVolume = Math.min(Math.max(volume, 0), 1);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"set_volume\",\n volume: validVolume,\n });\n } else {\n console.error(\"No message channel available to set volume\");\n }\n }, []);\n\n // Modify the useEffect hook that renders the LiveKit component\n useEffect(() => {\n if (!rootRef.current) return;\n\n if (connectionDetail) {\n if (!livekitComponentRef.current) {\n if (channelRef.current) {\n channelRef.current.port2.start();\n }\n\n livekitComponentRef.current = (\n <LiveKitRoom\n serverUrl={connectionDetail.serverUrl}\n token={connectionDetail.participantToken}\n audio={true}\n video={false}\n connect={true}\n onDisconnected={disconnect}\n onError={(error) => {\n console.error(\"LiveKit connection error:\", error);\n disconnect();\n if (options.onError) {\n options.onError(\n new Error(`LiveKit connection error: ${error.message}`)\n );\n }\n }}\n >\n <RoomAudioRenderer />\n {channelRef.current && (\n <StateMonitor\n port={channelRef.current.port2}\n initialConfig={\n waveformConfigRef.current || {\n barCount: 10,\n updateInterval: 20,\n }\n }\n />\n )}\n </LiveKitRoom>\n );\n }\n rootRef.current.render(livekitComponentRef.current);\n } else {\n livekitComponentRef.current = null;\n rootRef.current.render(<></>);\n }\n }, [connectionDetail, disconnect, options.onError]);\n\n return {\n connect,\n disconnect,\n state,\n messages,\n send,\n audioWaveform,\n toggleMic,\n setVolume,\n };\n}\n\n/**\n * Component that monitors LiveKit state and communicates back to the main hook\n */\nfunction StateMonitor({\n port,\n initialConfig,\n}: {\n port: MessagePort | undefined;\n initialConfig: {\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n };\n}) {\n const { agent, state } = useVoiceAssistant();\n const { send: sendChat } = useChat();\n\n // Initialize waveform config with the passed initial values, defaulting to \"agent\" if not specified\n const [waveformConfig, setWaveformConfig] = useState({\n speaker: initialConfig.speaker || \"agent\",\n barCount: initialConfig.barCount,\n updateInterval: initialConfig.updateInterval,\n });\n\n // Agent transcriptions\n const agentAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n agent?.identity\n )[0];\n const agentTranscription = useTrackTranscription(agentAudioTrack);\n\n // Use the current config for the waveform, applying different settings based on speaker\n const agentAudioWaveform = useAudioWaveform(agentAudioTrack, {\n barCount:\n waveformConfig.speaker === \"agent\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"agent\" ? waveformConfig.updateInterval : 20,\n });\n\n // User transcriptions\n const localParticipant = useLocalParticipant();\n const localMessages = useTrackTranscription({\n publication: localParticipant.microphoneTrack,\n source: Track.Source.Microphone,\n participant: localParticipant.localParticipant,\n });\n const localAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n localParticipant.localParticipant.identity\n )[0];\n const userAudioWaveform = useAudioWaveform(localAudioTrack, {\n barCount: waveformConfig.speaker === \"user\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"user\" ? waveformConfig.updateInterval : 20,\n });\n\n // Add separate effects to send agent and user waveform data\n useEffect(() => {\n if (!port || !agentAudioWaveform || !agentAudioWaveform.bars) return;\n\n // Send the agent waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: agentAudioWaveform.bars,\n speaker: \"agent\",\n });\n }, [port, agentAudioWaveform]);\n\n useEffect(() => {\n if (!port || !userAudioWaveform || !userAudioWaveform.bars) return;\n\n // Send the user waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: userAudioWaveform.bars,\n speaker: \"user\",\n });\n }, [port, userAudioWaveform]);\n\n // Listen for messages including config updates and mic toggle commands\n useEffect(() => {\n if (!port) return;\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n\n if (data.type === \"waveform_config\" && data.config) {\n // Verify we have both required properties before updating\n if (\n typeof data.config.barCount === \"number\" &&\n typeof data.config.updateInterval === \"number\"\n ) {\n setWaveformConfig(data.config);\n }\n } else if (data.type === \"send_text\") {\n if (sendChat) {\n sendChat(data.text);\n } else {\n console.error(\"sendChat function is not available\");\n }\n } else if (data.type === \"send_dtmf\") {\n if (localParticipant.localParticipant) {\n // Use standard DTMF code (RFC 4733)\n const standardDtmfCode = 101; // Standard DTMF payload type\n localParticipant.localParticipant.publishDtmf(\n standardDtmfCode,\n data.digit\n );\n } else {\n console.error(\"Local participant is not available for DTMF\");\n }\n } else if (\n data.type === \"toggle_mic\" &&\n typeof data.enabled === \"boolean\"\n ) {\n // Handle microphone toggle\n if (localParticipant.localParticipant) {\n localParticipant.localParticipant\n .setMicrophoneEnabled(data.enabled)\n .catch((error) => {\n console.error(\"Failed to toggle microphone:\", error);\n });\n } else {\n console.error(\"Local participant is not available for mic toggle\");\n }\n } else if (\n data.type === \"set_volume\" &&\n typeof data.volume === \"number\"\n ) {\n // Handle volume control\n if (agent) {\n // The agent is a RemoteParticipant, so we can call setVolume directly\n try {\n agent.setVolume(data.volume);\n console.log(`Set agent volume to ${data.volume}`);\n } catch (error) {\n console.error(\"Failed to set agent volume:\", error);\n }\n } else {\n console.error(\"Agent is not available for volume control\");\n }\n }\n };\n\n // Make sure we start the port\n port.start();\n\n port.addEventListener(\"message\", handleMessage);\n\n return () => {\n port.removeEventListener(\"message\", handleMessage);\n };\n }, [port, sendChat, localParticipant, agent]);\n\n // Send agent state updates\n useEffect(() => {\n if (port) {\n port.postMessage({ type: \"state_update\", state });\n }\n }, [state, port]);\n\n // Send agent transcriptions\n useEffect(() => {\n if (port && agentTranscription.segments.length > 0) {\n const transcriptions = agentTranscription.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"agent\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [agentTranscription.segments, port]);\n\n // Send user transcriptions\n useEffect(() => {\n if (port && localMessages.segments.length > 0) {\n const transcriptions = localMessages.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"user\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [localMessages.segments, port]);\n\n // Add data channel hook for function calls\n const { message: functionToolsExecuted } = useDataChannel(\n \"function_tools_executed\",\n (msg) => {\n if (!port) return;\n\n const textDecoder = new TextDecoder();\n const messageString =\n msg.payload instanceof Uint8Array\n ? textDecoder.decode(msg.payload)\n : String(msg.payload);\n\n let tool: FunctionToolsExecuted;\n try {\n tool = JSON.parse(messageString);\n\n // Send function calls to main hook via the port\n port.postMessage({\n type: \"function_tools_executed\",\n tool: tool,\n });\n } catch (e) {\n console.error(\"Failed to parse function call log:\", e);\n }\n }\n );\n\n return null;\n}\n","// export const HTTPS_API_ORIGIN = \"https://frontend-dev.tryvox.co/api/agent/sdk\";\nexport const HTTPS_API_ORIGIN = \"https://www.tryvox.co/api/agent/sdk\";\n// export const HTTPS_API_ORIGIN = \"http://localhost:3000/api/agent/sdk\";\nexport const SDK_VERSION = \"0.3.0\";\n"],"names":["StateMonitor","_ref4","port","initialConfig","agent","state","useVoiceAssistant","send","sendChat","useChat","waveformConfig","setWaveformConfig","useState","speaker","barCount","updateInterval","agentAudioTrack","useParticipantTracks","Track","Source","Microphone","identity","agentTranscription","useTrackTranscription","agentAudioWaveform","useAudioWaveform","localParticipant","useLocalParticipant","localMessages","publication","microphoneTrack","source","participant","localAudioTrack","userAudioWaveform","useEffect","bars","postMessage","type","waveformData","handleMessage","event","data","config","text","console","error","publishDtmf","digit","enabled","setMicrophoneEnabled","catch","volume","setVolume","log","start","addEventListener","removeEventListener","segments","length","transcriptions","map","segment","id","isFinal","final","timestamp","Date","now","useDataChannel","msg","textDecoder","TextDecoder","messageString","payload","Uint8Array","decode","String","tool","JSON","parse","e","options","connectionDetail","setConnectionDetail","setState","sessionTimestampRef","useRef","transcriptMap","setTranscriptMap","Map","messages","setMessages","prevMessagesRef","processedMessageIdsRef","Set","portalRootRef","rootRef","channelRef","livekitComponentRef","waveformDataMap","setWaveformDataMap","user","waveformConfigRef","isMicEnabled","setIsMicEnabled","allMessages","Array","from","values","sort","a","b","messagesString","stringify","current","onMessage","filter","has","forEach","add","channel","MessageChannel","port1","onmessage","handleTranscriptionUpdate","prevMap","functionCallsId","newMap","set","name","_channelRef$current","_channelRef$current2","close","port2","useCallback","t","_prevMap$get","messageType","existingTimestamp","get","message","div","document","createElement","style","display","body","appendChild","createRoot","unmount","removeChild","connect","_ref","agentId","apiKey","dynamicVariables","metadata","Promise","resolve","errorMessage","warn","onError","Error","reject","fetch","method","headers","Authorization","agent_id","runtime_context","version","call_web","dynamic_variables","then","response","_temp2","_result2","_exit","json","onConnect","_temp","ok","errorText","status","_catch","err","disconnect","onDisconnect","_ref2","messageId","undefined","audioWaveform","_ref3","speakerData","slice","fill","toggleMic","value","validVolume","Math","min","max","_jsxs","LiveKitRoom","serverUrl","token","participantToken","audio","video","onDisconnected","children","_jsx","RoomAudioRenderer","render","_Fragment"],"mappings":"uJA4iBA,SAASA,EAAYC,GAAC,IAAAC,KACpBA,EAAIC,cACJA,GAQDF,EACC,MAAMG,MAAEA,EAAKC,MAAEA,GAAUC,EAAAA,qBACjBC,KAAMC,GAAaC,EAAOA,WAG3BC,EAAgBC,GAAqBC,WAAS,CACnDC,QAASV,EAAcU,SAAW,QAClCC,SAAUX,EAAcW,SACxBC,eAAgBZ,EAAcY,iBAI1BC,EAAkBC,uBACtB,CAACC,EAAKA,MAACC,OAAOC,YACT,MAALhB,OAAK,EAALA,EAAOiB,UACP,GACIC,EAAqBC,EAAqBA,sBAACP,GAG3CQ,EAAqBC,EAAgBA,iBAACT,EAAiB,CAC3DF,SAC6B,UAA3BJ,EAAeG,QAAsBH,EAAeI,SAAW,IACjEC,eAC6B,UAA3BL,EAAeG,QAAsBH,EAAeK,eAAiB,KAInEW,EAAmBC,wBACnBC,EAAgBL,EAAqBA,sBAAC,CAC1CM,YAAaH,EAAiBI,gBAC9BC,OAAQb,EAAKA,MAACC,OAAOC,WACrBY,YAAaN,EAAiBA,mBAE1BO,EAAkBhB,EAAoBA,qBAC1C,CAACC,EAAKA,MAACC,OAAOC,YACdM,EAAiBA,iBAAiBL,UAClC,GACIa,EAAoBT,EAAAA,iBAAiBQ,EAAiB,CAC1DnB,SAAqC,SAA3BJ,EAAeG,QAAqBH,EAAeI,SAAW,IACxEC,eAC6B,SAA3BL,EAAeG,QAAqBH,EAAeK,eAAiB,KA2KxE,OAvKAoB,EAAAA,UAAU,KACHjC,GAASsB,GAAuBA,EAAmBY,MAGxDlC,EAAKmC,YAAY,CACfC,KAAM,kBACNC,aAAcf,EAAmBY,KACjCvB,QAAS,WAEV,CAACX,EAAMsB,IAEVW,EAAAA,UAAU,KACHjC,GAASgC,GAAsBA,EAAkBE,MAGtDlC,EAAKmC,YAAY,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AChB,EACC,IAGGO,EAAYkF,EAAAA,YAAanF,IAC7B,MAAMmJ,EAAcC,KAAKC,IAAID,KAAKE,IAAItJ,EAAQ,GAAI,GAC9C8C,EAAWiB,QACbjB,EAAWiB,QAAQQ,MAAMtF,YAAY,CACnCC,KAAM,aACNc,OAAQmJ,IAGV1J,QAAQC,MAAM,6CAChB,EACC,IAoDH,OAjDAX,EAAAA,UAAU,KACH8D,EAAQkB,UAEThC,GACGgB,EAAoBgB,UACnBjB,EAAWiB,SACbjB,EAAWiB,QAAQmB,MAAM/E,QAG3B4C,EAAoBgB,QAClBwF,EAAAA,KAACC,EAAWA,aACVC,UAAW1H,EAAiB0H,UAC5BC,MAAO3H,EAAiB4H,iBACxBC,OAAO,EACPC,OAAO,EACPzD,SAAS,EACT0D,eAAgBvB,EAChBzB,QAAUpH,IACRD,QAAQC,MAAM,4BAA6BA,GAC3C6I,IACIzG,EAAQgF,SACVhF,EAAQgF,QACN,IAAIC,MAAmCrH,6BAAAA,EAAM+F,SAEjD,EACDsE,SAAA,CAEDC,EAAAA,IAACC,EAAiBA,kBAAG,IACpBnH,EAAWiB,SACViG,EAAAA,IAACpN,EAAY,CACXE,KAAMgG,EAAWiB,QAAQmB,MACzBnI,cACEoG,EAAkBY,SAAW,CAC3BrG,SAAU,GACVC,eAAgB,UAQ9BkF,EAAQkB,QAAQmG,OAAOnH,EAAoBgB,WAE3ChB,EAAoBgB,QAAU,KAC9BlB,EAAQkB,QAAQmG,OAAOF,MAAAG,EAAAA,SAAA,CAAA,KACzB,EACC,CAACpI,EAAkBwG,EAAYzG,EAAQgF,UAEnC,CACLV,UACAmC,aACAtL,QACAsF,WACApF,OACAyL,gBACAK,YACAhJ,YAEJ"}
1
+ {"version":3,"file":"lib.cjs","sources":["../src/hooks/useVoxAI.tsx","../src/utils/constants.ts"],"sourcesContent":["import {\n LiveKitRoom,\n RoomAudioRenderer,\n useAudioWaveform,\n useChat,\n useDataChannel,\n useLocalParticipant,\n useParticipantTracks,\n useTrackTranscription,\n useVoiceAssistant,\n} from \"@livekit/components-react\";\nimport { Track } from \"livekit-client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport { HTTPS_API_ORIGIN, SDK_VERSION } from \"../utils/constants\";\n\ntype VoxConnectionDetail = {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n};\n\n/**\n * VoxAgentState\n * @description The state of the agent\n */\nexport type VoxAgentState =\n | \"disconnected\"\n | \"connecting\"\n | \"initializing\"\n | \"listening\"\n | \"thinking\"\n | \"speaking\";\n\n/**\n * Function call related types\n */\nexport interface FunctionToolsExecuted {\n type: \"function_tools_executed\";\n function_calls: FunctionCallInfo[];\n function_call_outputs: FunctionCallResult[];\n}\n\nexport interface FunctionCallInfo {\n id: string;\n type: string;\n call_id: string;\n arguments: Record<string, any>;\n name: string;\n}\n\nexport interface FunctionCallResult {\n id: string;\n name: string;\n type: string;\n call_id: string;\n output: string;\n is_error: boolean;\n}\n\n/**\n * VoxMessage\n * @description The message type between the agent and the user\n */\nexport type VoxMessage = {\n id?: string;\n name: \"agent\" | \"user\" | \"tool\";\n message?: string;\n timestamp: number;\n isFinal?: boolean;\n tool?: FunctionToolsExecuted;\n};\n\n/**\n * VoxAIOptions\n * @description The callback functions for the useVoxAI hook\n */\nexport interface VoxAIOptions {\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onMessage?: (message: VoxMessage) => void;\n}\n\n// Message channel event types\ntype MessageChannelEvent =\n | { type: \"state_update\"; state: VoxAgentState }\n | { type: \"transcription_update\"; transcriptions: TranscriptionSegment[] }\n | {\n type: \"waveform_update\";\n waveformData: number[];\n speaker: \"agent\" | \"user\";\n }\n | { type: \"function_tools_executed\"; tool: FunctionToolsExecuted };\n\ntype TranscriptionSegment = {\n id: string;\n text: string;\n isFinal: boolean;\n timestamp: number;\n speaker: \"agent\" | \"user\";\n};\n\n/**\n * ConnectParams\n * @param agentId - The agent ID\n * @param agentVersion - The agent version, if not provided, the current version will be used\n * @param apiKey - The API key\n * @param dynamicVariables - The dynamic variables\n * @param metadata - 이 메타데이터는 아웃바운드 웹훅, 통화 기록에 포함됩니다.\n */\nexport interface ConnectParams {\n agentId: string;\n agentVersion?: number;\n apiKey: string;\n dynamicVariables?: Record<string, any>;\n metadata?: Record<string, any>;\n}\n\n/**\n * useVoxAI\n * @description The hook for integrating with vox.ai voice assistant\n * @param options - The options for the useVoxAI hook\n * @returns The useVoxAI hook\n * @example\n * const { connect, disconnect, state, messages, send } = useVoxAI({\n * onConnect: () => console.log(\"Connected\"),\n * onDisconnect: () => console.log(\"Disconnected\"),\n * onError: (error) => console.error(\"Error:\", error),\n * onMessage: (message) => console.log(\"Message:\", message),\n * });\n */\nexport function useVoxAI(options: VoxAIOptions = {}) {\n // Connection state\n const [connectionDetail, setConnectionDetail] =\n useState<VoxConnectionDetail | null>(null);\n const [state, setState] = useState<VoxAgentState>(\"disconnected\");\n\n // Session timestamp to filter out stale asynchronous events\n const sessionTimestampRef = useRef<number>(Date.now());\n\n // Message handling\n const [transcriptMap, setTranscriptMap] = useState<Map<string, VoxMessage>>(\n new Map()\n );\n const [messages, setMessages] = useState<VoxMessage[]>([]);\n const prevMessagesRef = useRef<string>(\"\");\n\n // Track which messages we've already sent to the onMessage callback\n const processedMessageIdsRef = useRef<Set<string>>(new Set());\n\n // DOM manipulation for LiveKit portal\n const portalRootRef = useRef<HTMLDivElement | null>(null);\n const rootRef = useRef<Root | null>(null);\n\n // Communication channel\n const channelRef = useRef<MessageChannel | null>(null);\n\n // Add this near the start of your useVoxAI hook\n const livekitComponentRef = useRef<React.ReactNode>(null);\n\n // Replace the single waveform state with a map for multiple speakers\n const [waveformDataMap, setWaveformDataMap] = useState<\n Record<string, number[]>\n >({\n agent: [],\n user: [],\n });\n\n // Add back the waveform config reference\n const waveformConfigRef = useRef<{\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n } | null>(null);\n\n // Add a new state to track microphone status\n const [isMicEnabled, setIsMicEnabled] = useState<boolean>(true);\n\n // Update messages whenever transcriptMap changes\n useEffect(() => {\n const allMessages = Array.from(transcriptMap.values()).sort(\n (a, b) => a.timestamp - b.timestamp\n );\n\n // Only update if the messages have actually changed\n const messagesString = JSON.stringify(allMessages);\n if (messagesString !== prevMessagesRef.current) {\n prevMessagesRef.current = messagesString;\n setMessages(allMessages);\n\n // Only trigger onMessage for new final messages that haven't been processed yet\n if (options.onMessage) {\n allMessages\n .filter(\n (msg) =>\n msg.isFinal &&\n msg.id &&\n !processedMessageIdsRef.current.has(msg.id)\n )\n .forEach((msg) => {\n if (msg.id) {\n // Mark this message as processed\n processedMessageIdsRef.current.add(msg.id);\n // Call the callback\n options.onMessage?.(msg);\n }\n });\n }\n }\n }, [transcriptMap, options.onMessage]);\n\n // Initialize message channel - ensure ports are properly connected\n useEffect(() => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (e) => {\n const data = e.data as MessageChannelEvent;\n\n if (data.type === \"state_update\") {\n setState(data.state);\n } else if (data.type === \"transcription_update\") {\n handleTranscriptionUpdate(data.transcriptions);\n } else if (data.type === \"waveform_update\" && data.speaker) {\n // Store the waveform data for the specific speaker\n setWaveformDataMap((prevMap) => ({\n ...prevMap,\n [data.speaker]: data.waveformData,\n }));\n } else if (data.type === \"function_tools_executed\" && data.tool) {\n // Handle function calls\n const functionCallsId = `function-calls-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(functionCallsId, {\n id: functionCallsId,\n name: \"tool\",\n tool: data.tool,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n }\n };\n\n // Start the port\n channel.port1.start();\n\n // Store the channel reference\n channelRef.current = channel;\n\n return () => {\n channelRef.current?.port1.close();\n channelRef.current?.port2.close();\n channelRef.current = null;\n };\n }, []);\n\n // Process incoming transcriptions and filter out stale events\n const handleTranscriptionUpdate = useCallback(\n (transcriptions: TranscriptionSegment[]) => {\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n\n transcriptions.forEach((t) => {\n // Only process transcriptions generated after the current session timestamp\n if (t.timestamp < sessionTimestampRef.current) {\n return;\n }\n const messageType = t.speaker === \"agent\" ? \"agent\" : \"user\";\n // Use existing timestamp if we already have this segment\n const existingTimestamp = prevMap.get(t.id)?.timestamp || t.timestamp;\n\n newMap.set(t.id, {\n id: t.id,\n name: messageType,\n message: t.text,\n timestamp: existingTimestamp,\n isFinal: t.isFinal,\n });\n });\n\n return newMap;\n });\n },\n []\n );\n\n // Set up DOM portal for LiveKit\n useEffect(() => {\n const div = document.createElement(\"div\");\n div.style.display = \"none\";\n document.body.appendChild(div);\n portalRootRef.current = div;\n rootRef.current = createRoot(div);\n\n return () => {\n if (rootRef.current) {\n rootRef.current.unmount();\n }\n if (portalRootRef.current) {\n document.body.removeChild(portalRootRef.current);\n }\n };\n }, []);\n\n // Connect to VoxAI service - updated to include dynamicVariables\n const connect = useCallback(\n async ({ agentId, apiKey, dynamicVariables, metadata }: ConnectParams) => {\n try {\n // Prevent connecting if already in a connection state\n if (state !== \"disconnected\") {\n const errorMessage = `Connection attempt rejected: Already in a connection state (${state})`;\n console.warn(errorMessage);\n\n if (options.onError) {\n options.onError(new Error(errorMessage));\n }\n return Promise.reject(new Error(errorMessage));\n }\n\n // Update session timestamp for new connection\n sessionTimestampRef.current = Date.now();\n setState(\"connecting\");\n\n const response = await fetch(HTTPS_API_ORIGIN, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agent_id: agentId,\n metadata: {\n runtime_context: {\n source: {\n type: \"react-sdk\",\n version: SDK_VERSION,\n },\n },\n call_web: {\n dynamic_variables: dynamicVariables || {},\n metadata: metadata || {},\n },\n },\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Connection failed (${response.status}): ${errorText}`\n );\n }\n\n const data = await response.json();\n setConnectionDetail(data);\n\n if (options.onConnect) {\n options.onConnect();\n }\n } catch (err) {\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n if (options.onError) {\n options.onError(error);\n }\n }\n },\n [options, state]\n );\n\n // Disconnect from VoxAI service, updating the session timestamp to ignore stale events\n const disconnect = useCallback(() => {\n // Update session timestamp on disconnect\n sessionTimestampRef.current = Date.now();\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n if (options.onDisconnect) {\n options.onDisconnect();\n }\n }, [options]);\n\n // Update the send function with debugging and error checking\n const send = useCallback(\n ({ message, digit }: { message?: string; digit?: number }) => {\n if (state === \"disconnected\") {\n console.warn(\"Cannot send message: Not connected to a conversation\");\n return;\n }\n\n if (message) {\n const messageId = `user-text-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(messageId, {\n id: messageId,\n name: \"user\",\n message: message,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_text\",\n text: message,\n });\n } else {\n console.error(\"No message channel available to send message\");\n }\n }\n\n if (digit !== undefined) {\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_dtmf\",\n digit: digit,\n });\n } else {\n console.error(\"No message channel available to send DTMF\");\n }\n }\n },\n [state]\n );\n\n // Update the audioWaveform function to return data for the requested speaker\n const audioWaveform = useCallback(\n ({\n speaker = \"agent\",\n barCount = 10,\n updateInterval = 20,\n }: {\n speaker?: \"agent\" | \"user\";\n barCount?: number;\n updateInterval?: number;\n }): number[] => {\n waveformConfigRef.current = { speaker, barCount, updateInterval };\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"waveform_config\",\n config: { speaker, barCount, updateInterval },\n });\n }\n\n const speakerData = waveformDataMap[speaker] || [];\n return speakerData.length > 0\n ? speakerData.slice(0, barCount)\n : Array(barCount).fill(0);\n },\n [waveformDataMap]\n );\n\n // Add toggleMic function that will be exposed in the hook's return value\n const toggleMic = useCallback((value: boolean) => {\n setIsMicEnabled(value);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"toggle_mic\",\n enabled: value,\n });\n } else {\n console.error(\"No message channel available to toggle microphone\");\n }\n }, []);\n\n // Add setVolume function that will be exposed in the hook's return value\n const setVolume = useCallback((volume: number) => {\n const validVolume = Math.min(Math.max(volume, 0), 1);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"set_volume\",\n volume: validVolume,\n });\n } else {\n console.error(\"No message channel available to set volume\");\n }\n }, []);\n\n // Modify the useEffect hook that renders the LiveKit component\n useEffect(() => {\n if (!rootRef.current) return;\n\n if (connectionDetail) {\n if (!livekitComponentRef.current) {\n if (channelRef.current) {\n channelRef.current.port2.start();\n }\n\n livekitComponentRef.current = (\n <LiveKitRoom\n serverUrl={connectionDetail.serverUrl}\n token={connectionDetail.participantToken}\n audio={true}\n video={false}\n connect={true}\n onDisconnected={disconnect}\n onError={(error) => {\n console.error(\"LiveKit connection error:\", error);\n disconnect();\n if (options.onError) {\n options.onError(\n new Error(`LiveKit connection error: ${error.message}`)\n );\n }\n }}\n >\n <RoomAudioRenderer />\n {channelRef.current && (\n <StateMonitor\n port={channelRef.current.port2}\n initialConfig={\n waveformConfigRef.current || {\n barCount: 10,\n updateInterval: 20,\n }\n }\n />\n )}\n </LiveKitRoom>\n );\n }\n rootRef.current.render(livekitComponentRef.current);\n } else {\n livekitComponentRef.current = null;\n rootRef.current.render(<></>);\n }\n }, [connectionDetail, disconnect, options.onError]);\n\n return {\n connect,\n disconnect,\n state,\n messages,\n send,\n audioWaveform,\n toggleMic,\n setVolume,\n };\n}\n\n/**\n * Component that monitors LiveKit state and communicates back to the main hook\n */\nfunction StateMonitor({\n port,\n initialConfig,\n}: {\n port: MessagePort | undefined;\n initialConfig: {\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n };\n}) {\n const { agent, state } = useVoiceAssistant();\n const { send: sendChat } = useChat();\n\n // Initialize waveform config with the passed initial values, defaulting to \"agent\" if not specified\n const [waveformConfig, setWaveformConfig] = useState({\n speaker: initialConfig.speaker || \"agent\",\n barCount: initialConfig.barCount,\n updateInterval: initialConfig.updateInterval,\n });\n\n // Agent transcriptions\n const agentAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n agent?.identity\n )[0];\n const agentTranscription = useTrackTranscription(agentAudioTrack);\n\n // Use the current config for the waveform, applying different settings based on speaker\n const agentAudioWaveform = useAudioWaveform(agentAudioTrack, {\n barCount:\n waveformConfig.speaker === \"agent\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"agent\" ? waveformConfig.updateInterval : 20,\n });\n\n // User transcriptions\n const localParticipant = useLocalParticipant();\n const localMessages = useTrackTranscription({\n publication: localParticipant.microphoneTrack,\n source: Track.Source.Microphone,\n participant: localParticipant.localParticipant,\n });\n const localAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n localParticipant.localParticipant.identity\n )[0];\n const userAudioWaveform = useAudioWaveform(localAudioTrack, {\n barCount: waveformConfig.speaker === \"user\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"user\" ? waveformConfig.updateInterval : 20,\n });\n\n // Add separate effects to send agent and user waveform data\n useEffect(() => {\n if (!port || !agentAudioWaveform || !agentAudioWaveform.bars) return;\n\n // Send the agent waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: agentAudioWaveform.bars,\n speaker: \"agent\",\n });\n }, [port, agentAudioWaveform]);\n\n useEffect(() => {\n if (!port || !userAudioWaveform || !userAudioWaveform.bars) return;\n\n // Send the user waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: userAudioWaveform.bars,\n speaker: \"user\",\n });\n }, [port, userAudioWaveform]);\n\n // Listen for messages including config updates and mic toggle commands\n useEffect(() => {\n if (!port) return;\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n\n if (data.type === \"waveform_config\" && data.config) {\n // Verify we have both required properties before updating\n if (\n typeof data.config.barCount === \"number\" &&\n typeof data.config.updateInterval === \"number\"\n ) {\n setWaveformConfig(data.config);\n }\n } else if (data.type === \"send_text\") {\n if (sendChat) {\n sendChat(data.text);\n } else {\n console.error(\"sendChat function is not available\");\n }\n } else if (data.type === \"send_dtmf\") {\n if (localParticipant.localParticipant) {\n // Use standard DTMF code (RFC 4733)\n const standardDtmfCode = 101; // Standard DTMF payload type\n localParticipant.localParticipant.publishDtmf(\n standardDtmfCode,\n data.digit\n );\n } else {\n console.error(\"Local participant is not available for DTMF\");\n }\n } else if (\n data.type === \"toggle_mic\" &&\n typeof data.enabled === \"boolean\"\n ) {\n // Handle microphone toggle\n if (localParticipant.localParticipant) {\n localParticipant.localParticipant\n .setMicrophoneEnabled(data.enabled)\n .catch((error) => {\n console.error(\"Failed to toggle microphone:\", error);\n });\n } else {\n console.error(\"Local participant is not available for mic toggle\");\n }\n } else if (\n data.type === \"set_volume\" &&\n typeof data.volume === \"number\"\n ) {\n // Handle volume control\n if (agent) {\n // The agent is a RemoteParticipant, so we can call setVolume directly\n try {\n agent.setVolume(data.volume);\n console.log(`Set agent volume to ${data.volume}`);\n } catch (error) {\n console.error(\"Failed to set agent volume:\", error);\n }\n } else {\n console.error(\"Agent is not available for volume control\");\n }\n }\n };\n\n // Make sure we start the port\n port.start();\n\n port.addEventListener(\"message\", handleMessage);\n\n return () => {\n port.removeEventListener(\"message\", handleMessage);\n };\n }, [port, sendChat, localParticipant, agent]);\n\n // Send agent state updates\n useEffect(() => {\n if (port) {\n port.postMessage({ type: \"state_update\", state });\n }\n }, [state, port]);\n\n // Send agent transcriptions\n useEffect(() => {\n if (port && agentTranscription.segments.length > 0) {\n const transcriptions = agentTranscription.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"agent\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [agentTranscription.segments, port]);\n\n // Send user transcriptions\n useEffect(() => {\n if (port && localMessages.segments.length > 0) {\n const transcriptions = localMessages.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"user\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [localMessages.segments, port]);\n\n // Add data channel hook for function calls\n const { message: functionToolsExecuted } = useDataChannel(\n \"function_tools_executed\",\n (msg) => {\n if (!port) return;\n\n const textDecoder = new TextDecoder();\n const messageString =\n msg.payload instanceof Uint8Array\n ? textDecoder.decode(msg.payload)\n : String(msg.payload);\n\n let tool: FunctionToolsExecuted;\n try {\n tool = JSON.parse(messageString);\n\n // Send function calls to main hook via the port\n port.postMessage({\n type: \"function_tools_executed\",\n tool: tool,\n });\n } catch (e) {\n console.error(\"Failed to parse function call log:\", e);\n }\n }\n );\n\n return null;\n}\n","// export const HTTPS_API_ORIGIN = \"https://frontend-dev.tryvox.co/api/agent/sdk\";\nexport const HTTPS_API_ORIGIN = \"https://www.tryvox.co/api/agent/sdk\";\n// export const HTTPS_API_ORIGIN = \"http://localhost:3000/api/agent/sdk\";\nexport const SDK_VERSION = \"0.3.2\";\n"],"names":["StateMonitor","_ref4","port","initialConfig","agent","state","useVoiceAssistant","send","sendChat","useChat","waveformConfig","setWaveformConfig","useState","speaker","barCount","updateInterval","agentAudioTrack","useParticipantTracks","Track","Source","Microphone","identity","agentTranscription","useTrackTranscription","agentAudioWaveform","useAudioWaveform","localParticipant","useLocalParticipant","localMessages","publication","microphoneTrack","source","participant","localAudioTrack","userAudioWaveform","useEffect","bars","postMessage","type","waveformData","handleMessage","event","data","config","text","console","error","publishDtmf","digit","enabled","setMicrophoneEnabled","catch","volume","setVolume","log","start","addEventListener","removeEventListener","segments","length","transcriptions","map","segment","id","isFinal","final","timestamp","Date","now","useDataChannel","msg","textDecoder","TextDecoder","messageString","payload","Uint8Array","decode","String","tool","JSON","parse","e","options","connectionDetail","setConnectionDetail","setState","sessionTimestampRef","useRef","transcriptMap","setTranscriptMap","Map","messages","setMessages","prevMessagesRef","processedMessageIdsRef","Set","portalRootRef","rootRef","channelRef","livekitComponentRef","waveformDataMap","setWaveformDataMap","user","waveformConfigRef","isMicEnabled","setIsMicEnabled","allMessages","Array","from","values","sort","a","b","messagesString","stringify","current","onMessage","filter","has","forEach","add","channel","MessageChannel","port1","onmessage","handleTranscriptionUpdate","prevMap","functionCallsId","newMap","set","name","_channelRef$current","_channelRef$current2","close","port2","useCallback","t","_prevMap$get","messageType","existingTimestamp","get","message","div","document","createElement","style","display","body","appendChild","createRoot","unmount","removeChild","connect","_ref","agentId","apiKey","dynamicVariables","metadata","Promise","resolve","errorMessage","warn","onError","Error","reject","fetch","method","headers","Authorization","agent_id","runtime_context","version","call_web","dynamic_variables","then","response","_temp2","_result2","_exit","json","onConnect","_temp","ok","errorText","status","_catch","err","disconnect","onDisconnect","_ref2","messageId","undefined","audioWaveform","_ref3","speakerData","slice","fill","toggleMic","value","validVolume","Math","min","max","_jsxs","LiveKitRoom","serverUrl","token","participantToken","audio","video","onDisconnected","children","_jsx","RoomAudioRenderer","render","_Fragment"],"mappings":"uJA8iBA,SAASA,EAAYC,GAAC,IAAAC,KACpBA,EAAIC,cACJA,GAQDF,EACC,MAAMG,MAAEA,EAAKC,MAAEA,GAAUC,EAAAA,qBACjBC,KAAMC,GAAaC,EAAOA,WAG3BC,EAAgBC,GAAqBC,WAAS,CACnDC,QAASV,EAAcU,SAAW,QAClCC,SAAUX,EAAcW,SACxBC,eAAgBZ,EAAcY,iBAI1BC,EAAkBC,uBACtB,CAACC,EAAKA,MAACC,OAAOC,YACT,MAALhB,OAAK,EAALA,EAAOiB,UACP,GACIC,EAAqBC,EAAqBA,sBAACP,GAG3CQ,EAAqBC,EAAgBA,iBAACT,EAAiB,CA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AAQC,MAAM,4BAA6BA,GAC3C6I,IACIzG,EAAQgF,SACVhF,EAAQgF,QACN,IAAIC,MAAmCrH,6BAAAA,EAAM+F,SAEjD,EACDsE,SAAA,CAEDC,EAAAA,IAACC,EAAiBA,kBAAG,IACpBnH,EAAWiB,SACViG,EAAAA,IAACpN,EAAY,CACXE,KAAMgG,EAAWiB,QAAQmB,MACzBnI,cACEoG,EAAkBY,SAAW,CAC3BrG,SAAU,GACVC,eAAgB,UAQ9BkF,EAAQkB,QAAQmG,OAAOnH,EAAoBgB,WAE3ChB,EAAoBgB,QAAU,KAC9BlB,EAAQkB,QAAQmG,OAAOF,MAAAG,EAAAA,SAAA,CAAA,KACzB,EACC,CAACpI,EAAkBwG,EAAYzG,EAAQgF,UAEnC,CACLV,UACAmC,aACAtL,QACAsF,WACApF,OACAyL,gBACAK,YACAhJ,YAEJ"}
@@ -1,2 +1,2 @@
1
- import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{LiveKitRoom as r,RoomAudioRenderer as o,useVoiceAssistant as a,useChat as s,useParticipantTracks as i,useTrackTranscription as c,useAudioWaveform as l,useLocalParticipant as u,useDataChannel as p}from"@livekit/components-react";import{Track as d}from"livekit-client";import{useState as m,useRef as g,useEffect as f,useCallback as v}from"react";import{createRoot as y}from"react-dom/client";function b(){return b=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},b.apply(null,arguments)}function w(a={}){const[s,i]=m(null),[c,l]=m("disconnected"),u=g(Date.now()),[p,d]=m(new Map),[w,M]=m([]),_=g(""),k=g(new Set),C=g(null),x=g(null),E=g(null),D=g(null),[F,I]=m({agent:[],user:[]}),S=g(null),[P,N]=m(!0);f(()=>{const e=Array.from(p.values()).sort((e,t)=>e.timestamp-t.timestamp),t=JSON.stringify(e);t!==_.current&&(_.current=t,M(e),a.onMessage&&e.filter(e=>e.isFinal&&e.id&&!k.current.has(e.id)).forEach(e=>{e.id&&(k.current.add(e.id),null==a.onMessage||a.onMessage(e))}))},[p,a.onMessage]),f(()=>{const e=new MessageChannel;return e.port1.onmessage=e=>{const t=e.data;if("state_update"===t.type)l(t.state);else if("transcription_update"===t.type)$(t.transcriptions);else if("waveform_update"===t.type&&t.speaker)I(e=>b({},e,{[t.speaker]:t.waveformData}));else if("function_tools_executed"===t.type&&t.tool){const e=`function-calls-${Date.now()}`;d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"tool",tool:t.tool,timestamp:Date.now(),isFinal:!0}),r})}},e.port1.start(),E.current=e,()=>{var e,t;null==(e=E.current)||e.port1.close(),null==(t=E.current)||t.port2.close(),E.current=null}},[]);const $=v(e=>{d(t=>{const n=new Map(t);return e.forEach(e=>{var r;if(e.timestamp<u.current)return;const o="agent"===e.speaker?"agent":"user",a=(null==(r=t.get(e.id))?void 0:r.timestamp)||e.timestamp;n.set(e.id,{id:e.id,name:o,message:e.text,timestamp:a,isFinal:e.isFinal})}),n})},[]);f(()=>{const e=document.createElement("div");return e.style.display="none",document.body.appendChild(e),C.current=e,x.current=y(e),()=>{x.current&&x.current.unmount(),C.current&&document.body.removeChild(C.current)}},[]);const j=v(async({agentId:e,apiKey:t,dynamicVariables:n,metadata:r})=>{try{if("disconnected"!==c){const e=`Connection attempt rejected: Already in a connection state (${c})`;return console.warn(e),a.onError&&a.onError(new Error(e)),Promise.reject(new Error(e))}u.current=Date.now(),l("connecting");const o=await fetch("https://www.tryvox.co/api/agent/sdk",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({agent_id:e,metadata:{runtime_context:{source:{type:"react-sdk",version:"0.3.0"}},call_web:{dynamic_variables:n||{},metadata:r||{}}}})});if(!o.ok){const e=await o.text();throw new Error(`Connection failed (${o.status}): ${e}`)}const s=await o.json();i(s),a.onConnect&&a.onConnect()}catch(e){i(null),d(new Map),M([]),l("disconnected");const t=e instanceof Error?e:new Error(String(e));a.onError&&a.onError(t)}},[a,c]),O=v(()=>{u.current=Date.now(),i(null),d(new Map),M([]),l("disconnected"),a.onDisconnect&&a.onDisconnect()},[a]),T=v(({message:e,digit:t})=>{if("disconnected"!==c){if(e){const t=`user-text-${Date.now()}`;d(n=>{const r=new Map(n);return r.set(t,{id:t,name:"user",message:e,timestamp:Date.now(),isFinal:!0}),r}),E.current?E.current.port1.postMessage({type:"send_text",text:e}):console.error("No message channel available to send message")}void 0!==t&&(E.current?E.current.port1.postMessage({type:"send_dtmf",digit:t}):console.error("No message channel available to send DTMF"))}else console.warn("Cannot send message: Not connected to a conversation")},[c]),A=v(({speaker:e="agent",barCount:t=10,updateInterval:n=20})=>{S.current={speaker:e,barCount:t,updateInterval:n},E.current&&E.current.port1.postMessage({type:"waveform_config",config:{speaker:e,barCount:t,updateInterval:n}});const r=F[e]||[];return r.length>0?r.slice(0,t):Array(t).fill(0)},[F]),L=v(e=>{N(e),E.current?E.current.port1.postMessage({type:"toggle_mic",enabled:e}):console.error("No message channel available to toggle microphone")},[]),J=v(e=>{const t=Math.min(Math.max(e,0),1);E.current?E.current.port1.postMessage({type:"set_volume",volume:t}):console.error("No message channel available to set volume")},[]);return f(()=>{x.current&&(s?(D.current||(E.current&&E.current.port2.start(),D.current=e(r,{serverUrl:s.serverUrl,token:s.participantToken,audio:!0,video:!1,connect:!0,onDisconnected:O,onError:e=>{console.error("LiveKit connection error:",e),O(),a.onError&&a.onError(new Error(`LiveKit connection error: ${e.message}`))},children:[t(o,{}),E.current&&t(h,{port:E.current.port2,initialConfig:S.current||{barCount:10,updateInterval:20}})]})),x.current.render(D.current)):(D.current=null,x.current.render(t(n,{}))))},[s,O,a.onError]),{connect:j,disconnect:O,state:c,messages:w,send:T,audioWaveform:A,toggleMic:L,setVolume:J}}function h({port:e,initialConfig:t}){const{agent:n,state:r}=a(),{send:o}=s(),[g,v]=m({speaker:t.speaker||"agent",barCount:t.barCount,updateInterval:t.updateInterval}),y=i([d.Source.Microphone],null==n?void 0:n.identity)[0],b=c(y),w=l(y,{barCount:"agent"===g.speaker?g.barCount:120,updateInterval:"agent"===g.speaker?g.updateInterval:20}),h=u(),M=c({publication:h.microphoneTrack,source:d.Source.Microphone,participant:h.localParticipant}),_=i([d.Source.Microphone],h.localParticipant.identity)[0],k=l(_,{barCount:"user"===g.speaker?g.barCount:120,updateInterval:"user"===g.speaker?g.updateInterval:20});return f(()=>{e&&w&&w.bars&&e.postMessage({type:"waveform_update",waveformData:w.bars,speaker:"agent"})},[e,w]),f(()=>{e&&k&&k.bars&&e.postMessage({type:"waveform_update",waveformData:k.bars,speaker:"user"})},[e,k]),f(()=>{if(!e)return;const t=e=>{const t=e.data;if("waveform_config"===t.type&&t.config)"number"==typeof t.config.barCount&&"number"==typeof t.config.updateInterval&&v(t.config);else if("send_text"===t.type)o?o(t.text):console.error("sendChat function is not available");else if("send_dtmf"===t.type)h.localParticipant?h.localParticipant.publishDtmf(101,t.digit):console.error("Local participant is not available for DTMF");else if("toggle_mic"===t.type&&"boolean"==typeof t.enabled)h.localParticipant?h.localParticipant.setMicrophoneEnabled(t.enabled).catch(e=>{console.error("Failed to toggle microphone:",e)}):console.error("Local participant is not available for mic toggle");else if("set_volume"===t.type&&"number"==typeof t.volume)if(n)try{n.setVolume(t.volume),console.log(`Set agent volume to ${t.volume}`)}catch(e){console.error("Failed to set agent volume:",e)}else console.error("Agent is not available for volume control")};return e.start(),e.addEventListener("message",t),()=>{e.removeEventListener("message",t)}},[e,o,h,n]),f(()=>{e&&e.postMessage({type:"state_update",state:r})},[r,e]),f(()=>{if(e&&b.segments.length>0){const t=b.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"agent"}));e.postMessage({type:"transcription_update",transcriptions:t})}},[b.segments,e]),f(()=>{if(e&&M.segments.length>0){const t=M.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"user"}));e.postMessage({type:"transcription_update",transcriptions:t})}},[M.segments,e]),p("function_tools_executed",t=>{if(!e)return;const n=new TextDecoder,r=t.payload instanceof Uint8Array?n.decode(t.payload):String(t.payload);let o;try{o=JSON.parse(r),e.postMessage({type:"function_tools_executed",tool:o})}catch(e){console.error("Failed to parse function call log:",e)}}),null}export{w as useVoxAI};
1
+ import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{LiveKitRoom as r,RoomAudioRenderer as o,useVoiceAssistant as a,useChat as s,useParticipantTracks as i,useTrackTranscription as c,useAudioWaveform as l,useLocalParticipant as u,useDataChannel as p}from"@livekit/components-react";import{Track as d}from"livekit-client";import{useState as m,useRef as g,useEffect as f,useCallback as v}from"react";import{createRoot as y}from"react-dom/client";function b(){return b=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},b.apply(null,arguments)}function w(a={}){const[s,i]=m(null),[c,l]=m("disconnected"),u=g(Date.now()),[p,d]=m(new Map),[w,M]=m([]),_=g(""),k=g(new Set),C=g(null),x=g(null),E=g(null),D=g(null),[F,I]=m({agent:[],user:[]}),S=g(null),[P,N]=m(!0);f(()=>{const e=Array.from(p.values()).sort((e,t)=>e.timestamp-t.timestamp),t=JSON.stringify(e);t!==_.current&&(_.current=t,M(e),a.onMessage&&e.filter(e=>e.isFinal&&e.id&&!k.current.has(e.id)).forEach(e=>{e.id&&(k.current.add(e.id),null==a.onMessage||a.onMessage(e))}))},[p,a.onMessage]),f(()=>{const e=new MessageChannel;return e.port1.onmessage=e=>{const t=e.data;if("state_update"===t.type)l(t.state);else if("transcription_update"===t.type)$(t.transcriptions);else if("waveform_update"===t.type&&t.speaker)I(e=>b({},e,{[t.speaker]:t.waveformData}));else if("function_tools_executed"===t.type&&t.tool){const e=`function-calls-${Date.now()}`;d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"tool",tool:t.tool,timestamp:Date.now(),isFinal:!0}),r})}},e.port1.start(),E.current=e,()=>{var e,t;null==(e=E.current)||e.port1.close(),null==(t=E.current)||t.port2.close(),E.current=null}},[]);const $=v(e=>{d(t=>{const n=new Map(t);return e.forEach(e=>{var r;if(e.timestamp<u.current)return;const o="agent"===e.speaker?"agent":"user",a=(null==(r=t.get(e.id))?void 0:r.timestamp)||e.timestamp;n.set(e.id,{id:e.id,name:o,message:e.text,timestamp:a,isFinal:e.isFinal})}),n})},[]);f(()=>{const e=document.createElement("div");return e.style.display="none",document.body.appendChild(e),C.current=e,x.current=y(e),()=>{x.current&&x.current.unmount(),C.current&&document.body.removeChild(C.current)}},[]);const j=v(async({agentId:e,apiKey:t,dynamicVariables:n,metadata:r})=>{try{if("disconnected"!==c){const e=`Connection attempt rejected: Already in a connection state (${c})`;return console.warn(e),a.onError&&a.onError(new Error(e)),Promise.reject(new Error(e))}u.current=Date.now(),l("connecting");const o=await fetch("https://www.tryvox.co/api/agent/sdk",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({agent_id:e,metadata:{runtime_context:{source:{type:"react-sdk",version:"0.3.2"}},call_web:{dynamic_variables:n||{},metadata:r||{}}}})});if(!o.ok){const e=await o.text();throw new Error(`Connection failed (${o.status}): ${e}`)}const s=await o.json();i(s),a.onConnect&&a.onConnect()}catch(e){i(null),d(new Map),M([]),l("disconnected");const t=e instanceof Error?e:new Error(String(e));a.onError&&a.onError(t)}},[a,c]),O=v(()=>{u.current=Date.now(),i(null),d(new Map),M([]),l("disconnected"),a.onDisconnect&&a.onDisconnect()},[a]),T=v(({message:e,digit:t})=>{if("disconnected"!==c){if(e){const t=`user-text-${Date.now()}`;d(n=>{const r=new Map(n);return r.set(t,{id:t,name:"user",message:e,timestamp:Date.now(),isFinal:!0}),r}),E.current?E.current.port1.postMessage({type:"send_text",text:e}):console.error("No message channel available to send message")}void 0!==t&&(E.current?E.current.port1.postMessage({type:"send_dtmf",digit:t}):console.error("No message channel available to send DTMF"))}else console.warn("Cannot send message: Not connected to a conversation")},[c]),A=v(({speaker:e="agent",barCount:t=10,updateInterval:n=20})=>{S.current={speaker:e,barCount:t,updateInterval:n},E.current&&E.current.port1.postMessage({type:"waveform_config",config:{speaker:e,barCount:t,updateInterval:n}});const r=F[e]||[];return r.length>0?r.slice(0,t):Array(t).fill(0)},[F]),L=v(e=>{N(e),E.current?E.current.port1.postMessage({type:"toggle_mic",enabled:e}):console.error("No message channel available to toggle microphone")},[]),J=v(e=>{const t=Math.min(Math.max(e,0),1);E.current?E.current.port1.postMessage({type:"set_volume",volume:t}):console.error("No message channel available to set volume")},[]);return f(()=>{x.current&&(s?(D.current||(E.current&&E.current.port2.start(),D.current=e(r,{serverUrl:s.serverUrl,token:s.participantToken,audio:!0,video:!1,connect:!0,onDisconnected:O,onError:e=>{console.error("LiveKit connection error:",e),O(),a.onError&&a.onError(new Error(`LiveKit connection error: ${e.message}`))},children:[t(o,{}),E.current&&t(h,{port:E.current.port2,initialConfig:S.current||{barCount:10,updateInterval:20}})]})),x.current.render(D.current)):(D.current=null,x.current.render(t(n,{}))))},[s,O,a.onError]),{connect:j,disconnect:O,state:c,messages:w,send:T,audioWaveform:A,toggleMic:L,setVolume:J}}function h({port:e,initialConfig:t}){const{agent:n,state:r}=a(),{send:o}=s(),[g,v]=m({speaker:t.speaker||"agent",barCount:t.barCount,updateInterval:t.updateInterval}),y=i([d.Source.Microphone],null==n?void 0:n.identity)[0],b=c(y),w=l(y,{barCount:"agent"===g.speaker?g.barCount:120,updateInterval:"agent"===g.speaker?g.updateInterval:20}),h=u(),M=c({publication:h.microphoneTrack,source:d.Source.Microphone,participant:h.localParticipant}),_=i([d.Source.Microphone],h.localParticipant.identity)[0],k=l(_,{barCount:"user"===g.speaker?g.barCount:120,updateInterval:"user"===g.speaker?g.updateInterval:20});return f(()=>{e&&w&&w.bars&&e.postMessage({type:"waveform_update",waveformData:w.bars,speaker:"agent"})},[e,w]),f(()=>{e&&k&&k.bars&&e.postMessage({type:"waveform_update",waveformData:k.bars,speaker:"user"})},[e,k]),f(()=>{if(!e)return;const t=e=>{const t=e.data;if("waveform_config"===t.type&&t.config)"number"==typeof t.config.barCount&&"number"==typeof t.config.updateInterval&&v(t.config);else if("send_text"===t.type)o?o(t.text):console.error("sendChat function is not available");else if("send_dtmf"===t.type)h.localParticipant?h.localParticipant.publishDtmf(101,t.digit):console.error("Local participant is not available for DTMF");else if("toggle_mic"===t.type&&"boolean"==typeof t.enabled)h.localParticipant?h.localParticipant.setMicrophoneEnabled(t.enabled).catch(e=>{console.error("Failed to toggle microphone:",e)}):console.error("Local participant is not available for mic toggle");else if("set_volume"===t.type&&"number"==typeof t.volume)if(n)try{n.setVolume(t.volume),console.log(`Set agent volume to ${t.volume}`)}catch(e){console.error("Failed to set agent volume:",e)}else console.error("Agent is not available for volume control")};return e.start(),e.addEventListener("message",t),()=>{e.removeEventListener("message",t)}},[e,o,h,n]),f(()=>{e&&e.postMessage({type:"state_update",state:r})},[r,e]),f(()=>{if(e&&b.segments.length>0){const t=b.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"agent"}));e.postMessage({type:"transcription_update",transcriptions:t})}},[b.segments,e]),f(()=>{if(e&&M.segments.length>0){const t=M.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"user"}));e.postMessage({type:"transcription_update",transcriptions:t})}},[M.segments,e]),p("function_tools_executed",t=>{if(!e)return;const n=new TextDecoder,r=t.payload instanceof Uint8Array?n.decode(t.payload):String(t.payload);let o;try{o=JSON.parse(r),e.postMessage({type:"function_tools_executed",tool:o})}catch(e){console.error("Failed to parse function call log:",e)}}),null}export{w as useVoxAI};
2
2
  //# sourceMappingURL=lib.modern.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"lib.modern.js","sources":["../src/hooks/useVoxAI.tsx","../src/utils/constants.ts"],"sourcesContent":["import {\n LiveKitRoom,\n RoomAudioRenderer,\n useAudioWaveform,\n useChat,\n useDataChannel,\n useLocalParticipant,\n useParticipantTracks,\n useTrackTranscription,\n useVoiceAssistant,\n} from \"@livekit/components-react\";\nimport { Track } from \"livekit-client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport { HTTPS_API_ORIGIN, SDK_VERSION } from \"../utils/constants\";\n\ntype VoxConnectionDetail = {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n};\n\n/**\n * VoxAgentState\n * @description The state of the agent\n */\nexport type VoxAgentState =\n | \"disconnected\"\n | \"connecting\"\n | \"initializing\"\n | \"listening\"\n | \"thinking\"\n | \"speaking\";\n\n/**\n * Function call related types\n */\nexport interface FunctionToolsExecuted {\n type: \"function_tools_executed\";\n function_calls: FunctionCallInfo[];\n function_call_outputs: FunctionCallResult[];\n}\n\nexport interface FunctionCallInfo {\n id: string;\n type: string;\n call_id: string;\n arguments: string;\n name: string;\n}\n\nexport interface FunctionCallResult {\n id: string;\n name: string;\n type: string;\n call_id: string;\n output: string;\n is_error: boolean;\n}\n\n/**\n * VoxMessage\n * @description The message type between the agent and the user\n */\nexport type VoxMessage = {\n id?: string;\n name: \"agent\" | \"user\" | \"tool\";\n message?: string;\n timestamp: number;\n isFinal?: boolean;\n tool?: FunctionToolsExecuted;\n};\n\n/**\n * VoxAIOptions\n * @description The callback functions for the useVoxAI hook\n */\nexport interface VoxAIOptions {\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onMessage?: (message: VoxMessage) => void;\n}\n\n// Message channel event types\ntype MessageChannelEvent =\n | { type: \"state_update\"; state: VoxAgentState }\n | { type: \"transcription_update\"; transcriptions: TranscriptionSegment[] }\n | {\n type: \"waveform_update\";\n waveformData: number[];\n speaker: \"agent\" | \"user\";\n }\n | { type: \"function_tools_executed\"; tool: FunctionToolsExecuted };\n\ntype TranscriptionSegment = {\n id: string;\n text: string;\n isFinal: boolean;\n timestamp: number;\n speaker: \"agent\" | \"user\";\n};\n\n/**\n * ConnectParams\n * @param agentId - The agent ID\n * @param apiKey - The API key\n * @param dynamicVariables - The dynamic variables\n * @param metadata - 이 메타데이터는 아웃바운드 웹훅, 통화 기록에 포함됩니다.\n */\nexport interface ConnectParams {\n agentId: string;\n apiKey: string;\n dynamicVariables?: Record<string, any>;\n metadata?: Record<string, any>;\n}\n\n/**\n * useVoxAI\n * @description The hook for integrating with vox.ai voice assistant\n * @param options - The options for the useVoxAI hook\n * @returns The useVoxAI hook\n * @example\n * const { connect, disconnect, state, messages, send } = useVoxAI({\n * onConnect: () => console.log(\"Connected\"),\n * onDisconnect: () => console.log(\"Disconnected\"),\n * onError: (error) => console.error(\"Error:\", error),\n * onMessage: (message) => console.log(\"Message:\", message),\n * });\n */\nexport function useVoxAI(options: VoxAIOptions = {}) {\n // Connection state\n const [connectionDetail, setConnectionDetail] =\n useState<VoxConnectionDetail | null>(null);\n const [state, setState] = useState<VoxAgentState>(\"disconnected\");\n\n // Session timestamp to filter out stale asynchronous events\n const sessionTimestampRef = useRef<number>(Date.now());\n\n // Message handling\n const [transcriptMap, setTranscriptMap] = useState<Map<string, VoxMessage>>(\n new Map()\n );\n const [messages, setMessages] = useState<VoxMessage[]>([]);\n const prevMessagesRef = useRef<string>(\"\");\n\n // Track which messages we've already sent to the onMessage callback\n const processedMessageIdsRef = useRef<Set<string>>(new Set());\n\n // DOM manipulation for LiveKit portal\n const portalRootRef = useRef<HTMLDivElement | null>(null);\n const rootRef = useRef<Root | null>(null);\n\n // Communication channel\n const channelRef = useRef<MessageChannel | null>(null);\n\n // Add this near the start of your useVoxAI hook\n const livekitComponentRef = useRef<React.ReactNode>(null);\n\n // Replace the single waveform state with a map for multiple speakers\n const [waveformDataMap, setWaveformDataMap] = useState<\n Record<string, number[]>\n >({\n agent: [],\n user: [],\n });\n\n // Add back the waveform config reference\n const waveformConfigRef = useRef<{\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n } | null>(null);\n\n // Add a new state to track microphone status\n const [isMicEnabled, setIsMicEnabled] = useState<boolean>(true);\n\n // Update messages whenever transcriptMap changes\n useEffect(() => {\n const allMessages = Array.from(transcriptMap.values()).sort(\n (a, b) => a.timestamp - b.timestamp\n );\n\n // Only update if the messages have actually changed\n const messagesString = JSON.stringify(allMessages);\n if (messagesString !== prevMessagesRef.current) {\n prevMessagesRef.current = messagesString;\n setMessages(allMessages);\n\n // Only trigger onMessage for new final messages that haven't been processed yet\n if (options.onMessage) {\n allMessages\n .filter(\n (msg) =>\n msg.isFinal &&\n msg.id &&\n !processedMessageIdsRef.current.has(msg.id)\n )\n .forEach((msg) => {\n if (msg.id) {\n // Mark this message as processed\n processedMessageIdsRef.current.add(msg.id);\n // Call the callback\n options.onMessage?.(msg);\n }\n });\n }\n }\n }, [transcriptMap, options.onMessage]);\n\n // Initialize message channel - ensure ports are properly connected\n useEffect(() => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (e) => {\n const data = e.data as MessageChannelEvent;\n\n if (data.type === \"state_update\") {\n setState(data.state);\n } else if (data.type === \"transcription_update\") {\n handleTranscriptionUpdate(data.transcriptions);\n } else if (data.type === \"waveform_update\" && data.speaker) {\n // Store the waveform data for the specific speaker\n setWaveformDataMap((prevMap) => ({\n ...prevMap,\n [data.speaker]: data.waveformData,\n }));\n } else if (data.type === \"function_tools_executed\" && data.tool) {\n // Handle function calls\n const functionCallsId = `function-calls-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(functionCallsId, {\n id: functionCallsId,\n name: \"tool\",\n tool: data.tool,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n }\n };\n\n // Start the port\n channel.port1.start();\n\n // Store the channel reference\n channelRef.current = channel;\n\n return () => {\n channelRef.current?.port1.close();\n channelRef.current?.port2.close();\n channelRef.current = null;\n };\n }, []);\n\n // Process incoming transcriptions and filter out stale events\n const handleTranscriptionUpdate = useCallback(\n (transcriptions: TranscriptionSegment[]) => {\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n\n transcriptions.forEach((t) => {\n // Only process transcriptions generated after the current session timestamp\n if (t.timestamp < sessionTimestampRef.current) {\n return;\n }\n const messageType = t.speaker === \"agent\" ? \"agent\" : \"user\";\n // Use existing timestamp if we already have this segment\n const existingTimestamp = prevMap.get(t.id)?.timestamp || t.timestamp;\n\n newMap.set(t.id, {\n id: t.id,\n name: messageType,\n message: t.text,\n timestamp: existingTimestamp,\n isFinal: t.isFinal,\n });\n });\n\n return newMap;\n });\n },\n []\n );\n\n // Set up DOM portal for LiveKit\n useEffect(() => {\n const div = document.createElement(\"div\");\n div.style.display = \"none\";\n document.body.appendChild(div);\n portalRootRef.current = div;\n rootRef.current = createRoot(div);\n\n return () => {\n if (rootRef.current) {\n rootRef.current.unmount();\n }\n if (portalRootRef.current) {\n document.body.removeChild(portalRootRef.current);\n }\n };\n }, []);\n\n // Connect to VoxAI service - updated to include dynamicVariables\n const connect = useCallback(\n async ({ agentId, apiKey, dynamicVariables, metadata }: ConnectParams) => {\n try {\n // Prevent connecting if already in a connection state\n if (state !== \"disconnected\") {\n const errorMessage = `Connection attempt rejected: Already in a connection state (${state})`;\n console.warn(errorMessage);\n\n if (options.onError) {\n options.onError(new Error(errorMessage));\n }\n return Promise.reject(new Error(errorMessage));\n }\n\n // Update session timestamp for new connection\n sessionTimestampRef.current = Date.now();\n setState(\"connecting\");\n\n const response = await fetch(HTTPS_API_ORIGIN, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agent_id: agentId,\n metadata: {\n runtime_context: {\n source: {\n type: \"react-sdk\",\n version: SDK_VERSION,\n },\n },\n call_web: {\n dynamic_variables: dynamicVariables || {},\n metadata: metadata || {},\n },\n },\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Connection failed (${response.status}): ${errorText}`\n );\n }\n\n const data = await response.json();\n setConnectionDetail(data);\n\n if (options.onConnect) {\n options.onConnect();\n }\n } catch (err) {\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n if (options.onError) {\n options.onError(error);\n }\n }\n },\n [options, state]\n );\n\n // Disconnect from VoxAI service, updating the session timestamp to ignore stale events\n const disconnect = useCallback(() => {\n // Update session timestamp on disconnect\n sessionTimestampRef.current = Date.now();\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n if (options.onDisconnect) {\n options.onDisconnect();\n }\n }, [options]);\n\n // Update the send function with debugging and error checking\n const send = useCallback(\n ({ message, digit }: { message?: string; digit?: number }) => {\n if (state === \"disconnected\") {\n console.warn(\"Cannot send message: Not connected to a conversation\");\n return;\n }\n\n if (message) {\n const messageId = `user-text-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(messageId, {\n id: messageId,\n name: \"user\",\n message: message,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_text\",\n text: message,\n });\n } else {\n console.error(\"No message channel available to send message\");\n }\n }\n\n if (digit !== undefined) {\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_dtmf\",\n digit: digit,\n });\n } else {\n console.error(\"No message channel available to send DTMF\");\n }\n }\n },\n [state]\n );\n\n // Update the audioWaveform function to return data for the requested speaker\n const audioWaveform = useCallback(\n ({\n speaker = \"agent\",\n barCount = 10,\n updateInterval = 20,\n }: {\n speaker?: \"agent\" | \"user\";\n barCount?: number;\n updateInterval?: number;\n }): number[] => {\n waveformConfigRef.current = { speaker, barCount, updateInterval };\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"waveform_config\",\n config: { speaker, barCount, updateInterval },\n });\n }\n\n const speakerData = waveformDataMap[speaker] || [];\n return speakerData.length > 0\n ? speakerData.slice(0, barCount)\n : Array(barCount).fill(0);\n },\n [waveformDataMap]\n );\n\n // Add toggleMic function that will be exposed in the hook's return value\n const toggleMic = useCallback((value: boolean) => {\n setIsMicEnabled(value);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"toggle_mic\",\n enabled: value,\n });\n } else {\n console.error(\"No message channel available to toggle microphone\");\n }\n }, []);\n\n // Add setVolume function that will be exposed in the hook's return value\n const setVolume = useCallback((volume: number) => {\n const validVolume = Math.min(Math.max(volume, 0), 1);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"set_volume\",\n volume: validVolume,\n });\n } else {\n console.error(\"No message channel available to set volume\");\n }\n }, []);\n\n // Modify the useEffect hook that renders the LiveKit component\n useEffect(() => {\n if (!rootRef.current) return;\n\n if (connectionDetail) {\n if (!livekitComponentRef.current) {\n if (channelRef.current) {\n channelRef.current.port2.start();\n }\n\n livekitComponentRef.current = (\n <LiveKitRoom\n serverUrl={connectionDetail.serverUrl}\n token={connectionDetail.participantToken}\n audio={true}\n video={false}\n connect={true}\n onDisconnected={disconnect}\n onError={(error) => {\n console.error(\"LiveKit connection error:\", error);\n disconnect();\n if (options.onError) {\n options.onError(\n new Error(`LiveKit connection error: ${error.message}`)\n );\n }\n }}\n >\n <RoomAudioRenderer />\n {channelRef.current && (\n <StateMonitor\n port={channelRef.current.port2}\n initialConfig={\n waveformConfigRef.current || {\n barCount: 10,\n updateInterval: 20,\n }\n }\n />\n )}\n </LiveKitRoom>\n );\n }\n rootRef.current.render(livekitComponentRef.current);\n } else {\n livekitComponentRef.current = null;\n rootRef.current.render(<></>);\n }\n }, [connectionDetail, disconnect, options.onError]);\n\n return {\n connect,\n disconnect,\n state,\n messages,\n send,\n audioWaveform,\n toggleMic,\n setVolume,\n };\n}\n\n/**\n * Component that monitors LiveKit state and communicates back to the main hook\n */\nfunction StateMonitor({\n port,\n initialConfig,\n}: {\n port: MessagePort | undefined;\n initialConfig: {\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n };\n}) {\n const { agent, state } = useVoiceAssistant();\n const { send: sendChat } = useChat();\n\n // Initialize waveform config with the passed initial values, defaulting to \"agent\" if not specified\n const [waveformConfig, setWaveformConfig] = useState({\n speaker: initialConfig.speaker || \"agent\",\n barCount: initialConfig.barCount,\n updateInterval: initialConfig.updateInterval,\n });\n\n // Agent transcriptions\n const agentAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n agent?.identity\n )[0];\n const agentTranscription = useTrackTranscription(agentAudioTrack);\n\n // Use the current config for the waveform, applying different settings based on speaker\n const agentAudioWaveform = useAudioWaveform(agentAudioTrack, {\n barCount:\n waveformConfig.speaker === \"agent\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"agent\" ? waveformConfig.updateInterval : 20,\n });\n\n // User transcriptions\n const localParticipant = useLocalParticipant();\n const localMessages = useTrackTranscription({\n publication: localParticipant.microphoneTrack,\n source: Track.Source.Microphone,\n participant: localParticipant.localParticipant,\n });\n const localAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n localParticipant.localParticipant.identity\n )[0];\n const userAudioWaveform = useAudioWaveform(localAudioTrack, {\n barCount: waveformConfig.speaker === \"user\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"user\" ? waveformConfig.updateInterval : 20,\n });\n\n // Add separate effects to send agent and user waveform data\n useEffect(() => {\n if (!port || !agentAudioWaveform || !agentAudioWaveform.bars) return;\n\n // Send the agent waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: agentAudioWaveform.bars,\n speaker: \"agent\",\n });\n }, [port, agentAudioWaveform]);\n\n useEffect(() => {\n if (!port || !userAudioWaveform || !userAudioWaveform.bars) return;\n\n // Send the user waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: userAudioWaveform.bars,\n speaker: \"user\",\n });\n }, [port, userAudioWaveform]);\n\n // Listen for messages including config updates and mic toggle commands\n useEffect(() => {\n if (!port) return;\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n\n if (data.type === \"waveform_config\" && data.config) {\n // Verify we have both required properties before updating\n if (\n typeof data.config.barCount === \"number\" &&\n typeof data.config.updateInterval === \"number\"\n ) {\n setWaveformConfig(data.config);\n }\n } else if (data.type === \"send_text\") {\n if (sendChat) {\n sendChat(data.text);\n } else {\n console.error(\"sendChat function is not available\");\n }\n } else if (data.type === \"send_dtmf\") {\n if (localParticipant.localParticipant) {\n // Use standard DTMF code (RFC 4733)\n const standardDtmfCode = 101; // Standard DTMF payload type\n localParticipant.localParticipant.publishDtmf(\n standardDtmfCode,\n data.digit\n );\n } else {\n console.error(\"Local participant is not available for DTMF\");\n }\n } else if (\n data.type === \"toggle_mic\" &&\n typeof data.enabled === \"boolean\"\n ) {\n // Handle microphone toggle\n if (localParticipant.localParticipant) {\n localParticipant.localParticipant\n .setMicrophoneEnabled(data.enabled)\n .catch((error) => {\n console.error(\"Failed to toggle microphone:\", error);\n });\n } else {\n console.error(\"Local participant is not available for mic toggle\");\n }\n } else if (\n data.type === \"set_volume\" &&\n typeof data.volume === \"number\"\n ) {\n // Handle volume control\n if (agent) {\n // The agent is a RemoteParticipant, so we can call setVolume directly\n try {\n agent.setVolume(data.volume);\n console.log(`Set agent volume to ${data.volume}`);\n } catch (error) {\n console.error(\"Failed to set agent volume:\", error);\n }\n } else {\n console.error(\"Agent is not available for volume control\");\n }\n }\n };\n\n // Make sure we start the port\n port.start();\n\n port.addEventListener(\"message\", handleMessage);\n\n return () => {\n port.removeEventListener(\"message\", handleMessage);\n };\n }, [port, sendChat, localParticipant, agent]);\n\n // Send agent state updates\n useEffect(() => {\n if (port) {\n port.postMessage({ type: \"state_update\", state });\n }\n }, [state, port]);\n\n // Send agent transcriptions\n useEffect(() => {\n if (port && agentTranscription.segments.length > 0) {\n const transcriptions = agentTranscription.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"agent\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [agentTranscription.segments, port]);\n\n // Send user transcriptions\n useEffect(() => {\n if (port && localMessages.segments.length > 0) {\n const transcriptions = localMessages.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"user\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [localMessages.segments, port]);\n\n // Add data channel hook for function calls\n const { message: functionToolsExecuted } = useDataChannel(\n \"function_tools_executed\",\n (msg) => {\n if (!port) return;\n\n const textDecoder = new TextDecoder();\n const messageString =\n msg.payload instanceof Uint8Array\n ? textDecoder.decode(msg.payload)\n : String(msg.payload);\n\n let tool: FunctionToolsExecuted;\n try {\n tool = JSON.parse(messageString);\n\n // Send function calls to main hook via the port\n port.postMessage({\n type: \"function_tools_executed\",\n tool: tool,\n });\n } catch (e) {\n console.error(\"Failed to parse function call log:\", e);\n }\n }\n );\n\n return null;\n}\n","// export const HTTPS_API_ORIGIN = \"https://frontend-dev.tryvox.co/api/agent/sdk\";\nexport const HTTPS_API_ORIGIN = \"https://www.tryvox.co/api/agent/sdk\";\n// export const HTTPS_API_ORIGIN = \"http://localhost:3000/api/agent/sdk\";\nexport const SDK_VERSION = \"0.3.0\";\n"],"names":["useVoxAI","options","connectionDetail","setConnectionDetail","useState","state","setState","sessionTimestampRef","useRef","Date","now","transcriptMap","setTranscriptMap","Map","messages","setMessages","prevMessagesRef","processedMessageIdsRef","Set","portalRootRef","rootRef","channelRef","livekitComponentRef","waveformDataMap","setWaveformDataMap","agent","user","waveformConfigRef","isMicEnabled","setIsMicEnabled","useEffect","allMessages","Array","from","values","sort","a","b","timestamp","messagesString","JSON","stringify","current","onMessage","filter","msg","isFinal","id","has","forEach","add","channel","MessageChannel","port1","onmessage","e","data","type","handleTranscriptionUpdate","transcriptions","speaker","prevMap","_extends","waveformData","tool","functionCallsId","newMap","set","name","start","_channelRef$current","_channelRef$current2","close","port2","useCallback","t","_prevMap$get","messageType","existingTimestamp","get","message","text","div","document","createElement","style","display","body","appendChild","createRoot","unmount","removeChild","connect","async","agentId","apiKey","dynamicVariables","metadata","errorMessage","console","warn","onError","Error","Promise","reject","response","fetch","method","headers","Authorization","agent_id","runtime_context","source","version","call_web","dynamic_variables","ok","errorText","status","json","onConnect","err","error","String","disconnect","onDisconnect","send","digit","messageId","postMessage","undefined","audioWaveform","barCount","updateInterval","config","speakerData","length","slice","fill","toggleMic","value","enabled","setVolume","volume","validVolume","Math","min","max","_jsxs","LiveKitRoom","serverUrl","token","participantToken","audio","video","onDisconnected","children","_jsx","RoomAudioRenderer","StateMonitor","port","initialConfig","render","_Fragment","useVoiceAssistant","sendChat","useChat","waveformConfig","setWaveformConfig","agentAudioTrack","useParticipantTracks","Track","Source","Microphone","identity","agentTranscription","useTrackTranscription","agentAudioWaveform","useAudioWaveform","localParticipant","useLocalParticipant","localMessages","publication","microphoneTrack","participant","localAudioTrack","userAudioWaveform","bars","handleMessage","event","publishDtmf","setMicrophoneEnabled","catch","log","addEventListener","removeEventListener","segments","map","segment","final","useDataChannel","textDecoder","TextDecoder","messageString","payload","Uint8Array","decode","parse"],"mappings":"qqBAmIgB,SAAAA,EAASC,EAAwB,CAAA,GAE/C,MAAOC,EAAkBC,GACvBC,EAAqC,OAChCC,EAAOC,GAAYF,EAAwB,gBAG5CG,EAAsBC,EAAeC,KAAKC,QAGzCC,EAAeC,GAAoBR,EACxC,IAAIS,MAECC,EAAUC,GAAeX,EAAuB,IACjDY,EAAkBR,EAAe,IAGjCS,EAAyBT,EAAoB,IAAIU,KAGjDC,EAAgBX,EAA8B,MAC9CY,EAAUZ,EAAoB,MAG9Ba,EAAab,EAA8B,MAG3Cc,EAAsBd,EAAwB,OAG7Ce,EAAiBC,GAAsBpB,EAE5C,CACAqB,MAAO,GACPC,KAAM,KAIFC,EAAoBnB,EAIhB,OAGHoB,EAAcC,GAAmBzB,GAAkB,GAG1D0B,EAAU,KACR,MAAMC,EAAcC,MA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B,UAAWN,GAE1B,KACL5B,EAAKmC,oBAAoB,UAAWP,GACtC,EACC,CAAC5B,EAAMK,EAAUc,EAAkB1J,IAGtCK,EAAU,KACJkI,GACFA,EAAK/B,YAAY,CAAExE,KAAM,eAAgBpD,SAC3C,EACC,CAACA,EAAO2J,IAGXlI,EAAU,KACR,GAAIkI,GAAQe,EAAmBqB,SAAS5D,OAAS,EAAG,CAClD,MAAM7E,EAAiBoH,EAAmBqB,SAASC,IAAKC,IAAO,CAC7DvJ,GAAIuJ,EAAQvJ,GACZkC,KAAMqH,EAAQrH,KACdnC,QAASwJ,EAAQC,MACjBjK,UAAW7B,KAAKC,MAChBkD,QAAS,WAGXoG,EAAK/B,YAAY,CACfxE,KAAM,uBACNE,kBAEJ,GACC,CAACoH,EAAmBqB,SAAUpC,IAGjClI,EAAU,KACR,GAAIkI,GAAQqB,EAAce,SAAS5D,OAAS,EAAG,CAC7C,MAAM7E,EAAiB0H,EAAce,SAASC,IAAKC,IAAO,CACxDvJ,GAAIuJ,EAAQvJ,GACZkC,KAAMqH,EAAQrH,KACdnC,QAASwJ,EAAQC,MACjBjK,UAAW7B,KAAKC,MAChBkD,QAAS,UAGXoG,EAAK/B,YAAY,CACfxE,KAAM,uBACNE,kBAEJ,GACC,CAAC0H,EAAce,SAAUpC,IAGewC,EACzC,0BACC3J,IACC,IAAKmH,EAAM,OAEX,MAAMyC,EAAc,IAAIC,YAClBC,EACJ9J,EAAI+J,mBAAmBC,WACnBJ,EAAYK,OAAOjK,EAAI+J,SACvBjF,OAAO9E,EAAI+J,SAEjB,IAAI5I,EACJ,IACEA,EAAOxB,KAAKuK,MAAMJ,GAGlB3C,EAAK/B,YAAY,CACfxE,KAAM,0BACNO,KAAMA,GAEV,CAAE,MAAOT,GACP4C,QAAQuB,MAAM,qCAAsCnE,EACtD,IAKN,IAAA"}
1
+ {"version":3,"file":"lib.modern.js","sources":["../src/hooks/useVoxAI.tsx","../src/utils/constants.ts"],"sourcesContent":["import {\n LiveKitRoom,\n RoomAudioRenderer,\n useAudioWaveform,\n useChat,\n useDataChannel,\n useLocalParticipant,\n useParticipantTracks,\n useTrackTranscription,\n useVoiceAssistant,\n} from \"@livekit/components-react\";\nimport { Track } from \"livekit-client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport { HTTPS_API_ORIGIN, SDK_VERSION } from \"../utils/constants\";\n\ntype VoxConnectionDetail = {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n};\n\n/**\n * VoxAgentState\n * @description The state of the agent\n */\nexport type VoxAgentState =\n | \"disconnected\"\n | \"connecting\"\n | \"initializing\"\n | \"listening\"\n | \"thinking\"\n | \"speaking\";\n\n/**\n * Function call related types\n */\nexport interface FunctionToolsExecuted {\n type: \"function_tools_executed\";\n function_calls: FunctionCallInfo[];\n function_call_outputs: FunctionCallResult[];\n}\n\nexport interface FunctionCallInfo {\n id: string;\n type: string;\n call_id: string;\n arguments: Record<string, any>;\n name: string;\n}\n\nexport interface FunctionCallResult {\n id: string;\n name: string;\n type: string;\n call_id: string;\n output: string;\n is_error: boolean;\n}\n\n/**\n * VoxMessage\n * @description The message type between the agent and the user\n */\nexport type VoxMessage = {\n id?: string;\n name: \"agent\" | \"user\" | \"tool\";\n message?: string;\n timestamp: number;\n isFinal?: boolean;\n tool?: FunctionToolsExecuted;\n};\n\n/**\n * VoxAIOptions\n * @description The callback functions for the useVoxAI hook\n */\nexport interface VoxAIOptions {\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onMessage?: (message: VoxMessage) => void;\n}\n\n// Message channel event types\ntype MessageChannelEvent =\n | { type: \"state_update\"; state: VoxAgentState }\n | { type: \"transcription_update\"; transcriptions: TranscriptionSegment[] }\n | {\n type: \"waveform_update\";\n waveformData: number[];\n speaker: \"agent\" | \"user\";\n }\n | { type: \"function_tools_executed\"; tool: FunctionToolsExecuted };\n\ntype TranscriptionSegment = {\n id: string;\n text: string;\n isFinal: boolean;\n timestamp: number;\n speaker: \"agent\" | \"user\";\n};\n\n/**\n * ConnectParams\n * @param agentId - The agent ID\n * @param agentVersion - The agent version, if not provided, the current version will be used\n * @param apiKey - The API key\n * @param dynamicVariables - The dynamic variables\n * @param metadata - 이 메타데이터는 아웃바운드 웹훅, 통화 기록에 포함됩니다.\n */\nexport interface ConnectParams {\n agentId: string;\n agentVersion?: number;\n apiKey: string;\n dynamicVariables?: Record<string, any>;\n metadata?: Record<string, any>;\n}\n\n/**\n * useVoxAI\n * @description The hook for integrating with vox.ai voice assistant\n * @param options - The options for the useVoxAI hook\n * @returns The useVoxAI hook\n * @example\n * const { connect, disconnect, state, messages, send } = useVoxAI({\n * onConnect: () => console.log(\"Connected\"),\n * onDisconnect: () => console.log(\"Disconnected\"),\n * onError: (error) => console.error(\"Error:\", error),\n * onMessage: (message) => console.log(\"Message:\", message),\n * });\n */\nexport function useVoxAI(options: VoxAIOptions = {}) {\n // Connection state\n const [connectionDetail, setConnectionDetail] =\n useState<VoxConnectionDetail | null>(null);\n const [state, setState] = useState<VoxAgentState>(\"disconnected\");\n\n // Session timestamp to filter out stale asynchronous events\n const sessionTimestampRef = useRef<number>(Date.now());\n\n // Message handling\n const [transcriptMap, setTranscriptMap] = useState<Map<string, VoxMessage>>(\n new Map()\n );\n const [messages, setMessages] = useState<VoxMessage[]>([]);\n const prevMessagesRef = useRef<string>(\"\");\n\n // Track which messages we've already sent to the onMessage callback\n const processedMessageIdsRef = useRef<Set<string>>(new Set());\n\n // DOM manipulation for LiveKit portal\n const portalRootRef = useRef<HTMLDivElement | null>(null);\n const rootRef = useRef<Root | null>(null);\n\n // Communication channel\n const channelRef = useRef<MessageChannel | null>(null);\n\n // Add this near the start of your useVoxAI hook\n const livekitComponentRef = useRef<React.ReactNode>(null);\n\n // Replace the single waveform state with a map for multiple speakers\n const [waveformDataMap, setWaveformDataMap] = useState<\n Record<string, number[]>\n >({\n agent: [],\n user: [],\n });\n\n // Add back the waveform config reference\n const waveformConfigRef = useRef<{\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n } | null>(null);\n\n // Add a new state to track microphone status\n const [isMicEnabled, setIsMicEnabled] = useState<boolean>(true);\n\n // Update messages whenever transcriptMap changes\n useEffect(() => {\n const allMessages = Array.from(transcriptMap.values()).sort(\n (a, b) => a.timestamp - b.timestamp\n );\n\n // Only update if the messages have actually changed\n const messagesString = JSON.stringify(allMessages);\n if (messagesString !== prevMessagesRef.current) {\n prevMessagesRef.current = messagesString;\n setMessages(allMessages);\n\n // Only trigger onMessage for new final messages that haven't been processed yet\n if (options.onMessage) {\n allMessages\n .filter(\n (msg) =>\n msg.isFinal &&\n msg.id &&\n !processedMessageIdsRef.current.has(msg.id)\n )\n .forEach((msg) => {\n if (msg.id) {\n // Mark this message as processed\n processedMessageIdsRef.current.add(msg.id);\n // Call the callback\n options.onMessage?.(msg);\n }\n });\n }\n }\n }, [transcriptMap, options.onMessage]);\n\n // Initialize message channel - ensure ports are properly connected\n useEffect(() => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (e) => {\n const data = e.data as MessageChannelEvent;\n\n if (data.type === \"state_update\") {\n setState(data.state);\n } else if (data.type === \"transcription_update\") {\n handleTranscriptionUpdate(data.transcriptions);\n } else if (data.type === \"waveform_update\" && data.speaker) {\n // Store the waveform data for the specific speaker\n setWaveformDataMap((prevMap) => ({\n ...prevMap,\n [data.speaker]: data.waveformData,\n }));\n } else if (data.type === \"function_tools_executed\" && data.tool) {\n // Handle function calls\n const functionCallsId = `function-calls-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(functionCallsId, {\n id: functionCallsId,\n name: \"tool\",\n tool: data.tool,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n }\n };\n\n // Start the port\n channel.port1.start();\n\n // Store the channel reference\n channelRef.current = channel;\n\n return () => {\n channelRef.current?.port1.close();\n channelRef.current?.port2.close();\n channelRef.current = null;\n };\n }, []);\n\n // Process incoming transcriptions and filter out stale events\n const handleTranscriptionUpdate = useCallback(\n (transcriptions: TranscriptionSegment[]) => {\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n\n transcriptions.forEach((t) => {\n // Only process transcriptions generated after the current session timestamp\n if (t.timestamp < sessionTimestampRef.current) {\n return;\n }\n const messageType = t.speaker === \"agent\" ? \"agent\" : \"user\";\n // Use existing timestamp if we already have this segment\n const existingTimestamp = prevMap.get(t.id)?.timestamp || t.timestamp;\n\n newMap.set(t.id, {\n id: t.id,\n name: messageType,\n message: t.text,\n timestamp: existingTimestamp,\n isFinal: t.isFinal,\n });\n });\n\n return newMap;\n });\n },\n []\n );\n\n // Set up DOM portal for LiveKit\n useEffect(() => {\n const div = document.createElement(\"div\");\n div.style.display = \"none\";\n document.body.appendChild(div);\n portalRootRef.current = div;\n rootRef.current = createRoot(div);\n\n return () => {\n if (rootRef.current) {\n rootRef.current.unmount();\n }\n if (portalRootRef.current) {\n document.body.removeChild(portalRootRef.current);\n }\n };\n }, []);\n\n // Connect to VoxAI service - updated to include dynamicVariables\n const connect = useCallback(\n async ({ agentId, apiKey, dynamicVariables, metadata }: ConnectParams) => {\n try {\n // Prevent connecting if already in a connection state\n if (state !== \"disconnected\") {\n const errorMessage = `Connection attempt rejected: Already in a connection state (${state})`;\n console.warn(errorMessage);\n\n if (options.onError) {\n options.onError(new Error(errorMessage));\n }\n return Promise.reject(new Error(errorMessage));\n }\n\n // Update session timestamp for new connection\n sessionTimestampRef.current = Date.now();\n setState(\"connecting\");\n\n const response = await fetch(HTTPS_API_ORIGIN, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agent_id: agentId,\n metadata: {\n runtime_context: {\n source: {\n type: \"react-sdk\",\n version: SDK_VERSION,\n },\n },\n call_web: {\n dynamic_variables: dynamicVariables || {},\n metadata: metadata || {},\n },\n },\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Connection failed (${response.status}): ${errorText}`\n );\n }\n\n const data = await response.json();\n setConnectionDetail(data);\n\n if (options.onConnect) {\n options.onConnect();\n }\n } catch (err) {\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n if (options.onError) {\n options.onError(error);\n }\n }\n },\n [options, state]\n );\n\n // Disconnect from VoxAI service, updating the session timestamp to ignore stale events\n const disconnect = useCallback(() => {\n // Update session timestamp on disconnect\n sessionTimestampRef.current = Date.now();\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n if (options.onDisconnect) {\n options.onDisconnect();\n }\n }, [options]);\n\n // Update the send function with debugging and error checking\n const send = useCallback(\n ({ message, digit }: { message?: string; digit?: number }) => {\n if (state === \"disconnected\") {\n console.warn(\"Cannot send message: Not connected to a conversation\");\n return;\n }\n\n if (message) {\n const messageId = `user-text-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(messageId, {\n id: messageId,\n name: \"user\",\n message: message,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_text\",\n text: message,\n });\n } else {\n console.error(\"No message channel available to send message\");\n }\n }\n\n if (digit !== undefined) {\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_dtmf\",\n digit: digit,\n });\n } else {\n console.error(\"No message channel available to send DTMF\");\n }\n }\n },\n [state]\n );\n\n // Update the audioWaveform function to return data for the requested speaker\n const audioWaveform = useCallback(\n ({\n speaker = \"agent\",\n barCount = 10,\n updateInterval = 20,\n }: {\n speaker?: \"agent\" | \"user\";\n barCount?: number;\n updateInterval?: number;\n }): number[] => {\n waveformConfigRef.current = { speaker, barCount, updateInterval };\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"waveform_config\",\n config: { speaker, barCount, updateInterval },\n });\n }\n\n const speakerData = waveformDataMap[speaker] || [];\n return speakerData.length > 0\n ? speakerData.slice(0, barCount)\n : Array(barCount).fill(0);\n },\n [waveformDataMap]\n );\n\n // Add toggleMic function that will be exposed in the hook's return value\n const toggleMic = useCallback((value: boolean) => {\n setIsMicEnabled(value);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"toggle_mic\",\n enabled: value,\n });\n } else {\n console.error(\"No message channel available to toggle microphone\");\n }\n }, []);\n\n // Add setVolume function that will be exposed in the hook's return value\n const setVolume = useCallback((volume: number) => {\n const validVolume = Math.min(Math.max(volume, 0), 1);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"set_volume\",\n volume: validVolume,\n });\n } else {\n console.error(\"No message channel available to set volume\");\n }\n }, []);\n\n // Modify the useEffect hook that renders the LiveKit component\n useEffect(() => {\n if (!rootRef.current) return;\n\n if (connectionDetail) {\n if (!livekitComponentRef.current) {\n if (channelRef.current) {\n channelRef.current.port2.start();\n }\n\n livekitComponentRef.current = (\n <LiveKitRoom\n serverUrl={connectionDetail.serverUrl}\n token={connectionDetail.participantToken}\n audio={true}\n video={false}\n connect={true}\n onDisconnected={disconnect}\n onError={(error) => {\n console.error(\"LiveKit connection error:\", error);\n disconnect();\n if (options.onError) {\n options.onError(\n new Error(`LiveKit connection error: ${error.message}`)\n );\n }\n }}\n >\n <RoomAudioRenderer />\n {channelRef.current && (\n <StateMonitor\n port={channelRef.current.port2}\n initialConfig={\n waveformConfigRef.current || {\n barCount: 10,\n updateInterval: 20,\n }\n }\n />\n )}\n </LiveKitRoom>\n );\n }\n rootRef.current.render(livekitComponentRef.current);\n } else {\n livekitComponentRef.current = null;\n rootRef.current.render(<></>);\n }\n }, [connectionDetail, disconnect, options.onError]);\n\n return {\n connect,\n disconnect,\n state,\n messages,\n send,\n audioWaveform,\n toggleMic,\n setVolume,\n };\n}\n\n/**\n * Component that monitors LiveKit state and communicates back to the main hook\n */\nfunction StateMonitor({\n port,\n initialConfig,\n}: {\n port: MessagePort | undefined;\n initialConfig: {\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n };\n}) {\n const { agent, state } = useVoiceAssistant();\n const { send: sendChat } = useChat();\n\n // Initialize waveform config with the passed initial values, defaulting to \"agent\" if not specified\n const [waveformConfig, setWaveformConfig] = useState({\n speaker: initialConfig.speaker || \"agent\",\n barCount: initialConfig.barCount,\n updateInterval: initialConfig.updateInterval,\n });\n\n // Agent transcriptions\n const agentAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n agent?.identity\n )[0];\n const agentTranscription = useTrackTranscription(agentAudioTrack);\n\n // Use the current config for the waveform, applying different settings based on speaker\n const agentAudioWaveform = useAudioWaveform(agentAudioTrack, {\n barCount:\n waveformConfig.speaker === \"agent\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"agent\" ? waveformConfig.updateInterval : 20,\n });\n\n // User transcriptions\n const localParticipant = useLocalParticipant();\n const localMessages = useTrackTranscription({\n publication: localParticipant.microphoneTrack,\n source: Track.Source.Microphone,\n participant: localParticipant.localParticipant,\n });\n const localAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n localParticipant.localParticipant.identity\n )[0];\n const userAudioWaveform = useAudioWaveform(localAudioTrack, {\n barCount: waveformConfig.speaker === \"user\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"user\" ? waveformConfig.updateInterval : 20,\n });\n\n // Add separate effects to send agent and user waveform data\n useEffect(() => {\n if (!port || !agentAudioWaveform || !agentAudioWaveform.bars) return;\n\n // Send the agent waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: agentAudioWaveform.bars,\n speaker: \"agent\",\n });\n }, [port, agentAudioWaveform]);\n\n useEffect(() => {\n if (!port || !userAudioWaveform || !userAudioWaveform.bars) return;\n\n // Send the user waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: userAudioWaveform.bars,\n speaker: \"user\",\n });\n }, [port, userAudioWaveform]);\n\n // Listen for messages including config updates and mic toggle commands\n useEffect(() => {\n if (!port) return;\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n\n if (data.type === \"waveform_config\" && data.config) {\n // Verify we have both required properties before updating\n if (\n typeof data.config.barCount === \"number\" &&\n typeof data.config.updateInterval === \"number\"\n ) {\n setWaveformConfig(data.config);\n }\n } else if (data.type === \"send_text\") {\n if (sendChat) {\n sendChat(data.text);\n } else {\n console.error(\"sendChat function is not available\");\n }\n } else if (data.type === \"send_dtmf\") {\n if (localParticipant.localParticipant) {\n // Use standard DTMF code (RFC 4733)\n const standardDtmfCode = 101; // Standard DTMF payload type\n localParticipant.localParticipant.publishDtmf(\n standardDtmfCode,\n data.digit\n );\n } else {\n console.error(\"Local participant is not available for DTMF\");\n }\n } else if (\n data.type === \"toggle_mic\" &&\n typeof data.enabled === \"boolean\"\n ) {\n // Handle microphone toggle\n if (localParticipant.localParticipant) {\n localParticipant.localParticipant\n .setMicrophoneEnabled(data.enabled)\n .catch((error) => {\n console.error(\"Failed to toggle microphone:\", error);\n });\n } else {\n console.error(\"Local participant is not available for mic toggle\");\n }\n } else if (\n data.type === \"set_volume\" &&\n typeof data.volume === \"number\"\n ) {\n // Handle volume control\n if (agent) {\n // The agent is a RemoteParticipant, so we can call setVolume directly\n try {\n agent.setVolume(data.volume);\n console.log(`Set agent volume to ${data.volume}`);\n } catch (error) {\n console.error(\"Failed to set agent volume:\", error);\n }\n } else {\n console.error(\"Agent is not available for volume control\");\n }\n }\n };\n\n // Make sure we start the port\n port.start();\n\n port.addEventListener(\"message\", handleMessage);\n\n return () => {\n port.removeEventListener(\"message\", handleMessage);\n };\n }, [port, sendChat, localParticipant, agent]);\n\n // Send agent state updates\n useEffect(() => {\n if (port) {\n port.postMessage({ type: \"state_update\", state });\n }\n }, [state, port]);\n\n // Send agent transcriptions\n useEffect(() => {\n if (port && agentTranscription.segments.length > 0) {\n const transcriptions = agentTranscription.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"agent\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [agentTranscription.segments, port]);\n\n // Send user transcriptions\n useEffect(() => {\n if (port && localMessages.segments.length > 0) {\n const transcriptions = localMessages.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"user\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [localMessages.segments, port]);\n\n // Add data channel hook for function calls\n const { message: functionToolsExecuted } = useDataChannel(\n \"function_tools_executed\",\n (msg) => {\n if (!port) return;\n\n const textDecoder = new TextDecoder();\n const messageString =\n msg.payload instanceof Uint8Array\n ? textDecoder.decode(msg.payload)\n : String(msg.payload);\n\n let tool: FunctionToolsExecuted;\n try {\n tool = JSON.parse(messageString);\n\n // Send function calls to main hook via the port\n port.postMessage({\n type: \"function_tools_executed\",\n tool: tool,\n });\n } catch (e) {\n console.error(\"Failed to parse function call log:\", e);\n }\n }\n );\n\n return null;\n}\n","// export const HTTPS_API_ORIGIN = \"https://frontend-dev.tryvox.co/api/agent/sdk\";\nexport const HTTPS_API_ORIGIN = \"https://www.tryvox.co/api/agent/sdk\";\n// export const HTTPS_API_ORIGIN = \"http://localhost:3000/api/agent/sdk\";\nexport const SDK_VERSION = \"0.3.2\";\n"],"names":["useVoxAI","options","connectionDetail","setConnectionDetail","useState","state","setState","sessionTimestampRef","useRef","Date","now","transcriptMap","setTranscriptMap","Map","messages","setMessages","prevMessagesRef","processedMessageIdsRef","Set","portalRootRef","rootRef","channelRef","livekitComponentRef","waveformDataMap","setWaveformDataMap","agent","user","waveformConfigRef","isMicEnabled","setIsMicEnabled","useEffect","allMessages","Array","from","values","sort","a","b","timestamp","messagesString","JSON","stringify","current","onMessage","filter","msg","isFinal","id","has","forEach","add","channel","MessageChannel","port1","onmessage","e","data","type","handleTranscriptionUpdate","transcriptions","speaker","prevMap","_extends","waveformData","tool","functionCallsId","newMap","set","name","start","_channelRef$current","_channelRef$current2","close","port2","useCallback","t","_prevMap$get","messageType","existingTimestamp","get","message","text","div","document","createElement","style","display","body","appendChild","createRoot","unmount","removeChild","connect","async","agentId","apiKey","dynamicVariables","metadata","errorMessage","console","warn","onError","Error","Promise","reject","response","fetch","method","headers","Authorization","agent_id","runtime_context","source","version","call_web","dynamic_variables","ok","errorText","status","json","onConnect","err","error","String","disconnect","onDisconnect","send","digit","messageId","postMessage","undefined","audioWaveform","barCount","updateInterval","config","speakerData","length","slice","fill","toggleMic","value","enabled","setVolume","volume","validVolume","Math","min","max","_jsxs","LiveKitRoom","serverUrl","token","participantToken","audio","video","onDisconnected","children","_jsx","RoomAudioRenderer","StateMonitor","port","initialConfig","render","_Fragment","useVoiceAssistant","sendChat","useChat","waveformConfig","setWaveformConfig","agentAudioTrack","useParticipantTracks","Track","Source","Microphone","identity","agentTranscription","useTrackTranscription","agentAudioWaveform","useAudioWaveform","localParticipant","useLocalParticipant","localMessages","publication","microphoneTrack","participant","localAudioTrack","userAudioWaveform","bars","handleMessage","event","publishDtmf","setMicrophoneEnabled","catch","log","addEventListener","removeEventListener","segments","map","segment","final","useDataChannel","textDecoder","TextDecoder","messageString","payload","Uint8Array","decode","parse"],"mappings":"qqBAqIgB,SAAAA,EAASC,EAAwB,CAAA,GAE/C,MAAOC,EAAkBC,GACvBC,EAAqC,OAChCC,EAAOC,GAAYF,EAAwB,gBAG5CG,EAAsBC,EAAeC,KAAKC,QAGzCC,EAAeC,GAAoBR,EACxC,IAAIS,MAECC,EAAUC,GAAeX,EAAuB,IACjDY,EAAkBR,EAAe,IAGjCS,EAAyBT,EAAoB,IAAIU,KAGjDC,EAAgBX,EAA8B,MAC9CY,EAAUZ,EAAoB,MAG9Ba,EAAab,EAA8B,MAG3Cc,EAAsBd,EAAwB,OAG7Ce,EAAiBC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,QAAQuB,MAAM,qCAAsCnE,EACtD,IAKN,IAAA"}
@@ -1,2 +1,2 @@
1
- import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{LiveKitRoom as r,RoomAudioRenderer as o,useVoiceAssistant as a,useChat as s,useParticipantTracks as i,useTrackTranscription as c,useAudioWaveform as l,useLocalParticipant as u,useDataChannel as p}from"@livekit/components-react";import{Track as d}from"livekit-client";import{useState as m,useRef as g,useEffect as f,useCallback as v}from"react";import{createRoot as y}from"react-dom/client";function h(a){void 0===a&&(a={});const[s,i]=m(null),[c,l]=m("disconnected"),u=g(Date.now()),[p,d]=m(new Map),[h,w]=m([]),M=g(""),_=g(new Set),k=g(null),C=g(null),x=g(null),E=g(null),[D,P]=m({agent:[],user:[]}),F=g(null),[I,S]=m(!0);f(()=>{const e=Array.from(p.values()).sort((e,t)=>e.timestamp-t.timestamp),t=JSON.stringify(e);t!==M.current&&(M.current=t,w(e),a.onMessage&&e.filter(e=>e.isFinal&&e.id&&!_.current.has(e.id)).forEach(e=>{e.id&&(_.current.add(e.id),null==a.onMessage||a.onMessage(e))}))},[p,a.onMessage]),f(()=>{const e=new MessageChannel;return e.port1.onmessage=e=>{const t=e.data;if("state_update"===t.type)l(t.state);else if("transcription_update"===t.type)N(t.transcriptions);else if("waveform_update"===t.type&&t.speaker)P(e=>({...e,[t.speaker]:t.waveformData}));else if("function_tools_executed"===t.type&&t.tool){const e="function-calls-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"tool",tool:t.tool,timestamp:Date.now(),isFinal:!0}),r})}},e.port1.start(),x.current=e,()=>{var e,t;null==(e=x.current)||e.port1.close(),null==(t=x.current)||t.port2.close(),x.current=null}},[]);const N=v(e=>{d(t=>{const n=new Map(t);return e.forEach(e=>{var r;if(e.timestamp<u.current)return;const o="agent"===e.speaker?"agent":"user",a=(null==(r=t.get(e.id))?void 0:r.timestamp)||e.timestamp;n.set(e.id,{id:e.id,name:o,message:e.text,timestamp:a,isFinal:e.isFinal})}),n})},[]);f(()=>{const e=document.createElement("div");return e.style.display="none",document.body.appendChild(e),k.current=e,C.current=y(e),()=>{C.current&&C.current.unmount(),k.current&&document.body.removeChild(k.current)}},[]);const T=v(function(e){let{agentId:t,apiKey:n,dynamicVariables:r,metadata:o}=e;try{return Promise.resolve(function(e,s){try{var p=function(){if("disconnected"!==c){const e="Connection attempt rejected: Already in a connection state ("+c+")";return console.warn(e),a.onError&&a.onError(new Error(e)),Promise.reject(new Error(e))}return u.current=Date.now(),l("connecting"),Promise.resolve(fetch("https://www.tryvox.co/api/agent/sdk",{method:"POST",headers:{Authorization:"Bearer "+n,"Content-Type":"application/json"},body:JSON.stringify({agent_id:t,metadata:{runtime_context:{source:{type:"react-sdk",version:"0.3.0"}},call_web:{dynamic_variables:r||{},metadata:o||{}}}})})).then(function(e){function t(t){return Promise.resolve(e.json()).then(function(e){i(e),a.onConnect&&a.onConnect()})}const n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(t){throw new Error("Connection failed ("+e.status+"): "+t)})}();return n&&n.then?n.then(t):t()})}()}catch(e){return s(e)}return p&&p.then?p.then(void 0,s):p}(0,function(e){i(null),d(new Map),w([]),l("disconnected");const t=e instanceof Error?e:new Error(String(e));a.onError&&a.onError(t)}))}catch(e){return Promise.reject(e)}},[a,c]),j=v(()=>{u.current=Date.now(),i(null),d(new Map),w([]),l("disconnected"),a.onDisconnect&&a.onDisconnect()},[a]),A=v(e=>{let{message:t,digit:n}=e;if("disconnected"!==c){if(t){const e="user-text-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"user",message:t,timestamp:Date.now(),isFinal:!0}),r}),x.current?x.current.port1.postMessage({type:"send_text",text:t}):console.error("No message channel available to send message")}void 0!==n&&(x.current?x.current.port1.postMessage({type:"send_dtmf",digit:n}):console.error("No message channel available to send DTMF"))}else console.warn("Cannot send message: Not connected to a conversation")},[c]),L=v(e=>{let{speaker:t="agent",barCount:n=10,updateInterval:r=20}=e;F.current={speaker:t,barCount:n,updateInterval:r},x.current&&x.current.port1.postMessage({type:"waveform_config",config:{speaker:t,barCount:n,updateInterval:r}});const o=D[t]||[];return o.length>0?o.slice(0,n):Array(n).fill(0)},[D]),O=v(e=>{S(e),x.current?x.current.port1.postMessage({type:"toggle_mic",enabled:e}):console.error("No message channel available to toggle microphone")},[]),J=v(e=>{const t=Math.min(Math.max(e,0),1);x.current?x.current.port1.postMessage({type:"set_volume",volume:t}):console.error("No message channel available to set volume")},[]);return f(()=>{C.current&&(s?(E.current||(x.current&&x.current.port2.start(),E.current=e(r,{serverUrl:s.serverUrl,token:s.participantToken,audio:!0,video:!1,connect:!0,onDisconnected:j,onError:e=>{console.error("LiveKit connection error:",e),j(),a.onError&&a.onError(new Error("LiveKit connection error: "+e.message))},children:[t(o,{}),x.current&&t(b,{port:x.current.port2,initialConfig:F.current||{barCount:10,updateInterval:20}})]})),C.current.render(E.current)):(E.current=null,C.current.render(t(n,{}))))},[s,j,a.onError]),{connect:T,disconnect:j,state:c,messages:h,send:A,audioWaveform:L,toggleMic:O,setVolume:J}}function b(e){let{port:t,initialConfig:n}=e;const{agent:r,state:o}=a(),{send:g}=s(),[v,y]=m({speaker:n.speaker||"agent",barCount:n.barCount,updateInterval:n.updateInterval}),h=i([d.Source.Microphone],null==r?void 0:r.identity)[0],b=c(h),w=l(h,{barCount:"agent"===v.speaker?v.barCount:120,updateInterval:"agent"===v.speaker?v.updateInterval:20}),M=u(),_=c({publication:M.microphoneTrack,source:d.Source.Microphone,participant:M.localParticipant}),k=i([d.Source.Microphone],M.localParticipant.identity)[0],C=l(k,{barCount:"user"===v.speaker?v.barCount:120,updateInterval:"user"===v.speaker?v.updateInterval:20});return f(()=>{t&&w&&w.bars&&t.postMessage({type:"waveform_update",waveformData:w.bars,speaker:"agent"})},[t,w]),f(()=>{t&&C&&C.bars&&t.postMessage({type:"waveform_update",waveformData:C.bars,speaker:"user"})},[t,C]),f(()=>{if(!t)return;const e=e=>{const t=e.data;if("waveform_config"===t.type&&t.config)"number"==typeof t.config.barCount&&"number"==typeof t.config.updateInterval&&y(t.config);else if("send_text"===t.type)g?g(t.text):console.error("sendChat function is not available");else if("send_dtmf"===t.type)M.localParticipant?M.localParticipant.publishDtmf(101,t.digit):console.error("Local participant is not available for DTMF");else if("toggle_mic"===t.type&&"boolean"==typeof t.enabled)M.localParticipant?M.localParticipant.setMicrophoneEnabled(t.enabled).catch(e=>{console.error("Failed to toggle microphone:",e)}):console.error("Local participant is not available for mic toggle");else if("set_volume"===t.type&&"number"==typeof t.volume)if(r)try{r.setVolume(t.volume),console.log("Set agent volume to "+t.volume)}catch(e){console.error("Failed to set agent volume:",e)}else console.error("Agent is not available for volume control")};return t.start(),t.addEventListener("message",e),()=>{t.removeEventListener("message",e)}},[t,g,M,r]),f(()=>{t&&t.postMessage({type:"state_update",state:o})},[o,t]),f(()=>{if(t&&b.segments.length>0){const e=b.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"agent"}));t.postMessage({type:"transcription_update",transcriptions:e})}},[b.segments,t]),f(()=>{if(t&&_.segments.length>0){const e=_.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"user"}));t.postMessage({type:"transcription_update",transcriptions:e})}},[_.segments,t]),p("function_tools_executed",e=>{if(!t)return;const n=new TextDecoder,r=e.payload instanceof Uint8Array?n.decode(e.payload):String(e.payload);let o;try{o=JSON.parse(r),t.postMessage({type:"function_tools_executed",tool:o})}catch(e){console.error("Failed to parse function call log:",e)}}),null}export{h as useVoxAI};
1
+ import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{LiveKitRoom as r,RoomAudioRenderer as o,useVoiceAssistant as a,useChat as s,useParticipantTracks as i,useTrackTranscription as c,useAudioWaveform as l,useLocalParticipant as u,useDataChannel as p}from"@livekit/components-react";import{Track as d}from"livekit-client";import{useState as m,useRef as g,useEffect as f,useCallback as v}from"react";import{createRoot as y}from"react-dom/client";function h(a){void 0===a&&(a={});const[s,i]=m(null),[c,l]=m("disconnected"),u=g(Date.now()),[p,d]=m(new Map),[h,w]=m([]),M=g(""),_=g(new Set),k=g(null),C=g(null),x=g(null),E=g(null),[D,P]=m({agent:[],user:[]}),F=g(null),[I,S]=m(!0);f(()=>{const e=Array.from(p.values()).sort((e,t)=>e.timestamp-t.timestamp),t=JSON.stringify(e);t!==M.current&&(M.current=t,w(e),a.onMessage&&e.filter(e=>e.isFinal&&e.id&&!_.current.has(e.id)).forEach(e=>{e.id&&(_.current.add(e.id),null==a.onMessage||a.onMessage(e))}))},[p,a.onMessage]),f(()=>{const e=new MessageChannel;return e.port1.onmessage=e=>{const t=e.data;if("state_update"===t.type)l(t.state);else if("transcription_update"===t.type)N(t.transcriptions);else if("waveform_update"===t.type&&t.speaker)P(e=>({...e,[t.speaker]:t.waveformData}));else if("function_tools_executed"===t.type&&t.tool){const e="function-calls-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"tool",tool:t.tool,timestamp:Date.now(),isFinal:!0}),r})}},e.port1.start(),x.current=e,()=>{var e,t;null==(e=x.current)||e.port1.close(),null==(t=x.current)||t.port2.close(),x.current=null}},[]);const N=v(e=>{d(t=>{const n=new Map(t);return e.forEach(e=>{var r;if(e.timestamp<u.current)return;const o="agent"===e.speaker?"agent":"user",a=(null==(r=t.get(e.id))?void 0:r.timestamp)||e.timestamp;n.set(e.id,{id:e.id,name:o,message:e.text,timestamp:a,isFinal:e.isFinal})}),n})},[]);f(()=>{const e=document.createElement("div");return e.style.display="none",document.body.appendChild(e),k.current=e,C.current=y(e),()=>{C.current&&C.current.unmount(),k.current&&document.body.removeChild(k.current)}},[]);const T=v(function(e){let{agentId:t,apiKey:n,dynamicVariables:r,metadata:o}=e;try{return Promise.resolve(function(e,s){try{var p=function(){if("disconnected"!==c){const e="Connection attempt rejected: Already in a connection state ("+c+")";return console.warn(e),a.onError&&a.onError(new Error(e)),Promise.reject(new Error(e))}return u.current=Date.now(),l("connecting"),Promise.resolve(fetch("https://www.tryvox.co/api/agent/sdk",{method:"POST",headers:{Authorization:"Bearer "+n,"Content-Type":"application/json"},body:JSON.stringify({agent_id:t,metadata:{runtime_context:{source:{type:"react-sdk",version:"0.3.2"}},call_web:{dynamic_variables:r||{},metadata:o||{}}}})})).then(function(e){function t(t){return Promise.resolve(e.json()).then(function(e){i(e),a.onConnect&&a.onConnect()})}const n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(t){throw new Error("Connection failed ("+e.status+"): "+t)})}();return n&&n.then?n.then(t):t()})}()}catch(e){return s(e)}return p&&p.then?p.then(void 0,s):p}(0,function(e){i(null),d(new Map),w([]),l("disconnected");const t=e instanceof Error?e:new Error(String(e));a.onError&&a.onError(t)}))}catch(e){return Promise.reject(e)}},[a,c]),j=v(()=>{u.current=Date.now(),i(null),d(new Map),w([]),l("disconnected"),a.onDisconnect&&a.onDisconnect()},[a]),A=v(e=>{let{message:t,digit:n}=e;if("disconnected"!==c){if(t){const e="user-text-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"user",message:t,timestamp:Date.now(),isFinal:!0}),r}),x.current?x.current.port1.postMessage({type:"send_text",text:t}):console.error("No message channel available to send message")}void 0!==n&&(x.current?x.current.port1.postMessage({type:"send_dtmf",digit:n}):console.error("No message channel available to send DTMF"))}else console.warn("Cannot send message: Not connected to a conversation")},[c]),L=v(e=>{let{speaker:t="agent",barCount:n=10,updateInterval:r=20}=e;F.current={speaker:t,barCount:n,updateInterval:r},x.current&&x.current.port1.postMessage({type:"waveform_config",config:{speaker:t,barCount:n,updateInterval:r}});const o=D[t]||[];return o.length>0?o.slice(0,n):Array(n).fill(0)},[D]),O=v(e=>{S(e),x.current?x.current.port1.postMessage({type:"toggle_mic",enabled:e}):console.error("No message channel available to toggle microphone")},[]),J=v(e=>{const t=Math.min(Math.max(e,0),1);x.current?x.current.port1.postMessage({type:"set_volume",volume:t}):console.error("No message channel available to set volume")},[]);return f(()=>{C.current&&(s?(E.current||(x.current&&x.current.port2.start(),E.current=e(r,{serverUrl:s.serverUrl,token:s.participantToken,audio:!0,video:!1,connect:!0,onDisconnected:j,onError:e=>{console.error("LiveKit connection error:",e),j(),a.onError&&a.onError(new Error("LiveKit connection error: "+e.message))},children:[t(o,{}),x.current&&t(b,{port:x.current.port2,initialConfig:F.current||{barCount:10,updateInterval:20}})]})),C.current.render(E.current)):(E.current=null,C.current.render(t(n,{}))))},[s,j,a.onError]),{connect:T,disconnect:j,state:c,messages:h,send:A,audioWaveform:L,toggleMic:O,setVolume:J}}function b(e){let{port:t,initialConfig:n}=e;const{agent:r,state:o}=a(),{send:g}=s(),[v,y]=m({speaker:n.speaker||"agent",barCount:n.barCount,updateInterval:n.updateInterval}),h=i([d.Source.Microphone],null==r?void 0:r.identity)[0],b=c(h),w=l(h,{barCount:"agent"===v.speaker?v.barCount:120,updateInterval:"agent"===v.speaker?v.updateInterval:20}),M=u(),_=c({publication:M.microphoneTrack,source:d.Source.Microphone,participant:M.localParticipant}),k=i([d.Source.Microphone],M.localParticipant.identity)[0],C=l(k,{barCount:"user"===v.speaker?v.barCount:120,updateInterval:"user"===v.speaker?v.updateInterval:20});return f(()=>{t&&w&&w.bars&&t.postMessage({type:"waveform_update",waveformData:w.bars,speaker:"agent"})},[t,w]),f(()=>{t&&C&&C.bars&&t.postMessage({type:"waveform_update",waveformData:C.bars,speaker:"user"})},[t,C]),f(()=>{if(!t)return;const e=e=>{const t=e.data;if("waveform_config"===t.type&&t.config)"number"==typeof t.config.barCount&&"number"==typeof t.config.updateInterval&&y(t.config);else if("send_text"===t.type)g?g(t.text):console.error("sendChat function is not available");else if("send_dtmf"===t.type)M.localParticipant?M.localParticipant.publishDtmf(101,t.digit):console.error("Local participant is not available for DTMF");else if("toggle_mic"===t.type&&"boolean"==typeof t.enabled)M.localParticipant?M.localParticipant.setMicrophoneEnabled(t.enabled).catch(e=>{console.error("Failed to toggle microphone:",e)}):console.error("Local participant is not available for mic toggle");else if("set_volume"===t.type&&"number"==typeof t.volume)if(r)try{r.setVolume(t.volume),console.log("Set agent volume to "+t.volume)}catch(e){console.error("Failed to set agent volume:",e)}else console.error("Agent is not available for volume control")};return t.start(),t.addEventListener("message",e),()=>{t.removeEventListener("message",e)}},[t,g,M,r]),f(()=>{t&&t.postMessage({type:"state_update",state:o})},[o,t]),f(()=>{if(t&&b.segments.length>0){const e=b.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"agent"}));t.postMessage({type:"transcription_update",transcriptions:e})}},[b.segments,t]),f(()=>{if(t&&_.segments.length>0){const e=_.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"user"}));t.postMessage({type:"transcription_update",transcriptions:e})}},[_.segments,t]),p("function_tools_executed",e=>{if(!t)return;const n=new TextDecoder,r=e.payload instanceof Uint8Array?n.decode(e.payload):String(e.payload);let o;try{o=JSON.parse(r),t.postMessage({type:"function_tools_executed",tool:o})}catch(e){console.error("Failed to parse function call log:",e)}}),null}export{h as useVoxAI};
2
2
  //# sourceMappingURL=lib.module.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"lib.module.js","sources":["../src/hooks/useVoxAI.tsx","../src/utils/constants.ts"],"sourcesContent":["import {\n LiveKitRoom,\n RoomAudioRenderer,\n useAudioWaveform,\n useChat,\n useDataChannel,\n useLocalParticipant,\n useParticipantTracks,\n useTrackTranscription,\n useVoiceAssistant,\n} from \"@livekit/components-react\";\nimport { Track } from \"livekit-client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport { HTTPS_API_ORIGIN, SDK_VERSION } from \"../utils/constants\";\n\ntype VoxConnectionDetail = {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n};\n\n/**\n * VoxAgentState\n * @description The state of the agent\n */\nexport type VoxAgentState =\n | \"disconnected\"\n | \"connecting\"\n | \"initializing\"\n | \"listening\"\n | \"thinking\"\n | \"speaking\";\n\n/**\n * Function call related types\n */\nexport interface FunctionToolsExecuted {\n type: \"function_tools_executed\";\n function_calls: FunctionCallInfo[];\n function_call_outputs: FunctionCallResult[];\n}\n\nexport interface FunctionCallInfo {\n id: string;\n type: string;\n call_id: string;\n arguments: string;\n name: string;\n}\n\nexport interface FunctionCallResult {\n id: string;\n name: string;\n type: string;\n call_id: string;\n output: string;\n is_error: boolean;\n}\n\n/**\n * VoxMessage\n * @description The message type between the agent and the user\n */\nexport type VoxMessage = {\n id?: string;\n name: \"agent\" | \"user\" | \"tool\";\n message?: string;\n timestamp: number;\n isFinal?: boolean;\n tool?: FunctionToolsExecuted;\n};\n\n/**\n * VoxAIOptions\n * @description The callback functions for the useVoxAI hook\n */\nexport interface VoxAIOptions {\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onMessage?: (message: VoxMessage) => void;\n}\n\n// Message channel event types\ntype MessageChannelEvent =\n | { type: \"state_update\"; state: VoxAgentState }\n | { type: \"transcription_update\"; transcriptions: TranscriptionSegment[] }\n | {\n type: \"waveform_update\";\n waveformData: number[];\n speaker: \"agent\" | \"user\";\n }\n | { type: \"function_tools_executed\"; tool: FunctionToolsExecuted };\n\ntype TranscriptionSegment = {\n id: string;\n text: string;\n isFinal: boolean;\n timestamp: number;\n speaker: \"agent\" | \"user\";\n};\n\n/**\n * ConnectParams\n * @param agentId - The agent ID\n * @param apiKey - The API key\n * @param dynamicVariables - The dynamic variables\n * @param metadata - 이 메타데이터는 아웃바운드 웹훅, 통화 기록에 포함됩니다.\n */\nexport interface ConnectParams {\n agentId: string;\n apiKey: string;\n dynamicVariables?: Record<string, any>;\n metadata?: Record<string, any>;\n}\n\n/**\n * useVoxAI\n * @description The hook for integrating with vox.ai voice assistant\n * @param options - The options for the useVoxAI hook\n * @returns The useVoxAI hook\n * @example\n * const { connect, disconnect, state, messages, send } = useVoxAI({\n * onConnect: () => console.log(\"Connected\"),\n * onDisconnect: () => console.log(\"Disconnected\"),\n * onError: (error) => console.error(\"Error:\", error),\n * onMessage: (message) => console.log(\"Message:\", message),\n * });\n */\nexport function useVoxAI(options: VoxAIOptions = {}) {\n // Connection state\n const [connectionDetail, setConnectionDetail] =\n useState<VoxConnectionDetail | null>(null);\n const [state, setState] = useState<VoxAgentState>(\"disconnected\");\n\n // Session timestamp to filter out stale asynchronous events\n const sessionTimestampRef = useRef<number>(Date.now());\n\n // Message handling\n const [transcriptMap, setTranscriptMap] = useState<Map<string, VoxMessage>>(\n new Map()\n );\n const [messages, setMessages] = useState<VoxMessage[]>([]);\n const prevMessagesRef = useRef<string>(\"\");\n\n // Track which messages we've already sent to the onMessage callback\n const processedMessageIdsRef = useRef<Set<string>>(new Set());\n\n // DOM manipulation for LiveKit portal\n const portalRootRef = useRef<HTMLDivElement | null>(null);\n const rootRef = useRef<Root | null>(null);\n\n // Communication channel\n const channelRef = useRef<MessageChannel | null>(null);\n\n // Add this near the start of your useVoxAI hook\n const livekitComponentRef = useRef<React.ReactNode>(null);\n\n // Replace the single waveform state with a map for multiple speakers\n const [waveformDataMap, setWaveformDataMap] = useState<\n Record<string, number[]>\n >({\n agent: [],\n user: [],\n });\n\n // Add back the waveform config reference\n const waveformConfigRef = useRef<{\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n } | null>(null);\n\n // Add a new state to track microphone status\n const [isMicEnabled, setIsMicEnabled] = useState<boolean>(true);\n\n // Update messages whenever transcriptMap changes\n useEffect(() => {\n const allMessages = Array.from(transcriptMap.values()).sort(\n (a, b) => a.timestamp - b.timestamp\n );\n\n // Only update if the messages have actually changed\n const messagesString = JSON.stringify(allMessages);\n if (messagesString !== prevMessagesRef.current) {\n prevMessagesRef.current = messagesString;\n setMessages(allMessages);\n\n // Only trigger onMessage for new final messages that haven't been processed yet\n if (options.onMessage) {\n allMessages\n .filter(\n (msg) =>\n msg.isFinal &&\n msg.id &&\n !processedMessageIdsRef.current.has(msg.id)\n )\n .forEach((msg) => {\n if (msg.id) {\n // Mark this message as processed\n processedMessageIdsRef.current.add(msg.id);\n // Call the callback\n options.onMessage?.(msg);\n }\n });\n }\n }\n }, [transcriptMap, options.onMessage]);\n\n // Initialize message channel - ensure ports are properly connected\n useEffect(() => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (e) => {\n const data = e.data as MessageChannelEvent;\n\n if (data.type === \"state_update\") {\n setState(data.state);\n } else if (data.type === \"transcription_update\") {\n handleTranscriptionUpdate(data.transcriptions);\n } else if (data.type === \"waveform_update\" && data.speaker) {\n // Store the waveform data for the specific speaker\n setWaveformDataMap((prevMap) => ({\n ...prevMap,\n [data.speaker]: data.waveformData,\n }));\n } else if (data.type === \"function_tools_executed\" && data.tool) {\n // Handle function calls\n const functionCallsId = `function-calls-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(functionCallsId, {\n id: functionCallsId,\n name: \"tool\",\n tool: data.tool,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n }\n };\n\n // Start the port\n channel.port1.start();\n\n // Store the channel reference\n channelRef.current = channel;\n\n return () => {\n channelRef.current?.port1.close();\n channelRef.current?.port2.close();\n channelRef.current = null;\n };\n }, []);\n\n // Process incoming transcriptions and filter out stale events\n const handleTranscriptionUpdate = useCallback(\n (transcriptions: TranscriptionSegment[]) => {\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n\n transcriptions.forEach((t) => {\n // Only process transcriptions generated after the current session timestamp\n if (t.timestamp < sessionTimestampRef.current) {\n return;\n }\n const messageType = t.speaker === \"agent\" ? \"agent\" : \"user\";\n // Use existing timestamp if we already have this segment\n const existingTimestamp = prevMap.get(t.id)?.timestamp || t.timestamp;\n\n newMap.set(t.id, {\n id: t.id,\n name: messageType,\n message: t.text,\n timestamp: existingTimestamp,\n isFinal: t.isFinal,\n });\n });\n\n return newMap;\n });\n },\n []\n );\n\n // Set up DOM portal for LiveKit\n useEffect(() => {\n const div = document.createElement(\"div\");\n div.style.display = \"none\";\n document.body.appendChild(div);\n portalRootRef.current = div;\n rootRef.current = createRoot(div);\n\n return () => {\n if (rootRef.current) {\n rootRef.current.unmount();\n }\n if (portalRootRef.current) {\n document.body.removeChild(portalRootRef.current);\n }\n };\n }, []);\n\n // Connect to VoxAI service - updated to include dynamicVariables\n const connect = useCallback(\n async ({ agentId, apiKey, dynamicVariables, metadata }: ConnectParams) => {\n try {\n // Prevent connecting if already in a connection state\n if (state !== \"disconnected\") {\n const errorMessage = `Connection attempt rejected: Already in a connection state (${state})`;\n console.warn(errorMessage);\n\n if (options.onError) {\n options.onError(new Error(errorMessage));\n }\n return Promise.reject(new Error(errorMessage));\n }\n\n // Update session timestamp for new connection\n sessionTimestampRef.current = Date.now();\n setState(\"connecting\");\n\n const response = await fetch(HTTPS_API_ORIGIN, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agent_id: agentId,\n metadata: {\n runtime_context: {\n source: {\n type: \"react-sdk\",\n version: SDK_VERSION,\n },\n },\n call_web: {\n dynamic_variables: dynamicVariables || {},\n metadata: metadata || {},\n },\n },\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Connection failed (${response.status}): ${errorText}`\n );\n }\n\n const data = await response.json();\n setConnectionDetail(data);\n\n if (options.onConnect) {\n options.onConnect();\n }\n } catch (err) {\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n if (options.onError) {\n options.onError(error);\n }\n }\n },\n [options, state]\n );\n\n // Disconnect from VoxAI service, updating the session timestamp to ignore stale events\n const disconnect = useCallback(() => {\n // Update session timestamp on disconnect\n sessionTimestampRef.current = Date.now();\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n if (options.onDisconnect) {\n options.onDisconnect();\n }\n }, [options]);\n\n // Update the send function with debugging and error checking\n const send = useCallback(\n ({ message, digit }: { message?: string; digit?: number }) => {\n if (state === \"disconnected\") {\n console.warn(\"Cannot send message: Not connected to a conversation\");\n return;\n }\n\n if (message) {\n const messageId = `user-text-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(messageId, {\n id: messageId,\n name: \"user\",\n message: message,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_text\",\n text: message,\n });\n } else {\n console.error(\"No message channel available to send message\");\n }\n }\n\n if (digit !== undefined) {\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_dtmf\",\n digit: digit,\n });\n } else {\n console.error(\"No message channel available to send DTMF\");\n }\n }\n },\n [state]\n );\n\n // Update the audioWaveform function to return data for the requested speaker\n const audioWaveform = useCallback(\n ({\n speaker = \"agent\",\n barCount = 10,\n updateInterval = 20,\n }: {\n speaker?: \"agent\" | \"user\";\n barCount?: number;\n updateInterval?: number;\n }): number[] => {\n waveformConfigRef.current = { speaker, barCount, updateInterval };\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"waveform_config\",\n config: { speaker, barCount, updateInterval },\n });\n }\n\n const speakerData = waveformDataMap[speaker] || [];\n return speakerData.length > 0\n ? speakerData.slice(0, barCount)\n : Array(barCount).fill(0);\n },\n [waveformDataMap]\n );\n\n // Add toggleMic function that will be exposed in the hook's return value\n const toggleMic = useCallback((value: boolean) => {\n setIsMicEnabled(value);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"toggle_mic\",\n enabled: value,\n });\n } else {\n console.error(\"No message channel available to toggle microphone\");\n }\n }, []);\n\n // Add setVolume function that will be exposed in the hook's return value\n const setVolume = useCallback((volume: number) => {\n const validVolume = Math.min(Math.max(volume, 0), 1);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"set_volume\",\n volume: validVolume,\n });\n } else {\n console.error(\"No message channel available to set volume\");\n }\n }, []);\n\n // Modify the useEffect hook that renders the LiveKit component\n useEffect(() => {\n if (!rootRef.current) return;\n\n if (connectionDetail) {\n if (!livekitComponentRef.current) {\n if (channelRef.current) {\n channelRef.current.port2.start();\n }\n\n livekitComponentRef.current = (\n <LiveKitRoom\n serverUrl={connectionDetail.serverUrl}\n token={connectionDetail.participantToken}\n audio={true}\n video={false}\n connect={true}\n onDisconnected={disconnect}\n onError={(error) => {\n console.error(\"LiveKit connection error:\", error);\n disconnect();\n if (options.onError) {\n options.onError(\n new Error(`LiveKit connection error: ${error.message}`)\n );\n }\n }}\n >\n <RoomAudioRenderer />\n {channelRef.current && (\n <StateMonitor\n port={channelRef.current.port2}\n initialConfig={\n waveformConfigRef.current || {\n barCount: 10,\n updateInterval: 20,\n }\n }\n />\n )}\n </LiveKitRoom>\n );\n }\n rootRef.current.render(livekitComponentRef.current);\n } else {\n livekitComponentRef.current = null;\n rootRef.current.render(<></>);\n }\n }, [connectionDetail, disconnect, options.onError]);\n\n return {\n connect,\n disconnect,\n state,\n messages,\n send,\n audioWaveform,\n toggleMic,\n setVolume,\n };\n}\n\n/**\n * Component that monitors LiveKit state and communicates back to the main hook\n */\nfunction StateMonitor({\n port,\n initialConfig,\n}: {\n port: MessagePort | undefined;\n initialConfig: {\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n };\n}) {\n const { agent, state } = useVoiceAssistant();\n const { send: sendChat } = useChat();\n\n // Initialize waveform config with the passed initial values, defaulting to \"agent\" if not specified\n const [waveformConfig, setWaveformConfig] = useState({\n speaker: initialConfig.speaker || \"agent\",\n barCount: initialConfig.barCount,\n updateInterval: initialConfig.updateInterval,\n });\n\n // Agent transcriptions\n const agentAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n agent?.identity\n )[0];\n const agentTranscription = useTrackTranscription(agentAudioTrack);\n\n // Use the current config for the waveform, applying different settings based on speaker\n const agentAudioWaveform = useAudioWaveform(agentAudioTrack, {\n barCount:\n waveformConfig.speaker === \"agent\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"agent\" ? waveformConfig.updateInterval : 20,\n });\n\n // User transcriptions\n const localParticipant = useLocalParticipant();\n const localMessages = useTrackTranscription({\n publication: localParticipant.microphoneTrack,\n source: Track.Source.Microphone,\n participant: localParticipant.localParticipant,\n });\n const localAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n localParticipant.localParticipant.identity\n )[0];\n const userAudioWaveform = useAudioWaveform(localAudioTrack, {\n barCount: waveformConfig.speaker === \"user\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"user\" ? waveformConfig.updateInterval : 20,\n });\n\n // Add separate effects to send agent and user waveform data\n useEffect(() => {\n if (!port || !agentAudioWaveform || !agentAudioWaveform.bars) return;\n\n // Send the agent waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: agentAudioWaveform.bars,\n speaker: \"agent\",\n });\n }, [port, agentAudioWaveform]);\n\n useEffect(() => {\n if (!port || !userAudioWaveform || !userAudioWaveform.bars) return;\n\n // Send the user waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: userAudioWaveform.bars,\n speaker: \"user\",\n });\n }, [port, userAudioWaveform]);\n\n // Listen for messages including config updates and mic toggle commands\n useEffect(() => {\n if (!port) return;\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n\n if (data.type === \"waveform_config\" && data.config) {\n // Verify we have both required properties before updating\n if (\n typeof data.config.barCount === \"number\" &&\n typeof data.config.updateInterval === \"number\"\n ) {\n setWaveformConfig(data.config);\n }\n } else if (data.type === \"send_text\") {\n if (sendChat) {\n sendChat(data.text);\n } else {\n console.error(\"sendChat function is not available\");\n }\n } else if (data.type === \"send_dtmf\") {\n if (localParticipant.localParticipant) {\n // Use standard DTMF code (RFC 4733)\n const standardDtmfCode = 101; // Standard DTMF payload type\n localParticipant.localParticipant.publishDtmf(\n standardDtmfCode,\n data.digit\n );\n } else {\n console.error(\"Local participant is not available for DTMF\");\n }\n } else if (\n data.type === \"toggle_mic\" &&\n typeof data.enabled === \"boolean\"\n ) {\n // Handle microphone toggle\n if (localParticipant.localParticipant) {\n localParticipant.localParticipant\n .setMicrophoneEnabled(data.enabled)\n .catch((error) => {\n console.error(\"Failed to toggle microphone:\", error);\n });\n } else {\n console.error(\"Local participant is not available for mic toggle\");\n }\n } else if (\n data.type === \"set_volume\" &&\n typeof data.volume === \"number\"\n ) {\n // Handle volume control\n if (agent) {\n // The agent is a RemoteParticipant, so we can call setVolume directly\n try {\n agent.setVolume(data.volume);\n console.log(`Set agent volume to ${data.volume}`);\n } catch (error) {\n console.error(\"Failed to set agent volume:\", error);\n }\n } else {\n console.error(\"Agent is not available for volume control\");\n }\n }\n };\n\n // Make sure we start the port\n port.start();\n\n port.addEventListener(\"message\", handleMessage);\n\n return () => {\n port.removeEventListener(\"message\", handleMessage);\n };\n }, [port, sendChat, localParticipant, agent]);\n\n // Send agent state updates\n useEffect(() => {\n if (port) {\n port.postMessage({ type: \"state_update\", state });\n }\n }, [state, port]);\n\n // Send agent transcriptions\n useEffect(() => {\n if (port && agentTranscription.segments.length > 0) {\n const transcriptions = agentTranscription.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"agent\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [agentTranscription.segments, port]);\n\n // Send user transcriptions\n useEffect(() => {\n if (port && localMessages.segments.length > 0) {\n const transcriptions = localMessages.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"user\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [localMessages.segments, port]);\n\n // Add data channel hook for function calls\n const { message: functionToolsExecuted } = useDataChannel(\n \"function_tools_executed\",\n (msg) => {\n if (!port) return;\n\n const textDecoder = new TextDecoder();\n const messageString =\n msg.payload instanceof Uint8Array\n ? textDecoder.decode(msg.payload)\n : String(msg.payload);\n\n let tool: FunctionToolsExecuted;\n try {\n tool = JSON.parse(messageString);\n\n // Send function calls to main hook via the port\n port.postMessage({\n type: \"function_tools_executed\",\n tool: tool,\n });\n } catch (e) {\n console.error(\"Failed to parse function call log:\", e);\n }\n }\n );\n\n return null;\n}\n","// export const HTTPS_API_ORIGIN = \"https://frontend-dev.tryvox.co/api/agent/sdk\";\nexport const HTTPS_API_ORIGIN = \"https://www.tryvox.co/api/agent/sdk\";\n// export const HTTPS_API_ORIGIN = \"http://localhost:3000/api/agent/sdk\";\nexport const SDK_VERSION = \"0.3.0\";\n"],"names":["useVoxAI","options","connectionDetail","setConnectionDetail","useState","state","setState","sessionTimestampRef","useRef","Date","now","transcriptMap","setTranscriptMap","Map","messages","setMessages","prevMessagesRef","processedMessageIdsRef","Set","portalRootRef","rootRef","channelRef","livekitComponentRef","waveformDataMap","setWaveformDataMap","agent","user","waveformConfigRef","isMicEnabled","setIsMicEnabled","useEffect","allMessages","Array","from","values","sort","a","b","timestamp","messagesString","JSON","stringify","current","onMessage","filter","msg","isFinal","id","has","forEach","add","channel","MessageChannel","port1","onmessage","e","data","type","handleTranscriptionUpdate","transcriptions","speaker","prevMap","waveformData","tool","functionCallsId","newMap","set","name","start","_channelRef$current","_channelRef$current2","close","port2","useCallback","t","_prevMap$get","messageType","existingTimestamp","get","message","text","div","document","createElement","style","display","body","appendChild","createRoot","unmount","removeChild","connect","_ref","agentId","apiKey","dynamicVariables","metadata","Promise","resolve","errorMessage","console","warn","onError","Error","reject","fetch","method","headers","Authorization","agent_id","runtime_context","source","version","call_web","dynamic_variables","then","response","_temp2","_result2","_exit","json","onConnect","_temp","ok","errorText","status","_catch","err","error","String","disconnect","onDisconnect","send","_ref2","digit","messageId","postMessage","undefined","audioWaveform","_ref3","barCount","updateInterval","config","speakerData","length","slice","fill","toggleMic","value","enabled","setVolume","volume","validVolume","Math","min","max","_jsxs","LiveKitRoom","serverUrl","token","participantToken","audio","video","onDisconnected","children","_jsx","RoomAudioRenderer","StateMonitor","port","initialConfig","render","_Fragment","_ref4","useVoiceAssistant","sendChat","useChat","waveformConfig","setWaveformConfig","agentAudioTrack","useParticipantTracks","Track","Source","Microphone","identity","agentTranscription","useTrackTranscription","agentAudioWaveform","useAudioWaveform","localParticipant","useLocalParticipant","localMessages","publication","microphoneTrack","participant","localAudioTrack","userAudioWaveform","bars","handleMessage","event","publishDtmf","setMicrophoneEnabled","catch","log","addEventListener","removeEventListener","segments","map","segment","final","useDataChannel","textDecoder","TextDecoder","messageString","payload","Uint8Array","decode","parse"],"mappings":"6cAmIgB,SAAAA,EAASC,YAAAA,IAAAA,EAAwB,CAAA,GAE/C,MAAOC,EAAkBC,GACvBC,EAAqC,OAChCC,EAAOC,GAAYF,EAAwB,gBAG5CG,EAAsBC,EAAeC,KAAKC,QAGzCC,EAAeC,GAAoBR,EACxC,IAAIS,MAECC,EAAUC,GAAeX,EAAuB,IACjDY,EAAkBR,EAAe,IAGjCS,EAAyBT,EAAoB,IAAIU,KAGjDC,EAAgBX,EAA8B,MAC9CY,EAAUZ,EAAoB,MAG9Ba,EAAab,EAA8B,MAG3Cc,EAAsBd,EAAwB,OAG7Ce,EAAiBC,GAAsBpB,EAE5C,CACAqB,MAAO,GACPC,KAAM,KAIFC,EAAoBnB,EAIhB,OAGHoB,EAAcC,GAAmBzB,GAAkB,GAG1D0B,EAAU,KACR,MAAMC,EAAcC,MAAMC,KAAKtB,EAAcuB,UAAUC,KACrD,CAACC,EAAGC,IAAMD,EAAEE,UAAYD,EAAEC,WAItBC,EAAiBC,KAAKC,UAAUV,GAClCQ,IAAmBvB,EAAgB0B,UACrC1B,EAAgB0B,QAAUH,EAC1BxB,EAAYgB,GAGR9B,EAAQ0C,WACVZ,EACGa,OACEC,GACCA,EAAIC,SACJD,EAAIE,KACH9B,EAAuByB,QAAQM,IAAIH,EAAIE,KAE3CE,QAASJ,IACJA,EAAIE,KAE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/utils/constants.ts"],"sourcesContent":["import {\n LiveKitRoom,\n RoomAudioRenderer,\n useAudioWaveform,\n useChat,\n useDataChannel,\n useLocalParticipant,\n useParticipantTracks,\n useTrackTranscription,\n useVoiceAssistant,\n} from \"@livekit/components-react\";\nimport { Track } from \"livekit-client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport { HTTPS_API_ORIGIN, SDK_VERSION } from \"../utils/constants\";\n\ntype VoxConnectionDetail = {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n};\n\n/**\n * VoxAgentState\n * @description The state of the agent\n */\nexport type VoxAgentState =\n | \"disconnected\"\n | \"connecting\"\n | \"initializing\"\n | \"listening\"\n | \"thinking\"\n | \"speaking\";\n\n/**\n * Function call related types\n */\nexport interface FunctionToolsExecuted {\n type: \"function_tools_executed\";\n function_calls: FunctionCallInfo[];\n function_call_outputs: FunctionCallResult[];\n}\n\nexport interface FunctionCallInfo {\n id: string;\n type: string;\n call_id: string;\n arguments: Record<string, any>;\n name: string;\n}\n\nexport interface FunctionCallResult {\n id: string;\n name: string;\n type: string;\n call_id: string;\n output: string;\n is_error: boolean;\n}\n\n/**\n * VoxMessage\n * @description The message type between the agent and the user\n */\nexport type VoxMessage = {\n id?: string;\n name: \"agent\" | \"user\" | \"tool\";\n message?: string;\n timestamp: number;\n isFinal?: boolean;\n tool?: FunctionToolsExecuted;\n};\n\n/**\n * VoxAIOptions\n * @description The callback functions for the useVoxAI hook\n */\nexport interface VoxAIOptions {\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onMessage?: (message: VoxMessage) => void;\n}\n\n// Message channel event types\ntype MessageChannelEvent =\n | { type: \"state_update\"; state: VoxAgentState }\n | { type: \"transcription_update\"; transcriptions: TranscriptionSegment[] }\n | {\n type: \"waveform_update\";\n waveformData: number[];\n speaker: \"agent\" | \"user\";\n }\n | { type: \"function_tools_executed\"; tool: FunctionToolsExecuted };\n\ntype TranscriptionSegment = {\n id: string;\n text: string;\n isFinal: boolean;\n timestamp: number;\n speaker: \"agent\" | \"user\";\n};\n\n/**\n * ConnectParams\n * @param agentId - The agent ID\n * @param agentVersion - The agent version, if not provided, the current version will be used\n * @param apiKey - The API key\n * @param dynamicVariables - The dynamic variables\n * @param metadata - 이 메타데이터는 아웃바운드 웹훅, 통화 기록에 포함됩니다.\n */\nexport interface ConnectParams {\n agentId: string;\n agentVersion?: number;\n apiKey: string;\n dynamicVariables?: Record<string, any>;\n metadata?: Record<string, any>;\n}\n\n/**\n * useVoxAI\n * @description The hook for integrating with vox.ai voice assistant\n * @param options - The options for the useVoxAI hook\n * @returns The useVoxAI hook\n * @example\n * const { connect, disconnect, state, messages, send } = useVoxAI({\n * onConnect: () => console.log(\"Connected\"),\n * onDisconnect: () => console.log(\"Disconnected\"),\n * onError: (error) => console.error(\"Error:\", error),\n * onMessage: (message) => console.log(\"Message:\", message),\n * });\n */\nexport function useVoxAI(options: VoxAIOptions = {}) {\n // Connection state\n const [connectionDetail, setConnectionDetail] =\n useState<VoxConnectionDetail | null>(null);\n const [state, setState] = useState<VoxAgentState>(\"disconnected\");\n\n // Session timestamp to filter out stale asynchronous events\n const sessionTimestampRef = useRef<number>(Date.now());\n\n // Message handling\n const [transcriptMap, setTranscriptMap] = useState<Map<string, VoxMessage>>(\n new Map()\n );\n const [messages, setMessages] = useState<VoxMessage[]>([]);\n const prevMessagesRef = useRef<string>(\"\");\n\n // Track which messages we've already sent to the onMessage callback\n const processedMessageIdsRef = useRef<Set<string>>(new Set());\n\n // DOM manipulation for LiveKit portal\n const portalRootRef = useRef<HTMLDivElement | null>(null);\n const rootRef = useRef<Root | null>(null);\n\n // Communication channel\n const channelRef = useRef<MessageChannel | null>(null);\n\n // Add this near the start of your useVoxAI hook\n const livekitComponentRef = useRef<React.ReactNode>(null);\n\n // Replace the single waveform state with a map for multiple speakers\n const [waveformDataMap, setWaveformDataMap] = useState<\n Record<string, number[]>\n >({\n agent: [],\n user: [],\n });\n\n // Add back the waveform config reference\n const waveformConfigRef = useRef<{\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n } | null>(null);\n\n // Add a new state to track microphone status\n const [isMicEnabled, setIsMicEnabled] = useState<boolean>(true);\n\n // Update messages whenever transcriptMap changes\n useEffect(() => {\n const allMessages = Array.from(transcriptMap.values()).sort(\n (a, b) => a.timestamp - b.timestamp\n );\n\n // Only update if the messages have actually changed\n const messagesString = JSON.stringify(allMessages);\n if (messagesString !== prevMessagesRef.current) {\n prevMessagesRef.current = messagesString;\n setMessages(allMessages);\n\n // Only trigger onMessage for new final messages that haven't been processed yet\n if (options.onMessage) {\n allMessages\n .filter(\n (msg) =>\n msg.isFinal &&\n msg.id &&\n !processedMessageIdsRef.current.has(msg.id)\n )\n .forEach((msg) => {\n if (msg.id) {\n // Mark this message as processed\n processedMessageIdsRef.current.add(msg.id);\n // Call the callback\n options.onMessage?.(msg);\n }\n });\n }\n }\n }, [transcriptMap, options.onMessage]);\n\n // Initialize message channel - ensure ports are properly connected\n useEffect(() => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (e) => {\n const data = e.data as MessageChannelEvent;\n\n if (data.type === \"state_update\") {\n setState(data.state);\n } else if (data.type === \"transcription_update\") {\n handleTranscriptionUpdate(data.transcriptions);\n } else if (data.type === \"waveform_update\" && data.speaker) {\n // Store the waveform data for the specific speaker\n setWaveformDataMap((prevMap) => ({\n ...prevMap,\n [data.speaker]: data.waveformData,\n }));\n } else if (data.type === \"function_tools_executed\" && data.tool) {\n // Handle function calls\n const functionCallsId = `function-calls-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(functionCallsId, {\n id: functionCallsId,\n name: \"tool\",\n tool: data.tool,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n }\n };\n\n // Start the port\n channel.port1.start();\n\n // Store the channel reference\n channelRef.current = channel;\n\n return () => {\n channelRef.current?.port1.close();\n channelRef.current?.port2.close();\n channelRef.current = null;\n };\n }, []);\n\n // Process incoming transcriptions and filter out stale events\n const handleTranscriptionUpdate = useCallback(\n (transcriptions: TranscriptionSegment[]) => {\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n\n transcriptions.forEach((t) => {\n // Only process transcriptions generated after the current session timestamp\n if (t.timestamp < sessionTimestampRef.current) {\n return;\n }\n const messageType = t.speaker === \"agent\" ? \"agent\" : \"user\";\n // Use existing timestamp if we already have this segment\n const existingTimestamp = prevMap.get(t.id)?.timestamp || t.timestamp;\n\n newMap.set(t.id, {\n id: t.id,\n name: messageType,\n message: t.text,\n timestamp: existingTimestamp,\n isFinal: t.isFinal,\n });\n });\n\n return newMap;\n });\n },\n []\n );\n\n // Set up DOM portal for LiveKit\n useEffect(() => {\n const div = document.createElement(\"div\");\n div.style.display = \"none\";\n document.body.appendChild(div);\n portalRootRef.current = div;\n rootRef.current = createRoot(div);\n\n return () => {\n if (rootRef.current) {\n rootRef.current.unmount();\n }\n if (portalRootRef.current) {\n document.body.removeChild(portalRootRef.current);\n }\n };\n }, []);\n\n // Connect to VoxAI service - updated to include dynamicVariables\n const connect = useCallback(\n async ({ agentId, apiKey, dynamicVariables, metadata }: ConnectParams) => {\n try {\n // Prevent connecting if already in a connection state\n if (state !== \"disconnected\") {\n const errorMessage = `Connection attempt rejected: Already in a connection state (${state})`;\n console.warn(errorMessage);\n\n if (options.onError) {\n options.onError(new Error(errorMessage));\n }\n return Promise.reject(new Error(errorMessage));\n }\n\n // Update session timestamp for new connection\n sessionTimestampRef.current = Date.now();\n setState(\"connecting\");\n\n const response = await fetch(HTTPS_API_ORIGIN, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agent_id: agentId,\n metadata: {\n runtime_context: {\n source: {\n type: \"react-sdk\",\n version: SDK_VERSION,\n },\n },\n call_web: {\n dynamic_variables: dynamicVariables || {},\n metadata: metadata || {},\n },\n },\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Connection failed (${response.status}): ${errorText}`\n );\n }\n\n const data = await response.json();\n setConnectionDetail(data);\n\n if (options.onConnect) {\n options.onConnect();\n }\n } catch (err) {\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n if (options.onError) {\n options.onError(error);\n }\n }\n },\n [options, state]\n );\n\n // Disconnect from VoxAI service, updating the session timestamp to ignore stale events\n const disconnect = useCallback(() => {\n // Update session timestamp on disconnect\n sessionTimestampRef.current = Date.now();\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n if (options.onDisconnect) {\n options.onDisconnect();\n }\n }, [options]);\n\n // Update the send function with debugging and error checking\n const send = useCallback(\n ({ message, digit }: { message?: string; digit?: number }) => {\n if (state === \"disconnected\") {\n console.warn(\"Cannot send message: Not connected to a conversation\");\n return;\n }\n\n if (message) {\n const messageId = `user-text-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(messageId, {\n id: messageId,\n name: \"user\",\n message: message,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_text\",\n text: message,\n });\n } else {\n console.error(\"No message channel available to send message\");\n }\n }\n\n if (digit !== undefined) {\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_dtmf\",\n digit: digit,\n });\n } else {\n console.error(\"No message channel available to send DTMF\");\n }\n }\n },\n [state]\n );\n\n // Update the audioWaveform function to return data for the requested speaker\n const audioWaveform = useCallback(\n ({\n speaker = \"agent\",\n barCount = 10,\n updateInterval = 20,\n }: {\n speaker?: \"agent\" | \"user\";\n barCount?: number;\n updateInterval?: number;\n }): number[] => {\n waveformConfigRef.current = { speaker, barCount, updateInterval };\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"waveform_config\",\n config: { speaker, barCount, updateInterval },\n });\n }\n\n const speakerData = waveformDataMap[speaker] || [];\n return speakerData.length > 0\n ? speakerData.slice(0, barCount)\n : Array(barCount).fill(0);\n },\n [waveformDataMap]\n );\n\n // Add toggleMic function that will be exposed in the hook's return value\n const toggleMic = useCallback((value: boolean) => {\n setIsMicEnabled(value);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"toggle_mic\",\n enabled: value,\n });\n } else {\n console.error(\"No message channel available to toggle microphone\");\n }\n }, []);\n\n // Add setVolume function that will be exposed in the hook's return value\n const setVolume = useCallback((volume: number) => {\n const validVolume = Math.min(Math.max(volume, 0), 1);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"set_volume\",\n volume: validVolume,\n });\n } else {\n console.error(\"No message channel available to set volume\");\n }\n }, []);\n\n // Modify the useEffect hook that renders the LiveKit component\n useEffect(() => {\n if (!rootRef.current) return;\n\n if (connectionDetail) {\n if (!livekitComponentRef.current) {\n if (channelRef.current) {\n channelRef.current.port2.start();\n }\n\n livekitComponentRef.current = (\n <LiveKitRoom\n serverUrl={connectionDetail.serverUrl}\n token={connectionDetail.participantToken}\n audio={true}\n video={false}\n connect={true}\n onDisconnected={disconnect}\n onError={(error) => {\n console.error(\"LiveKit connection error:\", error);\n disconnect();\n if (options.onError) {\n options.onError(\n new Error(`LiveKit connection error: ${error.message}`)\n );\n }\n }}\n >\n <RoomAudioRenderer />\n {channelRef.current && (\n <StateMonitor\n port={channelRef.current.port2}\n initialConfig={\n waveformConfigRef.current || {\n barCount: 10,\n updateInterval: 20,\n }\n }\n />\n )}\n </LiveKitRoom>\n );\n }\n rootRef.current.render(livekitComponentRef.current);\n } else {\n livekitComponentRef.current = null;\n rootRef.current.render(<></>);\n }\n }, [connectionDetail, disconnect, options.onError]);\n\n return {\n connect,\n disconnect,\n state,\n messages,\n send,\n audioWaveform,\n toggleMic,\n setVolume,\n };\n}\n\n/**\n * Component that monitors LiveKit state and communicates back to the main hook\n */\nfunction StateMonitor({\n port,\n initialConfig,\n}: {\n port: MessagePort | undefined;\n initialConfig: {\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n };\n}) {\n const { agent, state } = useVoiceAssistant();\n const { send: sendChat } = useChat();\n\n // Initialize waveform config with the passed initial values, defaulting to \"agent\" if not specified\n const [waveformConfig, setWaveformConfig] = useState({\n speaker: initialConfig.speaker || \"agent\",\n barCount: initialConfig.barCount,\n updateInterval: initialConfig.updateInterval,\n });\n\n // Agent transcriptions\n const agentAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n agent?.identity\n )[0];\n const agentTranscription = useTrackTranscription(agentAudioTrack);\n\n // Use the current config for the waveform, applying different settings based on speaker\n const agentAudioWaveform = useAudioWaveform(agentAudioTrack, {\n barCount:\n waveformConfig.speaker === \"agent\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"agent\" ? waveformConfig.updateInterval : 20,\n });\n\n // User transcriptions\n const localParticipant = useLocalParticipant();\n const localMessages = useTrackTranscription({\n publication: localParticipant.microphoneTrack,\n source: Track.Source.Microphone,\n participant: localParticipant.localParticipant,\n });\n const localAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n localParticipant.localParticipant.identity\n )[0];\n const userAudioWaveform = useAudioWaveform(localAudioTrack, {\n barCount: waveformConfig.speaker === \"user\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"user\" ? waveformConfig.updateInterval : 20,\n });\n\n // Add separate effects to send agent and user waveform data\n useEffect(() => {\n if (!port || !agentAudioWaveform || !agentAudioWaveform.bars) return;\n\n // Send the agent waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: agentAudioWaveform.bars,\n speaker: \"agent\",\n });\n }, [port, agentAudioWaveform]);\n\n useEffect(() => {\n if (!port || !userAudioWaveform || !userAudioWaveform.bars) return;\n\n // Send the user waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: userAudioWaveform.bars,\n speaker: \"user\",\n });\n }, [port, userAudioWaveform]);\n\n // Listen for messages including config updates and mic toggle commands\n useEffect(() => {\n if (!port) return;\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n\n if (data.type === \"waveform_config\" && data.config) {\n // Verify we have both required properties before updating\n if (\n typeof data.config.barCount === \"number\" &&\n typeof data.config.updateInterval === \"number\"\n ) {\n setWaveformConfig(data.config);\n }\n } else if (data.type === \"send_text\") {\n if (sendChat) {\n sendChat(data.text);\n } else {\n console.error(\"sendChat function is not available\");\n }\n } else if (data.type === \"send_dtmf\") {\n if (localParticipant.localParticipant) {\n // Use standard DTMF code (RFC 4733)\n const standardDtmfCode = 101; // Standard DTMF payload type\n localParticipant.localParticipant.publishDtmf(\n standardDtmfCode,\n data.digit\n );\n } else {\n console.error(\"Local participant is not available for DTMF\");\n }\n } else if (\n data.type === \"toggle_mic\" &&\n typeof data.enabled === \"boolean\"\n ) {\n // Handle microphone toggle\n if (localParticipant.localParticipant) {\n localParticipant.localParticipant\n .setMicrophoneEnabled(data.enabled)\n .catch((error) => {\n console.error(\"Failed to toggle microphone:\", error);\n });\n } else {\n console.error(\"Local participant is not available for mic toggle\");\n }\n } else if (\n data.type === \"set_volume\" &&\n typeof data.volume === \"number\"\n ) {\n // Handle volume control\n if (agent) {\n // The agent is a RemoteParticipant, so we can call setVolume directly\n try {\n agent.setVolume(data.volume);\n console.log(`Set agent volume to ${data.volume}`);\n } catch (error) {\n console.error(\"Failed to set agent volume:\", error);\n }\n } else {\n console.error(\"Agent is not available for volume control\");\n }\n }\n };\n\n // Make sure we start the port\n port.start();\n\n port.addEventListener(\"message\", handleMessage);\n\n return () => {\n port.removeEventListener(\"message\", handleMessage);\n };\n }, [port, sendChat, localParticipant, agent]);\n\n // Send agent state updates\n useEffect(() => {\n if (port) {\n port.postMessage({ type: \"state_update\", state });\n }\n }, [state, port]);\n\n // Send agent transcriptions\n useEffect(() => {\n if (port && agentTranscription.segments.length > 0) {\n const transcriptions = agentTranscription.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"agent\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [agentTranscription.segments, port]);\n\n // Send user transcriptions\n useEffect(() => {\n if (port && localMessages.segments.length > 0) {\n const transcriptions = localMessages.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"user\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [localMessages.segments, port]);\n\n // Add data channel hook for function calls\n const { message: functionToolsExecuted } = useDataChannel(\n \"function_tools_executed\",\n (msg) => {\n if (!port) return;\n\n const textDecoder = new TextDecoder();\n const messageString =\n msg.payload instanceof Uint8Array\n ? textDecoder.decode(msg.payload)\n : String(msg.payload);\n\n let tool: FunctionToolsExecuted;\n try {\n tool = JSON.parse(messageString);\n\n // Send function calls to main hook via the port\n port.postMessage({\n type: \"function_tools_executed\",\n tool: tool,\n });\n } catch (e) {\n console.error(\"Failed to parse function call log:\", e);\n }\n }\n );\n\n return null;\n}\n","// export const HTTPS_API_ORIGIN = \"https://frontend-dev.tryvox.co/api/agent/sdk\";\nexport const HTTPS_API_ORIGIN = \"https://www.tryvox.co/api/agent/sdk\";\n// export const HTTPS_API_ORIGIN = \"http://localhost:3000/api/agent/sdk\";\nexport const SDK_VERSION = \"0.3.2\";\n"],"names":["useVoxAI","options","connectionDetail","setConnectionDetail","useState","state","setState","sessionTimestampRef","useRef","Date","now","transcriptMap","setTranscriptMap","Map","messages","setMessages","prevMessagesRef","processedMessageIdsRef","Set","portalRootRef","rootRef","channelRef","livekitComponentRef","waveformDataMap","setWaveformDataMap","agent","user","waveformConfigRef","isMicEnabled","setIsMicEnabled","useEffect","allMessages","Array","from","values","sort","a","b","timestamp","messagesString","JSON","stringify","current","onMessage","filter","msg","isFinal","id","has","forEach","add","channel","MessageChannel","port1","onmessage","e","data","type","handleTranscriptionUpdate","transcriptions","speaker","prevMap","waveformData","tool","functionCallsId","newMap","set","name","start","_channelRef$current","_channelRef$current2","close","port2","useCallback","t","_prevMap$get","messageType","existingTimestamp","get","message","text","div","document","createElement","style","display","body","appendChild","createRoot","unmount","removeChild","connect","_ref","agentId","apiKey","dynamicVariables","metadata","Promise","resolve","errorMessage","console","warn","onError","Error","reject","fetch","method","headers","Authorization","agent_id","runtime_context","source","version","call_web","dynamic_variables","then","response","_temp2","_result2","_exit","json","onConnect","_temp","ok","errorText","status","_catch","err","error","String","disconnect","onDisconnect","send","_ref2","digit","messageId","postMessage","undefined","audioWaveform","_ref3","barCount","updateInterval","config","speakerData","length","slice","fill","toggleMic","value","enabled","setVolume","volume","validVolume","Math","min","max","_jsxs","LiveKitRoom","serverUrl","token","participantToken","audio","video","onDisconnected","children","_jsx","RoomAudioRenderer","StateMonitor","port","initialConfig","render","_Fragment","_ref4","useVoiceAssistant","sendChat","useChat","waveformConfig","setWaveformConfig","agentAudioTrack","useParticipantTracks","Track","Source","Microphone","identity","agentTranscription","useTrackTranscription","agentAudioWaveform","useAudioWaveform","localParticipant","useLocalParticipant","localMessages","publication","microphoneTrack","participant","localAudioTrack","userAudioWaveform","bars","handleMessage","event","publishDtmf","setMicrophoneEnabled","catch","log","addEventListener","removeEventListener","segments","map","segment","final","useDataChannel","textDecoder","TextDecoder","messageString","payload","Uint8Array","decode","parse"],"mappings":"6cAqIgB,SAAAA,EAASC,YAAAA,IAAAA,EAAwB,CAAA,GAE/C,MAAOC,EAAkBC,GACvBC,EAAqC,OAChCC,EAAOC,GAAYF,EAAwB,gBAG5CG,EAAsBC,EAAeC,KAAKC,QAGzCC,EAAeC,GAAoBR,EACxC,IAAIS,MAECC,EAAUC,GAAeX,EAAuB,IACjDY,EAAkBR,EAAe,IAGjCS,EAAyBT,EAAoB,IAAIU,KAGjDC,EAAgBX,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M+H,EAAQ/H,KACdlC,QAASiK,EAAQC,MACjB1K,UAAW7B,KAAKC,MAChBkD,QAAS,UAGX4G,EAAKhC,YAAY,CACf/E,KAAM,uBACNE,kBAEJ,GACC,CAACmI,EAAce,SAAUrC,IAGeyC,EACzC,0BACCpK,IACC,IAAK2H,EAAM,OAEX,MAAM0C,EAAc,IAAIC,YAClBC,EACJvK,EAAIwK,mBAAmBC,WACnBJ,EAAYK,OAAO1K,EAAIwK,SACvBpF,OAAOpF,EAAIwK,SAEjB,IAAItJ,EACJ,IACEA,EAAOvB,KAAKgL,MAAMJ,GAGlB5C,EAAKhC,YAAY,CACf/E,KAAM,0BACNM,KAAMA,GAEV,CAAE,MAAOR,GACP6C,QAAQ4B,MAAM,qCAAsCzE,EACtD,IAKN,IAAA"}
package/dist/lib.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("@livekit/components-react"),require("livekit-client"),require("react"),require("react-dom/client")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","@livekit/components-react","livekit-client","react","react-dom/client"],t):t((e||self).react={},e.jsxRuntime,e.componentsReact,e.livekitClient,e.react,e.client)}(this,function(e,t,n,r,o,a){function s(e){let{port:t,initialConfig:a}=e;const{agent:s,state:i}=n.useVoiceAssistant(),{send:c}=n.useChat(),[u,l]=o.useState({speaker:a.speaker||"agent",barCount:a.barCount,updateInterval:a.updateInterval}),p=n.useParticipantTracks([r.Track.Source.Microphone],null==s?void 0:s.identity)[0],d=n.useTrackTranscription(p),f=n.useAudioWaveform(p,{barCount:"agent"===u.speaker?u.barCount:120,updateInterval:"agent"===u.speaker?u.updateInterval:20}),m=n.useLocalParticipant(),g=n.useTrackTranscription({publication:m.microphoneTrack,source:r.Track.Source.Microphone,participant:m.localParticipant}),v=n.useParticipantTracks([r.Track.Source.Microphone],m.localParticipant.identity)[0],y=n.useAudioWaveform(v,{barCount:"user"===u.speaker?u.barCount:120,updateInterval:"user"===u.speaker?u.updateInterval:20});return o.useEffect(()=>{t&&f&&f.bars&&t.postMessage({type:"waveform_update",waveformData:f.bars,speaker:"agent"})},[t,f]),o.useEffect(()=>{t&&y&&y.bars&&t.postMessage({type:"waveform_update",waveformData:y.bars,speaker:"user"})},[t,y]),o.useEffect(()=>{if(!t)return;const e=e=>{const t=e.data;if("waveform_config"===t.type&&t.config)"number"==typeof t.config.barCount&&"number"==typeof t.config.updateInterval&&l(t.config);else if("send_text"===t.type)c?c(t.text):console.error("sendChat function is not available");else if("send_dtmf"===t.type)m.localParticipant?m.localParticipant.publishDtmf(101,t.digit):console.error("Local participant is not available for DTMF");else if("toggle_mic"===t.type&&"boolean"==typeof t.enabled)m.localParticipant?m.localParticipant.setMicrophoneEnabled(t.enabled).catch(e=>{console.error("Failed to toggle microphone:",e)}):console.error("Local participant is not available for mic toggle");else if("set_volume"===t.type&&"number"==typeof t.volume)if(s)try{s.setVolume(t.volume),console.log("Set agent volume to "+t.volume)}catch(e){console.error("Failed to set agent volume:",e)}else console.error("Agent is not available for volume control")};return t.start(),t.addEventListener("message",e),()=>{t.removeEventListener("message",e)}},[t,c,m,s]),o.useEffect(()=>{t&&t.postMessage({type:"state_update",state:i})},[i,t]),o.useEffect(()=>{if(t&&d.segments.length>0){const e=d.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"agent"}));t.postMessage({type:"transcription_update",transcriptions:e})}},[d.segments,t]),o.useEffect(()=>{if(t&&g.segments.length>0){const e=g.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"user"}));t.postMessage({type:"transcription_update",transcriptions:e})}},[g.segments,t]),n.useDataChannel("function_tools_executed",e=>{if(!t)return;const n=new TextDecoder,r=e.payload instanceof Uint8Array?n.decode(e.payload):String(e.payload);let o;try{o=JSON.parse(r),t.postMessage({type:"function_tools_executed",tool:o})}catch(e){console.error("Failed to parse function call log:",e)}}),null}e.useVoxAI=function(e){void 0===e&&(e={});const[r,i]=o.useState(null),[c,u]=o.useState("disconnected"),l=o.useRef(Date.now()),[p,d]=o.useState(new Map),[f,m]=o.useState([]),g=o.useRef(""),v=o.useRef(new Set),y=o.useRef(null),b=o.useRef(null),h=o.useRef(null),k=o.useRef(null),[w,C]=o.useState({agent:[],user:[]}),M=o.useRef(null),[E,x]=o.useState(!0);o.useEffect(()=>{const t=Array.from(p.values()).sort((e,t)=>e.timestamp-t.timestamp),n=JSON.stringify(t);n!==g.current&&(g.current=n,m(t),e.onMessage&&t.filter(e=>e.isFinal&&e.id&&!v.current.has(e.id)).forEach(t=>{t.id&&(v.current.add(t.id),null==e.onMessage||e.onMessage(t))}))},[p,e.onMessage]),o.useEffect(()=>{const e=new MessageChannel;return e.port1.onmessage=e=>{const t=e.data;if("state_update"===t.type)u(t.state);else if("transcription_update"===t.type)_(t.transcriptions);else if("waveform_update"===t.type&&t.speaker)C(e=>({...e,[t.speaker]:t.waveformData}));else if("function_tools_executed"===t.type&&t.tool){const e="function-calls-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"tool",tool:t.tool,timestamp:Date.now(),isFinal:!0}),r})}},e.port1.start(),h.current=e,()=>{var e,t;null==(e=h.current)||e.port1.close(),null==(t=h.current)||t.port2.close(),h.current=null}},[]);const _=o.useCallback(e=>{d(t=>{const n=new Map(t);return e.forEach(e=>{var r;if(e.timestamp<l.current)return;const o="agent"===e.speaker?"agent":"user",a=(null==(r=t.get(e.id))?void 0:r.timestamp)||e.timestamp;n.set(e.id,{id:e.id,name:o,message:e.text,timestamp:a,isFinal:e.isFinal})}),n})},[]);o.useEffect(()=>{const e=document.createElement("div");return e.style.display="none",document.body.appendChild(e),y.current=e,b.current=a.createRoot(e),()=>{b.current&&b.current.unmount(),y.current&&document.body.removeChild(y.current)}},[]);const D=o.useCallback(function(t){let{agentId:n,apiKey:r,dynamicVariables:o,metadata:a}=t;try{return Promise.resolve(function(t,s){try{var p=function(){if("disconnected"!==c){const t="Connection attempt rejected: Already in a connection state ("+c+")";return console.warn(t),e.onError&&e.onError(new Error(t)),Promise.reject(new Error(t))}return l.current=Date.now(),u("connecting"),Promise.resolve(fetch("https://www.tryvox.co/api/agent/sdk",{method:"POST",headers:{Authorization:"Bearer "+r,"Content-Type":"application/json"},body:JSON.stringify({agent_id:n,metadata:{runtime_context:{source:{type:"react-sdk",version:"0.3.0"}},call_web:{dynamic_variables:o||{},metadata:a||{}}}})})).then(function(t){function n(n){return Promise.resolve(t.json()).then(function(t){i(t),e.onConnect&&e.onConnect()})}const r=function(){if(!t.ok)return Promise.resolve(t.text()).then(function(e){throw new Error("Connection failed ("+t.status+"): "+e)})}();return r&&r.then?r.then(n):n()})}()}catch(e){return s(e)}return p&&p.then?p.then(void 0,s):p}(0,function(t){i(null),d(new Map),m([]),u("disconnected");const n=t instanceof Error?t:new Error(String(t));e.onError&&e.onError(n)}))}catch(e){return Promise.reject(e)}},[e,c]),S=o.useCallback(()=>{l.current=Date.now(),i(null),d(new Map),m([]),u("disconnected"),e.onDisconnect&&e.onDisconnect()},[e]),T=o.useCallback(e=>{let{message:t,digit:n}=e;if("disconnected"!==c){if(t){const e="user-text-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"user",message:t,timestamp:Date.now(),isFinal:!0}),r}),h.current?h.current.port1.postMessage({type:"send_text",text:t}):console.error("No message channel available to send message")}void 0!==n&&(h.current?h.current.port1.postMessage({type:"send_dtmf",digit:n}):console.error("No message channel available to send DTMF"))}else console.warn("Cannot send message: Not connected to a conversation")},[c]),P=o.useCallback(e=>{let{speaker:t="agent",barCount:n=10,updateInterval:r=20}=e;M.current={speaker:t,barCount:n,updateInterval:r},h.current&&h.current.port1.postMessage({type:"waveform_config",config:{speaker:t,barCount:n,updateInterval:r}});const o=w[t]||[];return o.length>0?o.slice(0,n):Array(n).fill(0)},[w]),R=o.useCallback(e=>{x(e),h.current?h.current.port1.postMessage({type:"toggle_mic",enabled:e}):console.error("No message channel available to toggle microphone")},[]),j=o.useCallback(e=>{const t=Math.min(Math.max(e,0),1);h.current?h.current.port1.postMessage({type:"set_volume",volume:t}):console.error("No message channel available to set volume")},[]);return o.useEffect(()=>{b.current&&(r?(k.current||(h.current&&h.current.port2.start(),k.current=t.jsxs(n.LiveKitRoom,{serverUrl:r.serverUrl,token:r.participantToken,audio:!0,video:!1,connect:!0,onDisconnected:S,onError:t=>{console.error("LiveKit connection error:",t),S(),e.onError&&e.onError(new Error("LiveKit connection error: "+t.message))},children:[t.jsx(n.RoomAudioRenderer,{}),h.current&&t.jsx(s,{port:h.current.port2,initialConfig:M.current||{barCount:10,updateInterval:20}})]})),b.current.render(k.current)):(k.current=null,b.current.render(t.jsx(t.Fragment,{}))))},[r,S,e.onError]),{connect:D,disconnect:S,state:c,messages:f,send:T,audioWaveform:P,toggleMic:R,setVolume:j}}});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("@livekit/components-react"),require("livekit-client"),require("react"),require("react-dom/client")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","@livekit/components-react","livekit-client","react","react-dom/client"],t):t((e||self).react={},e.jsxRuntime,e.componentsReact,e.livekitClient,e.react,e.client)}(this,function(e,t,n,r,o,a){function s(e){let{port:t,initialConfig:a}=e;const{agent:s,state:i}=n.useVoiceAssistant(),{send:c}=n.useChat(),[u,l]=o.useState({speaker:a.speaker||"agent",barCount:a.barCount,updateInterval:a.updateInterval}),p=n.useParticipantTracks([r.Track.Source.Microphone],null==s?void 0:s.identity)[0],d=n.useTrackTranscription(p),f=n.useAudioWaveform(p,{barCount:"agent"===u.speaker?u.barCount:120,updateInterval:"agent"===u.speaker?u.updateInterval:20}),m=n.useLocalParticipant(),g=n.useTrackTranscription({publication:m.microphoneTrack,source:r.Track.Source.Microphone,participant:m.localParticipant}),v=n.useParticipantTracks([r.Track.Source.Microphone],m.localParticipant.identity)[0],y=n.useAudioWaveform(v,{barCount:"user"===u.speaker?u.barCount:120,updateInterval:"user"===u.speaker?u.updateInterval:20});return o.useEffect(()=>{t&&f&&f.bars&&t.postMessage({type:"waveform_update",waveformData:f.bars,speaker:"agent"})},[t,f]),o.useEffect(()=>{t&&y&&y.bars&&t.postMessage({type:"waveform_update",waveformData:y.bars,speaker:"user"})},[t,y]),o.useEffect(()=>{if(!t)return;const e=e=>{const t=e.data;if("waveform_config"===t.type&&t.config)"number"==typeof t.config.barCount&&"number"==typeof t.config.updateInterval&&l(t.config);else if("send_text"===t.type)c?c(t.text):console.error("sendChat function is not available");else if("send_dtmf"===t.type)m.localParticipant?m.localParticipant.publishDtmf(101,t.digit):console.error("Local participant is not available for DTMF");else if("toggle_mic"===t.type&&"boolean"==typeof t.enabled)m.localParticipant?m.localParticipant.setMicrophoneEnabled(t.enabled).catch(e=>{console.error("Failed to toggle microphone:",e)}):console.error("Local participant is not available for mic toggle");else if("set_volume"===t.type&&"number"==typeof t.volume)if(s)try{s.setVolume(t.volume),console.log("Set agent volume to "+t.volume)}catch(e){console.error("Failed to set agent volume:",e)}else console.error("Agent is not available for volume control")};return t.start(),t.addEventListener("message",e),()=>{t.removeEventListener("message",e)}},[t,c,m,s]),o.useEffect(()=>{t&&t.postMessage({type:"state_update",state:i})},[i,t]),o.useEffect(()=>{if(t&&d.segments.length>0){const e=d.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"agent"}));t.postMessage({type:"transcription_update",transcriptions:e})}},[d.segments,t]),o.useEffect(()=>{if(t&&g.segments.length>0){const e=g.segments.map(e=>({id:e.id,text:e.text,isFinal:e.final,timestamp:Date.now(),speaker:"user"}));t.postMessage({type:"transcription_update",transcriptions:e})}},[g.segments,t]),n.useDataChannel("function_tools_executed",e=>{if(!t)return;const n=new TextDecoder,r=e.payload instanceof Uint8Array?n.decode(e.payload):String(e.payload);let o;try{o=JSON.parse(r),t.postMessage({type:"function_tools_executed",tool:o})}catch(e){console.error("Failed to parse function call log:",e)}}),null}e.useVoxAI=function(e){void 0===e&&(e={});const[r,i]=o.useState(null),[c,u]=o.useState("disconnected"),l=o.useRef(Date.now()),[p,d]=o.useState(new Map),[f,m]=o.useState([]),g=o.useRef(""),v=o.useRef(new Set),y=o.useRef(null),b=o.useRef(null),h=o.useRef(null),k=o.useRef(null),[w,C]=o.useState({agent:[],user:[]}),M=o.useRef(null),[E,x]=o.useState(!0);o.useEffect(()=>{const t=Array.from(p.values()).sort((e,t)=>e.timestamp-t.timestamp),n=JSON.stringify(t);n!==g.current&&(g.current=n,m(t),e.onMessage&&t.filter(e=>e.isFinal&&e.id&&!v.current.has(e.id)).forEach(t=>{t.id&&(v.current.add(t.id),null==e.onMessage||e.onMessage(t))}))},[p,e.onMessage]),o.useEffect(()=>{const e=new MessageChannel;return e.port1.onmessage=e=>{const t=e.data;if("state_update"===t.type)u(t.state);else if("transcription_update"===t.type)_(t.transcriptions);else if("waveform_update"===t.type&&t.speaker)C(e=>({...e,[t.speaker]:t.waveformData}));else if("function_tools_executed"===t.type&&t.tool){const e="function-calls-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"tool",tool:t.tool,timestamp:Date.now(),isFinal:!0}),r})}},e.port1.start(),h.current=e,()=>{var e,t;null==(e=h.current)||e.port1.close(),null==(t=h.current)||t.port2.close(),h.current=null}},[]);const _=o.useCallback(e=>{d(t=>{const n=new Map(t);return e.forEach(e=>{var r;if(e.timestamp<l.current)return;const o="agent"===e.speaker?"agent":"user",a=(null==(r=t.get(e.id))?void 0:r.timestamp)||e.timestamp;n.set(e.id,{id:e.id,name:o,message:e.text,timestamp:a,isFinal:e.isFinal})}),n})},[]);o.useEffect(()=>{const e=document.createElement("div");return e.style.display="none",document.body.appendChild(e),y.current=e,b.current=a.createRoot(e),()=>{b.current&&b.current.unmount(),y.current&&document.body.removeChild(y.current)}},[]);const D=o.useCallback(function(t){let{agentId:n,apiKey:r,dynamicVariables:o,metadata:a}=t;try{return Promise.resolve(function(t,s){try{var p=function(){if("disconnected"!==c){const t="Connection attempt rejected: Already in a connection state ("+c+")";return console.warn(t),e.onError&&e.onError(new Error(t)),Promise.reject(new Error(t))}return l.current=Date.now(),u("connecting"),Promise.resolve(fetch("https://www.tryvox.co/api/agent/sdk",{method:"POST",headers:{Authorization:"Bearer "+r,"Content-Type":"application/json"},body:JSON.stringify({agent_id:n,metadata:{runtime_context:{source:{type:"react-sdk",version:"0.3.2"}},call_web:{dynamic_variables:o||{},metadata:a||{}}}})})).then(function(t){function n(n){return Promise.resolve(t.json()).then(function(t){i(t),e.onConnect&&e.onConnect()})}const r=function(){if(!t.ok)return Promise.resolve(t.text()).then(function(e){throw new Error("Connection failed ("+t.status+"): "+e)})}();return r&&r.then?r.then(n):n()})}()}catch(e){return s(e)}return p&&p.then?p.then(void 0,s):p}(0,function(t){i(null),d(new Map),m([]),u("disconnected");const n=t instanceof Error?t:new Error(String(t));e.onError&&e.onError(n)}))}catch(e){return Promise.reject(e)}},[e,c]),S=o.useCallback(()=>{l.current=Date.now(),i(null),d(new Map),m([]),u("disconnected"),e.onDisconnect&&e.onDisconnect()},[e]),T=o.useCallback(e=>{let{message:t,digit:n}=e;if("disconnected"!==c){if(t){const e="user-text-"+Date.now();d(n=>{const r=new Map(n);return r.set(e,{id:e,name:"user",message:t,timestamp:Date.now(),isFinal:!0}),r}),h.current?h.current.port1.postMessage({type:"send_text",text:t}):console.error("No message channel available to send message")}void 0!==n&&(h.current?h.current.port1.postMessage({type:"send_dtmf",digit:n}):console.error("No message channel available to send DTMF"))}else console.warn("Cannot send message: Not connected to a conversation")},[c]),P=o.useCallback(e=>{let{speaker:t="agent",barCount:n=10,updateInterval:r=20}=e;M.current={speaker:t,barCount:n,updateInterval:r},h.current&&h.current.port1.postMessage({type:"waveform_config",config:{speaker:t,barCount:n,updateInterval:r}});const o=w[t]||[];return o.length>0?o.slice(0,n):Array(n).fill(0)},[w]),R=o.useCallback(e=>{x(e),h.current?h.current.port1.postMessage({type:"toggle_mic",enabled:e}):console.error("No message channel available to toggle microphone")},[]),j=o.useCallback(e=>{const t=Math.min(Math.max(e,0),1);h.current?h.current.port1.postMessage({type:"set_volume",volume:t}):console.error("No message channel available to set volume")},[]);return o.useEffect(()=>{b.current&&(r?(k.current||(h.current&&h.current.port2.start(),k.current=t.jsxs(n.LiveKitRoom,{serverUrl:r.serverUrl,token:r.participantToken,audio:!0,video:!1,connect:!0,onDisconnected:S,onError:t=>{console.error("LiveKit connection error:",t),S(),e.onError&&e.onError(new Error("LiveKit connection error: "+t.message))},children:[t.jsx(n.RoomAudioRenderer,{}),h.current&&t.jsx(s,{port:h.current.port2,initialConfig:M.current||{barCount:10,updateInterval:20}})]})),b.current.render(k.current)):(k.current=null,b.current.render(t.jsx(t.Fragment,{}))))},[r,S,e.onError]),{connect:D,disconnect:S,state:c,messages:f,send:T,audioWaveform:P,toggleMic:R,setVolume:j}}});
2
2
  //# sourceMappingURL=lib.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"lib.umd.js","sources":["../src/hooks/useVoxAI.tsx","../src/utils/constants.ts"],"sourcesContent":["import {\n LiveKitRoom,\n RoomAudioRenderer,\n useAudioWaveform,\n useChat,\n useDataChannel,\n useLocalParticipant,\n useParticipantTracks,\n useTrackTranscription,\n useVoiceAssistant,\n} from \"@livekit/components-react\";\nimport { Track } from \"livekit-client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport { HTTPS_API_ORIGIN, SDK_VERSION } from \"../utils/constants\";\n\ntype VoxConnectionDetail = {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n};\n\n/**\n * VoxAgentState\n * @description The state of the agent\n */\nexport type VoxAgentState =\n | \"disconnected\"\n | \"connecting\"\n | \"initializing\"\n | \"listening\"\n | \"thinking\"\n | \"speaking\";\n\n/**\n * Function call related types\n */\nexport interface FunctionToolsExecuted {\n type: \"function_tools_executed\";\n function_calls: FunctionCallInfo[];\n function_call_outputs: FunctionCallResult[];\n}\n\nexport interface FunctionCallInfo {\n id: string;\n type: string;\n call_id: string;\n arguments: string;\n name: string;\n}\n\nexport interface FunctionCallResult {\n id: string;\n name: string;\n type: string;\n call_id: string;\n output: string;\n is_error: boolean;\n}\n\n/**\n * VoxMessage\n * @description The message type between the agent and the user\n */\nexport type VoxMessage = {\n id?: string;\n name: \"agent\" | \"user\" | \"tool\";\n message?: string;\n timestamp: number;\n isFinal?: boolean;\n tool?: FunctionToolsExecuted;\n};\n\n/**\n * VoxAIOptions\n * @description The callback functions for the useVoxAI hook\n */\nexport interface VoxAIOptions {\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onMessage?: (message: VoxMessage) => void;\n}\n\n// Message channel event types\ntype MessageChannelEvent =\n | { type: \"state_update\"; state: VoxAgentState }\n | { type: \"transcription_update\"; transcriptions: TranscriptionSegment[] }\n | {\n type: \"waveform_update\";\n waveformData: number[];\n speaker: \"agent\" | \"user\";\n }\n | { type: \"function_tools_executed\"; tool: FunctionToolsExecuted };\n\ntype TranscriptionSegment = {\n id: string;\n text: string;\n isFinal: boolean;\n timestamp: number;\n speaker: \"agent\" | \"user\";\n};\n\n/**\n * ConnectParams\n * @param agentId - The agent ID\n * @param apiKey - The API key\n * @param dynamicVariables - The dynamic variables\n * @param metadata - 이 메타데이터는 아웃바운드 웹훅, 통화 기록에 포함됩니다.\n */\nexport interface ConnectParams {\n agentId: string;\n apiKey: string;\n dynamicVariables?: Record<string, any>;\n metadata?: Record<string, any>;\n}\n\n/**\n * useVoxAI\n * @description The hook for integrating with vox.ai voice assistant\n * @param options - The options for the useVoxAI hook\n * @returns The useVoxAI hook\n * @example\n * const { connect, disconnect, state, messages, send } = useVoxAI({\n * onConnect: () => console.log(\"Connected\"),\n * onDisconnect: () => console.log(\"Disconnected\"),\n * onError: (error) => console.error(\"Error:\", error),\n * onMessage: (message) => console.log(\"Message:\", message),\n * });\n */\nexport function useVoxAI(options: VoxAIOptions = {}) {\n // Connection state\n const [connectionDetail, setConnectionDetail] =\n useState<VoxConnectionDetail | null>(null);\n const [state, setState] = useState<VoxAgentState>(\"disconnected\");\n\n // Session timestamp to filter out stale asynchronous events\n const sessionTimestampRef = useRef<number>(Date.now());\n\n // Message handling\n const [transcriptMap, setTranscriptMap] = useState<Map<string, VoxMessage>>(\n new Map()\n );\n const [messages, setMessages] = useState<VoxMessage[]>([]);\n const prevMessagesRef = useRef<string>(\"\");\n\n // Track which messages we've already sent to the onMessage callback\n const processedMessageIdsRef = useRef<Set<string>>(new Set());\n\n // DOM manipulation for LiveKit portal\n const portalRootRef = useRef<HTMLDivElement | null>(null);\n const rootRef = useRef<Root | null>(null);\n\n // Communication channel\n const channelRef = useRef<MessageChannel | null>(null);\n\n // Add this near the start of your useVoxAI hook\n const livekitComponentRef = useRef<React.ReactNode>(null);\n\n // Replace the single waveform state with a map for multiple speakers\n const [waveformDataMap, setWaveformDataMap] = useState<\n Record<string, number[]>\n >({\n agent: [],\n user: [],\n });\n\n // Add back the waveform config reference\n const waveformConfigRef = useRef<{\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n } | null>(null);\n\n // Add a new state to track microphone status\n const [isMicEnabled, setIsMicEnabled] = useState<boolean>(true);\n\n // Update messages whenever transcriptMap changes\n useEffect(() => {\n const allMessages = Array.from(transcriptMap.values()).sort(\n (a, b) => a.timestamp - b.timestamp\n );\n\n // Only update if the messages have actually changed\n const messagesString = JSON.stringify(allMessages);\n if (messagesString !== prevMessagesRef.current) {\n prevMessagesRef.current = messagesString;\n setMessages(allMessages);\n\n // Only trigger onMessage for new final messages that haven't been processed yet\n if (options.onMessage) {\n allMessages\n .filter(\n (msg) =>\n msg.isFinal &&\n msg.id &&\n !processedMessageIdsRef.current.has(msg.id)\n )\n .forEach((msg) => {\n if (msg.id) {\n // Mark this message as processed\n processedMessageIdsRef.current.add(msg.id);\n // Call the callback\n options.onMessage?.(msg);\n }\n });\n }\n }\n }, [transcriptMap, options.onMessage]);\n\n // Initialize message channel - ensure ports are properly connected\n useEffect(() => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (e) => {\n const data = e.data as MessageChannelEvent;\n\n if (data.type === \"state_update\") {\n setState(data.state);\n } else if (data.type === \"transcription_update\") {\n handleTranscriptionUpdate(data.transcriptions);\n } else if (data.type === \"waveform_update\" && data.speaker) {\n // Store the waveform data for the specific speaker\n setWaveformDataMap((prevMap) => ({\n ...prevMap,\n [data.speaker]: data.waveformData,\n }));\n } else if (data.type === \"function_tools_executed\" && data.tool) {\n // Handle function calls\n const functionCallsId = `function-calls-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(functionCallsId, {\n id: functionCallsId,\n name: \"tool\",\n tool: data.tool,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n }\n };\n\n // Start the port\n channel.port1.start();\n\n // Store the channel reference\n channelRef.current = channel;\n\n return () => {\n channelRef.current?.port1.close();\n channelRef.current?.port2.close();\n channelRef.current = null;\n };\n }, []);\n\n // Process incoming transcriptions and filter out stale events\n const handleTranscriptionUpdate = useCallback(\n (transcriptions: TranscriptionSegment[]) => {\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n\n transcriptions.forEach((t) => {\n // Only process transcriptions generated after the current session timestamp\n if (t.timestamp < sessionTimestampRef.current) {\n return;\n }\n const messageType = t.speaker === \"agent\" ? \"agent\" : \"user\";\n // Use existing timestamp if we already have this segment\n const existingTimestamp = prevMap.get(t.id)?.timestamp || t.timestamp;\n\n newMap.set(t.id, {\n id: t.id,\n name: messageType,\n message: t.text,\n timestamp: existingTimestamp,\n isFinal: t.isFinal,\n });\n });\n\n return newMap;\n });\n },\n []\n );\n\n // Set up DOM portal for LiveKit\n useEffect(() => {\n const div = document.createElement(\"div\");\n div.style.display = \"none\";\n document.body.appendChild(div);\n portalRootRef.current = div;\n rootRef.current = createRoot(div);\n\n return () => {\n if (rootRef.current) {\n rootRef.current.unmount();\n }\n if (portalRootRef.current) {\n document.body.removeChild(portalRootRef.current);\n }\n };\n }, []);\n\n // Connect to VoxAI service - updated to include dynamicVariables\n const connect = useCallback(\n async ({ agentId, apiKey, dynamicVariables, metadata }: ConnectParams) => {\n try {\n // Prevent connecting if already in a connection state\n if (state !== \"disconnected\") {\n const errorMessage = `Connection attempt rejected: Already in a connection state (${state})`;\n console.warn(errorMessage);\n\n if (options.onError) {\n options.onError(new Error(errorMessage));\n }\n return Promise.reject(new Error(errorMessage));\n }\n\n // Update session timestamp for new connection\n sessionTimestampRef.current = Date.now();\n setState(\"connecting\");\n\n const response = await fetch(HTTPS_API_ORIGIN, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agent_id: agentId,\n metadata: {\n runtime_context: {\n source: {\n type: \"react-sdk\",\n version: SDK_VERSION,\n },\n },\n call_web: {\n dynamic_variables: dynamicVariables || {},\n metadata: metadata || {},\n },\n },\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Connection failed (${response.status}): ${errorText}`\n );\n }\n\n const data = await response.json();\n setConnectionDetail(data);\n\n if (options.onConnect) {\n options.onConnect();\n }\n } catch (err) {\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n if (options.onError) {\n options.onError(error);\n }\n }\n },\n [options, state]\n );\n\n // Disconnect from VoxAI service, updating the session timestamp to ignore stale events\n const disconnect = useCallback(() => {\n // Update session timestamp on disconnect\n sessionTimestampRef.current = Date.now();\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n if (options.onDisconnect) {\n options.onDisconnect();\n }\n }, [options]);\n\n // Update the send function with debugging and error checking\n const send = useCallback(\n ({ message, digit }: { message?: string; digit?: number }) => {\n if (state === \"disconnected\") {\n console.warn(\"Cannot send message: Not connected to a conversation\");\n return;\n }\n\n if (message) {\n const messageId = `user-text-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(messageId, {\n id: messageId,\n name: \"user\",\n message: message,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_text\",\n text: message,\n });\n } else {\n console.error(\"No message channel available to send message\");\n }\n }\n\n if (digit !== undefined) {\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_dtmf\",\n digit: digit,\n });\n } else {\n console.error(\"No message channel available to send DTMF\");\n }\n }\n },\n [state]\n );\n\n // Update the audioWaveform function to return data for the requested speaker\n const audioWaveform = useCallback(\n ({\n speaker = \"agent\",\n barCount = 10,\n updateInterval = 20,\n }: {\n speaker?: \"agent\" | \"user\";\n barCount?: number;\n updateInterval?: number;\n }): number[] => {\n waveformConfigRef.current = { speaker, barCount, updateInterval };\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"waveform_config\",\n config: { speaker, barCount, updateInterval },\n });\n }\n\n const speakerData = waveformDataMap[speaker] || [];\n return speakerData.length > 0\n ? speakerData.slice(0, barCount)\n : Array(barCount).fill(0);\n },\n [waveformDataMap]\n );\n\n // Add toggleMic function that will be exposed in the hook's return value\n const toggleMic = useCallback((value: boolean) => {\n setIsMicEnabled(value);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"toggle_mic\",\n enabled: value,\n });\n } else {\n console.error(\"No message channel available to toggle microphone\");\n }\n }, []);\n\n // Add setVolume function that will be exposed in the hook's return value\n const setVolume = useCallback((volume: number) => {\n const validVolume = Math.min(Math.max(volume, 0), 1);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"set_volume\",\n volume: validVolume,\n });\n } else {\n console.error(\"No message channel available to set volume\");\n }\n }, []);\n\n // Modify the useEffect hook that renders the LiveKit component\n useEffect(() => {\n if (!rootRef.current) return;\n\n if (connectionDetail) {\n if (!livekitComponentRef.current) {\n if (channelRef.current) {\n channelRef.current.port2.start();\n }\n\n livekitComponentRef.current = (\n <LiveKitRoom\n serverUrl={connectionDetail.serverUrl}\n token={connectionDetail.participantToken}\n audio={true}\n video={false}\n connect={true}\n onDisconnected={disconnect}\n onError={(error) => {\n console.error(\"LiveKit connection error:\", error);\n disconnect();\n if (options.onError) {\n options.onError(\n new Error(`LiveKit connection error: ${error.message}`)\n );\n }\n }}\n >\n <RoomAudioRenderer />\n {channelRef.current && (\n <StateMonitor\n port={channelRef.current.port2}\n initialConfig={\n waveformConfigRef.current || {\n barCount: 10,\n updateInterval: 20,\n }\n }\n />\n )}\n </LiveKitRoom>\n );\n }\n rootRef.current.render(livekitComponentRef.current);\n } else {\n livekitComponentRef.current = null;\n rootRef.current.render(<></>);\n }\n }, [connectionDetail, disconnect, options.onError]);\n\n return {\n connect,\n disconnect,\n state,\n messages,\n send,\n audioWaveform,\n toggleMic,\n setVolume,\n };\n}\n\n/**\n * Component that monitors LiveKit state and communicates back to the main hook\n */\nfunction StateMonitor({\n port,\n initialConfig,\n}: {\n port: MessagePort | undefined;\n initialConfig: {\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n };\n}) {\n const { agent, state } = useVoiceAssistant();\n const { send: sendChat } = useChat();\n\n // Initialize waveform config with the passed initial values, defaulting to \"agent\" if not specified\n const [waveformConfig, setWaveformConfig] = useState({\n speaker: initialConfig.speaker || \"agent\",\n barCount: initialConfig.barCount,\n updateInterval: initialConfig.updateInterval,\n });\n\n // Agent transcriptions\n const agentAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n agent?.identity\n )[0];\n const agentTranscription = useTrackTranscription(agentAudioTrack);\n\n // Use the current config for the waveform, applying different settings based on speaker\n const agentAudioWaveform = useAudioWaveform(agentAudioTrack, {\n barCount:\n waveformConfig.speaker === \"agent\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"agent\" ? waveformConfig.updateInterval : 20,\n });\n\n // User transcriptions\n const localParticipant = useLocalParticipant();\n const localMessages = useTrackTranscription({\n publication: localParticipant.microphoneTrack,\n source: Track.Source.Microphone,\n participant: localParticipant.localParticipant,\n });\n const localAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n localParticipant.localParticipant.identity\n )[0];\n const userAudioWaveform = useAudioWaveform(localAudioTrack, {\n barCount: waveformConfig.speaker === \"user\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"user\" ? waveformConfig.updateInterval : 20,\n });\n\n // Add separate effects to send agent and user waveform data\n useEffect(() => {\n if (!port || !agentAudioWaveform || !agentAudioWaveform.bars) return;\n\n // Send the agent waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: agentAudioWaveform.bars,\n speaker: \"agent\",\n });\n }, [port, agentAudioWaveform]);\n\n useEffect(() => {\n if (!port || !userAudioWaveform || !userAudioWaveform.bars) return;\n\n // Send the user waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: userAudioWaveform.bars,\n speaker: \"user\",\n });\n }, [port, userAudioWaveform]);\n\n // Listen for messages including config updates and mic toggle commands\n useEffect(() => {\n if (!port) return;\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n\n if (data.type === \"waveform_config\" && data.config) {\n // Verify we have both required properties before updating\n if (\n typeof data.config.barCount === \"number\" &&\n typeof data.config.updateInterval === \"number\"\n ) {\n setWaveformConfig(data.config);\n }\n } else if (data.type === \"send_text\") {\n if (sendChat) {\n sendChat(data.text);\n } else {\n console.error(\"sendChat function is not available\");\n }\n } else if (data.type === \"send_dtmf\") {\n if (localParticipant.localParticipant) {\n // Use standard DTMF code (RFC 4733)\n const standardDtmfCode = 101; // Standard DTMF payload type\n localParticipant.localParticipant.publishDtmf(\n standardDtmfCode,\n data.digit\n );\n } else {\n console.error(\"Local participant is not available for DTMF\");\n }\n } else if (\n data.type === \"toggle_mic\" &&\n typeof data.enabled === \"boolean\"\n ) {\n // Handle microphone toggle\n if (localParticipant.localParticipant) {\n localParticipant.localParticipant\n .setMicrophoneEnabled(data.enabled)\n .catch((error) => {\n console.error(\"Failed to toggle microphone:\", error);\n });\n } else {\n console.error(\"Local participant is not available for mic toggle\");\n }\n } else if (\n data.type === \"set_volume\" &&\n typeof data.volume === \"number\"\n ) {\n // Handle volume control\n if (agent) {\n // The agent is a RemoteParticipant, so we can call setVolume directly\n try {\n agent.setVolume(data.volume);\n console.log(`Set agent volume to ${data.volume}`);\n } catch (error) {\n console.error(\"Failed to set agent volume:\", error);\n }\n } else {\n console.error(\"Agent is not available for volume control\");\n }\n }\n };\n\n // Make sure we start the port\n port.start();\n\n port.addEventListener(\"message\", handleMessage);\n\n return () => {\n port.removeEventListener(\"message\", handleMessage);\n };\n }, [port, sendChat, localParticipant, agent]);\n\n // Send agent state updates\n useEffect(() => {\n if (port) {\n port.postMessage({ type: \"state_update\", state });\n }\n }, [state, port]);\n\n // Send agent transcriptions\n useEffect(() => {\n if (port && agentTranscription.segments.length > 0) {\n const transcriptions = agentTranscription.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"agent\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [agentTranscription.segments, port]);\n\n // Send user transcriptions\n useEffect(() => {\n if (port && localMessages.segments.length > 0) {\n const transcriptions = localMessages.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"user\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [localMessages.segments, port]);\n\n // Add data channel hook for function calls\n const { message: functionToolsExecuted } = useDataChannel(\n \"function_tools_executed\",\n (msg) => {\n if (!port) return;\n\n const textDecoder = new TextDecoder();\n const messageString =\n msg.payload instanceof Uint8Array\n ? textDecoder.decode(msg.payload)\n : String(msg.payload);\n\n let tool: FunctionToolsExecuted;\n try {\n tool = JSON.parse(messageString);\n\n // Send function calls to main hook via the port\n port.postMessage({\n type: \"function_tools_executed\",\n tool: tool,\n });\n } catch (e) {\n console.error(\"Failed to parse function call log:\", e);\n }\n }\n );\n\n return null;\n}\n","// export const HTTPS_API_ORIGIN = \"https://frontend-dev.tryvox.co/api/agent/sdk\";\nexport const HTTPS_API_ORIGIN = \"https://www.tryvox.co/api/agent/sdk\";\n// export const HTTPS_API_ORIGIN = \"http://localhost:3000/api/agent/sdk\";\nexport const SDK_VERSION = \"0.3.0\";\n"],"names":["StateMonitor","_ref4","port","initialConfig","agent","state","useVoiceAssistant","send","sendChat","useChat","waveformConfig","setWaveformConfig","useState","speaker","barCount","updateInterval","agentAudioTrack","useParticipantTracks","Track","Source","Microphone","identity","agentTranscription","useTrackTranscription","agentAudioWaveform","useAudioWaveform","localParticipant","useLocalParticipant","localMessages","publication","microphoneTrack","source","participant","localAudioTrack","userAudioWaveform","useEffect","bars","postMessage","type","waveformData","handleMessage","event","data","config","text","console","error","publishDtmf","digit","enabled","setMicrophoneEnabled","catch","volume","setVolume","log","start","addEventListener","removeEventListener","segments","length","transcriptions","map","segment","id","isFinal","final","timestamp","Date","now","useDataChannel","msg","textDecoder","TextDecoder","messageString","payload","Uint8Array","decode","String","tool","JSON","parse","e","options","connectionDetail","setConnectionDetail","setState","sessionTimestampRef","useRef","transcriptMap","setTranscriptMap","Map","messages","setMessages","prevMessagesRef","processedMessageIdsRef","Set","portalRootRef","rootRef","channelRef","livekitComponentRef","waveformDataMap","setWaveformDataMap","user","waveformConfigRef","isMicEnabled","setIsMicEnabled","allMessages","Array","from","values","sort","a","b","messagesString","stringify","current","onMessage","filter","has","forEach","add","channel","MessageChannel","port1","onmessage","handleTranscriptionUpdate","prevMap","functionCallsId","newMap","set","name","_channelRef$current","_channelRef$current2","close","port2","useCallback","t","_prevMap$get","messageType","existingTimestamp","get","message","div","document","createElement","style","display","body","appendChild","createRoot","unmount","removeChild","connect","_ref","agentId","apiKey","dynamicVariables","metadata","Promise","resolve","errorMessage","warn","onError","Error","reject","fetch","method","headers","Authorization","agent_id","runtime_context","version","call_web","dynamic_variables","then","response","_temp2","_result2","_exit","json","onConnect","_temp","ok","errorText","status","_catch","err","disconnect","onDisconnect","_ref2","messageId","undefined","audioWaveform","_ref3","speakerData","slice","fill","toggleMic","value","validVolume","Math","min","max","_jsxs","LiveKitRoom","serverUrl","token","participantToken","audio","video","onDisconnected","children","_jsx","RoomAudioRenderer","render","_Fragment"],"mappings":"8gBA4iBA,SAASA,EAAYC,GAAC,IAAAC,KACpBA,EAAIC,cACJA,GAQDF,EACC,MAAMG,MAAEA,EAAKC,MAAEA,GAAUC,EAAAA,qBACjBC,KAAMC,GAAaC,EAAOA,WAG3BC,EAAgBC,GAAqBC,WAAS,CACnDC,QAASV,EAAcU,SAAW,QAClCC,SAAUX,EAAcW,SACxBC,eAAgBZ,EAAcY,iBAI1BC,EAAkBC,uBACtB,CAACC,EAAKA,MAACC,OAAOC,YACT,MAALhB,OAAK,EAALA,EAAOiB,UACP,GACIC,EAAqBC,EAAqBA,sBAACP,GAG3CQ,EAAqBC,EAAgBA,iBAACT,EAAiB,CAC3DF,SAC6B,UAA3BJ,EAAeG,QAAsBH,EAAeI,SAAW,IACjEC,eAC6B,UAA3BL,EAAeG,QAAsBH,EAAeK,eAAiB,KAInEW,EAAmBC,wBACnBC,EAAgBL,EAAqBA,sBAAC,CAC1CM,YAAaH,EAAiBI,gBAC9BC,OAAQb,EAAKA,MAACC,OAAOC,WACrBY,YAAaN,EAAiBA,mBAE1BO,EAAkBhB,EAAoBA,qBAC1C,CAACC,EAAKA,MAACC,OAAOC,YACdM,EAAiBA,iBAAiBL,UAClC,GACIa,EAAoBT,EAAAA,iBAAiBQ,EAAiB,CAC1DnB,SAAqC,SAA3BJ,EAAeG,QAAqBH,EAAeI,SAAW,IACxEC,eAC6B,SAA3BL,EAAeG,QAAqBH,EAAeK,eAAiB,KA2KxE,OAvKAoB,EAAAA,UAAU,KACHjC,GAASsB,GAAuBA,EAA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"}
1
+ {"version":3,"file":"lib.umd.js","sources":["../src/hooks/useVoxAI.tsx","../src/utils/constants.ts"],"sourcesContent":["import {\n LiveKitRoom,\n RoomAudioRenderer,\n useAudioWaveform,\n useChat,\n useDataChannel,\n useLocalParticipant,\n useParticipantTracks,\n useTrackTranscription,\n useVoiceAssistant,\n} from \"@livekit/components-react\";\nimport { Track } from \"livekit-client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport { HTTPS_API_ORIGIN, SDK_VERSION } from \"../utils/constants\";\n\ntype VoxConnectionDetail = {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n};\n\n/**\n * VoxAgentState\n * @description The state of the agent\n */\nexport type VoxAgentState =\n | \"disconnected\"\n | \"connecting\"\n | \"initializing\"\n | \"listening\"\n | \"thinking\"\n | \"speaking\";\n\n/**\n * Function call related types\n */\nexport interface FunctionToolsExecuted {\n type: \"function_tools_executed\";\n function_calls: FunctionCallInfo[];\n function_call_outputs: FunctionCallResult[];\n}\n\nexport interface FunctionCallInfo {\n id: string;\n type: string;\n call_id: string;\n arguments: Record<string, any>;\n name: string;\n}\n\nexport interface FunctionCallResult {\n id: string;\n name: string;\n type: string;\n call_id: string;\n output: string;\n is_error: boolean;\n}\n\n/**\n * VoxMessage\n * @description The message type between the agent and the user\n */\nexport type VoxMessage = {\n id?: string;\n name: \"agent\" | \"user\" | \"tool\";\n message?: string;\n timestamp: number;\n isFinal?: boolean;\n tool?: FunctionToolsExecuted;\n};\n\n/**\n * VoxAIOptions\n * @description The callback functions for the useVoxAI hook\n */\nexport interface VoxAIOptions {\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: Error) => void;\n onMessage?: (message: VoxMessage) => void;\n}\n\n// Message channel event types\ntype MessageChannelEvent =\n | { type: \"state_update\"; state: VoxAgentState }\n | { type: \"transcription_update\"; transcriptions: TranscriptionSegment[] }\n | {\n type: \"waveform_update\";\n waveformData: number[];\n speaker: \"agent\" | \"user\";\n }\n | { type: \"function_tools_executed\"; tool: FunctionToolsExecuted };\n\ntype TranscriptionSegment = {\n id: string;\n text: string;\n isFinal: boolean;\n timestamp: number;\n speaker: \"agent\" | \"user\";\n};\n\n/**\n * ConnectParams\n * @param agentId - The agent ID\n * @param agentVersion - The agent version, if not provided, the current version will be used\n * @param apiKey - The API key\n * @param dynamicVariables - The dynamic variables\n * @param metadata - 이 메타데이터는 아웃바운드 웹훅, 통화 기록에 포함됩니다.\n */\nexport interface ConnectParams {\n agentId: string;\n agentVersion?: number;\n apiKey: string;\n dynamicVariables?: Record<string, any>;\n metadata?: Record<string, any>;\n}\n\n/**\n * useVoxAI\n * @description The hook for integrating with vox.ai voice assistant\n * @param options - The options for the useVoxAI hook\n * @returns The useVoxAI hook\n * @example\n * const { connect, disconnect, state, messages, send } = useVoxAI({\n * onConnect: () => console.log(\"Connected\"),\n * onDisconnect: () => console.log(\"Disconnected\"),\n * onError: (error) => console.error(\"Error:\", error),\n * onMessage: (message) => console.log(\"Message:\", message),\n * });\n */\nexport function useVoxAI(options: VoxAIOptions = {}) {\n // Connection state\n const [connectionDetail, setConnectionDetail] =\n useState<VoxConnectionDetail | null>(null);\n const [state, setState] = useState<VoxAgentState>(\"disconnected\");\n\n // Session timestamp to filter out stale asynchronous events\n const sessionTimestampRef = useRef<number>(Date.now());\n\n // Message handling\n const [transcriptMap, setTranscriptMap] = useState<Map<string, VoxMessage>>(\n new Map()\n );\n const [messages, setMessages] = useState<VoxMessage[]>([]);\n const prevMessagesRef = useRef<string>(\"\");\n\n // Track which messages we've already sent to the onMessage callback\n const processedMessageIdsRef = useRef<Set<string>>(new Set());\n\n // DOM manipulation for LiveKit portal\n const portalRootRef = useRef<HTMLDivElement | null>(null);\n const rootRef = useRef<Root | null>(null);\n\n // Communication channel\n const channelRef = useRef<MessageChannel | null>(null);\n\n // Add this near the start of your useVoxAI hook\n const livekitComponentRef = useRef<React.ReactNode>(null);\n\n // Replace the single waveform state with a map for multiple speakers\n const [waveformDataMap, setWaveformDataMap] = useState<\n Record<string, number[]>\n >({\n agent: [],\n user: [],\n });\n\n // Add back the waveform config reference\n const waveformConfigRef = useRef<{\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n } | null>(null);\n\n // Add a new state to track microphone status\n const [isMicEnabled, setIsMicEnabled] = useState<boolean>(true);\n\n // Update messages whenever transcriptMap changes\n useEffect(() => {\n const allMessages = Array.from(transcriptMap.values()).sort(\n (a, b) => a.timestamp - b.timestamp\n );\n\n // Only update if the messages have actually changed\n const messagesString = JSON.stringify(allMessages);\n if (messagesString !== prevMessagesRef.current) {\n prevMessagesRef.current = messagesString;\n setMessages(allMessages);\n\n // Only trigger onMessage for new final messages that haven't been processed yet\n if (options.onMessage) {\n allMessages\n .filter(\n (msg) =>\n msg.isFinal &&\n msg.id &&\n !processedMessageIdsRef.current.has(msg.id)\n )\n .forEach((msg) => {\n if (msg.id) {\n // Mark this message as processed\n processedMessageIdsRef.current.add(msg.id);\n // Call the callback\n options.onMessage?.(msg);\n }\n });\n }\n }\n }, [transcriptMap, options.onMessage]);\n\n // Initialize message channel - ensure ports are properly connected\n useEffect(() => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (e) => {\n const data = e.data as MessageChannelEvent;\n\n if (data.type === \"state_update\") {\n setState(data.state);\n } else if (data.type === \"transcription_update\") {\n handleTranscriptionUpdate(data.transcriptions);\n } else if (data.type === \"waveform_update\" && data.speaker) {\n // Store the waveform data for the specific speaker\n setWaveformDataMap((prevMap) => ({\n ...prevMap,\n [data.speaker]: data.waveformData,\n }));\n } else if (data.type === \"function_tools_executed\" && data.tool) {\n // Handle function calls\n const functionCallsId = `function-calls-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(functionCallsId, {\n id: functionCallsId,\n name: \"tool\",\n tool: data.tool,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n }\n };\n\n // Start the port\n channel.port1.start();\n\n // Store the channel reference\n channelRef.current = channel;\n\n return () => {\n channelRef.current?.port1.close();\n channelRef.current?.port2.close();\n channelRef.current = null;\n };\n }, []);\n\n // Process incoming transcriptions and filter out stale events\n const handleTranscriptionUpdate = useCallback(\n (transcriptions: TranscriptionSegment[]) => {\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n\n transcriptions.forEach((t) => {\n // Only process transcriptions generated after the current session timestamp\n if (t.timestamp < sessionTimestampRef.current) {\n return;\n }\n const messageType = t.speaker === \"agent\" ? \"agent\" : \"user\";\n // Use existing timestamp if we already have this segment\n const existingTimestamp = prevMap.get(t.id)?.timestamp || t.timestamp;\n\n newMap.set(t.id, {\n id: t.id,\n name: messageType,\n message: t.text,\n timestamp: existingTimestamp,\n isFinal: t.isFinal,\n });\n });\n\n return newMap;\n });\n },\n []\n );\n\n // Set up DOM portal for LiveKit\n useEffect(() => {\n const div = document.createElement(\"div\");\n div.style.display = \"none\";\n document.body.appendChild(div);\n portalRootRef.current = div;\n rootRef.current = createRoot(div);\n\n return () => {\n if (rootRef.current) {\n rootRef.current.unmount();\n }\n if (portalRootRef.current) {\n document.body.removeChild(portalRootRef.current);\n }\n };\n }, []);\n\n // Connect to VoxAI service - updated to include dynamicVariables\n const connect = useCallback(\n async ({ agentId, apiKey, dynamicVariables, metadata }: ConnectParams) => {\n try {\n // Prevent connecting if already in a connection state\n if (state !== \"disconnected\") {\n const errorMessage = `Connection attempt rejected: Already in a connection state (${state})`;\n console.warn(errorMessage);\n\n if (options.onError) {\n options.onError(new Error(errorMessage));\n }\n return Promise.reject(new Error(errorMessage));\n }\n\n // Update session timestamp for new connection\n sessionTimestampRef.current = Date.now();\n setState(\"connecting\");\n\n const response = await fetch(HTTPS_API_ORIGIN, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agent_id: agentId,\n metadata: {\n runtime_context: {\n source: {\n type: \"react-sdk\",\n version: SDK_VERSION,\n },\n },\n call_web: {\n dynamic_variables: dynamicVariables || {},\n metadata: metadata || {},\n },\n },\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Connection failed (${response.status}): ${errorText}`\n );\n }\n\n const data = await response.json();\n setConnectionDetail(data);\n\n if (options.onConnect) {\n options.onConnect();\n }\n } catch (err) {\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n if (options.onError) {\n options.onError(error);\n }\n }\n },\n [options, state]\n );\n\n // Disconnect from VoxAI service, updating the session timestamp to ignore stale events\n const disconnect = useCallback(() => {\n // Update session timestamp on disconnect\n sessionTimestampRef.current = Date.now();\n setConnectionDetail(null);\n setTranscriptMap(new Map());\n setMessages([]);\n setState(\"disconnected\");\n\n if (options.onDisconnect) {\n options.onDisconnect();\n }\n }, [options]);\n\n // Update the send function with debugging and error checking\n const send = useCallback(\n ({ message, digit }: { message?: string; digit?: number }) => {\n if (state === \"disconnected\") {\n console.warn(\"Cannot send message: Not connected to a conversation\");\n return;\n }\n\n if (message) {\n const messageId = `user-text-${Date.now()}`;\n setTranscriptMap((prevMap) => {\n const newMap = new Map(prevMap);\n newMap.set(messageId, {\n id: messageId,\n name: \"user\",\n message: message,\n timestamp: Date.now(),\n isFinal: true,\n });\n return newMap;\n });\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_text\",\n text: message,\n });\n } else {\n console.error(\"No message channel available to send message\");\n }\n }\n\n if (digit !== undefined) {\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"send_dtmf\",\n digit: digit,\n });\n } else {\n console.error(\"No message channel available to send DTMF\");\n }\n }\n },\n [state]\n );\n\n // Update the audioWaveform function to return data for the requested speaker\n const audioWaveform = useCallback(\n ({\n speaker = \"agent\",\n barCount = 10,\n updateInterval = 20,\n }: {\n speaker?: \"agent\" | \"user\";\n barCount?: number;\n updateInterval?: number;\n }): number[] => {\n waveformConfigRef.current = { speaker, barCount, updateInterval };\n\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"waveform_config\",\n config: { speaker, barCount, updateInterval },\n });\n }\n\n const speakerData = waveformDataMap[speaker] || [];\n return speakerData.length > 0\n ? speakerData.slice(0, barCount)\n : Array(barCount).fill(0);\n },\n [waveformDataMap]\n );\n\n // Add toggleMic function that will be exposed in the hook's return value\n const toggleMic = useCallback((value: boolean) => {\n setIsMicEnabled(value);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"toggle_mic\",\n enabled: value,\n });\n } else {\n console.error(\"No message channel available to toggle microphone\");\n }\n }, []);\n\n // Add setVolume function that will be exposed in the hook's return value\n const setVolume = useCallback((volume: number) => {\n const validVolume = Math.min(Math.max(volume, 0), 1);\n if (channelRef.current) {\n channelRef.current.port1.postMessage({\n type: \"set_volume\",\n volume: validVolume,\n });\n } else {\n console.error(\"No message channel available to set volume\");\n }\n }, []);\n\n // Modify the useEffect hook that renders the LiveKit component\n useEffect(() => {\n if (!rootRef.current) return;\n\n if (connectionDetail) {\n if (!livekitComponentRef.current) {\n if (channelRef.current) {\n channelRef.current.port2.start();\n }\n\n livekitComponentRef.current = (\n <LiveKitRoom\n serverUrl={connectionDetail.serverUrl}\n token={connectionDetail.participantToken}\n audio={true}\n video={false}\n connect={true}\n onDisconnected={disconnect}\n onError={(error) => {\n console.error(\"LiveKit connection error:\", error);\n disconnect();\n if (options.onError) {\n options.onError(\n new Error(`LiveKit connection error: ${error.message}`)\n );\n }\n }}\n >\n <RoomAudioRenderer />\n {channelRef.current && (\n <StateMonitor\n port={channelRef.current.port2}\n initialConfig={\n waveformConfigRef.current || {\n barCount: 10,\n updateInterval: 20,\n }\n }\n />\n )}\n </LiveKitRoom>\n );\n }\n rootRef.current.render(livekitComponentRef.current);\n } else {\n livekitComponentRef.current = null;\n rootRef.current.render(<></>);\n }\n }, [connectionDetail, disconnect, options.onError]);\n\n return {\n connect,\n disconnect,\n state,\n messages,\n send,\n audioWaveform,\n toggleMic,\n setVolume,\n };\n}\n\n/**\n * Component that monitors LiveKit state and communicates back to the main hook\n */\nfunction StateMonitor({\n port,\n initialConfig,\n}: {\n port: MessagePort | undefined;\n initialConfig: {\n speaker?: \"agent\" | \"user\";\n barCount: number;\n updateInterval: number;\n };\n}) {\n const { agent, state } = useVoiceAssistant();\n const { send: sendChat } = useChat();\n\n // Initialize waveform config with the passed initial values, defaulting to \"agent\" if not specified\n const [waveformConfig, setWaveformConfig] = useState({\n speaker: initialConfig.speaker || \"agent\",\n barCount: initialConfig.barCount,\n updateInterval: initialConfig.updateInterval,\n });\n\n // Agent transcriptions\n const agentAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n agent?.identity\n )[0];\n const agentTranscription = useTrackTranscription(agentAudioTrack);\n\n // Use the current config for the waveform, applying different settings based on speaker\n const agentAudioWaveform = useAudioWaveform(agentAudioTrack, {\n barCount:\n waveformConfig.speaker === \"agent\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"agent\" ? waveformConfig.updateInterval : 20,\n });\n\n // User transcriptions\n const localParticipant = useLocalParticipant();\n const localMessages = useTrackTranscription({\n publication: localParticipant.microphoneTrack,\n source: Track.Source.Microphone,\n participant: localParticipant.localParticipant,\n });\n const localAudioTrack = useParticipantTracks(\n [Track.Source.Microphone],\n localParticipant.localParticipant.identity\n )[0];\n const userAudioWaveform = useAudioWaveform(localAudioTrack, {\n barCount: waveformConfig.speaker === \"user\" ? waveformConfig.barCount : 120, // default if not the selected speaker\n updateInterval:\n waveformConfig.speaker === \"user\" ? waveformConfig.updateInterval : 20,\n });\n\n // Add separate effects to send agent and user waveform data\n useEffect(() => {\n if (!port || !agentAudioWaveform || !agentAudioWaveform.bars) return;\n\n // Send the agent waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: agentAudioWaveform.bars,\n speaker: \"agent\",\n });\n }, [port, agentAudioWaveform]);\n\n useEffect(() => {\n if (!port || !userAudioWaveform || !userAudioWaveform.bars) return;\n\n // Send the user waveform data\n port.postMessage({\n type: \"waveform_update\",\n waveformData: userAudioWaveform.bars,\n speaker: \"user\",\n });\n }, [port, userAudioWaveform]);\n\n // Listen for messages including config updates and mic toggle commands\n useEffect(() => {\n if (!port) return;\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n\n if (data.type === \"waveform_config\" && data.config) {\n // Verify we have both required properties before updating\n if (\n typeof data.config.barCount === \"number\" &&\n typeof data.config.updateInterval === \"number\"\n ) {\n setWaveformConfig(data.config);\n }\n } else if (data.type === \"send_text\") {\n if (sendChat) {\n sendChat(data.text);\n } else {\n console.error(\"sendChat function is not available\");\n }\n } else if (data.type === \"send_dtmf\") {\n if (localParticipant.localParticipant) {\n // Use standard DTMF code (RFC 4733)\n const standardDtmfCode = 101; // Standard DTMF payload type\n localParticipant.localParticipant.publishDtmf(\n standardDtmfCode,\n data.digit\n );\n } else {\n console.error(\"Local participant is not available for DTMF\");\n }\n } else if (\n data.type === \"toggle_mic\" &&\n typeof data.enabled === \"boolean\"\n ) {\n // Handle microphone toggle\n if (localParticipant.localParticipant) {\n localParticipant.localParticipant\n .setMicrophoneEnabled(data.enabled)\n .catch((error) => {\n console.error(\"Failed to toggle microphone:\", error);\n });\n } else {\n console.error(\"Local participant is not available for mic toggle\");\n }\n } else if (\n data.type === \"set_volume\" &&\n typeof data.volume === \"number\"\n ) {\n // Handle volume control\n if (agent) {\n // The agent is a RemoteParticipant, so we can call setVolume directly\n try {\n agent.setVolume(data.volume);\n console.log(`Set agent volume to ${data.volume}`);\n } catch (error) {\n console.error(\"Failed to set agent volume:\", error);\n }\n } else {\n console.error(\"Agent is not available for volume control\");\n }\n }\n };\n\n // Make sure we start the port\n port.start();\n\n port.addEventListener(\"message\", handleMessage);\n\n return () => {\n port.removeEventListener(\"message\", handleMessage);\n };\n }, [port, sendChat, localParticipant, agent]);\n\n // Send agent state updates\n useEffect(() => {\n if (port) {\n port.postMessage({ type: \"state_update\", state });\n }\n }, [state, port]);\n\n // Send agent transcriptions\n useEffect(() => {\n if (port && agentTranscription.segments.length > 0) {\n const transcriptions = agentTranscription.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"agent\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [agentTranscription.segments, port]);\n\n // Send user transcriptions\n useEffect(() => {\n if (port && localMessages.segments.length > 0) {\n const transcriptions = localMessages.segments.map((segment) => ({\n id: segment.id,\n text: segment.text,\n isFinal: segment.final,\n timestamp: Date.now(),\n speaker: \"user\" as const,\n }));\n\n port.postMessage({\n type: \"transcription_update\",\n transcriptions,\n });\n }\n }, [localMessages.segments, port]);\n\n // Add data channel hook for function calls\n const { message: functionToolsExecuted } = useDataChannel(\n \"function_tools_executed\",\n (msg) => {\n if (!port) return;\n\n const textDecoder = new TextDecoder();\n const messageString =\n msg.payload instanceof Uint8Array\n ? textDecoder.decode(msg.payload)\n : String(msg.payload);\n\n let tool: FunctionToolsExecuted;\n try {\n tool = JSON.parse(messageString);\n\n // Send function calls to main hook via the port\n port.postMessage({\n type: \"function_tools_executed\",\n tool: tool,\n });\n } catch (e) {\n console.error(\"Failed to parse function call log:\", e);\n }\n }\n );\n\n return null;\n}\n","// export const HTTPS_API_ORIGIN = \"https://frontend-dev.tryvox.co/api/agent/sdk\";\nexport const HTTPS_API_ORIGIN = \"https://www.tryvox.co/api/agent/sdk\";\n// export const HTTPS_API_ORIGIN = \"http://localhost:3000/api/agent/sdk\";\nexport const SDK_VERSION = \"0.3.2\";\n"],"names":["StateMonitor","_ref4","port","initialConfig","agent","state","useVoiceAssistant","send","sendChat","useChat","waveformConfig","setWaveformConfig","useState","speaker","barCount","updateInterval","agentAudioTrack","useParticipantTracks","Track","Source","Microphone","identity","agentTranscription","useTrackTranscription","agentAudioWaveform","useAudioWaveform","localParticipant","useLocalParticipant","localMessages","publication","microphoneTrack","source","participant","localAudioTrack","userAudioWaveform","useEffect","bars","postMessage","type","waveformData","handleMessage","event","data","config","text","console","error","publishDtmf","digit","enabled","setMicrophoneEnabled","catch","volume","setVolume","log","start","addEventListener","removeEventListener","segments","length","transcriptions","map","segment","id","isFinal","final","timestamp","Date","now","useDataChannel","msg","textDecoder","TextDecoder","messageString","payload","Uint8Array","decode","String","tool","JSON","parse","e","options","connectionDetail","setConnectionDetail","setState","sessionTimestampRef","useRef","transcriptMap","setTranscriptMap","Map","messages","setMessages","prevMessagesRef","processedMessageIdsRef","Set","portalRootRef","rootRef","channelRef","livekitComponentRef","waveformDataMap","setWaveformDataMap","user","waveformConfigRef","isMicEnabled","setIsMicEnabled","allMessages","Array","from","values","sort","a","b","messagesString","stringify","current","onMessage","filter","has","forEach","add","channel","MessageChannel","port1","onmessage","handleTranscriptionUpdate","prevMap","functionCallsId","newMap","set","name","_channelRef$current","_channelRef$current2","close","port2","useCallback","t","_prevMap$get","messageType","existingTimestamp","get","message","div","document","createElement","style","display","body","appendChild","createRoot","unmount","removeChild","connect","_ref","agentId","apiKey","dynamicVariables","metadata","Promise","resolve","errorMessage","warn","onError","Error","reject","fetch","method","headers","Authorization","agent_id","runtime_context","version","call_web","dynamic_variables","then","response","_temp2","_result2","_exit","json","onConnect","_temp","ok","errorText","status","_catch","err","disconnect","onDisconnect","_ref2","messageId","undefined","audioWaveform","_ref3","speakerData","slice","fill","toggleMic","value","validVolume","Math","min","max","_jsxs","LiveKitRoom","serverUrl","token","participantToken","audio","video","onDisconnected","children","_jsx","RoomAudioRenderer","render","_Fragment"],"mappings":"8gBA8iBA,SAASA,EAAYC,GAAC,IAAAC,KACpBA,EAAIC,cACJA,GAQDF,EACC,MAAMG,MAAEA,EAAKC,MAAEA,GAAUC,EAAAA,qBACjBC,KAAMC,GAAaC,EAAOA,WAG3BC,EAAgBC,GAAqBC,WAAS,CACnDC,QAASV,EAAcU,SAAW,QAClCC,SAAUX,EAAcW,SACxBC,eAA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B4C,EAAoBgB,QAClBwF,EAAAA,KAACC,EAAWA,aACVC,UAAW1H,EAAiB0H,UAC5BC,MAAO3H,EAAiB4H,iBACxBC,OAAO,EACPC,OAAO,EACPzD,SAAS,EACT0D,eAAgBvB,EAChBzB,QAAUpH,IACRD,QAAQC,MAAM,4BAA6BA,GAC3C6I,IACIzG,EAAQgF,SACVhF,EAAQgF,QACN,IAAIC,MAAmCrH,6BAAAA,EAAM+F,SAEjD,EACDsE,SAAA,CAEDC,EAAAA,IAACC,EAAiBA,kBAAG,IACpBnH,EAAWiB,SACViG,EAAAA,IAACpN,EAAY,CACXE,KAAMgG,EAAWiB,QAAQmB,MACzBnI,cACEoG,EAAkBY,SAAW,CAC3BrG,SAAU,GACVC,eAAgB,UAQ9BkF,EAAQkB,QAAQmG,OAAOnH,EAAoBgB,WAE3ChB,EAAoBgB,QAAU,KAC9BlB,EAAQkB,QAAQmG,OAAOF,MAAAG,EAAAA,SAAA,CAAA,KACzB,EACC,CAACpI,EAAkBwG,EAAYzG,EAAQgF,UAEnC,CACLV,UACAmC,aACAtL,QACAsF,WACApF,OACAyL,gBACAK,YACAhJ,YAEJ"}
@@ -1,2 +1,2 @@
1
1
  export declare const HTTPS_API_ORIGIN = "https://www.tryvox.co/api/agent/sdk";
2
- export declare const SDK_VERSION = "0.3.0";
2
+ export declare const SDK_VERSION = "0.3.2";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vox-ai/react",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "vox.ai React Library",
5
5
  "main": "./dist/lib.umd.js",
6
6
  "module": "./dist/lib.module.js",