@runtypelabs/persona 3.4.0 → 3.5.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 CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var yd=Object.create;var _o=Object.defineProperty;var bd=Object.getOwnPropertyDescriptor;var xd=Object.getOwnPropertyNames;var vd=Object.getPrototypeOf,Cd=Object.prototype.hasOwnProperty;var wd=(e,r)=>{for(var t in r)_o(e,t,{get:r[t],enumerable:!0})},Ml=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of xd(r))!Cd.call(e,s)&&s!==t&&_o(e,s,{get:()=>r[s],enumerable:!(n=bd(r,s))||n.enumerable});return e};var kl=(e,r,t)=>(t=e!=null?yd(vd(e)):{},Ml(r||!e||!e.__esModule?_o(t,"default",{value:e,enumerable:!0}):t,e)),Sd=e=>Ml(_o({},"__esModule",{value:!0}),e);var yu={};wd(yu,{AgentWidgetClient:()=>lr,AgentWidgetSession:()=>Pr,AttachmentManager:()=>ur,DEFAULT_COMPONENTS:()=>Hs,DEFAULT_PALETTE:()=>Ws,DEFAULT_SEMANTIC:()=>Rs,DEFAULT_WIDGET_CONFIG:()=>Ct,PRESETS:()=>ga,PRESET_FULLSCREEN:()=>ua,PRESET_MINIMAL:()=>pa,PRESET_SHOP:()=>da,THEME_ZONES:()=>Zl,VERSION:()=>hr,accessibilityPlugin:()=>ld,animationsPlugin:()=>cd,applyThemeVariables:()=>Vn,attachHeaderToContainer:()=>gr,brandPlugin:()=>dd,buildComposer:()=>Hr,buildDefaultHeader:()=>Ns,buildHeader:()=>Dn,buildHeaderWithLayout:()=>Rr,buildMinimalHeader:()=>Os,collectEnrichedPageContext:()=>Vc,componentRegistry:()=>Nn,createActionManager:()=>Co,createAgentExperience:()=>ys,createBestAvailableVoiceProvider:()=>Qo,createBubbleWithLayout:()=>pc,createCSATFeedback:()=>fs,createComboButton:()=>ss,createComponentMiddleware:()=>Lc,createComponentStreamParser:()=>ps,createDefaultSanitizer:()=>Ls,createDemoCarousel:()=>id,createDirectivePostprocessor:()=>Rl,createDropdownMenu:()=>Jn,createFlexibleJsonStreamParser:()=>Ol,createIconButton:()=>vt,createImagePart:()=>ql,createJsonStreamParser:()=>Vo,createLabelButton:()=>fo,createLocalStorageAdapter:()=>ds,createMarkdownProcessor:()=>so,createMarkdownProcessorFromConfig:()=>ir,createMessageActions:()=>_s,createNPSFeedback:()=>hs,createPlainTextParser:()=>qo,createPlugin:()=>gd,createRegexJsonParser:()=>Uo,createStandardBubble:()=>Br,createTextPart:()=>Go,createTheme:()=>Wr,createThemeObserver:()=>rs,createToggleGroup:()=>ho,createTypingIndicator:()=>mr,createVoiceProvider:()=>pr,createWidgetHostLayout:()=>wo,createXmlParser:()=>Jo,default:()=>hu,defaultActionHandlers:()=>fr,defaultJsonActionParser:()=>vo,defaultParseRules:()=>aa,detectColorScheme:()=>uo,directivePostprocessor:()=>Hl,escapeHtml:()=>kr,extractComponentDirectiveFromMessage:()=>ms,fileToImagePart:()=>Ul,formatEnrichedContext:()=>Jc,generateAssistantMessageId:()=>cr,generateCodeSnippet:()=>ed,generateMessageId:()=>$l,generateStableSelector:()=>ia,generateUserMessageId:()=>Ir,getActiveTheme:()=>go,getColorScheme:()=>Ds,getDisplayText:()=>_l,getHeaderLayout:()=>$s,getImageParts:()=>zl,getPreset:()=>fd,hasComponentDirective:()=>gs,hasImages:()=>jl,headerLayouts:()=>as,highContrastPlugin:()=>ud,initAgentWidget:()=>na,isComponentDirectiveType:()=>kc,isDockedMountMode:()=>jt,isVoiceSupported:()=>lo,markdownPostprocessor:()=>ks,mergeWithDefaults:()=>cs,normalizeContent:()=>Fl,pluginRegistry:()=>xo,reducedMotionPlugin:()=>pd,renderComponentDirective:()=>us,renderLoadingIndicatorWithFallback:()=>Fs,resolveDockConfig:()=>un,resolveSanitizer:()=>Lr,resolveTokens:()=>ts,themeToCssVariables:()=>ns,validateImageFile:()=>Vl,validateTheme:()=>Bs});module.exports=Sd(yu);var Il=require("marked"),Ad=e=>{if(e)return e},so=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new Il.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=Ad(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},ir=e=>e?so({markedOptions:e.options,renderer:e.renderer}):so(),Ed=so(),ks=e=>Ed(e),kr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Pl=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Ll=e=>`%%FORM_PLACEHOLDER_${e}%%`,Wl=(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=Ll(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=Ll(r.length);return r.push({token:o,type:s}),o}),t},Rl=e=>{let r=ir(e);return t=>{let n=[],s=Wl(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Pl(i)}"></div>`;o=o.replace(d,u)}),o}},Hl=e=>{let r=[],t=Wl(e,r),n=ks(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Pl(o)}"></div>`;n=n.replace(a,d)}),n};var Bl=kl(require("dompurify"),1),Td={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"]},Md=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ls=()=>{let e=(0,Bl.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:")&&!Md.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Td)},Lr=e=>e===!1?null:typeof e=="function"?e:Ls();var Hn=require("partial-json"),jo=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ao=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)}},kd=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`},Dl=e=>e.status==="complete"?kd(e):e.status==="pending"?"Waiting":"",Ld=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 Nl=e=>e.status==="complete"?Ld(e):"Using tool...",Id=()=>{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,`
1
+ "use strict";var vd=Object.create;var jo=Object.defineProperty;var Cd=Object.getOwnPropertyDescriptor;var wd=Object.getOwnPropertyNames;var Sd=Object.getPrototypeOf,Ad=Object.prototype.hasOwnProperty;var Ed=(e,r)=>{for(var t in r)jo(e,t,{get:r[t],enumerable:!0})},Ll=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of wd(r))!Ad.call(e,s)&&s!==t&&jo(e,s,{get:()=>r[s],enumerable:!(n=Cd(r,s))||n.enumerable});return e};var Il=(e,r,t)=>(t=e!=null?vd(Sd(e)):{},Ll(r||!e||!e.__esModule?jo(t,"default",{value:e,enumerable:!0}):t,e)),Td=e=>Ll(jo({},"__esModule",{value:!0}),e);var vu={};Ed(vu,{AgentWidgetClient:()=>dr,AgentWidgetSession:()=>Wr,AttachmentManager:()=>mr,DEFAULT_COMPONENTS:()=>Ds,DEFAULT_PALETTE:()=>Hs,DEFAULT_SEMANTIC:()=>Bs,DEFAULT_WIDGET_CONFIG:()=>xt,PRESETS:()=>fa,PRESET_FULLSCREEN:()=>ma,PRESET_MINIMAL:()=>ga,PRESET_SHOP:()=>ua,THEME_ZONES:()=>ec,VERSION:()=>br,accessibilityPlugin:()=>dd,animationsPlugin:()=>pd,applyThemeVariables:()=>Jn,attachHeaderToContainer:()=>fr,brandPlugin:()=>ud,buildComposer:()=>Br,buildDefaultHeader:()=>$s,buildHeader:()=>Dn,buildHeaderWithLayout:()=>Hr,buildMinimalHeader:()=>Fs,collectEnrichedPageContext:()=>Kc,componentRegistry:()=>Nn,createActionManager:()=>wo,createAgentExperience:()=>bs,createBestAvailableVoiceProvider:()=>es,createBubbleWithLayout:()=>gc,createCSATFeedback:()=>hs,createComboButton:()=>as,createComponentMiddleware:()=>Pc,createComponentStreamParser:()=>us,createDefaultSanitizer:()=>Ps,createDemoCarousel:()=>cd,createDirectivePostprocessor:()=>Bl,createDropdownMenu:()=>Kn,createFlexibleJsonStreamParser:()=>Fl,createIconButton:()=>bt,createImagePart:()=>Vl,createJsonStreamParser:()=>Jo,createLabelButton:()=>ho,createLocalStorageAdapter:()=>ps,createMarkdownProcessor:()=>ao,createMarkdownProcessorFromConfig:()=>cr,createMessageActions:()=>zs,createNPSFeedback:()=>ys,createPlainTextParser:()=>Uo,createPlugin:()=>fd,createRegexJsonParser:()=>Vo,createStandardBubble:()=>Dr,createTextPart:()=>Yo,createTheme:()=>Rr,createThemeObserver:()=>os,createToggleGroup:()=>yo,createTypingIndicator:()=>hr,createVoiceProvider:()=>gr,createWidgetHostLayout:()=>So,createXmlParser:()=>Ko,default:()=>xu,defaultActionHandlers:()=>yr,defaultJsonActionParser:()=>Co,defaultParseRules:()=>la,detectColorScheme:()=>go,directivePostprocessor:()=>Dl,escapeHtml:()=>Lr,extractComponentDirectiveFromMessage:()=>fs,fileToImagePart:()=>Jl,formatEnrichedContext:()=>Gc,generateAssistantMessageId:()=>pr,generateCodeSnippet:()=>nd,generateMessageId:()=>_l,generateStableSelector:()=>ca,generateUserMessageId:()=>Pr,getActiveTheme:()=>mo,getColorScheme:()=>Os,getDisplayText:()=>zl,getHeaderLayout:()=>_s,getImageParts:()=>Ul,getPreset:()=>yd,hasComponentDirective:()=>ms,hasImages:()=>ql,headerLayouts:()=>is,highContrastPlugin:()=>md,initAgentWidget:()=>oa,isComponentDirectiveType:()=>Ic,isDockedMountMode:()=>jt,isVoiceSupported:()=>co,markdownPostprocessor:()=>Is,mergeWithDefaults:()=>ds,normalizeContent:()=>jl,pluginRegistry:()=>vo,reducedMotionPlugin:()=>gd,renderComponentDirective:()=>gs,renderLoadingIndicatorWithFallback:()=>js,resolveDockConfig:()=>un,resolveSanitizer:()=>Ir,resolveTokens:()=>ns,themeToCssVariables:()=>rs,validateImageFile:()=>Kl,validateTheme:()=>Ns});module.exports=Td(vu);var Wl=require("marked"),Md=e=>{if(e)return e},ao=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new Wl.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=Md(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},cr=e=>e?ao({markedOptions:e.options,renderer:e.renderer}):ao(),kd=ao(),Is=e=>kd(e),Lr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Rl=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Pl=e=>`%%FORM_PLACEHOLDER_${e}%%`,Hl=(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=Pl(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=Pl(r.length);return r.push({token:o,type:s}),o}),t},Bl=e=>{let r=cr(e);return t=>{let n=[],s=Hl(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Rl(i)}"></div>`;o=o.replace(p,u)}),o}},Dl=e=>{let r=[],t=Hl(e,r),n=Is(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Rl(o)}"></div>`;n=n.replace(a,p)}),n};var Nl=Il(require("dompurify"),1),Ld={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"]},Id=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ps=()=>{let e=(0,Nl.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:")&&!Id.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Ld)},Ir=e=>e===!1?null:typeof e=="function"?e:Ps();var Hn=require("partial-json"),zo=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)}},Pd=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`},Ol=e=>e.status==="complete"?Pd(e):e.status==="pending"?"Waiting":"",Wd=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 $l=e=>e.status==="complete"?Wd(e):"Using tool...",Rd=()=>{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()=>{}}},zo=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},qo=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Uo=()=>{var r;let e=Id();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)}},Vo=()=>{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,Hn.parse)(t,Hn.STR|Hn.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?jo(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=jo(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Ol=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?jo(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?jo(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,Hn.parse)(o,Hn.STR|Hn.OBJ),d=s(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Jo=()=>{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 Pd="https://api.runtype.com/v1/dispatch",Is="https://api.runtype.com",Ps=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 Wd(e){switch(e){case"json":return Vo;case"regex-json":return Uo;case"xml":return Jo;default:return qo}}var lr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:Pd,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:Wd(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$/,""))||Is;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$/,""))||Is}/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),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:r.messages.filter(Ps).map(m=>{var v,S,b;return{id:m.id,role:m.role,content:(b=(S=(v=m.contentParts)!=null?v:m.llmContent)!=null?S:m.rawContent)!=null?b:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...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 f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),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 S=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:S}),S}if(f.status===429){let S=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:S}),S}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$/,""))||Is}/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(Ps).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(Ps).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){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(r);if(a===null)return!1;let i=()=>{if(n.current)return n.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return n.current=d,s(d),d};if(a.text!==void 0){let d=i();d.content+=a.text,s(d)}return a.done&&(n.current&&(n.current.streaming=!1,s(n.current)),t({type:"status",status:"idle"})),a.error&&t({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(r,t,n){var Ke,mt,Re,tt,Te,N,re,ee,q,ce,ke,Q,K,_e,it,Lt,qt,Ut,G,Le,ft,yt,Ye,ot,Wt,Vt,de,E,Ee,ne,be,Ce,Xe,ye,Ie,De,nt,Et,Ne,Gn,xn,Yn,$n,yr,Fn,Mn,Ze,Z,an,rn,_r,vn,ht,ln,kn,jr,br,zr,Xn,Cn,Zn,Tt,wn,qr,_n,Sn,D,jn,zn,Ur,Ln,Qn,Vr,In,Pn,xr,vr,So,Ao,Eo,Jr,Cr,ze,Kr,cn,Qt,To,Mo,Gr,er,Wn,ko,Lo,Io,Es,tr,nr,wt,wr,Sr,Yr,Xr,Zr,Qr,Yt,on,Rn,Oe,eo,rr,mn,Po,Ar,Er,or,qn,Wo,Ro,fn;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,u=X=>{let Ge=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,bt=X.tools?X.tools.map(je=>({...je,chunks:je.chunks?[...je.chunks]:void 0})):void 0;return{...X,reasoning:Ge,toolCall:pt,tools:bt}},p=X=>{t({type:"message",message:u(X)})},f=null,m={current:null},v=new Map,S=new Map,b={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=X=>{if(X==null)return null;try{return String(X)}catch{return null}},_=X=>{var Ge,pt,bt,je,Ve;return k((Ve=(je=(bt=(pt=(Ge=X.stepId)!=null?Ge:X.step_id)!=null?pt:X.step)!=null?bt:X.parentId)!=null?je:X.flowStepId)!=null?Ve:X.flow_step_id)},w=X=>{var Ge,pt,bt,je,Ve,xt,C;return k((C=(xt=(Ve=(je=(bt=(pt=(Ge=X.callId)!=null?Ge:X.call_id)!=null?pt:X.requestId)!=null?bt:X.request_id)!=null?je:X.toolCallId)!=null?Ve:X.tool_call_id)!=null?xt:X.stepId)!=null?C:X.step_id)},I=()=>f||(f={id:n!=null?n:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(f),f),$=(X,Ge)=>{b.lastId=Ge,X&&b.byStep.set(X,Ge)},T=(X,Ge)=>{var Ve;let pt=(Ve=X.reasoningId)!=null?Ve:X.id,bt=_(X);if(pt){let xt=String(pt);return $(bt,xt),xt}if(bt){let xt=b.byStep.get(bt);if(xt)return b.lastId=xt,xt}if(b.lastId&&!Ge)return b.lastId;if(!Ge)return null;let je=`reason-${c()}`;return $(bt,je),je},V=X=>{let Ge=v.get(X);if(Ge)return Ge;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 v.set(X,pt),p(pt),pt},ue=(X,Ge)=>{x.lastId=Ge,X&&x.byCall.set(X,Ge)},oe=new Set,z=new Map,te=new Set,Ae=new Map,ie=X=>{if(!X)return!1;let Ge=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ge==="emit_artifact_markdown"||Ge==="emit_artifact_component"},Se=(X,Ge)=>{var Ve;let pt=(Ve=X.toolId)!=null?Ve:X.id,bt=w(X);if(pt){let xt=String(pt);return ue(bt,xt),xt}if(bt){let xt=x.byCall.get(bt);if(xt)return x.lastId=xt,xt}if(x.lastId&&!Ge)return x.lastId;if(!Ge)return null;let je=`tool-${c()}`;return ue(bt,je),je},ae=X=>{let Ge=S.get(X);if(Ge)return Ge;let pt={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:X,status:"pending"}};return S.set(X,pt),p(pt),pt},Y=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let Ge=Number(X);if(!Number.isNaN(Ge)&&Number.isFinite(Ge))return Ge;let pt=Date.parse(X);if(!Number.isNaN(pt))return pt}return Date.now()},ge=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},F=new Map,J=new Map,me=null,at=new Map,Ue=(Ke=this.config.iterationDisplay)!=null?Ke:"separate";for(;;){let{done:X,value:Ge}=await s.read();if(X)break;a+=o.decode(Ge,{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()=>{}}},qo=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},Uo=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Vo=()=>{var r;let e=Rd();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)}},Jo=()=>{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,Hn.parse)(t,Hn.STR|Hn.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?zo(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=zo(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Fl=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?zo(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?zo(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,Hn.parse)(o,Hn.STR|Hn.OBJ),p=s(i);p!==null&&(r=p)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Ko=()=>{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 Hd="https://api.runtype.com/v1/dispatch",Ws="https://api.runtype.com",Rs=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 Bd(e){switch(e){case"json":return Jo;case"regex-json":return Vo;case"xml":return Ko;default:return Uo}}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:Hd,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:Bd(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$/,""))||Ws;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$/,""))||Ws}/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 p=await this.initSession();if(new Date>=new Date(p.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),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,d={sessionId:p.sessionId,messages:r.messages.filter(Rs).map(m=>{var v,A,b;return{id:m.id,role:m.role,content:(b=(A=(v=m.contentParts)!=null?v:m.llmContent)!=null?A:m.rawContent)!=null?b:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),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 A=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:A}),A}if(f.status===429){let A=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:A}),A}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(p){let c=p instanceof Error?p:new Error(String(p));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 p=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:p}),p}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 p=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:p}),p}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$/,""))||Ws}/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(Rs).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(Rs).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 p=u=>{let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...u!==void 0&&{partId:u}};return n.current=d,s(d),d},c=u=>n.current?n.current:p(u);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)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}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 mt,Be,rt,Me,D,se,te,z,oe,Le,Z,J,ze,Ue,St,qt,Ut,K,Ie,ft,yt,Ze,it,Wt,Vt,ue,T,Ae,re,ye,Ce,Qe,he,Pe,Ne,ot,At,Oe,Yn,xn,Xn,$n,xr,Fn,Mn,et,X,an,rn,jr,vn,ht,ln,kn,zr,vr,qr,Zn,Cn,Qn,Et,wn,Ur,_n,Sn,H,jn,zn,Vr,Ln,er,Jr,In,Pn,Cr,wr,Ao,Eo,To,Kr,Sr,Ve,Gr,cn,Qt,Mo,ko,Yr,tr,Wn,Lo,Io,Po,Ts,nr,rr,vt,Ar,Er,Xr,Zr,Qr,eo,Yt,on,Rn,$e,to,or,mn,Wo,Tr,Mr,sr,qn,Ro,Ho,fn,ar;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),p=0,c=()=>i+p++,u=Q=>{let Ye=Q.reasoning?{...Q.reasoning,chunks:[...Q.reasoning.chunks]}:void 0,st=Q.toolCall?{...Q.toolCall,chunks:Q.toolCall.chunks?[...Q.toolCall.chunks]:void 0}:void 0,_e=Q.tools?Q.tools.map(qe=>({...qe,chunks:qe.chunks?[...qe.chunks]:void 0})):void 0;return{...Q,reasoning:Ye,toolCall:st,tools:_e}},d=Q=>{t({type:"message",message:u(Q)})},f=null,m={current:null},v={current:null},A=new Map,b=new Map,x={lastId:null,byStep:new Map},M={lastId:null,byCall:new Map},F=Q=>{if(Q==null)return null;try{return String(Q)}catch{return null}},S=Q=>{var Ye,st,_e,qe,Lt;return F((Lt=(qe=(_e=(st=(Ye=Q.stepId)!=null?Ye:Q.step_id)!=null?st:Q.step)!=null?_e:Q.parentId)!=null?qe:Q.flowStepId)!=null?Lt:Q.flow_step_id)},I=Q=>{var Ye,st,_e,qe,Lt,Tt,C;return F((C=(Tt=(Lt=(qe=(_e=(st=(Ye=Q.callId)!=null?Ye:Q.call_id)!=null?st:Q.requestId)!=null?_e:Q.request_id)!=null?qe:Q.toolCallId)!=null?Lt:Q.tool_call_id)!=null?Tt:Q.stepId)!=null?C:Q.step_id)},O=()=>f||(f={id:n!=null?n:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f),k=(Q,Ye)=>{x.lastId=Ye,Q&&x.byStep.set(Q,Ye)},V=(Q,Ye)=>{var Lt;let st=(Lt=Q.reasoningId)!=null?Lt:Q.id,_e=S(Q);if(st){let Tt=String(st);return k(_e,Tt),Tt}if(_e){let Tt=x.byStep.get(_e);if(Tt)return x.lastId=Tt,Tt}if(x.lastId&&!Ye)return x.lastId;if(!Ye)return null;let qe=`reason-${c()}`;return k(_e,qe),qe},ge=Q=>{let Ye=A.get(Q);if(Ye)return Ye;let st={id:`reason-${Q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Q,status:"streaming",chunks:[]}};return A.set(Q,st),d(st),st},ie=(Q,Ye)=>{M.lastId=Ye,Q&&M.byCall.set(Q,Ye)},_=new Set,ne=new Map,Te=new Set,le=new Map,ke=Q=>{if(!Q)return!1;let Ye=Q.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ye==="emit_artifact_markdown"||Ye==="emit_artifact_component"},de=(Q,Ye)=>{var Lt;let st=(Lt=Q.toolId)!=null?Lt:Q.id,_e=I(Q);if(st){let Tt=String(st);return ie(_e,Tt),Tt}if(_e){let Tt=M.byCall.get(_e);if(Tt)return M.lastId=Tt,Tt}if(M.lastId&&!Ye)return M.lastId;if(!Ye)return null;let qe=`tool-${c()}`;return ie(_e,qe),qe},Y=Q=>{let Ye=b.get(Q);if(Ye)return Ye;let st={id:`tool-${Q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Q,status:"pending"}};return b.set(Q,st),d(st),st},ce=Q=>{if(typeof Q=="number"&&Number.isFinite(Q))return Q;if(typeof Q=="string"){let Ye=Number(Q);if(!Number.isNaN(Ye)&&Number.isFinite(Ye))return Ye;let st=Date.parse(Q);if(!Number.isNaN(st))return st}return Date.now()},q=Q=>{if(typeof Q=="string")return Q;if(Q==null)return"";try{return JSON.stringify(Q)}catch{return String(Q)}},G=new Map,ve=new Map,xe=null,Ke=new Map,Xe=(mt=this.config.iterationDisplay)!=null?mt:"separate";for(;;){let{done:Q,value:Ye}=await s.read();if(Q)break;a+=o.decode(Ye,{stream:!0});let st=a.split(`
5
5
 
6
- `);a=(mt=pt.pop())!=null?mt:"";for(let bt of pt){let je=bt.split(`
7
- `),Ve="message",xt="";for(let H of je)H.startsWith("event:")?Ve=H.replace("event:","").trim():H.startsWith("data:")&&(xt+=H.replace("data:","").trim());if(!xt)continue;let C;try{C=JSON.parse(xt)}catch(H){t({type:"error",error:H instanceof Error?H:new Error("Failed to parse chat stream payload")});continue}let $e=Ve!=="message"?Ve:(Re=C.type)!=null?Re:"message";if((tt=this.onSSEEvent)==null||tt.call(this,$e,C),this.parseSSEEvent){m.current=f;let H=await this.handleCustomSSEEvent(C,t,m,p,c);if(m.current&&!f&&(f=m.current),H)continue}if($e==="reason_start"){let H=(Te=T(C,!0))!=null?Te:`reason-${c()}`,M=V(H);M.reasoning=(N=M.reasoning)!=null?N:{id:H,status:"streaming",chunks:[]},M.reasoning.startedAt=(ee=M.reasoning.startedAt)!=null?ee:Y((re=C.startedAt)!=null?re:C.timestamp),M.reasoning.completedAt=void 0,M.reasoning.durationMs=void 0,M.streaming=!0,M.reasoning.status="streaming",p(M)}else if($e==="reason_delta"||$e==="reason_chunk"){let H=(ce=(q=T(C,!1))!=null?q:T(C,!0))!=null?ce:`reason-${c()}`,M=V(H);M.reasoning=(ke=M.reasoning)!=null?ke:{id:H,status:"streaming",chunks:[]},M.reasoning.startedAt=(K=M.reasoning.startedAt)!=null?K:Y((Q=C.startedAt)!=null?Q:C.timestamp);let P=(Lt=(it=(_e=C.reasoningText)!=null?_e:C.text)!=null?it:C.delta)!=null?Lt:"";if(P&&C.hidden!==!0&&M.reasoning.chunks.push(String(P)),M.reasoning.status=C.done?"complete":"streaming",C.done){M.reasoning.completedAt=Y((qt=C.completedAt)!=null?qt:C.timestamp);let pe=(Ut=M.reasoning.startedAt)!=null?Ut:Date.now();M.reasoning.durationMs=Math.max(0,((G=M.reasoning.completedAt)!=null?G:Date.now())-pe)}M.streaming=M.reasoning.status!=="complete",p(M)}else if($e==="reason_complete"){let H=(ft=(Le=T(C,!1))!=null?Le:T(C,!0))!=null?ft:`reason-${c()}`,M=v.get(H);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=Y((yt=C.completedAt)!=null?yt:C.timestamp);let pe=(Ye=M.reasoning.startedAt)!=null?Ye:Date.now();M.reasoning.durationMs=Math.max(0,((ot=M.reasoning.completedAt)!=null?ot:Date.now())-pe),M.streaming=!1,p(M)}let P=_(C);P&&b.byStep.delete(P)}else if($e==="tool_start"){let H=(Wt=Se(C,!0))!=null?Wt:`tool-${c()}`,M=(Vt=C.toolName)!=null?Vt:C.name;if(ie(M)){oe.add(H);continue}let P=ae(H),pe=(de=P.toolCall)!=null?de:{id:H,status:"pending"};pe.name=M!=null?M:pe.name,pe.status="running",C.args!==void 0?pe.args=C.args:C.parameters!==void 0&&(pe.args=C.parameters),pe.startedAt=(Ee=pe.startedAt)!=null?Ee:Y((E=C.startedAt)!=null?E:C.timestamp),pe.completedAt=void 0,pe.durationMs=void 0,P.toolCall=pe,P.streaming=!0;let xe=C.agentContext;(xe||C.executionId)&&(P.agentMetadata={executionId:(ne=xe==null?void 0:xe.executionId)!=null?ne:C.executionId,iteration:(be=xe==null?void 0:xe.iteration)!=null?be:C.iteration}),p(P)}else if($e==="tool_chunk"||$e==="tool_delta"){let H=(Xe=(Ce=Se(C,!1))!=null?Ce:Se(C,!0))!=null?Xe:`tool-${c()}`;if(oe.has(H))continue;let M=ae(H),P=(ye=M.toolCall)!=null?ye:{id:H,status:"running"};P.startedAt=(De=P.startedAt)!=null?De:Y((Ie=C.startedAt)!=null?Ie:C.timestamp);let pe=(Ne=(Et=(nt=C.text)!=null?nt:C.delta)!=null?Et:C.message)!=null?Ne:"";pe&&(P.chunks=(Gn=P.chunks)!=null?Gn:[],P.chunks.push(String(pe))),P.status="running",M.toolCall=P,M.streaming=!0;let xe=C.agentContext;(xe||C.executionId)&&(M.agentMetadata=($n=M.agentMetadata)!=null?$n:{executionId:(xn=xe==null?void 0:xe.executionId)!=null?xn:C.executionId,iteration:(Yn=xe==null?void 0:xe.iteration)!=null?Yn:C.iteration}),p(M)}else if($e==="tool_complete"){let H=(Fn=(yr=Se(C,!1))!=null?yr:Se(C,!0))!=null?Fn:`tool-${c()}`;if(oe.has(H)){oe.delete(H);continue}let M=ae(H),P=(Mn=M.toolCall)!=null?Mn:{id:H,status:"running"};P.status="complete",C.result!==void 0&&(P.result=C.result),typeof C.duration=="number"&&(P.duration=C.duration),P.completedAt=Y((Ze=C.completedAt)!=null?Ze:C.timestamp);let pe=(Z=C.duration)!=null?Z:C.executionTime;if(typeof pe=="number")P.durationMs=pe;else{let Rt=(an=P.startedAt)!=null?an:Date.now();P.durationMs=Math.max(0,((rn=P.completedAt)!=null?rn:Date.now())-Rt)}M.toolCall=P,M.streaming=!1;let xe=C.agentContext;(xe||C.executionId)&&(M.agentMetadata=(ht=M.agentMetadata)!=null?ht:{executionId:(_r=xe==null?void 0:xe.executionId)!=null?_r:C.executionId,iteration:(vn=xe==null?void 0:xe.iteration)!=null?vn:C.iteration}),p(M);let lt=w(C);lt&&x.byCall.delete(lt)}else if($e==="step_chunk"||$e==="step_delta"){let H=C.stepType,M=C.executionType;if(H==="tool"||M==="context")continue;let P=I(),pe=(br=(jr=(kn=(ln=C.text)!=null?ln:C.delta)!=null?kn:C.content)!=null?jr:C.chunk)!=null?br:"";if(pe){let lt=((zr=J.get(P.id))!=null?zr:"")+pe;P.rawContent=lt,F.has(P.id)||F.set(P.id,this.createStreamParser());let Rt=F.get(P.id),Mt=lt.trim().startsWith("{")||lt.trim().startsWith("[");if(Mt&&J.set(P.id,lt),Rt.__isPlainTextParser===!0){P.content+=pe,J.delete(P.id),F.delete(P.id),P.rawContent=void 0,p(P);continue}let Ht=Rt.processChunk(lt);if(Ht instanceof Promise)Ht.then(ct=>{var It;let ut=typeof ct=="string"?ct:(It=ct==null?void 0:ct.text)!=null?It:null;if(ut!==null&&ut.trim()!==""){let gt=f;gt&&gt.id===P.id&&(gt.content=ut,p(gt))}else if(!Mt&&!lt.trim().startsWith("<")){let gt=f;gt&&gt.id===P.id&&(gt.content+=pe,J.delete(gt.id),F.delete(gt.id),gt.rawContent=void 0,p(gt))}}).catch(()=>{P.content+=pe,J.delete(P.id),F.delete(P.id),P.rawContent=void 0,p(P)});else{let ct=typeof Ht=="string"?Ht:(Xn=Ht==null?void 0:Ht.text)!=null?Xn:null;ct!==null&&ct.trim()!==""?(P.content=ct,p(P)):!Mt&&!lt.trim().startsWith("<")&&(P.content+=pe,J.delete(P.id),F.delete(P.id),P.rawContent=void 0,p(P))}}if(C.isComplete){let xe=(Zn=(Cn=C.result)==null?void 0:Cn.response)!=null?Zn:P.content;if(xe){let lt=J.get(P.id),Rt=lt!=null?lt:ge(xe);P.rawContent=Rt;let Mt=F.get(P.id),Nt=null,Ht=!1;if(Mt&&(Nt=Mt.getExtractedText(),Nt===null&&(Nt=zo(Rt)),Nt===null)){let ct=Mt.processChunk(Rt);ct instanceof Promise?(Ht=!0,ct.then(ut=>{var gt;let It=typeof ut=="string"?ut:(gt=ut==null?void 0:ut.text)!=null?gt:null;if(It!==null){let Ot=f;Ot&&Ot.id===P.id&&(Ot.content=It,Ot.streaming=!1,F.delete(Ot.id),J.delete(Ot.id),p(Ot))}})):Nt=typeof ct=="string"?ct:(Tt=ct==null?void 0:ct.text)!=null?Tt:null}if(!Ht){Nt!==null&&Nt.trim()!==""?P.content=Nt:J.has(P.id)||(P.content=ge(xe));let ct=F.get(P.id);if(ct){let ut=(wn=ct.close)==null?void 0:wn.call(ct);ut instanceof Promise&&ut.catch(()=>{}),F.delete(P.id)}J.delete(P.id),P.streaming=!1,p(P)}}}}else if($e==="step_complete"){let H=C.stepType,M=C.executionType;if(H==="tool"||M==="context")continue;let P=(qr=C.result)==null?void 0:qr.response,pe=I();if(P!=null){let xe=F.get(pe.id),lt=!1,Rt=!1;if(xe){let Mt=xe.getExtractedText(),Nt=J.get(pe.id),Ht=Nt!=null?Nt:ge(P);if(pe.rawContent=Ht,Mt!==null&&Mt.trim()!=="")pe.content=Mt,lt=!0;else{let ct=zo(Ht);if(ct!==null)pe.content=ct,lt=!0;else{let ut=xe.processChunk(Ht);if(ut instanceof Promise)Rt=!0,ut.then(It=>{var Ot;let gt=typeof It=="string"?It:(Ot=It==null?void 0:It.text)!=null?Ot:null;if(gt!==null&&gt.trim()!==""){let en=f;en&&en.id===pe.id&&(en.content=gt,en.streaming=!1,F.delete(en.id),J.delete(en.id),p(en))}else{let en=xe.getExtractedText(),dn=f;dn&&dn.id===pe.id&&(en!==null&&en.trim()!==""?dn.content=en:J.has(dn.id)||(dn.content=ge(P)),dn.streaming=!1,F.delete(dn.id),J.delete(dn.id),p(dn))}});else{let It=typeof ut=="string"?ut:(_n=ut==null?void 0:ut.text)!=null?_n:null;if(It!==null&&It.trim()!=="")pe.content=It,lt=!0;else{let gt=xe.getExtractedText();gt!==null&&gt.trim()!==""&&(pe.content=gt,lt=!0)}}}}}if(!Rt){if(!pe.rawContent){let Mt=J.get(pe.id);pe.rawContent=Mt!=null?Mt:ge(P)}if(!lt&&!J.has(pe.id)&&(pe.content=ge(P)),xe){let Mt=(Sn=xe.close)==null?void 0:Sn.call(xe);Mt instanceof Promise&&Mt.catch(()=>{})}F.delete(pe.id),J.delete(pe.id),pe.streaming=!1,p(pe)}}else F.delete(pe.id),J.delete(pe.id),pe.streaming=!1,p(pe)}else if($e==="flow_complete"){let H=(D=C.result)==null?void 0:D.response;if(H!=null){let M=I(),P=J.get(M.id),pe=P!=null?P:ge(H);M.rawContent=pe;let xe=ge(H),lt=F.get(M.id);if(lt){let Nt=zo(pe);if(Nt!==null)xe=Nt;else{let Ht=lt.processChunk(pe);Ht instanceof Promise&&Ht.then(ut=>{var gt;let It=typeof ut=="string"?ut:(gt=ut==null?void 0:ut.text)!=null?gt:null;if(It!==null){let Ot=f;Ot&&Ot.id===M.id&&(Ot.content=It,Ot.streaming=!1,p(Ot))}});let ct=lt.getExtractedText();ct!==null&&(xe=ct)}}F.delete(M.id),J.delete(M.id);let Rt=xe!==M.content,Mt=M.streaming!==!1;Rt&&(M.content=xe),M.streaming=!1,(Rt||Mt)&&p(M)}else if(f!==null){let M=f;F.delete(M.id),J.delete(M.id),M.streaming!==!1&&(M.streaming=!1,p(M))}t({type:"status",status:"idle"})}else if($e==="agent_start")me={executionId:C.executionId,agentId:(jn=C.agentId)!=null?jn:"virtual",agentName:(zn=C.agentName)!=null?zn:"",status:"running",currentIteration:0,maxTurns:(Ur=C.maxTurns)!=null?Ur:1,startedAt:Y(C.startedAt)};else if($e==="agent_iteration_start"){if(me&&(me.currentIteration=C.iteration),Ue==="separate"&&C.iteration>1){let H=f;H&&(H.streaming=!1,p(H),at.set(C.iteration-1,H),f=null)}}else if($e!=="agent_turn_start"){if($e==="agent_turn_delta"){if(C.contentType==="text"){let H=I();H.content+=(Ln=C.delta)!=null?Ln:"",H.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:me==null?void 0:me.agentName},p(H)}else if(C.contentType==="thinking"){let H=(Qn=C.turnId)!=null?Qn:`agent-think-${C.iteration}`,M=V(H);M.reasoning=(Vr=M.reasoning)!=null?Vr:{id:H,status:"streaming",chunks:[]},M.reasoning.chunks.push((In=C.delta)!=null?In:""),M.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},p(M)}else if(C.contentType==="tool_input"){let H=(Pn=C.toolCallId)!=null?Pn:x.lastId;if(H){let M=S.get(H);M!=null&&M.toolCall&&(M.toolCall.chunks=(xr=M.toolCall.chunks)!=null?xr:[],M.toolCall.chunks.push((vr=C.delta)!=null?vr:""),p(M))}}}else if($e==="agent_turn_complete"){let H=C.turnId;if(H){let M=v.get(H);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=Y(C.completedAt);let P=(So=M.reasoning.startedAt)!=null?So:Date.now();M.reasoning.durationMs=Math.max(0,((Ao=M.reasoning.completedAt)!=null?Ao:Date.now())-P),M.streaming=!1,p(M)}}}else if($e==="agent_tool_start"){let H=(Eo=C.toolCallId)!=null?Eo:`agent-tool-${c()}`;ue(w(C),H);let M=ae(H),P=(Jr=M.toolCall)!=null?Jr:{id:H,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};P.name=(ze=(Cr=C.toolName)!=null?Cr:C.name)!=null?ze:P.name,P.status="running",C.parameters!==void 0&&(P.args=C.parameters),P.startedAt=Y((Kr=C.startedAt)!=null?Kr:C.timestamp),M.toolCall=P,M.streaming=!0,M.agentMetadata={executionId:C.executionId,iteration:C.iteration},p(M)}else if($e==="agent_tool_delta"){let H=(cn=C.toolCallId)!=null?cn:x.lastId;if(H){let M=(Qt=S.get(H))!=null?Qt:ae(H);M.toolCall&&(M.toolCall.chunks=(To=M.toolCall.chunks)!=null?To:[],M.toolCall.chunks.push((Mo=C.delta)!=null?Mo:""),M.toolCall.status="running",M.streaming=!0,p(M))}}else if($e==="agent_tool_complete"){let H=(Gr=C.toolCallId)!=null?Gr:x.lastId;if(H){let M=(er=S.get(H))!=null?er:ae(H);if(M.toolCall){M.toolCall.status="complete",C.result!==void 0&&(M.toolCall.result=C.result),typeof C.executionTime=="number"&&(M.toolCall.durationMs=C.executionTime),M.toolCall.completedAt=Y((Wn=C.completedAt)!=null?Wn:C.timestamp),M.streaming=!1,p(M);let P=w(C);P&&x.byCall.delete(P)}}}else if($e!=="agent_iteration_complete"){if($e==="agent_reflection"||$e==="agent_reflect"){let H=`agent-reflection-${C.executionId}-${C.iteration}`,M={id:H,role:"assistant",content:(ko=C.reflection)!=null?ko:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:H,status:"complete",chunks:[(Lo=C.reflection)!=null?Lo:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(M)}else if($e==="agent_complete"){me&&(me.status=C.success?"complete":"error",me.completedAt=Y(C.completedAt),me.stopReason=C.stopReason);let H=f;H&&(H.streaming=!1,p(H)),t({type:"status",status:"idle"})}else if($e==="agent_error"){let H=typeof C.error=="string"?C.error:(Es=(Io=C.error)==null?void 0:Io.message)!=null?Es:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",H):t({type:"error",error:new Error(H)})}else if($e!=="agent_ping")if($e==="agent_approval_start"){let H=(tr=C.approvalId)!=null?tr:`approval-${c()}`,M={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:(nr=me==null?void 0:me.agentId)!=null?nr:"virtual",executionId:(wr=(wt=C.executionId)!=null?wt:me==null?void 0:me.executionId)!=null?wr:"",toolName:(Sr=C.toolName)!=null?Sr:"",toolType:C.toolType,description:(Xr=C.description)!=null?Xr:`Execute ${(Yr=C.toolName)!=null?Yr:"tool"}`,parameters:C.parameters}};p(M)}else if($e==="step_await"&&C.awaitReason==="approval_required"){let H=(Zr=C.approvalId)!=null?Zr:`approval-${c()}`,M={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:(Qr=me==null?void 0:me.agentId)!=null?Qr:"virtual",executionId:(on=(Yt=C.executionId)!=null?Yt:me==null?void 0:me.executionId)!=null?on:"",toolName:(Rn=C.toolName)!=null?Rn:"",toolType:C.toolType,description:(eo=C.description)!=null?eo:`Execute ${(Oe=C.toolName)!=null?Oe:"tool"}`,parameters:C.parameters}};p(M)}else if($e==="agent_approval_complete"){let H=C.approvalId;if(H){let P={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:(rr=C.decision)!=null?rr:"approved",agentId:(mn=me==null?void 0:me.agentId)!=null?mn:"virtual",executionId:(Ar=(Po=C.executionId)!=null?Po:me==null?void 0:me.executionId)!=null?Ar:"",toolName:(Er=C.toolName)!=null?Er:"",description:(or=C.description)!=null?or:"",resolvedAt:Date.now()}};p(P)}}else if($e==="artifact_start"||$e==="artifact_delta"||$e==="artifact_update"||$e==="artifact_complete"){if($e==="artifact_start"){let H=C.artifactType,M=String(C.id),P=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:M,artifactType:H,title:P,component:typeof C.component=="string"?C.component:void 0}),Ae.set(M,{markdown:"",title:P}),!te.has(M)){te.add(M);let pe={id:`artifact-ref-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:M,title:P,artifactType:H,status:"streaming"}})};z.set(M,pe),p(pe)}}else if($e==="artifact_delta"){let H=String(C.id),M=typeof C.delta=="string"?C.delta:String((qn=C.delta)!=null?qn:"");t({type:"artifact_delta",id:H,artDelta:M});let P=Ae.get(H);P&&(P.markdown+=M)}else if($e==="artifact_update"){let H=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:H,component:typeof C.component=="string"?C.component:void 0})}else if($e==="artifact_complete"){let H=String(C.id);t({type:"artifact_complete",id:H});let M=z.get(H);if(M){M.streaming=!1;try{let P=JSON.parse((Wo=M.rawContent)!=null?Wo:"{}");if(P.props){P.props.status="complete";let pe=Ae.get(H);pe!=null&&pe.markdown&&(P.props.markdown=pe.markdown)}M.rawContent=JSON.stringify(P)}catch{}Ae.delete(H),p(M),z.delete(H)}}}else if($e==="transcript_insert"){let H=C.message;if(!H||typeof H!="object")continue;let M=String((Ro=H.id)!=null?Ro:`msg-${c()}`),P=H.role,xe={id:M,role:P==="user"?"user":P==="system"?"system":"assistant",content:typeof H.content=="string"?H.content:"",rawContent:typeof H.rawContent=="string"?H.rawContent:void 0,createdAt:typeof H.createdAt=="string"?H.createdAt:new Date().toISOString(),streaming:H.streaming===!0,...typeof H.variant=="string"?{variant:H.variant}:{},sequence:c()};if(p(xe),xe.rawContent)try{let lt=JSON.parse(xe.rawContent),Rt=(fn=lt==null?void 0:lt.props)==null?void 0:fn.artifactId;typeof Rt=="string"&&te.add(Rt)}catch{}f=null,m.current=null,F.delete(M),J.delete(M)}else $e==="error"&&C.error&&t({type:"error",error:C.error instanceof Error?C.error:new Error(String(C.error))})}}}}}};function $l(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Ir(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function cr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Ko="[Image]";function Fl(e){return typeof e=="string"?[{type:"text",text:e}]:e}function _l(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function jl(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function zl(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function Go(e){return{type:"text",text:e}}function ql(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 Ul(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 Vl(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 Jl=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Rd=["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"],Bn=[...Jl,...Rd];function Hd(e){return Jl.includes(e)||e.startsWith("image/")}function Yo(e){return Hd(e.type)}async function Kl(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Yo(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 Gl(e,r=Bn,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 Bd(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Yl(e,r){let t=Bd(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 Xo=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 Zo=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 u=0;u<a.length;u++)i+=a[u]*a[u];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 Zo;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 u=`${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((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,S=x=>{v||(v=!0,clearTimeout(b),m(new Error(x)))},b=setTimeout(()=>S("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(b),f())},{once:!0}),this.ws.addEventListener("error",()=>{S("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!v){let k=x.code!==1006?` (code ${x.code})`:"";S("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 Xo(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 u=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});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),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 dr=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 pr(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(!dr.isSupported())throw new Error("Browser speech recognition not supported");return new dr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Qo(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return pr({type:"runtype",runtype:e.runtype});if(dr.isSupported())return pr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function lo(e){try{return Qo(e),!0}catch{return!1}}var Pr=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 lr(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 lo((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=pr(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 u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var u,p,f,m,v,S;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=c.transcript)!=null&&u.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&&((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=(S=this.pendingVoiceAssistantMessageId)!=null?S:(v=[...this.messages].reverse().find(x=>x.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 u,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,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,u;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:(u=r.browser)==null?void 0:u.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 lr(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:u}=r,f={id:a!=null?a:t==="user"?Ir():t==="assistant"?cr():`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},...u!==void 0&&{voiceProcessing:u}};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:u,streaming:p=!1}=n,m={id:d!=null?d:s==="user"?Ir():s==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...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,u,p,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=Ir(),o=cr(),a={id:s,role:"user",content:n||Ko,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 S=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!S){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,S||(v instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,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=cr();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 u={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(u),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,u;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 f=null;if(p instanceof Response){if(!p.ok){let m=await p.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${p.status}`)}f=p.body}else p instanceof ReadableStream&&(f=p);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(p){(u=(c=this.callbacks).onError)==null||u.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 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},En=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var Dd=kl(require("lucide"),1),he=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=Dd[s];return o?Nd(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 Nd(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,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),s.appendChild(d)}}}),s}var es={allowedTypes:Bn,maxFileSize:10*1024*1024,maxFiles:4};function Od(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $d(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,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 u=Gl(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await Kl(c),f=Yo(c)?URL.createObjectURL(c):null,m={id:Od(),file:c,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}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=Yo(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=$d(r.file.type),d=he(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=h("span");c.textContent=Yl(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=he("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 Ws={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}},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"}},Rs={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.gray.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.100",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.500",hover:"palette.colors.primary.600",focus:"palette.colors.primary.700",active:"palette.colors.primary.800",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.primary.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"}},Hs={button:{primary:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.text",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:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"semantic.colors.interactive.focus",ring:"semantic.colors.interactive.focus"}},launcher:{size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"semantic.colors.surface",border:"semantic.colors.border",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"semantic.colors.primary",iconForeground:"semantic.colors.textInverse",titleForeground:"semantic.colors.primary",subtitleForeground:"semantic.colors.textMuted",actionIconForeground:"semantic.colors.textMuted"},message:{user:{background:"semantic.colors.primary",text:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},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"}},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function co(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."))?co(e,n):n}function ts(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=co(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 Bs(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 Xl(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]=Xl(o,s):t[n]=s}return t}function Fd(e,r){return r?Xl(e,r):e}function Wr(e,r={}){var s,o,a,i,d,c,u,p,f,m,v,S,b;let t={palette:Ws,semantic:Rs,components:Hs},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,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.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,...(S=e==null?void 0:e.semantic)==null?void 0:S.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:Fd(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let x=Bs(n);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(k=>k.message).join(", ")}`)}if(r.plugins)for(let x of r.plugins)n=x.transform(n);return n}function ns(e){var v,S,b,x,k,_,w,I,$,T,V,ue,oe,z,te,Ae,ie,Se,ae,Y,ge,F,J,me,at,Ue,Ke,mt,Re,tt,Te,N,re,ee,q,ce,ke,Q,K,_e,it,Lt,qt,Ut,G,Le,ft,yt,Ye,ot,Wt,Vt,de,E,Ee,ne,be,Ce,Xe,ye,Ie,De,nt,Et,Ne,Gn,xn,Yn,$n,yr,Fn,Mn,Ze;let r=ts(e),t={};for(let[Z,an]of Object.entries(r)){let rn=Z.replace(/\./g,"-");t[`--persona-${rn}`]=an.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(S=t["--persona-semantic-colors-secondary"])!=null?S: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"]=(x=t["--persona-semantic-colors-surface"])!=null?x: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"]=(_=t["--persona-semantic-colors-container"])!=null?_: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"]=(I=t["--persona-semantic-colors-text-muted"])!=null?I:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=($=t["--persona-semantic-colors-text-inverse"])!=null?$: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"]=(V=t["--persona-semantic-colors-divider"])!=null?V:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(ue=t["--persona-components-voice-recording-indicator"])!=null?ue:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(oe=t["--persona-components-voice-recording-background"])!=null?oe:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(z=t["--persona-components-voice-processing-icon"])!=null?z:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ae=t["--persona-components-approval-requested-background"])!=null?Ae:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ie=t["--persona-components-approval-requested-border"])!=null?ie: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"]=(ae=t["--persona-components-approval-approve-background"])!=null?ae:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Y=t["--persona-components-approval-deny-background"])!=null?Y:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ge=t["--persona-components-attachment-image-background"])!=null?ge:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(F=t["--persona-components-attachment-image-border"])!=null?F:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(J=t["--persona-semantic-typography-fontFamily"])!=null?J:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(me=t["--persona-semantic-typography-fontSize"])!=null?me:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(at=t["--persona-semantic-typography-fontWeight"])!=null?at:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(Ue=t["--persona-semantic-typography-lineHeight"])!=null?Ue: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"]=(Ke=t["--persona-palette-radius-sm"])!=null?Ke:"0.125rem",t["--persona-radius-md"]=(mt=t["--persona-palette-radius-md"])!=null?mt:"0.375rem",t["--persona-radius-lg"]=(Re=t["--persona-palette-radius-lg"])!=null?Re:"0.5rem",t["--persona-radius-xl"]=(tt=t["--persona-palette-radius-xl"])!=null?tt:"0.75rem",t["--persona-launcher-radius"]=(N=(Te=t["--persona-components-launcher-borderRadius"])!=null?Te:t["--persona-palette-radius-full"])!=null?N:"9999px",t["--persona-button-radius"]=(ee=(re=t["--persona-components-button-primary-borderRadius"])!=null?re:t["--persona-palette-radius-full"])!=null?ee:"9999px",t["--persona-panel-radius"]=(ce=(q=t["--persona-components-panel-borderRadius"])!=null?q:t["--persona-radius-xl"])!=null?ce:"0.75rem",t["--persona-panel-border"]=(ke=t["--persona-components-panel-border"])!=null?ke:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(K=(Q=t["--persona-components-panel-shadow"])!=null?Q:t["--persona-palette-shadows-xl"])!=null?K:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(it=(_e=t["--persona-components-input-borderRadius"])!=null?_e:t["--persona-radius-lg"])!=null?it:"0.5rem",t["--persona-message-user-radius"]=(qt=(Lt=t["--persona-components-message-user-borderRadius"])!=null?Lt:t["--persona-radius-lg"])!=null?qt:"0.5rem",t["--persona-message-assistant-radius"]=(G=(Ut=t["--persona-components-message-assistant-borderRadius"])!=null?Ut:t["--persona-radius-lg"])!=null?G:"0.5rem",t["--persona-header-bg"]=(Le=t["--persona-components-header-background"])!=null?Le:t["--persona-surface"],t["--persona-header-border"]=(ft=t["--persona-components-header-border"])!=null?ft:t["--persona-divider"],t["--persona-header-icon-bg"]=(yt=t["--persona-components-header-iconBackground"])!=null?yt:t["--persona-primary"],t["--persona-header-icon-fg"]=(Ye=t["--persona-components-header-iconForeground"])!=null?Ye:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(ot=t["--persona-components-header-titleForeground"])!=null?ot:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Wt=t["--persona-components-header-subtitleForeground"])!=null?Wt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Vt=t["--persona-components-header-actionIconForeground"])!=null?Vt:t["--persona-muted"];let n=(de=e.components)==null?void 0:de.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-message-user-bg"]=(E=t["--persona-components-message-user-background"])!=null?E:t["--persona-accent"],t["--persona-message-user-text"]=(Ee=t["--persona-components-message-user-text"])!=null?Ee:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(ne=t["--persona-components-message-user-shadow"])!=null?ne:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(be=t["--persona-components-message-assistant-background"])!=null?be:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ce=t["--persona-components-message-assistant-text"])!=null?Ce:t["--persona-text"],t["--persona-message-assistant-border"]=(Xe=t["--persona-components-message-assistant-border"])!=null?Xe:t["--persona-border"],t["--persona-message-assistant-shadow"]=(ye=t["--persona-components-message-assistant-shadow"])!=null?ye:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(Ie=t["--persona-components-toolBubble-shadow"])!=null?Ie:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(De=t["--persona-components-reasoningBubble-shadow"])!=null?De:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(nt=t["--persona-components-composer-shadow"])!=null?nt:"none",t["--persona-md-inline-code-bg"]=(Et=t["--persona-components-markdown-inlineCode-background"])!=null?Et:t["--persona-container"],t["--persona-md-inline-code-color"]=(Ne=t["--persona-components-markdown-inlineCode-foreground"])!=null?Ne:t["--persona-text"],t["--persona-md-link-color"]=(xn=(Gn=t["--persona-components-markdown-link-foreground"])!=null?Gn:t["--persona-accent"])!=null?xn:"#3b82f6";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);let c=e.components,u=c==null?void 0:c.iconButton;u&&(u.background&&(t["--persona-icon-btn-bg"]=u.background),u.border&&(t["--persona-icon-btn-border"]=u.border),u.color&&(t["--persona-icon-btn-color"]=u.color),u.padding&&(t["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(t["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(t["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(t["--persona-icon-btn-active-border"]=u.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 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 Z=m.toolbar;Z.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=Z.iconHoverColor),Z.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=Z.iconHoverBackground),Z.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=Z.iconPadding),Z.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=Z.iconBorderRadius),Z.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=Z.iconBorder),Z.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=Z.toggleGroupGap),Z.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=Z.toggleBorderRadius),Z.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=Z.copyBackground),Z.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=Z.copyBorder),Z.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=Z.copyColor),Z.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=Z.copyBorderRadius),Z.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=Z.copyPadding),Z.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=Z.copyMenuBackground,t["--persona-dropdown-bg"]=(Yn=t["--persona-dropdown-bg"])!=null?Yn:Z.copyMenuBackground),Z.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=Z.copyMenuBorder,t["--persona-dropdown-border"]=($n=t["--persona-dropdown-border"])!=null?$n:Z.copyMenuBorder),Z.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=Z.copyMenuShadow,t["--persona-dropdown-shadow"]=(yr=t["--persona-dropdown-shadow"])!=null?yr:Z.copyMenuShadow),Z.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=Z.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Fn=t["--persona-dropdown-radius"])!=null?Fn:Z.copyMenuBorderRadius),Z.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Z.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Mn=t["--persona-dropdown-item-hover-bg"])!=null?Mn:Z.copyMenuItemHoverBackground),Z.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=Z.iconBackground),Z.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=Z.toolbarBorder)}if(m!=null&&m.tab){let Z=m.tab;Z.background&&(t["--persona-artifact-tab-bg"]=Z.background),Z.activeBackground&&(t["--persona-artifact-tab-active-bg"]=Z.activeBackground),Z.activeBorder&&(t["--persona-artifact-tab-active-border"]=Z.activeBorder),Z.borderRadius&&(t["--persona-artifact-tab-radius"]=Z.borderRadius),Z.textColor&&(t["--persona-artifact-tab-color"]=Z.textColor),Z.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=Z.hoverBackground),Z.listBackground&&(t["--persona-artifact-tab-list-bg"]=Z.listBackground),Z.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=Z.listBorderColor),Z.listPadding&&(t["--persona-artifact-tab-list-padding"]=Z.listPadding)}if(m!=null&&m.pane){let Z=m.pane;if(Z.toolbarBackground){let an=(Ze=co(e,Z.toolbarBackground))!=null?Ze:Z.toolbarBackground;t["--persona-artifact-toolbar-bg"]=an}}return t}var Zl={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 Ql=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function po(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];Ql(o)&&Ql(s)?t[n]=po(o,s):t[n]=s}return t}var _d={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}}},ec=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},uo=()=>{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"},jd=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":uo()},Ds=e=>jd(e),zd=e=>Wr(e),qd=e=>{var t;let r=Wr(void 0,{validate:!1});return Wr({...e,palette:{...r.palette,colors:{..._d.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},go=e=>{let r=Ds(e),t=ec(e==null?void 0:e.theme),n=ec(e==null?void 0:e.darkTheme);return r==="dark"?qd(po(t!=null?t:{},n!=null?n:{})):zd(t)},Ud=e=>ns(e),Vn=(e,r)=>{var o;let t=go(r),n=Ud(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)},rs=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(uo())});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(uo());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 tc=require("idiomorph"),nc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;tc.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 rc(e,r){var t,n,s,o,a,i,d,c,u,p,f,m,v,S,b,x,k,_;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,(u=(c=e.llmContent)==null?void 0:c.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(x=(b=(S=e.reasoning)==null?void 0:S.chunks)==null?void 0:b.length)!=null?x:0,(_=(k=e.contentParts)==null?void 0:k.length)!=null?_:0,r].join("\0")}function oc(){return new Map}function sc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function ac(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function ic(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}var Gt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var os={side:"right",width:"420px",animate:!0,reveal:"resize"},jt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},un=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:os.side,width:(s=r==null?void 0:r.width)!=null?s:os.width,animate:(o=r==null?void 0:r.animate)!=null?o:os.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:os.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 mo=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
6
+ `);a=(Be=st.pop())!=null?Be:"";for(let _e of st){let qe=_e.split(`
7
+ `),Lt="message",Tt="";for(let B of qe)B.startsWith("event:")?Lt=B.replace("event:","").trim():B.startsWith("data:")&&(Tt+=B.replace("data:","").trim());if(!Tt)continue;let C;try{C=JSON.parse(Tt)}catch(B){t({type:"error",error:B instanceof Error?B:new Error("Failed to parse chat stream payload")});continue}let Fe=Lt!=="message"?Lt:(rt=C.type)!=null?rt:"message";if((Me=this.onSSEEvent)==null||Me.call(this,Fe,C),this.parseSSEEvent){m.current=f;let B=await this.handleCustomSSEEvent(C,t,m,d,c,v);if(m.current&&m.current!==f&&(f=m.current),B)continue}if(Fe==="reason_start"){let B=(D=V(C,!0))!=null?D:`reason-${c()}`,w=ge(B);w.reasoning=(se=w.reasoning)!=null?se:{id:B,status:"streaming",chunks:[]},w.reasoning.startedAt=(z=w.reasoning.startedAt)!=null?z:ce((te=C.startedAt)!=null?te:C.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",d(w)}else if(Fe==="reason_delta"||Fe==="reason_chunk"){let B=(Le=(oe=V(C,!1))!=null?oe:V(C,!0))!=null?Le:`reason-${c()}`,w=ge(B);w.reasoning=(Z=w.reasoning)!=null?Z:{id:B,status:"streaming",chunks:[]},w.reasoning.startedAt=(ze=w.reasoning.startedAt)!=null?ze:ce((J=C.startedAt)!=null?J:C.timestamp);let $=(qt=(St=(Ue=C.reasoningText)!=null?Ue:C.text)!=null?St:C.delta)!=null?qt:"";if($&&C.hidden!==!0&&w.reasoning.chunks.push(String($)),w.reasoning.status=C.done?"complete":"streaming",C.done){w.reasoning.completedAt=ce((Ut=C.completedAt)!=null?Ut:C.timestamp);let ee=(K=w.reasoning.startedAt)!=null?K:Date.now();w.reasoning.durationMs=Math.max(0,((Ie=w.reasoning.completedAt)!=null?Ie:Date.now())-ee)}w.streaming=w.reasoning.status!=="complete",d(w)}else if(Fe==="reason_complete"){let B=(yt=(ft=V(C,!1))!=null?ft:V(C,!0))!=null?yt:`reason-${c()}`,w=A.get(B);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=ce((Ze=C.completedAt)!=null?Ze:C.timestamp);let ee=(it=w.reasoning.startedAt)!=null?it:Date.now();w.reasoning.durationMs=Math.max(0,((Wt=w.reasoning.completedAt)!=null?Wt:Date.now())-ee),w.streaming=!1,d(w)}let $=S(C);$&&x.byStep.delete($)}else if(Fe==="tool_start"){let B=(Vt=de(C,!0))!=null?Vt:`tool-${c()}`,w=(ue=C.toolName)!=null?ue:C.name;if(ke(w)){_.add(B);continue}let $=Y(B),ee=(T=$.toolCall)!=null?T:{id:B,status:"pending"};ee.name=w!=null?w:ee.name,ee.status="running",C.args!==void 0?ee.args=C.args:C.parameters!==void 0&&(ee.args=C.parameters),ee.startedAt=(re=ee.startedAt)!=null?re:ce((Ae=C.startedAt)!=null?Ae:C.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,$.toolCall=ee,$.streaming=!0;let Ee=C.agentContext;(Ee||C.executionId)&&($.agentMetadata={executionId:(ye=Ee==null?void 0:Ee.executionId)!=null?ye:C.executionId,iteration:(Ce=Ee==null?void 0:Ee.iteration)!=null?Ce:C.iteration}),d($)}else if(Fe==="tool_chunk"||Fe==="tool_delta"){let B=(he=(Qe=de(C,!1))!=null?Qe:de(C,!0))!=null?he:`tool-${c()}`;if(_.has(B))continue;let w=Y(B),$=(Pe=w.toolCall)!=null?Pe:{id:B,status:"running"};$.startedAt=(ot=$.startedAt)!=null?ot:ce((Ne=C.startedAt)!=null?Ne:C.timestamp);let ee=(Yn=(Oe=(At=C.text)!=null?At:C.delta)!=null?Oe:C.message)!=null?Yn:"";ee&&($.chunks=(xn=$.chunks)!=null?xn:[],$.chunks.push(String(ee))),$.status="running",w.toolCall=$,w.streaming=!0;let Ee=C.agentContext;(Ee||C.executionId)&&(w.agentMetadata=(xr=w.agentMetadata)!=null?xr:{executionId:(Xn=Ee==null?void 0:Ee.executionId)!=null?Xn:C.executionId,iteration:($n=Ee==null?void 0:Ee.iteration)!=null?$n:C.iteration}),d(w)}else if(Fe==="tool_complete"){let B=(Mn=(Fn=de(C,!1))!=null?Fn:de(C,!0))!=null?Mn:`tool-${c()}`;if(_.has(B)){_.delete(B);continue}let w=Y(B),$=(et=w.toolCall)!=null?et:{id:B,status:"running"};$.status="complete",C.result!==void 0&&($.result=C.result),typeof C.duration=="number"&&($.duration=C.duration),$.completedAt=ce((X=C.completedAt)!=null?X:C.timestamp);let ee=(an=C.duration)!=null?an:C.executionTime;if(typeof ee=="number")$.durationMs=ee;else{let Rt=(rn=$.startedAt)!=null?rn:Date.now();$.durationMs=Math.max(0,((jr=$.completedAt)!=null?jr:Date.now())-Rt)}w.toolCall=$,w.streaming=!1;let Ee=C.agentContext;(Ee||C.executionId)&&(w.agentMetadata=(ln=w.agentMetadata)!=null?ln:{executionId:(vn=Ee==null?void 0:Ee.executionId)!=null?vn:C.executionId,iteration:(ht=Ee==null?void 0:Ee.iteration)!=null?ht:C.iteration}),d(w);let ct=I(C);ct&&M.byCall.delete(ct)}else if(Fe==="step_chunk"||Fe==="step_delta"){let B=C.stepType,w=C.executionType;if(B==="tool"||w==="context")continue;let $=O(),ee=(qr=(vr=(zr=(kn=C.text)!=null?kn:C.delta)!=null?zr:C.content)!=null?vr:C.chunk)!=null?qr:"";if(ee){let ct=((Zn=ve.get($.id))!=null?Zn:"")+ee;$.rawContent=ct,G.has($.id)||G.set($.id,this.createStreamParser());let Rt=G.get($.id),Mt=ct.trim().startsWith("{")||ct.trim().startsWith("[");if(Mt&&ve.set($.id,ct),Rt.__isPlainTextParser===!0){$.content+=ee,ve.delete($.id),G.delete($.id),$.rawContent=void 0,d($);continue}let Ht=Rt.processChunk(ct);if(Ht instanceof Promise)Ht.then(dt=>{var It;let ut=typeof dt=="string"?dt:(It=dt==null?void 0:dt.text)!=null?It:null;if(ut!==null&&ut.trim()!==""){let gt=f;gt&&gt.id===$.id&&(gt.content=ut,d(gt))}else if(!Mt&&!ct.trim().startsWith("<")){let gt=f;gt&&gt.id===$.id&&(gt.content+=ee,ve.delete(gt.id),G.delete(gt.id),gt.rawContent=void 0,d(gt))}}).catch(()=>{$.content+=ee,ve.delete($.id),G.delete($.id),$.rawContent=void 0,d($)});else{let dt=typeof Ht=="string"?Ht:(Cn=Ht==null?void 0:Ht.text)!=null?Cn:null;dt!==null&&dt.trim()!==""?($.content=dt,d($)):!Mt&&!ct.trim().startsWith("<")&&($.content+=ee,ve.delete($.id),G.delete($.id),$.rawContent=void 0,d($))}}if(C.isComplete){let Ee=(Et=(Qn=C.result)==null?void 0:Qn.response)!=null?Et:$.content;if(Ee){let ct=ve.get($.id),Rt=ct!=null?ct:q(Ee);$.rawContent=Rt;let Mt=G.get($.id),Nt=null,Ht=!1;if(Mt&&(Nt=Mt.getExtractedText(),Nt===null&&(Nt=qo(Rt)),Nt===null)){let dt=Mt.processChunk(Rt);dt instanceof Promise?(Ht=!0,dt.then(ut=>{var gt;let It=typeof ut=="string"?ut:(gt=ut==null?void 0:ut.text)!=null?gt:null;if(It!==null){let Ot=f;Ot&&Ot.id===$.id&&(Ot.content=It,Ot.streaming=!1,G.delete(Ot.id),ve.delete(Ot.id),d(Ot))}})):Nt=typeof dt=="string"?dt:(wn=dt==null?void 0:dt.text)!=null?wn:null}if(!Ht){Nt!==null&&Nt.trim()!==""?$.content=Nt:ve.has($.id)||($.content=q(Ee));let dt=G.get($.id);if(dt){let ut=(Ur=dt.close)==null?void 0:Ur.call(dt);ut instanceof Promise&&ut.catch(()=>{}),G.delete($.id)}ve.delete($.id),$.streaming=!1,d($)}}}}else if(Fe==="step_complete"){let B=C.stepType,w=C.executionType;if(B==="tool"||w==="context")continue;let $=(_n=C.result)==null?void 0:_n.response,ee=O();if($!=null){let Ee=G.get(ee.id),ct=!1,Rt=!1;if(Ee){let Mt=Ee.getExtractedText(),Nt=ve.get(ee.id),Ht=Nt!=null?Nt:q($);if(ee.rawContent=Ht,Mt!==null&&Mt.trim()!=="")ee.content=Mt,ct=!0;else{let dt=qo(Ht);if(dt!==null)ee.content=dt,ct=!0;else{let ut=Ee.processChunk(Ht);if(ut instanceof Promise)Rt=!0,ut.then(It=>{var Ot;let gt=typeof It=="string"?It:(Ot=It==null?void 0:It.text)!=null?Ot:null;if(gt!==null&&gt.trim()!==""){let en=f;en&&en.id===ee.id&&(en.content=gt,en.streaming=!1,G.delete(en.id),ve.delete(en.id),d(en))}else{let en=Ee.getExtractedText(),dn=f;dn&&dn.id===ee.id&&(en!==null&&en.trim()!==""?dn.content=en:ve.has(dn.id)||(dn.content=q($)),dn.streaming=!1,G.delete(dn.id),ve.delete(dn.id),d(dn))}});else{let It=typeof ut=="string"?ut:(Sn=ut==null?void 0:ut.text)!=null?Sn:null;if(It!==null&&It.trim()!=="")ee.content=It,ct=!0;else{let gt=Ee.getExtractedText();gt!==null&&gt.trim()!==""&&(ee.content=gt,ct=!0)}}}}}if(!Rt){if(!ee.rawContent){let Mt=ve.get(ee.id);ee.rawContent=Mt!=null?Mt:q($)}if(!ct&&!ve.has(ee.id)&&(ee.content=q($)),Ee){let Mt=(H=Ee.close)==null?void 0:H.call(Ee);Mt instanceof Promise&&Mt.catch(()=>{})}G.delete(ee.id),ve.delete(ee.id),ee.streaming=!1,d(ee)}}else G.delete(ee.id),ve.delete(ee.id),ee.streaming=!1,d(ee)}else if(Fe==="flow_complete"){let B=(jn=C.result)==null?void 0:jn.response;if(B!=null){let w=O(),$=ve.get(w.id),ee=$!=null?$:q(B);w.rawContent=ee;let Ee=q(B),ct=G.get(w.id);if(ct){let Nt=qo(ee);if(Nt!==null)Ee=Nt;else{let Ht=ct.processChunk(ee);Ht instanceof Promise&&Ht.then(ut=>{var gt;let It=typeof ut=="string"?ut:(gt=ut==null?void 0:ut.text)!=null?gt:null;if(It!==null){let Ot=f;Ot&&Ot.id===w.id&&(Ot.content=It,Ot.streaming=!1,d(Ot))}});let dt=ct.getExtractedText();dt!==null&&(Ee=dt)}}G.delete(w.id),ve.delete(w.id);let Rt=Ee!==w.content,Mt=w.streaming!==!1;Rt&&(w.content=Ee),w.streaming=!1,(Rt||Mt)&&d(w)}else if(f!==null){let w=f;G.delete(w.id),ve.delete(w.id),w.streaming!==!1&&(w.streaming=!1,d(w))}t({type:"status",status:"idle"})}else if(Fe==="agent_start")xe={executionId:C.executionId,agentId:(zn=C.agentId)!=null?zn:"virtual",agentName:(Vr=C.agentName)!=null?Vr:"",status:"running",currentIteration:0,maxTurns:(Ln=C.maxTurns)!=null?Ln:1,startedAt:ce(C.startedAt)};else if(Fe==="agent_iteration_start"){if(xe&&(xe.currentIteration=C.iteration),Xe==="separate"&&C.iteration>1){let B=f;B&&(B.streaming=!1,d(B),Ke.set(C.iteration-1,B),f=null)}}else if(Fe!=="agent_turn_start"){if(Fe==="agent_turn_delta"){if(C.contentType==="text"){let B=O();B.content+=(er=C.delta)!=null?er:"",B.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:xe==null?void 0:xe.agentName},d(B)}else if(C.contentType==="thinking"){let B=(Jr=C.turnId)!=null?Jr:`agent-think-${C.iteration}`,w=ge(B);w.reasoning=(In=w.reasoning)!=null?In:{id:B,status:"streaming",chunks:[]},w.reasoning.chunks.push((Pn=C.delta)!=null?Pn:""),w.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},d(w)}else if(C.contentType==="tool_input"){let B=(Cr=C.toolCallId)!=null?Cr:M.lastId;if(B){let w=b.get(B);w!=null&&w.toolCall&&(w.toolCall.chunks=(wr=w.toolCall.chunks)!=null?wr:[],w.toolCall.chunks.push((Ao=C.delta)!=null?Ao:""),d(w))}}}else if(Fe==="agent_turn_complete"){let B=C.turnId;if(B){let w=A.get(B);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=ce(C.completedAt);let $=(Eo=w.reasoning.startedAt)!=null?Eo:Date.now();w.reasoning.durationMs=Math.max(0,((To=w.reasoning.completedAt)!=null?To:Date.now())-$),w.streaming=!1,d(w)}}}else if(Fe==="agent_tool_start"){let B=(Kr=C.toolCallId)!=null?Kr:`agent-tool-${c()}`;ie(I(C),B);let w=Y(B),$=(Sr=w.toolCall)!=null?Sr:{id:B,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};$.name=(Gr=(Ve=C.toolName)!=null?Ve:C.name)!=null?Gr:$.name,$.status="running",C.parameters!==void 0&&($.args=C.parameters),$.startedAt=ce((cn=C.startedAt)!=null?cn:C.timestamp),w.toolCall=$,w.streaming=!0,w.agentMetadata={executionId:C.executionId,iteration:C.iteration},d(w)}else if(Fe==="agent_tool_delta"){let B=(Qt=C.toolCallId)!=null?Qt:M.lastId;if(B){let w=(Mo=b.get(B))!=null?Mo:Y(B);w.toolCall&&(w.toolCall.chunks=(ko=w.toolCall.chunks)!=null?ko:[],w.toolCall.chunks.push((Yr=C.delta)!=null?Yr:""),w.toolCall.status="running",w.streaming=!0,d(w))}}else if(Fe==="agent_tool_complete"){let B=(tr=C.toolCallId)!=null?tr:M.lastId;if(B){let w=(Wn=b.get(B))!=null?Wn:Y(B);if(w.toolCall){w.toolCall.status="complete",C.result!==void 0&&(w.toolCall.result=C.result),typeof C.executionTime=="number"&&(w.toolCall.durationMs=C.executionTime),w.toolCall.completedAt=ce((Lo=C.completedAt)!=null?Lo:C.timestamp),w.streaming=!1,d(w);let $=I(C);$&&M.byCall.delete($)}}}else if(Fe!=="agent_iteration_complete"){if(Fe==="agent_reflection"||Fe==="agent_reflect"){let B=`agent-reflection-${C.executionId}-${C.iteration}`,w={id:B,role:"assistant",content:(Io=C.reflection)!=null?Io:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"complete",chunks:[(Po=C.reflection)!=null?Po:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};d(w)}else if(Fe==="agent_complete"){xe&&(xe.status=C.success?"complete":"error",xe.completedAt=ce(C.completedAt),xe.stopReason=C.stopReason);let B=f;B&&(B.streaming=!1,d(B)),t({type:"status",status:"idle"})}else if(Fe==="agent_error"){let B=typeof C.error=="string"?C.error:(nr=(Ts=C.error)==null?void 0:Ts.message)!=null?nr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",B):t({type:"error",error:new Error(B)})}else if(Fe!=="agent_ping")if(Fe==="agent_approval_start"){let B=(rr=C.approvalId)!=null?rr:`approval-${c()}`,w={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(vt=xe==null?void 0:xe.agentId)!=null?vt:"virtual",executionId:(Er=(Ar=C.executionId)!=null?Ar:xe==null?void 0:xe.executionId)!=null?Er:"",toolName:(Xr=C.toolName)!=null?Xr:"",toolType:C.toolType,description:(Qr=C.description)!=null?Qr:`Execute ${(Zr=C.toolName)!=null?Zr:"tool"}`,parameters:C.parameters}};d(w)}else if(Fe==="step_await"&&C.awaitReason==="approval_required"){let B=(eo=C.approvalId)!=null?eo:`approval-${c()}`,w={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(Yt=xe==null?void 0:xe.agentId)!=null?Yt:"virtual",executionId:(Rn=(on=C.executionId)!=null?on:xe==null?void 0:xe.executionId)!=null?Rn:"",toolName:($e=C.toolName)!=null?$e:"",toolType:C.toolType,description:(or=C.description)!=null?or:`Execute ${(to=C.toolName)!=null?to:"tool"}`,parameters:C.parameters}};d(w)}else if(Fe==="agent_approval_complete"){let B=C.approvalId;if(B){let $={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:(mn=C.decision)!=null?mn:"approved",agentId:(Wo=xe==null?void 0:xe.agentId)!=null?Wo:"virtual",executionId:(Mr=(Tr=C.executionId)!=null?Tr:xe==null?void 0:xe.executionId)!=null?Mr:"",toolName:(sr=C.toolName)!=null?sr:"",description:(qn=C.description)!=null?qn:"",resolvedAt:Date.now()}};d($)}}else if(Fe==="artifact_start"||Fe==="artifact_delta"||Fe==="artifact_update"||Fe==="artifact_complete"){if(Fe==="artifact_start"){let B=C.artifactType,w=String(C.id),$=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:w,artifactType:B,title:$,component:typeof C.component=="string"?C.component:void 0}),le.set(w,{markdown:"",title:$}),!Te.has(w)){Te.add(w);let ee={id:`artifact-ref-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:w,title:$,artifactType:B,status:"streaming"}})};ne.set(w,ee),d(ee)}}else if(Fe==="artifact_delta"){let B=String(C.id),w=typeof C.delta=="string"?C.delta:String((Ro=C.delta)!=null?Ro:"");t({type:"artifact_delta",id:B,artDelta:w});let $=le.get(B);$&&($.markdown+=w)}else if(Fe==="artifact_update"){let B=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:B,component:typeof C.component=="string"?C.component:void 0})}else if(Fe==="artifact_complete"){let B=String(C.id);t({type:"artifact_complete",id:B});let w=ne.get(B);if(w){w.streaming=!1;try{let $=JSON.parse((Ho=w.rawContent)!=null?Ho:"{}");if($.props){$.props.status="complete";let ee=le.get(B);ee!=null&&ee.markdown&&($.props.markdown=ee.markdown)}w.rawContent=JSON.stringify($)}catch{}le.delete(B),d(w),ne.delete(B)}}}else if(Fe==="transcript_insert"){let B=C.message;if(!B||typeof B!="object")continue;let w=String((fn=B.id)!=null?fn:`msg-${c()}`),$=B.role,Ee={id:w,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof B.content=="string"?B.content:"",rawContent:typeof B.rawContent=="string"?B.rawContent:void 0,createdAt:typeof B.createdAt=="string"?B.createdAt:new Date().toISOString(),streaming:B.streaming===!0,...typeof B.variant=="string"?{variant:B.variant}:{},sequence:c()};if(d(Ee),Ee.rawContent)try{let ct=JSON.parse(Ee.rawContent),Rt=(ar=ct==null?void 0:ct.props)==null?void 0:ar.artifactId;typeof Rt=="string"&&Te.add(Rt)}catch{}f=null,m.current=null,G.delete(w),ve.delete(w)}else Fe==="error"&&C.error&&t({type:"error",error:C.error instanceof Error?C.error:new Error(String(C.error))})}}}}}};function _l(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Pr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function pr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Go="[Image]";function jl(e){return typeof e=="string"?[{type:"text",text:e}]:e}function zl(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function ql(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Ul(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function Yo(e){return{type:"text",text:e}}function Vl(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 Jl(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 Kl(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 Gl=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Dd=["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"],Bn=[...Gl,...Dd];function Nd(e){return Gl.includes(e)||e.startsWith("image/")}function Xo(e){return Nd(e.type)}async function Yl(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Xo(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 Xl(e,r=Bn,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 Od(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Zl(e,r){let t=Od(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 Zo=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 p=new Uint8Array(this.remainder.length+r.length);p.set(this.remainder),p.set(r,this.remainder.length),t=p,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 p=this.activeSources.indexOf(a);p!==-1&&this.activeSources.splice(p,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 Qo=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 u=0;u<a.length;u++)i+=a[u]*a[u];let p=Math.sqrt(i/a.length);(n==="silence"?p<s.threshold:p>=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 lo=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 Qo;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,p=(n=this.config)==null?void 0:n.clientToken;if(!i||!p)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=${p}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,d=" 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,A=x=>{v||(v=!0,clearTimeout(b),m(new Error(x)))},b=setTimeout(()=>A("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(b),f())},{once:!0}),this.ws.addEventListener("error",()=>{A("WebSocket connection failed to "+u+"."+d)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!v){let M=x.code!==1006?` (code ${x.code})`:"";A("WebSocket connection failed"+M+"."+d)}},{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 Zo(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,p=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:p,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 u=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",d=new Blob(this.audioChunks,{type:u});await this.sendAudio(d),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),p=new Audio(i);this.currentAudio=p,this.currentAudioUrl=i,p.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===p&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await p.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 ur=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(p=>p[0]).map(p=>p.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(p=>p({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 gr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new lo(e.runtype);case"browser":if(!ur.isSupported())throw new Error("Browser speech recognition not supported");return new ur(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function es(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return gr({type:"runtype",runtype:e.runtype});if(ur.isSupported())return gr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function co(e){try{return es(e),!0}catch{return!1}}var Wr=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,p;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"),(p=(i=this.callbacks).onError)==null||p.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 co((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=gr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",p=(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 u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var u,d,f,m,v,A;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=c.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(d=c.transcript)!=null&&d.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=(A=this.pendingVoiceAssistantMessageId)!=null?A:(v=[...this.messages].reverse().find(x=>x.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:p,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var u,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(u=this.callbacks).onVoiceStatusChanged)==null||d.call(u,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,p,c,u;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:(p=r.runtype)==null?void 0:p.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(u=r.browser)==null?void 0:u.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:p,streaming:c=!1,voiceProcessing:u}=r,f={id:a!=null?a:t==="user"?Pr():t==="assistant"?pr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u}};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:p,createdAt:c,sequence:u,streaming:d=!1}=n,m={id:p!=null?p:s==="user"?Pr():s==="assistant"?pr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:d,...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,u,d,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=Pr(),o=pr(),a={id:s,role:"user",content:n||Go,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 p=[...this.messages];try{await this.client.dispatch({messages:p,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let A=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!A){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,A||(v instanceof Error?(d=(u=this.callbacks).onError)==null||d.call(u,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,p;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=pr();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 u={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(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(p=(i=this.callbacks).onError)==null||p.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 p,c,u;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 d;if(i?d=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):d=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let m=await d.json().catch(()=>null);throw new Error((p=m==null?void 0:m.error)!=null?p:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);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(d){(u=(c=this.callbacks).onError)==null||u.call(c,d instanceof Error?d:new Error(String(d)))}}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 p,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=(p=t.sequence)!=null?p: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},En=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var $d=Il(require("lucide"),1),fe=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=$d[s];return o?Fd(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 Fd(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 p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&p.setAttribute(c,String(u))}),s.appendChild(p)}}}),s}var ts={allowedTypes:Bn,maxFileSize:10*1024*1024,maxFiles:4};function _d(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function jd(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 mr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:ts.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:ts.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:ts.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:ts.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,p;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 u=Xl(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let d=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await Yl(c),f=Xo(c)?URL.createObjectURL(c):null,m={id:_d(),file:c,previewUrl:f,contentPart:d};this.attachments.push(m),this.renderPreview(m)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(p=(i=this.config).onAttachmentsChange)==null||p.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(p=>p.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=Xo(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=jd(r.file.type),p=fe(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let c=h("span");c.textContent=Zl(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=fe("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 Hs={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}},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"}},Bs={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.gray.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.100",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.500",hover:"palette.colors.primary.600",focus:"palette.colors.primary.700",active:"palette.colors.primary.800",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.primary.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"}},Ds={button:{primary:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.text",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:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"semantic.colors.interactive.focus",ring:"semantic.colors.interactive.focus"}},launcher:{size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"semantic.colors.surface",border:"semantic.colors.border",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"semantic.colors.primary",iconForeground:"semantic.colors.textInverse",titleForeground:"semantic.colors.primary",subtitleForeground:"semantic.colors.textMuted",actionIconForeground:"semantic.colors.textMuted"},message:{user:{background:"semantic.colors.primary",text:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},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"}},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function po(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."))?po(e,n):n}function ns(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let p=po(e,a);p!==void 0&&(r[i]={path:i,value:p,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 Ns(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 Ql(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]=Ql(o,s):t[n]=s}return t}function zd(e,r){return r?Ql(e,r):e}function Rr(e,r={}){var s,o,a,i,p,c,u,d,f,m,v,A,b;let t={palette:Hs,semantic:Bs,components:Ds},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,...(p=e==null?void 0:e.palette)==null?void 0:p.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,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(d=e==null?void 0:e.semantic)==null?void 0:d.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,...(A=e==null?void 0:e.semantic)==null?void 0:A.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:zd(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let x=Ns(n);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(M=>M.message).join(", ")}`)}if(r.plugins)for(let x of r.plugins)n=x.transform(n);return n}function rs(e){var v,A,b,x,M,F,S,I,O,k,V,ge,ie,_,ne,Te,le,ke,de,Y,ce,q,G,ve,xe,Ke,Xe,mt,Be,rt,Me,D,se,te,z,oe,Le,Z,J,ze,Ue,St,qt,Ut,K,Ie,ft,yt,Ze,it,Wt,Vt,ue,T,Ae,re,ye,Ce,Qe,he,Pe,Ne,ot,At,Oe,Yn,xn,Xn,$n,xr,Fn,Mn,et;let r=ns(e),t={};for(let[X,an]of Object.entries(r)){let rn=X.replace(/\./g,"-");t[`--persona-${rn}`]=an.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(A=t["--persona-semantic-colors-secondary"])!=null?A: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"]=(x=t["--persona-semantic-colors-surface"])!=null?x:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(M=t["--persona-semantic-colors-background"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(F=t["--persona-semantic-colors-container"])!=null?F:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(S=t["--persona-semantic-colors-text"])!=null?S:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(I=t["--persona-semantic-colors-text-muted"])!=null?I:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(O=t["--persona-semantic-colors-text-inverse"])!=null?O:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(k=t["--persona-semantic-colors-border"])!=null?k:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(V=t["--persona-semantic-colors-divider"])!=null?V: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"]=(ie=t["--persona-components-voice-recording-background"])!=null?ie: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"]=(le=t["--persona-components-approval-requested-border"])!=null?le:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ke=t["--persona-components-approval-requested-text"])!=null?ke:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(de=t["--persona-components-approval-approve-background"])!=null?de:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Y=t["--persona-components-approval-deny-background"])!=null?Y:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ce=t["--persona-components-attachment-image-background"])!=null?ce:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(q=t["--persona-components-attachment-image-border"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(G=t["--persona-semantic-typography-fontFamily"])!=null?G:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ve=t["--persona-semantic-typography-fontSize"])!=null?ve:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(xe=t["--persona-semantic-typography-fontWeight"])!=null?xe:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(Ke=t["--persona-semantic-typography-lineHeight"])!=null?Ke: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"]=(Xe=t["--persona-palette-radius-sm"])!=null?Xe:"0.125rem",t["--persona-radius-md"]=(mt=t["--persona-palette-radius-md"])!=null?mt:"0.375rem",t["--persona-radius-lg"]=(Be=t["--persona-palette-radius-lg"])!=null?Be:"0.5rem",t["--persona-radius-xl"]=(rt=t["--persona-palette-radius-xl"])!=null?rt:"0.75rem",t["--persona-launcher-radius"]=(D=(Me=t["--persona-components-launcher-borderRadius"])!=null?Me:t["--persona-palette-radius-full"])!=null?D:"9999px",t["--persona-button-radius"]=(te=(se=t["--persona-components-button-primary-borderRadius"])!=null?se:t["--persona-palette-radius-full"])!=null?te:"9999px",t["--persona-panel-radius"]=(oe=(z=t["--persona-components-panel-borderRadius"])!=null?z:t["--persona-radius-xl"])!=null?oe:"0.75rem",t["--persona-panel-border"]=(Le=t["--persona-components-panel-border"])!=null?Le:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(J=(Z=t["--persona-components-panel-shadow"])!=null?Z:t["--persona-palette-shadows-xl"])!=null?J:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ue=(ze=t["--persona-components-input-borderRadius"])!=null?ze:t["--persona-radius-lg"])!=null?Ue:"0.5rem",t["--persona-message-user-radius"]=(qt=(St=t["--persona-components-message-user-borderRadius"])!=null?St:t["--persona-radius-lg"])!=null?qt:"0.5rem",t["--persona-message-assistant-radius"]=(K=(Ut=t["--persona-components-message-assistant-borderRadius"])!=null?Ut:t["--persona-radius-lg"])!=null?K:"0.5rem",t["--persona-header-bg"]=(Ie=t["--persona-components-header-background"])!=null?Ie:t["--persona-surface"],t["--persona-header-border"]=(ft=t["--persona-components-header-border"])!=null?ft:t["--persona-divider"],t["--persona-header-icon-bg"]=(yt=t["--persona-components-header-iconBackground"])!=null?yt:t["--persona-primary"],t["--persona-header-icon-fg"]=(Ze=t["--persona-components-header-iconForeground"])!=null?Ze:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(it=t["--persona-components-header-titleForeground"])!=null?it:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Wt=t["--persona-components-header-subtitleForeground"])!=null?Wt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Vt=t["--persona-components-header-actionIconForeground"])!=null?Vt:t["--persona-muted"];let n=(ue=e.components)==null?void 0:ue.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-message-user-bg"]=(T=t["--persona-components-message-user-background"])!=null?T:t["--persona-accent"],t["--persona-message-user-text"]=(Ae=t["--persona-components-message-user-text"])!=null?Ae:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(re=t["--persona-components-message-user-shadow"])!=null?re:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(ye=t["--persona-components-message-assistant-background"])!=null?ye:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ce=t["--persona-components-message-assistant-text"])!=null?Ce:t["--persona-text"],t["--persona-message-assistant-border"]=(Qe=t["--persona-components-message-assistant-border"])!=null?Qe:t["--persona-border"],t["--persona-message-assistant-shadow"]=(he=t["--persona-components-message-assistant-shadow"])!=null?he:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(Pe=t["--persona-components-toolBubble-shadow"])!=null?Pe:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Ne=t["--persona-components-reasoningBubble-shadow"])!=null?Ne:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(ot=t["--persona-components-composer-shadow"])!=null?ot:"none",t["--persona-md-inline-code-bg"]=(At=t["--persona-components-markdown-inlineCode-background"])!=null?At:t["--persona-container"],t["--persona-md-inline-code-color"]=(Oe=t["--persona-components-markdown-inlineCode-foreground"])!=null?Oe:t["--persona-text"],t["--persona-md-link-color"]=(xn=(Yn=t["--persona-components-markdown-link-foreground"])!=null?Yn:t["--persona-accent"])!=null?xn:"#3b82f6";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 p=t["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(t["--persona-md-prose-font-family"]=p);let c=e.components,u=c==null?void 0:c.iconButton;u&&(u.background&&(t["--persona-icon-btn-bg"]=u.background),u.border&&(t["--persona-icon-btn-border"]=u.border),u.color&&(t["--persona-icon-btn-color"]=u.color),u.padding&&(t["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(t["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(t["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(t["--persona-icon-btn-active-border"]=u.activeBorder));let d=c==null?void 0:c.labelButton;d&&(d.background&&(t["--persona-label-btn-bg"]=d.background),d.border&&(t["--persona-label-btn-border"]=d.border),d.color&&(t["--persona-label-btn-color"]=d.color),d.padding&&(t["--persona-label-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-label-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-label-btn-hover-bg"]=d.hoverBackground),d.fontSize&&(t["--persona-label-btn-font-size"]=d.fontSize),d.gap&&(t["--persona-label-btn-gap"]=d.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 X=m.toolbar;X.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=X.iconHoverColor),X.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=X.iconHoverBackground),X.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=X.iconPadding),X.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=X.iconBorderRadius),X.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=X.iconBorder),X.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=X.toggleGroupGap),X.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=X.toggleBorderRadius),X.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=X.copyBackground),X.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=X.copyBorder),X.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=X.copyColor),X.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=X.copyBorderRadius),X.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=X.copyPadding),X.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=X.copyMenuBackground,t["--persona-dropdown-bg"]=(Xn=t["--persona-dropdown-bg"])!=null?Xn:X.copyMenuBackground),X.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=X.copyMenuBorder,t["--persona-dropdown-border"]=($n=t["--persona-dropdown-border"])!=null?$n:X.copyMenuBorder),X.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=X.copyMenuShadow,t["--persona-dropdown-shadow"]=(xr=t["--persona-dropdown-shadow"])!=null?xr:X.copyMenuShadow),X.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=X.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Fn=t["--persona-dropdown-radius"])!=null?Fn:X.copyMenuBorderRadius),X.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=X.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Mn=t["--persona-dropdown-item-hover-bg"])!=null?Mn:X.copyMenuItemHoverBackground),X.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=X.iconBackground),X.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=X.toolbarBorder)}if(m!=null&&m.tab){let X=m.tab;X.background&&(t["--persona-artifact-tab-bg"]=X.background),X.activeBackground&&(t["--persona-artifact-tab-active-bg"]=X.activeBackground),X.activeBorder&&(t["--persona-artifact-tab-active-border"]=X.activeBorder),X.borderRadius&&(t["--persona-artifact-tab-radius"]=X.borderRadius),X.textColor&&(t["--persona-artifact-tab-color"]=X.textColor),X.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=X.hoverBackground),X.listBackground&&(t["--persona-artifact-tab-list-bg"]=X.listBackground),X.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=X.listBorderColor),X.listPadding&&(t["--persona-artifact-tab-list-padding"]=X.listPadding)}if(m!=null&&m.pane){let X=m.pane;if(X.toolbarBackground){let an=(et=po(e,X.toolbarBackground))!=null?et:X.toolbarBackground;t["--persona-artifact-toolbar-bg"]=an}}return t}var ec={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 tc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function uo(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];tc(o)&&tc(s)?t[n]=uo(o,s):t[n]=s}return t}var qd={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}}},nc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},go=()=>{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"},Ud=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":go()},Os=e=>Ud(e),Vd=e=>Rr(e),Jd=e=>{var t;let r=Rr(void 0,{validate:!1});return Rr({...e,palette:{...r.palette,colors:{...qd.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},mo=e=>{let r=Os(e),t=nc(e==null?void 0:e.theme),n=nc(e==null?void 0:e.darkTheme);return r==="dark"?Jd(uo(t!=null?t:{},n!=null?n:{})):Vd(t)},Kd=e=>rs(e),Jn=(e,r)=>{var o;let t=mo(r),n=Kd(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)},os=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(go())});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(go());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 rc=require("idiomorph"),oc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;rc.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 sc(e,r){var t,n,s,o,a,i,p,c,u,d,f,m,v,A,b,x,M,F;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:"",(p=(i=e.rawContent)==null?void 0:i.length)!=null?p:0,(u=(c=e.llmContent)==null?void 0:c.length)!=null?u:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(x=(b=(A=e.reasoning)==null?void 0:A.chunks)==null?void 0:b.length)!=null?x:0,(F=(M=e.contentParts)==null?void 0:M.length)!=null?F:0,r].join("\0")}function ac(){return new Map}function ic(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function lc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function cc(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}var Gt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var ss={side:"right",width:"420px",animate:!0,reveal:"resize"},jt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},un=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 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 fo=(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,12 +12,12 @@
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 _,w,I,$,T,V,ue,oe,z,te,Ae,ie,Se;let a=(_=o.launcher)!=null?_:{},i=jt(o),d=t.querySelector("[data-role='launcher-title']");if(d){let ae=(w=a.title)!=null?w:"Chat Assistant";d.textContent=ae,d.setAttribute("title",ae)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let ae=(I=a.subtitle)!=null?I:"Get answers fast";c.textContent=ae,c.setAttribute("title",ae)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ae=($=a.agentIconSize)!=null?$:"40px";if(p.style.height=ae,p.style.width=ae,p.innerHTML="",a.agentIconName){let Y=parseFloat(ae)||24,ge=he(a.agentIconName,Y*.6,"var(--persona-text-inverse, #ffffff)",2);ge?(p.appendChild(ge),p.style.display=""):(p.textContent=(T=a.agentIconText)!=null?T:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(V=a.agentIconText)!=null?V:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let ae=(ue=a.agentIconSize)!=null?ue:"40px";f.style.height=ae,f.style.width=ae,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 ae=(oe=a.callToActionIconSize)!=null?oe:"32px";m.style.height=ae,m.style.width=ae,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary"));let Y=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Y=(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 ge=parseFloat(ae)||24,F=Math.max(ge-Y,8),J=he(a.callToActionIconName,F,"currentColor",2);J?m.appendChild(J):m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(te=a.callToActionIconText)!=null?te:"\u2197"}let v=a.position&&yn[a.position]?yn[a.position]:yn["bottom-right"],S="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 persona-z-50",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:`${S} ${v}`;let x="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=(Ae=a.border)!=null?Ae:x,t.style.boxShadow=(ie=a.shadow)!=null?ie: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=(Se=a.collapsedMaxWidth)!=null?Se:"",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, #2563eb))",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))"},Dn=e=>{var oe,z,te,Ae,ie,Se,ae,Y,ge,F,J,me,at,Ue,Ke,mt,Re,tt,Te,N,re,ee,q,ce,ke,Q,K,_e,it,Lt,qt,Ut;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=(oe=r==null?void 0:r.launcher)!=null?oe:{},o=(z=s.headerIconSize)!=null?z:"48px",a=(te=s.closeButtonSize)!=null?te:"32px",i=(Ae=s.closeButtonPlacement)!=null?Ae:"inline",d=(ie=s.headerIconHidden)!=null?ie:!1,c=s.headerIconName,u=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(u.style.height=o,u.style.width=o,u.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #2563eb))",u.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!d)if(c){let G=parseFloat(o)||24,Le=he(c,G*.6,"currentColor",1);Le?u.replaceChildren(Le):u.textContent=(ae=(Se=r==null?void 0:r.launcher)==null?void 0:Se.agentIconText)!=null?ae:"\u{1F4AC}"}else if((Y=r==null?void 0:r.launcher)!=null&&Y.iconUrl){let G=h("img");G.src=r.launcher.iconUrl,G.alt="",G.className="persona-rounded-xl persona-object-cover",G.style.height=o,G.style.width=o,u.replaceChildren(G)}else u.textContent=(F=(ge=r==null?void 0:r.launcher)==null?void 0:ge.agentIconText)!=null?F:"\u{1F4AC}";let p=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=(me=(J=r==null?void 0:r.launcher)==null?void 0:J.title)!=null?me:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=bn.subtitleColor,m.textContent=(Ue=(at=r==null?void 0:r.launcher)==null?void 0:at.subtitle)!=null?Ue:"Here to help you get answers fast",p.append(f,m),d?n.append(p):n.append(u,p);let v=(Ke=s.clearChat)!=null?Ke:{},S=(mt=v.enabled)!=null?mt:!0,b=(Re=v.placement)!=null?Re:"inline",x=null,k=null;if(S){let G=(tt=v.size)!=null?tt:"32px",Le=(Te=v.iconName)!=null?Te:"refresh-cw",ft=(N=v.iconColor)!=null?N:"",yt=(re=v.backgroundColor)!=null?re:"",Ye=(ee=v.borderWidth)!=null?ee:"",ot=(q=v.borderColor)!=null?q:"",Wt=(ce=v.borderRadius)!=null?ce:"",Vt=(ke=v.paddingX)!=null?ke:"",de=(Q=v.paddingY)!=null?Q:"",E=(K=v.tooltipText)!=null?K:"Clear chat",Ee=(_e=v.showTooltip)!=null?_e:!0;k=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"&&(k.style.right="48px"),x=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"),x.style.height=G,x.style.width=G,x.type="button",x.setAttribute("aria-label",E),x.style.color=ft||bn.actionIconColor;let ne=he(Le,"20px","currentColor",1);if(ne&&x.appendChild(ne),yt&&(x.style.backgroundColor=yt,x.classList.remove("hover:persona-bg-gray-100")),Ye||ot){let be=Ye||"0px",Ce=ot||"transparent";x.style.border=`${be} solid ${Ce}`,x.classList.remove("persona-border-none")}if(Wt&&(x.style.borderRadius=Wt,x.classList.remove("persona-rounded-full")),Vt?(x.style.paddingLeft=Vt,x.style.paddingRight=Vt):(x.style.paddingLeft="",x.style.paddingRight=""),de?(x.style.paddingTop=de,x.style.paddingBottom=de):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),Ee&&E&&x&&k){let be=null,Ce=()=>{if(be||!x)return;let ye=x.ownerDocument,Ie=ye.body;if(!Ie)return;be=En(ye,"div","persona-clear-chat-tooltip"),be.textContent=E;let De=En(ye,"div");De.className="persona-clear-chat-tooltip-arrow",be.appendChild(De);let nt=x.getBoundingClientRect();be.style.position="fixed",be.style.left=`${nt.left+nt.width/2}px`,be.style.top=`${nt.top-8}px`,be.style.transform="translate(-50%, -100%)",Ie.appendChild(be)},Xe=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};k.addEventListener("mouseenter",Ce),k.addEventListener("mouseleave",Xe),x.addEventListener("focus",Ce),x.addEventListener("blur",Xe),k._cleanupTooltip=()=>{Xe(),k&&(k.removeEventListener("mouseenter",Ce),k.removeEventListener("mouseleave",Xe)),x&&(x.removeEventListener("focus",Ce),x.removeEventListener("blur",Xe))}}b==="inline"&&n.appendChild(k)}let _=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":S&&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 I=(it=s.closeButtonTooltipText)!=null?it:"Close chat",$=(Lt=s.closeButtonShowTooltip)!=null?Lt:!0;w.setAttribute("aria-label",I),w.style.display=t?"":"none";let T=(qt=s.closeButtonIconName)!=null?qt:"x",V=(Ut=s.closeButtonIconText)!=null?Ut:"\xD7";w.style.color=s.closeButtonColor||bn.actionIconColor;let ue=he(T,"20px","currentColor",1);if(ue?w.appendChild(ue):w.textContent=V,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 G=s.closeButtonBorderWidth||"0px",Le=s.closeButtonBorderColor||"transparent";w.style.border=`${G} 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=""),_.appendChild(w),$&&I){let G=null,Le=()=>{if(G)return;let yt=w.ownerDocument,Ye=yt.body;if(!Ye)return;G=En(yt,"div","persona-clear-chat-tooltip"),G.textContent=I;let ot=En(yt,"div");ot.className="persona-clear-chat-tooltip-arrow",G.appendChild(ot);let Wt=w.getBoundingClientRect();G.style.position="fixed",G.style.left=`${Wt.left+Wt.width/2}px`,G.style.top=`${Wt.top-8}px`,G.style.transform="translate(-50%, -100%)",Ye.appendChild(G)},ft=()=>{G&&G.parentNode&&(G.parentNode.removeChild(G),G=null)};_.addEventListener("mouseenter",Le),_.addEventListener("mouseleave",ft),w.addEventListener("focus",Le),w.addEventListener("blur",ft),_._cleanupTooltip=()=>{ft(),_.removeEventListener("mouseenter",Le),_.removeEventListener("mouseleave",ft),w.removeEventListener("focus",Le),w.removeEventListener("blur",ft)}}return i!=="top-right"&&n.appendChild(_),{header:n,iconHolder:u,headerTitle:f,headerSubtitle:m,closeButton:w,closeButtonWrapper:_,clearChatButton:x,clearChatButtonWrapper:k}},gr=(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 Jn(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="10000"):(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=he(m.icon,16,"currentColor",1.5);b&&v.appendChild(b)}let S=document.createElement("span");S.textContent=m.label,v.appendChild(S),v.addEventListener("click",b=>{b.stopPropagation(),u(),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)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?c():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:u,toggle:p,destroy:f}}function vt(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=he(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function fo(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 u=h("button",c);if(u.type="button",u.setAttribute("aria-label",t),r){let f=he(r,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function ho(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 u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of r){let p;u.icon?p=vt({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),n(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),n(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function c(u){a=u,d()}return{element:o,setSelected:c}}function ss(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 u=h("span","persona-combo-btn-label");u.textContent=r,c.appendChild(u);let p=he(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",c.appendChild(p)),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 S,b;c.style.backgroundColor=(S=d.background)!=null?S:"",c.style.borderColor=(b=d.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Jn({items:n,onSelect:S=>{c.setAttribute("aria-expanded","false"),s(S)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",S=>{S.stopPropagation();let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),c.addEventListener("keydown",S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),c.click())}),{element:c,setLabel:S=>{u.textContent=S,c.setAttribute("aria-label",S)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let S=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",S?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Ns=e=>{var n;let r=Dn({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 Vd(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=he(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=Jn({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Os=e=>{var k,_,w,I,$,T,V,ue,oe;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 d=s==null?void 0:s.titleMenu,c,u;if(d)c=ss({label:(_=a.title)!=null?_:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=bn.titleColor,u=(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"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=bn.titleColor,u.textContent=(I=a.title)!=null?I:"Chat Assistant",c.appendChild(u),Vd(c,s==null?void 0:s.trailingActions,($=s==null?void 0:s.onAction)!=null?$:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let te=s.onTitleClick;c.addEventListener("click",Ae=>{Ae.target.closest("button")||te()}),c.addEventListener("keydown",Ae=>{(Ae.key==="Enter"||Ae.key===" ")&&(Ae.preventDefault(),te())})}let z=s==null?void 0:s.titleRowHover;z&&(c.style.borderRadius=(T=z.borderRadius)!=null?T:"10px",c.style.padding=(V=z.padding)!=null?V:"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 te,Ae;c.style.backgroundColor=(te=z.background)!=null?te:"",c.style.borderColor=(Ae=z.border)!=null?Ae:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let p=(ue=a.closeButtonSize)!=null?ue:"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=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||bn.actionIconColor;let v=(oe=a.closeButtonIconName)!=null?oe:"x",S=he(v,"20px","currentColor",2);S?m.appendChild(S):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let b=h("div");b.style.display="none";let x=h("span");return x.style.display="none",{header:i,iconHolder:b,headerTitle:u,headerSubtitle:x,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},as={default:Ns,minimal:Os},$s=e=>{var r;return(r=as[e])!=null?r:as.default},Rr=(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}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=$s(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 Hr=e=>{var Re,tt,Te,N,re,ee,q,ce,ke,Q,K,_e,it,Lt,qt,Ut,G,Le,ft,yt,Ye,ot,Wt,Vt,de,E,Ee;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=(tt=(Re=r==null?void 0:r.copy)==null?void 0:Re.inputPlaceholder)!=null?tt:"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 ne=Math.min(o.scrollHeight,d);o.style.height=`${ne}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 u=(Te=r==null?void 0:r.sendButton)!=null?Te:{},p=(N=u.useIcon)!=null?N:!1,f=(re=u.iconText)!=null?re:"\u2191",m=u.iconName,v=(ee=u.tooltipText)!=null?ee:"Send message",S=(q=u.showTooltip)!=null?q:!1,b=(ce=u.size)!=null?ce:"40px",x=u.backgroundColor,k=u.textColor,_=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=b,w.style.height=b,w.style.minWidth=b,w.style.minHeight=b,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",m){let ne=parseFloat(b)||24,be=k&&typeof k=="string"&&k.trim()?k.trim():"currentColor",Ce=he(m,ne,be,2);Ce?(w.appendChild(Ce),w.style.color=be):(w.textContent=f,k?w.style.color=k:w.classList.add("persona-text-white"))}else w.textContent=f,k?w.style.color=k:w.classList.add("persona-text-white");x?w.style.backgroundColor=x:w.classList.add("persona-bg-persona-primary")}else w.textContent=(Q=(ke=r==null?void 0:r.copy)==null?void 0:ke.sendButtonLabel)!=null?Q:"Send",k?w.style.color=k:w.classList.add("persona-text-white");if(u.borderWidth&&(w.style.borderWidth=u.borderWidth,w.style.borderStyle="solid"),u.borderColor&&(w.style.borderColor=u.borderColor),u.paddingX?(w.style.paddingLeft=u.paddingX,w.style.paddingRight=u.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),u.paddingY?(w.style.paddingTop=u.paddingY,w.style.paddingBottom=u.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),S&&v){let ne=h("div","persona-send-button-tooltip");ne.textContent=v,_.appendChild(ne)}_.appendChild(w);let I=(K=r==null?void 0:r.voiceRecognition)!=null?K:{},$=I.enabled===!0,T=null,V=null,ue=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),oe=((_e=I.provider)==null?void 0:_e.type)==="runtype";if($&&(ue||oe)){V=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 ne=(it=I.iconName)!=null?it:"mic",be=(Lt=I.iconSize)!=null?Lt:b,Ce=parseFloat(be)||24,Xe=(qt=I.backgroundColor)!=null?qt:x,ye=(Ut=I.iconColor)!=null?Ut:k;T.style.width=be,T.style.height=be,T.style.minWidth=be,T.style.minHeight=be,T.style.fontSize="18px",T.style.lineHeight="1";let Ie=ye||"currentColor",De=he(ne,Ce,Ie,1.5);De?(T.appendChild(De),T.style.color=Ie):(T.textContent="\u{1F3A4}",T.style.color=Ie),Xe?T.style.backgroundColor=Xe:T.classList.add("persona-bg-persona-primary"),ye?T.style.color=ye:!ye&&!k&&T.classList.add("persona-text-white"),I.borderWidth&&(T.style.borderWidth=I.borderWidth,T.style.borderStyle="solid"),I.borderColor&&(T.style.borderColor=I.borderColor),I.paddingX&&(T.style.paddingLeft=I.paddingX,T.style.paddingRight=I.paddingX),I.paddingY&&(T.style.paddingTop=I.paddingY,T.style.paddingBottom=I.paddingY),V.appendChild(T);let nt=(G=I.tooltipText)!=null?G:"Start voice recognition";if(((Le=I.showTooltip)!=null?Le:!1)&&nt){let Ne=h("div","persona-send-button-tooltip");Ne.textContent=nt,V.appendChild(Ne)}}let te=(ft=r==null?void 0:r.attachments)!=null?ft:{},Ae=te.enabled===!0,ie=null,Se=null,ae=null,Y=null;if(Ae){Y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Y.style.display="none",ae=h("input"),ae.type="file",ae.accept=((yt=te.allowedTypes)!=null?yt:Bn).join(","),ae.multiple=((Ye=te.maxFiles)!=null?Ye:4)>1,ae.style.display="none",ae.setAttribute("aria-label","Attach files"),Se=h("div","persona-send-button-wrapper"),ie=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ie.type="button",ie.setAttribute("aria-label",(ot=te.buttonTooltipText)!=null?ot:"Attach file");let ne=(Wt=te.buttonIconName)!=null?Wt:"paperclip",be=b,Ce=parseFloat(be)||40,Xe=Math.round(Ce*.6);ie.style.width=be,ie.style.height=be,ie.style.minWidth=be,ie.style.minHeight=be,ie.style.fontSize="18px",ie.style.lineHeight="1",ie.style.backgroundColor="transparent",ie.style.color="var(--persona-primary, #111827)",ie.style.border="none",ie.style.borderRadius="6px",ie.style.transition="background-color 0.15s ease",ie.addEventListener("mouseenter",()=>{ie.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ie.addEventListener("mouseleave",()=>{ie.style.backgroundColor="transparent"});let ye=he(ne,Xe,"currentColor",1.5);ye?ie.appendChild(ye):ie.textContent="\u{1F4CE}",ie.addEventListener("click",nt=>{nt.preventDefault(),ae==null||ae.click()}),Se.appendChild(ie);let Ie=(Vt=te.buttonTooltipText)!=null?Vt:"Attach file",De=h("div","persona-send-button-tooltip");De.textContent=Ie,Se.appendChild(De)}s.addEventListener("click",ne=>{ne.target!==w&&ne.target!==_&&ne.target!==T&&ne.target!==V&&ne.target!==ie&&ne.target!==Se&&o.focus()}),Y&&(Y.style.gap="8px",s.append(Y)),ae&&s.append(ae),s.append(o);let ge=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),F=h("div","persona-flex persona-items-center persona-gap-2");Se&&F.append(Se);let J=h("div","persona-flex persona-items-center persona-gap-1");V&&J.append(V),J.append(_),ge.append(F,J),s.append(ge);let me=(de=r==null?void 0:r.statusIndicator)!=null?de:{},at=me.align==="left"?"persona-text-left":me.align==="center"?"persona-text-center":"persona-text-right",Ue=h("div",`persona-mt-2 ${at} persona-text-xs persona-text-persona-muted`);Ue.setAttribute("data-persona-composer-status","");let Ke=(E=me.visible)!=null?E:!0;Ue.style.display=Ke?"":"none";let mt=(Ee=me.idleText)!=null?Ee:"Online";if(me.idleLink){let ne=h("a");ne.href=me.idleLink,ne.target="_blank",ne.rel="noopener noreferrer",ne.textContent=mt,ne.style.color="inherit",ne.style.textDecoration="none",Ue.appendChild(ne)}else Ue.textContent=mt;return t.append(n,s,Ue),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:_,micButton:T,micButtonWrapper:V,statusText:Ue,attachmentButton:ie,attachmentButtonWrapper:Se,attachmentInput:ae,attachmentPreviewsContainer:Y,actionsRow:ge,leftActions:F,rightActions:J}};var lc=e=>{var c,u,p,f,m,v,S;let r=(u=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?u:!0;if(jt(e)){let b=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),x=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return b.appendChild(x),{wrapper:b,panel:x}}if(!r){let b=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),x=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),k=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?f:"100%";return b.style.width=k,x.style.width="100%",b.appendChild(x),{wrapper:b,panel:x}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&yn[n.position]?yn[n.position]:yn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-z-50 persona-transition`),a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(S=(v=e==null?void 0:e.launcher)==null?void 0:v.width)!=null?S:e==null?void 0:e.launcherWidth,d=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},cc=(e,r=!0)=>{var b,x,k,_,w,I,$,T,V;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=((x=e==null?void 0:e.layout)==null?void 0:x.showHeader)!==!1,o=n?Rr(e,n,{showClose:r}):Dn({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=jt(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=(_=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?_:"Hello \u{1F44B}";let u=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(I=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?I:"Ask anything about your account or products.",d.append(c,u);let p=h("div","persona-flex persona-flex-col persona-gap-3"),f=($=e==null?void 0:e.layout)==null?void 0:$.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((T=e==null?void 0:e.copy)==null?void 0:T.showWelcomeCard)!==!1?a.append(d,p):(a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3"),a.append(p));let v=Hr({config:e}),S=((V=e==null?void 0:e.layout)==null?void 0:V.showFooter)!==!1;return s?gr(t,o,e):(o.header.style.display="none",gr(t,o,e)),t.append(a),S||(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:u,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 Jd=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Kd=320,Gd=320,Yd=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Xd=(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 p;let c=h("img");c.alt=((p=i.alt)==null?void 0:p.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=`${Kd}px`,c.style.maxHeight=`${Gd}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 u=!1;s+=1,c.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{u=!0}),Jd(i.image)?(c.src=i.image,n.appendChild(c)):(u=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},mr=()=>{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-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",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},Fs=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:mr};if(r){let s=r(n);if(s!==null)return s}return mr()},Zd=(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},dc=(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},Qd=(e,r="bubble")=>{let t=["vanilla-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("vanilla-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("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("vanilla-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("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("vanilla-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},_s=(e,r,t)=>{var m,v,S,b,x,k;let n=(m=r.showCopy)!=null?m:!0,s=(v=r.showUpvote)!=null?v:!0,o=(S=r.showDownvote)!=null?S:!0;if(!n&&!s&&!o){let _=h("div");return _.style.display="none",_.id=`actions-${e.id}`,_.setAttribute("data-actions-for",e.id),_}let a=(b=r.visibility)!=null?b:"hover",i=(x=r.align)!=null?x:"right",d=(k=r.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(_,w,I)=>{let $=vt({icon:_,label:w,size:14,className:"persona-message-action-btn"});return $.setAttribute("data-action",I),$};return n&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Br=(e,r,t,n,s,o)=>{var oe,z,te,Ae,ie,Se,ae;let a=t!=null?t:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,u=(z=d==null?void 0:d.show)!=null?z:!1,p=(te=c==null?void 0:c.show)!=null?te:!1,f=(Ae=d==null?void 0:d.position)!=null?Ae:"left",m=(ie=c==null?void 0:c.position)!=null?ie:"below",v=Qd(e.role,i),S=h("div",v.join(" "));S.id=`bubble-${e.id}`,S.setAttribute("data-message-id",e.id),S.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(S.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",S.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(S.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=Yd(e),x=(ae=(Se=e.content)==null?void 0:Se.trim())!=null?ae:"",_=b.length>0&&x===Ko,w=document.createElement("div");w.classList.add("persona-message-content");let I=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=null;if(_?($=document.createElement("div"),$.innerHTML=I,$.style.display="none",w.appendChild($)):w.innerHTML=I,p&&m==="inline"&&e.createdAt){let Y=dc(e,c);Y.classList.add("persona-ml-2","persona-inline"),w.appendChild(Y)}if(b.length>0){let Y=Xd(b,!_&&!!x,()=>{_&&$&&($.style.display="")});Y?S.appendChild(Y):_&&$&&($.style.display="")}if(S.appendChild(w),p&&m==="below"&&e.createdAt){let Y=dc(e,c);Y.classList.add("persona-mt-1"),S.appendChild(Y)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Y=Fs("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Y&&S.appendChild(Y)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let Y=_s(e,n,s);S.appendChild(Y)}if(!u||e.role==="system")return S;let V=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ue=Zd(d,e.role);return f==="right"||f==="left"&&e.role==="user"?V.append(S,ue):V.append(ue,S),S.classList.remove("persona-max-w-[85%]"),S.classList.add("persona-max-w-[calc(85%-2.5rem)]"),V},pc=(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}):Br(e,r,t,n,s,o)};var Dr=new Set,uc=(e,r)=>{let t=Dr.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=he(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},js=e=>{let r=e.reasoning,t=h("div",["vanilla-message-bubble","vanilla-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=Dr.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=Dl(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let d=h("div","persona-flex persona-items-center"),u=he(n?"chevron-up":"chevron-down",16,"currentColor",2);u?d.appendChild(u):d.textContent=n?"Hide":"Show";let p=h("div","persona-flex persona-items-center persona-ml-auto");p.append(d),s.append(o,p);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 x=he(n?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var Nr=new Set,gc=(e,r,t)=>{var c;let n=Nr.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 u=s.toggleTextColor||s.headerTextColor||"currentColor",p=he(n?"chevron-up":"chevron-down",16,u,2);p?d.appendChild(p):d.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},zs=(e,r)=>{var S;let t=e.toolCall,n=(S=r==null?void 0:r.toolCall)!=null?S:{},s=h("div",["vanilla-message-bubble","vanilla-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=Nr.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=Nl(t),i.appendChild(d);let c=h("div","persona-flex persona-items-center"),u=n.toggleTextColor||n.headerTextColor||"currentColor",p=he(o?"chevron-up":"chevron-down",16,u,2);p?c.appendChild(p):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"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Arguments";let k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(k.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(k.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(k.style.color=n.codeBlockTextColor),k.textContent=ao(t.args),b.append(x,k),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Activity";let k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(k.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(k.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(k.style.color=n.codeBlockTextColor),k.textContent=t.chunks.join(`
16
- `),b.append(x,k),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Result";let k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(k.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(k.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(k.style.color=n.codeBlockTextColor),k.textContent=ao(t.result),b.append(x,k),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",x=he(o?"chevron-up":"chevron-down",16,b,2);x?c.appendChild(x):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var qs=(e,r)=>{var S,b,x,k,_,w,I,$,T,V,ue,oe;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-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=(S=n==null?void 0:n.backgroundColor)!=null?S:"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)":(x=n==null?void 0:n.titleColor)!=null?x:"currentColor",u=he(d,20,c,2);u&&i.appendChild(u);let p=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=(k=n==null?void 0:n.title)!=null?k:"Approval Required",f.appendChild(m),!s){let z=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");z.setAttribute("data-approval-status",t.status),t.status==="approved"?(z.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",z.style.color="var(--persona-palette-colors-success-700, #15803d)",z.textContent="Approved"):t.status==="denied"?(z.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",z.style.color="var(--persona-palette-colors-error-700, #b91c1c)",z.textContent="Denied"):t.status==="timeout"&&(z.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",z.style.color="var(--persona-palette-colors-warning-700, #b45309)",z.textContent="Timeout"),f.appendChild(z)}p.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,p.appendChild(v),t.parameters){let z=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&&(z.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(z.style.color=n.parameterTextColor),z.style.fontSize="0.75rem",z.style.lineHeight="1rem",z.textContent=ao(t.parameters),p.appendChild(z)}if(s){let z=h("div","persona-flex persona-gap-2 persona-mt-2");z.setAttribute("data-approval-buttons","true");let te=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");te.type="button",te.style.backgroundColor=(_=n==null?void 0:n.approveButtonColor)!=null?_:"var(--persona-approval-approve-bg, #22c55e)",te.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",te.setAttribute("data-approval-action","approve");let Ae=he("shield-check",14,(I=n==null?void 0:n.approveButtonTextColor)!=null?I:"#ffffff",2);Ae&&(Ae.style.marginRight="4px",te.appendChild(Ae));let ie=document.createTextNode(($=n==null?void 0:n.approveLabel)!=null?$:"Approve");te.appendChild(ie);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=(V=n==null?void 0:n.denyButtonTextColor)!=null?V:"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 ae=he("shield-x",14,(ue=n==null?void 0:n.denyButtonTextColor)!=null?ue:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",Se.appendChild(ae));let Y=document.createTextNode((oe=n==null?void 0:n.denyLabel)!=null?oe:"Deny");Se.appendChild(Y),z.append(te,Se),p.appendChild(z)}return a.append(i,p),o.appendChild(a),o};var mc=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 u=document.createDocumentFragment(),p=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-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");v.type="button",v.textContent=m,v.disabled=p,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))}),u.appendChild(v),r.push(v)}),e.appendChild(u)}}};var yo=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 bo=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 Or(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var ep={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, #dbeafe)",text:"var(--persona-palette-colors-primary-700, #1e40af)"},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)"}},tp={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},np=["flowName","stepName","reasoningText","text","name","tool","toolName"],rp=100;function op(e,r){let t={...ep,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return tp}function sp(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function ap(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 ip(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 lp(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 cp(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 dp(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 Us(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");Or(c,(f=n.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(p()),c;function p(){var te,Ae;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 S=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=he(d?"chevron-down":"chevron-right","14px","currentColor",2);b&&S.appendChild(b);let x=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(te=n.timestampFormat)!=null?te:"relative";x.textContent=k==="relative"?sp(e.timestamp,t):ap(e.timestamp);let _=null;n.showSequenceNumbers!==!1&&(_=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),_.textContent=String(r+1));let w=op(e.type,n.badgeColors),I=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");I.style.backgroundColor=w.bg,I.style.color=w.text,I.style.borderColor=w.text+"50",I.textContent=e.type;let $=(Ae=n.descriptionFields)!=null?Ae:np,T=ip(e.payload,$),V=null;T&&(V=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),V.textContent=T);let ue=h("div","persona-flex-1 persona-min-w-0"),oe=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"),z=he("clipboard","12px","currentColor",1.5);return z&&oe.appendChild(z),oe.addEventListener("click",async ie=>{ie.stopPropagation(),await lp(cp(e)),oe.innerHTML="";let Se=he("check","12px","currentColor",1.5);Se&&oe.appendChild(Se),setTimeout(()=>{oe.innerHTML="";let ae=he("clipboard","12px","currentColor",1.5);ae&&oe.appendChild(ae)},1500)}),v.appendChild(S),v.appendChild(x),_&&v.appendChild(_),v.appendChild(I),V&&v.appendChild(V),v.appendChild(ue),v.appendChild(oe),m.appendChild(v),d&&m.appendChild(dp(e,a,i)),m}}function fc(e){var c,u;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(u=(c=s==null?void 0:s.features)==null?void 0:c.eventStream)!=null?u:{},i=o.find(p=>p.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&s){let p=i.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>d().element,onClose:n});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=a.classNames,f=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Or(f,p==null?void 0:p.panel);let m=[],v="",S="",b=null,x=[],k={},_=0,w=!1,I=0,$=0,T=!1,V=null,ue=!1,oe=0,z=new Set,te=new Map,Ae="",ie="",Se=null,ae,Y,ge,F,J;function me(){let de=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),E=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");Or(E,p==null?void 0:p.headerBar);let Ee=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ee.textContent="Events",ae=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"),ae.textContent="0";let ne=h("div","persona-flex-1");Y=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 be=h("option","");be.value="",be.textContent="All events",Y.appendChild(be),ge=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"),ge.type="button",ge.title="Copy All";let Xe=he("clipboard-copy","12px","currentColor",1.5);Xe&&ge.appendChild(Xe);let ye=h("span","persona-text-xs");ye.textContent="Copy All",ge.appendChild(ye),E.appendChild(Ee),E.appendChild(ae),E.appendChild(ne),E.appendChild(Y),E.appendChild(ge);let Ie=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Or(Ie,p==null?void 0:p.searchBar);let De=he("search","14px","var(--persona-muted, #9ca3af)",1.5),nt=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");De&&nt.appendChild(De),F=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"),Or(F,p==null?void 0:p.searchInput),F.type="text",F.placeholder="Search event payloads...",J=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"),J.type="button",J.style.display="none";let Et=he("x","12px","currentColor",2);return Et&&J.appendChild(Et),Ie.appendChild(nt),Ie.appendChild(F),Ie.appendChild(J),de.appendChild(E),de.appendChild(Ie),de}let at,Ue=o.find(de=>de.renderEventStreamToolbar);if(Ue!=null&&Ue.renderEventStreamToolbar&&s){let de=Ue.renderEventStreamToolbar({config:s,defaultRenderer:()=>me(),eventCount:r.getSize(),filteredCount:0,onFilterChange:E=>{v=E,ke(),_e()},onSearchChange:E=>{S=E,ke(),_e()}});at=de!=null?de:me()}else at=me();let Ke=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");Ke.style.display="none";let mt=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Re=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Re.style.height="100%";let tt=h("div","persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-bg-persona-accent persona-text-white persona-text-xs persona-px-3 persona-py-1.5 persona-rounded-full persona-cursor-pointer persona-shadow-md persona-z-10 persona-flex persona-items-center persona-gap-1");Or(tt,p==null?void 0:p.scrollIndicator),tt.style.display="none";let Te=he("arrow-down","12px","currentColor",2);Te&&tt.appendChild(Te);let N=h("span","");tt.appendChild(N);let re=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");re.style.display="none",mt.appendChild(Re),mt.appendChild(re),mt.appendChild(tt),f.setAttribute("tabindex","0"),f.appendChild(at),f.appendChild(Ke),f.appendChild(mt);function ee(){let de=r.getAll(),E={};for(let ye of de)E[ye.type]=(E[ye.type]||0)+1;let Ee=Object.keys(E).sort(),ne=Ee.length!==x.length||!Ee.every((ye,Ie)=>ye===x[Ie]),be=!ne&&Ee.some(ye=>E[ye]!==k[ye]),Ce=de.length!==Object.values(k).reduce((ye,Ie)=>ye+Ie,0);if(!ne&&!be&&!Ce||(x=Ee,k=E,!Y))return;let Xe=Y.value;if(Y.options[0].textContent="All events",ne){for(;Y.options.length>1;)Y.remove(1);for(let ye of Ee){let Ie=h("option","");Ie.value=ye,Ie.textContent=`${ye} (${E[ye]||0})`,Y.appendChild(Ie)}Xe&&Ee.includes(Xe)?Y.value=Xe:Xe&&(Y.value="",v="")}else for(let ye=1;ye<Y.options.length;ye++){let Ie=Y.options[ye];Ie.textContent=`${Ie.value} (${E[Ie.value]||0})`}}function q(){let de=r.getAll();if(v&&(de=de.filter(E=>E.type===v)),S){let E=S.toLowerCase();de=de.filter(Ee=>Ee.type.toLowerCase().includes(E)||Ee.payload.toLowerCase().includes(E))}return de}function ce(){return v!==""||S!==""}function ke(){_=0,I=0,w=!1,tt.style.display="none"}function Q(de){z.has(de)?z.delete(de):z.add(de),Se=de;let E=Re.scrollTop,Ee=w;ue=!0,w=!0,_e(),Re.scrollTop=E,w=Ee,ue=!1}function K(){return Re.scrollHeight-Re.scrollTop-Re.clientHeight<=50}function _e(){$=Date.now(),T=!1,ee();let de=r.getEvictedCount();de>0?(Ke.textContent=`${de.toLocaleString()} older events truncated`,Ke.style.display=""):Ke.style.display="none",m=q();let E=m.length,Ee=r.getSize()>0;ae&&(ae.textContent=String(r.getSize())),E===0&&Ee&&ce()?(re.textContent=S?`No events matching '${S}'`:"No events matching filter",re.style.display="",Re.style.display="none"):(re.style.display="none",Re.style.display=""),ge&&(ge.title=ce()?`Copy Filtered (${E})`:"Copy All"),w&&E>_&&(I+=E-_,N.textContent=`${I} new event${I===1?"":"s"}`,tt.style.display=""),_=E;let ne=r.getAll(),be=ne.length>0?ne[0].timestamp:0,Ce=new Set(m.map(Ie=>Ie.id));for(let Ie of z)Ce.has(Ie)||z.delete(Ie);let Xe=v!==Ae||S!==ie,ye=te.size===0&&m.length>0;if(Xe||ye||m.length===0){Re.innerHTML="",te.clear();let Ie=document.createDocumentFragment();for(let De=0;De<m.length;De++){let nt=Us(m[De],De,be,a,z,Q,o,s);te.set(m[De].id,nt),Ie.appendChild(nt)}Re.appendChild(Ie),Ae=v,ie=S,Se=null}else{if(Se!==null){let De=te.get(Se);if(De&&De.parentNode===Re){let nt=m.findIndex(Et=>Et.id===Se);if(nt>=0){let Et=Us(m[nt],nt,be,a,z,Q,o,s);Re.insertBefore(Et,De),De.remove(),te.set(Se,Et)}}Se=null}let Ie=new Set(m.map(De=>De.id));for(let[De,nt]of te)Ie.has(De)||(nt.remove(),te.delete(De));for(let De=0;De<m.length;De++){let nt=m[De];if(!te.has(nt.id)){let Et=Us(nt,De,be,a,z,Q,o,s);te.set(nt.id,Et),Re.appendChild(Et)}}}w||(Re.scrollTop=Re.scrollHeight)}function it(){if(Date.now()-$>=rp){V!==null&&(cancelAnimationFrame(V),V=null),_e();return}T||(T=!0,V=requestAnimationFrame(()=>{V=null,_e()}))}let Lt=(de,E)=>{if(!ge)return;ge.innerHTML="";let Ee=he(de,"12px","currentColor",1.5);Ee&&ge.appendChild(Ee);let ne=h("span","persona-text-xs");ne.textContent="Copy All",ge.appendChild(ne),setTimeout(()=>{ge.innerHTML="";let be=he("clipboard-copy","12px","currentColor",1.5);be&&ge.appendChild(be);let Ce=h("span","persona-text-xs");Ce.textContent="Copy All",ge.appendChild(Ce),ge.disabled=!1},E)},qt=async()=>{if(ge){ge.disabled=!0;try{let de;ce()?de=m:t?(de=await t(),de.length===0&&(de=r.getAll())):de=r.getAll();let E=de.map(Ee=>{try{return JSON.parse(Ee.payload)}catch{return Ee.payload}});await navigator.clipboard.writeText(JSON.stringify(E,null,2)),Lt("check",1500)}catch{Lt("x",1500)}}},Ut=()=>{Y&&(v=Y.value,ke(),_e())},G=()=>{!F||!J||(J.style.display=F.value?"":"none",b&&clearTimeout(b),b=setTimeout(()=>{S=F.value,ke(),_e()},150))},Le=()=>{!F||!J||(F.value="",S="",J.style.display="none",b&&clearTimeout(b),ke(),_e())},ft=()=>{if(ue)return;let de=Re.scrollTop,E=de>oe;oe=de,K()&&E?(w=!1,I=0,tt.style.display="none"):K()||(w=!0)},yt=de=>{de.deltaY<0&&(w=!0)},Ye=()=>{Re.scrollTop=Re.scrollHeight,w=!1,I=0,tt.style.display="none"},ot=de=>{let E=de.target;if(!E||E.closest("button"))return;let Ee=E.closest("[data-event-id]");if(!Ee)return;let ne=Ee.getAttribute("data-event-id");ne&&Q(ne)},Wt=de=>{if((de.metaKey||de.ctrlKey)&&de.key==="f"){de.preventDefault(),F==null||F.focus(),F==null||F.select();return}de.key==="Escape"&&(F&&document.activeElement===F?(Le(),F.blur(),f.focus()):n&&n())};ge&&ge.addEventListener("click",qt),Y&&Y.addEventListener("change",Ut),F&&F.addEventListener("input",G),J&&J.addEventListener("click",Le),Re.addEventListener("scroll",ft),Re.addEventListener("wheel",yt,{passive:!0}),Re.addEventListener("click",ot),tt.addEventListener("click",Ye),f.addEventListener("keydown",Wt);function Vt(){b&&clearTimeout(b),V!==null&&(cancelAnimationFrame(V),V=null),T=!1,te.clear(),ge&&ge.removeEventListener("click",qt),Y&&Y.removeEventListener("change",Ut),F&&F.removeEventListener("input",G),J&&J.removeEventListener("click",Le),Re.removeEventListener("scroll",ft),Re.removeEventListener("wheel",yt),Re.removeEventListener("click",ot),tt.removeEventListener("click",Ye),f.removeEventListener("keydown",Wt)}return{element:f,update:it,destroy:Vt}}}function hc(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-bg, #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 u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.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 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, #3b82f6)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(c.append(u,p),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 yc=(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",u=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:r.config,defaultRenderer:()=>hc(e,r)});if(u)return u}return hc(e,r)};var Vs=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)})}},Nn=new Vs;Nn.register("PersonaArtifactCard",yc);function pp(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 bc(e,r){var mt,Re,tt,Te;let t=(Re=(mt=e.features)==null?void 0:mt.artifacts)==null?void 0:Re.layout,s=((tt=t==null?void 0:t.toolbarPreset)!=null?tt:"default")==="document",o=(Te=t==null?void 0:t.panePadding)==null?void 0:Te.trim(),a=e.markdown?ir(e.markdown):null,i=Lr(e.sanitize),d=N=>{let re=a?a(N):kr(N);return i?i(re):re},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,u=()=>{c==null||c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),z==null||z.hide()};c&&c.addEventListener("click",()=>{var N;u(),(N=r.onDismiss)==null||N.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 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 N;u(),(N=r.onDismiss)==null||N.call(r)});let S="rendered",b=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),x=s?vt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):vt({icon:"eye",label:"Rendered view"}),k=s?vt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):vt({icon:"code-2",label:"Source"}),_=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,I=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,$=t==null?void 0:t.documentToolbarCopyMenuItems,T=!!(I&&$&&$.length>0),V=null,ue,oe=null,z=null;if(s&&(w||I)&&!T){if(ue=w?fo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let N=he("chevron-down",14,"currentColor",2);N&&ue.appendChild(N)}}else s&&T?(V=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ue=w?fo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),oe=vt({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"}}),V.append(ue,oe)):s?ue=vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):ue=vt({icon:"copy",label:"Copy"});let te=s?vt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):vt({icon:"refresh-cw",label:"Refresh"}),Ae=s?vt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):vt({icon:"x",label:"Close"}),ie=()=>{var ce,ke,Q;let N=(ce=J.find(K=>K.id===me))!=null?ce:J[J.length-1],re=(ke=N==null?void 0:N.id)!=null?ke:null,ee=(N==null?void 0:N.artifactType)==="markdown"&&(Q=N.markdown)!=null?Q:"",q=N?JSON.stringify({component:N.component,props:N.props},null,2):"";return{markdown:ee,jsonPayload:q,id:re}},Se=async()=>{var ce;let{markdown:N,jsonPayload:re}=ie(),ee=(ce=J.find(ke=>ke.id===me))!=null?ce:J[J.length-1],q=(ee==null?void 0:ee.artifactType)==="markdown"?N:ee?re:"";try{await navigator.clipboard.writeText(q)}catch{}};if(ue.addEventListener("click",async()=>{let N=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(N&&T){let{markdown:re,jsonPayload:ee,id:q}=ie();try{await N({actionId:"primary",artifactId:q,markdown:re,jsonPayload:ee})}catch{}return}await Se()}),oe&&($!=null&&$.length)){let N=()=>{var ee;return(ee=p.closest("[data-persona-root]"))!=null?ee:document.body},re=()=>{z=Jn({items:$.map(ee=>({id:ee.id,label:ee.label})),onSelect:async ee=>{let{markdown:q,jsonPayload:ce,id:ke}=ie(),Q=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Q?await Q({actionId:ee,artifactId:ke,markdown:q,jsonPayload:ce}):ee==="markdown"||ee==="md"?await navigator.clipboard.writeText(q):ee==="json"||ee==="source"?await navigator.clipboard.writeText(ce):await navigator.clipboard.writeText(q||ce)}catch{}},anchor:V!=null?V:oe,position:"bottom-right",portal:N()})};p.isConnected?re():requestAnimationFrame(re),oe.addEventListener("click",ee=>{ee.stopPropagation(),z==null||z.toggle()})}te.addEventListener("click",async()=>{var N;try{await((N=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:N.call(t))}catch{}Ue()}),Ae.addEventListener("click",()=>{var N;u(),(N=r.onDismiss)==null||N.call(r)});let ae=()=>{s&&(x.setAttribute("aria-pressed",S==="rendered"?"true":"false"),k.setAttribute("aria-pressed",S==="source"?"true":"false"))};x.addEventListener("click",()=>{S="rendered",ae(),Ue()}),k.addEventListener("click",()=>{S="source",ae(),Ue()});let Y=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(x,k),V?_.append(V,te,Ae):_.append(ue,te,Ae),f.append(b,Y,_),ae()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ge=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"),F=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ge.style.paddingLeft=o,ge.style.paddingRight=o,F.style.padding=o),p.appendChild(f),p.appendChild(ge),p.appendChild(F);let J=[],me=null,at=!1,Ue=()=>{var q,ce,ke,Q;let N=s&&J.length<=1;ge.classList.toggle("persona-hidden",N),ge.replaceChildren();for(let K of J){let _e=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");_e.type="button",_e.textContent=K.title||K.id.slice(0,8),K.id===me&&_e.classList.add("persona-bg-persona-container","persona-border-persona-border"),_e.addEventListener("click",()=>r.onSelect(K.id)),ge.appendChild(_e)}F.replaceChildren();let re=me&&J.find(K=>K.id===me)||J[J.length-1];if(!re)return;if(s){let K=re.artifactType==="markdown"?"MD":(q=re.component)!=null?q:"Component",it=(re.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Y.textContent=`${it} \xB7 ${K}`}else m.textContent="Artifacts";if(re.artifactType==="markdown"){if(s&&S==="source"){let _e=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");_e.textContent=(ce=re.markdown)!=null?ce:"",F.appendChild(_e);return}let K=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");K.innerHTML=d((ke=re.markdown)!=null?ke:""),F.appendChild(K);return}let ee=re.component?Nn.get(re.component):void 0;if(ee){let _e={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let it=ee((Q=re.props)!=null?Q:{},_e);if(it){F.appendChild(it);return}}catch{}}F.appendChild(pp(re))},Ke=()=>{var re;let N=J.length>0;if(p.classList.toggle("persona-hidden",!N),c){let ee=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,ce=((re=ee==null?void 0:ee.classList.contains("persona-artifact-narrow-host"))!=null?re:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;N&&ce&&at?(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(N){var re,ee,q;J=N.artifacts,me=(q=(ee=N.selectedId)!=null?ee:(re=N.artifacts[N.artifacts.length-1])==null?void 0:re.id)!=null?q:null,J.length>0&&(at=!0),Ue(),Ke()},setMobileOpen(N){at=N,!N&&c?(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):Ke()}}}function gn(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 xc(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"),!gn(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 up(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 is(e,r){var d,c,u,p,f,m,v,S,b,x;if(!gn(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"),up(e),xc(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",(u=t==null?void 0:t.splitGap)!=null?u:"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",(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=(S=t==null?void 0:t.documentToolbarIconColor)==null?void 0:S.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=(x=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:x.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),xc(e,r)}var vc=["panel","seamless"];function ls(e,r){var i,d,c,u,p,f;for(let m of vc)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"),!gn(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=vc.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.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 m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Cc(e,r){var t,n,s;return!r||!gn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function gp(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 mp(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 fp(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function hp(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function wc(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 Sc(e,r,t,n,s,o){let a=gp(s,200),i=hp(r,t,n,200);i=Math.max(a,i);let d=mp(o);return d!==null&&(i=Math.min(i,d)),fp(e,a,i)}var Ac={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"}},Js=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,S,b;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(S=Ac[a])!=null?S:Ac.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 x=h("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,d.appendChild(x)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var $,T;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${r.id}-${a}-${x.name}`;let _=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");_.textContent=x.label,k.appendChild(_);let w=($=x.type)!=null?$:"text",I;w==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=w),I.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",I.id=`${r.id}-${a}-${x.name}`,I.name=x.name,I.placeholder=(T=x.placeholder)!=null?T:"",x.required&&(I.required=!0),k.appendChild(I),u.appendChild(k)});let p=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",p.appendChild(f),p.appendChild(m),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async x=>{var I,$;x.preventDefault();let k=(I=t.formEndpoint)!=null?I:"/form",_=new FormData(u),w={};_.forEach((T,V)=>{w[V]=T}),w.type=a,m.disabled=!0,f.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 V=await T.json();f.textContent=($=V.message)!=null?$:"Thanks! We'll be in touch soon.",V.success&&V.nextPrompt&&await n.sendMessage(String(V.nextPrompt))}catch(T){f.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Ks=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()}},xo=new Ks;var Ct={apiUrl:"http://localhost:43111/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}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",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:"1px solid #e5e7eb",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",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",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:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!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 Ec(e,r){if(!(!e&&!r))return e?r?po(e,r):e:r}function cs(e){var r,t,n,s,o,a,i,d,c,u,p,f,m,v,S,b,x,k,_,w,I;return e?{...Ct,...e,theme:Ec(Ct.theme,e.theme),darkTheme:Ec(Ct.darkTheme,e.darkTheme),launcher:{...Ct.launcher,...e.launcher,dock:{...(r=Ct.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=Ct.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ct.copy,...e.copy},sendButton:{...Ct.sendButton,...e.sendButton},statusIndicator:{...Ct.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ct.voiceRecognition,...e.voiceRecognition},features:(()=>{var ue,oe;let $=(ue=Ct.features)==null?void 0:ue.artifacts,T=(oe=e.features)==null?void 0:oe.artifacts,V=$===void 0&&T===void 0?void 0:{...$,...T,layout:{...$==null?void 0:$.layout,...T==null?void 0:T.layout}};return{...Ct.features,...e.features,...V!==void 0?{artifacts:V}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Ct.suggestionChips,suggestionChipsConfig:{...Ct.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ct.layout,...e.layout,header:{...(a=Ct.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ct.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(u=Ct.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(S=(v=Ct.layout)==null?void 0:v.messages)==null?void 0:S.timestamp,...(x=(b=e.layout)==null?void 0:b.messages)==null?void 0:x.timestamp}},slots:{...(k=Ct.layout)==null?void 0:k.slots,...(_=e.layout)==null?void 0:_.slots}},markdown:{...Ct.markdown,...e.markdown,options:{...(w=Ct.markdown)==null?void 0:w.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Ct.messageActions,...e.messageActions}}:Ct}var Tc=()=>{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 yp=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},bp=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=yp(e),t=bp(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}},Gs=e=>typeof e=="string"?e:e==null?"":String(e),fr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Gs(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Gs(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:Gs(t.text)}}},Mc=e=>Array.isArray(e)?e.map(r=>String(r)):[],Co=e=>{let r=new Set(Mc(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Mc(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,u)=>c||(u==null?void 0:u({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 u=()=>{e.emit("action:resubmit",d)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var xp=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}},vp=e=>e.map(r=>({...r,streaming:!1})),ds=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?xp(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?vp(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 $r=require("partial-json");function Cp(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function wp(e,r){if(!Cp(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 ps(){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,$r.parse)(t,$r.STR|$r.OBJ),o=wp(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function kc(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function us(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=Nn.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 Lc(){let e=ps();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function gs(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 ms(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 Sp=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function fs(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=Sp}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=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 S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=s,m.appendChild(S),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 x=[];for(let $=1;$<=5;$++){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",`${$} star${$>1?"s":""}: ${c[$-1]}`),T.title=c[$-1],T.dataset.rating=String($),T.innerHTML=`
15
+ `,t.addEventListener("click",r);let n=o=>{var F,S,I,O,k,V,ge,ie,_,ne,Te,le,ke;let a=(F=o.launcher)!=null?F:{},i=jt(o),p=t.querySelector("[data-role='launcher-title']");if(p){let de=(S=a.title)!=null?S:"Chat Assistant";p.textContent=de,p.setAttribute("title",de)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let de=(I=a.subtitle)!=null?I:"Get answers fast";c.textContent=de,c.setAttribute("title",de)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let de=(O=a.agentIconSize)!=null?O:"40px";if(d.style.height=de,d.style.width=de,d.innerHTML="",a.agentIconName){let Y=parseFloat(de)||24,ce=fe(a.agentIconName,Y*.6,"var(--persona-text-inverse, #ffffff)",2);ce?(d.appendChild(ce),d.style.display=""):(d.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(V=a.agentIconText)!=null?V:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let de=(ge=a.agentIconSize)!=null?ge:"40px";f.style.height=de,f.style.width=de,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 de=(ie=a.callToActionIconSize)!=null?ie:"32px";m.style.height=de,m.style.width=de,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary"));let Y=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Y=(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 ce=parseFloat(de)||24,q=Math.max(ce-Y,8),G=fe(a.callToActionIconName,q,"currentColor",2);G?m.appendChild(G):m.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(ne=a.callToActionIconText)!=null?ne:"\u2197"}let v=a.position&&yn[a.position]?yn[a.position]:yn["bottom-right"],A="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 persona-z-50",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:`${A} ${v}`;let x="1px solid var(--persona-border, #e5e7eb)",M="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=(Te=a.border)!=null?Te:x,t.style.boxShadow=(le=a.shadow)!=null?le:M,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=(ke=a.collapsedMaxWidth)!=null?ke:"",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, #2563eb))",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))"},Dn=e=>{var ie,_,ne,Te,le,ke,de,Y,ce,q,G,ve,xe,Ke,Xe,mt,Be,rt,Me,D,se,te,z,oe,Le,Z,J,ze,Ue,St,qt,Ut;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=(ie=r==null?void 0:r.launcher)!=null?ie:{},o=(_=s.headerIconSize)!=null?_:"48px",a=(ne=s.closeButtonSize)!=null?ne:"32px",i=(Te=s.closeButtonPlacement)!=null?Te:"inline",p=(le=s.headerIconHidden)!=null?le:!1,c=s.headerIconName,u=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(u.style.height=o,u.style.width=o,u.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #2563eb))",u.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!p)if(c){let K=parseFloat(o)||24,Ie=fe(c,K*.6,"currentColor",1);Ie?u.replaceChildren(Ie):u.textContent=(de=(ke=r==null?void 0:r.launcher)==null?void 0:ke.agentIconText)!=null?de:"\u{1F4AC}"}else if((Y=r==null?void 0:r.launcher)!=null&&Y.iconUrl){let K=h("img");K.src=r.launcher.iconUrl,K.alt="",K.className="persona-rounded-xl persona-object-cover",K.style.height=o,K.style.width=o,u.replaceChildren(K)}else u.textContent=(q=(ce=r==null?void 0:r.launcher)==null?void 0:ce.agentIconText)!=null?q:"\u{1F4AC}";let d=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=(ve=(G=r==null?void 0:r.launcher)==null?void 0:G.title)!=null?ve:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=bn.subtitleColor,m.textContent=(Ke=(xe=r==null?void 0:r.launcher)==null?void 0:xe.subtitle)!=null?Ke:"Here to help you get answers fast",d.append(f,m),p?n.append(d):n.append(u,d);let v=(Xe=s.clearChat)!=null?Xe:{},A=(mt=v.enabled)!=null?mt:!0,b=(Be=v.placement)!=null?Be:"inline",x=null,M=null;if(A){let K=(rt=v.size)!=null?rt:"32px",Ie=(Me=v.iconName)!=null?Me:"refresh-cw",ft=(D=v.iconColor)!=null?D:"",yt=(se=v.backgroundColor)!=null?se:"",Ze=(te=v.borderWidth)!=null?te:"",it=(z=v.borderColor)!=null?z:"",Wt=(oe=v.borderRadius)!=null?oe:"",Vt=(Le=v.paddingX)!=null?Le:"",ue=(Z=v.paddingY)!=null?Z:"",T=(J=v.tooltipText)!=null?J:"Clear chat",Ae=(ze=v.showTooltip)!=null?ze:!0;M=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"&&(M.style.right="48px"),x=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"),x.style.height=K,x.style.width=K,x.type="button",x.setAttribute("aria-label",T),x.style.color=ft||bn.actionIconColor;let re=fe(Ie,"20px","currentColor",1);if(re&&x.appendChild(re),yt&&(x.style.backgroundColor=yt,x.classList.remove("hover:persona-bg-gray-100")),Ze||it){let ye=Ze||"0px",Ce=it||"transparent";x.style.border=`${ye} solid ${Ce}`,x.classList.remove("persona-border-none")}if(Wt&&(x.style.borderRadius=Wt,x.classList.remove("persona-rounded-full")),Vt?(x.style.paddingLeft=Vt,x.style.paddingRight=Vt):(x.style.paddingLeft="",x.style.paddingRight=""),ue?(x.style.paddingTop=ue,x.style.paddingBottom=ue):(x.style.paddingTop="",x.style.paddingBottom=""),M.appendChild(x),Ae&&T&&x&&M){let ye=null,Ce=()=>{if(ye||!x)return;let he=x.ownerDocument,Pe=he.body;if(!Pe)return;ye=En(he,"div","persona-clear-chat-tooltip"),ye.textContent=T;let Ne=En(he,"div");Ne.className="persona-clear-chat-tooltip-arrow",ye.appendChild(Ne);let ot=x.getBoundingClientRect();ye.style.position="fixed",ye.style.left=`${ot.left+ot.width/2}px`,ye.style.top=`${ot.top-8}px`,ye.style.transform="translate(-50%, -100%)",Pe.appendChild(ye)},Qe=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};M.addEventListener("mouseenter",Ce),M.addEventListener("mouseleave",Qe),x.addEventListener("focus",Ce),x.addEventListener("blur",Qe),M._cleanupTooltip=()=>{Qe(),M&&(M.removeEventListener("mouseenter",Ce),M.removeEventListener("mouseleave",Qe)),x&&(x.removeEventListener("focus",Ce),x.removeEventListener("blur",Qe))}}b==="inline"&&n.appendChild(M)}let F=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":A&&b==="inline"?"":"persona-ml-auto"),S=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");S.style.height=a,S.style.width=a,S.type="button";let I=(Ue=s.closeButtonTooltipText)!=null?Ue:"Close chat",O=(St=s.closeButtonShowTooltip)!=null?St:!0;S.setAttribute("aria-label",I),S.style.display=t?"":"none";let k=(qt=s.closeButtonIconName)!=null?qt:"x",V=(Ut=s.closeButtonIconText)!=null?Ut:"\xD7";S.style.color=s.closeButtonColor||bn.actionIconColor;let ge=fe(k,"20px","currentColor",1);if(ge?S.appendChild(ge):S.textContent=V,s.closeButtonBackgroundColor?(S.style.backgroundColor=s.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let K=s.closeButtonBorderWidth||"0px",Ie=s.closeButtonBorderColor||"transparent";S.style.border=`${K} solid ${Ie}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(S.style.borderRadius=s.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(S.style.paddingLeft=s.closeButtonPaddingX,S.style.paddingRight=s.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),s.closeButtonPaddingY?(S.style.paddingTop=s.closeButtonPaddingY,S.style.paddingBottom=s.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom=""),F.appendChild(S),O&&I){let K=null,Ie=()=>{if(K)return;let yt=S.ownerDocument,Ze=yt.body;if(!Ze)return;K=En(yt,"div","persona-clear-chat-tooltip"),K.textContent=I;let it=En(yt,"div");it.className="persona-clear-chat-tooltip-arrow",K.appendChild(it);let Wt=S.getBoundingClientRect();K.style.position="fixed",K.style.left=`${Wt.left+Wt.width/2}px`,K.style.top=`${Wt.top-8}px`,K.style.transform="translate(-50%, -100%)",Ze.appendChild(K)},ft=()=>{K&&K.parentNode&&(K.parentNode.removeChild(K),K=null)};F.addEventListener("mouseenter",Ie),F.addEventListener("mouseleave",ft),S.addEventListener("focus",Ie),S.addEventListener("blur",ft),F._cleanupTooltip=()=>{ft(),F.removeEventListener("mouseenter",Ie),F.removeEventListener("mouseleave",ft),S.removeEventListener("focus",Ie),S.removeEventListener("blur",ft)}}return i!=="top-right"&&n.appendChild(F),{header:n,iconHolder:u,headerTitle:f,headerSubtitle:m,closeButton:S,closeButtonWrapper:F,clearChatButton:x,clearChatButtonWrapper:M}},fr=(e,r,t)=>{var a,i,p,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(p=n.clearChat)==null?void 0:p.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 Kn(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="10000"):(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=fe(m.icon,16,"currentColor",1.5);b&&v.appendChild(b)}let A=document.createElement("span");A.textContent=m.label,v.appendChild(A),v.addEventListener("click",b=>{b.stopPropagation(),u(),t(m.id)}),a.appendChild(v)}let i=null;function p(){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(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!n.contains(v.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function d(){a.classList.contains("persona-hidden")?c():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:u,toggle:d,destroy:f}}function bt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,p=h("button","persona-icon-btn"+(o?" "+o:""));p.type="button",p.setAttribute("aria-label",t),p.title=t;let c=fe(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&p.appendChild(c),a&&p.addEventListener("click",a),i)for(let[u,d]of Object.entries(i))p.setAttribute(u,d);return p}function ho(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:p}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let u=h("button",c);if(u.type="button",u.setAttribute("aria-label",t),r){let f=fe(r,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let d=h("span");if(d.textContent=t,u.appendChild(d),i&&u.addEventListener("click",i),p)for(let[f,m]of Object.entries(p))u.setAttribute(f,m);return u}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 p(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of r){let d;u.icon?d=bt({icon:u.icon,label:u.label,onClick:()=>{a=u.id,p(),n(u.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",u.label),d.title=u.label,d.textContent=u.label,d.addEventListener("click",()=>{a=u.id,p(),n(u.id)})),d.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:d}),o.appendChild(d)}function c(u){a=u,p()}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:p}=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 u=h("span","persona-combo-btn-label");u.textContent=r,c.appendChild(u);let d=fe(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),p&&(c.style.borderRadius=(m=p.borderRadius)!=null?m:"10px",c.style.padding=(v=p.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 A,b;c.style.backgroundColor=(A=p.background)!=null?A:"",c.style.borderColor=(b=p.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Kn({items:n,onSelect:A=>{c.setAttribute("aria-expanded","false"),s(A)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",A=>{A.stopPropagation();let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),c.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),c.click())}),{element:c,setLabel:A=>{u.textContent=A,c.setAttribute("aria-label",A)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let A=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",A?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var $s=e=>{var n;let r=Dn({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 Gd(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 p=fe(a.icon,14,"currentColor",2);p&&i.appendChild(p)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let p=h("div","persona-relative");p.appendChild(i);let c=Kn({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:p,position:"bottom-left"});p.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),e.appendChild(p)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Fs=e=>{var M,F,S,I,O,k,V,ge,ie;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(M=r==null?void 0:r.launcher)!=null?M:{},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 p=s==null?void 0:s.titleMenu,c,u;if(p)c=as({label:(F=a.title)!=null?F:"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=bn.titleColor,u=(S=c.querySelector(".persona-combo-btn-label"))!=null?S:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=bn.titleColor,u.textContent=(I=a.title)!=null?I:"Chat Assistant",c.appendChild(u),Gd(c,s==null?void 0:s.trailingActions,(O=s==null?void 0:s.onAction)!=null?O: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=(k=_.borderRadius)!=null?k:"10px",c.style.padding=(V=_.padding)!=null?V:"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 d=(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=d,m.style.width=d,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||bn.actionIconColor;let v=(ie=a.closeButtonIconName)!=null?ie:"x",A=fe(v,"20px","currentColor",2);A?m.appendChild(A):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let b=h("div");b.style.display="none";let x=h("span");return x.style.display="none",{header:i,iconHolder:b,headerTitle:u,headerSubtitle:x,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},is={default:$s,minimal:Fs},_s=e=>{var r;return(r=is[e])!=null?r:is.default},Hr=(e,r,t)=>{var a,i,p;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}),u=h("div");u.style.display="none";let d=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:u,headerTitle:d,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=_s(n)({config:e,showClose:(p=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?p:!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 Br=e=>{var Be,rt,Me,D,se,te,z,oe,Le,Z,J,ze,Ue,St,qt,Ut,K,Ie,ft,yt,Ze,it,Wt,Vt,ue,T,Ae;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=(rt=(Be=r==null?void 0:r.copy)==null?void 0:Be.inputPlaceholder)!=null?rt:"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 p=3*20;o.style.maxHeight=`${p}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let re=Math.min(o.scrollHeight,p);o.style.height=`${re}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 u=(Me=r==null?void 0:r.sendButton)!=null?Me:{},d=(D=u.useIcon)!=null?D:!1,f=(se=u.iconText)!=null?se:"\u2191",m=u.iconName,v=(te=u.tooltipText)!=null?te:"Send message",A=(z=u.showTooltip)!=null?z:!1,b=(oe=u.size)!=null?oe:"40px",x=u.backgroundColor,M=u.textColor,F=h("div","persona-send-button-wrapper"),S=h("button",d?"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(S.type="submit",S.setAttribute("data-persona-composer-submit",""),d){if(S.style.width=b,S.style.height=b,S.style.minWidth=b,S.style.minHeight=b,S.style.fontSize="18px",S.style.lineHeight="1",S.innerHTML="",m){let re=parseFloat(b)||24,ye=M&&typeof M=="string"&&M.trim()?M.trim():"currentColor",Ce=fe(m,re,ye,2);Ce?(S.appendChild(Ce),S.style.color=ye):(S.textContent=f,M?S.style.color=M:S.classList.add("persona-text-white"))}else S.textContent=f,M?S.style.color=M:S.classList.add("persona-text-white");x?S.style.backgroundColor=x:S.classList.add("persona-bg-persona-primary")}else S.textContent=(Z=(Le=r==null?void 0:r.copy)==null?void 0:Le.sendButtonLabel)!=null?Z:"Send",M?S.style.color=M:S.classList.add("persona-text-white");if(u.borderWidth&&(S.style.borderWidth=u.borderWidth,S.style.borderStyle="solid"),u.borderColor&&(S.style.borderColor=u.borderColor),u.paddingX?(S.style.paddingLeft=u.paddingX,S.style.paddingRight=u.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),u.paddingY?(S.style.paddingTop=u.paddingY,S.style.paddingBottom=u.paddingY):(S.style.paddingTop="",S.style.paddingBottom=""),A&&v){let re=h("div","persona-send-button-tooltip");re.textContent=v,F.appendChild(re)}F.appendChild(S);let I=(J=r==null?void 0:r.voiceRecognition)!=null?J:{},O=I.enabled===!0,k=null,V=null,ge=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ie=((ze=I.provider)==null?void 0:ze.type)==="runtype";if(O&&(ge||ie)){V=h("div","persona-send-button-wrapper"),k=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),k.type="button",k.setAttribute("data-persona-composer-mic",""),k.setAttribute("aria-label","Start voice recognition");let re=(Ue=I.iconName)!=null?Ue:"mic",ye=(St=I.iconSize)!=null?St:b,Ce=parseFloat(ye)||24,Qe=(qt=I.backgroundColor)!=null?qt:x,he=(Ut=I.iconColor)!=null?Ut:M;k.style.width=ye,k.style.height=ye,k.style.minWidth=ye,k.style.minHeight=ye,k.style.fontSize="18px",k.style.lineHeight="1";let Pe=he||"currentColor",Ne=fe(re,Ce,Pe,1.5);Ne?(k.appendChild(Ne),k.style.color=Pe):(k.textContent="\u{1F3A4}",k.style.color=Pe),Qe?k.style.backgroundColor=Qe:k.classList.add("persona-bg-persona-primary"),he?k.style.color=he:!he&&!M&&k.classList.add("persona-text-white"),I.borderWidth&&(k.style.borderWidth=I.borderWidth,k.style.borderStyle="solid"),I.borderColor&&(k.style.borderColor=I.borderColor),I.paddingX&&(k.style.paddingLeft=I.paddingX,k.style.paddingRight=I.paddingX),I.paddingY&&(k.style.paddingTop=I.paddingY,k.style.paddingBottom=I.paddingY),V.appendChild(k);let ot=(K=I.tooltipText)!=null?K:"Start voice recognition";if(((Ie=I.showTooltip)!=null?Ie:!1)&&ot){let Oe=h("div","persona-send-button-tooltip");Oe.textContent=ot,V.appendChild(Oe)}}let ne=(ft=r==null?void 0:r.attachments)!=null?ft:{},Te=ne.enabled===!0,le=null,ke=null,de=null,Y=null;if(Te){Y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Y.style.display="none",de=h("input"),de.type="file",de.accept=((yt=ne.allowedTypes)!=null?yt:Bn).join(","),de.multiple=((Ze=ne.maxFiles)!=null?Ze:4)>1,de.style.display="none",de.setAttribute("aria-label","Attach files"),ke=h("div","persona-send-button-wrapper"),le=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",(it=ne.buttonTooltipText)!=null?it:"Attach file");let re=(Wt=ne.buttonIconName)!=null?Wt:"paperclip",ye=b,Ce=parseFloat(ye)||40,Qe=Math.round(Ce*.6);le.style.width=ye,le.style.height=ye,le.style.minWidth=ye,le.style.minHeight=ye,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let he=fe(re,Qe,"currentColor",1.5);he?le.appendChild(he):le.textContent="\u{1F4CE}",le.addEventListener("click",ot=>{ot.preventDefault(),de==null||de.click()}),ke.appendChild(le);let Pe=(Vt=ne.buttonTooltipText)!=null?Vt:"Attach file",Ne=h("div","persona-send-button-tooltip");Ne.textContent=Pe,ke.appendChild(Ne)}s.addEventListener("click",re=>{re.target!==S&&re.target!==F&&re.target!==k&&re.target!==V&&re.target!==le&&re.target!==ke&&o.focus()}),Y&&(Y.style.gap="8px",s.append(Y)),de&&s.append(de),s.append(o);let ce=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),q=h("div","persona-flex persona-items-center persona-gap-2");ke&&q.append(ke);let G=h("div","persona-flex persona-items-center persona-gap-1");V&&G.append(V),G.append(F),ce.append(q,G),s.append(ce);let ve=(ue=r==null?void 0:r.statusIndicator)!=null?ue:{},xe=ve.align==="left"?"persona-text-left":ve.align==="center"?"persona-text-center":"persona-text-right",Ke=h("div",`persona-mt-2 ${xe} persona-text-xs persona-text-persona-muted`);Ke.setAttribute("data-persona-composer-status","");let Xe=(T=ve.visible)!=null?T:!0;Ke.style.display=Xe?"":"none";let mt=(Ae=ve.idleText)!=null?Ae:"Online";if(ve.idleLink){let re=h("a");re.href=ve.idleLink,re.target="_blank",re.rel="noopener noreferrer",re.textContent=mt,re.style.color="inherit",re.style.textDecoration="none",Ke.appendChild(re)}else Ke.textContent=mt;return t.append(n,s,Ke),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:S,sendButtonWrapper:F,micButton:k,micButtonWrapper:V,statusText:Ke,attachmentButton:le,attachmentButtonWrapper:ke,attachmentInput:de,attachmentPreviewsContainer:Y,actionsRow:ce,leftActions:q,rightActions:G}};var dc=e=>{var c,u,d,f,m,v,A;let r=(u=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?u:!0;if(jt(e)){let b=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),x=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return b.appendChild(x),{wrapper:b,panel:x}}if(!r){let b=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),x=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),M=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return b.style.width=M,x.style.width="100%",b.appendChild(x),{wrapper:b,panel:x}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&yn[n.position]?yn[n.position]:yn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-z-50 persona-transition`),a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(A=(v=e==null?void 0:e.launcher)==null?void 0:v.width)!=null?A:e==null?void 0:e.launcherWidth,p=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=p,a.style.maxWidth=p,o.appendChild(a),{wrapper:o,panel:a}},pc=(e,r=!0)=>{var b,x,M,F,S,I,O,k,V;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=((x=e==null?void 0:e.layout)==null?void 0:x.showHeader)!==!1,o=n?Hr(e,n,{showClose:r}):Dn({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=jt(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",p=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(F=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?F:"Hello \u{1F44B}";let u=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(I=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?I:"Ask anything about your account or products.",p.append(c,u);let d=h("div","persona-flex persona-flex-col persona-gap-3"),f=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;f&&(d.style.maxWidth=f,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),p.setAttribute("data-persona-intro-card",""),((k=e==null?void 0:e.copy)==null?void 0:k.showWelcomeCard)!==!1||(p.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(p,d);let v=Br({config:e}),A=((V=e==null?void 0:e.layout)==null?void 0:V.showFooter)!==!1;return s?fr(t,o,e):(o.header.style.display="none",fr(t,o,e)),t.append(a),A||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:d,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:u,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 Yd=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Xd=320,Zd=320,Qd=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),ep=(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,p)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${p+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Xd}px`,c.style.maxHeight=`${Zd}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 u=!1;s+=1,c.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{u=!0}),Yd(i.image)?(c.src=i.image,n.appendChild(c)):(u=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},hr=()=>{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-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",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},js=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:hr};if(r){let s=r(n);if(s!==null)return s}return hr()},tp=(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},uc=(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},np=(e,r="bubble")=>{let t=["vanilla-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("vanilla-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("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("vanilla-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("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("vanilla-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},zs=(e,r,t)=>{var m,v,A,b,x,M;let n=(m=r.showCopy)!=null?m:!0,s=(v=r.showUpvote)!=null?v:!0,o=(A=r.showDownvote)!=null?A:!0;if(!n&&!s&&!o){let F=h("div");return F.style.display="none",F.id=`actions-${e.id}`,F.setAttribute("data-actions-for",e.id),F}let a=(b=r.visibility)!=null?b:"hover",i=(x=r.align)!=null?x:"right",p=(M=r.layout)!=null?M:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[p],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=(F,S,I)=>{let O=bt({icon:F,label:S,size:14,className:"persona-message-action-btn"});return O.setAttribute("data-action",I),O};return n&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},Dr=(e,r,t,n,s,o)=>{var ie,_,ne,Te,le,ke,de;let a=t!=null?t:{},i=(ie=a.layout)!=null?ie:"bubble",p=a.avatar,c=a.timestamp,u=(_=p==null?void 0:p.show)!=null?_:!1,d=(ne=c==null?void 0:c.show)!=null?ne:!1,f=(Te=p==null?void 0:p.position)!=null?Te:"left",m=(le=c==null?void 0:c.position)!=null?le:"below",v=np(e.role,i),A=h("div",v.join(" "));A.id=`bubble-${e.id}`,A.setAttribute("data-message-id",e.id),A.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=Qd(e),x=(de=(ke=e.content)==null?void 0:ke.trim())!=null?de:"",F=b.length>0&&x===Go,S=document.createElement("div");S.classList.add("persona-message-content");let I=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=null;if(F?(O=document.createElement("div"),O.innerHTML=I,O.style.display="none",S.appendChild(O)):S.innerHTML=I,d&&m==="inline"&&e.createdAt){let Y=uc(e,c);Y.classList.add("persona-ml-2","persona-inline"),S.appendChild(Y)}if(b.length>0){let Y=ep(b,!F&&!!x,()=>{F&&O&&(O.style.display="")});Y?A.appendChild(Y):F&&O&&(O.style.display="")}if(A.appendChild(S),d&&m==="below"&&e.createdAt){let Y=uc(e,c);Y.classList.add("persona-mt-1"),A.appendChild(Y)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Y=js("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Y&&A.appendChild(Y)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let Y=zs(e,n,s);A.appendChild(Y)}if(!u||e.role==="system")return A;let V=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ge=tp(p,e.role);return f==="right"||f==="left"&&e.role==="user"?V.append(A,ge):V.append(ge,A),A.classList.remove("persona-max-w-[85%]"),A.classList.add("persona-max-w-[calc(85%-2.5rem)]"),V},gc=(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}):Dr(e,r,t,n,s,o)};var Nr=new Set,mc=(e,r)=>{let t=Nr.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 p=fe(t?"chevron-up":"chevron-down",16,"currentColor",2);p?a.appendChild(p):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},qs=e=>{let r=e.reasoning,t=h("div",["vanilla-message-bubble","vanilla-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=Nr.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=Ol(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let p=h("div","persona-flex persona-items-center"),u=fe(n?"chevron-up":"chevron-down",16,"currentColor",2);u?p.appendChild(u):p.textContent=n?"Hide":"Show";let d=h("div","persona-flex persona-items-center persona-ml-auto");d.append(p),s.append(o,d);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"),p.innerHTML="";let x=fe(n?"chevron-up":"chevron-down",16,"currentColor",2);x?p.appendChild(x):p.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var Or=new Set,fc=(e,r,t)=>{var c;let n=Or.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"),p=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(p){p.innerHTML="";let u=s.toggleTextColor||s.headerTextColor||"currentColor",d=fe(n?"chevron-up":"chevron-down",16,u,2);d?p.appendChild(d):p.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},Us=(e,r)=>{var A;let t=e.toolCall,n=(A=r==null?void 0:r.toolCall)!=null?A:{},s=h("div",["vanilla-message-bubble","vanilla-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=Or.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"),p=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(p.style.color=n.headerTextColor),p.textContent=$l(t),i.appendChild(p);let c=h("div","persona-flex persona-items-center"),u=n.toggleTextColor||n.headerTextColor||"currentColor",d=fe(o?"chevron-up":"chevron-down",16,u,2);d?c.appendChild(d):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"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Arguments";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=io(t.args),b.append(x,M),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Activity";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=t.chunks.join(`
16
+ `),b.append(x,M),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Result";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=io(t.result),b.append(x,M),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",x=fe(o?"chevron-up":"chevron-down",16,b,2);x?c.appendChild(x):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var Vs=(e,r)=>{var A,b,x,M,F,S,I,O,k,V,ge,ie;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-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=(A=n==null?void 0:n.backgroundColor)!=null?A:"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 p=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)":(x=n==null?void 0:n.titleColor)!=null?x:"currentColor",u=fe(p,20,c,2);u&&i.appendChild(u);let d=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=(M=n==null?void 0:n.title)!=null?M:"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(_)}d.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,d.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=io(t.parameters),d.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=(F=n==null?void 0:n.approveButtonColor)!=null?F:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(S=n==null?void 0:n.approveButtonTextColor)!=null?S:"#ffffff",ne.setAttribute("data-approval-action","approve");let Te=fe("shield-check",14,(I=n==null?void 0:n.approveButtonTextColor)!=null?I:"#ffffff",2);Te&&(Te.style.marginRight="4px",ne.appendChild(Te));let le=document.createTextNode((O=n==null?void 0:n.approveLabel)!=null?O:"Approve");ne.appendChild(le);let ke=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");ke.type="button",ke.style.backgroundColor=(k=n==null?void 0:n.denyButtonColor)!=null?k:"transparent",ke.style.color=(V=n==null?void 0:n.denyButtonTextColor)!=null?V:"var(--persona-feedback-error, #dc2626)",ke.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ke.setAttribute("data-approval-action","deny");let de=fe("shield-x",14,(ge=n==null?void 0:n.denyButtonTextColor)!=null?ge:"var(--persona-feedback-error, #dc2626)",2);de&&(de.style.marginRight="4px",ke.appendChild(de));let Y=document.createTextNode((ie=n==null?void 0:n.denyLabel)!=null?ie:"Deny");ke.appendChild(Y),_.append(ne,ke),d.appendChild(_)}return a.append(i,d),o.appendChild(a),o};var hc=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 u=document.createDocumentFragment(),d=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-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");v.type="button",v.textContent=m,v.disabled=d,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))}),u.appendChild(v),r.push(v)}),e.appendChild(u)}}};var bo=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 $r(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, #dbeafe)",text:"var(--persona-palette-colors-primary-700, #1e40af)"},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)"}},op={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},sp=["flowName","stepName","reasoningText","text","name","tool","toolName"],ap=100;function ip(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 op}function lp(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function cp(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 dp(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 pp(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 up(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 gp(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]"),p=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=n,i.appendChild(p),i}}function Js(e,r,t,n,s,o,a,i){var f;let p=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");$r(c,(f=n.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>d(),isExpanded:p,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(d()),c;function d(){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 A=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=fe(p?"chevron-down":"chevron-right","14px","currentColor",2);b&&A.appendChild(b);let x=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(ne=n.timestampFormat)!=null?ne:"relative";x.textContent=M==="relative"?lp(e.timestamp,t):cp(e.timestamp);let F=null;n.showSequenceNumbers!==!1&&(F=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),F.textContent=String(r+1));let S=ip(e.type,n.badgeColors),I=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");I.style.backgroundColor=S.bg,I.style.color=S.text,I.style.borderColor=S.text+"50",I.textContent=e.type;let O=(Te=n.descriptionFields)!=null?Te:sp,k=dp(e.payload,O),V=null;k&&(V=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),V.textContent=k);let ge=h("div","persona-flex-1 persona-min-w-0"),ie=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"),_=fe("clipboard","12px","currentColor",1.5);return _&&ie.appendChild(_),ie.addEventListener("click",async le=>{le.stopPropagation(),await pp(up(e)),ie.innerHTML="";let ke=fe("check","12px","currentColor",1.5);ke&&ie.appendChild(ke),setTimeout(()=>{ie.innerHTML="";let de=fe("clipboard","12px","currentColor",1.5);de&&ie.appendChild(de)},1500)}),v.appendChild(A),v.appendChild(x),F&&v.appendChild(F),v.appendChild(I),V&&v.appendChild(V),v.appendChild(ge),v.appendChild(ie),m.appendChild(v),p&&m.appendChild(gp(e,a,i)),m}}function yc(e){var c,u;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(u=(c=s==null?void 0:s.features)==null?void 0:c.eventStream)!=null?u:{},i=o.find(d=>d.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&s){let d=i.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>p().element,onClose:n});if(d)return{element:d,update:()=>{},destroy:()=>{}}}return p();function p(){let d=a.classNames,f=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");$r(f,d==null?void 0:d.panel);let m=[],v="",A="",b=null,x=[],M={},F=0,S=!1,I=0,O=0,k=!1,V=null,ge=!1,ie=0,_=new Set,ne=new Map,Te="",le="",ke=null,de,Y,ce,q,G;function ve(){let ue=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),T=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");$r(T,d==null?void 0:d.headerBar);let Ae=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ae.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 re=h("div","persona-flex-1");Y=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 ye=h("option","");ye.value="",ye.textContent="All events",Y.appendChild(ye),ce=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"),ce.type="button",ce.title="Copy All";let Qe=fe("clipboard-copy","12px","currentColor",1.5);Qe&&ce.appendChild(Qe);let he=h("span","persona-text-xs");he.textContent="Copy All",ce.appendChild(he),T.appendChild(Ae),T.appendChild(de),T.appendChild(re),T.appendChild(Y),T.appendChild(ce);let Pe=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");$r(Pe,d==null?void 0:d.searchBar);let Ne=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),ot=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");Ne&&ot.appendChild(Ne),q=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"),$r(q,d==null?void 0:d.searchInput),q.type="text",q.placeholder="Search event payloads...",G=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"),G.type="button",G.style.display="none";let At=fe("x","12px","currentColor",2);return At&&G.appendChild(At),Pe.appendChild(ot),Pe.appendChild(q),Pe.appendChild(G),ue.appendChild(T),ue.appendChild(Pe),ue}let xe,Ke=o.find(ue=>ue.renderEventStreamToolbar);if(Ke!=null&&Ke.renderEventStreamToolbar&&s){let ue=Ke.renderEventStreamToolbar({config:s,defaultRenderer:()=>ve(),eventCount:r.getSize(),filteredCount:0,onFilterChange:T=>{v=T,Le(),ze()},onSearchChange:T=>{A=T,Le(),ze()}});xe=ue!=null?ue:ve()}else xe=ve();let Xe=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");Xe.style.display="none";let mt=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Be=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Be.style.height="100%";let rt=h("div","persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-bg-persona-accent persona-text-white persona-text-xs persona-px-3 persona-py-1.5 persona-rounded-full persona-cursor-pointer persona-shadow-md persona-z-10 persona-flex persona-items-center persona-gap-1");$r(rt,d==null?void 0:d.scrollIndicator),rt.style.display="none";let Me=fe("arrow-down","12px","currentColor",2);Me&&rt.appendChild(Me);let D=h("span","");rt.appendChild(D);let se=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");se.style.display="none",mt.appendChild(Be),mt.appendChild(se),mt.appendChild(rt),f.setAttribute("tabindex","0"),f.appendChild(xe),f.appendChild(Xe),f.appendChild(mt);function te(){let ue=r.getAll(),T={};for(let he of ue)T[he.type]=(T[he.type]||0)+1;let Ae=Object.keys(T).sort(),re=Ae.length!==x.length||!Ae.every((he,Pe)=>he===x[Pe]),ye=!re&&Ae.some(he=>T[he]!==M[he]),Ce=ue.length!==Object.values(M).reduce((he,Pe)=>he+Pe,0);if(!re&&!ye&&!Ce||(x=Ae,M=T,!Y))return;let Qe=Y.value;if(Y.options[0].textContent="All events",re){for(;Y.options.length>1;)Y.remove(1);for(let he of Ae){let Pe=h("option","");Pe.value=he,Pe.textContent=`${he} (${T[he]||0})`,Y.appendChild(Pe)}Qe&&Ae.includes(Qe)?Y.value=Qe:Qe&&(Y.value="",v="")}else for(let he=1;he<Y.options.length;he++){let Pe=Y.options[he];Pe.textContent=`${Pe.value} (${T[Pe.value]||0})`}}function z(){let ue=r.getAll();if(v&&(ue=ue.filter(T=>T.type===v)),A){let T=A.toLowerCase();ue=ue.filter(Ae=>Ae.type.toLowerCase().includes(T)||Ae.payload.toLowerCase().includes(T))}return ue}function oe(){return v!==""||A!==""}function Le(){F=0,I=0,S=!1,rt.style.display="none"}function Z(ue){_.has(ue)?_.delete(ue):_.add(ue),ke=ue;let T=Be.scrollTop,Ae=S;ge=!0,S=!0,ze(),Be.scrollTop=T,S=Ae,ge=!1}function J(){return Be.scrollHeight-Be.scrollTop-Be.clientHeight<=50}function ze(){O=Date.now(),k=!1,te();let ue=r.getEvictedCount();ue>0?(Xe.textContent=`${ue.toLocaleString()} older events truncated`,Xe.style.display=""):Xe.style.display="none",m=z();let T=m.length,Ae=r.getSize()>0;de&&(de.textContent=String(r.getSize())),T===0&&Ae&&oe()?(se.textContent=A?`No events matching '${A}'`:"No events matching filter",se.style.display="",Be.style.display="none"):(se.style.display="none",Be.style.display=""),ce&&(ce.title=oe()?`Copy Filtered (${T})`:"Copy All"),S&&T>F&&(I+=T-F,D.textContent=`${I} new event${I===1?"":"s"}`,rt.style.display=""),F=T;let re=r.getAll(),ye=re.length>0?re[0].timestamp:0,Ce=new Set(m.map(Pe=>Pe.id));for(let Pe of _)Ce.has(Pe)||_.delete(Pe);let Qe=v!==Te||A!==le,he=ne.size===0&&m.length>0;if(Qe||he||m.length===0){Be.innerHTML="",ne.clear();let Pe=document.createDocumentFragment();for(let Ne=0;Ne<m.length;Ne++){let ot=Js(m[Ne],Ne,ye,a,_,Z,o,s);ne.set(m[Ne].id,ot),Pe.appendChild(ot)}Be.appendChild(Pe),Te=v,le=A,ke=null}else{if(ke!==null){let Ne=ne.get(ke);if(Ne&&Ne.parentNode===Be){let ot=m.findIndex(At=>At.id===ke);if(ot>=0){let At=Js(m[ot],ot,ye,a,_,Z,o,s);Be.insertBefore(At,Ne),Ne.remove(),ne.set(ke,At)}}ke=null}let Pe=new Set(m.map(Ne=>Ne.id));for(let[Ne,ot]of ne)Pe.has(Ne)||(ot.remove(),ne.delete(Ne));for(let Ne=0;Ne<m.length;Ne++){let ot=m[Ne];if(!ne.has(ot.id)){let At=Js(ot,Ne,ye,a,_,Z,o,s);ne.set(ot.id,At),Be.appendChild(At)}}}S||(Be.scrollTop=Be.scrollHeight)}function Ue(){if(Date.now()-O>=ap){V!==null&&(cancelAnimationFrame(V),V=null),ze();return}k||(k=!0,V=requestAnimationFrame(()=>{V=null,ze()}))}let St=(ue,T)=>{if(!ce)return;ce.innerHTML="";let Ae=fe(ue,"12px","currentColor",1.5);Ae&&ce.appendChild(Ae);let re=h("span","persona-text-xs");re.textContent="Copy All",ce.appendChild(re),setTimeout(()=>{ce.innerHTML="";let ye=fe("clipboard-copy","12px","currentColor",1.5);ye&&ce.appendChild(ye);let Ce=h("span","persona-text-xs");Ce.textContent="Copy All",ce.appendChild(Ce),ce.disabled=!1},T)},qt=async()=>{if(ce){ce.disabled=!0;try{let ue;oe()?ue=m:t?(ue=await t(),ue.length===0&&(ue=r.getAll())):ue=r.getAll();let T=ue.map(Ae=>{try{return JSON.parse(Ae.payload)}catch{return Ae.payload}});await navigator.clipboard.writeText(JSON.stringify(T,null,2)),St("check",1500)}catch{St("x",1500)}}},Ut=()=>{Y&&(v=Y.value,Le(),ze())},K=()=>{!q||!G||(G.style.display=q.value?"":"none",b&&clearTimeout(b),b=setTimeout(()=>{A=q.value,Le(),ze()},150))},Ie=()=>{!q||!G||(q.value="",A="",G.style.display="none",b&&clearTimeout(b),Le(),ze())},ft=()=>{if(ge)return;let ue=Be.scrollTop,T=ue>ie;ie=ue,J()&&T?(S=!1,I=0,rt.style.display="none"):J()||(S=!0)},yt=ue=>{ue.deltaY<0&&(S=!0)},Ze=()=>{Be.scrollTop=Be.scrollHeight,S=!1,I=0,rt.style.display="none"},it=ue=>{let T=ue.target;if(!T||T.closest("button"))return;let Ae=T.closest("[data-event-id]");if(!Ae)return;let re=Ae.getAttribute("data-event-id");re&&Z(re)},Wt=ue=>{if((ue.metaKey||ue.ctrlKey)&&ue.key==="f"){ue.preventDefault(),q==null||q.focus(),q==null||q.select();return}ue.key==="Escape"&&(q&&document.activeElement===q?(Ie(),q.blur(),f.focus()):n&&n())};ce&&ce.addEventListener("click",qt),Y&&Y.addEventListener("change",Ut),q&&q.addEventListener("input",K),G&&G.addEventListener("click",Ie),Be.addEventListener("scroll",ft),Be.addEventListener("wheel",yt,{passive:!0}),Be.addEventListener("click",it),rt.addEventListener("click",Ze),f.addEventListener("keydown",Wt);function Vt(){b&&clearTimeout(b),V!==null&&(cancelAnimationFrame(V),V=null),k=!1,ne.clear(),ce&&ce.removeEventListener("click",qt),Y&&Y.removeEventListener("change",Ut),q&&q.removeEventListener("input",K),G&&G.removeEventListener("click",Ie),Be.removeEventListener("scroll",ft),Be.removeEventListener("wheel",yt),Be.removeEventListener("click",it),rt.removeEventListener("click",Ze),f.removeEventListener("keydown",Wt)}return{element:f,update:Ue,destroy:Vt}}}function bc(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-bg, #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 p=document.createElement("div");p.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-muted, #9ca3af)",p.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 u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let d=document.createElement("div");if(d.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",d.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, #3b82f6)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",d.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,d.appendChild(m)}else d.textContent=a;if(c.append(u,d),i.append(p,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:"",p=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:c,status:p},config:r.config,defaultRenderer:()=>bc(e,r)});if(u)return u}return bc(e,r)};var Ks=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)})}},Nn=new Ks;Nn.register("PersonaArtifactCard",xc);function mp(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 vc(e,r){var mt,Be,rt,Me;let t=(Be=(mt=e.features)==null?void 0:mt.artifacts)==null?void 0:Be.layout,s=((rt=t==null?void 0:t.toolbarPreset)!=null?rt:"default")==="document",o=(Me=t==null?void 0:t.panePadding)==null?void 0:Me.trim(),a=e.markdown?cr(e.markdown):null,i=Ir(e.sanitize),p=D=>{let se=a?a(D):Lr(D);return i?i(se):se},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,u=()=>{c==null||c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};c&&c.addEventListener("click",()=>{var D;u(),(D=r.onDismiss)==null||D.call(r)});let d=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");d.setAttribute("data-persona-theme-zone","artifact-pane"),s&&d.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 D;u(),(D=r.onDismiss)==null||D.call(r)});let A="rendered",b=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),x=s?bt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):bt({icon:"eye",label:"Rendered view"}),M=s?bt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):bt({icon:"code-2",label:"Source"}),F=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),S=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,I=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,O=t==null?void 0:t.documentToolbarCopyMenuItems,k=!!(I&&O&&O.length>0),V=null,ge,ie=null,_=null;if(s&&(S||I)&&!k){if(ge=S?ho({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let D=fe("chevron-down",14,"currentColor",2);D&&ge.appendChild(D)}}else s&&k?(V=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ge=S?ho({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),ie=bt({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"}}),V.append(ge,ie)):s?ge=bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):ge=bt({icon:"copy",label:"Copy"});let ne=s?bt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):bt({icon:"refresh-cw",label:"Refresh"}),Te=s?bt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):bt({icon:"x",label:"Close"}),le=()=>{var oe,Le,Z;let D=(oe=G.find(J=>J.id===ve))!=null?oe:G[G.length-1],se=(Le=D==null?void 0:D.id)!=null?Le:null,te=(D==null?void 0:D.artifactType)==="markdown"&&(Z=D.markdown)!=null?Z:"",z=D?JSON.stringify({component:D.component,props:D.props},null,2):"";return{markdown:te,jsonPayload:z,id:se}},ke=async()=>{var oe;let{markdown:D,jsonPayload:se}=le(),te=(oe=G.find(Le=>Le.id===ve))!=null?oe:G[G.length-1],z=(te==null?void 0:te.artifactType)==="markdown"?D:te?se:"";try{await navigator.clipboard.writeText(z)}catch{}};if(ge.addEventListener("click",async()=>{let D=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(D&&k){let{markdown:se,jsonPayload:te,id:z}=le();try{await D({actionId:"primary",artifactId:z,markdown:se,jsonPayload:te})}catch{}return}await ke()}),ie&&(O!=null&&O.length)){let D=()=>{var te;return(te=d.closest("[data-persona-root]"))!=null?te:document.body},se=()=>{_=Kn({items:O.map(te=>({id:te.id,label:te.label})),onSelect:async te=>{let{markdown:z,jsonPayload:oe,id:Le}=le(),Z=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Z?await Z({actionId:te,artifactId:Le,markdown:z,jsonPayload:oe}):te==="markdown"||te==="md"?await navigator.clipboard.writeText(z):te==="json"||te==="source"?await navigator.clipboard.writeText(oe):await navigator.clipboard.writeText(z||oe)}catch{}},anchor:V!=null?V:ie,position:"bottom-right",portal:D()})};d.isConnected?se():requestAnimationFrame(se),ie.addEventListener("click",te=>{te.stopPropagation(),_==null||_.toggle()})}ne.addEventListener("click",async()=>{var D;try{await((D=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:D.call(t))}catch{}Ke()}),Te.addEventListener("click",()=>{var D;u(),(D=r.onDismiss)==null||D.call(r)});let de=()=>{s&&(x.setAttribute("aria-pressed",A==="rendered"?"true":"false"),M.setAttribute("aria-pressed",A==="source"?"true":"false"))};x.addEventListener("click",()=>{A="rendered",de(),Ke()}),M.addEventListener("click",()=>{A="source",de(),Ke()});let Y=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(x,M),V?F.append(V,ne,Te):F.append(ge,ne,Te),f.append(b,Y,F),de()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ce=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"),q=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ce.style.paddingLeft=o,ce.style.paddingRight=o,q.style.padding=o),d.appendChild(f),d.appendChild(ce),d.appendChild(q);let G=[],ve=null,xe=!1,Ke=()=>{var z,oe,Le,Z;let D=s&&G.length<=1;ce.classList.toggle("persona-hidden",D),ce.replaceChildren();for(let J of G){let ze=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");ze.type="button",ze.textContent=J.title||J.id.slice(0,8),J.id===ve&&ze.classList.add("persona-bg-persona-container","persona-border-persona-border"),ze.addEventListener("click",()=>r.onSelect(J.id)),ce.appendChild(ze)}q.replaceChildren();let se=ve&&G.find(J=>J.id===ve)||G[G.length-1];if(!se)return;if(s){let J=se.artifactType==="markdown"?"MD":(z=se.component)!=null?z:"Component",Ue=(se.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Y.textContent=`${Ue} \xB7 ${J}`}else m.textContent="Artifacts";if(se.artifactType==="markdown"){if(s&&A==="source"){let ze=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ze.textContent=(oe=se.markdown)!=null?oe:"",q.appendChild(ze);return}let J=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");J.innerHTML=p((Le=se.markdown)!=null?Le:""),q.appendChild(J);return}let te=se.component?Nn.get(se.component):void 0;if(te){let ze={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Ue=te((Z=se.props)!=null?Z:{},ze);if(Ue){q.appendChild(Ue);return}}catch{}}q.appendChild(mp(se))},Xe=()=>{var se;let D=G.length>0;if(d.classList.toggle("persona-hidden",!D),c){let te=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,oe=((se=te==null?void 0:te.classList.contains("persona-artifact-narrow-host"))!=null?se:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;D&&oe&&xe?(c.classList.remove("persona-hidden"),d.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"))}};return{element:d,backdrop:c,update(D){var se,te,z;G=D.artifacts,ve=(z=(te=D.selectedId)!=null?te:(se=D.artifacts[D.artifacts.length-1])==null?void 0:se.id)!=null?z:null,G.length>0&&(xe=!0),Ke(),Xe()},setMobileOpen(D){xe=D,!D&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):Xe()}}}function gn(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 Cc(e,r){var o,a,i,p;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"),!gn(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=(p=t==null?void 0:t.paneBorderLeft)==null?void 0:p.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 fp(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 ls(e,r){var p,c,u,d,f,m,v,A,b,x;if(!gn(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"),fp(e),Cc(e,r);return}let t=(c=(p=r.features)==null?void 0:p.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(d=t==null?void 0:t.paneWidth)!=null?d:"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=(A=t==null?void 0:t.documentToolbarIconColor)==null?void 0:A.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=(x=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:x.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Cc(e,r)}var wc=["panel","seamless"];function cs(e,r){var i,p,c,u,d,f;for(let m of wc)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"),!gn(r))return;let t=(p=(i=r.features)==null?void 0:i.artifacts)==null?void 0:p.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=wc.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(d=t==null?void 0:t.paneShadow)==null?void 0:d.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 Sc(e,r){var t,n,s;return!r||!gn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function hp(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 yp(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 bp(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function xp(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Ac(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 Ec(e,r,t,n,s,o){let a=hp(s,200),i=xp(r,t,n,200);i=Math.max(a,i);let p=yp(o);return p!==null&&(i=Math.min(i,p)),bp(e,a,i)}var Tc={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"}},Gs=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,A,b;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(A=Tc[a])!=null?A:Tc.init;o.classList.add("persona-form-card","persona-space-y-4");let p=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,p.appendChild(c),i.description){let x=h("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,p.appendChild(x)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var O,k;let M=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${r.id}-${a}-${x.name}`;let F=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");F.textContent=x.label,M.appendChild(F);let S=(O=x.type)!=null?O:"text",I;S==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=S),I.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",I.id=`${r.id}-${a}-${x.name}`,I.name=x.name,I.placeholder=(k=x.placeholder)!=null?k:"",x.required&&(I.required=!0),M.appendChild(I),u.appendChild(M)});let d=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",d.appendChild(f),d.appendChild(m),u.appendChild(d),o.replaceChildren(p,u),u.addEventListener("submit",async x=>{var I,O;x.preventDefault();let M=(I=t.formEndpoint)!=null?I:"/form",F=new FormData(u),S={};F.forEach((k,V)=>{S[V]=k}),S.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let k=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let V=await k.json();f.textContent=(O=V.message)!=null?O:"Thanks! We'll be in touch soon.",V.success&&V.nextPrompt&&await n.sendMessage(String(V.nextPrompt))}catch(k){f.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Ys=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,p;return((i=a.priority)!=null?i:0)-((p=o.priority)!=null?p:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},vo=new Ys;var xt={apiUrl:"http://localhost:43111/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}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",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:"1px solid #e5e7eb",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",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",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:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!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 Mc(e,r){if(!(!e&&!r))return e?r?uo(e,r):e:r}function ds(e){var r,t,n,s,o,a,i,p,c,u,d,f,m,v,A,b,x,M,F,S,I;return e?{...xt,...e,theme:Mc(xt.theme,e.theme),darkTheme:Mc(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 ge,ie;let O=(ge=xt.features)==null?void 0:ge.artifacts,k=(ie=e.features)==null?void 0:ie.artifacts,V=O===void 0&&k===void 0?void 0:{...O,...k,layout:{...O==null?void 0:O.layout,...k==null?void 0:k.layout}};return{...xt.features,...e.features,...V!==void 0?{artifacts:V}:{}}})(),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:{...(p=xt.layout)==null?void 0:p.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(u=xt.layout)==null?void 0:u.messages)==null?void 0:d.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(A=(v=xt.layout)==null?void 0:v.messages)==null?void 0:A.timestamp,...(x=(b=e.layout)==null?void 0:b.messages)==null?void 0:x.timestamp}},slots:{...(M=xt.layout)==null?void 0:M.slots,...(F=e.layout)==null?void 0:F.slots}},markdown:{...xt.markdown,...e.markdown,options:{...(S=xt.markdown)==null?void 0:S.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...xt.messageActions,...e.messageActions}}:xt}var kc=()=>{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(p){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",p)}})}}};var vp=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Cp=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},Co=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=vp(e),t=Cp(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}},Xs=e=>typeof e=="string"?e:e==null?"":String(e),yr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Xs(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Xs(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:Xs(t.text)}}},Lc=e=>Array.isArray(e)?e.map(r=>String(r)):[],wo=e=>{let r=new Set(Lc(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Lc(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,u)=>c||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let p={action:i,message:o.message};e.emit("action:detected",p);for(let c of e.handlers)if(c)try{let u=()=>{e.emit("action:resubmit",p)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var wp=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}},Sp=e=>e.map(r=>({...r,streaming:!1})),ps=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?wp(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Sp(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 Fr=require("partial-json");function Ap(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Ep(e,r){if(!Ap(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 us(){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,Fr.parse)(t,Fr.STR|Fr.OBJ),o=Ep(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Ic(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function gs(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=Nn.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 Pc(){let e=us();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ms(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 fs(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 Tp=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hs(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:p=!0,ratingLabels:c=Tp}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let d=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 A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,m.appendChild(A),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 x=[];for(let O=1;O<=5;O++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${O} star${O>1?"s":""}: ${c[O-1]}`),k.title=c[O-1],k.dataset.rating=String(O),k.innerHTML=`
17
17
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
18
18
  <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>
19
19
  </svg>
20
- `,T.addEventListener("click",()=>{p=$,x.forEach((V,ue)=>{let oe=ue<$;V.classList.toggle("selected",oe),V.setAttribute("aria-checked",ue===$-1?"true":"false")})}),x.push(T),b.appendChild(T)}f.appendChild(b);let k=null;if(d){let $=document.createElement("div");$.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"),$.appendChild(k),f.appendChild($)}let _=document.createElement("div");_.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(),u.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(p===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let $=(k==null?void 0:k.value.trim())||void 0;await r(p,$),u.remove()}catch($){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",$)}}),_.appendChild(w),_.appendChild(I),f.appendChild(_),u.appendChild(f),u}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:u="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 f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=n,v.appendChild(S);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,v.appendChild(b),m.appendChild(v);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let _=document.createElement("span");_.className="persona-feedback-label-low",_.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=u,k.appendChild(_),k.appendChild(w);let I=document.createElement("div");I.className="persona-feedback-numbers";let $=[];for(let z=0;z<=10;z++){let te=document.createElement("button");te.type="button",te.className="persona-feedback-rating-btn persona-feedback-number-btn",te.setAttribute("role","radio"),te.setAttribute("aria-checked","false"),te.setAttribute("aria-label",`Rating ${z} out of 10`),te.textContent=String(z),te.dataset.rating=String(z),z<=6?te.classList.add("persona-feedback-detractor"):z<=8?te.classList.add("persona-feedback-passive"):te.classList.add("persona-feedback-promoter"),te.addEventListener("click",()=>{f=z,$.forEach((Ae,ie)=>{Ae.classList.toggle("selected",ie===z),Ae.setAttribute("aria-checked",ie===z?"true":"false")})}),$.push(te),I.appendChild(te)}x.appendChild(k),x.appendChild(I),m.appendChild(x);let T=null;if(d){let z=document.createElement("div");z.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"),z.appendChild(T),m.appendChild(z)}let V=document.createElement("div");V.className="persona-feedback-actions";let ue=document.createElement("button");ue.type="button",ue.className="persona-feedback-btn persona-feedback-btn-skip",ue.textContent=i,ue.addEventListener("click",()=>{t==null||t(),p.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="persona-feedback-btn persona-feedback-btn-submit",oe.textContent=a,oe.addEventListener("click",async()=>{if(f===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let z=(T==null?void 0:T.value.trim())||void 0;await r(f,z),p.remove()}catch(z){oe.disabled=!1,oe.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),V.appendChild(ue),V.appendChild(oe),m.appendChild(V),p.appendChild(m),p}var Fr="persona-chat-history",Ap=30*1e3,Ep={"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 Tp(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=Ep[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 Mp(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 kp(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Ys=e=>!e||typeof e!="object"?{}:{...e},Ic=e=>e.map(r=>({...r,streaming:!1})),Pc=(e,r,t)=>{let n=e!=null&&e.markdown?ir(e.markdown):null,s=Lr(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,u,p;let a=(c=o.text)!=null?c:"",i=(u=o.message.rawContent)!=null?u: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:(p=i!=null?i:o.text)!=null?p:""}):n?d=n(a):d=kr(a),s?s(d):d}},ys=(e,r,t)=>{var lt,Rt,Mt,Nt,Ht,ct,ut,It,gt,Ot,en,dn,ma,fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Ia,Pa,Wa,Ra,Ha,Ba,Da,Na,Oa,$a;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=cs(r),s=xo.getForInstance(n.plugins);n.components&&Nn.registerAll(n.components);let o=Tc(),a=(lt=n.storageAdapter)!=null?lt:ds(),i={},d=null,c=!1,u=l=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:A}=g;return A&&(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 u(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=u(g);y.metadata&&(i=Ys(y.metadata)),(Rt=y.messages)!=null&&Rt.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=u({messages:[],metadata:{}});(Mt=l.messages)!=null&&Mt.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},Gr()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[vo],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[fr.message,fr.messageAndClick],S=Co({parsers:m,handlers:v,getSessionMetadata:p,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let b=(Ht=(Nt=n.launcher)==null?void 0:Nt.enabled)!=null?Ht:!0,x=(ut=(ct=n.launcher)==null?void 0:ct.autoExpand)!=null?ut:!1,k=(It=n.autoFocusInput)!=null?It:!1,_=x,w=b,I=(Ot=(gt=n.layout)==null?void 0:gt.header)==null?void 0:Ot.layout,$=!1,T=b?x:!0,V=!1,ue=null,oe=()=>{V=!0,ue&&clearTimeout(ue),ue=setTimeout(()=>{V&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),V=!1)},1e4)},z=Pc(n,S,oe),te=(dn=(en=n.features)==null?void 0:en.showReasoning)!=null?dn:!0,Ae=(fa=(ma=n.features)==null?void 0:ma.showToolCalls)!=null?fa:!0,ie=(ya=(ha=n.features)==null?void 0:ha.showEventStreamToggle)!=null?ya:!1,ae=`${(xa=typeof n.persistState=="object"?(ba=n.persistState)==null?void 0:ba.keyPrefix:void 0)!=null?xa:"persona-"}event-stream`,Y=ie?new bo(ae):null,ge=(wa=(Ca=(va=n.features)==null?void 0:va.eventStream)==null?void 0:Ca.maxEvents)!=null?wa:2e3,F=ie?new yo(ge,Y):null,J=null,me=!1,at=null,Ue=0;Y==null||Y.open().then(()=>F==null?void 0:F.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Ke={onCopy:l=>{var g,y;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)}),(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(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,l)}},mt=(Sa=n.statusIndicator)!=null?Sa:{},Re=l=>{var g,y,A,L;return l==="idle"?(g=mt.idleText)!=null?g:Gt.idle:l==="connecting"?(y=mt.connectingText)!=null?y:Gt.connecting:l==="connected"?(A=mt.connectedText)!=null?A:Gt.connected:l==="error"?(L=mt.errorText)!=null?L:Gt.error:Gt[l]};function tt(l,g,y,A){if(A==="idle"&&y.idleLink){l.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=g,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=g}let{wrapper:Te,panel:N}=lc(n),re=cc(n,b),{container:ee,body:q,messagesWrapper:ce,suggestions:ke,textarea:Q,sendButton:K,sendButtonWrapper:_e,composerForm:it,statusText:Lt,introTitle:qt,introSubtitle:Ut,closeButton:G,iconHolder:Le,headerTitle:ft,headerSubtitle:yt,header:Ye,footer:ot,actionsRow:Wt,leftActions:Vt,rightActions:de}=re,E=re.micButton,Ee=re.micButtonWrapper,ne=re.attachmentButton,be=re.attachmentButtonWrapper,Ce=re.attachmentInput,Xe=re.attachmentPreviewsContainer,ye=null,Ie=null,De=s.find(l=>l.renderHeader);if(De!=null&&De.renderHeader){let l=De.renderHeader({config:n,defaultRenderer:()=>{let g=Dn({config:n,showClose:b});return gr(ee,g,n),g.header},onClose:()=>wt(!1,"user")});if(l){let g=ee.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Ye=l)}}let nt=()=>{var g,y,A,L;if(!F)return;if(me=!0,!J&&F&&(J=fc({buffer:F,getFullHistory:()=>F.getAllFromStore(),onClose:()=>Et(),config:n,plugins:s})),J&&(q.style.display="none",(g=ot.parentNode)==null||g.insertBefore(J.element,ot),J.update()),Ne){Ne.classList.remove("persona-text-persona-muted"),Ne.classList.add("persona-text-persona-accent"),Ne.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let R=(L=(A=(y=n.features)==null?void 0:y.eventStream)==null?void 0:A.classNames)==null?void 0:L.toggleButtonActive;R&&R.split(/\s+/).forEach(W=>W&&Ne.classList.add(W))}let l=()=>{if(!me)return;let R=Date.now();R-Ue>=200&&(J==null||J.update(),Ue=R),at=requestAnimationFrame(l)};Ue=0,at=requestAnimationFrame(l),o.emit("eventStream:opened",{timestamp:Date.now()})},Et=()=>{var l,g,y;if(me){if(me=!1,J&&J.element.remove(),q.style.display="",Ne){Ne.classList.remove("persona-text-persona-accent"),Ne.classList.add("persona-text-persona-muted"),Ne.style.boxShadow="";let A=(y=(g=(l=n.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;A&&A.split(/\s+/).forEach(L=>L&&Ne.classList.remove(L))}at!==null&&(cancelAnimationFrame(at),at=null),o.emit("eventStream:closed",{timestamp:Date.now()})}},Ne=null;if(ie){let l=(Ea=(Aa=n.features)==null?void 0:Aa.eventStream)==null?void 0:Ea.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");Ne=h("button",g),Ne.style.width="28px",Ne.style.height="28px",Ne.type="button",Ne.setAttribute("aria-label","Event Stream"),Ne.title="Event Stream";let y=he("activity","18px","currentColor",1.5);y&&Ne.appendChild(y);let A=re.clearChatButtonWrapper,L=re.closeButtonWrapper,R=A||L;R&&R.parentNode===Ye?Ye.insertBefore(Ne,R):Ye.appendChild(Ne),Ne.addEventListener("click",()=>{me?Et():nt()})}let Gn=l=>{var A,L,R;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=((A=g.allowedTypes)!=null?A:Bn).join(","),W.multiple=((L=g.maxFiles)!=null?L:4)>1,W.style.display="none",W.setAttribute("aria-label",(R=g.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(W)}},xn=s.find(l=>l.renderComposer);if(xn!=null&&xn.renderComposer){let l=n.composer,g=xn.renderComposer({config:n,defaultRenderer:()=>Hr({config:n}).footer,onSubmit:y=>{D&&!D.isStreaming()&&D.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ce==null||Ce.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y}},onVoiceToggle:((Ta=n.voiceRecognition)==null?void 0:Ta.enabled)===!0?()=>{Ie==null||Ie()}:void 0});g&&(ot.replaceWith(g),ot=g)}let Yn=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=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]");g&&(it=g),y&&(Q=y),A&&(K=A),L&&(E=L,Ee=L.parentElement),R&&(Lt=R);let W=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");W&&(ke=W);let U=l.querySelector(".persona-attachment-button");U&&(ne=U,be=U.parentElement),Ce=l.querySelector('input[type="file"]'),Xe=l.querySelector(".persona-attachment-previews");let O=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(Wt=O)};Gn(ot),Yn(ot);let $n=(Ma=n.layout)==null?void 0:Ma.contentMaxWidth;$n&&it&&(it.style.maxWidth=$n,it.style.marginLeft="auto",it.style.marginRight="auto"),(ka=n.attachments)!=null&&ka.enabled&&Ce&&Xe&&(ye=ur.fromConfig(n.attachments),ye.setPreviewsContainer(Xe),Ce.addEventListener("change",l=>{let g=l.target;ye==null||ye.handleFileSelect(g.files),g.value=""})),(()=>{var A,L;let l=(L=(A=n.layout)==null?void 0:A.slots)!=null?L:{},g=R=>{switch(R){case"body-top":return ee.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ce;case"footer-top":return ke;case"composer":return it;case"footer-bottom":return Lt;default:return null}},y=(R,W)=>{var U;switch(R){case"header-left":case"header-center":case"header-right":if(R==="header-left")Ye.insertBefore(W,Ye.firstChild);else if(R==="header-right")Ye.appendChild(W);else{let O=Ye.querySelector(".persona-flex-col");O?(U=O.parentNode)==null||U.insertBefore(W,O.nextSibling):Ye.appendChild(W)}break;case"body-top":{let O=q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(W):q.insertBefore(W,q.firstChild);break}case"body-bottom":q.appendChild(W);break;case"footer-top":ke.replaceWith(W);break;case"footer-bottom":Lt.replaceWith(W);break;default:break}};for(let[R,W]of Object.entries(l))if(W)try{let U=W({config:n,defaultContent:()=>g(R)});U&&y(R,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${R}":`,U)}})();let Fn=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let A=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let R=y.getAttribute("data-bubble-type");R==="reasoning"?(Dr.has(L)?Dr.delete(L):Dr.add(L),uc(L,A)):R==="tool"&&(Nr.has(L)?Nr.delete(L):Nr.add(L),gc(L,A,n))};ce.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Fn(l))}),ce.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Fn(l))});let Mn=new Map;ce.addEventListener("click",l=>{var W;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest("[data-actions-for]");if(!A)return;let L=A.getAttribute("data-actions-for");if(!L)return;let R=y.getAttribute("data-action");if(R==="copy"){let O=D.getMessages().find(se=>se.id===L);if(O&&Ke.onCopy){let se=O.content||"";navigator.clipboard.writeText(se).then(()=>{y.classList.add("persona-message-action-success");let ve=he("check",14,"currentColor",2);ve&&(y.innerHTML="",y.appendChild(ve)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let we=he("copy",14,"currentColor",2);we&&(y.innerHTML="",y.appendChild(we))},2e3)}).catch(ve=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ve)}),Ke.onCopy(O)}}else if(R==="upvote"||R==="downvote")if(((W=Mn.get(L))!=null?W:null)===R)Mn.delete(L),y.classList.remove("persona-message-action-active");else{let se=R==="upvote"?"downvote":"upvote",ve=A.querySelector(`[data-action="${se}"]`);ve&&ve.classList.remove("persona-message-action-active"),Mn.set(L,R),y.classList.add("persona-message-action-active");let He=D.getMessages().find(Me=>Me.id===L);He&&Ke.onFeedback&&Ke.onFeedback({type:R,messageId:He.id,message:He})}}),ce.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest(".vanilla-approval-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let R=y.getAttribute("data-approval-action");if(!R)return;let W=R==="approve"?"approved":"denied",O=D.getMessages().find(ve=>ve.id===L);if(!(O!=null&&O.approval))return;let se=A.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(we=>{we.disabled=!0,we.style.opacity="0.5",we.style.cursor="not-allowed"}),D.resolveApproval(O.approval,W)});let Ze=null,Z=null,an={artifacts:[],selectedId:null},rn=!1,_r={current:null};ce.addEventListener("click",l=>{var we,He,Me,B,We;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.getAttribute("data-download-artifact");if(!A||((Me=(He=(we=n.features)==null?void 0:we.artifacts)==null?void 0:He.onArtifactAction)==null?void 0:Me.call(He,{type:"download",artifactId:A}))===!0)return;let R=D.getArtifactById(A),W=R==null?void 0:R.markdown,U=(R==null?void 0:R.title)||"artifact";if(!W){let Pe=y.closest("[data-open-artifact]"),le=Pe==null?void 0:Pe.closest("[data-message-id]"),Be=le==null?void 0:le.getAttribute("data-message-id");if(Be){let qe=D.getMessages().find(fe=>fe.id===Be);if(qe!=null&&qe.rawContent)try{let fe=JSON.parse(qe.rawContent);W=(B=fe==null?void 0:fe.props)==null?void 0:B.markdown,U=((We=fe==null?void 0:fe.props)==null?void 0:We.title)||U}catch{}}}if(!W)return;let O=new Blob([W],{type:"text/markdown"}),se=URL.createObjectURL(O),ve=document.createElement("a");ve.href=se,ve.download=`${U}.md`,ve.click(),URL.revokeObjectURL(se)}),ce.addEventListener("click",l=>{var R,W,U;let y=l.target.closest("[data-open-artifact]");if(!y)return;let A=y.getAttribute("data-open-artifact");!A||((U=(W=(R=n.features)==null?void 0:R.artifacts)==null?void 0:W.onArtifactAction)==null?void 0:U.call(W,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),D.selectArtifact(A),Cn())}),ce.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,ht=null,ln=null,kn=null,jr=()=>{};function br(){kn==null||kn(),kn=null}let zr=()=>{var W;if(!vn||!ht)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){ht.style.removeProperty("position"),ht.style.removeProperty("left"),ht.style.removeProperty("top"),ht.style.removeProperty("bottom"),ht.style.removeProperty("width"),ht.style.removeProperty("z-index");return}let A=vn.firstElementChild;if(!A||A===ht)return;let L=10;ht.style.position="absolute",ht.style.top="0",ht.style.bottom="0",ht.style.width=`${L}px`,ht.style.zIndex="5";let R=A.offsetWidth-L/2;ht.style.left=`${Math.max(0,R)}px`},Xn=()=>{},Cn=()=>{var y,A,L,R,W;if(!Ze||!gn(n))return;is(e,n),ls(e,n),Xn();let l=(R=(L=(A=(y=n.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:L.narrowHostMaxWidth)!=null?R:520,g=N.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),Ze.update(an),rn?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),(W=Ze.backdrop)==null||W.classList.add("persona-hidden")):an.artifacts.length>0&&(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)),jr()};if(gn(n)){N.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(ee),Ze=bc(n,{onSelect:y=>{var A;return(A=_r.current)==null?void 0:A.selectArtifact(y)},onDismiss:()=>{rn=!0,Cn()}}),Ze.element.classList.add("persona-hidden"),vn=g,g.appendChild(l),g.appendChild(Ze.element),Ze.backdrop&&N.appendChild(Ze.backdrop),N.appendChild(g),jr=()=>{var A,L,R,W;if(!vn||!Ze)return;if(!(((R=(L=(A=n.features)==null?void 0:A.artifacts)==null?void 0:L.layout)==null?void 0:R.resizable)===!0)){ln==null||ln(),ln=null,br(),ht&&(ht.remove(),ht=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!ht){let U=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let O=e.ownerDocument,se=(W=O.defaultView)!=null?W:window,ve=we=>{var le,Be;if(!Ze||we.button!==0||e.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;we.preventDefault(),br();let He=we.clientX,Me=Ze.element.getBoundingClientRect().width,B=(Be=(le=n.features)==null?void 0:le.artifacts)==null?void 0:Be.layout,We=st=>{let qe=vn.getBoundingClientRect().width,fe=e.classList.contains("persona-artifact-appearance-seamless"),Bt=fe?0:wc(vn,se),dt=fe?0:U.getBoundingClientRect().width||6,tn=Me-(st.clientX-He),Jt=Sc(tn,qe,Bt,dt,B==null?void 0:B.resizableMinWidth,B==null?void 0:B.resizableMaxWidth);Ze.element.style.width=`${Jt}px`,Ze.element.style.maxWidth="none",zr()},Pe=()=>{O.removeEventListener("pointermove",We),O.removeEventListener("pointerup",Pe),O.removeEventListener("pointercancel",Pe),kn=null;try{U.releasePointerCapture(we.pointerId)}catch{}};kn=Pe,O.addEventListener("pointermove",We),O.addEventListener("pointerup",Pe),O.addEventListener("pointercancel",Pe);try{U.setPointerCapture(we.pointerId)}catch{}};U.addEventListener("pointerdown",ve),ht=U,vn.insertBefore(U,Ze.element),ln=()=>{U.removeEventListener("pointerdown",ve)}}if(ht){let U=an.artifacts.length>0&&!rn;ht.classList.toggle("persona-hidden",!U),zr()}},Xn=()=>{var se,ve,we,He,Me,B,We,Pe,le,Be,st,qe,fe,Bt;if(!b||!Ze||((ve=(se=n.launcher)==null?void 0:se.sidebarMode)!=null?ve:!1)||jt(n)&&un(n).reveal==="emerge")return;let A=(we=e.ownerDocument.defaultView)!=null?we:window,L=(Me=(He=n.launcher)==null?void 0:He.mobileFullscreen)!=null?Me:!0,R=(We=(B=n.launcher)==null?void 0:B.mobileBreakpoint)!=null?We:640;if(L&&A.innerWidth<=R||!Cc(n,b))return;let W=(Be=(le=(Pe=n.launcher)==null?void 0:Pe.width)!=null?le:n.launcherWidth)!=null?Be:"min(400px, calc(100vw - 24px))",U=(Bt=(fe=(qe=(st=n.features)==null?void 0:st.artifacts)==null?void 0:qe.layout)==null?void 0:fe.expandedPanelWidth)!=null?Bt:"min(720px, calc(100vw - 24px))";an.artifacts.length>0&&!rn?(N.style.width=U,N.style.maxWidth=U):(N.style.width=W,N.style.maxWidth=W)},typeof ResizeObserver!="undefined"&&(Z=new ResizeObserver(()=>{Cn()}),Z.observe(N))}else N.appendChild(ee);e.appendChild(Te);let Zn=()=>{var dt,tn,Jt,Xt,$t,pn,Je,At,Ho,Bo,Do,No,Oo,Ts,Ms,Pt,$o,to,no,Tr,Fo,Un;let l=jt(n),g=(tn=(dt=n.launcher)==null?void 0:dt.sidebarMode)!=null?tn:!1,y=l||g||((Xt=(Jt=n.launcher)==null?void 0:Jt.fullHeight)!=null?Xt:!1),A=(($t=n.launcher)==null?void 0:$t.enabled)===!1,L=(Je=(pn=n.theme)==null?void 0:pn.components)==null?void 0:Je.panel,R=go(n),W=(Kt,Ft)=>{var An;return Kt==null||Kt===""?Ft:(An=co(R,Kt))!=null?An:Kt},U=(At=e.ownerDocument.defaultView)!=null?At:window,O=(Bo=(Ho=n.launcher)==null?void 0:Ho.mobileFullscreen)!=null?Bo:!0,se=(No=(Do=n.launcher)==null?void 0:Do.mobileBreakpoint)!=null?No:640,ve=U.innerWidth<=se,we=O&&ve&&b,He=(Ts=(Oo=n.launcher)==null?void 0:Oo.position)!=null?Ts:"bottom-left",Me=He==="bottom-left"||He==="top-left",B=(Pt=(Ms=n.launcher)==null?void 0:Ms.zIndex)!=null?Pt:9999,We=g||we?"none":"1px solid var(--persona-border)",Pe=we?"none":g?Me?"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&&(Pe="none",We="none");let le=g||we?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Be=W(L==null?void 0:L.border,We),st=W(L==null?void 0:L.shadow,Pe),qe=W(L==null?void 0:L.borderRadius,le);if(e.style.cssText="",Te.style.cssText="",N.style.cssText="",ee.style.cssText="",q.style.cssText="",ot.style.cssText="",we){Te.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"),Te.style.cssText=`
20
+ `,k.addEventListener("click",()=>{d=O,x.forEach((V,ge)=>{let ie=ge<O;V.classList.toggle("selected",ie),V.setAttribute("aria-checked",ge===O-1?"true":"false")})}),x.push(k),b.appendChild(k)}f.appendChild(b);let M=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=o,M.rows=3,M.setAttribute("aria-label","Additional comments"),O.appendChild(M),f.appendChild(O)}let F=document.createElement("div");F.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{t==null||t(),u.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(d===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let O=(M==null?void 0:M.value.trim())||void 0;await r(d,O),u.remove()}catch(O){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",O)}}),F.appendChild(S),F.appendChild(I),f.appendChild(F),u.appendChild(f),u}function ys(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:p=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-nps",d.setAttribute("role","dialog"),d.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 A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=n,v.appendChild(A);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,v.appendChild(b),m.appendChild(v);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let S=document.createElement("span");S.className="persona-feedback-label-high",S.textContent=u,M.appendChild(F),M.appendChild(S);let I=document.createElement("div");I.className="persona-feedback-numbers";let O=[];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=_,O.forEach((Te,le)=>{Te.classList.toggle("selected",le===_),Te.setAttribute("aria-checked",le===_?"true":"false")})}),O.push(ne),I.appendChild(ne)}x.appendChild(M),x.appendChild(I),m.appendChild(x);let k=null;if(p){let _=document.createElement("div");_.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"),_.appendChild(k),m.appendChild(_)}let V=document.createElement("div");V.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(),d.remove()});let ie=document.createElement("button");return ie.type="button",ie.className="persona-feedback-btn persona-feedback-btn-submit",ie.textContent=a,ie.addEventListener("click",async()=>{if(f===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}ie.disabled=!0,ie.textContent="Submitting...";try{let _=(k==null?void 0:k.value.trim())||void 0;await r(f,_),d.remove()}catch(_){ie.disabled=!1,ie.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),V.appendChild(ge),V.appendChild(ie),m.appendChild(V),d.appendChild(m),d}var _r="persona-chat-history",Mp=30*1e3,kp={"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 Lp(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 p=(s=kp[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${p}`,{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 Ip(e){var r,t,n,s,o,a,i,p,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:(p=(i=e.persist)==null?void 0:i.focusInput)!=null?p:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Pp(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Zs=e=>!e||typeof e!="object"?{}:{...e},Wc=e=>e.map(r=>({...r,streaming:!1})),Rc=(e,r,t)=>{let n=e!=null&&e.markdown?cr(e.markdown):null,s=Ir(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,u,d;let a=(c=o.text)!=null?c:"",i=(u=o.message.rawContent)!=null?u: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 p;return e!=null&&e.postprocessMessage?p=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):n?p=n(a):p=Lr(a),s?s(p):p}},bs=(e,r,t)=>{var Ee,ct,Rt,Mt,Nt,Ht,dt,ut,It,gt,Ot,en,dn,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Ia,Pa,Wa,Ra,Ha,Ba,Da,Na,Oa,$a,Fa;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=ds(r),s=vo.getForInstance(n.plugins);n.components&&Nn.registerAll(n.components);let o=kc(),a=(Ee=n.storageAdapter)!=null?Ee:ps(),i={},p=null,c=!1,u=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")p=l.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return u(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=u(g);y.metadata&&(i=Zs(y.metadata)),(ct=y.messages)!=null&&ct.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=u({messages:[],metadata:{}});(Rt=l.messages)!=null&&Rt.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let d=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},Yr()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Co],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[yr.message,yr.messageAndClick],A=wo({parsers:m,handlers:v,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let b=(Nt=(Mt=n.launcher)==null?void 0:Mt.enabled)!=null?Nt:!0,x=(dt=(Ht=n.launcher)==null?void 0:Ht.autoExpand)!=null?dt:!1,M=(ut=n.autoFocusInput)!=null?ut:!1,F=x,S=b,I=(gt=(It=n.layout)==null?void 0:It.header)==null?void 0:gt.layout,O=!1,k=b?x:!0,V=!1,ge=null,ie=()=>{V=!0,ge&&clearTimeout(ge),ge=setTimeout(()=>{V&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),V=!1)},1e4)},_=Rc(n,A,ie),ne=(en=(Ot=n.features)==null?void 0:Ot.showReasoning)!=null?en:!0,Te=(ha=(dn=n.features)==null?void 0:dn.showToolCalls)!=null?ha:!0,le=(ba=(ya=n.features)==null?void 0:ya.showEventStreamToggle)!=null?ba:!1,de=`${(va=typeof n.persistState=="object"?(xa=n.persistState)==null?void 0:xa.keyPrefix:void 0)!=null?va:"persona-"}event-stream`,Y=le?new xo(de):null,ce=(Sa=(wa=(Ca=n.features)==null?void 0:Ca.eventStream)==null?void 0:wa.maxEvents)!=null?Sa:2e3,q=le?new bo(ce,Y):null,G=null,ve=!1,xe=null,Ke=0;Y==null||Y.open().then(()=>q==null?void 0:q.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Xe={onCopy:l=>{var g,y;o.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.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),H!=null&&H.isClientTokenMode()&&H.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)}},mt=(Aa=n.statusIndicator)!=null?Aa:{},Be=l=>{var g,y,E,L;return l==="idle"?(g=mt.idleText)!=null?g:Gt.idle:l==="connecting"?(y=mt.connectingText)!=null?y:Gt.connecting:l==="connected"?(E=mt.connectedText)!=null?E:Gt.connected:l==="error"?(L=mt.errorText)!=null?L:Gt.error:Gt[l]};function rt(l,g,y,E){if(E==="idle"&&y.idleLink){l.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=g,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=g}let{wrapper:Me,panel:D}=dc(n),se=pc(n,b),{container:te,body:z,messagesWrapper:oe,suggestions:Le,textarea:Z,sendButton:J,sendButtonWrapper:ze,composerForm:Ue,statusText:St,introTitle:qt,introSubtitle:Ut,closeButton:K,iconHolder:Ie,headerTitle:ft,headerSubtitle:yt,header:Ze,footer:it,actionsRow:Wt,leftActions:Vt,rightActions:ue}=se,T=se.micButton,Ae=se.micButtonWrapper,re=se.attachmentButton,ye=se.attachmentButtonWrapper,Ce=se.attachmentInput,Qe=se.attachmentPreviewsContainer,he=null,Pe=null,Ne=s.find(l=>l.renderHeader);if(Ne!=null&&Ne.renderHeader){let l=Ne.renderHeader({config:n,defaultRenderer:()=>{let g=Dn({config:n,showClose:b});return fr(te,g,n),g.header},onClose:()=>vt(!1,"user")});if(l){let g=te.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Ze=l)}}let ot=()=>{var g,y,E,L;if(!q)return;if(ve=!0,!G&&q&&(G=yc({buffer:q,getFullHistory:()=>q.getAllFromStore(),onClose:()=>At(),config:n,plugins:s})),G&&(z.style.display="none",(g=it.parentNode)==null||g.insertBefore(G.element,it),G.update()),Oe){Oe.classList.remove("persona-text-persona-muted"),Oe.classList.add("persona-text-persona-accent"),Oe.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let W=(L=(E=(y=n.features)==null?void 0:y.eventStream)==null?void 0:E.classNames)==null?void 0:L.toggleButtonActive;W&&W.split(/\s+/).forEach(P=>P&&Oe.classList.add(P))}let l=()=>{if(!ve)return;let W=Date.now();W-Ke>=200&&(G==null||G.update(),Ke=W),xe=requestAnimationFrame(l)};Ke=0,xe=requestAnimationFrame(l),o.emit("eventStream:opened",{timestamp:Date.now()})},At=()=>{var l,g,y;if(ve){if(ve=!1,G&&G.element.remove(),z.style.display="",Oe){Oe.classList.remove("persona-text-persona-accent"),Oe.classList.add("persona-text-persona-muted"),Oe.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(L=>L&&Oe.classList.remove(L))}xe!==null&&(cancelAnimationFrame(xe),xe=null),o.emit("eventStream:closed",{timestamp:Date.now()})}},Oe=null;if(le){let l=(Ta=(Ea=n.features)==null?void 0:Ea.eventStream)==null?void 0:Ta.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");Oe=h("button",g),Oe.style.width="28px",Oe.style.height="28px",Oe.type="button",Oe.setAttribute("aria-label","Event Stream"),Oe.title="Event Stream";let y=fe("activity","18px","currentColor",1.5);y&&Oe.appendChild(y);let E=se.clearChatButtonWrapper,L=se.closeButtonWrapper,W=E||L;W&&W.parentNode===Ze?Ze.insertBefore(Oe,W):Ze.appendChild(Oe),Oe.addEventListener("click",()=>{ve?At():ot()})}let Yn=l=>{var E,L,W;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 P=l.querySelector("[data-persona-composer-form]");P!=null&&P.parentNode?P.parentNode.insertBefore(y,P):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let P=h("input");P.type="file",P.accept=((E=g.allowedTypes)!=null?E:Bn).join(","),P.multiple=((L=g.maxFiles)!=null?L:4)>1,P.style.display="none",P.setAttribute("aria-label",(W=g.buttonTooltipText)!=null?W:"Attach files"),l.appendChild(P)}},xn=s.find(l=>l.renderComposer);if(xn!=null&&xn.renderComposer){let l=n.composer,g=xn.renderComposer({config:n,defaultRenderer:()=>Br({config:n}).footer,onSubmit:y=>{H&&!H.isStreaming()&&H.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ce==null||Ce.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y}},onVoiceToggle:((Ma=n.voiceRecognition)==null?void 0:Ma.enabled)===!0?()=>{Pe==null||Pe()}:void 0});g&&(it.replaceWith(g),it=g)}let Xn=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),W=l.querySelector("[data-persona-composer-status]");g&&(Ue=g),y&&(Z=y),E&&(J=E),L&&(T=L,Ae=L.parentElement),W&&(St=W);let P=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");P&&(Le=P);let U=l.querySelector(".persona-attachment-button");U&&(re=U,ye=U.parentElement),Ce=l.querySelector('input[type="file"]'),Qe=l.querySelector(".persona-attachment-previews");let N=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");N&&(Wt=N)};Yn(it),Xn(it);let $n=(ka=n.layout)==null?void 0:ka.contentMaxWidth;$n&&Ue&&(Ue.style.maxWidth=$n,Ue.style.marginLeft="auto",Ue.style.marginRight="auto"),(La=n.attachments)!=null&&La.enabled&&Ce&&Qe&&(he=mr.fromConfig(n.attachments),he.setPreviewsContainer(Qe),Ce.addEventListener("change",l=>{let g=l.target;he==null||he.handleFileSelect(g.files),g.value=""})),(()=>{var E,L;let l=(L=(E=n.layout)==null?void 0:E.slots)!=null?L:{},g=W=>{switch(W){case"body-top":return te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return oe;case"footer-top":return Le;case"composer":return Ue;case"footer-bottom":return St;default:return null}},y=(W,P)=>{var U;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")Ze.insertBefore(P,Ze.firstChild);else if(W==="header-right")Ze.appendChild(P);else{let N=Ze.querySelector(".persona-flex-col");N?(U=N.parentNode)==null||U.insertBefore(P,N.nextSibling):Ze.appendChild(P)}break;case"body-top":{let N=z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(P):z.insertBefore(P,z.firstChild);break}case"body-bottom":z.appendChild(P);break;case"footer-top":Le.replaceWith(P);break;case"footer-bottom":St.replaceWith(P);break;default:break}};for(let[W,P]of Object.entries(l))if(P)try{let U=P({config:n,defaultContent:()=>g(W)});U&&y(W,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,U)}})();let Fn=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let E=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let W=y.getAttribute("data-bubble-type");W==="reasoning"?(Nr.has(L)?Nr.delete(L):Nr.add(L),mc(L,E)):W==="tool"&&(Or.has(L)?Or.delete(L):Or.add(L),fc(L,E,n))};oe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Fn(l))}),oe.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Fn(l))});let Mn=new Map;oe.addEventListener("click",l=>{var P;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 L=E.getAttribute("data-actions-for");if(!L)return;let W=y.getAttribute("data-action");if(W==="copy"){let N=H.getMessages().find(ae=>ae.id===L);if(N&&Xe.onCopy){let ae=N.content||"";navigator.clipboard.writeText(ae).then(()=>{y.classList.add("persona-message-action-success");let be=fe("check",14,"currentColor",2);be&&(y.innerHTML="",y.appendChild(be)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let we=fe("copy",14,"currentColor",2);we&&(y.innerHTML="",y.appendChild(we))},2e3)}).catch(be=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",be)}),Xe.onCopy(N)}}else if(W==="upvote"||W==="downvote")if(((P=Mn.get(L))!=null?P:null)===W)Mn.delete(L),y.classList.remove("persona-message-action-active");else{let ae=W==="upvote"?"downvote":"upvote",be=E.querySelector(`[data-action="${ae}"]`);be&&be.classList.remove("persona-message-action-active"),Mn.set(L,W),y.classList.add("persona-message-action-active");let We=H.getMessages().find(Se=>Se.id===L);We&&Xe.onFeedback&&Xe.onFeedback({type:W,messageId:We.id,message:We})}}),oe.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest(".vanilla-approval-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let W=y.getAttribute("data-approval-action");if(!W)return;let P=W==="approve"?"approved":"denied",N=H.getMessages().find(be=>be.id===L);if(!(N!=null&&N.approval))return;let ae=E.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(we=>{we.disabled=!0,we.style.opacity="0.5",we.style.cursor="not-allowed"}),H.resolveApproval(N.approval,P)});let et=null,X=null,an={artifacts:[],selectedId:null},rn=!1,jr={current:null};oe.addEventListener("click",l=>{var we,We,Se,R,He;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.getAttribute("data-download-artifact");if(!E||((Se=(We=(we=n.features)==null?void 0:we.artifacts)==null?void 0:We.onArtifactAction)==null?void 0:Se.call(We,{type:"download",artifactId:E}))===!0)return;let W=H.getArtifactById(E),P=W==null?void 0:W.markdown,U=(W==null?void 0:W.title)||"artifact";if(!P){let Re=y.closest("[data-open-artifact]"),pe=Re==null?void 0:Re.closest("[data-message-id]"),De=pe==null?void 0:pe.getAttribute("data-message-id");if(De){let Je=H.getMessages().find(me=>me.id===De);if(Je!=null&&Je.rawContent)try{let me=JSON.parse(Je.rawContent);P=(R=me==null?void 0:me.props)==null?void 0:R.markdown,U=((He=me==null?void 0:me.props)==null?void 0:He.title)||U}catch{}}}if(!P)return;let N=new Blob([P],{type:"text/markdown"}),ae=URL.createObjectURL(N),be=document.createElement("a");be.href=ae,be.download=`${U}.md`,be.click(),URL.revokeObjectURL(ae)}),oe.addEventListener("click",l=>{var W,P,U;let y=l.target.closest("[data-open-artifact]");if(!y)return;let E=y.getAttribute("data-open-artifact");!E||((U=(P=(W=n.features)==null?void 0:W.artifacts)==null?void 0:P.onArtifactAction)==null?void 0:U.call(P,{type:"open",artifactId:E}))===!0||(l.preventDefault(),l.stopPropagation(),H.selectArtifact(E),Cn())}),oe.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,ht=null,ln=null,kn=null,zr=()=>{};function vr(){kn==null||kn(),kn=null}let qr=()=>{var P;if(!vn||!ht)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((P=e.ownerDocument.defaultView)!=null?P:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){ht.style.removeProperty("position"),ht.style.removeProperty("left"),ht.style.removeProperty("top"),ht.style.removeProperty("bottom"),ht.style.removeProperty("width"),ht.style.removeProperty("z-index");return}let E=vn.firstElementChild;if(!E||E===ht)return;let L=10;ht.style.position="absolute",ht.style.top="0",ht.style.bottom="0",ht.style.width=`${L}px`,ht.style.zIndex="5";let W=E.offsetWidth-L/2;ht.style.left=`${Math.max(0,W)}px`},Zn=()=>{},Cn=()=>{var y,E,L,W,P;if(!et||!gn(n))return;ls(e,n),cs(e,n),Zn();let l=(W=(L=(E=(y=n.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:L.narrowHostMaxWidth)!=null?W:520,g=D.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),et.update(an),rn?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),(P=et.backdrop)==null||P.classList.add("persona-hidden")):an.artifacts.length>0&&(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)),zr()};if(gn(n)){D.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(te),et=vc(n,{onSelect:y=>{var E;return(E=jr.current)==null?void 0:E.selectArtifact(y)},onDismiss:()=>{rn=!0,Cn()}}),et.element.classList.add("persona-hidden"),vn=g,g.appendChild(l),g.appendChild(et.element),et.backdrop&&D.appendChild(et.backdrop),D.appendChild(g),zr=()=>{var E,L,W,P;if(!vn||!et)return;if(!(((W=(L=(E=n.features)==null?void 0:E.artifacts)==null?void 0:L.layout)==null?void 0:W.resizable)===!0)){ln==null||ln(),ln=null,vr(),ht&&(ht.remove(),ht=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!ht){let U=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let N=e.ownerDocument,ae=(P=N.defaultView)!=null?P:window,be=we=>{var pe,De;if(!et||we.button!==0||e.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;we.preventDefault(),vr();let We=we.clientX,Se=et.element.getBoundingClientRect().width,R=(De=(pe=n.features)==null?void 0:pe.artifacts)==null?void 0:De.layout,He=lt=>{let Je=vn.getBoundingClientRect().width,me=e.classList.contains("persona-artifact-appearance-seamless"),Bt=me?0:Ac(vn,ae),pt=me?0:U.getBoundingClientRect().width||6,tn=Se-(lt.clientX-We),Jt=Ec(tn,Je,Bt,pt,R==null?void 0:R.resizableMinWidth,R==null?void 0:R.resizableMaxWidth);et.element.style.width=`${Jt}px`,et.element.style.maxWidth="none",qr()},Re=()=>{N.removeEventListener("pointermove",He),N.removeEventListener("pointerup",Re),N.removeEventListener("pointercancel",Re),kn=null;try{U.releasePointerCapture(we.pointerId)}catch{}};kn=Re,N.addEventListener("pointermove",He),N.addEventListener("pointerup",Re),N.addEventListener("pointercancel",Re);try{U.setPointerCapture(we.pointerId)}catch{}};U.addEventListener("pointerdown",be),ht=U,vn.insertBefore(U,et.element),ln=()=>{U.removeEventListener("pointerdown",be)}}if(ht){let U=an.artifacts.length>0&&!rn;ht.classList.toggle("persona-hidden",!U),qr()}},Zn=()=>{var ae,be,we,We,Se,R,He,Re,pe,De,lt,Je,me,Bt;if(!b||!et||((be=(ae=n.launcher)==null?void 0:ae.sidebarMode)!=null?be:!1)||jt(n)&&un(n).reveal==="emerge")return;let E=(we=e.ownerDocument.defaultView)!=null?we:window,L=(Se=(We=n.launcher)==null?void 0:We.mobileFullscreen)!=null?Se:!0,W=(He=(R=n.launcher)==null?void 0:R.mobileBreakpoint)!=null?He:640;if(L&&E.innerWidth<=W||!Sc(n,b))return;let P=(De=(pe=(Re=n.launcher)==null?void 0:Re.width)!=null?pe:n.launcherWidth)!=null?De:"min(400px, calc(100vw - 24px))",U=(Bt=(me=(Je=(lt=n.features)==null?void 0:lt.artifacts)==null?void 0:Je.layout)==null?void 0:me.expandedPanelWidth)!=null?Bt:"min(720px, calc(100vw - 24px))";an.artifacts.length>0&&!rn?(D.style.width=U,D.style.maxWidth=U):(D.style.width=P,D.style.maxWidth=P)},typeof ResizeObserver!="undefined"&&(X=new ResizeObserver(()=>{Cn()}),X.observe(D))}else D.appendChild(te);e.appendChild(Me);let Qn=()=>{var pt,tn,Jt,Xt,$t,pn,Ge,wt,Bo,Do,No,Oo,$o,Ms,ks,Pt,Fo,no,ro,kr,_o,Un;let l=jt(n),g=(tn=(pt=n.launcher)==null?void 0:pt.sidebarMode)!=null?tn:!1,y=l||g||((Xt=(Jt=n.launcher)==null?void 0:Jt.fullHeight)!=null?Xt:!1),E=(($t=n.launcher)==null?void 0:$t.enabled)===!1,L=(Ge=(pn=n.theme)==null?void 0:pn.components)==null?void 0:Ge.panel,W=mo(n),P=(Kt,Ft)=>{var An;return Kt==null||Kt===""?Ft:(An=po(W,Kt))!=null?An:Kt},U=(wt=e.ownerDocument.defaultView)!=null?wt:window,N=(Do=(Bo=n.launcher)==null?void 0:Bo.mobileFullscreen)!=null?Do:!0,ae=(Oo=(No=n.launcher)==null?void 0:No.mobileBreakpoint)!=null?Oo:640,be=U.innerWidth<=ae,we=N&&be&&b,We=(Ms=($o=n.launcher)==null?void 0:$o.position)!=null?Ms:"bottom-left",Se=We==="bottom-left"||We==="top-left",R=(Pt=(ks=n.launcher)==null?void 0:ks.zIndex)!=null?Pt:9999,He=g||we?"none":"1px solid var(--persona-border)",Re=we?"none":g?Se?"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&&(Re="none",He="none");let pe=g||we?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",De=P(L==null?void 0:L.border,He),lt=P(L==null?void 0:L.shadow,Re),Je=P(L==null?void 0:L.borderRadius,pe);if(e.style.cssText="",Me.style.cssText="",D.style.cssText="",te.style.cssText="",z.style.cssText="",it.style.cssText="",we){Me.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"),Me.style.cssText=`
21
21
  position: fixed !important;
22
22
  inset: 0 !important;
23
23
  width: 100% !important;
@@ -27,9 +27,9 @@
27
27
  padding: 0 !important;
28
28
  display: flex !important;
29
29
  flex-direction: column !important;
30
- z-index: ${B} !important;
30
+ z-index: ${R} !important;
31
31
  background-color: var(--persona-surface, #ffffff) !important;
32
- `,N.style.cssText=`
32
+ `,D.style.cssText=`
33
33
  position: relative !important;
34
34
  display: flex !important;
35
35
  flex-direction: column !important;
@@ -42,7 +42,7 @@
42
42
  padding: 0 !important;
43
43
  box-shadow: none !important;
44
44
  border-radius: 0 !important;
45
- `,ee.style.cssText=`
45
+ `,te.style.cssText=`
46
46
  display: flex !important;
47
47
  flex-direction: column !important;
48
48
  flex: 1 1 0% !important;
@@ -53,7 +53,7 @@
53
53
  overflow: hidden !important;
54
54
  border-radius: 0 !important;
55
55
  border: none !important;
56
- `,q.style.flex="1 1 0%",q.style.minHeight="0",q.style.overflowY="auto",ot.style.flexShrink="0",$=!0;return}let fe=(to=($o=n==null?void 0:n.launcher)==null?void 0:$o.width)!=null?to:n==null?void 0:n.launcherWidth,Bt=fe!=null?fe:"min(400px, calc(100vw - 24px))";if(!g&&!l)A&&y?(N.style.width="100%",N.style.maxWidth="100%"):(N.style.width=Bt,N.style.maxWidth=Bt);else if(l)if(un(n).reveal==="emerge"){let Ft=un(n).width;N.style.width=Ft,N.style.maxWidth=Ft}else N.style.width="100%",N.style.maxWidth="100%";if(Xn(),N.style.boxShadow=st,N.style.borderRadius=qe,ee.style.border=Be,ee.style.borderRadius=qe,l&&!we&&(L==null?void 0:L.border)===void 0&&(ee.style.border="none",un(n).side==="right"?ee.style.borderLeft="1px solid var(--persona-border)":ee.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",A&&(e.style.width="100%"),Te.style.display="flex",Te.style.flexDirection="column",Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.maxHeight="100%",Te.style.height="100%",A&&(Te.style.overflow="hidden"),N.style.display="flex",N.style.flexDirection="column",N.style.flex="1 1 0%",N.style.minHeight="0",N.style.maxHeight="100%",N.style.height="100%",N.style.overflow="hidden",ee.style.display="flex",ee.style.flexDirection="column",ee.style.flex="1 1 0%",ee.style.minHeight="0",ee.style.maxHeight="100%",ee.style.overflow="hidden",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.overflowY="auto",ot.style.flexShrink="0"),Te.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"),!g&&!A&&!l&&((no=yn[He])!=null?no:yn["bottom-right"]).split(" ").forEach(Ft=>Te.classList.add(Ft)),g){let Kt=(Fo=(Tr=n.launcher)==null?void 0:Tr.sidebarWidth)!=null?Fo:"420px";Te.style.cssText=`
56
+ `,z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",it.style.flexShrink="0",O=!0;return}let me=(no=(Fo=n==null?void 0:n.launcher)==null?void 0:Fo.width)!=null?no:n==null?void 0:n.launcherWidth,Bt=me!=null?me:"min(400px, calc(100vw - 24px))";if(!g&&!l)E&&y?(D.style.width="100%",D.style.maxWidth="100%"):(D.style.width=Bt,D.style.maxWidth=Bt);else if(l)if(un(n).reveal==="emerge"){let Ft=un(n).width;D.style.width=Ft,D.style.maxWidth=Ft}else D.style.width="100%",D.style.maxWidth="100%";if(Zn(),D.style.boxShadow=lt,D.style.borderRadius=Je,te.style.border=De,te.style.borderRadius=Je,l&&!we&&(L==null?void 0:L.border)===void 0&&(te.style.border="none",un(n).side==="right"?te.style.borderLeft="1px solid var(--persona-border)":te.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",E&&(e.style.width="100%"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",E&&(Me.style.overflow="hidden"),D.style.display="flex",D.style.flexDirection="column",D.style.flex="1 1 0%",D.style.minHeight="0",D.style.maxHeight="100%",D.style.height="100%",D.style.overflow="hidden",te.style.display="flex",te.style.flexDirection="column",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.maxHeight="100%",te.style.overflow="hidden",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",it.style.flexShrink="0"),Me.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"),!g&&!E&&!l&&((ro=yn[We])!=null?ro:yn["bottom-right"]).split(" ").forEach(Ft=>Me.classList.add(Ft)),g){let Kt=(_o=(kr=n.launcher)==null?void 0:kr.sidebarWidth)!=null?_o:"420px";Me.style.cssText=`
57
57
  position: fixed !important;
58
58
  top: 0 !important;
59
59
  bottom: 0 !important;
@@ -64,9 +64,9 @@
64
64
  padding: 0 !important;
65
65
  display: flex !important;
66
66
  flex-direction: column !important;
67
- z-index: ${B} !important;
68
- ${Me?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
69
- `,N.style.cssText=`
67
+ z-index: ${R} !important;
68
+ ${Se?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
69
+ `,D.style.cssText=`
70
70
  position: relative !important;
71
71
  display: flex !important;
72
72
  flex-direction: column !important;
@@ -77,9 +77,9 @@
77
77
  min-height: 0 !important;
78
78
  margin: 0 !important;
79
79
  padding: 0 !important;
80
- box-shadow: ${st} !important;
81
- border-radius: ${qe} !important;
82
- `,N.style.setProperty("width","100%","important"),N.style.setProperty("max-width","100%","important"),ee.style.cssText=`
80
+ box-shadow: ${lt} !important;
81
+ border-radius: ${Je} !important;
82
+ `,D.style.setProperty("width","100%","important"),D.style.setProperty("max-width","100%","important"),te.style.cssText=`
83
83
  display: flex !important;
84
84
  flex-direction: column !important;
85
85
  flex: 1 1 0% !important;
@@ -88,29 +88,29 @@
88
88
  min-height: 0 !important;
89
89
  max-height: 100% !important;
90
90
  overflow: hidden !important;
91
- border-radius: ${qe} !important;
92
- border: ${Be} !important;
93
- `,ot.style.cssText=`
91
+ border-radius: ${Je} !important;
92
+ border: ${De} !important;
93
+ `,it.style.cssText=`
94
94
  flex-shrink: 0 !important;
95
95
  border-top: none !important;
96
96
  padding: 8px 16px 12px 16px !important;
97
- `}if(!A&&!l){let Kt="max-height: -moz-available !important; max-height: stretch !important;",Ft=g?"":"padding-top: 1.25em !important;",An=!g&&((Un=n.launcher)==null?void 0:Un.zIndex)!=null?`z-index: ${n.launcher.zIndex} !important;`:"";Te.style.cssText+=Kt+Ft+An}};Zn(),Vn(e,n),is(e,n),ls(e,n);let Tt=[];Z&&Tt.push(()=>{Z==null||Z.disconnect(),Z=null}),Tt.push(()=>{ln==null||ln(),ln=null,br(),ht&&(ht.remove(),ht=null),Ze==null||Ze.element.style.removeProperty("width"),Ze==null||Ze.element.style.removeProperty("maxWidth")}),ie&&Tt.push(()=>{at!==null&&(cancelAnimationFrame(at),at=null),J==null||J.destroy(),J=null,F==null||F.destroy(),F=null,Y=null});let wn=null,qr=()=>{wn&&(wn(),wn=null),n.colorScheme==="auto"&&(wn=rs(()=>{Vn(e,n)}))};qr(),Tt.push(()=>{wn&&(wn(),wn=null)});let _n=mc(ke),Sn=null,D,jn=!1,zn=oc(),Ur=0,Ln=!0,Qn=0,Vr=0,In=null,Pn=!1,xr=0,vr=!1,So=125,Ao=2e3,Eo=5,Jr=50,Cr=new Map,ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Kr=(Ia=(La=n.voiceRecognition)==null?void 0:La.autoResume)!=null?Ia:!1,cn=l=>{o.emit("voice:state",{active:ze.active,source:l,timestamp:Date.now()})},Qt=()=>{f(l=>({...l,voiceState:{active:ze.active,timestamp:Date.now(),manuallyDeactivated:ze.manuallyDeactivated}}))},To=()=>{var A,L;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Ys(i.voiceState),g=!!l.active,y=Number((L=l.timestamp)!=null?L:0);ze.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<Ap&&setTimeout(()=>{var R,W;ze.active||(ze.manuallyDeactivated=!1,((W=(R=n.voiceRecognition)==null?void 0:R.provider)==null?void 0:W.type)==="runtype"?D.toggleVoice().then(()=>{ze.active=D.isVoiceActive(),cn("restore"),D.isVoiceActive()&&qn()}):rr("restore"))},1e3)},Mo=()=>D?Ic(D.getMessages()).filter(l=>!l.__skipPersist):[];function Gr(l){if(!(a!=null&&a.save))return;let y={messages:l?Ic(l):D?Mo():[],metadata:i};try{let A=a.save(y);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 er=(l=!1)=>{if(!Ln)return;let g=Date.now();Pn&&g<xr&&!l||(Pn&&g>=xr&&(Pn=!1),!(!l&&!jn)&&(g-Vr<So||(Vr=g,In&&cancelAnimationFrame(In),In=requestAnimationFrame(()=>{Pn||!Ln||(vr=!0,q.scrollTop=q.scrollHeight,Qn=q.scrollTop,requestAnimationFrame(()=>{vr=!1}),In=null)}))))},Wn=null,ko=()=>Te.querySelector("#persona-scroll-container")||q,Lo=(l,g=500)=>{let y=l.scrollTop,A=l.clientHeight,L=l.scrollHeight,R=L-y;if(y+A>=L-2||Math.abs(R)<5)return;Wn!==null&&(cancelAnimationFrame(Wn),Wn=null);let U=performance.now(),O=ve=>1-Math.pow(1-ve,3),se=ve=>{let we=l.scrollHeight;we!==L&&(L=we,R=L-y);let He=ve-U,Me=Math.min(He/g,1),B=O(Me),We=y+R*B;l.scrollTop=We,Me<1?Wn=requestAnimationFrame(se):(l.scrollTop=l.scrollHeight,Wn=null)};Wn=requestAnimationFrame(se)},Io=l=>{let g=new Map;l.forEach(y=>{let A=Cr.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!A&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(A!=null&&A.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(A?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Cr.clear(),g.forEach((y,A)=>{Cr.set(A,y)})},tr=(l,g,y)=>{var ve,we,He,Me;let A=document.createElement("div"),R=(()=>{var We;let B=s.find(Pe=>Pe.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((We=n.loadingIndicator)!=null&&We.render)return n.loadingIndicator.render})(),W=new Set;g.forEach(B=>{var fe,Bt;W.add(B.id);let We=rc(B,Ur),Pe=sc(zn,B.id,We);if(Pe){A.appendChild(Pe.cloneNode(!0));return}let le=null,Be=s.find(dt=>!!(B.variant==="reasoning"&&dt.renderReasoning||B.variant==="tool"&&dt.renderToolCall||B.variant==="approval"&&dt.renderApproval||!B.variant&&dt.renderMessage)),st=(fe=n.layout)==null?void 0:fe.messages;if(Be)if(B.variant==="reasoning"&&B.reasoning&&Be.renderReasoning){if(!te)return;le=Be.renderReasoning({message:B,defaultRenderer:()=>js(B),config:n})}else if(B.variant==="tool"&&B.toolCall&&Be.renderToolCall){if(!Ae)return;le=Be.renderToolCall({message:B,defaultRenderer:()=>zs(B,n),config:n})}else if(B.variant==="approval"&&B.approval&&Be.renderApproval){if(n.approval===!1)return;le=Be.renderApproval({message:B,defaultRenderer:()=>qs(B,n),config:n})}else Be.renderMessage&&(le=Be.renderMessage({message:B,defaultRenderer:()=>{let dt=Br(B,y,st,n.messageActions,Ke,{loadingIndicatorRenderer:R,widgetConfig:n});return B.role!=="user"&&Js(dt,B,n,D),dt},config:n}));if(!le&&B.role==="assistant"&&!B.variant&&n.enableComponentStreaming!==!1&&gs(B)){let tn=ms(B);if(tn){let Jt=us(tn,{config:n,message:B,transform:y});if(Jt)if(n.wrapComponentDirectiveInBubble!==!1){let $t=document.createElement("div");if($t.className=["vanilla-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),$t.id=`bubble-${B.id}`,$t.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let pn=document.createElement("div");pn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",pn.innerHTML=y({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),$t.appendChild(pn)}$t.appendChild(Jt),le=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${B.id}`,$t.setAttribute("data-message-id",B.id),$t.setAttribute("data-persona-component-directive","true"),B.content&&B.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:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),$t.appendChild(pn)}$t.appendChild(Jt),le=$t}}}if(!le)if(B.variant==="reasoning"&&B.reasoning){if(!te)return;le=js(B)}else if(B.variant==="tool"&&B.toolCall){if(!Ae)return;le=zs(B,n)}else if(B.variant==="approval"&&B.approval){if(n.approval===!1)return;le=qs(B,n)}else{let dt=(Bt=n.layout)==null?void 0:Bt.messages;dt!=null&&dt.renderUserMessage&&B.role==="user"?le=dt.renderUserMessage({message:B,config:n,streaming:!!B.streaming}):dt!=null&&dt.renderAssistantMessage&&B.role==="assistant"?le=dt.renderAssistantMessage({message:B,config:n,streaming:!!B.streaming}):le=Br(B,y,dt,n.messageActions,Ke,{loadingIndicatorRenderer:R,widgetConfig:n}),B.role!=="user"&&le&&Js(le,B,n,D)}let qe=document.createElement("div");qe.className="persona-flex",qe.id=`wrapper-${B.id}`,qe.setAttribute("data-wrapper-id",B.id),B.role==="user"&&qe.classList.add("persona-justify-end"),(le==null?void 0:le.getAttribute("data-persona-component-directive"))==="true"&&qe.classList.add("persona-w-full"),qe.appendChild(le),ac(zn,B.id,We,qe),A.appendChild(qe)}),ic(zn,W);let U=g.some(B=>B.role==="assistant"&&B.streaming),O=g[g.length-1],se=(O==null?void 0:O.role)==="assistant"&&!O.streaming&&O.variant!=="approval";if(jn&&g.some(B=>B.role==="user")&&!U&&!se){let B={config:n,streaming:!0,location:"standalone",defaultRenderer:mr},We=s.find(le=>le.renderLoadingIndicator),Pe=null;if(We!=null&&We.renderLoadingIndicator&&(Pe=We.renderLoadingIndicator(B)),Pe===null&&((ve=n.loadingIndicator)!=null&&ve.render)&&(Pe=n.loadingIndicator.render(B)),Pe===null&&(Pe=mr()),Pe){let le=document.createElement("div"),Be=((we=n.loadingIndicator)==null?void 0:we.showBubble)!==!1;le.className=Be?["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(" "),le.setAttribute("data-typing-indicator","true"),le.appendChild(Pe);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-typing-indicator",st.setAttribute("data-wrapper-id","typing-indicator"),st.appendChild(le),A.appendChild(st)}}if(!jn&&g.length>0){let B=g[g.length-1],We={config:n,lastMessage:B,messageCount:g.length},Pe=s.find(Be=>Be.renderIdleIndicator),le=null;if(Pe!=null&&Pe.renderIdleIndicator&&(le=Pe.renderIdleIndicator(We)),le===null&&((He=n.loadingIndicator)!=null&&He.renderIdle)&&(le=n.loadingIndicator.renderIdle(We)),le){let Be=document.createElement("div"),st=((Me=n.loadingIndicator)==null?void 0:Me.showBubble)!==!1;Be.className=st?["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(" "),Be.setAttribute("data-idle-indicator","true"),Be.appendChild(le);let qe=document.createElement("div");qe.className="persona-flex",qe.id="wrapper-idle-indicator",qe.setAttribute("data-wrapper-id","idle-indicator"),qe.appendChild(Be),A.appendChild(qe)}}nc(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let B=ko();Lo(B)})})},nr=()=>{var O,se,ve,we,He;if(!b)return;let l=jt(n),g=(O=e.ownerDocument.defaultView)!=null?O:window,y=(ve=(se=n.launcher)==null?void 0:se.mobileBreakpoint)!=null?ve:640,A=(He=(we=n.launcher)==null?void 0:we.mobileFullscreen)!=null?He:!0,L=g.innerWidth<=y,R=A&&L&&b,W=un(n).reveal;T?(Te.style.removeProperty("display"),Te.style.display=l?"flex":"",Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),N.classList.remove("persona-scale-95","persona-opacity-0"),N.classList.add("persona-scale-100","persona-opacity-100"),je?je.element.style.display="none":Ve&&(Ve.style.display="none")):(l?l&&(W==="overlay"||W==="push")&&!R?(Te.style.removeProperty("display"),Te.style.display="flex",Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),N.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Te.style.setProperty("display","none","important"),Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),N.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Te.style.display="",Te.classList.add("persona-pointer-events-none","persona-opacity-0"),N.classList.remove("persona-scale-100","persona-opacity-100"),N.classList.add("persona-scale-95","persona-opacity-0")),je?je.element.style.display=l?"none":"":Ve&&(Ve.style.display=l?"none":""))},wt=(l,g="user")=>{if(!b||T===l)return;let y=T;T=l,nr(),T&&(xt(),er(!0));let A={open:T,source:g,timestamp:Date.now()};T&&!y?o.emit("widget:opened",A):!T&&y&&o.emit("widget:closed",A),o.emit("widget:state",{open:T,launcherEnabled:b,voiceActive:ze.active,streaming:D.isStreaming()})},wr=l=>{K.disabled=l,E&&(E.disabled=l),_n.buttons.forEach(g=>{g.disabled=l}),ot.dataset.personaComposerStreaming=l?"true":"false",ot.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},Sr=()=>{ze.active||Q&&Q.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Sr(),200)});let Yr=()=>{var g,y,A,L,R,W,U,O,se,ve;qt.textContent=(y=(g=n.copy)==null?void 0:g.welcomeTitle)!=null?y:"Hello \u{1F44B}",Ut.textContent=(L=(A=n.copy)==null?void 0:A.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",Q.placeholder=(W=(R=n.copy)==null?void 0:R.inputPlaceholder)!=null?W:"How can I help...",(O=(U=n.sendButton)==null?void 0:U.useIcon)!=null&&O||(K.textContent=(ve=(se=n.copy)==null?void 0:se.sendButtonLabel)!=null?ve:"Send"),Q.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Q.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 Pr(n,{onMessagesChanged(l){tr(ce,l,z),D&&(l.some(L=>L.role==="user")?_n.render([],D,Q,l):_n.render(n.suggestionChips,D,Q,l,n.suggestionChipsConfig)),er(!jn),Io(l);let g=[...l].reverse().find(A=>A.role==="user"),y=ze.lastUserMessageId;g&&g.id!==y&&(ze.lastUserMessageId=g.id,o.emit("user:message",g)),ze.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Gr(l)},onStatusChanged(l){var A;let g=(A=n.statusIndicator)!=null?A:{};tt(Lt,(L=>{var R,W,U,O;return L==="idle"?(R=g.idleText)!=null?R:Gt.idle:L==="connecting"?(W=g.connectingText)!=null?W:Gt.connecting:L==="connected"?(U=g.connectedText)!=null?U:Gt.connected:L==="error"?(O=g.errorText)!=null?O:Gt.error:Gt[L]})(l),g,l)},onStreamingChanged(l){jn=l,wr(l),D&&tr(ce,D.getMessages(),z),l||er(!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":fn(),Wo();break;case"speaking":fn(),Ro();break;default:l==="idle"&&D.isBargeInActive()?(fn(),qn(),E==null||E.setAttribute("aria-label","End voice session")):(ze.active=!1,fn(),cn("system"),Qt());break}},onArtifactsState(l){an=l,Cn()}}),_r.current=D,((Wa=(Pa=n.voiceRecognition)==null?void 0:Pa.provider)==null?void 0:Wa.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)}),F&&D.setSSEEventCallback((l,g)=>{F==null||F.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=Ys(l.metadata),S.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 Xr=l=>{var L;l.preventDefault();let g=Q.value.trim(),y=(L=ye==null?void 0:ye.hasAttachments())!=null?L:!1;if(!g&&!y)return;let A;y&&(A=[],A.push(...ye.getContentParts()),g&&A.push(Go(g))),Q.value="",Q.style.height="auto",D.sendMessage(g,{contentParts:A}),y&&ye.clearAttachments()},Zr=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),K.click())},Qr=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!ye)return;let g=Tp(l.clipboardData);g.length!==0&&(l.preventDefault(),await ye.handleFiles(g))},Yt=null,on=!1,Rn=null,Oe=null,eo=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,rr=(l="user")=>{var R,W,U,O,se,ve,we,He;if(on||D.isStreaming())return;let g=eo();if(!g)return;Yt=new g;let A=(W=((R=n.voiceRecognition)!=null?R:{}).pauseDuration)!=null?W:2e3;Yt.continuous=!0,Yt.interimResults=!0,Yt.lang="en-US";let L=Q.value;Yt.onresult=Me=>{let B="",We="";for(let le=0;le<Me.results.length;le++){let Be=Me.results[le],st=Be[0].transcript;Be.isFinal?B+=st+" ":We=st}let Pe=L+B+We;Q.value=Pe,Rn&&clearTimeout(Rn),(B||We)&&(Rn=window.setTimeout(()=>{let le=Q.value.trim();le&&Yt&&on&&(mn(),Q.value="",Q.style.height="auto",D.sendMessage(le,{viaVoice:!0}))},A))},Yt.onerror=Me=>{Me.error!=="no-speech"&&mn()},Yt.onend=()=>{if(on){let Me=Q.value.trim();Me&&Me!==L.trim()&&(Q.value="",Q.style.height="auto",D.sendMessage(Me,{viaVoice:!0})),mn()}};try{if(Yt.start(),on=!0,ze.active=!0,l!=="system"&&(ze.manuallyDeactivated=!1),cn(l),Qt(),E){let Me=(U=n.voiceRecognition)!=null?U:{};Oe={backgroundColor:E.style.backgroundColor,color:E.style.color,borderColor:E.style.borderColor,iconName:(O=Me.iconName)!=null?O:"mic",iconSize:parseFloat((we=(ve=Me.iconSize)!=null?ve:(se=n.sendButton)==null?void 0:se.size)!=null?we:"40")||24};let B=(He=Me.recordingBackgroundColor)!=null?He:"#ef4444",We=Me.recordingIconColor,Pe=Me.recordingBorderColor;if(E.classList.add("persona-voice-recording"),E.style.backgroundColor=B,We){E.style.color=We;let le=E.querySelector("svg");le&&le.setAttribute("stroke",We)}Pe&&(E.style.borderColor=Pe),E.setAttribute("aria-label","Stop voice recognition")}}catch{mn("system")}},mn=(l="user")=>{if(on){if(on=!1,Rn&&(clearTimeout(Rn),Rn=null),Yt){try{Yt.stop()}catch{}Yt=null}if(ze.active=!1,cn(l),Qt(),E){if(E.classList.remove("persona-voice-recording"),Oe){E.style.backgroundColor=Oe.backgroundColor,E.style.color=Oe.color,E.style.borderColor=Oe.borderColor;let g=E.querySelector("svg");g&&g.setAttribute("stroke",Oe.color||"currentColor"),Oe=null}E.setAttribute("aria-label","Start voice recognition")}}},Po=(l,g)=>{var le,Be,st,qe,fe,Bt,dt,tn;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((le=l==null?void 0:l.provider)==null?void 0:le.type)==="runtype";if(!(y||A))return null;let R=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 U=(Be=l==null?void 0:l.iconName)!=null?Be:"mic",O=(st=g==null?void 0:g.size)!=null?st:"40px",se=(qe=l==null?void 0:l.iconSize)!=null?qe:O,ve=parseFloat(se)||24,we=(fe=l==null?void 0:l.backgroundColor)!=null?fe:g==null?void 0:g.backgroundColor,He=(Bt=l==null?void 0:l.iconColor)!=null?Bt:g==null?void 0:g.textColor;W.style.width=se,W.style.height=se,W.style.minWidth=se,W.style.minHeight=se,W.style.fontSize="18px",W.style.lineHeight="1";let Me=He||"currentColor",B=he(U,ve,Me,1.5);B?(W.appendChild(B),W.style.color=Me):(W.textContent="\u{1F3A4}",W.style.color=Me),we?W.style.backgroundColor=we:W.classList.add("persona-bg-persona-primary"),He?W.style.color=He:!He&&!(g!=null&&g.textColor)&&W.classList.add("persona-text-white"),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),R.appendChild(W);let We=(dt=l==null?void 0:l.tooltipText)!=null?dt:"Start voice recognition";if(((tn=l==null?void 0:l.showTooltip)!=null?tn:!1)&&We){let Jt=h("div","persona-send-button-tooltip");Jt.textContent=We,R.appendChild(Jt)}return{micButton:W,micButtonWrapper:R}},Ar=()=>{var g,y,A,L,R;if(!E||Oe)return;let l=(g=n.voiceRecognition)!=null?g:{};Oe={backgroundColor:E.style.backgroundColor,color:E.style.color,borderColor:E.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((R=(L=l.iconSize)!=null?L:(A=n.sendButton)==null?void 0:A.size)!=null?R:"40")||24}},Er=(l,g)=>{var R,W,U,O,se;if(!E)return;let y=E.querySelector("svg");y&&y.remove();let A=(se=Oe==null?void 0:Oe.iconSize)!=null?se:parseFloat((O=(U=(R=n.voiceRecognition)==null?void 0:R.iconSize)!=null?U:(W=n.sendButton)==null?void 0:W.size)!=null?O:"40")||24,L=he(l,A,g,1.5);L&&E.appendChild(L)},or=()=>{E&&E.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},qn=()=>{var L,R;if(!E)return;Ar();let l=(L=n.voiceRecognition)!=null?L:{},g=(R=l.recordingBackgroundColor)!=null?R:"#ef4444",y=l.recordingIconColor,A=l.recordingBorderColor;if(or(),E.classList.add("persona-voice-recording"),E.style.backgroundColor=g,y){E.style.color=y;let W=E.querySelector("svg");W&&W.setAttribute("stroke",y)}A&&(E.style.borderColor=A),E.setAttribute("aria-label","Stop voice recognition")},Wo=()=>{var U,O,se,ve,we,He,Me,B;if(!E)return;Ar();let l=(U=n.voiceRecognition)!=null?U:{},g=D.getVoiceInterruptionMode(),y=(O=l.processingIconName)!=null?O:"loader",A=(ve=(se=l.processingIconColor)!=null?se:Oe==null?void 0:Oe.color)!=null?ve:"",L=(He=(we=l.processingBackgroundColor)!=null?we:Oe==null?void 0:Oe.backgroundColor)!=null?He:"",R=(B=(Me=l.processingBorderColor)!=null?Me:Oe==null?void 0:Oe.borderColor)!=null?B:"";or(),E.classList.add("persona-voice-processing"),E.style.backgroundColor=L,E.style.borderColor=R;let W=A||"currentColor";E.style.color=W,Er(y,W),E.setAttribute("aria-label","Processing voice input"),g==="none"&&(E.style.cursor="default")},Ro=()=>{var se,ve,we,He,Me,B,We,Pe,le,Be,st,qe;if(!E)return;Ar();let l=(se=n.voiceRecognition)!=null?se:{},g=D.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",A=(ve=l.speakingIconName)!=null?ve:y,L=(B=l.speakingIconColor)!=null?B:g==="barge-in"?(He=(we=l.recordingIconColor)!=null?we:Oe==null?void 0:Oe.color)!=null?He:"":(Me=Oe==null?void 0:Oe.color)!=null?Me:"",R=(le=l.speakingBackgroundColor)!=null?le:g==="barge-in"?(We=l.recordingBackgroundColor)!=null?We:"#ef4444":(Pe=Oe==null?void 0:Oe.backgroundColor)!=null?Pe:"",W=(qe=l.speakingBorderColor)!=null?qe:g==="barge-in"?(Be=l.recordingBorderColor)!=null?Be:"":(st=Oe==null?void 0:Oe.borderColor)!=null?st:"";or(),E.classList.add("persona-voice-speaking"),E.style.backgroundColor=R,E.style.borderColor=W;let U=L||"currentColor";E.style.color=U,Er(A,U);let O=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";E.setAttribute("aria-label",O),g==="none"&&(E.style.cursor="default"),g==="barge-in"&&E.classList.add("persona-voice-recording")},fn=()=>{var l,g,y;E&&(or(),Oe&&(E.style.backgroundColor=(l=Oe.backgroundColor)!=null?l:"",E.style.color=(g=Oe.color)!=null?g:"",E.style.borderColor=(y=Oe.borderColor)!=null?y:"",Er(Oe.iconName,Oe.color||"currentColor"),Oe=null),E.style.cursor="",E.setAttribute("aria-label","Start voice recognition"))},X=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let y=D.getVoiceStatus(),A=D.getVoiceInterruptionMode();if(A==="none"&&(y==="processing"||y==="speaking"))return;if(A==="cancel"&&(y==="processing"||y==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,Qt(),cn("user"),fn()});return}D.toggleVoice().then(()=>{ze.active=D.isVoiceActive(),ze.manuallyDeactivated=!D.isVoiceActive(),Qt(),cn("user"),D.isVoiceActive()?qn():fn()});return}if(on){let y=Q.value.trim();ze.manuallyDeactivated=!0,Qt(),mn("user"),y&&(Q.value="",Q.style.height="auto",D.sendMessage(y))}else ze.manuallyDeactivated=!1,Qt(),rr("user")};Ie=X,E&&(E.addEventListener("click",X),Tt.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),fn()):mn("system"),E&&E.removeEventListener("click",X)}));let Ge=o.on("assistant:complete",()=>{Kr&&(ze.active||ze.manuallyDeactivated||Kr==="assistant"&&!ze.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!ze.active&&!ze.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?D.toggleVoice().then(()=>{ze.active=D.isVoiceActive(),cn("auto"),D.isVoiceActive()&&qn()}):rr("auto"))},600))});Tt.push(Ge);let pt=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});Tt.push(pt);let bt=()=>{wt(!T,"user")},je=null,Ve=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>mo(n,bt).element,onToggle:bt});g&&(Ve=g)}Ve||(je=mo(n,bt))}je?e.appendChild(je.element):Ve&&e.appendChild(Ve),nr(),_n.render(n.suggestionChips,D,Q,void 0,n.suggestionChipsConfig),Yr(),wr(D.isStreaming()),er(!0),To(),k&&(b?T&&setTimeout(()=>Sr(),200):setTimeout(()=>Sr(),0));let xt=()=>{var O,se,ve,we,He,Me,B,We,Pe,le,Be,st,qe;let l=jt(n),g=(se=(O=n.launcher)==null?void 0:O.sidebarMode)!=null?se:!1,y=l||g||((we=(ve=n.launcher)==null?void 0:ve.fullHeight)!=null?we:!1),A=(He=e.ownerDocument.defaultView)!=null?He:window,L=(B=(Me=n.launcher)==null?void 0:Me.mobileFullscreen)!=null?B:!0,R=(Pe=(We=n.launcher)==null?void 0:We.mobileBreakpoint)!=null?Pe:640,W=A.innerWidth<=R,U=L&&W&&b;try{if(U){Zn(),Vn(e,n);return}if($&&($=!1,Zn(),Vn(e,n)),!b&&!l){N.style.height="",N.style.width="";return}if(!g&&!l){let fe=(Be=(le=n==null?void 0:n.launcher)==null?void 0:le.width)!=null?Be:n==null?void 0:n.launcherWidth,Bt=fe!=null?fe:"min(400px, calc(100vw - 24px))";N.style.width=Bt,N.style.maxWidth=Bt}if(Xn(),!y){let fe=A.innerHeight,Bt=64,dt=(qe=(st=n.launcher)==null?void 0:st.heightOffset)!=null?qe:0,tn=Math.max(200,fe-Bt),Jt=Math.min(640,tn),Xt=Math.max(200,Jt-dt);N.style.height=`${Xt}px`}}finally{nr()}};xt();let C=(Ra=e.ownerDocument.defaultView)!=null?Ra:window;C.addEventListener("resize",xt),Tt.push(()=>C.removeEventListener("resize",xt)),Qn=q.scrollTop;let $e=()=>{let l=q.scrollTop,g=q.scrollHeight,y=q.clientHeight,A=g-l-y,L=Math.abs(l-Qn);if(Qn=l,!vr&&!(L<=Eo)){if(!Ln&&A<Jr){Pn=!1,Ln=!0;return}Ln&&A>Jr&&(Pn=!0,xr=Date.now()+Ao,Ln=!1)}};q.addEventListener("scroll",$e,{passive:!0}),Tt.push(()=>q.removeEventListener("scroll",$e)),Tt.push(()=>{In&&cancelAnimationFrame(In)});let H=()=>{G&&(Sn&&(G.removeEventListener("click",Sn),Sn=null),b?(G.style.display="",Sn=()=>{wt(!1,"user")},G.addEventListener("click",Sn)):G.style.display="none")};H(),(()=>{let{clearChatButton:l}=re;l&&l.addEventListener("click",()=>{D.clearMessages(),zn.clear();try{localStorage.removeItem(Fr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Fr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Fr)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(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},S.syncFromMetadata(),F==null||F.clear(),J==null||J.update()})})(),it&&it.addEventListener("submit",Xr),Q==null||Q.addEventListener("keydown",Zr),Q==null||Q.addEventListener("paste",Qr),Tt.push(()=>{it&&it.removeEventListener("submit",Xr),Q==null||Q.removeEventListener("keydown",Zr),Q==null||Q.removeEventListener("paste",Qr)}),Tt.push(()=>{D.cancel()}),je?Tt.push(()=>{je==null||je.destroy()}):Ve&&Tt.push(()=>{Ve==null||Ve.remove()});let P={update(l){var Fa,_a,ja,za,qa,Ua,Va,Ja,Ka,Ga,Ya,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Ni,Oi,$i,Fi,_i,ji,zi,qi,Ui,Vi,Ji,Ki,Gi,Yi,Xi,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;let g=n.toolCall,y=n.messageActions,A=(Fa=n.layout)==null?void 0:Fa.messages,L=n.colorScheme,R=n.loadingIndicator,W=n.iterationDisplay;n={...n,...l},Zn(),Vn(e,n),is(e,n),ls(e,n),Cn(),n.colorScheme!==L&&qr();let U=xo.getForInstance(n.plugins);s.length=0,s.push(...U),b=(ja=(_a=n.launcher)==null?void 0:_a.enabled)!=null?ja:!0,x=(qa=(za=n.launcher)==null?void 0:za.autoExpand)!=null?qa:!1,te=(Va=(Ua=n.features)==null?void 0:Ua.showReasoning)!=null?Va:!0,Ae=(Ka=(Ja=n.features)==null?void 0:Ja.showToolCalls)!=null?Ka:!0;let O=ie;if(ie=(Ya=(Ga=n.features)==null?void 0:Ga.showEventStreamToggle)!=null?Ya:!1,ie&&!O){if(F||(Y=new bo(ae),F=new yo(ge,Y),Y.open().then(()=>F==null?void 0:F.restore()).catch(()=>{}),D.setSSEEventCallback((j,Qe)=>{F.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:j,timestamp:Date.now(),payload:JSON.stringify(Qe)})})),!Ne&&Ye){let j=(Za=(Xa=n.features)==null?void 0:Xa.eventStream)==null?void 0:Za.classNames,Qe="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(j!=null&&j.toggleButton?" "+j.toggleButton:"");Ne=h("button",Qe),Ne.style.width="28px",Ne.style.height="28px",Ne.type="button",Ne.setAttribute("aria-label","Event Stream"),Ne.title="Event Stream";let St=he("activity","18px","currentColor",1.5);St&&Ne.appendChild(St);let Fe=re.clearChatButtonWrapper,rt=re.closeButtonWrapper,Dt=Fe||rt;Dt&&Dt.parentNode===Ye?Ye.insertBefore(Ne,Dt):Ye.appendChild(Ne),Ne.addEventListener("click",()=>{me?Et():nt()})}}else!ie&&O&&(Et(),Ne&&(Ne.remove(),Ne=null),F==null||F.clear(),Y==null||Y.destroy(),F=null,Y=null);if(((Qa=n.launcher)==null?void 0:Qa.enabled)===!1&&je&&(je.destroy(),je=null),((ei=n.launcher)==null?void 0:ei.enabled)===!1&&Ve&&(Ve.remove(),Ve=null),((ti=n.launcher)==null?void 0:ti.enabled)!==!1&&!je&&!Ve){let j=s.find(Qe=>Qe.renderLauncher);if(j!=null&&j.renderLauncher){let Qe=j.renderLauncher({config:n,defaultRenderer:()=>mo(n,bt).element,onToggle:bt});Qe&&(Ve=Qe,e.appendChild(Ve))}Ve||(je=mo(n,bt),e.appendChild(je.element))}je&&je.update(n),ft&&((ni=n.launcher)==null?void 0:ni.title)!==void 0&&(ft.textContent=n.launcher.title),yt&&((ri=n.launcher)==null?void 0:ri.subtitle)!==void 0&&(yt.textContent=n.launcher.subtitle);let se=(oi=n.layout)==null?void 0:oi.header;if((se==null?void 0:se.layout)!==I&&Ye){let j=se?Rr(n,se,{showClose:b,onClose:()=>wt(!1,"user")}):Dn({config:n,showClose:b,onClose:()=>wt(!1,"user")});Ye.replaceWith(j.header),Ye=j.header,Le=j.iconHolder,ft=j.headerTitle,yt=j.headerSubtitle,G=j.closeButton,I=se==null?void 0:se.layout}else if(se&&(Le&&(Le.style.display=se.showIcon===!1?"none":""),ft&&(ft.style.display=se.showTitle===!1?"none":""),yt&&(yt.style.display=se.showSubtitle===!1?"none":""),G&&(G.style.display=se.showCloseButton===!1?"none":""),re.clearChatButtonWrapper)){let j=se.showClearChat;if(j!==void 0){re.clearChatButtonWrapper.style.display=j?"":"none";let{closeButtonWrapper:Qe}=re;Qe&&!Qe.classList.contains("persona-absolute")&&(j?Qe.classList.remove("persona-ml-auto"):Qe.classList.add("persona-ml-auto"))}}let we=((si=n.layout)==null?void 0:si.showHeader)!==!1;Ye&&(Ye.style.display=we?"":"none");let He=((ai=n.layout)==null?void 0:ai.showFooter)!==!1;ot&&(ot.style.display=He?"":"none"),b!==w?b?wt(x,"auto"):(T=!0,nr()):x!==_&&wt(x,"auto"),_=x,w=b,xt(),H();let We=JSON.stringify(l.toolCall)!==JSON.stringify(g),Pe=JSON.stringify(n.messageActions)!==JSON.stringify(y),le=JSON.stringify((ii=n.layout)==null?void 0:ii.messages)!==JSON.stringify(A),Be=((li=n.loadingIndicator)==null?void 0:li.render)!==(R==null?void 0:R.render)||((ci=n.loadingIndicator)==null?void 0:ci.renderIdle)!==(R==null?void 0:R.renderIdle)||((di=n.loadingIndicator)==null?void 0:di.showBubble)!==(R==null?void 0:R.showBubble),st=n.iterationDisplay!==W;(We||Pe||le||Be||st)&&D&&(Ur++,tr(ce,D.getMessages(),z));let fe=(pi=n.launcher)!=null?pi:{},Bt=(ui=fe.headerIconHidden)!=null?ui:!1,dt=(mi=(gi=n.layout)==null?void 0:gi.header)==null?void 0:mi.showIcon,tn=Bt||dt===!1,Jt=fe.headerIconName,Xt=(fi=fe.headerIconSize)!=null?fi:"48px";if(Le){let j=ee.querySelector(".persona-border-b-persona-divider"),Qe=j==null?void 0:j.querySelector(".persona-flex-col");if(tn)Le.style.display="none",j&&Qe&&!j.contains(Qe)&&j.insertBefore(Qe,j.firstChild);else{if(Le.style.display="",Le.style.height=Xt,Le.style.width=Xt,j&&Qe&&(j.contains(Le)?Le.nextSibling!==Qe&&(Le.remove(),j.insertBefore(Le,Qe)):j.insertBefore(Le,Qe)),Jt){let Fe=parseFloat(Xt)||24,rt=he(Jt,Fe*.6,"#ffffff",2);rt?Le.replaceChildren(rt):Le.textContent=(hi=fe.agentIconText)!=null?hi:"\u{1F4AC}"}else if(fe.iconUrl){let Fe=Le.querySelector("img");if(Fe)Fe.src=fe.iconUrl,Fe.style.height=Xt,Fe.style.width=Xt;else{let rt=document.createElement("img");rt.src=fe.iconUrl,rt.alt="",rt.className="persona-rounded-xl persona-object-cover",rt.style.height=Xt,rt.style.width=Xt,Le.replaceChildren(rt)}}else{let Fe=Le.querySelector("svg"),rt=Le.querySelector("img");(Fe||rt)&&Le.replaceChildren(),Le.textContent=(yi=fe.agentIconText)!=null?yi:"\u{1F4AC}"}let St=Le.querySelector("img");St&&(St.style.height=Xt,St.style.width=Xt)}}let $t=(xi=(bi=n.layout)==null?void 0:bi.header)==null?void 0:xi.showTitle,pn=(Ci=(vi=n.layout)==null?void 0:vi.header)==null?void 0:Ci.showSubtitle;if(ft&&(ft.style.display=$t===!1?"none":""),yt&&(yt.style.display=pn===!1?"none":""),G){((Si=(wi=n.layout)==null?void 0:wi.header)==null?void 0:Si.showCloseButton)===!1?G.style.display="none":G.style.display="";let Qe=(Ai=fe.closeButtonSize)!=null?Ai:"32px",St=(Ei=fe.closeButtonPlacement)!=null?Ei:"inline";G.style.height=Qe,G.style.width=Qe;let{closeButtonWrapper:Fe}=re,rt=St==="top-right",Dt=Fe==null?void 0:Fe.classList.contains("persona-absolute");if(Fe&&rt!==Dt)if(Fe.remove(),rt)Fe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ee.style.position="relative",ee.appendChild(Fe);else{let et=(Mi=(Ti=fe.clearChat)==null?void 0:Ti.placement)!=null?Mi:"inline",_t=(Li=(ki=fe.clearChat)==null?void 0:ki.enabled)!=null?Li:!0;Fe.className=_t&&et==="inline"?"":"persona-ml-auto";let nn=ee.querySelector(".persona-border-b-persona-divider");nn&&nn.appendChild(Fe)}if(G.style.color=fe.closeButtonColor||bn.actionIconColor,fe.closeButtonBackgroundColor?(G.style.backgroundColor=fe.closeButtonBackgroundColor,G.classList.remove("hover:persona-bg-gray-100")):(G.style.backgroundColor="",G.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let et=fe.closeButtonBorderWidth||"0px",_t=fe.closeButtonBorderColor||"transparent";G.style.border=`${et} solid ${_t}`,G.classList.remove("persona-border-none")}else G.style.border="",G.classList.add("persona-border-none");fe.closeButtonBorderRadius?(G.style.borderRadius=fe.closeButtonBorderRadius,G.classList.remove("persona-rounded-full")):(G.style.borderRadius="",G.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(G.style.paddingLeft=fe.closeButtonPaddingX,G.style.paddingRight=fe.closeButtonPaddingX):(G.style.paddingLeft="",G.style.paddingRight=""),fe.closeButtonPaddingY?(G.style.paddingTop=fe.closeButtonPaddingY,G.style.paddingBottom=fe.closeButtonPaddingY):(G.style.paddingTop="",G.style.paddingBottom="");let zt=(Ii=fe.closeButtonIconName)!=null?Ii:"x",hn=(Pi=fe.closeButtonIconText)!=null?Pi:"\xD7";G.innerHTML="";let Zt=he(zt,"20px","currentColor",2);Zt?G.appendChild(Zt):G.textContent=hn;let kt=(Wi=fe.closeButtonTooltipText)!=null?Wi:"Close chat",sn=(Ri=fe.closeButtonShowTooltip)!=null?Ri:!0;if(G.setAttribute("aria-label",kt),Fe&&(Fe._cleanupTooltip&&(Fe._cleanupTooltip(),delete Fe._cleanupTooltip),sn&&kt)){let et=null,_t=()=>{if(et||!G)return;let sr=G.ownerDocument,ro=sr.body;if(!ro)return;et=En(sr,"div","persona-clear-chat-tooltip"),et.textContent=kt;let oo=En(sr,"div");oo.className="persona-clear-chat-tooltip-arrow",et.appendChild(oo);let ar=G.getBoundingClientRect();et.style.position="fixed",et.style.left=`${ar.left+ar.width/2}px`,et.style.top=`${ar.top-8}px`,et.style.transform="translate(-50%, -100%)",ro.appendChild(et)},nn=()=>{et&&et.parentNode&&(et.parentNode.removeChild(et),et=null)};Fe.addEventListener("mouseenter",_t),Fe.addEventListener("mouseleave",nn),G.addEventListener("focus",_t),G.addEventListener("blur",nn),Fe._cleanupTooltip=()=>{nn(),Fe&&(Fe.removeEventListener("mouseenter",_t),Fe.removeEventListener("mouseleave",nn)),G&&(G.removeEventListener("focus",_t),G.removeEventListener("blur",nn))}}}let{clearChatButton:Je,clearChatButtonWrapper:At}=re;if(Je){let j=(Hi=fe.clearChat)!=null?Hi:{},Qe=(Bi=j.enabled)!=null?Bi:!0,St=(Ni=(Di=n.layout)==null?void 0:Di.header)==null?void 0:Ni.showClearChat,Fe=St!==void 0?St:Qe,rt=(Oi=j.placement)!=null?Oi:"inline";if(At){At.style.display=Fe?"":"none";let{closeButtonWrapper:Dt}=re;Dt&&!Dt.classList.contains("persona-absolute")&&(Fe?Dt.classList.remove("persona-ml-auto"):Dt.classList.add("persona-ml-auto"));let zt=rt==="top-right",hn=At.classList.contains("persona-absolute");if(zt!==hn&&Fe){if(At.remove(),zt)At.className="persona-absolute persona-top-4 persona-z-50",At.style.right="48px",ee.style.position="relative",ee.appendChild(At);else{At.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",At.style.right="";let kt=ee.querySelector(".persona-border-b-persona-divider"),sn=re.closeButtonWrapper;kt&&sn&&sn.parentElement===kt?kt.insertBefore(At,sn):kt&&kt.appendChild(At)}let Zt=re.closeButtonWrapper;Zt&&!Zt.classList.contains("persona-absolute")&&(zt?Zt.classList.add("persona-ml-auto"):Zt.classList.remove("persona-ml-auto"))}}if(Fe){let Dt=($i=j.size)!=null?$i:"32px";Je.style.height=Dt,Je.style.width=Dt;let zt=(Fi=j.iconName)!=null?Fi:"refresh-cw",hn=(_i=j.iconColor)!=null?_i:"";Je.style.color=hn||bn.actionIconColor,Je.innerHTML="";let Zt=he(zt,"20px","currentColor",2);if(Zt&&Je.appendChild(Zt),j.backgroundColor?(Je.style.backgroundColor=j.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),j.borderWidth||j.borderColor){let et=j.borderWidth||"0px",_t=j.borderColor||"transparent";Je.style.border=`${et} solid ${_t}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");j.borderRadius?(Je.style.borderRadius=j.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),j.paddingX?(Je.style.paddingLeft=j.paddingX,Je.style.paddingRight=j.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),j.paddingY?(Je.style.paddingTop=j.paddingY,Je.style.paddingBottom=j.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let kt=(ji=j.tooltipText)!=null?ji:"Clear chat",sn=(zi=j.showTooltip)!=null?zi:!0;if(Je.setAttribute("aria-label",kt),At&&(At._cleanupTooltip&&(At._cleanupTooltip(),delete At._cleanupTooltip),sn&&kt)){let et=null,_t=()=>{if(et||!Je)return;let sr=Je.ownerDocument,ro=sr.body;if(!ro)return;et=En(sr,"div","persona-clear-chat-tooltip"),et.textContent=kt;let oo=En(sr,"div");oo.className="persona-clear-chat-tooltip-arrow",et.appendChild(oo);let ar=Je.getBoundingClientRect();et.style.position="fixed",et.style.left=`${ar.left+ar.width/2}px`,et.style.top=`${ar.top-8}px`,et.style.transform="translate(-50%, -100%)",ro.appendChild(et)},nn=()=>{et&&et.parentNode&&(et.parentNode.removeChild(et),et=null)};At.addEventListener("mouseenter",_t),At.addEventListener("mouseleave",nn),Je.addEventListener("focus",_t),Je.addEventListener("blur",nn),At._cleanupTooltip=()=>{nn(),At&&(At.removeEventListener("mouseenter",_t),At.removeEventListener("mouseleave",nn)),Je&&(Je.removeEventListener("focus",_t),Je.removeEventListener("blur",nn))}}}}let Ho=n.actionParsers&&n.actionParsers.length?n.actionParsers:[vo],Bo=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[fr.message,fr.messageAndClick];S=Co({parsers:Ho,handlers:Bo,getSessionMetadata:p,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),z=Pc(n,S,oe),D.updateConfig(n),tr(ce,D.getMessages(),z),_n.render(n.suggestionChips,D,Q,void 0,n.suggestionChipsConfig),Yr(),wr(D.isStreaming());let Do=((qi=n.voiceRecognition)==null?void 0:qi.enabled)===!0,No=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Oo=((Vi=(Ui=n.voiceRecognition)==null?void 0:Ui.provider)==null?void 0:Vi.type)==="runtype";if(Do&&(No||Oo))if(!E||!Ee){let j=Po(n.voiceRecognition,n.sendButton);j&&(E=j.micButton,Ee=j.micButtonWrapper,de.insertBefore(Ee,_e),E.addEventListener("click",X),E.disabled=D.isStreaming())}else{let j=(Ji=n.voiceRecognition)!=null?Ji:{},Qe=(Ki=n.sendButton)!=null?Ki:{},St=(Gi=j.iconName)!=null?Gi:"mic",Fe=(Yi=Qe.size)!=null?Yi:"40px",rt=(Xi=j.iconSize)!=null?Xi:Fe,Dt=parseFloat(rt)||24;E.style.width=rt,E.style.height=rt,E.style.minWidth=rt,E.style.minHeight=rt;let zt=(Qi=(Zi=j.iconColor)!=null?Zi:Qe.textColor)!=null?Qi:"currentColor";E.innerHTML="";let hn=he(St,Dt,zt,2);hn?E.appendChild(hn):E.textContent="\u{1F3A4}";let Zt=(el=j.backgroundColor)!=null?el:Qe.backgroundColor;Zt?(E.style.backgroundColor=Zt,E.classList.remove("persona-bg-persona-primary")):(E.style.backgroundColor="",E.classList.add("persona-bg-persona-primary")),zt?(E.style.color=zt,E.classList.remove("persona-text-white")):!zt&&!Qe.textColor&&(E.style.color="",E.classList.add("persona-text-white")),j.borderWidth?(E.style.borderWidth=j.borderWidth,E.style.borderStyle="solid"):(E.style.borderWidth="",E.style.borderStyle=""),j.borderColor?E.style.borderColor=j.borderColor:E.style.borderColor="",j.paddingX?(E.style.paddingLeft=j.paddingX,E.style.paddingRight=j.paddingX):(E.style.paddingLeft="",E.style.paddingRight=""),j.paddingY?(E.style.paddingTop=j.paddingY,E.style.paddingBottom=j.paddingY):(E.style.paddingTop="",E.style.paddingBottom="");let kt=Ee==null?void 0:Ee.querySelector(".persona-send-button-tooltip"),sn=(tl=j.tooltipText)!=null?tl:"Start voice recognition";if(((nl=j.showTooltip)!=null?nl:!1)&&sn)if(kt)kt.textContent=sn,kt.style.display="";else{let _t=document.createElement("div");_t.className="persona-send-button-tooltip",_t.textContent=sn,Ee==null||Ee.insertBefore(_t,E)}else kt&&(kt.style.display="none");Ee.style.display="",E.disabled=D.isStreaming()}else E&&Ee&&(Ee.style.display="none",((ol=(rl=n.voiceRecognition)==null?void 0:rl.provider)==null?void 0:ol.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():on&&mn());if(((sl=n.attachments)==null?void 0:sl.enabled)===!0)if(!be||!ne){let j=(al=n.attachments)!=null?al:{},St=(ll=((il=n.sendButton)!=null?il:{}).size)!=null?ll:"40px";Xe||(Xe=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Xe.style.display="none",it.insertBefore(Xe,Q)),Ce||(Ce=document.createElement("input"),Ce.type="file",Ce.accept=((cl=j.allowedTypes)!=null?cl:Bn).join(","),Ce.multiple=((dl=j.maxFiles)!=null?dl:4)>1,Ce.style.display="none",Ce.setAttribute("aria-label","Attach files"),it.insertBefore(Ce,Q)),be=h("div","persona-send-button-wrapper"),ne=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ne.type="button",ne.setAttribute("aria-label",(pl=j.buttonTooltipText)!=null?pl:"Attach file");let Fe=(ul=j.buttonIconName)!=null?ul:"paperclip",rt=St,Dt=parseFloat(rt)||40,zt=Math.round(Dt*.6);ne.style.width=rt,ne.style.height=rt,ne.style.minWidth=rt,ne.style.minHeight=rt,ne.style.fontSize="18px",ne.style.lineHeight="1",ne.style.backgroundColor="transparent",ne.style.color="var(--persona-primary, #111827)",ne.style.border="none",ne.style.borderRadius="6px",ne.style.transition="background-color 0.15s ease",ne.addEventListener("mouseenter",()=>{ne.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ne.addEventListener("mouseleave",()=>{ne.style.backgroundColor="transparent"});let hn=he(Fe,zt,"currentColor",1.5);hn?ne.appendChild(hn):ne.textContent="\u{1F4CE}",ne.addEventListener("click",sn=>{sn.preventDefault(),Ce==null||Ce.click()}),be.appendChild(ne);let Zt=(gl=j.buttonTooltipText)!=null?gl:"Attach file",kt=h("div","persona-send-button-tooltip");kt.textContent=Zt,be.appendChild(kt),Vt.append(be),!ye&&Ce&&Xe&&(ye=ur.fromConfig(j),ye.setPreviewsContainer(Xe),Ce.addEventListener("change",async()=>{ye&&(Ce!=null&&Ce.files)&&(await ye.handleFileSelect(Ce.files),Ce.value="")}))}else{be.style.display="";let j=(ml=n.attachments)!=null?ml:{};Ce&&(Ce.accept=((fl=j.allowedTypes)!=null?fl:Bn).join(","),Ce.multiple=((hl=j.maxFiles)!=null?hl:4)>1),ye&&ye.updateConfig({allowedTypes:j.allowedTypes,maxFileSize:j.maxFileSize,maxFiles:j.maxFiles})}else be&&(be.style.display="none"),ye&&ye.clearAttachments();let Pt=(yl=n.sendButton)!=null?yl:{},$o=(bl=Pt.useIcon)!=null?bl:!1,to=(xl=Pt.iconText)!=null?xl:"\u2191",no=Pt.iconName,Tr=(vl=Pt.tooltipText)!=null?vl:"Send message",Fo=(Cl=Pt.showTooltip)!=null?Cl:!1,Un=(wl=Pt.size)!=null?wl:"40px",Kt=Pt.backgroundColor,Ft=Pt.textColor;if($o){if(K.style.width=Un,K.style.height=Un,K.style.minWidth=Un,K.style.minHeight=Un,K.style.fontSize="18px",K.style.lineHeight="1",K.innerHTML="",no){let j=parseFloat(Un)||24,Qe=Ft&&typeof Ft=="string"&&Ft.trim()?Ft.trim():"currentColor",St=he(no,j,Qe,2);St?(K.appendChild(St),K.style.color=Qe):(K.textContent=to,Ft?K.style.color=Ft:K.classList.add("persona-text-white"))}else K.textContent=to,Ft?K.style.color=Ft:K.classList.add("persona-text-white");K.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Kt?(K.style.backgroundColor=Kt,K.classList.remove("persona-bg-persona-primary")):K.classList.add("persona-bg-persona-primary")}else K.textContent=(Al=(Sl=n.copy)==null?void 0:Sl.sendButtonLabel)!=null?Al:"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",Kt?(K.style.backgroundColor=Kt,K.classList.remove("persona-bg-persona-accent")):K.classList.add("persona-bg-persona-accent"),Ft?K.style.color=Ft:K.classList.add("persona-text-white");Pt.borderWidth?(K.style.borderWidth=Pt.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),Pt.borderColor?K.style.borderColor=Pt.borderColor:K.style.borderColor="",Pt.paddingX?(K.style.paddingLeft=Pt.paddingX,K.style.paddingRight=Pt.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),Pt.paddingY?(K.style.paddingTop=Pt.paddingY,K.style.paddingBottom=Pt.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let An=_e==null?void 0:_e.querySelector(".persona-send-button-tooltip");if(Fo&&Tr)if(An)An.textContent=Tr,An.style.display="";else{let j=document.createElement("div");j.className="persona-send-button-tooltip",j.textContent=Tr,_e==null||_e.insertBefore(j,K)}else An&&(An.style.display="none");let Mr=(El=n.statusIndicator)!=null?El:{},hd=(Tl=Mr.visible)!=null?Tl:!0;if(Lt.style.display=hd?"":"none",D){let j=D.getStatus();tt(Lt,(St=>{var Fe,rt,Dt,zt;return St==="idle"?(Fe=Mr.idleText)!=null?Fe:Gt.idle:St==="connecting"?(rt=Mr.connectingText)!=null?rt:Gt.connecting:St==="connected"?(Dt=Mr.connectedText)!=null?Dt:Gt.connected:St==="error"?(zt=Mr.errorText)!=null?zt:Gt.error:Gt[St]})(j),Mr,j)}},open(){b&&wt(!0,"api")},close(){b&&wt(!1,"api")},toggle(){b&&wt(!T,"api")},clearChat(){rn=!1,D.clearMessages(),zn.clear();try{localStorage.removeItem(Fr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Fr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Fr)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={},S.syncFromMetadata(),F==null||F.clear(),J==null||J.update()},setMessage(l){return!Q||D.isStreaming()?!1:(!T&&b&&wt(!0,"system"),Q.value=l,Q.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let g=(l==null?void 0:l.trim())||Q.value.trim();return g?(!T&&b&&wt(!0,"system"),Q.value="",Q.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&&wt(!0,"system"),ze.manuallyDeactivated=!1,Qt(),D.toggleVoice().then(()=>{ze.active=D.isVoiceActive(),cn("user"),D.isVoiceActive()&&qn()})),!0):on?!0:eo()?(!T&&b&&wt(!0,"system"),ze.manuallyDeactivated=!1,Qt(),rr("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(()=>{ze.active=!1,ze.manuallyDeactivated=!0,Qt(),cn("user"),fn()}),!0):!1:on?(ze.manuallyDeactivated=!0,Qt(),mn("user"),!0):!1},injectMessage(l){return!T&&b&&wt(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!T&&b&&wt(!0,"system");let g=D.injectAssistantMessage(l);return V&&(V=!1,ue&&(clearTimeout(ue),ue=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),g},injectUserMessage(l){return!T&&b&&wt(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!T&&b&&wt(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!T&&b&&wt(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!T&&b&&wt(!0,"system"),D.injectTestEvent(l)},async connectStream(l,g){return D.connectStream(l,g)},__pushEventStreamEvent(l){F&&F.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ie||!F||nt()},hideEventStream(){me&&Et()},isEventStreamVisible(){return me},showArtifacts(){gn(n)&&(rn=!1,Cn(),Ze==null||Ze.setMobileOpen(!0))},hideArtifacts(){gn(n)&&(rn=!0,Cn())},upsertArtifact(l){return gn(n)?(rn=!1,D.upsertArtifact(l)):null},selectArtifact(l){gn(n)&&D.selectArtifact(l)},clearArtifacts(){gn(n)&&D.clearArtifacts()},focusInput(){return b&&!T||!Q?!1:(Q.focus(),!0)},async resolveApproval(l,g){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,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 ze.active},getState(){return{open:b&&T,launcherEnabled:b,voiceActive:ze.active,streaming:D.isStreaming()}},showCSATFeedback(l){!T&&b&&wt(!0,"system");let g=ce.querySelector(".persona-feedback-container");g&&g.remove();let y=fs({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});ce.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!T&&b&&wt(!0,"system");let g=ce.querySelector(".persona-feedback-container");g&&g.remove();let y=hs({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});ce.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(){Tt.forEach(l=>l()),Te.remove(),je==null||je.destroy(),Ve==null||Ve.remove(),Sn&&G.removeEventListener("click",Sn)}};if((((Ha=t==null?void 0:t.debugTools)!=null?Ha:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:P,getMessages:P.getMessages,getStatus:P.getStatus,getMetadata:P.getPersistentMetadata,updateMetadata:P.updatePersistentMetadata,clearHistory:()=>P.clearChat(),setVoiceActive:y=>y?P.startVoiceRecognition():P.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Tt.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=U=>{let O=U.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&P.focusInput()};if(window.addEventListener("persona:focusInput",g),Tt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ie){let U=se=>{let ve=se.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===l)&&P.showEventStream()},O=se=>{let ve=se.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===l)&&P.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",O),Tt.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",O)})}let y=U=>{let O=U.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&P.showArtifacts()},A=U=>{let O=U.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&P.hideArtifacts()},L=U=>{let O=U.detail;O!=null&&O.instanceId&&O.instanceId!==l||O!=null&&O.artifact&&P.upsertArtifact(O.artifact)},R=U=>{let O=U.detail;O!=null&&O.instanceId&&O.instanceId!==l||typeof(O==null?void 0:O.id)=="string"&&P.selectArtifact(O.id)},W=U=>{let O=U.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&P.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",W),Tt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",W)})}let xe=Mp(n.persistState);if(xe&&b){let l=kp(xe.storage),g=`${xe.keyPrefix}widget-open`,y=`${xe.keyPrefix}widget-voice`,A=`${xe.keyPrefix}widget-voice-mode`;if(l){let L=((Ba=xe.persist)==null?void 0:Ba.openState)&&l.getItem(g)==="true",R=((Da=xe.persist)==null?void 0:Da.voiceState)&&l.getItem(y)==="true",W=((Na=xe.persist)==null?void 0:Na.voiceState)&&l.getItem(A)==="true";if(L&&setTimeout(()=>{P.open(),setTimeout(()=>{var U;if(R||W)P.startVoiceRecognition();else if((U=xe.persist)!=null&&U.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Oa=xe.persist)!=null&&Oa.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),($a=xe.persist)!=null&&$a.voiceState&&(o.on("voice:state",U=>{l.setItem(y,U.active?"true":"false")}),o.on("user:message",U=>{l.setItem(A,U.viaVoice?"true":"false")})),xe.clearOnChatClear){let U=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(A)},O=()=>U();window.addEventListener("persona:clear-chat",O),Tt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return c&&b&&setTimeout(()=>{P.open()},0),P};var Lp=(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},Wc=(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"},ea=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=""},Rc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",ea(e)},Xs=e=>{e.style.transition=""},Zs=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=""},Qs=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},bs=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Ip=(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))},Pp=(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)},Hc=(e,r,t,n,s,o,a)=>{var v,S,b,x,k,_;let i=un(o),d=i.reveal==="push";Ip(e,r,t,n,d),Pp(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,u=(S=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?S:!0,p=(x=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?x:640,f=c!=null?c.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Zs(r),Xs(n),Rc(n),Qs(t),bs(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((_=(k=o==null?void 0:o.launcher)==null?void 0:k.zIndex)!=null?_:9999),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"),Rc(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Zs(r),Xs(n),Qs(t),bs(s,n);let w=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",$=a?"translateX(0)":I;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=$,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",Xs(n),ea(n),bs(s,n);let w=Lp(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),$=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=`${I+w}px`,r.style.transition=$,r.style.transform=T,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${I}px`,t.style.maxWidth=`${I}px`,t.style.minWidth=`${I}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="",Zs(r),ea(n),Qs(t),bs(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",$=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 ${I}`,n.style.width=I,n.style.maxWidth=I,n.style.minWidth=I,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||T?"hidden":"visible",n.style.transition=$,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")}},Wp=(e,r)=>{let t=e.ownerDocument.createElement("div");return Wc(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Wc(t,n)},destroy(){t.remove()}}},Rp=(e,r)=>{var k,_,w,I;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"),u=t.createElement("div"),p=(_=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)==null||_?(I=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?I:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),n.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),un(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Hc(a,i,d,c,u,r,p)}),f.observe(a))},S=()=>{Hc(a,i,d,c,u,r,p),v()},b=a.ownerDocument.defaultView,x=()=>{S()};return b==null||b.addEventListener("resize",x),un(r).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),S(),{mode:"docked",host:u,shell:a,syncWidgetState($){let T=$.launcherEnabled?$.open:!0;p!==T&&(p=T,S())},updateConfig($){var T,V;r=$,((V=(T=r==null?void 0:r.launcher)==null?void 0:T.enabled)!=null?V:!0)===!1&&(p=!0),S()},destroy(){b==null||b.removeEventListener("resize",x),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},wo=(e,r)=>jt(r)?Rp(e,r):Wp(e,r);var ta={},Hp=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},Bp=()=>{try{if(typeof ta!="undefined"&&ta.url)return new URL("../widget.css",ta.url).href}catch{}return null},Bc=(e,r)=>{let t=Bp(),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)}},na=e=>{var b;let r=Hp(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=wo(r,s),a,i=[],d=(x,k)=>{var $,T;let w=!((T=($=k==null?void 0:k.launcher)==null?void 0:$.enabled)!=null?T:!0)||jt(k),I=n.createElement("div");if(I.setAttribute("data-persona-root","true"),w&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),t){let V=x.attachShadow({mode:"open"});V.appendChild(I),Bc(V,n)}else x.appendChild(I),Bc(x,n);return r.id&&I.setAttribute("data-persona-instance",r.id),I},c=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let x=d(o.host,s);a=ys(x,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(x=>x()),i=[],a.destroy()};p(),(b=e.onReady)==null||b.call(e);let m=x=>{f(),o.destroy(),o=wo(r,x),s=x,p()},v={update(x){var I,$,T,V,ue,oe;let k={...s,...x,launcher:{...(I=s==null?void 0:s.launcher)!=null?I:{},...($=x==null?void 0:x.launcher)!=null?$:{},dock:{...(V=(T=s==null?void 0:s.launcher)==null?void 0:T.dock)!=null?V:{},...(oe=(ue=x==null?void 0:x.launcher)==null?void 0:ue.dock)!=null?oe:{}}}},_=jt(s),w=jt(k);if(_!==w){m(k);return}s=k,o.updateConfig(s),a.update(x),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},S=new Proxy(v,{get(x,k,_){if(k==="host")return o.host;if(k in x)return Reflect.get(x,k,_);let w=a[k];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=S),S};var Fc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Dp=new Set(["button","a","input","select","textarea","details","summary"]),Np=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ra=/\b(product|card|item|listing|result)\b/i,sa=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Op=3e3,$p=100;function _c(e){let r=typeof e.className=="string"?e.className:"";if(ra.test(r)||e.id&&ra.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&ra.test(n.value))return!0}return!1}function jc(e){var r;return sa.test(((r=e.textContent)!=null?r:"").trim())}function zc(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 Fp(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Dc(e){let r=e.match(sa);return r?r[0]:null}function Nc(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 _p(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 jp="commerce-card",zp="result-card";function Oc(e){return!_c(e)||!jc(e)||!zc(e)&&!Fp(e)?0:5200}function $c(e){var n;return!_c(e)||jc(e)||!zc(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:jp,scoreElement(e){return Oc(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,u;if(Oc(e)===0)return null;let{title:t,href:n}=Nc(e),s=(u=(c=Dc(((d=e.textContent)!=null?d:"").trim()))!=null?c:Dc(r.text))!=null?u:"",o=_p(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(`
98
- `)}},{id:zp,scoreElement(e){return $c(e)},formatSummary(e,r){if($c(e)===0)return null;let{title:t,href:n}=Nc(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
99
- `)}}];function qp(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Up(e){var u,p,f,m,v,S,b,x,k,_,w,I,$;let r=(u=e.options)!=null?u:{},t=(f=(p=r.maxElements)!=null?p:e.maxElements)!=null?f:80,n=(v=(m=r.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",s=(b=(S=r.maxTextLength)!=null?S:e.maxTextLength)!=null?b:200,o=(k=(x=r.visibleOnly)!=null?x:e.visibleOnly)!=null?k:!0,a=(_=r.root)!=null?_:e.root,i=(w=r.mode)!=null?w:"structured",d=(I=r.maxCandidates)!=null?I:Math.max(500,t*10),c=($=e.rules)!=null?$:aa;return i==="simple"&&e.rules&&e.rules.length>0?(qp(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function oa(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Vp=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Jp(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"||Dp.has(r)||t&&Np.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function qc(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 Kp(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 d=e.getAttribute("role");d&&(r.role=d);for(let c=0;c<e.attributes.length;c++){let u=e.attributes[c];u.name.startsWith("data-")&&(r[u.name]=u.value)}return r}function ia(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${oa(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Vp){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${oa(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=>oa(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 d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}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 Gp(e){return e==="static"?$p:Op}function Uc(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:ia(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:Jp(e),attributes:Kp(e)}}function Yp(e,r,t,n){let s=Gp(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 Xp(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 Zp(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,u=c.tagName.toLowerCase();if(Fc.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!qc(c)){i=a.nextNode();continue}let p=Uc(c,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(b=>b==="role");if(!f&&!m){i=a.nextNode();continue}if(n.has(p.selector)){i=a.nextNode();continue}n.add(p.selector);let{score:v,formattingRule:S}=Yp(c,p,e.rules,t);s.push({el:c,domIndex:o,enriched:p,score:v,formattingRule:S}),o+=1}i=a.nextNode()}s.sort((c,u)=>{let p=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;Xp(d,c)||d.push(c)}return d.sort((c,u)=>{let p=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex}),d.map(c=>{var f;let u;if((f=c.formattingRule)!=null&&f.formatSummary){let m=c.formattingRule.formatSummary(c.el,c.enriched,t);m&&(u=m)}let p={...c.enriched};return u&&(p.formattedSummary=u),p})}function Qp(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 d=o,c=d.tagName.toLowerCase();if(Fc.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!qc(d)){o=s.nextNode();continue}let u=Uc(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!p&&!f){o=s.nextNode();continue}n.has(u.selector)||(n.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Vc(e={}){var n;let r=Up(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?Qp(r,t):Zp(r,t):[]}var xs=100;function Jc(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:
97
+ `}if(!E&&!l){let Kt="max-height: -moz-available !important; max-height: stretch !important;",Ft=g?"":"padding-top: 1.25em !important;",An=!g&&((Un=n.launcher)==null?void 0:Un.zIndex)!=null?`z-index: ${n.launcher.zIndex} !important;`:"";Me.style.cssText+=Kt+Ft+An}};Qn(),Jn(e,n),ls(e,n),cs(e,n);let Et=[];X&&Et.push(()=>{X==null||X.disconnect(),X=null}),Et.push(()=>{ln==null||ln(),ln=null,vr(),ht&&(ht.remove(),ht=null),et==null||et.element.style.removeProperty("width"),et==null||et.element.style.removeProperty("maxWidth")}),le&&Et.push(()=>{xe!==null&&(cancelAnimationFrame(xe),xe=null),G==null||G.destroy(),G=null,q==null||q.destroy(),q=null,Y=null});let wn=null,Ur=()=>{wn&&(wn(),wn=null),n.colorScheme==="auto"&&(wn=os(()=>{Jn(e,n)}))};Ur(),Et.push(()=>{wn&&(wn(),wn=null)});let _n=hc(Le),Sn=null,H,jn=!1,zn=ac(),Vr=0,Ln=!0,er=0,Jr=0,In=null,Pn=!1,Cr=0,wr=!1,Ao=125,Eo=2e3,To=5,Kr=50,Sr=new Map,Ve={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Gr=(Pa=(Ia=n.voiceRecognition)==null?void 0:Ia.autoResume)!=null?Pa:!1,cn=l=>{o.emit("voice:state",{active:Ve.active,source:l,timestamp:Date.now()})},Qt=()=>{f(l=>({...l,voiceState:{active:Ve.active,timestamp:Date.now(),manuallyDeactivated:Ve.manuallyDeactivated}}))},Mo=()=>{var E,L;if(((E=n.voiceRecognition)==null?void 0:E.enabled)===!1)return;let l=Zs(i.voiceState),g=!!l.active,y=Number((L=l.timestamp)!=null?L:0);Ve.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<Mp&&setTimeout(()=>{var W,P;Ve.active||(Ve.manuallyDeactivated=!1,((P=(W=n.voiceRecognition)==null?void 0:W.provider)==null?void 0:P.type)==="runtype"?H.toggleVoice().then(()=>{Ve.active=H.isVoiceActive(),cn("restore"),H.isVoiceActive()&&qn()}):or("restore"))},1e3)},ko=()=>H?Wc(H.getMessages()).filter(l=>!l.__skipPersist):[];function Yr(l){if(!(a!=null&&a.save))return;let y={messages:l?Wc(l):H?ko():[],metadata:i};try{let E=a.save(y);E instanceof Promise&&E.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)}}let tr=(l=!1)=>{if(!Ln)return;let g=Date.now();Pn&&g<Cr&&!l||(Pn&&g>=Cr&&(Pn=!1),!(!l&&!jn)&&(g-Jr<Ao||(Jr=g,In&&cancelAnimationFrame(In),In=requestAnimationFrame(()=>{Pn||!Ln||(wr=!0,z.scrollTop=z.scrollHeight,er=z.scrollTop,requestAnimationFrame(()=>{wr=!1}),In=null)}))))},Wn=null,Lo=()=>Me.querySelector("#persona-scroll-container")||z,Io=(l,g=500)=>{let y=l.scrollTop,E=l.clientHeight,L=l.scrollHeight,W=L-y;if(y+E>=L-2||Math.abs(W)<5)return;Wn!==null&&(cancelAnimationFrame(Wn),Wn=null);let U=performance.now(),N=be=>1-Math.pow(1-be,3),ae=be=>{let we=l.scrollHeight;we!==L&&(L=we,W=L-y);let We=be-U,Se=Math.min(We/g,1),R=N(Se),He=y+W*R;l.scrollTop=He,Se<1?Wn=requestAnimationFrame(ae):(l.scrollTop=l.scrollHeight,Wn=null)};Wn=requestAnimationFrame(ae)},Po=l=>{let g=new Map;l.forEach(y=>{let E=Sr.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}))}),Sr.clear(),g.forEach((y,E)=>{Sr.set(E,y)})},nr=(l,g,y)=>{var be,we,We,Se;let E=document.createElement("div"),W=(()=>{var He;let R=s.find(Re=>Re.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((He=n.loadingIndicator)!=null&&He.render)return n.loadingIndicator.render})(),P=new Set;g.forEach(R=>{var me,Bt;P.add(R.id);let He=sc(R,Vr),Re=ic(zn,R.id,He);if(Re){E.appendChild(Re.cloneNode(!0));return}let pe=null,De=s.find(pt=>!!(R.variant==="reasoning"&&pt.renderReasoning||R.variant==="tool"&&pt.renderToolCall||R.variant==="approval"&&pt.renderApproval||!R.variant&&pt.renderMessage)),lt=(me=n.layout)==null?void 0:me.messages;if(De)if(R.variant==="reasoning"&&R.reasoning&&De.renderReasoning){if(!ne)return;pe=De.renderReasoning({message:R,defaultRenderer:()=>qs(R),config:n})}else if(R.variant==="tool"&&R.toolCall&&De.renderToolCall){if(!Te)return;pe=De.renderToolCall({message:R,defaultRenderer:()=>Us(R,n),config:n})}else if(R.variant==="approval"&&R.approval&&De.renderApproval){if(n.approval===!1)return;pe=De.renderApproval({message:R,defaultRenderer:()=>Vs(R,n),config:n})}else De.renderMessage&&(pe=De.renderMessage({message:R,defaultRenderer:()=>{let pt=Dr(R,y,lt,n.messageActions,Xe,{loadingIndicatorRenderer:W,widgetConfig:n});return R.role!=="user"&&Gs(pt,R,n,H),pt},config:n}));if(!pe&&R.role==="assistant"&&!R.variant&&n.enableComponentStreaming!==!1&&ms(R)){let tn=fs(R);if(tn){let Jt=gs(tn,{config:n,message:R,transform:y});if(Jt)if(n.wrapComponentDirectiveInBubble!==!1){let $t=document.createElement("div");if($t.className=["vanilla-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),$t.id=`bubble-${R.id}`,$t.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let pn=document.createElement("div");pn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",pn.innerHTML=y({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),$t.appendChild(pn)}$t.appendChild(Jt),pe=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${R.id}`,$t.setAttribute("data-message-id",R.id),$t.setAttribute("data-persona-component-directive","true"),R.content&&R.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:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),$t.appendChild(pn)}$t.appendChild(Jt),pe=$t}}}if(!pe)if(R.variant==="reasoning"&&R.reasoning){if(!ne)return;pe=qs(R)}else if(R.variant==="tool"&&R.toolCall){if(!Te)return;pe=Us(R,n)}else if(R.variant==="approval"&&R.approval){if(n.approval===!1)return;pe=Vs(R,n)}else{let pt=(Bt=n.layout)==null?void 0:Bt.messages;pt!=null&&pt.renderUserMessage&&R.role==="user"?pe=pt.renderUserMessage({message:R,config:n,streaming:!!R.streaming}):pt!=null&&pt.renderAssistantMessage&&R.role==="assistant"?pe=pt.renderAssistantMessage({message:R,config:n,streaming:!!R.streaming}):pe=Dr(R,y,pt,n.messageActions,Xe,{loadingIndicatorRenderer:W,widgetConfig:n}),R.role!=="user"&&pe&&Gs(pe,R,n,H)}let Je=document.createElement("div");Je.className="persona-flex",Je.id=`wrapper-${R.id}`,Je.setAttribute("data-wrapper-id",R.id),R.role==="user"&&Je.classList.add("persona-justify-end"),(pe==null?void 0:pe.getAttribute("data-persona-component-directive"))==="true"&&Je.classList.add("persona-w-full"),Je.appendChild(pe),lc(zn,R.id,He,Je),E.appendChild(Je)}),cc(zn,P);let U=g.some(R=>R.role==="assistant"&&R.streaming),N=g[g.length-1],ae=(N==null?void 0:N.role)==="assistant"&&!N.streaming&&N.variant!=="approval";if(jn&&g.some(R=>R.role==="user")&&!U&&!ae){let R={config:n,streaming:!0,location:"standalone",defaultRenderer:hr},He=s.find(pe=>pe.renderLoadingIndicator),Re=null;if(He!=null&&He.renderLoadingIndicator&&(Re=He.renderLoadingIndicator(R)),Re===null&&((be=n.loadingIndicator)!=null&&be.render)&&(Re=n.loadingIndicator.render(R)),Re===null&&(Re=hr()),Re){let pe=document.createElement("div"),De=((we=n.loadingIndicator)==null?void 0:we.showBubble)!==!1;pe.className=De?["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(" "),pe.setAttribute("data-typing-indicator","true"),pe.appendChild(Re);let lt=document.createElement("div");lt.className="persona-flex",lt.id="wrapper-typing-indicator",lt.setAttribute("data-wrapper-id","typing-indicator"),lt.appendChild(pe),E.appendChild(lt)}}if(!jn&&g.length>0){let R=g[g.length-1],He={config:n,lastMessage:R,messageCount:g.length},Re=s.find(De=>De.renderIdleIndicator),pe=null;if(Re!=null&&Re.renderIdleIndicator&&(pe=Re.renderIdleIndicator(He)),pe===null&&((We=n.loadingIndicator)!=null&&We.renderIdle)&&(pe=n.loadingIndicator.renderIdle(He)),pe){let De=document.createElement("div"),lt=((Se=n.loadingIndicator)==null?void 0:Se.showBubble)!==!1;De.className=lt?["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(" "),De.setAttribute("data-idle-indicator","true"),De.appendChild(pe);let Je=document.createElement("div");Je.className="persona-flex",Je.id="wrapper-idle-indicator",Je.setAttribute("data-wrapper-id","idle-indicator"),Je.appendChild(De),E.appendChild(Je)}}oc(l,E),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let R=Lo();Io(R)})})},rr=()=>{var N,ae,be,we,We;if(!b)return;let l=jt(n),g=(N=e.ownerDocument.defaultView)!=null?N:window,y=(be=(ae=n.launcher)==null?void 0:ae.mobileBreakpoint)!=null?be:640,E=(We=(we=n.launcher)==null?void 0:we.mobileFullscreen)!=null?We:!0,L=g.innerWidth<=y,W=E&&L&&b,P=un(n).reveal;k?(Me.style.removeProperty("display"),Me.style.display=l?"flex":"",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-95","persona-opacity-0"),D.classList.add("persona-scale-100","persona-opacity-100"),_e?_e.element.style.display="none":qe&&(qe.style.display="none")):(l?l&&(P==="overlay"||P==="push")&&!W?(Me.style.removeProperty("display"),Me.style.display="flex",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.setProperty("display","none","important"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.display="",Me.classList.add("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100"),D.classList.add("persona-scale-95","persona-opacity-0")),_e?_e.element.style.display=l?"none":"":qe&&(qe.style.display=l?"none":""))},vt=(l,g="user")=>{if(!b||k===l)return;let y=k;k=l,rr(),k&&(Lt(),tr(!0));let E={open:k,source:g,timestamp:Date.now()};k&&!y?o.emit("widget:opened",E):!k&&y&&o.emit("widget:closed",E),o.emit("widget:state",{open:k,launcherEnabled:b,voiceActive:Ve.active,streaming:H.isStreaming()})},Ar=l=>{J.disabled=l,T&&(T.disabled=l),_n.buttons.forEach(g=>{g.disabled=l}),it.dataset.personaComposerStreaming=l?"true":"false",it.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},Er=()=>{Ve.active||Z&&Z.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Er(),200)});let Xr=()=>{var y,E,L,W,P,U,N,ae,be,we,We;qt.textContent=(E=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?E:"Hello \u{1F44B}",Ut.textContent=(W=(L=n.copy)==null?void 0:L.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",Z.placeholder=(U=(P=n.copy)==null?void 0:P.inputPlaceholder)!=null?U:"How can I help...";let l=z.querySelector("[data-persona-intro-card]");if(l){let Se=((N=n.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Se?"":"none",Se?(z.classList.remove("persona-gap-3"),z.classList.add("persona-gap-6")):(z.classList.remove("persona-gap-6"),z.classList.add("persona-gap-3"))}(be=(ae=n.sendButton)==null?void 0:ae.useIcon)!=null&&be||(J.textContent=(We=(we=n.copy)==null?void 0:we.sendButtonLabel)!=null?We:"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=>{f(g=>({...g,sessionId:l}))}}),H=new Wr(n,{onMessagesChanged(l){nr(oe,l,_),H&&(l.some(L=>L.role==="user")?_n.render([],H,Z,l):_n.render(n.suggestionChips,H,Z,l,n.suggestionChipsConfig)),tr(!jn),Po(l);let g=[...l].reverse().find(E=>E.role==="user"),y=Ve.lastUserMessageId;g&&g.id!==y&&(Ve.lastUserMessageId=g.id,o.emit("user:message",g)),Ve.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Yr(l)},onStatusChanged(l){var E;let g=(E=n.statusIndicator)!=null?E:{};rt(St,(L=>{var W,P,U,N;return L==="idle"?(W=g.idleText)!=null?W:Gt.idle:L==="connecting"?(P=g.connectingText)!=null?P:Gt.connecting:L==="connected"?(U=g.connectedText)!=null?U:Gt.connected:L==="error"?(N=g.errorText)!=null?N:Gt.error:Gt[L]})(l),g,l)},onStreamingChanged(l){jn=l,Ar(l),H&&nr(oe,H.getMessages(),_),l||tr(!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":fn(),Ro();break;case"speaking":fn(),Ho();break;default:l==="idle"&&H.isBargeInActive()?(fn(),qn(),T==null||T.setAttribute("aria-label","End voice session")):(Ve.active=!1,fn(),cn("system"),Qt());break}},onArtifactsState(l){an=l,Cn()}}),jr.current=H,((Ra=(Wa=n.voiceRecognition)==null?void 0:Wa.provider)==null?void 0:Ra.type)==="runtype")try{H.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&H.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),q&&H.setSSEEventCallback((l,g)=>{q==null||q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),p&&p.then(l=>{var g;l&&(l.metadata&&(i=Zs(l.metadata),A.syncFromMetadata()),(g=l.messages)!=null&&g.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Zr=l=>{var L;l.preventDefault();let g=Z.value.trim(),y=(L=he==null?void 0:he.hasAttachments())!=null?L:!1;if(!g&&!y)return;let E;y&&(E=[],E.push(...he.getContentParts()),g&&E.push(Yo(g))),Z.value="",Z.style.height="auto",H.sendMessage(g,{contentParts:E}),y&&he.clearAttachments()},Qr=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),J.click())},eo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!he)return;let g=Lp(l.clipboardData);g.length!==0&&(l.preventDefault(),await he.handleFiles(g))},Yt=null,on=!1,Rn=null,$e=null,to=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,or=(l="user")=>{var W,P,U,N,ae,be,we,We;if(on||H.isStreaming())return;let g=to();if(!g)return;Yt=new g;let E=(P=((W=n.voiceRecognition)!=null?W:{}).pauseDuration)!=null?P:2e3;Yt.continuous=!0,Yt.interimResults=!0,Yt.lang="en-US";let L=Z.value;Yt.onresult=Se=>{let R="",He="";for(let pe=0;pe<Se.results.length;pe++){let De=Se.results[pe],lt=De[0].transcript;De.isFinal?R+=lt+" ":He=lt}let Re=L+R+He;Z.value=Re,Rn&&clearTimeout(Rn),(R||He)&&(Rn=window.setTimeout(()=>{let pe=Z.value.trim();pe&&Yt&&on&&(mn(),Z.value="",Z.style.height="auto",H.sendMessage(pe,{viaVoice:!0}))},E))},Yt.onerror=Se=>{Se.error!=="no-speech"&&mn()},Yt.onend=()=>{if(on){let Se=Z.value.trim();Se&&Se!==L.trim()&&(Z.value="",Z.style.height="auto",H.sendMessage(Se,{viaVoice:!0})),mn()}};try{if(Yt.start(),on=!0,Ve.active=!0,l!=="system"&&(Ve.manuallyDeactivated=!1),cn(l),Qt(),T){let Se=(U=n.voiceRecognition)!=null?U:{};$e={backgroundColor:T.style.backgroundColor,color:T.style.color,borderColor:T.style.borderColor,iconName:(N=Se.iconName)!=null?N:"mic",iconSize:parseFloat((we=(be=Se.iconSize)!=null?be:(ae=n.sendButton)==null?void 0:ae.size)!=null?we:"40")||24};let R=(We=Se.recordingBackgroundColor)!=null?We:"#ef4444",He=Se.recordingIconColor,Re=Se.recordingBorderColor;if(T.classList.add("persona-voice-recording"),T.style.backgroundColor=R,He){T.style.color=He;let pe=T.querySelector("svg");pe&&pe.setAttribute("stroke",He)}Re&&(T.style.borderColor=Re),T.setAttribute("aria-label","Stop voice recognition")}}catch{mn("system")}},mn=(l="user")=>{if(on){if(on=!1,Rn&&(clearTimeout(Rn),Rn=null),Yt){try{Yt.stop()}catch{}Yt=null}if(Ve.active=!1,cn(l),Qt(),T){if(T.classList.remove("persona-voice-recording"),$e){T.style.backgroundColor=$e.backgroundColor,T.style.color=$e.color,T.style.borderColor=$e.borderColor;let g=T.querySelector("svg");g&&g.setAttribute("stroke",$e.color||"currentColor"),$e=null}T.setAttribute("aria-label","Start voice recognition")}}},Wo=(l,g)=>{var pe,De,lt,Je,me,Bt,pt,tn;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),E=((pe=l==null?void 0:l.provider)==null?void 0:pe.type)==="runtype";if(!(y||E))return null;let W=h("div","persona-send-button-wrapper"),P=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");P.type="button",P.setAttribute("aria-label","Start voice recognition");let U=(De=l==null?void 0:l.iconName)!=null?De:"mic",N=(lt=g==null?void 0:g.size)!=null?lt:"40px",ae=(Je=l==null?void 0:l.iconSize)!=null?Je:N,be=parseFloat(ae)||24,we=(me=l==null?void 0:l.backgroundColor)!=null?me:g==null?void 0:g.backgroundColor,We=(Bt=l==null?void 0:l.iconColor)!=null?Bt:g==null?void 0:g.textColor;P.style.width=ae,P.style.height=ae,P.style.minWidth=ae,P.style.minHeight=ae,P.style.fontSize="18px",P.style.lineHeight="1";let Se=We||"currentColor",R=fe(U,be,Se,1.5);R?(P.appendChild(R),P.style.color=Se):(P.textContent="\u{1F3A4}",P.style.color=Se),we?P.style.backgroundColor=we:P.classList.add("persona-bg-persona-primary"),We?P.style.color=We:!We&&!(g!=null&&g.textColor)&&P.classList.add("persona-text-white"),l!=null&&l.borderWidth&&(P.style.borderWidth=l.borderWidth,P.style.borderStyle="solid"),l!=null&&l.borderColor&&(P.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(P.style.paddingLeft=l.paddingX,P.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(P.style.paddingTop=l.paddingY,P.style.paddingBottom=l.paddingY),W.appendChild(P);let He=(pt=l==null?void 0:l.tooltipText)!=null?pt:"Start voice recognition";if(((tn=l==null?void 0:l.showTooltip)!=null?tn:!1)&&He){let Jt=h("div","persona-send-button-tooltip");Jt.textContent=He,W.appendChild(Jt)}return{micButton:P,micButtonWrapper:W}},Tr=()=>{var g,y,E,L,W;if(!T||$e)return;let l=(g=n.voiceRecognition)!=null?g:{};$e={backgroundColor:T.style.backgroundColor,color:T.style.color,borderColor:T.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((W=(L=l.iconSize)!=null?L:(E=n.sendButton)==null?void 0:E.size)!=null?W:"40")||24}},Mr=(l,g)=>{var W,P,U,N,ae;if(!T)return;let y=T.querySelector("svg");y&&y.remove();let E=(ae=$e==null?void 0:$e.iconSize)!=null?ae:parseFloat((N=(U=(W=n.voiceRecognition)==null?void 0:W.iconSize)!=null?U:(P=n.sendButton)==null?void 0:P.size)!=null?N:"40")||24,L=fe(l,E,g,1.5);L&&T.appendChild(L)},sr=()=>{T&&T.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},qn=()=>{var L,W;if(!T)return;Tr();let l=(L=n.voiceRecognition)!=null?L:{},g=(W=l.recordingBackgroundColor)!=null?W:"#ef4444",y=l.recordingIconColor,E=l.recordingBorderColor;if(sr(),T.classList.add("persona-voice-recording"),T.style.backgroundColor=g,y){T.style.color=y;let P=T.querySelector("svg");P&&P.setAttribute("stroke",y)}E&&(T.style.borderColor=E),T.setAttribute("aria-label","Stop voice recognition")},Ro=()=>{var U,N,ae,be,we,We,Se,R;if(!T)return;Tr();let l=(U=n.voiceRecognition)!=null?U:{},g=H.getVoiceInterruptionMode(),y=(N=l.processingIconName)!=null?N:"loader",E=(be=(ae=l.processingIconColor)!=null?ae:$e==null?void 0:$e.color)!=null?be:"",L=(We=(we=l.processingBackgroundColor)!=null?we:$e==null?void 0:$e.backgroundColor)!=null?We:"",W=(R=(Se=l.processingBorderColor)!=null?Se:$e==null?void 0:$e.borderColor)!=null?R:"";sr(),T.classList.add("persona-voice-processing"),T.style.backgroundColor=L,T.style.borderColor=W;let P=E||"currentColor";T.style.color=P,Mr(y,P),T.setAttribute("aria-label","Processing voice input"),g==="none"&&(T.style.cursor="default")},Ho=()=>{var ae,be,we,We,Se,R,He,Re,pe,De,lt,Je;if(!T)return;Tr();let l=(ae=n.voiceRecognition)!=null?ae:{},g=H.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",E=(be=l.speakingIconName)!=null?be:y,L=(R=l.speakingIconColor)!=null?R:g==="barge-in"?(We=(we=l.recordingIconColor)!=null?we:$e==null?void 0:$e.color)!=null?We:"":(Se=$e==null?void 0:$e.color)!=null?Se:"",W=(pe=l.speakingBackgroundColor)!=null?pe:g==="barge-in"?(He=l.recordingBackgroundColor)!=null?He:"#ef4444":(Re=$e==null?void 0:$e.backgroundColor)!=null?Re:"",P=(Je=l.speakingBorderColor)!=null?Je:g==="barge-in"?(De=l.recordingBorderColor)!=null?De:"":(lt=$e==null?void 0:$e.borderColor)!=null?lt:"";sr(),T.classList.add("persona-voice-speaking"),T.style.backgroundColor=W,T.style.borderColor=P;let U=L||"currentColor";T.style.color=U,Mr(E,U);let N=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";T.setAttribute("aria-label",N),g==="none"&&(T.style.cursor="default"),g==="barge-in"&&T.classList.add("persona-voice-recording")},fn=()=>{var l,g,y;T&&(sr(),$e&&(T.style.backgroundColor=(l=$e.backgroundColor)!=null?l:"",T.style.color=(g=$e.color)!=null?g:"",T.style.borderColor=(y=$e.borderColor)!=null?y:"",Mr($e.iconName,$e.color||"currentColor"),$e=null),T.style.cursor="",T.setAttribute("aria-label","Start voice recognition"))},ar=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let y=H.getVoiceStatus(),E=H.getVoiceInterruptionMode();if(E==="none"&&(y==="processing"||y==="speaking"))return;if(E==="cancel"&&(y==="processing"||y==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,Qt(),cn("user"),fn()});return}H.toggleVoice().then(()=>{Ve.active=H.isVoiceActive(),Ve.manuallyDeactivated=!H.isVoiceActive(),Qt(),cn("user"),H.isVoiceActive()?qn():fn()});return}if(on){let y=Z.value.trim();Ve.manuallyDeactivated=!0,Qt(),mn("user"),y&&(Z.value="",Z.style.height="auto",H.sendMessage(y))}else Ve.manuallyDeactivated=!1,Qt(),or("user")};Pe=ar,T&&(T.addEventListener("click",ar),Et.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),fn()):mn("system"),T&&T.removeEventListener("click",ar)}));let Q=o.on("assistant:complete",()=>{Gr&&(Ve.active||Ve.manuallyDeactivated||Gr==="assistant"&&!Ve.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!Ve.active&&!Ve.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.toggleVoice().then(()=>{Ve.active=H.isVoiceActive(),cn("auto"),H.isVoiceActive()&&qn()}):or("auto"))},600))});Et.push(Q);let Ye=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});Et.push(Ye);let st=()=>{vt(!k,"user")},_e=null,qe=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>fo(n,st).element,onToggle:st});g&&(qe=g)}qe||(_e=fo(n,st))}_e?e.appendChild(_e.element):qe&&e.appendChild(qe),rr(),_n.render(n.suggestionChips,H,Z,void 0,n.suggestionChipsConfig),Xr(),Ar(H.isStreaming()),tr(!0),Mo(),M&&(b?k&&setTimeout(()=>Er(),200):setTimeout(()=>Er(),0));let Lt=()=>{var N,ae,be,we,We,Se,R,He,Re,pe,De,lt,Je;let l=jt(n),g=(ae=(N=n.launcher)==null?void 0:N.sidebarMode)!=null?ae:!1,y=l||g||((we=(be=n.launcher)==null?void 0:be.fullHeight)!=null?we:!1),E=(We=e.ownerDocument.defaultView)!=null?We:window,L=(R=(Se=n.launcher)==null?void 0:Se.mobileFullscreen)!=null?R:!0,W=(Re=(He=n.launcher)==null?void 0:He.mobileBreakpoint)!=null?Re:640,P=E.innerWidth<=W,U=L&&P&&b;try{if(U){Qn(),Jn(e,n);return}if(O&&(O=!1,Qn(),Jn(e,n)),!b&&!l){D.style.height="",D.style.width="";return}if(!g&&!l){let me=(De=(pe=n==null?void 0:n.launcher)==null?void 0:pe.width)!=null?De:n==null?void 0:n.launcherWidth,Bt=me!=null?me:"min(400px, calc(100vw - 24px))";D.style.width=Bt,D.style.maxWidth=Bt}if(Zn(),!y){let me=E.innerHeight,Bt=64,pt=(Je=(lt=n.launcher)==null?void 0:lt.heightOffset)!=null?Je:0,tn=Math.max(200,me-Bt),Jt=Math.min(640,tn),Xt=Math.max(200,Jt-pt);D.style.height=`${Xt}px`}}finally{rr()}};Lt();let Tt=(Ha=e.ownerDocument.defaultView)!=null?Ha:window;Tt.addEventListener("resize",Lt),Et.push(()=>Tt.removeEventListener("resize",Lt)),er=z.scrollTop;let C=()=>{let l=z.scrollTop,g=z.scrollHeight,y=z.clientHeight,E=g-l-y,L=Math.abs(l-er);if(er=l,!wr&&!(L<=To)){if(!Ln&&E<Kr){Pn=!1,Ln=!0;return}Ln&&E>Kr&&(Pn=!0,Cr=Date.now()+Eo,Ln=!1)}};z.addEventListener("scroll",C,{passive:!0}),Et.push(()=>z.removeEventListener("scroll",C)),Et.push(()=>{In&&cancelAnimationFrame(In)});let Fe=()=>{K&&(Sn&&(K.removeEventListener("click",Sn),Sn=null),b?(K.style.display="",Sn=()=>{vt(!1,"user")},K.addEventListener("click",Sn)):K.style.display="none")};Fe(),(()=>{let{clearChatButton:l}=se;l&&l.addEventListener("click",()=>{H.clearMessages(),zn.clear();try{localStorage.removeItem(_r),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_r}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==_r)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={},A.syncFromMetadata(),q==null||q.clear(),G==null||G.update()})})(),Ue&&Ue.addEventListener("submit",Zr),Z==null||Z.addEventListener("keydown",Qr),Z==null||Z.addEventListener("paste",eo),Et.push(()=>{Ue&&Ue.removeEventListener("submit",Zr),Z==null||Z.removeEventListener("keydown",Qr),Z==null||Z.removeEventListener("paste",eo)}),Et.push(()=>{H.cancel()}),_e?Et.push(()=>{_e==null||_e.destroy()}):qe&&Et.push(()=>{qe==null||qe.remove()});let w={update(l){var _a,ja,za,qa,Ua,Va,Ja,Ka,Ga,Ya,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Ni,Oi,$i,Fi,_i,ji,zi,qi,Ui,Vi,Ji,Ki,Gi,Yi,Xi,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;let g=n.toolCall,y=n.messageActions,E=(_a=n.layout)==null?void 0:_a.messages,L=n.colorScheme,W=n.loadingIndicator,P=n.iterationDisplay;n={...n,...l},Qn(),Jn(e,n),ls(e,n),cs(e,n),Cn(),n.colorScheme!==L&&Ur();let U=vo.getForInstance(n.plugins);s.length=0,s.push(...U),b=(za=(ja=n.launcher)==null?void 0:ja.enabled)!=null?za:!0,x=(Ua=(qa=n.launcher)==null?void 0:qa.autoExpand)!=null?Ua:!1,ne=(Ja=(Va=n.features)==null?void 0:Va.showReasoning)!=null?Ja:!0,Te=(Ga=(Ka=n.features)==null?void 0:Ka.showToolCalls)!=null?Ga:!0;let N=le;if(le=(Xa=(Ya=n.features)==null?void 0:Ya.showEventStreamToggle)!=null?Xa:!1,le&&!N){if(q||(Y=new xo(de),q=new bo(ce,Y),Y.open().then(()=>q==null?void 0:q.restore()).catch(()=>{}),H.setSSEEventCallback((j,tt)=>{q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:j,timestamp:Date.now(),payload:JSON.stringify(tt)})})),!Oe&&Ze){let j=(Qa=(Za=n.features)==null?void 0:Za.eventStream)==null?void 0:Qa.classNames,tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(j!=null&&j.toggleButton?" "+j.toggleButton:"");Oe=h("button",tt),Oe.style.width="28px",Oe.style.height="28px",Oe.type="button",Oe.setAttribute("aria-label","Event Stream"),Oe.title="Event Stream";let Ct=fe("activity","18px","currentColor",1.5);Ct&&Oe.appendChild(Ct);let je=se.clearChatButtonWrapper,at=se.closeButtonWrapper,Dt=je||at;Dt&&Dt.parentNode===Ze?Ze.insertBefore(Oe,Dt):Ze.appendChild(Oe),Oe.addEventListener("click",()=>{ve?At():ot()})}}else!le&&N&&(At(),Oe&&(Oe.remove(),Oe=null),q==null||q.clear(),Y==null||Y.destroy(),q=null,Y=null);if(((ei=n.launcher)==null?void 0:ei.enabled)===!1&&_e&&(_e.destroy(),_e=null),((ti=n.launcher)==null?void 0:ti.enabled)===!1&&qe&&(qe.remove(),qe=null),((ni=n.launcher)==null?void 0:ni.enabled)!==!1&&!_e&&!qe){let j=s.find(tt=>tt.renderLauncher);if(j!=null&&j.renderLauncher){let tt=j.renderLauncher({config:n,defaultRenderer:()=>fo(n,st).element,onToggle:st});tt&&(qe=tt,e.appendChild(qe))}qe||(_e=fo(n,st),e.appendChild(_e.element))}_e&&_e.update(n),ft&&((ri=n.launcher)==null?void 0:ri.title)!==void 0&&(ft.textContent=n.launcher.title),yt&&((oi=n.launcher)==null?void 0:oi.subtitle)!==void 0&&(yt.textContent=n.launcher.subtitle);let ae=(si=n.layout)==null?void 0:si.header;if((ae==null?void 0:ae.layout)!==I&&Ze){let j=ae?Hr(n,ae,{showClose:b,onClose:()=>vt(!1,"user")}):Dn({config:n,showClose:b,onClose:()=>vt(!1,"user")});Ze.replaceWith(j.header),Ze=j.header,Ie=j.iconHolder,ft=j.headerTitle,yt=j.headerSubtitle,K=j.closeButton,I=ae==null?void 0:ae.layout}else if(ae&&(Ie&&(Ie.style.display=ae.showIcon===!1?"none":""),ft&&(ft.style.display=ae.showTitle===!1?"none":""),yt&&(yt.style.display=ae.showSubtitle===!1?"none":""),K&&(K.style.display=ae.showCloseButton===!1?"none":""),se.clearChatButtonWrapper)){let j=ae.showClearChat;if(j!==void 0){se.clearChatButtonWrapper.style.display=j?"":"none";let{closeButtonWrapper:tt}=se;tt&&!tt.classList.contains("persona-absolute")&&(j?tt.classList.remove("persona-ml-auto"):tt.classList.add("persona-ml-auto"))}}let we=((ai=n.layout)==null?void 0:ai.showHeader)!==!1;Ze&&(Ze.style.display=we?"":"none");let We=((ii=n.layout)==null?void 0:ii.showFooter)!==!1;it&&(it.style.display=We?"":"none"),b!==S?b?vt(x,"auto"):(k=!0,rr()):x!==F&&vt(x,"auto"),F=x,S=b,Lt(),Fe();let He=JSON.stringify(l.toolCall)!==JSON.stringify(g),Re=JSON.stringify(n.messageActions)!==JSON.stringify(y),pe=JSON.stringify((li=n.layout)==null?void 0:li.messages)!==JSON.stringify(E),De=((ci=n.loadingIndicator)==null?void 0:ci.render)!==(W==null?void 0:W.render)||((di=n.loadingIndicator)==null?void 0:di.renderIdle)!==(W==null?void 0:W.renderIdle)||((pi=n.loadingIndicator)==null?void 0:pi.showBubble)!==(W==null?void 0:W.showBubble),lt=n.iterationDisplay!==P;(He||Re||pe||De||lt)&&H&&(Vr++,nr(oe,H.getMessages(),_));let me=(ui=n.launcher)!=null?ui:{},Bt=(gi=me.headerIconHidden)!=null?gi:!1,pt=(fi=(mi=n.layout)==null?void 0:mi.header)==null?void 0:fi.showIcon,tn=Bt||pt===!1,Jt=me.headerIconName,Xt=(hi=me.headerIconSize)!=null?hi:"48px";if(Ie){let j=te.querySelector(".persona-border-b-persona-divider"),tt=j==null?void 0:j.querySelector(".persona-flex-col");if(tn)Ie.style.display="none",j&&tt&&!j.contains(tt)&&j.insertBefore(tt,j.firstChild);else{if(Ie.style.display="",Ie.style.height=Xt,Ie.style.width=Xt,j&&tt&&(j.contains(Ie)?Ie.nextSibling!==tt&&(Ie.remove(),j.insertBefore(Ie,tt)):j.insertBefore(Ie,tt)),Jt){let je=parseFloat(Xt)||24,at=fe(Jt,je*.6,"#ffffff",2);at?Ie.replaceChildren(at):Ie.textContent=(yi=me.agentIconText)!=null?yi:"\u{1F4AC}"}else if(me.iconUrl){let je=Ie.querySelector("img");if(je)je.src=me.iconUrl,je.style.height=Xt,je.style.width=Xt;else{let at=document.createElement("img");at.src=me.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=Xt,at.style.width=Xt,Ie.replaceChildren(at)}}else{let je=Ie.querySelector("svg"),at=Ie.querySelector("img");(je||at)&&Ie.replaceChildren(),Ie.textContent=(bi=me.agentIconText)!=null?bi:"\u{1F4AC}"}let Ct=Ie.querySelector("img");Ct&&(Ct.style.height=Xt,Ct.style.width=Xt)}}let $t=(vi=(xi=n.layout)==null?void 0:xi.header)==null?void 0:vi.showTitle,pn=(wi=(Ci=n.layout)==null?void 0:Ci.header)==null?void 0:wi.showSubtitle;if(ft&&(ft.style.display=$t===!1?"none":""),yt&&(yt.style.display=pn===!1?"none":""),K){((Ai=(Si=n.layout)==null?void 0:Si.header)==null?void 0:Ai.showCloseButton)===!1?K.style.display="none":K.style.display="";let tt=(Ei=me.closeButtonSize)!=null?Ei:"32px",Ct=(Ti=me.closeButtonPlacement)!=null?Ti:"inline";K.style.height=tt,K.style.width=tt;let{closeButtonWrapper:je}=se,at=Ct==="top-right",Dt=je==null?void 0:je.classList.contains("persona-absolute");if(je&&at!==Dt)if(je.remove(),at)je.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",te.style.position="relative",te.appendChild(je);else{let nt=(ki=(Mi=me.clearChat)==null?void 0:Mi.placement)!=null?ki:"inline",_t=(Ii=(Li=me.clearChat)==null?void 0:Li.enabled)!=null?Ii:!0;je.className=_t&&nt==="inline"?"":"persona-ml-auto";let nn=te.querySelector(".persona-border-b-persona-divider");nn&&nn.appendChild(je)}if(K.style.color=me.closeButtonColor||bn.actionIconColor,me.closeButtonBackgroundColor?(K.style.backgroundColor=me.closeButtonBackgroundColor,K.classList.remove("hover:persona-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:persona-bg-gray-100")),me.closeButtonBorderWidth||me.closeButtonBorderColor){let nt=me.closeButtonBorderWidth||"0px",_t=me.closeButtonBorderColor||"transparent";K.style.border=`${nt} solid ${_t}`,K.classList.remove("persona-border-none")}else K.style.border="",K.classList.add("persona-border-none");me.closeButtonBorderRadius?(K.style.borderRadius=me.closeButtonBorderRadius,K.classList.remove("persona-rounded-full")):(K.style.borderRadius="",K.classList.add("persona-rounded-full")),me.closeButtonPaddingX?(K.style.paddingLeft=me.closeButtonPaddingX,K.style.paddingRight=me.closeButtonPaddingX):(K.style.paddingLeft="",K.style.paddingRight=""),me.closeButtonPaddingY?(K.style.paddingTop=me.closeButtonPaddingY,K.style.paddingBottom=me.closeButtonPaddingY):(K.style.paddingTop="",K.style.paddingBottom="");let zt=(Pi=me.closeButtonIconName)!=null?Pi:"x",hn=(Wi=me.closeButtonIconText)!=null?Wi:"\xD7";K.innerHTML="";let Zt=fe(zt,"20px","currentColor",2);Zt?K.appendChild(Zt):K.textContent=hn;let kt=(Ri=me.closeButtonTooltipText)!=null?Ri:"Close chat",sn=(Hi=me.closeButtonShowTooltip)!=null?Hi:!0;if(K.setAttribute("aria-label",kt),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),sn&&kt)){let nt=null,_t=()=>{if(nt||!K)return;let ir=K.ownerDocument,oo=ir.body;if(!oo)return;nt=En(ir,"div","persona-clear-chat-tooltip"),nt.textContent=kt;let so=En(ir,"div");so.className="persona-clear-chat-tooltip-arrow",nt.appendChild(so);let lr=K.getBoundingClientRect();nt.style.position="fixed",nt.style.left=`${lr.left+lr.width/2}px`,nt.style.top=`${lr.top-8}px`,nt.style.transform="translate(-50%, -100%)",oo.appendChild(nt)},nn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};je.addEventListener("mouseenter",_t),je.addEventListener("mouseleave",nn),K.addEventListener("focus",_t),K.addEventListener("blur",nn),je._cleanupTooltip=()=>{nn(),je&&(je.removeEventListener("mouseenter",_t),je.removeEventListener("mouseleave",nn)),K&&(K.removeEventListener("focus",_t),K.removeEventListener("blur",nn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:wt}=se;if(Ge){let j=(Bi=me.clearChat)!=null?Bi:{},tt=(Di=j.enabled)!=null?Di:!0,Ct=(Oi=(Ni=n.layout)==null?void 0:Ni.header)==null?void 0:Oi.showClearChat,je=Ct!==void 0?Ct:tt,at=($i=j.placement)!=null?$i:"inline";if(wt){wt.style.display=je?"":"none";let{closeButtonWrapper:Dt}=se;Dt&&!Dt.classList.contains("persona-absolute")&&(je?Dt.classList.remove("persona-ml-auto"):Dt.classList.add("persona-ml-auto"));let zt=at==="top-right",hn=wt.classList.contains("persona-absolute");if(zt!==hn&&je){if(wt.remove(),zt)wt.className="persona-absolute persona-top-4 persona-z-50",wt.style.right="48px",te.style.position="relative",te.appendChild(wt);else{wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wt.style.right="";let kt=te.querySelector(".persona-border-b-persona-divider"),sn=se.closeButtonWrapper;kt&&sn&&sn.parentElement===kt?kt.insertBefore(wt,sn):kt&&kt.appendChild(wt)}let Zt=se.closeButtonWrapper;Zt&&!Zt.classList.contains("persona-absolute")&&(zt?Zt.classList.add("persona-ml-auto"):Zt.classList.remove("persona-ml-auto"))}}if(je){let Dt=(Fi=j.size)!=null?Fi:"32px";Ge.style.height=Dt,Ge.style.width=Dt;let zt=(_i=j.iconName)!=null?_i:"refresh-cw",hn=(ji=j.iconColor)!=null?ji:"";Ge.style.color=hn||bn.actionIconColor,Ge.innerHTML="";let Zt=fe(zt,"20px","currentColor",2);if(Zt&&Ge.appendChild(Zt),j.backgroundColor?(Ge.style.backgroundColor=j.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),j.borderWidth||j.borderColor){let nt=j.borderWidth||"0px",_t=j.borderColor||"transparent";Ge.style.border=`${nt} solid ${_t}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");j.borderRadius?(Ge.style.borderRadius=j.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),j.paddingX?(Ge.style.paddingLeft=j.paddingX,Ge.style.paddingRight=j.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),j.paddingY?(Ge.style.paddingTop=j.paddingY,Ge.style.paddingBottom=j.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let kt=(zi=j.tooltipText)!=null?zi:"Clear chat",sn=(qi=j.showTooltip)!=null?qi:!0;if(Ge.setAttribute("aria-label",kt),wt&&(wt._cleanupTooltip&&(wt._cleanupTooltip(),delete wt._cleanupTooltip),sn&&kt)){let nt=null,_t=()=>{if(nt||!Ge)return;let ir=Ge.ownerDocument,oo=ir.body;if(!oo)return;nt=En(ir,"div","persona-clear-chat-tooltip"),nt.textContent=kt;let so=En(ir,"div");so.className="persona-clear-chat-tooltip-arrow",nt.appendChild(so);let lr=Ge.getBoundingClientRect();nt.style.position="fixed",nt.style.left=`${lr.left+lr.width/2}px`,nt.style.top=`${lr.top-8}px`,nt.style.transform="translate(-50%, -100%)",oo.appendChild(nt)},nn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};wt.addEventListener("mouseenter",_t),wt.addEventListener("mouseleave",nn),Ge.addEventListener("focus",_t),Ge.addEventListener("blur",nn),wt._cleanupTooltip=()=>{nn(),wt&&(wt.removeEventListener("mouseenter",_t),wt.removeEventListener("mouseleave",nn)),Ge&&(Ge.removeEventListener("focus",_t),Ge.removeEventListener("blur",nn))}}}}let Bo=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Co],Do=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[yr.message,yr.messageAndClick];A=wo({parsers:Bo,handlers:Do,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),_=Rc(n,A,ie),H.updateConfig(n),nr(oe,H.getMessages(),_),_n.render(n.suggestionChips,H,Z,void 0,n.suggestionChipsConfig),Xr(),Ar(H.isStreaming());let No=((Ui=n.voiceRecognition)==null?void 0:Ui.enabled)===!0,Oo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),$o=((Ji=(Vi=n.voiceRecognition)==null?void 0:Vi.provider)==null?void 0:Ji.type)==="runtype";if(No&&(Oo||$o))if(!T||!Ae){let j=Wo(n.voiceRecognition,n.sendButton);j&&(T=j.micButton,Ae=j.micButtonWrapper,ue.insertBefore(Ae,ze),T.addEventListener("click",ar),T.disabled=H.isStreaming())}else{let j=(Ki=n.voiceRecognition)!=null?Ki:{},tt=(Gi=n.sendButton)!=null?Gi:{},Ct=(Yi=j.iconName)!=null?Yi:"mic",je=(Xi=tt.size)!=null?Xi:"40px",at=(Zi=j.iconSize)!=null?Zi:je,Dt=parseFloat(at)||24;T.style.width=at,T.style.height=at,T.style.minWidth=at,T.style.minHeight=at;let zt=(el=(Qi=j.iconColor)!=null?Qi:tt.textColor)!=null?el:"currentColor";T.innerHTML="";let hn=fe(Ct,Dt,zt,2);hn?T.appendChild(hn):T.textContent="\u{1F3A4}";let Zt=(tl=j.backgroundColor)!=null?tl:tt.backgroundColor;Zt?(T.style.backgroundColor=Zt,T.classList.remove("persona-bg-persona-primary")):(T.style.backgroundColor="",T.classList.add("persona-bg-persona-primary")),zt?(T.style.color=zt,T.classList.remove("persona-text-white")):!zt&&!tt.textColor&&(T.style.color="",T.classList.add("persona-text-white")),j.borderWidth?(T.style.borderWidth=j.borderWidth,T.style.borderStyle="solid"):(T.style.borderWidth="",T.style.borderStyle=""),j.borderColor?T.style.borderColor=j.borderColor:T.style.borderColor="",j.paddingX?(T.style.paddingLeft=j.paddingX,T.style.paddingRight=j.paddingX):(T.style.paddingLeft="",T.style.paddingRight=""),j.paddingY?(T.style.paddingTop=j.paddingY,T.style.paddingBottom=j.paddingY):(T.style.paddingTop="",T.style.paddingBottom="");let kt=Ae==null?void 0:Ae.querySelector(".persona-send-button-tooltip"),sn=(nl=j.tooltipText)!=null?nl:"Start voice recognition";if(((rl=j.showTooltip)!=null?rl:!1)&&sn)if(kt)kt.textContent=sn,kt.style.display="";else{let _t=document.createElement("div");_t.className="persona-send-button-tooltip",_t.textContent=sn,Ae==null||Ae.insertBefore(_t,T)}else kt&&(kt.style.display="none");Ae.style.display="",T.disabled=H.isStreaming()}else T&&Ae&&(Ae.style.display="none",((sl=(ol=n.voiceRecognition)==null?void 0:ol.provider)==null?void 0:sl.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():on&&mn());if(((al=n.attachments)==null?void 0:al.enabled)===!0)if(!ye||!re){let j=(il=n.attachments)!=null?il:{},Ct=(cl=((ll=n.sendButton)!=null?ll:{}).size)!=null?cl:"40px";Qe||(Qe=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Qe.style.display="none",Ue.insertBefore(Qe,Z)),Ce||(Ce=document.createElement("input"),Ce.type="file",Ce.accept=((dl=j.allowedTypes)!=null?dl:Bn).join(","),Ce.multiple=((pl=j.maxFiles)!=null?pl:4)>1,Ce.style.display="none",Ce.setAttribute("aria-label","Attach files"),Ue.insertBefore(Ce,Z)),ye=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",(ul=j.buttonTooltipText)!=null?ul:"Attach file");let je=(gl=j.buttonIconName)!=null?gl:"paperclip",at=Ct,Dt=parseFloat(at)||40,zt=Math.round(Dt*.6);re.style.width=at,re.style.height=at,re.style.minWidth=at,re.style.minHeight=at,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 hn=fe(je,zt,"currentColor",1.5);hn?re.appendChild(hn):re.textContent="\u{1F4CE}",re.addEventListener("click",sn=>{sn.preventDefault(),Ce==null||Ce.click()}),ye.appendChild(re);let Zt=(ml=j.buttonTooltipText)!=null?ml:"Attach file",kt=h("div","persona-send-button-tooltip");kt.textContent=Zt,ye.appendChild(kt),Vt.append(ye),!he&&Ce&&Qe&&(he=mr.fromConfig(j),he.setPreviewsContainer(Qe),Ce.addEventListener("change",async()=>{he&&(Ce!=null&&Ce.files)&&(await he.handleFileSelect(Ce.files),Ce.value="")}))}else{ye.style.display="";let j=(fl=n.attachments)!=null?fl:{};Ce&&(Ce.accept=((hl=j.allowedTypes)!=null?hl:Bn).join(","),Ce.multiple=((yl=j.maxFiles)!=null?yl:4)>1),he&&he.updateConfig({allowedTypes:j.allowedTypes,maxFileSize:j.maxFileSize,maxFiles:j.maxFiles})}else ye&&(ye.style.display="none"),he&&he.clearAttachments();let Pt=(bl=n.sendButton)!=null?bl:{},Fo=(xl=Pt.useIcon)!=null?xl:!1,no=(vl=Pt.iconText)!=null?vl:"\u2191",ro=Pt.iconName,kr=(Cl=Pt.tooltipText)!=null?Cl:"Send message",_o=(wl=Pt.showTooltip)!=null?wl:!1,Un=(Sl=Pt.size)!=null?Sl:"40px",Kt=Pt.backgroundColor,Ft=Pt.textColor;if(Fo){if(J.style.width=Un,J.style.height=Un,J.style.minWidth=Un,J.style.minHeight=Un,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",ro){let j=parseFloat(Un)||24,tt=Ft&&typeof Ft=="string"&&Ft.trim()?Ft.trim():"currentColor",Ct=fe(ro,j,tt,2);Ct?(J.appendChild(Ct),J.style.color=tt):(J.textContent=no,Ft?J.style.color=Ft:J.classList.add("persona-text-white"))}else J.textContent=no,Ft?J.style.color=Ft:J.classList.add("persona-text-white");J.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Kt?(J.style.backgroundColor=Kt,J.classList.remove("persona-bg-persona-primary")):J.classList.add("persona-bg-persona-primary")}else J.textContent=(El=(Al=n.copy)==null?void 0:Al.sendButtonLabel)!=null?El:"Send",J.style.width="",J.style.height="",J.style.minWidth="",J.style.minHeight="",J.style.fontSize="",J.style.lineHeight="",J.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",Kt?(J.style.backgroundColor=Kt,J.classList.remove("persona-bg-persona-accent")):J.classList.add("persona-bg-persona-accent"),Ft?J.style.color=Ft:J.classList.add("persona-text-white");Pt.borderWidth?(J.style.borderWidth=Pt.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),Pt.borderColor?J.style.borderColor=Pt.borderColor:J.style.borderColor="",Pt.paddingX?(J.style.paddingLeft=Pt.paddingX,J.style.paddingRight=Pt.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),Pt.paddingY?(J.style.paddingTop=Pt.paddingY,J.style.paddingBottom=Pt.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let An=ze==null?void 0:ze.querySelector(".persona-send-button-tooltip");if(_o&&kr)if(An)An.textContent=kr,An.style.display="";else{let j=document.createElement("div");j.className="persona-send-button-tooltip",j.textContent=kr,ze==null||ze.insertBefore(j,J)}else An&&(An.style.display="none");let Ls=(Tl=n.layout)==null?void 0:Tl.contentMaxWidth;Ls?(oe.style.maxWidth=Ls,oe.style.marginLeft="auto",oe.style.marginRight="auto",oe.style.width="100%",Ue&&(Ue.style.maxWidth=Ls,Ue.style.marginLeft="auto",Ue.style.marginRight="auto")):(oe.style.maxWidth="",oe.style.marginLeft="",oe.style.marginRight="",oe.style.width="",Ue&&(Ue.style.maxWidth="",Ue.style.marginLeft="",Ue.style.marginRight=""));let Vn=(Ml=n.statusIndicator)!=null?Ml:{},bd=(kl=Vn.visible)!=null?kl:!0;if(St.style.display=bd?"":"none",H){let j=H.getStatus();rt(St,(Ct=>{var je,at,Dt,zt;return Ct==="idle"?(je=Vn.idleText)!=null?je:Gt.idle:Ct==="connecting"?(at=Vn.connectingText)!=null?at:Gt.connecting:Ct==="connected"?(Dt=Vn.connectedText)!=null?Dt:Gt.connected:Ct==="error"?(zt=Vn.errorText)!=null?zt:Gt.error:Gt[Ct]})(j),Vn,j)}St.classList.remove("persona-text-left","persona-text-center","persona-text-right");let xd=Vn.align==="left"?"persona-text-left":Vn.align==="center"?"persona-text-center":"persona-text-right";St.classList.add(xd)},open(){b&&vt(!0,"api")},close(){b&&vt(!1,"api")},toggle(){b&&vt(!k,"api")},clearChat(){rn=!1,H.clearMessages(),zn.clear();try{localStorage.removeItem(_r),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_r}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==_r)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={},A.syncFromMetadata(),q==null||q.clear(),G==null||G.update()},setMessage(l){return!Z||H.isStreaming()?!1:(!k&&b&&vt(!0,"system"),Z.value=l,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let g=(l==null?void 0:l.trim())||Z.value.trim();return g?(!k&&b&&vt(!0,"system"),Z.value="",Z.style.height="auto",H.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return H.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(H.isVoiceActive()||(!k&&b&&vt(!0,"system"),Ve.manuallyDeactivated=!1,Qt(),H.toggleVoice().then(()=>{Ve.active=H.isVoiceActive(),cn("user"),H.isVoiceActive()&&qn()})),!0):on?!0:to()?(!k&&b&&vt(!0,"system"),Ve.manuallyDeactivated=!1,Qt(),or("user"),!0):!1},stopVoiceRecognition(){var l,g;return((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,Qt(),cn("user"),fn()}),!0):!1:on?(Ve.manuallyDeactivated=!0,Qt(),mn("user"),!0):!1},injectMessage(l){return!k&&b&&vt(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!k&&b&&vt(!0,"system");let g=H.injectAssistantMessage(l);return V&&(V=!1,ge&&(clearTimeout(ge),ge=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),g},injectUserMessage(l){return!k&&b&&vt(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!k&&b&&vt(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!k&&b&&vt(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!k&&b&&vt(!0,"system"),H.injectTestEvent(l)},async connectStream(l,g){return H.connectStream(l,g)},__pushEventStreamEvent(l){q&&q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!le||!q||ot()},hideEventStream(){ve&&At()},isEventStreamVisible(){return ve},showArtifacts(){gn(n)&&(rn=!1,Cn(),et==null||et.setMobileOpen(!0))},hideArtifacts(){gn(n)&&(rn=!0,Cn())},upsertArtifact(l){return gn(n)?(rn=!1,H.upsertArtifact(l)):null},selectArtifact(l){gn(n)&&H.selectArtifact(l)},clearArtifacts(){gn(n)&&H.clearArtifacts()},focusInput(){return b&&!k||!Z?!1:(Z.focus(),!0)},async resolveApproval(l,g){let E=H.getMessages().find(L=>{var W;return L.variant==="approval"&&((W=L.approval)==null?void 0:W.id)===l});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${l}`);return H.resolveApproval(E.approval,g)},getMessages(){return H.getMessages()},getStatus(){return H.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&&k},isVoiceActive(){return Ve.active},getState(){return{open:b&&k,launcherEnabled:b,voiceActive:Ve.active,streaming:H.isStreaming()}},showCSATFeedback(l){!k&&b&&vt(!0,"system");let g=oe.querySelector(".persona-feedback-container");g&&g.remove();let y=hs({onSubmit:async(E,L)=>{var W;H.isClientTokenMode()&&await H.submitCSATFeedback(E,L),(W=l==null?void 0:l.onSubmit)==null||W.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});oe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&b&&vt(!0,"system");let g=oe.querySelector(".persona-feedback-container");g&&g.remove();let y=ys({onSubmit:async(E,L)=>{var W;H.isClientTokenMode()&&await H.submitNPSFeedback(E,L),(W=l==null?void 0:l.onSubmit)==null||W.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});oe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return H.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return H.submitNPSFeedback(l,g)},destroy(){Et.forEach(l=>l()),Me.remove(),_e==null||_e.destroy(),qe==null||qe.remove(),Sn&&K.removeEventListener("click",Sn)}};if((((Ba=t==null?void 0:t.debugTools)!=null?Ba:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:w,getMessages:w.getMessages,getStatus:w.getStatus,getMetadata:w.getPersistentMetadata,updateMetadata:w.updatePersistentMetadata,clearHistory:()=>w.clearChat(),setVoiceActive:y=>y?w.startVoiceRecognition():w.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Et.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=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.focusInput()};if(window.addEventListener("persona:focusInput",g),Et.push(()=>{window.removeEventListener("persona:focusInput",g)}),le){let U=ae=>{let be=ae.detail;(!(be!=null&&be.instanceId)||be.instanceId===l)&&w.showEventStream()},N=ae=>{let be=ae.detail;(!(be!=null&&be.instanceId)||be.instanceId===l)&&w.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",N),Et.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",N)})}let y=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.showArtifacts()},E=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.hideArtifacts()},L=U=>{let N=U.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&w.upsertArtifact(N.artifact)},W=U=>{let N=U.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&w.selectArtifact(N.id)},P=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",P),Et.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",P)})}let ee=Ip(n.persistState);if(ee&&b){let l=Pp(ee.storage),g=`${ee.keyPrefix}widget-open`,y=`${ee.keyPrefix}widget-voice`,E=`${ee.keyPrefix}widget-voice-mode`;if(l){let L=((Da=ee.persist)==null?void 0:Da.openState)&&l.getItem(g)==="true",W=((Na=ee.persist)==null?void 0:Na.voiceState)&&l.getItem(y)==="true",P=((Oa=ee.persist)==null?void 0:Oa.voiceState)&&l.getItem(E)==="true";if(L&&setTimeout(()=>{w.open(),setTimeout(()=>{var U;if(W||P)w.startVoiceRecognition();else if((U=ee.persist)!=null&&U.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),($a=ee.persist)!=null&&$a.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(Fa=ee.persist)!=null&&Fa.voiceState&&(o.on("voice:state",U=>{l.setItem(y,U.active?"true":"false")}),o.on("user:message",U=>{l.setItem(E,U.viaVoice?"true":"false")})),ee.clearOnChatClear){let U=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(E)},N=()=>U();window.addEventListener("persona:clear-chat",N),Et.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return c&&b&&setTimeout(()=>{w.open()},0),w};var Wp=(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},Hc=(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"},na=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=""},Bc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",na(e)},Qs=e=>{e.style.transition=""},ea=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=""},ta=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},xs=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Rp=(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))},Hp=(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)},Dc=(e,r,t,n,s,o,a)=>{var v,A,b,x,M,F;let i=un(o),p=i.reveal==="push";Rp(e,r,t,n,p),Hp(e,r,t,n,i.side,p),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,u=(A=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?A:!0,d=(x=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?x:640,f=c!=null?c.innerWidth<=d:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ea(r),Qs(n),Bc(n),ta(t),xs(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((F=(M=o==null?void 0:o.launcher)==null?void 0:M.zIndex)!=null?F:9999),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",p&&(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"),Bc(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ea(r),Qs(n),ta(t),xs(s,n);let S=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",O=a?"translateX(0)":I;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=S,n.style.transform=O,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",Qs(n),na(n),xs(s,n);let S=Wp(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),O=i.animate?"transform 180ms ease":"none",k=i.side==="right"?a?`translateX(-${S}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${S}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=`${I+S}px`,r.style.transition=O,r.style.transform=k,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${I}px`,t.style.maxWidth=`${I}px`,t.style.minWidth=`${I}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="",ea(r),na(n),ta(t),xs(s,n);let S=i.reveal==="emerge";S?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",O=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",k=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${I}`,n.style.width=I,n.style.maxWidth=I,n.style.minWidth=I,n.style.minHeight="0",n.style.position="relative",n.style.overflow=S||k?"hidden":"visible",n.style.transition=O,S&&(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")}},Bp=(e,r)=>{let t=e.ownerDocument.createElement("div");return Hc(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Hc(t,n)},destroy(){t.remove()}}},Dp=(e,r)=>{var M,F,S,I;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"),p=t.createElement("div"),c=t.createElement("aside"),u=t.createElement("div"),d=(F=(M=r==null?void 0:r.launcher)==null?void 0:M.enabled)==null||F?(I=(S=r==null?void 0:r.launcher)==null?void 0:S.autoExpand)!=null?I:!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),n.insertBefore(a,e),p.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),un(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Dc(a,i,p,c,u,r,d)}),f.observe(a))},A=()=>{Dc(a,i,p,c,u,r,d),v()},b=a.ownerDocument.defaultView,x=()=>{A()};return b==null||b.addEventListener("resize",x),un(r).reveal==="push"?(i.appendChild(p),i.appendChild(c),a.appendChild(i)):(a.appendChild(p),a.appendChild(c)),A(),{mode:"docked",host:u,shell:a,syncWidgetState(O){let k=O.launcherEnabled?O.open:!0;d!==k&&(d=k,A())},updateConfig(O){var k,V;r=O,((V=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)!=null?V:!0)===!1&&(d=!0),A()},destroy(){b==null||b.removeEventListener("resize",x),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},So=(e,r)=>jt(r)?Dp(e,r):Bp(e,r);var ra={},Np=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},Op=()=>{try{if(typeof ra!="undefined"&&ra.url)return new URL("../widget.css",ra.url).href}catch{}return null},Nc=(e,r)=>{let t=Op(),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)}},oa=e=>{var b;let r=Np(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=So(r,s),a,i=[],p=(x,M)=>{var O,k;let S=!((k=(O=M==null?void 0:M.launcher)==null?void 0:O.enabled)!=null?k:!0)||jt(M),I=n.createElement("div");if(I.setAttribute("data-persona-root","true"),S&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),t){let V=x.attachShadow({mode:"open"});V.appendChild(I),Nc(V,n)}else x.appendChild(I),Nc(x,n);return r.id&&I.setAttribute("data-persona-instance",r.id),I},c=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let x=p(o.host,s);a=bs(x,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(x=>x()),i=[],a.destroy()};d(),(b=e.onReady)==null||b.call(e);let m=x=>{f(),o.destroy(),o=So(r,x),s=x,d()},v={update(x){var I,O,k,V,ge,ie;let M={...s,...x,launcher:{...(I=s==null?void 0:s.launcher)!=null?I:{},...(O=x==null?void 0:x.launcher)!=null?O:{},dock:{...(V=(k=s==null?void 0:s.launcher)==null?void 0:k.dock)!=null?V:{},...(ie=(ge=x==null?void 0:x.launcher)==null?void 0:ge.dock)!=null?ie:{}}}},F=jt(s),S=jt(M);if(F!==S){m(M);return}s=M,o.updateConfig(s),a.update(x),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},A=new Proxy(v,{get(x,M,F){if(M==="host")return o.host;if(M in x)return Reflect.get(x,M,F);let S=a[M];return typeof S=="function"?S.bind(a):S}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=A),A};var jc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),$p=new Set(["button","a","input","select","textarea","details","summary"]),Fp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),sa=/\b(product|card|item|listing|result)\b/i,ia=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,_p=3e3,jp=100;function zc(e){let r=typeof e.className=="string"?e.className:"";if(sa.test(r)||e.id&&sa.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&sa.test(n.value))return!0}return!1}function qc(e){var r;return ia.test(((r=e.textContent)!=null?r:"").trim())}function Uc(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 zp(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Oc(e){let r=e.match(ia);return r?r[0]:null}function $c(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 qp(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 Up="commerce-card",Vp="result-card";function Fc(e){return!zc(e)||!qc(e)||!Uc(e)&&!zp(e)?0:5200}function _c(e){var n;return!zc(e)||qc(e)||!Uc(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 la=[{id:Up,scoreElement(e){return Fc(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||ia.test(n)&&n.length<32)}return!0},formatSummary(e,r){var p,c,u;if(Fc(e)===0)return null;let{title:t,href:n}=$c(e),s=(u=(c=Oc(((p=e.textContent)!=null?p:"").trim()))!=null?c:Oc(r.text))!=null?u:"",o=qp(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(`
98
+ `)}},{id:Vp,scoreElement(e){return _c(e)},formatSummary(e,r){if(_c(e)===0)return null;let{title:t,href:n}=$c(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
99
+ `)}}];function Jp(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Kp(e){var u,d,f,m,v,A,b,x,M,F,S,I,O;let r=(u=e.options)!=null?u:{},t=(f=(d=r.maxElements)!=null?d:e.maxElements)!=null?f:80,n=(v=(m=r.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",s=(b=(A=r.maxTextLength)!=null?A:e.maxTextLength)!=null?b:200,o=(M=(x=r.visibleOnly)!=null?x:e.visibleOnly)!=null?M:!0,a=(F=r.root)!=null?F:e.root,i=(S=r.mode)!=null?S:"structured",p=(I=r.maxCandidates)!=null?I:Math.max(500,t*10),c=(O=e.rules)!=null?O:la;return i==="simple"&&e.rules&&e.rules.length>0?(Jp(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:p,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function aa(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Gp=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Yp(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"||$p.has(r)||t&&Fp.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Vc(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 Xp(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 p=e.getAttribute("role");p&&(r.role=p);for(let c=0;c<e.attributes.length;c++){let u=e.attributes[c];u.name.startsWith("data-")&&(r[u.name]=u.value)}return r}function ca(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${aa(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Gp){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${aa(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=>aa(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 p=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}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 Zp(e){return e==="static"?jp:_p}function Jc(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:ca(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:Yp(e),attributes:Xp(e)}}function Qp(e,r,t,n){let s=Zp(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 eu(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 tu(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,u=c.tagName.toLowerCase();if(jc.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Vc(c)){i=a.nextNode();continue}let d=Jc(c,e.maxTextLength),f=d.text.length>0,m=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(b=>b==="role");if(!f&&!m){i=a.nextNode();continue}if(n.has(d.selector)){i=a.nextNode();continue}n.add(d.selector);let{score:v,formattingRule:A}=Qp(c,d,e.rules,t);s.push({el:c,domIndex:o,enriched:d,score:v,formattingRule:A}),o+=1}i=a.nextNode()}s.sort((c,u)=>{let d=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return d!==f?d-f:u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex});let p=[];for(let c of s){if(p.length>=e.maxElements)break;eu(p,c)||p.push(c)}return p.sort((c,u)=>{let d=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return d!==f?d-f:d===1&&u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex}),p.map(c=>{var f;let u;if((f=c.formattingRule)!=null&&f.formatSummary){let m=c.formattingRule.formatSummary(c.el,c.enriched,t);m&&(u=m)}let d={...c.enriched};return u&&(d.formattedSummary=u),d})}function nu(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 p=o,c=p.tagName.toLowerCase();if(jc.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Vc(p)){o=s.nextNode();continue}let u=Jc(p,e.maxTextLength),d=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!d&&!f){o=s.nextNode();continue}n.has(u.selector)||(n.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let p of t)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function Kc(e={}){var n;let r=Kp(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?nu(r,t):tu(r,t):[]}var vs=100;function Gc(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:
100
100
  ${a.map(i=>`- ${i.split(`
101
101
  `).join(`
102
102
  `)}`).join(`
103
- `)}`)}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,xs)}" (clickable)`);n.push(`Interactive elements:
103
+ `)}`)}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,vs)}" (clickable)`);n.push(`Interactive elements:
104
104
  ${a.join(`
105
- `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,xs)}" (navigable)`);n.push(`Navigation links:
105
+ `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,vs)}" (navigable)`);n.push(`Navigation links:
106
106
  ${a.join(`
107
- `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,xs)}" (input)`);n.push(`Form inputs:
107
+ `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,vs)}" (input)`);n.push(`Form inputs:
108
108
  ${a.join(`
109
- `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,xs)}"`);n.push(`Content:
109
+ `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,vs)}"`);n.push(`Content:
110
110
  ${a.join(`
111
111
  `)}`)}return n.join(`
112
112
 
113
- `)}var Kc={name:"@runtypelabs/persona",version:"3.4.0",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"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref","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 hr=Kc.version;function On(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function tu(e){if(e)return{getHeaders:On(e.getHeaders),onFeedback:On(e.onFeedback),onCopy:On(e.onCopy),requestMiddleware:On(e.requestMiddleware),actionHandlers:On(e.actionHandlers),actionParsers:On(e.actionParsers),postprocessMessage:On(e.postprocessMessage),contextProviders:On(e.contextProviders),streamParser:On(e.streamParser)}}var Gc=`({ text, message }: any) => {
113
+ `)}var Yc={name:"@runtypelabs/persona",version:"3.5.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"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref","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 br=Yc.version;function On(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function ou(e){if(e)return{getHeaders:On(e.getHeaders),onFeedback:On(e.onFeedback),onCopy:On(e.onCopy),requestMiddleware:On(e.requestMiddleware),actionHandlers:On(e.actionHandlers),actionParsers:On(e.actionParsers),postprocessMessage:On(e.postprocessMessage),contextProviders:On(e.contextProviders),streamParser:On(e.streamParser)}}var Xc=`({ text, message }: any) => {
114
114
  const jsonSource = (message as any).rawContent || text || message.content;
115
115
  if (!jsonSource || typeof jsonSource !== 'string') return null;
116
116
  let cleanJson = jsonSource
@@ -123,7 +123,7 @@ ${a.join(`
123
123
  if (parsed.action) return { type: parsed.action, payload: parsed };
124
124
  } catch (e) { return null; }
125
125
  return null;
126
- }`,Yc=`function(ctx) {
126
+ }`,Zc=`function(ctx) {
127
127
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
128
128
  if (!jsonSource || typeof jsonSource !== 'string') return null;
129
129
  var cleanJson = jsonSource
@@ -136,7 +136,7 @@ ${a.join(`
136
136
  if (parsed.action) return { type: parsed.action, payload: parsed };
137
137
  } catch (e) { return null; }
138
138
  return null;
139
- }`,Xc=`(action: any, context: any) => {
139
+ }`,Qc=`(action: any, context: any) => {
140
140
  if (action.type !== 'nav_then_click') return;
141
141
  const payload = action.payload || action.raw || {};
142
142
  const url = payload?.page;
@@ -153,7 +153,7 @@ ${a.join(`
153
153
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
154
154
  window.location.href = targetUrl;
155
155
  return { handled: true, displayText: text };
156
- }`,Zc=`function(action, context) {
156
+ }`,ed=`function(action, context) {
157
157
  if (action.type !== 'nav_then_click') return;
158
158
  var payload = action.payload || action.raw || {};
159
159
  var url = payload.page;
@@ -170,26 +170,26 @@ ${a.join(`
170
170
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
171
171
  window.location.href = targetUrl;
172
172
  return { handled: true, displayText: text };
173
- }`,nu=`(parsed: any) => {
173
+ }`,su=`(parsed: any) => {
174
174
  if (!parsed || typeof parsed !== 'object') return null;
175
175
  if (parsed.action === 'nav_then_click') return 'Navigating...';
176
176
  if (parsed.action === 'message') return parsed.text || '';
177
177
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
178
178
  return parsed.text || null;
179
- }`,ru=`function(parsed) {
179
+ }`,au=`function(parsed) {
180
180
  if (!parsed || typeof parsed !== 'object') return null;
181
181
  if (parsed.action === 'nav_then_click') return 'Navigating...';
182
182
  if (parsed.action === 'message') return parsed.text || '';
183
183
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
184
184
  return parsed.text || null;
185
- }`;function ou(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 vs(e){var r,t;return(t=(r=e.parserType)!=null?r:ou(e.streamParser))!=null?t:"plain"}function Cs(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 ws(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 Ss(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 As(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,d])=>{typeof d=="string"?t.push(`${r} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${r} ${i}: ${d},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?t.push(`${r} ${d}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${d}: ${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 la(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 Qc(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}: {`),Qc(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function Kn(e,r,t,n){t&&(e.push(`${n}${r}: {`),Qc(e,t,`${n} `),e.push(`${n}},`))}function ed(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:tu(t.hooks)}:void 0;return r==="esm"?su(n,s):r==="script-installer"?lu(n):r==="script-advanced"?du(n,s):r==="react-component"?au(n,s):r==="react-advanced"?iu(n,s):cu(n,s)}function su(e,r){let t=r==null?void 0:r.hooks,n=vs(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&&Kn(o,"theme",e.theme," "),e.launcher&&Kn(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(...Cs(e," ")),o.push(...ws(e," ",t)),o.push(...Ss(e," ")),o.push(...As(e," ")),o.push(...la(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(`
186
- `)}function au(e,r){let t=r==null?void 0:r.hooks,n=vs(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&&Kn(o,"theme",e.theme," "),e.launcher&&Kn(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(...Cs(e," ")),o.push(...ws(e," ",t)),o.push(...Ss(e," ")),o.push(...As(e," ")),o.push(...la(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(`
187
- `)}function iu(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&&Kn(n,"theme",e.theme," "),e.launcher&&Kn(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(...Cs(e," ")),n.push(...ws(e," ",t)),n.push(...Ss(e," ")),n.push(...As(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(${nu}),`)),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(` ${Gc}`),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(` ${Gc}`),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(` ${Xc}`),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(` ${Xc}`),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(`
188
- `)}function td(e){var s;let r=vs(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,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[u]=p)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function lu(e){let r=td(e),t=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${hr}/dist/install.global.js" data-config='${t}'></script>`}function cu(e,r){let t=r==null?void 0:r.hooks,n=vs(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${hr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${hr}/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&&Kn(o,"theme",e.theme," "),e.launcher&&Kn(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(...Cs(e," ")),o.push(...ws(e," ",t)),o.push(...Ss(e," ")),o.push(...As(e," ")),o.push(...la(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(`
189
- `)}function du(e,r){let t=r==null?void 0:r.hooks,n=td(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
185
+ }`;function iu(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 Cs(e){var r,t;return(t=(r=e.parserType)!=null?r:iu(e.streamParser))!=null?t:"plain"}function ws(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 Ss(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 As(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 Es(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,p])=>{typeof p=="string"?t.push(`${r} ${i}: "${p}",`):typeof p=="boolean"&&t.push(`${r} ${i}: ${p},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([p,c])=>{p!=="format"&&(typeof c=="string"?t.push(`${r} ${p}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${p}: ${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 da(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 td(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}: {`),td(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function Gn(e,r,t,n){t&&(e.push(`${n}${r}: {`),td(e,t,`${n} `),e.push(`${n}},`))}function nd(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:ou(t.hooks)}:void 0;return r==="esm"?lu(n,s):r==="script-installer"?pu(n):r==="script-advanced"?gu(n,s):r==="react-component"?cu(n,s):r==="react-advanced"?du(n,s):uu(n,s)}function lu(e,r){let t=r==null?void 0:r.hooks,n=Cs(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&&Gn(o,"theme",e.theme," "),e.launcher&&Gn(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(...ws(e," ")),o.push(...Ss(e," ",t)),o.push(...As(e," ")),o.push(...Es(e," ")),o.push(...da(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(`
186
+ `)}function cu(e,r){let t=r==null?void 0:r.hooks,n=Cs(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&&Gn(o,"theme",e.theme," "),e.launcher&&Gn(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(...ws(e," ")),o.push(...Ss(e," ",t)),o.push(...As(e," ")),o.push(...Es(e," ")),o.push(...da(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(`
187
+ `)}function du(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&&Gn(n,"theme",e.theme," "),e.launcher&&Gn(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(...ws(e," ")),n.push(...Ss(e," ",t)),n.push(...As(e," ")),n.push(...Es(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(${su}),`)),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(` ${Xc}`),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(` ${Xc}`),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(` ${Qc}`),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(` ${Qc}`),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(`
188
+ `)}function rd(e){var s;let r=Cs(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,p])=>{i!=="render"&&(typeof p=="string"||typeof p=="boolean")&&(a[i]=p)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,p])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof p=="object"&&p!==null)a.avatar=p;else if(i==="timestamp"&&typeof p=="object"&&p!==null){let c={};Object.entries(p).forEach(([u,d])=>{u!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[u]=d)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof p=="string"||typeof p=="boolean")&&(a[i]=p)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function pu(e){let r=rd(e),t=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${br}/dist/install.global.js" data-config='${t}'></script>`}function uu(e,r){let t=r==null?void 0:r.hooks,n=Cs(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${br}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${br}/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&&Gn(o,"theme",e.theme," "),e.launcher&&Gn(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(...ws(e," ")),o.push(...Ss(e," ",t)),o.push(...As(e," ")),o.push(...Es(e," ")),o.push(...da(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(`
189
+ `)}function gu(e,r){let t=r==null?void 0:r.hooks,n=rd(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
190
190
  `).map((a,i)=>i===0?a:" "+a).join(`
191
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${hr}/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(${ru});`),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(` ${Yc}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Yc}`),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(` ${Zc}`),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(` ${Zc}`),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(`
192
- `)}var nd={desktop:{w:1280,h:800},mobile:{w:390,h:844}},rd=.1,od=.15,sd=1.5,ca=24,ad=40,pu=`
191
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${br}/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(${au});`),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(` ${Zc}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Zc}`),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(` ${ed}`),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(` ${ed}`),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(`
192
+ `)}var od={desktop:{w:1280,h:800},mobile:{w:390,h:844}},sd=.1,ad=.15,id=1.5,pa=24,ld=40,mu=`
193
193
  /* \u2500\u2500 Root \u2500\u2500 */
194
194
  .persona-dc-root {
195
195
  display: flex;
@@ -340,7 +340,7 @@ ${a.join(`
340
340
  .persona-dc-stage {
341
341
  height: 550px;
342
342
  min-height: 400px;
343
- padding: ${ca}px;
343
+ padding: ${pa}px;
344
344
  overflow: auto;
345
345
  background: #f0f1f3;
346
346
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -430,5 +430,5 @@ ${a.join(`
430
430
  min-height: 300px;
431
431
  }
432
432
  }
433
- `;function uu(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=pu,document.head.appendChild(e)}function gu(e,r){let t=e.clientWidth-ca*2-ad,n=e.clientHeight-ca*2-ad;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function mu(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 id(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");uu();let u=Math.max(0,Math.min(n,t.length-1)),p=s,f=o,m=null,v=1,S=!1,b=h("div","persona-dc-root"),x=h("div","persona-dc-toolbar"),k=h("div","persona-dc-toolbar-lead"),_=h("div","persona-dc-toolbar-trail"),w=vt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>tt(-1)}),I=h("div");I.style.position="relative";let $=h("button","persona-dc-title-btn");$.type="button",$.setAttribute("aria-expanded","false"),$.setAttribute("aria-haspopup","listbox");let T=h("span","persona-dc-title-text"),V=h("span","persona-dc-title-chevron"),ue=he("chevron-down",12,"currentColor",2);ue&&V.appendChild(ue),$.append(T,V);let oe=h("div","persona-dc-dropdown");oe.setAttribute("role","listbox"),oe.style.display="none";let z=!1;function te(){oe.innerHTML="";for(let q=0;q<t.length;q++){let ce=t[q],ke=h("button","persona-dc-dropdown-item");ke.type="button",ke.setAttribute("role","option"),ke.setAttribute("aria-current",q===u?"true":"false");let Q=h("span");if(Q.textContent=ce.title,ke.appendChild(Q),ce.description){let K=h("span","persona-dc-dropdown-desc");K.textContent=ce.description,ke.appendChild(K)}ke.addEventListener("click",()=>{ie(),Te(q)}),oe.appendChild(ke)}}function Ae(){z=!z,oe.style.display=z?"":"none",$.setAttribute("aria-expanded",z?"true":"false"),z&&te()}function ie(){z&&(z=!1,oe.style.display="none",$.setAttribute("aria-expanded","false"))}$.addEventListener("click",q=>{q.stopPropagation(),Ae()});let Se=()=>ie();document.addEventListener("click",Se),I.append($,oe);let ae=vt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>tt(1)}),Y=h("span","persona-dc-counter");k.append(w,I,ae,Y);let ge=null;i&&(ge=ho({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:q=>{p=q,Ue.dataset.device=p,m=null,N()}}),_.appendChild(ge.element));let F=null;if(a){let q=h("div","persona-dc-zoom-controls"),ce=vt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let K=m!=null?m:v;m=Math.max(od,K-rd),N()}});F=h("span","persona-dc-zoom-level"),F.title="Reset to 100%",F.style.cursor="pointer",F.addEventListener("click",()=>{m=1,N()});let ke=vt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let K=m!=null?m:v;m=Math.min(sd,K+rd),N()}}),Q=vt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,N()}});q.append(ce,F,ke,Q),_.appendChild(q)}if(d){let q=h("div","persona-dc-separator");_.appendChild(q);let ce=ho({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ke=>{f=ke,Ue.dataset.colorScheme=f,mt()}});_.appendChild(ce.element)}let J=h("div","persona-dc-separator");_.appendChild(J);let me=vt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});_.appendChild(me),x.append(k,_);let at=h("div","persona-dc-stage"),Ue=h("div","persona-dc-iframe-wrapper");Ue.dataset.device=p,Ue.dataset.colorScheme=f;let Ke=h("iframe","persona-dc-iframe");Ke.setAttribute("sandbox","allow-scripts allow-same-origin"),Ke.setAttribute("loading","lazy"),Ke.title=t[u].title,Ue.appendChild(Ke),at.appendChild(Ue),b.append(x,at),e.appendChild(b);function mt(){var q;try{let ce=(q=Ke.contentDocument)==null?void 0:q.body;if(!ce)return;f==="dark"?ce.classList.add("theme-dark"):ce.classList.remove("theme-dark")}catch{}}Ke.addEventListener("load",()=>mt());function Re(){let q=t[u];T.textContent=q.title,Y.textContent=`${u+1} / ${t.length}`,Ke.title=q.title}function tt(q){let ce=((u+q)%t.length+t.length)%t.length;Te(ce)}function Te(q){q<0||q>=t.length||(u=q,Ke.src=t[u].url,Re(),c==null||c(u,t[u]))}function N(){var ke;if(S)return;let q=(ke=nd[p])!=null?ke:nd.desktop;v=gu(at,q);let ce=Math.max(od,Math.min(sd,m!=null?m:v));mu(Ue,Ke,q,ce,p),F&&(F.textContent=`${Math.round(ce*100)}%`)}let re=new ResizeObserver(()=>N());re.observe(at),Re(),Ke.src=t[u].url,requestAnimationFrame(()=>N());function ee(){S||(S=!0,re.disconnect(),document.removeEventListener("click",Se),b.remove())}return{element:b,goTo:Te,next:()=>tt(1),prev:()=>tt(-1),getIndex:()=>u,setDevice(q){p=q,Ue.dataset.device=q,ge==null||ge.setSelected(q),m=null,N()},setColorScheme(q){f=q,Ue.dataset.colorScheme=q},setZoom(q){m=q,N()},destroy:ee}}function ld(){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, #1d4ed8)"}}}function cd(){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 dd(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:Tn(e.colors.primary,.95),100:Tn(e.colors.primary,.9),200:Tn(e.colors.primary,.8),300:Tn(e.colors.primary,.7),400:Tn(e.colors.primary,.6),500:e.colors.primary,600:Tn(e.colors.primary,.8),700:Tn(e.colors.primary,.7),800:Tn(e.colors.primary,.6),900:Tn(e.colors.primary,.5),950:Tn(e.colors.primary,.45)}}),{...r,palette:t}}}}function pd(){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 Tn(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 gd(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var fu={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"}}},md={components:{panel:{borderRadius:"0",shadow:"none"}}},da={id:"shop",label:"Shopping Assistant",config:{theme:fu,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:"min(400px, calc(100vw - 24px))"},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?"]}},pa={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:md}},ua={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:md}},ga={shop:da,minimal:pa,fullscreen:ua};function fd(e){return ga[e]}var hu=na;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,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
+ `;function fu(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=mu,document.head.appendChild(e)}function hu(e,r){let t=e.clientWidth-pa*2-ld,n=e.clientHeight-pa*2-ld;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function yu(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 cd(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");fu();let u=Math.max(0,Math.min(n,t.length-1)),d=s,f=o,m=null,v=1,A=!1,b=h("div","persona-dc-root"),x=h("div","persona-dc-toolbar"),M=h("div","persona-dc-toolbar-lead"),F=h("div","persona-dc-toolbar-trail"),S=bt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>rt(-1)}),I=h("div");I.style.position="relative";let O=h("button","persona-dc-title-btn");O.type="button",O.setAttribute("aria-expanded","false"),O.setAttribute("aria-haspopup","listbox");let k=h("span","persona-dc-title-text"),V=h("span","persona-dc-title-chevron"),ge=fe("chevron-down",12,"currentColor",2);ge&&V.appendChild(ge),O.append(k,V);let ie=h("div","persona-dc-dropdown");ie.setAttribute("role","listbox"),ie.style.display="none";let _=!1;function ne(){ie.innerHTML="";for(let z=0;z<t.length;z++){let oe=t[z],Le=h("button","persona-dc-dropdown-item");Le.type="button",Le.setAttribute("role","option"),Le.setAttribute("aria-current",z===u?"true":"false");let Z=h("span");if(Z.textContent=oe.title,Le.appendChild(Z),oe.description){let J=h("span","persona-dc-dropdown-desc");J.textContent=oe.description,Le.appendChild(J)}Le.addEventListener("click",()=>{le(),Me(z)}),ie.appendChild(Le)}}function Te(){_=!_,ie.style.display=_?"":"none",O.setAttribute("aria-expanded",_?"true":"false"),_&&ne()}function le(){_&&(_=!1,ie.style.display="none",O.setAttribute("aria-expanded","false"))}O.addEventListener("click",z=>{z.stopPropagation(),Te()});let ke=()=>le();document.addEventListener("click",ke),I.append(O,ie);let de=bt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>rt(1)}),Y=h("span","persona-dc-counter");M.append(S,I,de,Y);let ce=null;i&&(ce=yo({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:z=>{d=z,Ke.dataset.device=d,m=null,D()}}),F.appendChild(ce.element));let q=null;if(a){let z=h("div","persona-dc-zoom-controls"),oe=bt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let J=m!=null?m:v;m=Math.max(ad,J-sd),D()}});q=h("span","persona-dc-zoom-level"),q.title="Reset to 100%",q.style.cursor="pointer",q.addEventListener("click",()=>{m=1,D()});let Le=bt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let J=m!=null?m:v;m=Math.min(id,J+sd),D()}}),Z=bt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,D()}});z.append(oe,q,Le,Z),F.appendChild(z)}if(p){let z=h("div","persona-dc-separator");F.appendChild(z);let oe=yo({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:Le=>{f=Le,Ke.dataset.colorScheme=f,mt()}});F.appendChild(oe.element)}let G=h("div","persona-dc-separator");F.appendChild(G);let ve=bt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});F.appendChild(ve),x.append(M,F);let xe=h("div","persona-dc-stage"),Ke=h("div","persona-dc-iframe-wrapper");Ke.dataset.device=d,Ke.dataset.colorScheme=f;let Xe=h("iframe","persona-dc-iframe");Xe.setAttribute("sandbox","allow-scripts allow-same-origin"),Xe.setAttribute("loading","lazy"),Xe.title=t[u].title,Ke.appendChild(Xe),xe.appendChild(Ke),b.append(x,xe),e.appendChild(b);function mt(){var z;try{let oe=(z=Xe.contentDocument)==null?void 0:z.body;if(!oe)return;f==="dark"?oe.classList.add("theme-dark"):oe.classList.remove("theme-dark")}catch{}}Xe.addEventListener("load",()=>mt());function Be(){let z=t[u];k.textContent=z.title,Y.textContent=`${u+1} / ${t.length}`,Xe.title=z.title}function rt(z){let oe=((u+z)%t.length+t.length)%t.length;Me(oe)}function Me(z){z<0||z>=t.length||(u=z,Xe.src=t[u].url,Be(),c==null||c(u,t[u]))}function D(){var Le;if(A)return;let z=(Le=od[d])!=null?Le:od.desktop;v=hu(xe,z);let oe=Math.max(ad,Math.min(id,m!=null?m:v));yu(Ke,Xe,z,oe,d),q&&(q.textContent=`${Math.round(oe*100)}%`)}let se=new ResizeObserver(()=>D());se.observe(xe),Be(),Xe.src=t[u].url,requestAnimationFrame(()=>D());function te(){A||(A=!0,se.disconnect(),document.removeEventListener("click",ke),b.remove())}return{element:b,goTo:Me,next:()=>rt(1),prev:()=>rt(-1),getIndex:()=>u,setDevice(z){d=z,Ke.dataset.device=z,ce==null||ce.setSelected(z),m=null,D()},setColorScheme(z){f=z,Ke.dataset.colorScheme=z},setZoom(z){m=z,D()},destroy:te}}function dd(){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, #1d4ed8)"}}}function pd(){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 ud(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:Tn(e.colors.primary,.95),100:Tn(e.colors.primary,.9),200:Tn(e.colors.primary,.8),300:Tn(e.colors.primary,.7),400:Tn(e.colors.primary,.6),500:e.colors.primary,600:Tn(e.colors.primary,.8),700:Tn(e.colors.primary,.7),800:Tn(e.colors.primary,.6),900:Tn(e.colors.primary,.5),950:Tn(e.colors.primary,.45)}}),{...r,palette:t}}}}function gd(){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 md(){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 Tn(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 fd(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var bu={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"}}},hd={components:{panel:{borderRadius:"0",shadow:"none"}}},ua={id:"shop",label:"Shopping Assistant",config:{theme:bu,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:"min(400px, calc(100vw - 24px))"},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?"]}},ga={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:hd}},ma={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:hd}},fa={shop:ua,minimal:ga,fullscreen:ma};function yd(e){return fa[e]}var xu=oa;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,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});
434
434
  //# sourceMappingURL=index.cjs.map