@crestapps/ai-chat-ui 2.0.0-preview.260 → 2.0.0-preview.263
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/ai-chat.js +6 -2
- package/dist/ai-chat.js.map +1 -1
- package/dist/ai-chat.min.js +1 -1
- package/dist/ai-chat.min.js.map +1 -1
- package/dist/chat-interaction.js +6 -2
- package/dist/chat-interaction.js.map +1 -1
- package/dist/chat-interaction.min.js +2 -2
- package/dist/chat-interaction.min.js.map +1 -1
- package/dist/chat-markers.js +31 -0
- package/dist/chat-markers.js.map +1 -1
- package/dist/chat-markers.min.js +1 -1
- package/dist/chat-markers.min.js.map +1 -1
- package/package.json +1 -1
package/dist/ai-chat.min.js
CHANGED
|
@@ -77,5 +77,5 @@ References:
|
|
|
77
77
|
|
|
78
78
|
`),e.responseId&&(a=e.responseId),r+=e.content),t.rawContent=r,v(t,i),this.messages[s]=t,this.$nextTick(()=>{z(t),this.scrollToBottom()})},complete:()=>{this.processReferences(i,s),this.streamingFinished();let e=this.messages[s];e&&(e.isStreaming=!1),(!e||!e.content)&&this.hideTypingIndicator(),this.isConversationMode&&this.textToSpeechEnabled&&e&&e.content&&this.synthesizeSpeech(e.content),this.stream?.dispose(),this.stream=null},error:e=>{this.processReferences(i,s),this.streamingFinished();let t=this.messages[s];t&&(t.isStreaming=!1),this.hideTypingIndicator(),this.isNavigatingAway||this.addMessage(this.getServiceDownMessage()),this.stream?.dispose(),this.stream=null,console.error(`Stream error:`,e)}})};this.syncPageTools().then(l,l)}},collectRunContext(){let e=[];if(u.sendPageContext===!1)return e;try{e.push({description:u.aguiCurrentPageLabel,value:(document.title?document.title+` `:``)+`(`+window.location.pathname+window.location.search+`)`});let t=this.lastPageSelection;t&&t.text&&Date.now()-t.at<3e5&&e.push({description:u.aguiSelectedTextLabel,value:t.text.slice(0,1e3)})}catch(e){console.warn(`The page context could not be read.`,e)}for(let t of y._contextProviders)try{let n=[].concat(t()||[]);for(let t of n)t&&t.value&&e.push({description:String(t.description||`Detail`),value:typeof t.value==`string`?t.value:JSON.stringify(t.value)})}catch(e){console.warn(`An AG-UI context provider failed.`,e)}return e.slice(0,20)},trackPageSelection(){try{let e=window.getSelection?window.getSelection():null,t=e?String(e).trim():``;if(!t||this.chatContainer&&e.anchorNode&&this.chatContainer.contains(e.anchorNode))return;this.lastPageSelection={text:t,at:Date.now()}}catch{}},getSharedState(){let e=y._stateProvider;if(e&&typeof e.get==`function`)try{let t=e.get();if(t&&typeof t==`object`&&!Array.isArray(t))return this.sharedStateCache=O(t),t}catch(e){console.warn(`The AG-UI state provider failed.`,e)}},applySharedState(e){let t=e.type===`STATE_DELTA`?e.delta||[]:null,n=t?re(this.sharedStateCache??{},t):O(e.snapshot??{});this.sharedStateCache=n;let r=y._stateProvider;if(r&&typeof r.apply==`function`)try{r.apply(O(n),t)}catch(e){console.warn(`The AG-UI state provider could not apply the state.`,e)}document.dispatchEvent(new CustomEvent(`crestapps:agui-state`,{detail:{type:e.type,state:O(n),delta:t}}))},ensureAGUIMessage(e,t){return e.message||=(this.hideTypingIndicator(),this.messages.push({id:t||e.assistantMessageId||k(),role:`assistant`,title:e.title,content:``,htmlContent:``,isStreaming:!0,userRating:null,toolCalls:[],reasoning:``,appearance:e.appearance}),e.messageIndex=this.messages.length-1,this.messages[e.messageIndex]),e.message},refreshAGUIMessage(e){let t=e.message;t&&(t.rawContent=e.content,v(t,e.references),this.messages[e.messageIndex]=t,this.$nextTick(()=>{z(t),this.scrollToBottom()}))},handleAGUIEvent(e,t){if(t&&typeof t.type==`string`)switch(t.type){case`RUN_STARTED`:t.threadId&&t.threadId!==e.threadId&&t.threadId!==this.getSessionId()&&this.initializeSession(t.threadId,!0);break;case`CUSTOM`:this.handleAGUICustomEvent(e,t.name,t.value||{});break;case`TEXT_MESSAGE_START`:this.ensureAGUIMessage(e,t.messageId),e.textMessageId&&e.textMessageId!==t.messageId&&e.content&&(e.content+=`
|
|
79
79
|
|
|
80
|
-
`),e.textMessageId=t.messageId;break;case`TEXT_MESSAGE_CONTENT`:this.ensureAGUIMessage(e,t.messageId),e.content+=t.delta||``,this.refreshAGUIMessage(e);break;case`REASONING_MESSAGE_CONTENT`:{let n=this.ensureAGUIMessage(e,e.assistantMessageId);n.reasoning=(n.reasoning||``)+(t.delta||``),this.refreshAGUIMessage(e);break}case`TOOL_CALL_START`:{let n=this.ensureAGUIMessage(e,t.parentMessageId),r={id:t.toolCallId,name:t.toolCallName,arguments:``,result:``,status:`requested`,interruptId:null};n.toolCalls=n.toolCalls||[],n.toolCalls.push(r),e.toolCalls[t.toolCallId]=n.toolCalls[n.toolCalls.length-1],this.refreshAGUIMessage(e),t.toolCallName===`page_navigate`&&this.markRunContinuesOnNextPage(e.threadId||this.getSessionId());break}case`TOOL_CALL_ARGS`:{let n=e.toolCalls[t.toolCallId];n&&(n.arguments+=t.delta||``);break}case`TOOL_CALL_END`:this.refreshAGUIMessage(e);break;case`TOOL_CALL_RESULT`:{let n=e.toolCalls[t.toolCallId];n&&(n.result=typeof t.content==`string`?t.content:JSON.stringify(t.content??``),n.status=e.rejectedCallIds.has(t.toolCallId)?`rejected`:`completed`,this.refreshAGUIMessage(e));break}case`STATE_SNAPSHOT`:case`STATE_DELTA`:this.applySharedState(t);break;case`RUN_FINISHED`:{let n=t.outcome||{};if(n.type===`interrupt`&&Array.isArray(n.interrupts)){for(let t of n.interrupts){let n=t&&e.toolCalls[t.toolCallId];n&&(n.status=`awaitingApproval`,n.interruptId=t.id)}this.refreshAGUIMessage(e)}break}case`RUN_ERROR`:e.error=t.message||``,this.hideTypingIndicator(),t.code===`session_start_rejected`&&this.rejectPendingSessionRequest(t.message),this.isNavigatingAway||this.addMessage(this.getErrorMessage(t.message))}},handleAGUICustomEvent(e,t,n){switch(t){case`crestapps.assistant_message`:e.assistantMessageId=n.messageId,e.title=n.title,e.appearance=this.normalizeAssistantAppearance(n.appearance),e.message&&(e.message.title=e.title,e.message.appearance=e.appearance);break;case`crestapps.references`:for(let[t,r]of Object.entries(n.references||{}))e.references[t]=o(r)??{};this.refreshAGUIMessage(e);break;case`crestapps.message_replaced`:this.ensureAGUIMessage(e,n.messageId),e.content=n.content||``,this.refreshAGUIMessage(e);break;case`crestapps.tool_calls_resolved`:{let t=this.messages.find(e=>e.id===n.messageId);for(let t of C(n.toolCalls))t.status===`rejected`&&e.rejectedCallIds.add(t.id);t&&(t.toolCalls=C(n.toolCalls),t.rawContent=t.rawContent??t.content??``,v(t,t.references));break}}},finishAGUIRun(e){e.finished||(e.finished=!0,e.message?(this.processReferences(e.references,e.messageIndex),e.message.isStreaming=!1):this.hideTypingIndicator(),this.streamingFinished(),this.isConversationMode&&this.textToSpeechEnabled&&e.message&&e.message.content&&this.synthesizeSpeech(e.message.content),this.stream?.dispose(),this.stream=null,this.aguiRun===e&&(this.aguiRun=null))},streamAGUIRun(e,t,n,r,i){let a=!!(i&&i.continueRun);t&&M(null),this.stream&&=(this.stream.dispose(),null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;let o={threadId:``,message:null,messageIndex:-1,assistantMessageId:null,title:null,appearance:null,content:``,references:{},textMessageId:null,toolCalls:{},rejectedCallIds:new Set,finished:!1,error:null};this.aguiRun=o;let s=()=>{o.threadId=this.getSessionId()||``;let i={threadId:o.threadId,runId:k(),messages:t?[{id:k(),role:`user`,content:t}]:[],tools:[],context:this.collectRunContext(),forwardedProps:{profileId:e,sessionProfileId:n||null}};a&&(i.forwardedProps.continueRun=!0,i.forwardedProps.continuePage=(document.title?document.title+` `:``)+`(`+window.location.pathname+window.location.search+`)`);let s=this.getSharedState();s!==void 0&&(i.state=s),r&&r.length&&(i.resume=r),this.stream=this.connection.stream(`RunAgent`,i).subscribe({next:e=>this.handleAGUIEvent(o,e),complete:()=>this.finishAGUIRun(o),error:i=>{let s=String(i&&i.message||i||``);!r&&!a&&!o.message&&s.includes(`Method does not exist`)?(this.aguiDisabled=!0,this.stream=null,this.hideTypingIndicator(),this.streamingFinished(),this.streamMessage(e,t,n)):(this.finishAGUIRun(o),this.isNavigatingAway||this.addMessage(this.getServiceDownMessage()),console.error(`Stream error:`,i))}})};(this.pendingSessionPromise?this.pendingSessionPromise.catch(()=>null):Promise.resolve()).then(()=>this.syncPageTools()).then(s,s)},answerApproval(e,t){let n=null,r=null;for(let t of this.messages){let i=(t.toolCalls||[]).find(t=>t.interruptId===e);if(i){n=t,r=i;break}}if(!r||r.status!==`awaitingApproval`||this.stream)return;r.status=t?`approved`:`rejected`,r.decided=!0,n.rawContent=n.rawContent??n.content??``,v(n,n.references);let i=n.toolCalls.filter(e=>e.interruptId);if(i.some(e=>e.status===`awaitingApproval`))return;let a=i.filter(e=>e.decided).map(e=>({interruptId:e.interruptId,status:`resolved`,payload:{approved:e.status===`approved`}}));this.streamAGUIRun(this.getProfileId(),null,null,a)},markRunContinuesOnNextPage(e){if(!e)return;let t=j();M({sessionId:e,depth:(t&&t.sessionId===e?t.depth:0)+1,at:Date.now()})},continueRunOnThisPage(e){let t=j();if(!t||!e||t.sessionId!==e.sessionId||this.aguiDisabled)return;if(Date.now()-t.at>12e4){M(null),this.hideTypingIndicator();return}let n=e.messages||[],r=n.length?n[n.length-1]:null;!r||r.role!==`assistant`||!r.continuesOnNextPage?!r||r.role===`user`?this.showTypingIndicator():M(null):t.depth>5?M(null):(M({sessionId:t.sessionId,depth:t.depth,at:0}),!this.stream&&(r.continuesOnNextPage=!1,this.streamAGUIRun(this.getProfileId(),null,null,null,{continueRun:!0})))},getServiceDownMessage(){return{role:`assistant`,content:`Our service is currently unavailable. Please try again later. We apologize for the inconvenience.`,htmlContent:``}},getErrorMessage(e){return{role:`assistant`,content:typeof e==`string`&&e.trim()?e:`Something went wrong. Please try again.`,htmlContent:``}},processReferences(e,t){if(e=c(e),Object.keys(e).length){let n=this.messages[t];n.rawContent=n.rawContent??n.content??``,v(n,e),this.messages[t]=n,this.$nextTick(()=>{z(n),this.scrollToBottom()})}},streamingStarted(){var e=this.buttonElement.getAttribute(`data-stop-icon`);e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&this.inputElement.setAttribute(`disabled`,`disabled`)},streamingFinished(){var e=this.buttonElement.getAttribute(`data-start-icon`);if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&(this.inputElement.removeAttribute(`disabled`),this.inputElement.focus()),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(`.ai-streaming-icon`),n=0;n<t.length;n++)t[n].classList.remove(`ai-streaming-icon`),t[n].classList.add(`ai-bot-icon`);for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1)},handleExternalTtsStop(e){e?.detail?.sourceId!==this.ttsInstanceId&&this.stopAudio(!1)},updateTtsPlaybackButtons(){this.chatContainer&&this.chatContainer.querySelectorAll(`[data-tts-message-index]`).forEach(e=>{var t=Number(e.getAttribute(`data-tts-message-index`))===this.ttsPlayingMessageIndex;e.classList.toggle(`tts-playing`,t),e.setAttribute(`title`,t?`Pause audio`:`Read aloud`)})},updateCopyButtons(){this.chatContainer&&this.chatContainer.querySelectorAll(`[data-copy-message-index]`).forEach(e=>{var t=Number(e.getAttribute(`data-copy-message-index`))===this.copiedMessageIndex,n=t?`<i class="fa-solid fa-check"></i>`:`<i class="fa-solid fa-copy"></i>`;e.classList.toggle(`text-success`,t),e.classList.toggle(`text-secondary`,!t),e.setAttribute(`title`,t?this.copiedTitle:this.copyTitle),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))})},setCopyButtonState(e,t){if(e){var n=t?`<i class="fa-solid fa-check"></i>`:`<i class="fa-solid fa-copy"></i>`;e.classList.toggle(`text-success`,t),e.classList.toggle(`text-secondary`,!t),e.setAttribute(`title`,t?this.copiedTitle:this.copyTitle),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))}},synthesizeSpeech(e,t){this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=t===void 0?-1:t,this.connection.invoke(`SynthesizeSpeech`,this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(e=>{console.error(`TTS synthesis error:`,e),this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this._ttsCacheIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())}))},toggleMessageTts(e,t){this.ttsPlayingMessageIndex===t?this.stopAudio():(this.stopAudio(!1),window.dispatchEvent(new CustomEvent(`crestapps-ai-chat-stop-tts`,{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=t,this.$nextTick(()=>this.updateTtsPlaybackButtons()),this.ttsAudioCache[t]?this.playAudioBlob(this.ttsAudioCache[t]):this.synthesizeSpeech(e.content,t))},playCollectedAudio(){if(this.audioChunks.length===0){!this.currentAudioElement&&this.audioPlayQueue.length===0&&(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons()));return}let e=this.audioChunks.reduce((e,t)=>e+t.length,0),t=new Uint8Array(e),n=0;for(let e of this.audioChunks)t.set(e,n),n+=e.length;this.audioChunks=[];let r=new Blob([t],{type:`audio/mp3`});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=r,this._ttsCacheIndex=-1),this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)},playAudioBlob(e){let t=URL.createObjectURL(e),n=new Audio(t);this.currentAudioUrl=t,this.currentAudioElement=n,this.isPlayingAudio=!0,n.addEventListener(`ended`,()=>{this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.playNextInQueue()}),n.addEventListener(`error`,()=>{this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.playNextInQueue()}),n.play().catch(e=>{console.error(`Audio playback error:`,e),this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())})},playNextInQueue(){if(this.audioPlayQueue.length>0){var e=this.audioPlayQueue.shift();this.playAudioBlob(e)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons()),this.conversationModeOnAudioEnded()},stopAudio(){this.currentAudioElement&&=(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,null),this.currentAudioUrl&&=(URL.revokeObjectURL(this.currentAudioUrl),null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())},voiceSettingsElement(){var e=this.conversationButton&&this.conversationButton.nextElementSibling;return e&&e.id===`realtime-audio-settings`?e:null},setVoiceSessionLive(e){this.inputElement&&(this.inputElement.hidden=e),this.buttonElement&&(this.buttonElement.hidden=e),this.conversationButton&&this.conversationButton.classList.toggle(`flex-grow-1`,e);var t=this.voiceSettingsElement();t&&(t.hidden=!e);var n=this.realtimeHintElement;n&&n.classList.toggle(`d-none`,!e)},toggleConversationMode(){this.realtimeEnabled?this.realtimeController&&this.realtimeController.toggle():this.isConversationMode?this.stopConversationMode():this.startConversationMode()},forceStopActiveVoice(){this.isConversationMode&&(this.realtimeEnabled?this.stopRealtimeConversation():this.stopConversationMode())},startRealtimeConversation(){this.realtimeController&&this.realtimeController.start()},stopRealtimeConversation(){this.realtimeController&&this.realtimeController.stop()},setupRealtimeController(e){if(!this.realtimeController&&this.conversationButton){if(!window.CoreAIRealtime||typeof window.CoreAIRealtime.attach!=`function`)console.error(`realtime-audio.js is not loaded; realtime voice is unavailable on this page.`);else{var t=this;this.realtimeController=window.CoreAIRealtime.attach({connection:this.connection,ensureConnected:function(){return t.ensureConnectionStarted().then(function(e){if(!e)throw Error(`The chat connection is not available.`);return e})},sendStart:function(e,n,r,i,a,o){t.connection.send(`StartRealtimeConversation`,t.getProfileId(),t.getSessionId()||``,e,n,r,i,a,o)},webRtcEnabled:this.realtimeWebRtcEnabled,sendStartWebRtc:function(e,n,r,i,a,o){t.connection.send(`StartRealtimeWebRtc`,t.getProfileId(),t.getSessionId()||``,e,n,r,i,a,o)},webRtcIceServers:this.realtimeWebRtcIceServers||void 0,voiceName:this.realtimeVoiceName||``,getVoiceName:function(){return t.realtimeVoiceName||``},realtimeEnabled:!0,selectors:{realtimeButton:e.conversationButtonElementSelector,micButton:e.micButtonElementSelector},onSessionStateChanged:function(e){t.setVoiceSessionLive(e)},onActivate:function(){t.isConversationMode=!0,t._conversationAssistantMessage=null,t._conversationPartialMessage=null,t.removeNotification(`conversation-ended`)},onDeactivate:function(){t.isConversationMode=!1,t.finishRealtimeConversationCleanup()},onUserTurnPending:function(e){t.addRealtimePendingTurn(e)},onUserTurnDropped:function(e){t.dropRealtimePendingTurn(e)}})}}},finishRealtimeConversationCleanup(){if(this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:`conversation-ended`,content:`Conversation ended.`,icon:`fa-solid fa-circle-check`,dismissible:!0,autoDismissMs:5e3})},addRealtimePendingTurn(e){if(e){this._realtimePendingTurns=this._realtimePendingTurns||{};var t=this.messages.length;this.addMessage({role:`user`,content:``,isPartial:!0}),this._realtimePendingTurns[e]=this.messages[t]}},fillRealtimePendingTurn(e,t){if(e){if(t){var n=t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`);e.content=t,e.htmlContent=`<p>`+n+`</p>`,e.isPartial=!1}else{var r=this.messages.indexOf(e);r>=0&&this.messages.splice(r,1)}}},dropRealtimePendingTurn(e){if(e&&this._realtimePendingTurns){var t=this._realtimePendingTurns[e];if(t){delete this._realtimePendingTurns[e];var n=this.messages.indexOf(t);n>=0&&this.messages.splice(n,1)}}},startConversationMode(){this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript=``,this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification(`conversation-ended`),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(e=>{this._conversationSubject=new signalR.Subject,this._conversationStream=e;var t=.12;this._conversationCapture=this._createPcmCapture(e,(e,n)=>{this.isPlayingAudio&&n>=t&&this.stopAudio();try{this._conversationSubject.next(e)}catch{}});var n=this.getProfileId(),r=this.getSessionId()||``,i=navigator.language||document.documentElement.lang||`en-US`,a=this._conversationCapture&&this._conversationCapture.sampleRate||16e3;this.connection.send(`StartConversation`,n,r,this._conversationSubject,`audio/pcm;rate=`+a,i),this.isRecording=!0}).catch(e=>{console.error(`Microphone access denied:`,e),this.isConversationMode=!1,this.updateConversationButton()}))},stopConversationMode(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke(`StopConversation`).catch(function(){}),this.isRecording){if(this._stopPcmCapture(this._conversationCapture),this._conversationCapture=null,this._conversationSubject)try{this._conversationSubject.complete()}catch{}this.isRecording=!1}if(this.stopAudio(),this._conversationPartialTranscript=``,this._conversationPartialMessage=null,this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:`conversation-ended`,content:`Conversation ended.`,icon:`fa-solid fa-circle-check`,dismissible:!0,autoDismissMs:5e3})}},updateConversationButton(){if(this.conversationButton){if(this.isConversationMode){this.conversationButton.classList.add(`active`,`btn-primary`),this.conversationButton.classList.remove(`btn-dark`,`btn-outline-dark`,`btn-outline-secondary`),this.conversationButton.title=this.conversationButton.getAttribute(`data-end-title`)||`End Conversation`;var e=this.conversationButton.getAttribute(`data-end-html`);e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove(`active`,`btn-primary`),this.conversationButton.classList.remove(`btn-dark`,`btn-outline-secondary`),this.conversationButton.classList.add(`btn-outline-dark`),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute(`data-start-title`)||`Start Conversation`;var t=this.conversationButton.getAttribute(`data-start-html`);t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}}},conversationModeSendPrompt(){},conversationModeOnAudioEnded(){},generatePrompt(e){if(!e){console.error(`The element paramter is required.`);return}let t=e.getAttribute(`data-profile-id`),n=this.getSessionId(),r=this.getProfileId();!t||!n?console.error(`The given element is missing data-profile-id or the session has not yet started.`):this.streamMessage(t,null,r)},createSessionUrl(e,t,n){let r=e.toLowerCase().startsWith(`http`)?e:window.location.origin+e,i=new URL(r);return i.searchParams.set(t,n),i.toString()},showTypingIndicator(){this.addMessage({role:`indicator`,htmlContent:u.indicatorTemplate})},hideTypingIndicator(){let e=this.messages.length;return this.messages=this.messages.filter(e=>e.role!==`indicator`),e-this.messages.length},receiveNotification(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(t=>t.type===e.type);t>=0?this.notifications.splice(t,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.$nextTick(()=>{this.scrollToBottom()})}},updateNotification(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(t=>t.type===e.type);t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e))}},scheduleNotificationDismiss(e){!e||!e.type||!e.autoDismissMs||e.autoDismissMs<=0||(this.notificationDismissTimers[e.type]=setTimeout(()=>{this.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(t=>t.type!==e)},dismissNotification(e){this.removeNotification(e)},handleNotificationAction(e,t){if(this.connection){var n=this.getSessionId();this.connection.invoke(`HandleNotificationAction`,n,e,t).catch(function(e){console.error(`Error handling notification action:`,e)})}},scrollToBottom(){this.autoScroll&&setTimeout(()=>{this.chatContainer.scrollTop=this.chatContainer.scrollHeight-this.chatContainer.clientHeight},50)},handleUserInput(e){this.prompt=e.target.value},getProfileId(){return this.inputElement?this.inputElement.getAttribute(`data-profile-id`):null},setSessionId(e){this.inputElement&&this.inputElement.setAttribute(`data-session-id`,e||``)},resetSession(){this.forceStopActiveVoice(),this.stopRecording(),this.rejectPendingSessionRequest(`Session was reset.`),this.setSessionId(``),this.isSessionStarted=!1,this.sessionRating=null,this.messages=[],this.documents=[],u.initialPrompt?this.addMessage({role:`assistant`,content:u.initialPrompt}):this.showPlaceholder(),f&&typeof f.onSessionReset==`function`&&f.onSessionReset(this,u)},startNewSession(){if(!this.applyOrchestratorAvailability())return;let e=this.getProfileId();e&&this.connection&&(this.forceStopActiveVoice(),this.requestNewSession(e).catch(e=>console.error(e)))},async ensureSessionForDocuments(e){return this.getSessionId()||(!e||!this.connection?null:await this.requestNewSession(e))},requestNewSession(e){return this.pendingSessionPromise?this.pendingSessionPromise:!e||!this.connection?Promise.resolve(null):(this.pendingSessionPromise=new Promise((e,t)=>{this.pendingSessionResolver=e,this.pendingSessionRejector=t,this.pendingSessionTimeoutId=window.setTimeout(()=>{this.rejectPendingSessionRequest(`Timed out while creating a chat session.`)},15e3)}),this.connection.invoke(`StartSession`,e,null).catch(e=>{this.rejectPendingSessionRequest(e)}),this.pendingSessionPromise)},resolvePendingSessionRequest(e){this.pendingSessionResolver&&this.pendingSessionResolver(e),this.clearPendingSessionRequest()},rejectPendingSessionRequest(e){this.pendingSessionRejector&&this.pendingSessionRejector(e),this.clearPendingSessionRequest()},clearPendingSessionRequest(){this.pendingSessionTimeoutId&&window.clearTimeout(this.pendingSessionTimeoutId),this.pendingSessionPromise=null,this.pendingSessionResolver=null,this.pendingSessionRejector=null,this.pendingSessionTimeoutId=null},initializeApp(){if(this.inputElement=document.querySelector(u.inputElementSelector),this.buttonElement=document.querySelector(u.sendButtonElementSelector),this.chatContainer=document.querySelector(u.chatContainerElementSelector),this.placeholder=document.querySelector(u.placeholderElementSelector),!this.inputElement||!this.buttonElement||!this.chatContainer||!this.placeholder)return console.error(`AI chat app could not initialize because one or more required elements were not found.`,{inputElementSelector:u.inputElementSelector,sendButtonElementSelector:u.sendButtonElementSelector,chatContainerElementSelector:u.chatContainerElementSelector,placeholderElementSelector:u.placeholderElementSelector}),!1;this.applyOrchestratorAvailability(),this.chatContainer.addEventListener(`click`,e=>{let t=e.target&&e.target.closest?e.target.closest(`[data-agui-interrupt]`):null;t&&this.chatContainer.contains(t)&&(e.preventDefault(),this.answerApproval(t.getAttribute(`data-agui-interrupt`),t.getAttribute(`data-agui-approved`)===`true`))}),document.addEventListener(`selectionchange`,()=>this.trackPageSelection());let e=this.getSessionId();if(!d&&e&&this.loadSession(e),u.sessionDocumentsEnabled&&u.documentBarSelector&&(this.documentBar=document.querySelector(u.documentBarSelector),this.documentBar)){this.renderDocumentBar();var t=document.createElement(`input`);t.type=`file`,t.id=`ai-chat-doc-input`,t.className=`d-none`,t.multiple=!0,u.allowedExtensions&&(t.accept=u.allowedExtensions),t.addEventListener(`change`,e=>this.handleFileInputChange(e)),this.documentBar.parentElement.appendChild(t);var n=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;n&&(n.addEventListener(`dragover`,e=>this.handleDragOver(e)),n.addEventListener(`dragleave`,e=>this.handleDragLeave(e)),n.addEventListener(`drop`,e=>this.handleDrop(e)))}this.chatContainer.addEventListener(`scroll`,()=>{if(!this.stream)return;let e=this.chatContainer.scrollHeight-this.chatContainer.clientHeight-this.chatContainer.scrollTop<=30;this.autoScroll=e}),this.inputElement.addEventListener(`keydown`,e=>{this.stream==null&&e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.buttonElement.click())}),this.inputElement.addEventListener(`input`,e=>{this.handleUserInput(e),e.target.value.trim()?this.buttonElement.removeAttribute(`disabled`):this.buttonElement.setAttribute(`disabled`,!0)}),this.buttonElement.addEventListener(`click`,()=>{if(this.stream!=null){if(this.stream.dispose(),this.stream=null,this.streamingFinished(),this.hideTypingIndicator(),this.messages.length>0){let e=this.messages[this.messages.length-1];e.role===`assistant`&&!e.content?this.messages.pop():e.isStreaming&&=!1}}else this.sendMessage()});let r=document.getElementsByClassName(`profile-generated-prompt`);for(var i=0;i<r.length;i++)r[i].addEventListener(`click`,e=>{e.preventDefault(),this.generatePrompt(e.target)});let a=document.getElementsByClassName(`chat-session-history-item`);for(i=0;i<a.length;i++)a[i].addEventListener(`click`,e=>{e.preventDefault();var t=e.target.getAttribute(`data-session-id`);t?(this.loadSession(t),this.showChatScreen()):console.error(`an element with the class chat-session-history-item with no data-session-id set.`)});let o=Array.isArray(u.messages)?u.messages:[];for(let e=0;e<o.length;e++)this.addMessage(o[e]);return this.messages.length===0&&u.initialPrompt&&this.addMessage({role:`assistant`,content:u.initialPrompt}),this.$nextTick(()=>{this.refreshAllFeedbackIcons()}),this.chatContainer&&this.chatContainer.addEventListener(`click`,e=>{var t=e.target.closest(`.ai-code-copy-btn`);if(t){var n=t.closest(`.ai-code-block`)||t.closest(`pre`);if(n){var r=n.querySelector(`code`);r&&(navigator.clipboard.writeText(r.textContent),t.innerHTML=`<i class="fa-solid fa-check"></i> `+(u.codeCopiedText||`Copied!`),setTimeout(()=>{t.innerHTML=`<i class="fa-regular fa-copy"></i>`},2e3))}}}),this.speechToTextEnabled&&u.micButtonElementSelector&&(this.micButton=document.querySelector(u.micButtonElementSelector),this.micButton&&(this.micButton.style.display=``,this.micButton.addEventListener(`click`,()=>{this.toggleRecording()}))),(this.conversationModeEnabled||this.realtimeEnabled)&&u.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(u.conversationButtonElementSelector),this.conversationButton&&(this.realtimeEnabled?(this.setupRealtimeController(u),this.setVoiceSessionLive(!1)):this.conversationButton.addEventListener(`click`,()=>{this.toggleConversationMode()}))),!0},loadSession(e){this.connection.invoke(`LoadSession`,e).catch(e=>console.error(e))},reloadCurrentSession(){var e=this.getSessionId();e&&this.loadSession(e)},initializeSession(e,t){if(this.isSessionStarted&&!t)e&&this.getSessionId()===e&&this.resolvePendingSessionRequest(e);else if(this.fireEvent(new CustomEvent(`initializingSessionCoreAIChat`,{detail:{sessionId:e}})),this.setSessionId(e),this.isSessionStarted=!0,this.resolvePendingSessionRequest(e),f&&typeof f.onSessionInitialized==`function`&&f.onSessionInitialized(this,e,u),!d&&e&&u.sessionUrlTemplate&&typeof history<`u`&&history.replaceState){var n=u.sessionUrlTemplate.replace(`{sessionId}`,encodeURIComponent(e));history.replaceState(null,``,n)}},getSessionId(){let e=this.inputElement?this.inputElement.getAttribute(`data-session-id`):null;return!e&&f&&typeof f.resolveSessionId==`function`&&(e=f.resolveSessionId(this,u)),e},clearCopiedMessageState(){this.copyResetTimeoutId&&=(window.clearTimeout(this.copyResetTimeoutId),null),this.activeCopyButton&&=(this.setCopyButtonState(this.activeCopyButton,!1),null),this.copiedMessageIndex=-1},copyResponse(e,t,n){let r=e&&typeof e==`object`?e.copyContent??e.content??``:e??``,i=n?.currentTarget||n?.target?.closest?.(`[data-copy-message-index]`)||null;navigator.clipboard.writeText(r).then(()=>{this.clearCopiedMessageState(),this.copiedMessageIndex=typeof t==`number`?t:-1,this.activeCopyButton=i,i?this.setCopyButtonState(i,!0):this.$nextTick(()=>this.updateCopyButtons()),this.copyResetTimeoutId=window.setTimeout(()=>{this.clearCopiedMessageState(),this.$nextTick(()=>this.updateCopyButtons())},Number(u.copyResetDelayMs)||2e3)}).catch(e=>console.error(`Failed to copy response:`,e))},updateFeedbackIcons(e,t){if(e){var n=e.querySelector(`.rate-up-btn`),r=e.querySelector(`.rate-down-btn`);if(n){var i=t===!0?`fa-solid fa-thumbs-up`:`fa-regular fa-thumbs-up`,a=document.createElement(`span`);a.className=i,a.style.fontSize=`0.9rem`,n.textContent=``,n.appendChild(a)}if(r){var o=t===!1?`fa-solid fa-thumbs-down`:`fa-regular fa-thumbs-down`,s=document.createElement(`span`);s.className=o,s.style.fontSize=`0.9rem`,r.textContent=``,r.appendChild(s)}}},refreshAllFeedbackIcons(){for(var e=this.$el.querySelectorAll(`.ai-chat-message-assistant-feedback`),t=0;t<e.length;t++){var n=e[t].getAttribute(`data-message-id`),r=this.messages.find(e=>e.id===n);r&&this.updateFeedbackIcons(e[t],r.userRating)}},rateMessage(e,t){var n=this.getSessionId();if(n&&e.id&&this.connection){var r=e.userRating===t?null:t;e.userRating=r;var i=this.$el.querySelector(`.ai-chat-message-assistant-feedback[data-message-id="`+e.id+`"]`);this.updateFeedbackIcons(i,r),r!==null&&i&&setTimeout(()=>{var e=t?`.rate-up-btn`:`.rate-down-btn`,n=i.querySelector(e);n&&(n.classList.remove(`spark-effect`),n.offsetWidth,n.classList.add(`spark-effect`),n.addEventListener(`animationend`,function e(){n.removeEventListener(`animationend`,e),n.classList.remove(`spark-effect`)}))},50),this.connection.invoke(`RateMessage`,n,e.id,t).catch(function(e){console.error(`Failed to rate message:`,e)})}}},watch:{documents:{handler(){this.renderDocumentBar(),f&&typeof f.onDocumentsChanged==`function`&&f.onDocumentsChanged(this,this.documents,u)},deep:!0},isUploading(){this.renderDocumentBar()},isDocumentOperationPending(){this.renderDocumentBar()},isPlayingAudio(){},copiedMessageIndex(){this.$nextTick(()=>this.updateCopyButtons())},isConversationMode(e){this.micButton&&(this.micButton.style.display=e?`none`:this.speechToTextEnabled?``:`none`),this.realtimeEnabled||this.setVoiceSessionLive(e)}},mounted(){(async()=>{await this.startConnection(),this.initializeApp()&&d&&f&&typeof f.onMounted==`function`&&f.onMounted(this,u),this.$nextTick(()=>{this.updateCopyButtons(),i(this.$el),this.fontAwesomeObserver=a(this.$el)})})(),window.addEventListener(`beforeunload`,this.handleBeforeUnload),window.addEventListener(`crestapps-ai-chat-stop-tts`,this.handleExternalTtsStop)},beforeUnmount(){window.removeEventListener(`beforeunload`,this.handleBeforeUnload),window.removeEventListener(`crestapps-ai-chat-stop-tts`,this.handleExternalTtsStop),this.fontAwesomeObserver&&=(this.fontAwesomeObserver.disconnect(),null),this.clearCopiedMessageState(),this.stopAudio(!1),this.stream&&=(this.stream.dispose(),null),this.connection&&this.connection.stop(),f&&typeof f.onBeforeUnmount==`function`&&f.onBeforeUnmount(this,u)},template:u.messageTemplate},m=Vue.createApp(p).mount(u.appElementSelector);return f&&typeof f.attach==`function`&&f.attach(m,u),m},q=`[data-coreai-chat-config],[data-coreai-chat-app-element-selector]`;function J(e,t){let n=e.getAttribute(t);return n===null||n===``?null:n}function oe(e){if(e==null)return null;if(typeof e==`boolean`)return e;let t=String(e).trim().toLowerCase();return t===`true`||t!==`false`&&null}function Y(e,t,n){let r=J(e,t);if(!r)return null;try{return JSON.parse(r)}catch(e){return console.error(`Failed to parse `+n+` JSON.`,e),null}}function se(e,t){let n=t||{};if(e.hasAttribute(`data-coreai-chat-widget-container-selector`)&&n.allowWidgetHost!==!0)return null;let r=J(e,`data-coreai-chat-app-element-selector`);if(!r)return null;let i={signalRHubUrl:J(e,`data-coreai-chat-signalr-hub-url`),appElementSelector:r,chatContainerElementSelector:J(e,`data-coreai-chat-container-element-selector`),inputElementSelector:J(e,`data-coreai-chat-input-element-selector`),sendButtonElementSelector:J(e,`data-coreai-chat-send-button-element-selector`),placeholderElementSelector:J(e,`data-coreai-chat-placeholder-element-selector`),messages:Y(e,`data-coreai-chat-messages`,`CoreAI chat messages`)??void 0,chatMode:J(e,`data-coreai-chat-mode`),micButtonElementSelector:J(e,`data-coreai-chat-mic-button-element-selector`),conversationButtonElementSelector:J(e,`data-coreai-chat-conversation-button-element-selector`),realtimeHintElementSelector:J(e,`data-coreai-chat-realtime-hint-element-selector`),ttsVoiceName:J(e,`data-coreai-chat-tts-voice-name`),realtimeVoiceName:J(e,`data-coreai-chat-realtime-voice-name`),documentBarSelector:J(e,`data-coreai-chat-document-bar-selector`),uploadDocumentUrl:J(e,`data-coreai-chat-upload-document-url`),removeDocumentUrl:J(e,`data-coreai-chat-remove-document-url`),allowedExtensions:J(e,`data-coreai-chat-allowed-extensions`),supportedExtensionsText:J(e,`data-coreai-chat-supported-extensions-text`),existingDocuments:Y(e,`data-coreai-chat-existing-documents`,`CoreAI chat existing documents`)??void 0,initialPrompt:J(e,`data-coreai-chat-initial-prompt`),sessionUrlTemplate:J(e,`data-coreai-chat-session-url-template`),userLabel:J(e,`data-coreai-chat-user-label`),assistantLabel:J(e,`data-coreai-chat-assistant-label`),assistantAvatarUrl:J(e,`data-coreai-chat-assistant-avatar-url`),copyTitle:J(e,`data-coreai-chat-copy-title`),copiedTitle:J(e,`data-coreai-chat-copied-title`)},a={metricsEnabled:`data-coreai-chat-metrics-enabled`,textToSpeechEnabled:`data-coreai-chat-text-to-speech-enabled`,sessionDocumentsEnabled:`data-coreai-chat-session-documents-enabled`,singleResponseMode:`data-coreai-chat-single-response-mode`,realtimeEnabled:`data-coreai-chat-realtime-enabled`,realtimeWebRtcEnabled:`data-coreai-chat-realtime-webrtc-enabled`};return Object.keys(a).forEach(t=>{let n=oe(J(e,a[t]));n!==null&&(i[t]=n)}),U(i)}function X(e,t){let n=Y(e,`data-coreai-chat-config`,`CoreAI chat config`),r=se(e,t);return!n&&!r?null:Object.assign({},n||{},r||{})}function Z(e){if(!e||e.dataset.coreAiChatInitialized===`true`)return e&&e.__coreAIChatApp||null;let t=X(e);if(!t)return null;let n=K(t);return n?(e.dataset.coreAiChatInitialized=`true`,e.__coreAIChatApp=n,n):null}function Q(e){e&&typeof e.querySelectorAll==`function`&&(typeof e.matches==`function`&&e.matches(q)&&Z(e),e.querySelectorAll(q).forEach(Z))}function $(){Q(document),typeof MutationObserver<`u`&&new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e&&e.nodeType===1&&Q(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,$,{once:!0}):$(),{initialize:K,initializeFromElement:Z,buildConfigFromElement:X}}(),document.addEventListener(`click`,function(e){let t=e.target.closest(`.download-chart-btn`);if(!t)return;let n=t.getAttribute(`data-chart-id`),r=n?document.getElementById(n):null;if(!r){console.error(`Chart canvas not found:`,n);return}let i=document.createElement(`a`);i.download=`chart-`+n+`.png`,i.href=r.toDataURL(`image/png`),i.click()}),document.addEventListener(`click`,function(e){let t=e.target.closest(`.ai-download-image`);if(!t)return;let n=t.closest(`.generated-image-container`)?.querySelector(`img`);if(!n)return;let r=n.src;r&&r.startsWith(`data:`)&&(e.preventDefault(),fetch(r).then(function(e){return e.blob()}).then(function(e){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t.getAttribute(`download`)||`generated-image.png`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error(`Failed to download image:`,e)}))})})();
|
|
80
|
+
`),e.textMessageId=t.messageId;break;case`TEXT_MESSAGE_CONTENT`:this.ensureAGUIMessage(e,t.messageId),e.content+=t.delta||``,this.refreshAGUIMessage(e);break;case`REASONING_MESSAGE_CONTENT`:{let n=this.ensureAGUIMessage(e,e.assistantMessageId);n.reasoning=(n.reasoning||``)+(t.delta||``),this.refreshAGUIMessage(e);break}case`TOOL_CALL_START`:{let n=this.ensureAGUIMessage(e,t.parentMessageId),r={id:t.toolCallId,name:t.toolCallName,arguments:``,result:``,status:`requested`,interruptId:null};n.toolCalls=n.toolCalls||[],n.toolCalls.push(r),e.toolCalls[t.toolCallId]=n.toolCalls[n.toolCalls.length-1],this.refreshAGUIMessage(e),t.toolCallName===`page_navigate`&&this.markRunContinuesOnNextPage(e.threadId||this.getSessionId());break}case`TOOL_CALL_ARGS`:{let n=e.toolCalls[t.toolCallId];n&&(n.arguments+=t.delta||``);break}case`TOOL_CALL_END`:this.refreshAGUIMessage(e);break;case`TOOL_CALL_RESULT`:{let n=e.toolCalls[t.toolCallId];n&&(n.result=typeof t.content==`string`?t.content:JSON.stringify(t.content??``),n.status=e.rejectedCallIds.has(t.toolCallId)?`rejected`:`completed`,this.refreshAGUIMessage(e));break}case`STATE_SNAPSHOT`:case`STATE_DELTA`:this.applySharedState(t);break;case`RUN_FINISHED`:{let n=t.outcome||{};if(n.type===`interrupt`&&Array.isArray(n.interrupts)){for(let t of n.interrupts){let n=t&&e.toolCalls[t.toolCallId];n&&(n.status=`awaitingApproval`,n.interruptId=t.id)}this.refreshAGUIMessage(e)}break}case`RUN_ERROR`:e.error=t.message||``,this.hideTypingIndicator(),t.code===`session_start_rejected`&&this.rejectPendingSessionRequest(t.message),this.isNavigatingAway||this.addMessage(this.getErrorMessage(t.message))}},handleAGUICustomEvent(e,t,n){switch(t){case`crestapps.assistant_message`:e.assistantMessageId=n.messageId,e.title=n.title,e.appearance=this.normalizeAssistantAppearance(n.appearance),e.message&&(e.message.title=e.title,e.message.appearance=e.appearance);break;case`crestapps.references`:for(let[t,r]of Object.entries(n.references||{}))e.references[t]=o(r)??{};this.refreshAGUIMessage(e);break;case`crestapps.message_replaced`:this.ensureAGUIMessage(e,n.messageId),e.content=n.content||``,this.refreshAGUIMessage(e);break;case`crestapps.tool_calls_resolved`:{let t=this.messages.find(e=>e.id===n.messageId);for(let t of C(n.toolCalls))t.status===`rejected`&&e.rejectedCallIds.add(t.id);t&&(t.toolCalls=C(n.toolCalls),t.rawContent=t.rawContent??t.content??``,v(t,t.references));break}}},finishAGUIRun(e){e.finished||(e.finished=!0,e.message?(this.processReferences(e.references,e.messageIndex),e.message.isStreaming=!1):this.hideTypingIndicator(),this.streamingFinished(),this.isConversationMode&&this.textToSpeechEnabled&&e.message&&e.message.content&&this.synthesizeSpeech(e.message.content),this.stream?.dispose(),this.stream=null,this.aguiRun===e&&(this.aguiRun=null))},streamAGUIRun(e,t,n,r,i){let a=!!(i&&i.continueRun);t&&M(null),this.stream&&=(this.stream.dispose(),null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;let o={threadId:``,message:null,messageIndex:-1,assistantMessageId:null,title:null,appearance:null,content:``,references:{},textMessageId:null,toolCalls:{},rejectedCallIds:new Set,finished:!1,error:null};this.aguiRun=o;let s=()=>{o.threadId=this.getSessionId()||``;let i={threadId:o.threadId,runId:k(),messages:t?[{id:k(),role:`user`,content:t}]:[],tools:[],context:this.collectRunContext(),forwardedProps:{profileId:e,sessionProfileId:n||null}};a&&(i.forwardedProps.continueRun=!0,i.forwardedProps.continuePage=(document.title?document.title+` `:``)+`(`+window.location.pathname+window.location.search+`)`);let s=this.getSharedState();s!==void 0&&(i.state=s),r&&r.length&&(i.resume=r),this.stream=this.connection.stream(`RunAgent`,i).subscribe({next:e=>this.handleAGUIEvent(o,e),complete:()=>this.finishAGUIRun(o),error:i=>{let s=String(i&&i.message||i||``);!r&&!a&&!o.message&&s.includes(`Method does not exist`)?(this.aguiDisabled=!0,this.stream=null,this.hideTypingIndicator(),this.streamingFinished(),this.streamMessage(e,t,n)):(this.finishAGUIRun(o),this.isNavigatingAway||this.addMessage(this.getServiceDownMessage()),console.error(`Stream error:`,i))}})};(this.pendingSessionPromise?this.pendingSessionPromise.catch(()=>null):Promise.resolve()).then(()=>this.syncPageTools()).then(s,s)},answerApproval(e,t){let n=null,r=null;for(let t of this.messages){let i=(t.toolCalls||[]).find(t=>t.interruptId===e);if(i){n=t,r=i;break}}if(!r||r.status!==`awaitingApproval`||this.stream)return;r.status=t?`approved`:`rejected`,r.decided=!0,n.rawContent=n.rawContent??n.content??``,v(n,n.references);let i=n.toolCalls.filter(e=>e.interruptId);if(i.some(e=>e.status===`awaitingApproval`))return;let a=i.filter(e=>e.decided).map(e=>({interruptId:e.interruptId,status:`resolved`,payload:{approved:e.status===`approved`}}));this.streamAGUIRun(this.getProfileId(),null,null,a)},markRunContinuesOnNextPage(e){if(!e)return;let t=j();M({sessionId:e,depth:(t&&t.sessionId===e?t.depth:0)+1,at:Date.now()})},continueRunOnThisPage(e){let t=j();if(!t||!e||t.sessionId!==e.sessionId||this.aguiDisabled)return;if(Date.now()-t.at>12e4){M(null),this.hideTypingIndicator();return}let n=e.messages||[],r=n.length?n[n.length-1]:null;!r||r.role!==`assistant`||!r.continuesOnNextPage?!r||r.role===`user`?this.showTypingIndicator():M(null):t.depth>5?M(null):(M({sessionId:t.sessionId,depth:t.depth,at:0}),!this.stream&&(r.continuesOnNextPage=!1,this.streamAGUIRun(this.getProfileId(),null,null,null,{continueRun:!0})))},getServiceDownMessage(){return{role:`assistant`,content:`Our service is currently unavailable. Please try again later. We apologize for the inconvenience.`,htmlContent:``}},getErrorMessage(e){return{role:`assistant`,content:typeof e==`string`&&e.trim()?e:`Something went wrong. Please try again.`,htmlContent:``}},processReferences(e,t){if(e=c(e),Object.keys(e).length){let n=this.messages[t];n.rawContent=n.rawContent??n.content??``,v(n,e),this.messages[t]=n,this.$nextTick(()=>{z(n),this.scrollToBottom()})}},streamingStarted(){var e=this.buttonElement.getAttribute(`data-stop-icon`);e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&this.inputElement.setAttribute(`disabled`,`disabled`)},streamingFinished(){var e=this.buttonElement.getAttribute(`data-start-icon`);if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&(this.inputElement.removeAttribute(`disabled`),this.inputElement.focus()),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(`.ai-streaming-icon`),n=0;n<t.length;n++)t[n].classList.remove(`ai-streaming-icon`),t[n].classList.add(`ai-bot-icon`);for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1)},handleExternalTtsStop(e){e?.detail?.sourceId!==this.ttsInstanceId&&this.stopAudio(!1)},updateTtsPlaybackButtons(){this.chatContainer&&this.chatContainer.querySelectorAll(`[data-tts-message-index]`).forEach(e=>{var t=Number(e.getAttribute(`data-tts-message-index`))===this.ttsPlayingMessageIndex;e.classList.toggle(`tts-playing`,t),e.setAttribute(`title`,t?`Pause audio`:`Read aloud`)})},updateCopyButtons(){this.chatContainer&&this.chatContainer.querySelectorAll(`[data-copy-message-index]`).forEach(e=>{var t=Number(e.getAttribute(`data-copy-message-index`))===this.copiedMessageIndex,n=t?`<i class="fa-solid fa-check"></i>`:`<i class="fa-solid fa-copy"></i>`;e.classList.toggle(`text-success`,t),e.classList.toggle(`text-secondary`,!t),e.setAttribute(`title`,t?this.copiedTitle:this.copyTitle),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))})},setCopyButtonState(e,t){if(e){var n=t?`<i class="fa-solid fa-check"></i>`:`<i class="fa-solid fa-copy"></i>`;e.classList.toggle(`text-success`,t),e.classList.toggle(`text-secondary`,!t),e.setAttribute(`title`,t?this.copiedTitle:this.copyTitle),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))}},synthesizeSpeech(e,t){this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=t===void 0?-1:t,this.connection.invoke(`SynthesizeSpeech`,this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(e=>{console.error(`TTS synthesis error:`,e),this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this._ttsCacheIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())}))},toggleMessageTts(e,t){this.ttsPlayingMessageIndex===t?this.stopAudio():(this.stopAudio(!1),window.dispatchEvent(new CustomEvent(`crestapps-ai-chat-stop-tts`,{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=t,this.$nextTick(()=>this.updateTtsPlaybackButtons()),this.ttsAudioCache[t]?this.playAudioBlob(this.ttsAudioCache[t]):this.synthesizeSpeech(e.content,t))},playCollectedAudio(){if(this.audioChunks.length===0){!this.currentAudioElement&&this.audioPlayQueue.length===0&&(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons()));return}let e=this.audioChunks.reduce((e,t)=>e+t.length,0),t=new Uint8Array(e),n=0;for(let e of this.audioChunks)t.set(e,n),n+=e.length;this.audioChunks=[];let r=new Blob([t],{type:`audio/mp3`});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=r,this._ttsCacheIndex=-1),this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)},playAudioBlob(e){let t=URL.createObjectURL(e),n=new Audio(t);this.currentAudioUrl=t,this.currentAudioElement=n,this.isPlayingAudio=!0,n.addEventListener(`ended`,()=>{this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.playNextInQueue()}),n.addEventListener(`error`,()=>{this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.playNextInQueue()}),n.play().catch(e=>{console.error(`Audio playback error:`,e),this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())})},playNextInQueue(){if(this.audioPlayQueue.length>0){var e=this.audioPlayQueue.shift();this.playAudioBlob(e)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons()),this.conversationModeOnAudioEnded()},stopAudio(){this.currentAudioElement&&=(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,null),this.currentAudioUrl&&=(URL.revokeObjectURL(this.currentAudioUrl),null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())},voiceSettingsElement(){var e=this.conversationButton&&this.conversationButton.nextElementSibling;return e&&e.id===`realtime-audio-settings`?e:null},setVoiceSessionLive(e){this.inputElement&&(this.inputElement.hidden=e),this.buttonElement&&(this.buttonElement.hidden=e),this.conversationButton&&this.conversationButton.classList.toggle(`flex-grow-1`,e);var t=this.voiceSettingsElement();t&&(t.hidden=!e);var n=this.realtimeHintElement;n&&n.classList.toggle(`d-none`,!e)},toggleConversationMode(){this.realtimeEnabled?this.realtimeController&&this.realtimeController.toggle():this.isConversationMode?this.stopConversationMode():this.startConversationMode()},forceStopActiveVoice(){this.isConversationMode&&(this.realtimeEnabled?this.stopRealtimeConversation():this.stopConversationMode())},startRealtimeConversation(){this.realtimeController&&this.realtimeController.start()},stopRealtimeConversation(){this.realtimeController&&this.realtimeController.stop()},setupRealtimeController(e){if(!this.realtimeController&&this.conversationButton){if(!window.CoreAIRealtime||typeof window.CoreAIRealtime.attach!=`function`)console.error(`realtime-audio.js is not loaded; realtime voice is unavailable on this page.`);else{var t=this;this.realtimeController=window.CoreAIRealtime.attach({connection:this.connection,ensureConnected:function(){return t.ensureConnectionStarted().then(function(e){if(!e)throw Error(`The chat connection is not available.`);return e})},sendStart:function(e,n,r,i,a,o){t.connection.send(`StartRealtimeConversation`,t.getProfileId(),t.getSessionId()||``,e,n,r,i,a,o)},webRtcEnabled:this.realtimeWebRtcEnabled,sendStartWebRtc:function(e,n,r,i,a,o){t.connection.send(`StartRealtimeWebRtc`,t.getProfileId(),t.getSessionId()||``,e,n,r,i,a,o)},webRtcIceServers:this.realtimeWebRtcIceServers||void 0,voiceName:this.realtimeVoiceName||``,getVoiceName:function(){return t.realtimeVoiceName||``},realtimeEnabled:!0,selectors:{realtimeButton:e.conversationButtonElementSelector,micButton:e.micButtonElementSelector},onSessionStateChanged:function(e){t.setVoiceSessionLive(e)},onActivate:function(){t.isConversationMode=!0,t._conversationAssistantMessage=null,t._conversationPartialMessage=null,t.removeNotification(`conversation-ended`)},onDeactivate:function(){t.isConversationMode=!1,t.finishRealtimeConversationCleanup()},onUserTurnPending:function(e){t.addRealtimePendingTurn(e)},onUserTurnDropped:function(e){t.dropRealtimePendingTurn(e)}})}}},finishRealtimeConversationCleanup(){if(this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:`conversation-ended`,content:`Conversation ended.`,icon:`fa-solid fa-circle-check`,dismissible:!0,autoDismissMs:5e3})},addRealtimePendingTurn(e){if(e){this._realtimePendingTurns=this._realtimePendingTurns||{};var t=this.messages.length;this.addMessage({role:`user`,content:``,isPartial:!0}),this._realtimePendingTurns[e]=this.messages[t]}},fillRealtimePendingTurn(e,t){if(e){if(t){var n=t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`);e.content=t,e.htmlContent=`<p>`+n+`</p>`,e.isPartial=!1}else{var r=this.messages.indexOf(e);r>=0&&this.messages.splice(r,1)}}},dropRealtimePendingTurn(e){if(e&&this._realtimePendingTurns){var t=this._realtimePendingTurns[e];if(t){delete this._realtimePendingTurns[e];var n=this.messages.indexOf(t);n>=0&&this.messages.splice(n,1)}}},startConversationMode(){this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript=``,this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification(`conversation-ended`),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(e=>{this._conversationSubject=new signalR.Subject,this._conversationStream=e;var t=.12;this._conversationCapture=this._createPcmCapture(e,(e,n)=>{this.isPlayingAudio&&n>=t&&this.stopAudio();try{this._conversationSubject.next(e)}catch{}});var n=this.getProfileId(),r=this.getSessionId()||``,i=navigator.language||document.documentElement.lang||`en-US`,a=this._conversationCapture&&this._conversationCapture.sampleRate||16e3;this.connection.send(`StartConversation`,n,r,this._conversationSubject,`audio/pcm;rate=`+a,i),this.isRecording=!0}).catch(e=>{console.error(`Microphone access denied:`,e),this.isConversationMode=!1,this.updateConversationButton()}))},stopConversationMode(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke(`StopConversation`).catch(function(){}),this.isRecording){if(this._stopPcmCapture(this._conversationCapture),this._conversationCapture=null,this._conversationSubject)try{this._conversationSubject.complete()}catch{}this.isRecording=!1}if(this.stopAudio(),this._conversationPartialTranscript=``,this._conversationPartialMessage=null,this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:`conversation-ended`,content:`Conversation ended.`,icon:`fa-solid fa-circle-check`,dismissible:!0,autoDismissMs:5e3})}},updateConversationButton(){if(this.conversationButton){if(this.isConversationMode){this.conversationButton.classList.add(`active`,`btn-primary`),this.conversationButton.classList.remove(`btn-dark`,`btn-outline-dark`,`btn-outline-secondary`),this.conversationButton.title=this.conversationButton.getAttribute(`data-end-title`)||`End Conversation`;var e=this.conversationButton.getAttribute(`data-end-html`);e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove(`active`,`btn-primary`),this.conversationButton.classList.remove(`btn-dark`,`btn-outline-secondary`),this.conversationButton.classList.add(`btn-outline-dark`),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute(`data-start-title`)||`Start Conversation`;var t=this.conversationButton.getAttribute(`data-start-html`);t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}}},conversationModeSendPrompt(){},conversationModeOnAudioEnded(){},generatePrompt(e){if(!e){console.error(`The element paramter is required.`);return}let t=e.getAttribute(`data-profile-id`),n=this.getSessionId(),r=this.getProfileId();!t||!n?console.error(`The given element is missing data-profile-id or the session has not yet started.`):this.streamMessage(t,null,r)},createSessionUrl(e,t,n){let r=e.toLowerCase().startsWith(`http`)?e:window.location.origin+e,i=new URL(r);return i.searchParams.set(t,n),i.toString()},showTypingIndicator(){this.addMessage({role:`indicator`,htmlContent:u.indicatorTemplate})},hideTypingIndicator(){let e=this.messages.length;return this.messages=this.messages.filter(e=>e.role!==`indicator`),e-this.messages.length},receiveNotification(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(t=>t.type===e.type);t>=0?this.notifications.splice(t,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.$nextTick(()=>{this.scrollToBottom()})}},updateNotification(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(t=>t.type===e.type);t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e))}},scheduleNotificationDismiss(e){!e||!e.type||!e.autoDismissMs||e.autoDismissMs<=0||(this.notificationDismissTimers[e.type]=setTimeout(()=>{this.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(t=>t.type!==e)},dismissNotification(e){this.removeNotification(e)},handleNotificationAction(e,t){if(this.connection){var n=this.getSessionId();this.connection.invoke(`HandleNotificationAction`,n,e,t).catch(function(e){console.error(`Error handling notification action:`,e)})}},scrollToBottom(){this.autoScroll&&setTimeout(()=>{this.chatContainer.scrollTop=this.chatContainer.scrollHeight-this.chatContainer.clientHeight},50)},handleUserInput(e){this.prompt=e.target.value},getProfileId(){return this.inputElement?this.inputElement.getAttribute(`data-profile-id`):null},setSessionId(e){this.inputElement&&this.inputElement.setAttribute(`data-session-id`,e||``)},resetSession(){this.forceStopActiveVoice(),this.stopRecording(),this.rejectPendingSessionRequest(`Session was reset.`),this.setSessionId(``),this.isSessionStarted=!1,this.sessionRating=null,this.messages=[],this.documents=[],u.initialPrompt?this.addMessage({role:`assistant`,content:u.initialPrompt}):this.showPlaceholder(),f&&typeof f.onSessionReset==`function`&&f.onSessionReset(this,u)},startNewSession(){if(!this.applyOrchestratorAvailability())return;let e=this.getProfileId();e&&this.connection&&(this.forceStopActiveVoice(),this.requestNewSession(e).catch(e=>console.error(e)))},async ensureSessionForDocuments(e){return this.getSessionId()||(!e||!this.connection?null:await this.requestNewSession(e))},requestNewSession(e){return this.pendingSessionPromise?this.pendingSessionPromise:!e||!this.connection?Promise.resolve(null):(this.pendingSessionPromise=new Promise((e,t)=>{this.pendingSessionResolver=e,this.pendingSessionRejector=t,this.pendingSessionTimeoutId=window.setTimeout(()=>{this.rejectPendingSessionRequest(`Timed out while creating a chat session.`)},15e3)}),this.connection.invoke(`StartSession`,e,null).catch(e=>{this.rejectPendingSessionRequest(e)}),this.pendingSessionPromise)},resolvePendingSessionRequest(e){this.pendingSessionResolver&&this.pendingSessionResolver(e),this.clearPendingSessionRequest()},rejectPendingSessionRequest(e){this.pendingSessionRejector&&this.pendingSessionRejector(e),this.clearPendingSessionRequest()},clearPendingSessionRequest(){this.pendingSessionTimeoutId&&window.clearTimeout(this.pendingSessionTimeoutId),this.pendingSessionPromise=null,this.pendingSessionResolver=null,this.pendingSessionRejector=null,this.pendingSessionTimeoutId=null},initializeApp(){if(this.inputElement=document.querySelector(u.inputElementSelector),this.buttonElement=document.querySelector(u.sendButtonElementSelector),this.chatContainer=document.querySelector(u.chatContainerElementSelector),this.placeholder=document.querySelector(u.placeholderElementSelector),!this.inputElement||!this.buttonElement||!this.chatContainer||!this.placeholder)return console.error(`AI chat app could not initialize because one or more required elements were not found.`,{inputElementSelector:u.inputElementSelector,sendButtonElementSelector:u.sendButtonElementSelector,chatContainerElementSelector:u.chatContainerElementSelector,placeholderElementSelector:u.placeholderElementSelector}),!1;this.applyOrchestratorAvailability(),this.chatContainer.addEventListener(`click`,e=>{let t=e.target&&e.target.closest?e.target.closest(`[data-agui-interrupt]`):null;t&&this.chatContainer.contains(t)&&(e.preventDefault(),this.answerApproval(t.getAttribute(`data-agui-interrupt`),t.getAttribute(`data-agui-approved`)===`true`))}),document.addEventListener(`selectionchange`,()=>this.trackPageSelection());let e=this.getSessionId();if(!d&&e&&this.loadSession(e),u.sessionDocumentsEnabled&&u.documentBarSelector&&(this.documentBar=document.querySelector(u.documentBarSelector),this.documentBar)){this.renderDocumentBar();var t=document.createElement(`input`);t.type=`file`,t.id=`ai-chat-doc-input`,t.className=`d-none`,t.multiple=!0,u.allowedExtensions&&(t.accept=u.allowedExtensions),t.addEventListener(`change`,e=>this.handleFileInputChange(e)),this.documentBar.parentElement.appendChild(t);var n=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;n&&(n.addEventListener(`dragover`,e=>this.handleDragOver(e)),n.addEventListener(`dragleave`,e=>this.handleDragLeave(e)),n.addEventListener(`drop`,e=>this.handleDrop(e)))}this.chatContainer.addEventListener(`scroll`,()=>{if(!this.stream)return;let e=this.chatContainer.scrollHeight-this.chatContainer.clientHeight-this.chatContainer.scrollTop<=30;this.autoScroll=e}),this.inputElement.addEventListener(`keydown`,e=>{this.stream==null&&e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.buttonElement.click())}),this.inputElement.addEventListener(`input`,e=>{this.handleUserInput(e),e.target.value.trim()?this.buttonElement.removeAttribute(`disabled`):this.buttonElement.setAttribute(`disabled`,!0)}),this.buttonElement.addEventListener(`click`,()=>{if(this.stream!=null){if(this.stream.dispose(),this.stream=null,this.streamingFinished(),this.hideTypingIndicator(),this.messages.length>0){let e=this.messages[this.messages.length-1];e.role===`assistant`&&!e.content?this.messages.pop():e.isStreaming&&=!1}}else this.sendMessage()});let r=document.getElementsByClassName(`profile-generated-prompt`);for(var i=0;i<r.length;i++)r[i].addEventListener(`click`,e=>{e.preventDefault(),this.generatePrompt(e.target)});let a=document.getElementsByClassName(`chat-session-history-item`);for(i=0;i<a.length;i++)a[i].addEventListener(`click`,e=>{e.preventDefault();var t=e.target.getAttribute(`data-session-id`);t?(this.loadSession(t),this.showChatScreen()):console.error(`an element with the class chat-session-history-item with no data-session-id set.`)});let o=Array.isArray(u.messages)?u.messages:[];for(let e=0;e<o.length;e++)this.addMessage(o[e]);return this.messages.length===0&&u.initialPrompt&&this.addMessage({role:`assistant`,content:u.initialPrompt}),this.$nextTick(()=>{this.refreshAllFeedbackIcons()}),this.chatContainer&&this.chatContainer.addEventListener(`click`,e=>{var t=e.target.closest(`.ai-code-copy-btn`);if(t){var n=t.closest(`.ai-code-block`)||t.closest(`pre`);if(n){var r=n.querySelector(`code`);r&&(navigator.clipboard.writeText(r.textContent),t.innerHTML=`<i class="fa-solid fa-check"></i> `+(u.codeCopiedText||`Copied!`),setTimeout(()=>{t.innerHTML=`<i class="fa-regular fa-copy"></i>`},2e3))}}}),this.speechToTextEnabled&&u.micButtonElementSelector&&(this.micButton=document.querySelector(u.micButtonElementSelector),this.micButton&&(this.micButton.style.display=``,this.micButton.addEventListener(`click`,()=>{this.toggleRecording()}))),(this.conversationModeEnabled||this.realtimeEnabled)&&u.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(u.conversationButtonElementSelector),this.conversationButton&&(this.realtimeEnabled?(this.setupRealtimeController(u),this.setVoiceSessionLive(!1)):this.conversationButton.addEventListener(`click`,()=>{this.toggleConversationMode()}))),!0},loadSession(e){this.connection.invoke(`LoadSession`,e).catch(e=>console.error(e))},reloadCurrentSession(){var e=this.getSessionId();e&&this.loadSession(e)},initializeSession(e,t){if(this.isSessionStarted&&!t)e&&this.getSessionId()===e&&this.resolvePendingSessionRequest(e);else if(this.fireEvent(new CustomEvent(`initializingSessionCoreAIChat`,{detail:{sessionId:e}})),this.setSessionId(e),this.isSessionStarted=!0,this.resolvePendingSessionRequest(e),f&&typeof f.onSessionInitialized==`function`&&f.onSessionInitialized(this,e,u),!d&&e&&u.sessionUrlTemplate&&typeof history<`u`&&history.replaceState){var n=u.sessionUrlTemplate.replace(`{sessionId}`,encodeURIComponent(e));history.replaceState(null,``,n)}},getSessionId(){let e=this.inputElement?this.inputElement.getAttribute(`data-session-id`):null;return!e&&f&&typeof f.resolveSessionId==`function`&&(e=f.resolveSessionId(this,u)),e},clearCopiedMessageState(){this.copyResetTimeoutId&&=(window.clearTimeout(this.copyResetTimeoutId),null),this.activeCopyButton&&=(this.setCopyButtonState(this.activeCopyButton,!1),null),this.copiedMessageIndex=-1},copyResponse(e,t,n){let r=e&&typeof e==`object`?e.copyContent??e.content??``:e??``,i=n?.currentTarget||n?.target?.closest?.(`[data-copy-message-index]`)||null;navigator.clipboard.writeText(r).then(()=>{this.clearCopiedMessageState(),this.copiedMessageIndex=typeof t==`number`?t:-1,this.activeCopyButton=i,i?this.setCopyButtonState(i,!0):this.$nextTick(()=>this.updateCopyButtons()),this.copyResetTimeoutId=window.setTimeout(()=>{this.clearCopiedMessageState(),this.$nextTick(()=>this.updateCopyButtons())},Number(u.copyResetDelayMs)||2e3)}).catch(e=>console.error(`Failed to copy response:`,e))},updateFeedbackIcons(e,t){if(e){var n=e.querySelector(`.rate-up-btn`),r=e.querySelector(`.rate-down-btn`);if(n){var i=t===!0?`fa-solid fa-thumbs-up`:`fa-regular fa-thumbs-up`,a=document.createElement(`span`);a.className=i,a.style.fontSize=`0.9rem`,n.textContent=``,n.appendChild(a)}if(r){var o=t===!1?`fa-solid fa-thumbs-down`:`fa-regular fa-thumbs-down`,s=document.createElement(`span`);s.className=o,s.style.fontSize=`0.9rem`,r.textContent=``,r.appendChild(s)}}},refreshAllFeedbackIcons(){for(var e=this.$el.querySelectorAll(`.ai-chat-message-assistant-feedback`),t=0;t<e.length;t++){var n=e[t].getAttribute(`data-message-id`),r=this.messages.find(e=>e.id===n);r&&this.updateFeedbackIcons(e[t],r.userRating)}},rateMessage(e,t){var n=this.getSessionId();if(n&&e.id&&this.connection){var r=e.userRating===t?null:t;e.userRating=r;var i=this.$el.querySelector(`.ai-chat-message-assistant-feedback[data-message-id="`+e.id+`"]`);this.updateFeedbackIcons(i,r),r!==null&&i&&setTimeout(()=>{var e=t?`.rate-up-btn`:`.rate-down-btn`,n=i.querySelector(e);n&&(n.classList.remove(`spark-effect`),n.offsetWidth,n.classList.add(`spark-effect`),n.addEventListener(`animationend`,function e(){n.removeEventListener(`animationend`,e),n.classList.remove(`spark-effect`)}))},50),this.connection.invoke(`RateMessage`,n,e.id,t).catch(function(e){console.error(`Failed to rate message:`,e)})}}},watch:{documents:{handler(){this.renderDocumentBar(),f&&typeof f.onDocumentsChanged==`function`&&f.onDocumentsChanged(this,this.documents,u)},deep:!0},isUploading(){this.renderDocumentBar()},isDocumentOperationPending(){this.renderDocumentBar()},isPlayingAudio(){},copiedMessageIndex(){this.$nextTick(()=>this.updateCopyButtons())},isConversationMode(e){this.micButton&&(this.micButton.style.display=e?`none`:this.speechToTextEnabled?``:`none`),this.realtimeEnabled||this.setVoiceSessionLive(e)}},mounted(){(async()=>{await this.startConnection(),this.initializeApp()&&d&&f&&typeof f.onMounted==`function`&&f.onMounted(this,u),this.$nextTick(()=>{this.updateCopyButtons(),i(this.$el),this.fontAwesomeObserver=a(this.$el)})})(),window.addEventListener(`beforeunload`,this.handleBeforeUnload),window.addEventListener(`crestapps-ai-chat-stop-tts`,this.handleExternalTtsStop)},beforeUnmount(){window.removeEventListener(`beforeunload`,this.handleBeforeUnload),window.removeEventListener(`crestapps-ai-chat-stop-tts`,this.handleExternalTtsStop),this.fontAwesomeObserver&&=(this.fontAwesomeObserver.disconnect(),null),this.clearCopiedMessageState(),this.stopAudio(!1),this.stream&&=(this.stream.dispose(),null),this.connection&&this.connection.stop(),f&&typeof f.onBeforeUnmount==`function`&&f.onBeforeUnmount(this,u)},template:u.messageTemplate};window.CoreAIChatSurface.registerRoot(document.querySelector(u.appElementSelector));let m=Vue.createApp(p).mount(u.appElementSelector);return f&&typeof f.attach==`function`&&f.attach(m,u),m},q=`[data-coreai-chat-config],[data-coreai-chat-app-element-selector]`;function J(e,t){let n=e.getAttribute(t);return n===null||n===``?null:n}function oe(e){if(e==null)return null;if(typeof e==`boolean`)return e;let t=String(e).trim().toLowerCase();return t===`true`||t!==`false`&&null}function Y(e,t,n){let r=J(e,t);if(!r)return null;try{return JSON.parse(r)}catch(e){return console.error(`Failed to parse `+n+` JSON.`,e),null}}function se(e,t){let n=t||{};if(e.hasAttribute(`data-coreai-chat-widget-container-selector`)&&n.allowWidgetHost!==!0)return null;let r=J(e,`data-coreai-chat-app-element-selector`);if(!r)return null;let i={signalRHubUrl:J(e,`data-coreai-chat-signalr-hub-url`),appElementSelector:r,chatContainerElementSelector:J(e,`data-coreai-chat-container-element-selector`),inputElementSelector:J(e,`data-coreai-chat-input-element-selector`),sendButtonElementSelector:J(e,`data-coreai-chat-send-button-element-selector`),placeholderElementSelector:J(e,`data-coreai-chat-placeholder-element-selector`),messages:Y(e,`data-coreai-chat-messages`,`CoreAI chat messages`)??void 0,chatMode:J(e,`data-coreai-chat-mode`),micButtonElementSelector:J(e,`data-coreai-chat-mic-button-element-selector`),conversationButtonElementSelector:J(e,`data-coreai-chat-conversation-button-element-selector`),realtimeHintElementSelector:J(e,`data-coreai-chat-realtime-hint-element-selector`),ttsVoiceName:J(e,`data-coreai-chat-tts-voice-name`),realtimeVoiceName:J(e,`data-coreai-chat-realtime-voice-name`),documentBarSelector:J(e,`data-coreai-chat-document-bar-selector`),uploadDocumentUrl:J(e,`data-coreai-chat-upload-document-url`),removeDocumentUrl:J(e,`data-coreai-chat-remove-document-url`),allowedExtensions:J(e,`data-coreai-chat-allowed-extensions`),supportedExtensionsText:J(e,`data-coreai-chat-supported-extensions-text`),existingDocuments:Y(e,`data-coreai-chat-existing-documents`,`CoreAI chat existing documents`)??void 0,initialPrompt:J(e,`data-coreai-chat-initial-prompt`),sessionUrlTemplate:J(e,`data-coreai-chat-session-url-template`),userLabel:J(e,`data-coreai-chat-user-label`),assistantLabel:J(e,`data-coreai-chat-assistant-label`),assistantAvatarUrl:J(e,`data-coreai-chat-assistant-avatar-url`),copyTitle:J(e,`data-coreai-chat-copy-title`),copiedTitle:J(e,`data-coreai-chat-copied-title`)},a={metricsEnabled:`data-coreai-chat-metrics-enabled`,textToSpeechEnabled:`data-coreai-chat-text-to-speech-enabled`,sessionDocumentsEnabled:`data-coreai-chat-session-documents-enabled`,singleResponseMode:`data-coreai-chat-single-response-mode`,realtimeEnabled:`data-coreai-chat-realtime-enabled`,realtimeWebRtcEnabled:`data-coreai-chat-realtime-webrtc-enabled`};return Object.keys(a).forEach(t=>{let n=oe(J(e,a[t]));n!==null&&(i[t]=n)}),U(i)}function X(e,t){let n=Y(e,`data-coreai-chat-config`,`CoreAI chat config`),r=se(e,t);return!n&&!r?null:Object.assign({},n||{},r||{})}function Z(e){if(!e||e.dataset.coreAiChatInitialized===`true`)return e&&e.__coreAIChatApp||null;let t=X(e);if(!t)return null;let n=K(t);return n?(e.dataset.coreAiChatInitialized=`true`,e.__coreAIChatApp=n,n):null}function Q(e){if(!e||typeof e.querySelectorAll!=`function`)return;let t=e=>!window.CoreAIChatSurface.isInsideRenderedMessage(e);typeof e.matches==`function`&&e.matches(q)&&t(e)&&Z(e),e.querySelectorAll(q).forEach(e=>{t(e)&&Z(e)})}function $(){Q(document),typeof MutationObserver<`u`&&new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e&&e.nodeType===1&&Q(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,$,{once:!0}):$(),{initialize:K,initializeFromElement:Z,buildConfigFromElement:X}}(),document.addEventListener(`click`,function(e){let t=e.target.closest(`.download-chart-btn`);if(!t)return;let n=t.getAttribute(`data-chart-id`),r=n?document.getElementById(n):null;if(!r){console.error(`Chart canvas not found:`,n);return}let i=document.createElement(`a`);i.download=`chart-`+n+`.png`,i.href=r.toDataURL(`image/png`),i.click()}),document.addEventListener(`click`,function(e){let t=e.target.closest(`.ai-download-image`);if(!t)return;let n=t.closest(`.generated-image-container`)?.querySelector(`img`);if(!n)return;let r=n.src;r&&r.startsWith(`data:`)&&(e.preventDefault(),fetch(r).then(function(e){return e.blob()}).then(function(e){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t.getAttribute(`download`)||`generated-image.png`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error(`Failed to download image:`,e)}))})})();
|
|
81
81
|
//# sourceMappingURL=ai-chat.min.js.map
|