@crestapps/ai-chat-ui 2.0.0-preview.259 → 2.0.0-preview.260
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-chat.js +6 -3
- package/dist/ai-chat.js.map +1 -1
- package/dist/ai-chat.min.js +3 -3
- package/dist/ai-chat.min.js.map +1 -1
- package/dist/chat-interaction.js +6 -3
- package/dist/chat-interaction.js.map +1 -1
- package/dist/chat-interaction.min.js +4 -4
- package/dist/chat-interaction.min.js.map +1 -1
- package/dist/chat-markers.js +166 -0
- package/dist/chat-markers.js.map +1 -1
- package/dist/chat-markers.min.js +1 -1
- package/dist/chat-markers.min.js.map +1 -1
- package/package.json +1 -1
package/dist/ai-chat.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(){window.crestAppsAGUI=(function(e){return e._contextProviders=Array.isArray(e._contextProviders)?e._contextProviders:[],e._stateProvider=e._stateProvider||null,e.registerContextProvider=function(t){typeof t==`function`&&e._contextProviders.push(t)},e.registerStateProvider=function(t){e._stateProvider=t&&typeof t==`object`?t:null},e})(window.crestAppsAGUI||{}),window.coreAIChatManager=function(){var e={generatedImageAltText:`Generated Image`,generatedImageMaxWidth:400,downloadImageTitle:`Download image`,downloadChartTitle:`Download chart as image`,downloadChartButtonText:`Download`,userLabel:`You`,assistantLabel:`Assistant`,protocol:`agui`,sendPageContext:!0,aguiThinkingLabel:`Thinking`,aguiInputLabel:`Input`,aguiResultLabel:`Result`,aguiApprovalPrompt:`Allow this action?`,aguiAllowLabel:`Allow`,aguiDenyLabel:`Deny`,aguiAllowedLabel:`Allowed`,aguiDeniedLabel:`Denied`,aguiWaitingLabel:`Waiting for your answer`,aguiRunningLabel:`Running`,aguiCurrentPageLabel:`Current page`,aguiSelectedTextLabel:`Text the user selected on the page`,aguiToolLabels:{},assistantAvatarUrl:null,thumbsUpTitle:`Thumbs up`,thumbsDownTitle:`Thumbs down`,copyTitle:`Click here to copy response to clipboard.`,copiedTitle:`Response copied to clipboard.`,codeCopiedText:`Copied!`,copyResetDelayMs:2e3,widget:{chatWidgetContainer:null,chatWidgetStateName:null,chatHistorySection:null,showHistoryButton:null,closeHistoryButton:null,newChatButton:null,toggleButtonSelector:null,resetSizeButtonSelector:null,dragHandleSelector:`.ai-chat-widget-header`,enableDragging:!0,enableResizing:!0,persistLayout:!0,defaultWidth:null,defaultHeight:null,minWidth:320,minHeight:420},messageTemplate:`
|
|
1
|
+
(function(){window.crestAppsAGUI=(function(e){return e._contextProviders=Array.isArray(e._contextProviders)?e._contextProviders:[],e._stateProvider=e._stateProvider||null,e.registerContextProvider=function(t){typeof t==`function`&&e._contextProviders.push(t)},e.registerStateProvider=function(t){e._stateProvider=t&&typeof t==`object`?t:null},e})(window.crestAppsAGUI||{}),window.coreAIChatManager=function(){var e={generatedImageAltText:`Generated Image`,generatedImageMaxWidth:400,allowedImageHosts:[],downloadImageTitle:`Download image`,downloadChartTitle:`Download chart as image`,downloadChartButtonText:`Download`,userLabel:`You`,assistantLabel:`Assistant`,protocol:`agui`,sendPageContext:!0,aguiThinkingLabel:`Thinking`,aguiInputLabel:`Input`,aguiResultLabel:`Result`,aguiApprovalPrompt:`Allow this action?`,aguiAllowLabel:`Allow`,aguiDenyLabel:`Deny`,aguiAllowedLabel:`Allowed`,aguiDeniedLabel:`Denied`,aguiWaitingLabel:`Waiting for your answer`,aguiRunningLabel:`Running`,aguiCurrentPageLabel:`Current page`,aguiSelectedTextLabel:`Text the user selected on the page`,aguiToolLabels:{},assistantAvatarUrl:null,thumbsUpTitle:`Thumbs up`,thumbsDownTitle:`Thumbs down`,copyTitle:`Click here to copy response to clipboard.`,copiedTitle:`Response copied to clipboard.`,codeCopiedText:`Copied!`,copyResetDelayMs:2e3,widget:{chatWidgetContainer:null,chatWidgetStateName:null,chatHistorySection:null,showHistoryButton:null,closeHistoryButton:null,newChatButton:null,toggleButtonSelector:null,resetSizeButtonSelector:null,dragHandleSelector:`.ai-chat-widget-header`,enableDragging:!0,enableResizing:!0,persistLayout:!0,defaultWidth:null,defaultHeight:null,minWidth:320,minHeight:420},messageTemplate:`
|
|
2
2
|
<div class="ai-chat-messages">
|
|
3
3
|
<div v-for="(message, index) in messages" :key="'msg-' + index" class="ai-chat-message-item">
|
|
4
4
|
<div>
|
|
@@ -68,12 +68,12 @@
|
|
|
68
68
|
|
|
69
69
|
References:
|
|
70
70
|
`;for(let e of t)n+=`${e.displayIndex}. ${e.label}`,e.link&&(n+=` - ${e.link}`),n+=`
|
|
71
|
-
`;return n.trimEnd()}function v(e,t){let n=c(t??e.references),r=typeof e.rawContent==`string`?e.rawContent:typeof e.content==`string`?e.content:``,i=u(r,n),a=g(i,n);return e.rawContent=r,e.content=r,e.displayContent=a.content,e.references=n,e.citationReferences=a.citations,e.copyContent=_(m(i),a.citations),e.htmlContent=D(e)+H(a.content,e),e}let y=window.crestAppsAGUI,b={page_get_info:`Reading the page`,page_read_content:`Reading the page's content`,page_list_links:`Looking at the page's links`,page_navigate:`Opening a page`,page_list_form_fields:`Reading the form`,page_set_form_field:`Filling in a field`,update_shared_state:`Updating what you share`},x=[`requested`,`completed`,`awaitingApproval`,`approved`,`rejected`,`awaitingClient`];function S(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function ne(e){return typeof e==`number`?x[e]||`requested`:typeof e==`string`&&e?e.charAt(0).toLowerCase()+e.slice(1):`requested`}function C(e){return Array.isArray(e)?e.filter(e=>e&&(e.callId||e.id)).map(e=>({id:e.callId||e.id,name:e.name||``,arguments:e.arguments||``,result:e.result||``,status:ne(e.status),interruptId:e.interruptId||e.approvalRequestId||null})):[]}function w(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function T(t){let n=Object.assign({},b,e.aguiToolLabels||{})[t.name];n||=(n=String(t.name||`tool`).replace(/[_.-]+/g,` `),n.charAt(0).toUpperCase()+n.slice(1));let r=w(t.arguments);return r&&t.name===`page_set_form_field`&&r.field?n+=`: `+r.field:r&&t.name===`page_navigate`&&r.url&&(n+=`: `+r.url),n}function E(e,t){let n=w(e),r=typeof n==`object`&&n?JSON.stringify(n,null,2):String(e??``);return r.length>t&&(r=r.slice(0,t)+`…`),r}function D(t){let n=Array.isArray(t.toolCalls)?t.toolCalls:[],r=[];t.reasoning&&r.push(`<details class="ai-chat-agui-reasoning"><summary>`+S(e.aguiThinkingLabel)+`</summary><div class="ai-chat-agui-reasoning-text">`+S(t.reasoning)+`</div></details>`);for(let t of n){let n=t.status||`requested`,i=`fa-solid fa-circle-notch fa-spin`,a=e.aguiRunningLabel;n===`completed`||n===`approved`?(i=`fa-solid fa-check`,a=n===`approved`?e.aguiAllowedLabel:``):n===`rejected`?(i=`fa-solid fa-ban`,a=e.aguiDeniedLabel):n===`awaitingApproval`&&(i=`fa-solid fa-hand`,a=e.aguiWaitingLabel);let o=``;t.arguments&&t.arguments!==`{}`&&(o+=`<div class="ai-chat-agui-tool-section"><div class="ai-chat-agui-tool-section-label">`+S(e.aguiInputLabel)+`</div><pre>`+S(E(t.arguments,2e3))+`</pre></div>`),t.result&&(o+=`<div class="ai-chat-agui-tool-section"><div class="ai-chat-agui-tool-section-label">`+S(e.aguiResultLabel)+`</div><pre>`+S(E(t.result,2e3))+`</pre></div>`);let s=`<i class="`+i+`" aria-hidden="true"></i> <span class="ai-chat-agui-tool-name">`+S(T(t))+`</span>`+(a?` <span class="ai-chat-agui-tool-state">`+S(a)+`</span>`:``),c=`<div class="ai-chat-agui-tool ai-chat-agui-tool-`+S(n)+`" data-agui-tool-call="`+S(t.id)+`">`;c+=o?`<details><summary>`+s+`</summary>`+o+`</details>`:`<div class="ai-chat-agui-tool-summary">`+s+`</div>`,n===`awaitingApproval`&&t.interruptId&&(c+=`<div class="ai-chat-agui-approval"><span>`+S(e.aguiApprovalPrompt)+`</span><button type="button" class="btn btn-sm btn-primary" data-agui-interrupt="`+S(t.interruptId)+`" data-agui-approved="true">`+S(e.aguiAllowLabel)+`</button><button type="button" class="btn btn-sm btn-outline-secondary" data-agui-interrupt="`+S(t.interruptId)+`" data-agui-approved="false">`+S(e.aguiDenyLabel)+`</button></div>`),c+=`</div>`,r.push(c)}return r.length?DOMPurify.sanitize(`<div class="ai-chat-agui-activity">`+r.join(``)+`</div>`):``}function O(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}function re(e,t){let n=O(e)??{};for(let e of t||[]){if(!e||typeof e.path!=`string`)continue;if(e.path===``){e.op===`replace`&&e.value&&typeof e.value==`object`&&(n=O(e.value));continue}let t=e.path.slice(1).split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),r=t.pop(),i=n;for(let e of t)i=i?.[Array.isArray(i)?Number(e):e];if(typeof i==`object`&&i){if(Array.isArray(i)){let t=r===`-`?i.length:Number(r);e.op===`add`?i.splice(t,0,O(e.value)):e.op===`replace`?i[t]=O(e.value):e.op===`remove`&&i.splice(t,1)}else e.op===`remove`?delete i[r]:(e.op===`add`||e.op===`replace`)&&(i[r]=O(e.value))}}return n}function k(){return window.crypto&&typeof window.crypto.randomUUID==`function`?window.crypto.randomUUID().replace(/-/g,``):Date.now().toString(36)+Math.random().toString(36).slice(2)}let A=`crestapps-agui-continue-run`;function j(){try{let e=JSON.parse(window.sessionStorage.getItem(A)||`null`);return e&&typeof e.sessionId==`string`?e:null}catch{return null}}function M(e){try{e?window.sessionStorage.setItem(A,JSON.stringify(e)):window.sessionStorage.removeItem(A)}catch{}}let N=new marked.Renderer;N.link=function(e){var n=t(e.href);return n?`<a href="${n}" target="_blank" rel="noopener noreferrer">${e.text}</a>`:e.text||``},N.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>`},N.image=function(n){let r=t(n.href);if(!r)return``;let i=n.text||e.generatedImageAltText;return`<span class="generated-image-container">
|
|
71
|
+
`;return n.trimEnd()}function v(e,t){let n=c(t??e.references),r=typeof e.rawContent==`string`?e.rawContent:typeof e.content==`string`?e.content:``,i=u(r,n),a=g(i,n);return e.rawContent=r,e.content=r,e.displayContent=a.content,e.references=n,e.citationReferences=a.citations,e.copyContent=_(m(i),a.citations),e.htmlContent=D(e)+H(a.content,e),e}let y=window.crestAppsAGUI,b={page_get_info:`Reading the page`,page_read_content:`Reading the page's content`,page_list_links:`Looking at the page's links`,page_navigate:`Opening a page`,page_list_form_fields:`Reading the form`,page_set_form_field:`Filling in a field`,update_shared_state:`Updating what you share`},x=[`requested`,`completed`,`awaitingApproval`,`approved`,`rejected`,`awaitingClient`];function S(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function ne(e){return typeof e==`number`?x[e]||`requested`:typeof e==`string`&&e?e.charAt(0).toLowerCase()+e.slice(1):`requested`}function C(e){return Array.isArray(e)?e.filter(e=>e&&(e.callId||e.id)).map(e=>({id:e.callId||e.id,name:e.name||``,arguments:e.arguments||``,result:e.result||``,status:ne(e.status),interruptId:e.interruptId||e.approvalRequestId||null})):[]}function w(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function T(t){let n=Object.assign({},b,e.aguiToolLabels||{})[t.name];n||=(n=String(t.name||`tool`).replace(/[_.-]+/g,` `),n.charAt(0).toUpperCase()+n.slice(1));let r=w(t.arguments);return r&&t.name===`page_set_form_field`&&r.field?n+=`: `+r.field:r&&t.name===`page_navigate`&&r.url&&(n+=`: `+r.url),n}function E(e,t){let n=w(e),r=typeof n==`object`&&n?JSON.stringify(n,null,2):String(e??``);return r.length>t&&(r=r.slice(0,t)+`…`),r}function D(t){let n=Array.isArray(t.toolCalls)?t.toolCalls:[],r=[];t.reasoning&&r.push(`<details class="ai-chat-agui-reasoning"><summary>`+S(e.aguiThinkingLabel)+`</summary><div class="ai-chat-agui-reasoning-text">`+S(t.reasoning)+`</div></details>`);for(let t of n){let n=t.status||`requested`,i=`fa-solid fa-circle-notch fa-spin`,a=e.aguiRunningLabel;n===`completed`||n===`approved`?(i=`fa-solid fa-check`,a=n===`approved`?e.aguiAllowedLabel:``):n===`rejected`?(i=`fa-solid fa-ban`,a=e.aguiDeniedLabel):n===`awaitingApproval`&&(i=`fa-solid fa-hand`,a=e.aguiWaitingLabel);let o=``;t.arguments&&t.arguments!==`{}`&&(o+=`<div class="ai-chat-agui-tool-section"><div class="ai-chat-agui-tool-section-label">`+S(e.aguiInputLabel)+`</div><pre>`+S(E(t.arguments,2e3))+`</pre></div>`),t.result&&(o+=`<div class="ai-chat-agui-tool-section"><div class="ai-chat-agui-tool-section-label">`+S(e.aguiResultLabel)+`</div><pre>`+S(E(t.result,2e3))+`</pre></div>`);let s=`<i class="`+i+`" aria-hidden="true"></i> <span class="ai-chat-agui-tool-name">`+S(T(t))+`</span>`+(a?` <span class="ai-chat-agui-tool-state">`+S(a)+`</span>`:``),c=`<div class="ai-chat-agui-tool ai-chat-agui-tool-`+S(n)+`" data-agui-tool-call="`+S(t.id)+`">`;c+=o?`<details><summary>`+s+`</summary>`+o+`</details>`:`<div class="ai-chat-agui-tool-summary">`+s+`</div>`,n===`awaitingApproval`&&t.interruptId&&(c+=`<div class="ai-chat-agui-approval"><span>`+S(e.aguiApprovalPrompt)+`</span><button type="button" class="btn btn-sm btn-primary" data-agui-interrupt="`+S(t.interruptId)+`" data-agui-approved="true">`+S(e.aguiAllowLabel)+`</button><button type="button" class="btn btn-sm btn-outline-secondary" data-agui-interrupt="`+S(t.interruptId)+`" data-agui-approved="false">`+S(e.aguiDenyLabel)+`</button></div>`),c+=`</div>`,r.push(c)}return r.length?DOMPurify.sanitize(`<div class="ai-chat-agui-activity">`+r.join(``)+`</div>`):``}function O(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}function re(e,t){let n=O(e)??{};for(let e of t||[]){if(!e||typeof e.path!=`string`)continue;if(e.path===``){e.op===`replace`&&e.value&&typeof e.value==`object`&&(n=O(e.value));continue}let t=e.path.slice(1).split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),r=t.pop(),i=n;for(let e of t)i=i?.[Array.isArray(i)?Number(e):e];if(typeof i==`object`&&i){if(Array.isArray(i)){let t=r===`-`?i.length:Number(r);e.op===`add`?i.splice(t,0,O(e.value)):e.op===`replace`?i[t]=O(e.value):e.op===`remove`&&i.splice(t,1)}else e.op===`remove`?delete i[r]:(e.op===`add`||e.op===`replace`)&&(i[r]=O(e.value))}}return n}function k(){return window.crypto&&typeof window.crypto.randomUUID==`function`?window.crypto.randomUUID().replace(/-/g,``):Date.now().toString(36)+Math.random().toString(36).slice(2)}let A=`crestapps-agui-continue-run`;function j(){try{let e=JSON.parse(window.sessionStorage.getItem(A)||`null`);return e&&typeof e.sessionId==`string`?e:null}catch{return null}}function M(e){try{e?window.sessionStorage.setItem(A,JSON.stringify(e)):window.sessionStorage.removeItem(A)}catch{}}let N=new marked.Renderer;N.link=function(e){var n=t(e.href);return n?`<a href="${n}" target="_blank" rel="noopener noreferrer">${e.text}</a>`:e.text||``},N.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>`},N.image=function(n){let r=t(n.href);if(!r)return``;if(!window.CoreAIImages.isAllowedSource(r,{allowedHosts:e.allowedImageHosts}))return window.CoreAIImages.linkHtml(r,n.text);let i=n.text||e.generatedImageAltText;return`<span class="generated-image-container">
|
|
72
72
|
<img src="${r}" alt="${i}" class="img-thumbnail" style="max-width: ${e.generatedImageMaxWidth}px; height: auto;" />
|
|
73
73
|
<a href="${r}" target="_blank" download="${i}" title="${e.downloadImageTitle}" class="btn btn-sm btn-outline-secondary ai-download-image">
|
|
74
74
|
<i class="fa-solid fa-download"></i>
|
|
75
75
|
</a>
|
|
76
|
-
</span>`};let ie=0,P=[];window.__chartConfigs=window.__chartConfigs||{};function ae(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 F=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=F(e);if(!t||t.startIndex!==0)return;let n=`chat_chart_${++ie}`;return{type:`chart`,raw:e.substring(0,t.endIndex),chartId:n,json:t.json}},renderer(e){return P.push({chartId:e.chartId,config:e.json}),window.__chartConfigs[e.chartId]=e.json,ae(e.chartId)}}]});function I(){typeof document<`u`&&typeof requestAnimationFrame==`function`&&(requestAnimationFrame(R),requestAnimationFrame(L))}function L(){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 R(){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 z(e){if(I(),!e||!e._pendingCharts||!e._pendingCharts.length)return;let t=[...e._pendingCharts];e._pendingCharts=[],requestAnimationFrame(()=>{for(let e of t)B(e.chartId,e.config)})}function B(e,t){let n=document.getElementById(e);if(!n)return!1;if(typeof Chart>`u`)return 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>).`),!1;if(n.offsetParent===null)return window.__chartConfigs[e]=t,!1;try{n._chartInstance&&n._chartInstance.destroy();let r=typeof t==`string`?JSON.parse(t):t;return r.options??={},r.options.responsive=!0,r.options.maintainAspectRatio=!0,r.options.aspectRatio??=4/3,n._chartInstance=new Chart(n,r),delete window.__chartConfigs[e],!0}catch(e){return console.error(`Error creating chart:`,e),!1}}window.renderPendingCharts=function(){if(typeof Chart>`u`)return;let e=window.__chartConfigs;e&&requestAnimationFrame(()=>{for(let t of Object.keys(e))B(t,e[t])})};function V(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 H(e,t){P=[];let n=V(marked.parse(e,{renderer:N}));t._pendingCharts=P.length>0?[...P]:[];let r=DOMPurify.sanitize(n,{ADD_TAGS:[`canvas`],ADD_ATTR:[`target`]});return window.CoreAIChatImageCarousel?window.CoreAIChatImageCarousel.stackAdjacentImages(r):r}function U(e){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function W(e,r,i){if(!e)return e;let a=n(r||`Assistant`),o=t(i),s=o?`<span class="ai-streaming-avatar"><img class="ai-chat-assistant-avatar" src="`+G(o)+`" alt="" /></span>`:`<span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>`;return e.replace(/\{\{\s*assistantLabel\s*\}\}/g,a).replace(/\{\{\s*assistantIcon\s*\}\}/g,s)}function G(e){return n(e).replace(/"/g,`"`).replace(/'/g,`'`)}let K=n=>{let r=U(n),s=U(r.widget),u=Object.assign({},e,r);u.widget=Object.assign({},e.widget||{},s),u.indicatorTemplate=W(u.indicatorTemplate,u.assistantLabel,u.assistantAvatarUrl);let d=!!(s.chatWidgetContainer&&s.chatWidgetStateName),f=window.coreAIChatWidgetBehavior||null;if(e=u,!u.signalRHubUrl){console.error(`The signalRHubUrl is required.`);return}if(!u.appElementSelector){console.error(`The appElementSelector is required.`);return}if(!u.chatContainerElementSelector){console.error(`The chatContainerElementSelector is required.`);return}if(!u.inputElementSelector){console.error(`The inputElementSelector is required.`);return}if(!u.sendButtonElementSelector){console.error(`The sendButtonElementSelector is required.`);return}let p={data(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,pageTools:null,aguiRun:null,aguiDisabled:!1,sharedStateCache:null,lastPageSelection:null,messages:[],notifications:[],prompt:``,documents:u.existingDocuments||[],isUploading:!1,isDocumentOperationPending:!1,documentOperationQueue:null,uploadErrors:[],isDragOver:!1,documentBar:null,metricsEnabled:!!u.metricsEnabled,userLabel:u.userLabel,assistantLabel:u.assistantLabel,assistantAvatarUrl:t(u.assistantAvatarUrl)||null,thumbsUpTitle:u.thumbsUpTitle,thumbsDownTitle:u.thumbsDownTitle,copyTitle:u.copyTitle,copiedTitle:u.copiedTitle,isRecording:!1,mediaRecorder:null,preRecordingPrompt:``,micButton:null,speechToTextEnabled:!u.realtimeEnabled&&(u.chatMode===`AudioInput`||u.chatMode===`Conversation`),textToSpeechEnabled:!u.realtimeEnabled&&u.chatMode===`Conversation`||!!u.textToSpeechEnabled,ttsVoiceName:u.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsButton:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:`ai-chat-`+Math.random().toString(36).slice(2),singleResponseMode:!!u.singleResponseMode,conversationModeEnabled:u.chatMode===`Conversation`,realtimeEnabled:!!u.realtimeEnabled,realtimeWebRtcEnabled:u.realtimeWebRtcEnabled===!0&&typeof window.RTCPeerConnection==`function`,realtimeWebRtcIceServers:Array.isArray(u.realtimeWebRtcIceServers)&&u.realtimeWebRtcIceServers.length?u.realtimeWebRtcIceServers:null,realtimeVoiceName:u.realtimeVoiceName||null,conversationButton:null,realtimeHintElement:u.realtimeHintElementSelector?document.querySelector(u.realtimeHintElementSelector):null,isConversationMode:!1,notificationDismissTimers:{},pendingSessionPromise:null,pendingSessionResolver:null,pendingSessionRejector:null,pendingSessionTimeoutId:null,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},handleDragOver(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!0;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.add(`ai-chat-drag-over`)}},handleDragLeave(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.remove(`ai-chat-drag-over`)}},handleDrop(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.remove(`ai-chat-drag-over`),e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&this.uploadFiles(Array.from(e.dataTransfer.files))}},triggerFileInput(){if(u.sessionDocumentsEnabled&&!this.isDocumentOperationPending){var e=document.getElementById(`ai-chat-doc-input`);e&&e.click()}},handleFileInputChange(e){var t=e.target.files?Array.from(e.target.files):[];t&&t.length>0&&this.uploadFiles(t),e.target.value=``},queueDocumentOperation(e){var t=this,n=(this.documentOperationQueue||Promise.resolve()).catch(function(){}).then(async function(){t.isDocumentOperationPending=!0;try{return await e()}finally{t.isDocumentOperationPending=!1}});return this.documentOperationQueue=n.finally(function(){t.documentOperationQueue===n&&(t.documentOperationQueue=null)}),this.documentOperationQueue},async uploadFiles(e){if(u.uploadDocumentUrl){var t=Array.isArray(e)?e.slice():Array.from(e||[]);if(t.length!==0)return this.queueDocumentOperation(async()=>{var e=this.getSessionId(),n=this.getProfileId();if(!e)try{e=await this.ensureSessionForDocuments(n)}catch(e){console.error(`Failed to create a chat session for document upload:`,e),this.uploadErrors=[{fileName:``,error:`Could not create a chat session for the upload.`}],this.renderDocumentBar();return}if(!e)console.warn(`Cannot upload documents without a session or profile.`),this.uploadErrors=[{fileName:``,error:`Could not create a chat session for the upload.`}],this.renderDocumentBar();else{this.isUploading=!0,this.uploadErrors=[],this.renderDocumentBar();try{var r=new FormData;r.append(`sessionId`,e);for(var i=0;i<t.length;i++)r.append(`files`,t[i]);var a=await fetch(u.uploadDocumentUrl,{method:`POST`,body:r});if(!a.ok){var o=await a.text(),s=this.extractReadableErrorMessage(o,`Upload failed. Please try again.`);console.error(`Upload failed:`,o),this.uploadErrors=[{fileName:``,error:s}];return}var c=await l(a,`Upload failed. Please try again.`);if(!c.ok){console.error(`Upload failed: response was not JSON.`,{status:a.status,redirected:a.redirected}),this.uploadErrors=[{fileName:``,error:c.message}];return}var d=c.data;d.sessionId&&d.sessionId!==this.getSessionId()&&this.initializeSession(d.sessionId),Array.isArray(d.documents)?this.documents=d.documents:d.uploaded&&d.uploaded.length>0&&(this.documents=this.documents.concat(d.uploaded)),d.failed&&d.failed.length>0&&(this.uploadErrors=d.failed)}catch(e){console.error(`Upload error:`,e),this.uploadErrors=[{fileName:``,error:`Upload failed. Please try again.`}],this.getSessionId()&&this.reloadCurrentSession()}finally{this.isUploading=!1,this.renderDocumentBar()}}})}},async removeDocument(e){if(u.removeDocumentUrl)return this.queueDocumentOperation(async()=>{try{var t=this.getSessionId(),n=await fetch(u.removeDocumentUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({itemId:t,documentId:e.documentId})});if(n.ok){var r=await l(n,`The request could not be completed.`);if(!r.ok){console.error(`Response was not JSON.`,{status:n.status,redirected:n.redirected});return}var i=r.data;if(Array.isArray(i.documents))this.documents=i.documents;else{var a=this.documents.indexOf(e);a>-1&&this.documents.splice(a,1)}}else{var o=await n.text(),s=this.extractReadableErrorMessage(o,`Failed to remove document. Please try again.`);console.error(`Failed to remove document:`,n.status,o),this.uploadErrors=[{fileName:e.fileName||``,error:s}],t&&this.reloadCurrentSession(),this.renderDocumentBar()}}catch(t){console.error(`Remove document error:`,t),this.uploadErrors=[{fileName:e.fileName||``,error:`Failed to remove document. Please try again.`}],this.getSessionId()&&this.reloadCurrentSession(),this.renderDocumentBar()}})},formatFileSize(e){return e<1024?e+` B`:e<1048576?(e/1024).toFixed(1)+` KB`:(e/1048576).toFixed(1)+` MB`},renderDocumentBar(){if(this.documentBar){if(!u.sessionDocumentsEnabled)this.documentBar.classList.add(`d-none`);else{this.documentBar.classList.remove(`d-none`);var e=`<div class="ai-chat-doc-bar p-2">`;e+=`<div class="d-flex flex-wrap align-items-center gap-1">`;for(var t=0;t<this.documents.length;t++){var n=this.documents[t],r=n.fileName||`Document`;r.length>20&&(r=r.substring(0,17)+`...`),e+=`<span class="badge bg-secondary bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="`+this.escapeHtml(n.fileName||``)+`">`,e+=`<i class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></i> `,e+=this.escapeHtml(r),e+=` <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-doc-index="`+t+`" aria-label="Remove"`+(this.isDocumentOperationPending?` disabled`:``)+`></button>`,e+=`</span>`}for(var i=0;i<this.uploadErrors.length;i++){var a=this.uploadErrors[i],o=a.error||`Upload failed`;e+=`<span class="alert alert-danger d-flex align-items-start gap-2 w-100 mb-1 py-1 px-2" role="alert" style="font-size: 0.8rem;">`,e+=`<i class="fa-solid fa-circle-exclamation mt-1" style="font-size: 0.7rem;"></i>`,e+=`<span class="flex-grow-1">`,a.fileName&&(e+=`<strong>`+this.escapeHtml(a.fileName)+`</strong>: `),e+=this.escapeHtml(o),e+=`</span>`,e+=`<button type="button" class="btn-close btn-close-sm" style="font-size: 0.5rem;" data-error-index="`+i+`" aria-label="Dismiss"></button>`,e+=`</span>`}this.isUploading&&(e+=`<span class="badge bg-info bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;">`,e+=`<span class="spinner-border spinner-border-sm" style="width: 0.7rem; height: 0.7rem;"></span> Uploading...`,e+=`</span>`),e+=`<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill ai-chat-doc-add-btn d-inline-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 0.15rem 0.5rem;" title="Attach documents"`+(this.isDocumentOperationPending?` disabled`:``)+`>`,e+=`<i class="fa-solid fa-paperclip"></i>`,this.documents.length===0&&!this.isUploading&&(e+=` <span>Attach files</span>`),e+=`</button>`,e+=`</div>`,u.supportedExtensionsText&&(e+=`<div class="small text-muted mt-2">Supported formats: `+this.escapeHtml(u.supportedExtensionsText)+`</div>`),e+=`</div>`,this.documentBar.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}));for(var s=this,c=this.documentBar.querySelectorAll(`[data-doc-index]`),l=0;l<c.length;l++)c[l].addEventListener(`click`,(function(e){return function(t){if(t.preventDefault(),t.stopPropagation(),!s.isDocumentOperationPending){var n=s.documents[e];n&&s.removeDocument(n)}}})(parseInt(c[l].getAttribute(`data-doc-index`))));for(var d=this.documentBar.querySelectorAll(`[data-error-index]`),f=0;f<d.length;f++)d[f].addEventListener(`click`,(function(e){return function(t){t.preventDefault(),t.stopPropagation(),s.uploadErrors.splice(e,1),s.renderDocumentBar()}})(parseInt(d[f].getAttribute(`data-error-index`))));var p=this.documentBar.querySelector(`.ai-chat-doc-add-btn`);p&&p.addEventListener(`click`,function(e){e.preventDefault(),!s.isDocumentOperationPending&&s.triggerFileInput()})}}},escapeHtml(e){var t=document.createElement(`div`);return t.textContent=e,t.innerHTML},extractReadableErrorMessage(e,t){if(!e||typeof e!=`string`)return t;var n=e.trim();if(!n)return t;if(n.startsWith(`{`)||n.startsWith(`[`))try{var r=JSON.parse(n),i=r?.error||r?.message||r?.title||r?.detail;return typeof i==`string`&&i.trim()?i.trim():t}catch{return t}return/<[^>]+>/.test(n)?t:n},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(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.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.getAssistantAvatarUrl(e)?[this.shouldAnimateAssistantIcon(e,t)?`ai-streaming-avatar`:`ai-bot-avatar`]:[this.shouldAnimateAssistantIcon(e,t)?`ai-streaming-icon`:`ai-bot-icon`,n&&n.cssClass?n.cssClass:``]},getAssistantAvatarUrl(e){return!this.assistantAvatarUrl||e&&this.normalizeAssistantAppearance(e.appearance)?null:this.assistantAvatarUrl},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)},async startConnection(){this.connection=new signalR.HubConnectionBuilder().withUrl(u.signalRHubUrl).withAutomaticReconnect().build(),this.connection.serverTimeoutInMilliseconds=6e5,this.connection.keepAliveIntervalInMilliseconds=15e3,this.connection.on(`LoadSession`,e=>{this.stream&&e&&e.sessionId===this.getSessionId()||(this.forceStopActiveVoice(),this.initializeSession(e.sessionId,!0),this.messages=[],this.documents=e.documents||[],this.uploadErrors=[],(e.messages??[]).forEach(e=>{this.addMessage(e),this.$nextTick(()=>{z(e)})}),this.$nextTick(()=>{this.refreshAllFeedbackIcons()}),this.messages.length===0&&u.initialPrompt&&this.addMessage({role:`assistant`,content:u.initialPrompt}),this.continueRunOnThisPage(e))}),this.connection.on(`ReceiveError`,e=>{console.error(`SignalR Error: `,e),this.isRecording&&this.stopRecording(),this.rejectPendingSessionRequest(e),this.hideTypingIndicator(),f&&typeof f.handleReceiveError==`function`?f.handleReceiveError(this,e,u):this.isNavigatingAway||this.addMessage(this.getErrorMessage(e))}),this.connection.on(`ReceiveSessionStartRejected`,e=>{this.rejectPendingSessionRequest(e),this.hideTypingIndicator(),this.isNavigatingAway||this.addMessage(this.getErrorMessage(e))}),this.connection.on(`MessageRated`,(e,t)=>{var n=this.messages.find(t=>t.id===e);n&&(n.userRating=t)}),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,`&`).replace(/</g,`<`).replace(/>/g,`>`)+`</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(e&&this.getSessionId()!==e&&this.initializeSession(e),t&&this._realtimePendingTurns&&this._realtimePendingTurns[t]){var r=this._realtimePendingTurns[t];delete this._realtimePendingTurns[t],this.stopAudio(),this.fillRealtimePendingTurn(r,n)}else if(n){if(this.stopAudio(),this._conversationPartialMessage){var i=n.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`);this._conversationPartialMessage.content=n,this._conversationPartialMessage.htmlContent=`<p>`+i+`</p>`,this._conversationPartialMessage.isPartial=!1,this._conversationPartialMessage=null}else if(this._conversationAssistantMessage){var a=this._conversationAssistantMessage.index,o={role:`user`,content:n,rawContent:n,userRating:null,references:{}};v(o,o.references),this.messages.splice(a,0,o),this._conversationAssistantMessage.index=a+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,userRating:null,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||{})),v(d,d.references),this.$nextTick(()=>{z(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||{})),v(r,r.references)),this._conversationAssistantMessage=null,this._conversationAssistantResponseId=null}}),this.connection.on(`ReceiveAudioChunk`,(e,t,n)=>{if(!t)return;let r=atob(t),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);n===`audio/pcm`?this.realtimeController&&this.realtimeController.receivePcm(i):this.audioChunks.push(i)}),this.connection.on(`ReceiveAudioComplete`,()=>{this.playCollectedAudio()}),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.realtimeEnabled&&this.isConversationMode&&this.stopRealtimeConversation()}),this.connection.onreconnected(()=>{console.info(`SignalR: reconnected.`),this.isSessionStarted&&this.reloadCurrentSession()}),this.connection.onclose(e=>{this.isNavigatingAway||(this.realtimeEnabled&&this.isConversationMode&&this.stopRealtimeConversation(),e&&console.warn(`SignalR connection closed with error:`,e.message||e))});try{await this.connection.start()}catch(e){console.error(`SignalR Connection Error: `,e)}this.ensurePageTools()},ensurePageTools(){return!this.pageTools&&this.connection&&window.crestAppsWebMcp&&typeof window.crestAppsWebMcp.connectChat==`function`&&(this.pageTools=window.crestAppsWebMcp.connectChat(this.connection)),this.pageTools},async syncPageTools(){var e=this.ensurePageTools();if(e)try{await e.sync()}catch(e){console.warn(`The page tools could not be sent to the chat.`,e)}},async ensureConnectionStarted(){if(!this.connection)return!1;var e=signalR.HubConnectionState;if(this.connection.state===e.Connected)return!0;if(this.connection.state===e.Disconnected){try{await this.connection.start()}catch(e){console.error(`SignalR Connection Error: `,e)}return this.connection.state===e.Connected}return await new Promise(t=>{var n=e=>{clearTimeout(r),clearInterval(i),t(e)},r=setTimeout(()=>n(this.connection.state===e.Connected),1e4),i=setInterval(()=>{this.connection.state===e.Connected?n(!0):this.connection.state===e.Disconnected&&n(!1)},100)})},addMessageInternal(e){e.role===`assistant`&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=H(e.content,e)),this.fireEvent(new CustomEvent(`addingCoreAIPromotMessage`,{detail:{message:e}})),this.messages.push(e),this.$nextTick(()=>{this.fireEvent(new CustomEvent(`addedCoreAIPromotMessage`,{detail:{message:e}}))})},addMessage(e){e.userRating===void 0&&(e.userRating=null),e.role===`assistant`&&e.toolCalls&&(e.toolCalls=C(e.toolCalls)),(e.content||e.toolCalls&&e.toolCalls.length)&&(e.rawContent=e.rawContent??e.content??``,v(e,e.references)),this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(()=>{z(e),this.scrollToBottom()})},addMessages(e){for(let t=0;t<e.length;t++)this.addMessageInternal(e[t]);this.hidePlaceholder(),this.$nextTick(()=>{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},isOrchestratorAvailable(){return u.isOrchestratorAvailable!==!1},applyOrchestratorAvailability(){if(this.isOrchestratorAvailable())return!0;let e=u.orchestratorUnavailableMessage||`This orchestrator is not currently available.`;return this.inputElement&&(this.inputElement.disabled=!0,this.inputElement.value=``,this.inputElement.placeholder=e),this.buttonElement&&(this.buttonElement.disabled=!0),this.micButtonElement&&(this.micButtonElement.disabled=!0,this.micButtonElement.style.display=`none`),this.conversationButtonElement&&(this.conversationButtonElement.disabled=!0,this.conversationButtonElement.style.display=`none`),!1},fireEvent(e){document.dispatchEvent(e)},isIndicator(e){return e.role===`indicator`},sendMessage(){if(!this.applyOrchestratorAvailability())return;let e=this.prompt.trim();e&&(this.forceStopActiveVoice(),this.isRecording&&this.stopRecording(),this._audioInputSent=!0,this.singleResponseMode&&this.messages.splice(0,this.messages.length),this.addMessage({role:`user`,content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value=``,this.prompt=``)},startRecording(){!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(e=>{this.preRecordingPrompt=this.prompt,this._audioInputSent=!1;var t=new signalR.Subject,n=this.getProfileId(),r=this.getSessionId()||``;this._sttCapture=this._createPcmCapture(e,e=>{try{t.next(e)}catch{}}),this._sttSubject=t;var i=this._sttCapture&&this._sttCapture.sampleRate||16e3,a=navigator.language||document.documentElement.lang||`en-US`;this.connection.send(`SendAudioStream`,n,r,t,`audio/pcm;rate=`+i,a),this.isRecording=!0,this.updateMicButton()}).catch(e=>{console.error(`Microphone access denied:`,e)})},stopRecording(){if(this.isRecording){if(this._stopPcmCapture(this._sttCapture),this._sttCapture=null,this._sttSubject){try{this._sttSubject.complete()}catch{}this._sttSubject=null}this.isRecording=!1,this.updateMicButton()}},_createPcmCapture(e,t){var n=window.AudioContext||window.webkitAudioContext,r;try{r=new n({sampleRate:16e3})}catch{r=new n}var i=r.sampleRate,a=r.createMediaStreamSource(e),o=r.createScriptProcessor(4096,1,1),s=this;return o.onaudioprocess=function(e){var n=e.inputBuffer.getChannelData(0),r=s._downsampleToInt16(n,i,16e3);if(r&&r.length!==0){for(var a=0,o=0;o<r.length;o++){var c=r[o]/32768;a+=c*c}for(var l=Math.sqrt(a/r.length),u=new Uint8Array(r.buffer),d=``,f=0;f<u.length;f++)d+=String.fromCharCode(u[f]);t(btoa(d),l)}},a.connect(o),o.connect(r.destination),{audioContext:r,source:a,processor:o,stream:e,sampleRate:16e3}},_stopPcmCapture(e){if(e){try{e.processor&&(e.processor.onaudioprocess=null,e.processor.disconnect())}catch{}try{e.source&&e.source.disconnect()}catch{}try{e.stream&&e.stream.getTracks().forEach(function(e){e.stop()})}catch{}try{e.audioContext&&e.audioContext.close()}catch{}}},_downsampleToInt16(e,t,n){var r,i;if(!(n<t)){var a=new Int16Array(e.length);for(i=0;i<e.length;i++)r=Math.max(-1,Math.min(1,e[i])),a[i]=r<0?r*32768:r*32767;return a}for(var o=t/n,s=Math.floor(e.length/o),c=new Int16Array(s),l=0;l<s;l++){var u=l*o,d=Math.floor(u),f=d+1<e.length?d+1:e.length-1,p=u-d;r=e[d]*(1-p)+e[f]*p,r=Math.max(-1,Math.min(1,r)),c[l]=r<0?r*32768:r*32767}return c},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>`))},streamMessage(e,t,n){if((u.protocol||`agui`)===`agui`&&!this.aguiDisabled)this.streamAGUIRun(e,t,n,null);else{this.stream&&=(this.stream.dispose(),null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var r=``,i={},a=null,s=this.messages.length,c=this.getSessionId(),l=()=>{this.stream=this.connection.stream(`SendMessage`,e,t,c,n).subscribe({next:e=>{let t=this.messages[s];if(!t){e.sessionId&&!c&&this.initializeSession(e.sessionId),this.hideTypingIndicator(),s=this.messages.length;let n={id:e.messageId,role:`assistant`,title:e.title,content:``,htmlContent:``,isStreaming:!0,userRating:null};this.messages.push(n),t=n}if(e.title&&(!t.title||t.title!==e.title)&&(t.title=e.title),e.references&&typeof e.references==`object`&&Object.keys(e.references).length)for(let[t,n]of Object.entries(e.references))i[t]=o(n)??{};e.content&&(e.responseId&&a&&e.responseId!==a&&(r+=`
|
|
76
|
+
</span>`};let ie=0,P=[];window.__chartConfigs=window.__chartConfigs||{};function ae(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 F=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=F(e);if(!t||t.startIndex!==0)return;let n=`chat_chart_${++ie}`;return{type:`chart`,raw:e.substring(0,t.endIndex),chartId:n,json:t.json}},renderer(e){return P.push({chartId:e.chartId,config:e.json}),window.__chartConfigs[e.chartId]=e.json,ae(e.chartId)}}]});function I(){typeof document<`u`&&typeof requestAnimationFrame==`function`&&(requestAnimationFrame(R),requestAnimationFrame(L))}function L(){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 R(){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 z(e){if(I(),!e||!e._pendingCharts||!e._pendingCharts.length)return;let t=[...e._pendingCharts];e._pendingCharts=[],requestAnimationFrame(()=>{for(let e of t)B(e.chartId,e.config)})}function B(e,t){let n=document.getElementById(e);if(!n)return!1;if(typeof Chart>`u`)return 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>).`),!1;if(n.offsetParent===null)return window.__chartConfigs[e]=t,!1;try{n._chartInstance&&n._chartInstance.destroy();let r=typeof t==`string`?JSON.parse(t):t;return r.options??={},r.options.responsive=!0,r.options.maintainAspectRatio=!0,r.options.aspectRatio??=4/3,n._chartInstance=new Chart(n,r),delete window.__chartConfigs[e],!0}catch(e){return console.error(`Error creating chart:`,e),!1}}window.renderPendingCharts=function(){if(typeof Chart>`u`)return;let e=window.__chartConfigs;e&&requestAnimationFrame(()=>{for(let t of Object.keys(e))B(t,e[t])})};function V(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 H(t,n){P=[];let r=V(marked.parse(t,{renderer:N}));n._pendingCharts=P.length>0?[...P]:[];let i=window.CoreAIImages.sanitize(DOMPurify,r,{ADD_TAGS:[`canvas`],ADD_ATTR:[`target`]},{allowedHosts:e.allowedImageHosts});return window.CoreAIChatImageCarousel?window.CoreAIChatImageCarousel.stackAdjacentImages(i):i}function U(e){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function W(e,r,i){if(!e)return e;let a=n(r||`Assistant`),o=t(i),s=o?`<span class="ai-streaming-avatar"><img class="ai-chat-assistant-avatar" src="`+G(o)+`" alt="" /></span>`:`<span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>`;return e.replace(/\{\{\s*assistantLabel\s*\}\}/g,a).replace(/\{\{\s*assistantIcon\s*\}\}/g,s)}function G(e){return n(e).replace(/"/g,`"`).replace(/'/g,`'`)}let K=n=>{let r=U(n),s=U(r.widget),u=Object.assign({},e,r);u.widget=Object.assign({},e.widget||{},s),u.indicatorTemplate=W(u.indicatorTemplate,u.assistantLabel,u.assistantAvatarUrl);let d=!!(s.chatWidgetContainer&&s.chatWidgetStateName),f=window.coreAIChatWidgetBehavior||null;if(e=u,!u.signalRHubUrl){console.error(`The signalRHubUrl is required.`);return}if(!u.appElementSelector){console.error(`The appElementSelector is required.`);return}if(!u.chatContainerElementSelector){console.error(`The chatContainerElementSelector is required.`);return}if(!u.inputElementSelector){console.error(`The inputElementSelector is required.`);return}if(!u.sendButtonElementSelector){console.error(`The sendButtonElementSelector is required.`);return}let p={data(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,pageTools:null,aguiRun:null,aguiDisabled:!1,sharedStateCache:null,lastPageSelection:null,messages:[],notifications:[],prompt:``,documents:u.existingDocuments||[],isUploading:!1,isDocumentOperationPending:!1,documentOperationQueue:null,uploadErrors:[],isDragOver:!1,documentBar:null,metricsEnabled:!!u.metricsEnabled,userLabel:u.userLabel,assistantLabel:u.assistantLabel,assistantAvatarUrl:t(u.assistantAvatarUrl)||null,thumbsUpTitle:u.thumbsUpTitle,thumbsDownTitle:u.thumbsDownTitle,copyTitle:u.copyTitle,copiedTitle:u.copiedTitle,isRecording:!1,mediaRecorder:null,preRecordingPrompt:``,micButton:null,speechToTextEnabled:!u.realtimeEnabled&&(u.chatMode===`AudioInput`||u.chatMode===`Conversation`),textToSpeechEnabled:!u.realtimeEnabled&&u.chatMode===`Conversation`||!!u.textToSpeechEnabled,ttsVoiceName:u.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsButton:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:`ai-chat-`+Math.random().toString(36).slice(2),singleResponseMode:!!u.singleResponseMode,conversationModeEnabled:u.chatMode===`Conversation`,realtimeEnabled:!!u.realtimeEnabled,realtimeWebRtcEnabled:u.realtimeWebRtcEnabled===!0&&typeof window.RTCPeerConnection==`function`,realtimeWebRtcIceServers:Array.isArray(u.realtimeWebRtcIceServers)&&u.realtimeWebRtcIceServers.length?u.realtimeWebRtcIceServers:null,realtimeVoiceName:u.realtimeVoiceName||null,conversationButton:null,realtimeHintElement:u.realtimeHintElementSelector?document.querySelector(u.realtimeHintElementSelector):null,isConversationMode:!1,notificationDismissTimers:{},pendingSessionPromise:null,pendingSessionResolver:null,pendingSessionRejector:null,pendingSessionTimeoutId:null,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},handleDragOver(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!0;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.add(`ai-chat-drag-over`)}},handleDragLeave(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.remove(`ai-chat-drag-over`)}},handleDrop(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.remove(`ai-chat-drag-over`),e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&this.uploadFiles(Array.from(e.dataTransfer.files))}},triggerFileInput(){if(u.sessionDocumentsEnabled&&!this.isDocumentOperationPending){var e=document.getElementById(`ai-chat-doc-input`);e&&e.click()}},handleFileInputChange(e){var t=e.target.files?Array.from(e.target.files):[];t&&t.length>0&&this.uploadFiles(t),e.target.value=``},queueDocumentOperation(e){var t=this,n=(this.documentOperationQueue||Promise.resolve()).catch(function(){}).then(async function(){t.isDocumentOperationPending=!0;try{return await e()}finally{t.isDocumentOperationPending=!1}});return this.documentOperationQueue=n.finally(function(){t.documentOperationQueue===n&&(t.documentOperationQueue=null)}),this.documentOperationQueue},async uploadFiles(e){if(u.uploadDocumentUrl){var t=Array.isArray(e)?e.slice():Array.from(e||[]);if(t.length!==0)return this.queueDocumentOperation(async()=>{var e=this.getSessionId(),n=this.getProfileId();if(!e)try{e=await this.ensureSessionForDocuments(n)}catch(e){console.error(`Failed to create a chat session for document upload:`,e),this.uploadErrors=[{fileName:``,error:`Could not create a chat session for the upload.`}],this.renderDocumentBar();return}if(!e)console.warn(`Cannot upload documents without a session or profile.`),this.uploadErrors=[{fileName:``,error:`Could not create a chat session for the upload.`}],this.renderDocumentBar();else{this.isUploading=!0,this.uploadErrors=[],this.renderDocumentBar();try{var r=new FormData;r.append(`sessionId`,e);for(var i=0;i<t.length;i++)r.append(`files`,t[i]);var a=await fetch(u.uploadDocumentUrl,{method:`POST`,headers:window.CoreAIAntiforgery.headers(u,void 0,u.uploadDocumentUrl),body:r});if(!a.ok){var o=await a.text(),s=this.extractReadableErrorMessage(o,`Upload failed. Please try again.`);console.error(`Upload failed:`,o),this.uploadErrors=[{fileName:``,error:s}];return}var c=await l(a,`Upload failed. Please try again.`);if(!c.ok){console.error(`Upload failed: response was not JSON.`,{status:a.status,redirected:a.redirected}),this.uploadErrors=[{fileName:``,error:c.message}];return}var d=c.data;d.sessionId&&d.sessionId!==this.getSessionId()&&this.initializeSession(d.sessionId),Array.isArray(d.documents)?this.documents=d.documents:d.uploaded&&d.uploaded.length>0&&(this.documents=this.documents.concat(d.uploaded)),d.failed&&d.failed.length>0&&(this.uploadErrors=d.failed)}catch(e){console.error(`Upload error:`,e),this.uploadErrors=[{fileName:``,error:`Upload failed. Please try again.`}],this.getSessionId()&&this.reloadCurrentSession()}finally{this.isUploading=!1,this.renderDocumentBar()}}})}},async removeDocument(e){if(u.removeDocumentUrl)return this.queueDocumentOperation(async()=>{try{var t=this.getSessionId(),n=await fetch(u.removeDocumentUrl,{method:`POST`,headers:window.CoreAIAntiforgery.headers(u,{"Content-Type":`application/json`},u.removeDocumentUrl),body:JSON.stringify({itemId:t,documentId:e.documentId})});if(n.ok){var r=await l(n,`The request could not be completed.`);if(!r.ok){console.error(`Response was not JSON.`,{status:n.status,redirected:n.redirected});return}var i=r.data;if(Array.isArray(i.documents))this.documents=i.documents;else{var a=this.documents.indexOf(e);a>-1&&this.documents.splice(a,1)}}else{var o=await n.text(),s=this.extractReadableErrorMessage(o,`Failed to remove document. Please try again.`);console.error(`Failed to remove document:`,n.status,o),this.uploadErrors=[{fileName:e.fileName||``,error:s}],t&&this.reloadCurrentSession(),this.renderDocumentBar()}}catch(t){console.error(`Remove document error:`,t),this.uploadErrors=[{fileName:e.fileName||``,error:`Failed to remove document. Please try again.`}],this.getSessionId()&&this.reloadCurrentSession(),this.renderDocumentBar()}})},formatFileSize(e){return e<1024?e+` B`:e<1048576?(e/1024).toFixed(1)+` KB`:(e/1048576).toFixed(1)+` MB`},renderDocumentBar(){if(this.documentBar){if(!u.sessionDocumentsEnabled)this.documentBar.classList.add(`d-none`);else{this.documentBar.classList.remove(`d-none`);var e=`<div class="ai-chat-doc-bar p-2">`;e+=`<div class="d-flex flex-wrap align-items-center gap-1">`;for(var t=0;t<this.documents.length;t++){var n=this.documents[t],r=n.fileName||`Document`;r.length>20&&(r=r.substring(0,17)+`...`),e+=`<span class="badge bg-secondary bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="`+this.escapeHtml(n.fileName||``)+`">`,e+=`<i class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></i> `,e+=this.escapeHtml(r),e+=` <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-doc-index="`+t+`" aria-label="Remove"`+(this.isDocumentOperationPending?` disabled`:``)+`></button>`,e+=`</span>`}for(var i=0;i<this.uploadErrors.length;i++){var a=this.uploadErrors[i],o=a.error||`Upload failed`;e+=`<span class="alert alert-danger d-flex align-items-start gap-2 w-100 mb-1 py-1 px-2" role="alert" style="font-size: 0.8rem;">`,e+=`<i class="fa-solid fa-circle-exclamation mt-1" style="font-size: 0.7rem;"></i>`,e+=`<span class="flex-grow-1">`,a.fileName&&(e+=`<strong>`+this.escapeHtml(a.fileName)+`</strong>: `),e+=this.escapeHtml(o),e+=`</span>`,e+=`<button type="button" class="btn-close btn-close-sm" style="font-size: 0.5rem;" data-error-index="`+i+`" aria-label="Dismiss"></button>`,e+=`</span>`}this.isUploading&&(e+=`<span class="badge bg-info bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;">`,e+=`<span class="spinner-border spinner-border-sm" style="width: 0.7rem; height: 0.7rem;"></span> Uploading...`,e+=`</span>`),e+=`<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill ai-chat-doc-add-btn d-inline-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 0.15rem 0.5rem;" title="Attach documents"`+(this.isDocumentOperationPending?` disabled`:``)+`>`,e+=`<i class="fa-solid fa-paperclip"></i>`,this.documents.length===0&&!this.isUploading&&(e+=` <span>Attach files</span>`),e+=`</button>`,e+=`</div>`,u.supportedExtensionsText&&(e+=`<div class="small text-muted mt-2">Supported formats: `+this.escapeHtml(u.supportedExtensionsText)+`</div>`),e+=`</div>`,this.documentBar.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}));for(var s=this,c=this.documentBar.querySelectorAll(`[data-doc-index]`),l=0;l<c.length;l++)c[l].addEventListener(`click`,(function(e){return function(t){if(t.preventDefault(),t.stopPropagation(),!s.isDocumentOperationPending){var n=s.documents[e];n&&s.removeDocument(n)}}})(parseInt(c[l].getAttribute(`data-doc-index`))));for(var d=this.documentBar.querySelectorAll(`[data-error-index]`),f=0;f<d.length;f++)d[f].addEventListener(`click`,(function(e){return function(t){t.preventDefault(),t.stopPropagation(),s.uploadErrors.splice(e,1),s.renderDocumentBar()}})(parseInt(d[f].getAttribute(`data-error-index`))));var p=this.documentBar.querySelector(`.ai-chat-doc-add-btn`);p&&p.addEventListener(`click`,function(e){e.preventDefault(),!s.isDocumentOperationPending&&s.triggerFileInput()})}}},escapeHtml(e){var t=document.createElement(`div`);return t.textContent=e,t.innerHTML},extractReadableErrorMessage(e,t){if(!e||typeof e!=`string`)return t;var n=e.trim();if(!n)return t;if(n.startsWith(`{`)||n.startsWith(`[`))try{var r=JSON.parse(n),i=r?.error||r?.message||r?.title||r?.detail;return typeof i==`string`&&i.trim()?i.trim():t}catch{return t}return/<[^>]+>/.test(n)?t:n},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(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.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.getAssistantAvatarUrl(e)?[this.shouldAnimateAssistantIcon(e,t)?`ai-streaming-avatar`:`ai-bot-avatar`]:[this.shouldAnimateAssistantIcon(e,t)?`ai-streaming-icon`:`ai-bot-icon`,n&&n.cssClass?n.cssClass:``]},getAssistantAvatarUrl(e){return!this.assistantAvatarUrl||e&&this.normalizeAssistantAppearance(e.appearance)?null:this.assistantAvatarUrl},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)},async startConnection(){this.connection=new signalR.HubConnectionBuilder().withUrl(u.signalRHubUrl).withAutomaticReconnect().build(),this.connection.serverTimeoutInMilliseconds=6e5,this.connection.keepAliveIntervalInMilliseconds=15e3,this.connection.on(`LoadSession`,e=>{this.stream&&e&&e.sessionId===this.getSessionId()||(this.forceStopActiveVoice(),this.initializeSession(e.sessionId,!0),this.messages=[],this.documents=e.documents||[],this.uploadErrors=[],(e.messages??[]).forEach(e=>{this.addMessage(e),this.$nextTick(()=>{z(e)})}),this.$nextTick(()=>{this.refreshAllFeedbackIcons()}),this.messages.length===0&&u.initialPrompt&&this.addMessage({role:`assistant`,content:u.initialPrompt}),this.continueRunOnThisPage(e))}),this.connection.on(`ReceiveError`,e=>{console.error(`SignalR Error: `,e),this.isRecording&&this.stopRecording(),this.rejectPendingSessionRequest(e),this.hideTypingIndicator(),f&&typeof f.handleReceiveError==`function`?f.handleReceiveError(this,e,u):this.isNavigatingAway||this.addMessage(this.getErrorMessage(e))}),this.connection.on(`ReceiveSessionStartRejected`,e=>{this.rejectPendingSessionRequest(e),this.hideTypingIndicator(),this.isNavigatingAway||this.addMessage(this.getErrorMessage(e))}),this.connection.on(`MessageRated`,(e,t)=>{var n=this.messages.find(t=>t.id===e);n&&(n.userRating=t)}),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,`&`).replace(/</g,`<`).replace(/>/g,`>`)+`</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(e&&this.getSessionId()!==e&&this.initializeSession(e),t&&this._realtimePendingTurns&&this._realtimePendingTurns[t]){var r=this._realtimePendingTurns[t];delete this._realtimePendingTurns[t],this.stopAudio(),this.fillRealtimePendingTurn(r,n)}else if(n){if(this.stopAudio(),this._conversationPartialMessage){var i=n.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`);this._conversationPartialMessage.content=n,this._conversationPartialMessage.htmlContent=`<p>`+i+`</p>`,this._conversationPartialMessage.isPartial=!1,this._conversationPartialMessage=null}else if(this._conversationAssistantMessage){var a=this._conversationAssistantMessage.index,o={role:`user`,content:n,rawContent:n,userRating:null,references:{}};v(o,o.references),this.messages.splice(a,0,o),this._conversationAssistantMessage.index=a+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,userRating:null,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||{})),v(d,d.references),this.$nextTick(()=>{z(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||{})),v(r,r.references)),this._conversationAssistantMessage=null,this._conversationAssistantResponseId=null}}),this.connection.on(`ReceiveAudioChunk`,(e,t,n)=>{if(!t)return;let r=atob(t),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);n===`audio/pcm`?this.realtimeController&&this.realtimeController.receivePcm(i):this.audioChunks.push(i)}),this.connection.on(`ReceiveAudioComplete`,()=>{this.playCollectedAudio()}),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.realtimeEnabled&&this.isConversationMode&&this.stopRealtimeConversation()}),this.connection.onreconnected(()=>{console.info(`SignalR: reconnected.`),this.isSessionStarted&&this.reloadCurrentSession()}),this.connection.onclose(e=>{this.isNavigatingAway||(this.realtimeEnabled&&this.isConversationMode&&this.stopRealtimeConversation(),e&&console.warn(`SignalR connection closed with error:`,e.message||e))});try{await this.connection.start()}catch(e){console.error(`SignalR Connection Error: `,e)}this.ensurePageTools()},ensurePageTools(){return!this.pageTools&&this.connection&&window.crestAppsWebMcp&&typeof window.crestAppsWebMcp.connectChat==`function`&&(this.pageTools=window.crestAppsWebMcp.connectChat(this.connection)),this.pageTools},async syncPageTools(){var e=this.ensurePageTools();if(e)try{await e.sync()}catch(e){console.warn(`The page tools could not be sent to the chat.`,e)}},async ensureConnectionStarted(){if(!this.connection)return!1;var e=signalR.HubConnectionState;if(this.connection.state===e.Connected)return!0;if(this.connection.state===e.Disconnected){try{await this.connection.start()}catch(e){console.error(`SignalR Connection Error: `,e)}return this.connection.state===e.Connected}return await new Promise(t=>{var n=e=>{clearTimeout(r),clearInterval(i),t(e)},r=setTimeout(()=>n(this.connection.state===e.Connected),1e4),i=setInterval(()=>{this.connection.state===e.Connected?n(!0):this.connection.state===e.Disconnected&&n(!1)},100)})},addMessageInternal(e){e.role===`assistant`&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=H(e.content,e)),this.fireEvent(new CustomEvent(`addingCoreAIPromotMessage`,{detail:{message:e}})),this.messages.push(e),this.$nextTick(()=>{this.fireEvent(new CustomEvent(`addedCoreAIPromotMessage`,{detail:{message:e}}))})},addMessage(e){e.userRating===void 0&&(e.userRating=null),e.role===`assistant`&&e.toolCalls&&(e.toolCalls=C(e.toolCalls)),(e.content||e.toolCalls&&e.toolCalls.length)&&(e.rawContent=e.rawContent??e.content??``,v(e,e.references)),this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(()=>{z(e),this.scrollToBottom()})},addMessages(e){for(let t=0;t<e.length;t++)this.addMessageInternal(e[t]);this.hidePlaceholder(),this.$nextTick(()=>{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},isOrchestratorAvailable(){return u.isOrchestratorAvailable!==!1},applyOrchestratorAvailability(){if(this.isOrchestratorAvailable())return!0;let e=u.orchestratorUnavailableMessage||`This orchestrator is not currently available.`;return this.inputElement&&(this.inputElement.disabled=!0,this.inputElement.value=``,this.inputElement.placeholder=e),this.buttonElement&&(this.buttonElement.disabled=!0),this.micButtonElement&&(this.micButtonElement.disabled=!0,this.micButtonElement.style.display=`none`),this.conversationButtonElement&&(this.conversationButtonElement.disabled=!0,this.conversationButtonElement.style.display=`none`),!1},fireEvent(e){document.dispatchEvent(e)},isIndicator(e){return e.role===`indicator`},sendMessage(){if(!this.applyOrchestratorAvailability())return;let e=this.prompt.trim();e&&(this.forceStopActiveVoice(),this.isRecording&&this.stopRecording(),this._audioInputSent=!0,this.singleResponseMode&&this.messages.splice(0,this.messages.length),this.addMessage({role:`user`,content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value=``,this.prompt=``)},startRecording(){!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(e=>{this.preRecordingPrompt=this.prompt,this._audioInputSent=!1;var t=new signalR.Subject,n=this.getProfileId(),r=this.getSessionId()||``;this._sttCapture=this._createPcmCapture(e,e=>{try{t.next(e)}catch{}}),this._sttSubject=t;var i=this._sttCapture&&this._sttCapture.sampleRate||16e3,a=navigator.language||document.documentElement.lang||`en-US`;this.connection.send(`SendAudioStream`,n,r,t,`audio/pcm;rate=`+i,a),this.isRecording=!0,this.updateMicButton()}).catch(e=>{console.error(`Microphone access denied:`,e)})},stopRecording(){if(this.isRecording){if(this._stopPcmCapture(this._sttCapture),this._sttCapture=null,this._sttSubject){try{this._sttSubject.complete()}catch{}this._sttSubject=null}this.isRecording=!1,this.updateMicButton()}},_createPcmCapture(e,t){var n=window.AudioContext||window.webkitAudioContext,r;try{r=new n({sampleRate:16e3})}catch{r=new n}var i=r.sampleRate,a=r.createMediaStreamSource(e),o=r.createScriptProcessor(4096,1,1),s=this;return o.onaudioprocess=function(e){var n=e.inputBuffer.getChannelData(0),r=s._downsampleToInt16(n,i,16e3);if(r&&r.length!==0){for(var a=0,o=0;o<r.length;o++){var c=r[o]/32768;a+=c*c}for(var l=Math.sqrt(a/r.length),u=new Uint8Array(r.buffer),d=``,f=0;f<u.length;f++)d+=String.fromCharCode(u[f]);t(btoa(d),l)}},a.connect(o),o.connect(r.destination),{audioContext:r,source:a,processor:o,stream:e,sampleRate:16e3}},_stopPcmCapture(e){if(e){try{e.processor&&(e.processor.onaudioprocess=null,e.processor.disconnect())}catch{}try{e.source&&e.source.disconnect()}catch{}try{e.stream&&e.stream.getTracks().forEach(function(e){e.stop()})}catch{}try{e.audioContext&&e.audioContext.close()}catch{}}},_downsampleToInt16(e,t,n){var r,i;if(!(n<t)){var a=new Int16Array(e.length);for(i=0;i<e.length;i++)r=Math.max(-1,Math.min(1,e[i])),a[i]=r<0?r*32768:r*32767;return a}for(var o=t/n,s=Math.floor(e.length/o),c=new Int16Array(s),l=0;l<s;l++){var u=l*o,d=Math.floor(u),f=d+1<e.length?d+1:e.length-1,p=u-d;r=e[d]*(1-p)+e[f]*p,r=Math.max(-1,Math.min(1,r)),c[l]=r<0?r*32768:r*32767}return c},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>`))},streamMessage(e,t,n){if((u.protocol||`agui`)===`agui`&&!this.aguiDisabled)this.streamAGUIRun(e,t,n,null);else{this.stream&&=(this.stream.dispose(),null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var r=``,i={},a=null,s=this.messages.length,c=this.getSessionId(),l=()=>{this.stream=this.connection.stream(`SendMessage`,e,t,c,n).subscribe({next:e=>{let t=this.messages[s];if(!t){e.sessionId&&!c&&this.initializeSession(e.sessionId),this.hideTypingIndicator(),s=this.messages.length;let n={id:e.messageId,role:`assistant`,title:e.title,content:``,htmlContent:``,isStreaming:!0,userRating:null};this.messages.push(n),t=n}if(e.title&&(!t.title||t.title!==e.title)&&(t.title=e.title),e.references&&typeof e.references==`object`&&Object.keys(e.references).length)for(let[t,n]of Object.entries(e.references))i[t]=o(n)??{};e.content&&(e.responseId&&a&&e.responseId!==a&&(r+=`
|
|
77
77
|
|
|
78
78
|
`),e.responseId&&(a=e.responseId),r+=e.content),t.rawContent=r,v(t,i),this.messages[s]=t,this.$nextTick(()=>{z(t),this.scrollToBottom()})},complete:()=>{this.processReferences(i,s),this.streamingFinished();let e=this.messages[s];e&&(e.isStreaming=!1),(!e||!e.content)&&this.hideTypingIndicator(),this.isConversationMode&&this.textToSpeechEnabled&&e&&e.content&&this.synthesizeSpeech(e.content),this.stream?.dispose(),this.stream=null},error:e=>{this.processReferences(i,s),this.streamingFinished();let t=this.messages[s];t&&(t.isStreaming=!1),this.hideTypingIndicator(),this.isNavigatingAway||this.addMessage(this.getServiceDownMessage()),this.stream?.dispose(),this.stream=null,console.error(`Stream error:`,e)}})};this.syncPageTools().then(l,l)}},collectRunContext(){let e=[];if(u.sendPageContext===!1)return e;try{e.push({description:u.aguiCurrentPageLabel,value:(document.title?document.title+` `:``)+`(`+window.location.pathname+window.location.search+`)`});let t=this.lastPageSelection;t&&t.text&&Date.now()-t.at<3e5&&e.push({description:u.aguiSelectedTextLabel,value:t.text.slice(0,1e3)})}catch(e){console.warn(`The page context could not be read.`,e)}for(let t of y._contextProviders)try{let n=[].concat(t()||[]);for(let t of n)t&&t.value&&e.push({description:String(t.description||`Detail`),value:typeof t.value==`string`?t.value:JSON.stringify(t.value)})}catch(e){console.warn(`An AG-UI context provider failed.`,e)}return e.slice(0,20)},trackPageSelection(){try{let e=window.getSelection?window.getSelection():null,t=e?String(e).trim():``;if(!t||this.chatContainer&&e.anchorNode&&this.chatContainer.contains(e.anchorNode))return;this.lastPageSelection={text:t,at:Date.now()}}catch{}},getSharedState(){let e=y._stateProvider;if(e&&typeof e.get==`function`)try{let t=e.get();if(t&&typeof t==`object`&&!Array.isArray(t))return this.sharedStateCache=O(t),t}catch(e){console.warn(`The AG-UI state provider failed.`,e)}},applySharedState(e){let t=e.type===`STATE_DELTA`?e.delta||[]:null,n=t?re(this.sharedStateCache??{},t):O(e.snapshot??{});this.sharedStateCache=n;let r=y._stateProvider;if(r&&typeof r.apply==`function`)try{r.apply(O(n),t)}catch(e){console.warn(`The AG-UI state provider could not apply the state.`,e)}document.dispatchEvent(new CustomEvent(`crestapps:agui-state`,{detail:{type:e.type,state:O(n),delta:t}}))},ensureAGUIMessage(e,t){return e.message||=(this.hideTypingIndicator(),this.messages.push({id:t||e.assistantMessageId||k(),role:`assistant`,title:e.title,content:``,htmlContent:``,isStreaming:!0,userRating:null,toolCalls:[],reasoning:``,appearance:e.appearance}),e.messageIndex=this.messages.length-1,this.messages[e.messageIndex]),e.message},refreshAGUIMessage(e){let t=e.message;t&&(t.rawContent=e.content,v(t,e.references),this.messages[e.messageIndex]=t,this.$nextTick(()=>{z(t),this.scrollToBottom()}))},handleAGUIEvent(e,t){if(t&&typeof t.type==`string`)switch(t.type){case`RUN_STARTED`:t.threadId&&t.threadId!==e.threadId&&t.threadId!==this.getSessionId()&&this.initializeSession(t.threadId,!0);break;case`CUSTOM`:this.handleAGUICustomEvent(e,t.name,t.value||{});break;case`TEXT_MESSAGE_START`:this.ensureAGUIMessage(e,t.messageId),e.textMessageId&&e.textMessageId!==t.messageId&&e.content&&(e.content+=`
|
|
79
79
|
|