@flowengage/react-chatbot 0.2.7 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/flowengage-embed.js
CHANGED
|
@@ -323,7 +323,7 @@ class ScribeAudioProcessor extends AudioWorkletProcessor {
|
|
|
323
323
|
|
|
324
324
|
registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
325
325
|
|
|
326
|
-
`),bh,xh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(bh||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(xh||={});var Sh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new vh(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await yh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};Sh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var Ch=class extends Jm{static startSession(e){return e.textOnly?dh.startSession(e):gh.startSession(e)}};function wh(...e){en()&&console.log(`[FlowEngage:voice-tools]`,...e)}function Th(e){if(e.labels&&e.labels.length)return e.labels[0].textContent?.trim()||null;let t=e.id;if(t)try{let e=document.querySelector(`label[for="${CSS.escape(t)}"]`);if(e)return e.textContent?.trim()||null}catch{let e=document.querySelector(`label[for="${t.replace(/"/g,`\\"`)}"]`);if(e)return e.textContent?.trim()||null}let n=e.parentElement;for(let e=0;e<4&&n;e+=1){if(n.tagName===`LABEL`)return n.textContent?.trim()||null;n=n.parentElement}return null}function Eh(){return Array.from(document.querySelectorAll(`input, select, textarea`)).filter(e=>{let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0})}function Dh(){return Eh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:Th(e),placeholder:e.placeholder||null}))}function Oh(){return Array.from(document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}).slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function kh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.name,e.id,e.placeholder,Th(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`)].filter(Boolean).map(e=>String(e).toLowerCase()),i=0;for(let e of r){if(!e)continue;if(e.includes(n)||n.includes(e)){i=Math.max(i,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);i=Math.max(i,r/t.length*88)}return i}function Ah(e,t){let n=null,r=0;for(let i of e){let e=kh(i,t);e>r&&(r=e,n=i)}return!n||r<38?null:n}function jh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function Mh(e){let t=Array.from(document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}),n=null,r=0;for(let i of t){let t=jh(i,e);t>r&&(r=t,n=i)}return!n||r<36?null:n}function Nh(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function Ph(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function Fh(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function Ih(e,t){let n=e.tagName,r=(e.type||``).toLowerCase();if(n===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(r===`checkbox`||r===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let i=String(t);if(n===`INPUT`||n===`TEXTAREA`){let t=n===`TEXTAREA`?window.HTMLTextAreaElement.prototype:window.HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(t,`value`);r?.set?r.set.call(e,i):e.value=i}else e.value=i;return e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0}function Lh(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``);return{navigate_to_page:async e=>{wh(`navigate_to_page ▶ raw parameters:`,e);let t=Nh(e),n=Ph(t),r=t.section_text??t.sectionText??t.section;if(wh(`navigate_to_page · coerced:`,{url:n,sectionText:r}),!n){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return wh(`navigate_to_page ✖`,e),e}try{if(wh(`navigate_to_page → shadowNavigate`,n),await cn(n),await new Promise(e=>setTimeout(e,400)),r&&typeof r==`string`){let e=rn(null,r);e&&an(e),wh(`navigate_to_page · highlight`,{sectionText:r,found:!!e})}let e=`OK_NAVIGATION ${n}`;return wh(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return wh(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{wh(`highlight_on_page ▶`,e);let t=Nh(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=rn(n||null,r||null);return i?(an(i),wh(`highlight_on_page ✓`),`Highlighted the section.`):(wh(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{wh(`search_site_content ▶`,e);let r=Fh(Nh(e));if(wh(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return wh(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return wh(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return wh(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;wh(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if(wh(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return wh(`search_site_content ✖`,e),e}let o=a.results||[];return wh(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return wh(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=Dh(),t=Oh();return wh(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key can be label text, placeholder (e.g. Enter Website URL), name, or id. After filling, use click_page_button with button_text (e.g. Conduct Audit) to submit.`})},fill_form_fields:async e=>{let t=Nh(e)?.fields;if(wh(`fill_form_fields ▶`,{fieldCount:Array.isArray(t)?t.length:0}),!Array.isArray(t)||t.length===0)return`No fields provided. Use list_page_forms first.`;let n=Eh(),r=[];for(let e of t){let t=e?.field_key??e?.fieldKey,i=e?.value;if(t==null||i==null)continue;let a=Ah(n,String(t));a&&(Ih(a,i),r.push(String(t)))}if(!r.length)return wh(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. website url, Enter Website URL).`;let i=`Filled fields: ${r.join(`, `)}`;return wh(`fill_form_fields ✓`,i),i},click_page_button:async e=>{let t=Nh(e),n=(t.button_text??t.buttonText??t.text??``).trim();if(wh(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=Mh(n);if(!r)return wh(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{r.click();let e=`OK_CLICK ${(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`}`;return wh(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return wh(`click_page_button ✖`,t),t}}}}var Rh={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},zh={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function Bh({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[l,u]=(0,v.useState)(`idle`),[d,f]=(0,v.useState)(null),[p,m]=(0,v.useState)(!1),h=(0,v.useRef)(null),g=(0,v.useRef)(null);(0,v.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;let o=Lh({siteId:n||null,apiBaseUrl:r||null}),s=await Ch.startSession({agentId:e,clientTools:o,onModeChange:({mode:e})=>{t||u(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};a.current=[...a.current,i]},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),u(`error`),f(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),m(!1),u(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,h.current=s,m(!0),u(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: search_site_content then navigate_to_page with section_text when relevant — no permission ask. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit) when the user wants to submit.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),u(`error`),f(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):h.current&&h.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let _=(0,v.useCallback)(async()=>{try{await h.current?.endSession?.()}catch{}h.current=null,m(!1),u(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),y=l===`listening`||l===`speaking`,b=zh[l]||zh.idle,x=Rh[l]||Rh.idle;return(0,O.jsxs)(`div`,{ref:g,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,O.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[y&&(0,O.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${b}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),y&&(0,O.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${b}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,O.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:x,border:`3px solid ${b}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:l===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${x}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,O.jsx)(vn,{size:44,color:b})})]}),(0,O.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:l===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[l===`idle`&&`Starting voice session…`,l===`listening`&&`Listening…`,l===`speaking`&&`AI is speaking…`,l===`error`&&(d||`Error`)]}),transcript.length>0&&(0,O.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:transcript.map((e,t)=>(0,O.jsx)(`div`,{style:{display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,O.jsx)(`div`,{style:{maxWidth:`85%`,padding:`8px 12px`,borderRadius:`14px`,fontSize:`13px`,lineHeight:1.5,background:e.sender===`user`?`var(--flowengage-primary)`:`#f3f4f6`,color:e.sender===`user`?`#fff`:`#111827`},children:e.message})},t))}),(0,O.jsxs)(`button`,{onClick:_,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,O.jsx)(yn,{size:18}),`End Voice Session`]}),(0,O.jsx)(`style`,{children:`
|
|
326
|
+
`),bh,xh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(bh||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(xh||={});var Sh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new vh(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await yh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};Sh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var Ch=class extends Jm{static startSession(e){return e.textOnly?dh.startSession(e):gh.startSession(e)}};function wh(...e){en()&&console.log(`[FlowEngage:voice-tools]`,...e)}function Th(e){if(e.labels&&e.labels.length)return e.labels[0].textContent?.trim()||null;let t=e.id;if(t)try{let e=document.querySelector(`label[for="${CSS.escape(t)}"]`);if(e)return e.textContent?.trim()||null}catch{let e=document.querySelector(`label[for="${t.replace(/"/g,`\\"`)}"]`);if(e)return e.textContent?.trim()||null}let n=e.parentElement;for(let e=0;e<4&&n;e+=1){if(n.tagName===`LABEL`)return n.textContent?.trim()||null;n=n.parentElement}return null}function Eh(){return Array.from(document.querySelectorAll(`input, select, textarea`)).filter(e=>{let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0})}function Dh(){return Eh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:Th(e),placeholder:e.placeholder||null}))}function Oh(){return Array.from(document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}).slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function kh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.name,e.id,e.placeholder,Th(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`)].filter(Boolean).map(e=>String(e).toLowerCase()),i=0;for(let e of r){if(!e)continue;if(e.includes(n)||n.includes(e)){i=Math.max(i,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);i=Math.max(i,r/t.length*88)}return i}function Ah(e,t){let n=null,r=0;for(let i of e){let e=kh(i,t);e>r&&(r=e,n=i)}return!n||r<38?null:n}function jh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function Mh(e){let t=Array.from(document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}),n=null,r=0;for(let i of t){let t=jh(i,e);t>r&&(r=t,n=i)}return!n||r<36?null:n}function Nh(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function Ph(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function Fh(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function Ih(e,t){let n=e.tagName,r=(e.type||``).toLowerCase();if(n===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(r===`checkbox`||r===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let i=String(t);if(n===`INPUT`||n===`TEXTAREA`){let t=n===`TEXTAREA`?window.HTMLTextAreaElement.prototype:window.HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(t,`value`);r?.set?r.set.call(e,i):e.value=i}else e.value=i;return e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0}function Lh(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``);return{navigate_to_page:async e=>{wh(`navigate_to_page ▶ raw parameters:`,e);let t=Nh(e),n=Ph(t),r=t.section_text??t.sectionText??t.section;if(wh(`navigate_to_page · coerced:`,{url:n,sectionText:r}),!n){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return wh(`navigate_to_page ✖`,e),e}try{if(wh(`navigate_to_page → shadowNavigate`,n),await cn(n),await new Promise(e=>setTimeout(e,400)),r&&typeof r==`string`){let e=rn(null,r);e&&an(e),wh(`navigate_to_page · highlight`,{sectionText:r,found:!!e})}let e=`OK_NAVIGATION ${n}`;return wh(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return wh(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{wh(`highlight_on_page ▶`,e);let t=Nh(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=rn(n||null,r||null);return i?(an(i),wh(`highlight_on_page ✓`),`Highlighted the section.`):(wh(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{wh(`search_site_content ▶`,e);let r=Fh(Nh(e));if(wh(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return wh(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return wh(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return wh(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;wh(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if(wh(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return wh(`search_site_content ✖`,e),e}let o=a.results||[];return wh(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return wh(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=Dh(),t=Oh();return wh(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key can be label text, placeholder (e.g. Enter Website URL), name, or id. After filling, use click_page_button with button_text (e.g. Conduct Audit) to submit.`})},fill_form_fields:async e=>{let t=Nh(e)?.fields;if(wh(`fill_form_fields ▶`,{fieldCount:Array.isArray(t)?t.length:0}),!Array.isArray(t)||t.length===0)return`No fields provided. Use list_page_forms first.`;let n=Eh(),r=[];for(let e of t){let t=e?.field_key??e?.fieldKey,i=e?.value;if(t==null||i==null)continue;let a=Ah(n,String(t));a&&(Ih(a,i),r.push(String(t)))}if(!r.length)return wh(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. website url, Enter Website URL).`;let i=`Filled fields: ${r.join(`, `)}`;return wh(`fill_form_fields ✓`,i),i},click_page_button:async e=>{let t=Nh(e),n=(t.button_text??t.buttonText??t.text??``).trim();if(wh(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=Mh(n);if(!r)return wh(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{r.click();let e=`OK_CLICK ${(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`}`;return wh(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return wh(`click_page_button ✖`,t),t}}}}var Rh={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},zh={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function Bh({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[l,u]=(0,v.useState)(`idle`),[d,f]=(0,v.useState)(null),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)([]),_=(0,v.useRef)(null),y=(0,v.useRef)(null);(0,v.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;g([]);let o=Lh({siteId:n||null,apiBaseUrl:r||null}),s=await Ch.startSession({agentId:e,clientTools:o,onModeChange:({mode:e})=>{t||u(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};a.current=[...a.current,i],g(e=>[...e,i])},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),u(`error`),f(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),m(!1),u(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,_.current=s,m(!0),u(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: search_site_content then navigate_to_page with section_text when relevant — no permission ask. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit) when the user wants to submit.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),u(`error`),f(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):_.current&&_.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let b=(0,v.useCallback)(async()=>{try{await _.current?.endSession?.()}catch{}_.current=null,m(!1),u(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),x=l===`listening`||l===`speaking`,ee=zh[l]||zh.idle,te=Rh[l]||Rh.idle;return(0,O.jsxs)(`div`,{ref:y,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,O.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[x&&(0,O.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${ee}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),x&&(0,O.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${ee}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,O.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:te,border:`3px solid ${ee}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:l===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${te}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,O.jsx)(vn,{size:44,color:ee})})]}),(0,O.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:l===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[l===`idle`&&`Starting voice session…`,l===`listening`&&`Listening…`,l===`speaking`&&`AI is speaking…`,l===`error`&&(d||`Error`)]}),h.length>0&&(0,O.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:h.map((e,t)=>(0,O.jsx)(`div`,{style:{display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,O.jsx)(`div`,{style:{maxWidth:`85%`,padding:`8px 12px`,borderRadius:`14px`,fontSize:`13px`,lineHeight:1.5,background:e.sender===`user`?`var(--flowengage-primary)`:`#f3f4f6`,color:e.sender===`user`?`#fff`:`#111827`},children:e.message})},t))}),(0,O.jsxs)(`button`,{onClick:b,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,O.jsx)(yn,{size:18}),`End Voice Session`]}),(0,O.jsx)(`style`,{children:`
|
|
327
327
|
@keyframes fe-orb-pulse {
|
|
328
328
|
0% { transform: scale(1); opacity: 0.6; }
|
|
329
329
|
50% { transform: scale(1.18); opacity: 0.15; }
|
|
@@ -315,7 +315,7 @@ class ScribeAudioProcessor extends AudioWorkletProcessor {
|
|
|
315
315
|
|
|
316
316
|
registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
317
317
|
|
|
318
|
-
`),uh,dh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(uh||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(dh||={});var fh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new ch(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await lh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};fh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var ph=class extends Rm{static startSession(e){return e.textOnly?th.startSession(e):oh.startSession(e)}};function $(...e){Yt()&&console.log(`[FlowEngage:voice-tools]`,...e)}function mh(e){if(e.labels&&e.labels.length)return e.labels[0].textContent?.trim()||null;let t=e.id;if(t)try{let e=document.querySelector(`label[for="${CSS.escape(t)}"]`);if(e)return e.textContent?.trim()||null}catch{let e=document.querySelector(`label[for="${t.replace(/"/g,`\\"`)}"]`);if(e)return e.textContent?.trim()||null}let n=e.parentElement;for(let e=0;e<4&&n;e+=1){if(n.tagName===`LABEL`)return n.textContent?.trim()||null;n=n.parentElement}return null}function hh(){return Array.from(document.querySelectorAll(`input, select, textarea`)).filter(e=>{let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0})}function gh(){return hh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:mh(e),placeholder:e.placeholder||null}))}function _h(){return Array.from(document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}).slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function vh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.name,e.id,e.placeholder,mh(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`)].filter(Boolean).map(e=>String(e).toLowerCase()),i=0;for(let e of r){if(!e)continue;if(e.includes(n)||n.includes(e)){i=Math.max(i,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);i=Math.max(i,r/t.length*88)}return i}function yh(e,t){let n=null,r=0;for(let i of e){let e=vh(i,t);e>r&&(r=e,n=i)}return!n||r<38?null:n}function bh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function xh(e){let t=Array.from(document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}),n=null,r=0;for(let i of t){let t=bh(i,e);t>r&&(r=t,n=i)}return!n||r<36?null:n}function Sh(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function Ch(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function wh(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function Th(e,t){let n=e.tagName,r=(e.type||``).toLowerCase();if(n===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(r===`checkbox`||r===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let i=String(t);if(n===`INPUT`||n===`TEXTAREA`){let t=n===`TEXTAREA`?window.HTMLTextAreaElement.prototype:window.HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(t,`value`);r?.set?r.set.call(e,i):e.value=i}else e.value=i;return e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0}function Eh(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``);return{navigate_to_page:async e=>{$(`navigate_to_page ▶ raw parameters:`,e);let t=Sh(e),n=Ch(t),r=t.section_text??t.sectionText??t.section;if($(`navigate_to_page · coerced:`,{url:n,sectionText:r}),!n){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}try{if($(`navigate_to_page → shadowNavigate`,n),await nn(n),await new Promise(e=>setTimeout(e,400)),r&&typeof r==`string`){let e=Qt(null,r);e&&$t(e),$(`navigate_to_page · highlight`,{sectionText:r,found:!!e})}let e=`OK_NAVIGATION ${n}`;return $(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{$(`highlight_on_page ▶`,e);let t=Sh(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=Qt(n||null,r||null);return i?($t(i),$(`highlight_on_page ✓`),`Highlighted the section.`):($(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=wh(Sh(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return $(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=gh(),t=_h();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key can be label text, placeholder (e.g. Enter Website URL), name, or id. After filling, use click_page_button with button_text (e.g. Conduct Audit) to submit.`})},fill_form_fields:async e=>{let t=Sh(e)?.fields;if($(`fill_form_fields ▶`,{fieldCount:Array.isArray(t)?t.length:0}),!Array.isArray(t)||t.length===0)return`No fields provided. Use list_page_forms first.`;let n=hh(),r=[];for(let e of t){let t=e?.field_key??e?.fieldKey,i=e?.value;if(t==null||i==null)continue;let a=yh(n,String(t));a&&(Th(a,i),r.push(String(t)))}if(!r.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. website url, Enter Website URL).`;let i=`Filled fields: ${r.join(`, `)}`;return $(`fill_form_fields ✓`,i),i},click_page_button:async e=>{let t=Sh(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=xh(n);if(!r)return $(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{r.click();let e=`OK_CLICK ${(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`}`;return $(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}}}var Dh={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},Oh={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function kh({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[d,f]=(0,l.useState)(`idle`),[p,ee]=(0,l.useState)(null),[m,te]=(0,l.useState)(!1),ne=(0,l.useRef)(null),re=(0,l.useRef)(null);(0,l.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;let o=Eh({siteId:n||null,apiBaseUrl:r||null}),s=await ph.startSession({agentId:e,clientTools:o,onModeChange:({mode:e})=>{t||f(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};a.current=[...a.current,i]},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),f(`error`),ee(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),te(!1),f(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,ne.current=s,te(!0),f(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: search_site_content then navigate_to_page with section_text when relevant — no permission ask. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit) when the user wants to submit.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),f(`error`),ee(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):ne.current&&ne.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let ie=(0,l.useCallback)(async()=>{try{await ne.current?.endSession?.()}catch{}ne.current=null,te(!1),f(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),ae=d===`listening`||d===`speaking`,h=Oh[d]||Oh.idle,oe=Dh[d]||Dh.idle;return(0,u.jsxs)(`div`,{ref:re,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,u.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[ae&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${h}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),ae&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${h}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,u.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:oe,border:`3px solid ${h}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:d===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${oe}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,u.jsx)(fn,{size:44,color:h})})]}),(0,u.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:d===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[d===`idle`&&`Starting voice session…`,d===`listening`&&`Listening…`,d===`speaking`&&`AI is speaking…`,d===`error`&&(p||`Error`)]}),transcript.length>0&&(0,u.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:transcript.map((e,t)=>(0,u.jsx)(`div`,{style:{display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,u.jsx)(`div`,{style:{maxWidth:`85%`,padding:`8px 12px`,borderRadius:`14px`,fontSize:`13px`,lineHeight:1.5,background:e.sender===`user`?`var(--flowengage-primary)`:`#f3f4f6`,color:e.sender===`user`?`#fff`:`#111827`},children:e.message})},t))}),(0,u.jsxs)(`button`,{onClick:ie,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,u.jsx)(pn,{size:18}),`End Voice Session`]}),(0,u.jsx)(`style`,{children:`
|
|
318
|
+
`),uh,dh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(uh||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(dh||={});var fh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new ch(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await lh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};fh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var ph=class extends Rm{static startSession(e){return e.textOnly?th.startSession(e):oh.startSession(e)}};function $(...e){Yt()&&console.log(`[FlowEngage:voice-tools]`,...e)}function mh(e){if(e.labels&&e.labels.length)return e.labels[0].textContent?.trim()||null;let t=e.id;if(t)try{let e=document.querySelector(`label[for="${CSS.escape(t)}"]`);if(e)return e.textContent?.trim()||null}catch{let e=document.querySelector(`label[for="${t.replace(/"/g,`\\"`)}"]`);if(e)return e.textContent?.trim()||null}let n=e.parentElement;for(let e=0;e<4&&n;e+=1){if(n.tagName===`LABEL`)return n.textContent?.trim()||null;n=n.parentElement}return null}function hh(){return Array.from(document.querySelectorAll(`input, select, textarea`)).filter(e=>{let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0})}function gh(){return hh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:mh(e),placeholder:e.placeholder||null}))}function _h(){return Array.from(document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}).slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function vh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.name,e.id,e.placeholder,mh(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`)].filter(Boolean).map(e=>String(e).toLowerCase()),i=0;for(let e of r){if(!e)continue;if(e.includes(n)||n.includes(e)){i=Math.max(i,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);i=Math.max(i,r/t.length*88)}return i}function yh(e,t){let n=null,r=0;for(let i of e){let e=vh(i,t);e>r&&(r=e,n=i)}return!n||r<38?null:n}function bh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function xh(e){let t=Array.from(document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(e.disabled)return!1;try{let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}),n=null,r=0;for(let i of t){let t=bh(i,e);t>r&&(r=t,n=i)}return!n||r<36?null:n}function Sh(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function Ch(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function wh(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function Th(e,t){let n=e.tagName,r=(e.type||``).toLowerCase();if(n===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(r===`checkbox`||r===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let i=String(t);if(n===`INPUT`||n===`TEXTAREA`){let t=n===`TEXTAREA`?window.HTMLTextAreaElement.prototype:window.HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(t,`value`);r?.set?r.set.call(e,i):e.value=i}else e.value=i;return e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0}function Eh(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``);return{navigate_to_page:async e=>{$(`navigate_to_page ▶ raw parameters:`,e);let t=Sh(e),n=Ch(t),r=t.section_text??t.sectionText??t.section;if($(`navigate_to_page · coerced:`,{url:n,sectionText:r}),!n){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}try{if($(`navigate_to_page → shadowNavigate`,n),await nn(n),await new Promise(e=>setTimeout(e,400)),r&&typeof r==`string`){let e=Qt(null,r);e&&$t(e),$(`navigate_to_page · highlight`,{sectionText:r,found:!!e})}let e=`OK_NAVIGATION ${n}`;return $(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{$(`highlight_on_page ▶`,e);let t=Sh(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=Qt(n||null,r||null);return i?($t(i),$(`highlight_on_page ✓`),`Highlighted the section.`):($(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=wh(Sh(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return $(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=gh(),t=_h();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key can be label text, placeholder (e.g. Enter Website URL), name, or id. After filling, use click_page_button with button_text (e.g. Conduct Audit) to submit.`})},fill_form_fields:async e=>{let t=Sh(e)?.fields;if($(`fill_form_fields ▶`,{fieldCount:Array.isArray(t)?t.length:0}),!Array.isArray(t)||t.length===0)return`No fields provided. Use list_page_forms first.`;let n=hh(),r=[];for(let e of t){let t=e?.field_key??e?.fieldKey,i=e?.value;if(t==null||i==null)continue;let a=yh(n,String(t));a&&(Th(a,i),r.push(String(t)))}if(!r.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. website url, Enter Website URL).`;let i=`Filled fields: ${r.join(`, `)}`;return $(`fill_form_fields ✓`,i),i},click_page_button:async e=>{let t=Sh(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=xh(n);if(!r)return $(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{r.click();let e=`OK_CLICK ${(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`}`;return $(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}}}var Dh={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},Oh={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function kh({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[d,f]=(0,l.useState)(`idle`),[p,ee]=(0,l.useState)(null),[m,te]=(0,l.useState)(!1),[ne,re]=(0,l.useState)([]),ie=(0,l.useRef)(null),ae=(0,l.useRef)(null);(0,l.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;re([]);let o=Eh({siteId:n||null,apiBaseUrl:r||null}),s=await ph.startSession({agentId:e,clientTools:o,onModeChange:({mode:e})=>{t||f(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};a.current=[...a.current,i],re(e=>[...e,i])},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),f(`error`),ee(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),te(!1),f(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,ie.current=s,te(!0),f(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: search_site_content then navigate_to_page with section_text when relevant — no permission ask. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit) when the user wants to submit.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),f(`error`),ee(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):ie.current&&ie.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let h=(0,l.useCallback)(async()=>{try{await ie.current?.endSession?.()}catch{}ie.current=null,te(!1),f(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),oe=d===`listening`||d===`speaking`,se=Oh[d]||Oh.idle,ce=Dh[d]||Dh.idle;return(0,u.jsxs)(`div`,{ref:ae,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,u.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[oe&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${se}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),oe&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${se}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,u.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:ce,border:`3px solid ${se}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:d===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${ce}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,u.jsx)(fn,{size:44,color:se})})]}),(0,u.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:d===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[d===`idle`&&`Starting voice session…`,d===`listening`&&`Listening…`,d===`speaking`&&`AI is speaking…`,d===`error`&&(p||`Error`)]}),ne.length>0&&(0,u.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:ne.map((e,t)=>(0,u.jsx)(`div`,{style:{display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,u.jsx)(`div`,{style:{maxWidth:`85%`,padding:`8px 12px`,borderRadius:`14px`,fontSize:`13px`,lineHeight:1.5,background:e.sender===`user`?`var(--flowengage-primary)`:`#f3f4f6`,color:e.sender===`user`?`#fff`:`#111827`},children:e.message})},t))}),(0,u.jsxs)(`button`,{onClick:h,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,u.jsx)(pn,{size:18}),`End Voice Session`]}),(0,u.jsx)(`style`,{children:`
|
|
319
319
|
@keyframes fe-orb-pulse {
|
|
320
320
|
0% { transform: scale(1); opacity: 0.6; }
|
|
321
321
|
50% { transform: scale(1.18); opacity: 0.15; }
|