bstp-agent-widget 0.2.123 → 0.2.124

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/element.cjs CHANGED
@@ -399,7 +399,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
399
399
  `+t+`]`}return r.pop(),i=t,c}}}}))}));function tH(e){let t=e.indexOf(`{`),n=e.indexOf(`[`);return t===-1?n:n===-1?t:Math.min(t,n)}function nH(e){return e===`{`||e===`[`}function rH(e){return e===`}`||e===`]`}function iH(e){return e===`}`?`{`:`[`}function aH(e,t){let n=[],r=!1,i=!1;for(let a=t;a<e.length;a++){let t=e[a]??``;if(r){if(i){i=!1;continue}if(t===`\\`){i=!0;continue}if(t===`"`){r=!1;continue}continue}if(!(t===`"`&&e[a-1]===`\\`)){if(t===`"`){r=!0;continue}if(nH(t)){n.push(t);continue}if(rH(t)&&(n[n.length-1]===iH(t)&&n.pop(),n.length===0))return{end:a+1,openStack:[],inString:!1}}}return{end:null,openStack:n,inString:r}}function oH(e){let t=tH(e);if(t<0)return e;let{end:n,openStack:r,inString:i}=aH(e,t);if(n!==null)return e;let a=``;return i&&(a+=`"`),r.length>0&&(a+=r.reverse().map(e=>e===`{`?`}`:`]`).join(``)),a?`${e}${a}`:e}function sH(e,t){return aH(e,t).end}var cH=l(eH());function lH(e){try{return JSON.parse(e)}catch{return null}}function uH(e){return lH(e)??(()=>{try{return cH.default.parse(e)}catch{return null}})()}function dH(e){return e.replace(/\\r\\n/g,`
400
400
  `).replace(/\\n/g,`
401
401
  `).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\//g,`/`).replace(/\\\\/g,`\\`)}function fH(e){return e&&e.replace(/([{\s,])([A-Za-z0-9_@$-]+)\s*:/g,(e,t,n)=>`${t}"${n}":`)}function pH(e){let t=e.trim();t=t.replace(/[""]/g,`"`).replace(/['']/g,`'`),t=t.replace(/,\s*([}\]])/g,`$1`);try{t=fH(t)}catch{}return t=oH(t),uH(t)}function mH(e){if(!e||typeof e!=`string`)return null;let t=lH(e);if(t!=null)return t;try{let t=cH.default.parse(e);if(t!=null)return t}catch{}if(e.includes(`\\"`)||e.includes(`\\n`)||e.includes(`\\r`)||e.includes(`\\\\`)){let t=uH(dH(e));if(t!=null)return t}try{return pH(e)}catch{return null}}function hH(e){let t=tH(e);if(t<0)return null;let n=sH(e,t);if(n!==null)return{start:t,json:e.slice(t,n).trim(),consumed:n-t};let r=e.slice(t),i=r.search(/\r?\n\r?\n/);return i>20&&(r=r.slice(0,i).trimEnd()),{start:t,json:oH(r).trim(),consumed:r.length}}var gH=`"structuredData":`,_H=`\\"structuredData\\":`;function vH(e){let t=e.indexOf(gH);if(t<0&&(t=e.indexOf(_H)),t<0)return null;let n=t+17,r=e.indexOf(`{`,n);if(r<0||r>n+10)return null;let i=sH(e,r),a,o;i===null?(a=e.slice(t,r).trim()+oH(e.slice(r)).trim(),o=e.length-t):(a=e.slice(t,i).trim(),o=i-t),t===e.indexOf(_H)&&(a=a.replace(/\\"/g,`"`));let s=`{`+a+`}`;return{start:t,fullJson:s,consumed:o}}function yH(e){let t=e.trim();if(!t||t.length<10)return!1;let n=tH(t);return n>=0&&sH(t,n)===null&&t.length-n>10}function bH(e){let t=/^\s*(?:\r?\n)?\s*(?:'{3}|"{3}|`{3})(?:\s*json\s*)?(?:'{3}|"{3}|`{3})?\s*(?:\r?\n)?/i.exec(e);return!t||!/'{3}|"{3}|`{3}/i.test(t[0])?0:t[0].length}function xH(e){return/^\s*(?:[\]}]+\s*)+/.exec(e)?.[0].length??0}function SH(e){return e&&typeof e==`object`?e:null}function CH(e){return Array.isArray(e)?e:[]}function wH(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=Number(e);return Number.isFinite(t)?t:null}return null}function TH(e,t,n){let r=wH(e.used)??wH(e.currentValueRaw)??0,i=wH(e.allowance),a=wH(e.remaining),o=i??wH(e.total)??(r!=null&&a!=null?r+a:null)??wH(e.valueRaw)??(r>0?r:0),s=typeof e.unit==`string`?e.unit:``,c=typeof e.name==`string`?e.name:t.toUpperCase();if(o<=0)return null;let l=n?wH(e.percentUsed)??void 0:void 0,u={key:t,label:c,used:r,total:o,unit:s};return l!=null&&(u.percentUsed=l),u}function EH(e){let t=[],n=CH(e?.responseList);for(let e of n){let n=TH(e,typeof e.type==`string`?e.type:`usage`,!0);n&&t.push(n)}return t.length>0?t:null}function DH(e){let t=e.items;if(Array.isArray(t)&&t.length>0){let e=SH(t[0]);if(e)return e}return e}function OH(e){let t=SH(e),n=SH(SH(t?.structuredData)?.data??t?.data);if(!n)return null;let r=EH(n);if(r)return r;let i=CH(n?.usageTypes);if(i.length===0)return null;let a=[];for(let e of i){let t=typeof e.type==`string`?e.type:`usage`,n=DH(e);if(!n)continue;let r=TH(n,t);r&&a.push(r)}return a.length>0?a:null}function kH(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function AH(e){if(!e||typeof e!=`object`)return null;let t=e,n=kH(t.buttonText);if(!n)return null;let r=kH(t.targetAgent)??void 0;return{buttonText:n,agentMessage:kH(t.agentMessage)??r??n,...r?{targetAgent:r}:{}}}function jH(e){if(!e||typeof e!=`object`)return null;let t=e;if(!Array.isArray(t.actions))return null;let n=t.actions.map(AH).filter(e=>e!==null);return n.length===0?null:{actions:n}}function MH(e){return e&&typeof e==`object`?e:null}function NH(e){if(typeof e!=`string`)return null;switch(e){case`card`:case`link`:case`chart`:case`highlightBox`:return e;default:return null}}function PH(e){let t=MH(e);if(!t)return null;let n=MH(t.structuredData),r=[MH(n?.visualization)?.type,MH(n?.visualizationConfig)?.visualizationType,n?.visualizationType,MH(t.visualization)?.type,MH(t.visualizationConfig)?.visualizationType,t.visualizationType];for(let e of r)if(typeof e==`string`)return NH(e)??e;return null}function FH(e){if(typeof e!=`string`)return null;let t=e.trim();switch(t){case`accountOverview`:case`customerProfile`:case`offerRecommendation`:case`basket`:case`usageAnalysis`:case`twinInsight`:return t;default:return`unknown`}}function IH(e){let t=MH(e);if(!t)return null;let n=MH(t.structuredData),r=n?.data??t.data,i=MH(n?.visualization),a=MH(t.visualization);return{data:r,visualizationConfig:i?.config??a?.config??t.visualizationConfig,responseType:FH(n?.responseType??t.responseType)}}function LH(e){let t=MH(e);return!t||MH(t.structuredData)?e:typeof t.responseType==`string`||MH(t.visualization)||MH(t.visualizationConfig)||typeof t.visualizationType==`string`||t.data!==void 0?{structuredData:t}:e}function RH(e){let t=MH(e);return t?MH(t.structuredData)||MH(t.visualization)||MH(t.visualizationConfig)||Array.isArray(t.actions)?!0:typeof t.visualizationType==`string`||typeof t.responseType==`string`:!1}var zH=new hE(`widget-config-builder`);function BH(e){let t=jH(e);if(t)return{type:`widget`,config:{type:`actions`,actions:t.actions}};let n=PH(e),r=IH(e),i={visualizationConfig:r?.visualizationConfig,responseType:r?.responseType??void 0};if(!n){let t=r?.data??e;return NV(t)?{type:`widget`,config:{type:`card`,data:t,...i}}:null}if(n===`chart`){let t=e?OH(e):null;return!t||t.length===0?null:{type:`widget`,config:{type:n,items:t,...i}}}if(n===`card`||n===`link`||n===`highlightBox`){let e=r?.data;if(!NV(e))return null;let t=n;if(n===`card`){let e=r?.responseType;e===`accountOverview`?t=`account-overview`:e===`offerRecommendation`&&(t=`offer-card`)}let a={type:t,data:e,...i};return zH.debug(`Creating widget`,{visualizationType:n,responseType:r?.responseType,widgetType:t,config:a}),{type:`widget`,config:a}}return{type:`widget`,config:{type:n}}}var VH=new hE(`useAgentMarkdownRendererElements`),HH={async:!1,breaks:!0,gfm:!0};function UH(e){return kF.parse(e,HH)}function WH(e,t,n){let r=UH(t);return r.trim()?(e.push({type:`markdown`,key:`md-${n}`,content:r}),n+1):n}function GH(e){return["```json",JSON.stringify(e,null,2),"```"].join(`
402
- `)}function KH(e){let t=e.trim();return!t||!/^[{\[]/.test(t)?null:mH(t)}function qH(e,t){return(0,H.useMemo)(()=>{let n=$V(e),r=KH(n);if(r)return[{type:`markdown`,key:`json-0`,content:UH(GH(r))}];let i=WV(n),a=[],o=0;for(let e of i){if(e.type===`markdown`){o=WH(a,e.content,o);continue}try{let n=GV(e.dsl);if(!n){let t=KH(e.dsl);o=WH(a,t?GH(t):e.raw,o);continue}let r=jV(n,t);if(r.kind===`widget`){a.push({type:`widget`,key:`widget-${o++}`,widget:r.widget});continue}o=WH(a,GH(r.payload),o)}catch(t){VH.error(`Failed to parse widget`,{error:t instanceof Error?t.message:String(t)}),o=WH(a,e.raw,o)}}return a},[e,t])}var JH={agentChatMdRenderer:`_agentChatMdRenderer_5jigp_1`},YH=(0,H.memo)(({content:e,onWidgetEvent:t})=>{let n=qH(e,t);return(0,U.jsx)(q,{className:JH.agentChatMdRenderer,children:n.map(e=>e.type===`markdown`?(0,U.jsx)(XN,{html:e.content},e.key):(0,U.jsx)(q,{children:e.widget},e.key))})});YH.displayName=`AgentMarkdownRenderer`;var XH={body:`_body_1vtnd_1`,messageBubble:`_messageBubble_1vtnd_21`,messageBubbleUser:`_messageBubbleUser_1vtnd_33`,userText:`_userText_1vtnd_54`,messageBubbleAssistant:`_messageBubbleAssistant_1vtnd_62`,messageList:`_messageList_1vtnd_84`};function ZH({messages:e,isLoading:t,error:n,scrollViewportRef:r,onWidgetEvent:i}){return(0,U.jsx)(By,{className:XH.body,gap:0,children:(0,U.jsx)(ol,{h:`100%`,type:`always`,scrollbarSize:8,offsetScrollbars:!0,viewportRef:r,children:(0,U.jsxs)(By,{className:XH.messageList,gap:0,children:[n&&(0,U.jsx)(Wf,{color:`red`,variant:`light`,radius:`md`,children:n}),e.map(e=>(0,U.jsx)(q,{className:`${XH.messageBubble} ${e.sentBy===`user`?XH.messageBubbleUser:XH.messageBubbleAssistant}`,children:e.sentBy===`assistant`?(0,U.jsx)(YH,{content:e.text,onWidgetEvent:i}):(0,U.jsx)(Yf,{className:XH.userText,children:e.text})},e.id)),t&&(0,U.jsx)(q,{className:`${XH.messageBubble} ${XH.messageBubbleAssistant}`,children:(0,U.jsx)(HM,{messages:[`Thinking`,`Analyzing your request`,`Searching for information`,`Processing data`,`Preparing response`,`Almost there`]})})]})})})}var QH={root:`_root_h7hgt_1`,input:`_input_h7hgt_6`,section:`_section_h7hgt_34`};function $H({composerText:e,onComposerTextChange:t,isLoading:n,isListening:r,onSubmit:i,rightSection:a,rightSectionWidth:o}){return(0,U.jsx)(Rb,{placeholder:r?`Listening...`:`Ask me anything...`,value:e,onChange:e=>t(e.currentTarget.value),disabled:n,radius:`md`,size:`md`,rightSection:a,rightSectionWidth:o,rightSectionPointerEvents:`all`,classNames:{root:QH.root,input:QH.input,section:QH.section},styles:{input:{minHeight:`100%`}},onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),i())}})}function eU({size:e,...t}){return(0,U.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,...GF(e),...t,children:[(0,U.jsx)(`path`,{d:`M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z`}),(0,U.jsx)(`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2`}),(0,U.jsx)(`line`,{x1:`12`,x2:`12`,y1:`19`,y2:`22`})]})}function tU({size:e,...t}){return(0,U.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,...GF(e),...t,children:(0,U.jsx)(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`})})}function nU({isListening:e,isLoading:t,onToggleVoice:n,size:r}){let i=Vj();return(0,U.jsx)(uy,{label:e?`Stop recording`:`Voice input`,children:(0,U.jsx)(hu,{onClick:n,disabled:t,size:r??`lg`,radius:`md`,variant:e?`filled`:`subtle`,color:e?`red`:`accent`,"aria-label":e?`Stop voice recording`:`Start voice recording`,styles:{root:e?void 0:{color:i.other.color[`secondary-default`],backgroundColor:`transparent`,boxShadow:`inset 0 0 0 1px ${i.other.color[`secondary-light`]}33`}},children:e?(0,U.jsx)(tU,{size:`sm`}):(0,U.jsx)(eU,{size:`sm`})})})}function rU({size:e,...t}){return(0,U.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,...GF(e),...t,children:[(0,U.jsx)(`path`,{d:`m22 2-7 20-4-9-9-4Z`}),(0,U.jsx)(`path`,{d:`M22 2 11 13`})]})}var iU={footer:`_footer_zlzuq_1`,actionGroup:`_actionGroup_zlzuq_8`,poweredBy:`_poweredBy_zlzuq_12`,sendButton:`_sendButton_zlzuq_18`};function aU({composerText:e,onComposerTextChange:t,isLoading:n,isListening:r,isVoiceSupported:i,canSend:a,onSubmit:o,onToggleVoice:s}){let c=i?74:40;return(0,U.jsxs)(By,{className:iU.footer,gap:`sm`,children:[(0,U.jsx)($H,{composerText:e,onComposerTextChange:t,isLoading:n,isListening:r,onSubmit:o,rightSectionWidth:c,rightSection:(0,U.jsxs)(Tu,{className:iU.actionGroup,wrap:`nowrap`,gap:4,align:`center`,children:[i&&(0,U.jsx)(nU,{isListening:r,isLoading:n,onToggleVoice:s,size:30}),(0,U.jsx)(hu,{onClick:o,disabled:!a||n,size:30,radius:`md`,variant:`filled`,color:`accent`,className:iU.sendButton,"aria-label":`Send message`,children:(0,U.jsx)(rU,{size:`sm`})})]})}),(0,U.jsx)(Yf,{ta:`center`,size:`xs`,c:`dimmed`,className:iU.poweredBy,pt:2,children:`Powered by Exceeder · Etiya`})]})}function oU({size:e,...t}){return(0,U.jsxs)(`svg`,{viewBox:`0 0 22 22`,fill:`none`,...GF(e),...t,children:[(0,U.jsx)(`rect`,{x:`4`,y:`4`,width:`14`,height:`2.5`,rx:`1.2`,fill:`currentColor`}),(0,U.jsx)(`rect`,{x:`4`,y:`9.75`,width:`10`,height:`2.5`,rx:`1.2`,fill:`currentColor`,opacity:`0.88`}),(0,U.jsx)(`rect`,{x:`4`,y:`15.5`,width:`14`,height:`2.5`,rx:`1.2`,fill:`currentColor`})]})}function sU({size:e,...t}){return(0,U.jsx)(`svg`,{viewBox:`0 0 15 15`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...GF(e),...t,children:(0,U.jsx)(`path`,{d:`M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})}var cU={header:`_header_5x292_19`,headerLeft:`_headerLeft_5x292_31`,headerInfo:`_headerInfo_5x292_36`,orbContainer:`_orbContainer_5x292_40`,orbOuter:`_orbOuter_5x292_54`,orbPulse:`_orbPulse_5x292_1`,orbMiddle:`_orbMiddle_5x292_63`,orbInner:`_orbInner_5x292_72`,orbFloat:`_orbFloat_5x292_1`,headerMeta:`_headerMeta_5x292_85`,statusDot:`_statusDot_5x292_89`,statusText:`_statusText_5x292_103`,closeButton:`_closeButton_5x292_112`,title:`_title_5x292_123`,topSubHeader:`_topSubHeader_5x292_135`,subHeaderLeft:`_subHeaderLeft_5x292_145`,subHeaderIcon:`_subHeaderIcon_5x292_151`,subHeaderTitle:`_subHeaderTitle_5x292_162`,subHeaderStatus:`_subHeaderStatus_5x292_168`};function lU({panelTitle:e,isLoading:t,isOnline:n,onClose:r}){let i=Vj();return(0,U.jsxs)(Tf,{className:cU.header,align:`center`,justify:`space-between`,children:[(0,U.jsxs)(Tu,{className:cU.headerLeft,wrap:`nowrap`,gap:`sm`,align:`center`,children:[(0,U.jsxs)(q,{className:cU.orbContainer,"data-loading":t||void 0,children:[(0,U.jsx)(q,{className:cU.orbOuter}),(0,U.jsx)(q,{className:cU.orbMiddle}),(0,U.jsx)(q,{className:cU.orbInner,children:(0,U.jsx)(oU,{size:`sm`,color:i.other.color[`text-white`]})})]}),(0,U.jsxs)(By,{className:cU.headerInfo,gap:2,justify:`center`,children:[(0,U.jsx)(Yf,{className:cU.title,fw:800,children:e}),(0,U.jsxs)(Tu,{className:cU.headerMeta,wrap:`nowrap`,gap:6,align:`center`,children:[(0,U.jsx)(q,{className:cU.statusDot,"data-loading":t||void 0,"data-online":n||void 0}),(0,U.jsx)(Yf,{className:cU.statusText,span:!0,children:t?`Typing…`:n?`Online`:`Offline`})]})]})]}),(0,U.jsx)(hu,{variant:`subtle`,size:`lg`,radius:`md`,onClick:r,className:cU.closeButton,"aria-label":`Close agent chat`,children:(0,U.jsx)(sU,{size:`sm`})})]})}var uU={root:`_root_nkl8r_1`,surface:`_surface_nkl8r_9`,resizeHandle:`_resizeHandle_nkl8r_22`};function dU({visible:e,onClose:t,messages:n,composerText:r,onComposerTextChange:i,isLoading:a,error:o,canSend:s,onSubmit:c,isListening:l,isVoiceSupported:u,onToggleVoice:d,actions:f,onActionClick:p,panelTitle:m,runtimeInfo:h,scrollViewportRef:g,actualWidth:_=420,floatingTop:v=`var(--mantine-custom-space-150)`,floatingHeight:y=`100%`,floatingMaxHeight:b=`calc(100vh - var(--mantine-custom-space-150) - var(--mantine-custom-space-150))`,shellGap:x=`var(--mantine-custom-space-150)`,panelHeaderHeight:S=56,panelResizableWidth:C,panelBorder:w,panelBorderRadius:T,zIndex:E}){let D=h.hasCustomerToken&&h.hasGenaiToken,O=e=>{if(e.type===`action-click`&&e.data){let t=f.find(t=>t.buttonText===e.data?.buttonText);t&&p(t)}};if(!e)return null;let k=typeof T==`number`?`${T}px`:T;return(0,U.jsxs)(q,{className:uU.root,style:{width:_,maxWidth:`calc(100vw - var(--mantine-custom-space-400) - var(--mantine-custom-space-400))`,height:y,maxHeight:b,top:v,right:x,zIndex:E,"--agent-widget-panel-header-height":`${S}px`,"--agent-widget-shell-gap":x,"--agent-widget-panel-border":w,"--agent-widget-panel-radius":k},children:[C&&(0,U.jsx)(q,{onPointerDown:C.handlePointerDown,className:uU.resizeHandle,style:C.style}),(0,U.jsxs)(q,{className:uU.surface,children:[(0,U.jsx)(lU,{panelTitle:m,isLoading:a,isOnline:D,onClose:t}),(0,U.jsx)(ZH,{messages:n,isLoading:a,error:o,scrollViewportRef:g,onWidgetEvent:O}),(0,U.jsx)(aU,{composerText:r,onComposerTextChange:i,isLoading:a,isListening:l,isVoiceSupported:u,canSend:s,onSubmit:c,onToggleVoice:d})]})]})}function fU(e){return(0,H.useMemo)(()=>{let t=e===`MULTI`?`MULTI`:`SINGLE`;return{agentType:t,isMultiAgent:t===`MULTI`}},[e])}function pU(e){return typeof e==`object`&&!!e}function mU(e){let t=Number(e);return Number.isFinite(t)&&t>0?t:null}function hU(e){if(Array.isArray(e))return e.filter(pU);if(!pU(e))return[];for(let t of[`data`,`items`,`results`,`content`,`rows`,`list`,`response`]){let n=e[t];if(Array.isArray(n))return n.filter(pU);if(pU(n)){let e=hU(n);if(e.length>0)return e}}for(let t of Object.values(e))if(Array.isArray(t)){let e=t.filter(pU);if(e.length>0)return e}return[]}function gU(e){let t=mU(e.assistantId??e.assistant_id??e.id??e.agentId??e.agent_id??e.appId??e.app_id);if(!t)return null;let n=e.description??e.appDescription??e.app_description??e.label??e.name??e.assistantName??e.assistant_name??e.agentName??e.agent_name??e.title,r=typeof n==`string`&&n.trim().length>0?n.trim():`Agent ${t}`,i=e.assistantKey??e.assistant_key??e.key??e.agentKey??e.agent_key??e.code,a=typeof i==`string`&&i.trim().length>0?i.trim():r.toLowerCase().replace(/\s+/g,`-`),o=e.initialMessage??e.initial_message??e.welcomeMessage??e.welcome_message,s=typeof o==`string`&&o.trim().length>0?o.trim():void 0;return{assistantId:t,label:r,assistantKey:a,...s?{initialMessage:s}:{}}}function _U(e){let t=mU(e.appId??e.app_id??e.id??e.assistantId??e.assistant_id);if(!t)return null;let n=e.description??e.name??e.label??e.title??e.appName??e.app_name,r=typeof n==`string`&&n.trim().length>0?n.trim():`Agent ${t}`,i=e.assistantKey??e.assistant_key??e.key??e.code,a=typeof i==`string`&&i.trim().length>0?i.trim():r.toLowerCase().replace(/\s+/g,`-`),o=e.initialMessage??e.initial_message??e.welcomeMessage??e.welcome_message,s=typeof o==`string`&&o.trim().length>0?o.trim():void 0;return{assistantId:t,label:r,assistantKey:a,...s?{initialMessage:s}:{}}}function vU(e){if(Array.isArray(e.apps)&&e.apps.length>0){let t=e.apps.map(e=>_U(e)).filter(e=>e!==null);if(t.length>0)return t}let t=gU(e);return t?[t]:[]}function yU(e){return hU(e).flatMap(e=>vU(e))}var bU={runtimeInfo:{customerId:null,hasCustomerToken:!1,hasGenaiToken:!1}},xU=dE(e=>({...bU,setRuntimeInfo:t=>e({runtimeInfo:t}),updateCustomerId:t=>e(e=>({runtimeInfo:{...e.runtimeInfo,customerId:t}})),updateCustomerToken:t=>e(e=>({runtimeInfo:{...e.runtimeInfo,hasCustomerToken:t}})),updateGenaiToken:t=>e(e=>({runtimeInfo:{...e.runtimeInfo,hasGenaiToken:t}})),resetRuntimeInfo:()=>e({runtimeInfo:bU.runtimeInfo})}));async function SU(e,t){try{let n=new URLSearchParams;n.set(`username`,atob(e)),n.set(`password`,atob(t));let r=await TE.post(`/login`,n,{anonymous:!0,headers:{"Content-Type":`application/x-www-form-urlencoded`}});return r.data?.access_token&&(_T(r.data.access_token),xT(!1)),r.data}catch(e){throw e}}async function CU(e,t){try{let n=await TE.post(`/tenants/switch`,{tenant_id:e},{anonymous:!0,headers:{Authorization:`Bearer ${t}`}});return n.data?.data?.access_token&&_T(n.data.data.access_token),yT(n.data?.data?.tenant_id??e),xT(!0),n.data}catch(e){throw e}}async function wU(e){try{return(await TE.post(`/agent-message`,e,{anonymous:!0})).data}catch(e){throw e}}async function TU(e){try{return(await TE.post(`/agentic-app-chat`,e,{anonymous:!0})).data}catch(e){throw e}}async function EU(e){let{customerToken:t,tenantId:n,...r}=e;try{return(await TE.post(`/assistant`,r,{anonymous:!0,headers:{Authorization:`Bearer ${t}`,"x-tenant-id":String(n)}})).data}catch(e){throw e}}async function DU(e){let{customerToken:t,tenantId:n,...r}=e;try{return(await TE.post(`/fetch-agentic-app`,r,{anonymous:!0,headers:{Authorization:`Bearer ${t}`,"x-tenant-id":String(n)}})).data}catch(e){throw e}}var OU={loginToGenai:SU,switchTenant:CU,sendAgentMessage:wU,sendAgenticAppChat:TU,fetchAssistants:EU,fetchAgenticApps:DU};function kU({mutationKey:e,mutationFn:t,defaultOptions:n={}}){return function(r){return eS({...n,...r,meta:{...n?.meta,...r?.meta},mutationKey:e,mutationFn:t})}}var AU=kU({mutationKey:[`genai`,`agentic-apps`],mutationFn:async e=>OU.fetchAgenticApps(e)}),jU=kU({mutationKey:[`genai`,`assistants`],mutationFn:async e=>OU.fetchAssistants(e)});function MU(e,t){return e&&t.includes(e)?e:t[0]}function NU(e,t,n){let{mutateAsync:r}=jU(),{mutateAsync:i}=AU(),{isMultiAgent:a}=fU(e),[o,s]=(0,H.useState)(null),c=(0,H.useRef)(null),l=(0,H.useRef)(null),u=gT(),d=vT(),f=d?Number(d):null,p=bT();(0,H.useEffect)(()=>{if(!n){s(null);return}if(!u||!f||Number.isNaN(f)||f<=0||!p){s(null),c.current=null,l.current=null;return}let e=`${a?`multi`:`single`}:${f}:${u}`;if(c.current===e||l.current===e)return;l.current=e;let t=!0;return(async()=>{try{let n=a?await i({page:1,limit:10,customerToken:u,tenantId:f}):await r({page:1,limit:20,agent_type:`SINGLE`,customerToken:u,tenantId:f});if(!t)return;s(yU(n)),c.current=e}catch{t&&(s([]),c.current=null)}finally{l.current===e&&(l.current=null)}})(),()=>{t=!1}},[n,i,r,u,f,a,p]);let m=o??[],h=MU(t,m.map(e=>e.assistantId));return{availableAssistants:m,selectedAssistantId:h,selectedAssistant:m.find(e=>e.assistantId===h)}}function PU(){let e=(0,H.useContext)(OM),{agentType:t}=fU(e?.agentType),{selectedAssistantId:n,selectedAssistant:r}=NU(e?.agentType,e?.assistantId,!!e),i=(0,H.useMemo)(()=>e?{...e,assistantId:n,agentType:t,assistantLabel:r?.label,assistantInitialMessage:r?.initialMessage}:null,[e,t,r,n]);if(!i)throw Error(`AgentConfigContext is missing.`);return i}function FU(){let e=(0,H.useContext)(kM);if(!e)throw Error(`AgentRuntimeContext is missing.`);return e}function IU(){let e=FU();return(0,H.useMemo)(()=>{let t=e?.customerToken;return typeof t!=`string`||t.trim().length===0?null:t},[e?.customerToken])}var LU=kU({mutationKey:[`genai`,`agent-message`],mutationFn:async({payload:e})=>OU.sendAgentMessage(e)}),RU=kU({mutationKey:[`genai`,`agentic-app-chat`],mutationFn:async({payload:e})=>OU.sendAgenticAppChat(e)});function zU(){let e=LU(),t=RU();return{sendChatMessage:(0,H.useCallback)(async n=>{let{agentType:r,message:i,selectedAgentId:a,customerId:o,customerToken:s,chatId:c}=n;return r===`MULTI`?t.mutateAsync({payload:{message:i,app_id:a,...o?{unique_user_id:o}:{}}}):e.mutateAsync({payload:{message:i,chat_id:c,assistant_id:a,is_sync:!0,...o?{unique_user_id:o}:{},tool_headers:{_default:{Authorization:`Bearer ${s}`}}}})},[e,t])}}function BU(e){return e.assistantId??null}function VU(e){return BU(e)?e.assistantInitialMessage??null:null}function HU(e){return e.customerId}function UU(e){return e.customerToken}function WU(e){return e.language??null}function GU(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.message??(Array.isArray(t.messages)?t.messages[0]:null);if(!n||typeof n!=`object`)return null;let r=n.chat_id,i=typeof r==`number`&&Number.isFinite(r)?r:null,a=typeof n.message==`string`?n.message:``,o=typeof n.created_at==`string`?n.created_at:new Date().toISOString();return a?{chatId:i,text:a,createdAt:o}:null}function KU(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function qU(){let e=FU(),t=IU(),n=PU(),{agentType:r,isMultiAgent:i}=fU(n.agentType),{sendChatMessage:a}=zU(),[o,s]=(0,H.useState)([]),[c,l]=(0,H.useState)(``),[u,d]=(0,H.useState)(null),[f,p]=(0,H.useState)(!1),[m,h]=(0,H.useState)(null),g=(0,H.useRef)(!1),_=BU(n),v=i?n.assistantLabel??`Assistant`:`Assistant`,y=(0,H.useCallback)(e=>{let t={id:KU(),sentBy:`user`,text:e};s(e=>[...e,t])},[]),b=(0,H.useCallback)((e,t)=>{let n={id:KU(),sentBy:`assistant`,text:e,createdAt:t};s(e=>[...e,n])},[]),x=(0,H.useCallback)(async(o,s)=>{if(!o.trim())return;if(l(``),s?.showUserBubble!==!1&&y(o),!e||!n){h(`Chat is not configured.`);return}if(!_){h(`Chat configuration is missing.`);return}let c=HU(e),f=i?null:t;if(!i&&!f){h(`Missing customer token.`);return}p(!0),h(null);try{let e=GU(await a({agentType:r,message:o,selectedAgentId:_,customerId:c||void 0,customerToken:f??``,chatId:u}));if(!e)return;e.chatId!==null&&d(e.chatId),b(e.text,e.createdAt)}catch{h(`Something went wrong. Please try again.`)}finally{p(!1)}},[e,n,u,y,b,a,t,r,i]);return{messages:o,composerText:c,setComposerText:l,isLoading:f,error:m,sendMessage:x,sendInitialMessage:(0,H.useCallback)(async()=>{if(g.current||f||o.length>0||!e||!n||!BU(n))return!1;let t=HU(e),r=VU(n)?.trim(),i=null;return i=r?t?`${r} ${t}`.trim():r:t?`Hello, my customer id is ${t}`:`Hello`,i.trim()?(g.current=!0,await x(i,{showUserBubble:!1}),!0):!1},[e,n,f,o.length,x]),resetChat:(0,H.useCallback)(()=>{s([]),l(``),d(null),h(null),g.current=!1},[]),agentDisplayName:v,canSend:c.trim().length>0}}function JU(e,t){let n=(0,H.useRef)([]);return{actions:(0,H.useMemo)(()=>{let t=[...e].reverse().find(e=>e.sentBy===`assistant`);if(!t)return n.current;let r=ZV(t.text).find(e=>e.type===`widget`&&e.config.type===`actions`),i=r?.type===`widget`?r.config.actions??[]:[];return i.length>0&&(n.current=i),n.current},[e]),handleActionClick:(0,H.useCallback)(e=>{t(e.buttonText)},[t])}}function YU(e={}){let{axis:t=`y`,direction:n=1,onResizeChange:r}=e,[i,a]=(0,H.useState)(0),o=(0,H.useRef)({startPos:0,startOffset:0}),{startInteraction:s}=FM(),c=t===`y`?`ns-resize`:t===`x`?`ew-resize`:`nwse-resize`;return{offset:i,handlePointerDown:(0,H.useCallback)(e=>{e.preventDefault(),e.stopPropagation();let l=t===`y`?e.clientY:e.clientX,u=i;o.current={startPos:l,startOffset:u},s({cursor:c,onMove:e=>{let i;i=t===`y`?-(e.clientY-l):(e.clientX-l)*n;let o=u+i;a(o),r?.(o)}})},[i,t,n,c,r,s]),style:{cursor:c,touchAction:`none`}}}var XU=[`#root main`,`#root`,`main`,`.main-content`,`#app`,`body`];function ZU(e,t,n,r,i){let a=(0,H.useRef)(Math.max(280,t??420)),o=(0,H.useRef)(n??!1),s=(0,H.useRef)(null),c=e?.reserveLayoutSpace??!0,l=(0,H.useCallback)(()=>{let t=e?.hostContainerSelector,n=[...t?t.split(`,`).map(e=>e.trim()).filter(Boolean):[],...XU];for(let e of n){let t=document.querySelector(e);if(t)return t}return document.body},[e?.hostContainerSelector]),u=(0,H.useCallback)(e=>{let t=document.documentElement;if(!c){if(t.style.removeProperty(`--agent-widget-panel-width`),s.current){let{element:e,inlinePaddingBefore:t}=s.current;e.style.paddingRight=t,s.current=null}return}if(e===null?t.style.removeProperty(`--agent-widget-panel-width`):t.style.setProperty(`--agent-widget-panel-width`,`${e}px`),e===null){if(s.current){let{element:e,inlinePaddingBefore:t}=s.current;e.style.paddingRight=t,s.current=null}return}if(!s.current||!document.contains(s.current.element)){let e=l();if(!e)return;s.current={element:e,inlinePaddingBefore:e.style.paddingRight,widthApplied:0}}let{element:n,inlinePaddingBefore:r,widthApplied:i}=s.current;e!==i&&(n.style.paddingRight=r,n.style.paddingRight=`calc(${r||`0px`} + ${e}px)`,s.current.widthApplied=e)},[l,c]),d=YU({axis:`x`,direction:-1,onResizeChange:(0,H.useCallback)(e=>{let n=Math.max(280,(t??420)+e);a.current=n,u(n)},[t,u])});(0,H.useEffect)(()=>{o.current=n??!1},[n]),(0,H.useEffect)(()=>{let e=Math.max(280,t??420);a.current=e,o.current&&u(e)},[t,u]),(0,H.useEffect)(()=>{if(!n){u(null),document.documentElement.removeAttribute(`data-agent-widget-open`);return}return u(a.current),document.documentElement.setAttribute(`data-agent-widget-open`,`true`),()=>{u(null),document.documentElement.removeAttribute(`data-agent-widget-open`)}},[n,u]);let f=d?Math.max(280,(t??420)+d.offset):t??420,p=r===`100%`||r===`100vh`,m=typeof e?.panelGap==`number`?`${e.panelGap}px`:e?.panelGap??`var(--mantine-custom-space-150)`,h=i??0;return{panelResizableWidth:d,actualWidth:f,shellGap:m,floatingTop:h?`calc(${h}px + ${m})`:m,floatingHeight:p?`calc(100vh - ${h}px - ${m} - ${m})`:typeof r==`number`?`${r}px`:r??`100%`,floatingMaxHeight:`calc(100vh - ${h}px - ${m} - ${m})`}}function QU(){let e=FU(),{runtimeInfo:t,setRuntimeInfo:n}=xU(),r=(0,H.useCallback)(async()=>{if(!e){n({customerId:null,hasCustomerToken:!1,hasGenaiToken:!1});return}let t=HU(e),r=await UU(e),i=gT();n({customerId:t,hasCustomerToken:!!r,hasGenaiToken:!!i})},[e,n]);return(0,H.useEffect)(()=>{r()},[e,r]),{runtimeInfo:t,refreshRuntimeInfo:r}}function $U(){let e=FU();return(0,H.useMemo)(()=>e&&WU(e)||`en-US`,[e])}function eW(e={}){let{lang:t=`en-EN`,continuous:n=!0,interimResults:r=!0,onResult:i,onError:a,onTextChange:o,pauseOnSubmit:s=!1}=e,[c,l]=(0,H.useState)(!1),[u,d]=(0,H.useState)(``),[f,p]=(0,H.useState)(!1),m=(0,H.useRef)(null),h=(0,H.useRef)(``),g=(0,H.useRef)(!1),_=(0,H.useRef)(!1),v=(0,H.useRef)(``),y=(0,H.useRef)(``),b=(0,H.useRef)(null),x=(0,H.useRef)(!1),S=(0,H.useRef)(o),C=(0,H.useRef)(c);(0,H.useEffect)(()=>{S.current=o,C.current=c}),(0,H.useEffect)(()=>{let e=window.SpeechRecognition||window.webkitSpeechRecognition;if(typeof e!=`function`){p(!1);return}let o;try{o=new e,p(!0)}catch(e){console.log(`useAgentSpeechToText: Speech recognition is present but not constructable`,e),p(!1);return}return o.lang=t,o.continuous=n,o.interimResults=r,o.onresult=e=>{if(x.current)return;_.current=!0;let t=``,n=``;for(let r=e.resultIndex;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n+=a}t&&(h.current=(h.current+` `+t).trim());let r=(h.current+` `+n).trim();if(d(r),i?.(r,!!t),S.current)if(t){b.current!=null&&(cancelAnimationFrame(b.current),b.current=null);let e=v.current.trim(),t=[e,r.replace(e,``).trim()].filter(Boolean).join(` `).trim();v.current=t,S.current(t)}else y.current=r,b.current??=requestAnimationFrame(()=>{b.current=null;let e=y.current;S.current?.(e)})},o.onerror=e=>{console.log(`useAgentSpeechToText: Speech recognition error`,e.error),l(!1),a?.(e.error)},o.onend=()=>{if(g.current||!C.current){l(!1);return}queueMicrotask(()=>{if(!g.current)try{m.current?.start()}catch{l(!1)}})},m.current=o,()=>{m.current&&m.current.stop()}},[t,n,r,i,a]);let w=(0,H.useCallback)(()=>{if(!(!m.current||!f))try{d(``),h.current=``,g.current=!1,_.current=!1,x.current=!1,v.current=``,y.current=``,b.current!=null&&(cancelAnimationFrame(b.current),b.current=null),m.current.start(),l(!0)}catch(e){console.log(`useAgentSpeechToText: Failed to start speech recognition`,e),a?.(`Failed to start speech recognition`)}},[f,a]),T=(0,H.useCallback)(()=>{if(m.current)try{g.current=!0,m.current.stop(),l(!1)}catch(e){console.log(`useAgentSpeechToText: Failed to stop speech recognition`,e)}},[]);return{isListening:c,transcript:u,isSupported:f,startListening:w,stopListening:T,toggleListening:(0,H.useCallback)(()=>{c?T():w()},[c,w,T]),reset:(0,H.useCallback)(()=>{x.current=!0,v.current=``,y.current=``,b.current!=null&&(cancelAnimationFrame(b.current),b.current=null),s&&setTimeout(()=>{x.current=!1},500)},[s])}}var tW={bottom:24,right:24},nW=1e4;function rW(e){return{panelWidth:e?.panelWidth??420,panelHeight:e?.panelHeight??`100%`,panelHeaderHeight:e?.panelHeaderHeight??56,panelTopOffset:e?.panelTopOffset,panelGap:e?.panelGap,panelBorder:e?.panelBorder,panelBorderRadius:e?.panelBorderRadius,zIndex:e?.zIndex??nW,fabPosition:{...typeof e?.fabTopOffset==`number`?{top:e.fabTopOffset}:{bottom:e?.fabBottomOffset??tW.bottom},...typeof e?.fabLeftOffset==`number`?{left:e.fabLeftOffset}:{right:e?.fabRightOffset??tW.right}}}}function iW({isListening:e,stopListening:t,reset:n,sendMessage:r,composerText:i,setComposerText:a,startListening:o,close:s}){return{handleSubmit:()=>{e&&t(),n(),r(i)},handleToggleVoice:()=>{e?t():(a(``),o())},handleClose:()=>{e&&t(),s()}}}var aW=64;function oW(e,t={}){let{enabled:n=!0,behavior:r=`smooth`}=t,i=(0,H.useRef)(null),a=(0,H.useRef)(!0);return(0,H.useEffect)(()=>{let e=i.current;if(!e)return;let t=()=>{a.current=e.scrollHeight-e.scrollTop-e.clientHeight<=aW},n=()=>{t()};return e.addEventListener(`scroll`,n),()=>e.removeEventListener(`scroll`,n)},[]),(0,H.useEffect)(()=>{if(!n||!a.current)return;let e=i.current;if(!e)return;let t=()=>{let t=globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches?`auto`:r;requestAnimationFrame(()=>{let n=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTo({top:n,behavior:t})})};requestAnimationFrame(()=>requestAnimationFrame(t))},e),i}var sW=kU({mutationKey:[`genai`,`login`],mutationFn:async({serviceAccount:e,serviceKey:t})=>OU.loginToGenai(e,t)}),cW=new hE(`useGenaiLogin`),lW=null,uW=null;function dW(e=!1){let t=(0,H.useContext)(OM),{mutateAsync:n}=sW(),[r,i]=(0,H.useState)(!1),[a,o]=(0,H.useState)(null),[s,c]=(0,H.useState)(null),[l,u]=(0,H.useState)(null);return(0,H.useEffect)(()=>{(async()=>{let r=gT();if(r&&!e){c(r);return}let a=t?.serviceAccount&&t?.serviceKey&&t?.tenantId?{serviceAccount:t.serviceAccount,serviceKey:t.serviceKey,tenantId:t.tenantId}:null;if(!a)return;u(a);let s=`${a.serviceAccount}::${a.serviceKey}`;if(lW===s&&!e){uW&&c(await uW);return}e&&(lW=null,uW=null),lW=s,i(!0),o(null),uW=(async()=>(await n({serviceAccount:a.serviceAccount,serviceKey:a.serviceKey})).access_token??null)();try{c(await uW)}catch(e){cW.error(`GenAI login failed`,{error:e instanceof Error?e.message:String(e)}),o(`Failed to authenticate with GenAI service`)}finally{uW=null,i(!1)}})()},[t,n,e]),{isLoggingIn:r,loginError:a,loginToken:s,genaiInit:l}}var fW=kU({mutationKey:[`genai`,`tenant-switch`],mutationFn:async({tenant_id:e,token:t})=>OU.switchTenant(e,t)}),pW=new hE(`useGenaiTenantSwitch`),mW=null,hW=null;function gW(e,t,n=!1){let{mutateAsync:r}=fW(),[i,a]=(0,H.useState)(!1),[o,s]=(0,H.useState)(null),[c,l]=(0,H.useState)(!1);return(0,H.useEffect)(()=>{(async()=>{if(!e||!t)return;let i=gT();if(i&&i!==e&&!n){l(!0);return}if(hW===e&&!n){mW&&(await mW,l(!!gT()));return}n&&(hW=null,mW=null),hW=e,a(!0),s(null),mW=(async()=>{await r({tenant_id:t,token:e})})();try{await mW,l(!0)}catch(e){pW.error(`GenAI tenant switch failed`,{error:e instanceof Error?e.message:String(e)}),s(`Failed to switch tenant`)}finally{mW=null,a(!1)}})()},[e,t,r,n]),{isSwitching:i,switchError:o,hasToken:c}}function _W(e=!1){let{isLoggingIn:t,loginError:n,loginToken:r,genaiInit:i}=dW(e),{isSwitching:a,switchError:o,hasToken:s}=gW(r,i?.tenantId,e);return{isAuthenticating:t||a,authError:n??o,hasToken:s}}function vW(e={}){let{defaultOpen:t=!1,persist:n=!0}=e,[r,i]=Wt({key:n?RT.PANEL_OPEN:`panel-state-${Date.now()}`,defaultValue:t,getInitialValueInEffect:!1}),a=(0,H.useRef)(!1);return(0,H.useEffect)(()=>{r&&!a.current&&e.onOpen&&(a.current=!0,e.onOpen())},[r,e.onOpen]),(0,H.useEffect)(()=>{let e=document.querySelector(`main`)||document.querySelector(`.main-content`)||document.body;return r?e?.classList.add(`panel-open`):(e?.classList.remove(`panel-open`),e?.style.removeProperty(`margin-right`)),()=>{e?.classList.remove(`panel-open`),e?.style.removeProperty(`margin-right`)}},[r]),{isOpen:r,open:(0,H.useCallback)(async()=>{i(!0),e.onOpen&&!a.current&&(a.current=!0,await e.onOpen())},[i,e.onOpen]),close:(0,H.useCallback)(()=>{i(!1)},[i]),toggle:(0,H.useCallback)(()=>{i(e=>!e)},[i]),setOpen:(0,H.useCallback)(e=>{i(e)},[i])}}function yW({runtime:e,uiOptions:t}){let n=e.forceReAuth,{isAuthenticating:r,hasToken:i}=_W(n),{panelWidth:a,panelHeight:o,panelHeaderHeight:s,panelTopOffset:c,panelBorder:l,panelBorderRadius:u,zIndex:d,fabPosition:f}=rW(t),p=(0,H.useRef)(!1),{messages:m,composerText:h,setComposerText:g,isLoading:_,error:v,sendMessage:y,sendInitialMessage:b,agentDisplayName:x,canSend:S}=qU(),{actions:C,handleActionClick:w}=JU(m,g),{runtimeInfo:T,refreshRuntimeInfo:E}=QU(),{isOpen:D,open:O,close:k}=vW({defaultOpen:!1,persist:!0,onOpen:async()=>{p.current||(p.current=!0,await E())}});(0,H.useEffect)(()=>{(async()=>{p.current&&D&&!r&&i&&await b()&&(p.current=!1)})()},[D,r,i,b]);let A=oW([m.length,_]),{isListening:j,isSupported:M,startListening:N,stopListening:P,reset:ee}=eW({lang:$U(),continuous:!0,pauseOnSubmit:!0,onTextChange:g}),{panelResizableWidth:F,actualWidth:I,shellGap:te,floatingTop:ne,floatingHeight:re,floatingMaxHeight:ie}=ZU(t,a,D,o,c),{handleSubmit:L,handleToggleVoice:ae,handleClose:oe}=iW({isListening:j,stopListening:P,reset:ee,sendMessage:y,composerText:h,setComposerText:g,startListening:N,close:k});return(0,U.jsxs)(U.Fragment,{children:[!D&&(0,U.jsx)(BM,{onClick:()=>void O(),zIndex:d,position:f,label:x}),D&&(0,U.jsx)(dU,{visible:!0,onClose:oe,messages:m,composerText:h,onComposerTextChange:g,isLoading:_,error:v,canSend:S,onSubmit:L,actions:C,onActionClick:w,isListening:j,isVoiceSupported:M,onToggleVoice:ae,panelTitle:x,runtimeInfo:T,scrollViewportRef:A,actualWidth:I,floatingTop:ne,floatingHeight:re,floatingMaxHeight:ie,shellGap:te,panelHeaderHeight:s,panelResizableWidth:F,panelBorder:l,panelBorderRadius:u,zIndex:d})]})}function bW(e){return(0,U.jsx)(yW,{...e})}function xW(e,t){if(typeof e==`function`){e(t);return}e&&(e.current=t)}function SW(e){return{url:{app:e.app??``,api:e.api??``,apiPaths:{crm:``,uiAuthz:``}},keycloak:{url:``,realm:``,clientId:``},features:{enableThemeManager:!0}}}var CW=(0,H.forwardRef)((e,t)=>{let{config:n,runtime:r,uiOptions:i,className:a,style:o,rootElement:s}=e,c=(0,H.useRef)(null),l=SW(n);Pe.locale||Pe.activate(`en`),EE(l,n);let u=(0,H.useMemo)(()=>CM({themeName:i?.themeName}),[i?.themeName]);return(0,U.jsx)(PM,{appConfig:l,config:n,runtime:r,theme:(0,H.useMemo)(()=>i?.theme?Vr(u,i.theme):u,[i?.theme,u]),rootElement:s??c.current,children:(0,U.jsx)(`div`,{className:a,ref:e=>{c.current=e,xW(t,e)},style:o,children:(0,U.jsx)(bW,{config:n,runtime:r,uiOptions:i})})})});CW.displayName=`Widget`;var wW=`:root,
402
+ `)}function KH(e){let t=e.trim();return!t||!/^[{\[]/.test(t)?null:mH(t)}function qH(e,t){return(0,H.useMemo)(()=>{let n=$V(e),r=KH(n);if(r)return[{type:`markdown`,key:`json-0`,content:UH(GH(r))}];let i=WV(n),a=[],o=0;for(let e of i){if(e.type===`markdown`){o=WH(a,e.content,o);continue}try{let n=GV(e.dsl);if(!n){let t=KH(e.dsl);o=WH(a,t?GH(t):e.raw,o);continue}let r=jV(n,t);if(r.kind===`widget`){a.push({type:`widget`,key:`widget-${o++}`,widget:r.widget});continue}o=WH(a,GH(r.payload),o)}catch(t){VH.error(`Failed to parse widget`,{error:t instanceof Error?t.message:String(t)}),o=WH(a,e.raw,o)}}return a},[e,t])}var JH={agentChatMdRenderer:`_agentChatMdRenderer_5jigp_1`},YH=(0,H.memo)(({content:e,onWidgetEvent:t})=>{let n=qH(e,t);return(0,U.jsx)(q,{className:JH.agentChatMdRenderer,children:n.map(e=>e.type===`markdown`?(0,U.jsx)(XN,{html:e.content},e.key):(0,U.jsx)(q,{children:e.widget},e.key))})});YH.displayName=`AgentMarkdownRenderer`;var XH={body:`_body_1vtnd_1`,messageBubble:`_messageBubble_1vtnd_21`,messageBubbleUser:`_messageBubbleUser_1vtnd_33`,userText:`_userText_1vtnd_54`,messageBubbleAssistant:`_messageBubbleAssistant_1vtnd_62`,messageList:`_messageList_1vtnd_84`};function ZH({messages:e,isLoading:t,error:n,scrollViewportRef:r,onWidgetEvent:i}){return(0,U.jsx)(By,{className:XH.body,gap:0,children:(0,U.jsx)(ol,{h:`100%`,type:`always`,scrollbarSize:8,offsetScrollbars:!0,viewportRef:r,children:(0,U.jsxs)(By,{className:XH.messageList,gap:0,children:[n&&(0,U.jsx)(Wf,{color:`red`,variant:`light`,radius:`md`,children:n}),e.map(e=>(0,U.jsx)(q,{className:`${XH.messageBubble} ${e.sentBy===`user`?XH.messageBubbleUser:XH.messageBubbleAssistant}`,children:e.sentBy===`assistant`?(0,U.jsx)(YH,{content:e.text,onWidgetEvent:i}):(0,U.jsx)(Yf,{className:XH.userText,children:e.text})},e.id)),t&&(0,U.jsx)(q,{className:`${XH.messageBubble} ${XH.messageBubbleAssistant}`,children:(0,U.jsx)(HM,{messages:[`Thinking`,`Analyzing your request`,`Searching for information`,`Processing data`,`Preparing response`,`Almost there`]})})]})})})}var QH={root:`_root_h7hgt_1`,input:`_input_h7hgt_6`,section:`_section_h7hgt_34`};function $H({composerText:e,onComposerTextChange:t,isLoading:n,isListening:r,onSubmit:i,rightSection:a,rightSectionWidth:o}){return(0,U.jsx)(Rb,{placeholder:r?`Listening...`:`Ask me anything...`,value:e,onChange:e=>t(e.currentTarget.value),disabled:n,radius:`md`,size:`md`,rightSection:a,rightSectionWidth:o,rightSectionPointerEvents:`all`,classNames:{root:QH.root,input:QH.input,section:QH.section},styles:{input:{minHeight:`100%`}},onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),i())}})}function eU({size:e,...t}){return(0,U.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,...GF(e),...t,children:[(0,U.jsx)(`path`,{d:`M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z`}),(0,U.jsx)(`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2`}),(0,U.jsx)(`line`,{x1:`12`,x2:`12`,y1:`19`,y2:`22`})]})}function tU({size:e,...t}){return(0,U.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,...GF(e),...t,children:(0,U.jsx)(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`})})}function nU({isListening:e,isLoading:t,onToggleVoice:n,size:r}){let i=Vj();return(0,U.jsx)(uy,{label:e?`Stop recording`:`Voice input`,children:(0,U.jsx)(hu,{onClick:n,disabled:t,size:r??`lg`,radius:`md`,variant:e?`filled`:`subtle`,color:e?`red`:`accent`,"aria-label":e?`Stop voice recording`:`Start voice recording`,styles:{root:e?void 0:{color:i.other.color[`secondary-default`],backgroundColor:`transparent`,boxShadow:`inset 0 0 0 1px ${i.other.color[`secondary-light`]}33`}},children:e?(0,U.jsx)(tU,{size:`sm`}):(0,U.jsx)(eU,{size:`sm`})})})}function rU({size:e,...t}){return(0,U.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,...GF(e),...t,children:[(0,U.jsx)(`path`,{d:`m22 2-7 20-4-9-9-4Z`}),(0,U.jsx)(`path`,{d:`M22 2 11 13`})]})}var iU={footer:`_footer_zlzuq_1`,actionGroup:`_actionGroup_zlzuq_8`,poweredBy:`_poweredBy_zlzuq_12`,sendButton:`_sendButton_zlzuq_18`};function aU({composerText:e,onComposerTextChange:t,isLoading:n,isListening:r,isVoiceSupported:i,canSend:a,onSubmit:o,onToggleVoice:s}){let c=i?74:40;return(0,U.jsxs)(By,{className:iU.footer,gap:`sm`,children:[(0,U.jsx)($H,{composerText:e,onComposerTextChange:t,isLoading:n,isListening:r,onSubmit:o,rightSectionWidth:c,rightSection:(0,U.jsxs)(Tu,{className:iU.actionGroup,wrap:`nowrap`,gap:4,align:`center`,children:[i&&(0,U.jsx)(nU,{isListening:r,isLoading:n,onToggleVoice:s,size:30}),(0,U.jsx)(hu,{onClick:o,disabled:!a||n,size:30,radius:`md`,variant:`filled`,color:`accent`,className:iU.sendButton,"aria-label":`Send message`,children:(0,U.jsx)(rU,{size:`sm`})})]})}),(0,U.jsx)(Yf,{ta:`center`,size:`xs`,c:`dimmed`,className:iU.poweredBy,pt:2,children:`Powered by Exceeder · Etiya`})]})}function oU({size:e,...t}){return(0,U.jsxs)(`svg`,{viewBox:`0 0 22 22`,fill:`none`,...GF(e),...t,children:[(0,U.jsx)(`rect`,{x:`4`,y:`4`,width:`14`,height:`2.5`,rx:`1.2`,fill:`currentColor`}),(0,U.jsx)(`rect`,{x:`4`,y:`9.75`,width:`10`,height:`2.5`,rx:`1.2`,fill:`currentColor`,opacity:`0.88`}),(0,U.jsx)(`rect`,{x:`4`,y:`15.5`,width:`14`,height:`2.5`,rx:`1.2`,fill:`currentColor`})]})}function sU({size:e,...t}){return(0,U.jsx)(`svg`,{viewBox:`0 0 15 15`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,...GF(e),...t,children:(0,U.jsx)(`path`,{d:`M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})}var cU={header:`_header_8tb8q_19`,headerLeft:`_headerLeft_8tb8q_31`,headerInfo:`_headerInfo_8tb8q_36`,orbContainer:`_orbContainer_8tb8q_40`,orbOuter:`_orbOuter_8tb8q_54`,orbPulse:`_orbPulse_8tb8q_1`,orbMiddle:`_orbMiddle_8tb8q_63`,orbInner:`_orbInner_8tb8q_72`,orbFloat:`_orbFloat_8tb8q_1`,headerMeta:`_headerMeta_8tb8q_85`,statusDot:`_statusDot_8tb8q_89`,statusText:`_statusText_8tb8q_103`,closeButton:`_closeButton_8tb8q_112`,title:`_title_8tb8q_123`,topSubHeader:`_topSubHeader_8tb8q_135`,subHeaderLeft:`_subHeaderLeft_8tb8q_145`,subHeaderIcon:`_subHeaderIcon_8tb8q_151`,subHeaderTitle:`_subHeaderTitle_8tb8q_162`,subHeaderStatus:`_subHeaderStatus_8tb8q_168`};function lU({panelTitle:e,isLoading:t,isOnline:n,onClose:r}){let i=Vj();return(0,U.jsxs)(Tf,{className:cU.header,align:`center`,justify:`space-between`,children:[(0,U.jsxs)(Tu,{className:cU.headerLeft,wrap:`nowrap`,gap:`sm`,align:`center`,children:[(0,U.jsxs)(q,{className:cU.orbContainer,"data-loading":t||void 0,children:[(0,U.jsx)(q,{className:cU.orbOuter}),(0,U.jsx)(q,{className:cU.orbMiddle}),(0,U.jsx)(q,{className:cU.orbInner,children:(0,U.jsx)(oU,{size:`sm`,color:i.other.color[`text-white`]})})]}),(0,U.jsxs)(By,{className:cU.headerInfo,gap:2,justify:`center`,children:[(0,U.jsx)(Yf,{className:cU.title,fw:800,children:e}),(0,U.jsxs)(Tu,{className:cU.headerMeta,wrap:`nowrap`,gap:6,align:`center`,children:[(0,U.jsx)(q,{className:cU.statusDot,"data-loading":t||void 0,"data-online":n||void 0}),(0,U.jsx)(Yf,{className:cU.statusText,span:!0,children:t?`Typing…`:n?`Online`:`Offline`})]})]})]}),(0,U.jsx)(hu,{variant:`subtle`,size:`lg`,radius:`md`,onClick:r,className:cU.closeButton,"aria-label":`Close agent chat`,children:(0,U.jsx)(sU,{size:`sm`})})]})}var uU={root:`_root_nkl8r_1`,surface:`_surface_nkl8r_9`,resizeHandle:`_resizeHandle_nkl8r_22`};function dU({visible:e,onClose:t,messages:n,composerText:r,onComposerTextChange:i,isLoading:a,error:o,canSend:s,onSubmit:c,isListening:l,isVoiceSupported:u,onToggleVoice:d,actions:f,onActionClick:p,panelTitle:m,runtimeInfo:h,scrollViewportRef:g,actualWidth:_=420,floatingTop:v=`var(--mantine-custom-space-150)`,floatingHeight:y=`100%`,floatingMaxHeight:b=`calc(100vh - var(--mantine-custom-space-150) - var(--mantine-custom-space-150))`,shellGap:x=`var(--mantine-custom-space-150)`,panelHeaderHeight:S=56,panelResizableWidth:C,panelBorder:w,panelBorderRadius:T,zIndex:E}){let D=h.hasCustomerToken&&h.hasGenaiToken,O=e=>{if(e.type===`action-click`&&e.data){let t=f.find(t=>t.buttonText===e.data?.buttonText);t&&p(t)}};if(!e)return null;let k=typeof T==`number`?`${T}px`:T;return(0,U.jsxs)(q,{className:uU.root,style:{width:_,maxWidth:`calc(100vw - var(--mantine-custom-space-400) - var(--mantine-custom-space-400))`,height:y,maxHeight:b,top:v,right:x,zIndex:E,"--agent-widget-panel-header-height":`${S}px`,"--agent-widget-shell-gap":x,"--agent-widget-panel-border":w,"--agent-widget-panel-radius":k},children:[C&&(0,U.jsx)(q,{onPointerDown:C.handlePointerDown,className:uU.resizeHandle,style:C.style}),(0,U.jsxs)(q,{className:uU.surface,children:[(0,U.jsx)(lU,{panelTitle:m,isLoading:a,isOnline:D,onClose:t}),(0,U.jsx)(ZH,{messages:n,isLoading:a,error:o,scrollViewportRef:g,onWidgetEvent:O}),(0,U.jsx)(aU,{composerText:r,onComposerTextChange:i,isLoading:a,isListening:l,isVoiceSupported:u,canSend:s,onSubmit:c,onToggleVoice:d})]})]})}function fU(e){return(0,H.useMemo)(()=>{let t=e===`MULTI`?`MULTI`:`SINGLE`;return{agentType:t,isMultiAgent:t===`MULTI`}},[e])}function pU(e){return typeof e==`object`&&!!e}function mU(e){let t=Number(e);return Number.isFinite(t)&&t>0?t:null}function hU(e){if(Array.isArray(e))return e.filter(pU);if(!pU(e))return[];for(let t of[`data`,`items`,`results`,`content`,`rows`,`list`,`response`]){let n=e[t];if(Array.isArray(n))return n.filter(pU);if(pU(n)){let e=hU(n);if(e.length>0)return e}}for(let t of Object.values(e))if(Array.isArray(t)){let e=t.filter(pU);if(e.length>0)return e}return[]}function gU(e){let t=mU(e.assistantId??e.assistant_id??e.id??e.agentId??e.agent_id??e.appId??e.app_id);if(!t)return null;let n=e.description??e.appDescription??e.app_description??e.label??e.name??e.assistantName??e.assistant_name??e.agentName??e.agent_name??e.title,r=typeof n==`string`&&n.trim().length>0?n.trim():`Agent ${t}`,i=e.assistantKey??e.assistant_key??e.key??e.agentKey??e.agent_key??e.code,a=typeof i==`string`&&i.trim().length>0?i.trim():r.toLowerCase().replace(/\s+/g,`-`),o=e.initialMessage??e.initial_message??e.welcomeMessage??e.welcome_message,s=typeof o==`string`&&o.trim().length>0?o.trim():void 0;return{assistantId:t,label:r,assistantKey:a,...s?{initialMessage:s}:{}}}function _U(e){let t=mU(e.appId??e.app_id??e.id??e.assistantId??e.assistant_id);if(!t)return null;let n=e.description??e.name??e.label??e.title??e.appName??e.app_name,r=typeof n==`string`&&n.trim().length>0?n.trim():`Agent ${t}`,i=e.assistantKey??e.assistant_key??e.key??e.code,a=typeof i==`string`&&i.trim().length>0?i.trim():r.toLowerCase().replace(/\s+/g,`-`),o=e.initialMessage??e.initial_message??e.welcomeMessage??e.welcome_message,s=typeof o==`string`&&o.trim().length>0?o.trim():void 0;return{assistantId:t,label:r,assistantKey:a,...s?{initialMessage:s}:{}}}function vU(e){if(Array.isArray(e.apps)&&e.apps.length>0){let t=e.apps.map(e=>_U(e)).filter(e=>e!==null);if(t.length>0)return t}let t=gU(e);return t?[t]:[]}function yU(e){return hU(e).flatMap(e=>vU(e))}var bU={runtimeInfo:{customerId:null,hasCustomerToken:!1,hasGenaiToken:!1}},xU=dE(e=>({...bU,setRuntimeInfo:t=>e({runtimeInfo:t}),updateCustomerId:t=>e(e=>({runtimeInfo:{...e.runtimeInfo,customerId:t}})),updateCustomerToken:t=>e(e=>({runtimeInfo:{...e.runtimeInfo,hasCustomerToken:t}})),updateGenaiToken:t=>e(e=>({runtimeInfo:{...e.runtimeInfo,hasGenaiToken:t}})),resetRuntimeInfo:()=>e({runtimeInfo:bU.runtimeInfo})}));async function SU(e,t){try{let n=new URLSearchParams;n.set(`username`,atob(e)),n.set(`password`,atob(t));let r=await TE.post(`/login`,n,{anonymous:!0,headers:{"Content-Type":`application/x-www-form-urlencoded`}});return r.data?.access_token&&(_T(r.data.access_token),xT(!1)),r.data}catch(e){throw e}}async function CU(e,t){try{let n=await TE.post(`/tenants/switch`,{tenant_id:e},{anonymous:!0,headers:{Authorization:`Bearer ${t}`}});return n.data?.data?.access_token&&_T(n.data.data.access_token),yT(n.data?.data?.tenant_id??e),xT(!0),n.data}catch(e){throw e}}async function wU(e){try{return(await TE.post(`/agent-message`,e,{anonymous:!0})).data}catch(e){throw e}}async function TU(e){try{return(await TE.post(`/agentic-app-chat`,e,{anonymous:!0})).data}catch(e){throw e}}async function EU(e){let{customerToken:t,tenantId:n,...r}=e;try{return(await TE.post(`/assistant`,r,{anonymous:!0,headers:{Authorization:`Bearer ${t}`,"x-tenant-id":String(n)}})).data}catch(e){throw e}}async function DU(e){let{customerToken:t,tenantId:n,...r}=e;try{return(await TE.post(`/fetch-agentic-app`,r,{anonymous:!0,headers:{Authorization:`Bearer ${t}`,"x-tenant-id":String(n)}})).data}catch(e){throw e}}var OU={loginToGenai:SU,switchTenant:CU,sendAgentMessage:wU,sendAgenticAppChat:TU,fetchAssistants:EU,fetchAgenticApps:DU};function kU({mutationKey:e,mutationFn:t,defaultOptions:n={}}){return function(r){return eS({...n,...r,meta:{...n?.meta,...r?.meta},mutationKey:e,mutationFn:t})}}var AU=kU({mutationKey:[`genai`,`agentic-apps`],mutationFn:async e=>OU.fetchAgenticApps(e)}),jU=kU({mutationKey:[`genai`,`assistants`],mutationFn:async e=>OU.fetchAssistants(e)});function MU(e,t){return e&&t.includes(e)?e:t[0]}function NU(e,t,n){let{mutateAsync:r}=jU(),{mutateAsync:i}=AU(),{isMultiAgent:a}=fU(e),[o,s]=(0,H.useState)(null),c=(0,H.useRef)(null),l=(0,H.useRef)(null),u=gT(),d=vT(),f=d?Number(d):null,p=bT();(0,H.useEffect)(()=>{if(!n){s(null);return}if(!u||!f||Number.isNaN(f)||f<=0||!p){s(null),c.current=null,l.current=null;return}let e=`${a?`multi`:`single`}:${f}:${u}`;if(c.current===e||l.current===e)return;l.current=e;let t=!0;return(async()=>{try{let n=a?await i({page:1,limit:10,customerToken:u,tenantId:f}):await r({page:1,limit:20,agent_type:`SINGLE`,customerToken:u,tenantId:f});if(!t)return;s(yU(n)),c.current=e}catch{t&&(s([]),c.current=null)}finally{l.current===e&&(l.current=null)}})(),()=>{t=!1}},[n,i,r,u,f,a,p]);let m=o??[],h=MU(t,m.map(e=>e.assistantId));return{availableAssistants:m,selectedAssistantId:h,selectedAssistant:m.find(e=>e.assistantId===h)}}function PU(){let e=(0,H.useContext)(OM),{agentType:t}=fU(e?.agentType),{selectedAssistantId:n,selectedAssistant:r}=NU(e?.agentType,e?.assistantId,!!e),i=(0,H.useMemo)(()=>e?{...e,assistantId:n,agentType:t,assistantLabel:r?.label,assistantInitialMessage:r?.initialMessage}:null,[e,t,r,n]);if(!i)throw Error(`AgentConfigContext is missing.`);return i}function FU(){let e=(0,H.useContext)(kM);if(!e)throw Error(`AgentRuntimeContext is missing.`);return e}function IU(){let e=FU();return(0,H.useMemo)(()=>{let t=e?.customerToken;return typeof t!=`string`||t.trim().length===0?null:t},[e?.customerToken])}var LU=kU({mutationKey:[`genai`,`agent-message`],mutationFn:async({payload:e})=>OU.sendAgentMessage(e)}),RU=kU({mutationKey:[`genai`,`agentic-app-chat`],mutationFn:async({payload:e})=>OU.sendAgenticAppChat(e)});function zU(){let e=LU(),t=RU();return{sendChatMessage:(0,H.useCallback)(async n=>{let{agentType:r,message:i,selectedAgentId:a,customerId:o,customerToken:s,chatId:c}=n;return r===`MULTI`?t.mutateAsync({payload:{message:i,app_id:a,...o?{unique_user_id:o}:{}}}):e.mutateAsync({payload:{message:i,chat_id:c,assistant_id:a,is_sync:!0,...o?{unique_user_id:o}:{},tool_headers:{_default:{Authorization:`Bearer ${s}`}}}})},[e,t])}}function BU(e){return e.assistantId??null}function VU(e){return BU(e)?e.assistantInitialMessage??null:null}function HU(e){return e.customerId}function UU(e){return e.customerToken}function WU(e){return e.language??null}function GU(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.message??(Array.isArray(t.messages)?t.messages[0]:null);if(!n||typeof n!=`object`)return null;let r=n.chat_id,i=typeof r==`number`&&Number.isFinite(r)?r:null,a=typeof n.message==`string`?n.message:``,o=typeof n.created_at==`string`?n.created_at:new Date().toISOString();return a?{chatId:i,text:a,createdAt:o}:null}function KU(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function qU(){let e=FU(),t=IU(),n=PU(),{agentType:r,isMultiAgent:i}=fU(n.agentType),{sendChatMessage:a}=zU(),[o,s]=(0,H.useState)([]),[c,l]=(0,H.useState)(``),[u,d]=(0,H.useState)(null),[f,p]=(0,H.useState)(!1),[m,h]=(0,H.useState)(null),g=(0,H.useRef)(!1),_=BU(n),v=i?n.assistantLabel??`Assistant`:`Assistant`,y=(0,H.useCallback)(e=>{let t={id:KU(),sentBy:`user`,text:e};s(e=>[...e,t])},[]),b=(0,H.useCallback)((e,t)=>{let n={id:KU(),sentBy:`assistant`,text:e,createdAt:t};s(e=>[...e,n])},[]),x=(0,H.useCallback)(async(o,s)=>{if(!o.trim())return;if(l(``),s?.showUserBubble!==!1&&y(o),!e||!n){h(`Chat is not configured.`);return}if(!_){h(`Chat configuration is missing.`);return}let c=HU(e),f=i?null:t;if(!i&&!f){h(`Missing customer token.`);return}p(!0),h(null);try{let e=GU(await a({agentType:r,message:o,selectedAgentId:_,customerId:c||void 0,customerToken:f??``,chatId:u}));if(!e)return;e.chatId!==null&&d(e.chatId),b(e.text,e.createdAt)}catch{h(`Something went wrong. Please try again.`)}finally{p(!1)}},[e,n,u,y,b,a,t,r,i]);return{messages:o,composerText:c,setComposerText:l,isLoading:f,error:m,sendMessage:x,sendInitialMessage:(0,H.useCallback)(async()=>{if(g.current||f||o.length>0||!e||!n||!BU(n))return!1;let t=HU(e),r=VU(n)?.trim(),i=null;return i=r?t?`${r} ${t}`.trim():r:t?`Hello, my customer id is ${t}`:`Hello`,i.trim()?(g.current=!0,await x(i,{showUserBubble:!1}),!0):!1},[e,n,f,o.length,x]),resetChat:(0,H.useCallback)(()=>{s([]),l(``),d(null),h(null),g.current=!1},[]),agentDisplayName:v,canSend:c.trim().length>0}}function JU(e,t){let n=(0,H.useRef)([]);return{actions:(0,H.useMemo)(()=>{let t=[...e].reverse().find(e=>e.sentBy===`assistant`);if(!t)return n.current;let r=ZV(t.text).find(e=>e.type===`widget`&&e.config.type===`actions`),i=r?.type===`widget`?r.config.actions??[]:[];return i.length>0&&(n.current=i),n.current},[e]),handleActionClick:(0,H.useCallback)(e=>{t(e.buttonText)},[t])}}function YU(e={}){let{axis:t=`y`,direction:n=1,onResizeChange:r}=e,[i,a]=(0,H.useState)(0),o=(0,H.useRef)({startPos:0,startOffset:0}),{startInteraction:s}=FM(),c=t===`y`?`ns-resize`:t===`x`?`ew-resize`:`nwse-resize`;return{offset:i,handlePointerDown:(0,H.useCallback)(e=>{e.preventDefault(),e.stopPropagation();let l=t===`y`?e.clientY:e.clientX,u=i;o.current={startPos:l,startOffset:u},s({cursor:c,onMove:e=>{let i;i=t===`y`?-(e.clientY-l):(e.clientX-l)*n;let o=u+i;a(o),r?.(o)}})},[i,t,n,c,r,s]),style:{cursor:c,touchAction:`none`}}}var XU=[`#root main`,`#root`,`main`,`.main-content`,`#app`,`body`];function ZU(e,t,n,r,i){let a=(0,H.useRef)(Math.max(280,t??420)),o=(0,H.useRef)(n??!1),s=(0,H.useRef)(null),c=e?.reserveLayoutSpace??!0,l=(0,H.useCallback)(()=>{let t=e?.hostContainerSelector,n=[...t?t.split(`,`).map(e=>e.trim()).filter(Boolean):[],...XU];for(let e of n){let t=document.querySelector(e);if(t)return t}return document.body},[e?.hostContainerSelector]),u=(0,H.useCallback)(e=>{let t=document.documentElement;if(!c){if(t.style.removeProperty(`--agent-widget-panel-width`),s.current){let{element:e,inlinePaddingBefore:t}=s.current;e.style.paddingRight=t,s.current=null}return}if(e===null?t.style.removeProperty(`--agent-widget-panel-width`):t.style.setProperty(`--agent-widget-panel-width`,`${e}px`),e===null){if(s.current){let{element:e,inlinePaddingBefore:t}=s.current;e.style.paddingRight=t,s.current=null}return}if(!s.current||!document.contains(s.current.element)){let e=l();if(!e)return;s.current={element:e,inlinePaddingBefore:e.style.paddingRight,widthApplied:0}}let{element:n,inlinePaddingBefore:r,widthApplied:i}=s.current;e!==i&&(n.style.paddingRight=r,n.style.paddingRight=`calc(${r||`0px`} + ${e}px)`,s.current.widthApplied=e)},[l,c]),d=YU({axis:`x`,direction:-1,onResizeChange:(0,H.useCallback)(e=>{let n=Math.max(280,(t??420)+e);a.current=n,u(n)},[t,u])});(0,H.useEffect)(()=>{o.current=n??!1},[n]),(0,H.useEffect)(()=>{let e=Math.max(280,t??420);a.current=e,o.current&&u(e)},[t,u]),(0,H.useEffect)(()=>{if(!n){u(null),document.documentElement.removeAttribute(`data-agent-widget-open`);return}return u(a.current),document.documentElement.setAttribute(`data-agent-widget-open`,`true`),()=>{u(null),document.documentElement.removeAttribute(`data-agent-widget-open`)}},[n,u]);let f=d?Math.max(280,(t??420)+d.offset):t??420,p=r===`100%`||r===`100vh`,m=typeof e?.panelGap==`number`?`${e.panelGap}px`:e?.panelGap??`var(--mantine-custom-space-150)`,h=i??0;return{panelResizableWidth:d,actualWidth:f,shellGap:m,floatingTop:h?`calc(${h}px + ${m})`:m,floatingHeight:p?`calc(100vh - ${h}px - ${m} - ${m})`:typeof r==`number`?`${r}px`:r??`100%`,floatingMaxHeight:`calc(100vh - ${h}px - ${m} - ${m})`}}function QU(){let e=FU(),{runtimeInfo:t,setRuntimeInfo:n}=xU(),r=(0,H.useCallback)(async()=>{if(!e){n({customerId:null,hasCustomerToken:!1,hasGenaiToken:!1});return}let t=HU(e),r=await UU(e),i=gT();n({customerId:t,hasCustomerToken:!!r,hasGenaiToken:!!i})},[e,n]);return(0,H.useEffect)(()=>{r()},[e,r]),{runtimeInfo:t,refreshRuntimeInfo:r}}function $U(){let e=FU();return(0,H.useMemo)(()=>e&&WU(e)||`en-US`,[e])}function eW(e={}){let{lang:t=`en-EN`,continuous:n=!0,interimResults:r=!0,onResult:i,onError:a,onTextChange:o,pauseOnSubmit:s=!1}=e,[c,l]=(0,H.useState)(!1),[u,d]=(0,H.useState)(``),[f,p]=(0,H.useState)(!1),m=(0,H.useRef)(null),h=(0,H.useRef)(``),g=(0,H.useRef)(!1),_=(0,H.useRef)(!1),v=(0,H.useRef)(``),y=(0,H.useRef)(``),b=(0,H.useRef)(null),x=(0,H.useRef)(!1),S=(0,H.useRef)(o),C=(0,H.useRef)(c);(0,H.useEffect)(()=>{S.current=o,C.current=c}),(0,H.useEffect)(()=>{let e=window.SpeechRecognition||window.webkitSpeechRecognition;if(typeof e!=`function`){p(!1);return}let o;try{o=new e,p(!0)}catch(e){console.log(`useAgentSpeechToText: Speech recognition is present but not constructable`,e),p(!1);return}return o.lang=t,o.continuous=n,o.interimResults=r,o.onresult=e=>{if(x.current)return;_.current=!0;let t=``,n=``;for(let r=e.resultIndex;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n+=a}t&&(h.current=(h.current+` `+t).trim());let r=(h.current+` `+n).trim();if(d(r),i?.(r,!!t),S.current)if(t){b.current!=null&&(cancelAnimationFrame(b.current),b.current=null);let e=v.current.trim(),t=[e,r.replace(e,``).trim()].filter(Boolean).join(` `).trim();v.current=t,S.current(t)}else y.current=r,b.current??=requestAnimationFrame(()=>{b.current=null;let e=y.current;S.current?.(e)})},o.onerror=e=>{console.log(`useAgentSpeechToText: Speech recognition error`,e.error),l(!1),a?.(e.error)},o.onend=()=>{if(g.current||!C.current){l(!1);return}queueMicrotask(()=>{if(!g.current)try{m.current?.start()}catch{l(!1)}})},m.current=o,()=>{m.current&&m.current.stop()}},[t,n,r,i,a]);let w=(0,H.useCallback)(()=>{if(!(!m.current||!f))try{d(``),h.current=``,g.current=!1,_.current=!1,x.current=!1,v.current=``,y.current=``,b.current!=null&&(cancelAnimationFrame(b.current),b.current=null),m.current.start(),l(!0)}catch(e){console.log(`useAgentSpeechToText: Failed to start speech recognition`,e),a?.(`Failed to start speech recognition`)}},[f,a]),T=(0,H.useCallback)(()=>{if(m.current)try{g.current=!0,m.current.stop(),l(!1)}catch(e){console.log(`useAgentSpeechToText: Failed to stop speech recognition`,e)}},[]);return{isListening:c,transcript:u,isSupported:f,startListening:w,stopListening:T,toggleListening:(0,H.useCallback)(()=>{c?T():w()},[c,w,T]),reset:(0,H.useCallback)(()=>{x.current=!0,v.current=``,y.current=``,b.current!=null&&(cancelAnimationFrame(b.current),b.current=null),s&&setTimeout(()=>{x.current=!1},500)},[s])}}var tW={bottom:24,right:24},nW=1e4;function rW(e){return{panelWidth:e?.panelWidth??420,panelHeight:e?.panelHeight??`100%`,panelHeaderHeight:e?.panelHeaderHeight??56,panelTopOffset:e?.panelTopOffset,panelGap:e?.panelGap,panelBorder:e?.panelBorder,panelBorderRadius:e?.panelBorderRadius,zIndex:e?.zIndex??nW,fabPosition:{...typeof e?.fabTopOffset==`number`?{top:e.fabTopOffset}:{bottom:e?.fabBottomOffset??tW.bottom},...typeof e?.fabLeftOffset==`number`?{left:e.fabLeftOffset}:{right:e?.fabRightOffset??tW.right}}}}function iW({isListening:e,stopListening:t,reset:n,sendMessage:r,composerText:i,setComposerText:a,startListening:o,close:s}){return{handleSubmit:()=>{e&&t(),n(),r(i)},handleToggleVoice:()=>{e?t():(a(``),o())},handleClose:()=>{e&&t(),s()}}}var aW=64;function oW(e,t={}){let{enabled:n=!0,behavior:r=`smooth`}=t,i=(0,H.useRef)(null),a=(0,H.useRef)(!0);return(0,H.useEffect)(()=>{let e=i.current;if(!e)return;let t=()=>{a.current=e.scrollHeight-e.scrollTop-e.clientHeight<=aW},n=()=>{t()};return e.addEventListener(`scroll`,n),()=>e.removeEventListener(`scroll`,n)},[]),(0,H.useEffect)(()=>{if(!n||!a.current)return;let e=i.current;if(!e)return;let t=()=>{let t=globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches?`auto`:r;requestAnimationFrame(()=>{let n=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTo({top:n,behavior:t})})};requestAnimationFrame(()=>requestAnimationFrame(t))},e),i}var sW=kU({mutationKey:[`genai`,`login`],mutationFn:async({serviceAccount:e,serviceKey:t})=>OU.loginToGenai(e,t)}),cW=new hE(`useGenaiLogin`),lW=null,uW=null;function dW(e=!1){let t=(0,H.useContext)(OM),{mutateAsync:n}=sW(),[r,i]=(0,H.useState)(!1),[a,o]=(0,H.useState)(null),[s,c]=(0,H.useState)(null),[l,u]=(0,H.useState)(null);return(0,H.useEffect)(()=>{(async()=>{let r=gT();if(r&&!e){c(r);return}let a=t?.serviceAccount&&t?.serviceKey&&t?.tenantId?{serviceAccount:t.serviceAccount,serviceKey:t.serviceKey,tenantId:t.tenantId}:null;if(!a)return;u(a);let s=`${a.serviceAccount}::${a.serviceKey}`;if(lW===s&&!e){uW&&c(await uW);return}e&&(lW=null,uW=null),lW=s,i(!0),o(null),uW=(async()=>(await n({serviceAccount:a.serviceAccount,serviceKey:a.serviceKey})).access_token??null)();try{c(await uW)}catch(e){cW.error(`GenAI login failed`,{error:e instanceof Error?e.message:String(e)}),o(`Failed to authenticate with GenAI service`)}finally{uW=null,i(!1)}})()},[t,n,e]),{isLoggingIn:r,loginError:a,loginToken:s,genaiInit:l}}var fW=kU({mutationKey:[`genai`,`tenant-switch`],mutationFn:async({tenant_id:e,token:t})=>OU.switchTenant(e,t)}),pW=new hE(`useGenaiTenantSwitch`),mW=null,hW=null;function gW(e,t,n=!1){let{mutateAsync:r}=fW(),[i,a]=(0,H.useState)(!1),[o,s]=(0,H.useState)(null),[c,l]=(0,H.useState)(!1);return(0,H.useEffect)(()=>{(async()=>{if(!e||!t)return;let i=gT();if(i&&i!==e&&!n){l(!0);return}if(hW===e&&!n){mW&&(await mW,l(!!gT()));return}n&&(hW=null,mW=null),hW=e,a(!0),s(null),mW=(async()=>{await r({tenant_id:t,token:e})})();try{await mW,l(!0)}catch(e){pW.error(`GenAI tenant switch failed`,{error:e instanceof Error?e.message:String(e)}),s(`Failed to switch tenant`)}finally{mW=null,a(!1)}})()},[e,t,r,n]),{isSwitching:i,switchError:o,hasToken:c}}function _W(e=!1){let{isLoggingIn:t,loginError:n,loginToken:r,genaiInit:i}=dW(e),{isSwitching:a,switchError:o,hasToken:s}=gW(r,i?.tenantId,e);return{isAuthenticating:t||a,authError:n??o,hasToken:s}}function vW(e={}){let{defaultOpen:t=!1,persist:n=!0}=e,[r,i]=Wt({key:n?RT.PANEL_OPEN:`panel-state-${Date.now()}`,defaultValue:t,getInitialValueInEffect:!1}),a=(0,H.useRef)(!1);return(0,H.useEffect)(()=>{r&&!a.current&&e.onOpen&&(a.current=!0,e.onOpen())},[r,e.onOpen]),(0,H.useEffect)(()=>{let e=document.querySelector(`main`)||document.querySelector(`.main-content`)||document.body;return r?e?.classList.add(`panel-open`):(e?.classList.remove(`panel-open`),e?.style.removeProperty(`margin-right`)),()=>{e?.classList.remove(`panel-open`),e?.style.removeProperty(`margin-right`)}},[r]),{isOpen:r,open:(0,H.useCallback)(async()=>{i(!0),e.onOpen&&!a.current&&(a.current=!0,await e.onOpen())},[i,e.onOpen]),close:(0,H.useCallback)(()=>{i(!1)},[i]),toggle:(0,H.useCallback)(()=>{i(e=>!e)},[i]),setOpen:(0,H.useCallback)(e=>{i(e)},[i])}}function yW({runtime:e,uiOptions:t}){let n=e.forceReAuth,{isAuthenticating:r,hasToken:i}=_W(n),{panelWidth:a,panelHeight:o,panelHeaderHeight:s,panelTopOffset:c,panelBorder:l,panelBorderRadius:u,zIndex:d,fabPosition:f}=rW(t),p=(0,H.useRef)(!1),m=(0,H.useRef)(!1),[h,g]=(0,H.useState)(!1),{messages:_,composerText:v,setComposerText:y,isLoading:b,error:x,sendMessage:S,sendInitialMessage:C,agentDisplayName:w,canSend:T}=qU(),{actions:E,handleActionClick:D}=JU(_,y),{runtimeInfo:O,refreshRuntimeInfo:k}=QU(),{isOpen:A,open:j,close:M}=vW({defaultOpen:!1,persist:!0,onOpen:async()=>{p.current||(p.current=!0,await k()),m.current||g(!0)}});(0,H.useEffect)(()=>{(async()=>{h&&A&&!r&&i&&await C()&&(m.current=!0,g(!1))})()},[A,r,i,C,h]);let N=oW([_.length,b]),{isListening:P,isSupported:ee,startListening:F,stopListening:I,reset:te}=eW({lang:$U(),continuous:!0,pauseOnSubmit:!0,onTextChange:y}),{panelResizableWidth:ne,actualWidth:re,shellGap:ie,floatingTop:L,floatingHeight:ae,floatingMaxHeight:oe}=ZU(t,a,A,o,c),{handleSubmit:se,handleToggleVoice:ce,handleClose:le}=iW({isListening:P,stopListening:I,reset:te,sendMessage:S,composerText:v,setComposerText:y,startListening:F,close:M});return(0,U.jsxs)(U.Fragment,{children:[!A&&(0,U.jsx)(BM,{onClick:()=>void j(),zIndex:d,position:f,label:w}),A&&(0,U.jsx)(dU,{visible:!0,onClose:le,messages:_,composerText:v,onComposerTextChange:y,isLoading:b,error:x,canSend:T,onSubmit:se,actions:E,onActionClick:D,isListening:P,isVoiceSupported:ee,onToggleVoice:ce,panelTitle:w,runtimeInfo:O,scrollViewportRef:N,actualWidth:re,floatingTop:L,floatingHeight:ae,floatingMaxHeight:oe,shellGap:ie,panelHeaderHeight:s,panelResizableWidth:ne,panelBorder:l,panelBorderRadius:u,zIndex:d})]})}function bW(e){return(0,U.jsx)(yW,{...e})}function xW(e,t){if(typeof e==`function`){e(t);return}e&&(e.current=t)}function SW(e){return{url:{app:e.app??``,api:e.api??``,apiPaths:{crm:``,uiAuthz:``}},keycloak:{url:``,realm:``,clientId:``},features:{enableThemeManager:!0}}}var CW=(0,H.forwardRef)((e,t)=>{let{config:n,runtime:r,uiOptions:i,className:a,style:o,rootElement:s}=e,c=(0,H.useRef)(null),l=SW(n);Pe.locale||Pe.activate(`en`),EE(l,n);let u=(0,H.useMemo)(()=>CM({themeName:i?.themeName}),[i?.themeName]);return(0,U.jsx)(PM,{appConfig:l,config:n,runtime:r,theme:(0,H.useMemo)(()=>i?.theme?Vr(u,i.theme):u,[i?.theme,u]),rootElement:s??c.current,children:(0,U.jsx)(`div`,{className:a,ref:e=>{c.current=e,xW(t,e)},style:o,children:(0,U.jsx)(bW,{config:n,runtime:r,uiOptions:i})})})});CW.displayName=`Widget`;var wW=`:root,
403
403
  :host {
404
404
  color-scheme: var(--mantine-color-scheme);
405
405
  }