@runtypelabs/persona 3.9.2 → 3.10.1
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/index.cjs +45 -42
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +148 -0
- package/dist/index.d.ts +148 -0
- package/dist/index.global.js +67 -64
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +45 -42
- package/dist/index.js.map +1 -1
- package/dist/theme-editor.cjs +959 -214
- package/dist/theme-editor.d.cts +157 -3
- package/dist/theme-editor.d.ts +157 -3
- package/dist/theme-editor.js +955 -214
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +8 -0
- package/dist/theme-reference.d.ts +8 -0
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +154 -0
- package/package.json +1 -1
- package/src/client.test.ts +312 -1
- package/src/client.ts +247 -24
- package/src/components/messages.ts +1 -1
- package/src/components/reasoning-bubble.ts +117 -28
- package/src/components/tool-bubble.ts +161 -27
- package/src/defaults.ts +12 -0
- package/src/styles/widget.css +154 -0
- package/src/theme-editor/index.ts +5 -0
- package/src/theme-editor/preview-utils.test.ts +58 -0
- package/src/theme-editor/preview-utils.ts +220 -4
- package/src/theme-editor/sections.test.ts +20 -0
- package/src/theme-editor/sections.ts +10 -0
- package/src/theme-reference.ts +8 -3
- package/src/tool-call-display-defaults.test.ts +23 -0
- package/src/types.ts +155 -0
- package/src/ui.attachments-drop.test.ts +188 -0
- package/src/ui.scroll.test.ts +150 -0
- package/src/ui.tool-display.test.ts +204 -0
- package/src/ui.ts +275 -7
- package/src/utils/message-fingerprint.test.ts +17 -0
- package/src/utils/message-fingerprint.ts +13 -1
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
1
|
+
"use strict";var Mp=Object.create;var gs=Object.defineProperty;var kp=Object.getOwnPropertyDescriptor;var Lp=Object.getOwnPropertyNames;var Ip=Object.getPrototypeOf,Pp=Object.prototype.hasOwnProperty;var Wp=(e,r)=>{for(var t in r)gs(e,t,{get:r[t],enumerable:!0})},Hc=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Lp(r))!Pp.call(e,s)&&s!==t&&gs(e,s,{get:()=>r[s],enumerable:!(n=kp(r,s))||n.enumerable});return e};var Bc=(e,r,t)=>(t=e!=null?Mp(Ip(e)):{},Hc(r||!e||!e.__esModule?gs(t,"default",{value:e,enumerable:!0}):t,e)),Rp=e=>Hc(gs({},"__esModule",{value:!0}),e);var Rm={};Wp(Rm,{AgentWidgetClient:()=>jr,AgentWidgetSession:()=>co,AttachmentManager:()=>Ur,DEFAULT_COMPONENTS:()=>da,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ts,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Pn,DEFAULT_PALETTE:()=>la,DEFAULT_SEMANTIC:()=>ca,DEFAULT_WIDGET_CONFIG:()=>kt,PRESETS:()=>Va,PRESET_FULLSCREEN:()=>qa,PRESET_MINIMAL:()=>za,PRESET_SHOP:()=>ja,THEME_ZONES:()=>ld,VERSION:()=>Xr,accessibilityPlugin:()=>yp,animationsPlugin:()=>bp,applyThemeVariables:()=>Ar,attachHeaderToContainer:()=>Jr,brandPlugin:()=>xp,buildComposer:()=>mo,buildDefaultHeader:()=>fa,buildHeader:()=>pr,buildHeaderWithLayout:()=>uo,buildMinimalHeader:()=>ha,collectEnrichedPageContext:()=>tp,componentRegistry:()=>ur,createActionManager:()=>Qo,createAgentExperience:()=>Js,createBestAvailableVoiceProvider:()=>As,createBubbleWithLayout:()=>vd,createCSATFeedback:()=>qs,createComboButton:()=>Bs,createComponentMiddleware:()=>Nd,createComponentStreamParser:()=>$s,createDefaultSanitizer:()=>sa,createDemoCarousel:()=>hp,createDirectivePostprocessor:()=>$c,createDropdownMenu:()=>Mr,createFlexibleJsonStreamParser:()=>Vc,createIconButton:()=>Pt,createImagePart:()=>Zc,createJsonStreamParser:()=>bs,createLabelButton:()=>Jo,createLocalStorageAdapter:()=>Os,createMarkdownProcessor:()=>Bo,createMarkdownProcessorFromConfig:()=>$r,createMessageActions:()=>xa,createNPSFeedback:()=>Vs,createPlainTextParser:()=>hs,createPlugin:()=>wp,createRegexJsonParser:()=>ys,createStandardBubble:()=>go,createTextPart:()=>Do,createTheme:()=>po,createThemeObserver:()=>Is,createToggleGroup:()=>Yo,createTypingIndicator:()=>Yr,createVoiceProvider:()=>Vr,createWidgetHostLayout:()=>es,createXmlParser:()=>xs,default:()=>Wm,defaultActionHandlers:()=>Gr,defaultJsonActionParser:()=>Zo,defaultParseRules:()=>Fa,detectColorScheme:()=>_o,directivePostprocessor:()=>_c,escapeHtml:()=>so,extractComponentDirectiveFromMessage:()=>zs,fileToImagePart:()=>Qc,formatEnrichedContext:()=>np,generateAssistantMessageId:()=>zr,generateCodeSnippet:()=>cp,generateMessageId:()=>Jc,generateStableSelector:()=>Oa,generateUserMessageId:()=>lo,getActiveTheme:()=>jo,getColorScheme:()=>ua,getDisplayText:()=>Gc,getHeaderLayout:()=>ya,getImageParts:()=>Kc,getPreset:()=>Ap,hasComponentDirective:()=>js,hasImages:()=>Xc,headerLayouts:()=>Ds,highContrastPlugin:()=>Cp,initAgentWidget:()=>Ha,isComponentDirectiveType:()=>Dd,isDockedMountMode:()=>Xt,isVoiceSupported:()=>Fo,markdownPostprocessor:()=>oa,mergeWithDefaults:()=>Ms,normalizeContent:()=>Yc,pluginRegistry:()=>Ko,reducedMotionPlugin:()=>vp,renderComponentDirective:()=>_s,renderLoadingIndicatorWithFallback:()=>ba,resolveDockConfig:()=>Fn,resolveSanitizer:()=>ao,resolveTokens:()=>ks,themeToCssVariables:()=>Ls,validateImageFile:()=>ed,validateTheme:()=>pa});module.exports=Rp(Rm);var Nc=require("marked"),Hp=e=>{if(e)return e},Bo=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new Nc.Marked({gfm:(s=r==null?void 0:r.gfm)!=null?s:!0,breaks:(o=r==null?void 0:r.breaks)!=null?o:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=Hp(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},$r=e=>e?Bo({markedOptions:e.options,renderer:e.renderer}):Bo(),Bp=Bo(),oa=e=>Bp(e),so=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Fc=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Dc=e=>`%%FORM_PLACEHOLDER_${e}%%`,Oc=(e,r)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Dc(r.length);return r.push({token:a,type:String(o.type)}),a}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,s)=>{let o=Dc(r.length);return r.push({token:o,type:s}),o}),t},$c=e=>{let r=$r(e);return t=>{let n=[],s=Oc(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let u=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Fc(i)}"></div>`;o=o.replace(u,d)}),o}},_c=e=>{let r=[],t=Oc(e,r),n=oa(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Fc(o)}"></div>`;n=n.replace(a,u)}),n};var jc=Bc(require("dompurify"),1),Dp={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Np=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,sa=()=>{let e=(0,jc.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(r,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!Np.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Dp)},ao=e=>e===!1?null:typeof e=="function"?e:sa();var cr=require("partial-json"),fs=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),io=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Fp=e=>{var a,i;let r=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:r,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,r-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},zc=e=>e.status==="complete"?Fp(e):e.status==="pending"?"Waiting":"",Op=e=>{var s,o,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var qc=e=>e.status==="complete"?Op(e):"Using tool...",$p=()=>{let e=null,r=0,t=n=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=n.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},rs=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},os=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ss=()=>{var r;let e=cp();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},as=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,sr.parse)(t,sr.STR|sr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?ns(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=ns(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},hc=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?ns(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?ns(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=(0,sr.parse)(o,sr.STR|sr.OBJ),d=s(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},is=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var dp="https://api.runtype.com/v1/dispatch",qs="https://api.runtype.com",Js=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function pp(e){switch(e){case"json":return as;case"regex-json":return ss;case"xml":return is;default:return os}}var Dr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:dp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:pp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||qs;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||qs}/v1/client/feedback`}async sendFeedback(r){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(r.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,u={sessionId:d.sessionId,messages:r.messages.filter(Js).map(m=>{var v,M,b;return{id:m.id,role:m.role,content:(b=(M=(v=m.contentParts)!=null?v:m.llmContent)!=null?M:m.rawContent)!=null?b:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:n.signal});if(!f.ok){let m=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}if(f.status===429){let M=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:M}),M}let v=new Error(m.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!f.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||qs}/v1/agents/${r.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(Js).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(Js).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return n.current=u,s(u),u},c=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt,Ne,le,Ie,At,Et,Ze,Qe,Kt,Gt,Zt,O,Le,ue,at,Be,Z,ye,Pe,dt,Ot,nt,$t,it,qe,lt,_e,_t,Un,Xn,Dn,Xe,Mr,Vn,kr,kn,Vr,dr,Kn,et,xn,Fn,an,pr,vn,ft,ln,Ln,ur,Zn,gr,qn,Cn,Jn,ht,Wt,Rt,wn,mr,Nn,Sn,D,On,In,fr,gn,An,te,$n,qr,fo,Jr,Je,ho,Pn,mn,Yo,Go,yo,Qn,Xo,Yr,Gr,er,bo,hr,yr,Ko,Zo,zs,Lr,Ir,Tt,Xr,Kr,xo,vo,Co,wo,cn,En,tr,je,So,Pr,_n;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=X=>{let Ye=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,pt=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,It=X.tools?X.tools.map(Pt=>({...Pt,chunks:Pt.chunks?[...Pt.chunks]:void 0})):void 0;return{...X,reasoning:Ye,toolCall:pt,tools:It}},u=X=>{t({type:"message",message:p(X)})},f=null,m={current:null},v={current:null},M=!1,b=new Map,C=new Map,S={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},w=X=>{if(X==null)return null;try{return String(X)}catch{return null}},L=X=>{var Ye,pt,It,Pt,Qt;return w((Qt=(Pt=(It=(pt=(Ye=X.stepId)!=null?Ye:X.step_id)!=null?pt:X.step)!=null?It:X.parentId)!=null?Pt:X.flowStepId)!=null?Qt:X.flow_step_id)},B=X=>{var Ye,pt,It,Pt,Qt,Ht,x;return w((x=(Ht=(Qt=(Pt=(It=(pt=(Ye=X.callId)!=null?Ye:X.call_id)!=null?pt:X.requestId)!=null?It:X.request_id)!=null?Pt:X.toolCallId)!=null?Qt:X.tool_call_id)!=null?Ht:X.stepId)!=null?x:X.step_id)},T=n,Y=!1,ge=()=>{if(f)return f;let X;return!Y&&T?(X=T,Y=!0):T&&v.current?X=`${T}_${v.current}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:X,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(f),f},ce=(X,Ye)=>{S.lastId=Ye,X&&S.byStep.set(X,Ye)},$=(X,Ye)=>{var Qt;let pt=(Qt=X.reasoningId)!=null?Qt:X.id,It=L(X);if(pt){let Ht=String(pt);return ce(It,Ht),Ht}if(It){let Ht=S.byStep.get(It);if(Ht)return S.lastId=Ht,Ht}if(S.lastId&&!Ye)return S.lastId;if(!Ye)return null;let Pt=`reason-${c()}`;return ce(It,Pt),Pt},ne=X=>{let Ye=b.get(X);if(Ye)return Ye;let pt={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:X,status:"streaming",chunks:[]}};return b.set(X,pt),u(pt),pt},Te=(X,Ye)=>{R.lastId=Ye,X&&R.byCall.set(X,Ye)},re=new Set,Se=new Map,He=new Set,he=new Map,Me=X=>{if(!X)return!1;let Ye=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ye==="emit_artifact_markdown"||Ye==="emit_artifact_component"},ke=(X,Ye)=>{var Qt;let pt=(Qt=X.toolId)!=null?Qt:X.id,It=B(X);if(pt){let Ht=String(pt);return Te(It,Ht),Ht}if(It){let Ht=R.byCall.get(It);if(Ht)return R.lastId=Ht,Ht}if(R.lastId&&!Ye)return R.lastId;if(!Ye)return null;let Pt=`tool-${c()}`;return Te(It,Pt),Pt},oe=X=>{let Ye=C.get(X);if(Ye)return Ye;let pt={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:X,status:"pending"}};return C.set(X,pt),u(pt),pt},be=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let Ye=Number(X);if(!Number.isNaN(Ye)&&Number.isFinite(Ye))return Ye;let pt=Date.parse(X);if(!Number.isNaN(pt))return pt}return Date.now()},$e=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},pe=new Map,de=new Map,se=null,De=new Map,ot=(St=this.config.iterationDisplay)!=null?St:"separate";for(;;){let{done:X,value:Ye}=await s.read();if(X)break;a+=o.decode(Ye,{stream:!0});let pt=a.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},_r=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},hs=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ys=()=>{var r;let e=$p();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},bs=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,cr.parse)(t,cr.STR|cr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?fs(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=fs(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Vc=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?fs(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?fs(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=(0,cr.parse)(o,cr.STR|cr.OBJ),u=s(i);u!==null&&(r=u)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},xs=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var _p="https://api.runtype.com/v1/dispatch",aa="https://api.runtype.com",ia=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function jp(e){switch(e){case"json":return bs;case"regex-json":return ys;case"xml":return xs;default:return hs}}var Uc=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function zp(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let s=Uc(t);if(!Uc(n))return e;if(!s||n===t||n.startsWith(t))return r;let a=_r(e);return _r(r)!==null&&a===null?r:e}var jr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:_p,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:jp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||aa;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||aa}/v1/client/feedback`}async sendFeedback(r){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let f=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:f}),f}let c=await this.buildPayload(r.messages),d=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,p={sessionId:u.sessionId,messages:r.messages.filter(ia).map(f=>{var v,E,x;return{id:f.id,role:f.role,content:(x=(E=(v=f.contentParts)!=null?v:f.llmContent)!=null?E:f.rawContent)!=null?x:f.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let g=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:n.signal});if(!g.ok){let f=await g.json().catch(()=>({error:"Chat request failed"}));if(g.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let E=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:E}),E}if(g.status===429){let E=new Error(f.hint||"Message limit reached for this session.");throw t({type:"error",error:E}),E}let v=new Error(f.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!g.body){let f=new Error("No response body received");throw t({type:"error",error:f}),f}t({type:"status",status:"connected"});try{await this.streamResponse(g.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||aa}/v1/agents/${r.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(ia).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(ia).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let u=d=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...d!==void 0&&{partId:d}};return n.current=p,s(p),p},c=d=>n.current?n.current:u(d);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),u(i.partId)),i.partId!==void 0&&(a.current=i.partId);let d=c(i.partId);i.partId!==void 0&&!d.partId&&(d.partId=i.partId),d.content+=i.text,s(d)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var V,oe,Oe,Z,te,Lt,lt,Nt,Kt,$e,ce,He,Wt,Rt,ot,st,rn,tn,on,j,Ie,ue,gt,Fe,ne,ye,De,xt,zt,ct,qt,ft,Ke,ht,We,Vt,Gn,tr,$n,Qe,Lr,Xn,Ir,Wn,Kr,gr,nr,at,wn,_n,dn,fr,Sn,wt,pn,Rn,hr,rr,yr,Kn,An,Zn,vt,$t,_t,En,br,jn,Tn,D,zn,Hn,xr,gn,Mn,ee,qn,or,ts,vo,Zr,Ze,Co,Bn,fn,ns,rs,wo,sr,os,Qr,So,ar,Ao,vr,Cr,ss,as,ta,Pr,Wr,Ht,eo,to,Eo,To,Mo,ko,un,kn,ir,qe,Lo,Rr,Vn,is,no,ro,Hr,wr;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,d=X=>{let Ve=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,_e=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,Tt=X.tools?X.tools.map(yt=>({...yt,chunks:yt.chunks?[...yt.chunks]:void 0})):void 0;return{...X,reasoning:Ve,toolCall:_e,tools:Tt}},p=X=>{t({type:"message",message:d(X)})},g=null,f={current:null},v={current:null},E=!1,x=new Map,C=new Map,k={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},w=X=>{if(X==null)return null;try{return String(X)}catch{return null}},M=X=>{var Ve,_e,Tt,yt,St;return w((St=(yt=(Tt=(_e=(Ve=X.stepId)!=null?Ve:X.step_id)!=null?_e:X.step)!=null?Tt:X.parentId)!=null?yt:X.flowStepId)!=null?St:X.flow_step_id)},W=X=>{var Ve,_e,Tt,yt,St,et,y;return w((y=(et=(St=(yt=(Tt=(_e=(Ve=X.callId)!=null?Ve:X.call_id)!=null?_e:X.requestId)!=null?Tt:X.request_id)!=null?yt:X.toolCallId)!=null?St:X.tool_call_id)!=null?et:X.stepId)!=null?y:X.step_id)},T=n,G=!1,K=()=>{if(g)return g;let X;return!G&&T?(X=T,G=!0):T&&v.current?X=`${T}_${v.current}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:X,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(g),g},J=(X,Ve)=>{k.lastId=Ve,X&&k.byStep.set(X,Ve)},I=(X,Ve)=>{var St;let _e=(St=X.reasoningId)!=null?St:X.id,Tt=M(X);if(_e){let et=String(_e);return J(Tt,et),et}if(Tt){let et=k.byStep.get(Tt);if(et)return k.lastId=et,et}if(k.lastId&&!Ve)return k.lastId;if(!Ve)return null;let yt=`reason-${c()}`;return J(Tt,yt),yt},Q=X=>{let Ve=x.get(X);if(Ve)return Ve;let _e={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:X,status:"streaming",chunks:[]}};return x.set(X,_e),p(_e),_e},Ce=(X,Ve)=>{H.lastId=Ve,X&&H.byCall.set(X,Ve)},re=new Set,Ae=new Map,Ne=new Set,he=new Map,ke=X=>{if(!X)return!1;let Ve=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ve==="emit_artifact_markdown"||Ve==="emit_artifact_component"},Le=(X,Ve)=>{var St;let _e=(St=X.toolId)!=null?St:X.id,Tt=W(X);if(_e){let et=String(_e);return Ce(Tt,et),et}if(Tt){let et=H.byCall.get(Tt);if(et)return H.lastId=et,et}if(H.lastId&&!Ve)return H.lastId;if(!Ve)return null;let yt=`tool-${c()}`;return Ce(Tt,yt),yt},ae=X=>{let Ve=C.get(X);if(Ve)return Ve;let _e={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:X,status:"pending"}};return C.set(X,_e),p(_e),_e},xe=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let Ve=Number(X);if(!Number.isNaN(Ve)&&Number.isFinite(Ve))return Ve;let _e=Date.parse(X);if(!Number.isNaN(_e))return _e}return Date.now()},je=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},de=new Map,ie=new Map,Ee=new Map,Be=new Map;function it(X,Ve,_e,Tt){let yt=X.get(Ve);yt||(yt=[],X.set(Ve,yt));let St=0,et=yt.length;for(;St<et;){let se=St+et>>>1;yt[se].seq<_e?St=se+1:et=se}yt.splice(St,0,{seq:_e,text:Tt});let y="";for(let se=0;se<yt.length;se++)y+=yt[se].text;return y}let Et=null,q=(X,Ve)=>{let _e=je(Ve),Tt=ie.get(X.id),yt=zp(Tt,_e);X.rawContent=yt;let St=de.get(X.id),et=Y=>{var pe;let N=(pe=X.content)!=null?pe:"";Y.trim()!==""&&(N.trim().length===0||Y.startsWith(N)||Y.trimStart().startsWith(N.trim()))&&(X.content=Y)},y=()=>{var Y;if(St){let N=(Y=St.close)==null?void 0:Y.call(St);N instanceof Promise&&N.catch(()=>{})}de.delete(X.id),ie.delete(X.id),X.streaming=!1,p(X)};if(!St){et(_e),y();return}let se=_r(yt);if(se!==null&&se.trim()!==""){et(se),y();return}let P=Y=>{var Ye;let N=typeof Y=="string"?Y:(Ye=Y==null?void 0:Y.text)!=null?Ye:null;if(N!==null&&N.trim()!=="")return N;let pe=St.getExtractedText();return pe!==null&&pe.trim()!==""?pe:_e},S;try{S=St.processChunk(yt)}catch{et(_e),y();return}if(S instanceof Promise){S.then(Y=>{et(P(Y)),y()}).catch(()=>{et(_e),y()});return}et(P(S)),y()},F=null,le=new Map,_=(V=this.config.iterationDisplay)!=null?V:"separate";for(;;){let{done:X,value:Ve}=await s.read();if(X)break;a+=o.decode(Ve,{stream:!0});let _e=a.split(`
|
|
5
5
|
|
|
6
|
-
`);a=(
|
|
7
|
-
`),Qt="message",Ht="";for(let I of Pt)I.startsWith("event:")?Qt=I.replace("event:","").trim():I.startsWith("data:")&&(Ht+=I.replace("data:","").trim());if(!Ht)continue;let x;try{x=JSON.parse(Ht)}catch(I){t({type:"error",error:I instanceof Error?I:new Error("Failed to parse chat stream payload")});continue}let We=Qt!=="message"?Qt:(q=x.type)!=null?q:"message";if((ae=this.onSSEEvent)==null||ae.call(this,We,x),this.parseSSEEvent){m.current=f;let I=await this.handleCustomSSEEvent(x,t,m,u,c,v);if(m.current&&m.current!==f&&(f=m.current),I)continue}if(We==="reason_start"){let I=(_=$(x,!0))!=null?_:`reason-${c()}`,A=ne(I);A.reasoning=(z=A.reasoning)!=null?z:{id:I,status:"streaming",chunks:[]},A.reasoning.startedAt=(Fe=A.reasoning.startedAt)!=null?Fe:be((ee=x.startedAt)!=null?ee:x.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",u(A)}else if(We==="reason_delta"||We==="reason_chunk"){let I=(K=(J=$(x,!1))!=null?J:$(x,!0))!=null?K:`reason-${c()}`,A=ne(I);A.reasoning=(vt=A.reasoning)!=null?vt:{id:I,status:"streaming",chunks:[]},A.reasoning.startedAt=(Lt=A.reasoning.startedAt)!=null?Lt:be((tt=x.startedAt)!=null?tt:x.timestamp);let G=(le=(Ne=(Vt=x.reasoningText)!=null?Vt:x.text)!=null?Ne:x.delta)!=null?le:"";if(G&&x.hidden!==!0&&A.reasoning.chunks.push(String(G)),A.reasoning.status=x.done?"complete":"streaming",x.done){A.reasoning.completedAt=be((Ie=x.completedAt)!=null?Ie:x.timestamp);let N=(At=A.reasoning.startedAt)!=null?At:Date.now();A.reasoning.durationMs=Math.max(0,((Et=A.reasoning.completedAt)!=null?Et:Date.now())-N)}A.streaming=A.reasoning.status!=="complete",u(A)}else if(We==="reason_complete"){let I=(Qe=(Ze=$(x,!1))!=null?Ze:$(x,!0))!=null?Qe:`reason-${c()}`,A=b.get(I);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=be((Kt=x.completedAt)!=null?Kt:x.timestamp);let N=(Gt=A.reasoning.startedAt)!=null?Gt:Date.now();A.reasoning.durationMs=Math.max(0,((Zt=A.reasoning.completedAt)!=null?Zt:Date.now())-N),A.streaming=!1,u(A)}let G=L(x);G&&S.byStep.delete(G)}else if(We==="tool_start"){let I=(O=ke(x,!0))!=null?O:`tool-${c()}`,A=(Le=x.toolName)!=null?Le:x.name;if(Me(A)){re.add(I);continue}let G=oe(I),N=(ue=G.toolCall)!=null?ue:{id:I,status:"pending"};N.name=A!=null?A:N.name,N.status="running",x.args!==void 0?N.args=x.args:x.parameters!==void 0&&(N.args=x.parameters),N.startedAt=(Be=N.startedAt)!=null?Be:be((at=x.startedAt)!=null?at:x.timestamp),N.completedAt=void 0,N.durationMs=void 0,G.toolCall=N,G.streaming=!0;let Q=x.agentContext;(Q||x.executionId)&&(G.agentMetadata={executionId:(Z=Q==null?void 0:Q.executionId)!=null?Z:x.executionId,iteration:(ye=Q==null?void 0:Q.iteration)!=null?ye:x.iteration}),u(G)}else if(We==="tool_chunk"||We==="tool_delta"){let I=(dt=(Pe=ke(x,!1))!=null?Pe:ke(x,!0))!=null?dt:`tool-${c()}`;if(re.has(I))continue;let A=oe(I),G=(Ot=A.toolCall)!=null?Ot:{id:I,status:"running"};G.startedAt=($t=G.startedAt)!=null?$t:be((nt=x.startedAt)!=null?nt:x.timestamp);let N=(lt=(qe=(it=x.text)!=null?it:x.delta)!=null?qe:x.message)!=null?lt:"";N&&(G.chunks=(_e=G.chunks)!=null?_e:[],G.chunks.push(String(N))),G.status="running",A.toolCall=G,A.streaming=!0;let Q=x.agentContext;(Q||x.executionId)&&(A.agentMetadata=(Xn=A.agentMetadata)!=null?Xn:{executionId:(_t=Q==null?void 0:Q.executionId)!=null?_t:x.executionId,iteration:(Un=Q==null?void 0:Q.iteration)!=null?Un:x.iteration}),u(A)}else if(We==="tool_complete"){let I=(Xe=(Dn=ke(x,!1))!=null?Dn:ke(x,!0))!=null?Xe:`tool-${c()}`;if(re.has(I)){re.delete(I);continue}let A=oe(I),G=(Mr=A.toolCall)!=null?Mr:{id:I,status:"running"};G.status="complete",x.result!==void 0&&(G.result=x.result),typeof x.duration=="number"&&(G.duration=x.duration),G.completedAt=be((Vn=x.completedAt)!=null?Vn:x.timestamp);let N=(kr=x.duration)!=null?kr:x.executionTime;if(typeof N=="number")G.durationMs=N;else{let Mt=(kn=G.startedAt)!=null?kn:Date.now();G.durationMs=Math.max(0,((Vr=G.completedAt)!=null?Vr:Date.now())-Mt)}A.toolCall=G,A.streaming=!1;let Q=x.agentContext;(Q||x.executionId)&&(A.agentMetadata=(et=A.agentMetadata)!=null?et:{executionId:(dr=Q==null?void 0:Q.executionId)!=null?dr:x.executionId,iteration:(Kn=Q==null?void 0:Q.iteration)!=null?Kn:x.iteration}),u(A);let ut=B(x);ut&&R.byCall.delete(ut)}else if(We==="text_start"){let I=x.partId;if(I!==void 0&&v.current!==null&&I!==v.current){let A=f;A&&(A.streaming=!1,u(A),f=null,M=!0)}I!==void 0&&(v.current=I)}else if(We==="text_end"){let I=f;I&&(I.streaming=!1,u(I),f=null,M=!0)}else if(We==="step_chunk"||We==="step_delta"){let I=x.stepType,A=x.executionType;if(I==="tool"||A==="context")continue;let G=x.partId;if(G!==void 0&&v.current!==null&&G!==v.current){let ut=f;ut&&(ut.streaming=!1,u(ut),f=null,M=!0)}G!==void 0&&(v.current=G);let N=ge();G!==void 0&&!N.partId&&(N.partId=G);let Q=(pr=(an=(Fn=(xn=x.text)!=null?xn:x.delta)!=null?Fn:x.content)!=null?an:x.chunk)!=null?pr:"";if(Q){let Mt=((vn=de.get(N.id))!=null?vn:"")+Q;N.rawContent=Mt,pe.has(N.id)||pe.set(N.id,this.createStreamParser());let Bt=pe.get(N.id),en=Mt.trim().startsWith("{")||Mt.trim().startsWith("[");if(en&&de.set(N.id,Mt),Bt.__isPlainTextParser===!0){N.content+=Q,de.delete(N.id),pe.delete(N.id),N.rawContent=void 0,u(N);continue}let tn=Bt.processChunk(Mt);if(tn instanceof Promise)tn.then(Ae=>{var yt;let Ct=typeof Ae=="string"?Ae:(yt=Ae==null?void 0:Ae.text)!=null?yt:null;if(Ct!==null&&Ct.trim()!==""){let bt=f;bt&&bt.id===N.id&&(bt.content=Ct,u(bt))}else if(!en&&!Mt.trim().startsWith("<")){let bt=f;bt&&bt.id===N.id&&(bt.content+=Q,de.delete(bt.id),pe.delete(bt.id),bt.rawContent=void 0,u(bt))}}).catch(()=>{N.content+=Q,de.delete(N.id),pe.delete(N.id),N.rawContent=void 0,u(N)});else{let Ae=typeof tn=="string"?tn:(ft=tn==null?void 0:tn.text)!=null?ft:null;Ae!==null&&Ae.trim()!==""?(N.content=Ae,u(N)):!en&&!Mt.trim().startsWith("<")&&(N.content+=Q,de.delete(N.id),pe.delete(N.id),N.rawContent=void 0,u(N))}}if(x.isComplete){let ut=(Ln=(ln=x.result)==null?void 0:ln.response)!=null?Ln:N.content;if(ut){let Mt=de.get(N.id),Bt=Mt!=null?Mt:$e(ut);N.rawContent=Bt;let en=pe.get(N.id),qt=null,tn=!1;if(en&&(qt=en.getExtractedText(),qt===null&&(qt=rs(Bt)),qt===null)){let Ae=en.processChunk(Bt);Ae instanceof Promise?(tn=!0,Ae.then(Ct=>{var bt;let yt=typeof Ct=="string"?Ct:(bt=Ct==null?void 0:Ct.text)!=null?bt:null;if(yt!==null){let Dt=f;Dt&&Dt.id===N.id&&(Dt.content=yt,Dt.streaming=!1,pe.delete(Dt.id),de.delete(Dt.id),u(Dt))}})):qt=typeof Ae=="string"?Ae:(ur=Ae==null?void 0:Ae.text)!=null?ur:null}if(!tn){qt!==null&&qt.trim()!==""?N.content=qt:de.has(N.id)||(N.content=$e(ut));let Ae=pe.get(N.id);if(Ae){let Ct=(Zn=Ae.close)==null?void 0:Zn.call(Ae);Ct instanceof Promise&&Ct.catch(()=>{}),pe.delete(N.id)}de.delete(N.id),N.streaming=!1,u(N)}}}}else if(We==="step_complete"){let I=x.stepType,A=x.executionType;if(I==="tool"||A==="context")continue;if(M){if(f!==null){let Q=f;pe.delete(Q.id),de.delete(Q.id),Q.streaming!==!1&&(Q.streaming=!1,u(Q))}continue}let G=(gr=x.result)==null?void 0:gr.response,N=ge();if(G!=null){let Q=pe.get(N.id),ut=!1,Mt=!1;if(Q){let Bt=Q.getExtractedText(),en=de.get(N.id),qt=en!=null?en:$e(G);if(N.rawContent=qt,Bt!==null&&Bt.trim()!=="")N.content=Bt,ut=!0;else{let tn=rs(qt);if(tn!==null)N.content=tn,ut=!0;else{let Ae=Q.processChunk(qt);if(Ae instanceof Promise)Mt=!0,Ae.then(Ct=>{var bt;let yt=typeof Ct=="string"?Ct:(bt=Ct==null?void 0:Ct.text)!=null?bt:null;if(yt!==null&&yt.trim()!==""){let Dt=f;Dt&&Dt.id===N.id&&(Dt.content=yt,Dt.streaming=!1,pe.delete(Dt.id),de.delete(Dt.id),u(Dt))}else{let Dt=Q.getExtractedText(),Wn=f;Wn&&Wn.id===N.id&&(Dt!==null&&Dt.trim()!==""?Wn.content=Dt:de.has(Wn.id)||(Wn.content=$e(G)),Wn.streaming=!1,pe.delete(Wn.id),de.delete(Wn.id),u(Wn))}});else{let Ct=typeof Ae=="string"?Ae:(qn=Ae==null?void 0:Ae.text)!=null?qn:null;if(Ct!==null&&Ct.trim()!=="")N.content=Ct,ut=!0;else{let yt=Q.getExtractedText();yt!==null&&yt.trim()!==""&&(N.content=yt,ut=!0)}}}}}if(!Mt){if(!N.rawContent){let Bt=de.get(N.id);N.rawContent=Bt!=null?Bt:$e(G)}if(!ut&&!de.has(N.id)&&(N.content=$e(G)),Q){let Bt=(Cn=Q.close)==null?void 0:Cn.call(Q);Bt instanceof Promise&&Bt.catch(()=>{})}pe.delete(N.id),de.delete(N.id),N.streaming=!1,u(N)}}else pe.delete(N.id),de.delete(N.id),N.streaming=!1,u(N)}else if(We==="flow_complete"){let I=(Jn=x.result)==null?void 0:Jn.response;if(M){if(f!==null){let A=f;pe.delete(A.id),de.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}}else if(I!=null){let A=ge(),G=de.get(A.id),N=G!=null?G:$e(I);A.rawContent=N;let Q=$e(I),ut=pe.get(A.id);if(ut){let en=rs(N);if(en!==null)Q=en;else{let qt=ut.processChunk(N);qt instanceof Promise&&qt.then(Ae=>{var yt;let Ct=typeof Ae=="string"?Ae:(yt=Ae==null?void 0:Ae.text)!=null?yt:null;if(Ct!==null){let bt=f;bt&&bt.id===A.id&&(bt.content=Ct,bt.streaming=!1,u(bt))}});let tn=ut.getExtractedText();tn!==null&&(Q=tn)}}pe.delete(A.id),de.delete(A.id);let Mt=Q!==A.content,Bt=A.streaming!==!1;Mt&&(A.content=Q),A.streaming=!1,(Mt||Bt)&&u(A)}else if(f!==null){let A=f;pe.delete(A.id),de.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}t({type:"status",status:"idle"})}else if(We==="agent_start")se={executionId:x.executionId,agentId:(ht=x.agentId)!=null?ht:"virtual",agentName:(Wt=x.agentName)!=null?Wt:"",status:"running",currentIteration:0,maxTurns:(Rt=x.maxTurns)!=null?Rt:1,startedAt:be(x.startedAt)};else if(We==="agent_iteration_start"){if(se&&(se.currentIteration=x.iteration),ot==="separate"&&x.iteration>1){let I=f;I&&(I.streaming=!1,u(I),De.set(x.iteration-1,I),f=null)}}else if(We!=="agent_turn_start"){if(We==="agent_turn_delta"){if(x.contentType==="text"){let I=ge();I.content+=(wn=x.delta)!=null?wn:"",I.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:x.turnId,agentName:se==null?void 0:se.agentName},u(I)}else if(x.contentType==="thinking"){let I=(mr=x.turnId)!=null?mr:`agent-think-${x.iteration}`,A=ne(I);A.reasoning=(Nn=A.reasoning)!=null?Nn:{id:I,status:"streaming",chunks:[]},A.reasoning.chunks.push((Sn=x.delta)!=null?Sn:""),A.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:x.turnId},u(A)}else if(x.contentType==="tool_input"){let I=(D=x.toolCallId)!=null?D:R.lastId;if(I){let A=C.get(I);A!=null&&A.toolCall&&(A.toolCall.chunks=(On=A.toolCall.chunks)!=null?On:[],A.toolCall.chunks.push((In=x.delta)!=null?In:""),u(A))}}}else if(We==="agent_turn_complete"){let I=x.turnId;if(I){let A=b.get(I);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=be(x.completedAt);let G=(fr=A.reasoning.startedAt)!=null?fr:Date.now();A.reasoning.durationMs=Math.max(0,((gn=A.reasoning.completedAt)!=null?gn:Date.now())-G),A.streaming=!1,u(A)}}}else if(We==="agent_tool_start"){let I=(An=x.toolCallId)!=null?An:`agent-tool-${c()}`;Te(B(x),I);let A=oe(I),G=(te=A.toolCall)!=null?te:{id:I,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};G.name=(qr=($n=x.toolName)!=null?$n:x.name)!=null?qr:G.name,G.status="running",x.parameters!==void 0&&(G.args=x.parameters),G.startedAt=be((fo=x.startedAt)!=null?fo:x.timestamp),A.toolCall=G,A.streaming=!0,A.agentMetadata={executionId:x.executionId,iteration:x.iteration},u(A)}else if(We==="agent_tool_delta"){let I=(Jr=x.toolCallId)!=null?Jr:R.lastId;if(I){let A=(Je=C.get(I))!=null?Je:oe(I);A.toolCall&&(A.toolCall.chunks=(ho=A.toolCall.chunks)!=null?ho:[],A.toolCall.chunks.push((Pn=x.delta)!=null?Pn:""),A.toolCall.status="running",A.streaming=!0,u(A))}}else if(We==="agent_tool_complete"){let I=(mn=x.toolCallId)!=null?mn:R.lastId;if(I){let A=(Yo=C.get(I))!=null?Yo:oe(I);if(A.toolCall){A.toolCall.status="complete",x.result!==void 0&&(A.toolCall.result=x.result),typeof x.executionTime=="number"&&(A.toolCall.durationMs=x.executionTime),A.toolCall.completedAt=be((Go=x.completedAt)!=null?Go:x.timestamp),A.streaming=!1,u(A);let G=B(x);G&&R.byCall.delete(G)}}}else if(We!=="agent_iteration_complete"){if(We==="agent_reflection"||We==="agent_reflect"){let I=`agent-reflection-${x.executionId}-${x.iteration}`,A={id:I,role:"assistant",content:(yo=x.reflection)!=null?yo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:I,status:"complete",chunks:[(Qn=x.reflection)!=null?Qn:""]},agentMetadata:{executionId:x.executionId,iteration:x.iteration}};u(A)}else if(We==="agent_complete"){se&&(se.status=x.success?"complete":"error",se.completedAt=be(x.completedAt),se.stopReason=x.stopReason);let I=f;I&&(I.streaming=!1,u(I)),t({type:"status",status:"idle"})}else if(We==="agent_error"){let I=typeof x.error=="string"?x.error:(Yr=(Xo=x.error)==null?void 0:Xo.message)!=null?Yr:"Agent execution error";x.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",I):t({type:"error",error:new Error(I)})}else if(We!=="agent_ping")if(We==="agent_approval_start"){let I=(Gr=x.approvalId)!=null?Gr:`approval-${c()}`,A={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(er=se==null?void 0:se.agentId)!=null?er:"virtual",executionId:(hr=(bo=x.executionId)!=null?bo:se==null?void 0:se.executionId)!=null?hr:"",toolName:(yr=x.toolName)!=null?yr:"",toolType:x.toolType,description:(Zo=x.description)!=null?Zo:`Execute ${(Ko=x.toolName)!=null?Ko:"tool"}`,parameters:x.parameters}};u(A)}else if(We==="step_await"&&x.awaitReason==="approval_required"){let I=(zs=x.approvalId)!=null?zs:`approval-${c()}`,A={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(Lr=se==null?void 0:se.agentId)!=null?Lr:"virtual",executionId:(Tt=(Ir=x.executionId)!=null?Ir:se==null?void 0:se.executionId)!=null?Tt:"",toolName:(Xr=x.toolName)!=null?Xr:"",toolType:x.toolType,description:(xo=x.description)!=null?xo:`Execute ${(Kr=x.toolName)!=null?Kr:"tool"}`,parameters:x.parameters}};u(A)}else if(We==="agent_approval_complete"){let I=x.approvalId;if(I){let G={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:(vo=x.decision)!=null?vo:"approved",agentId:(Co=se==null?void 0:se.agentId)!=null?Co:"virtual",executionId:(cn=(wo=x.executionId)!=null?wo:se==null?void 0:se.executionId)!=null?cn:"",toolName:(En=x.toolName)!=null?En:"",description:(tr=x.description)!=null?tr:"",resolvedAt:Date.now()}};u(G)}}else if(We==="artifact_start"||We==="artifact_delta"||We==="artifact_update"||We==="artifact_complete"){if(We==="artifact_start"){let I=x.artifactType,A=String(x.id),G=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:A,artifactType:I,title:G,component:typeof x.component=="string"?x.component:void 0}),he.set(A,{markdown:"",title:G}),!He.has(A)){He.add(A);let N={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:G,artifactType:I,status:"streaming"}})};Se.set(A,N),u(N)}}else if(We==="artifact_delta"){let I=String(x.id),A=typeof x.delta=="string"?x.delta:String((je=x.delta)!=null?je:"");t({type:"artifact_delta",id:I,artDelta:A});let G=he.get(I);G&&(G.markdown+=A)}else if(We==="artifact_update"){let I=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:I,component:typeof x.component=="string"?x.component:void 0})}else if(We==="artifact_complete"){let I=String(x.id);t({type:"artifact_complete",id:I});let A=Se.get(I);if(A){A.streaming=!1;try{let G=JSON.parse((So=A.rawContent)!=null?So:"{}");if(G.props){G.props.status="complete";let N=he.get(I);N!=null&&N.markdown&&(G.props.markdown=N.markdown)}A.rawContent=JSON.stringify(G)}catch{}he.delete(I),u(A),Se.delete(I)}}}else if(We==="transcript_insert"){let I=x.message;if(!I||typeof I!="object")continue;let A=String((Pr=I.id)!=null?Pr:`msg-${c()}`),G=I.role,Q={id:A,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof I.content=="string"?I.content:"",rawContent:typeof I.rawContent=="string"?I.rawContent:void 0,createdAt:typeof I.createdAt=="string"?I.createdAt:new Date().toISOString(),streaming:I.streaming===!0,...typeof I.variant=="string"?{variant:I.variant}:{},sequence:c()};if(u(Q),Q.rawContent)try{let ut=JSON.parse(Q.rawContent),Mt=(_n=ut==null?void 0:ut.props)==null?void 0:_n.artifactId;typeof Mt=="string"&&He.add(Mt)}catch{}f=null,m.current=null,pe.delete(A),de.delete(A)}else We==="error"&&x.error&&t({type:"error",error:x.error instanceof Error?x.error:new Error(String(x.error))})}}}}}};function yc(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function ro(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Fr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var ls="[Image]";function bc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function xc(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function vc(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Cc(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function cs(e){return{type:"text",text:e}}function wc(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Sc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Ac(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${r.join(", ")}`}}var Ec=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],up=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],ar=[...Ec,...up];function gp(e){return Ec.includes(e)||e.startsWith("image/")}function ds(e){return gp(e.type)}async function Tc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;ds(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Mc(e,r=ar,t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${r.join(", ")}`}}function mp(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function kc(e,r){let t=mp(r).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var ps=class{constructor(r=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(r){this.finishedCallbacks.push(r)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var us=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(n==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Io=class{constructor(r){this.config=r;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new us;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,M=C=>{v||(v=!0,clearTimeout(b),m(new Error(C)))},b=setTimeout(()=>M("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(b),f())},{once:!0}),this.ws.addEventListener("error",()=>{M("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",C=>{if(!C.wasClean&&!v){let S=C.code!==1006?` (code ${C.code})`:"";M("WebSocket connection failed"+S+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ps(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,d=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Nr=class{constructor(r={}){this.config=r;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Or(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Io(e.runtype);case"browser":if(!Nr.isSupported())throw new Error("Browser speech recognition not supported");return new Nr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function gs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Or({type:"runtype",runtype:e.runtype});if(Nr.isSupported())return Or({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Po(e){try{return gs(e),!0}catch{return!1}}var oo=class e{constructor(r={},t){this.config=r;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,d;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Dr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return Po((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Or(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,u,f,m,v,M;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=c.transcript)!=null&&u.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let b=(M=this.pendingVoiceAssistantMessageId)!=null?M:(v=[...this.messages].reverse().find(C=>C.role==="assistant"))==null?void 0:v.id;b&&this.ttsSpokenMessageIds.add(b)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var p,u;this.voiceStatus=c,this.voiceActive=c==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,d,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Dr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p}=r,f={id:a!=null?a:t==="user"?ro():t==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1}=n,m={id:d!=null?d:s==="user"?ro():s==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(m)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,p,u,f,m;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=ro(),o=Fr(),a={id:s,role:"user",content:n||ls,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!M){let b={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,M||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Fr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,c,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):u=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),u){let f=null;if(u instanceof Response){if(!u.ok){let m=await u.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${u.status}`)}f=u.body}else u instanceof ReadableStream&&(f=u);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(u){(p=(c=this.callbacks).onError)==null||p.call(c,u instanceof Error?u:new Error(String(u)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var d,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Yn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var fp=ac(require("lucide"),1),me=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=fp[s];return o?hp(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function hp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}}}),s}var ms={allowedTypes:ar,maxFileSize:10*1024*1024,maxFiles:4};function yp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function bp(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var $r=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:ms.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:ms.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:ms.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:ms.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,d;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let p=Mc(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,u);continue}try{let u=await Tc(c),f=ds(c)?URL.createObjectURL(c):null,m={id:yp(),file:c,previewUrl:f,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(d=>d.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=ds(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=h("img");a.src=r.previewUrl,a.alt=r.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",n.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=bp(r.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=h("span");c.textContent=kc(r.file.type,r.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),n.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=me("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var Lc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Wo(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];Lc(o)&&Lc(s)?t[n]=Wo(o,s):t[n]=s}return t}var Mn="min(440px, calc(100vw - 24px))",fs="440px",xt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Mn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Ic(e,r){if(!(!e&&!r))return e?r?Wo(e,r):e:r}function hs(e){var r,t,n,s,o,a,i,d,c,p,u,f,m,v,M,b,C,S,R,w,L;return e?{...xt,...e,theme:Ic(xt.theme,e.theme),darkTheme:Ic(xt.darkTheme,e.darkTheme),launcher:{...xt.launcher,...e.launcher,dock:{...(r=xt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=xt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...xt.copy,...e.copy},sendButton:{...xt.sendButton,...e.sendButton},statusIndicator:{...xt.statusIndicator,...e.statusIndicator},voiceRecognition:{...xt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ne,Te,re,Se;let B=(ne=xt.features)==null?void 0:ne.artifacts,T=(Te=e.features)==null?void 0:Te.artifacts,Y=(re=xt.features)==null?void 0:re.scrollToBottom,ge=(Se=e.features)==null?void 0:Se.scrollToBottom,ce=B===void 0&&T===void 0?void 0:{...B,...T,layout:{...B==null?void 0:B.layout,...T==null?void 0:T.layout}},$=Y===void 0&&ge===void 0?void 0:{...Y,...ge};return{...xt.features,...e.features,...$!==void 0?{scrollToBottom:$}:{},...ce!==void 0?{artifacts:ce}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:xt.suggestionChips,suggestionChipsConfig:{...xt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...xt.layout,...e.layout,header:{...(a=xt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=xt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=xt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(M=(v=xt.layout)==null?void 0:v.messages)==null?void 0:M.timestamp,...(C=(b=e.layout)==null?void 0:b.messages)==null?void 0:C.timestamp}},slots:{...(S=xt.layout)==null?void 0:S.slots,...(R=e.layout)==null?void 0:R.slots}},markdown:{...xt.markdown,...e.markdown,options:{...(w=xt.markdown)==null?void 0:w.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...xt.messageActions,...e.messageActions}}:xt}var Ys={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Gs={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Xs={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Mn,maxWidth:fs,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Ro(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ro(e,n):n}function ys(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let d=Ro(e,a);d!==void 0&&(r[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),r}function Ks(e){let r=[],t=[];return e.palette||r.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:r.length===0,errors:r,warnings:t}}function Pc(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=Pc(o,s):t[n]=s}return t}function xp(e,r){return r?Pc(e,r):e}function so(e,r={}){var s,o,a,i,d,c,p,u,f,m,v,M,b;let t={palette:Ys,semantic:Gs,components:Xs},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(M=e==null?void 0:e.semantic)==null?void 0:M.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:xp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let C=Ks(n);if(!C.valid)throw new Error(`Theme validation failed: ${C.errors.map(S=>S.message).join(", ")}`)}if(r.plugins)for(let C of r.plugins)n=C.transform(n);return n}function bs(e){var v,M,b,C,S,R,w,L,B,T,Y,ge,ce,$,ne,Te,re,Se,He,he,Me,ke,oe,be,$e,pe,de,se,De,ot,St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt,Ne,le,Ie,At,Et,Ze,Qe,Kt,Gt,Zt,O,Le,ue,at,Be,Z,ye,Pe,dt,Ot,nt,$t,it,qe,lt,_e,_t,Un,Xn,Dn,Xe,Mr,Vn,kr,kn,Vr,dr,Kn,et,xn,Fn,an,pr,vn,ft,ln,Ln,ur,Zn,gr,qn,Cn,Jn,ht,Wt,Rt,wn,mr,Nn,Sn,D,On,In,fr,gn,An;let r=ys(e),t={};for(let[te,$n]of Object.entries(r)){let qr=te.replace(/\./g,"-");t[`--persona-${qr}`]=$n.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(b=t["--persona-semantic-colors-accent"])!=null?b:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(C=t["--persona-semantic-colors-surface"])!=null?C:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(S=t["--persona-semantic-colors-background"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(R=t["--persona-semantic-colors-container"])!=null?R:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(L=t["--persona-semantic-colors-text-muted"])!=null?L:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(B=t["--persona-semantic-colors-text-inverse"])!=null?B:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(T=t["--persona-semantic-colors-border"])!=null?T:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(Y=t["--persona-semantic-colors-divider"])!=null?Y:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(ge=t["--persona-components-voice-recording-indicator"])!=null?ge:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(ce=t["--persona-components-voice-recording-background"])!=null?ce:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=($=t["--persona-components-voice-processing-icon"])!=null?$:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Te=t["--persona-components-approval-requested-background"])!=null?Te:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(re=t["--persona-components-approval-requested-border"])!=null?re:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Se=t["--persona-components-approval-requested-text"])!=null?Se:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(He=t["--persona-components-approval-approve-background"])!=null?He:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(he=t["--persona-components-approval-deny-background"])!=null?he:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Me=t["--persona-components-attachment-image-background"])!=null?Me:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ke=t["--persona-components-attachment-image-border"])!=null?ke:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(oe=t["--persona-semantic-typography-fontFamily"])!=null?oe:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(be=t["--persona-semantic-typography-fontSize"])!=null?be:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=($e=t["--persona-semantic-typography-fontWeight"])!=null?$e:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(pe=t["--persona-semantic-typography-lineHeight"])!=null?pe:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(de=t["--persona-palette-radius-sm"])!=null?de:"0.125rem",t["--persona-radius-md"]=(se=t["--persona-palette-radius-md"])!=null?se:"0.375rem",t["--persona-radius-lg"]=(De=t["--persona-palette-radius-lg"])!=null?De:"0.5rem",t["--persona-radius-xl"]=(ot=t["--persona-palette-radius-xl"])!=null?ot:"0.75rem",t["--persona-radius-full"]=(St=t["--persona-palette-radius-full"])!=null?St:"9999px",t["--persona-launcher-radius"]=(q=(j=t["--persona-components-launcher-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?q:"9999px",t["--persona-launcher-bg"]=(ae=t["--persona-components-launcher-background"])!=null?ae:t["--persona-primary"],t["--persona-launcher-fg"]=(_=t["--persona-components-launcher-foreground"])!=null?_:t["--persona-text-inverse"],t["--persona-launcher-border"]=(z=t["--persona-components-launcher-border"])!=null?z:t["--persona-border"],t["--persona-button-primary-bg"]=(ee=t["--persona-components-button-primary-background"])!=null?ee:t["--persona-primary"],t["--persona-button-primary-fg"]=(Fe=t["--persona-components-button-primary-foreground"])!=null?Fe:t["--persona-text-inverse"],t["--persona-button-radius"]=(K=(J=t["--persona-components-button-primary-borderRadius"])!=null?J:t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-panel-radius"]=(tt=(vt=t["--persona-components-panel-borderRadius"])!=null?vt:t["--persona-radius-xl"])!=null?tt:"0.75rem",t["--persona-panel-border"]=(Lt=t["--persona-components-panel-border"])!=null?Lt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ne=(Vt=t["--persona-components-panel-shadow"])!=null?Vt:t["--persona-palette-shadows-xl"])!=null?Ne:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ie=(le=t["--persona-components-input-borderRadius"])!=null?le:t["--persona-radius-lg"])!=null?Ie:"0.5rem",t["--persona-message-user-radius"]=(Et=(At=t["--persona-components-message-user-borderRadius"])!=null?At:t["--persona-radius-lg"])!=null?Et:"0.5rem",t["--persona-message-assistant-radius"]=(Qe=(Ze=t["--persona-components-message-assistant-borderRadius"])!=null?Ze:t["--persona-radius-lg"])!=null?Qe:"0.5rem",t["--persona-header-bg"]=(Kt=t["--persona-components-header-background"])!=null?Kt:t["--persona-surface"],t["--persona-header-border"]=(Gt=t["--persona-components-header-border"])!=null?Gt:t["--persona-divider"],t["--persona-header-icon-bg"]=(Zt=t["--persona-components-header-iconBackground"])!=null?Zt:t["--persona-primary"],t["--persona-header-icon-fg"]=(O=t["--persona-components-header-iconForeground"])!=null?O:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Le=t["--persona-components-header-titleForeground"])!=null?Le:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ue=t["--persona-components-header-subtitleForeground"])!=null?ue:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(at=t["--persona-components-header-actionIconForeground"])!=null?at:t["--persona-muted"];let n=(Be=e.components)==null?void 0:Be.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(Z=t["--persona-components-input-background"])!=null?Z:t["--persona-surface"],t["--persona-input-placeholder"]=(ye=t["--persona-components-input-placeholder"])!=null?ye:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Pe=t["--persona-components-message-user-background"])!=null?Pe:t["--persona-accent"],t["--persona-message-user-text"]=(dt=t["--persona-components-message-user-text"])!=null?dt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ot=t["--persona-components-message-user-shadow"])!=null?Ot:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(nt=t["--persona-components-message-assistant-background"])!=null?nt:t["--persona-surface"],t["--persona-message-assistant-text"]=($t=t["--persona-components-message-assistant-text"])!=null?$t:t["--persona-text"],t["--persona-message-assistant-border"]=(it=t["--persona-components-message-assistant-border"])!=null?it:t["--persona-border"],t["--persona-message-assistant-shadow"]=(qe=t["--persona-components-message-assistant-shadow"])!=null?qe:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(_e=(lt=t["--persona-components-scrollToBottom-background"])!=null?lt:t["--persona-button-primary-bg"])!=null?_e:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Un=(_t=t["--persona-components-scrollToBottom-foreground"])!=null?_t:t["--persona-button-primary-fg"])!=null?Un:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Xn=t["--persona-components-scrollToBottom-border"])!=null?Xn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Dn=t["--persona-components-scrollToBottom-size"])!=null?Dn:"40px",t["--persona-scroll-to-bottom-radius"]=(Vn=(Mr=(Xe=t["--persona-components-scrollToBottom-borderRadius"])!=null?Xe:t["--persona-button-radius"])!=null?Mr:t["--persona-radius-full"])!=null?Vn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(kn=(kr=t["--persona-components-scrollToBottom-shadow"])!=null?kr:t["--persona-palette-shadows-sm"])!=null?kn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Vr=t["--persona-components-scrollToBottom-padding"])!=null?Vr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(dr=t["--persona-components-scrollToBottom-gap"])!=null?dr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(et=(Kn=t["--persona-components-scrollToBottom-fontSize"])!=null?Kn:t["--persona-palette-typography-fontSize-sm"])!=null?et:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(xn=t["--persona-components-scrollToBottom-iconSize"])!=null?xn:"14px",t["--persona-tool-bubble-shadow"]=(Fn=t["--persona-components-toolBubble-shadow"])!=null?Fn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(an=t["--persona-components-reasoningBubble-shadow"])!=null?an:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(pr=t["--persona-components-composer-shadow"])!=null?pr:"none",t["--persona-md-inline-code-bg"]=(vn=t["--persona-components-markdown-inlineCode-background"])!=null?vn:t["--persona-container"],t["--persona-md-inline-code-color"]=(ft=t["--persona-components-markdown-inlineCode-foreground"])!=null?ft:t["--persona-text"],t["--persona-md-link-color"]=(Ln=(ln=t["--persona-components-markdown-link-foreground"])!=null?ln:t["--persona-accent"])!=null?Ln:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let d=t["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(t["--persona-md-prose-font-family"]=d),t["--persona-md-code-block-bg"]=(ur=t["--persona-components-markdown-codeBlock-background"])!=null?ur:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Zn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Zn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(gr=t["--persona-components-markdown-codeBlock-textColor"])!=null?gr:"inherit",t["--persona-md-table-header-bg"]=(qn=t["--persona-components-markdown-table-headerBackground"])!=null?qn:t["--persona-container"],t["--persona-md-table-border-color"]=(Cn=t["--persona-components-markdown-table-borderColor"])!=null?Cn:t["--persona-border"],t["--persona-md-hr-color"]=(Jn=t["--persona-components-markdown-hr-color"])!=null?Jn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(ht=t["--persona-components-markdown-blockquote-borderColor"])!=null?ht:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Wt=t["--persona-components-markdown-blockquote-background"])!=null?Wt:"transparent",t["--persona-md-blockquote-text-color"]=(Rt=t["--persona-components-markdown-blockquote-textColor"])!=null?Rt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(wn=t["--persona-components-collapsibleWidget-container"])!=null?wn:t["--persona-surface"],t["--cw-surface"]=(mr=t["--persona-components-collapsibleWidget-surface"])!=null?mr:t["--persona-surface"],t["--cw-border"]=(Nn=t["--persona-components-collapsibleWidget-border"])!=null?Nn:t["--persona-border"],t["--persona-message-border"]=(Sn=t["--persona-components-message-border"])!=null?Sn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let u=c==null?void 0:c.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let te=m.toolbar;te.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=te.iconHoverColor),te.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=te.iconHoverBackground),te.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=te.iconPadding),te.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=te.iconBorderRadius),te.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=te.iconBorder),te.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=te.toggleGroupGap),te.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=te.toggleBorderRadius),te.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=te.copyBackground),te.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=te.copyBorder),te.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=te.copyColor),te.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=te.copyBorderRadius),te.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=te.copyPadding),te.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=te.copyMenuBackground,t["--persona-dropdown-bg"]=(D=t["--persona-dropdown-bg"])!=null?D:te.copyMenuBackground),te.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=te.copyMenuBorder,t["--persona-dropdown-border"]=(On=t["--persona-dropdown-border"])!=null?On:te.copyMenuBorder),te.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=te.copyMenuShadow,t["--persona-dropdown-shadow"]=(In=t["--persona-dropdown-shadow"])!=null?In:te.copyMenuShadow),te.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=te.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(fr=t["--persona-dropdown-radius"])!=null?fr:te.copyMenuBorderRadius),te.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=te.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:te.copyMenuItemHoverBackground),te.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=te.iconBackground),te.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=te.toolbarBorder)}if(m!=null&&m.tab){let te=m.tab;te.background&&(t["--persona-artifact-tab-bg"]=te.background),te.activeBackground&&(t["--persona-artifact-tab-active-bg"]=te.activeBackground),te.activeBorder&&(t["--persona-artifact-tab-active-border"]=te.activeBorder),te.borderRadius&&(t["--persona-artifact-tab-radius"]=te.borderRadius),te.textColor&&(t["--persona-artifact-tab-color"]=te.textColor),te.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=te.hoverBackground),te.listBackground&&(t["--persona-artifact-tab-list-bg"]=te.listBackground),te.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=te.listBorderColor),te.listPadding&&(t["--persona-artifact-tab-list-padding"]=te.listPadding)}if(m!=null&&m.pane){let te=m.pane;if(te.toolbarBackground){let $n=(An=Ro(e,te.toolbarBackground))!=null?An:te.toolbarBackground;t["--persona-artifact-toolbar-bg"]=$n}}return t}var Wc={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var vp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Rc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ho=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Cp=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Ho()},Zs=e=>Cp(e),wp=e=>so(e),Sp=e=>{var t;let r=so(void 0,{validate:!1});return so({...e,palette:{...r.palette,colors:{...vp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Bo=e=>{let r=Zs(e),t=Rc(e==null?void 0:e.theme),n=Rc(e==null?void 0:e.darkTheme);return r==="dark"?Sp(Wo(t!=null?t:{},n!=null?n:{})):wp(t)},Ap=e=>bs(e),wr=(e,r)=>{var o;let t=Bo(r),n=Ap(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},xs=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Ho())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Ho());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var Hc=require("idiomorph"),Bc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Hc.Idiomorph.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&n&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function Dc(e,r){var t,n,s,o,a,i,d,c,p,u,f,m,v,M,b,C,S,R;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(C=(b=(M=e.reasoning)==null?void 0:M.chunks)==null?void 0:b.length)!=null?C:0,(R=(S=e.contentParts)==null?void 0:S.length)!=null?R:0,r].join("\0")}function Fc(){return new Map}function Nc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Oc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function $c(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function vs(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Do(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Fo(e,r){return Do(e)-e.scrollTop<=r}function Cs(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function ws(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var sn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,Sr=yn+1;function Qs(e,r=yn){let t=e.style.position,n=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var No=0,Ar=null;function ea(e=document){var t;if(No++,No===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Ar={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,No=Math.max(0,No-1),No===0&&Ar)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=Ar.originalOverflow,s.style.position=Ar.originalPosition,s.style.top=Ar.originalTop,s.style.width=Ar.originalWidth,o.scrollTo(0,Ar.scrollY),Ar=null}}}var Ss={side:"right",width:"420px",animate:!0,reveal:"resize"},Ut=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Hn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:Ss.side,width:(s=r==null?void 0:r.width)!=null?s:Ss.width,animate:(o=r==null?void 0:r.animate)!=null?o:Ss.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:Ss.reveal}};var zn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Oo=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
|
|
6
|
+
`);a=(oe=_e.pop())!=null?oe:"";for(let Tt of _e){let yt=Tt.split(`
|
|
7
|
+
`),St="message",et="";for(let P of yt)P.startsWith("event:")?St=P.replace("event:","").trim():P.startsWith("data:")&&(et+=P.replace("data:","").trim());if(!et)continue;let y;try{y=JSON.parse(et)}catch(P){t({type:"error",error:P instanceof Error?P:new Error("Failed to parse chat stream payload")});continue}let se=St!=="message"?St:(Oe=y.type)!=null?Oe:"message";if((Z=this.onSSEEvent)==null||Z.call(this,se,y),this.parseSSEEvent){f.current=g;let P=await this.handleCustomSSEEvent(y,t,f,p,c,v);if(f.current&&f.current!==g&&(g=f.current),P)continue}if(se==="reason_start"){let P=(te=I(y,!0))!=null?te:`reason-${c()}`,S=Q(P);S.reasoning=(Lt=S.reasoning)!=null?Lt:{id:P,status:"streaming",chunks:[]},S.reasoning.startedAt=(Nt=S.reasoning.startedAt)!=null?Nt:xe((lt=y.startedAt)!=null?lt:y.timestamp),S.reasoning.completedAt=void 0,S.reasoning.durationMs=void 0,S.streaming=!0,S.reasoning.status="streaming",p(S)}else if(se==="reason_delta"||se==="reason_chunk"){let P=($e=(Kt=I(y,!1))!=null?Kt:I(y,!0))!=null?$e:`reason-${c()}`,S=Q(P);S.reasoning=(ce=S.reasoning)!=null?ce:{id:P,status:"streaming",chunks:[]},S.reasoning.startedAt=(Wt=S.reasoning.startedAt)!=null?Wt:xe((He=y.startedAt)!=null?He:y.timestamp);let Y=(st=(ot=(Rt=y.reasoningText)!=null?Rt:y.text)!=null?ot:y.delta)!=null?st:"";if(Y&&y.hidden!==!0){let N=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(N!==void 0){let pe=it(Be,P,N,String(Y));S.reasoning.chunks=[pe]}else S.reasoning.chunks.push(String(Y))}if(S.reasoning.status=y.done?"complete":"streaming",y.done){S.reasoning.completedAt=xe((rn=y.completedAt)!=null?rn:y.timestamp);let N=(tn=S.reasoning.startedAt)!=null?tn:Date.now();S.reasoning.durationMs=Math.max(0,((on=S.reasoning.completedAt)!=null?on:Date.now())-N),Be.delete(P)}S.streaming=S.reasoning.status!=="complete",p(S)}else if(se==="reason_complete"){let P=(Ie=(j=I(y,!1))!=null?j:I(y,!0))!=null?Ie:`reason-${c()}`,S=x.get(P);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=xe((ue=y.completedAt)!=null?ue:y.timestamp);let N=(gt=S.reasoning.startedAt)!=null?gt:Date.now();S.reasoning.durationMs=Math.max(0,((Fe=S.reasoning.completedAt)!=null?Fe:Date.now())-N),S.streaming=!1,Be.delete(P),p(S)}let Y=M(y);Y&&k.byStep.delete(Y)}else if(se==="tool_start"){let P=(ne=Le(y,!0))!=null?ne:`tool-${c()}`,S=(ye=y.toolName)!=null?ye:y.name;if(ke(S)){re.add(P);continue}let Y=ae(P),N=(De=Y.toolCall)!=null?De:{id:P,status:"pending"};N.name=S!=null?S:N.name,N.status="running",y.args!==void 0?N.args=y.args:y.parameters!==void 0&&(N.args=y.parameters),N.startedAt=(zt=N.startedAt)!=null?zt:xe((xt=y.startedAt)!=null?xt:y.timestamp),N.completedAt=void 0,N.durationMs=void 0,Y.toolCall=N,Y.streaming=!0;let pe=y.agentContext;(pe||y.executionId)&&(Y.agentMetadata={executionId:(ct=pe==null?void 0:pe.executionId)!=null?ct:y.executionId,iteration:(qt=pe==null?void 0:pe.iteration)!=null?qt:y.iteration}),p(Y)}else if(se==="tool_chunk"||se==="tool_delta"){let P=(Ke=(ft=Le(y,!1))!=null?ft:Le(y,!0))!=null?Ke:`tool-${c()}`;if(re.has(P))continue;let S=ae(P),Y=(ht=S.toolCall)!=null?ht:{id:P,status:"running"};Y.startedAt=(Vt=Y.startedAt)!=null?Vt:xe((We=y.startedAt)!=null?We:y.timestamp);let N=($n=(tr=(Gn=y.text)!=null?Gn:y.delta)!=null?tr:y.message)!=null?$n:"";N&&(Y.chunks=(Qe=Y.chunks)!=null?Qe:[],Y.chunks.push(String(N))),Y.status="running",S.toolCall=Y,S.streaming=!0;let pe=y.agentContext;(pe||y.executionId)&&(S.agentMetadata=(Ir=S.agentMetadata)!=null?Ir:{executionId:(Lr=pe==null?void 0:pe.executionId)!=null?Lr:y.executionId,iteration:(Xn=pe==null?void 0:pe.iteration)!=null?Xn:y.iteration}),p(S)}else if(se==="tool_complete"){let P=(Kr=(Wn=Le(y,!1))!=null?Wn:Le(y,!0))!=null?Kr:`tool-${c()}`;if(re.has(P)){re.delete(P);continue}let S=ae(P),Y=(gr=S.toolCall)!=null?gr:{id:P,status:"running"};Y.status="complete",y.result!==void 0&&(Y.result=y.result),typeof y.duration=="number"&&(Y.duration=y.duration),Y.completedAt=xe((nr=y.completedAt)!=null?nr:y.timestamp);let N=(at=y.duration)!=null?at:y.executionTime;if(typeof N=="number")Y.durationMs=N;else{let tt=(wn=Y.startedAt)!=null?wn:Date.now();Y.durationMs=Math.max(0,((_n=Y.completedAt)!=null?_n:Date.now())-tt)}S.toolCall=Y,S.streaming=!1;let pe=y.agentContext;(pe||y.executionId)&&(S.agentMetadata=(Sn=S.agentMetadata)!=null?Sn:{executionId:(dn=pe==null?void 0:pe.executionId)!=null?dn:y.executionId,iteration:(fr=pe==null?void 0:pe.iteration)!=null?fr:y.iteration}),p(S);let Ye=W(y);Ye&&H.byCall.delete(Ye)}else if(se==="text_start"){let P=y.partId;if(P!==void 0&&v.current!==null&&P!==v.current){let S=g;S&&(S.streaming=!1,p(S),Et=S,g=null,E=!0)}P!==void 0&&(v.current=P)}else if(se==="text_end"){let P=g;P&&(P.streaming=!1,p(P),Et=P,g=null,E=!0)}else if(se==="step_chunk"||se==="step_delta"){let P=y.stepType,S=y.executionType;if(P==="tool"||S==="context")continue;let Y=y.partId;if(Y!==void 0&&v.current!==null&&Y!==v.current){let Ye=g;Ye&&(Ye.streaming=!1,p(Ye),Et=Ye,g=null,E=!0)}Y!==void 0&&(v.current=Y);let N=K();Y!==void 0&&!N.partId&&(N.partId=Y);let pe=(hr=(Rn=(pn=(wt=y.text)!=null?wt:y.delta)!=null?pn:y.content)!=null?Rn:y.chunk)!=null?hr:"";if(pe){let Ye=typeof y.seq=="number"?y.seq:void 0,tt;Ye!==void 0?tt=it(Ee,N.id,Ye,pe):tt=((rr=ie.get(N.id))!=null?rr:"")+pe,N.rawContent=tt,de.has(N.id)||de.set(N.id,this.createStreamParser());let Bt=de.get(N.id),nn=tt.trim().startsWith("{")||tt.trim().startsWith("[");if(nn&&ie.set(N.id,tt),Bt.__isPlainTextParser===!0){Ye!==void 0?N.content=tt:N.content+=pe,ie.delete(N.id),de.delete(N.id),N.rawContent=void 0,p(N);continue}let Zt=Bt.processChunk(tt);if(Zt instanceof Promise)Zt.then(Ge=>{var Qt;let Mt=typeof Ge=="string"?Ge:(Qt=Ge==null?void 0:Ge.text)!=null?Qt:null;if(Mt!==null&&Mt.trim()!=="")N.content=Mt,p(N);else if(!nn&&!tt.trim().startsWith("<")){let Ot=g;Ot&&Ot.id===N.id&&(Ye!==void 0?Ot.content=tt:Ot.content+=pe,ie.delete(Ot.id),de.delete(Ot.id),Ot.rawContent=void 0,p(Ot))}}).catch(()=>{Ye!==void 0?N.content=tt:N.content+=pe,ie.delete(N.id),de.delete(N.id),N.rawContent=void 0,p(N)});else{let Ge=typeof Zt=="string"?Zt:(yr=Zt==null?void 0:Zt.text)!=null?yr:null;Ge!==null&&Ge.trim()!==""?(N.content=Ge,p(N)):!nn&&!tt.trim().startsWith("<")&&(Ye!==void 0?N.content=tt:N.content+=pe,ie.delete(N.id),de.delete(N.id),N.rawContent=void 0,p(N))}}if(y.isComplete){let Ye=(An=(Kn=y.result)==null?void 0:Kn.response)!=null?An:N.content;if(Ye){let tt=ie.get(N.id),Bt=tt!=null?tt:je(Ye);N.rawContent=Bt;let nn=de.get(N.id),Ft=null,Zt=!1;if(nn&&(Ft=nn.getExtractedText(),Ft===null&&(Ft=_r(Bt)),Ft===null)){let Ge=nn.processChunk(Bt);Ge instanceof Promise?(Zt=!0,Ge.then(Mt=>{var Ot;let Qt=typeof Mt=="string"?Mt:(Ot=Mt==null?void 0:Mt.text)!=null?Ot:null;if(Qt!==null){let It=g;It&&It.id===N.id&&(It.content=Qt,It.streaming=!1,de.delete(It.id),ie.delete(It.id),Ee.delete(It.id),p(It))}})):Ft=typeof Ge=="string"?Ge:(Zn=Ge==null?void 0:Ge.text)!=null?Zn:null}if(!Zt){Ft!==null&&Ft.trim()!==""?N.content=Ft:ie.has(N.id)||(N.content=je(Ye));let Ge=de.get(N.id);if(Ge){let Mt=(vt=Ge.close)==null?void 0:vt.call(Ge);Mt instanceof Promise&&Mt.catch(()=>{}),de.delete(N.id)}ie.delete(N.id),Ee.delete(N.id),N.streaming=!1,p(N)}}}}else if(se==="step_complete"){let P=y.stepType,S=y.executionType;if(P==="tool"||S==="context")continue;if(E){if(g!==null){let tt=g;de.delete(tt.id),ie.delete(tt.id),Ee.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,p(tt))}let pe=($t=y.result)==null?void 0:$t.response,Ye=Et;Ye&&(pe!=null?q(Ye,pe):(de.delete(Ye.id),ie.delete(Ye.id))),Et=null;continue}let Y=(_t=y.result)==null?void 0:_t.response,N=K();if(Y!=null){let pe=de.get(N.id),Ye=!1,tt=!1;if(pe){let Bt=pe.getExtractedText(),nn=ie.get(N.id),Ft=nn!=null?nn:je(Y);if(N.rawContent=Ft,Bt!==null&&Bt.trim()!=="")N.content=Bt,Ye=!0;else{let Zt=_r(Ft);if(Zt!==null)N.content=Zt,Ye=!0;else{let Ge=pe.processChunk(Ft);if(Ge instanceof Promise)tt=!0,Ge.then(Mt=>{var Ot;let Qt=typeof Mt=="string"?Mt:(Ot=Mt==null?void 0:Mt.text)!=null?Ot:null;if(Qt!==null&&Qt.trim()!==""){let It=g;It&&It.id===N.id&&(It.content=Qt,It.streaming=!1,de.delete(It.id),ie.delete(It.id),Ee.delete(It.id),p(It))}else{let It=pe.getExtractedText(),Ln=g;Ln&&Ln.id===N.id&&(It!==null&&It.trim()!==""?Ln.content=It:ie.has(Ln.id)||(Ln.content=je(Y)),Ln.streaming=!1,de.delete(Ln.id),ie.delete(Ln.id),Ee.delete(Ln.id),p(Ln))}});else{let Mt=typeof Ge=="string"?Ge:(En=Ge==null?void 0:Ge.text)!=null?En:null;if(Mt!==null&&Mt.trim()!=="")N.content=Mt,Ye=!0;else{let Qt=pe.getExtractedText();Qt!==null&&Qt.trim()!==""&&(N.content=Qt,Ye=!0)}}}}}if(!tt){if(!N.rawContent){let Bt=ie.get(N.id);N.rawContent=Bt!=null?Bt:je(Y)}if(!Ye&&!ie.has(N.id)&&(N.content=je(Y)),pe){let Bt=(br=pe.close)==null?void 0:br.call(pe);Bt instanceof Promise&&Bt.catch(()=>{})}de.delete(N.id),ie.delete(N.id),Ee.delete(N.id),N.streaming=!1,p(N)}}else de.delete(N.id),ie.delete(N.id),Ee.delete(N.id),N.streaming=!1,p(N)}else if(se==="flow_complete"){let P=(jn=y.result)==null?void 0:jn.response;if(E){if(g!==null){let S=g;de.delete(S.id),ie.delete(S.id),Ee.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}}else if(P!=null){let S=K(),Y=ie.get(S.id),N=Y!=null?Y:je(P);S.rawContent=N;let pe=je(P),Ye=de.get(S.id);if(Ye){let nn=_r(N);if(nn!==null)pe=nn;else{let Ft=Ye.processChunk(N);Ft instanceof Promise&&Ft.then(Ge=>{var Qt;let Mt=typeof Ge=="string"?Ge:(Qt=Ge==null?void 0:Ge.text)!=null?Qt:null;Mt!==null&&(S.content=Mt,S.streaming=!1,p(S))});let Zt=Ye.getExtractedText();Zt!==null&&(pe=Zt)}}de.delete(S.id),ie.delete(S.id),Ee.delete(S.id);let tt=pe!==S.content,Bt=S.streaming!==!1;tt&&(S.content=pe),S.streaming=!1,(tt||Bt)&&p(S)}else if(g!==null){let S=g;de.delete(S.id),ie.delete(S.id),Ee.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}t({type:"status",status:"idle"})}else if(se==="agent_start")F={executionId:y.executionId,agentId:(Tn=y.agentId)!=null?Tn:"virtual",agentName:(D=y.agentName)!=null?D:"",status:"running",currentIteration:0,maxTurns:(zn=y.maxTurns)!=null?zn:1,startedAt:xe(y.startedAt)};else if(se==="agent_iteration_start"){if(F&&(F.currentIteration=y.iteration),_==="separate"&&y.iteration>1){let P=g;P&&(P.streaming=!1,p(P),le.set(y.iteration-1,P),g=null)}}else if(se!=="agent_turn_start"){if(se==="agent_turn_delta"){if(y.contentType==="text"){let P=K();P.content+=(Hn=y.delta)!=null?Hn:"",P.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId,agentName:F==null?void 0:F.agentName},p(P)}else if(y.contentType==="thinking"){let P=(xr=y.turnId)!=null?xr:`agent-think-${y.iteration}`,S=Q(P);S.reasoning=(gn=S.reasoning)!=null?gn:{id:P,status:"streaming",chunks:[]},S.reasoning.chunks.push((Mn=y.delta)!=null?Mn:""),S.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:y.turnId},p(S)}else if(y.contentType==="tool_input"){let P=(ee=y.toolCallId)!=null?ee:H.lastId;if(P){let S=C.get(P);S!=null&&S.toolCall&&(S.toolCall.chunks=(qn=S.toolCall.chunks)!=null?qn:[],S.toolCall.chunks.push((or=y.delta)!=null?or:""),p(S))}}}else if(se==="agent_turn_complete"){let P=y.turnId;if(P){let S=x.get(P);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=xe(y.completedAt);let Y=(ts=S.reasoning.startedAt)!=null?ts:Date.now();S.reasoning.durationMs=Math.max(0,((vo=S.reasoning.completedAt)!=null?vo:Date.now())-Y),S.streaming=!1,p(S)}}}else if(se==="agent_tool_start"){let P=(Zr=y.toolCallId)!=null?Zr:`agent-tool-${c()}`;Ce(W(y),P);let S=ae(P),Y=(Ze=S.toolCall)!=null?Ze:{id:P,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Y.name=(Bn=(Co=y.toolName)!=null?Co:y.name)!=null?Bn:Y.name,Y.status="running",y.parameters!==void 0&&(Y.args=y.parameters),Y.startedAt=xe((fn=y.startedAt)!=null?fn:y.timestamp),S.toolCall=Y,S.streaming=!0,S.agentMetadata={executionId:y.executionId,iteration:y.iteration},p(S)}else if(se==="agent_tool_delta"){let P=(ns=y.toolCallId)!=null?ns:H.lastId;if(P){let S=(rs=C.get(P))!=null?rs:ae(P);S.toolCall&&(S.toolCall.chunks=(wo=S.toolCall.chunks)!=null?wo:[],S.toolCall.chunks.push((sr=y.delta)!=null?sr:""),S.toolCall.status="running",S.streaming=!0,p(S))}}else if(se==="agent_tool_complete"){let P=(os=y.toolCallId)!=null?os:H.lastId;if(P){let S=(Qr=C.get(P))!=null?Qr:ae(P);if(S.toolCall){S.toolCall.status="complete",y.result!==void 0&&(S.toolCall.result=y.result),typeof y.executionTime=="number"&&(S.toolCall.durationMs=y.executionTime),S.toolCall.completedAt=xe((So=y.completedAt)!=null?So:y.timestamp),S.streaming=!1,p(S);let Y=W(y);Y&&H.byCall.delete(Y)}}}else if(se!=="agent_iteration_complete"){if(se==="agent_reflection"||se==="agent_reflect"){let P=`agent-reflection-${y.executionId}-${y.iteration}`,S={id:P,role:"assistant",content:(ar=y.reflection)!=null?ar:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:P,status:"complete",chunks:[(Ao=y.reflection)!=null?Ao:""]},agentMetadata:{executionId:y.executionId,iteration:y.iteration}};p(S)}else if(se==="agent_complete"){F&&(F.status=y.success?"complete":"error",F.completedAt=xe(y.completedAt),F.stopReason=y.stopReason);let P=g;P&&(P.streaming=!1,p(P)),t({type:"status",status:"idle"})}else if(se==="agent_error"){let P=typeof y.error=="string"?y.error:(Cr=(vr=y.error)==null?void 0:vr.message)!=null?Cr:"Agent execution error";y.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",P):t({type:"error",error:new Error(P)})}else if(se!=="agent_ping")if(se==="agent_approval_start"){let P=(ss=y.approvalId)!=null?ss:`approval-${c()}`,S={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:(as=F==null?void 0:F.agentId)!=null?as:"virtual",executionId:(Pr=(ta=y.executionId)!=null?ta:F==null?void 0:F.executionId)!=null?Pr:"",toolName:(Wr=y.toolName)!=null?Wr:"",toolType:y.toolType,description:(eo=y.description)!=null?eo:`Execute ${(Ht=y.toolName)!=null?Ht:"tool"}`,parameters:y.parameters}};p(S)}else if(se==="step_await"&&y.awaitReason==="approval_required"){let P=(to=y.approvalId)!=null?to:`approval-${c()}`,S={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:(Eo=F==null?void 0:F.agentId)!=null?Eo:"virtual",executionId:(Mo=(To=y.executionId)!=null?To:F==null?void 0:F.executionId)!=null?Mo:"",toolName:(ko=y.toolName)!=null?ko:"",toolType:y.toolType,description:(kn=y.description)!=null?kn:`Execute ${(un=y.toolName)!=null?un:"tool"}`,parameters:y.parameters}};p(S)}else if(se==="agent_approval_complete"){let P=y.approvalId;if(P){let Y={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:(ir=y.decision)!=null?ir:"approved",agentId:(qe=F==null?void 0:F.agentId)!=null?qe:"virtual",executionId:(Rr=(Lo=y.executionId)!=null?Lo:F==null?void 0:F.executionId)!=null?Rr:"",toolName:(Vn=y.toolName)!=null?Vn:"",description:(is=y.description)!=null?is:"",resolvedAt:Date.now()}};p(Y)}}else if(se==="artifact_start"||se==="artifact_delta"||se==="artifact_update"||se==="artifact_complete"){if(se==="artifact_start"){let P=y.artifactType,S=String(y.id),Y=typeof y.title=="string"?y.title:void 0;if(t({type:"artifact_start",id:S,artifactType:P,title:Y,component:typeof y.component=="string"?y.component:void 0}),he.set(S,{markdown:"",title:Y}),!Ne.has(S)){Ne.add(S);let N={id:`artifact-ref-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:S,title:Y,artifactType:P,status:"streaming"}})};Ae.set(S,N),p(N)}}else if(se==="artifact_delta"){let P=String(y.id),S=typeof y.delta=="string"?y.delta:String((no=y.delta)!=null?no:"");t({type:"artifact_delta",id:P,artDelta:S});let Y=he.get(P);Y&&(Y.markdown+=S)}else if(se==="artifact_update"){let P=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};t({type:"artifact_update",id:String(y.id),props:P,component:typeof y.component=="string"?y.component:void 0})}else if(se==="artifact_complete"){let P=String(y.id);t({type:"artifact_complete",id:P});let S=Ae.get(P);if(S){S.streaming=!1;try{let Y=JSON.parse((ro=S.rawContent)!=null?ro:"{}");if(Y.props){Y.props.status="complete";let N=he.get(P);N!=null&&N.markdown&&(Y.props.markdown=N.markdown)}S.rawContent=JSON.stringify(Y)}catch{}he.delete(P),p(S),Ae.delete(P)}}}else if(se==="transcript_insert"){let P=y.message;if(!P||typeof P!="object")continue;let S=String((Hr=P.id)!=null?Hr:`msg-${c()}`),Y=P.role,pe={id:S,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof P.content=="string"?P.content:"",rawContent:typeof P.rawContent=="string"?P.rawContent:void 0,createdAt:typeof P.createdAt=="string"?P.createdAt:new Date().toISOString(),streaming:P.streaming===!0,...typeof P.variant=="string"?{variant:P.variant}:{},sequence:c()};if(p(pe),pe.rawContent)try{let Ye=JSON.parse(pe.rawContent),tt=(wr=Ye==null?void 0:Ye.props)==null?void 0:wr.artifactId;typeof tt=="string"&&Ne.add(tt)}catch{}g=null,f.current=null,de.delete(S),ie.delete(S),Ee.delete(S)}else se==="error"&&y.error&&t({type:"error",error:y.error instanceof Error?y.error:new Error(String(y.error))})}}}}}};function Jc(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function lo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function zr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var vs="[Image]";function Yc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Gc(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Xc(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Kc(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function Do(e){return{type:"text",text:e}}function Zc(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Qc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function ed(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${r.join(", ")}`}}var td=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],qp=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],dr=[...td,...qp];function Vp(e){return td.includes(e)||e.startsWith("image/")}function Cs(e){return Vp(e.type)}async function nd(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Cs(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function rd(e,r=dr,t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${r.join(", ")}`}}function Up(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function od(e,r){let t=Up(r).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var ws=class{constructor(r=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let u=new Uint8Array(this.remainder.length+r.length);u.set(this.remainder),u.set(r,this.remainder.length),t=u,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(r){this.finishedCallbacks.push(r)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var Ss=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let d=0;d<a.length;d++)i+=a[d]*a[d];let u=Math.sqrt(i/a.length);(n==="silence"?u<s.threshold:u>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var No=class{constructor(r){this.config=r;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ss;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,u=(n=this.config)==null?void 0:n.clientToken;if(!i||!u)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let d=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let v=!1,E=C=>{v||(v=!0,clearTimeout(x),f(new Error(C)))},x=setTimeout(()=>E("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(x),g())},{once:!0}),this.ws.addEventListener("error",()=>{E("WebSocket connection failed to "+d+"."+p)},{once:!0}),this.ws.addEventListener("close",C=>{if(!C.wasClean&&!v){let k=C.code!==1006?` (code ${C.code})`:"";E("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ws(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,u=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let d=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:d});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var qr=class{constructor(r={}){this.config=r;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Vr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new No(e.runtype);case"browser":if(!qr.isSupported())throw new Error("Browser speech recognition not supported");return new qr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function As(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Vr({type:"runtype",runtype:e.runtype});if(qr.isSupported())return Vr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Fo(e){try{return As(e),!0}catch{return!1}}var co=class e{constructor(r={},t){this.config=r;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,u;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(u=(i=this.callbacks).onError)==null||u.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new jr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return Fo((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Vr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",u=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var d,p,g,f,v,E;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((d=c.transcript)!=null&&d.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=c.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(f=c.text)!=null&&f.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let x=(E=this.pendingVoiceAssistantMessageId)!=null?E:(v=[...this.messages].reverse().find(C=>C.role==="assistant"))==null?void 0:v.id;x&&this.ttsSpokenMessageIds.add(x)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var d,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(d=this.callbacks).onVoiceStatusChanged)==null||p.call(d,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,u,c,d;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(u=r.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(d=r.browser)==null?void 0:d.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new jr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:u,streaming:c=!1,voiceProcessing:d}=r,g={id:a!=null?a:t==="user"?lo():t==="assistant"?zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...d!==void 0&&{voiceProcessing:d}};return this.upsertMessage(g),g}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:u,createdAt:c,sequence:d,streaming:p=!1}=n,f={id:u!=null?u:s==="user"?lo():s==="assistant"?zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(f)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,d,p,g,f;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=lo(),o=zr(),a={id:s,role:"user",content:n||vs,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!E){let x={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(x)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,E||(v instanceof Error?(p=(d=this.callbacks).onError)==null||p.call(d,v):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(v))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=zr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let d={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(d),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(u=(i=this.callbacks).onError)==null||u.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var u,c,d;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):p=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),p){let g=null;if(p instanceof Response){if(!p.ok){let f=await p.json().catch(()=>null);throw new Error((u=f==null?void 0:f.error)!=null?u:`Approval request failed: ${p.status}`)}g=p.body}else p instanceof ReadableStream&&(g=p);g?await this.connectStream(g):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(d=(c=this.callbacks).onError)==null||d.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var u,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(u=t.sequence)!=null?u:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Qn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var Jp=Bc(require("lucide"),1),me=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=Jp[s];return o?Yp(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function Yp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,d])=>{c!=="stroke"&&u.setAttribute(c,String(d))}),s.appendChild(u)}}}),s}var Es={allowedTypes:dr,maxFileSize:10*1024*1024,maxFiles:4};function Gp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Xp(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Ur=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Es.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Es.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:Es.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:Es.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,u;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let d=rd(c,this.config.allowedTypes,this.config.maxFileSize);if(!d.valid){let p=(s=d.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await nd(c),g=Cs(c)?URL.createObjectURL(c):null,f={id:Gp(),file:c,previewUrl:g,contentPart:p};this.attachments.push(f),this.renderPreview(f)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(u=>u.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=Cs(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=h("img");a.src=r.previewUrl,a.alt=r.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",n.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Xp(r.file.type),u=me(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=od(r.file.type,r.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),n.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=me("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var sd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Oo(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];sd(o)&&sd(s)?t[n]=Oo(o,s):t[n]=s}return t}var Pn="min(440px, calc(100vw - 24px))",Ts="440px",kt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Pn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ad(e,r){if(!(!e&&!r))return e?r?Oo(e,r):e:r}function Ms(e){var r,t,n,s,o,a,i,u,c,d,p,g,f,v,E,x,C,k,H,w,M;return e?{...kt,...e,theme:ad(kt.theme,e.theme),darkTheme:ad(kt.darkTheme,e.darkTheme),launcher:{...kt.launcher,...e.launcher,dock:{...(r=kt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=kt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...kt.copy,...e.copy},sendButton:{...kt.sendButton,...e.sendButton},statusIndicator:{...kt.statusIndicator,...e.statusIndicator},voiceRecognition:{...kt.voiceRecognition,...e.voiceRecognition},features:(()=>{var Q,Ce,re,Ae;let W=(Q=kt.features)==null?void 0:Q.artifacts,T=(Ce=e.features)==null?void 0:Ce.artifacts,G=(re=kt.features)==null?void 0:re.scrollToBottom,K=(Ae=e.features)==null?void 0:Ae.scrollToBottom,J=W===void 0&&T===void 0?void 0:{...W,...T,layout:{...W==null?void 0:W.layout,...T==null?void 0:T.layout}},I=G===void 0&&K===void 0?void 0:{...G,...K};return{...kt.features,...e.features,...I!==void 0?{scrollToBottom:I}:{},...J!==void 0?{artifacts:J}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:kt.suggestionChips,suggestionChipsConfig:{...kt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...kt.layout,...e.layout,header:{...(a=kt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=kt.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(d=kt.layout)==null?void 0:d.messages)==null?void 0:p.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(E=(v=kt.layout)==null?void 0:v.messages)==null?void 0:E.timestamp,...(C=(x=e.layout)==null?void 0:x.messages)==null?void 0:C.timestamp}},slots:{...(k=kt.layout)==null?void 0:k.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...kt.markdown,...e.markdown,options:{...(w=kt.markdown)==null?void 0:w.options,...(M=e.markdown)==null?void 0:M.options}},messageActions:{...kt.messageActions,...e.messageActions}}:kt}var la={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},ca={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},da={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Pn,maxWidth:Ts,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function $o(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?$o(e,n):n}function ks(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let u=$o(e,a);u!==void 0&&(r[i]={path:i,value:u,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),r}function pa(e){let r=[],t=[];return e.palette||r.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:r.length===0,errors:r,warnings:t}}function id(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=id(o,s):t[n]=s}return t}function Kp(e,r){return r?id(e,r):e}function po(e,r={}){var s,o,a,i,u,c,d,p,g,f,v,E,x;let t={palette:la,semantic:ca,components:da},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(u=e==null?void 0:e.palette)==null?void 0:u.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(d=e==null?void 0:e.semantic)==null?void 0:d.colors,interactive:{...t.semantic.colors.interactive,...(g=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:g.interactive},feedback:{...t.semantic.colors.feedback,...(v=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(E=e==null?void 0:e.semantic)==null?void 0:E.spacing},typography:{...t.semantic.typography,...(x=e==null?void 0:e.semantic)==null?void 0:x.typography}},components:Kp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let C=pa(n);if(!C.valid)throw new Error(`Theme validation failed: ${C.errors.map(k=>k.message).join(", ")}`)}if(r.plugins)for(let C of r.plugins)n=C.transform(n);return n}function Ls(e){var v,E,x,C,k,H,w,M,W,T,G,K,J,I,Q,Ce,re,Ae,Ne,he,ke,Le,ae,xe,je,de,ie,Ee,Be,it,Et,q,F,le,_,V,oe,Oe,Z,te,Lt,lt,Nt,Kt,$e,ce,He,Wt,Rt,ot,st,rn,tn,on,j,Ie,ue,gt,Fe,ne,ye,De,xt,zt,ct,qt,ft,Ke,ht,We,Vt,Gn,tr,$n,Qe,Lr,Xn,Ir,Wn,Kr,gr,nr,at,wn,_n,dn,fr,Sn,wt,pn,Rn,hr,rr,yr,Kn,An,Zn,vt,$t,_t,En,br,jn,Tn,D,zn,Hn,xr,gn,Mn;let r=ks(e),t={};for(let[ee,qn]of Object.entries(r)){let or=ee.replace(/\./g,"-");t[`--persona-${or}`]=qn.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(E=t["--persona-semantic-colors-secondary"])!=null?E:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(x=t["--persona-semantic-colors-accent"])!=null?x:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(C=t["--persona-semantic-colors-surface"])!=null?C:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(k=t["--persona-semantic-colors-background"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(H=t["--persona-semantic-colors-container"])!=null?H:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(M=t["--persona-semantic-colors-text-muted"])!=null?M:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(W=t["--persona-semantic-colors-text-inverse"])!=null?W:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(T=t["--persona-semantic-colors-border"])!=null?T:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(G=t["--persona-semantic-colors-divider"])!=null?G:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(K=t["--persona-components-voice-recording-indicator"])!=null?K:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(J=t["--persona-components-voice-recording-background"])!=null?J:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(I=t["--persona-components-voice-processing-icon"])!=null?I:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(Q=t["--persona-components-voice-speaking-icon"])!=null?Q:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ce=t["--persona-components-approval-requested-background"])!=null?Ce:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(re=t["--persona-components-approval-requested-border"])!=null?re:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ae=t["--persona-components-approval-requested-text"])!=null?Ae:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(Ne=t["--persona-components-approval-approve-background"])!=null?Ne:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(he=t["--persona-components-approval-deny-background"])!=null?he:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ke=t["--persona-components-attachment-image-background"])!=null?ke:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Le=t["--persona-components-attachment-image-border"])!=null?Le:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ae=t["--persona-semantic-typography-fontFamily"])!=null?ae:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(xe=t["--persona-semantic-typography-fontSize"])!=null?xe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(je=t["--persona-semantic-typography-fontWeight"])!=null?je:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(de=t["--persona-semantic-typography-lineHeight"])!=null?de:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(ie=t["--persona-palette-radius-sm"])!=null?ie:"0.125rem",t["--persona-radius-md"]=(Ee=t["--persona-palette-radius-md"])!=null?Ee:"0.375rem",t["--persona-radius-lg"]=(Be=t["--persona-palette-radius-lg"])!=null?Be:"0.5rem",t["--persona-radius-xl"]=(it=t["--persona-palette-radius-xl"])!=null?it:"0.75rem",t["--persona-radius-full"]=(Et=t["--persona-palette-radius-full"])!=null?Et:"9999px",t["--persona-launcher-radius"]=(F=(q=t["--persona-components-launcher-borderRadius"])!=null?q:t["--persona-palette-radius-full"])!=null?F:"9999px",t["--persona-launcher-bg"]=(le=t["--persona-components-launcher-background"])!=null?le:t["--persona-primary"],t["--persona-launcher-fg"]=(_=t["--persona-components-launcher-foreground"])!=null?_:t["--persona-text-inverse"],t["--persona-launcher-border"]=(V=t["--persona-components-launcher-border"])!=null?V:t["--persona-border"],t["--persona-button-primary-bg"]=(oe=t["--persona-components-button-primary-background"])!=null?oe:t["--persona-primary"],t["--persona-button-primary-fg"]=(Oe=t["--persona-components-button-primary-foreground"])!=null?Oe:t["--persona-text-inverse"],t["--persona-button-radius"]=(te=(Z=t["--persona-components-button-primary-borderRadius"])!=null?Z:t["--persona-palette-radius-full"])!=null?te:"9999px",t["--persona-panel-radius"]=(lt=(Lt=t["--persona-components-panel-borderRadius"])!=null?Lt:t["--persona-radius-xl"])!=null?lt:"0.75rem",t["--persona-panel-border"]=(Nt=t["--persona-components-panel-border"])!=null?Nt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=($e=(Kt=t["--persona-components-panel-shadow"])!=null?Kt:t["--persona-palette-shadows-xl"])!=null?$e:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(He=(ce=t["--persona-components-input-borderRadius"])!=null?ce:t["--persona-radius-lg"])!=null?He:"0.5rem",t["--persona-message-user-radius"]=(Rt=(Wt=t["--persona-components-message-user-borderRadius"])!=null?Wt:t["--persona-radius-lg"])!=null?Rt:"0.5rem",t["--persona-message-assistant-radius"]=(st=(ot=t["--persona-components-message-assistant-borderRadius"])!=null?ot:t["--persona-radius-lg"])!=null?st:"0.5rem",t["--persona-header-bg"]=(rn=t["--persona-components-header-background"])!=null?rn:t["--persona-surface"],t["--persona-header-border"]=(tn=t["--persona-components-header-border"])!=null?tn:t["--persona-divider"],t["--persona-header-icon-bg"]=(on=t["--persona-components-header-iconBackground"])!=null?on:t["--persona-primary"],t["--persona-header-icon-fg"]=(j=t["--persona-components-header-iconForeground"])!=null?j:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ie=t["--persona-components-header-titleForeground"])!=null?Ie:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ue=t["--persona-components-header-subtitleForeground"])!=null?ue:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(gt=t["--persona-components-header-actionIconForeground"])!=null?gt:t["--persona-muted"];let n=(Fe=e.components)==null?void 0:Fe.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(ne=t["--persona-components-input-background"])!=null?ne:t["--persona-surface"],t["--persona-input-placeholder"]=(ye=t["--persona-components-input-placeholder"])!=null?ye:t["--persona-text-muted"],t["--persona-message-user-bg"]=(De=t["--persona-components-message-user-background"])!=null?De:t["--persona-accent"],t["--persona-message-user-text"]=(xt=t["--persona-components-message-user-text"])!=null?xt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(zt=t["--persona-components-message-user-shadow"])!=null?zt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(ct=t["--persona-components-message-assistant-background"])!=null?ct:t["--persona-surface"],t["--persona-message-assistant-text"]=(qt=t["--persona-components-message-assistant-text"])!=null?qt:t["--persona-text"],t["--persona-message-assistant-border"]=(ft=t["--persona-components-message-assistant-border"])!=null?ft:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Ke=t["--persona-components-message-assistant-shadow"])!=null?Ke:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(We=(ht=t["--persona-components-scrollToBottom-background"])!=null?ht:t["--persona-button-primary-bg"])!=null?We:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Gn=(Vt=t["--persona-components-scrollToBottom-foreground"])!=null?Vt:t["--persona-button-primary-fg"])!=null?Gn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(tr=t["--persona-components-scrollToBottom-border"])!=null?tr:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=($n=t["--persona-components-scrollToBottom-size"])!=null?$n:"40px",t["--persona-scroll-to-bottom-radius"]=(Xn=(Lr=(Qe=t["--persona-components-scrollToBottom-borderRadius"])!=null?Qe:t["--persona-button-radius"])!=null?Lr:t["--persona-radius-full"])!=null?Xn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Wn=(Ir=t["--persona-components-scrollToBottom-shadow"])!=null?Ir:t["--persona-palette-shadows-sm"])!=null?Wn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Kr=t["--persona-components-scrollToBottom-padding"])!=null?Kr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(gr=t["--persona-components-scrollToBottom-gap"])!=null?gr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(at=(nr=t["--persona-components-scrollToBottom-fontSize"])!=null?nr:t["--persona-palette-typography-fontSize-sm"])!=null?at:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(wn=t["--persona-components-scrollToBottom-iconSize"])!=null?wn:"14px",t["--persona-tool-bubble-shadow"]=(_n=t["--persona-components-toolBubble-shadow"])!=null?_n:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(dn=t["--persona-components-reasoningBubble-shadow"])!=null?dn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(fr=t["--persona-components-composer-shadow"])!=null?fr:"none",t["--persona-md-inline-code-bg"]=(Sn=t["--persona-components-markdown-inlineCode-background"])!=null?Sn:t["--persona-container"],t["--persona-md-inline-code-color"]=(wt=t["--persona-components-markdown-inlineCode-foreground"])!=null?wt:t["--persona-text"],t["--persona-md-link-color"]=(Rn=(pn=t["--persona-components-markdown-link-foreground"])!=null?pn:t["--persona-accent"])!=null?Rn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(hr=t["--persona-components-markdown-codeBlock-background"])!=null?hr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(rr=t["--persona-components-markdown-codeBlock-borderColor"])!=null?rr:t["--persona-border"],t["--persona-md-code-block-text-color"]=(yr=t["--persona-components-markdown-codeBlock-textColor"])!=null?yr:"inherit",t["--persona-md-table-header-bg"]=(Kn=t["--persona-components-markdown-table-headerBackground"])!=null?Kn:t["--persona-container"],t["--persona-md-table-border-color"]=(An=t["--persona-components-markdown-table-borderColor"])!=null?An:t["--persona-border"],t["--persona-md-hr-color"]=(Zn=t["--persona-components-markdown-hr-color"])!=null?Zn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(vt=t["--persona-components-markdown-blockquote-borderColor"])!=null?vt:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=($t=t["--persona-components-markdown-blockquote-background"])!=null?$t:"transparent",t["--persona-md-blockquote-text-color"]=(_t=t["--persona-components-markdown-blockquote-textColor"])!=null?_t:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(En=t["--persona-components-collapsibleWidget-container"])!=null?En:t["--persona-surface"],t["--cw-surface"]=(br=t["--persona-components-collapsibleWidget-surface"])!=null?br:t["--persona-surface"],t["--cw-border"]=(jn=t["--persona-components-collapsibleWidget-border"])!=null?jn:t["--persona-border"],t["--persona-message-border"]=(Tn=t["--persona-components-message-border"])!=null?Tn:t["--persona-border"];let c=e.components,d=c==null?void 0:c.iconButton;d&&(d.background&&(t["--persona-icon-btn-bg"]=d.background),d.border&&(t["--persona-icon-btn-border"]=d.border),d.color&&(t["--persona-icon-btn-color"]=d.color),d.padding&&(t["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(t["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(t["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(t["--persona-icon-btn-active-border"]=d.activeBorder));let p=c==null?void 0:c.labelButton;p&&(p.background&&(t["--persona-label-btn-bg"]=p.background),p.border&&(t["--persona-label-btn-border"]=p.border),p.color&&(t["--persona-label-btn-color"]=p.color),p.padding&&(t["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(t["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(t["--persona-label-btn-gap"]=p.gap));let g=c==null?void 0:c.toggleGroup;g&&(g.gap&&(t["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(t["--persona-toggle-group-radius"]=g.borderRadius));let f=c==null?void 0:c.artifact;if(f!=null&&f.toolbar){let ee=f.toolbar;ee.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ee.iconHoverColor),ee.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ee.iconHoverBackground),ee.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ee.iconPadding),ee.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ee.iconBorderRadius),ee.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ee.iconBorder),ee.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ee.toggleGroupGap),ee.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ee.toggleBorderRadius),ee.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ee.copyBackground),ee.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ee.copyBorder),ee.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ee.copyColor),ee.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ee.copyBorderRadius),ee.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ee.copyPadding),ee.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ee.copyMenuBackground,t["--persona-dropdown-bg"]=(D=t["--persona-dropdown-bg"])!=null?D:ee.copyMenuBackground),ee.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ee.copyMenuBorder,t["--persona-dropdown-border"]=(zn=t["--persona-dropdown-border"])!=null?zn:ee.copyMenuBorder),ee.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ee.copyMenuShadow,t["--persona-dropdown-shadow"]=(Hn=t["--persona-dropdown-shadow"])!=null?Hn:ee.copyMenuShadow),ee.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ee.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(xr=t["--persona-dropdown-radius"])!=null?xr:ee.copyMenuBorderRadius),ee.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ee.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:ee.copyMenuItemHoverBackground),ee.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ee.iconBackground),ee.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ee.toolbarBorder)}if(f!=null&&f.tab){let ee=f.tab;ee.background&&(t["--persona-artifact-tab-bg"]=ee.background),ee.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ee.activeBackground),ee.activeBorder&&(t["--persona-artifact-tab-active-border"]=ee.activeBorder),ee.borderRadius&&(t["--persona-artifact-tab-radius"]=ee.borderRadius),ee.textColor&&(t["--persona-artifact-tab-color"]=ee.textColor),ee.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ee.hoverBackground),ee.listBackground&&(t["--persona-artifact-tab-list-bg"]=ee.listBackground),ee.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ee.listBorderColor),ee.listPadding&&(t["--persona-artifact-tab-list-padding"]=ee.listPadding)}if(f!=null&&f.pane){let ee=f.pane;if(ee.toolbarBackground){let qn=(Mn=$o(e,ee.toolbarBackground))!=null?Mn:ee.toolbarBackground;t["--persona-artifact-toolbar-bg"]=qn}}return t}var ld={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Zp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},cd=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},_o=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Qp=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":_o()},ua=e=>Qp(e),eu=e=>po(e),tu=e=>{var t;let r=po(void 0,{validate:!1});return po({...e,palette:{...r.palette,colors:{...Zp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},jo=e=>{let r=ua(e),t=cd(e==null?void 0:e.theme),n=cd(e==null?void 0:e.darkTheme);return r==="dark"?tu(Oo(t!=null?t:{},n!=null?n:{})):eu(t)},nu=e=>Ls(e),Ar=(e,r)=>{var o;let t=jo(r),n=nu(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Is=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(_o())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(_o());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var dd=require("idiomorph"),pd=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;dd.Idiomorph.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&n&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function ud(e,r){var t,n,s,o,a,i,u,c,d,p,g,f,v,E,x,C,k,H,w,M,W,T,G,K,J,I,Q;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(d=(c=e.llmContent)==null?void 0:c.length)!=null?d:0,(g=(p=e.approval)==null?void 0:p.status)!=null?g:"",(v=(f=e.toolCall)==null?void 0:f.status)!=null?v:"",(C=(x=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:x.length)!=null?C:0,(M=(w=(H=(k=e.toolCall)==null?void 0:k.chunks)==null?void 0:H[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?M:"",typeof((W=e.toolCall)==null?void 0:W.args)=="string"?e.toolCall.args.length:(T=e.toolCall)!=null&&T.args?JSON.stringify(e.toolCall.args).length:0,(J=(K=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:K.length)!=null?J:0,(Q=(I=e.contentParts)==null?void 0:I.length)!=null?Q:0,r].join("\0")}function md(){return new Map}function gd(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function fd(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function hd(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function Ps(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function zo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function qo(e,r){return zo(e)-e.scrollTop<=r}function Ws(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,d=t-n;return a||Math.abs(d)<o?{action:"none",delta:d,nextLastScrollTop:t}:!r&&s&&(!c||d>0)?{action:"resume",delta:d,nextLastScrollTop:t}:r&&i&&d<0?{action:"pause",delta:d,nextLastScrollTop:t}:r&&u&&!s?{action:"pause",delta:d,nextLastScrollTop:t}:{action:"none",delta:d,nextLastScrollTop:t}}function Rs(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var cn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},vn=1e5,Er=vn+1;function ma(e,r=vn){let t=e.style.position,n=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Vo=0,Tr=null;function ga(e=document){var t;if(Vo++,Vo===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Tr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Vo=Math.max(0,Vo-1),Vo===0&&Tr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=Tr.originalOverflow,s.style.position=Tr.originalPosition,s.style.top=Tr.originalTop,s.style.width=Tr.originalWidth,o.scrollTo(0,Tr.scrollY),Tr=null}}}var Hs={side:"right",width:"420px",animate:!0,reveal:"resize"},Xt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Fn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:Hs.side,width:(s=r==null?void 0:r.width)!=null?s:Hs.width,animate:(o=r==null?void 0:r.animate)!=null?o:Hs.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:Hs.reveal}};var Yn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Uo=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
|
|
8
8
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
9
9
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
10
10
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -12,11 +12,14 @@
|
|
|
12
12
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
13
13
|
</span>
|
|
14
14
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
15
|
-
`,t.addEventListener("click",r);let n=o=>{var R,w,L,B,T,Y,ge,ce,$,ne,Te,re,Se,He;let a=(R=o.launcher)!=null?R:{},i=Ut(o),d=t.querySelector("[data-role='launcher-title']");if(d){let he=(w=a.title)!=null?w:"Chat Assistant";d.textContent=he,d.setAttribute("title",he)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let he=(L=a.subtitle)!=null?L:"Get answers fast";c.textContent=he,c.setAttribute("title",he)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=t.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let he=(B=a.agentIconSize)!=null?B:"40px";if(u.style.height=he,u.style.width=he,u.innerHTML="",a.agentIconName){let Me=parseFloat(he)||24,ke=me(a.agentIconName,Me*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(u.appendChild(ke),u.style.display=""):(u.textContent=(T=a.agentIconText)!=null?T:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(Y=a.agentIconText)!=null?Y:"\u{1F4AC}",u.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let he=(ge=a.agentIconSize)!=null?ge:"40px";f.style.height=he,f.style.width=he,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let he=(ce=a.callToActionIconSize)!=null?ce:"32px";m.style.height=he,m.style.width=he,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Me=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Me=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let ke=parseFloat(he)||24,oe=Math.max(ke-Me,8),be=me(a.callToActionIconName,oe,"currentColor",2);be?m.appendChild(be):m.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else m.textContent=(ne=a.callToActionIconText)!=null?ne:"\u2197"}let v=a.position&&zn[a.position]?zn[a.position]:zn["bottom-right"],M="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",b="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?b:`${M} ${v}`,i||(t.style.zIndex=String((Te=a.zIndex)!=null?Te:yn));let C="1px solid var(--persona-border, #e5e7eb)",S="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(re=a.border)!=null?re:C,t.style.boxShadow=(Se=a.shadow)!=null?Se:S,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(He=a.collapsedMaxWidth)!=null?He:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var bn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ir=e=>{var ce,$,ne,Te,re,Se,He,he,Me,ke,oe,be,$e,pe,de,se,De,ot,St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(ce=r==null?void 0:r.launcher)!=null?ce:{},o=($=s.headerIconSize)!=null?$:"48px",a=(ne=s.closeButtonSize)!=null?ne:"32px",i=(Te=s.closeButtonPlacement)!=null?Te:"inline",d=(re=s.headerIconHidden)!=null?re:!1,c=s.headerIconName,p=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(p.style.height=o,p.style.width=o,p.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",p.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!d)if(c){let Ne=parseFloat(o)||24,le=me(c,Ne*.6,"currentColor",1);le?p.replaceChildren(le):p.textContent=(He=(Se=r==null?void 0:r.launcher)==null?void 0:Se.agentIconText)!=null?He:"\u{1F4AC}"}else if((he=r==null?void 0:r.launcher)!=null&&he.iconUrl){let Ne=h("img");Ne.src=r.launcher.iconUrl,Ne.alt="",Ne.className="persona-rounded-xl persona-object-cover",Ne.style.height=o,Ne.style.width=o,p.replaceChildren(Ne)}else p.textContent=(ke=(Me=r==null?void 0:r.launcher)==null?void 0:Me.agentIconText)!=null?ke:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=bn.titleColor,f.textContent=(be=(oe=r==null?void 0:r.launcher)==null?void 0:oe.title)!=null?be:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=bn.subtitleColor,m.textContent=(pe=($e=r==null?void 0:r.launcher)==null?void 0:$e.subtitle)!=null?pe:"Here to help you get answers fast",u.append(f,m),d?n.append(u):n.append(p,u);let v=(de=s.clearChat)!=null?de:{},M=(se=v.enabled)!=null?se:!0,b=(De=v.placement)!=null?De:"inline",C=null,S=null;if(M){let Ne=(ot=v.size)!=null?ot:"32px",le=(St=v.iconName)!=null?St:"refresh-cw",Ie=(j=v.iconColor)!=null?j:"",At=(q=v.backgroundColor)!=null?q:"",Et=(ae=v.borderWidth)!=null?ae:"",Ze=(_=v.borderColor)!=null?_:"",Qe=(z=v.borderRadius)!=null?z:"",Kt=(ee=v.paddingX)!=null?ee:"",Gt=(Fe=v.paddingY)!=null?Fe:"",Zt=(J=v.tooltipText)!=null?J:"Clear chat",O=(K=v.showTooltip)!=null?K:!0;S=h("div",b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),b==="top-right"&&(S.style.right="48px"),C=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),C.style.height=Ne,C.style.width=Ne,C.type="button",C.setAttribute("aria-label",Zt),C.style.color=Ie||bn.actionIconColor;let Le=me(le,"20px","currentColor",1);if(Le&&C.appendChild(Le),At&&(C.style.backgroundColor=At,C.classList.remove("hover:persona-bg-gray-100")),Et||Ze){let ue=Et||"0px",at=Ze||"transparent";C.style.border=`${ue} solid ${at}`,C.classList.remove("persona-border-none")}if(Qe&&(C.style.borderRadius=Qe,C.classList.remove("persona-rounded-full")),Kt?(C.style.paddingLeft=Kt,C.style.paddingRight=Kt):(C.style.paddingLeft="",C.style.paddingRight=""),Gt?(C.style.paddingTop=Gt,C.style.paddingBottom=Gt):(C.style.paddingTop="",C.style.paddingBottom=""),S.appendChild(C),O&&Zt&&C&&S){let ue=null,at=()=>{if(ue||!C)return;let Z=C.ownerDocument,ye=Z.body;if(!ye)return;ue=Yn(Z,"div","persona-clear-chat-tooltip"),ue.textContent=Zt;let Pe=Yn(Z,"div");Pe.className="persona-clear-chat-tooltip-arrow",ue.appendChild(Pe);let dt=C.getBoundingClientRect();ue.style.position="fixed",ue.style.zIndex=String(Sr),ue.style.left=`${dt.left+dt.width/2}px`,ue.style.top=`${dt.top-8}px`,ue.style.transform="translate(-50%, -100%)",ye.appendChild(ue)},Be=()=>{ue&&ue.parentNode&&(ue.parentNode.removeChild(ue),ue=null)};S.addEventListener("mouseenter",at),S.addEventListener("mouseleave",Be),C.addEventListener("focus",at),C.addEventListener("blur",Be),S._cleanupTooltip=()=>{Be(),S&&(S.removeEventListener("mouseenter",at),S.removeEventListener("mouseleave",Be)),C&&(C.removeEventListener("focus",at),C.removeEventListener("blur",Be))}}b==="inline"&&n.appendChild(S)}let R=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":M&&b==="inline"?"":"persona-ml-auto"),w=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");w.style.height=a,w.style.width=a,w.type="button";let L=(vt=s.closeButtonTooltipText)!=null?vt:"Close chat",B=(tt=s.closeButtonShowTooltip)!=null?tt:!0;w.setAttribute("aria-label",L),w.style.display=t?"":"none";let T=(Lt=s.closeButtonIconName)!=null?Lt:"x",Y=(Vt=s.closeButtonIconText)!=null?Vt:"\xD7";w.style.color=s.closeButtonColor||bn.actionIconColor;let ge=me(T,"20px","currentColor",1);if(ge?w.appendChild(ge):w.textContent=Y,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let Ne=s.closeButtonBorderWidth||"0px",le=s.closeButtonBorderColor||"transparent";w.style.border=`${Ne} solid ${le}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),R.appendChild(w),B&&L){let Ne=null,le=()=>{if(Ne)return;let At=w.ownerDocument,Et=At.body;if(!Et)return;Ne=Yn(At,"div","persona-clear-chat-tooltip"),Ne.textContent=L;let Ze=Yn(At,"div");Ze.className="persona-clear-chat-tooltip-arrow",Ne.appendChild(Ze);let Qe=w.getBoundingClientRect();Ne.style.position="fixed",Ne.style.zIndex=String(Sr),Ne.style.left=`${Qe.left+Qe.width/2}px`,Ne.style.top=`${Qe.top-8}px`,Ne.style.transform="translate(-50%, -100%)",Et.appendChild(Ne)},Ie=()=>{Ne&&Ne.parentNode&&(Ne.parentNode.removeChild(Ne),Ne=null)};R.addEventListener("mouseenter",le),R.addEventListener("mouseleave",Ie),w.addEventListener("focus",le),w.addEventListener("blur",Ie),R._cleanupTooltip=()=>{Ie(),R.removeEventListener("mouseenter",le),R.removeEventListener("mouseleave",Ie),w.removeEventListener("focus",le),w.removeEventListener("blur",Ie)}}return i!=="top-right"&&n.appendChild(R),{header:n,iconHolder:p,headerTitle:f,headerSubtitle:m,closeButton:w,closeButtonWrapper:R,clearChatButton:C,clearChatButtonWrapper:S}},_r=(e,r,t)=>{var a,i,d,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(d=n.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function Er(e){let{items:r,onSelect:t,anchor:n,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Sr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of r){if(m.dividerBefore){let b=document.createElement("hr");a.appendChild(b)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let b=me(m.icon,16,"currentColor",1.5);b&&v.appendChild(b)}let M=document.createElement("span");M.textContent=m.label,v.appendChild(M),v.addEventListener("click",b=>{b.stopPropagation(),p(),t(m.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let m=n.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!n.contains(v.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function wt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=me(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function $o(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=h("button",c);if(p.type="button",p.setAttribute("aria-label",t),r){let f=me(r,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let u=h("span");if(u.textContent=t,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))p.setAttribute(f,m);return p}function _o(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let u;p.icon?u=wt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(u=h("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),o.appendChild(u)}function c(p){a=p,d()}return{element:o,setSelected:c}}function As(e){var m,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let p=h("span","persona-combo-btn-label");p.textContent=r,c.appendChild(p);let u=me(t,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var M,b;c.style.backgroundColor=(M=d.background)!=null?M:"",c.style.borderColor=(b=d.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Er({items:n,onSelect:M=>{c.setAttribute("aria-expanded","false"),s(M)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",M=>{M.stopPropagation();let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),c.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),c.click())}),{element:c,setLabel:M=>{p.textContent=M,c.setAttribute("aria-label",M)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let M=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var ta=e=>{var n;let r=ir({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return r};function Ep(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let d=me(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let c=Er({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var na=e=>{var S,R,w,L,B,T,Y,ge,ce;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(S=r==null?void 0:r.launcher)!=null?S:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,c,p;if(d)c=As({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=bn.titleColor,p=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=bn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),Ep(c,s==null?void 0:s.trailingActions,(B=s==null?void 0:s.onAction)!=null?B:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ne=s.onTitleClick;c.addEventListener("click",Te=>{Te.target.closest("button")||ne()}),c.addEventListener("keydown",Te=>{(Te.key==="Enter"||Te.key===" ")&&(Te.preventDefault(),ne())})}let $=s==null?void 0:s.titleRowHover;$&&(c.style.borderRadius=(T=$.borderRadius)!=null?T:"10px",c.style.padding=(Y=$.padding)!=null?Y:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var ne,Te;c.style.backgroundColor=(ne=$.background)!=null?ne:"",c.style.borderColor=(Te=$.border)!=null?Te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=(ge=a.closeButtonSize)!=null?ge:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||bn.actionIconColor;let v=(ce=a.closeButtonIconName)!=null?ce:"x",M=me(v,"20px","currentColor",2);M?m.appendChild(M):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let b=h("div");b.style.display="none";let C=h("span");return C.style.display="none",{header:i,iconHolder:b,headerTitle:p,headerSubtitle:C,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Es={default:ta,minimal:na},ra=e=>{var r;return(r=Es[e])!=null?r:Es.default},ao=(e,r,t)=>{var a,i,d;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),p=h("div");p.style.display="none";let u=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=ra(n)({config:e,showClose:(d=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var io=e=>{var De,ot,St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt,Ne,le,Ie,At,Et,Ze,Qe,Kt,Gt,Zt,O;let{config:r}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let n=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(ot=(De=r==null?void 0:r.copy)==null?void 0:De.inputPlaceholder)!=null?ot:"Type your message\u2026",o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let d=3*20;o.style.maxHeight=`${d}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let Le=Math.min(o.scrollHeight,d);o.style.height=`${Le}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let p=(St=r==null?void 0:r.sendButton)!=null?St:{},u=(j=p.useIcon)!=null?j:!1,f=(q=p.iconText)!=null?q:"\u2191",m=p.iconName,v=(ae=p.tooltipText)!=null?ae:"Send message",M=(_=p.showTooltip)!=null?_:!1,b=(z=p.size)!=null?z:"40px",C=p.backgroundColor,S=p.textColor,R=h("div","persona-send-button-wrapper"),w=h("button",u?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),u){if(w.style.width=b,w.style.height=b,w.style.minWidth=b,w.style.minHeight=b,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",S?w.style.color=S:w.style.color="var(--persona-button-primary-fg, #ffffff)",m){let Le=parseFloat(b)||24,ue=(S==null?void 0:S.trim())||"currentColor",at=me(m,Le,ue,2);at?w.appendChild(at):w.textContent=f}else w.textContent=f;C?w.style.backgroundColor=C:w.classList.add("persona-bg-persona-primary")}else w.textContent=(Fe=(ee=r==null?void 0:r.copy)==null?void 0:ee.sendButtonLabel)!=null?Fe:"Send",S?w.style.color=S:w.classList.add("persona-text-white");if(p.borderWidth&&(w.style.borderWidth=p.borderWidth,w.style.borderStyle="solid"),p.borderColor&&(w.style.borderColor=p.borderColor),p.paddingX?(w.style.paddingLeft=p.paddingX,w.style.paddingRight=p.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),p.paddingY?(w.style.paddingTop=p.paddingY,w.style.paddingBottom=p.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),M&&v){let Le=h("div","persona-send-button-tooltip");Le.textContent=v,R.appendChild(Le)}R.appendChild(w);let L=(J=r==null?void 0:r.voiceRecognition)!=null?J:{},B=L.enabled===!0,T=null,Y=null,ge=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ce=((K=L.provider)==null?void 0:K.type)==="runtype";if(B&&(ge||ce)){Y=h("div","persona-send-button-wrapper"),T=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),T.type="button",T.setAttribute("data-persona-composer-mic",""),T.setAttribute("aria-label","Start voice recognition");let Le=(vt=L.iconName)!=null?vt:"mic",ue=(tt=L.iconSize)!=null?tt:b,at=parseFloat(ue)||24,Be=(Lt=L.backgroundColor)!=null?Lt:C,Z=(Vt=L.iconColor)!=null?Vt:S;T.style.width=ue,T.style.height=ue,T.style.minWidth=ue,T.style.minHeight=ue,T.style.fontSize="18px",T.style.lineHeight="1",Z?T.style.color=Z:T.style.color="var(--persona-text, #111827)";let Pe=me(Le,at,Z||"currentColor",1.5);Pe?T.appendChild(Pe):T.textContent="\u{1F3A4}",Be&&(T.style.backgroundColor=Be),L.borderWidth&&(T.style.borderWidth=L.borderWidth,T.style.borderStyle="solid"),L.borderColor&&(T.style.borderColor=L.borderColor),L.paddingX&&(T.style.paddingLeft=L.paddingX,T.style.paddingRight=L.paddingX),L.paddingY&&(T.style.paddingTop=L.paddingY,T.style.paddingBottom=L.paddingY),Y.appendChild(T);let dt=(Ne=L.tooltipText)!=null?Ne:"Start voice recognition";if(((le=L.showTooltip)!=null?le:!1)&&dt){let nt=h("div","persona-send-button-tooltip");nt.textContent=dt,Y.appendChild(nt)}}let ne=(Ie=r==null?void 0:r.attachments)!=null?Ie:{},Te=ne.enabled===!0,re=null,Se=null,He=null,he=null;if(Te){he=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),he.style.display="none",He=h("input"),He.type="file",He.accept=((At=ne.allowedTypes)!=null?At:ar).join(","),He.multiple=((Et=ne.maxFiles)!=null?Et:4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),Se=h("div","persona-send-button-wrapper"),re=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),re.type="button",re.setAttribute("aria-label",(Ze=ne.buttonTooltipText)!=null?Ze:"Attach file");let Le=(Qe=ne.buttonIconName)!=null?Qe:"paperclip",ue=b,at=parseFloat(ue)||40,Be=Math.round(at*.6);re.style.width=ue,re.style.height=ue,re.style.minWidth=ue,re.style.minHeight=ue,re.style.fontSize="18px",re.style.lineHeight="1",re.style.backgroundColor="transparent",re.style.color="var(--persona-primary, #111827)",re.style.border="none",re.style.borderRadius="6px",re.style.transition="background-color 0.15s ease",re.addEventListener("mouseenter",()=>{re.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),re.addEventListener("mouseleave",()=>{re.style.backgroundColor="transparent"});let Z=me(Le,Be,"currentColor",1.5);Z?re.appendChild(Z):re.textContent="\u{1F4CE}",re.addEventListener("click",dt=>{dt.preventDefault(),He==null||He.click()}),Se.appendChild(re);let ye=(Kt=ne.buttonTooltipText)!=null?Kt:"Attach file",Pe=h("div","persona-send-button-tooltip");Pe.textContent=ye,Se.appendChild(Pe)}s.addEventListener("click",Le=>{Le.target!==w&&Le.target!==R&&Le.target!==T&&Le.target!==Y&&Le.target!==re&&Le.target!==Se&&o.focus()}),he&&(he.style.gap="8px",s.append(he)),He&&s.append(He),s.append(o);let Me=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),ke=h("div","persona-flex persona-items-center persona-gap-2");Se&&ke.append(Se);let oe=h("div","persona-flex persona-items-center persona-gap-1");Y&&oe.append(Y),oe.append(R),Me.append(ke,oe),s.append(Me);let be=(Gt=r==null?void 0:r.statusIndicator)!=null?Gt:{},$e=be.align==="left"?"persona-text-left":be.align==="center"?"persona-text-center":"persona-text-right",pe=h("div",`persona-mt-2 ${$e} persona-text-xs persona-text-persona-muted`);pe.setAttribute("data-persona-composer-status","");let de=(Zt=be.visible)!=null?Zt:!0;pe.style.display=de?"":"none";let se=(O=be.idleText)!=null?O:"Online";if(be.idleLink){let Le=h("a");Le.href=be.idleLink,Le.target="_blank",Le.rel="noopener noreferrer",Le.textContent=se,Le.style.color="inherit",Le.style.textDecoration="none",pe.appendChild(Le)}else pe.textContent=se;return t.append(n,s,pe),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:R,micButton:T,micButtonWrapper:Y,statusText:pe,attachmentButton:re,attachmentButtonWrapper:Se,attachmentInput:He,attachmentPreviewsContainer:he,actionsRow:Me,leftActions:ke,rightActions:oe}};var _c=e=>{var c,p,u,f,m,v,M,b,C;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(Ut(e)){let S=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),R=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return S.appendChild(R),{wrapper:S,panel:R}}if(!r){let S=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),R=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(f=(u=e==null?void 0:e.launcher)==null?void 0:u.width)!=null?f:"100%";return S.style.width=w,R.style.width="100%",S.appendChild(R),{wrapper:S,panel:R}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&zn[n.position]?zn[n.position]:zn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:yn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(C=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?C:e==null?void 0:e.launcherWidth,d=i!=null?i:Mn;return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},jc=(e,r=!0)=>{var b,C,S,R,w,L,B,T,Y;let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(b=e==null?void 0:e.layout)==null?void 0:b.header,s=((C=e==null?void 0:e.layout)==null?void 0:C.showHeader)!==!1,o=n?ao(e,n,{showClose:r}):ir({config:e,showClose:r}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=Ut(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",d=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(R=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeTitle)!=null?R:"Hello \u{1F44B}";let p=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(L=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",d.append(c,p);let u=h("div","persona-flex persona-flex-col persona-gap-3"),f=(B=e==null?void 0:e.layout)==null?void 0:B.contentMaxWidth;f&&(u.style.maxWidth=f,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),d.setAttribute("data-persona-intro-card",""),((T=e==null?void 0:e.copy)==null?void 0:T.showWelcomeCard)!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,u);let v=io({config:e}),M=((Y=e==null?void 0:e.layout)==null?void 0:Y.showFooter)!==!1;return s?_r(t,o,e):(o.header.style.display="none",_r(t,o,e)),t.append(a),M||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:u,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle:p,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var Tp=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Mp=320,kp=320,Lp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Ip=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,d)=>{var u;let c=h("img");c.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Mp}px`,c.style.maxHeight=`${kp}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),Tp(i.image)?(c.src=i.image,n.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},jr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},oa=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:jr};if(r){let s=r(n);if(s!==null)return s}return jr()},Pp=(e,r)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let s=h("img");s.src=n,s.alt=r==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},zc=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Wp=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},sa=(e,r,t)=>{var m,v,M,b,C,S;let n=(m=r.showCopy)!=null?m:!0,s=(v=r.showUpvote)!=null?v:!0,o=(M=r.showDownvote)!=null?M:!0;if(!n&&!s&&!o){let R=h("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let a=(b=r.visibility)!=null?b:"hover",i=(C=r.align)!=null?C:"right",d=(S=r.layout)!=null?S:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let f=(R,w,L)=>{let B=wt({icon:R,label:w,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",L),B};return n&&u.appendChild(f("copy","Copy message","copy")),s&&u.appendChild(f("thumbs-up","Upvote","upvote")),o&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},lo=(e,r,t,n,s,o)=>{var ce,$,ne,Te,re,Se,He;let a=t!=null?t:{},i=(ce=a.layout)!=null?ce:"bubble",d=a.avatar,c=a.timestamp,p=($=d==null?void 0:d.show)!=null?$:!1,u=(ne=c==null?void 0:c.show)!=null?ne:!1,f=(Te=d==null?void 0:d.position)!=null?Te:"left",m=(re=c==null?void 0:c.position)!=null?re:"below",v=Wp(e.role,i),M=h("div",v.join(" "));M.id=`bubble-${e.id}`,M.setAttribute("data-message-id",e.id),M.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(M.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",M.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(M.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",M.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=Lp(e),C=(He=(Se=e.content)==null?void 0:Se.trim())!=null?He:"",R=b.length>0&&C===ls,w=document.createElement("div");w.classList.add("persona-message-content");let L=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),B=null;if(R?(B=document.createElement("div"),B.innerHTML=L,B.style.display="none",w.appendChild(B)):w.innerHTML=L,u&&m==="inline"&&e.createdAt){let he=zc(e,c);he.classList.add("persona-ml-2","persona-inline"),w.appendChild(he)}if(b.length>0){let he=Ip(b,!R&&!!C,()=>{R&&B&&(B.style.display="")});he?M.appendChild(he):R&&B&&(B.style.display="")}if(M.appendChild(w),u&&m==="below"&&e.createdAt){let he=zc(e,c);he.classList.add("persona-mt-1"),M.appendChild(he)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let he=oa("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&M.appendChild(he)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let he=sa(e,n,s);M.appendChild(he)}if(!p||e.role==="system")return M;let Y=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ge=Pp(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Y.append(M,ge):Y.append(ge,M),M.classList.remove("persona-max-w-[85%]"),M.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},Uc=(e,r,t,n,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):lo(e,r,t,n,s,o)};var co=new Set,Vc=(e,r)=>{let t=co.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t");if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let o=n.querySelector(".persona-ml-auto"),a=o==null?void 0:o.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=me(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},aa=e=>{let r=e.reasoning,t=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),!r)return t;let n=co.has(e.id),s=h("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");s.type="button",s.setAttribute("aria-expanded",n?"true":"false"),s.setAttribute("data-expand-header","true"),s.setAttribute("data-bubble-type","reasoning");let o=h("div","persona-flex persona-flex-col persona-text-left"),a=h("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",o.appendChild(a);let i=h("span","persona-text-xs persona-text-persona-primary");i.textContent=mc(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let d=h("div","persona-flex persona-items-center"),p=me(n?"chevron-up":"chevron-down",16,"currentColor",2);p?d.appendChild(p):d.textContent=n?"Hide":"Show";let u=h("div","persona-flex persona-items-center persona-ml-auto");u.append(d),s.append(o,u);let f=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");f.style.display=n?"":"none";let m=r.chunks.join(""),v=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return v.textContent=m||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(v),(()=>{s.setAttribute("aria-expanded",n?"true":"false"),d.innerHTML="";let C=me(n?"chevron-up":"chevron-down",16,"currentColor",2);C?d.appendChild(C):d.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var po=new Set,qc=(e,r,t)=>{var c;let n=po.has(e),s=(c=t==null?void 0:t.toolCall)!=null?c:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t");if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",u=me(n?"chevron-up":"chevron-down",16,p,2);u?d.appendChild(u):d.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},ia=(e,r)=>{var M;let t=e.toolCall,n=(M=r==null?void 0:r.toolCall)!=null?M:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=po.has(e.id),a=h("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");a.type="button",a.setAttribute("aria-expanded",o?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(a.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(a.style.paddingLeft=n.headerPaddingX,a.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(a.style.paddingTop=n.headerPaddingY,a.style.paddingBottom=n.headerPaddingY);let i=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(d.style.color=n.headerTextColor),d.textContent=fc(t),i.appendChild(d);let c=h("div","persona-flex persona-items-center"),p=n.toggleTextColor||n.headerTextColor||"currentColor",u=me(o?"chevron-up":"chevron-down",16,p,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show";let f=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");f.append(c),a.append(i,f);let m=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=o?"":"none",n.contentBackgroundColor&&(m.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(m.style.color=n.contentTextColor),n.contentPaddingX&&(m.style.paddingLeft=n.contentPaddingX,m.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(m.style.paddingTop=n.contentPaddingY,m.style.paddingBottom=n.contentPaddingY),t.name){let b=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?b.style.color=n.contentTextColor:n.headerTextColor&&(b.style.color=n.headerTextColor),b.textContent=t.name,m.appendChild(b)}if(t.args!==void 0){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Arguments";let S=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=Lo(t.args),b.append(C,S),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Activity";let S=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=t.chunks.join(""),b.append(C,S),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Result";let S=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=Lo(t.result),b.append(C,S),m.appendChild(b)}if(t.status==="complete"&&typeof t.duration=="number"){let b=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(b.style.color=n.contentTextColor),b.textContent=`Duration: ${t.duration}ms`,m.appendChild(b)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let b=n.toggleTextColor||n.headerTextColor||"currentColor",C=me(o?"chevron-up":"chevron-down",16,b,2);C?c.appendChild(C):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var la=(e,r)=>{var M,b,C,S,R,w,L,B,T,Y,ge,ce;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(M=n==null?void 0:n.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(b=n==null?void 0:n.borderColor)!=null?b:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(C=n==null?void 0:n.titleColor)!=null?C:"currentColor",p=me(d,20,c,2);p&&i.appendChild(p);let u=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(S=n==null?void 0:n.title)!=null?S:"Approval Required",f.appendChild(m),!s){let $=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");$.setAttribute("data-approval-status",t.status),t.status==="approved"?($.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",$.style.color="var(--persona-palette-colors-success-700, #15803d)",$.textContent="Approved"):t.status==="denied"?($.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",$.style.color="var(--persona-palette-colors-error-700, #b91c1c)",$.textContent="Denied"):t.status==="timeout"&&($.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",$.style.color="var(--persona-palette-colors-warning-700, #b45309)",$.textContent="Timeout"),f.appendChild($)}u.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,u.appendChild(v),t.parameters){let $=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&($.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&($.style.color=n.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=Lo(t.parameters),u.appendChild($)}if(s){let $=h("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let ne=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ne.type="button",ne.style.backgroundColor=(R=n==null?void 0:n.approveButtonColor)!=null?R:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",ne.setAttribute("data-approval-action","approve");let Te=me("shield-check",14,(L=n==null?void 0:n.approveButtonTextColor)!=null?L:"#ffffff",2);Te&&(Te.style.marginRight="4px",ne.appendChild(Te));let re=document.createTextNode((B=n==null?void 0:n.approveLabel)!=null?B:"Approve");ne.appendChild(re);let Se=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Se.type="button",Se.style.backgroundColor=(T=n==null?void 0:n.denyButtonColor)!=null?T:"transparent",Se.style.color=(Y=n==null?void 0:n.denyButtonTextColor)!=null?Y:"var(--persona-feedback-error, #dc2626)",Se.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Se.setAttribute("data-approval-action","deny");let He=me("shield-x",14,(ge=n==null?void 0:n.denyButtonTextColor)!=null?ge:"var(--persona-feedback-error, #dc2626)",2);He&&(He.style.marginRight="4px",Se.appendChild(He));let he=document.createTextNode((ce=n==null?void 0:n.denyLabel)!=null?ce:"Deny");Se.appendChild(he),$.append(ne,Se),u.appendChild($)}return a.append(i,u),o.appendChild(a),o};var Jc=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let p=document.createDocumentFragment(),u=s?s.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(m=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=u,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),p.appendChild(v),r.push(v)}),e.appendChild(p)}}};var jo=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var zo=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function uo(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Rp={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Hp={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Bp=["flowName","stepName","reasoningText","text","name","tool","toolName"],Dp=100;function Fp(e,r){let t={...Rp,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Hp}function Np(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function Op(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${s}.${o}`}function $p(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let s=n.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function _p(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function jp(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function zp(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function ca(e,r,t,n,s,o,a,i){var f;let d=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");uo(c,(f=n.classNames)==null?void 0:f.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(u()),c;function u(){var ne,Te;let m=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let M=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=me(d?"chevron-down":"chevron-right","14px","currentColor",2);b&&M.appendChild(b);let C=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(ne=n.timestampFormat)!=null?ne:"relative";C.textContent=S==="relative"?Np(e.timestamp,t):Op(e.timestamp);let R=null;n.showSequenceNumbers!==!1&&(R=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(r+1));let w=Fp(e.type,n.badgeColors),L=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");L.style.backgroundColor=w.bg,L.style.color=w.text,L.style.borderColor=w.text+"50",L.textContent=e.type;let B=(Te=n.descriptionFields)!=null?Te:Bp,T=$p(e.payload,B),Y=null;T&&(Y=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Y.textContent=T);let ge=h("div","persona-flex-1 persona-min-w-0"),ce=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),$=me("clipboard","12px","currentColor",1.5);return $&&ce.appendChild($),ce.addEventListener("click",async re=>{re.stopPropagation(),await _p(jp(e)),ce.innerHTML="";let Se=me("check","12px","currentColor",1.5);Se&&ce.appendChild(Se),setTimeout(()=>{ce.innerHTML="";let He=me("clipboard","12px","currentColor",1.5);He&&ce.appendChild(He)},1500)}),v.appendChild(M),v.appendChild(C),R&&v.appendChild(R),v.appendChild(L),Y&&v.appendChild(Y),v.appendChild(ge),v.appendChild(ce),m.appendChild(v),d&&m.appendChild(zp(e,a,i)),m}}function Yc(e){var m,v,M,b,C;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(m=s==null?void 0:s.features)==null?void 0:m.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,d=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(M=a==null?void 0:a.label)!=null?M:"",p=(C=(b=s==null?void 0:s.features)==null?void 0:b.eventStream)!=null?C:{},u=o.find(S=>S.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&s){let S=u.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(S)return{element:S,update:()=>{},destroy:()=>{}}}return f();function f(){let S=p.classNames,R=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");uo(R,S==null?void 0:S.panel);let w=[],L="",B="",T=null,Y=[],ge={},ce=0,$=vs(),ne=0,Te=0,re=!1,Se=null,He=!1,he=0,Me=new Set,ke=new Map,oe="",be="",$e=null,pe,de,se,De,ot;function St(){let Z=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),ye=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");uo(ye,S==null?void 0:S.headerBar);let Pe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Pe.textContent="Events",pe=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),pe.textContent="0";let dt=h("div","persona-flex-1");de=h("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ot=h("option","");Ot.value="",Ot.textContent="All events",de.appendChild(Ot),se=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),se.type="button",se.title="Copy All";let $t=me("clipboard-copy","12px","currentColor",1.5);$t&&se.appendChild($t);let it=h("span","persona-text-xs");it.textContent="Copy All",se.appendChild(it),ye.appendChild(Pe),ye.appendChild(pe),ye.appendChild(dt),ye.appendChild(de),ye.appendChild(se);let qe=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");uo(qe,S==null?void 0:S.searchBar);let lt=me("search","14px","var(--persona-muted, #9ca3af)",1.5),_e=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");lt&&_e.appendChild(lt),De=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),uo(De,S==null?void 0:S.searchInput),De.type="text",De.placeholder="Search event payloads...",ot=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ot.type="button",ot.style.display="none";let _t=me("x","12px","currentColor",2);return _t&&ot.appendChild(_t),qe.appendChild(_e),qe.appendChild(De),qe.appendChild(ot),Z.appendChild(ye),Z.appendChild(qe),Z}let j,q=o.find(Z=>Z.renderEventStreamToolbar);if(q!=null&&q.renderEventStreamToolbar&&s){let Z=q.renderEventStreamToolbar({config:s,defaultRenderer:()=>St(),eventCount:r.getSize(),filteredCount:0,onFilterChange:ye=>{L=ye,Vt(),Ie()},onSearchChange:ye=>{B=ye,Vt(),Ie()}});j=Z!=null?Z:St()}else j=St();let ae=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");ae.style.display="none";let _=h("div","persona-flex-1 persona-min-h-0 persona-relative"),z=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");z.style.height="100%";let ee=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");uo(ee,S==null?void 0:S.scrollIndicator),ee.style.display="none",ee.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Fe=me(d,"14px","currentColor",2);Fe&&ee.appendChild(Fe);let J=h("span","");J.textContent=c,ee.appendChild(J);let K=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");K.style.display="none",_.appendChild(z),_.appendChild(K),_.appendChild(ee),R.setAttribute("tabindex","0"),R.appendChild(j),R.appendChild(ae),R.appendChild(_);function vt(){let Z=r.getAll(),ye={};for(let it of Z)ye[it.type]=(ye[it.type]||0)+1;let Pe=Object.keys(ye).sort(),dt=Pe.length!==Y.length||!Pe.every((it,qe)=>it===Y[qe]),Ot=!dt&&Pe.some(it=>ye[it]!==ge[it]),nt=Z.length!==Object.values(ge).reduce((it,qe)=>it+qe,0);if(!dt&&!Ot&&!nt||(Y=Pe,ge=ye,!de))return;let $t=de.value;if(de.options[0].textContent="All events",dt){for(;de.options.length>1;)de.remove(1);for(let it of Pe){let qe=h("option","");qe.value=it,qe.textContent=`${it} (${ye[it]||0})`,de.appendChild(qe)}$t&&Pe.includes($t)?de.value=$t:$t&&(de.value="",L="")}else for(let it=1;it<de.options.length;it++){let qe=de.options[it];qe.textContent=`${qe.value} (${ye[qe.value]||0})`}}function tt(){let Z=r.getAll();if(L&&(Z=Z.filter(ye=>ye.type===L)),B){let ye=B.toLowerCase();Z=Z.filter(Pe=>Pe.type.toLowerCase().includes(ye)||Pe.payload.toLowerCase().includes(ye))}return Z}function Lt(){return L!==""||B!==""}function Vt(){ce=0,ne=0,$.resume(),ee.style.display="none"}function Ne(Z){Me.has(Z)?Me.delete(Z):Me.add(Z),$e=Z;let ye=z.scrollTop,Pe=$.isFollowing();He=!0,$.pause(),Ie(),z.scrollTop=ye,Pe&&$.resume(),He=!1}function le(){return Fo(z,50)}function Ie(){Te=Date.now(),re=!1,vt();let Z=r.getEvictedCount();Z>0?(ae.textContent=`${Z.toLocaleString()} older events truncated`,ae.style.display=""):ae.style.display="none",w=tt();let ye=w.length,Pe=r.getSize()>0;pe&&(pe.textContent=String(r.getSize())),ye===0&&Pe&&Lt()?(K.textContent=B?`No events matching '${B}'`:"No events matching filter",K.style.display="",z.style.display="none"):(K.style.display="none",z.style.display=""),se&&(se.title=Lt()?`Copy Filtered (${ye})`:"Copy All"),i&&!$.isFollowing()&&ye>ce&&(ne+=ye-ce,J.textContent=c?`${c}${ne>0?` (${ne})`:""}`:"",ee.style.display=""),ce=ye;let dt=r.getAll(),Ot=dt.length>0?dt[0].timestamp:0,nt=new Set(w.map(qe=>qe.id));for(let qe of Me)nt.has(qe)||Me.delete(qe);let $t=L!==oe||B!==be,it=ke.size===0&&w.length>0;if($t||it||w.length===0){z.innerHTML="",ke.clear();let qe=document.createDocumentFragment();for(let lt=0;lt<w.length;lt++){let _e=ca(w[lt],lt,Ot,p,Me,Ne,o,s);ke.set(w[lt].id,_e),qe.appendChild(_e)}z.appendChild(qe),oe=L,be=B,$e=null}else{if($e!==null){let lt=ke.get($e);if(lt&<.parentNode===z){let _e=w.findIndex(_t=>_t.id===$e);if(_e>=0){let _t=ca(w[_e],_e,Ot,p,Me,Ne,o,s);z.insertBefore(_t,lt),lt.remove(),ke.set($e,_t)}}$e=null}let qe=new Set(w.map(lt=>lt.id));for(let[lt,_e]of ke)qe.has(lt)||(_e.remove(),ke.delete(lt));for(let lt=0;lt<w.length;lt++){let _e=w[lt];if(!ke.has(_e.id)){let _t=ca(_e,lt,Ot,p,Me,Ne,o,s);ke.set(_e.id,_t),z.appendChild(_t)}}}$.isFollowing()&&(z.scrollTop=z.scrollHeight)}function At(){if(Date.now()-Te>=Dp){Se!==null&&(cancelAnimationFrame(Se),Se=null),Ie();return}re||(re=!0,Se=requestAnimationFrame(()=>{Se=null,Ie()}))}let Et=(Z,ye)=>{if(!se)return;se.innerHTML="";let Pe=me(Z,"12px","currentColor",1.5);Pe&&se.appendChild(Pe);let dt=h("span","persona-text-xs");dt.textContent="Copy All",se.appendChild(dt),setTimeout(()=>{se.innerHTML="";let Ot=me("clipboard-copy","12px","currentColor",1.5);Ot&&se.appendChild(Ot);let nt=h("span","persona-text-xs");nt.textContent="Copy All",se.appendChild(nt),se.disabled=!1},ye)},Ze=async()=>{if(se){se.disabled=!0;try{let Z;Lt()?Z=w:t?(Z=await t(),Z.length===0&&(Z=r.getAll())):Z=r.getAll();let ye=Z.map(Pe=>{try{return JSON.parse(Pe.payload)}catch{return Pe.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),Et("check",1500)}catch{Et("x",1500)}}},Qe=()=>{de&&(L=de.value,Vt(),Ie())},Kt=()=>{!De||!ot||(ot.style.display=De.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{B=De.value,Vt(),Ie()},150))},Gt=()=>{!De||!ot||(De.value="",B="",ot.style.display="none",T&&clearTimeout(T),Vt(),Ie())},Zt=()=>{if(He)return;let Z=z.scrollTop,{action:ye,nextLastScrollTop:Pe}=Cs({following:$.isFollowing(),currentScrollTop:Z,lastScrollTop:he,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=Pe,ye==="resume"?($.resume(),ne=0,ee.style.display="none"):ye==="pause"&&($.pause(),i&&(J.textContent=c,ee.style.display=""))},O=Z=>{let ye=ws({following:$.isFollowing(),deltaY:Z.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});ye==="pause"?($.pause(),i&&(J.textContent=c,ee.style.display="")):ye==="resume"&&($.resume(),ne=0,ee.style.display="none")},Le=()=>{i&&(z.scrollTop=z.scrollHeight,$.resume(),ne=0,ee.style.display="none")},ue=Z=>{let ye=Z.target;if(!ye||ye.closest("button"))return;let Pe=ye.closest("[data-event-id]");if(!Pe)return;let dt=Pe.getAttribute("data-event-id");dt&&Ne(dt)},at=Z=>{if((Z.metaKey||Z.ctrlKey)&&Z.key==="f"){Z.preventDefault(),De==null||De.focus(),De==null||De.select();return}Z.key==="Escape"&&(De&&document.activeElement===De?(Gt(),De.blur(),R.focus()):n&&n())};se&&se.addEventListener("click",Ze),de&&de.addEventListener("change",Qe),De&&De.addEventListener("input",Kt),ot&&ot.addEventListener("click",Gt),z.addEventListener("scroll",Zt),z.addEventListener("wheel",O,{passive:!0}),z.addEventListener("click",ue),ee.addEventListener("click",Le),R.addEventListener("keydown",at);function Be(){T&&clearTimeout(T),Se!==null&&(cancelAnimationFrame(Se),Se=null),re=!1,ke.clear(),se&&se.removeEventListener("click",Ze),de&&de.removeEventListener("change",Qe),De&&De.removeEventListener("input",Kt),ot&&ot.removeEventListener("click",Gt),z.removeEventListener("scroll",Zt),z.removeEventListener("wheel",O),z.removeEventListener("click",ue),ee.removeEventListener("click",Le),R.removeEventListener("keydown",at)}return{element:R,update:At,destroy:Be}}}function Gc(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=t;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(c.append(p,u),i.append(d,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",n),i.append(f)}return i}var Xc=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:r.config,defaultRenderer:()=>Gc(e,r)});if(p)return p}return Gc(e,r)};var da=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},lr=new da;lr.register("PersonaArtifactCard",Xc);function Up(e){var s;let r=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),r.appendChild(t),r.appendChild(n),r}function Kc(e,r){var se,De,ot,St;let t=(De=(se=e.features)==null?void 0:se.artifacts)==null?void 0:De.layout,s=((ot=t==null?void 0:t.toolbarPreset)!=null?ot:"default")==="document",o=(St=t==null?void 0:t.panePadding)==null?void 0:St.trim(),a=e.markdown?Br(e.markdown):null,i=no(e.sanitize),d=j=>{let q=a?a(j):to(j);return i?i(q):q},c=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),$==null||$.hide()};c&&c.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let u=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),s&&u.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let M="rendered",b=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),C=s?wt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):wt({icon:"eye",label:"Rendered view"}),S=s?wt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):wt({icon:"code-2",label:"Source"}),R=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,B=t==null?void 0:t.documentToolbarCopyMenuItems,T=!!(L&&B&&B.length>0),Y=null,ge,ce=null,$=null;if(s&&(w||L)&&!T){if(ge=w?$o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let j=me("chevron-down",14,"currentColor",2);j&&ge.appendChild(j)}}else s&&T?(Y=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ge=w?$o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),ce=wt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),Y.append(ge,ce)):s?ge=wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):ge=wt({icon:"copy",label:"Copy"});let ne=s?wt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):wt({icon:"refresh-cw",label:"Refresh"}),Te=s?wt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):wt({icon:"x",label:"Close"}),re=()=>{var z,ee,Fe;let j=(z=oe.find(J=>J.id===be))!=null?z:oe[oe.length-1],q=(ee=j==null?void 0:j.id)!=null?ee:null,ae=(j==null?void 0:j.artifactType)==="markdown"&&(Fe=j.markdown)!=null?Fe:"",_=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:ae,jsonPayload:_,id:q}},Se=async()=>{var z;let{markdown:j,jsonPayload:q}=re(),ae=(z=oe.find(ee=>ee.id===be))!=null?z:oe[oe.length-1],_=(ae==null?void 0:ae.artifactType)==="markdown"?j:ae?q:"";try{await navigator.clipboard.writeText(_)}catch{}};if(ge.addEventListener("click",async()=>{let j=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(j&&T){let{markdown:q,jsonPayload:ae,id:_}=re();try{await j({actionId:"primary",artifactId:_,markdown:q,jsonPayload:ae})}catch{}return}await Se()}),ce&&(B!=null&&B.length)){let j=()=>{var ae;return(ae=u.closest("[data-persona-root]"))!=null?ae:document.body},q=()=>{$=Er({items:B.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:_,jsonPayload:z,id:ee}=re(),Fe=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Fe?await Fe({actionId:ae,artifactId:ee,markdown:_,jsonPayload:z}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(_):ae==="json"||ae==="source"?await navigator.clipboard.writeText(z):await navigator.clipboard.writeText(_||z)}catch{}},anchor:Y!=null?Y:ce,position:"bottom-right",portal:j()})};u.isConnected?q():requestAnimationFrame(q),ce.addEventListener("click",ae=>{ae.stopPropagation(),$==null||$.toggle()})}ne.addEventListener("click",async()=>{var j;try{await((j=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:j.call(t))}catch{}pe()}),Te.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let He=()=>{s&&(C.setAttribute("aria-pressed",M==="rendered"?"true":"false"),S.setAttribute("aria-pressed",M==="source"?"true":"false"))};C.addEventListener("click",()=>{M="rendered",He(),pe()}),S.addEventListener("click",()=>{M="source",He(),pe()});let he=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),b.append(C,S),Y?R.append(Y,ne,Te):R.append(ge,ne,Te),f.append(b,he,R),He()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let Me=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Me.style.paddingLeft=o,Me.style.paddingRight=o,ke.style.padding=o),u.appendChild(f),u.appendChild(Me),u.appendChild(ke);let oe=[],be=null,$e=!1,pe=()=>{var _,z,ee,Fe;let j=s&&oe.length<=1;Me.classList.toggle("persona-hidden",j),Me.replaceChildren();for(let J of oe){let K=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");K.type="button",K.textContent=J.title||J.id.slice(0,8),J.id===be&&K.classList.add("persona-bg-persona-container","persona-border-persona-border"),K.addEventListener("click",()=>r.onSelect(J.id)),Me.appendChild(K)}ke.replaceChildren();let q=be&&oe.find(J=>J.id===be)||oe[oe.length-1];if(!q)return;if(s){let J=q.artifactType==="markdown"?"MD":(_=q.component)!=null?_:"Component",vt=(q.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${vt} \xB7 ${J}`}else m.textContent="Artifacts";if(q.artifactType==="markdown"){if(s&&M==="source"){let K=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");K.textContent=(z=q.markdown)!=null?z:"",ke.appendChild(K);return}let J=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");J.innerHTML=d((ee=q.markdown)!=null?ee:""),ke.appendChild(J);return}let ae=q.component?lr.get(q.component):void 0;if(ae){let K={message:{id:q.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let vt=ae((Fe=q.props)!=null?Fe:{},K);if(vt){ke.appendChild(vt);return}}catch{}}ke.appendChild(Up(q))},de=()=>{var q;let j=oe.length>0;if(u.classList.toggle("persona-hidden",!j),c){let ae=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,z=((q=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?q:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&z&&$e?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(j){var q,ae,_;oe=j.artifacts,be=(_=(ae=j.selectedId)!=null?ae:(q=j.artifacts[j.artifacts.length-1])==null?void 0:q.id)!=null?_:null,oe.length>0&&($e=!0),pe(),de()},setMobileOpen(j){$e=j,!j&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):de()}}}function Bn(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function Zc(e,r){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Bn(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Vp(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ts(e,r){var d,c,p,u,f,m,v,M,b,C;if(!Bn(r)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Vp(e),Zc(e,r);return}let t=(c=(d=r.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=t==null?void 0:t.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(M=t==null?void 0:t.documentToolbarIconColor)==null?void 0:M.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(b=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(C=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:C.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Zc(e,r)}var Qc=["panel","seamless"];function Ms(e,r){var i,d,c,p,u,f;for(let m of Qc)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!Bn(r))return;let t=(d=(i=r.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Qc.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(u=t==null?void 0:t.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function ed(e,r){var t,n,s;return!r||!Bn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function qp(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function Jp(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function Yp(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function Gp(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function td(e,r){var a;let n=(a=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(n);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function nd(e,r,t,n,s,o){let a=qp(s,200),i=Gp(r,t,n,200);i=Math.max(a,i);let d=Jp(o);return d!==null&&(i=Math.min(i,d)),Yp(e,a,i)}var rd={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},pa=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,M,b;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(M=rd[a])!=null?M:rd.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let C=h("p","persona-text-sm persona-text-persona-muted");C.textContent=i.description,d.appendChild(C)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(C=>{var B,T;let S=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${r.id}-${a}-${C.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=C.label,S.appendChild(R);let w=(B=C.type)!=null?B:"text",L;w==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=w),L.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",L.id=`${r.id}-${a}-${C.name}`,L.name=C.name,L.placeholder=(T=C.placeholder)!=null?T:"",C.required&&(L.required=!0),S.appendChild(L),p.appendChild(S)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(b=i.submitLabel)!=null?b:"Submit",u.appendChild(f),u.appendChild(m),p.appendChild(u),o.replaceChildren(d,p),p.addEventListener("submit",async C=>{var L,B;C.preventDefault();let S=(L=t.formEndpoint)!=null?L:"/form",R=new FormData(p),w={};R.forEach((T,Y)=>{w[Y]=T}),w.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let T=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let Y=await T.json();f.textContent=(B=Y.message)!=null?B:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await n.sendMessage(String(Y.nextPrompt))}catch(T){f.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var ua=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Uo=new ua;var od=()=>{let e=new Map,r=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Xp=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Kp=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let s=t;s<r.length;s+=1){let o=r[s];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,s+1)}return null},Vo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=Xp(e),t=Kp(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:s,...o}=n;return{type:String(s),payload:o,raw:n}}catch{return null}},ga=e=>typeof e=="string"?e:e==null?"":String(e),zr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ga(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=ga(t.element);if(n&&((s=r.document)!=null&&s.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:ga(t.text)}}},sd=e=>Array.isArray(e)?e.map(r=>String(r)):[],qo=e=>{let r=new Set(sd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(sd(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var Zp=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},Qp=e=>e.map(r=>({...r,streaming:!1})),ks=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?Zp(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Qp(t.messages):void 0};n.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var go=require("partial-json");function eu(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function tu(e,r){if(!eu(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function Ls(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let s=(0,go.parse)(t,go.STR|go.OBJ),o=tu(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function ad(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Is(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=lr.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function id(){let e=Ls();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ps(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Ws(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var nu=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Rs(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=nu}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,m.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,m.appendChild(M),f.appendChild(m);let b=document.createElement("div");b.className="persona-feedback-rating persona-feedback-rating-csat",b.setAttribute("role","radiogroup"),b.setAttribute("aria-label","Satisfaction rating from 1 to 5");let C=[];for(let B=1;B<=5;B++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-star-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`${B} star${B>1?"s":""}: ${c[B-1]}`),T.title=c[B-1],T.dataset.rating=String(B),T.innerHTML=`
|
|
15
|
+
`,t.addEventListener("click",r);let n=o=>{var H,w,M,W,T,G,K,J,I,Q,Ce,re,Ae,Ne;let a=(H=o.launcher)!=null?H:{},i=Xt(o),u=t.querySelector("[data-role='launcher-title']");if(u){let he=(w=a.title)!=null?w:"Chat Assistant";u.textContent=he,u.setAttribute("title",he)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let he=(M=a.subtitle)!=null?M:"Get answers fast";c.textContent=he,c.setAttribute("title",he)}let d=t.querySelector(".persona-flex-col");d&&(a.textHidden||i?d.style.display="none":d.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let he=(W=a.agentIconSize)!=null?W:"40px";if(p.style.height=he,p.style.width=he,p.innerHTML="",a.agentIconName){let ke=parseFloat(he)||24,Le=me(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(p.appendChild(Le),p.style.display=""):(p.textContent=(T=a.agentIconText)!=null?T:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(G=a.agentIconText)!=null?G:"\u{1F4AC}",p.style.display="")}let g=t.querySelector("[data-role='launcher-image']");if(g){let he=(K=a.agentIconSize)!=null?K:"40px";g.style.height=he,g.style.width=he,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=t.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let he=(J=a.callToActionIconSize)!=null?J:"32px";f.style.height=he,f.style.width=he,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let ke=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,ke=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Le=parseFloat(he)||24,ae=Math.max(Le-ke,8),xe=me(a.callToActionIconName,ae,"currentColor",2);xe?f.appendChild(xe):f.textContent=(I=a.callToActionIconText)!=null?I:"\u2197"}else f.textContent=(Q=a.callToActionIconText)!=null?Q:"\u2197"}let v=a.position&&Yn[a.position]?Yn[a.position]:Yn["bottom-right"],E="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",x="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?x:`${E} ${v}`,i||(t.style.zIndex=String((Ce=a.zIndex)!=null?Ce:vn));let C="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(re=a.border)!=null?re:C,t.style.boxShadow=(Ae=a.shadow)!=null?Ae:k,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Ne=a.collapsedMaxWidth)!=null?Ne:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var Cn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},pr=e=>{var J,I,Q,Ce,re,Ae,Ne,he,ke,Le,ae,xe,je,de,ie,Ee,Be,it,Et,q,F,le,_,V,oe,Oe,Z,te,Lt,lt,Nt,Kt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(J=r==null?void 0:r.launcher)!=null?J:{},o=(I=s.headerIconSize)!=null?I:"48px",a=(Q=s.closeButtonSize)!=null?Q:"32px",i=(Ce=s.closeButtonPlacement)!=null?Ce:"inline",u=(re=s.headerIconHidden)!=null?re:!1,c=s.headerIconName,d=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(d.style.height=o,d.style.width=o,d.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",d.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!u)if(c){let $e=parseFloat(o)||24,ce=me(c,$e*.6,"currentColor",1);ce?d.replaceChildren(ce):d.textContent=(Ne=(Ae=r==null?void 0:r.launcher)==null?void 0:Ae.agentIconText)!=null?Ne:"\u{1F4AC}"}else if((he=r==null?void 0:r.launcher)!=null&&he.iconUrl){let $e=h("img");$e.src=r.launcher.iconUrl,$e.alt="",$e.className="persona-rounded-xl persona-object-cover",$e.style.height=o,$e.style.width=o,d.replaceChildren($e)}else d.textContent=(Le=(ke=r==null?void 0:r.launcher)==null?void 0:ke.agentIconText)!=null?Le:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=h("span","persona-text-base persona-font-semibold");g.style.color=Cn.titleColor,g.textContent=(xe=(ae=r==null?void 0:r.launcher)==null?void 0:ae.title)!=null?xe:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Cn.subtitleColor,f.textContent=(de=(je=r==null?void 0:r.launcher)==null?void 0:je.subtitle)!=null?de:"Here to help you get answers fast",p.append(g,f),u?n.append(p):n.append(d,p);let v=(ie=s.clearChat)!=null?ie:{},E=(Ee=v.enabled)!=null?Ee:!0,x=(Be=v.placement)!=null?Be:"inline",C=null,k=null;if(E){let $e=(it=v.size)!=null?it:"32px",ce=(Et=v.iconName)!=null?Et:"refresh-cw",He=(q=v.iconColor)!=null?q:"",Wt=(F=v.backgroundColor)!=null?F:"",Rt=(le=v.borderWidth)!=null?le:"",ot=(_=v.borderColor)!=null?_:"",st=(V=v.borderRadius)!=null?V:"",rn=(oe=v.paddingX)!=null?oe:"",tn=(Oe=v.paddingY)!=null?Oe:"",on=(Z=v.tooltipText)!=null?Z:"Clear chat",j=(te=v.showTooltip)!=null?te:!0;k=h("div",x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),x==="top-right"&&(k.style.right="48px"),C=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),C.style.height=$e,C.style.width=$e,C.type="button",C.setAttribute("aria-label",on),C.style.color=He||Cn.actionIconColor;let Ie=me(ce,"20px","currentColor",1);if(Ie&&C.appendChild(Ie),Wt&&(C.style.backgroundColor=Wt,C.classList.remove("hover:persona-bg-gray-100")),Rt||ot){let ue=Rt||"0px",gt=ot||"transparent";C.style.border=`${ue} solid ${gt}`,C.classList.remove("persona-border-none")}if(st&&(C.style.borderRadius=st,C.classList.remove("persona-rounded-full")),rn?(C.style.paddingLeft=rn,C.style.paddingRight=rn):(C.style.paddingLeft="",C.style.paddingRight=""),tn?(C.style.paddingTop=tn,C.style.paddingBottom=tn):(C.style.paddingTop="",C.style.paddingBottom=""),k.appendChild(C),j&&on&&C&&k){let ue=null,gt=()=>{if(ue||!C)return;let ne=C.ownerDocument,ye=ne.body;if(!ye)return;ue=Qn(ne,"div","persona-clear-chat-tooltip"),ue.textContent=on;let De=Qn(ne,"div");De.className="persona-clear-chat-tooltip-arrow",ue.appendChild(De);let xt=C.getBoundingClientRect();ue.style.position="fixed",ue.style.zIndex=String(Er),ue.style.left=`${xt.left+xt.width/2}px`,ue.style.top=`${xt.top-8}px`,ue.style.transform="translate(-50%, -100%)",ye.appendChild(ue)},Fe=()=>{ue&&ue.parentNode&&(ue.parentNode.removeChild(ue),ue=null)};k.addEventListener("mouseenter",gt),k.addEventListener("mouseleave",Fe),C.addEventListener("focus",gt),C.addEventListener("blur",Fe),k._cleanupTooltip=()=>{Fe(),k&&(k.removeEventListener("mouseenter",gt),k.removeEventListener("mouseleave",Fe)),C&&(C.removeEventListener("focus",gt),C.removeEventListener("blur",Fe))}}x==="inline"&&n.appendChild(k)}let H=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":E&&x==="inline"?"":"persona-ml-auto"),w=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");w.style.height=a,w.style.width=a,w.type="button";let M=(Lt=s.closeButtonTooltipText)!=null?Lt:"Close chat",W=(lt=s.closeButtonShowTooltip)!=null?lt:!0;w.setAttribute("aria-label",M),w.style.display=t?"":"none";let T=(Nt=s.closeButtonIconName)!=null?Nt:"x",G=(Kt=s.closeButtonIconText)!=null?Kt:"\xD7";w.style.color=s.closeButtonColor||Cn.actionIconColor;let K=me(T,"20px","currentColor",1);if(K?w.appendChild(K):w.textContent=G,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let $e=s.closeButtonBorderWidth||"0px",ce=s.closeButtonBorderColor||"transparent";w.style.border=`${$e} solid ${ce}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),H.appendChild(w),W&&M){let $e=null,ce=()=>{if($e)return;let Wt=w.ownerDocument,Rt=Wt.body;if(!Rt)return;$e=Qn(Wt,"div","persona-clear-chat-tooltip"),$e.textContent=M;let ot=Qn(Wt,"div");ot.className="persona-clear-chat-tooltip-arrow",$e.appendChild(ot);let st=w.getBoundingClientRect();$e.style.position="fixed",$e.style.zIndex=String(Er),$e.style.left=`${st.left+st.width/2}px`,$e.style.top=`${st.top-8}px`,$e.style.transform="translate(-50%, -100%)",Rt.appendChild($e)},He=()=>{$e&&$e.parentNode&&($e.parentNode.removeChild($e),$e=null)};H.addEventListener("mouseenter",ce),H.addEventListener("mouseleave",He),w.addEventListener("focus",ce),w.addEventListener("blur",He),H._cleanupTooltip=()=>{He(),H.removeEventListener("mouseenter",ce),H.removeEventListener("mouseleave",He),w.removeEventListener("focus",ce),w.removeEventListener("blur",He)}}return i!=="top-right"&&n.appendChild(H),{header:n,iconHolder:d,headerTitle:g,headerSubtitle:f,closeButton:w,closeButtonWrapper:H,clearChatButton:C,clearChatButtonWrapper:k}},Jr=(e,r,t)=>{var a,i,u,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(u=n.clearChat)==null?void 0:u.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function Mr(e){let{items:r,onSelect:t,anchor:n,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Er)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of r){if(f.dividerBefore){let x=document.createElement("hr");a.appendChild(x)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let x=me(f.icon,16,"currentColor",1.5);x&&v.appendChild(x)}let E=document.createElement("span");E.textContent=f.label,v.appendChild(E),v.addEventListener("click",x=>{x.stopPropagation(),d(),t(f.id)}),a.appendChild(v)}let i=null;function u(){if(!o)return;let f=n.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function c(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!n.contains(v.target)&&d()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function d(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?c():d()}function g(){d(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:d,toggle:p,destroy:g}}function Pt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=me(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[d,p]of Object.entries(i))u.setAttribute(d,p);return u}function Jo(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let d=h("button",c);if(d.type="button",d.setAttribute("aria-label",t),r){let g=me(r,o!=null?o:14,"currentColor",2);g&&d.appendChild(g)}let p=h("span");if(p.textContent=t,d.appendChild(p),i&&d.addEventListener("click",i),u)for(let[g,f]of Object.entries(u))d.setAttribute(g,f);return d}function Yo(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function u(){for(let d of i)d.btn.setAttribute("aria-pressed",d.id===a?"true":"false")}for(let d of r){let p;d.icon?p=Pt({icon:d.icon,label:d.label,onClick:()=>{a=d.id,u(),n(d.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",d.label),p.title=d.label,p.textContent=d.label,p.addEventListener("click",()=>{a=d.id,u(),n(d.id)})),p.setAttribute("aria-pressed",d.id===a?"true":"false"),i.push({id:d.id,btn:p}),o.appendChild(p)}function c(d){a=d,u()}return{element:o,setSelected:c}}function Bs(e){var f,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let d=h("span","persona-combo-btn-label");d.textContent=r,c.appendChild(d);let p=me(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",c.appendChild(p)),u&&(c.style.borderRadius=(f=u.borderRadius)!=null?f:"10px",c.style.padding=(v=u.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var E,x;c.style.backgroundColor=(E=u.background)!=null?E:"",c.style.borderColor=(x=u.border)!=null?x:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=Mr({items:n,onSelect:E=>{c.setAttribute("aria-expanded","false"),s(E)},anchor:c,position:o,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",E=>{E.stopPropagation();let x=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),g.toggle()}),c.addEventListener("keydown",E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),c.click())}),{element:c,setLabel:E=>{d.textContent=E,c.setAttribute("aria-label",E)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let E=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var fa=e=>{var n;let r=pr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return r};function ru(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let u=me(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=Mr({items:a.menuItems,onSelect:d=>t==null?void 0:t(d),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",d=>{d.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var ha=e=>{var k,H,w,M,W,T,G,K,J;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(k=r==null?void 0:r.launcher)!=null?k:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let u=s==null?void 0:s.titleMenu,c,d;if(u)c=Bs({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=Cn.titleColor,d=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=h("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Cn.titleColor,d.textContent=(M=a.title)!=null?M:"Chat Assistant",c.appendChild(d),ru(c,s==null?void 0:s.trailingActions,(W=s==null?void 0:s.onAction)!=null?W:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let Q=s.onTitleClick;c.addEventListener("click",Ce=>{Ce.target.closest("button")||Q()}),c.addEventListener("keydown",Ce=>{(Ce.key==="Enter"||Ce.key===" ")&&(Ce.preventDefault(),Q())})}let I=s==null?void 0:s.titleRowHover;I&&(c.style.borderRadius=(T=I.borderRadius)!=null?T:"10px",c.style.padding=(G=I.padding)!=null?G:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var Q,Ce;c.style.backgroundColor=(Q=I.background)!=null?Q:"",c.style.borderColor=(Ce=I.border)!=null?Ce:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let p=(K=a.closeButtonSize)!=null?K:"32px",g=h("div",""),f=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=p,f.style.width=p,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=t?"":"none",f.style.color=a.closeButtonColor||Cn.actionIconColor;let v=(J=a.closeButtonIconName)!=null?J:"x",E=me(v,"20px","currentColor",2);E?f.appendChild(E):f.textContent="\xD7",n&&f.addEventListener("click",n),g.appendChild(f),i.appendChild(g);let x=h("div");x.style.display="none";let C=h("span");return C.style.display="none",{header:i,iconHolder:x,headerTitle:d,headerSubtitle:C,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Ds={default:fa,minimal:ha},ya=e=>{var r;return(r=Ds[e])!=null?r:Ds.default},uo=(e,r,t)=>{var a,i,u;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),d=h("div");d.style.display="none";let p=h("span"),g=h("span"),f=h("button");f.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:d,headerTitle:p,headerSubtitle:g,closeButton:f,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=ya(n)({config:e,showClose:(u=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var mo=e=>{var Be,it,Et,q,F,le,_,V,oe,Oe,Z,te,Lt,lt,Nt,Kt,$e,ce,He,Wt,Rt,ot,st,rn,tn,on,j;let{config:r}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let n=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(it=(Be=r==null?void 0:r.copy)==null?void 0:Be.inputPlaceholder)!=null?it:"Type your message\u2026",o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let Ie=Math.min(o.scrollHeight,u);o.style.height=`${Ie}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let d=(Et=r==null?void 0:r.sendButton)!=null?Et:{},p=(q=d.useIcon)!=null?q:!1,g=(F=d.iconText)!=null?F:"\u2191",f=d.iconName,v=(le=d.tooltipText)!=null?le:"Send message",E=(_=d.showTooltip)!=null?_:!1,x=(V=d.size)!=null?V:"40px",C=d.backgroundColor,k=d.textColor,H=h("div","persona-send-button-wrapper"),w=h("button",p?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),p){if(w.style.width=x,w.style.height=x,w.style.minWidth=x,w.style.minHeight=x,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",k?w.style.color=k:w.style.color="var(--persona-button-primary-fg, #ffffff)",f){let Ie=parseFloat(x)||24,ue=(k==null?void 0:k.trim())||"currentColor",gt=me(f,Ie,ue,2);gt?w.appendChild(gt):w.textContent=g}else w.textContent=g;C?w.style.backgroundColor=C:w.classList.add("persona-bg-persona-primary")}else w.textContent=(Oe=(oe=r==null?void 0:r.copy)==null?void 0:oe.sendButtonLabel)!=null?Oe:"Send",k?w.style.color=k:w.classList.add("persona-text-white");if(d.borderWidth&&(w.style.borderWidth=d.borderWidth,w.style.borderStyle="solid"),d.borderColor&&(w.style.borderColor=d.borderColor),d.paddingX?(w.style.paddingLeft=d.paddingX,w.style.paddingRight=d.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),d.paddingY?(w.style.paddingTop=d.paddingY,w.style.paddingBottom=d.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),E&&v){let Ie=h("div","persona-send-button-tooltip");Ie.textContent=v,H.appendChild(Ie)}H.appendChild(w);let M=(Z=r==null?void 0:r.voiceRecognition)!=null?Z:{},W=M.enabled===!0,T=null,G=null,K=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),J=((te=M.provider)==null?void 0:te.type)==="runtype";if(W&&(K||J)){G=h("div","persona-send-button-wrapper"),T=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),T.type="button",T.setAttribute("data-persona-composer-mic",""),T.setAttribute("aria-label","Start voice recognition");let Ie=(Lt=M.iconName)!=null?Lt:"mic",ue=(lt=M.iconSize)!=null?lt:x,gt=parseFloat(ue)||24,Fe=(Nt=M.backgroundColor)!=null?Nt:C,ne=(Kt=M.iconColor)!=null?Kt:k;T.style.width=ue,T.style.height=ue,T.style.minWidth=ue,T.style.minHeight=ue,T.style.fontSize="18px",T.style.lineHeight="1",ne?T.style.color=ne:T.style.color="var(--persona-text, #111827)";let De=me(Ie,gt,ne||"currentColor",1.5);De?T.appendChild(De):T.textContent="\u{1F3A4}",Fe&&(T.style.backgroundColor=Fe),M.borderWidth&&(T.style.borderWidth=M.borderWidth,T.style.borderStyle="solid"),M.borderColor&&(T.style.borderColor=M.borderColor),M.paddingX&&(T.style.paddingLeft=M.paddingX,T.style.paddingRight=M.paddingX),M.paddingY&&(T.style.paddingTop=M.paddingY,T.style.paddingBottom=M.paddingY),G.appendChild(T);let xt=($e=M.tooltipText)!=null?$e:"Start voice recognition";if(((ce=M.showTooltip)!=null?ce:!1)&&xt){let ct=h("div","persona-send-button-tooltip");ct.textContent=xt,G.appendChild(ct)}}let Q=(He=r==null?void 0:r.attachments)!=null?He:{},Ce=Q.enabled===!0,re=null,Ae=null,Ne=null,he=null;if(Ce){he=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),he.style.display="none",Ne=h("input"),Ne.type="file",Ne.accept=((Wt=Q.allowedTypes)!=null?Wt:dr).join(","),Ne.multiple=((Rt=Q.maxFiles)!=null?Rt:4)>1,Ne.style.display="none",Ne.setAttribute("aria-label","Attach files"),Ae=h("div","persona-send-button-wrapper"),re=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),re.type="button",re.setAttribute("aria-label",(ot=Q.buttonTooltipText)!=null?ot:"Attach file");let Ie=(st=Q.buttonIconName)!=null?st:"paperclip",ue=x,gt=parseFloat(ue)||40,Fe=Math.round(gt*.6);re.style.width=ue,re.style.height=ue,re.style.minWidth=ue,re.style.minHeight=ue,re.style.fontSize="18px",re.style.lineHeight="1",re.style.backgroundColor="transparent",re.style.color="var(--persona-primary, #111827)",re.style.border="none",re.style.borderRadius="6px",re.style.transition="background-color 0.15s ease",re.addEventListener("mouseenter",()=>{re.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),re.addEventListener("mouseleave",()=>{re.style.backgroundColor="transparent"});let ne=me(Ie,Fe,"currentColor",1.5);ne?re.appendChild(ne):re.textContent="\u{1F4CE}",re.addEventListener("click",xt=>{xt.preventDefault(),Ne==null||Ne.click()}),Ae.appendChild(re);let ye=(rn=Q.buttonTooltipText)!=null?rn:"Attach file",De=h("div","persona-send-button-tooltip");De.textContent=ye,Ae.appendChild(De)}s.addEventListener("click",Ie=>{Ie.target!==w&&Ie.target!==H&&Ie.target!==T&&Ie.target!==G&&Ie.target!==re&&Ie.target!==Ae&&o.focus()}),he&&(he.style.gap="8px",s.append(he)),Ne&&s.append(Ne),s.append(o);let ke=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Le=h("div","persona-flex persona-items-center persona-gap-2");Ae&&Le.append(Ae);let ae=h("div","persona-flex persona-items-center persona-gap-1");G&&ae.append(G),ae.append(H),ke.append(Le,ae),s.append(ke);let xe=(tn=r==null?void 0:r.statusIndicator)!=null?tn:{},je=xe.align==="left"?"persona-text-left":xe.align==="center"?"persona-text-center":"persona-text-right",de=h("div",`persona-mt-2 ${je} persona-text-xs persona-text-persona-muted`);de.setAttribute("data-persona-composer-status","");let ie=(on=xe.visible)!=null?on:!0;de.style.display=ie?"":"none";let Ee=(j=xe.idleText)!=null?j:"Online";if(xe.idleLink){let Ie=h("a");Ie.href=xe.idleLink,Ie.target="_blank",Ie.rel="noopener noreferrer",Ie.textContent=Ee,Ie.style.color="inherit",Ie.style.textDecoration="none",de.appendChild(Ie)}else de.textContent=Ee;return t.append(n,s,de),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:H,micButton:T,micButtonWrapper:G,statusText:de,attachmentButton:re,attachmentButtonWrapper:Ae,attachmentInput:Ne,attachmentPreviewsContainer:he,actionsRow:ke,leftActions:Le,rightActions:ae}};var yd=e=>{var c,d,p,g,f,v,E,x,C;let r=(d=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?d:!0;if(Xt(e)){let k=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),H=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return k.appendChild(H),{wrapper:k,panel:H}}if(!r){let k=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),H=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(g=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?g:"100%";return k.style.width=w,H.style.width="100%",k.appendChild(H),{wrapper:k,panel:H}}let n=(f=e==null?void 0:e.launcher)!=null?f:{},s=n.position&&Yn[n.position]?Yn[n.position]:Yn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:vn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(C=(x=e==null?void 0:e.launcher)==null?void 0:x.width)!=null?C:e==null?void 0:e.launcherWidth,u=i!=null?i:Pn;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},bd=(e,r=!0)=>{var x,C,k,H,w,M,W,T,G;let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(x=e==null?void 0:e.layout)==null?void 0:x.header,s=((C=e==null?void 0:e.layout)==null?void 0:C.showHeader)!==!1,o=n?uo(e,n,{showClose:r}):pr({config:e,showClose:r}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=Xt(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(H=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?H:"Hello \u{1F44B}";let d=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");d.textContent=(M=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",u.append(c,d);let p=h("div","persona-flex persona-flex-col persona-gap-3"),g=(W=e==null?void 0:e.layout)==null?void 0:W.contentMaxWidth;g&&(p.style.maxWidth=g,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((T=e==null?void 0:e.copy)==null?void 0:T.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,p);let v=mo({config:e}),E=((G=e==null?void 0:e.layout)==null?void 0:G.showFooter)!==!1;return s?Jr(t,o,e):(o.header.style.display="none",Jr(t,o,e)),t.append(a),E||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:p,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle:d,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var ou=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},su=320,au=320,iu=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),lu=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,u)=>{var p;let c=h("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${su}px`,c.style.maxHeight=`${au}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let d=!1;s+=1,c.addEventListener("error",()=>{d||(d=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{d=!0}),ou(i.image)?(c.src=i.image,n.appendChild(c)):(d=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},Yr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},ba=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Yr};if(r){let s=r(n);if(s!==null)return s}return Yr()},cu=(e,r)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let s=h("img");s.src=n,s.alt=r==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},xd=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},du=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},xa=(e,r,t)=>{var f,v,E,x,C,k;let n=(f=r.showCopy)!=null?f:!0,s=(v=r.showUpvote)!=null?v:!0,o=(E=r.showDownvote)!=null?E:!0;if(!n&&!s&&!o){let H=h("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(x=r.visibility)!=null?x:"hover",i=(C=r.align)!=null?C:"right",u=(k=r.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],d={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${d} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let g=(H,w,M)=>{let W=Pt({icon:H,label:w,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",M),W};return n&&p.appendChild(g("copy","Copy message","copy")),s&&p.appendChild(g("thumbs-up","Upvote","upvote")),o&&p.appendChild(g("thumbs-down","Downvote","downvote")),p},go=(e,r,t,n,s,o)=>{var J,I,Q,Ce,re,Ae,Ne;let a=t!=null?t:{},i=(J=a.layout)!=null?J:"bubble",u=a.avatar,c=a.timestamp,d=(I=u==null?void 0:u.show)!=null?I:!1,p=(Q=c==null?void 0:c.show)!=null?Q:!1,g=(Ce=u==null?void 0:u.position)!=null?Ce:"left",f=(re=c==null?void 0:c.position)!=null?re:"below",v=du(e.role,i),E=h("div",v.join(" "));E.id=`bubble-${e.id}`,E.setAttribute("data-message-id",e.id),E.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(E.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",E.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(E.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",E.style.color="var(--persona-message-assistant-text, var(--persona-text))");let x=iu(e),C=(Ne=(Ae=e.content)==null?void 0:Ae.trim())!=null?Ne:"",H=x.length>0&&C===vs,w=document.createElement("div");w.classList.add("persona-message-content");let M=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),W=null;if(H?(W=document.createElement("div"),W.innerHTML=M,W.style.display="none",w.appendChild(W)):w.innerHTML=M,p&&f==="inline"&&e.createdAt){let he=xd(e,c);he.classList.add("persona-ml-2","persona-inline"),w.appendChild(he)}if(x.length>0){let he=lu(x,!H&&!!C,()=>{H&&W&&(W.style.display="")});he?E.appendChild(he):H&&W&&(W.style.display="")}if(E.appendChild(w),p&&f==="below"&&e.createdAt){let he=xd(e,c);he.classList.add("persona-mt-1"),E.appendChild(he)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let he=ba("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&E.appendChild(he)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let he=xa(e,n,s);E.appendChild(he)}if(!d||e.role==="system")return E;let G=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),K=cu(u,e.role);return g==="right"||g==="left"&&e.role==="user"?G.append(E,K):G.append(K,E),E.classList.remove("persona-max-w-[85%]"),E.classList.add("persona-max-w-[calc(85%-2.5rem)]"),G},vd=(e,r,t,n,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):go(e,r,t,n,s,o)};var fo=new Set,pu=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),uu=(e,r)=>{var n,s;let t=(s=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
|
|
16
|
+
`):""},Cd=(e,r)=>{let t=fo.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),o=r.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=me(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},va=(e,r)=>{var M,W,T,G,K,J,I;let t=e.reasoning,n=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!t)return n;let s=(W=(M=r==null?void 0:r.features)==null?void 0:M.reasoningDisplay)!=null?W:{},o=s.expandable!==!1,a=o&&fo.has(e.id),i=t.status!=="complete",u=uu(e,(T=s.previewMaxLines)!=null?T:3),c=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let d=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=(K=(G=r==null?void 0:r.reasoning)==null?void 0:G.renderCollapsedSummary)==null?void 0:K.call(G,{message:e,reasoning:t,defaultSummary:g,previewText:u,isActive:i,config:r!=null?r:{}});typeof f=="string"&&f.trim()?(p.textContent=f,d.appendChild(p)):f instanceof HTMLElement?d.appendChild(f):(p.textContent=g,d.appendChild(p));let v=h("span","persona-text-xs persona-text-persona-primary");v.textContent=zc(t),d.appendChild(v),t.status==="complete"?p.style.display="none":p.style.display="";let E=null;if(o){E=h("div","persona-flex persona-items-center");let Ce=me(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?E.appendChild(Ce):E.textContent=a?"Hide":"Show";let re=h("div","persona-flex persona-items-center persona-ml-auto");re.append(E),c.append(d,re)}else c.append(d);let x=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(x.setAttribute("data-persona-collapsed-preview","reasoning"),x.style.display="none",x.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&u){let Q=(I=(J=r==null?void 0:r.reasoning)==null?void 0:J.renderCollapsedPreview)==null?void 0:I.call(J,{message:e,reasoning:t,defaultPreview:u,isActive:i,config:r!=null?r:{}});pu(x,Q)||(x.textContent=u),x.style.display=""}if(!a&&i&&s.activeMinHeight&&(n.style.minHeight=s.activeMinHeight),!o)return n.append(c,x),n;let C=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");C.style.display=a?"":"none";let k=t.chunks.join(""),H=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return H.textContent=k||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),C.appendChild(H),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),E){E.innerHTML="";let Ce=me(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?E.appendChild(Ce):E.textContent=a?"Hide":"Show"}C.style.display=a?"":"none",x.style.display=a?"none":x.textContent||x.childNodes.length?"":"none"})(),n.append(c,x,C),n};var ho=new Set,mu=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),gu=(e,r)=>{var o;let t=e.toolCall;if(!t)return"";let n=((o=t.chunks)!=null?o:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-r).join(`
|
|
17
|
+
`);let s=io(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,r).join(`
|
|
18
|
+
`):""},fu=(e,r)=>{var c,d,p,g;let t=e.toolCall,n=(c=r==null?void 0:r.features)==null?void 0:c.toolCallDisplay,s=(d=n==null?void 0:n.collapsedMode)!=null?d:"tool-call",o=gu(e,(p=n==null?void 0:n.previewMaxLines)!=null?p:3),a=t?qc(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=a;return s==="tool-name"?u=((g=t.name)==null?void 0:g.trim())||a:s==="tool-preview"&&o&&(u=o),{summary:u,previewText:o,isActive:i}},wd=(e,r,t)=>{var d;let n=ho.has(e),s=(d=t==null?void 0:t.toolCall)!=null?d:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",g=me(n?"chevron-up":"chevron-down",16,p,2);g?c.appendChild(g):c.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Ca=(e,r)=>{var H,w,M,W,T,G;let t=e.toolCall,n=(H=r==null?void 0:r.toolCall)!=null?H:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=(M=(w=r==null?void 0:r.features)==null?void 0:w.toolCallDisplay)!=null?M:{},a=o.expandable!==!1,i=a&&ho.has(e.id),{summary:u,previewText:c,isActive:d}=fu(e,r),p=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(p.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(p.style.paddingLeft=n.headerPaddingX,p.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(p.style.paddingTop=n.headerPaddingY,p.style.paddingBottom=n.headerPaddingY);let g=h("div","persona-flex persona-flex-col persona-text-left"),f=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let v=(T=n.renderCollapsedSummary)==null?void 0:T.call(n,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:(W=o.collapsedMode)!=null?W:"tool-call",isActive:d,config:r!=null?r:{}});typeof v=="string"&&v.trim()?(f.textContent=v,g.appendChild(f)):v instanceof HTMLElement?g.appendChild(v):(f.textContent=u,g.appendChild(f));let E=null;if(a){E=h("div","persona-flex persona-items-center");let K=n.toggleTextColor||n.headerTextColor||"currentColor",J=me(i?"chevron-up":"chevron-down",16,K,2);J?E.appendChild(J):E.textContent=i?"Hide":"Show";let I=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");I.append(E),p.append(g,I)}else p.append(g);let x=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(x.setAttribute("data-persona-collapsed-preview","tool"),x.style.display="none",x.style.whiteSpace="pre-wrap",!i&&d&&o.activePreview&&c){let K=(G=n.renderCollapsedPreview)==null?void 0:G.call(n,{message:e,toolCall:t,defaultPreview:c,isActive:d,config:r!=null?r:{}});mu(x,K)||(x.textContent=c),x.style.display=""}if(!i&&d&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,x),s;let C=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(C.style.display=i?"":"none",n.contentBackgroundColor&&(C.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(C.style.color=n.contentTextColor),n.contentPaddingX&&(C.style.paddingLeft=n.contentPaddingX,C.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(C.style.paddingTop=n.contentPaddingY,C.style.paddingBottom=n.contentPaddingY),t.name){let K=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?K.style.color=n.contentTextColor:n.headerTextColor&&(K.style.color=n.headerTextColor),K.textContent=t.name,C.appendChild(K)}if(t.args!==void 0){let K=h("div","persona-space-y-1"),J=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(J.style.color=n.labelTextColor),J.textContent="Arguments";let I=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(I.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(I.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(I.style.color=n.codeBlockTextColor),I.textContent=io(t.args),K.append(J,I),C.appendChild(K)}if(t.chunks&&t.chunks.length){let K=h("div","persona-space-y-1"),J=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(J.style.color=n.labelTextColor),J.textContent="Activity";let I=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(I.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(I.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(I.style.color=n.codeBlockTextColor),I.textContent=t.chunks.join(""),K.append(J,I),C.appendChild(K)}if(t.status==="complete"&&t.result!==void 0){let K=h("div","persona-space-y-1"),J=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(J.style.color=n.labelTextColor),J.textContent="Result";let I=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(I.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(I.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(I.style.color=n.codeBlockTextColor),I.textContent=io(t.result),K.append(J,I),C.appendChild(K)}if(t.status==="complete"&&typeof t.duration=="number"){let K=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(K.style.color=n.contentTextColor),K.textContent=`Duration: ${t.duration}ms`,C.appendChild(K)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let K=n.toggleTextColor||n.headerTextColor||"currentColor",J=me(i?"chevron-up":"chevron-down",16,K,2);J?E.appendChild(J):E.textContent=i?"Hide":"Show"}C.style.display=i?"":"none",x.style.display=i?"none":x.textContent||x.childNodes.length?"":"none"})(),s.append(p,x,C),s};var wa=(e,r)=>{var E,x,C,k,H,w,M,W,T,G,K,J;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(E=n==null?void 0:n.backgroundColor)!=null?E:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(x=n==null?void 0:n.borderColor)!=null?x:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let u=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(C=n==null?void 0:n.titleColor)!=null?C:"currentColor",d=me(u,20,c,2);d&&i.appendChild(d);let p=h("div","persona-flex-1 persona-min-w-0"),g=h("div","persona-flex persona-items-center persona-gap-2"),f=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(f.style.color=n.titleColor),f.textContent=(k=n==null?void 0:n.title)!=null?k:"Approval Required",g.appendChild(f),!s){let I=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");I.setAttribute("data-approval-status",t.status),t.status==="approved"?(I.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",I.style.color="var(--persona-palette-colors-success-700, #15803d)",I.textContent="Approved"):t.status==="denied"?(I.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",I.style.color="var(--persona-palette-colors-error-700, #b91c1c)",I.textContent="Denied"):t.status==="timeout"&&(I.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",I.style.color="var(--persona-palette-colors-warning-700, #b45309)",I.textContent="Timeout"),g.appendChild(I)}p.appendChild(g);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,p.appendChild(v),t.parameters){let I=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(I.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(I.style.color=n.parameterTextColor),I.style.fontSize="0.75rem",I.style.lineHeight="1rem",I.textContent=io(t.parameters),p.appendChild(I)}if(s){let I=h("div","persona-flex persona-gap-2 persona-mt-2");I.setAttribute("data-approval-buttons","true");let Q=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");Q.type="button",Q.style.backgroundColor=(H=n==null?void 0:n.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",Q.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",Q.setAttribute("data-approval-action","approve");let Ce=me("shield-check",14,(M=n==null?void 0:n.approveButtonTextColor)!=null?M:"#ffffff",2);Ce&&(Ce.style.marginRight="4px",Q.appendChild(Ce));let re=document.createTextNode((W=n==null?void 0:n.approveLabel)!=null?W:"Approve");Q.appendChild(re);let Ae=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Ae.type="button",Ae.style.backgroundColor=(T=n==null?void 0:n.denyButtonColor)!=null?T:"transparent",Ae.style.color=(G=n==null?void 0:n.denyButtonTextColor)!=null?G:"var(--persona-feedback-error, #dc2626)",Ae.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ae.setAttribute("data-approval-action","deny");let Ne=me("shield-x",14,(K=n==null?void 0:n.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",2);Ne&&(Ne.style.marginRight="4px",Ae.appendChild(Ne));let he=document.createTextNode((J=n==null?void 0:n.denyLabel)!=null?J:"Deny");Ae.appendChild(he),I.append(Q,Ae),p.appendChild(I)}return a.append(i,p),o.appendChild(a),o};var Sd=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(f=>f.role==="user"))return;let d=document.createDocumentFragment(),p=s?s.isStreaming():!1,g=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(f=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=f,v.disabled=p,i!=null&&i.fontFamily&&(v.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(f))}),d.appendChild(v),r.push(v)}),e.appendChild(d)}}};var Go=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xo=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function yo(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var hu={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},yu={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},bu=["flowName","stepName","reasoningText","text","name","tool","toolName"],xu=100;function vu(e,r){let t={...hu,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return yu}function Cu(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function wu(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${s}.${o}`}function Su(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let s=n.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function Au(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Eu(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function Tu(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=n,i.appendChild(u),i}}function Sa(e,r,t,n,s,o,a,i){var g;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");yo(c,(g=n.classNames)==null?void 0:g.eventRow);let d=a.find(f=>f.renderEventStreamRow);if(d!=null&&d.renderEventStreamRow&&i){let f=d.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(f)return c.appendChild(f),c}return c.appendChild(p()),c;function p(){var Q,Ce;let f=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let E=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),x=me(u?"chevron-down":"chevron-right","14px","currentColor",2);x&&E.appendChild(x);let C=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(Q=n.timestampFormat)!=null?Q:"relative";C.textContent=k==="relative"?Cu(e.timestamp,t):wu(e.timestamp);let H=null;n.showSequenceNumbers!==!1&&(H=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(r+1));let w=vu(e.type,n.badgeColors),M=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");M.style.backgroundColor=w.bg,M.style.color=w.text,M.style.borderColor=w.text+"50",M.textContent=e.type;let W=(Ce=n.descriptionFields)!=null?Ce:bu,T=Su(e.payload,W),G=null;T&&(G=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),G.textContent=T);let K=h("div","persona-flex-1 persona-min-w-0"),J=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),I=me("clipboard","12px","currentColor",1.5);return I&&J.appendChild(I),J.addEventListener("click",async re=>{re.stopPropagation(),await Au(Eu(e)),J.innerHTML="";let Ae=me("check","12px","currentColor",1.5);Ae&&J.appendChild(Ae),setTimeout(()=>{J.innerHTML="";let Ne=me("clipboard","12px","currentColor",1.5);Ne&&J.appendChild(Ne)},1500)}),v.appendChild(E),v.appendChild(C),H&&v.appendChild(H),v.appendChild(M),G&&v.appendChild(G),v.appendChild(K),v.appendChild(J),f.appendChild(v),u&&f.appendChild(Tu(e,a,i)),f}}function Ad(e){var f,v,E,x,C;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(f=s==null?void 0:s.features)==null?void 0:f.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(E=a==null?void 0:a.label)!=null?E:"",d=(C=(x=s==null?void 0:s.features)==null?void 0:x.eventStream)!=null?C:{},p=o.find(k=>k.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&s){let k=p.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>g().element,onClose:n});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return g();function g(){let k=d.classNames,H=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");yo(H,k==null?void 0:k.panel);let w=[],M="",W="",T=null,G=[],K={},J=0,I=Ps(),Q=0,Ce=0,re=!1,Ae=null,Ne=!1,he=0,ke=new Set,Le=new Map,ae="",xe="",je=null,de,ie,Ee,Be,it;function Et(){let ne=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),ye=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");yo(ye,k==null?void 0:k.headerBar);let De=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");De.textContent="Events",de=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),de.textContent="0";let xt=h("div","persona-flex-1");ie=h("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let zt=h("option","");zt.value="",zt.textContent="All events",ie.appendChild(zt),Ee=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),Ee.type="button",Ee.title="Copy All";let qt=me("clipboard-copy","12px","currentColor",1.5);qt&&Ee.appendChild(qt);let ft=h("span","persona-text-xs");ft.textContent="Copy All",Ee.appendChild(ft),ye.appendChild(De),ye.appendChild(de),ye.appendChild(xt),ye.appendChild(ie),ye.appendChild(Ee);let Ke=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");yo(Ke,k==null?void 0:k.searchBar);let ht=me("search","14px","var(--persona-muted, #9ca3af)",1.5),We=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");ht&&We.appendChild(ht),Be=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),yo(Be,k==null?void 0:k.searchInput),Be.type="text",Be.placeholder="Search event payloads...",it=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),it.type="button",it.style.display="none";let Vt=me("x","12px","currentColor",2);return Vt&&it.appendChild(Vt),Ke.appendChild(We),Ke.appendChild(Be),Ke.appendChild(it),ne.appendChild(ye),ne.appendChild(Ke),ne}let q,F=o.find(ne=>ne.renderEventStreamToolbar);if(F!=null&&F.renderEventStreamToolbar&&s){let ne=F.renderEventStreamToolbar({config:s,defaultRenderer:()=>Et(),eventCount:r.getSize(),filteredCount:0,onFilterChange:ye=>{M=ye,Kt(),He()},onSearchChange:ye=>{W=ye,Kt(),He()}});q=ne!=null?ne:Et()}else q=Et();let le=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");le.style.display="none";let _=h("div","persona-flex-1 persona-min-h-0 persona-relative"),V=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");V.style.height="100%";let oe=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");yo(oe,k==null?void 0:k.scrollIndicator),oe.style.display="none",oe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Oe=me(u,"14px","currentColor",2);Oe&&oe.appendChild(Oe);let Z=h("span","");Z.textContent=c,oe.appendChild(Z);let te=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");te.style.display="none",_.appendChild(V),_.appendChild(te),_.appendChild(oe),H.setAttribute("tabindex","0"),H.appendChild(q),H.appendChild(le),H.appendChild(_);function Lt(){let ne=r.getAll(),ye={};for(let ft of ne)ye[ft.type]=(ye[ft.type]||0)+1;let De=Object.keys(ye).sort(),xt=De.length!==G.length||!De.every((ft,Ke)=>ft===G[Ke]),zt=!xt&&De.some(ft=>ye[ft]!==K[ft]),ct=ne.length!==Object.values(K).reduce((ft,Ke)=>ft+Ke,0);if(!xt&&!zt&&!ct||(G=De,K=ye,!ie))return;let qt=ie.value;if(ie.options[0].textContent="All events",xt){for(;ie.options.length>1;)ie.remove(1);for(let ft of De){let Ke=h("option","");Ke.value=ft,Ke.textContent=`${ft} (${ye[ft]||0})`,ie.appendChild(Ke)}qt&&De.includes(qt)?ie.value=qt:qt&&(ie.value="",M="")}else for(let ft=1;ft<ie.options.length;ft++){let Ke=ie.options[ft];Ke.textContent=`${Ke.value} (${ye[Ke.value]||0})`}}function lt(){let ne=r.getAll();if(M&&(ne=ne.filter(ye=>ye.type===M)),W){let ye=W.toLowerCase();ne=ne.filter(De=>De.type.toLowerCase().includes(ye)||De.payload.toLowerCase().includes(ye))}return ne}function Nt(){return M!==""||W!==""}function Kt(){J=0,Q=0,I.resume(),oe.style.display="none"}function $e(ne){ke.has(ne)?ke.delete(ne):ke.add(ne),je=ne;let ye=V.scrollTop,De=I.isFollowing();Ne=!0,I.pause(),He(),V.scrollTop=ye,De&&I.resume(),Ne=!1}function ce(){return qo(V,50)}function He(){Ce=Date.now(),re=!1,Lt();let ne=r.getEvictedCount();ne>0?(le.textContent=`${ne.toLocaleString()} older events truncated`,le.style.display=""):le.style.display="none",w=lt();let ye=w.length,De=r.getSize()>0;de&&(de.textContent=String(r.getSize())),ye===0&&De&&Nt()?(te.textContent=W?`No events matching '${W}'`:"No events matching filter",te.style.display="",V.style.display="none"):(te.style.display="none",V.style.display=""),Ee&&(Ee.title=Nt()?`Copy Filtered (${ye})`:"Copy All"),i&&!I.isFollowing()&&ye>J&&(Q+=ye-J,Z.textContent=c?`${c}${Q>0?` (${Q})`:""}`:"",oe.style.display=""),J=ye;let xt=r.getAll(),zt=xt.length>0?xt[0].timestamp:0,ct=new Set(w.map(Ke=>Ke.id));for(let Ke of ke)ct.has(Ke)||ke.delete(Ke);let qt=M!==ae||W!==xe,ft=Le.size===0&&w.length>0;if(qt||ft||w.length===0){V.innerHTML="",Le.clear();let Ke=document.createDocumentFragment();for(let ht=0;ht<w.length;ht++){let We=Sa(w[ht],ht,zt,d,ke,$e,o,s);Le.set(w[ht].id,We),Ke.appendChild(We)}V.appendChild(Ke),ae=M,xe=W,je=null}else{if(je!==null){let ht=Le.get(je);if(ht&&ht.parentNode===V){let We=w.findIndex(Vt=>Vt.id===je);if(We>=0){let Vt=Sa(w[We],We,zt,d,ke,$e,o,s);V.insertBefore(Vt,ht),ht.remove(),Le.set(je,Vt)}}je=null}let Ke=new Set(w.map(ht=>ht.id));for(let[ht,We]of Le)Ke.has(ht)||(We.remove(),Le.delete(ht));for(let ht=0;ht<w.length;ht++){let We=w[ht];if(!Le.has(We.id)){let Vt=Sa(We,ht,zt,d,ke,$e,o,s);Le.set(We.id,Vt),V.appendChild(Vt)}}}I.isFollowing()&&(V.scrollTop=V.scrollHeight)}function Wt(){if(Date.now()-Ce>=xu){Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),He();return}re||(re=!0,Ae=requestAnimationFrame(()=>{Ae=null,He()}))}let Rt=(ne,ye)=>{if(!Ee)return;Ee.innerHTML="";let De=me(ne,"12px","currentColor",1.5);De&&Ee.appendChild(De);let xt=h("span","persona-text-xs");xt.textContent="Copy All",Ee.appendChild(xt),setTimeout(()=>{Ee.innerHTML="";let zt=me("clipboard-copy","12px","currentColor",1.5);zt&&Ee.appendChild(zt);let ct=h("span","persona-text-xs");ct.textContent="Copy All",Ee.appendChild(ct),Ee.disabled=!1},ye)},ot=async()=>{if(Ee){Ee.disabled=!0;try{let ne;Nt()?ne=w:t?(ne=await t(),ne.length===0&&(ne=r.getAll())):ne=r.getAll();let ye=ne.map(De=>{try{return JSON.parse(De.payload)}catch{return De.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),Rt("check",1500)}catch{Rt("x",1500)}}},st=()=>{ie&&(M=ie.value,Kt(),He())},rn=()=>{!Be||!it||(it.style.display=Be.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{W=Be.value,Kt(),He()},150))},tn=()=>{!Be||!it||(Be.value="",W="",it.style.display="none",T&&clearTimeout(T),Kt(),He())},on=()=>{if(Ne)return;let ne=V.scrollTop,{action:ye,nextLastScrollTop:De}=Ws({following:I.isFollowing(),currentScrollTop:ne,lastScrollTop:he,nearBottom:ce(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=De,ye==="resume"?(I.resume(),Q=0,oe.style.display="none"):ye==="pause"&&(I.pause(),i&&(Z.textContent=c,oe.style.display=""))},j=ne=>{let ye=Rs({following:I.isFollowing(),deltaY:ne.deltaY,nearBottom:ce(),resumeWhenNearBottom:!0});ye==="pause"?(I.pause(),i&&(Z.textContent=c,oe.style.display="")):ye==="resume"&&(I.resume(),Q=0,oe.style.display="none")},Ie=()=>{i&&(V.scrollTop=V.scrollHeight,I.resume(),Q=0,oe.style.display="none")},ue=ne=>{let ye=ne.target;if(!ye||ye.closest("button"))return;let De=ye.closest("[data-event-id]");if(!De)return;let xt=De.getAttribute("data-event-id");xt&&$e(xt)},gt=ne=>{if((ne.metaKey||ne.ctrlKey)&&ne.key==="f"){ne.preventDefault(),Be==null||Be.focus(),Be==null||Be.select();return}ne.key==="Escape"&&(Be&&document.activeElement===Be?(tn(),Be.blur(),H.focus()):n&&n())};Ee&&Ee.addEventListener("click",ot),ie&&ie.addEventListener("change",st),Be&&Be.addEventListener("input",rn),it&&it.addEventListener("click",tn),V.addEventListener("scroll",on),V.addEventListener("wheel",j,{passive:!0}),V.addEventListener("click",ue),oe.addEventListener("click",Ie),H.addEventListener("keydown",gt);function Fe(){T&&clearTimeout(T),Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),re=!1,Le.clear(),Ee&&Ee.removeEventListener("click",ot),ie&&ie.removeEventListener("change",st),Be&&Be.removeEventListener("input",rn),it&&it.removeEventListener("click",tn),V.removeEventListener("scroll",on),V.removeEventListener("wheel",j),V.removeEventListener("click",ue),oe.removeEventListener("click",Ie),H.removeEventListener("keydown",gt)}return{element:H,update:Wt,destroy:Fe}}}function Ed(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let d=document.createElement("div");d.className="persona-truncate persona-text-sm persona-font-medium",d.style.color="var(--persona-text, #1f2937)",d.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(f)}else p.textContent=a;if(c.append(d,p),i.append(u,c),s==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${t}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",n),i.append(g)}return i}var Td=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",d=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:r.config,defaultRenderer:()=>Ed(e,r)});if(d)return d}return Ed(e,r)};var Aa=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},ur=new Aa;ur.register("PersonaArtifactCard",Td);function Mu(e){var s;let r=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),r.appendChild(t),r.appendChild(n),r}function Md(e,r){var Ee,Be,it,Et;let t=(Be=(Ee=e.features)==null?void 0:Ee.artifacts)==null?void 0:Be.layout,s=((it=t==null?void 0:t.toolbarPreset)!=null?it:"default")==="document",o=(Et=t==null?void 0:t.panePadding)==null?void 0:Et.trim(),a=e.markdown?$r(e.markdown):null,i=ao(e.sanitize),u=q=>{let F=a?a(q):so(q);return i?i(F):F},c=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,d=()=>{c==null||c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),I==null||I.hide()};c&&c.addEventListener("click",()=>{var q;d(),(q=r.onDismiss)==null||q.call(r)});let p=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let g=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&g.classList.add("persona-artifact-toolbar-document");let f=h("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var q;d(),(q=r.onDismiss)==null||q.call(r)});let E="rendered",x=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),C=s?Pt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Pt({icon:"eye",label:"Rendered view"}),k=s?Pt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Pt({icon:"code-2",label:"Source"}),H=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,M=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,W=t==null?void 0:t.documentToolbarCopyMenuItems,T=!!(M&&W&&W.length>0),G=null,K,J=null,I=null;if(s&&(w||M)&&!T){if(K=w?Jo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),M){let q=me("chevron-down",14,"currentColor",2);q&&K.appendChild(q)}}else s&&T?(G=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),K=w?Jo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),J=Pt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),G.append(K,J)):s?K=Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):K=Pt({icon:"copy",label:"Copy"});let Q=s?Pt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Pt({icon:"refresh-cw",label:"Refresh"}),Ce=s?Pt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Pt({icon:"x",label:"Close"}),re=()=>{var V,oe,Oe;let q=(V=ae.find(Z=>Z.id===xe))!=null?V:ae[ae.length-1],F=(oe=q==null?void 0:q.id)!=null?oe:null,le=(q==null?void 0:q.artifactType)==="markdown"&&(Oe=q.markdown)!=null?Oe:"",_=q?JSON.stringify({component:q.component,props:q.props},null,2):"";return{markdown:le,jsonPayload:_,id:F}},Ae=async()=>{var V;let{markdown:q,jsonPayload:F}=re(),le=(V=ae.find(oe=>oe.id===xe))!=null?V:ae[ae.length-1],_=(le==null?void 0:le.artifactType)==="markdown"?q:le?F:"";try{await navigator.clipboard.writeText(_)}catch{}};if(K.addEventListener("click",async()=>{let q=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(q&&T){let{markdown:F,jsonPayload:le,id:_}=re();try{await q({actionId:"primary",artifactId:_,markdown:F,jsonPayload:le})}catch{}return}await Ae()}),J&&(W!=null&&W.length)){let q=()=>{var le;return(le=p.closest("[data-persona-root]"))!=null?le:document.body},F=()=>{I=Mr({items:W.map(le=>({id:le.id,label:le.label})),onSelect:async le=>{let{markdown:_,jsonPayload:V,id:oe}=re(),Oe=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Oe?await Oe({actionId:le,artifactId:oe,markdown:_,jsonPayload:V}):le==="markdown"||le==="md"?await navigator.clipboard.writeText(_):le==="json"||le==="source"?await navigator.clipboard.writeText(V):await navigator.clipboard.writeText(_||V)}catch{}},anchor:G!=null?G:J,position:"bottom-right",portal:q()})};p.isConnected?F():requestAnimationFrame(F),J.addEventListener("click",le=>{le.stopPropagation(),I==null||I.toggle()})}Q.addEventListener("click",async()=>{var q;try{await((q=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:q.call(t))}catch{}de()}),Ce.addEventListener("click",()=>{var q;d(),(q=r.onDismiss)==null||q.call(r)});let Ne=()=>{s&&(C.setAttribute("aria-pressed",E==="rendered"?"true":"false"),k.setAttribute("aria-pressed",E==="source"?"true":"false"))};C.addEventListener("click",()=>{E="rendered",Ne(),de()}),k.addEventListener("click",()=>{E="source",Ne(),de()});let he=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(g.replaceChildren(),x.append(C,k),G?H.append(G,Q,Ce):H.append(K,Q,Ce),g.append(x,he,H),Ne()):(g.appendChild(f),g.appendChild(v)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let ke=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ke.style.paddingLeft=o,ke.style.paddingRight=o,Le.style.padding=o),p.appendChild(g),p.appendChild(ke),p.appendChild(Le);let ae=[],xe=null,je=!1,de=()=>{var _,V,oe,Oe;let q=s&&ae.length<=1;ke.classList.toggle("persona-hidden",q),ke.replaceChildren();for(let Z of ae){let te=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");te.type="button",te.textContent=Z.title||Z.id.slice(0,8),Z.id===xe&&te.classList.add("persona-bg-persona-container","persona-border-persona-border"),te.addEventListener("click",()=>r.onSelect(Z.id)),ke.appendChild(te)}Le.replaceChildren();let F=xe&&ae.find(Z=>Z.id===xe)||ae[ae.length-1];if(!F)return;if(s){let Z=F.artifactType==="markdown"?"MD":(_=F.component)!=null?_:"Component",Lt=(F.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${Lt} \xB7 ${Z}`}else f.textContent="Artifacts";if(F.artifactType==="markdown"){if(s&&E==="source"){let te=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");te.textContent=(V=F.markdown)!=null?V:"",Le.appendChild(te);return}let Z=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Z.innerHTML=u((oe=F.markdown)!=null?oe:""),Le.appendChild(Z);return}let le=F.component?ur.get(F.component):void 0;if(le){let te={message:{id:F.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Lt=le((Oe=F.props)!=null?Oe:{},te);if(Lt){Le.appendChild(Lt);return}}catch{}}Le.appendChild(Mu(F))},ie=()=>{var F;let q=ae.length>0;if(p.classList.toggle("persona-hidden",!q),c){let le=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,V=((F=le==null?void 0:le.classList.contains("persona-artifact-narrow-host"))!=null?F:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;q&&V&&je?(c.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:c,update(q){var F,le,_;ae=q.artifacts,xe=(_=(le=q.selectedId)!=null?le:(F=q.artifacts[q.artifacts.length-1])==null?void 0:F.id)!=null?_:null,ae.length>0&&(je=!0),de(),ie()},setMobileOpen(q){je=q,!q&&c?(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ie()}}}function On(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function kd(e,r){var o,a,i,u;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!On(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function ku(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ns(e,r){var u,c,d,p,g,f,v,E,x,C;if(!On(r)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),ku(e),kd(e,r);return}let t=(c=(u=r.features)==null?void 0:u.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(d=t==null?void 0:t.splitGap)!=null?d:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=t==null?void 0:t.paneMaxWidth)!=null?g:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(f=t==null?void 0:t.paneBackground)==null?void 0:f.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(E=t==null?void 0:t.documentToolbarIconColor)==null?void 0:E.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(x=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:x.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(C=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:C.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),kd(e,r)}var Ld=["panel","seamless"];function Fs(e,r){var i,u,c,d,p,g;for(let f of Ld)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!On(r))return;let t=(u=(i=r.features)==null?void 0:i.artifacts)==null?void 0:u.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Ld.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(d=t==null?void 0:t.paneBorderRadius)==null?void 0:d.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((g=t.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Id(e,r){var t,n,s;return!r||!On(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Lu(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function Iu(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function Pu(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function Wu(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Pd(e,r){var a;let n=(a=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(n);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function Wd(e,r,t,n,s,o){let a=Lu(s,200),i=Wu(r,t,n,200);i=Math.max(a,i);let u=Iu(o);return u!==null&&(i=Math.min(i,u)),Pu(e,a,i)}var Rd={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Ea=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,E,x;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(E=Rd[a])!=null?E:Rd.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let C=h("p","persona-text-sm persona-text-persona-muted");C.textContent=i.description,u.appendChild(C)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",i.fields.forEach(C=>{var W,T;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${r.id}-${a}-${C.name}`;let H=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=C.label,k.appendChild(H);let w=(W=C.type)!=null?W:"text",M;w==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=w),M.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",M.id=`${r.id}-${a}-${C.name}`,M.name=C.name,M.placeholder=(T=C.placeholder)!=null?T:"",C.required&&(M.required=!0),k.appendChild(M),d.appendChild(k)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=(x=i.submitLabel)!=null?x:"Submit",p.appendChild(g),p.appendChild(f),d.appendChild(p),o.replaceChildren(u,d),d.addEventListener("submit",async C=>{var M,W;C.preventDefault();let k=(M=t.formEndpoint)!=null?M:"/form",H=new FormData(d),w={};H.forEach((T,G)=>{w[G]=T}),w.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let T=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let G=await T.json();g.textContent=(W=G.message)!=null?W:"Thanks! We'll be in touch soon.",G.success&&G.nextPrompt&&await n.sendMessage(String(G.nextPrompt))}catch(T){g.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Ta=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Ko=new Ta;var Hd=()=>{let e=new Map,r=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var Ru=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Hu=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let s=t;s<r.length;s+=1){let o=r[s];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,s+1)}return null},Zo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=Ru(e),t=Hu(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:s,...o}=n;return{type:String(s),payload:o,raw:n}}catch{return null}},Ma=e=>typeof e=="string"?e:e==null?"":String(e),Gr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ma(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Ma(t.element);if(n&&((s=r.document)!=null&&s.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Ma(t.text)}}},Bd=e=>Array.isArray(e)?e.map(r=>String(r)):[],Qo=e=>{let r=new Set(Bd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Bd(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,d)=>c||(d==null?void 0:d({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let d=()=>{e.emit("action:resubmit",u)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});if(!p)continue;if(p.handled){let g=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:g,resubmit:p.resubmit}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:t}};var Bu=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},Du=e=>e.map(r=>({...r,streaming:!1})),Os=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?Bu(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Du(t.messages):void 0};n.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var bo=require("partial-json");function Nu(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Fu(e,r){if(!Nu(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function $s(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let s=(0,bo.parse)(t,bo.STR|bo.OBJ),o=Fu(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Dd(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _s(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=ur.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Nd(){let e=$s();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function js(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function zs(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var Ou=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function qs(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,ratingLabels:c=Ou}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let p=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,f.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,f.appendChild(E),g.appendChild(f);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-csat",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Satisfaction rating from 1 to 5");let C=[];for(let W=1;W<=5;W++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-star-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${c[W-1]}`),T.title=c[W-1],T.dataset.rating=String(W),T.innerHTML=`
|
|
16
19
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
17
20
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
18
21
|
</svg>
|
|
19
|
-
`,T.addEventListener("click",()=>{u=B,C.forEach((Y,ge)=>{let ce=ge<B;Y.classList.toggle("selected",ce),Y.setAttribute("aria-checked",ge===B-1?"true":"false")})}),C.push(T),b.appendChild(T)}f.appendChild(b);let S=null;if(d){let B=document.createElement("div");B.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),B.appendChild(S),f.appendChild(B)}let R=document.createElement("div");R.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),p.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(u===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let B=(S==null?void 0:S.value.trim())||void 0;await r(u,B),p.remove()}catch(B){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",B)}}),R.appendChild(w),R.appendChild(L),f.appendChild(R),p.appendChild(f),p}function Hs(e){let{onSubmit:r,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=n,v.appendChild(M);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,v.appendChild(b),m.appendChild(v);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-nps",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,S.appendChild(R),S.appendChild(w);let L=document.createElement("div");L.className="persona-feedback-numbers";let B=[];for(let $=0;$<=10;$++){let ne=document.createElement("button");ne.type="button",ne.className="persona-feedback-rating-btn persona-feedback-number-btn",ne.setAttribute("role","radio"),ne.setAttribute("aria-checked","false"),ne.setAttribute("aria-label",`Rating ${$} out of 10`),ne.textContent=String($),ne.dataset.rating=String($),$<=6?ne.classList.add("persona-feedback-detractor"):$<=8?ne.classList.add("persona-feedback-passive"):ne.classList.add("persona-feedback-promoter"),ne.addEventListener("click",()=>{f=$,B.forEach((Te,re)=>{Te.classList.toggle("selected",re===$),Te.setAttribute("aria-checked",re===$?"true":"false")})}),B.push(ne),L.appendChild(ne)}C.appendChild(S),C.appendChild(L),m.appendChild(C);let T=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=o,T.rows=3,T.setAttribute("aria-label","Additional comments"),$.appendChild(T),m.appendChild($)}let Y=document.createElement("div");Y.className="persona-feedback-actions";let ge=document.createElement("button");ge.type="button",ge.className="persona-feedback-btn persona-feedback-btn-skip",ge.textContent=i,ge.addEventListener("click",()=>{t==null||t(),u.remove()});let ce=document.createElement("button");return ce.type="button",ce.className="persona-feedback-btn persona-feedback-btn-submit",ce.textContent=a,ce.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}ce.disabled=!0,ce.textContent="Submitting...";try{let $=(T==null?void 0:T.value.trim())||void 0;await r(f,$),u.remove()}catch($){ce.disabled=!1,ce.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),Y.appendChild(ge),Y.appendChild(ce),m.appendChild(Y),u.appendChild(m),u}var mo="persona-chat-history",ru=30*1e3,ou={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function su(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let d=(s=ou[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function au(e){var r,t,n,s,o,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function iu(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var ma=e=>!e||typeof e!="object"?{}:{...e},ld=e=>e.map(r=>({...r,streaming:!1})),cd=(e,r,t)=>{let n=e!=null&&e.markdown?Br(e.markdown):null,s=no(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,p,u;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let f=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(u=i!=null?i:o.text)!=null?u:""}):n?d=n(a):d=to(a),s?s(d):d}},Bs=(e,r,t)=>{var bt,Dt,Wn,Wa,Ra,Ha,Ba,Da,Fa,Na,Oa,$a,_a,ja,za,Ua,Va,qa,Ja,Ya,Ga,Xa,Ka,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,gi,mi;e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=hs(r),s=Uo.getForInstance(n.plugins);n.components&&lr.registerAll(n.components);let o=od(),a=(bt=n.storageAdapter)!=null?bt:ks(),i={},d=null,c=!1,p=l=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:E}=g;return E&&(c=!0),y}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return p(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=p(g);y.metadata&&(i=ma(y.metadata)),(Dt=y.messages)!=null&&Dt.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(Wn=l.messages)!=null&&Wn.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},yo()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Vo],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[zr.message,zr.messageAndClick],M=qo({parsers:m,handlers:v,getSessionMetadata:u,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let b=(Ra=(Wa=n.launcher)==null?void 0:Wa.enabled)!=null?Ra:!0,C=(Ba=(Ha=n.launcher)==null?void 0:Ha.autoExpand)!=null?Ba:!1,S=(Da=n.autoFocusInput)!=null?Da:!1,R=C,w=b,L=(Na=(Fa=n.layout)==null?void 0:Fa.header)==null?void 0:Na.layout,B=!1,T=b?C:!0,Y=!1,ge=null,ce=()=>{Y=!0,ge&&clearTimeout(ge),ge=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},$=cd(n,M,ce),ne=($a=(Oa=n.features)==null?void 0:Oa.showReasoning)!=null?$a:!0,Te=(ja=(_a=n.features)==null?void 0:_a.showToolCalls)!=null?ja:!0,re=(Ua=(za=n.features)==null?void 0:za.showEventStreamToggle)!=null?Ua:!1,Se=(qa=(Va=n.features)==null?void 0:Va.scrollToBottom)!=null?qa:{},he=`${(Ya=typeof n.persistState=="object"?(Ja=n.persistState)==null?void 0:Ja.keyPrefix:void 0)!=null?Ya:"persona-"}event-stream`,Me=re?new zo(he):null,ke=(Ka=(Xa=(Ga=n.features)==null?void 0:Ga.eventStream)==null?void 0:Xa.maxEvents)!=null?Ka:2e3,oe=re?new jo(ke,Me):null,be=null,$e=!1,pe=null,de=0;Me==null||Me.open().then(()=>oe==null?void 0:oe.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let se={onCopy:l=>{var g,y;o.emit("message:copy",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.id,"copy").catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onCopy)==null||y.call(g,l)},onFeedback:l=>{var g,y;o.emit("message:feedback",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.messageId,l.type).catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,l)}},De=(Za=n.statusIndicator)!=null?Za:{},ot=l=>{var g,y,E,k;return l==="idle"?(g=De.idleText)!=null?g:sn.idle:l==="connecting"?(y=De.connectingText)!=null?y:sn.connecting:l==="connected"?(E=De.connectedText)!=null?E:sn.connected:l==="error"?(k=De.errorText)!=null?k:sn.error:sn[l]};function St(l,g,y,E){if(E==="idle"&&y.idleLink){l.textContent="";let k=document.createElement("a");k.href=y.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=g,k.style.color="inherit",k.style.textDecoration="none",l.appendChild(k)}else l.textContent=g}let{wrapper:j,panel:q}=_c(n),ae=jc(n,b),{container:_,body:z,messagesWrapper:ee,suggestions:Fe,textarea:J,sendButton:K,sendButtonWrapper:vt,composerForm:tt,statusText:Lt,introTitle:Vt,introSubtitle:Ne,closeButton:le,iconHolder:Ie,headerTitle:At,headerSubtitle:Et,header:Ze,footer:Qe,actionsRow:Kt,leftActions:Gt,rightActions:Zt}=ae,O=ae.micButton,Le=ae.micButtonWrapper,ue=ae.attachmentButton,at=ae.attachmentButtonWrapper,Be=ae.attachmentInput,Z=ae.attachmentPreviewsContainer;_.classList.add("persona-relative"),z.classList.add("persona-relative");let ye=12,Pe=()=>{var l;return(l=Se.label)!=null?l:""},dt=()=>{var l;return(l=Se.iconName)!=null?l:"arrow-down"},Ot=()=>Se.enabled!==!1,nt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");nt.type="button",nt.style.display="none",nt.setAttribute("data-persona-scroll-to-bottom","true");let $t=h("span","persona-flex persona-items-center"),it=h("span","");nt.append($t,it),_.appendChild(nt);let qe=()=>{let g=Qe.style.display==="none"?0:Qe.offsetHeight;nt.style.bottom=`${g+ye}px`};qe();let lt=()=>{let l=!!Pe();nt.setAttribute("aria-label",Pe()||"Jump to latest"),nt.title=Pe(),nt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),$t.innerHTML="";let g=me(dt(),"14px","currentColor",2);g?($t.appendChild(g),$t.style.display=""):$t.style.display="none",it.textContent=Pe(),it.style.display=l?"":"none"};lt();let _e=null,_t=null,Un=s.find(l=>l.renderHeader);if(Un!=null&&Un.renderHeader){let l=Un.renderHeader({config:n,defaultRenderer:()=>{let g=ir({config:n,showClose:b});return _r(_,g,n),g.header},onClose:()=>Tt(!1,"user")});if(l){let g=_.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Ze=l)}}let Xn=()=>{var g,y,E,k;if(!oe)return;if($e=!0,!be&&oe&&(be=Yc({buffer:oe,getFullHistory:()=>oe.getAllFromStore(),onClose:()=>Dn(),config:n,plugins:s})),be&&(z.style.display="none",(g=Qe.parentNode)==null||g.insertBefore(be.element,Qe),be.update()),Xe){Xe.style.boxShadow=`inset 0 0 0 1.5px ${bn.actionIconColor}`;let P=(k=(E=(y=n.features)==null?void 0:y.eventStream)==null?void 0:E.classNames)==null?void 0:k.toggleButtonActive;P&&P.split(/\s+/).forEach(W=>W&&Xe.classList.add(W))}let l=()=>{if(!$e)return;let P=Date.now();P-de>=200&&(be==null||be.update(),de=P),pe=requestAnimationFrame(l)};de=0,pe=requestAnimationFrame(l),er(),o.emit("eventStream:opened",{timestamp:Date.now()})},Dn=()=>{var l,g,y;if($e){if($e=!1,be&&be.element.remove(),z.style.display="",Xe){Xe.style.boxShadow="";let E=(y=(g=(l=n.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;E&&E.split(/\s+/).forEach(k=>k&&Xe.classList.remove(k))}pe!==null&&(cancelAnimationFrame(pe),pe=null),er(),o.emit("eventStream:closed",{timestamp:Date.now()})}},Xe=null;if(re){let l=(ei=(Qa=n.features)==null?void 0:Qa.eventStream)==null?void 0:ei.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");Xe=h("button",g),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=bn.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let y=me("activity","18px","currentColor",1.5);y&&Xe.appendChild(y);let E=ae.clearChatButtonWrapper,k=ae.closeButtonWrapper,P=E||k;P&&P.parentNode===Ze?Ze.insertBefore(Xe,P):Ze.appendChild(Xe),Xe.addEventListener("click",()=>{$e?Dn():Xn()})}let Mr=l=>{var E,k,P;let g=n.attachments;if(!(g!=null&&g.enabled))return;let y=l.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let W=l.querySelector("[data-persona-composer-form]");W!=null&&W.parentNode?W.parentNode.insertBefore(y,W):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let W=h("input");W.type="file",W.accept=((E=g.allowedTypes)!=null?E:ar).join(","),W.multiple=((k=g.maxFiles)!=null?k:4)>1,W.style.display="none",W.setAttribute("aria-label",(P=g.buttonTooltipText)!=null?P:"Attach files"),l.appendChild(W)}},Vn=s.find(l=>l.renderComposer);if(Vn!=null&&Vn.renderComposer){let l=n.composer,g=Vn.renderComposer({config:n,defaultRenderer:()=>io({config:n}).footer,onSubmit:y=>{D&&!D.isStreaming()&&D.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Be==null||Be.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((ti=n.voiceRecognition)==null?void 0:ti.enabled)===!0?()=>{_t==null||_t()}:void 0});g&&(Qe.replaceWith(g),Qe=g)}let kr=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),k=l.querySelector("[data-persona-composer-mic]"),P=l.querySelector("[data-persona-composer-status]");g&&(tt=g),y&&(J=y),E&&(K=E),k&&(O=k,Le=k.parentElement),P&&(Lt=P);let W=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");W&&(Fe=W);let V=l.querySelector(".persona-attachment-button");V&&(ue=V,at=V.parentElement),Be=l.querySelector('input[type="file"]'),Z=l.querySelector(".persona-attachment-previews");let F=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(Kt=F)};Mr(Qe),kr(Qe);let kn=(ni=n.layout)==null?void 0:ni.contentMaxWidth;kn&&tt&&(tt.style.maxWidth=kn,tt.style.marginLeft="auto",tt.style.marginRight="auto"),kn&&Fe&&(Fe.style.maxWidth=kn,Fe.style.marginLeft="auto",Fe.style.marginRight="auto"),kn&&Z&&(Z.style.maxWidth=kn,Z.style.marginLeft="auto",Z.style.marginRight="auto"),(ri=n.attachments)!=null&&ri.enabled&&Be&&Z&&(_e=$r.fromConfig(n.attachments),_e.setPreviewsContainer(Z),Be.addEventListener("change",l=>{let g=l.target;_e==null||_e.handleFileSelect(g.files),g.value=""})),(()=>{var E,k;let l=(k=(E=n.layout)==null?void 0:E.slots)!=null?k:{},g=P=>{switch(P){case"body-top":return _.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ee;case"footer-top":return Fe;case"composer":return tt;case"footer-bottom":return Lt;default:return null}},y=(P,W)=>{var V;switch(P){case"header-left":case"header-center":case"header-right":if(P==="header-left")Ze.insertBefore(W,Ze.firstChild);else if(P==="header-right")Ze.appendChild(W);else{let F=Ze.querySelector(".persona-flex-col");F?(V=F.parentNode)==null||V.insertBefore(W,F.nextSibling):Ze.appendChild(W)}break;case"body-top":{let F=z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(W):z.insertBefore(W,z.firstChild);break}case"body-bottom":z.appendChild(W);break;case"footer-top":Fe.replaceWith(W);break;case"footer-bottom":Lt.replaceWith(W);break;default:break}};for(let[P,W]of Object.entries(l))if(W)try{let V=W({config:n,defaultContent:()=>g(P)});V&&y(P,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${P}":`,V)}})();let dr=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let E=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!E)return;let k=E.getAttribute("data-message-id");if(!k)return;let P=y.getAttribute("data-bubble-type");P==="reasoning"?(co.has(k)?co.delete(k):co.add(k),Vc(k,E)):P==="tool"&&(po.has(k)?po.delete(k):po.add(k),qc(k,E,n)),In.delete(k)};ee.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),dr(l))}),ee.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),dr(l))});let Kn=new Map;ee.addEventListener("click",l=>{var W;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest("[data-actions-for]");if(!E)return;let k=E.getAttribute("data-actions-for");if(!k)return;let P=y.getAttribute("data-action");if(P==="copy"){let F=D.getMessages().find(ie=>ie.id===k);if(F&&se.onCopy){let ie=F.content||"";navigator.clipboard.writeText(ie).then(()=>{y.classList.add("persona-message-action-success");let ve=me("check",14,"currentColor",2);ve&&(y.innerHTML="",y.appendChild(ve)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let we=me("copy",14,"currentColor",2);we&&(y.innerHTML="",y.appendChild(we))},2e3)}).catch(ve=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ve)}),se.onCopy(F)}}else if(P==="upvote"||P==="downvote")if(((W=Kn.get(k))!=null?W:null)===P)Kn.delete(k),y.classList.remove("persona-message-action-active");else{let ie=P==="upvote"?"downvote":"upvote",ve=E.querySelector(`[data-action="${ie}"]`);ve&&ve.classList.remove("persona-message-action-active"),Kn.set(k,P),y.classList.add("persona-message-action-active");let xe=D.getMessages().find(ze=>ze.id===k);xe&&se.onFeedback&&se.onFeedback({type:P,messageId:xe.id,message:xe})}}),ee.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest(".persona-approval-bubble");if(!E)return;let k=E.getAttribute("data-message-id");if(!k)return;let P=y.getAttribute("data-approval-action");if(!P)return;let W=P==="approve"?"approved":"denied",F=D.getMessages().find(ve=>ve.id===k);if(!(F!=null&&F.approval))return;let ie=E.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(we=>{we.disabled=!0,we.style.opacity="0.5",we.style.cursor="not-allowed"}),D.resolveApproval(F.approval,W)});let et=null,xn=null,Fn={artifacts:[],selectedId:null},an=!1,pr={current:null};ee.addEventListener("click",l=>{var we,xe,ze,H,Oe;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.getAttribute("data-download-artifact");if(!E||((ze=(xe=(we=n.features)==null?void 0:we.artifacts)==null?void 0:xe.onArtifactAction)==null?void 0:ze.call(xe,{type:"download",artifactId:E}))===!0)return;let P=D.getArtifactById(E),W=P==null?void 0:P.markdown,V=(P==null?void 0:P.title)||"artifact";if(!W){let Ee=y.closest("[data-open-artifact]"),fe=Ee==null?void 0:Ee.closest("[data-message-id]"),Re=fe==null?void 0:fe.getAttribute("data-message-id");if(Re){let Ge=D.getMessages().find(Ce=>Ce.id===Re);if(Ge!=null&&Ge.rawContent)try{let Ce=JSON.parse(Ge.rawContent);W=(H=Ce==null?void 0:Ce.props)==null?void 0:H.markdown,V=((Oe=Ce==null?void 0:Ce.props)==null?void 0:Oe.title)||V}catch{}}}if(!W)return;let F=new Blob([W],{type:"text/markdown"}),ie=URL.createObjectURL(F),ve=document.createElement("a");ve.href=ie,ve.download=`${V}.md`,ve.click(),URL.revokeObjectURL(ie)}),ee.addEventListener("click",l=>{var P,W,V;let y=l.target.closest("[data-open-artifact]");if(!y)return;let E=y.getAttribute("data-open-artifact");!E||((V=(W=(P=n.features)==null?void 0:P.artifacts)==null?void 0:W.onArtifactAction)==null?void 0:V.call(W,{type:"open",artifactId:E}))===!0||(l.preventDefault(),l.stopPropagation(),an=!1,D.selectArtifact(E),Cn())}),ee.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let vn=null,ft=null,ln=null,Ln=null,ur=()=>{};function Zn(){Ln==null||Ln(),Ln=null}let gr=()=>{var W;if(!vn||!ft)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((W=e.ownerDocument.defaultView)!=null?W:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){ft.style.removeProperty("position"),ft.style.removeProperty("left"),ft.style.removeProperty("top"),ft.style.removeProperty("bottom"),ft.style.removeProperty("width"),ft.style.removeProperty("z-index");return}let E=vn.firstElementChild;if(!E||E===ft)return;let k=10;ft.style.position="absolute",ft.style.top="0",ft.style.bottom="0",ft.style.width=`${k}px`,ft.style.zIndex="5";let P=E.offsetWidth-k/2;ft.style.left=`${Math.max(0,P)}px`},qn=()=>{},Cn=()=>{var y,E,k,P,W;if(!et||!Bn(n))return;Ts(e,n),Ms(e,n),qn();let l=(P=(k=(E=(y=n.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:k.narrowHostMaxWidth)!=null?P:520,g=q.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),et.update(Fn),an?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),(W=et.backdrop)==null||W.classList.add("persona-hidden")):Fn.artifacts.length>0&&(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)),ur()};if(Bn(n)){q.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(_),et=Kc(n,{onSelect:y=>{var E;return(E=pr.current)==null?void 0:E.selectArtifact(y)},onDismiss:()=>{an=!0,Cn()}}),et.element.classList.add("persona-hidden"),vn=g,g.appendChild(l),g.appendChild(et.element),et.backdrop&&q.appendChild(et.backdrop),q.appendChild(g),ur=()=>{var E,k,P,W;if(!vn||!et)return;if(!(((P=(k=(E=n.features)==null?void 0:E.artifacts)==null?void 0:k.layout)==null?void 0:P.resizable)===!0)){ln==null||ln(),ln=null,Zn(),ft&&(ft.remove(),ft=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!ft){let V=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let F=e.ownerDocument,ie=(W=F.defaultView)!=null?W:window,ve=we=>{var fe,Re;if(!et||we.button!==0||e.classList.contains("persona-artifact-narrow-host")||ie.innerWidth<=640)return;we.preventDefault(),Zn();let xe=we.clientX,ze=et.element.getBoundingClientRect().width,H=(Re=(fe=n.features)==null?void 0:fe.artifacts)==null?void 0:Re.layout,Oe=ct=>{let Ge=vn.getBoundingClientRect().width,Ce=e.classList.contains("persona-artifact-appearance-seamless"),Xt=Ce?0:td(vn,ie),gt=Ce?0:V.getBoundingClientRect().width||6,dn=ze-(ct.clientX-xe),nn=nd(dn,Ge,Xt,gt,H==null?void 0:H.resizableMinWidth,H==null?void 0:H.resizableMaxWidth);et.element.style.width=`${nn}px`,et.element.style.maxWidth="none",gr()},Ee=()=>{F.removeEventListener("pointermove",Oe),F.removeEventListener("pointerup",Ee),F.removeEventListener("pointercancel",Ee),Ln=null;try{V.releasePointerCapture(we.pointerId)}catch{}};Ln=Ee,F.addEventListener("pointermove",Oe),F.addEventListener("pointerup",Ee),F.addEventListener("pointercancel",Ee);try{V.setPointerCapture(we.pointerId)}catch{}};V.addEventListener("pointerdown",ve),ft=V,vn.insertBefore(V,et.element),ln=()=>{V.removeEventListener("pointerdown",ve)}}if(ft){let V=Fn.artifacts.length>0&&!an;ft.classList.toggle("persona-hidden",!V),gr()}},qn=()=>{var ie,ve,we,xe,ze,H,Oe,Ee,fe,Re,ct,Ge,Ce,Xt;if(!b||!et||((ve=(ie=n.launcher)==null?void 0:ie.sidebarMode)!=null?ve:!1)||Ut(n)&&Hn(n).reveal==="emerge")return;let E=(we=e.ownerDocument.defaultView)!=null?we:window,k=(ze=(xe=n.launcher)==null?void 0:xe.mobileFullscreen)!=null?ze:!0,P=(Oe=(H=n.launcher)==null?void 0:H.mobileBreakpoint)!=null?Oe:640;if(k&&E.innerWidth<=P||!ed(n,b))return;let W=(Re=(fe=(Ee=n.launcher)==null?void 0:Ee.width)!=null?fe:n.launcherWidth)!=null?Re:Mn,V=(Xt=(Ce=(Ge=(ct=n.features)==null?void 0:ct.artifacts)==null?void 0:Ge.layout)==null?void 0:Ce.expandedPanelWidth)!=null?Xt:"min(720px, calc(100vw - 24px))";Fn.artifacts.length>0&&!an?(q.style.width=V,q.style.maxWidth=V):(q.style.width=W,q.style.maxWidth=W)},typeof ResizeObserver!="undefined"&&(xn=new ResizeObserver(()=>{Cn()}),xn.observe(q))}else q.appendChild(_);e.appendChild(j);let Jn=()=>{var gt,dn,nn,rn,Ft,pn,Ve,mt,Rn,br,nr,xr,rr,Zr,Qr,jt,Qo,Ao,Eo,eo,es,vr,Wr;let l=Ut(n),g=(dn=(gt=n.launcher)==null?void 0:gt.sidebarMode)!=null?dn:!1,y=l||g||((rn=(nn=n.launcher)==null?void 0:nn.fullHeight)!=null?rn:!1),E=((Ft=n.launcher)==null?void 0:Ft.enabled)===!1,k=(Ve=(pn=n.theme)==null?void 0:pn.components)==null?void 0:Ve.panel,P=Bo(n),W=(Jt,fn)=>{var or;return Jt==null||Jt===""?fn:(or=Ro(P,Jt))!=null?or:Jt},V=(mt=e.ownerDocument.defaultView)!=null?mt:window,F=(br=(Rn=n.launcher)==null?void 0:Rn.mobileFullscreen)!=null?br:!0,ie=(xr=(nr=n.launcher)==null?void 0:nr.mobileBreakpoint)!=null?xr:640,ve=V.innerWidth<=ie,we=F&&ve&&b,xe=(Zr=(rr=n.launcher)==null?void 0:rr.position)!=null?Zr:"bottom-left",ze=xe==="bottom-left"||xe==="top-left",H=(jt=(Qr=n.launcher)==null?void 0:Qr.zIndex)!=null?jt:yn,Oe=g||we?"none":"1px solid var(--persona-border)",Ee=we?"none":g?ze?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!we&&(Ee="none",Oe="none");let fe=g||we?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Re=W(k==null?void 0:k.border,Oe),ct=W(k==null?void 0:k.shadow,Ee),Ge=W(k==null?void 0:k.borderRadius,fe);if(e.style.cssText="",j.style.cssText="",q.style.cssText="",_.style.cssText="",z.style.cssText="",Qe.style.cssText="",we){j.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),j.style.cssText=`
|
|
22
|
+
`,T.addEventListener("click",()=>{p=W,C.forEach((G,K)=>{let J=K<W;G.classList.toggle("selected",J),G.setAttribute("aria-checked",K===W-1?"true":"false")})}),C.push(T),x.appendChild(T)}g.appendChild(x);let k=null;if(u){let W=document.createElement("div");W.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),W.appendChild(k),g.appendChild(W)}let H=document.createElement("div");H.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),d.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=a,M.addEventListener("click",async()=>{if(p===null){x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);return}M.disabled=!0,M.textContent="Submitting...";try{let W=(k==null?void 0:k.value.trim())||void 0;await r(p,W),d.remove()}catch(W){M.disabled=!1,M.textContent=a,console.error("[CSAT Feedback] Failed to submit:",W)}}),H.appendChild(w),H.appendChild(M),g.appendChild(H),d.appendChild(g),d}function Vs(e){let{onSubmit:r,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,lowLabel:c="Not likely",highLabel:d="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=n,v.appendChild(E);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,v.appendChild(x),f.appendChild(v);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-nps",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=d,k.appendChild(H),k.appendChild(w);let M=document.createElement("div");M.className="persona-feedback-numbers";let W=[];for(let I=0;I<=10;I++){let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-rating-btn persona-feedback-number-btn",Q.setAttribute("role","radio"),Q.setAttribute("aria-checked","false"),Q.setAttribute("aria-label",`Rating ${I} out of 10`),Q.textContent=String(I),Q.dataset.rating=String(I),I<=6?Q.classList.add("persona-feedback-detractor"):I<=8?Q.classList.add("persona-feedback-passive"):Q.classList.add("persona-feedback-promoter"),Q.addEventListener("click",()=>{g=I,W.forEach((Ce,re)=>{Ce.classList.toggle("selected",re===I),Ce.setAttribute("aria-checked",re===I?"true":"false")})}),W.push(Q),M.appendChild(Q)}C.appendChild(k),C.appendChild(M),f.appendChild(C);let T=null;if(u){let I=document.createElement("div");I.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=o,T.rows=3,T.setAttribute("aria-label","Additional comments"),I.appendChild(T),f.appendChild(I)}let G=document.createElement("div");G.className="persona-feedback-actions";let K=document.createElement("button");K.type="button",K.className="persona-feedback-btn persona-feedback-btn-skip",K.textContent=i,K.addEventListener("click",()=>{t==null||t(),p.remove()});let J=document.createElement("button");return J.type="button",J.className="persona-feedback-btn persona-feedback-btn-submit",J.textContent=a,J.addEventListener("click",async()=>{if(g===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}J.disabled=!0,J.textContent="Submitting...";try{let I=(T==null?void 0:T.value.trim())||void 0;await r(g,I),p.remove()}catch(I){J.disabled=!1,J.textContent=a,console.error("[NPS Feedback] Failed to submit:",I)}}),G.appendChild(K),G.appendChild(J),f.appendChild(G),p.appendChild(f),p}var xo="persona-chat-history",$u=30*1e3,_u={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function ju(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let u=(s=_u[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function Us(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function zu(e){var r,t,n,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function qu(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var ka=e=>!e||typeof e!="object"?{}:{...e},Fd=e=>e.map(r=>({...r,streaming:!1})),Od=(e,r,t)=>{let n=e!=null&&e.markdown?$r(e.markdown):null,s=ao(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,d,p;let a=(c=o.text)!=null?c:"",i=(d=o.message.rawContent)!=null?d:null;if(r){let g=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&t&&t())}let u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):n?u=n(a):u=so(a),s?s(u):u}};function $d(e){var i,u,c,d;let r=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(u=e==null?void 0:e.iconSize)!=null?u:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(d=e==null?void 0:e.iconStrokeWidth)!=null?d:.5,a=me(t,n,s,o);if(a&&r.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,r.appendChild(p)}return r}var Js=(e,r,t)=>{var Ja,Ya,Ga,Xa,Ka,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,mi,gi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=Ms(r),s=Ko.getForInstance(n.plugins);n.components&&ur.registerAll(n.components);let o=Hd(),a=(Ja=n.storageAdapter)!=null?Ja:Os(),i={},u=null,c=!1,d=l=>{if(n.onStateLoaded)try{let m=n.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:b,open:A}=m;return A&&(c=!0),b}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")u=l.then(m=>{let b=m!=null?m:{messages:[],metadata:{}};return d(b)});else{let m=l!=null?l:{messages:[],metadata:{}},b=d(m);b.metadata&&(i=ka(b.metadata)),(Ya=b.messages)!=null&&Ya.length&&(n={...n,initialMessages:b.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=d({messages:[],metadata:{}});(Ga=l.messages)!=null&&Ga.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>i,g=l=>{var b;i=(b=l({...i}))!=null?b:{},wo()},f=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Zo],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Gr.message,Gr.messageAndClick],E=Qo({parsers:f,handlers:v,getSessionMetadata:p,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let x=(Ka=(Xa=n.launcher)==null?void 0:Xa.enabled)!=null?Ka:!0,C=(Qa=(Za=n.launcher)==null?void 0:Za.autoExpand)!=null?Qa:!1,k=(ei=n.autoFocusInput)!=null?ei:!1,H=C,w=x,M=(ni=(ti=n.layout)==null?void 0:ti.header)==null?void 0:ni.layout,W=!1,T=x?C:!0,G=!1,K=null,J=()=>{G=!0,K&&clearTimeout(K),K=setTimeout(()=>{G&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),G=!1)},1e4)},I=Od(n,E,J),Q=(oi=(ri=n.features)==null?void 0:ri.showReasoning)!=null?oi:!0,Ce=(ai=(si=n.features)==null?void 0:si.showToolCalls)!=null?ai:!0,re=(li=(ii=n.features)==null?void 0:ii.showEventStreamToggle)!=null?li:!1,Ae=(di=(ci=n.features)==null?void 0:ci.scrollToBottom)!=null?di:{},he=`${(ui=typeof n.persistState=="object"?(pi=n.persistState)==null?void 0:pi.keyPrefix:void 0)!=null?ui:"persona-"}event-stream`,ke=re?new Xo(he):null,Le=(fi=(gi=(mi=n.features)==null?void 0:mi.eventStream)==null?void 0:gi.maxEvents)!=null?fi:2e3,ae=re?new Go(Le,ke):null,xe=null,je=!1,de=null,ie=0;ke==null||ke.open().then(()=>ae==null?void 0:ae.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Ee={onCopy:l=>{var m,b;o.emit("message:copy",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(b=(m=n.messageActions)==null?void 0:m.onCopy)==null||b.call(m,l)},onFeedback:l=>{var m,b;o.emit("message:feedback",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.messageId,l.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(b=(m=n.messageActions)==null?void 0:m.onFeedback)==null||b.call(m,l)}},Be=(hi=n.statusIndicator)!=null?hi:{},it=l=>{var m,b,A,L;return l==="idle"?(m=Be.idleText)!=null?m:cn.idle:l==="connecting"?(b=Be.connectingText)!=null?b:cn.connecting:l==="connected"?(A=Be.connectedText)!=null?A:cn.connected:l==="error"?(L=Be.errorText)!=null?L:cn.error:cn[l]};function Et(l,m,b,A){if(A==="idle"&&b.idleLink){l.textContent="";let L=document.createElement("a");L.href=b.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=m,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=m}let{wrapper:q,panel:F}=yd(n),le=bd(n,x),{container:_,body:V,messagesWrapper:oe,suggestions:Oe,textarea:Z,sendButton:te,sendButtonWrapper:Lt,composerForm:lt,statusText:Nt,introTitle:Kt,introSubtitle:$e,closeButton:ce,iconHolder:He,headerTitle:Wt,headerSubtitle:Rt,header:ot,footer:st,actionsRow:rn,leftActions:tn,rightActions:on}=le,j=le.micButton,Ie=le.micButtonWrapper,ue=le.attachmentButton,gt=le.attachmentButtonWrapper,Fe=le.attachmentInput,ne=le.attachmentPreviewsContainer;_.classList.add("persona-relative"),V.classList.add("persona-relative");let ye=12,De=()=>{var l;return(l=Ae.label)!=null?l:""},xt=()=>{var l;return(l=Ae.iconName)!=null?l:"arrow-down"},zt=()=>Ae.enabled!==!1,ct=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");ct.type="button",ct.style.display="none",ct.setAttribute("data-persona-scroll-to-bottom","true");let qt=h("span","persona-flex persona-items-center"),ft=h("span","");ct.append(qt,ft),_.appendChild(ct);let Ke=()=>{let m=st.style.display==="none"?0:st.offsetHeight;ct.style.bottom=`${m+ye}px`};Ke();let ht=()=>{let l=!!De();ct.setAttribute("aria-label",De()||"Jump to latest"),ct.title=De(),ct.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),qt.innerHTML="";let m=me(xt(),"14px","currentColor",2);m?(qt.appendChild(m),qt.style.display=""):qt.style.display="none",ft.textContent=De(),ft.style.display=l?"":"none"};ht();let We=null,Vt=null,Gn=s.find(l=>l.renderHeader);if(Gn!=null&&Gn.renderHeader){let l=Gn.renderHeader({config:n,defaultRenderer:()=>{let m=pr({config:n,showClose:x});return Jr(_,m,n),m.header},onClose:()=>Ht(!1,"user")});if(l){let m=_.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),ot=l)}}let tr=()=>{var m,b,A,L;if(!ae)return;if(je=!0,!xe&&ae&&(xe=Ad({buffer:ae,getFullHistory:()=>ae.getAllFromStore(),onClose:()=>$n(),config:n,plugins:s})),xe&&(V.style.display="none",(m=st.parentNode)==null||m.insertBefore(xe.element,st),xe.update()),Qe){Qe.style.boxShadow=`inset 0 0 0 1.5px ${Cn.actionIconColor}`;let R=(L=(A=(b=n.features)==null?void 0:b.eventStream)==null?void 0:A.classNames)==null?void 0:L.toggleButtonActive;R&&R.split(/\s+/).forEach(B=>B&&Qe.classList.add(B))}let l=()=>{if(!je)return;let R=Date.now();R-ie>=200&&(xe==null||xe.update(),ie=R),de=requestAnimationFrame(l)};ie=0,de=requestAnimationFrame(l),ar(),o.emit("eventStream:opened",{timestamp:Date.now()})},$n=()=>{var l,m,b;if(je){if(je=!1,xe&&xe.element.remove(),V.style.display="",Qe){Qe.style.boxShadow="";let A=(b=(m=(l=n.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:b.toggleButtonActive;A&&A.split(/\s+/).forEach(L=>L&&Qe.classList.remove(L))}de!==null&&(cancelAnimationFrame(de),de=null),ar(),o.emit("eventStream:closed",{timestamp:Date.now()})}},Qe=null;if(re){let l=(bi=(yi=n.features)==null?void 0:yi.eventStream)==null?void 0:bi.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");Qe=h("button",m),Qe.style.width="28px",Qe.style.height="28px",Qe.style.color=Cn.actionIconColor,Qe.type="button",Qe.setAttribute("aria-label","Event Stream"),Qe.title="Event Stream";let b=me("activity","18px","currentColor",1.5);b&&Qe.appendChild(b);let A=le.clearChatButtonWrapper,L=le.closeButtonWrapper,R=A||L;R&&R.parentNode===ot?ot.insertBefore(Qe,R):ot.appendChild(Qe),Qe.addEventListener("click",()=>{je?$n():tr()})}let Lr=l=>{var A,L,R;let m=n.attachments;if(!(m!=null&&m.enabled))return;let b=l.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let B=l.querySelector("[data-persona-composer-form]");B!=null&&B.parentNode?B.parentNode.insertBefore(b,B):l.insertBefore(b,l.firstChild)}if(!l.querySelector('input[type="file"]')){let B=h("input");B.type="file",B.accept=((A=m.allowedTypes)!=null?A:dr).join(","),B.multiple=((L=m.maxFiles)!=null?L:4)>1,B.style.display="none",B.setAttribute("aria-label",(R=m.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(B)}},Xn=s.find(l=>l.renderComposer);if(Xn!=null&&Xn.renderComposer){let l=n.composer,m=Xn.renderComposer({config:n,defaultRenderer:()=>mo({config:n}).footer,onSubmit:b=>{var B;if(!D||D.isStreaming())return;let A=b.trim(),L=(B=We==null?void 0:We.hasAttachments())!=null?B:!1;if(!A&&!L)return;let R;L&&(R=[],R.push(...We.getContentParts()),A&&R.push(Do(A))),D.sendMessage(A,{contentParts:R}),L&&We.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe==null||Fe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:b=>{n.composer={...n.composer,selectedModelId:b},n.agent&&(n.agent={...n.agent,model:b})},onVoiceToggle:((xi=n.voiceRecognition)==null?void 0:xi.enabled)===!0?()=>{Vt==null||Vt()}:void 0});m&&(st.replaceWith(m),st=m)}let Ir=l=>{let m=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),R=l.querySelector("[data-persona-composer-status]");m&&(lt=m),b&&(Z=b),A&&(te=A),L&&(j=L,Ie=L.parentElement),R&&(Nt=R);let B=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");B&&(Oe=B);let z=l.querySelector(".persona-attachment-button");z&&(ue=z,gt=z.parentElement),Fe=l.querySelector('input[type="file"]'),ne=l.querySelector(".persona-attachment-previews");let O=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(rn=O)};Lr(st),Ir(st);let Wn=(vi=n.layout)==null?void 0:vi.contentMaxWidth;if(Wn&<&&(lt.style.maxWidth=Wn,lt.style.marginLeft="auto",lt.style.marginRight="auto"),Wn&&Oe&&(Oe.style.maxWidth=Wn,Oe.style.marginLeft="auto",Oe.style.marginRight="auto"),Wn&&ne&&(ne.style.maxWidth=Wn,ne.style.marginLeft="auto",ne.style.marginRight="auto"),(Ci=n.attachments)!=null&&Ci.enabled&&Fe&&ne){We=Ur.fromConfig(n.attachments),We.setPreviewsContainer(ne),Fe.addEventListener("change",b=>{let A=b.target;We==null||We.handleFileSelect(A.files),A.value=""});let l=n.attachments.dropOverlay,m=$d(l);_.appendChild(m)}(()=>{var A,L;let l=(L=(A=n.layout)==null?void 0:A.slots)!=null?L:{},m=R=>{switch(R){case"body-top":return _.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return oe;case"footer-top":return Oe;case"composer":return lt;case"footer-bottom":return Nt;default:return null}},b=(R,B)=>{var z;switch(R){case"header-left":case"header-center":case"header-right":if(R==="header-left")ot.insertBefore(B,ot.firstChild);else if(R==="header-right")ot.appendChild(B);else{let O=ot.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(B,O.nextSibling):ot.appendChild(B)}break;case"body-top":{let O=V.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(B):V.insertBefore(B,V.firstChild);break}case"body-bottom":V.appendChild(B);break;case"footer-top":Oe.replaceWith(B);break;case"footer-bottom":Nt.replaceWith(B);break;default:break}};for(let[R,B]of Object.entries(l))if(B)try{let z=B({config:n,defaultContent:()=>m(R)});z&&b(R,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${R}":`,z)}})();let gr=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let A=b.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let R=b.getAttribute("data-bubble-type");R==="reasoning"?(fo.has(L)?fo.delete(L):fo.add(L),Cd(L,A)):R==="tool"&&(ho.has(L)?ho.delete(L):ho.add(L),wd(L,A,n)),Hn.delete(L)};oe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),gr(l))}),oe.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),gr(l))});let nr=new Map;oe.addEventListener("click",l=>{var B;let b=l.target.closest(".persona-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let A=b.closest("[data-actions-for]");if(!A)return;let L=A.getAttribute("data-actions-for");if(!L)return;let R=b.getAttribute("data-action");if(R==="copy"){let O=D.getMessages().find(ge=>ge.id===L);if(O&&Ee.onCopy){let ge=O.content||"";navigator.clipboard.writeText(ge).then(()=>{b.classList.add("persona-message-action-success");let ve=me("check",14,"currentColor",2);ve&&(b.innerHTML="",b.appendChild(ve)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let Se=me("copy",14,"currentColor",2);Se&&(b.innerHTML="",b.appendChild(Se))},2e3)}).catch(ve=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ve)}),Ee.onCopy(O)}}else if(R==="upvote"||R==="downvote")if(((B=nr.get(L))!=null?B:null)===R)nr.delete(L),b.classList.remove("persona-message-action-active");else{let ge=R==="upvote"?"downvote":"upvote",ve=A.querySelector(`[data-action="${ge}"]`);ve&&ve.classList.remove("persona-message-action-active"),nr.set(L,R),b.classList.add("persona-message-action-active");let be=D.getMessages().find(Te=>Te.id===L);be&&Ee.onFeedback&&Ee.onFeedback({type:R,messageId:be.id,message:be})}}),oe.addEventListener("click",l=>{let b=l.target.closest("button[data-approval-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let A=b.closest(".persona-approval-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let R=b.getAttribute("data-approval-action");if(!R)return;let B=R==="approve"?"approved":"denied",O=D.getMessages().find(ve=>ve.id===L);if(!(O!=null&&O.approval))return;let ge=A.querySelector("[data-approval-buttons]");ge&&ge.querySelectorAll("button").forEach(Se=>{Se.disabled=!0,Se.style.opacity="0.5",Se.style.cursor="not-allowed"}),D.resolveApproval(O.approval,B)});let at=null,wn=null,_n={artifacts:[],selectedId:null},dn=!1,fr={current:null};oe.addEventListener("click",l=>{var Se,be,Te,ze,pt;let b=l.target.closest("[data-download-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let A=b.getAttribute("data-download-artifact");if(!A||((Te=(be=(Se=n.features)==null?void 0:Se.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Te.call(be,{type:"download",artifactId:A}))===!0)return;let R=D.getArtifactById(A),B=R==null?void 0:R.markdown,z=(R==null?void 0:R.title)||"artifact";if(!B){let Xe=b.closest("[data-open-artifact]"),$=Xe==null?void 0:Xe.closest("[data-message-id]"),Me=$==null?void 0:$.getAttribute("data-message-id");if(Me){let fe=D.getMessages().find(Re=>Re.id===Me);if(fe!=null&&fe.rawContent)try{let Re=JSON.parse(fe.rawContent);B=(ze=Re==null?void 0:Re.props)==null?void 0:ze.markdown,z=((pt=Re==null?void 0:Re.props)==null?void 0:pt.title)||z}catch{}}}if(!B)return;let O=new Blob([B],{type:"text/markdown"}),ge=URL.createObjectURL(O),ve=document.createElement("a");ve.href=ge,ve.download=`${z}.md`,ve.click(),URL.revokeObjectURL(ge)}),oe.addEventListener("click",l=>{var R,B,z;let b=l.target.closest("[data-open-artifact]");if(!b)return;let A=b.getAttribute("data-open-artifact");!A||((z=(B=(R=n.features)==null?void 0:R.artifacts)==null?void 0:B.onArtifactAction)==null?void 0:z.call(B,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),dn=!1,D.selectArtifact(A),An())}),oe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let Sn=null,wt=null,pn=null,Rn=null,hr=()=>{};function rr(){Rn==null||Rn(),Rn=null}let yr=()=>{var B;if(!Sn||!wt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),b=((B=e.ownerDocument.defaultView)!=null?B:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||b){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let A=Sn.firstElementChild;if(!A||A===wt)return;let L=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${L}px`,wt.style.zIndex="5";let R=A.offsetWidth-L/2;wt.style.left=`${Math.max(0,R)}px`},Kn=()=>{},An=()=>{var b,A,L,R,B;if(!at||!On(n))return;Ns(e,n),Fs(e,n),Kn();let l=(R=(L=(A=(b=n.features)==null?void 0:b.artifacts)==null?void 0:A.layout)==null?void 0:L.narrowHostMaxWidth)!=null?R:520,m=F.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),at.update(_n),dn?(at.setMobileOpen(!1),at.element.classList.add("persona-hidden"),(B=at.backdrop)==null||B.classList.add("persona-hidden")):_n.artifacts.length>0&&(at.element.classList.remove("persona-hidden"),at.setMobileOpen(!0)),hr()};if(On(n)){F.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(_),at=Md(n,{onSelect:b=>{var A;return(A=fr.current)==null?void 0:A.selectArtifact(b)},onDismiss:()=>{dn=!0,An()}}),at.element.classList.add("persona-hidden"),Sn=m,m.appendChild(l),m.appendChild(at.element),at.backdrop&&F.appendChild(at.backdrop),F.appendChild(m),hr=()=>{var A,L,R,B;if(!Sn||!at)return;if(!(((R=(L=(A=n.features)==null?void 0:A.artifacts)==null?void 0:L.layout)==null?void 0:R.resizable)===!0)){pn==null||pn(),pn=null,rr(),wt&&(wt.remove(),wt=null),at.element.style.removeProperty("width"),at.element.style.removeProperty("maxWidth");return}if(!wt){let z=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,ge=(B=O.defaultView)!=null?B:window,ve=Se=>{var $,Me;if(!at||Se.button!==0||e.classList.contains("persona-artifact-narrow-host")||ge.innerWidth<=640)return;Se.preventDefault(),rr();let be=Se.clientX,Te=at.element.getBoundingClientRect().width,ze=(Me=($=n.features)==null?void 0:$.artifacts)==null?void 0:Me.layout,pt=Pe=>{let fe=Sn.getBoundingClientRect().width,Re=e.classList.contains("persona-artifact-appearance-seamless"),Ct=Re?0:Pd(Sn,ge),bt=Re?0:z.getBoundingClientRect().width||6,Yt=Te-(Pe.clientX-be),sn=Wd(Yt,fe,Ct,bt,ze==null?void 0:ze.resizableMinWidth,ze==null?void 0:ze.resizableMaxWidth);at.element.style.width=`${sn}px`,at.element.style.maxWidth="none",yr()},Xe=()=>{O.removeEventListener("pointermove",pt),O.removeEventListener("pointerup",Xe),O.removeEventListener("pointercancel",Xe),Rn=null;try{z.releasePointerCapture(Se.pointerId)}catch{}};Rn=Xe,O.addEventListener("pointermove",pt),O.addEventListener("pointerup",Xe),O.addEventListener("pointercancel",Xe);try{z.setPointerCapture(Se.pointerId)}catch{}};z.addEventListener("pointerdown",ve),wt=z,Sn.insertBefore(z,at.element),pn=()=>{z.removeEventListener("pointerdown",ve)}}if(wt){let z=_n.artifacts.length>0&&!dn;wt.classList.toggle("persona-hidden",!z),yr()}},Kn=()=>{var ge,ve,Se,be,Te,ze,pt,Xe,$,Me,Pe,fe,Re,Ct;if(!x||!at||((ve=(ge=n.launcher)==null?void 0:ge.sidebarMode)!=null?ve:!1)||Xt(n)&&Fn(n).reveal==="emerge")return;let A=(Se=e.ownerDocument.defaultView)!=null?Se:window,L=(Te=(be=n.launcher)==null?void 0:be.mobileFullscreen)!=null?Te:!0,R=(pt=(ze=n.launcher)==null?void 0:ze.mobileBreakpoint)!=null?pt:640;if(L&&A.innerWidth<=R||!Id(n,x))return;let B=(Me=($=(Xe=n.launcher)==null?void 0:Xe.width)!=null?$:n.launcherWidth)!=null?Me:Pn,z=(Ct=(Re=(fe=(Pe=n.features)==null?void 0:Pe.artifacts)==null?void 0:fe.layout)==null?void 0:Re.expandedPanelWidth)!=null?Ct:"min(720px, calc(100vw - 24px))";_n.artifacts.length>0&&!dn?(F.style.width=z,F.style.maxWidth=z):(F.style.width=B,F.style.maxWidth=B)},typeof ResizeObserver!="undefined"&&(wn=new ResizeObserver(()=>{An()}),wn.observe(F))}else F.appendChild(_);e.appendChild(q);let Zn=()=>{var bt,Yt,sn,we,hn,an,Un,rt,ut,yn,lr,Ue,At,Br,Dr,ls,cs,ds,na,ra,Ut,ps,Io;let l=Xt(n),m=(Yt=(bt=n.launcher)==null?void 0:bt.sidebarMode)!=null?Yt:!1,b=l||m||((we=(sn=n.launcher)==null?void 0:sn.fullHeight)!=null?we:!1),A=((hn=n.launcher)==null?void 0:hn.enabled)===!1,L=(Un=(an=n.theme)==null?void 0:an.components)==null?void 0:Un.panel,R=jo(n),B=(bn,Nn)=>{var oo;return bn==null||bn===""?Nn:(oo=$o(R,bn))!=null?oo:bn},z=(rt=e.ownerDocument.defaultView)!=null?rt:window,O=(yn=(ut=n.launcher)==null?void 0:ut.mobileFullscreen)!=null?yn:!0,ge=(Ue=(lr=n.launcher)==null?void 0:lr.mobileBreakpoint)!=null?Ue:640,ve=z.innerWidth<=ge,Se=O&&ve&&x,be=(Br=(At=n.launcher)==null?void 0:At.position)!=null?Br:"bottom-left",Te=be==="bottom-left"||be==="top-left",ze=(ls=(Dr=n.launcher)==null?void 0:Dr.zIndex)!=null?ls:vn,pt=m||Se?"none":"1px solid var(--persona-border)",Xe=Se?"none":m?Te?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Se&&(Xe="none",pt="none");let $=m||Se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Me=B(L==null?void 0:L.border,pt),Pe=B(L==null?void 0:L.shadow,Xe),fe=B(L==null?void 0:L.borderRadius,$);if(e.style.cssText="",q.style.cssText="",F.style.cssText="",_.style.cssText="",V.style.cssText="",st.style.cssText="",Se){q.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),q.style.cssText=`
|
|
20
23
|
position: fixed !important;
|
|
21
24
|
inset: 0 !important;
|
|
22
25
|
width: 100% !important;
|
|
@@ -26,9 +29,9 @@
|
|
|
26
29
|
padding: 0 !important;
|
|
27
30
|
display: flex !important;
|
|
28
31
|
flex-direction: column !important;
|
|
29
|
-
z-index: ${
|
|
32
|
+
z-index: ${ze} !important;
|
|
30
33
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
31
|
-
`,
|
|
34
|
+
`,F.style.cssText=`
|
|
32
35
|
position: relative !important;
|
|
33
36
|
display: flex !important;
|
|
34
37
|
flex-direction: column !important;
|
|
@@ -52,20 +55,20 @@
|
|
|
52
55
|
overflow: hidden !important;
|
|
53
56
|
border-radius: 0 !important;
|
|
54
57
|
border: none !important;
|
|
55
|
-
`,
|
|
58
|
+
`,V.style.flex="1 1 0%",V.style.minHeight="0",V.style.overflowY="auto",st.style.flexShrink="0",W=!0;return}let Re=(ds=(cs=n==null?void 0:n.launcher)==null?void 0:cs.width)!=null?ds:n==null?void 0:n.launcherWidth,Ct=Re!=null?Re:Pn;if(!m&&!l)A&&b?(F.style.width="100%",F.style.maxWidth="100%"):(F.style.width=Ct,F.style.maxWidth=Ct);else if(l)if(Fn(n).reveal==="emerge"){let Nn=Fn(n).width;F.style.width=Nn,F.style.maxWidth=Nn}else F.style.width="100%",F.style.maxWidth="100%";if(Kn(),F.style.boxShadow=Pe,F.style.borderRadius=fe,_.style.border=Me,_.style.borderRadius=fe,l&&!Se&&(L==null?void 0:L.border)===void 0&&(_.style.border="none",Fn(n).side==="right"?_.style.borderLeft="1px solid var(--persona-border)":_.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",A&&(e.style.width="100%"),q.style.display="flex",q.style.flexDirection="column",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.maxHeight="100%",q.style.height="100%",A&&(q.style.overflow="hidden"),F.style.display="flex",F.style.flexDirection="column",F.style.flex="1 1 0%",F.style.minHeight="0",F.style.maxHeight="100%",F.style.height="100%",F.style.overflow="hidden",_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.overflow="hidden",V.style.flex="1 1 0%",V.style.minHeight="0",V.style.overflowY="auto",st.style.flexShrink="0"),q.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!A&&!l&&((na=Yn[be])!=null?na:Yn["bottom-right"]).split(" ").forEach(Nn=>q.classList.add(Nn)),m){let bn=(Ut=(ra=n.launcher)==null?void 0:ra.sidebarWidth)!=null?Ut:"420px";q.style.cssText=`
|
|
56
59
|
position: fixed !important;
|
|
57
60
|
top: 0 !important;
|
|
58
61
|
bottom: 0 !important;
|
|
59
|
-
width: ${
|
|
62
|
+
width: ${bn} !important;
|
|
60
63
|
height: 100vh !important;
|
|
61
64
|
max-height: 100vh !important;
|
|
62
65
|
margin: 0 !important;
|
|
63
66
|
padding: 0 !important;
|
|
64
67
|
display: flex !important;
|
|
65
68
|
flex-direction: column !important;
|
|
66
|
-
z-index: ${
|
|
67
|
-
${
|
|
68
|
-
`,
|
|
69
|
+
z-index: ${ze} !important;
|
|
70
|
+
${Te?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
71
|
+
`,F.style.cssText=`
|
|
69
72
|
position: relative !important;
|
|
70
73
|
display: flex !important;
|
|
71
74
|
flex-direction: column !important;
|
|
@@ -76,9 +79,9 @@
|
|
|
76
79
|
min-height: 0 !important;
|
|
77
80
|
margin: 0 !important;
|
|
78
81
|
padding: 0 !important;
|
|
79
|
-
box-shadow: ${
|
|
80
|
-
border-radius: ${
|
|
81
|
-
`,
|
|
82
|
+
box-shadow: ${Pe} !important;
|
|
83
|
+
border-radius: ${fe} !important;
|
|
84
|
+
`,F.style.setProperty("width","100%","important"),F.style.setProperty("max-width","100%","important"),_.style.cssText=`
|
|
82
85
|
display: flex !important;
|
|
83
86
|
flex-direction: column !important;
|
|
84
87
|
flex: 1 1 0% !important;
|
|
@@ -87,29 +90,29 @@
|
|
|
87
90
|
min-height: 0 !important;
|
|
88
91
|
max-height: 100% !important;
|
|
89
92
|
overflow: hidden !important;
|
|
90
|
-
border-radius: ${
|
|
91
|
-
border: ${
|
|
92
|
-
`,
|
|
93
|
+
border-radius: ${fe} !important;
|
|
94
|
+
border: ${Me} !important;
|
|
95
|
+
`,st.style.cssText=`
|
|
93
96
|
flex-shrink: 0 !important;
|
|
94
97
|
border-top: none !important;
|
|
95
98
|
padding: 8px 16px 12px 16px !important;
|
|
96
|
-
`}if(!E&&!l){let Jt="max-height: -moz-available !important; max-height: stretch !important;",fn=g?"":"padding-top: 1.25em !important;",or=g?"":`z-index: ${(Wr=(vr=n.launcher)==null?void 0:vr.zIndex)!=null?Wr:yn} !important;`;j.style.cssText+=Jt+fn+or}};Jn(),wr(e,n),Ts(e,n),Ms(e,n);let ht=[],Wt=null,Rt=null;ht.push(()=>{Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null}),xn&&ht.push(()=>{xn==null||xn.disconnect(),xn=null}),ht.push(()=>{ln==null||ln(),ln=null,Zn(),ft&&(ft.remove(),ft=null),et==null||et.element.style.removeProperty("width"),et==null||et.element.style.removeProperty("maxWidth")}),re&&ht.push(()=>{pe!==null&&(cancelAnimationFrame(pe),pe=null),be==null||be.destroy(),be=null,oe==null||oe.destroy(),oe=null,Me=null});let wn=null,mr=()=>{wn&&(wn(),wn=null),n.colorScheme==="auto"&&(wn=xs(()=>{wr(e,n)}))};mr(),ht.push(()=>{wn&&(wn(),wn=null)});let Nn=Jc(Fe),Sn=null,D,On=!1,In=Fc(),fr=0,gn=vs(),An=0,te=null,$n=!1,qr=1,fo=8,Jr=new Map,Je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ho=(si=(oi=n.voiceRecognition)==null?void 0:oi.autoResume)!=null?si:!1,Pn=l=>{o.emit("voice:state",{active:Je.active,source:l,timestamp:Date.now()})},mn=()=>{f(l=>({...l,voiceState:{active:Je.active,timestamp:Date.now(),manuallyDeactivated:Je.manuallyDeactivated}}))},Yo=()=>{var E,k;if(((E=n.voiceRecognition)==null?void 0:E.enabled)===!1)return;let l=ma(i.voiceState),g=!!l.active,y=Number((k=l.timestamp)!=null?k:0);Je.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<ru&&setTimeout(()=>{var P,W;Je.active||(Je.manuallyDeactivated=!1,((W=(P=n.voiceRecognition)==null?void 0:P.provider)==null?void 0:W.type)==="runtype"?D.toggleVoice().then(()=>{Je.active=D.isVoiceActive(),Pn("restore"),D.isVoiceActive()&&Pt()}):Pr("restore"))},1e3)},Go=()=>D?ld(D.getMessages()).filter(l=>!l.__skipPersist):[];function yo(l){if(!(a!=null&&a.save))return;let y={messages:l?ld(l):D?Go():[],metadata:i};try{let E=a.save(y);E instanceof Promise&&E.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)}}let Qn=null,Xo=()=>j.querySelector("#persona-scroll-container")||z,Yr=()=>{Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),$n=!1},Gr=()=>{te!==null&&(cancelAnimationFrame(te),te=null),Yr()},er=()=>{if(!Ot()||$e){nt.parentNode&&nt.remove(),nt.style.display="none";return}nt.parentNode!==_&&_.appendChild(nt),qe();let l=Do(z)>0;nt.style.display=gn.isFollowing()||!l?"none":""},bo=()=>{gn.pause()&&(Gr(),er())},hr=()=>{gn.resume(),er()},yr=(l=!1)=>{gn.isFollowing()&&(!l&&!On||(Gr(),te=requestAnimationFrame(()=>{te=null,gn.isFollowing()&&Ko(Xo(),l?220:140)})))},Ko=(l,g=500)=>{let y=l.scrollTop,E=Do(l),k=E-y;if(Math.abs(k)<1){An=l.scrollTop;return}Yr();let P=performance.now();$n=!0;let W=F=>1-Math.pow(1-F,3),V=F=>{if(!gn.isFollowing()){Yr();return}let ie=Do(l);ie!==E&&(E=ie,k=E-y);let ve=F-P,we=Math.min(ve/g,1),xe=W(we),ze=y+k*xe;l.scrollTop=ze,An=l.scrollTop,we<1?Qn=requestAnimationFrame(V):(l.scrollTop=E,An=l.scrollTop,Qn=null,$n=!1)};Qn=requestAnimationFrame(V)},Zo=l=>{let g=new Map;l.forEach(y=>{let E=Jr.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!E&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(E!=null&&E.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(E?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Jr.clear(),g.forEach((y,E)=>{Jr.set(E,y)})},Lr=(l,g,y)=>{var ve,we,xe,ze;let E=document.createElement("div"),P=(()=>{var Oe;let H=s.find(Ee=>Ee.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((Oe=n.loadingIndicator)!=null&&Oe.render)return n.loadingIndicator.render})(),W=new Set;g.forEach(H=>{var Ce,Xt;W.add(H.id);let Oe=Dc(H,fr),Ee=Nc(In,H.id,Oe);if(Ee){E.appendChild(Ee.cloneNode(!0));return}let fe=null,Re=s.find(gt=>!!(H.variant==="reasoning"&>.renderReasoning||H.variant==="tool"&>.renderToolCall||H.variant==="approval"&>.renderApproval||!H.variant&>.renderMessage)),ct=(Ce=n.layout)==null?void 0:Ce.messages;if(Re)if(H.variant==="reasoning"&&H.reasoning&&Re.renderReasoning){if(!ne)return;fe=Re.renderReasoning({message:H,defaultRenderer:()=>aa(H),config:n})}else if(H.variant==="tool"&&H.toolCall&&Re.renderToolCall){if(!Te)return;fe=Re.renderToolCall({message:H,defaultRenderer:()=>ia(H,n),config:n})}else if(H.variant==="approval"&&H.approval&&Re.renderApproval){if(n.approval===!1)return;fe=Re.renderApproval({message:H,defaultRenderer:()=>la(H,n),config:n})}else Re.renderMessage&&(fe=Re.renderMessage({message:H,defaultRenderer:()=>{let gt=lo(H,y,ct,n.messageActions,se,{loadingIndicatorRenderer:P,widgetConfig:n});return H.role!=="user"&&pa(gt,H,n,D),gt},config:n}));if(!fe&&H.role==="assistant"&&!H.variant&&n.enableComponentStreaming!==!1&&Ps(H)){let dn=Ws(H);if(dn){let nn=Is(dn,{config:n,message:H,transform:y});if(nn)if(n.wrapComponentDirectiveInBubble!==!1){let Ft=document.createElement("div");if(Ft.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ft.id=`bubble-${H.id}`,Ft.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let pn=document.createElement("div");pn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",pn.innerHTML=y({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Ft.appendChild(pn)}Ft.appendChild(nn),fe=Ft}else{let Ft=document.createElement("div");if(Ft.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ft.id=`bubble-${H.id}`,Ft.setAttribute("data-message-id",H.id),Ft.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let pn=document.createElement("div");pn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",pn.innerHTML=y({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Ft.appendChild(pn)}Ft.appendChild(nn),fe=Ft}}}if(!fe)if(H.variant==="reasoning"&&H.reasoning){if(!ne)return;fe=aa(H)}else if(H.variant==="tool"&&H.toolCall){if(!Te)return;fe=ia(H,n)}else if(H.variant==="approval"&&H.approval){if(n.approval===!1)return;fe=la(H,n)}else{let gt=(Xt=n.layout)==null?void 0:Xt.messages;gt!=null&>.renderUserMessage&&H.role==="user"?fe=gt.renderUserMessage({message:H,config:n,streaming:!!H.streaming}):gt!=null&>.renderAssistantMessage&&H.role==="assistant"?fe=gt.renderAssistantMessage({message:H,config:n,streaming:!!H.streaming}):fe=lo(H,y,gt,n.messageActions,se,{loadingIndicatorRenderer:P,widgetConfig:n}),H.role!=="user"&&fe&&pa(fe,H,n,D)}let Ge=document.createElement("div");Ge.className="persona-flex",Ge.id=`wrapper-${H.id}`,Ge.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Ge.classList.add("persona-justify-end"),(fe==null?void 0:fe.getAttribute("data-persona-component-directive"))==="true"&&Ge.classList.add("persona-w-full"),Ge.appendChild(fe),Oc(In,H.id,Oe,Ge),E.appendChild(Ge)}),$c(In,W);let V=g.some(H=>H.role==="assistant"&&H.streaming),F=g[g.length-1],ie=(F==null?void 0:F.role)==="assistant"&&!F.streaming&&F.variant!=="approval";if(On&&g.some(H=>H.role==="user")&&!V&&!ie){let H={config:n,streaming:!0,location:"standalone",defaultRenderer:jr},Oe=s.find(fe=>fe.renderLoadingIndicator),Ee=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(Ee=Oe.renderLoadingIndicator(H)),Ee===null&&((ve=n.loadingIndicator)!=null&&ve.render)&&(Ee=n.loadingIndicator.render(H)),Ee===null&&(Ee=jr()),Ee){let fe=document.createElement("div"),Re=((we=n.loadingIndicator)==null?void 0:we.showBubble)!==!1;fe.className=Re?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Ee);let ct=document.createElement("div");ct.className="persona-flex",ct.id="wrapper-typing-indicator",ct.setAttribute("data-wrapper-id","typing-indicator"),ct.appendChild(fe),E.appendChild(ct)}}if(!On&&g.length>0){let H=g[g.length-1],Oe={config:n,lastMessage:H,messageCount:g.length},Ee=s.find(Re=>Re.renderIdleIndicator),fe=null;if(Ee!=null&&Ee.renderIdleIndicator&&(fe=Ee.renderIdleIndicator(Oe)),fe===null&&((xe=n.loadingIndicator)!=null&&xe.renderIdle)&&(fe=n.loadingIndicator.renderIdle(Oe)),fe){let Re=document.createElement("div"),ct=((ze=n.loadingIndicator)==null?void 0:ze.showBubble)!==!1;Re.className=ct?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Re.setAttribute("data-idle-indicator","true"),Re.appendChild(fe);let Ge=document.createElement("div");Ge.className="persona-flex",Ge.id="wrapper-idle-indicator",Ge.setAttribute("data-wrapper-id","idle-indicator"),Ge.appendChild(Re),E.appendChild(Ge)}}Bc(l,E)},Ir=()=>{var F,ie,ve,we,xe;if(!b)return;let l=Ut(n),g=(F=e.ownerDocument.defaultView)!=null?F:window,y=(ve=(ie=n.launcher)==null?void 0:ie.mobileBreakpoint)!=null?ve:640,E=(xe=(we=n.launcher)==null?void 0:we.mobileFullscreen)!=null?xe:!0,k=g.innerWidth<=y,P=E&&k&&b,W=Hn(n).reveal;T?(j.style.removeProperty("display"),j.style.display=l?"flex":"",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-95","persona-opacity-0"),q.classList.add("persona-scale-100","persona-opacity-100"),N?N.element.style.display="none":Q&&(Q.style.display="none")):(l?l&&(W==="overlay"||W==="push")&&!P?(j.style.removeProperty("display"),j.style.display="flex",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.setProperty("display","none","important"),j.classList.remove("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.display="",j.classList.add("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-100","persona-opacity-100"),q.classList.add("persona-scale-95","persona-opacity-0")),N?N.element.style.display=l?"none":"":Q&&(Q.style.display=l?"none":""))},Tt=(l,g="user")=>{var P,W;if(!b||T===l)return;let y=T;T=l,Ir();let E=(()=>{var ze,H,Oe,Ee,fe,Re,ct;let V=(H=(ze=n.launcher)==null?void 0:ze.sidebarMode)!=null?H:!1,F=(Oe=e.ownerDocument.defaultView)!=null?Oe:window,ie=(fe=(Ee=n.launcher)==null?void 0:Ee.mobileFullscreen)!=null?fe:!0,ve=(ct=(Re=n.launcher)==null?void 0:Re.mobileBreakpoint)!=null?ct:640,we=F.innerWidth<=ve,xe=Ut(n)&&ie&&we;return V||ie&&we&&b||xe})();if(T&&E){if(!Wt){let V=e.getRootNode(),F=V instanceof ShadowRoot?V.host:e.closest(".persona-host");F&&(Wt=Qs(F,(W=(P=n.launcher)==null?void 0:P.zIndex)!=null?W:yn))}Rt||(Rt=ea(e.ownerDocument))}else T||(Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null);T&&(ut(),yr(!0));let k={open:T,source:g,timestamp:Date.now()};T&&!y?o.emit("widget:opened",k):!T&&y&&o.emit("widget:closed",k),o.emit("widget:state",{open:T,launcherEnabled:b,voiceActive:Je.active,streaming:D.isStreaming()})},Xr=l=>{K.disabled=l,O&&(O.disabled=l),Nn.buttons.forEach(g=>{g.disabled=l}),Qe.dataset.personaComposerStreaming=l?"true":"false",Qe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},Kr=()=>{Je.active||J&&J.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Kr(),200)});let xo=()=>{var y,E,k,P,W,V,F,ie,ve,we,xe;Vt.textContent=(E=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?E:"Hello \u{1F44B}",Ne.textContent=(P=(k=n.copy)==null?void 0:k.welcomeSubtitle)!=null?P:"Ask anything about your account or products.",J.placeholder=(V=(W=n.copy)==null?void 0:W.inputPlaceholder)!=null?V:"How can I help...";let l=z.querySelector("[data-persona-intro-card]");if(l){let ze=((F=n.copy)==null?void 0:F.showWelcomeCard)!==!1;l.style.display=ze?"":"none",ze?(z.classList.remove("persona-gap-3"),z.classList.add("persona-gap-6")):(z.classList.remove("persona-gap-6"),z.classList.add("persona-gap-3"))}(ve=(ie=n.sendButton)==null?void 0:ie.useIcon)!=null&&ve||(K.textContent=(xe=(we=n.copy)==null?void 0:we.sendButtonLabel)!=null?xe:"Send"),J.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',J.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};if(n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(g=>({...g,sessionId:l}))}}),D=new oo(n,{onMessagesChanged(l){Lr(ee,l,$),D&&(l.some(k=>k.role==="user")?Nn.render([],D,J,l):Nn.render(n.suggestionChips,D,J,l,n.suggestionChipsConfig)),yr(!On),Zo(l);let g=[...l].reverse().find(E=>E.role==="user"),y=Je.lastUserMessageId;g&&g.id!==y&&(Je.lastUserMessageId=g.id,o.emit("user:message",g)),Je.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),yo(l)},onStatusChanged(l){var E;let g=(E=n.statusIndicator)!=null?E:{};St(Lt,(k=>{var P,W,V,F;return k==="idle"?(P=g.idleText)!=null?P:sn.idle:k==="connecting"?(W=g.connectingText)!=null?W:sn.connecting:k==="connected"?(V=g.connectedText)!=null?V:sn.connected:k==="error"?(F=g.errorText)!=null?F:sn.error:sn[k]})(l),g,l)},onStreamingChanged(l){On=l,Xr(l),D&&Lr(ee,D.getMessages(),$),l||yr(!0)},onVoiceStatusChanged(l){var g,y;if(((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":x(),Qt();break;case"speaking":x(),Ht();break;default:l==="idle"&&D.isBargeInActive()?(x(),Pt(),O==null||O.setAttribute("aria-label","End voice session")):(Je.active=!1,x(),Pn("system"),mn());break}},onArtifactsState(l){Fn=l,Cn()}}),pr.current=D,((ii=(ai=n.voiceRecognition)==null?void 0:ai.provider)==null?void 0:ii.type)==="runtype")try{D.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&D.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),oe&&D.setSSEEventCallback((l,g)=>{oe==null||oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),d&&d.then(l=>{var g;l&&(l.metadata&&(i=ma(l.metadata),M.syncFromMetadata()),(g=l.messages)!=null&&g.length&&D.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let vo=l=>{var k;l.preventDefault();let g=J.value.trim(),y=(k=_e==null?void 0:_e.hasAttachments())!=null?k:!1;if(!g&&!y)return;let E;y&&(E=[],E.push(..._e.getContentParts()),g&&E.push(cs(g))),J.value="",J.style.height="auto",D.sendMessage(g,{contentParts:E}),y&&_e.clearAttachments()},Co=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),K.click())},wo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!_e)return;let g=su(l.clipboardData);g.length!==0&&(l.preventDefault(),await _e.handleFiles(g))},cn=null,En=!1,tr=null,je=null,So=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Pr=(l="user")=>{var P,W,V,F,ie,ve,we;if(En||D.isStreaming())return;let g=So();if(!g)return;cn=new g;let E=(W=((P=n.voiceRecognition)!=null?P:{}).pauseDuration)!=null?W:2e3;cn.continuous=!0,cn.interimResults=!0,cn.lang="en-US";let k=J.value;cn.onresult=xe=>{let ze="",H="";for(let Ee=0;Ee<xe.results.length;Ee++){let fe=xe.results[Ee],Re=fe[0].transcript;fe.isFinal?ze+=Re+" ":H=Re}let Oe=k+ze+H;J.value=Oe,tr&&clearTimeout(tr),(ze||H)&&(tr=window.setTimeout(()=>{let Ee=J.value.trim();Ee&&cn&&En&&(_n(),J.value="",J.style.height="auto",D.sendMessage(Ee,{viaVoice:!0}))},E))},cn.onerror=xe=>{xe.error!=="no-speech"&&_n()},cn.onend=()=>{if(En){let xe=J.value.trim();xe&&xe!==k.trim()&&(J.value="",J.style.height="auto",D.sendMessage(xe,{viaVoice:!0})),_n()}};try{if(cn.start(),En=!0,Je.active=!0,l!=="system"&&(Je.manuallyDeactivated=!1),Pn(l),mn(),O){let xe=(V=n.voiceRecognition)!=null?V:{};je={backgroundColor:O.style.backgroundColor,color:O.style.color,borderColor:O.style.borderColor,iconName:(F=xe.iconName)!=null?F:"mic",iconSize:parseFloat((we=(ve=xe.iconSize)!=null?ve:(ie=n.sendButton)==null?void 0:ie.size)!=null?we:"40")||24};let ze=xe.recordingBackgroundColor,H=xe.recordingIconColor,Oe=xe.recordingBorderColor;if(O.classList.add("persona-voice-recording"),O.style.backgroundColor=ze!=null?ze:"var(--persona-voice-recording-bg, #ef4444)",O.style.color=H!=null?H:"var(--persona-voice-recording-indicator, #ffffff)",H){let Ee=O.querySelector("svg");Ee&&Ee.setAttribute("stroke",H)}Oe&&(O.style.borderColor=Oe),O.setAttribute("aria-label","Stop voice recognition")}}catch{_n("system")}},_n=(l="user")=>{if(En){if(En=!1,tr&&(clearTimeout(tr),tr=null),cn){try{cn.stop()}catch{}cn=null}if(Je.active=!1,Pn(l),mn(),O){if(O.classList.remove("persona-voice-recording"),je){O.style.backgroundColor=je.backgroundColor,O.style.color=je.color,O.style.borderColor=je.borderColor;let g=O.querySelector("svg");g&&g.setAttribute("stroke",je.color||"currentColor"),je=null}O.setAttribute("aria-label","Start voice recognition")}}},X=(l,g)=>{var fe,Re,ct,Ge,Ce,Xt,gt,dn;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),E=((fe=l==null?void 0:l.provider)==null?void 0:fe.type)==="runtype";if(!(y||E))return null;let P=h("div","persona-send-button-wrapper"),W=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");W.type="button",W.setAttribute("aria-label","Start voice recognition");let V=(Re=l==null?void 0:l.iconName)!=null?Re:"mic",F=(ct=g==null?void 0:g.size)!=null?ct:"40px",ie=(Ge=l==null?void 0:l.iconSize)!=null?Ge:F,ve=parseFloat(ie)||24,we=(Ce=l==null?void 0:l.backgroundColor)!=null?Ce:g==null?void 0:g.backgroundColor,xe=(Xt=l==null?void 0:l.iconColor)!=null?Xt:g==null?void 0:g.textColor;W.style.width=ie,W.style.height=ie,W.style.minWidth=ie,W.style.minHeight=ie,W.style.fontSize="18px",W.style.lineHeight="1",xe?W.style.color=xe:W.style.color="var(--persona-text, #111827)";let H=me(V,ve,xe||"currentColor",1.5);H?W.appendChild(H):W.textContent="\u{1F3A4}",we?W.style.backgroundColor=we:W.style.backgroundColor="",l!=null&&l.borderWidth&&(W.style.borderWidth=l.borderWidth,W.style.borderStyle="solid"),l!=null&&l.borderColor&&(W.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(W.style.paddingLeft=l.paddingX,W.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(W.style.paddingTop=l.paddingY,W.style.paddingBottom=l.paddingY),P.appendChild(W);let Oe=(gt=l==null?void 0:l.tooltipText)!=null?gt:"Start voice recognition";if(((dn=l==null?void 0:l.showTooltip)!=null?dn:!1)&&Oe){let nn=h("div","persona-send-button-tooltip");nn.textContent=Oe,P.appendChild(nn)}return{micButton:W,micButtonWrapper:P}},Ye=()=>{var g,y,E,k,P;if(!O||je)return;let l=(g=n.voiceRecognition)!=null?g:{};je={backgroundColor:O.style.backgroundColor,color:O.style.color,borderColor:O.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((P=(k=l.iconSize)!=null?k:(E=n.sendButton)==null?void 0:E.size)!=null?P:"40")||24}},pt=(l,g)=>{var P,W,V,F,ie;if(!O)return;let y=O.querySelector("svg");y&&y.remove();let E=(ie=je==null?void 0:je.iconSize)!=null?ie:parseFloat((F=(V=(P=n.voiceRecognition)==null?void 0:P.iconSize)!=null?V:(W=n.sendButton)==null?void 0:W.size)!=null?F:"40")||24,k=me(l,E,g,1.5);k&&O.appendChild(k)},It=()=>{O&&O.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Pt=()=>{var k;if(!O)return;Ye();let l=(k=n.voiceRecognition)!=null?k:{},g=l.recordingBackgroundColor,y=l.recordingIconColor,E=l.recordingBorderColor;if(It(),O.classList.add("persona-voice-recording"),O.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",O.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let P=O.querySelector("svg");P&&P.setAttribute("stroke",y)}E&&(O.style.borderColor=E),O.setAttribute("aria-label","Stop voice recognition")},Qt=()=>{var V,F,ie,ve,we,xe,ze,H;if(!O)return;Ye();let l=(V=n.voiceRecognition)!=null?V:{},g=D.getVoiceInterruptionMode(),y=(F=l.processingIconName)!=null?F:"loader",E=(ve=(ie=l.processingIconColor)!=null?ie:je==null?void 0:je.color)!=null?ve:"",k=(xe=(we=l.processingBackgroundColor)!=null?we:je==null?void 0:je.backgroundColor)!=null?xe:"",P=(H=(ze=l.processingBorderColor)!=null?ze:je==null?void 0:je.borderColor)!=null?H:"";It(),O.classList.add("persona-voice-processing"),O.style.backgroundColor=k,O.style.borderColor=P;let W=E||"currentColor";O.style.color=W,pt(y,W),O.setAttribute("aria-label","Processing voice input"),g==="none"&&(O.style.cursor="default")},Ht=()=>{var ie,ve,we,xe,ze,H,Oe,Ee,fe,Re,ct,Ge;if(!O)return;Ye();let l=(ie=n.voiceRecognition)!=null?ie:{},g=D.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",E=(ve=l.speakingIconName)!=null?ve:y,k=(H=l.speakingIconColor)!=null?H:g==="barge-in"?(xe=(we=l.recordingIconColor)!=null?we:je==null?void 0:je.color)!=null?xe:"":(ze=je==null?void 0:je.color)!=null?ze:"",P=(fe=l.speakingBackgroundColor)!=null?fe:g==="barge-in"?(Oe=l.recordingBackgroundColor)!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)":(Ee=je==null?void 0:je.backgroundColor)!=null?Ee:"",W=(Ge=l.speakingBorderColor)!=null?Ge:g==="barge-in"?(Re=l.recordingBorderColor)!=null?Re:"":(ct=je==null?void 0:je.borderColor)!=null?ct:"";It(),O.classList.add("persona-voice-speaking"),O.style.backgroundColor=P,O.style.borderColor=W;let V=k||"currentColor";O.style.color=V,pt(E,V);let F=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";O.setAttribute("aria-label",F),g==="none"&&(O.style.cursor="default"),g==="barge-in"&&O.classList.add("persona-voice-recording")},x=()=>{var l,g,y;O&&(It(),je&&(O.style.backgroundColor=(l=je.backgroundColor)!=null?l:"",O.style.color=(g=je.color)!=null?g:"",O.style.borderColor=(y=je.borderColor)!=null?y:"",pt(je.iconName,je.color||"currentColor"),je=null),O.style.cursor="",O.setAttribute("aria-label","Start voice recognition"))},We=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let y=D.getVoiceStatus(),E=D.getVoiceInterruptionMode();if(E==="none"&&(y==="processing"||y==="speaking"))return;if(E==="cancel"&&(y==="processing"||y==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{Je.active=!1,Je.manuallyDeactivated=!0,mn(),Pn("user"),x()});return}D.toggleVoice().then(()=>{Je.active=D.isVoiceActive(),Je.manuallyDeactivated=!D.isVoiceActive(),mn(),Pn("user"),D.isVoiceActive()?Pt():x()});return}if(En){let y=J.value.trim();Je.manuallyDeactivated=!0,mn(),_n("user"),y&&(J.value="",J.style.height="auto",D.sendMessage(y))}else Je.manuallyDeactivated=!1,mn(),Pr("user")};_t=We,O&&(O.addEventListener("click",We),ht.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),x()):_n("system"),O&&O.removeEventListener("click",We)}));let I=o.on("assistant:complete",()=>{ho&&(Je.active||Je.manuallyDeactivated||ho==="assistant"&&!Je.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!Je.active&&!Je.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?D.toggleVoice().then(()=>{Je.active=D.isVoiceActive(),Pn("auto"),D.isVoiceActive()&&Pt()}):Pr("auto"))},600))});ht.push(I);let A=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});ht.push(A);let G=()=>{Tt(!T,"user")},N=null,Q=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>Oo(n,G).element,onToggle:G});g&&(Q=g)}Q||(N=Oo(n,G))}N?e.appendChild(N.element):Q&&e.appendChild(Q),Ir(),Nn.render(n.suggestionChips,D,J,void 0,n.suggestionChipsConfig),xo(),Xr(D.isStreaming()),yr(!0),Yo(),S&&(b?T&&setTimeout(()=>Kr(),200):setTimeout(()=>Kr(),0));let ut=()=>{var F,ie,ve,we,xe,ze,H,Oe,Ee,fe,Re,ct,Ge,Ce,Xt,gt,dn,nn,rn,Ft,pn,Ve;let l=Ut(n),g=(ie=(F=n.launcher)==null?void 0:F.sidebarMode)!=null?ie:!1,y=l||g||((we=(ve=n.launcher)==null?void 0:ve.fullHeight)!=null?we:!1),E=(xe=e.ownerDocument.defaultView)!=null?xe:window,k=(H=(ze=n.launcher)==null?void 0:ze.mobileFullscreen)!=null?H:!0,P=(Ee=(Oe=n.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?Ee:640,W=E.innerWidth<=P,V=k&&W&&b;try{if(V){Jn(),wr(e,n);return}if(B&&(B=!1,Jn(),wr(e,n)),!b&&!l){q.style.height="",q.style.width="";return}if(!g&&!l){let mt=(Re=(fe=n==null?void 0:n.launcher)==null?void 0:fe.width)!=null?Re:n==null?void 0:n.launcherWidth,Rn=mt!=null?mt:Mn;q.style.width=Rn,q.style.maxWidth=Rn}if(qn(),!y){let mt=E.innerHeight,Rn=64,br=(Ge=(ct=n.launcher)==null?void 0:ct.heightOffset)!=null?Ge:0,nr=Math.max(200,mt-Rn),xr=Math.min(640,nr),rr=Math.max(200,xr-br);q.style.height=`${rr}px`}}finally{if(qe(),Ir(),T&&b){let Rn=((Ce=e.ownerDocument.defaultView)!=null?Ce:window).innerWidth<=((gt=(Xt=n.launcher)==null?void 0:Xt.mobileBreakpoint)!=null?gt:640),br=(nn=(dn=n.launcher)==null?void 0:dn.sidebarMode)!=null?nn:!1,nr=(Ft=(rn=n.launcher)==null?void 0:rn.mobileFullscreen)!=null?Ft:!0,xr=Ut(n)&&nr&&Rn,rr=br||nr&&Rn&&b||xr;if(rr&&!Rt){let Zr=e.getRootNode(),Qr=Zr instanceof ShadowRoot?Zr.host:e.closest(".persona-host");Qr&&!Wt&&(Wt=Qs(Qr,(Ve=(pn=n.launcher)==null?void 0:pn.zIndex)!=null?Ve:yn)),Rt=ea(e.ownerDocument)}else rr||(Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null)}}};ut();let Mt=(li=e.ownerDocument.defaultView)!=null?li:window;if(Mt.addEventListener("resize",ut),ht.push(()=>Mt.removeEventListener("resize",ut)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{qe()});l.observe(Qe),ht.push(()=>l.disconnect())}An=z.scrollTop;let Bt=()=>{let l=z.scrollTop,{action:g,nextLastScrollTop:y}=Cs({following:gn.isFollowing(),currentScrollTop:l,lastScrollTop:An,nearBottom:Fo(z,fo),userScrollThreshold:qr,isAutoScrolling:$n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=y,g==="resume"){hr();return}g==="pause"&&bo()};z.addEventListener("scroll",Bt,{passive:!0}),ht.push(()=>z.removeEventListener("scroll",Bt));let en=l=>{let g=ws({following:gn.isFollowing(),deltaY:l.deltaY,nearBottom:Fo(z,fo),resumeWhenNearBottom:!0});g==="pause"?bo():g==="resume"&&hr()};z.addEventListener("wheel",en,{passive:!0}),ht.push(()=>z.removeEventListener("wheel",en)),nt.addEventListener("click",()=>{z.scrollTop=z.scrollHeight,An=z.scrollTop,hr(),yr(!0)}),ht.push(()=>nt.remove()),ht.push(()=>{Gr()});let qt=()=>{le&&(Sn&&(le.removeEventListener("click",Sn),Sn=null),b?(le.style.display="",Sn=()=>{Tt(!1,"user")},le.addEventListener("click",Sn)):le.style.display="none")};qt(),(()=>{let{clearChatButton:l}=ae;l&&l.addEventListener("click",()=>{D.clearMessages(),In.clear(),hr();try{localStorage.removeItem(mo),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${mo}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==mo)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},M.syncFromMetadata(),oe==null||oe.clear(),be==null||be.update()})})(),tt&&tt.addEventListener("submit",vo),J==null||J.addEventListener("keydown",Co),J==null||J.addEventListener("paste",wo),ht.push(()=>{tt&&tt.removeEventListener("submit",vo),J==null||J.removeEventListener("keydown",Co),J==null||J.removeEventListener("paste",wo)}),ht.push(()=>{D.cancel()}),N?ht.push(()=>{N==null||N.destroy()}):Q&&ht.push(()=>{Q==null||Q.remove()});let Ae={update(l){var fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Fi,Ni,Oi,$i,_i,ji,zi,Ui,Vi,qi,Ji,Yi,Gi,Xi,Ki,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,gl,ml,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Fl,Nl,Ol,$l,_l,jl,zl,Ul,Vl,ql,Jl,Yl,Gl,Xl,Kl,Zl,Ql,ec,tc,nc,rc,oc;let g=n.toolCall,y=n.messageActions,E=(fi=n.layout)==null?void 0:fi.messages,k=n.colorScheme,P=n.loadingIndicator,W=n.iterationDisplay;n={...n,...l},Jn(),wr(e,n),Ts(e,n),Ms(e,n),Cn(),n.colorScheme!==k&&mr();let V=Uo.getForInstance(n.plugins);s.length=0,s.push(...V),b=(yi=(hi=n.launcher)==null?void 0:hi.enabled)!=null?yi:!0,C=(xi=(bi=n.launcher)==null?void 0:bi.autoExpand)!=null?xi:!1,ne=(Ci=(vi=n.features)==null?void 0:vi.showReasoning)!=null?Ci:!0,Te=(Si=(wi=n.features)==null?void 0:wi.showToolCalls)!=null?Si:!0,Se=(Ei=(Ai=n.features)==null?void 0:Ai.scrollToBottom)!=null?Ei:{},lt(),er();let F=re;if(re=(Mi=(Ti=n.features)==null?void 0:Ti.showEventStreamToggle)!=null?Mi:!1,re&&!F){if(oe||(Me=new zo(he),oe=new jo(ke,Me),Me.open().then(()=>oe==null?void 0:oe.restore()).catch(()=>{}),D.setSSEEventCallback((U,rt)=>{oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:U,timestamp:Date.now(),payload:JSON.stringify(rt)})})),!Xe&&Ze){let U=(Li=(ki=n.features)==null?void 0:ki.eventStream)==null?void 0:Li.classNames,rt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(U!=null&&U.toggleButton?" "+U.toggleButton:"");Xe=h("button",rt),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=bn.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let kt=me("activity","18px","currentColor",1.5);kt&&Xe.appendChild(kt);let Ue=ae.clearChatButtonWrapper,st=ae.closeButtonWrapper,zt=Ue||st;zt&&zt.parentNode===Ze?Ze.insertBefore(Xe,zt):Ze.appendChild(Xe),Xe.addEventListener("click",()=>{$e?Dn():Xn()})}}else!re&&F&&(Dn(),Xe&&(Xe.remove(),Xe=null),oe==null||oe.clear(),Me==null||Me.destroy(),oe=null,Me=null);if(((Ii=n.launcher)==null?void 0:Ii.enabled)===!1&&N&&(N.destroy(),N=null),((Pi=n.launcher)==null?void 0:Pi.enabled)===!1&&Q&&(Q.remove(),Q=null),((Wi=n.launcher)==null?void 0:Wi.enabled)!==!1&&!N&&!Q){let U=s.find(rt=>rt.renderLauncher);if(U!=null&&U.renderLauncher){let rt=U.renderLauncher({config:n,defaultRenderer:()=>Oo(n,G).element,onToggle:G});rt&&(Q=rt,e.appendChild(Q))}Q||(N=Oo(n,G),e.appendChild(N.element))}N&&N.update(n),At&&((Ri=n.launcher)==null?void 0:Ri.title)!==void 0&&(At.textContent=n.launcher.title),Et&&((Hi=n.launcher)==null?void 0:Hi.subtitle)!==void 0&&(Et.textContent=n.launcher.subtitle);let ie=(Bi=n.layout)==null?void 0:Bi.header;if((ie==null?void 0:ie.layout)!==L&&Ze){let U=ie?ao(n,ie,{showClose:b,onClose:()=>Tt(!1,"user")}):ir({config:n,showClose:b,onClose:()=>Tt(!1,"user")});Ze.replaceWith(U.header),Ze=U.header,Ie=U.iconHolder,At=U.headerTitle,Et=U.headerSubtitle,le=U.closeButton,L=ie==null?void 0:ie.layout}else if(ie&&(Ie&&(Ie.style.display=ie.showIcon===!1?"none":""),At&&(At.style.display=ie.showTitle===!1?"none":""),Et&&(Et.style.display=ie.showSubtitle===!1?"none":""),le&&(le.style.display=ie.showCloseButton===!1?"none":""),ae.clearChatButtonWrapper)){let U=ie.showClearChat;if(U!==void 0){ae.clearChatButtonWrapper.style.display=U?"":"none";let{closeButtonWrapper:rt}=ae;rt&&!rt.classList.contains("persona-absolute")&&(U?rt.classList.remove("persona-ml-auto"):rt.classList.add("persona-ml-auto"))}}let we=((Di=n.layout)==null?void 0:Di.showHeader)!==!1;Ze&&(Ze.style.display=we?"":"none");let xe=((Fi=n.layout)==null?void 0:Fi.showFooter)!==!1;Qe&&(Qe.style.display=xe?"":"none"),qe(),er(),b!==w?b?Tt(C,"auto"):(T=!0,Ir()):C!==R&&Tt(C,"auto"),R=C,w=b,ut(),qt();let Oe=JSON.stringify(l.toolCall)!==JSON.stringify(g),Ee=JSON.stringify(n.messageActions)!==JSON.stringify(y),fe=JSON.stringify((Ni=n.layout)==null?void 0:Ni.messages)!==JSON.stringify(E),Re=((Oi=n.loadingIndicator)==null?void 0:Oi.render)!==(P==null?void 0:P.render)||(($i=n.loadingIndicator)==null?void 0:$i.renderIdle)!==(P==null?void 0:P.renderIdle)||((_i=n.loadingIndicator)==null?void 0:_i.showBubble)!==(P==null?void 0:P.showBubble),ct=n.iterationDisplay!==W;(Oe||Ee||fe||Re||ct)&&D&&(fr++,Lr(ee,D.getMessages(),$));let Ce=(ji=n.launcher)!=null?ji:{},Xt=(zi=Ce.headerIconHidden)!=null?zi:!1,gt=(Vi=(Ui=n.layout)==null?void 0:Ui.header)==null?void 0:Vi.showIcon,dn=Xt||gt===!1,nn=Ce.headerIconName,rn=(qi=Ce.headerIconSize)!=null?qi:"48px";if(Ie){let U=_.querySelector(".persona-border-b-persona-divider"),rt=U==null?void 0:U.querySelector(".persona-flex-col");if(dn)Ie.style.display="none",U&&rt&&!U.contains(rt)&&U.insertBefore(rt,U.firstChild);else{if(Ie.style.display="",Ie.style.height=rn,Ie.style.width=rn,U&&rt&&(U.contains(Ie)?Ie.nextSibling!==rt&&(Ie.remove(),U.insertBefore(Ie,rt)):U.insertBefore(Ie,rt)),nn){let Ue=parseFloat(rn)||24,st=me(nn,Ue*.6,"#ffffff",2);st?Ie.replaceChildren(st):Ie.textContent=(Ji=Ce.agentIconText)!=null?Ji:"\u{1F4AC}"}else if(Ce.iconUrl){let Ue=Ie.querySelector("img");if(Ue)Ue.src=Ce.iconUrl,Ue.style.height=rn,Ue.style.width=rn;else{let st=document.createElement("img");st.src=Ce.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=rn,st.style.width=rn,Ie.replaceChildren(st)}}else{let Ue=Ie.querySelector("svg"),st=Ie.querySelector("img");(Ue||st)&&Ie.replaceChildren(),Ie.textContent=(Yi=Ce.agentIconText)!=null?Yi:"\u{1F4AC}"}let kt=Ie.querySelector("img");kt&&(kt.style.height=rn,kt.style.width=rn)}}let Ft=(Xi=(Gi=n.layout)==null?void 0:Gi.header)==null?void 0:Xi.showTitle,pn=(Zi=(Ki=n.layout)==null?void 0:Ki.header)==null?void 0:Zi.showSubtitle;if(At&&(At.style.display=Ft===!1?"none":""),Et&&(Et.style.display=pn===!1?"none":""),le){((el=(Qi=n.layout)==null?void 0:Qi.header)==null?void 0:el.showCloseButton)===!1?le.style.display="none":le.style.display="";let rt=(tl=Ce.closeButtonSize)!=null?tl:"32px",kt=(nl=Ce.closeButtonPlacement)!=null?nl:"inline";le.style.height=rt,le.style.width=rt;let{closeButtonWrapper:Ue}=ae,st=kt==="top-right",zt=Ue==null?void 0:Ue.classList.contains("persona-absolute");if(Ue&&st!==zt)if(Ue.remove(),st)Ue.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",_.style.position="relative",_.appendChild(Ue);else{let Ke=(ol=(rl=Ce.clearChat)==null?void 0:rl.placement)!=null?ol:"inline",Yt=(al=(sl=Ce.clearChat)==null?void 0:sl.enabled)!=null?al:!0;Ue.className=Yt&&Ke==="inline"?"":"persona-ml-auto";let hn=_.querySelector(".persona-border-b-persona-divider");hn&&hn.appendChild(Ue)}if(le.style.color=Ce.closeButtonColor||bn.actionIconColor,Ce.closeButtonBackgroundColor?(le.style.backgroundColor=Ce.closeButtonBackgroundColor,le.classList.remove("hover:persona-bg-gray-100")):(le.style.backgroundColor="",le.classList.add("hover:persona-bg-gray-100")),Ce.closeButtonBorderWidth||Ce.closeButtonBorderColor){let Ke=Ce.closeButtonBorderWidth||"0px",Yt=Ce.closeButtonBorderColor||"transparent";le.style.border=`${Ke} solid ${Yt}`,le.classList.remove("persona-border-none")}else le.style.border="",le.classList.add("persona-border-none");Ce.closeButtonBorderRadius?(le.style.borderRadius=Ce.closeButtonBorderRadius,le.classList.remove("persona-rounded-full")):(le.style.borderRadius="",le.classList.add("persona-rounded-full")),Ce.closeButtonPaddingX?(le.style.paddingLeft=Ce.closeButtonPaddingX,le.style.paddingRight=Ce.closeButtonPaddingX):(le.style.paddingLeft="",le.style.paddingRight=""),Ce.closeButtonPaddingY?(le.style.paddingTop=Ce.closeButtonPaddingY,le.style.paddingBottom=Ce.closeButtonPaddingY):(le.style.paddingTop="",le.style.paddingBottom="");let on=(il=Ce.closeButtonIconName)!=null?il:"x",jn=(ll=Ce.closeButtonIconText)!=null?ll:"\xD7";le.innerHTML="";let un=me(on,"20px","currentColor",2);un?le.appendChild(un):le.textContent=jn;let Nt=(cl=Ce.closeButtonTooltipText)!=null?cl:"Close chat",Tn=(dl=Ce.closeButtonShowTooltip)!=null?dl:!0;if(le.setAttribute("aria-label",Nt),Ue&&(Ue._cleanupTooltip&&(Ue._cleanupTooltip(),delete Ue._cleanupTooltip),Tn&&Nt)){let Ke=null,Yt=()=>{if(Ke||!le)return;let Rr=le.ownerDocument,To=Rr.body;if(!To)return;Ke=Yn(Rr,"div","persona-clear-chat-tooltip"),Ke.textContent=Nt;let Mo=Yn(Rr,"div");Mo.className="persona-clear-chat-tooltip-arrow",Ke.appendChild(Mo);let Hr=le.getBoundingClientRect();Ke.style.position="fixed",Ke.style.zIndex=String(Sr),Ke.style.left=`${Hr.left+Hr.width/2}px`,Ke.style.top=`${Hr.top-8}px`,Ke.style.transform="translate(-50%, -100%)",To.appendChild(Ke)},hn=()=>{Ke&&Ke.parentNode&&(Ke.parentNode.removeChild(Ke),Ke=null)};Ue.addEventListener("mouseenter",Yt),Ue.addEventListener("mouseleave",hn),le.addEventListener("focus",Yt),le.addEventListener("blur",hn),Ue._cleanupTooltip=()=>{hn(),Ue&&(Ue.removeEventListener("mouseenter",Yt),Ue.removeEventListener("mouseleave",hn)),le&&(le.removeEventListener("focus",Yt),le.removeEventListener("blur",hn))}}}let{clearChatButton:Ve,clearChatButtonWrapper:mt}=ae;if(Ve){let U=(pl=Ce.clearChat)!=null?pl:{},rt=(ul=U.enabled)!=null?ul:!0,kt=(ml=(gl=n.layout)==null?void 0:gl.header)==null?void 0:ml.showClearChat,Ue=kt!==void 0?kt:rt,st=(fl=U.placement)!=null?fl:"inline";if(mt){mt.style.display=Ue?"":"none";let{closeButtonWrapper:zt}=ae;zt&&!zt.classList.contains("persona-absolute")&&(Ue?zt.classList.remove("persona-ml-auto"):zt.classList.add("persona-ml-auto"));let on=st==="top-right",jn=mt.classList.contains("persona-absolute");if(on!==jn&&Ue){if(mt.remove(),on)mt.className="persona-absolute persona-top-4 persona-z-50",mt.style.right="48px",_.style.position="relative",_.appendChild(mt);else{mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",mt.style.right="";let Nt=_.querySelector(".persona-border-b-persona-divider"),Tn=ae.closeButtonWrapper;Nt&&Tn&&Tn.parentElement===Nt?Nt.insertBefore(mt,Tn):Nt&&Nt.appendChild(mt)}let un=ae.closeButtonWrapper;un&&!un.classList.contains("persona-absolute")&&(on?un.classList.add("persona-ml-auto"):un.classList.remove("persona-ml-auto"))}}if(Ue){let zt=(hl=U.size)!=null?hl:"32px";Ve.style.height=zt,Ve.style.width=zt;let on=(yl=U.iconName)!=null?yl:"refresh-cw",jn=(bl=U.iconColor)!=null?bl:"";Ve.style.color=jn||bn.actionIconColor,Ve.innerHTML="";let un=me(on,"20px","currentColor",2);if(un&&Ve.appendChild(un),U.backgroundColor?(Ve.style.backgroundColor=U.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),U.borderWidth||U.borderColor){let Ke=U.borderWidth||"0px",Yt=U.borderColor||"transparent";Ve.style.border=`${Ke} solid ${Yt}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");U.borderRadius?(Ve.style.borderRadius=U.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),U.paddingX?(Ve.style.paddingLeft=U.paddingX,Ve.style.paddingRight=U.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),U.paddingY?(Ve.style.paddingTop=U.paddingY,Ve.style.paddingBottom=U.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Nt=(xl=U.tooltipText)!=null?xl:"Clear chat",Tn=(vl=U.showTooltip)!=null?vl:!0;if(Ve.setAttribute("aria-label",Nt),mt&&(mt._cleanupTooltip&&(mt._cleanupTooltip(),delete mt._cleanupTooltip),Tn&&Nt)){let Ke=null,Yt=()=>{if(Ke||!Ve)return;let Rr=Ve.ownerDocument,To=Rr.body;if(!To)return;Ke=Yn(Rr,"div","persona-clear-chat-tooltip"),Ke.textContent=Nt;let Mo=Yn(Rr,"div");Mo.className="persona-clear-chat-tooltip-arrow",Ke.appendChild(Mo);let Hr=Ve.getBoundingClientRect();Ke.style.position="fixed",Ke.style.zIndex=String(Sr),Ke.style.left=`${Hr.left+Hr.width/2}px`,Ke.style.top=`${Hr.top-8}px`,Ke.style.transform="translate(-50%, -100%)",To.appendChild(Ke)},hn=()=>{Ke&&Ke.parentNode&&(Ke.parentNode.removeChild(Ke),Ke=null)};mt.addEventListener("mouseenter",Yt),mt.addEventListener("mouseleave",hn),Ve.addEventListener("focus",Yt),Ve.addEventListener("blur",hn),mt._cleanupTooltip=()=>{hn(),mt&&(mt.removeEventListener("mouseenter",Yt),mt.removeEventListener("mouseleave",hn)),Ve&&(Ve.removeEventListener("focus",Yt),Ve.removeEventListener("blur",hn))}}}}let Rn=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Vo],br=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[zr.message,zr.messageAndClick];M=qo({parsers:Rn,handlers:br,getSessionMetadata:u,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),$=cd(n,M,ce),D.updateConfig(n),Lr(ee,D.getMessages(),$),Nn.render(n.suggestionChips,D,J,void 0,n.suggestionChipsConfig),xo(),Xr(D.isStreaming());let nr=((Cl=n.voiceRecognition)==null?void 0:Cl.enabled)===!0,xr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),rr=((Sl=(wl=n.voiceRecognition)==null?void 0:wl.provider)==null?void 0:Sl.type)==="runtype";if(nr&&(xr||rr))if(!O||!Le){let U=X(n.voiceRecognition,n.sendButton);U&&(O=U.micButton,Le=U.micButtonWrapper,Zt.insertBefore(Le,vt),O.addEventListener("click",We),O.disabled=D.isStreaming())}else{let U=(Al=n.voiceRecognition)!=null?Al:{},rt=(El=n.sendButton)!=null?El:{},kt=(Tl=U.iconName)!=null?Tl:"mic",Ue=(Ml=rt.size)!=null?Ml:"40px",st=(kl=U.iconSize)!=null?kl:Ue,zt=parseFloat(st)||24;O.style.width=st,O.style.height=st,O.style.minWidth=st,O.style.minHeight=st;let on=(Il=(Ll=U.iconColor)!=null?Ll:rt.textColor)!=null?Il:"currentColor";O.innerHTML="";let jn=me(kt,zt,on,2);jn?O.appendChild(jn):O.textContent="\u{1F3A4}";let un=(Pl=U.backgroundColor)!=null?Pl:rt.backgroundColor;un?O.style.backgroundColor=un:O.style.backgroundColor="",on?O.style.color=on:O.style.color="var(--persona-text, #111827)",U.borderWidth?(O.style.borderWidth=U.borderWidth,O.style.borderStyle="solid"):(O.style.borderWidth="",O.style.borderStyle=""),U.borderColor?O.style.borderColor=U.borderColor:O.style.borderColor="",U.paddingX?(O.style.paddingLeft=U.paddingX,O.style.paddingRight=U.paddingX):(O.style.paddingLeft="",O.style.paddingRight=""),U.paddingY?(O.style.paddingTop=U.paddingY,O.style.paddingBottom=U.paddingY):(O.style.paddingTop="",O.style.paddingBottom="");let Nt=Le==null?void 0:Le.querySelector(".persona-send-button-tooltip"),Tn=(Wl=U.tooltipText)!=null?Wl:"Start voice recognition";if(((Rl=U.showTooltip)!=null?Rl:!1)&&Tn)if(Nt)Nt.textContent=Tn,Nt.style.display="";else{let Yt=document.createElement("div");Yt.className="persona-send-button-tooltip",Yt.textContent=Tn,Le==null||Le.insertBefore(Yt,O)}else Nt&&(Nt.style.display="none");Le.style.display="",O.disabled=D.isStreaming()}else O&&Le&&(Le.style.display="none",((Bl=(Hl=n.voiceRecognition)==null?void 0:Hl.provider)==null?void 0:Bl.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():En&&_n());if(((Dl=n.attachments)==null?void 0:Dl.enabled)===!0)if(!at||!ue){let U=(Fl=n.attachments)!=null?Fl:{},kt=(Ol=((Nl=n.sendButton)!=null?Nl:{}).size)!=null?Ol:"40px";Z||(Z=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Z.style.display="none",tt.insertBefore(Z,J)),Be||(Be=document.createElement("input"),Be.type="file",Be.accept=(($l=U.allowedTypes)!=null?$l:ar).join(","),Be.multiple=((_l=U.maxFiles)!=null?_l:4)>1,Be.style.display="none",Be.setAttribute("aria-label","Attach files"),tt.insertBefore(Be,J)),at=h("div","persona-send-button-wrapper"),ue=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ue.type="button",ue.setAttribute("aria-label",(jl=U.buttonTooltipText)!=null?jl:"Attach file");let Ue=(zl=U.buttonIconName)!=null?zl:"paperclip",st=kt,zt=parseFloat(st)||40,on=Math.round(zt*.6);ue.style.width=st,ue.style.height=st,ue.style.minWidth=st,ue.style.minHeight=st,ue.style.fontSize="18px",ue.style.lineHeight="1",ue.style.backgroundColor="transparent",ue.style.color="var(--persona-primary, #111827)",ue.style.border="none",ue.style.borderRadius="6px",ue.style.transition="background-color 0.15s ease",ue.addEventListener("mouseenter",()=>{ue.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ue.addEventListener("mouseleave",()=>{ue.style.backgroundColor="transparent"});let jn=me(Ue,on,"currentColor",1.5);jn?ue.appendChild(jn):ue.textContent="\u{1F4CE}",ue.addEventListener("click",Tn=>{Tn.preventDefault(),Be==null||Be.click()}),at.appendChild(ue);let un=(Ul=U.buttonTooltipText)!=null?Ul:"Attach file",Nt=h("div","persona-send-button-tooltip");Nt.textContent=un,at.appendChild(Nt),Gt.append(at),!_e&&Be&&Z&&(_e=$r.fromConfig(U),_e.setPreviewsContainer(Z),Be.addEventListener("change",async()=>{_e&&(Be!=null&&Be.files)&&(await _e.handleFileSelect(Be.files),Be.value="")}))}else{at.style.display="";let U=(Vl=n.attachments)!=null?Vl:{};Be&&(Be.accept=((ql=U.allowedTypes)!=null?ql:ar).join(","),Be.multiple=((Jl=U.maxFiles)!=null?Jl:4)>1),_e&&_e.updateConfig({allowedTypes:U.allowedTypes,maxFileSize:U.maxFileSize,maxFiles:U.maxFiles})}else at&&(at.style.display="none"),_e&&_e.clearAttachments();let jt=(Yl=n.sendButton)!=null?Yl:{},Qo=(Gl=jt.useIcon)!=null?Gl:!1,Ao=(Xl=jt.iconText)!=null?Xl:"\u2191",Eo=jt.iconName,eo=(Kl=jt.tooltipText)!=null?Kl:"Send message",es=(Zl=jt.showTooltip)!=null?Zl:!1,vr=(Ql=jt.size)!=null?Ql:"40px",Wr=jt.backgroundColor,Jt=jt.textColor;if(Qo){if(K.style.width=vr,K.style.height=vr,K.style.minWidth=vr,K.style.minHeight=vr,K.style.fontSize="18px",K.style.lineHeight="1",K.innerHTML="",Jt?K.style.color=Jt:K.style.color="var(--persona-button-primary-fg, #ffffff)",Eo){let U=parseFloat(vr)||24,rt=(Jt==null?void 0:Jt.trim())||"currentColor",kt=me(Eo,U,rt,2);kt?K.appendChild(kt):K.textContent=Ao}else K.textContent=Ao;K.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wr?(K.style.backgroundColor=Wr,K.classList.remove("persona-bg-persona-primary")):(K.style.backgroundColor="",K.classList.add("persona-bg-persona-primary"))}else K.textContent=(tc=(ec=n.copy)==null?void 0:ec.sendButtonLabel)!=null?tc:"Send",K.style.width="",K.style.height="",K.style.minWidth="",K.style.minHeight="",K.style.fontSize="",K.style.lineHeight="",K.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wr?(K.style.backgroundColor=Wr,K.classList.remove("persona-bg-persona-accent")):K.classList.add("persona-bg-persona-accent"),Jt?K.style.color=Jt:K.classList.add("persona-text-white");jt.borderWidth?(K.style.borderWidth=jt.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),jt.borderColor?K.style.borderColor=jt.borderColor:K.style.borderColor="",jt.paddingX?(K.style.paddingLeft=jt.paddingX,K.style.paddingRight=jt.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),jt.paddingY?(K.style.paddingTop=jt.paddingY,K.style.paddingBottom=jt.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let fn=vt==null?void 0:vt.querySelector(".persona-send-button-tooltip");if(es&&eo)if(fn)fn.textContent=eo,fn.style.display="";else{let U=document.createElement("div");U.className="persona-send-button-tooltip",U.textContent=eo,vt==null||vt.insertBefore(U,K)}else fn&&(fn.style.display="none");let or=(nc=n.layout)==null?void 0:nc.contentMaxWidth;or?(ee.style.maxWidth=or,ee.style.marginLeft="auto",ee.style.marginRight="auto",ee.style.width="100%",tt&&(tt.style.maxWidth=or,tt.style.marginLeft="auto",tt.style.marginRight="auto"),Fe&&(Fe.style.maxWidth=or,Fe.style.marginLeft="auto",Fe.style.marginRight="auto")):(ee.style.maxWidth="",ee.style.marginLeft="",ee.style.marginRight="",ee.style.width="",tt&&(tt.style.maxWidth="",tt.style.marginLeft="",tt.style.marginRight=""),Fe&&(Fe.style.maxWidth="",Fe.style.marginLeft="",Fe.style.marginRight=""));let Cr=(rc=n.statusIndicator)!=null?rc:{},Yd=(oc=Cr.visible)!=null?oc:!0;if(Lt.style.display=Yd?"":"none",D){let U=D.getStatus();St(Lt,(kt=>{var Ue,st,zt,on;return kt==="idle"?(Ue=Cr.idleText)!=null?Ue:sn.idle:kt==="connecting"?(st=Cr.connectingText)!=null?st:sn.connecting:kt==="connected"?(zt=Cr.connectedText)!=null?zt:sn.connected:kt==="error"?(on=Cr.errorText)!=null?on:sn.error:sn[kt]})(U),Cr,U)}Lt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Gd=Cr.align==="left"?"persona-text-left":Cr.align==="center"?"persona-text-center":"persona-text-right";Lt.classList.add(Gd)},open(){b&&Tt(!0,"api")},close(){b&&Tt(!1,"api")},toggle(){b&&Tt(!T,"api")},clearChat(){an=!1,D.clearMessages(),In.clear(),hr();try{localStorage.removeItem(mo),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${mo}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==mo)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let g=a.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}i={},M.syncFromMetadata(),oe==null||oe.clear(),be==null||be.update()},setMessage(l){return!J||D.isStreaming()?!1:(!T&&b&&Tt(!0,"system"),J.value=l,J.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let g=(l==null?void 0:l.trim())||J.value.trim();return g?(!T&&b&&Tt(!0,"system"),J.value="",J.style.height="auto",D.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return D.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(D.isVoiceActive()||(!T&&b&&Tt(!0,"system"),Je.manuallyDeactivated=!1,mn(),D.toggleVoice().then(()=>{Je.active=D.isVoiceActive(),Pn("user"),D.isVoiceActive()&&Pt()})),!0):En?!0:So()?(!T&&b&&Tt(!0,"system"),Je.manuallyDeactivated=!1,mn(),Pr("user"),!0):!1},stopVoiceRecognition(){var l,g;return((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{Je.active=!1,Je.manuallyDeactivated=!0,mn(),Pn("user"),x()}),!0):!1:En?(Je.manuallyDeactivated=!0,mn(),_n("user"),!0):!1},injectMessage(l){return!T&&b&&Tt(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!T&&b&&Tt(!0,"system");let g=D.injectAssistantMessage(l);return Y&&(Y=!1,ge&&(clearTimeout(ge),ge=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),g},injectUserMessage(l){return!T&&b&&Tt(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!T&&b&&Tt(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!T&&b&&Tt(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!T&&b&&Tt(!0,"system"),D.injectTestEvent(l)},async connectStream(l,g){return D.connectStream(l,g)},__pushEventStreamEvent(l){oe&&oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!re||!oe||Xn()},hideEventStream(){$e&&Dn()},isEventStreamVisible(){return $e},showArtifacts(){Bn(n)&&(an=!1,Cn(),et==null||et.setMobileOpen(!0))},hideArtifacts(){Bn(n)&&(an=!0,Cn())},upsertArtifact(l){return Bn(n)?(an=!1,D.upsertArtifact(l)):null},selectArtifact(l){Bn(n)&&D.selectArtifact(l)},clearArtifacts(){Bn(n)&&D.clearArtifacts()},focusInput(){return b&&!T||!J?!1:(J.focus(),!0)},async resolveApproval(l,g){let E=D.getMessages().find(k=>{var P;return k.variant==="approval"&&((P=k.approval)==null?void 0:P.id)===l});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${l}`);return D.resolveApproval(E.approval,g)},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,g){return o.on(l,g)},off(l,g){o.off(l,g)},isOpen(){return b&&T},isVoiceActive(){return Je.active},getState(){return{open:b&&T,launcherEnabled:b,voiceActive:Je.active,streaming:D.isStreaming()}},showCSATFeedback(l){!T&&b&&Tt(!0,"system");let g=ee.querySelector(".persona-feedback-container");g&&g.remove();let y=Rs({onSubmit:async(E,k)=>{var P;D.isClientTokenMode()&&await D.submitCSATFeedback(E,k),(P=l==null?void 0:l.onSubmit)==null||P.call(l,E,k)},onDismiss:l==null?void 0:l.onDismiss,...l});ee.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!T&&b&&Tt(!0,"system");let g=ee.querySelector(".persona-feedback-container");g&&g.remove();let y=Hs({onSubmit:async(E,k)=>{var P;D.isClientTokenMode()&&await D.submitNPSFeedback(E,k),(P=l==null?void 0:l.onSubmit)==null||P.call(l,E,k)},onDismiss:l==null?void 0:l.onDismiss,...l});ee.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return D.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return D.submitNPSFeedback(l,g)},destroy(){ht.forEach(l=>l()),j.remove(),N==null||N.destroy(),Q==null||Q.remove(),Sn&&le.removeEventListener("click",Sn)}};if((((ci=t==null?void 0:t.debugTools)!=null?ci:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:Ae,getMessages:Ae.getMessages,getStatus:Ae.getStatus,getMetadata:Ae.getPersistentMetadata,updateMetadata:Ae.updatePersistentMetadata,clearHistory:()=>Ae.clearChat(),setVoiceActive:y=>y?Ae.startVoiceRecognition():Ae.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ht.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=V=>{let F=V.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Ae.focusInput()};if(window.addEventListener("persona:focusInput",g),ht.push(()=>{window.removeEventListener("persona:focusInput",g)}),re){let V=ie=>{let ve=ie.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===l)&&Ae.showEventStream()},F=ie=>{let ve=ie.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===l)&&Ae.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",F),ht.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",F)})}let y=V=>{let F=V.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Ae.showArtifacts()},E=V=>{let F=V.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Ae.hideArtifacts()},k=V=>{let F=V.detail;F!=null&&F.instanceId&&F.instanceId!==l||F!=null&&F.artifact&&Ae.upsertArtifact(F.artifact)},P=V=>{let F=V.detail;F!=null&&F.instanceId&&F.instanceId!==l||typeof(F==null?void 0:F.id)=="string"&&Ae.selectArtifact(F.id)},W=V=>{let F=V.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Ae.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",P),window.addEventListener("persona:clearArtifacts",W),ht.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",P),window.removeEventListener("persona:clearArtifacts",W)})}let yt=au(n.persistState);if(yt&&b){let l=iu(yt.storage),g=`${yt.keyPrefix}widget-open`,y=`${yt.keyPrefix}widget-voice`,E=`${yt.keyPrefix}widget-voice-mode`;if(l){let k=((di=yt.persist)==null?void 0:di.openState)&&l.getItem(g)==="true",P=((pi=yt.persist)==null?void 0:pi.voiceState)&&l.getItem(y)==="true",W=((ui=yt.persist)==null?void 0:ui.voiceState)&&l.getItem(E)==="true";if(k&&setTimeout(()=>{Ae.open(),setTimeout(()=>{var V;if(P||W)Ae.startVoiceRecognition();else if((V=yt.persist)!=null&&V.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(gi=yt.persist)!=null&&gi.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(mi=yt.persist)!=null&&mi.voiceState&&(o.on("voice:state",V=>{l.setItem(y,V.active?"true":"false")}),o.on("user:message",V=>{l.setItem(E,V.viaVoice?"true":"false")})),yt.clearOnChatClear){let V=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(E)},F=()=>V();window.addEventListener("persona:clear-chat",F),ht.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return c&&b&&setTimeout(()=>{Ae.open()},0),Ae};var lu=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},dd=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},ba=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},pd=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",ba(e)},fa=e=>{e.style.transition=""},ha=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},ya=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ds=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},cu=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},du=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},ud=(e,r,t,n,s,o,a)=>{var v,M,b,C,S,R;let i=Hn(o),d=i.reveal==="push";cu(e,r,t,n,d),du(e,r,t,n,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(M=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?M:!0,u=(C=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?C:640,f=c!=null?c.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ha(r),fa(n),pd(n),ya(t),Ds(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((R=(S=o==null?void 0:o.launcher)==null?void 0:S.zIndex)!=null?R:yn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),pd(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ha(r),fa(n),ya(t),Ds(s,n);let w=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",B=a?"translateX(0)":L;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=B,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",fa(n),ba(n),Ds(s,n);let w=lu(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),B=i.animate?"transform 180ms ease":"none",T=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${L+w}px`,r.style.transition=B,r.style.transform=T,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",ha(r),ba(n),ya(t),Ds(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",B=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",T=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${L}`,n.style.width=L,n.style.maxWidth=L,n.style.minWidth=L,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||T?"hidden":"visible",n.style.transition=B,w&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},pu=(e,r)=>{let t=e.ownerDocument.createElement("div");return dd(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){dd(t,n)},destroy(){t.remove()}}},uu=(e,r)=>{var S,R,w,L;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),u=(R=(S=r==null?void 0:r.launcher)==null?void 0:S.enabled)==null||R?(L=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),Hn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{ud(a,i,d,c,p,r,u)}),f.observe(a))},M=()=>{ud(a,i,d,c,p,r,u),v()},b=a.ownerDocument.defaultView,C=()=>{M()};return b==null||b.addEventListener("resize",C),Hn(r).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(B){let T=B.launcherEnabled?B.open:!0;u!==T&&(u=T,M())},updateConfig(B){var T,Y;r=B,((Y=(T=r==null?void 0:r.launcher)==null?void 0:T.enabled)!=null?Y:!0)===!1&&(u=!0),M()},destroy(){b==null||b.removeEventListener("resize",C),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Jo=(e,r)=>Ut(r)?uu(e,r):pu(e,r);var xa={},gu=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},mu=()=>{try{if(typeof xa!="undefined"&&xa.url)return new URL("../widget.css",xa.url).href}catch{}return null},gd=(e,r)=>{let t=mu(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},va=e=>{var b;let r=gu(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Jo(r,s),a,i=[],d=(C,S)=>{var B,T;let w=!((T=(B=S==null?void 0:S.launcher)==null?void 0:B.enabled)!=null?T:!0)||Ut(S),L=n.createElement("div");if(L.setAttribute("data-persona-root","true"),w&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let Y=C.attachShadow({mode:"open"});Y.appendChild(L),gd(Y,n)}else C.appendChild(L),gd(C,n);return r.id&&L.setAttribute("data-persona-instance",r.id),L},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(C=>C()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let C=d(o.host,s);a=Bs(C,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(C=>C()),i=[],a.destroy()};u(),(b=e.onReady)==null||b.call(e);let m=C=>{f(),o.destroy(),o=Jo(r,C),s=C,u()},v={update(C){var L,B,T,Y,ge,ce;let S={...s,...C,launcher:{...(L=s==null?void 0:s.launcher)!=null?L:{},...(B=C==null?void 0:C.launcher)!=null?B:{},dock:{...(Y=(T=s==null?void 0:s.launcher)==null?void 0:T.dock)!=null?Y:{},...(ce=(ge=C==null?void 0:C.launcher)==null?void 0:ge.dock)!=null?ce:{}}}},R=Ut(s),w=Ut(S);if(R!==w){m(S);return}s=S,o.updateConfig(s),a.update(C),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},M=new Proxy(v,{get(C,S,R){if(S==="host")return o.host;if(S in C)return Reflect.get(C,S,R);let w=a[S];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=M),M};var bd=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),fu=new Set(["button","a","input","select","textarea","details","summary"]),hu=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ca=/\b(product|card|item|listing|result)\b/i,Sa=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,yu=3e3,bu=100;function xd(e){let r=typeof e.className=="string"?e.className:"";if(Ca.test(r)||e.id&&Ca.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&Ca.test(n.value))return!0}return!1}function vd(e){var r;return Sa.test(((r=e.textContent)!=null?r:"").trim())}function Cd(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function xu(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function md(e){let r=e.match(Sa);return r?r[0]:null}function fd(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function vu(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var Cu="commerce-card",wu="result-card";function hd(e){return!xd(e)||!vd(e)||!Cd(e)&&!xu(e)?0:5200}function yd(e){var n;return!xd(e)||vd(e)||!Cd(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Aa=[{id:Cu,scoreElement(e){return hd(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||Sa.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,c,p;if(hd(e)===0)return null;let{title:t,href:n}=fd(e),s=(p=(c=md(((d=e.textContent)!=null?d:"").trim()))!=null?c:md(r.text))!=null?p:"",o=vu(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
97
|
-
`)}},{id:
|
|
98
|
-
`)}}];function
|
|
99
|
+
`}if(!A&&!l){let bn="max-height: -moz-available !important; max-height: stretch !important;",Nn=m?"":"padding-top: 1.25em !important;",oo=m?"":`z-index: ${(Io=(ps=n.launcher)==null?void 0:ps.zIndex)!=null?Io:vn} !important;`;q.style.cssText+=bn+Nn+oo}};Zn(),Ar(e,n),Ns(e,n),Fs(e,n);let vt=[],$t=null,_t=null;vt.push(()=>{$t==null||$t(),$t=null,_t==null||_t(),_t=null}),wn&&vt.push(()=>{wn==null||wn.disconnect(),wn=null}),vt.push(()=>{pn==null||pn(),pn=null,rr(),wt&&(wt.remove(),wt=null),at==null||at.element.style.removeProperty("width"),at==null||at.element.style.removeProperty("maxWidth")}),re&&vt.push(()=>{de!==null&&(cancelAnimationFrame(de),de=null),xe==null||xe.destroy(),xe=null,ae==null||ae.destroy(),ae=null,ke=null});let En=null,br=()=>{En&&(En(),En=null),n.colorScheme==="auto"&&(En=Is(()=>{Ar(e,n)}))};br(),vt.push(()=>{En&&(En(),En=null)});let jn=Sd(Oe),Tn=null,D,zn=!1,Hn=md(),xr=0,gn=Ps(),Mn=0,ee=null,qn=!1,or=!1,ts=1,vo=8,Zr=new Map,Ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Co=(Si=(wi=n.voiceRecognition)==null?void 0:wi.autoResume)!=null?Si:!1,Bn=l=>{o.emit("voice:state",{active:Ze.active,source:l,timestamp:Date.now()})},fn=()=>{g(l=>({...l,voiceState:{active:Ze.active,timestamp:Date.now(),manuallyDeactivated:Ze.manuallyDeactivated}}))},ns=()=>{var A,L;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=ka(i.voiceState),m=!!l.active,b=Number((L=l.timestamp)!=null?L:0);Ze.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-b<$u&&setTimeout(()=>{var R,B;Ze.active||(Ze.manuallyDeactivated=!1,((B=(R=n.voiceRecognition)==null?void 0:R.provider)==null?void 0:B.type)==="runtype"?D.toggleVoice().then(()=>{Ze.active=D.isVoiceActive(),Bn("restore"),D.isVoiceActive()&&wr()}):Rr("restore"))},1e3)},rs=()=>D?Fd(D.getMessages()).filter(l=>!l.__skipPersist):[];function wo(l){if(!(a!=null&&a.save))return;let b={messages:l?Fd(l):D?rs():[],metadata:i};try{let A=a.save(b);A instanceof Promise&&A.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let sr=null,os=()=>q.querySelector("#persona-scroll-container")||V,Qr=()=>{sr!==null&&(cancelAnimationFrame(sr),sr=null),qn=!1},So=()=>{ee!==null&&(cancelAnimationFrame(ee),ee=null),or=!1,Qr()},ar=()=>{if(!zt()||je){ct.parentNode&&ct.remove(),ct.style.display="none";return}ct.parentNode!==_&&_.appendChild(ct),Ke();let l=zo(V)>0;ct.style.display=gn.isFollowing()||!l?"none":""},Ao=()=>{gn.pause()&&(So(),ar())},vr=()=>{gn.resume(),ar()},Cr=(l=!1)=>{gn.isFollowing()&&(!l&&!zn||(ee!==null&&(cancelAnimationFrame(ee),ee=null),or=!0,ee=requestAnimationFrame(()=>{ee=null,or=!1,gn.isFollowing()&&ss(os(),l?220:140)})))},ss=(l,m=500)=>{let b=l.scrollTop,A=zo(l),L=A-b;if(Math.abs(L)<1){Mn=l.scrollTop;return}Qr();let R=performance.now();qn=!0;let B=O=>1-Math.pow(1-O,3),z=O=>{if(!gn.isFollowing()){Qr();return}let ge=zo(l);ge!==A&&(A=ge,L=A-b);let ve=O-R,Se=Math.min(ve/m,1),be=B(Se),Te=b+L*be;l.scrollTop=Te,Mn=l.scrollTop,Se<1?sr=requestAnimationFrame(z):(l.scrollTop=A,Mn=l.scrollTop,sr=null,qn=!1)};sr=requestAnimationFrame(z)},as=l=>{let m=new Map;l.forEach(b=>{let A=Zr.get(b.id);m.set(b.id,{streaming:b.streaming,role:b.role}),!A&&b.role==="assistant"&&o.emit("assistant:message",b),b.role==="assistant"&&(A!=null&&A.streaming)&&b.streaming===!1&&o.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(A?b.approval.status!=="pending"&&o.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):o.emit("approval:requested",{approval:b.approval,message:b}))}),Zr.clear(),m.forEach((b,A)=>{Zr.set(A,b)})},Pr=(l,m,b)=>{var Se,be,Te,ze,pt,Xe;let A=document.createElement("div"),R=(()=>{var Me;let $=s.find(Pe=>Pe.renderLoadingIndicator);if($!=null&&$.renderLoadingIndicator)return $.renderLoadingIndicator;if((Me=n.loadingIndicator)!=null&&Me.render)return n.loadingIndicator.render})(),B=($,Me)=>Me==null?!1:typeof Me=="string"?($.textContent=Me,!0):($.appendChild(Me),!0),z=new Set;if(m.forEach($=>{var Yt,sn;z.add($.id);let Me=ud($,xr),Pe=gd(Hn,$.id,Me);if(Pe){A.appendChild(Pe.cloneNode(!0));return}let fe=null,Re=s.find(we=>!!($.variant==="reasoning"&&we.renderReasoning||$.variant==="tool"&&we.renderToolCall||$.variant==="approval"&&we.renderApproval||!$.variant&&we.renderMessage)),Ct=(Yt=n.layout)==null?void 0:Yt.messages;if(Re)if($.variant==="reasoning"&&$.reasoning&&Re.renderReasoning){if(!Q)return;fe=Re.renderReasoning({message:$,defaultRenderer:()=>va($,n),config:n})}else if($.variant==="tool"&&$.toolCall&&Re.renderToolCall){if(!Ce)return;fe=Re.renderToolCall({message:$,defaultRenderer:()=>Ca($,n),config:n})}else if($.variant==="approval"&&$.approval&&Re.renderApproval){if(n.approval===!1)return;fe=Re.renderApproval({message:$,defaultRenderer:()=>wa($,n),config:n})}else Re.renderMessage&&(fe=Re.renderMessage({message:$,defaultRenderer:()=>{let we=go($,b,Ct,n.messageActions,Ee,{loadingIndicatorRenderer:R,widgetConfig:n});return $.role!=="user"&&Ea(we,$,n,D),we},config:n}));if(!fe&&$.role==="assistant"&&!$.variant&&n.enableComponentStreaming!==!1&&js($)){let hn=zs($);if(hn){let an=_s(hn,{config:n,message:$,transform:b});if(an)if(n.wrapComponentDirectiveInBubble!==!1){let rt=document.createElement("div");if(rt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),rt.id=`bubble-${$.id}`,rt.setAttribute("data-message-id",$.id),$.content&&$.content.trim()){let ut=document.createElement("div");ut.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ut.innerHTML=b({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),rt.appendChild(ut)}rt.appendChild(an),fe=rt}else{let rt=document.createElement("div");if(rt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",rt.id=`bubble-${$.id}`,rt.setAttribute("data-message-id",$.id),rt.setAttribute("data-persona-component-directive","true"),$.content&&$.content.trim()){let ut=document.createElement("div");ut.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ut.innerHTML=b({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),rt.appendChild(ut)}rt.appendChild(an),fe=rt}}}if(!fe)if($.variant==="reasoning"&&$.reasoning){if(!Q)return;fe=va($,n)}else if($.variant==="tool"&&$.toolCall){if(!Ce)return;fe=Ca($,n)}else if($.variant==="approval"&&$.approval){if(n.approval===!1)return;fe=wa($,n)}else{let we=(sn=n.layout)==null?void 0:sn.messages;we!=null&&we.renderUserMessage&&$.role==="user"?fe=we.renderUserMessage({message:$,config:n,streaming:!!$.streaming}):we!=null&&we.renderAssistantMessage&&$.role==="assistant"?fe=we.renderAssistantMessage({message:$,config:n,streaming:!!$.streaming}):fe=go($,b,we,n.messageActions,Ee,{loadingIndicatorRenderer:R,widgetConfig:n}),$.role!=="user"&&fe&&Ea(fe,$,n,D)}let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${$.id}`,bt.setAttribute("data-wrapper-id",$.id),$.role==="user"&&bt.classList.add("persona-justify-end"),(fe==null?void 0:fe.getAttribute("data-persona-component-directive"))==="true"&&bt.classList.add("persona-w-full"),bt.appendChild(fe),fd(Hn,$.id,Me,bt),A.appendChild(bt)}),(be=(Se=n.features)==null?void 0:Se.toolCallDisplay)!=null&&be.grouped){let $=[],Me=[];m.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ce){Me.push(Pe);return}Me.length>1&&$.push(Me),Me=[]}),Me.length>1&&$.push(Me),$.forEach((Pe,fe)=>{var an,Un;let Re=Pe.map(rt=>Array.from(A.children).find(ut=>ut instanceof HTMLElement&&ut.getAttribute("data-wrapper-id")===rt.id)).filter(rt=>!!rt);if(Re.length<2)return;let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id=`wrapper-tool-group-${fe}-${Pe[0].id}`,Ct.setAttribute("data-wrapper-id",`tool-group-${fe}-${Pe[0].id}`);let bt=document.createElement("div");bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",bt.setAttribute("data-persona-tool-group","true");let Yt=document.createElement("div");Yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let sn=`Called ${Pe.length} tools`,we=(Un=(an=n.toolCall)==null?void 0:an.renderGroupedSummary)==null?void 0:Un.call(an,{messages:Pe,toolCalls:Pe.map(rt=>rt.toolCall).filter(rt=>!!rt),defaultSummary:sn,config:n});B(Yt,we)||(Yt.textContent=sn);let hn=document.createElement("div");hn.className="persona-tool-group-stack persona-flex persona-flex-col",bt.append(Yt,hn),Ct.appendChild(bt),Re[0].before(Ct),Re.forEach((rt,ut)=>{let yn=document.createElement("div");yn.className="persona-tool-group-item persona-relative",yn.setAttribute("data-persona-tool-group-item","true"),ut<Re.length-1&&yn.setAttribute("data-persona-tool-group-connector","true"),yn.appendChild(rt),hn.appendChild(yn)})})}hd(Hn,z);let O=m.some($=>$.role==="assistant"&&$.streaming),ge=m[m.length-1],ve=(ge==null?void 0:ge.role)==="assistant"&&!ge.streaming&&ge.variant!=="approval";if(zn&&m.some($=>$.role==="user")&&!O&&!ve){let $={config:n,streaming:!0,location:"standalone",defaultRenderer:Yr},Me=s.find(fe=>fe.renderLoadingIndicator),Pe=null;if(Me!=null&&Me.renderLoadingIndicator&&(Pe=Me.renderLoadingIndicator($)),Pe===null&&((Te=n.loadingIndicator)!=null&&Te.render)&&(Pe=n.loadingIndicator.render($)),Pe===null&&(Pe=Yr()),Pe){let fe=document.createElement("div"),Re=((ze=n.loadingIndicator)==null?void 0:ze.showBubble)!==!1;fe.className=Re?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Pe);let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id="wrapper-typing-indicator",Ct.setAttribute("data-wrapper-id","typing-indicator"),Ct.appendChild(fe),A.appendChild(Ct)}}if(!zn&&m.length>0){let $=m[m.length-1],Me={config:n,lastMessage:$,messageCount:m.length},Pe=s.find(Re=>Re.renderIdleIndicator),fe=null;if(Pe!=null&&Pe.renderIdleIndicator&&(fe=Pe.renderIdleIndicator(Me)),fe===null&&((pt=n.loadingIndicator)!=null&&pt.renderIdle)&&(fe=n.loadingIndicator.renderIdle(Me)),fe){let Re=document.createElement("div"),Ct=((Xe=n.loadingIndicator)==null?void 0:Xe.showBubble)!==!1;Re.className=Ct?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Re.setAttribute("data-idle-indicator","true"),Re.appendChild(fe);let bt=document.createElement("div");bt.className="persona-flex",bt.id="wrapper-idle-indicator",bt.setAttribute("data-wrapper-id","idle-indicator"),bt.appendChild(Re),A.appendChild(bt)}}pd(l,A)},Wr=()=>{var O,ge,ve,Se,be;if(!x)return;let l=Xt(n),m=(O=e.ownerDocument.defaultView)!=null?O:window,b=(ve=(ge=n.launcher)==null?void 0:ge.mobileBreakpoint)!=null?ve:640,A=(be=(Se=n.launcher)==null?void 0:Se.mobileFullscreen)!=null?be:!0,L=m.innerWidth<=b,R=A&&L&&x,B=Fn(n).reveal;T?(q.style.removeProperty("display"),q.style.display=l?"flex":"",q.classList.remove("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-95","persona-opacity-0"),F.classList.add("persona-scale-100","persona-opacity-100"),y?y.element.style.display="none":se&&(se.style.display="none")):(l?l&&(B==="overlay"||B==="push")&&!R?(q.style.removeProperty("display"),q.style.display="flex",q.classList.remove("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(q.style.setProperty("display","none","important"),q.classList.remove("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(q.style.display="",q.classList.add("persona-pointer-events-none","persona-opacity-0"),F.classList.remove("persona-scale-100","persona-opacity-100"),F.classList.add("persona-scale-95","persona-opacity-0")),y?y.element.style.display=l?"none":"":se&&(se.style.display=l?"none":""))},Ht=(l,m="user")=>{var R,B;if(!x||T===l)return;let b=T;T=l,Wr();let A=(()=>{var Te,ze,pt,Xe,$,Me,Pe;let z=(ze=(Te=n.launcher)==null?void 0:Te.sidebarMode)!=null?ze:!1,O=(pt=e.ownerDocument.defaultView)!=null?pt:window,ge=($=(Xe=n.launcher)==null?void 0:Xe.mobileFullscreen)!=null?$:!0,ve=(Pe=(Me=n.launcher)==null?void 0:Me.mobileBreakpoint)!=null?Pe:640,Se=O.innerWidth<=ve,be=Xt(n)&&ge&&Se;return z||ge&&Se&&x||be})();if(T&&A){if(!$t){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&($t=ma(O,(B=(R=n.launcher)==null?void 0:R.zIndex)!=null?B:vn))}_t||(_t=ga(e.ownerDocument))}else T||($t==null||$t(),$t=null,_t==null||_t(),_t=null);T&&(P(),Cr(!0));let L={open:T,source:m,timestamp:Date.now()};T&&!b?o.emit("widget:opened",L):!T&&b&&o.emit("widget:closed",L),o.emit("widget:state",{open:T,launcherEnabled:x,voiceActive:Ze.active,streaming:D.isStreaming()})},eo=l=>{te.disabled=l,j&&(j.disabled=l),jn.buttons.forEach(m=>{m.disabled=l}),st.dataset.personaComposerStreaming=l?"true":"false",st.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},to=()=>{Ze.active||Z&&Z.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>to(),200)});let Eo=()=>{var b,A,L,R,B,z,O,ge,ve,Se,be;Kt.textContent=(A=(b=n.copy)==null?void 0:b.welcomeTitle)!=null?A:"Hello \u{1F44B}",$e.textContent=(R=(L=n.copy)==null?void 0:L.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",Z.placeholder=(z=(B=n.copy)==null?void 0:B.inputPlaceholder)!=null?z:"How can I help...";let l=V.querySelector("[data-persona-intro-card]");if(l){let Te=((O=n.copy)==null?void 0:O.showWelcomeCard)!==!1;l.style.display=Te?"":"none",Te?(V.classList.remove("persona-gap-3"),V.classList.add("persona-gap-6")):(V.classList.remove("persona-gap-6"),V.classList.add("persona-gap-3"))}(ve=(ge=n.sendButton)==null?void 0:ge.useIcon)!=null&&ve||(te.textContent=(be=(Se=n.copy)==null?void 0:Se.sendButtonLabel)!=null?be:"Send"),Z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Z.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};if(n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{g(m=>({...m,sessionId:l}))}}),D=new co(n,{onMessagesChanged(l){Pr(oe,l,I),D&&(l.some(L=>L.role==="user")?jn.render([],D,Z,l):jn.render(n.suggestionChips,D,Z,l,n.suggestionChipsConfig)),Cr(!zn),as(l);let m=[...l].reverse().find(A=>A.role==="user"),b=Ze.lastUserMessageId;m&&m.id!==b&&(Ze.lastUserMessageId=m.id,o.emit("user:message",m)),Ze.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),wo(l)},onStatusChanged(l){var A;let m=(A=n.statusIndicator)!=null?A:{};Et(Nt,(L=>{var R,B,z,O;return L==="idle"?(R=m.idleText)!=null?R:cn.idle:L==="connecting"?(B=m.connectingText)!=null?B:cn.connecting:L==="connected"?(z=m.connectedText)!=null?z:cn.connected:L==="error"?(O=m.errorText)!=null?O:cn.error:cn[L]})(l),m,l)},onStreamingChanged(l){zn=l,eo(l),D&&Pr(oe,D.getMessages(),I),l||Cr(!0)},onVoiceStatusChanged(l){var m,b;if(((b=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:b.type)==="runtype")switch(l){case"listening":break;case"processing":_e(),X();break;case"speaking":_e(),Ve();break;default:l==="idle"&&D.isBargeInActive()?(_e(),wr(),j==null||j.setAttribute("aria-label","End voice session")):(Ze.active=!1,_e(),Bn("system"),fn());break}},onArtifactsState(l){_n=l,An()}}),fr.current=D,((Ei=(Ai=n.voiceRecognition)==null?void 0:Ai.provider)==null?void 0:Ei.type)==="runtype")try{D.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&D.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),ae&&D.setSSEEventCallback((l,m)=>{ae==null||ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(l=>{var m;l&&(l.metadata&&(i=ka(l.metadata),E.syncFromMetadata()),(m=l.messages)!=null&&m.length&&D.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let To=l=>{var L;l.preventDefault();let m=Z.value.trim(),b=(L=We==null?void 0:We.hasAttachments())!=null?L:!1;if(!m&&!b)return;let A;b&&(A=[],A.push(...We.getContentParts()),m&&A.push(Do(m))),Z.value="",Z.style.height="auto",D.sendMessage(m,{contentParts:A}),b&&We.clearAttachments()},Mo=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),te.click())},ko=async l=>{var b;if(((b=n.attachments)==null?void 0:b.enabled)!==!0||!We)return;let m=ju(l.clipboardData);m.length!==0&&(l.preventDefault(),await We.handleFiles(m))},un=null,kn=!1,ir=null,qe=null,Lo=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Rr=(l="user")=>{var R,B,z,O,ge,ve,Se;if(kn||D.isStreaming())return;let m=Lo();if(!m)return;un=new m;let A=(B=((R=n.voiceRecognition)!=null?R:{}).pauseDuration)!=null?B:2e3;un.continuous=!0,un.interimResults=!0,un.lang="en-US";let L=Z.value;un.onresult=be=>{let Te="",ze="";for(let Xe=0;Xe<be.results.length;Xe++){let $=be.results[Xe],Me=$[0].transcript;$.isFinal?Te+=Me+" ":ze=Me}let pt=L+Te+ze;Z.value=pt,ir&&clearTimeout(ir),(Te||ze)&&(ir=window.setTimeout(()=>{let Xe=Z.value.trim();Xe&&un&&kn&&(Vn(),Z.value="",Z.style.height="auto",D.sendMessage(Xe,{viaVoice:!0}))},A))},un.onerror=be=>{be.error!=="no-speech"&&Vn()},un.onend=()=>{if(kn){let be=Z.value.trim();be&&be!==L.trim()&&(Z.value="",Z.style.height="auto",D.sendMessage(be,{viaVoice:!0})),Vn()}};try{if(un.start(),kn=!0,Ze.active=!0,l!=="system"&&(Ze.manuallyDeactivated=!1),Bn(l),fn(),j){let be=(z=n.voiceRecognition)!=null?z:{};qe={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(O=be.iconName)!=null?O:"mic",iconSize:parseFloat((Se=(ve=be.iconSize)!=null?ve:(ge=n.sendButton)==null?void 0:ge.size)!=null?Se:"40")||24};let Te=be.recordingBackgroundColor,ze=be.recordingIconColor,pt=be.recordingBorderColor;if(j.classList.add("persona-voice-recording"),j.style.backgroundColor=Te!=null?Te:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=ze!=null?ze:"var(--persona-voice-recording-indicator, #ffffff)",ze){let Xe=j.querySelector("svg");Xe&&Xe.setAttribute("stroke",ze)}pt&&(j.style.borderColor=pt),j.setAttribute("aria-label","Stop voice recognition")}}catch{Vn("system")}},Vn=(l="user")=>{if(kn){if(kn=!1,ir&&(clearTimeout(ir),ir=null),un){try{un.stop()}catch{}un=null}if(Ze.active=!1,Bn(l),fn(),j){if(j.classList.remove("persona-voice-recording"),qe){j.style.backgroundColor=qe.backgroundColor,j.style.color=qe.color,j.style.borderColor=qe.borderColor;let m=j.querySelector("svg");m&&m.setAttribute("stroke",qe.color||"currentColor"),qe=null}j.setAttribute("aria-label","Start voice recognition")}}},is=(l,m)=>{var $,Me,Pe,fe,Re,Ct,bt,Yt;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=(($=l==null?void 0:l.provider)==null?void 0:$.type)==="runtype";if(!(b||A))return null;let R=h("div","persona-send-button-wrapper"),B=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");B.type="button",B.setAttribute("aria-label","Start voice recognition");let z=(Me=l==null?void 0:l.iconName)!=null?Me:"mic",O=(Pe=m==null?void 0:m.size)!=null?Pe:"40px",ge=(fe=l==null?void 0:l.iconSize)!=null?fe:O,ve=parseFloat(ge)||24,Se=(Re=l==null?void 0:l.backgroundColor)!=null?Re:m==null?void 0:m.backgroundColor,be=(Ct=l==null?void 0:l.iconColor)!=null?Ct:m==null?void 0:m.textColor;B.style.width=ge,B.style.height=ge,B.style.minWidth=ge,B.style.minHeight=ge,B.style.fontSize="18px",B.style.lineHeight="1",be?B.style.color=be:B.style.color="var(--persona-text, #111827)";let ze=me(z,ve,be||"currentColor",1.5);ze?B.appendChild(ze):B.textContent="\u{1F3A4}",Se?B.style.backgroundColor=Se:B.style.backgroundColor="",l!=null&&l.borderWidth&&(B.style.borderWidth=l.borderWidth,B.style.borderStyle="solid"),l!=null&&l.borderColor&&(B.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(B.style.paddingLeft=l.paddingX,B.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(B.style.paddingTop=l.paddingY,B.style.paddingBottom=l.paddingY),R.appendChild(B);let pt=(bt=l==null?void 0:l.tooltipText)!=null?bt:"Start voice recognition";if(((Yt=l==null?void 0:l.showTooltip)!=null?Yt:!1)&&pt){let sn=h("div","persona-send-button-tooltip");sn.textContent=pt,R.appendChild(sn)}return{micButton:B,micButtonWrapper:R}},no=()=>{var m,b,A,L,R;if(!j||qe)return;let l=(m=n.voiceRecognition)!=null?m:{};qe={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(b=l.iconName)!=null?b:"mic",iconSize:parseFloat((R=(L=l.iconSize)!=null?L:(A=n.sendButton)==null?void 0:A.size)!=null?R:"40")||24}},ro=(l,m)=>{var R,B,z,O,ge;if(!j)return;let b=j.querySelector("svg");b&&b.remove();let A=(ge=qe==null?void 0:qe.iconSize)!=null?ge:parseFloat((O=(z=(R=n.voiceRecognition)==null?void 0:R.iconSize)!=null?z:(B=n.sendButton)==null?void 0:B.size)!=null?O:"40")||24,L=me(l,A,m,1.5);L&&j.appendChild(L)},Hr=()=>{j&&j.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},wr=()=>{var L;if(!j)return;no();let l=(L=n.voiceRecognition)!=null?L:{},m=l.recordingBackgroundColor,b=l.recordingIconColor,A=l.recordingBorderColor;if(Hr(),j.classList.add("persona-voice-recording"),j.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let R=j.querySelector("svg");R&&R.setAttribute("stroke",b)}A&&(j.style.borderColor=A),j.setAttribute("aria-label","Stop voice recognition")},X=()=>{var z,O,ge,ve,Se,be,Te,ze;if(!j)return;no();let l=(z=n.voiceRecognition)!=null?z:{},m=D.getVoiceInterruptionMode(),b=(O=l.processingIconName)!=null?O:"loader",A=(ve=(ge=l.processingIconColor)!=null?ge:qe==null?void 0:qe.color)!=null?ve:"",L=(be=(Se=l.processingBackgroundColor)!=null?Se:qe==null?void 0:qe.backgroundColor)!=null?be:"",R=(ze=(Te=l.processingBorderColor)!=null?Te:qe==null?void 0:qe.borderColor)!=null?ze:"";Hr(),j.classList.add("persona-voice-processing"),j.style.backgroundColor=L,j.style.borderColor=R;let B=A||"currentColor";j.style.color=B,ro(b,B),j.setAttribute("aria-label","Processing voice input"),m==="none"&&(j.style.cursor="default")},Ve=()=>{var ge,ve,Se,be,Te,ze,pt,Xe,$,Me,Pe,fe;if(!j)return;no();let l=(ge=n.voiceRecognition)!=null?ge:{},m=D.getVoiceInterruptionMode(),b=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",A=(ve=l.speakingIconName)!=null?ve:b,L=(ze=l.speakingIconColor)!=null?ze:m==="barge-in"?(be=(Se=l.recordingIconColor)!=null?Se:qe==null?void 0:qe.color)!=null?be:"":(Te=qe==null?void 0:qe.color)!=null?Te:"",R=($=l.speakingBackgroundColor)!=null?$:m==="barge-in"?(pt=l.recordingBackgroundColor)!=null?pt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=qe==null?void 0:qe.backgroundColor)!=null?Xe:"",B=(fe=l.speakingBorderColor)!=null?fe:m==="barge-in"?(Me=l.recordingBorderColor)!=null?Me:"":(Pe=qe==null?void 0:qe.borderColor)!=null?Pe:"";Hr(),j.classList.add("persona-voice-speaking"),j.style.backgroundColor=R,j.style.borderColor=B;let z=L||"currentColor";j.style.color=z,ro(A,z);let O=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";j.setAttribute("aria-label",O),m==="none"&&(j.style.cursor="default"),m==="barge-in"&&j.classList.add("persona-voice-recording")},_e=()=>{var l,m,b;j&&(Hr(),qe&&(j.style.backgroundColor=(l=qe.backgroundColor)!=null?l:"",j.style.color=(m=qe.color)!=null?m:"",j.style.borderColor=(b=qe.borderColor)!=null?b:"",ro(qe.iconName,qe.color||"currentColor"),qe=null),j.style.cursor="",j.setAttribute("aria-label","Start voice recognition"))},Tt=()=>{var l,m;if(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let b=D.getVoiceStatus(),A=D.getVoiceInterruptionMode();if(A==="none"&&(b==="processing"||b==="speaking"))return;if(A==="cancel"&&(b==="processing"||b==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{Ze.active=!1,Ze.manuallyDeactivated=!0,fn(),Bn("user"),_e()});return}D.toggleVoice().then(()=>{Ze.active=D.isVoiceActive(),Ze.manuallyDeactivated=!D.isVoiceActive(),fn(),Bn("user"),D.isVoiceActive()?wr():_e()});return}if(kn){let b=Z.value.trim();Ze.manuallyDeactivated=!0,fn(),Vn("user"),b&&(Z.value="",Z.style.height="auto",D.sendMessage(b))}else Ze.manuallyDeactivated=!1,fn(),Rr("user")};Vt=Tt,j&&(j.addEventListener("click",Tt),vt.push(()=>{var l,m;((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),_e()):Vn("system"),j&&j.removeEventListener("click",Tt)}));let yt=o.on("assistant:complete",()=>{Co&&(Ze.active||Ze.manuallyDeactivated||Co==="assistant"&&!Ze.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!Ze.active&&!Ze.manuallyDeactivated&&(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.toggleVoice().then(()=>{Ze.active=D.isVoiceActive(),Bn("auto"),D.isVoiceActive()&&wr()}):Rr("auto"))},600))});vt.push(yt);let St=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});vt.push(St);let et=()=>{Ht(!T,"user")},y=null,se=null;if(x){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:n,defaultRenderer:()=>Uo(n,et).element,onToggle:et});m&&(se=m)}se||(y=Uo(n,et))}y?e.appendChild(y.element):se&&e.appendChild(se),Wr(),jn.render(n.suggestionChips,D,Z,void 0,n.suggestionChipsConfig),Eo(),eo(D.isStreaming()),Cr(!0),ns(),k&&(x?T&&setTimeout(()=>to(),200):setTimeout(()=>to(),0));let P=()=>{var O,ge,ve,Se,be,Te,ze,pt,Xe,$,Me,Pe,fe,Re,Ct,bt,Yt,sn,we,hn,an,Un;let l=Xt(n),m=(ge=(O=n.launcher)==null?void 0:O.sidebarMode)!=null?ge:!1,b=l||m||((Se=(ve=n.launcher)==null?void 0:ve.fullHeight)!=null?Se:!1),A=(be=e.ownerDocument.defaultView)!=null?be:window,L=(ze=(Te=n.launcher)==null?void 0:Te.mobileFullscreen)!=null?ze:!0,R=(Xe=(pt=n.launcher)==null?void 0:pt.mobileBreakpoint)!=null?Xe:640,B=A.innerWidth<=R,z=L&&B&&x;try{if(z){Zn(),Ar(e,n);return}if(W&&(W=!1,Zn(),Ar(e,n)),!x&&!l){F.style.height="",F.style.width="";return}if(!m&&!l){let rt=(Me=($=n==null?void 0:n.launcher)==null?void 0:$.width)!=null?Me:n==null?void 0:n.launcherWidth,ut=rt!=null?rt:Pn;F.style.width=ut,F.style.maxWidth=ut}if(Kn(),!b){let rt=A.innerHeight,ut=64,yn=(fe=(Pe=n.launcher)==null?void 0:Pe.heightOffset)!=null?fe:0,lr=Math.max(200,rt-ut),Ue=Math.min(640,lr),At=Math.max(200,Ue-yn);F.style.height=`${At}px`}}finally{if(Ke(),Wr(),T&&x){let ut=((Re=e.ownerDocument.defaultView)!=null?Re:window).innerWidth<=((bt=(Ct=n.launcher)==null?void 0:Ct.mobileBreakpoint)!=null?bt:640),yn=(sn=(Yt=n.launcher)==null?void 0:Yt.sidebarMode)!=null?sn:!1,lr=(hn=(we=n.launcher)==null?void 0:we.mobileFullscreen)!=null?hn:!0,Ue=Xt(n)&&lr&&ut,At=yn||lr&&ut&&x||Ue;if(At&&!_t){let Br=e.getRootNode(),Dr=Br instanceof ShadowRoot?Br.host:e.closest(".persona-host");Dr&&!$t&&($t=ma(Dr,(Un=(an=n.launcher)==null?void 0:an.zIndex)!=null?Un:vn)),_t=ga(e.ownerDocument)}else At||($t==null||$t(),$t=null,_t==null||_t(),_t=null)}}};P();let S=(Ti=e.ownerDocument.defaultView)!=null?Ti:window;if(S.addEventListener("resize",P),vt.push(()=>S.removeEventListener("resize",P)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ke()});l.observe(st),vt.push(()=>l.disconnect())}Mn=V.scrollTop;let Y=()=>{let l=V.scrollTop,{action:m,nextLastScrollTop:b}=Ws({following:gn.isFollowing(),currentScrollTop:l,lastScrollTop:Mn,nearBottom:qo(V,vo),userScrollThreshold:ts,isAutoScrolling:qn||or,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Mn=b,m==="resume"){vr();return}m==="pause"&&Ao()};V.addEventListener("scroll",Y,{passive:!0}),vt.push(()=>V.removeEventListener("scroll",Y));let N=l=>{let m=Rs({following:gn.isFollowing(),deltaY:l.deltaY,nearBottom:qo(V,vo),resumeWhenNearBottom:!0});m==="pause"?Ao():m==="resume"&&vr()};V.addEventListener("wheel",N,{passive:!0}),vt.push(()=>V.removeEventListener("wheel",N)),ct.addEventListener("click",()=>{V.scrollTop=V.scrollHeight,Mn=V.scrollTop,vr(),Cr(!0)}),vt.push(()=>ct.remove()),vt.push(()=>{So()});let pe=()=>{ce&&(Tn&&(ce.removeEventListener("click",Tn),Tn=null),x?(ce.style.display="",Tn=()=>{Ht(!1,"user")},ce.addEventListener("click",Tn)):ce.style.display="none")};pe(),(()=>{let{clearChatButton:l}=le;l&&l.addEventListener("click",()=>{D.clearMessages(),Hn.clear(),vr();try{localStorage.removeItem(xo),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xo}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==xo)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),a!=null&&a.clear)try{let b=a.clear();b instanceof Promise&&b.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}i={},E.syncFromMetadata(),ae==null||ae.clear(),xe==null||xe.update()})})(),lt&<.addEventListener("submit",To),Z==null||Z.addEventListener("keydown",Mo),Z==null||Z.addEventListener("paste",ko);let tt="persona-attachment-drop-active",Bt=0,nn=()=>{Bt=0,_.classList.remove(tt)},Ft=()=>{var l;return((l=n.attachments)==null?void 0:l.enabled)===!0&&We!==null},Zt=l=>{!Us(l.dataTransfer)||!Ft()||(Bt++,Bt===1&&_.classList.add(tt))},Ge=l=>{!Us(l.dataTransfer)||!Ft()||(Bt--,Bt<=0&&nn())},Mt=l=>{!Us(l.dataTransfer)||!Ft()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Qt=l=>{var b;if(!Us(l.dataTransfer)||!Ft())return;l.preventDefault(),l.stopPropagation(),nn();let m=Array.from((b=l.dataTransfer.files)!=null?b:[]);m.length!==0&&We.handleFiles(m)},Ot=!0;_.addEventListener("dragenter",Zt,Ot),_.addEventListener("dragleave",Ge,Ot),e.addEventListener("dragover",Mt,Ot),e.addEventListener("drop",Qt,Ot);let It=e.ownerDocument,Ln=l=>{Ft()&&l.preventDefault()},Ua=l=>{Ft()&&l.preventDefault()};It.addEventListener("dragover",Ln),It.addEventListener("drop",Ua),vt.push(()=>{lt&<.removeEventListener("submit",To),Z==null||Z.removeEventListener("keydown",Mo),Z==null||Z.removeEventListener("paste",ko)}),vt.push(()=>{_.removeEventListener("dragenter",Zt,Ot),_.removeEventListener("dragleave",Ge,Ot),e.removeEventListener("dragover",Mt,Ot),e.removeEventListener("drop",Qt,Ot),It.removeEventListener("dragover",Ln),It.removeEventListener("drop",Ua),nn()}),vt.push(()=>{D.cancel()}),y?vt.push(()=>{y==null||y.destroy()}):se&&vt.push(()=>{se==null||se.remove()});let Jt={update(l){var Ri,Hi,Bi,Di,Ni,Fi,Oi,$i,_i,ji,zi,qi,Vi,Ui,Ji,Yi,Gi,Xi,Ki,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,zl,ql,Vl,Ul,Jl,Yl,Gl,Xl,Kl,Zl,Ql,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,Cc,wc,Sc,Ac,Ec,Tc,Mc,kc,Lc,Ic,Pc,Wc,Rc;let m=n.toolCall,b=n.messageActions,A=(Ri=n.layout)==null?void 0:Ri.messages,L=n.colorScheme,R=n.loadingIndicator,B=n.iterationDisplay,z=(Hi=n.features)==null?void 0:Hi.showReasoning,O=(Bi=n.features)==null?void 0:Bi.showToolCalls,ge=(Di=n.features)==null?void 0:Di.toolCallDisplay,ve=(Ni=n.features)==null?void 0:Ni.reasoningDisplay;n={...n,...l},Zn(),Ar(e,n),Ns(e,n),Fs(e,n),An(),n.colorScheme!==L&&br();let Se=Ko.getForInstance(n.plugins);s.length=0,s.push(...Se),x=(Oi=(Fi=n.launcher)==null?void 0:Fi.enabled)!=null?Oi:!0,C=(_i=($i=n.launcher)==null?void 0:$i.autoExpand)!=null?_i:!1,Q=(zi=(ji=n.features)==null?void 0:ji.showReasoning)!=null?zi:!0,Ce=(Vi=(qi=n.features)==null?void 0:qi.showToolCalls)!=null?Vi:!0,Ae=(Ji=(Ui=n.features)==null?void 0:Ui.scrollToBottom)!=null?Ji:{},ht(),ar();let be=re;if(re=(Gi=(Yi=n.features)==null?void 0:Yi.showEventStreamToggle)!=null?Gi:!1,re&&!be){if(ae||(ke=new Xo(he),ae=new Go(Le,ke),ke.open().then(()=>ae==null?void 0:ae.restore()).catch(()=>{}),D.setSSEEventCallback((U,dt)=>{ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:U,timestamp:Date.now(),payload:JSON.stringify(dt)})})),!Qe&&ot){let U=(Ki=(Xi=n.features)==null?void 0:Xi.eventStream)==null?void 0:Ki.classNames,dt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(U!=null&&U.toggleButton?" "+U.toggleButton:"");Qe=h("button",dt),Qe.style.width="28px",Qe.style.height="28px",Qe.style.color=Cn.actionIconColor,Qe.type="button",Qe.setAttribute("aria-label","Event Stream"),Qe.title="Event Stream";let Dt=me("activity","18px","currentColor",1.5);Dt&&Qe.appendChild(Dt);let Je=le.clearChatButtonWrapper,mt=le.closeButtonWrapper,Gt=Je||mt;Gt&&Gt.parentNode===ot?ot.insertBefore(Qe,Gt):ot.appendChild(Qe),Qe.addEventListener("click",()=>{je?$n():tr()})}}else!re&&be&&($n(),Qe&&(Qe.remove(),Qe=null),ae==null||ae.clear(),ke==null||ke.destroy(),ae=null,ke=null);if(((Zi=n.launcher)==null?void 0:Zi.enabled)===!1&&y&&(y.destroy(),y=null),((Qi=n.launcher)==null?void 0:Qi.enabled)===!1&&se&&(se.remove(),se=null),((el=n.launcher)==null?void 0:el.enabled)!==!1&&!y&&!se){let U=s.find(dt=>dt.renderLauncher);if(U!=null&&U.renderLauncher){let dt=U.renderLauncher({config:n,defaultRenderer:()=>Uo(n,et).element,onToggle:et});dt&&(se=dt,e.appendChild(se))}se||(y=Uo(n,et),e.appendChild(y.element))}y&&y.update(n),Wt&&((tl=n.launcher)==null?void 0:tl.title)!==void 0&&(Wt.textContent=n.launcher.title),Rt&&((nl=n.launcher)==null?void 0:nl.subtitle)!==void 0&&(Rt.textContent=n.launcher.subtitle);let Te=(rl=n.layout)==null?void 0:rl.header;if((Te==null?void 0:Te.layout)!==M&&ot){let U=Te?uo(n,Te,{showClose:x,onClose:()=>Ht(!1,"user")}):pr({config:n,showClose:x,onClose:()=>Ht(!1,"user")});ot.replaceWith(U.header),ot=U.header,He=U.iconHolder,Wt=U.headerTitle,Rt=U.headerSubtitle,ce=U.closeButton,M=Te==null?void 0:Te.layout}else if(Te&&(He&&(He.style.display=Te.showIcon===!1?"none":""),Wt&&(Wt.style.display=Te.showTitle===!1?"none":""),Rt&&(Rt.style.display=Te.showSubtitle===!1?"none":""),ce&&(ce.style.display=Te.showCloseButton===!1?"none":""),le.clearChatButtonWrapper)){let U=Te.showClearChat;if(U!==void 0){le.clearChatButtonWrapper.style.display=U?"":"none";let{closeButtonWrapper:dt}=le;dt&&!dt.classList.contains("persona-absolute")&&(U?dt.classList.remove("persona-ml-auto"):dt.classList.add("persona-ml-auto"))}}let pt=((ol=n.layout)==null?void 0:ol.showHeader)!==!1;ot&&(ot.style.display=pt?"":"none");let Xe=((sl=n.layout)==null?void 0:sl.showFooter)!==!1;st&&(st.style.display=Xe?"":"none"),Ke(),ar(),x!==w?x?Ht(C,"auto"):(T=!0,Wr()):C!==H&&Ht(C,"auto"),H=C,w=x,P(),pe();let Pe=JSON.stringify(l.toolCall)!==JSON.stringify(m),fe=JSON.stringify(n.messageActions)!==JSON.stringify(b),Re=JSON.stringify((al=n.layout)==null?void 0:al.messages)!==JSON.stringify(A),Ct=((il=n.loadingIndicator)==null?void 0:il.render)!==(R==null?void 0:R.render)||((ll=n.loadingIndicator)==null?void 0:ll.renderIdle)!==(R==null?void 0:R.renderIdle)||((cl=n.loadingIndicator)==null?void 0:cl.showBubble)!==(R==null?void 0:R.showBubble),bt=n.iterationDisplay!==B,Yt=((pl=(dl=n.features)==null?void 0:dl.showReasoning)!=null?pl:!0)!==(z!=null?z:!0)||((ml=(ul=n.features)==null?void 0:ul.showToolCalls)!=null?ml:!0)!==(O!=null?O:!0)||JSON.stringify((gl=n.features)==null?void 0:gl.toolCallDisplay)!==JSON.stringify(ge)||JSON.stringify((fl=n.features)==null?void 0:fl.reasoningDisplay)!==JSON.stringify(ve);(Pe||fe||Re||Ct||bt||Yt)&&D&&(xr++,Pr(oe,D.getMessages(),I));let we=(hl=n.launcher)!=null?hl:{},hn=(yl=we.headerIconHidden)!=null?yl:!1,an=(xl=(bl=n.layout)==null?void 0:bl.header)==null?void 0:xl.showIcon,Un=hn||an===!1,rt=we.headerIconName,ut=(vl=we.headerIconSize)!=null?vl:"48px";if(He){let U=_.querySelector(".persona-border-b-persona-divider"),dt=U==null?void 0:U.querySelector(".persona-flex-col");if(Un)He.style.display="none",U&&dt&&!U.contains(dt)&&U.insertBefore(dt,U.firstChild);else{if(He.style.display="",He.style.height=ut,He.style.width=ut,U&&dt&&(U.contains(He)?He.nextSibling!==dt&&(He.remove(),U.insertBefore(He,dt)):U.insertBefore(He,dt)),rt){let Je=parseFloat(ut)||24,mt=me(rt,Je*.6,"#ffffff",2);mt?He.replaceChildren(mt):He.textContent=(Cl=we.agentIconText)!=null?Cl:"\u{1F4AC}"}else if(we.iconUrl){let Je=He.querySelector("img");if(Je)Je.src=we.iconUrl,Je.style.height=ut,Je.style.width=ut;else{let mt=document.createElement("img");mt.src=we.iconUrl,mt.alt="",mt.className="persona-rounded-xl persona-object-cover",mt.style.height=ut,mt.style.width=ut,He.replaceChildren(mt)}}else{let Je=He.querySelector("svg"),mt=He.querySelector("img");(Je||mt)&&He.replaceChildren(),He.textContent=(wl=we.agentIconText)!=null?wl:"\u{1F4AC}"}let Dt=He.querySelector("img");Dt&&(Dt.style.height=ut,Dt.style.width=ut)}}let yn=(Al=(Sl=n.layout)==null?void 0:Sl.header)==null?void 0:Al.showTitle,lr=(Tl=(El=n.layout)==null?void 0:El.header)==null?void 0:Tl.showSubtitle;if(Wt&&(Wt.style.display=yn===!1?"none":""),Rt&&(Rt.style.display=lr===!1?"none":""),ce){((kl=(Ml=n.layout)==null?void 0:Ml.header)==null?void 0:kl.showCloseButton)===!1?ce.style.display="none":ce.style.display="";let dt=(Ll=we.closeButtonSize)!=null?Ll:"32px",Dt=(Il=we.closeButtonPlacement)!=null?Il:"inline";ce.style.height=dt,ce.style.width=dt;let{closeButtonWrapper:Je}=le,mt=Dt==="top-right",Gt=Je==null?void 0:Je.classList.contains("persona-absolute");if(Je&&mt!==Gt)if(Je.remove(),mt)Je.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",_.style.position="relative",_.appendChild(Je);else{let nt=(Wl=(Pl=we.clearChat)==null?void 0:Pl.placement)!=null?Wl:"inline",en=(Hl=(Rl=we.clearChat)==null?void 0:Rl.enabled)!=null?Hl:!0;Je.className=en&&nt==="inline"?"":"persona-ml-auto";let xn=_.querySelector(".persona-border-b-persona-divider");xn&&xn.appendChild(Je)}if(ce.style.color=we.closeButtonColor||Cn.actionIconColor,we.closeButtonBackgroundColor?(ce.style.backgroundColor=we.closeButtonBackgroundColor,ce.classList.remove("hover:persona-bg-gray-100")):(ce.style.backgroundColor="",ce.classList.add("hover:persona-bg-gray-100")),we.closeButtonBorderWidth||we.closeButtonBorderColor){let nt=we.closeButtonBorderWidth||"0px",en=we.closeButtonBorderColor||"transparent";ce.style.border=`${nt} solid ${en}`,ce.classList.remove("persona-border-none")}else ce.style.border="",ce.classList.add("persona-border-none");we.closeButtonBorderRadius?(ce.style.borderRadius=we.closeButtonBorderRadius,ce.classList.remove("persona-rounded-full")):(ce.style.borderRadius="",ce.classList.add("persona-rounded-full")),we.closeButtonPaddingX?(ce.style.paddingLeft=we.closeButtonPaddingX,ce.style.paddingRight=we.closeButtonPaddingX):(ce.style.paddingLeft="",ce.style.paddingRight=""),we.closeButtonPaddingY?(ce.style.paddingTop=we.closeButtonPaddingY,ce.style.paddingBottom=we.closeButtonPaddingY):(ce.style.paddingTop="",ce.style.paddingBottom="");let ln=(Bl=we.closeButtonIconName)!=null?Bl:"x",Jn=(Dl=we.closeButtonIconText)!=null?Dl:"\xD7";ce.innerHTML="";let mn=me(ln,"20px","currentColor",2);mn?ce.appendChild(mn):ce.textContent=Jn;let jt=(Nl=we.closeButtonTooltipText)!=null?Nl:"Close chat",In=(Fl=we.closeButtonShowTooltip)!=null?Fl:!0;if(ce.setAttribute("aria-label",jt),Je&&(Je._cleanupTooltip&&(Je._cleanupTooltip(),delete Je._cleanupTooltip),In&&jt)){let nt=null,en=()=>{if(nt||!ce)return;let Fr=ce.ownerDocument,Ro=Fr.body;if(!Ro)return;nt=Qn(Fr,"div","persona-clear-chat-tooltip"),nt.textContent=jt;let Ho=Qn(Fr,"div");Ho.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Ho);let Or=ce.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Er),nt.style.left=`${Or.left+Or.width/2}px`,nt.style.top=`${Or.top-8}px`,nt.style.transform="translate(-50%, -100%)",Ro.appendChild(nt)},xn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Je.addEventListener("mouseenter",en),Je.addEventListener("mouseleave",xn),ce.addEventListener("focus",en),ce.addEventListener("blur",xn),Je._cleanupTooltip=()=>{xn(),Je&&(Je.removeEventListener("mouseenter",en),Je.removeEventListener("mouseleave",xn)),ce&&(ce.removeEventListener("focus",en),ce.removeEventListener("blur",xn))}}}let{clearChatButton:Ue,clearChatButtonWrapper:At}=le;if(Ue){let U=(Ol=we.clearChat)!=null?Ol:{},dt=($l=U.enabled)!=null?$l:!0,Dt=(jl=(_l=n.layout)==null?void 0:_l.header)==null?void 0:jl.showClearChat,Je=Dt!==void 0?Dt:dt,mt=(zl=U.placement)!=null?zl:"inline";if(At){At.style.display=Je?"":"none";let{closeButtonWrapper:Gt}=le;Gt&&!Gt.classList.contains("persona-absolute")&&(Je?Gt.classList.remove("persona-ml-auto"):Gt.classList.add("persona-ml-auto"));let ln=mt==="top-right",Jn=At.classList.contains("persona-absolute");if(ln!==Jn&&Je){if(At.remove(),ln)At.className="persona-absolute persona-top-4 persona-z-50",At.style.right="48px",_.style.position="relative",_.appendChild(At);else{At.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",At.style.right="";let jt=_.querySelector(".persona-border-b-persona-divider"),In=le.closeButtonWrapper;jt&&In&&In.parentElement===jt?jt.insertBefore(At,In):jt&&jt.appendChild(At)}let mn=le.closeButtonWrapper;mn&&!mn.classList.contains("persona-absolute")&&(ln?mn.classList.add("persona-ml-auto"):mn.classList.remove("persona-ml-auto"))}}if(Je){let Gt=(ql=U.size)!=null?ql:"32px";Ue.style.height=Gt,Ue.style.width=Gt;let ln=(Vl=U.iconName)!=null?Vl:"refresh-cw",Jn=(Ul=U.iconColor)!=null?Ul:"";Ue.style.color=Jn||Cn.actionIconColor,Ue.innerHTML="";let mn=me(ln,"20px","currentColor",2);if(mn&&Ue.appendChild(mn),U.backgroundColor?(Ue.style.backgroundColor=U.backgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),U.borderWidth||U.borderColor){let nt=U.borderWidth||"0px",en=U.borderColor||"transparent";Ue.style.border=`${nt} solid ${en}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");U.borderRadius?(Ue.style.borderRadius=U.borderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),U.paddingX?(Ue.style.paddingLeft=U.paddingX,Ue.style.paddingRight=U.paddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),U.paddingY?(Ue.style.paddingTop=U.paddingY,Ue.style.paddingBottom=U.paddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let jt=(Jl=U.tooltipText)!=null?Jl:"Clear chat",In=(Yl=U.showTooltip)!=null?Yl:!0;if(Ue.setAttribute("aria-label",jt),At&&(At._cleanupTooltip&&(At._cleanupTooltip(),delete At._cleanupTooltip),In&&jt)){let nt=null,en=()=>{if(nt||!Ue)return;let Fr=Ue.ownerDocument,Ro=Fr.body;if(!Ro)return;nt=Qn(Fr,"div","persona-clear-chat-tooltip"),nt.textContent=jt;let Ho=Qn(Fr,"div");Ho.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Ho);let Or=Ue.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Er),nt.style.left=`${Or.left+Or.width/2}px`,nt.style.top=`${Or.top-8}px`,nt.style.transform="translate(-50%, -100%)",Ro.appendChild(nt)},xn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};At.addEventListener("mouseenter",en),At.addEventListener("mouseleave",xn),Ue.addEventListener("focus",en),Ue.addEventListener("blur",xn),At._cleanupTooltip=()=>{xn(),At&&(At.removeEventListener("mouseenter",en),At.removeEventListener("mouseleave",xn)),Ue&&(Ue.removeEventListener("focus",en),Ue.removeEventListener("blur",xn))}}}}let Br=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Zo],Dr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Gr.message,Gr.messageAndClick];E=Qo({parsers:Br,handlers:Dr,getSessionMetadata:p,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),I=Od(n,E,J),D.updateConfig(n),Pr(oe,D.getMessages(),I),jn.render(n.suggestionChips,D,Z,void 0,n.suggestionChipsConfig),Eo(),eo(D.isStreaming());let ls=((Gl=n.voiceRecognition)==null?void 0:Gl.enabled)===!0,cs=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ds=((Kl=(Xl=n.voiceRecognition)==null?void 0:Xl.provider)==null?void 0:Kl.type)==="runtype";if(ls&&(cs||ds))if(!j||!Ie){let U=is(n.voiceRecognition,n.sendButton);U&&(j=U.micButton,Ie=U.micButtonWrapper,on.insertBefore(Ie,Lt),j.addEventListener("click",Tt),j.disabled=D.isStreaming())}else{let U=(Zl=n.voiceRecognition)!=null?Zl:{},dt=(Ql=n.sendButton)!=null?Ql:{},Dt=(ec=U.iconName)!=null?ec:"mic",Je=(tc=dt.size)!=null?tc:"40px",mt=(nc=U.iconSize)!=null?nc:Je,Gt=parseFloat(mt)||24;j.style.width=mt,j.style.height=mt,j.style.minWidth=mt,j.style.minHeight=mt;let ln=(oc=(rc=U.iconColor)!=null?rc:dt.textColor)!=null?oc:"currentColor";j.innerHTML="";let Jn=me(Dt,Gt,ln,2);Jn?j.appendChild(Jn):j.textContent="\u{1F3A4}";let mn=(sc=U.backgroundColor)!=null?sc:dt.backgroundColor;mn?j.style.backgroundColor=mn:j.style.backgroundColor="",ln?j.style.color=ln:j.style.color="var(--persona-text, #111827)",U.borderWidth?(j.style.borderWidth=U.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),U.borderColor?j.style.borderColor=U.borderColor:j.style.borderColor="",U.paddingX?(j.style.paddingLeft=U.paddingX,j.style.paddingRight=U.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),U.paddingY?(j.style.paddingTop=U.paddingY,j.style.paddingBottom=U.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let jt=Ie==null?void 0:Ie.querySelector(".persona-send-button-tooltip"),In=(ac=U.tooltipText)!=null?ac:"Start voice recognition";if(((ic=U.showTooltip)!=null?ic:!1)&&In)if(jt)jt.textContent=In,jt.style.display="";else{let en=document.createElement("div");en.className="persona-send-button-tooltip",en.textContent=In,Ie==null||Ie.insertBefore(en,j)}else jt&&(jt.style.display="none");Ie.style.display="",j.disabled=D.isStreaming()}else j&&Ie&&(Ie.style.display="none",((cc=(lc=n.voiceRecognition)==null?void 0:lc.provider)==null?void 0:cc.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():kn&&Vn());if(((dc=n.attachments)==null?void 0:dc.enabled)===!0)if(!gt||!ue){let U=(pc=n.attachments)!=null?pc:{},Dt=(mc=((uc=n.sendButton)!=null?uc:{}).size)!=null?mc:"40px";ne||(ne=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ne.style.display="none",lt.insertBefore(ne,Z)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=((gc=U.allowedTypes)!=null?gc:dr).join(","),Fe.multiple=((fc=U.maxFiles)!=null?fc:4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),lt.insertBefore(Fe,Z)),gt=h("div","persona-send-button-wrapper"),ue=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ue.type="button",ue.setAttribute("aria-label",(hc=U.buttonTooltipText)!=null?hc:"Attach file");let Je=(yc=U.buttonIconName)!=null?yc:"paperclip",mt=Dt,Gt=parseFloat(mt)||40,ln=Math.round(Gt*.6);ue.style.width=mt,ue.style.height=mt,ue.style.minWidth=mt,ue.style.minHeight=mt,ue.style.fontSize="18px",ue.style.lineHeight="1",ue.style.backgroundColor="transparent",ue.style.color="var(--persona-primary, #111827)",ue.style.border="none",ue.style.borderRadius="6px",ue.style.transition="background-color 0.15s ease",ue.addEventListener("mouseenter",()=>{ue.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ue.addEventListener("mouseleave",()=>{ue.style.backgroundColor="transparent"});let Jn=me(Je,ln,"currentColor",1.5);Jn?ue.appendChild(Jn):ue.textContent="\u{1F4CE}",ue.addEventListener("click",In=>{In.preventDefault(),Fe==null||Fe.click()}),gt.appendChild(ue);let mn=(bc=U.buttonTooltipText)!=null?bc:"Attach file",jt=h("div","persona-send-button-tooltip");jt.textContent=mn,gt.appendChild(jt),tn.append(gt),!We&&Fe&&ne&&(We=Ur.fromConfig(U),We.setPreviewsContainer(ne),Fe.addEventListener("change",async()=>{We&&(Fe!=null&&Fe.files)&&(await We.handleFileSelect(Fe.files),Fe.value="")})),_.querySelector(".persona-attachment-drop-overlay")||_.appendChild($d(U.dropOverlay))}else{gt.style.display="";let U=(xc=n.attachments)!=null?xc:{};Fe&&(Fe.accept=((vc=U.allowedTypes)!=null?vc:dr).join(","),Fe.multiple=((Cc=U.maxFiles)!=null?Cc:4)>1),We&&We.updateConfig({allowedTypes:U.allowedTypes,maxFileSize:U.maxFileSize,maxFiles:U.maxFiles})}else gt&&(gt.style.display="none"),We&&We.clearAttachments(),(wc=_.querySelector(".persona-attachment-drop-overlay"))==null||wc.remove();let Ut=(Sc=n.sendButton)!=null?Sc:{},ps=(Ac=Ut.useIcon)!=null?Ac:!1,Io=(Ec=Ut.iconText)!=null?Ec:"\u2191",bn=Ut.iconName,Nn=(Tc=Ut.tooltipText)!=null?Tc:"Send message",oo=(Mc=Ut.showTooltip)!=null?Mc:!1,Po=(kc=Ut.size)!=null?kc:"40px",us=Ut.backgroundColor,Nr=Ut.textColor;if(ps){if(te.style.width=Po,te.style.height=Po,te.style.minWidth=Po,te.style.minHeight=Po,te.style.fontSize="18px",te.style.lineHeight="1",te.innerHTML="",Nr?te.style.color=Nr:te.style.color="var(--persona-button-primary-fg, #ffffff)",bn){let U=parseFloat(Po)||24,dt=(Nr==null?void 0:Nr.trim())||"currentColor",Dt=me(bn,U,dt,2);Dt?te.appendChild(Dt):te.textContent=Io}else te.textContent=Io;te.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",us?(te.style.backgroundColor=us,te.classList.remove("persona-bg-persona-primary")):(te.style.backgroundColor="",te.classList.add("persona-bg-persona-primary"))}else te.textContent=(Ic=(Lc=n.copy)==null?void 0:Lc.sendButtonLabel)!=null?Ic:"Send",te.style.width="",te.style.height="",te.style.minWidth="",te.style.minHeight="",te.style.fontSize="",te.style.lineHeight="",te.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",us?(te.style.backgroundColor=us,te.classList.remove("persona-bg-persona-accent")):te.classList.add("persona-bg-persona-accent"),Nr?te.style.color=Nr:te.classList.add("persona-text-white");Ut.borderWidth?(te.style.borderWidth=Ut.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),Ut.borderColor?te.style.borderColor=Ut.borderColor:te.style.borderColor="",Ut.paddingX?(te.style.paddingLeft=Ut.paddingX,te.style.paddingRight=Ut.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),Ut.paddingY?(te.style.paddingTop=Ut.paddingY,te.style.paddingBottom=Ut.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Wo=Lt==null?void 0:Lt.querySelector(".persona-send-button-tooltip");if(oo&&Nn)if(Wo)Wo.textContent=Nn,Wo.style.display="";else{let U=document.createElement("div");U.className="persona-send-button-tooltip",U.textContent=Nn,Lt==null||Lt.insertBefore(U,te)}else Wo&&(Wo.style.display="none");let ms=(Pc=n.layout)==null?void 0:Pc.contentMaxWidth;ms?(oe.style.maxWidth=ms,oe.style.marginLeft="auto",oe.style.marginRight="auto",oe.style.width="100%",lt&&(lt.style.maxWidth=ms,lt.style.marginLeft="auto",lt.style.marginRight="auto"),Oe&&(Oe.style.maxWidth=ms,Oe.style.marginLeft="auto",Oe.style.marginRight="auto")):(oe.style.maxWidth="",oe.style.marginLeft="",oe.style.marginRight="",oe.style.width="",lt&&(lt.style.maxWidth="",lt.style.marginLeft="",lt.style.marginRight=""),Oe&&(Oe.style.maxWidth="",Oe.style.marginLeft="",Oe.style.marginRight=""));let Sr=(Wc=n.statusIndicator)!=null?Wc:{},Ep=(Rc=Sr.visible)!=null?Rc:!0;if(Nt.style.display=Ep?"":"none",D){let U=D.getStatus();Et(Nt,(Dt=>{var Je,mt,Gt,ln;return Dt==="idle"?(Je=Sr.idleText)!=null?Je:cn.idle:Dt==="connecting"?(mt=Sr.connectingText)!=null?mt:cn.connecting:Dt==="connected"?(Gt=Sr.connectedText)!=null?Gt:cn.connected:Dt==="error"?(ln=Sr.errorText)!=null?ln:cn.error:cn[Dt]})(U),Sr,U)}Nt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Tp=Sr.align==="left"?"persona-text-left":Sr.align==="center"?"persona-text-center":"persona-text-right";Nt.classList.add(Tp)},open(){x&&Ht(!0,"api")},close(){x&&Ht(!1,"api")},toggle(){x&&Ht(!T,"api")},clearChat(){dn=!1,D.clearMessages(),Hn.clear(),vr();try{localStorage.removeItem(xo),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xo}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==xo)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let m=a.clear();m instanceof Promise&&m.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}i={},E.syncFromMetadata(),ae==null||ae.clear(),xe==null||xe.update()},setMessage(l){return!Z||D.isStreaming()?!1:(!T&&x&&Ht(!0,"system"),Z.value=l,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let m=(l==null?void 0:l.trim())||Z.value.trim();return m?(!T&&x&&Ht(!0,"system"),Z.value="",Z.style.height="auto",D.sendMessage(m),!0):!1},startVoiceRecognition(){var m,b;return D.isStreaming()?!1:((b=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:b.type)==="runtype"?(D.isVoiceActive()||(!T&&x&&Ht(!0,"system"),Ze.manuallyDeactivated=!1,fn(),D.toggleVoice().then(()=>{Ze.active=D.isVoiceActive(),Bn("user"),D.isVoiceActive()&&wr()})),!0):kn?!0:Lo()?(!T&&x&&Ht(!0,"system"),Ze.manuallyDeactivated=!1,fn(),Rr("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{Ze.active=!1,Ze.manuallyDeactivated=!0,fn(),Bn("user"),_e()}),!0):!1:kn?(Ze.manuallyDeactivated=!0,fn(),Vn("user"),!0):!1},injectMessage(l){return!T&&x&&Ht(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!T&&x&&Ht(!0,"system");let m=D.injectAssistantMessage(l);return G&&(G=!1,K&&(clearTimeout(K),K=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),m},injectUserMessage(l){return!T&&x&&Ht(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!T&&x&&Ht(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!T&&x&&Ht(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!T&&x&&Ht(!0,"system"),D.injectTestEvent(l)},async connectStream(l,m){return D.connectStream(l,m)},__pushEventStreamEvent(l){ae&&ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!re||!ae||tr()},hideEventStream(){je&&$n()},isEventStreamVisible(){return je},showArtifacts(){On(n)&&(dn=!1,An(),at==null||at.setMobileOpen(!0))},hideArtifacts(){On(n)&&(dn=!0,An())},upsertArtifact(l){return On(n)?(dn=!1,D.upsertArtifact(l)):null},selectArtifact(l){On(n)&&D.selectArtifact(l)},clearArtifacts(){On(n)&&D.clearArtifacts()},focusInput(){return x&&!T||!Z?!1:(Z.focus(),!0)},async resolveApproval(l,m){let A=D.getMessages().find(L=>{var R;return L.variant==="approval"&&((R=L.approval)==null?void 0:R.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return D.resolveApproval(A.approval,m)},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){g(l)},on(l,m){return o.on(l,m)},off(l,m){o.off(l,m)},isOpen(){return x&&T},isVoiceActive(){return Ze.active},getState(){return{open:x&&T,launcherEnabled:x,voiceActive:Ze.active,streaming:D.isStreaming()}},showCSATFeedback(l){!T&&x&&Ht(!0,"system");let m=oe.querySelector(".persona-feedback-container");m&&m.remove();let b=qs({onSubmit:async(A,L)=>{var R;D.isClientTokenMode()&&await D.submitCSATFeedback(A,L),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});oe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!T&&x&&Ht(!0,"system");let m=oe.querySelector(".persona-feedback-container");m&&m.remove();let b=Vs({onSubmit:async(A,L)=>{var R;D.isClientTokenMode()&&await D.submitNPSFeedback(A,L),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});oe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return D.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return D.submitNPSFeedback(l,m)},destroy(){vt.forEach(l=>l()),q.remove(),y==null||y.destroy(),se==null||se.remove(),Tn&&ce.removeEventListener("click",Tn)}};if((((Mi=t==null?void 0:t.debugTools)!=null?Mi:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:Jt,getMessages:Jt.getMessages,getStatus:Jt.getStatus,getMetadata:Jt.getPersistentMetadata,updateMetadata:Jt.updatePersistentMetadata,clearHistory:()=>Jt.clearChat(),setVoiceActive:b=>b?Jt.startVoiceRecognition():Jt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,vt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&Jt.focusInput()};if(window.addEventListener("persona:focusInput",m),vt.push(()=>{window.removeEventListener("persona:focusInput",m)}),re){let z=ge=>{let ve=ge.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===l)&&Jt.showEventStream()},O=ge=>{let ve=ge.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===l)&&Jt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),vt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let b=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&Jt.showArtifacts()},A=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&Jt.hideArtifacts()},L=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==l||O!=null&&O.artifact&&Jt.upsertArtifact(O.artifact)},R=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==l||typeof(O==null?void 0:O.id)=="string"&&Jt.selectArtifact(O.id)},B=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&Jt.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",B),vt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",B)})}let Dn=zu(n.persistState);if(Dn&&x){let l=qu(Dn.storage),m=`${Dn.keyPrefix}widget-open`,b=`${Dn.keyPrefix}widget-voice`,A=`${Dn.keyPrefix}widget-voice-mode`;if(l){let L=((ki=Dn.persist)==null?void 0:ki.openState)&&l.getItem(m)==="true",R=((Li=Dn.persist)==null?void 0:Li.voiceState)&&l.getItem(b)==="true",B=((Ii=Dn.persist)==null?void 0:Ii.voiceState)&&l.getItem(A)==="true";if(L&&setTimeout(()=>{Jt.open(),setTimeout(()=>{var z;if(R||B)Jt.startVoiceRecognition();else if((z=Dn.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Pi=Dn.persist)!=null&&Pi.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(Wi=Dn.persist)!=null&&Wi.voiceState&&(o.on("voice:state",z=>{l.setItem(b,z.active?"true":"false")}),o.on("user:message",z=>{l.setItem(A,z.viaVoice?"true":"false")})),Dn.clearOnChatClear){let z=()=>{l.removeItem(m),l.removeItem(b),l.removeItem(A)},O=()=>z();window.addEventListener("persona:clear-chat",O),vt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return c&&x&&setTimeout(()=>{Jt.open()},0),Jt};var Vu=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},_d=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Wa=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},jd=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Wa(e)},La=e=>{e.style.transition=""},Ia=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Pa=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ys=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Uu=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},Ju=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},zd=(e,r,t,n,s,o,a)=>{var v,E,x,C,k,H;let i=Fn(o),u=i.reveal==="push";Uu(e,r,t,n,u),Ju(e,r,t,n,i.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,d=(E=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?E:!0,p=(C=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileBreakpoint)!=null?C:640,g=c!=null?c.innerWidth<=p:!1;if(d&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ia(r),La(n),jd(n),Pa(t),Ys(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((H=(k=o==null?void 0:o.launcher)==null?void 0:k.zIndex)!=null?H:vn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),jd(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ia(r),La(n),Pa(t),Ys(s,n);let w=i.animate?"transform 180ms ease":"none",M=i.side==="right"?"translateX(100%)":"translateX(-100%)",W=a?"translateX(0)":M;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=W,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",La(n),Wa(n),Ys(s,n);let w=Vu(i.width,e.clientWidth),M=Math.max(0,e.clientWidth),W=i.animate?"transform 180ms ease":"none",T=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${M+w}px`,r.style.transition=W,r.style.transform=T,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${M}px`,t.style.maxWidth=`${M}px`,t.style.minWidth=`${M}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ia(r),Wa(n),Pa(t),Ys(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let M=a?i.width:"0px",W=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",T=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${M}`,n.style.width=M,n.style.maxWidth=M,n.style.minWidth=M,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||T?"hidden":"visible",n.style.transition=W,w&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Yu=(e,r)=>{let t=e.ownerDocument.createElement("div");return _d(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){_d(t,n)},destroy(){t.remove()}}},Gu=(e,r)=>{var k,H,w,M;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),u=t.createElement("div"),c=t.createElement("aside"),d=t.createElement("div"),p=(H=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)==null||H?(M=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?M:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),n.insertBefore(a,e),u.appendChild(e);let g=null,f=()=>{g==null||g.disconnect(),g=null},v=()=>{f(),Fn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{zd(a,i,u,c,d,r,p)}),g.observe(a))},E=()=>{zd(a,i,u,c,d,r,p),v()},x=a.ownerDocument.defaultView,C=()=>{E()};return x==null||x.addEventListener("resize",C),Fn(r).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),E(),{mode:"docked",host:d,shell:a,syncWidgetState(W){let T=W.launcherEnabled?W.open:!0;p!==T&&(p=T,E())},updateConfig(W){var T,G;r=W,((G=(T=r==null?void 0:r.launcher)==null?void 0:T.enabled)!=null?G:!0)===!1&&(p=!0),E()},destroy(){x==null||x.removeEventListener("resize",C),f(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},es=(e,r)=>Xt(r)?Gu(e,r):Yu(e,r);var Ra={},Xu=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},Ku=()=>{try{if(typeof Ra!="undefined"&&Ra.url)return new URL("../widget.css",Ra.url).href}catch{}return null},qd=(e,r)=>{let t=Ku(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},Ha=e=>{var x;let r=Xu(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=es(r,s),a,i=[],u=(C,k)=>{var W,T;let w=!((T=(W=k==null?void 0:k.launcher)==null?void 0:W.enabled)!=null?T:!0)||Xt(k),M=n.createElement("div");if(M.setAttribute("data-persona-root","true"),w&&(M.style.height="100%",M.style.display="flex",M.style.flexDirection="column",M.style.flex="1",M.style.minHeight="0"),t){let G=C.attachShadow({mode:"open"});G.appendChild(M),qd(G,n)}else C.appendChild(M),qd(C,n);return r.id&&M.setAttribute("data-persona-instance",r.id),M},c=()=>{o.syncWidgetState(a.getState())},d=()=>{i.forEach(C=>C()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let C=u(o.host,s);a=Js(C,s,{debugTools:e.debugTools}),d()},g=()=>{i.forEach(C=>C()),i=[],a.destroy()};p(),(x=e.onReady)==null||x.call(e);let f=C=>{g(),o.destroy(),o=es(r,C),s=C,p()},v={update(C){var M,W,T,G,K,J;let k={...s,...C,launcher:{...(M=s==null?void 0:s.launcher)!=null?M:{},...(W=C==null?void 0:C.launcher)!=null?W:{},dock:{...(G=(T=s==null?void 0:s.launcher)==null?void 0:T.dock)!=null?G:{},...(J=(K=C==null?void 0:C.launcher)==null?void 0:K.dock)!=null?J:{}}}},H=Xt(s),w=Xt(k);if(H!==w){f(k);return}s=k,o.updateConfig(s),a.update(C),c()},destroy(){g(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},E=new Proxy(v,{get(C,k,H){if(k==="host")return o.host;if(k in C)return Reflect.get(C,k,H);let w=a[k];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=E),E};var Gd=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Zu=new Set(["button","a","input","select","textarea","details","summary"]),Qu=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ba=/\b(product|card|item|listing|result)\b/i,Na=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,em=3e3,tm=100;function Xd(e){let r=typeof e.className=="string"?e.className:"";if(Ba.test(r)||e.id&&Ba.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&Ba.test(n.value))return!0}return!1}function Kd(e){var r;return Na.test(((r=e.textContent)!=null?r:"").trim())}function Zd(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function nm(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Vd(e){let r=e.match(Na);return r?r[0]:null}function Ud(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function rm(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var om="commerce-card",sm="result-card";function Jd(e){return!Xd(e)||!Kd(e)||!Zd(e)&&!nm(e)?0:5200}function Yd(e){var n;return!Xd(e)||Kd(e)||!Zd(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Fa=[{id:om,scoreElement(e){return Jd(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||Na.test(n)&&n.length<32)}return!0},formatSummary(e,r){var u,c,d;if(Jd(e)===0)return null;let{title:t,href:n}=Ud(e),s=(d=(c=Vd(((u=e.textContent)!=null?u:"").trim()))!=null?c:Vd(r.text))!=null?d:"",o=rm(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
100
|
+
`)}},{id:sm,scoreElement(e){return Yd(e)},formatSummary(e,r){if(Yd(e)===0)return null;let{title:t,href:n}=Ud(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
|
|
101
|
+
`)}}];function am(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function im(e){var d,p,g,f,v,E,x,C,k,H,w,M,W;let r=(d=e.options)!=null?d:{},t=(g=(p=r.maxElements)!=null?p:e.maxElements)!=null?g:80,n=(v=(f=r.excludeSelector)!=null?f:e.excludeSelector)!=null?v:".persona-host",s=(x=(E=r.maxTextLength)!=null?E:e.maxTextLength)!=null?x:200,o=(k=(C=r.visibleOnly)!=null?C:e.visibleOnly)!=null?k:!0,a=(H=r.root)!=null?H:e.root,i=(w=r.mode)!=null?w:"structured",u=(M=r.maxCandidates)!=null?M:Math.max(500,t*10),c=(W=e.rules)!=null?W:Fa;return i==="simple"&&e.rules&&e.rules.length>0?(am(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:u,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function Da(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var lm=["data-testid","data-product","data-action","data-id","data-name","data-type"];function cm(e){let r=e.tagName.toLowerCase(),t=e.getAttribute("role");return r==="a"&&e.hasAttribute("href")?"navigable":r==="input"||r==="select"||r==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":r==="button"||t==="button"||Zu.has(r)||t&&Qu.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Qd(e){if(e.hidden)return!1;try{let r=getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function dm(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let s=e.getAttribute("aria-label");s&&(r["aria-label"]=s);let o=e.getAttribute("type");o&&(r.type=o);let a=e.getAttribute("value");a&&(r.value=a);let i=e.getAttribute("name");i&&(r.name=i);let u=e.getAttribute("role");u&&(r.role=u);for(let c=0;c<e.attributes.length;c++){let d=e.attributes[c];d.name.startsWith("data-")&&(r[d.name]=d.value)}return r}function Oa(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${Da(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of lm){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${Da(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${r}.${t.map(a=>Da(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(i>=0){let u=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(u).length===1)return u}catch{}}}}let n=e.parentElement;if(n){let o=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(o>=0)return`${r}:nth-of-type(${o+1})`}return r}function pm(e){return e==="static"?tm:em}function ep(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:Oa(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:cm(e),attributes:dm(e)}}function um(e,r,t,n){let s=pm(r.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,r,n);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function mm(e,r){var t;for(let n of e)if(r.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(r.el)&&n.formattingRule.shouldSuppressDescendant(n.el,r.el,r.enriched))return!0;return!1}function gm(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,s=[],o=0,a=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,d=c.tagName.toLowerCase();if(Gd.has(d)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Qd(c)){i=a.nextNode();continue}let p=ep(c,e.maxTextLength),g=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(x=>x==="role");if(!g&&!f){i=a.nextNode();continue}if(n.has(p.selector)){i=a.nextNode();continue}n.add(p.selector);let{score:v,formattingRule:E}=um(c,p,e.rules,t);s.push({el:c,domIndex:o,enriched:p,score:v,formattingRule:E}),o+=1}i=a.nextNode()}s.sort((c,d)=>{let p=c.enriched.interactivity==="static"?1:0,g=d.enriched.interactivity==="static"?1:0;return p!==g?p-g:d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex});let u=[];for(let c of s){if(u.length>=e.maxElements)break;mm(u,c)||u.push(c)}return u.sort((c,d)=>{let p=c.enriched.interactivity==="static"?1:0,g=d.enriched.interactivity==="static"?1:0;return p!==g?p-g:p===1&&d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex}),u.map(c=>{var g;let d;if((g=c.formattingRule)!=null&&g.formatSummary){let f=c.formattingRule.formatSummary(c.el,c.enriched,t);f&&(d=f)}let p={...c.enriched};return d&&(p.formattedSummary=d),p})}function fm(e,r){let t=[],n=new Set,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let u=o,c=u.tagName.toLowerCase();if(Gd.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Qd(u)){o=s.nextNode();continue}let d=ep(u,e.maxTextLength),p=d.text.length>0,g=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(f=>f==="role");if(!p&&!g){o=s.nextNode();continue}n.has(d.selector)||(n.add(d.selector),t.push(d))}o=s.nextNode()}let a=[],i=[];for(let u of t)u.interactivity!=="static"?a.push(u):i.push(u);return[...a,...i].slice(0,e.maxElements)}function tp(e={}){var n;let r=im(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?fm(r,t):gm(r,t):[]}var Gs=100;function np(e,r={}){var o;if(e.length===0)return"No page elements found.";let t=(o=r.mode)!=null?o:"structured",n=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
|
|
99
102
|
${a.map(i=>`- ${i.split(`
|
|
100
103
|
`).join(`
|
|
101
104
|
`)}`).join(`
|
|
102
|
-
`)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
105
|
+
`)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Gs)}" (clickable)`);n.push(`Interactive elements:
|
|
103
106
|
${a.join(`
|
|
104
|
-
`)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,
|
|
107
|
+
`)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Gs)}" (navigable)`);n.push(`Navigation links:
|
|
105
108
|
${a.join(`
|
|
106
|
-
`)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,
|
|
109
|
+
`)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Gs)}" (input)`);n.push(`Form inputs:
|
|
107
110
|
${a.join(`
|
|
108
|
-
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
111
|
+
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Gs)}"`);n.push(`Content:
|
|
109
112
|
${a.join(`
|
|
110
113
|
`)}`)}return n.join(`
|
|
111
114
|
|
|
112
|
-
`)}var
|
|
115
|
+
`)}var rp={name:"@runtypelabs/persona",version:"3.10.1",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var Xr=rp.version;function mr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function ym(e){if(e)return{getHeaders:mr(e.getHeaders),onFeedback:mr(e.onFeedback),onCopy:mr(e.onCopy),requestMiddleware:mr(e.requestMiddleware),actionHandlers:mr(e.actionHandlers),actionParsers:mr(e.actionParsers),postprocessMessage:mr(e.postprocessMessage),contextProviders:mr(e.contextProviders),streamParser:mr(e.streamParser)}}var op=`({ text, message }: any) => {
|
|
113
116
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
114
117
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
115
118
|
let cleanJson = jsonSource
|
|
@@ -122,7 +125,7 @@ ${a.join(`
|
|
|
122
125
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
123
126
|
} catch (e) { return null; }
|
|
124
127
|
return null;
|
|
125
|
-
}`,
|
|
128
|
+
}`,sp=`function(ctx) {
|
|
126
129
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
127
130
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
128
131
|
var cleanJson = jsonSource
|
|
@@ -135,7 +138,7 @@ ${a.join(`
|
|
|
135
138
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
136
139
|
} catch (e) { return null; }
|
|
137
140
|
return null;
|
|
138
|
-
}`,
|
|
141
|
+
}`,ap=`(action: any, context: any) => {
|
|
139
142
|
if (action.type !== 'nav_then_click') return;
|
|
140
143
|
const payload = action.payload || action.raw || {};
|
|
141
144
|
const url = payload?.page;
|
|
@@ -152,7 +155,7 @@ ${a.join(`
|
|
|
152
155
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
153
156
|
window.location.href = targetUrl;
|
|
154
157
|
return { handled: true, displayText: text };
|
|
155
|
-
}`,
|
|
158
|
+
}`,ip=`function(action, context) {
|
|
156
159
|
if (action.type !== 'nav_then_click') return;
|
|
157
160
|
var payload = action.payload || action.raw || {};
|
|
158
161
|
var url = payload.page;
|
|
@@ -169,26 +172,26 @@ ${a.join(`
|
|
|
169
172
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
170
173
|
window.location.href = targetUrl;
|
|
171
174
|
return { handled: true, displayText: text };
|
|
172
|
-
}`,
|
|
175
|
+
}`,bm=`(parsed: any) => {
|
|
173
176
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
174
177
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
175
178
|
if (parsed.action === 'message') return parsed.text || '';
|
|
176
179
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
177
180
|
return parsed.text || null;
|
|
178
|
-
}`,
|
|
181
|
+
}`,xm=`function(parsed) {
|
|
179
182
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
180
183
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
181
184
|
if (parsed.action === 'message') return parsed.text || '';
|
|
182
185
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
183
186
|
return parsed.text || null;
|
|
184
|
-
}`;function
|
|
185
|
-
`)}function
|
|
186
|
-
`)}function $u(e,r){let t=r==null?void 0:r.hooks,n=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Tr(n,"theme",e.theme," "),e.launcher&&Tr(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{n.push(` ${s}: "${o}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"?n.push(` ${s}: ${o},`):typeof o=="number"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{n.push(` ${s}: ${o},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{n.push(` "${s}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...Os(e," ")),n.push(...$s(e," ",t)),n.push(..._s(e," ")),n.push(...js(e," ")),t!=null&&t.getHeaders&&n.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&n.push(` contextProviders: ${t.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?n.push(` streamParser: ${t.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${Bu}),`)),t!=null&&t.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${Md}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${Md}`),n.push(" ],")),t!=null&&t.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${t.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${Ld}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${Ld}`),n.push(" ],")),t!=null&&t.postprocessMessage?n.push(` postprocessMessage: ${t.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
|
|
187
|
-
`)}function
|
|
188
|
-
`)}function
|
|
187
|
+
}`;function vm(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function Xs(e){var r,t;return(t=(r=e.parserType)!=null?r:vm(e.streamParser))!=null?t:"plain"}function Ks(e,r){let t=[];return e.toolCall&&(t.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([n,s])=>{typeof s=="string"&&t.push(`${r} ${n}: "${s}",`)}),t.push(`${r}},`)),t}function Zs(e,r,t){let n=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(n.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?n.push(`${r} ${a}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${a}: ${i},`))}),t!=null&&t.onFeedback&&n.push(`${r} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&n.push(`${r} onCopy: ${t.onCopy},`),n.push(`${r}},`)),n}function Qs(e,r){let t=[];if(e.markdown){let n=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(n||s)&&(t.push(`${r}markdown: {`),n&&(t.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`)}),t.push(`${r} },`)),s&&t.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${r}},`))}return t}function ea(e,r){let t=[];if(e.layout){let n=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(n||s)&&(t.push(`${r}layout: {`),n&&(t.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),s&&(t.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${r} avatar: {`),Object.entries(a).forEach(([i,u])=>{typeof u=="string"?t.push(`${r} ${i}: "${u}",`):typeof u=="boolean"&&t.push(`${r} ${i}: ${u},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([u])=>u!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?t.push(`${r} ${u}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${u}: ${c},`))}),t.push(`${r} },`)):typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),t.push(`${r}},`))}return t}function $a(e,r){let t=[];return e&&(e.getHeaders&&t.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${r}streamParser: ${e.streamParser},`)),t}function lp(e,r,t){Object.entries(r).forEach(([n,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${n}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${n}: {`),lp(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function kr(e,r,t,n){t&&(e.push(`${n}${r}: {`),lp(e,t,`${n} `),e.push(`${n}},`))}function cp(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:ym(t.hooks)}:void 0;return r==="esm"?Cm(n,s):r==="script-installer"?Am(n):r==="script-advanced"?Tm(n,s):r==="react-component"?wm(n,s):r==="react-advanced"?Sm(n,s):Em(n,s)}function Cm(e,r){let t=r==null?void 0:r.hooks,n=Xs(e),s=n!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&kr(o,"theme",e.theme," "),e.launcher&&kr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ks(e," ")),o.push(...Zs(e," ",t)),o.push(...Qs(e," ")),o.push(...ea(e," ")),o.push(...$a(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
|
|
188
|
+
`)}function wm(e,r){let t=r==null?void 0:r.hooks,n=Xs(e),s=n!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&kr(o,"theme",e.theme," "),e.launcher&&kr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ks(e," ")),o.push(...Zs(e," ",t)),o.push(...Qs(e," ")),o.push(...ea(e," ")),o.push(...$a(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
|
|
189
|
+
`)}function Sm(e,r){let t=r==null?void 0:r.hooks,n=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&kr(n,"theme",e.theme," "),e.launcher&&kr(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{n.push(` ${s}: "${o}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"?n.push(` ${s}: ${o},`):typeof o=="number"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{n.push(` ${s}: ${o},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{n.push(` "${s}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...Ks(e," ")),n.push(...Zs(e," ",t)),n.push(...Qs(e," ")),n.push(...ea(e," ")),t!=null&&t.getHeaders&&n.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&n.push(` contextProviders: ${t.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?n.push(` streamParser: ${t.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${bm}),`)),t!=null&&t.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${op}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${op}`),n.push(" ],")),t!=null&&t.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${t.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${ap}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${ap}`),n.push(" ],")),t!=null&&t.postprocessMessage?n.push(` postprocessMessage: ${t.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
|
|
190
|
+
`)}function dp(e){var s;let r=Xs(e),t=r!=="plain",n={};if(e.apiUrl&&(n.apiUrl=e.apiUrl),e.clientToken&&(n.clientToken=e.clientToken),e.flowId&&(n.flowId=e.flowId),t&&(n.parserType=r),e.theme&&(n.theme=e.theme),e.launcher&&(n.launcher=e.launcher),e.copy&&(n.copy=e.copy),e.sendButton&&(n.sendButton=e.sendButton),e.voiceRecognition&&(n.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(n.statusIndicator=e.statusIndicator),e.features&&(n.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(n.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(n.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(n.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(n.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(n.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(n.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,u])=>{i!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,u])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof u=="object"&&u!==null)a.avatar=u;else if(i==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([d,p])=>{d!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[d]=p)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function Am(e){let r=dp(e),t=JSON.stringify(r,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Xr}/dist/install.global.js" data-config='${t}'></script>`}function Em(e,r){let t=r==null?void 0:r.hooks,n=Xs(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Xr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Xr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&kr(o,"theme",e.theme," "),e.launcher&&kr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ks(e," ")),o.push(...Zs(e," ",t)),o.push(...Qs(e," ")),o.push(...ea(e," ")),o.push(...$a(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
|
|
191
|
+
`)}function Tm(e,r){let t=r==null?void 0:r.hooks,n=dp(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
|
|
189
192
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
190
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${
|
|
191
|
-
`)}var
|
|
193
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Xr}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${xm});`),o.push(" };")),o.push(""),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${t.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${sp}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${sp}`),o.push(" ];")),o.push(""),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${t.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${ip}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${ip}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
|
|
194
|
+
`)}var pp={desktop:{w:1280,h:800},mobile:{w:390,h:844}},up=.1,mp=.15,gp=1.5,_a=24,fp=40,Mm=`
|
|
192
195
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
193
196
|
.persona-dc-root {
|
|
194
197
|
display: flex;
|
|
@@ -339,7 +342,7 @@ ${a.join(`
|
|
|
339
342
|
.persona-dc-stage {
|
|
340
343
|
height: 550px;
|
|
341
344
|
min-height: 400px;
|
|
342
|
-
padding: ${
|
|
345
|
+
padding: ${_a}px;
|
|
343
346
|
overflow: auto;
|
|
344
347
|
background: #f0f1f3;
|
|
345
348
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -429,5 +432,5 @@ ${a.join(`
|
|
|
429
432
|
min-height: 300px;
|
|
430
433
|
}
|
|
431
434
|
}
|
|
432
|
-
`;function Vu(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Uu,document.head.appendChild(e)}function qu(e,r){let t=e.clientWidth-Ma*2-Nd,n=e.clientHeight-Ma*2-Nd;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function Ju(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Od(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Vu();let p=Math.max(0,Math.min(n,t.length-1)),u=s,f=o,m=null,v=1,M=!1,b=h("div","persona-dc-root"),C=h("div","persona-dc-toolbar"),S=h("div","persona-dc-toolbar-lead"),R=h("div","persona-dc-toolbar-trail"),w=wt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>ot(-1)}),L=h("div");L.style.position="relative";let B=h("button","persona-dc-title-btn");B.type="button",B.setAttribute("aria-expanded","false"),B.setAttribute("aria-haspopup","listbox");let T=h("span","persona-dc-title-text"),Y=h("span","persona-dc-title-chevron"),ge=me("chevron-down",12,"currentColor",2);ge&&Y.appendChild(ge),B.append(T,Y);let ce=h("div","persona-dc-dropdown");ce.setAttribute("role","listbox"),ce.style.display="none";let $=!1;function ne(){ce.innerHTML="";for(let _=0;_<t.length;_++){let z=t[_],ee=h("button","persona-dc-dropdown-item");ee.type="button",ee.setAttribute("role","option"),ee.setAttribute("aria-current",_===p?"true":"false");let Fe=h("span");if(Fe.textContent=z.title,ee.appendChild(Fe),z.description){let J=h("span","persona-dc-dropdown-desc");J.textContent=z.description,ee.appendChild(J)}ee.addEventListener("click",()=>{re(),St(_)}),ce.appendChild(ee)}}function Te(){$=!$,ce.style.display=$?"":"none",B.setAttribute("aria-expanded",$?"true":"false"),$&&ne()}function re(){$&&($=!1,ce.style.display="none",B.setAttribute("aria-expanded","false"))}B.addEventListener("click",_=>{_.stopPropagation(),Te()});let Se=()=>re();document.addEventListener("click",Se),L.append(B,ce);let He=wt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>ot(1)}),he=h("span","persona-dc-counter");S.append(w,L,He,he);let Me=null;i&&(Me=_o({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:_=>{u=_,pe.dataset.device=u,m=null,j()}}),R.appendChild(Me.element));let ke=null;if(a){let _=h("div","persona-dc-zoom-controls"),z=wt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let J=m!=null?m:v;m=Math.max(Dd,J-Bd),j()}});ke=h("span","persona-dc-zoom-level"),ke.title="Reset to 100%",ke.style.cursor="pointer",ke.addEventListener("click",()=>{m=1,j()});let ee=wt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let J=m!=null?m:v;m=Math.min(Fd,J+Bd),j()}}),Fe=wt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,j()}});_.append(z,ke,ee,Fe),R.appendChild(_)}if(d){let _=h("div","persona-dc-separator");R.appendChild(_);let z=_o({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ee=>{f=ee,pe.dataset.colorScheme=f,se()}});R.appendChild(z.element)}let oe=h("div","persona-dc-separator");R.appendChild(oe);let be=wt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});R.appendChild(be),C.append(S,R);let $e=h("div","persona-dc-stage"),pe=h("div","persona-dc-iframe-wrapper");pe.dataset.device=u,pe.dataset.colorScheme=f;let de=h("iframe","persona-dc-iframe");de.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),de.setAttribute("loading","lazy"),de.title=t[p].title,pe.appendChild(de),$e.appendChild(pe),b.append(C,$e),e.appendChild(b);function se(){var _;try{let z=(_=de.contentDocument)==null?void 0:_.body;if(!z)return;f==="dark"?z.classList.add("theme-dark"):z.classList.remove("theme-dark")}catch{}}de.addEventListener("load",()=>se());function De(){let _=t[p];T.textContent=_.title,he.textContent=`${p+1} / ${t.length}`,de.title=_.title}function ot(_){let z=((p+_)%t.length+t.length)%t.length;St(z)}function St(_){_<0||_>=t.length||(p=_,de.src=t[p].url,De(),c==null||c(p,t[p]))}function j(){var ee;if(M)return;let _=(ee=Hd[u])!=null?ee:Hd.desktop;v=qu($e,_);let z=Math.max(Dd,Math.min(Fd,m!=null?m:v));Ju(pe,de,_,z,u),ke&&(ke.textContent=`${Math.round(z*100)}%`)}let q=new ResizeObserver(()=>j());q.observe($e),De(),de.src=t[p].url,requestAnimationFrame(()=>j());function ae(){M||(M=!0,q.disconnect(),document.removeEventListener("click",Se),b.remove())}return{element:b,goTo:St,next:()=>ot(1),prev:()=>ot(-1),getIndex:()=>p,setDevice(_){u=_,pe.dataset.device=_,Me==null||Me.setSelected(_),m=null,j()},setColorScheme(_){f=_,pe.dataset.colorScheme=_},setZoom(_){m=_,j()},destroy:ae}}function $d(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function _d(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function jd(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:Gn(e.colors.primary,.95),100:Gn(e.colors.primary,.9),200:Gn(e.colors.primary,.8),300:Gn(e.colors.primary,.7),400:Gn(e.colors.primary,.6),500:e.colors.primary,600:Gn(e.colors.primary,.8),700:Gn(e.colors.primary,.7),800:Gn(e.colors.primary,.6),900:Gn(e.colors.primary,.5),950:Gn(e.colors.primary,.45)}}),{...r,palette:t}}}}function zd(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Ud(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Gn(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Vd(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Yu={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},qd={components:{panel:{borderRadius:"0",shadow:"none"}}},ka={id:"shop",label:"Shopping Assistant",config:{theme:Yu,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Mn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},La={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:qd}},Ia={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:qd}},Pa={shop:ka,minimal:La,fullscreen:Ia};function Jd(e){return Pa[e]}var Gu=va;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,THEME_ZONES,VERSION,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createStandardBubble,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultParseRules,detectColorScheme,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,reducedMotionPlugin,renderComponentDirective,renderLoadingIndicatorWithFallback,resolveDockConfig,resolveSanitizer,resolveTokens,themeToCssVariables,validateImageFile,validateTheme});
|
|
435
|
+
`;function km(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Mm,document.head.appendChild(e)}function Lm(e,r){let t=e.clientWidth-_a*2-fp,n=e.clientHeight-_a*2-fp;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function Im(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function hp(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");km();let d=Math.max(0,Math.min(n,t.length-1)),p=s,g=o,f=null,v=1,E=!1,x=h("div","persona-dc-root"),C=h("div","persona-dc-toolbar"),k=h("div","persona-dc-toolbar-lead"),H=h("div","persona-dc-toolbar-trail"),w=Pt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>it(-1)}),M=h("div");M.style.position="relative";let W=h("button","persona-dc-title-btn");W.type="button",W.setAttribute("aria-expanded","false"),W.setAttribute("aria-haspopup","listbox");let T=h("span","persona-dc-title-text"),G=h("span","persona-dc-title-chevron"),K=me("chevron-down",12,"currentColor",2);K&&G.appendChild(K),W.append(T,G);let J=h("div","persona-dc-dropdown");J.setAttribute("role","listbox"),J.style.display="none";let I=!1;function Q(){J.innerHTML="";for(let _=0;_<t.length;_++){let V=t[_],oe=h("button","persona-dc-dropdown-item");oe.type="button",oe.setAttribute("role","option"),oe.setAttribute("aria-current",_===d?"true":"false");let Oe=h("span");if(Oe.textContent=V.title,oe.appendChild(Oe),V.description){let Z=h("span","persona-dc-dropdown-desc");Z.textContent=V.description,oe.appendChild(Z)}oe.addEventListener("click",()=>{re(),Et(_)}),J.appendChild(oe)}}function Ce(){I=!I,J.style.display=I?"":"none",W.setAttribute("aria-expanded",I?"true":"false"),I&&Q()}function re(){I&&(I=!1,J.style.display="none",W.setAttribute("aria-expanded","false"))}W.addEventListener("click",_=>{_.stopPropagation(),Ce()});let Ae=()=>re();document.addEventListener("click",Ae),M.append(W,J);let Ne=Pt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>it(1)}),he=h("span","persona-dc-counter");k.append(w,M,Ne,he);let ke=null;i&&(ke=Yo({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:_=>{p=_,de.dataset.device=p,f=null,q()}}),H.appendChild(ke.element));let Le=null;if(a){let _=h("div","persona-dc-zoom-controls"),V=Pt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Z=f!=null?f:v;f=Math.max(mp,Z-up),q()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{f=1,q()});let oe=Pt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Z=f!=null?f:v;f=Math.min(gp,Z+up),q()}}),Oe=Pt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,q()}});_.append(V,Le,oe,Oe),H.appendChild(_)}if(u){let _=h("div","persona-dc-separator");H.appendChild(_);let V=Yo({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:oe=>{g=oe,de.dataset.colorScheme=g,Ee()}});H.appendChild(V.element)}let ae=h("div","persona-dc-separator");H.appendChild(ae);let xe=Pt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[d].url,"_blank")}});H.appendChild(xe),C.append(k,H);let je=h("div","persona-dc-stage"),de=h("div","persona-dc-iframe-wrapper");de.dataset.device=p,de.dataset.colorScheme=g;let ie=h("iframe","persona-dc-iframe");ie.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ie.setAttribute("loading","lazy"),ie.title=t[d].title,de.appendChild(ie),je.appendChild(de),x.append(C,je),e.appendChild(x);function Ee(){var _;try{let V=(_=ie.contentDocument)==null?void 0:_.body;if(!V)return;g==="dark"?V.classList.add("theme-dark"):V.classList.remove("theme-dark")}catch{}}ie.addEventListener("load",()=>Ee());function Be(){let _=t[d];T.textContent=_.title,he.textContent=`${d+1} / ${t.length}`,ie.title=_.title}function it(_){let V=((d+_)%t.length+t.length)%t.length;Et(V)}function Et(_){_<0||_>=t.length||(d=_,ie.src=t[d].url,Be(),c==null||c(d,t[d]))}function q(){var oe;if(E)return;let _=(oe=pp[p])!=null?oe:pp.desktop;v=Lm(je,_);let V=Math.max(mp,Math.min(gp,f!=null?f:v));Im(de,ie,_,V,p),Le&&(Le.textContent=`${Math.round(V*100)}%`)}let F=new ResizeObserver(()=>q());F.observe(je),Be(),ie.src=t[d].url,requestAnimationFrame(()=>q());function le(){E||(E=!0,F.disconnect(),document.removeEventListener("click",Ae),x.remove())}return{element:x,goTo:Et,next:()=>it(1),prev:()=>it(-1),getIndex:()=>d,setDevice(_){p=_,de.dataset.device=_,ke==null||ke.setSelected(_),f=null,q()},setColorScheme(_){g=_,de.dataset.colorScheme=_},setZoom(_){f=_,q()},destroy:le}}function yp(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function bp(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function xp(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:er(e.colors.primary,.95),100:er(e.colors.primary,.9),200:er(e.colors.primary,.8),300:er(e.colors.primary,.7),400:er(e.colors.primary,.6),500:e.colors.primary,600:er(e.colors.primary,.8),700:er(e.colors.primary,.7),800:er(e.colors.primary,.6),900:er(e.colors.primary,.5),950:er(e.colors.primary,.45)}}),{...r,palette:t}}}}function vp(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Cp(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function er(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function wp(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Pm={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Sp={components:{panel:{borderRadius:"0",shadow:"none"}}},ja={id:"shop",label:"Shopping Assistant",config:{theme:Pm,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Pn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},za={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Sp}},qa={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Sp}},Va={shop:ja,minimal:za,fullscreen:qa};function Ap(e){return Va[e]}var Wm=Ha;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,THEME_ZONES,VERSION,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createStandardBubble,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultParseRules,detectColorScheme,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,reducedMotionPlugin,renderComponentDirective,renderLoadingIndicatorWithFallback,resolveDockConfig,resolveSanitizer,resolveTokens,themeToCssVariables,validateImageFile,validateTheme});
|
|
433
436
|
//# sourceMappingURL=index.cjs.map
|