@crestapps/ai-chat-ui 2.0.0-preview.215 → 2.0.0-preview.223

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.
Files changed (49) hide show
  1. package/dist/ai-chat-widget.js +762 -964
  2. package/dist/ai-chat-widget.js.map +1 -1
  3. package/dist/ai-chat-widget.min.js +1 -1
  4. package/dist/ai-chat-widget.min.js.map +1 -1
  5. package/dist/ai-chat.css +0 -2
  6. package/dist/ai-chat.js +2380 -3698
  7. package/dist/ai-chat.js.map +1 -1
  8. package/dist/ai-chat.min.css +1 -1
  9. package/dist/ai-chat.min.js +78 -1
  10. package/dist/ai-chat.min.js.map +1 -1
  11. package/dist/chat-image-carousel.css +0 -2
  12. package/dist/chat-image-carousel.js +306 -482
  13. package/dist/chat-image-carousel.js.map +1 -1
  14. package/dist/chat-image-carousel.min.css +1 -1
  15. package/dist/chat-image-carousel.min.js +1 -1
  16. package/dist/chat-image-carousel.min.js.map +1 -1
  17. package/dist/chat-interaction-settings.js +221 -293
  18. package/dist/chat-interaction-settings.js.map +1 -1
  19. package/dist/chat-interaction-settings.min.js +1 -1
  20. package/dist/chat-interaction-settings.min.js.map +1 -1
  21. package/dist/chat-interaction.js +2330 -3557
  22. package/dist/chat-interaction.js.map +1 -1
  23. package/dist/chat-interaction.min.js +62 -1
  24. package/dist/chat-interaction.min.js.map +1 -1
  25. package/dist/chat-markers.js +193 -485
  26. package/dist/chat-markers.js.map +1 -1
  27. package/dist/chat-markers.min.js +2 -1
  28. package/dist/chat-markers.min.js.map +1 -1
  29. package/dist/chat-widget.css +0 -2
  30. package/dist/chat-widget.min.css +1 -1
  31. package/dist/document-drop-zone.css +0 -2
  32. package/dist/document-drop-zone.js +127 -153
  33. package/dist/document-drop-zone.js.map +1 -1
  34. package/dist/document-drop-zone.min.css +1 -1
  35. package/dist/document-drop-zone.min.js +1 -1
  36. package/dist/document-drop-zone.min.js.map +1 -1
  37. package/dist/realtime-audio.js +1639 -2504
  38. package/dist/realtime-audio.js.map +1 -1
  39. package/dist/realtime-audio.min.js +3 -1
  40. package/dist/realtime-audio.min.js.map +1 -1
  41. package/dist/technical-name-generator.js +58 -80
  42. package/dist/technical-name-generator.js.map +1 -1
  43. package/dist/technical-name-generator.min.js +1 -1
  44. package/dist/technical-name-generator.min.js.map +1 -1
  45. package/package.json +1 -5
  46. package/dist/ai-chat.css.map +0 -1
  47. package/dist/chat-image-carousel.css.map +0 -1
  48. package/dist/chat-widget.css.map +0 -1
  49. package/dist/document-drop-zone.css.map +0 -1
@@ -1,2 +1,63 @@
1
- var _excluded=["placeholder"];function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",a=n.toStringTag||"@@toStringTag";function o(n,i,a,o){var c=i&&i.prototype instanceof s?i:s,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,a){var o,s,c,l=0,u=a||[],d=!1,m={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return o=t,s=0,c=e,m.n=n,r}};function f(n,i){for(s=n,c=i,t=0;!d&&l&&!a&&t<u.length;t++){var a,o=u[t],f=m.p,h=o[2];n>3?(a=h===i)&&(c=o[(s=o[4])?5:(s=3,3)],o[4]=o[5]=e):o[0]<=f&&((a=n<2&&f<o[1])?(s=0,m.v=i,m.n=o[1]):f<h&&(a=n<3||o[0]>i||i>h)&&(o[4]=n,o[5]=i,m.n=h,s=0))}if(a||n>1)return r;throw d=!0,i}return function(a,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(t=s<2?e:c)||!d;){o||(s?s<3?(s>1&&(m.n=-1),f(s,c)):m.n=c:m.v=c);try{if(l=2,o){if(s||(a="next"),t=o[a]){if(!(t=t.call(o,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=o.return)&&t.call(o),s<2&&(c=TypeError("The iterator does not provide a '"+a+"' method"),s=1);o=e}else if((t=(d=m.n<0)?c:n.call(i,m))!==r)break}catch(t){o=e,s=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,a,o),!0),l}var r={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),d=l.prototype=s.prototype=Object.create(u);function m(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=l,_regeneratorDefine2(d,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,a,"GeneratorFunction"),_regeneratorDefine2(d),_regeneratorDefine2(d,a,"Generator"),_regeneratorDefine2(d,i,function(){return this}),_regeneratorDefine2(d,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:o,m:m}})()}function _regeneratorDefine2(e,t,n,i){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}_regeneratorDefine2=function(e,t,n,i){function o(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?a?a(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(o("next",0),o("throw",1),o("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,a,o,r){try{var s=e[o](r),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(i,a)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,a){var o=e.apply(t,n);function r(e){asyncGeneratorStep(o,i,a,r,s,"next",e)}function s(e){asyncGeneratorStep(o,i,a,r,s,"throw",e)}r(void 0)})}}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _objectWithoutProperties(e,t){if(null==e)return{};var n,i,a=_objectWithoutPropertiesLoose(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(i=0;i<o.length;i++)n=o[i],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function _objectWithoutPropertiesLoose(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;n[i]=e[i]}return n}function _createForOfIteratorHelper(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,a=function(){};return{s:a,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,r=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return r=e.done,e},e:function(e){s=!0,o=e},f:function(){try{r||null==n.return||n.return()}finally{if(s)throw o}}}}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray(e,t)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function _iterableToArrayLimit(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,a,o,r,s=[],c=!0,l=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(s.push(i.value),s.length!==t);c=!0);}catch(e){l=!0,a=e}finally{try{if(!c&&null!=n.return&&(r=n.return(),Object(r)!==r))return}finally{if(l)throw a}}return s}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}window.chatInteractionManager=function(e,t,n,i,a,o,r,s,c,l){var u={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",codeCopiedText:"Copied!",copyTitle:"Click here to copy response to clipboard.",copiedTitle:"Response copied to clipboard.",copyResetDelayMs:2e3,assistantLabel:"Assistant",messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-msg-role ai-chat-msg-role-user">You</div>\n <div v-else-if="message.role !== \'indicator\'" :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>\n {{ getAssistantLabel(message) }}\n </div>\n <div class="ai-chat-message-body lh-base">\n <h4 v-if="message.title">{{ message.title }}</h4>\n <div v-html="message.htmlContent"></div>\n <ol v-if="message.citationReferences && message.citationReferences.length" class="ai-chat-citation-list">\n <li v-for="citation in message.citationReferences" :key="\'citation-\' + (citation.referenceKey || citation.displayIndex)" class="ai-chat-citation-item">\n <a v-if="citation.link" :href="citation.link" :target="citation.isDownload ? null : \'_blank\'" :rel="citation.isDownload ? null : \'noopener noreferrer\'">{{ citation.label }}</a>\n <span v-else>{{ citation.label }}</span>\n </li>\n </ol>\n <span class="message-buttons-container" v-if="!isIndicator(message)">\n <button v-if="textToSpeechEnabled && !isConversationMode && message.role === \'assistant\' && !message.isStreaming" class="btn btn-sm btn-link text-secondary p-0 me-1 button-message-toolbox" :class="{ \'tts-playing\': ttsPlayingMessageIndex === index }" :data-tts-message-index="index" @click="toggleMessageTts(message, index)" :title="ttsPlayingMessageIndex === index ? \'Pause audio\' : \'Read aloud\'">\n <i :class="ttsPlayingMessageIndex === index ? \'fa-solid fa-circle-pause\' : \'fa-solid fa-circle-play\'"></i>\n </button>\n <button type="button" class="btn btn-sm btn-link p-0 button-message-toolbox ai-response-copy-btn" :class="copiedMessageIndex === index ? \'text-success\' : \'text-secondary\'" :data-copy-message-index="index" @click="copyResponse(message, index, $event)" :title="copiedMessageIndex === index ? copiedTitle : copyTitle">\n <i :class="copiedMessageIndex === index ? \'fa-solid fa-check\' : \'fa-solid fa-copy\'"></i>\n </button>\n </span>\n </div>\n </div>\n </div>\n <div v-for="notification in notifications" :key="\'notif-\' + notification.type" class="ai-chat-notification" :class="\'ai-chat-notification-\' + (notification.type || \'info\') + \' \' + (notification.cssClass || \'\')">\n <div class="ai-chat-notification-content">\n <i v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></i>\n <span class="ai-chat-notification-text">{{ notification.content }}</span>\n <button v-if="notification.dismissible" class="btn btn-sm btn-link p-0 ms-2 ai-chat-notification-dismiss" @click="dismissNotification(notification.type)" title="Dismiss">\n <i class="fa-solid fa-xmark"></i>\n </button>\n </div>\n <div v-if="notification.actions && notification.actions.length" class="ai-chat-notification-actions">\n <button v-for="action in notification.actions" :key="action.name" class="btn btn-sm" :class="action.cssClass || \'btn-outline-secondary\'" @click="handleNotificationAction(notification.type, action.name)">\n <i v-if="action.icon" :class="action.icon" class="me-1"></i>\n {{ action.label }}\n </button>\n </div>\n </div>\n </div>\n ',indicatorTemplate:'\n <div class="ai-chat-msg-role ai-chat-msg-role-assistant">\n <span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>\n Assistant\n </div>\n ',untitledText:"Untitled",clearHistoryTitle:"Clear History",clearHistoryMessage:"Are you sure you want to clear the chat history? This action cannot be undone. Your documents, parameters, and tools will be preserved.",clearHistoryOkText:"Yes",clearHistoryCancelText:"Cancel"};function d(e){if(!e)return"";var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?"":e}function m(e){var t=document.createElement("span");return t.textContent=e,t.innerHTML}function f(e){var t=window.FontAwesome;(function(e){if(!e||1!==e.nodeType)return!1;var t='i[class*="fa-"],i.fa,i.fas,i.far,i.fab';return!("function"!=typeof e.matches||!e.matches(t))||"function"==typeof e.querySelector&&!!e.querySelector(t)})(e)&&t&&t.dom&&"function"==typeof t.dom.i2svg&&t.dom.i2svg({node:e})}function h(e){if(!e||"undefined"==typeof MutationObserver)return null;var t=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){f(e)})})});return t.observe(e,{childList:!0,subtree:!0}),t}function p(e){var t,n,i,a,o,r,s,c,l,u,m,f;if(!e||"object"!==_typeof(e))return null;var h=Object.assign({},e);return h.index=null!==(t=null!==(n=h.index)&&void 0!==n?n:h.Index)&&void 0!==t?t:0,h.text=null!==(i=null!==(a=h.text)&&void 0!==a?a:h.Text)&&void 0!==i?i:null,h.title=null!==(o=null!==(r=h.title)&&void 0!==r?r:h.Title)&&void 0!==o?o:null,h.link=d(null!==(s=null!==(c=h.link)&&void 0!==c?c:h.Link)&&void 0!==s?s:null),h.referenceType=null!==(l=null!==(u=h.referenceType)&&void 0!==u?u:h.ReferenceType)&&void 0!==l?l:null,h.isGenerated=!0===(null!==(m=h.isGenerated)&&void 0!==m?m:h.IsGenerated),h.isImage=!0===(null!==(f=h.isImage)&&void 0!==f?f:h.IsImage),h}function g(e){return!(!e||"object"!==_typeof(e))&&("string"==typeof e.referenceType&&"document"===e.referenceType.toLowerCase()||!("string"!=typeof e.link||!/\/ai\/documents\/.+\/download(?:$|\?)/i.test(e.link)))}function v(e){if(!e||"object"!==_typeof(e))return{};for(var t={},n=0,i=Object.entries(e);n<i.length;n++){var a,o=_slicedToArray(i[n],2),r=o[0],s=o[1];t[r]=null!==(a=p(s))&&void 0!==a?a:{}}return t}var y=window.CoreAIChatMarkers.expandImageMarkers;function b(e,t){return e.title||e.text||t}var C=0,S=null!==(e=null===(t=window.CoreAIChatMarkers)||void 0===t?void 0:t.citationIdentity)&&void 0!==e?e:function(){return"unmerged-".concat(++C)},A=null!==(n=null===(i=window.CoreAIChatMarkers)||void 0===i?void 0:i.splitCombinedCitations)&&void 0!==n?n:function(e){return e},I=null!==(a=null===(o=window.CoreAIChatMarkers)||void 0===o?void 0:o.collapseRepeatedCitations)&&void 0!==a?a:function(e){return e},T=null!==(r=null===(s=window.CoreAIChatMarkers)||void 0===s?void 0:s.separateAdjacentCitations)&&void 0!==r?r:function(e){return e},w=null!==(c=null===(l=window.CoreAIChatMarkers)||void 0===l?void 0:l.citationMarkerHtml)&&void 0!==c?c:function(e){return"<sup>".concat(e,"</sup>")};function x(e,t){var n=v(null!=t?t:e.references),i="string"==typeof e.rawContent?e.rawContent:"string"==typeof e.content?e.content:"",a=y(i,n),o=function(e,t){var n=A((e||"").trim()),i=v(t),a=Object.entries(i);if(!a.length)return{content:n,citations:[]};var o=a.filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)}),r=a.filter(function(e){var t=_slicedToArray(e,2),i=t[0];return t[1].isGenerated&&!n.includes(i)});if(!o.length&&!r.length)return{content:n,citations:[]};o.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index}),r.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var s,c=[],l=new Map,u=[],d=1,m=_createForOfIteratorHelper(o);try{for(m.s();!(s=m.n()).done;){var f=_slicedToArray(s.value,2),h=f[0],p=f[1],y=b(p,h),C=p.link||null,x=S(y,C),E=l.get(x);E||(E={referenceKey:h,referenceKeys:[],displayIndex:d++,label:y,link:C,isDownload:g(p)},l.set(x,E),c.push(E)),E.referenceKeys.push(h);var _="__CITE_".concat(E.displayIndex,"_").concat(p.index||E.displayIndex,"__");n=n.replaceAll(h,_),u.push({placeholder:_,displayIndex:E.displayIndex,label:E.label})}}catch(e){m.e(e)}finally{m.f()}for(var M=0,k=u;M<k.length;M++){var R=k[M];n=n.replaceAll(R.placeholder,w(R.displayIndex,R.label))}n=I(n),n=T(n);var P,B=_createForOfIteratorHelper(r);try{for(B.s();!(P=B.n()).done;){var N=_slicedToArray(P.value,2),L=N[0],D=N[1];c.push({referenceKey:L,referenceKeys:[L],displayIndex:d,label:b(D,L),link:D.link||null,isDownload:!0,placeholder:null}),d++}}catch(e){B.e(e)}finally{B.f()}return{content:n,citations:c.map(function(e){return e.placeholder,_objectWithoutProperties(e,_excluded)})}}(a,n);return e.rawContent=i,e.content=i,e.displayContent=o.content,e.references=n,e.citationReferences=o.citations,e.copyContent=function(e,t){var n=(e||"").trim();if(!n||!Array.isArray(t)||0===t.length)return n;var i,a=_createForOfIteratorHelper(t);try{for(a.s();!(i=a.n()).done;){var o,r,s=i.value,c=_createForOfIteratorHelper(null!==(o=s.referenceKeys)&&void 0!==o&&o.length?s.referenceKeys:[s.referenceKey]);try{for(c.s();!(r=c.n()).done;){var l=r.value;n=n.replaceAll(l,"[".concat(s.displayIndex,"]"))}}catch(e){c.e(e)}finally{c.f()}}}catch(e){a.e(e)}finally{a.f()}n+="\n\nReferences:\n";var u,d=_createForOfIteratorHelper(t);try{for(d.s();!(u=d.n()).done;){var m=u.value;n+="".concat(m.displayIndex,". ").concat(m.label),m.link&&(n+=" - ".concat(m.link)),n+="\n"}}catch(e){d.e(e)}finally{d.f()}return n.trimEnd()}(A(a),o.citations),e.htmlContent=N(o.content,e),e}var E=new marked.Renderer;E.link=function(e){var t=d(e.href);return t?'<a href="'.concat(t,'" target="_blank" rel="noopener noreferrer">').concat(e.text,"</a>"):e.text||""},E.code=function(e){var t=e.text||"",n=(e.lang||"").trim(),i=t;if("undefined"!=typeof hljs)if(n&&hljs.getLanguage(n))try{i=hljs.highlight(t,{language:n}).value}catch(e){}else try{i=hljs.highlightAuto(t).value}catch(e){}else i=m(t);var a=n?m(n):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><i class="fa-solid fa-code"></i> '.concat(a,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><i class="fa-regular fa-copy"></i></button></div><pre><code class="hljs').concat(n?" language-"+n:"",'">').concat(i,"</code></pre></div>")},E.image=function(e){var t=d(e.href);if(!t)return"";var n=e.text||u.generatedImageAltText,i=u.generatedImageMaxWidth;return'<span class="generated-image-container">\n <img src="'.concat(t,'" alt="').concat(n,'" class="img-thumbnail" style="max-width: ').concat(i,'px; height: auto;" />\n <a href="').concat(t,'" target="_blank" download="').concat(n,'" title="').concat(u.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <i class="fa-solid fa-download"></i>\n </a>\n </span>')};var _=0,M=[];window.__chartConfigs=window.__chartConfigs||{};var k=window.CoreAIChatMarkers.findChartMarker;function R(){if("function"==typeof mediumZoom){var e=document.querySelectorAll(".generated-image-container img:not([data-zoom-wired])");if(0!==e.length){var t,n=_createForOfIteratorHelper(e);try{for(n.s();!(t=n.n()).done;){t.value.setAttribute("data-zoom-wired","true")}}catch(e){n.e(e)}finally{n.f()}mediumZoom(e,{margin:16,background:"rgba(15, 15, 15, 0.92)"})}}}function P(){var e,t=_createForOfIteratorHelper(document.querySelectorAll(".generated-image-container img:not([data-broken-wired])"));try{var n=function(){var t=e.value;t.setAttribute("data-broken-wired","true"),t.addEventListener("error",function(){var e=t.closest(".generated-image-container");if(e&&!e.dataset.brokenHandled){e.dataset.brokenHandled="true",e.hidden=!0;var n=document.createElement("p");n.className="text-muted small fst-italic mb-2",n.textContent=t.alt?'(the picture "'.concat(t.alt,'" could not be loaded)'):"(that picture could not be loaded)",e.insertAdjacentElement("afterend",n)}},{once:!0})};for(t.s();!(e=t.n()).done;)n()}catch(e){t.e(e)}finally{t.f()}}function B(e){if("undefined"!=typeof document&&"function"==typeof requestAnimationFrame&&(requestAnimationFrame(P),requestAnimationFrame(R)),e&&e._pendingCharts&&e._pendingCharts.length){var t=_toConsumableArray(e._pendingCharts);e._pendingCharts=[],requestAnimationFrame(function(){var e,n=_createForOfIteratorHelper(t);try{for(n.s();!(e=n.n()).done;){var i=e.value,a=document.getElementById(i.chartId);if(a)if("undefined"!=typeof Chart)if(null!==a.offsetParent)try{var o,r,s;a._chartInstance&&a._chartInstance.destroy();var c="string"==typeof i.config?JSON.parse(i.config):i.config;null!==(o=c.options)&&void 0!==o||(c.options={}),c.options.responsive=!0,c.options.maintainAspectRatio=!0,null!==(s=(r=c.options).aspectRatio)&&void 0!==s||(r.aspectRatio=4/3),a._chartInstance=new Chart(a,c)}catch(e){console.error("Error creating chart:",e)}else window.__chartConfigs[i.chartId]=i.config;else console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).')}}catch(e){n.e(e)}finally{n.f()}})}}function N(e,t){M=[];var n=function(e){return e.replace(/<table>/g,'<div class="table-responsive"><table class="table table-sm table-bordered table-striped align-middle">').replace(/<\/table>/g,"</table></div>")}(marked.parse(e,{renderer:E}));t._pendingCharts=M.length>0?_toConsumableArray(M):[];var i=DOMPurify.sanitize(n,{ADD_TAGS:["canvas"],ADD_ATTR:["target"]});return window.CoreAIChatImageCarousel?window.CoreAIChatImageCarousel.stackAdjacentImages(i):i}marked.use({extensions:[{name:"chart",level:"block",start:function(e){var t=e.indexOf("[chart:");return t>=0?t:void 0},tokenizer:function(e){var t=k(e);if(t&&0===t.startIndex){var n="chat_chart_".concat(++_);return{type:"chart",raw:e.substring(0,t.endIndex),chartId:n,json:t.json}}},renderer:function(e){return M.push({chartId:e.chartId,config:e.json}),window.__chartConfigs[e.chartId]=e.json,t=e.chartId,'<div class="chart-container" style="position: relative; width: 100%; max-width: 560px; min-height: 420px;">'+'<canvas id="'.concat(t,'"></canvas>')+'</div><div class="mt-2">'+'<button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="'.concat(t,'" title="').concat(u.downloadChartTitle,'">')+'<i class="fa-solid fa-download"></i> '.concat(u.downloadChartButtonText)+"</button></div>";var t}}]});var L=function(e){var t,n=Object.assign({},u,(t=e)&&"object"===_typeof(t)?Object.fromEntries(Object.entries(t).filter(function(e){return void 0!==_slicedToArray(e,2)[1]})):{});if(u=n,n.signalRHubUrl)if(n.appElementSelector)if(n.chatContainerElementSelector)if(n.inputElementSelector){if(n.sendButtonElementSelector){var i=Vue.createApp({data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isInteractionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],prompt:"",initialFieldValues:new Map,settingsDirty:!1,saveSettingsTimeout:null,saveIndicatorTimeout:null,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===n.chatMode||"Conversation"===n.chatMode,textToSpeechEnabled:"Conversation"===n.chatMode||!!n.textToSpeechEnabled,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:"chat-interaction-"+Math.random().toString(36).slice(2),conversationModeEnabled:"Conversation"===n.chatMode,conversationButton:null,isConversationMode:!1,realtimeController:null,realtimeButton:null,realtimeEnabled:!0===n.realtimeEnabled,notifications:[],notificationDismissTimers:{},copyTitle:n.copyTitle,copiedTitle:n.copiedTitle,copiedMessageIndex:-1,copyResetTimeoutId:null,activeCopyButton:null}},computed:{lastAssistantIndex:function(){for(var e=this.messages.length-1;e>=0;e--)if("assistant"===this.messages[e].role)return e;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},startConnection:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var i;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return e.connection=(new signalR.HubConnectionBuilder).withUrl(n.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadInteraction",function(t){var n;e.initializeInteraction(t.itemId,!0),e.messages=[];var i=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');i&&t.title&&(i.value=t.title),(null!==(n=t.messages)&&void 0!==n?n:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){B(t)})})}),e.connection.on("SettingsSaved",function(t,i){var a=document.querySelector('.chat-interaction-history-item[data-interaction-id="'.concat(t,'"]'));a&&(a.textContent=i||n.untitledText);var o=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');o&&i&&(o.value=i),e.showSaveIndicator("Saved","text-success")}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.showSaveIndicator("Save failed","text-danger"),e.isRecording&&e.stopRecording()}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var a='<p class="ai-partial-transcript">'+n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=a):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:a,isPartial:!0},e.messages.push(e._conversationPartialMessage)),e.scrollToBottom()}}else n&&!e._audioInputSent&&(e.prompt=e.preRecordingPrompt+n,e.inputElement&&(e.inputElement.value=e.prompt,e.inputElement.dispatchEvent(new Event("input"))))}),e.connection.on("ReceiveConversationUserMessage",function(t,n,i){if(n&&e._realtimePendingTurns&&e._realtimePendingTurns[n]){var a=e._realtimePendingTurns[n];if(delete e._realtimePendingTurns[n],e.stopAudio(),i)a.content=i,a.rawContent=i,a.isPartial=!1,x(a,a.references);else{var o=e.messages.indexOf(a);o>=0&&e.messages.splice(o,1)}}else if(i){if(e.stopAudio(),e._conversationPartialMessage){var r=i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");e._conversationPartialMessage.content=i,e._conversationPartialMessage.htmlContent="<p>"+r+"</p>",e._conversationPartialMessage.isPartial=!1,e._conversationPartialMessage=null}else if(e._conversationAssistantMessage){var s=e._conversationAssistantMessage.index,c={role:"user",content:i,rawContent:i,references:{}};x(c,c.references),e.messages.splice(s,0,c),e._conversationAssistantMessage.index=s+1}else e.addMessage({role:"user",content:i});e.scrollToBottom()}}),e.connection.on("ReceiveConversationAssistantToken",function(t,n,i,a,o,r){if(e._conversationAssistantMessage&&e._conversationAssistantResponseId&&a&&e._conversationAssistantResponseId!==a){var s=e.messages[e._conversationAssistantMessage.index];s&&(s.isStreaming=!1),e._conversationAssistantMessage=null}if(!e._conversationAssistantMessage){e.stopAudio(),e.hideTypingIndicator();for(var c=0;c<e.messages.length;c++)e.messages[c].isStreaming&&(e.messages[c].isStreaming=!1);var l=e.messages.length,u={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,appearance:e.normalizeAssistantAppearance(r),references:{}};e.messages.push(u),e._conversationAssistantMessage={index:l,content:""},e._conversationAssistantResponseId=a}e._conversationAssistantMessage.content+=i;var d=e.messages[e._conversationAssistantMessage.index];d&&(d.appearance||(d.appearance=e.normalizeAssistantAppearance(r)),d.rawContent=e._conversationAssistantMessage.content,d.references=v(Object.assign({},d.references||{},o||{})),x(d,d.references),e.$nextTick(function(){B(d),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n,i){if(e._conversationAssistantMessage){var a=e.messages[e._conversationAssistantMessage.index];a&&(a.isStreaming=!1,a.references=v(Object.assign({},a.references||{},i||{})),x(a,a.references)),e._conversationAssistantMessage=null,e._conversationAssistantResponseId=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var a=atob(n),o=new Uint8Array(a.length),r=0;r<a.length;r++)o[r]=a.charCodeAt(r);"audio/pcm"===i&&e.realtimeController?e.realtimeController.receivePcm(o):e.audioChunks.push(o)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("HistoryCleared",function(t){e.messages=[],e.showPlaceholder();var n=document.getElementById("clearHistoryBtn");n&&n.classList.add("d-none")}),e.connection.on("ReceiveNotification",function(t){e.receiveNotification(t)}),e.connection.on("UpdateNotification",function(t){e.updateNotification(t)}),e.connection.on("RemoveNotification",function(t){e.removeNotification(t)}),e.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),e.connection.onreconnected(function(){console.info("SignalR: reconnected."),e.reloadCurrentInteraction()}),e.connection.onclose(function(t){e.isNavigatingAway||t&&console.warn("SignalR connection closed with error:",t.message||t)}),t.p=1,t.n=2,e.connection.start();case 2:t.n=4;break;case 3:t.p=3,i=t.v,console.error("SignalR Connection Error: ",i);case 4:return t.a(2)}},t,null,[[1,3]])}))()},addMessageInternal:function(e){var t=this;"assistant"===e.role&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=N(e.content,e)),this.fireEvent(new CustomEvent("addingChatInteractionMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedChatInteractionMessage",{detail:{message:e}}))})},addMessage:function(e){var t,n=this;e.content&&(e.rawContent=null!==(t=e.rawContent)&&void 0!==t?t:e.content,x(e,e.references));this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(function(){B(e),n.scrollToBottom()})},hidePlaceholder:function(){this.placeholder&&this.placeholder.classList.add("d-none"),this.isPlaceholderVisible=!1},showPlaceholder:function(){this.placeholder&&this.placeholder.classList.remove("d-none"),this.isPlaceholderVisible=!0},fireEvent:function(e){document.dispatchEvent(e)},normalizeAssistantAppearance:function(e){if(!e)return null;var t="string"==typeof e.label?e.label.trim():"",n="string"==typeof e.icon?e.icon.trim():"",i="string"==typeof e.cssClass?e.cssClass.trim():"",a=!!e.disableStreamingAnimation;return t||n||i||a?{label:t,icon:n,cssClass:i,disableStreamingAnimation:a}:null},getAssistantLabel:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:u.assistantLabel},getAssistantRoleClasses:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=["ai-chat-msg-role"];return t&&t.cssClass?n.push(t.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var n,i;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:if(n=e.prompt.trim()){t.n=1;break}return t.a(2);case 1:return e.endActiveVoiceSession(),e.isRecording&&e.stopRecording(),e._audioInputSent=!0,t.n=2,e.flushPendingSave();case 2:e.addMessage({role:"user",content:n}),(i=document.getElementById("clearHistoryBtn"))&&i.classList.remove("d-none"),e.streamMessage(n),e.inputElement.value="",e.prompt="";case 3:return t.a(2)}},t)}))()},streamMessage:function(e){var t=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var n="",i={},a=null,o=this.messages.length,r=this.getItemId();this.stream=this.connection.stream("SendMessage",r,e).subscribe({next:function(e){var s=t.messages[o];if(!s){e.sessionId&&!r&&t.setItemId(e.sessionId),t.hideTypingIndicator(),o=t.messages.length;var c={role:"assistant",content:"",htmlContent:"",isStreaming:!0};t.messages.push(c),s=c}if(e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length)for(var l=0,u=Object.entries(e.references);l<u.length;l++){var d,m=_slicedToArray(u[l],2),f=m[0],h=m[1];i[f]=null!==(d=p(h))&&void 0!==d?d:{}}e.content&&(e.responseId&&a&&e.responseId!==a&&(n+="\n\n"),e.responseId&&(a=e.responseId),n+=e.content),s.rawContent=n,x(s,i),t.messages[o]=s,t.$nextTick(function(){B(s),t.scrollToBottom()})},complete:function(){var e;t.processReferences(i,o),t.streamingFinished();var n=t.messages[o];n&&(n.isStreaming=!1),n&&n.content||t.hideTypingIndicator(),t.isConversationMode&&t.textToSpeechEnabled&&n&&n.content&&t.synthesizeSpeech(n.content),null===(e=t.stream)||void 0===e||e.dispose(),t.stream=null},error:function(e){var n;t.processReferences(i,o),t.streamingFinished();var a=t.messages[o];a&&(a.isStreaming=!1),t.hideTypingIndicator(),t.isNavigatingAway||t.addMessage(t.getServiceDownMessage()),null===(n=t.stream)||void 0===n||n.dispose(),t.stream=null,console.error("Stream error:",e)}})},getServiceDownMessage:function(){return{role:"assistant",content:"Our service is currently unavailable. Please try again later. We apologize for the inconvenience.",htmlContent:""}},processReferences:function(e,t){var n=this;if(e=v(e),Object.keys(e).length){var i,a,o=this.messages[t];o.rawContent=null!==(i=null!==(a=o.rawContent)&&void 0!==a?a:o.content)&&void 0!==i?i:"",x(o,e),this.messages[t]=o,this.$nextTick(function(){B(o),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),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);this.settingsDirty&&this.debouncedSaveSettings()},handleExternalTtsStop:function(e){var t;(null==e||null===(t=e.detail)||void 0===t?void 0:t.sourceId)!==this.ttsInstanceId&&this.stopAudio(!1)},updateTtsPlaybackButtons:function(){var e=this;this.chatContainer&&this.chatContainer.querySelectorAll("[data-tts-message-index]").forEach(function(t){var n=Number(t.getAttribute("data-tts-message-index"))===e.ttsPlayingMessageIndex,i=n?'<i class="fa-solid fa-circle-pause"></i>':'<i class="fa-solid fa-circle-play"></i>';t.classList.toggle("tts-playing",n),t.setAttribute("title",n?"Pause audio":"Read aloud"),t.replaceChildren(DOMPurify.sanitize(i,{RETURN_DOM_FRAGMENT:!0}))})},updateCopyButtons:function(){var e=this;this.chatContainer&&this.chatContainer.querySelectorAll("[data-copy-message-index]").forEach(function(t){var n=Number(t.getAttribute("data-copy-message-index"))===e.copiedMessageIndex,i=n?'<i class="fa-solid fa-check"></i>':'<i class="fa-solid fa-copy"></i>';t.classList.toggle("text-success",n),t.classList.toggle("text-secondary",!n),t.setAttribute("title",n?e.copiedTitle:e.copyTitle),t.replaceChildren(DOMPurify.sanitize(i,{RETURN_DOM_FRAGMENT:!0}))})},setCopyButtonState:function(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:function(e,t){var n=this;this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=void 0!==t?t:-1,this.connection.invoke("SynthesizeSpeech",this.getItemId(),e,this.ttsVoiceName).catch(function(e){console.error("TTS synthesis error:",e),n.isPlayingAudio=!1,n.ttsPlayingMessageIndex=-1,n._ttsCacheIndex=-1,n.$nextTick(function(){return n.updateTtsPlaybackButtons()})}))},toggleMessageTts:function(e,t){var n=this;this.ttsPlayingMessageIndex!==t?(this.stopAudio(!1),window.dispatchEvent(new CustomEvent("crestapps-ai-chat-stop-tts",{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=t,this.$nextTick(function(){return n.updateTtsPlaybackButtons()}),this.ttsAudioCache[t]?this.playAudioBlob(this.ttsAudioCache[t]):this.synthesizeSpeech(e.content,t)):this.stopAudio()},playCollectedAudio:function(){var e=this;if(0!==this.audioChunks.length){var t,n=this.audioChunks.reduce(function(e,t){return e+t.length},0),i=new Uint8Array(n),a=0,o=_createForOfIteratorHelper(this.audioChunks);try{for(o.s();!(t=o.n()).done;){var r=t.value;i.set(r,a),a+=r.length}}catch(e){o.e(e)}finally{o.f()}this.audioChunks=[];var s=new Blob([i],{type:"audio/mp3"});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=s,this._ttsCacheIndex=-1),this.isPlayingAudio&&this.currentAudioElement?this.audioPlayQueue.push(s):this.playAudioBlob(s)}else this.isPlayingAudio||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()}))},playAudioBlob:function(e){var t=this,n=URL.createObjectURL(e),i=new Audio(n);this.currentAudioUrl=n,this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.playNextInQueue()}),i.addEventListener("error",function(){t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.playNextInQueue()}),i.play().catch(function(e){console.error("Audio playback error:",e),t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.audioPlayQueue=[],t.isPlayingAudio=!1,t.ttsPlayingMessageIndex=-1,t.$nextTick(function(){return t.updateTtsPlaybackButtons()})})},playNextInQueue:function(){var e=this;if(this.audioPlayQueue.length>0){var t=this.audioPlayQueue.shift();this.playAudioBlob(t)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()}),this.conversationModeOnAudioEnded()},stopAudio:function(){var e=this;this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()})},setVoiceSessionLive:function(e){this.inputElement&&(this.inputElement.hidden=e),this.buttonElement&&(this.buttonElement.hidden=e),[this.realtimeButton,this.conversationButton].forEach(function(t){t&&t.classList.toggle("flex-grow-1",e)});var t=this.realtimeButton&&this.realtimeButton.nextElementSibling,n=t&&"realtime-audio-settings"===t.id?t:null;n&&(n.hidden=!e)},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},endActiveVoiceSession:function(){this.realtimeController&&this.realtimeController.isActive()?this.realtimeController.stop():this.isConversationMode&&this.stopConversationMode()},startConversationMode:function(){var e=this;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(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e._conversationSubject=new signalR.Subject,e._conversationStream=t;var i=window.AudioContext||window.webkitAudioContext;i&&(e._conversationAudioCtx=new i,e._conversationAnalyser=e._conversationAudioCtx.createAnalyser(),e._conversationAnalyser.fftSize=256,e._conversationAudioCtx.createMediaStreamSource(t).connect(e._conversationAnalyser));var a=Promise.resolve(),o=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&o){var n=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(n);for(var i=0,r=0;r<n.length;r++)i+=n[r];i/n.length>=30&&e.stopAudio()}a=a.then(_asyncToGenerator(_regenerator().m(function n(){var i,a,o,r;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,a=new Uint8Array(i),o=a.reduce(function(e,t){return e+String.fromCharCode(t)},""),r=btoa(o);try{e._conversationSubject.next(r)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var r=e.getItemId(),s=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",r,e._conversationSubject,n,s),e.mediaRecorder.start(250),e.isRecording=!0}).catch(function(t){console.error("Microphone access denied:",t),e.isConversationMode=!1,e.updateConversationButton()}))},stopConversationMode:function(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke("StopConversation").catch(function(){}),this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript="",this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=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:function(){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:function(){},conversationModeOnAudioEnded:function(){},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:n.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},scrollToBottom:function(){var e=this;this.autoScroll&&setTimeout(function(){e.chatContainer.scrollTop=e.chatContainer.scrollHeight-e.chatContainer.clientHeight},50)},handleUserInput:function(e){this.prompt=e.target.value},getItemId:function(){return this.inputElement.getAttribute("data-interaction-id")||this.inputElement.getAttribute("data-item-id")},getSaveIndicatorElement:function(){return n.saveIndicatorElementSelector?document.querySelector(n.saveIndicatorElementSelector):document.querySelector("[data-chat-interaction-save-indicator]")},showSaveIndicator:function(e,t){var n=this,i=this.getSaveIndicatorElement();i&&(i.textContent=e||"",i.className="settings-save-indicator "+(t||"text-muted"),this.saveIndicatorTimeout&&(clearTimeout(this.saveIndicatorTimeout),this.saveIndicatorTimeout=null),e&&(this.saveIndicatorTimeout=setTimeout(function(){i.textContent="",n.saveIndicatorTimeout=null},3e3)))},clearPendingSettingsSave:function(){this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null)},getFieldLabel:function(e){var t,n=null===(t=e.closest(".mb-3, .col-6, .col, .form-group, .form-floating"))||void 0===t?void 0:t.querySelector("label");return n?(n.textContent||"").replace(/\s+/g," ").trim()||e.dataset.setting||"This field":e.dataset.setting||"This field"},getValidationFeedbackElement:function(e){var t=e.nextElementSibling;return t&&t.classList.contains("invalid-feedback")||((t=document.createElement("div")).className="invalid-feedback",e.insertAdjacentElement("afterend",t)),t},clearSettingValidationError:function(e){e.classList.remove("is-invalid"),e.removeAttribute("aria-invalid");var t=e.nextElementSibling;t&&t.classList.contains("invalid-feedback")&&(t.textContent="")},setSettingValidationError:function(e,t){var n=this.getValidationFeedbackElement(e);e.classList.add("is-invalid"),e.setAttribute("aria-invalid","true"),n.textContent=t},getSettingValidationMessage:function(e){if(!e||e.disabled||"number"!==e.type)return null;var t=(e.value||"").trim();if(!t)return null;var n=Number(t),i=this.getFieldLabel(e);if(Number.isNaN(n))return"".concat(i," must be a valid number.");var a=e.getAttribute("min");if(null!==a&&n<Number(a))return"".concat(i," must be ").concat(a," or greater.");var o=e.getAttribute("max");return null!==o&&n>Number(o)?"".concat(i," must be ").concat(o," or less."):null},validateSettingInput:function(e){var t=this.getSettingValidationMessage(e);return t?(this.setSettingValidationError(e,t),!1):(this.clearSettingValidationError(e),!0)},validateSettings:function(){var e=this,t=!0;return this.getSettingInputs().forEach(function(n){t=e.validateSettingInput(n)&&t}),t},queueSettingsSave:function(){if(!this.validateSettings())return this.clearPendingSettingsSave(),this.settingsDirty=!1,void this.showSaveIndicator("Fix errors","text-danger");this.settingsDirty=!0,this.showSaveIndicator("Saving...","text-warning"),this.debouncedSaveSettings()},getSettingInputs:function(){var e=document.querySelectorAll(".setting-input[data-setting]");return e.length>0?e:document.querySelectorAll('input[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), select[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), textarea[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["])')},getSelectedGroupValues:function(e,t){var n=document.querySelectorAll('.capability-checkbox[data-save-group="'.concat(e,'"]:checked, .capability-checkbox[data-group="').concat(e,'"]:checked'));if(n.length>0){var i=[];return n.forEach(function(e){var t=e.getAttribute("data-item-id")||e.value;t&&i.push(t)}),i}if(!t)return[];var a=[];return document.querySelectorAll(t).forEach(function(e){var t=e.name.replace(".IsSelected",".ItemId"),n=document.querySelector('input[type="hidden"][name="'.concat(t,'"]'));n&&n.value&&a.push(n.value)}),a},getPromptTemplateSelections:function(){var e=[];return document.querySelectorAll(".prompt-template-card").forEach(function(t){var n=t.querySelector(".prompt-template-id-input"),i=t.querySelector(".prompt-template-parameters-input"),a=n?n.value:t.getAttribute("data-template-id");a&&e.push({templateId:a,promptParameters:i?(i.value||"").trim():""})}),e},receiveNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0?this.notifications.splice(t,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.scrollToBottom()}},updateNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e),this.scrollToBottom())}},scheduleNotificationDismiss:function(e){var t=this;e&&e.type&&e.autoDismissMs&&!(e.autoDismissMs<=0)&&(this.notificationDismissTimers[e.type]=setTimeout(function(){t.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss:function(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification:function(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(function(t){return t.type!==e})},dismissNotification:function(e){this.removeNotification(e)},handleNotificationAction:function(e,t){if(this.connection){var n=this.getItemId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){return console.error("Failed to handle notification action:",e)})}},setItemId:function(e){this.inputElement.setAttribute("data-interaction-id",e||""),this.inputElement.setAttribute("data-item-id",e||"")},resetInteraction:function(){this.setItemId(""),this.isInteractionStarted=!1,this.messages=[],this.showPlaceholder()},initializeApp:function(){var e=this;this.inputElement=document.querySelector(n.inputElementSelector),this.buttonElement=document.querySelector(n.sendButtonElementSelector),this.chatContainer=document.querySelector(n.chatContainerElementSelector),this.placeholder=document.querySelector(n.placeholderElementSelector);var t=this.getItemId();t&&this.loadInteraction(t),this.chatContainer.addEventListener("scroll",function(){if(e.stream){var t=e.chatContainer.scrollHeight-e.chatContainer.clientHeight-e.chatContainer.scrollTop<=30;e.autoScroll=t}}),this.inputElement.addEventListener("keyup",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||e.buttonElement.click())}),this.inputElement.addEventListener("input",function(t){e.handleUserInput(t),t.target.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)}),this.inputElement.addEventListener("paste",function(t){setTimeout(function(){e.prompt=e.inputElement.value,e.inputElement.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)},0)}),this.buttonElement.addEventListener("click",function(){if(null==e.stream)e.sendMessage();else if(e.stream.dispose(),e.stream=null,e.streamingFinished(),e.hideTypingIndicator(),e.messages.length>0){var t=e.messages[e.messages.length-1];"assistant"!==t.role||t.content?t.isStreaming&&(t.isStreaming=!1):e.messages.pop()}});for(var i=document.getElementsByClassName("chat-interaction-history-item"),a=0;a<i.length;a++)i[a].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-interaction-id");n?e.loadInteraction(n):console.error("An element with the class chat-interaction-history-item with no data-interaction-id set.")});for(var o=Array.isArray(n.messages)?n.messages:[],r=0;r<o.length;r++)this.addMessage(o[r]);this.chatContainer&&this.chatContainer.addEventListener("click",function(e){var t=e.target.closest(".ai-code-copy-btn");if(t){var i=t.closest(".ai-code-block")||t.closest("pre");if(i){var a=i.querySelector("code");if(a){navigator.clipboard.writeText(a.textContent);var o=n.codeCopiedText||"Copied!";t.innerHTML='<i class="fa-solid fa-check"></i> '+o,setTimeout(function(){t.innerHTML='<i class="fa-regular fa-copy"></i>'},2e3)}}}}),document.addEventListener("input",function(t){t.target.matches(".setting-input[data-setting]")&&(e.validateSettingInput(t.target),e.queueSettingsSave())}),document.addEventListener("change",function(t){if(t.target.matches(".setting-input[data-setting], .capability-checkbox[data-save-group], .capability-checkbox[data-group], .group-toggle, .ci-agent-global-toggle"))return t.target.matches(".setting-input[data-setting]")&&e.validateSettingInput(t.target),void e.queueSettingsSave();t.target.closest(".prompt-template-parameters-input, .prompt-template-id-input")&&e.queueSettingsSave()}),document.addEventListener("click",function(t){t.target.closest(".prompt-template-add-btn, .remove-prompt-template-btn")&&setTimeout(function(){e.queueSettingsSave()},0)});var s=document.getElementById("clearHistoryBtn");s&&s.addEventListener("click",function(){var t=s.getAttribute("data-interaction-id");t&&e.clearHistory(t)}),this.speechToTextEnabled&&n.micButtonElementSelector&&(this.micButton=document.querySelector(n.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&n.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(n.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()})),window.CoreAIRealtime&&n.realtimeButtonElementSelector&&(this.realtimeButton=document.querySelector(n.realtimeButtonElementSelector),this.realtimeController=window.CoreAIRealtime.attach({connection:this.connection,ensureConnected:function(){return Promise.resolve(e.connection)},sendStart:function(t,n,i,a,o,r){e.connection.send("StartRealtimeConversation",e.getItemId(),t,n,i,a,o,r)},webRtcEnabled:!0===n.realtimeWebRtcEnabled,sendStartWebRtc:function(t,n,i,a,o,r){e.connection.send("StartRealtimeWebRtc",e.getItemId(),t,n,i,a,o,r)},webRtcIceServers:Array.isArray(n.realtimeWebRtcIceServers)?n.realtimeWebRtcIceServers:void 0,voiceName:n.realtimeVoiceName||"",getVoiceName:function(){var e=n.realtimeVoiceSelectElementSelector?document.querySelector(n.realtimeVoiceSelectElementSelector):null;return e?e.value:""},capableDeployments:n.realtimeCapableDeployments||[],realtimeEnabled:!0===n.realtimeEnabled,selectors:{realtimeButton:n.realtimeButtonElementSelector,micButton:n.micButtonElementSelector,conversationButton:n.conversationButtonElementSelector},onSessionStateChanged:function(t){e.setVoiceSessionLive(t)},onActivate:function(){e.isConversationMode=!0,e._conversationPartialMessage=null,e._conversationAssistantMessage=null},onDeactivate:function(){if(e.isConversationMode=!1,e._conversationAssistantMessage){var t=e.messages[e._conversationAssistantMessage.index];t&&(t.isStreaming=!1),e._conversationAssistantMessage=null}},onEnterRealtimeMode:function(){e.isRecording&&e.stopRecording(),!e.isConversationMode||e.realtimeController&&e.realtimeController.isActive()||e.stopConversationMode()},onUserTurnPending:function(t){if(t){var n={role:"user",content:"",rawContent:"",references:{},isPartial:!0};x(n,n.references),e._realtimePendingTurns=e._realtimePendingTurns||{},e._realtimePendingTurns[t]=n,e.messages.push(n),e.scrollToBottom()}},onUserTurnDropped:function(t){if(t&&e._realtimePendingTurns){var n=e._realtimePendingTurns[t];if(n){delete e._realtimePendingTurns[t];var i=e.messages.indexOf(n);i>=0&&e.messages.splice(i,1)}}}}),this.setupRealtimeVoicePicker(n),this.setVoiceSessionLive(!1))},setupRealtimeVoicePicker:function(e){if(e.realtimeVoiceSelectElementSelector&&e.realtimeVoicesUrl){var t=document.querySelector(e.realtimeVoiceSelectElementSelector);if(t){var n=e.realtimeVoiceGroupElementSelector?document.querySelector(e.realtimeVoiceGroupElementSelector):null,i=e.conversationDeploymentSelectElementSelector?document.querySelector(e.conversationDeploymentSelectElementSelector):null,a=(e.realtimeCapableDeployments||[]).map(function(e){return(e||"").toLowerCase()}),o=e.realtimeVoiceName||"",r=this;i&&i.addEventListener("change",c),c()}}function s(){if(!r.conversationModeEnabled)return"";var t=i&&i.value||e.defaultRealtimeDeploymentName||(a.length?a[0]:"");return function(e){return e&&-1!==a.indexOf(e.toLowerCase())}(t)?t:""}function c(){return l.apply(this,arguments)}function l(){return(l=_asyncToGenerator(_regenerator().m(function i(){var a,c,l,u,d,m,f,h,p,g;return _regenerator().w(function(i){for(;;)switch(i.p=i.n){case 0:if(a=s(),c=!!a,n&&n.classList.toggle("d-none",!c),r.realtimeController&&r.realtimeController.applyMode(c),c){i.n=1;break}return i.a(2);case 1:return t.innerHTML='<option value="">Default voice</option>',i.p=2,i.n=3,fetch(e.realtimeVoicesUrl+"?deploymentName="+encodeURIComponent(a),{credentials:"same-origin"});case 3:if(l=i.v,u=(l.headers.get("content-type")||"").toLowerCase(),l.ok&&!(u.indexOf("json")<0)){i.n=4;break}return i.a(2);case 4:return i.n=5,l.json();case 5:if((d=i.v)&&Array.isArray(d.voices)){i.n=6;break}return i.a(2);case 6:m=new Map,f=_createForOfIteratorHelper(d.voices);try{for(f.s();!(h=f.n()).done;)p=h.value,g=p.gender||"Voices",m.has(g)||m.set(g,[]),m.get(g).push(p)}catch(e){f.e(e)}finally{f.f()}Array.from(m.keys()).sort(function(e,t){return e.localeCompare(t)}).forEach(function(e){var n=document.createElement("optgroup");n.label=e,m.get(e).forEach(function(e){var t=document.createElement("option");t.value=e.id,t.textContent=e.name,t.selected=e.id===o,n.appendChild(t)}),t.appendChild(n)}),i.n=8;break;case 7:i.p=7,i.v;case 8:return i.a(2)}},i,null,[[2,7]])}))).apply(this,arguments)}},loadInteraction:function(e){this.connection.invoke("LoadInteraction",e).catch(function(e){return console.error(e)})},reloadCurrentInteraction:function(){var e=this.getItemId();e&&this.loadInteraction(e)},clearHistory:function(e){var t=this,i=function(){t.realtimeController&&t.realtimeController.isActive()&&t.realtimeController.stop(),t.stream&&(t.stream.dispose(),t.stream=null,t.hideTypingIndicator(),t.streamingFinished()),t.connection.invoke("ClearHistory",e).catch(function(e){return console.error("Error clearing history:",e)})};"function"!=typeof confirmDialog?window.confirm(n.clearHistoryMessage||"Clear all messages?")&&i():confirmDialog({title:n.clearHistoryTitle,message:n.clearHistoryMessage,okText:n.clearHistoryOkText,cancelText:n.clearHistoryCancelText,callback:function(e){e&&i()}})},debouncedSaveSettings:function(){var e=this;this.clearPendingSettingsSave(),this.stream||(this.saveSettingsTimeout=setTimeout(function(){e.settingsDirty&&(e.saveSettings(),e.settingsDirty=!1),e.saveSettingsTimeout=null},850))},getSelectedToolNames:function(){return this.getSelectedGroupValues("toolNames",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Tools["]:checked')},getSelectedMcpConnectionIds:function(){return this.getSelectedGroupValues("mcpConnectionIds",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Connections["]:checked')},getSelectedA2AConnectionIds:function(){return this.getSelectedGroupValues("a2aConnectionIds")},getSelectedAgentNames:function(){return this.getSelectedGroupValues("agentNames",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Agents["]:checked')},saveSettings:function(){var e=this,t=this.getItemId();if(!t)return Promise.resolve();if(!this.validateSettings())return this.showSaveIndicator("Fix errors","text-danger"),Promise.resolve();var n={};this.getSettingInputs().forEach(function(e){var t=e.dataset.setting||(e.name||"").replace("ChatInteraction.","").replace(/^[A-Z]/,function(e){return e.toLowerCase()});t&&("checkbox"===e.type?n[t]=e.checked:"number"===e.type?n[t]=e.value?parseFloat(e.value):null:n[t]=e.value||null)}),n.toolNames=this.getSelectedToolNames(),n.mcpConnectionIds=this.getSelectedMcpConnectionIds(),n.a2aConnectionIds=this.getSelectedA2AConnectionIds(),n.agentNames=this.getSelectedAgentNames();var i=this.getPromptTemplateSelections();return i.length>0&&(n.promptTemplates=i,n.promptTemplateIds=i.map(function(e){return e.templateId})),this.connection.invoke("SaveSettings",t,n).catch(function(t){console.error("Error saving settings:",t),e.showSaveIndicator("Save failed","text-danger")})},flushPendingSave:function(){return this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null),this.settingsDirty?(this.settingsDirty=!1,this.saveSettings()):Promise.resolve()},initializeInteraction:function(e,t){this.isInteractionStarted&&!t||(this.fireEvent(new CustomEvent("initializingChatInteraction",{detail:{itemId:e}})),this.setItemId(e),this.isInteractionStarted=!0)},clearCopiedMessageState:function(){this.copyResetTimeoutId&&(window.clearTimeout(this.copyResetTimeoutId),this.copyResetTimeoutId=null),this.activeCopyButton&&(this.setCopyButtonState(this.activeCopyButton,!1),this.activeCopyButton=null),this.copiedMessageIndex=-1},copyResponse:function(e,t,i){var a,o,r,s,c=this,l=e&&"object"===_typeof(e)?null!==(a=null!==(o=e.copyContent)&&void 0!==o?o:e.content)&&void 0!==a?a:"":null!=e?e:"",u=(null==i?void 0:i.currentTarget)||(null==i||null===(r=i.target)||void 0===r||null===(s=r.closest)||void 0===s?void 0:s.call(r,"[data-copy-message-index]"))||null;navigator.clipboard.writeText(l).then(function(){c.clearCopiedMessageState(),c.copiedMessageIndex="number"==typeof t?t:-1,c.activeCopyButton=u,u?c.setCopyButtonState(u,!0):c.$nextTick(function(){return c.updateCopyButtons()}),c.copyResetTimeoutId=window.setTimeout(function(){c.clearCopiedMessageState(),c.$nextTick(function(){return c.updateCopyButtons()})},Number(n.copyResetDelayMs)||2e3)}).catch(function(e){return console.error("Failed to copy response:",e)})},startRecording:function(){var e=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e.preRecordingPrompt=e.prompt,e._audioInputSent=!1;var i=new signalR.Subject,a=e.getItemId(),o=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(o=o.then(_asyncToGenerator(_regenerator().m(function t(){var n,a,o,r;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,a=new Uint8Array(n),o=a.reduce(function(e,t){return e+String.fromCharCode(t)},""),r=btoa(o),i.next(r);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),o.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",a,i,n,r),e.mediaRecorder.start(250),e.isRecording=!0,e.updateMicButton()}).catch(function(e){console.error("Microphone access denied:",e)})},stopRecording:function(){this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1,this.updateMicButton())},toggleRecording:function(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton:function(){this.micButton&&(this.isRecording?(this.micButton.classList.add("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-stop"></i>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-microphone"></i>'))}},watch:{isPlayingAudio:function(){},isConversationMode:function(e){this.micButton&&(this.micButton.style.display=e?"none":this.speechToTextEnabled?"":"none"),this.realtimeEnabled||this.setVoiceSessionLive(e)},copiedMessageIndex:function(){var e=this;this.$nextTick(function(){return e.updateCopyButtons()})}},mounted:function(){var e=this;_asyncToGenerator(_regenerator().m(function t(){return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.startConnection();case 1:e.initializeApp(),e.$nextTick(function(){e.updateCopyButtons(),f(e.$el),e.fontAwesomeObserver=h(e.$el)});case 2:return t.a(2)}},t)}))(),window.addEventListener("beforeunload",this.handleBeforeUnload),window.addEventListener("crestapps-ai-chat-stop-tts",this.handleExternalTtsStop)},beforeUnmount:function(){window.removeEventListener("beforeunload",this.handleBeforeUnload),window.removeEventListener("crestapps-ai-chat-stop-tts",this.handleExternalTtsStop),this.fontAwesomeObserver&&(this.fontAwesomeObserver.disconnect(),this.fontAwesomeObserver=null),this.clearCopiedMessageState(),this.stopAudio(!1),this.stream&&(this.stream.dispose(),this.stream=null),this.connection&&this.connection.stop()},template:n.messageTemplate}).mount(n.appElementSelector);return i}console.error("The sendButtonElementSelector is required.")}else console.error("The inputElementSelector is required.");else console.error("The chatContainerElementSelector is required.");else console.error("The appElementSelector is required.");else console.error("The signalRHubUrl is required.")},D="[data-chat-interaction-config]";function O(e){if(!e||"true"===e.dataset.chatInteractionInitialized)return e&&e.__chatInteractionApp||null;var t=function(e,t,n){var i=e.getAttribute(t);if(!i)return null;try{return JSON.parse(i)}catch(e){return console.error("Failed to parse "+n+" JSON.",e),null}}(e,"data-chat-interaction-config","chat interaction config");if(!t)return null;var n=L(t);return n?(e.dataset.chatInteractionInitialized="true",e.__chatInteractionApp=n,n):null}function j(e){e&&"function"==typeof e.querySelectorAll&&("function"==typeof e.matches&&e.matches(D)&&O(e),e.querySelectorAll(D).forEach(O))}function U(){(j(document),"undefined"!=typeof MutationObserver)&&new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){e&&1===e.nodeType&&j(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",U,{once:!0}):U(),{initialize:L,initializeFromElement:O}}(),window.chatInteractionDocumentManager=function(){var e="__chatInteractionDocumentManagerState";function t(e){return e&&"object"===_typeof(e)?{documentId:e.documentId||e.DocumentId||"",fileName:e.fileName||e.FileName||"",fileSize:e.fileSize||e.FileSize||0}:null}function n(e){return!e||e<1024?(e||0)+" B":e<1048576?(e/1024).toFixed(1)+" KB":(e/1048576).toFixed(1)+" MB"}function i(e,t){return(e||"").trim().toLowerCase()+"::"+(t||0)}function a(e,t){return t.has(i(e.name,e.size))}function o(o){if(o&&o.itemId){var r=document.getElementById("chat-doc-upload"),s=document.getElementById("chat-documents-list"),c=document.getElementById("chat-doc-upload-status"),l=document.getElementById("chat-doc-upload-progress"),u=document.getElementById("chat-doc-upload-progress-bar"),d=document.getElementById("chat-doc-upload-queue");if(r&&s&&c&&l&&u&&d){var m=r[e];m&&"function"==typeof m.dispose&&m.dispose();var f,h=(Array.isArray(o.existingDocuments)?o.existingDocuments:[]).map(t).filter(function(e){return e&&e.documentId});0===h.length&&(h=(f=s)?Array.from(f.querySelectorAll("[data-chat-document-id]")).map(function(e){return t({documentId:e.dataset.chatDocumentId,fileName:e.dataset.chatDocumentName,fileSize:Number(e.dataset.chatDocumentSize||0)})}).filter(function(e){return e&&e.documentId}):[]);var p=[],g=!1,v=function(e){!function(e){E.apply(this,arguments)}(e.target.files?Array.from(e.target.files):[])};return r.addEventListener("change",v),r[e]={dispose:function(){r.removeEventListener("change",v)}},b(),A(),C(null),S(null),r[e]}}function y(e,t,n){var i=document.createElement(e);return t&&(i.className=t),i.textContent=n,i}function b(){s.innerHTML="",0!==h.length?h.forEach(function(e){var t=window.document.createElement("div");t.className="d-flex align-items-center gap-2 border rounded px-2 py-2 bg-white chat-document-row",t.dataset.chatDocumentId=e.documentId,t.dataset.chatDocumentName=e.fileName,t.dataset.chatDocumentSize=e.fileSize;var i=window.document.createElement("div");i.className="d-flex gap-1";var a=o.downloadDocumentBaseUrl||"/ai/documents/",r=y("a","btn btn-sm btn-outline-secondary","");r.title="Download",r.href=a+encodeURIComponent(e.documentId)+"/download";var c=window.document.createElement("i");c.className="fa-solid fa-download",r.appendChild(c);var l=y("button","btn btn-sm btn-outline-danger remove-chat-document-btn","");l.type="button",l.title="Remove",l.dataset.documentId=e.documentId;var u=window.document.createElement("i");u.className="fa-solid fa-trash",l.appendChild(u),l.addEventListener("click",function(){return function(e){return _.apply(this,arguments)}(e.documentId)}),i.appendChild(r),i.appendChild(l);var d=window.document.createElement("div");d.className="min-w-0";var m=y("div","fw-semibold small text-truncate",e.fileName||"Document"),f=window.document.createElement("i");f.className="fa-solid fa-file-lines me-1",m.prepend(f);var h=y("div","text-muted small",n(e.fileSize));d.appendChild(m),d.appendChild(h),t.appendChild(i),t.appendChild(d),s.appendChild(t)}):s.appendChild(y("div","text-muted small","No documents uploaded yet."))}function C(e,t){if(!e)return c.textContent="",void(c.className="small mt-2 d-none");c.textContent=e,c.className="small mt-2 "+(t||"text-muted")}function S(e,t,n){if(null==e)return l.className="progress mt-2 d-none",l.setAttribute("aria-valuenow","0"),u.className="progress-bar progress-bar-striped progress-bar-animated",u.style.width="0%",void(u.textContent="0%");var i=Math.max(0,Math.min(100,Math.round(e)));l.className="progress mt-2",l.setAttribute("aria-valuenow",i.toString()),u.className="progress-bar "+(n||"progress-bar-striped progress-bar-animated"),u.style.width=i+"%",u.textContent=t||i+"%"}function A(){d.innerHTML="",p.forEach(function(e){var t=function(e){switch(e){case"uploaded":return{label:"Uploaded",badgeClass:"text-bg-success",progressClass:"bg-success"};case"failed":return{label:"Failed",badgeClass:"text-bg-danger",progressClass:"bg-danger"};case"uploading":return{label:"Uploading",badgeClass:"text-bg-warning",progressClass:"bg-warning progress-bar-striped progress-bar-animated"};default:return{label:"Queued",badgeClass:"text-bg-secondary",progressClass:"bg-secondary progress-bar-striped progress-bar-animated"}}}(e.status),i=document.createElement("div");i.className="border rounded px-2 py-2 bg-white";var a=document.createElement("div");a.className="d-flex justify-content-between align-items-start gap-2";var o=document.createElement("div");o.className="flex-grow-1 min-w-0",o.appendChild(y("div","fw-semibold small",e.fileName)),o.appendChild(y("div","text-muted small",n(e.fileSize)));var r=y("span","badge "+t.badgeClass,t.label);a.appendChild(o),a.appendChild(r);var s=document.createElement("div");s.className="progress mt-2",s.setAttribute("role","progressbar"),s.setAttribute("aria-valuemin","0"),s.setAttribute("aria-valuemax","100"),s.setAttribute("aria-valuenow",e.progress.toString());var c=document.createElement("div");c.className="progress-bar "+t.progressClass,c.style.width=e.progress+"%",c.textContent=e.progress+"%",s.appendChild(c);var l=y("div","failed"===e.status?"small text-danger mt-2":"small text-muted mt-2",function(e){return"failed"===e.status&&e.error?e.error:"uploaded"===e.status?"Upload completed successfully.":"uploading"===e.status?e.progress+"% uploaded":"Waiting to upload..."}(e));i.appendChild(a),i.appendChild(s),i.appendChild(l),d.appendChild(i)})}function I(e,t){return{id:e.name+"::"+e.size+"::"+e.lastModified+"::"+t+"::"+Date.now(),fileName:e.name,fileSize:e.size,status:"queued",progress:0,error:null}}function T(e,t){p=p.map(function(n){return n.id===e?Object.assign({},n,t):n}),A()}function w(e){p=p.filter(function(t){return!e(t)}),A()}function x(e,t,n,i){return new Promise(function(a,r){var s=new FormData;s.append("chatInteractionId",o.itemId),s.append("files",e);var c=new XMLHttpRequest;c.open("POST",o.uploadDocumentUrl,!0),c.upload.addEventListener("progress",function(e){if(e.lengthComputable){var a=Math.round(e.loaded/e.total*100);T(t,{status:"uploading",progress:a}),S((n+e.loaded/e.total)/i*100,"Uploading "+(n+1)+" of "+i,"progress-bar-striped progress-bar-animated")}}),c.addEventListener("load",function(){if(c.status>=200&&c.status<300)try{a(JSON.parse(c.responseText))}catch(e){r(new Error("Upload failed: invalid server response."))}else r(new Error((c.responseText||"Upload failed.").trim()))}),c.addEventListener("error",function(){r(new Error("Upload failed. Please check your connection and try again."))}),c.send(s)})}function E(){return(E=_asyncToGenerator(_regenerator().m(function e(n){var s,c,l,u,d,m,f,v,y,E,_,M,k,R,P,B,N;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(o.uploadDocumentUrl&&n&&0!==n.length){e.n=1;break}return e.a(2);case 1:if(!g){e.n=2;break}return C("A document upload is already in progress.","text-warning"),e.a(2);case 2:if(g=!0,s=[],c=[],l=new Set(h.map(function(e){return i(e.fileName,e.fileSize)})),Array.from(n).forEach(function(e){a(e,l)?c.push(e):(l.add(i(e.name,e.size)),s.push(e))}),c.length>0&&(p=p.concat(c.map(function(e,t){return Object.assign(I(e,t),{status:"failed",progress:100,error:"This document is already attached."})})),A()),0!==s.length){e.n=3;break}return g=!1,C(c.map(function(e){return e.name+": This document is already attached."}).join(" | "),"text-warning"),S(null),e.a(2);case 3:u=s.map(I),p=p.concat(u),A(),S(0,"Preparing upload...","progress-bar-striped progress-bar-animated"),r.disabled=!0,e.p=4,d=0,m=c.map(function(e){return e.name+": This document is already attached."}),f=0;case 5:if(!(f<s.length)){e.n=10;break}return v=s[f],T((y=u[f]).id,{status:"uploading",progress:0,error:null}),C("Uploading "+(f+1)+" of "+s.length+" document(s)...","text-warning"),e.p=6,e.n=7,x(v,y.id,f,s.length);case 7:E=e.v,_=(Array.isArray(E.uploaded)?E.uploaded:[]).map(t).filter(function(e){return e&&e.documentId}),M=Array.isArray(E.failed)?E.failed:[],_.length>0?(d+=_.length,h=h.concat(_),T(y.id,{status:"uploaded",progress:100,error:null})):(k=M.length>0?M.map(function(e){return e.fileName+": "+e.error}).join(" | "):"The server did not confirm that the file was uploaded.",0===M.length&&m.push(k),T(y.id,{status:"failed",progress:100,error:k})),M.length>0&&(R=M.map(function(e){return e.fileName+": "+e.error}).join(" | "),m.push(R),T(y.id,{status:"failed",progress:100,error:R})),e.n=9;break;case 8:e.p=8,B=e.v,P=B&&B.message?B.message:"Upload failed. Please try again.",console.error("Upload failed:",B),m.push(v.name+": "+P),T(y.id,{status:"failed",progress:y.progress||0,error:P});case 9:f++,e.n=5;break;case 10:if(b(),!(m.length>0)){e.n=11;break}return w(function(e){return"uploaded"===e.status}),C((d>0?"Uploaded "+d+" document(s). ":"")+m.join(" | "),d>0?"text-warning":"text-danger"),S(null),e.a(2);case 11:w(function(){return!0}),C("Uploaded "+d+" document(s).","text-success"),S(null),e.n=13;break;case 12:e.p=12,N=e.v,console.error("Upload failed:",N),C("Upload failed. Please try again.","text-danger"),S(null);case 13:return e.p=13,g=!1,r.disabled=!1,r.value="",e.f(13);case 14:return e.a(2)}},e,null,[[6,8],[4,12,13,14]])}))).apply(this,arguments)}function _(){return(_=_asyncToGenerator(_regenerator().m(function e(n){var i,a,r,s,c;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(o.removeDocumentUrl&&n&&window.confirm("Remove this document?")){e.n=1;break}return e.a(2);case 1:return e.p=1,e.n=2,fetch(o.removeDocumentUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({itemId:o.itemId,documentId:n})});case 2:if((i=e.v).ok){e.n=4;break}return s=console,e.n=3,i.text();case 3:return s.error.call(s,"Failed to remove document:",e.v),C("Failed to remove document.","text-danger"),e.a(2);case 4:if(!((i.headers.get("content-type")||"").toLowerCase().indexOf("json")<0)){e.n=5;break}return console.error("Remove document: response was not JSON.",{status:i.status,redirected:i.redirected}),C(i.redirected?"You may not be signed in, or you do not have permission for this. Please reload and try again.":"Failed to remove document.","text-danger"),e.a(2);case 5:return e.n=6,i.json();case 6:a=e.v,r=(Array.isArray(a.documents)?a.documents:[]).map(t).filter(function(e){return e&&e.documentId}),h=r.length>0?r:h.filter(function(e){return e.documentId!==n}),b(),C("Document removed.","text-success"),e.n=8;break;case 7:e.p=7,c=e.v,console.error("Remove failed:",c),C("Failed to remove document.","text-danger");case 8:return e.a(2)}},e,null,[[1,7]])}))).apply(this,arguments)}}function r(t){if(!t||"true"===t.dataset.chatInteractionDocumentManagerInitialized)return t&&t[e]||null;var n=function(e,t,n){var i=e.getAttribute(t);if(!i)return null;try{return JSON.parse(i)}catch(e){return console.error("Failed to parse "+n+" JSON.",e),null}}(t,"data-chat-interaction-document-manager-config","chat interaction document manager config");if(!n)return null;var i=o(n);return i?(t.dataset.chatInteractionDocumentManagerInitialized="true",i):null}function s(e){e&&"function"==typeof e.querySelectorAll&&("function"==typeof e.matches&&e.matches("[data-chat-interaction-document-manager-config]")&&r(e),e.querySelectorAll("[data-chat-interaction-document-manager-config]").forEach(r))}function c(){(s(document),"undefined"!=typeof MutationObserver)&&new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){e&&1===e.nodeType&&s(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",c,{once:!0}):c(),{initialize:o,initializeFromElement:r}}(),document.addEventListener("click",function(e){var t=e.target.closest(".download-chart-btn");if(t){var n=t.getAttribute("data-chart-id"),i=n?document.getElementById(n):null;if(i){var a=document.createElement("a");a.download="chart-"+n+".png",a.href=i.toDataURL("image/png"),a.click()}else console.error("Chart canvas not found:",n)}}),document.addEventListener("click",function(e){var t=e.target.closest(".ai-download-image");if(t){var n=t.closest(".generated-image-container"),i=null==n?void 0:n.querySelector("img");if(i){var a=i.src;a&&a.startsWith("data:")&&(e.preventDefault(),fetch(a).then(function(e){return e.blob()}).then(function(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error("Failed to download image:",e)}))}}});
1
+ (function(){window.chatInteractionManager=function(){var e={generatedImageAltText:`Generated Image`,generatedImageMaxWidth:400,downloadImageTitle:`Download image`,downloadChartTitle:`Download chart as image`,downloadChartButtonText:`Download`,codeCopiedText:`Copied!`,copyTitle:`Click here to copy response to clipboard.`,copiedTitle:`Response copied to clipboard.`,copyResetDelayMs:2e3,assistantLabel:`Assistant`,messageTemplate:`
2
+ <div class="ai-chat-messages">
3
+ <div v-for="(message, index) in messages" :key="index" class="ai-chat-message-item">
4
+ <div>
5
+ <div v-if="message.role === 'user'" class="ai-chat-msg-role ai-chat-msg-role-user">You</div>
6
+ <div v-else-if="message.role !== 'indicator'" :class="getAssistantRoleClasses(message)">
7
+ <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>
8
+ {{ getAssistantLabel(message) }}
9
+ </div>
10
+ <div class="ai-chat-message-body lh-base">
11
+ <h4 v-if="message.title">{{ message.title }}</h4>
12
+ <div v-html="message.htmlContent"></div>
13
+ <ol v-if="message.citationReferences && message.citationReferences.length" class="ai-chat-citation-list">
14
+ <li v-for="citation in message.citationReferences" :key="'citation-' + (citation.referenceKey || citation.displayIndex)" class="ai-chat-citation-item">
15
+ <a v-if="citation.link" :href="citation.link" :target="citation.isDownload ? null : '_blank'" :rel="citation.isDownload ? null : 'noopener noreferrer'">{{ citation.label }}</a>
16
+ <span v-else>{{ citation.label }}</span>
17
+ </li>
18
+ </ol>
19
+ <span class="message-buttons-container" v-if="!isIndicator(message)">
20
+ <button v-if="textToSpeechEnabled && !isConversationMode && message.role === 'assistant' && !message.isStreaming" class="btn btn-sm btn-link text-secondary p-0 me-1 button-message-toolbox" :class="{ 'tts-playing': ttsPlayingMessageIndex === index }" :data-tts-message-index="index" @click="toggleMessageTts(message, index)" :title="ttsPlayingMessageIndex === index ? 'Pause audio' : 'Read aloud'">
21
+ <i :class="ttsPlayingMessageIndex === index ? 'fa-solid fa-circle-pause' : 'fa-solid fa-circle-play'"></i>
22
+ </button>
23
+ <button type="button" class="btn btn-sm btn-link p-0 button-message-toolbox ai-response-copy-btn" :class="copiedMessageIndex === index ? 'text-success' : 'text-secondary'" :data-copy-message-index="index" @click="copyResponse(message, index, $event)" :title="copiedMessageIndex === index ? copiedTitle : copyTitle">
24
+ <i :class="copiedMessageIndex === index ? 'fa-solid fa-check' : 'fa-solid fa-copy'"></i>
25
+ </button>
26
+ </span>
27
+ </div>
28
+ </div>
29
+ </div>
30
+ <div v-for="notification in notifications" :key="'notif-' + notification.type" class="ai-chat-notification" :class="'ai-chat-notification-' + (notification.type || 'info') + ' ' + (notification.cssClass || '')">
31
+ <div class="ai-chat-notification-content">
32
+ <i v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></i>
33
+ <span class="ai-chat-notification-text">{{ notification.content }}</span>
34
+ <button v-if="notification.dismissible" class="btn btn-sm btn-link p-0 ms-2 ai-chat-notification-dismiss" @click="dismissNotification(notification.type)" title="Dismiss">
35
+ <i class="fa-solid fa-xmark"></i>
36
+ </button>
37
+ </div>
38
+ <div v-if="notification.actions && notification.actions.length" class="ai-chat-notification-actions">
39
+ <button v-for="action in notification.actions" :key="action.name" class="btn btn-sm" :class="action.cssClass || 'btn-outline-secondary'" @click="handleNotificationAction(notification.type, action.name)">
40
+ <i v-if="action.icon" :class="action.icon" class="me-1"></i>
41
+ {{ action.label }}
42
+ </button>
43
+ </div>
44
+ </div>
45
+ </div>
46
+ `,indicatorTemplate:`
47
+ <div class="ai-chat-msg-role ai-chat-msg-role-assistant">
48
+ <span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>
49
+ Assistant
50
+ </div>
51
+ `,untitledText:`Untitled`,clearHistoryTitle:`Clear History`,clearHistoryMessage:`Are you sure you want to clear the chat history? This action cannot be undone. Your documents, parameters, and tools will be preserved.`,clearHistoryOkText:`Yes`,clearHistoryCancelText:`Cancel`};function t(e){if(!e)return``;var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?``:e}function n(e){var t=document.createElement(`span`);return t.textContent=e,t.innerHTML}function r(e){if(!e||e.nodeType!==1)return!1;var t=`i[class*="fa-"],i.fa,i.fas,i.far,i.fab`;return typeof e.matches==`function`&&e.matches(t)?!0:typeof e.querySelector==`function`&&!!e.querySelector(t)}function i(e){var t=window.FontAwesome;r(e)&&t&&t.dom&&typeof t.dom.i2svg==`function`&&t.dom.i2svg({node:e})}function a(e){if(!e||typeof MutationObserver>`u`)return null;var t=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){i(e)})})});return t.observe(e,{childList:!0,subtree:!0}),t}function o(e){if(!e||typeof e!=`object`)return null;let n=Object.assign({},e);return n.index=n.index??n.Index??0,n.text=n.text??n.Text??null,n.title=n.title??n.Title??null,n.link=t(n.link??n.Link??null),n.referenceType=n.referenceType??n.ReferenceType??null,n.isGenerated=(n.isGenerated??n.IsGenerated)===!0,n.isImage=(n.isImage??n.IsImage)===!0,n}function s(e){return!e||typeof e!=`object`?!1:!!(typeof e.referenceType==`string`&&e.referenceType.toLowerCase()===`document`||typeof e.link==`string`&&/\/ai\/documents\/.+\/download(?:$|\?)/i.test(e.link))}function c(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))t[n]=o(r)??{};return t}let l=window.CoreAIChatMarkers.expandImageMarkers;function u(e,t){return e.title||e.text||t}let d=0,f=window.CoreAIChatMarkers?.citationIdentity??(()=>`unmerged-${++d}`),p=window.CoreAIChatMarkers?.splitCombinedCitations??(e=>e),m=window.CoreAIChatMarkers?.collapseRepeatedCitations??(e=>e),h=window.CoreAIChatMarkers?.separateAdjacentCitations??(e=>e),g=window.CoreAIChatMarkers?.citationMarkerHtml??(e=>`<sup>${e}</sup>`);function _(e,t){let n=p((e||``).trim()),r=c(t),i=Object.entries(r);if(!i.length)return{content:n,citations:[]};let a=i.filter(([e])=>n.includes(e)),o=i.filter(([e,t])=>t.isGenerated&&!n.includes(e));if(!a.length&&!o.length)return{content:n,citations:[]};a.sort(([,e],[,t])=>e.index-t.index),o.sort(([,e],[,t])=>e.index-t.index);let l=[],d=new Map,_=[],v=1;for(let[e,t]of a){let r=u(t,e),i=t.link||null,a=f(r,i),o=d.get(a);o||(o={referenceKey:e,referenceKeys:[],displayIndex:v++,label:r,link:i,isDownload:s(t)},d.set(a,o),l.push(o)),o.referenceKeys.push(e);let c=`__CITE_${o.displayIndex}_${t.index||o.displayIndex}__`;n=n.replaceAll(e,c),_.push({placeholder:c,displayIndex:o.displayIndex,label:o.label})}for(let e of _)n=n.replaceAll(e.placeholder,g(e.displayIndex,e.label));n=m(n),n=h(n);for(let[e,t]of o)l.push({referenceKey:e,referenceKeys:[e],displayIndex:v,label:u(t,e),link:t.link||null,isDownload:!0,placeholder:null}),v++;return{content:n,citations:l.map(({placeholder:e,...t})=>t)}}function v(e,t){let n=(e||``).trim();if(!n||!Array.isArray(t)||t.length===0)return n;for(let e of t)for(let t of e.referenceKeys?.length?e.referenceKeys:[e.referenceKey])n=n.replaceAll(t,`[${e.displayIndex}]`);n+=`
52
+
53
+ References:
54
+ `;for(let e of t)n+=`${e.displayIndex}. ${e.label}`,e.link&&(n+=` - ${e.link}`),n+=`
55
+ `;return n.trimEnd()}function y(e,t){let n=c(t??e.references),r=typeof e.rawContent==`string`?e.rawContent:typeof e.content==`string`?e.content:``,i=l(r,n),a=_(i,n);return e.rawContent=r,e.content=r,e.displayContent=a.content,e.references=n,e.citationReferences=a.citations,e.copyContent=v(p(i),a.citations),e.htmlContent=A(a.content,e),e}let b=new marked.Renderer;b.link=function(e){var n=t(e.href);return n?`<a href="${n}" target="_blank" rel="noopener noreferrer">${e.text}</a>`:e.text||``},b.code=function(e){var t=e.text||``,r=(e.lang||``).trim(),i=t;if(typeof hljs<`u`){if(r&&hljs.getLanguage(r))try{i=hljs.highlight(t,{language:r}).value}catch{}else try{i=hljs.highlightAuto(t).value}catch{}}else i=n(t);return`<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><i class="fa-solid fa-code"></i> ${r?n(r):`code`}</span><button type="button" class="ai-code-copy-btn" title="Copy code"><i class="fa-regular fa-copy"></i></button></div><pre><code class="hljs${r?` language-`+r:``}">${i}</code></pre></div>`},b.image=function(n){let r=t(n.href);if(!r)return``;let i=n.text||e.generatedImageAltText;return`<span class="generated-image-container">
56
+ <img src="${r}" alt="${i}" class="img-thumbnail" style="max-width: ${e.generatedImageMaxWidth}px; height: auto;" />
57
+ <a href="${r}" target="_blank" download="${i}" title="${e.downloadImageTitle}" class="btn btn-sm btn-outline-secondary ai-download-image">
58
+ <i class="fa-solid fa-download"></i>
59
+ </a>
60
+ </span>`};let x=0,S=[];window.__chartConfigs=window.__chartConfigs||{};function C(t){return`<div class="chart-container" style="position: relative; width: 100%; max-width: 560px; min-height: 420px;"><canvas id="${t}"></canvas></div><div class="mt-2"><button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="${t}" title="${e.downloadChartTitle}"><i class="fa-solid fa-download"></i> ${e.downloadChartButtonText}</button></div>`}let w=window.CoreAIChatMarkers.findChartMarker;marked.use({extensions:[{name:`chart`,level:`block`,start(e){let t=e.indexOf(`[chart:`);return t>=0?t:void 0},tokenizer(e){let t=w(e);if(!t||t.startIndex!==0)return;let n=`chat_chart_${++x}`;return{type:`chart`,raw:e.substring(0,t.endIndex),chartId:n,json:t.json}},renderer(e){return S.push({chartId:e.chartId,config:e.json}),window.__chartConfigs[e.chartId]=e.json,C(e.chartId)}}]});function T(){typeof document<`u`&&typeof requestAnimationFrame==`function`&&(requestAnimationFrame(D),requestAnimationFrame(E))}function E(){if(typeof mediumZoom!=`function`)return;let e=document.querySelectorAll(`.generated-image-container img:not([data-zoom-wired])`);if(e.length!==0){for(let t of e)t.setAttribute(`data-zoom-wired`,`true`);mediumZoom(e,{margin:16,background:`rgba(15, 15, 15, 0.92)`})}}function D(){let e=document.querySelectorAll(`.generated-image-container img:not([data-broken-wired])`);for(let t of e)t.setAttribute(`data-broken-wired`,`true`),t.addEventListener(`error`,function(){let e=t.closest(`.generated-image-container`);if(!e||e.dataset.brokenHandled)return;e.dataset.brokenHandled=`true`,e.hidden=!0;let n=document.createElement(`p`);n.className=`text-muted small fst-italic mb-2`,n.textContent=t.alt?`(the picture "${t.alt}" could not be loaded)`:`(that picture could not be loaded)`,e.insertAdjacentElement(`afterend`,n)},{once:!0})}function O(e){if(T(),!e||!e._pendingCharts||!e._pendingCharts.length)return;let t=[...e._pendingCharts];e._pendingCharts=[],requestAnimationFrame(()=>{for(let e of t){let t=document.getElementById(e.chartId);if(t){if(typeof Chart>`u`)console.warn(`Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).`);else if(t.offsetParent===null)window.__chartConfigs[e.chartId]=e.config;else try{t._chartInstance&&t._chartInstance.destroy();let n=typeof e.config==`string`?JSON.parse(e.config):e.config;n.options??={},n.options.responsive=!0,n.options.maintainAspectRatio=!0,n.options.aspectRatio??=4/3,t._chartInstance=new Chart(t,n)}catch(e){console.error(`Error creating chart:`,e)}}}})}function k(e){return e.replace(/<table>/g,`<div class="table-responsive"><table class="table table-sm table-bordered table-striped align-middle">`).replace(/<\/table>/g,`</table></div>`)}function A(e,t){S=[];let n=k(marked.parse(e,{renderer:b}));t._pendingCharts=S.length>0?[...S]:[];let r=DOMPurify.sanitize(n,{ADD_TAGS:[`canvas`],ADD_ATTR:[`target`]});return window.CoreAIChatImageCarousel?window.CoreAIChatImageCarousel.stackAdjacentImages(r):r}function j(e){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}let M=t=>{let n=Object.assign({},e,j(t));if(e=n,!n.signalRHubUrl)console.error(`The signalRHubUrl is required.`);else if(!n.appElementSelector)console.error(`The appElementSelector is required.`);else if(!n.chatContainerElementSelector)console.error(`The chatContainerElementSelector is required.`);else if(!n.inputElementSelector)console.error(`The inputElementSelector is required.`);else if(!n.sendButtonElementSelector)console.error(`The sendButtonElementSelector is required.`);else return Vue.createApp({data(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isInteractionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],prompt:``,initialFieldValues:new Map,settingsDirty:!1,saveSettingsTimeout:null,saveIndicatorTimeout:null,isRecording:!1,mediaRecorder:null,preRecordingPrompt:``,micButton:null,speechToTextEnabled:n.chatMode===`AudioInput`||n.chatMode===`Conversation`,textToSpeechEnabled:n.chatMode===`Conversation`||!!n.textToSpeechEnabled,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:`chat-interaction-`+Math.random().toString(36).slice(2),conversationModeEnabled:n.chatMode===`Conversation`,conversationButton:null,isConversationMode:!1,realtimeController:null,realtimeButton:null,realtimeEnabled:n.realtimeEnabled===!0,notifications:[],notificationDismissTimers:{},copyTitle:n.copyTitle,copiedTitle:n.copiedTitle,copiedMessageIndex:-1,copyResetTimeoutId:null,activeCopyButton:null}},computed:{lastAssistantIndex(){for(var e=this.messages.length-1;e>=0;e--)if(this.messages[e].role===`assistant`)return e;return-1}},methods:{handleBeforeUnload(){this.isNavigatingAway=!0},async startConnection(){this.connection=new signalR.HubConnectionBuilder().withUrl(n.signalRHubUrl).withAutomaticReconnect().build(),this.connection.serverTimeoutInMilliseconds=6e5,this.connection.keepAliveIntervalInMilliseconds=15e3,this.connection.on(`LoadInteraction`,e=>{this.initializeInteraction(e.itemId,!0),this.messages=[];let t=document.querySelector(`[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]`);t&&e.title&&(t.value=e.title),(e.messages??[]).forEach(e=>{this.addMessage(e),this.$nextTick(()=>{O(e)})})}),this.connection.on(`SettingsSaved`,(e,t)=>{let r=document.querySelector(`.chat-interaction-history-item[data-interaction-id="${e}"]`);r&&(r.textContent=t||n.untitledText);let i=document.querySelector(`[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]`);i&&t&&(i.value=t),this.showSaveIndicator(`Saved`,`text-success`)}),this.connection.on(`ReceiveError`,e=>{console.error(`SignalR Error: `,e),this.showSaveIndicator(`Save failed`,`text-danger`),this.isRecording&&this.stopRecording()}),this.connection.on(`ReceiveTranscript`,(e,t,n)=>{if(this.isConversationMode){if(!n&&t){this._conversationPartialTranscript=t;var r=`<p class="ai-partial-transcript">`+t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)+`</p>`;this._conversationPartialMessage?(this._conversationPartialMessage.content=t,this._conversationPartialMessage.htmlContent=r):(this.hidePlaceholder(),this._conversationPartialMessage={role:`user`,content:t,htmlContent:r,isPartial:!0},this.messages.push(this._conversationPartialMessage)),this.scrollToBottom()}}else t&&!this._audioInputSent&&(this.prompt=this.preRecordingPrompt+t,this.inputElement&&(this.inputElement.value=this.prompt,this.inputElement.dispatchEvent(new Event(`input`))))}),this.connection.on(`ReceiveConversationUserMessage`,(e,t,n)=>{if(t&&this._realtimePendingTurns&&this._realtimePendingTurns[t]){var r=this._realtimePendingTurns[t];if(delete this._realtimePendingTurns[t],this.stopAudio(),n)r.content=n,r.rawContent=n,r.isPartial=!1,y(r,r.references);else{var i=this.messages.indexOf(r);i>=0&&this.messages.splice(i,1)}}else if(n){if(this.stopAudio(),this._conversationPartialMessage){var a=n.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`);this._conversationPartialMessage.content=n,this._conversationPartialMessage.htmlContent=`<p>`+a+`</p>`,this._conversationPartialMessage.isPartial=!1,this._conversationPartialMessage=null}else if(this._conversationAssistantMessage){var o=this._conversationAssistantMessage.index,s={role:`user`,content:n,rawContent:n,references:{}};y(s,s.references),this.messages.splice(o,0,s),this._conversationAssistantMessage.index=o+1}else this.addMessage({role:`user`,content:n});this.scrollToBottom()}}),this.connection.on(`ReceiveConversationAssistantToken`,(e,t,n,r,i,a)=>{if(this._conversationAssistantMessage&&this._conversationAssistantResponseId&&r&&this._conversationAssistantResponseId!==r){var o=this.messages[this._conversationAssistantMessage.index];o&&(o.isStreaming=!1),this._conversationAssistantMessage=null}if(!this._conversationAssistantMessage){this.stopAudio(),this.hideTypingIndicator();for(var s=0;s<this.messages.length;s++)this.messages[s].isStreaming&&(this.messages[s].isStreaming=!1);var l=this.messages.length,u={id:t,role:`assistant`,content:``,htmlContent:``,isStreaming:!0,appearance:this.normalizeAssistantAppearance(a),references:{}};this.messages.push(u),this._conversationAssistantMessage={index:l,content:``},this._conversationAssistantResponseId=r}this._conversationAssistantMessage.content+=n;var d=this.messages[this._conversationAssistantMessage.index];d&&(d.appearance||=this.normalizeAssistantAppearance(a),d.rawContent=this._conversationAssistantMessage.content,d.references=c(Object.assign({},d.references||{},i||{})),y(d,d.references),this.$nextTick(()=>{O(d),this.scrollToBottom()}))}),this.connection.on(`ReceiveConversationAssistantComplete`,(e,t,n)=>{if(this._conversationAssistantMessage){var r=this.messages[this._conversationAssistantMessage.index];r&&(r.isStreaming=!1,r.references=c(Object.assign({},r.references||{},n||{})),y(r,r.references)),this._conversationAssistantMessage=null,this._conversationAssistantResponseId=null}}),this.connection.on(`ReceiveAudioChunk`,(e,t,n)=>{if(t){let e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);n===`audio/pcm`&&this.realtimeController?this.realtimeController.receivePcm(r):this.audioChunks.push(r)}}),this.connection.on(`ReceiveAudioComplete`,e=>{this.playCollectedAudio()}),this.connection.on(`HistoryCleared`,e=>{this.messages=[],this.showPlaceholder();let t=document.getElementById(`clearHistoryBtn`);t&&t.classList.add(`d-none`)}),this.connection.on(`ReceiveNotification`,e=>{this.receiveNotification(e)}),this.connection.on(`UpdateNotification`,e=>{this.updateNotification(e)}),this.connection.on(`RemoveNotification`,e=>{this.removeNotification(e)}),this.connection.onreconnecting(()=>{console.warn(`SignalR: reconnecting...`)}),this.connection.onreconnected(()=>{console.info(`SignalR: reconnected.`),this.reloadCurrentInteraction()}),this.connection.onclose(e=>{this.isNavigatingAway||e&&console.warn(`SignalR connection closed with error:`,e.message||e)});try{await this.connection.start()}catch(e){console.error(`SignalR Connection Error: `,e)}},addMessageInternal(e){e.role===`assistant`&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=A(e.content,e)),this.fireEvent(new CustomEvent(`addingChatInteractionMessage`,{detail:{message:e}})),this.messages.push(e),this.$nextTick(()=>{this.fireEvent(new CustomEvent(`addedChatInteractionMessage`,{detail:{message:e}}))})},addMessage(e){e.content&&(e.rawContent=e.rawContent??e.content,y(e,e.references)),this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(()=>{O(e),this.scrollToBottom()})},hidePlaceholder(){this.placeholder&&this.placeholder.classList.add(`d-none`),this.isPlaceholderVisible=!1},showPlaceholder(){this.placeholder&&this.placeholder.classList.remove(`d-none`),this.isPlaceholderVisible=!0},fireEvent(e){document.dispatchEvent(e)},normalizeAssistantAppearance(e){if(!e)return null;var t=typeof e.label==`string`?e.label.trim():``,n=typeof e.icon==`string`?e.icon.trim():``,r=typeof e.cssClass==`string`?e.cssClass.trim():``,i=!!e.disableStreamingAnimation;return!t&&!n&&!r&&!i?null:{label:t,icon:n,cssClass:r,disableStreamingAnimation:i}},getAssistantLabel(t){var n=t?this.normalizeAssistantAppearance(t.appearance):null;return n&&n.label?n.label:e.assistantLabel},getAssistantRoleClasses(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=[`ai-chat-msg-role`];return t&&t.cssClass?n.push(t.cssClass):n.push(`ai-chat-msg-role-assistant`),n},getAssistantIconClasses(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?`ai-streaming-icon`:`ai-bot-icon`,n&&n.cssClass?n.cssClass:``]},getAssistantIcon(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:`fa fa-robot`},shouldAnimateAssistantIcon(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},isIndicator(e){return e.role===`indicator`},async sendMessage(){let e=this.prompt.trim();if(!e)return;this.endActiveVoiceSession(),this.isRecording&&this.stopRecording(),this._audioInputSent=!0,await this.flushPendingSave(),this.addMessage({role:`user`,content:e});let t=document.getElementById(`clearHistoryBtn`);t&&t.classList.remove(`d-none`),this.streamMessage(e),this.inputElement.value=``,this.prompt=``},streamMessage(e){this.stream&&=(this.stream.dispose(),null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var t=``,n={},r=null,i=this.messages.length,a=this.getItemId();this.stream=this.connection.stream(`SendMessage`,a,e).subscribe({next:e=>{let s=this.messages[i];if(!s){e.sessionId&&!a&&this.setItemId(e.sessionId),this.hideTypingIndicator(),i=this.messages.length;let t={role:`assistant`,content:``,htmlContent:``,isStreaming:!0};this.messages.push(t),s=t}if(e.references&&typeof e.references==`object`&&Object.keys(e.references).length)for(let[t,r]of Object.entries(e.references))n[t]=o(r)??{};e.content&&(e.responseId&&r&&e.responseId!==r&&(t+=`
61
+
62
+ `),e.responseId&&(r=e.responseId),t+=e.content),s.rawContent=t,y(s,n),this.messages[i]=s,this.$nextTick(()=>{O(s),this.scrollToBottom()})},complete:()=>{this.processReferences(n,i),this.streamingFinished();let e=this.messages[i];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(n,i),this.streamingFinished();let t=this.messages[i];t&&(t.isStreaming=!1),this.hideTypingIndicator(),this.isNavigatingAway||this.addMessage(this.getServiceDownMessage()),this.stream?.dispose(),this.stream=null,console.error(`Stream error:`,e)}})},getServiceDownMessage(){return{role:`assistant`,content:`Our service is currently unavailable. Please try again later. We apologize for the inconvenience.`,htmlContent:``}},processReferences(e,t){if(e=c(e),Object.keys(e).length){let n=this.messages[t];n.rawContent=n.rawContent??n.content??``,y(n,e),this.messages[t]=n,this.$nextTick(()=>{O(n),this.scrollToBottom()})}},streamingStarted(){var e=this.buttonElement.getAttribute(`data-stop-icon`);e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))},streamingFinished(){var e=this.buttonElement.getAttribute(`data-start-icon`);if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),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(var n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1);this.settingsDirty&&this.debouncedSaveSettings()},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,n=t?`<i class="fa-solid fa-circle-pause"></i>`:`<i class="fa-solid fa-circle-play"></i>`;e.classList.toggle(`tts-playing`,t),e.setAttribute(`title`,t?`Pause audio`:`Read aloud`),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))})},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.getItemId(),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.isPlayingAudio&&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.isPlayingAudio&&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){let 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())},setVoiceSessionLive(e){this.inputElement&&(this.inputElement.hidden=e),this.buttonElement&&(this.buttonElement.hidden=e),[this.realtimeButton,this.conversationButton].forEach(function(t){t&&t.classList.toggle(`flex-grow-1`,e)});var t=this.realtimeButton&&this.realtimeButton.nextElementSibling,n=t&&t.id===`realtime-audio-settings`?t:null;n&&(n.hidden=!e)},toggleConversationMode(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},endActiveVoiceSession(){this.realtimeController&&this.realtimeController.isActive()?this.realtimeController.stop():this.isConversationMode&&this.stopConversationMode()},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=>{var t=MediaRecorder.isTypeSupported(`audio/ogg;codecs=opus`)?`audio/ogg;codecs=opus`:MediaRecorder.isTypeSupported(`audio/webm;codecs=opus`)?`audio/webm;codecs=opus`:`audio/webm`;this.mediaRecorder=new MediaRecorder(e,{mimeType:t,audioBitsPerSecond:128e3}),this._conversationSubject=new signalR.Subject,this._conversationStream=e;var n=window.AudioContext||window.webkitAudioContext;n&&(this._conversationAudioCtx=new n,this._conversationAnalyser=this._conversationAudioCtx.createAnalyser(),this._conversationAnalyser.fftSize=256,this._conversationAudioCtx.createMediaStreamSource(e).connect(this._conversationAnalyser));var r=Promise.resolve(),i=this._conversationAnalyser,a=30;this.mediaRecorder.addEventListener(`dataavailable`,e=>{if(e.data&&e.data.size>0){if(this.isPlayingAudio&&i){var t=new Uint8Array(i.frequencyBinCount);i.getByteFrequencyData(t);for(var n=0,o=0;o<t.length;o++)n+=t[o];n/t.length>=a&&this.stopAudio()}r=r.then(async()=>{var t=await e.data.arrayBuffer(),n=new Uint8Array(t).reduce(function(e,t){return e+String.fromCharCode(t)},``),r=btoa(n);try{this._conversationSubject.next(r)}catch{}})}}),this.mediaRecorder.addEventListener(`stop`,()=>{e.getTracks().forEach(e=>e.stop()),r.then(()=>{try{this._conversationSubject.complete()}catch{}})});var o=this.getItemId(),s=navigator.language||document.documentElement.lang||`en-US`;this.connection.send(`StartConversation`,o,this._conversationSubject,t,s),this.mediaRecorder.start(250),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&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript=``,this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=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(){},showTypingIndicator(){this.addMessage({role:`indicator`,htmlContent:n.indicatorTemplate})},hideTypingIndicator(){let e=this.messages.length;return this.messages=this.messages.filter(e=>e.role!==`indicator`),e-this.messages.length},scrollToBottom(){this.autoScroll&&setTimeout(()=>{this.chatContainer.scrollTop=this.chatContainer.scrollHeight-this.chatContainer.clientHeight},50)},handleUserInput(e){this.prompt=e.target.value},getItemId(){return this.inputElement.getAttribute(`data-interaction-id`)||this.inputElement.getAttribute(`data-item-id`)},getSaveIndicatorElement(){return n.saveIndicatorElementSelector?document.querySelector(n.saveIndicatorElementSelector):document.querySelector(`[data-chat-interaction-save-indicator]`)},showSaveIndicator(e,t){let n=this.getSaveIndicatorElement();n&&(n.textContent=e||``,n.className=`settings-save-indicator `+(t||`text-muted`),this.saveIndicatorTimeout&&=(clearTimeout(this.saveIndicatorTimeout),null),e&&(this.saveIndicatorTimeout=setTimeout(()=>{n.textContent=``,this.saveIndicatorTimeout=null},3e3)))},clearPendingSettingsSave(){this.saveSettingsTimeout&&=(clearTimeout(this.saveSettingsTimeout),null)},getFieldLabel(e){let t=e.closest(`.mb-3, .col-6, .col, .form-group, .form-floating`)?.querySelector(`label`);return t?(t.textContent||``).replace(/\s+/g,` `).trim()||e.dataset.setting||`This field`:e.dataset.setting||`This field`},getValidationFeedbackElement(e){let t=e.nextElementSibling;return t&&t.classList.contains(`invalid-feedback`)||(t=document.createElement(`div`),t.className=`invalid-feedback`,e.insertAdjacentElement(`afterend`,t)),t},clearSettingValidationError(e){e.classList.remove(`is-invalid`),e.removeAttribute(`aria-invalid`);let t=e.nextElementSibling;t&&t.classList.contains(`invalid-feedback`)&&(t.textContent=``)},setSettingValidationError(e,t){let n=this.getValidationFeedbackElement(e);e.classList.add(`is-invalid`),e.setAttribute(`aria-invalid`,`true`),n.textContent=t},getSettingValidationMessage(e){if(!e||e.disabled||e.type!==`number`)return null;let t=(e.value||``).trim();if(!t)return null;let n=Number(t),r=this.getFieldLabel(e);if(Number.isNaN(n))return`${r} must be a valid number.`;let i=e.getAttribute(`min`);if(i!==null&&n<Number(i))return`${r} must be ${i} or greater.`;let a=e.getAttribute(`max`);return a!==null&&n>Number(a)?`${r} must be ${a} or less.`:null},validateSettingInput(e){let t=this.getSettingValidationMessage(e);return t?(this.setSettingValidationError(e,t),!1):(this.clearSettingValidationError(e),!0)},validateSettings(){let e=!0;return this.getSettingInputs().forEach(t=>{e=this.validateSettingInput(t)&&e}),e},queueSettingsSave(){this.validateSettings()?(this.settingsDirty=!0,this.showSaveIndicator(`Saving...`,`text-warning`),this.debouncedSaveSettings()):(this.clearPendingSettingsSave(),this.settingsDirty=!1,this.showSaveIndicator(`Fix errors`,`text-danger`))},getSettingInputs(){let e=document.querySelectorAll(`.setting-input[data-setting]`);return e.length>0?e:document.querySelectorAll(`input[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), select[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), textarea[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["])`)},getSelectedGroupValues(e,t){let n=document.querySelectorAll(`.capability-checkbox[data-save-group="${e}"]:checked, .capability-checkbox[data-group="${e}"]:checked`);if(n.length>0){let e=[];return n.forEach(t=>{let n=t.getAttribute(`data-item-id`)||t.value;n&&e.push(n)}),e}if(!t)return[];let r=[];return document.querySelectorAll(t).forEach(e=>{let t=e.name.replace(`.IsSelected`,`.ItemId`),n=document.querySelector(`input[type="hidden"][name="${t}"]`);n&&n.value&&r.push(n.value)}),r},getPromptTemplateSelections(){let e=[];return document.querySelectorAll(`.prompt-template-card`).forEach(t=>{let n=t.querySelector(`.prompt-template-id-input`),r=t.querySelector(`.prompt-template-parameters-input`),i=n?n.value:t.getAttribute(`data-template-id`);i&&e.push({templateId:i,promptParameters:r?(r.value||``).trim():``})}),e},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.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),this.scrollToBottom())}},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.getItemId();this.connection.invoke(`HandleNotificationAction`,n,e,t).catch(e=>console.error(`Failed to handle notification action:`,e))}},setItemId(e){this.inputElement.setAttribute(`data-interaction-id`,e||``),this.inputElement.setAttribute(`data-item-id`,e||``)},resetInteraction(){this.setItemId(``),this.isInteractionStarted=!1,this.messages=[],this.showPlaceholder()},initializeApp(){this.inputElement=document.querySelector(n.inputElementSelector),this.buttonElement=document.querySelector(n.sendButtonElementSelector),this.chatContainer=document.querySelector(n.chatContainerElementSelector),this.placeholder=document.querySelector(n.placeholderElementSelector);let e=this.getItemId();e&&this.loadInteraction(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(`keyup`,e=>{this.stream==null&&e.key===`Enter`&&!e.shiftKey&&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.inputElement.addEventListener(`paste`,e=>{setTimeout(()=>{this.prompt=this.inputElement.value,this.inputElement.value.trim()?this.buttonElement.removeAttribute(`disabled`):this.buttonElement.setAttribute(`disabled`,!0)},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 t=document.getElementsByClassName(`chat-interaction-history-item`);for(var r=0;r<t.length;r++)t[r].addEventListener(`click`,e=>{e.preventDefault();var t=e.target.getAttribute(`data-interaction-id`);t?this.loadInteraction(t):console.error(`An element with the class chat-interaction-history-item with no data-interaction-id set.`)});let i=Array.isArray(n.messages)?n.messages:[];for(let e=0;e<i.length;e++)this.addMessage(i[e]);this.chatContainer&&this.chatContainer.addEventListener(`click`,e=>{var t=e.target.closest(`.ai-code-copy-btn`);if(t){var r=t.closest(`.ai-code-block`)||t.closest(`pre`);if(r){var i=r.querySelector(`code`);i&&(navigator.clipboard.writeText(i.textContent),t.innerHTML=`<i class="fa-solid fa-check"></i> `+(n.codeCopiedText||`Copied!`),setTimeout(()=>{t.innerHTML=`<i class="fa-regular fa-copy"></i>`},2e3))}}}),document.addEventListener(`input`,e=>{e.target.matches(`.setting-input[data-setting]`)&&(this.validateSettingInput(e.target),this.queueSettingsSave())}),document.addEventListener(`change`,e=>{e.target.matches(`.setting-input[data-setting], .capability-checkbox[data-save-group], .capability-checkbox[data-group], .group-toggle, .ci-agent-global-toggle`)?(e.target.matches(`.setting-input[data-setting]`)&&this.validateSettingInput(e.target),this.queueSettingsSave()):e.target.closest(`.prompt-template-parameters-input, .prompt-template-id-input`)&&this.queueSettingsSave()}),document.addEventListener(`click`,e=>{e.target.closest(`.prompt-template-add-btn, .remove-prompt-template-btn`)&&setTimeout(()=>{this.queueSettingsSave()},0)});let a=document.getElementById(`clearHistoryBtn`);a&&a.addEventListener(`click`,()=>{let e=a.getAttribute(`data-interaction-id`);e&&this.clearHistory(e)}),this.speechToTextEnabled&&n.micButtonElementSelector&&(this.micButton=document.querySelector(n.micButtonElementSelector),this.micButton&&(this.micButton.style.display=``,this.micButton.addEventListener(`click`,()=>{this.toggleRecording()}))),this.conversationModeEnabled&&n.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(n.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener(`click`,()=>{this.toggleConversationMode()})),window.CoreAIRealtime&&n.realtimeButtonElementSelector&&(this.realtimeButton=document.querySelector(n.realtimeButtonElementSelector),this.realtimeController=window.CoreAIRealtime.attach({connection:this.connection,ensureConnected:()=>Promise.resolve(this.connection),sendStart:(e,t,n,r,i,a)=>{this.connection.send(`StartRealtimeConversation`,this.getItemId(),e,t,n,r,i,a)},webRtcEnabled:n.realtimeWebRtcEnabled===!0,sendStartWebRtc:(e,t,n,r,i,a)=>{this.connection.send(`StartRealtimeWebRtc`,this.getItemId(),e,t,n,r,i,a)},webRtcIceServers:Array.isArray(n.realtimeWebRtcIceServers)?n.realtimeWebRtcIceServers:void 0,voiceName:n.realtimeVoiceName||``,getVoiceName:()=>{var e=n.realtimeVoiceSelectElementSelector?document.querySelector(n.realtimeVoiceSelectElementSelector):null;return e?e.value:``},capableDeployments:n.realtimeCapableDeployments||[],realtimeEnabled:n.realtimeEnabled===!0,selectors:{realtimeButton:n.realtimeButtonElementSelector,micButton:n.micButtonElementSelector,conversationButton:n.conversationButtonElementSelector},onSessionStateChanged:e=>{this.setVoiceSessionLive(e)},onActivate:()=>{this.isConversationMode=!0,this._conversationPartialMessage=null,this._conversationAssistantMessage=null},onDeactivate:()=>{if(this.isConversationMode=!1,this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}},onEnterRealtimeMode:()=>{this.isRecording&&this.stopRecording(),this.isConversationMode&&(!this.realtimeController||!this.realtimeController.isActive())&&this.stopConversationMode()},onUserTurnPending:e=>{if(e){var t={role:`user`,content:``,rawContent:``,references:{},isPartial:!0};y(t,t.references),this._realtimePendingTurns=this._realtimePendingTurns||{},this._realtimePendingTurns[e]=t,this.messages.push(t),this.scrollToBottom()}},onUserTurnDropped: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)}}}}),this.setupRealtimeVoicePicker(n),this.setVoiceSessionLive(!1))},setupRealtimeVoicePicker(e){if(!e.realtimeVoiceSelectElementSelector||!e.realtimeVoicesUrl)return;var t=document.querySelector(e.realtimeVoiceSelectElementSelector);if(!t)return;var n=e.realtimeVoiceGroupElementSelector?document.querySelector(e.realtimeVoiceGroupElementSelector):null,r=e.conversationDeploymentSelectElementSelector?document.querySelector(e.conversationDeploymentSelectElementSelector):null,i=(e.realtimeCapableDeployments||[]).map(function(e){return(e||``).toLowerCase()}),a=e.realtimeVoiceName||``,o=this;function s(e){return e&&i.indexOf(e.toLowerCase())!==-1}function c(){if(!o.conversationModeEnabled)return``;var t=r&&r.value||e.defaultRealtimeDeploymentName||(i.length?i[0]:``);return s(t)?t:``}async function l(){var r=c(),i=!!r;if(n&&n.classList.toggle(`d-none`,!i),o.realtimeController&&o.realtimeController.applyMode(i),i){t.innerHTML=`<option value="">Default voice</option>`;try{let n=await fetch(e.realtimeVoicesUrl+`?deploymentName=`+encodeURIComponent(r),{credentials:`same-origin`}),i=(n.headers.get(`content-type`)||``).toLowerCase();if(!n.ok||i.indexOf(`json`)<0)return;let o=await n.json();if(!o||!Array.isArray(o.voices))return;let s=new Map;for(let e of o.voices){let t=e.gender||`Voices`;s.has(t)||s.set(t,[]),s.get(t).push(e)}Array.from(s.keys()).sort((e,t)=>e.localeCompare(t)).forEach(function(e){let n=document.createElement(`optgroup`);n.label=e,s.get(e).forEach(function(e){let t=document.createElement(`option`);t.value=e.id,t.textContent=e.name,t.selected=e.id===a,n.appendChild(t)}),t.appendChild(n)})}catch{}}}r&&r.addEventListener(`change`,l),l()},loadInteraction(e){this.connection.invoke(`LoadInteraction`,e).catch(e=>console.error(e))},reloadCurrentInteraction(){let e=this.getItemId();e&&this.loadInteraction(e)},clearHistory(e){let t=this,r=()=>{t.realtimeController&&t.realtimeController.isActive()&&t.realtimeController.stop(),t.stream&&(t.stream.dispose(),t.stream=null,t.hideTypingIndicator(),t.streamingFinished()),t.connection.invoke(`ClearHistory`,e).catch(e=>console.error(`Error clearing history:`,e))};typeof confirmDialog==`function`?confirmDialog({title:n.clearHistoryTitle,message:n.clearHistoryMessage,okText:n.clearHistoryOkText,cancelText:n.clearHistoryCancelText,callback:function(e){e&&r()}}):window.confirm(n.clearHistoryMessage||`Clear all messages?`)&&r()},debouncedSaveSettings(){this.clearPendingSettingsSave(),!this.stream&&(this.saveSettingsTimeout=setTimeout(()=>{this.settingsDirty&&=(this.saveSettings(),!1),this.saveSettingsTimeout=null},850))},getSelectedToolNames(){return this.getSelectedGroupValues(`toolNames`,`input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Tools["]:checked`)},getSelectedMcpConnectionIds(){return this.getSelectedGroupValues(`mcpConnectionIds`,`input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Connections["]:checked`)},getSelectedA2AConnectionIds(){return this.getSelectedGroupValues(`a2aConnectionIds`)},getSelectedAgentNames(){return this.getSelectedGroupValues(`agentNames`,`input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Agents["]:checked`)},saveSettings(){let e=this.getItemId();if(!e)return Promise.resolve();if(!this.validateSettings())return this.showSaveIndicator(`Fix errors`,`text-danger`),Promise.resolve();let t={};this.getSettingInputs().forEach(e=>{let n=e.dataset.setting||(e.name||``).replace(`ChatInteraction.`,``).replace(/^[A-Z]/,e=>e.toLowerCase());n&&(e.type===`checkbox`?t[n]=e.checked:e.type===`number`?t[n]=e.value?parseFloat(e.value):null:t[n]=e.value||null)}),t.toolNames=this.getSelectedToolNames(),t.mcpConnectionIds=this.getSelectedMcpConnectionIds(),t.a2aConnectionIds=this.getSelectedA2AConnectionIds(),t.agentNames=this.getSelectedAgentNames();let n=this.getPromptTemplateSelections();return n.length>0&&(t.promptTemplates=n,t.promptTemplateIds=n.map(e=>e.templateId)),this.connection.invoke(`SaveSettings`,e,t).catch(e=>{console.error(`Error saving settings:`,e),this.showSaveIndicator(`Save failed`,`text-danger`)})},flushPendingSave(){return this.saveSettingsTimeout&&=(clearTimeout(this.saveSettingsTimeout),null),this.settingsDirty?(this.settingsDirty=!1,this.saveSettings()):Promise.resolve()},initializeInteraction(e,t){(!this.isInteractionStarted||t)&&(this.fireEvent(new CustomEvent(`initializingChatInteraction`,{detail:{itemId:e}})),this.setItemId(e),this.isInteractionStarted=!0)},clearCopiedMessageState(){this.copyResetTimeoutId&&=(window.clearTimeout(this.copyResetTimeoutId),null),this.activeCopyButton&&=(this.setCopyButtonState(this.activeCopyButton,!1),null),this.copiedMessageIndex=-1},copyResponse(e,t,r){let i=e&&typeof e==`object`?e.copyContent??e.content??``:e??``,a=r?.currentTarget||r?.target?.closest?.(`[data-copy-message-index]`)||null;navigator.clipboard.writeText(i).then(()=>{this.clearCopiedMessageState(),this.copiedMessageIndex=typeof t==`number`?t:-1,this.activeCopyButton=a,a?this.setCopyButtonState(a,!0):this.$nextTick(()=>this.updateCopyButtons()),this.copyResetTimeoutId=window.setTimeout(()=>{this.clearCopiedMessageState(),this.$nextTick(()=>this.updateCopyButtons())},Number(n.copyResetDelayMs)||2e3)}).catch(e=>console.error(`Failed to copy response:`,e))},startRecording(){!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(e=>{var t=MediaRecorder.isTypeSupported(`audio/ogg;codecs=opus`)?`audio/ogg;codecs=opus`:MediaRecorder.isTypeSupported(`audio/webm;codecs=opus`)?`audio/webm;codecs=opus`:`audio/webm`;this.mediaRecorder=new MediaRecorder(e,{mimeType:t,audioBitsPerSecond:128e3}),this.preRecordingPrompt=this.prompt,this._audioInputSent=!1;var n=new signalR.Subject,r=this.getItemId(),i=Promise.resolve();this.mediaRecorder.addEventListener(`dataavailable`,e=>{e.data&&e.data.size>0&&(i=i.then(async()=>{var t=await e.data.arrayBuffer(),r=new Uint8Array(t).reduce(function(e,t){return e+String.fromCharCode(t)},``),i=btoa(r);n.next(i)}))}),this.mediaRecorder.addEventListener(`stop`,()=>{e.getTracks().forEach(e=>e.stop()),i.then(()=>n.complete())});var a=navigator.language||document.documentElement.lang||`en-US`;this.connection.send(`SendAudioStream`,r,n,t,a),this.mediaRecorder.start(250),this.isRecording=!0,this.updateMicButton()}).catch(e=>{console.error(`Microphone access denied:`,e)})},stopRecording(){this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1,this.updateMicButton())},toggleRecording(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton(){this.micButton&&(this.isRecording?(this.micButton.classList.add(`stt-recording`),this.micButton.innerHTML=`<i class="fa-solid fa-stop"></i>`):(this.micButton.classList.remove(`stt-recording`),this.micButton.innerHTML=`<i class="fa-solid fa-microphone"></i>`))}},watch:{isPlayingAudio(){},isConversationMode(e){this.micButton&&(this.micButton.style.display=e?`none`:this.speechToTextEnabled?``:`none`),this.realtimeEnabled||this.setVoiceSessionLive(e)},copiedMessageIndex(){this.$nextTick(()=>this.updateCopyButtons())}},mounted(){(async()=>{await this.startConnection(),this.initializeApp(),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()},template:n.messageTemplate}).mount(n.appElementSelector)},N=`[data-chat-interaction-config]`;function P(e,t,n){let r=e.getAttribute(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return console.error(`Failed to parse `+n+` JSON.`,e),null}}function F(e){if(!e||e.dataset.chatInteractionInitialized===`true`)return e&&e.__chatInteractionApp||null;let t=P(e,`data-chat-interaction-config`,`chat interaction config`);if(!t)return null;let n=M(t);return n?(e.dataset.chatInteractionInitialized=`true`,e.__chatInteractionApp=n,n):null}function I(e){e&&typeof e.querySelectorAll==`function`&&(typeof e.matches==`function`&&e.matches(N)&&F(e),e.querySelectorAll(N).forEach(F))}function L(){I(document),typeof MutationObserver<`u`&&new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e&&e.nodeType===1&&I(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,L,{once:!0}):L(),{initialize:M,initializeFromElement:F}}(),window.chatInteractionDocumentManager=function(){let e=`__chatInteractionDocumentManagerState`;function t(e){return!e||typeof e!=`object`?null:{documentId:e.documentId||e.DocumentId||``,fileName:e.fileName||e.FileName||``,fileSize:e.fileSize||e.FileSize||0}}function n(e){return!e||e<1024?(e||0)+` B`:e<1048576?(e/1024).toFixed(1)+` KB`:(e/1048576).toFixed(1)+` MB`}function r(e,t){return(e||``).trim().toLowerCase()+`::`+(t||0)}function i(e,t){return t.has(r(e.name,e.size))}function a(e){return e?Array.from(e.querySelectorAll(`[data-chat-document-id]`)).map(e=>t({documentId:e.dataset.chatDocumentId,fileName:e.dataset.chatDocumentName,fileSize:Number(e.dataset.chatDocumentSize||0)})).filter(e=>e&&e.documentId):[]}function o(o){if(!o||!o.itemId)return;let s=document.getElementById(`chat-doc-upload`),c=document.getElementById(`chat-documents-list`),l=document.getElementById(`chat-doc-upload-status`),u=document.getElementById(`chat-doc-upload-progress`),d=document.getElementById(`chat-doc-upload-progress-bar`),f=document.getElementById(`chat-doc-upload-queue`);if(!s||!c||!l||!u||!d||!f)return;let p=s[e];p&&typeof p.dispose==`function`&&p.dispose();let m=(Array.isArray(o.existingDocuments)?o.existingDocuments:[]).map(t).filter(e=>e&&e.documentId);m.length===0&&(m=a(c));let h=[],g=!1;function _(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}function v(){c.innerHTML=``,m.length===0?c.appendChild(_(`div`,`text-muted small`,`No documents uploaded yet.`)):m.forEach(e=>{let t=window.document.createElement(`div`);t.className=`d-flex align-items-center gap-2 border rounded px-2 py-2 bg-white chat-document-row`,t.dataset.chatDocumentId=e.documentId,t.dataset.chatDocumentName=e.fileName,t.dataset.chatDocumentSize=e.fileSize;let r=window.document.createElement(`div`);r.className=`d-flex gap-1`;let i=o.downloadDocumentBaseUrl||`/ai/documents/`,a=_(`a`,`btn btn-sm btn-outline-secondary`,``);a.title=`Download`,a.href=i+encodeURIComponent(e.documentId)+`/download`;let s=window.document.createElement(`i`);s.className=`fa-solid fa-download`,a.appendChild(s);let l=_(`button`,`btn btn-sm btn-outline-danger remove-chat-document-btn`,``);l.type=`button`,l.title=`Remove`,l.dataset.documentId=e.documentId;let u=window.document.createElement(`i`);u.className=`fa-solid fa-trash`,l.appendChild(u),l.addEventListener(`click`,()=>k(e.documentId)),r.appendChild(a),r.appendChild(l);let d=window.document.createElement(`div`);d.className=`min-w-0`;let f=_(`div`,`fw-semibold small text-truncate`,e.fileName||`Document`),p=window.document.createElement(`i`);p.className=`fa-solid fa-file-lines me-1`,f.prepend(p);let m=_(`div`,`text-muted small`,n(e.fileSize));d.appendChild(f),d.appendChild(m),t.appendChild(r),t.appendChild(d),c.appendChild(t)})}function y(e,t){e?(l.textContent=e,l.className=`small mt-2 `+(t||`text-muted`)):(l.textContent=``,l.className=`small mt-2 d-none`)}function b(e,t,n){if(e==null){u.className=`progress mt-2 d-none`,u.setAttribute(`aria-valuenow`,`0`),d.className=`progress-bar progress-bar-striped progress-bar-animated`,d.style.width=`0%`,d.textContent=`0%`;return}let r=Math.max(0,Math.min(100,Math.round(e)));u.className=`progress mt-2`,u.setAttribute(`aria-valuenow`,r.toString()),d.className=`progress-bar `+(n||`progress-bar-striped progress-bar-animated`),d.style.width=r+`%`,d.textContent=t||r+`%`}function x(e){switch(e){case`uploaded`:return{label:`Uploaded`,badgeClass:`text-bg-success`,progressClass:`bg-success`};case`failed`:return{label:`Failed`,badgeClass:`text-bg-danger`,progressClass:`bg-danger`};case`uploading`:return{label:`Uploading`,badgeClass:`text-bg-warning`,progressClass:`bg-warning progress-bar-striped progress-bar-animated`};default:return{label:`Queued`,badgeClass:`text-bg-secondary`,progressClass:`bg-secondary progress-bar-striped progress-bar-animated`}}}function S(e){return e.status===`failed`&&e.error?e.error:e.status===`uploaded`?`Upload completed successfully.`:e.status===`uploading`?e.progress+`% uploaded`:`Waiting to upload...`}function C(){f.innerHTML=``,h.forEach(e=>{let t=x(e.status),r=document.createElement(`div`);r.className=`border rounded px-2 py-2 bg-white`;let i=document.createElement(`div`);i.className=`d-flex justify-content-between align-items-start gap-2`;let a=document.createElement(`div`);a.className=`flex-grow-1 min-w-0`,a.appendChild(_(`div`,`fw-semibold small`,e.fileName)),a.appendChild(_(`div`,`text-muted small`,n(e.fileSize)));let o=_(`span`,`badge `+t.badgeClass,t.label);i.appendChild(a),i.appendChild(o);let s=document.createElement(`div`);s.className=`progress mt-2`,s.setAttribute(`role`,`progressbar`),s.setAttribute(`aria-valuemin`,`0`),s.setAttribute(`aria-valuemax`,`100`),s.setAttribute(`aria-valuenow`,e.progress.toString());let c=document.createElement(`div`);c.className=`progress-bar `+t.progressClass,c.style.width=e.progress+`%`,c.textContent=e.progress+`%`,s.appendChild(c);let l=_(`div`,e.status===`failed`?`small text-danger mt-2`:`small text-muted mt-2`,S(e));r.appendChild(i),r.appendChild(s),r.appendChild(l),f.appendChild(r)})}function w(e,t){return{id:e.name+`::`+e.size+`::`+e.lastModified+`::`+t+`::`+Date.now(),fileName:e.name,fileSize:e.size,status:`queued`,progress:0,error:null}}function T(e,t){h=h.map(n=>n.id===e?Object.assign({},n,t):n),C()}function E(e){h=h.filter(t=>!e(t)),C()}function D(e,t,n,r){return new Promise((i,a)=>{let s=new FormData;s.append(`chatInteractionId`,o.itemId),s.append(`files`,e);let c=new XMLHttpRequest;c.open(`POST`,o.uploadDocumentUrl,!0),c.upload.addEventListener(`progress`,e=>{e.lengthComputable&&(T(t,{status:`uploading`,progress:Math.round(e.loaded/e.total*100)}),b((n+e.loaded/e.total)/r*100,`Uploading `+(n+1)+` of `+r,`progress-bar-striped progress-bar-animated`))}),c.addEventListener(`load`,()=>{if(c.status>=200&&c.status<300)try{i(JSON.parse(c.responseText))}catch{a(Error(`Upload failed: invalid server response.`))}else a(Error((c.responseText||`Upload failed.`).trim()))}),c.addEventListener(`error`,()=>{a(Error(`Upload failed. Please check your connection and try again.`))}),c.send(s)})}async function O(e){if(!o.uploadDocumentUrl||!e||e.length===0)return;if(g){y(`A document upload is already in progress.`,`text-warning`);return}g=!0;let n=[],a=[],c=new Set(m.map(e=>r(e.fileName,e.fileSize)));if(Array.from(e).forEach(e=>{i(e,c)?a.push(e):(c.add(r(e.name,e.size)),n.push(e))}),a.length>0&&(h=h.concat(a.map((e,t)=>Object.assign(w(e,t),{status:`failed`,progress:100,error:`This document is already attached.`}))),C()),n.length===0){g=!1,y(a.map(e=>e.name+`: This document is already attached.`).join(` | `),`text-warning`),b(null);return}let l=n.map(w);h=h.concat(l),C(),b(0,`Preparing upload...`,`progress-bar-striped progress-bar-animated`),s.disabled=!0;try{let e=0,r=a.map(e=>e.name+`: This document is already attached.`);for(let i=0;i<n.length;i++){let a=n[i],o=l[i];T(o.id,{status:`uploading`,progress:0,error:null}),y(`Uploading `+(i+1)+` of `+n.length+` document(s)...`,`text-warning`);try{let s=await D(a,o.id,i,n.length),c=(Array.isArray(s.uploaded)?s.uploaded:[]).map(t).filter(e=>e&&e.documentId),l=Array.isArray(s.failed)?s.failed:[];if(c.length>0)e+=c.length,m=m.concat(c),T(o.id,{status:`uploaded`,progress:100,error:null});else{let e=l.length>0?l.map(e=>e.fileName+`: `+e.error).join(` | `):`The server did not confirm that the file was uploaded.`;l.length===0&&r.push(e),T(o.id,{status:`failed`,progress:100,error:e})}if(l.length>0){let e=l.map(e=>e.fileName+`: `+e.error).join(` | `);r.push(e),T(o.id,{status:`failed`,progress:100,error:e})}}catch(e){let t=e&&e.message?e.message:`Upload failed. Please try again.`;console.error(`Upload failed:`,e),r.push(a.name+`: `+t),T(o.id,{status:`failed`,progress:o.progress||0,error:t})}}if(v(),r.length>0){E(e=>e.status===`uploaded`),y((e>0?`Uploaded `+e+` document(s). `:``)+r.join(` | `),e>0?`text-warning`:`text-danger`),b(null);return}E(()=>!0),y(`Uploaded `+e+` document(s).`,`text-success`),b(null)}catch(e){console.error(`Upload failed:`,e),y(`Upload failed. Please try again.`,`text-danger`),b(null)}finally{g=!1,s.disabled=!1,s.value=``}}async function k(e){if(o.removeDocumentUrl&&e&&window.confirm(`Remove this document?`))try{let n=await fetch(o.removeDocumentUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({itemId:o.itemId,documentId:e})});if(!n.ok){console.error(`Failed to remove document:`,await n.text()),y(`Failed to remove document.`,`text-danger`);return}if((n.headers.get(`content-type`)||``).toLowerCase().indexOf(`json`)<0){console.error(`Remove document: response was not JSON.`,{status:n.status,redirected:n.redirected}),y(n.redirected?`You may not be signed in, or you do not have permission for this. Please reload and try again.`:`Failed to remove document.`,`text-danger`);return}let r=await n.json(),i=(Array.isArray(r.documents)?r.documents:[]).map(t).filter(e=>e&&e.documentId);m=i.length>0?i:m.filter(t=>t.documentId!==e),v(),y(`Document removed.`,`text-success`)}catch(e){console.error(`Remove failed:`,e),y(`Failed to remove document.`,`text-danger`)}}let A=e=>{O(e.target.files?Array.from(e.target.files):[])};return s.addEventListener(`change`,A),s[e]={dispose:()=>{s.removeEventListener(`change`,A)}},v(),C(),y(null),b(null),s[e]}function s(e,t,n){let r=e.getAttribute(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return console.error(`Failed to parse `+n+` JSON.`,e),null}}function c(t){if(!t||t.dataset.chatInteractionDocumentManagerInitialized===`true`)return t&&t[e]||null;let n=s(t,`data-chat-interaction-document-manager-config`,`chat interaction document manager config`);if(!n)return null;let r=o(n);return r?(t.dataset.chatInteractionDocumentManagerInitialized=`true`,r):null}function l(e){e&&typeof e.querySelectorAll==`function`&&(typeof e.matches==`function`&&e.matches(`[data-chat-interaction-document-manager-config]`)&&c(e),e.querySelectorAll(`[data-chat-interaction-document-manager-config]`).forEach(c))}function u(){l(document),typeof MutationObserver<`u`&&new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e&&e.nodeType===1&&l(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,u,{once:!0}):u(),{initialize:o,initializeFromElement:c}}(),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)}))})})();
2
63
  //# sourceMappingURL=chat-interaction.min.js.map