@runtypelabs/persona 3.27.0 → 3.29.0
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/codegen.cjs +80 -0
- package/dist/codegen.d.cts +152 -0
- package/dist/codegen.d.ts +152 -0
- package/dist/codegen.js +80 -0
- package/dist/index.cjs +35 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.global.js +20 -20
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +38 -38
- package/dist/index.js.map +1 -1
- package/package.json +8 -2
- package/src/codegen.test.ts +82 -0
- package/src/codegen.ts +20 -0
- package/src/utils/code-generators.ts +38 -9
package/dist/index.cjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
"use strict";var mg=Object.create;var Ba=Object.defineProperty;var gg=Object.getOwnPropertyDescriptor;var fg=Object.getOwnPropertyNames;var hg=Object.getPrototypeOf,yg=Object.prototype.hasOwnProperty;var bg=(e,n)=>{for(var t in n)Ba(e,t,{get:n[t],enumerable:!0})},zp=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of fg(n))!yg.call(e,s)&&s!==t&&Ba(e,s,{get:()=>n[s],enumerable:!(r=gg(n,s))||r.enumerable});return e};var Vp=(e,n,t)=>(t=e!=null?mg(hg(e)):{},zp(n||!e||!e.__esModule?Ba(t,"default",{value:e,enumerable:!0}):t,e)),xg=e=>zp(Ba({},"__esModule",{value:!0}),e);var Ey={};bg(Ey,{ASK_USER_QUESTION_TOOL_NAME:()=>bl,AgentWidgetClient:()=>Ro,AgentWidgetSession:()=>os,AttachmentManager:()=>No,DEFAULT_COMPONENTS:()=>el,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Za,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Xn,DEFAULT_PALETTE:()=>Yi,DEFAULT_SEMANTIC:()=>Zi,DEFAULT_WIDGET_CONFIG:()=>Nt,PRESETS:()=>Vl,PRESET_FULLSCREEN:()=>zl,PRESET_MINIMAL:()=>ql,PRESET_SHOP:()=>Ul,THEME_ZONES:()=>Cu,VERSION:()=>Uo,WEBMCP_TOOL_PREFIX:()=>_s,WebMcpBridge:()=>ts,accessibilityPlugin:()=>zm,animationsPlugin:()=>Vm,applyThemeVariables:()=>ao,attachHeaderToContainer:()=>Fo,brandPlugin:()=>Km,buildComposer:()=>cs,buildDefaultHeader:()=>ll,buildHeader:()=>_r,buildHeaderWithLayout:()=>ls,buildMinimalHeader:()=>cl,collectEnrichedPageContext:()=>jm,componentRegistry:()=>Ur,createActionManager:()=>ua,createAgentExperience:()=>Ni,createAskUserQuestionBubble:()=>om,createBestAvailableVoiceProvider:()=>Qa,createBubbleWithLayout:()=>Uu,createCSATFeedback:()=>Hi,createComboButton:()=>fi,createComponentMiddleware:()=>Cm,createComponentStreamParser:()=>Pi,createDefaultSanitizer:()=>Ji,createDemoCarousel:()=>ug,createDirectivePostprocessor:()=>Qp,createDropdownMenu:()=>po,createFlexibleJsonStreamParser:()=>ou,createIconButton:()=>jt,createImagePart:()=>pu,createJsonStreamParser:()=>Ua,createLabelButton:()=>oa,createLocalStorageAdapter:()=>Li,createMarkdownProcessor:()=>Os,createMarkdownProcessorFromConfig:()=>Po,createMessageActions:()=>gl,createNPSFeedback:()=>Bi,createPlainTextParser:()=>$a,createPlugin:()=>Xm,createRegexJsonParser:()=>ja,createStandardBubble:()=>ds,createTextPart:()=>qs,createTheme:()=>as,createThemeObserver:()=>ri,createToggleGroup:()=>sa,createTypingIndicator:()=>Oo,createVoiceProvider:()=>Do,createWidgetHostLayout:()=>ma,createXmlParser:()=>qa,default:()=>Zm,defaultActionHandlers:()=>jo,defaultJsonActionParser:()=>pa,defaultParseRules:()=>$l,detectColorScheme:()=>Js,directivePostprocessor:()=>Yp,ensureAskUserQuestionSheet:()=>fs,escapeHtml:()=>Io,extractComponentDirectiveFromMessage:()=>Ri,fileToImagePart:()=>uu,formatEnrichedContext:()=>Um,generateAssistantMessageId:()=>Ho,generateCodeSnippet:()=>sg,generateMessageId:()=>au,generateStableSelector:()=>jl,generateUserMessageId:()=>rs,getActiveTheme:()=>is,getColorScheme:()=>nl,getDisplayText:()=>lu,getHeaderLayout:()=>dl,getImageParts:()=>du,getPreset:()=>Ym,hasComponentDirective:()=>Wi,hasImages:()=>cu,headerLayouts:()=>hi,highContrastPlugin:()=>Gm,initAgentWidget:()=>Nl,isAskUserQuestionMessage:()=>$r,isComponentDirectiveType:()=>wm,isDockedMountMode:()=>rn,isVoiceSupported:()=>Vs,isWebMcpToolName:()=>$s,listRegisteredStreamAnimations:()=>Bu,markdownPostprocessor:()=>Ki,mergeWithDefaults:()=>ei,normalizeContent:()=>iu,parseAskUserQuestionPayload:()=>jr,pluginRegistry:()=>da,reducedMotionPlugin:()=>Jm,registerStreamAnimationPlugin:()=>Ru,removeAskUserQuestionSheet:()=>go,renderComponentDirective:()=>Ii,renderLoadingIndicatorWithFallback:()=>ml,renderLucideIcon:()=>be,resolveDockConfig:()=>ir,resolveSanitizer:()=>es,resolveTokens:()=>ti,stripWebMcpPrefix:()=>Gi,themeToCssVariables:()=>ni,unregisterStreamAnimationPlugin:()=>Hu,validateImageFile:()=>mu,validateTheme:()=>tl});module.exports=xg(Ey);var Jp=require("marked"),vg=e=>{if(e)return e},Os=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new Jp.Marked({gfm:(s=n==null?void 0:n.gfm)!=null?s:!0,breaks:(o=n==null?void 0:n.breaks)!=null?o:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=vg(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},Po=e=>e?Os({markedOptions:e.options,renderer:e.renderer}):Os(),wg=Os(),Ki=e=>wg(e),Io=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Gp=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Kp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Xp=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Kp(n.length);return n.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=Kp(n.length);return n.push({token:o,type:s}),o}),t},Qp=e=>{let n=Po(e);return t=>{let r=[],s=Xp(t,r),o=n(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Gp(i)}"></div>`;o=o.replace(d,p)}),o}},Yp=e=>{let n=[],t=Xp(e,n),r=Ki(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Gp(o)}"></div>`;r=r.replace(a,d)}),r};var Zp=Vp(require("dompurify"),1),Cg={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"]},Ag=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ji=()=>{let e=(0,Zp.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(n,t)=>{if(t.attrName==="src"||t.attrName==="href"){let r=t.attrValue;r.toLowerCase().startsWith("data:")&&!Ag.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,Cg)},es=e=>e===!1?null:typeof e=="function"?e:Ji();var _s="webmcp:",Da={warn(e,...n){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...n)}};function tu(e){if(e.length===0)return"0:empty";let n=e.map(t=>{var r,s;return[t.name,(r=t.description)!=null?r:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(s=t.origin)!=null?s:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${e.length}:${Sg(n.join(""))}`}function eu(e,n){let t=3735928559^n,r=1103547991^n;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);t=Math.imul(t^o,2654435761),r=Math.imul(r^o,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)}function Sg(e){let n=eu(e,0).toString(36),t=eu(e,2654435761).toString(36);return`${n}.${t}`}var ts=class{constructor(n){this.config=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=n.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(n){this.confirmHandler=n}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let n=this.getModelContext();if(!n)return[];let t;try{t=await n.getTools()}catch(s){return Da.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}let r=typeof location!="undefined"?location.origin:"";return t.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Eg(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(n,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return br("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let u=typeof document!="undefined"&&!!document.modelContext;return br(u?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=Gi(n),a;try{a=await s.getTools()}catch(u){let v=u instanceof Error?u.message:String(u);return br(`Failed to read WebMCP registry: ${v}`)}let i=a.find(u=>u.name===o);if(!i)return br(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return br(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let d={toolName:o,args:t,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return br("User declined the tool call.");if(r!=null&&r.aborted)return br("Aborted by cancel()");let l=new AbortController,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),g=()=>l.abort();r&&(r.aborted?l.abort():r.addEventListener("abort",g,{once:!0}));try{let u=await s.executeTool(i,Pg(t),{signal:l.signal});return Mg(u)}catch(u){if(p)return br(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let v=u instanceof Error?u.message:String(u);return br(v)}finally{clearTimeout(m),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(n){Da.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",n),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let n=document.modelContext;if(!n||typeof n!="object")return null;let t=n;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Da.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):n}async requestConfirm(n){var r;let t=(r=this.confirmHandler)!=null?r:kg;try{return await t(n)}catch(s){return Da.warn(`Confirm handler threw for WebMCP tool '${n.toolName}'; declining.`,s),!1}}passesClientAllowlist(n){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(r=>Tg(n,r))}},Gi=e=>e.startsWith(_s)?e.slice(_s.length):e,$s=e=>e.startsWith(_s),Tg=(e,n)=>{if(n==="*")return!0;let t=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)},Eg=e=>{if(!(e===void 0||e===""))try{let n=JSON.parse(e);return n!==null&&typeof n=="object"?n:void 0}catch{return}},Mg=e=>{if(e==null)return{content:[{type:"text",text:""}]};let n;try{n=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return n!==null&&typeof n=="object"&&Array.isArray(n.content)?n:{content:[{type:"text",text:typeof n=="string"?n:Ig(n)}]}},br=e=>({isError:!0,content:[{type:"text",text:e}]}),kg=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let n=Lg(e.args),t=`Allow the AI to call ${e.toolName}`+(n?`
|
|
1
|
+
"use strict";var gg=Object.create;var Da=Object.defineProperty;var fg=Object.getOwnPropertyDescriptor;var hg=Object.getOwnPropertyNames;var yg=Object.getPrototypeOf,bg=Object.prototype.hasOwnProperty;var xg=(e,t)=>{for(var n in t)Da(e,n,{get:t[n],enumerable:!0})},Vp=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of hg(t))!bg.call(e,s)&&s!==n&&Da(e,s,{get:()=>t[s],enumerable:!(r=fg(t,s))||r.enumerable});return e};var Kp=(e,t,n)=>(n=e!=null?gg(yg(e)):{},Vp(t||!e||!e.__esModule?Da(n,"default",{value:e,enumerable:!0}):n,e)),vg=e=>Vp(Da({},"__esModule",{value:!0}),e);var My={};xg(My,{ASK_USER_QUESTION_TOOL_NAME:()=>xl,AgentWidgetClient:()=>Ro,AgentWidgetSession:()=>os,AttachmentManager:()=>No,DEFAULT_COMPONENTS:()=>tl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ei,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Xn,DEFAULT_PALETTE:()=>Zi,DEFAULT_SEMANTIC:()=>el,DEFAULT_WIDGET_CONFIG:()=>Nt,PRESETS:()=>Kl,PRESET_FULLSCREEN:()=>Vl,PRESET_MINIMAL:()=>zl,PRESET_SHOP:()=>ql,THEME_ZONES:()=>Au,VERSION:()=>Uo,WEBMCP_TOOL_PREFIX:()=>$s,WebMcpBridge:()=>ts,accessibilityPlugin:()=>Vm,animationsPlugin:()=>Km,applyThemeVariables:()=>ao,attachHeaderToContainer:()=>Fo,brandPlugin:()=>Jm,buildComposer:()=>cs,buildDefaultHeader:()=>cl,buildHeader:()=>$r,buildHeaderWithLayout:()=>ls,buildMinimalHeader:()=>dl,collectEnrichedPageContext:()=>Um,componentRegistry:()=>Ur,createActionManager:()=>ua,createAgentExperience:()=>Fi,createAskUserQuestionBubble:()=>sm,createBestAvailableVoiceProvider:()=>Ya,createBubbleWithLayout:()=>qu,createCSATFeedback:()=>Bi,createComboButton:()=>hi,createComponentMiddleware:()=>Am,createComponentStreamParser:()=>Ii,createDefaultSanitizer:()=>Gi,createDemoCarousel:()=>mg,createDirectivePostprocessor:()=>Yp,createDropdownMenu:()=>po,createFlexibleJsonStreamParser:()=>su,createIconButton:()=>jt,createImagePart:()=>uu,createJsonStreamParser:()=>qa,createLabelButton:()=>oa,createLocalStorageAdapter:()=>Pi,createMarkdownProcessor:()=>Os,createMarkdownProcessorFromConfig:()=>Po,createMessageActions:()=>fl,createNPSFeedback:()=>Di,createPlainTextParser:()=>ja,createPlugin:()=>Qm,createRegexJsonParser:()=>Ua,createStandardBubble:()=>ds,createTextPart:()=>qs,createTheme:()=>as,createThemeObserver:()=>oi,createToggleGroup:()=>sa,createTypingIndicator:()=>Oo,createVoiceProvider:()=>Do,createWidgetHostLayout:()=>ma,createXmlParser:()=>za,default:()=>eg,defaultActionHandlers:()=>jo,defaultJsonActionParser:()=>pa,defaultParseRules:()=>jl,detectColorScheme:()=>Js,directivePostprocessor:()=>Zp,ensureAskUserQuestionSheet:()=>fs,escapeHtml:()=>Io,extractComponentDirectiveFromMessage:()=>Hi,fileToImagePart:()=>mu,formatEnrichedContext:()=>qm,generateAssistantMessageId:()=>Ho,generateCodeSnippet:()=>ag,generateMessageId:()=>iu,generateStableSelector:()=>Ul,generateUserMessageId:()=>rs,getActiveTheme:()=>is,getColorScheme:()=>rl,getDisplayText:()=>cu,getHeaderLayout:()=>pl,getImageParts:()=>pu,getPreset:()=>Zm,hasComponentDirective:()=>Ri,hasImages:()=>du,headerLayouts:()=>yi,highContrastPlugin:()=>Xm,initAgentWidget:()=>Fl,isAskUserQuestionMessage:()=>_r,isComponentDirectiveType:()=>Cm,isDockedMountMode:()=>rn,isVoiceSupported:()=>Vs,isWebMcpToolName:()=>_s,listRegisteredStreamAnimations:()=>Du,markdownPostprocessor:()=>Ji,mergeWithDefaults:()=>ti,normalizeContent:()=>lu,parseAskUserQuestionPayload:()=>jr,pluginRegistry:()=>da,reducedMotionPlugin:()=>Gm,registerStreamAnimationPlugin:()=>Hu,removeAskUserQuestionSheet:()=>go,renderComponentDirective:()=>Wi,renderLoadingIndicatorWithFallback:()=>gl,renderLucideIcon:()=>be,resolveDockConfig:()=>ir,resolveSanitizer:()=>es,resolveTokens:()=>ni,stripWebMcpPrefix:()=>Xi,themeToCssVariables:()=>ri,unregisterStreamAnimationPlugin:()=>Bu,validateImageFile:()=>gu,validateTheme:()=>nl});module.exports=vg(My);var Gp=require("marked"),wg=e=>{if(e)return e},Os=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new Gp.Marked({gfm:(s=t==null?void 0:t.gfm)!=null?s:!0,breaks:(o=t==null?void 0:t.breaks)!=null?o:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),r=wg(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},Po=e=>e?Os({markedOptions:e.options,renderer:e.renderer}):Os(),Cg=Os(),Ji=e=>Cg(e),Io=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Xp=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Jp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Qp=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Jp(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=Jp(t.length);return t.push({token:o,type:s}),o}),n},Yp=e=>{let t=Po(e);return n=>{let r=[],s=Qp(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Xp(i)}"></div>`;o=o.replace(d,p)}),o}},Zp=e=>{let t=[],n=Qp(e,t),r=Ji(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Xp(o)}"></div>`;r=r.replace(a,d)}),r};var eu=Kp(require("dompurify"),1),Ag={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"]},Sg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Gi=()=>{let e=(0,eu.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let r=n.attrValue;r.toLowerCase().startsWith("data:")&&!Sg.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Ag)},es=e=>e===!1?null:typeof e=="function"?e:Gi();var $s="webmcp:",Na={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function nu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Tg(t.join(""))}`}function tu(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Tg(e){let t=tu(e,0).toString(36),n=tu(e,2654435761).toString(36);return`${t}.${n}`}var ts=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return Na.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Mg(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return br("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let u=typeof document!="undefined"&&!!document.modelContext;return br(u?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=Xi(t),a;try{a=await s.getTools()}catch(u){let v=u instanceof Error?u.message:String(u);return br(`Failed to read WebMCP registry: ${v}`)}let i=a.find(u=>u.name===o);if(!i)return br(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return br(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let d={toolName:o,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return br("User declined the tool call.");if(r!=null&&r.aborted)return br("Aborted by cancel()");let l=new AbortController,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),g=()=>l.abort();r&&(r.aborted?l.abort():r.addEventListener("abort",g,{once:!0}));try{let u=await s.executeTool(i,Ig(n),{signal:l.signal});return kg(u)}catch(u){if(p)return br(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let v=u instanceof Error?u.message:String(u);return br(v)}finally{clearTimeout(m),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Na.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Na.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:Lg;try{return await n(t)}catch(s){return Na.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>Eg(t,r))}},Xi=e=>e.startsWith($s)?e.slice($s.length):e,_s=e=>e.startsWith($s),Eg=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Mg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},kg=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Wg(t)}]}},br=e=>({isError:!0,content:[{type:"text",text:e}]}),Lg=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Pg(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
2
2
|
|
|
3
3
|
Arguments:
|
|
4
|
-
${
|
|
4
|
+
${t}`:"")+(e.description?`
|
|
5
5
|
|
|
6
|
-
${e.description}`:"");return window.confirm(
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ns=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)}},
|
|
6
|
+
${e.description}`:"");return window.confirm(n)},Pg=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Ig=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Wg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Fr=require("partial-json"),Fa=e=>e.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ns=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)}},Rg=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},ru=e=>e.status==="complete"?Rg(e):e.status==="pending"?"Waiting":"",Hg=e=>{var s,o,a;let n=(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 n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var ou=e=>e.status==="complete"?Hg(e):"Using tool...",Oa=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Us=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Oa(t)},$a=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Oa(t)},Qi=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Us(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},_a=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&js(r,n.slice(o,a.index),[]),a[1]!==void 0?js(r,a[1],["bold"]):a[2]!==void 0?js(r,a[2],["italic"]):a[3]!==void 0&&js(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&js(r,n.slice(o),[]),r},js=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Bg=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
8
8
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Wo=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},$a=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ja=()=>{var n;let e=Hg();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Ua=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,Fr.parse)(t,Fr.STR|Fr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Na(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Na(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},ou=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Na(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Na(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:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=(0,Fr.parse)(o,Fr.STR|Fr.OBJ),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},qa=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var za=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Bg="https://api.runtype.com/v1/dispatch",Va="https://api.runtype.com";function Dg(e){var o,a;let n=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[n];if(r)return`attachment.${r}`;let s=n.indexOf("/");if(s>0){let i=(a=(o=n.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Qi=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 Ng(e){switch(e){case"json":return Ua;case"regex-json":return ja;case"xml":return qa;default:return $a}}var su=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Fg(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=su(t);if(!su(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=Wo(e);return Wo(n)!==null&&a===null?n:e}var Ro=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,s,o;this.apiUrl=(t=n.apiUrl)!=null?t:Bg,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Ng(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders,this.webMcpBridge=((o=n.webmcp)==null?void 0:o.enabled)===!0?new ts(n.webmcp):null}setSSEEventCallback(n){this.onSSEEvent=n}setWebMcpConfirmHandler(n){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(n)}isWebMcpOperational(){var n;return((n=this.webMcpBridge)==null?void 0:n.isOperational())===!0}executeWebMcpToolCall(n,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(n,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Va}/v1/client/${n}`}getClientSession(){return this.clientSession}async initSession(){var n,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 r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.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,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Va}/v1/client/feedback`}async sendFeedback(n){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(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});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(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let I=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:I}),I}let l=await this.buildPayload(n.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,m={sessionId:d.sessionId,messages:n.messages.filter(Qi).map(I=>{var R,w,W;return{id:I.id,role:I.role,content:(W=(w=(R=I.contentParts)!=null?R:I.llmContent)!=null?w:I.rawContent)!=null?W:I.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,u=!!(g&&g.length>0),v=u?tu(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,A=u&&x&&this.lastSentClientToolsFingerprint===v,E=!1,B=null,P;for(let I=0;;I++){let w={...m,...u&&(E||!A)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:r.signal}),P.status===409&&I===0&&u){let W=await P.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}B=W!=null?W:{error:"Chat request failed"}}break}if(!P.ok){let I=B!=null?B:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:w}),w}if(P.status===429){let w=new Error(I.hint||"Message limit reached for this session.");throw t({type:"error",error:w}),w}let R=new Error(I.error||"Failed to send message");throw t({type:"error",error:R}),R}if(!P.body){let I=new Error("No response body received");throw t({type:"error",error:I}),I}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(P.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.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:r.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:r.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(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.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:r.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:r.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,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Va}/v1/agents/${n.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:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Va}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:n,toolOutputs:t,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(n){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(Qi).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:n,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(n){var o;let r={messages:n.slice().filter(Qi).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:n,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=m,s(m),m},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.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(n,t,r){var cn,Bn,Yn,qe;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=F=>{let Se=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,De=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Ne=F.tools?F.tools.map(je=>({...je,chunks:je.chunks?[...je.chunks]:void 0})):void 0;return{...F,reasoning:Se,toolCall:De,tools:Ne}},m=F=>{if(F.role!=="assistant"||F.variant)return!0;let Se=Array.isArray(F.contentParts)&&F.contentParts.length>0,De=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||Se||De||!!F.stopReason},g=F=>{m(F)&&t({type:"message",message:p(F)})},u=null,v=null,x={current:null},A={current:null},E=!1,B=new Map,P=new Map,I=new Map,R=new Map,w={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},_=(F,Se,De="")=>`${F}::${Se}::${De}`,$=(F,Se)=>`${F}::${Se}::`,D=(F,Se,De,Ne)=>{let je=_(F,Se,De),pt=I.get(je);if(pt)return pt;let ot=De?`-${De}`:"",St={id:`nested-${F}-${Se}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Ne,parentToolId:F,parentStepId:Se}};return I.set(je,St),g(St),St},U=F=>{if(F==null)return null;try{return String(F)}catch{return null}},V=F=>{var Se,De,Ne,je,pt;return U((pt=(je=(Ne=(De=(Se=F.stepId)!=null?Se:F.step_id)!=null?De:F.step)!=null?Ne:F.parentId)!=null?je:F.flowStepId)!=null?pt:F.flow_step_id)},se=F=>{var Se,De,Ne,je,pt,ot,St;return U((St=(ot=(pt=(je=(Ne=(De=(Se=F.callId)!=null?Se:F.call_id)!=null?De:F.requestId)!=null?Ne:F.request_id)!=null?je:F.toolCallId)!=null?pt:F.tool_call_id)!=null?ot:F.stepId)!=null?St:F.step_id)},Re=r,Ue=!1,Fe=()=>{if(u)return u;let F;return!Ue&&Re?(F=Re,Ue=!0):Re&&A.current?F=`${Re}_${A.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(u),u},fe=(F,Se)=>{w.lastId=Se,F&&w.byStep.set(F,Se)},xe=(F,Se)=>{var pt;let De=(pt=F.reasoningId)!=null?pt:F.id,Ne=V(F);if(De){let ot=String(De);return fe(Ne,ot),ot}if(Ne){let ot=w.byStep.get(Ne);if(ot)return w.lastId=ot,ot}if(w.lastId&&!Se)return w.lastId;if(!Se)return null;let je=`reason-${l()}`;return fe(Ne,je),je},Pe=F=>{let Se=B.get(F);if(Se)return Se;let De={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return B.set(F,De),g(De),De},Be=(F,Se)=>{W.lastId=Se,F&&W.byCall.set(F,Se)},te=new Set,Ie=new Map,K=new Set,ce=new Map,we=F=>{if(!F)return!1;let Se=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return Se==="emit_artifact_markdown"||Se==="emit_artifact_component"},he=(F,Se)=>{var pt;let De=(pt=F.toolId)!=null?pt:F.id,Ne=se(F);if(De){let ot=String(De);return Be(Ne,ot),ot}if(Ne){let ot=W.byCall.get(Ne);if(ot)return W.lastId=ot,ot}if(W.lastId&&!Se)return W.lastId;if(!Se)return null;let je=`tool-${l()}`;return Be(Ne,je),je},Ce=F=>{let Se=P.get(F);if(Se)return Se;let De={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return P.set(F,De),g(De),De},Ve=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let Se=Number(F);if(!Number.isNaN(Se)&&Number.isFinite(Se))return Se;let De=Date.parse(F);if(!Number.isNaN(De))return De}return Date.now()},Y=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},ne=new Map,ae=new Map,me=new Map,le=new Map,oe=null,Ye=(F,Se,De)=>{var St;let Ne=me.get(F);Ne||(Ne=[],me.set(F,Ne));let je=0,pt=Ne.length;for(;je<pt;){let Ut=je+pt>>>1;Ne[Ut].seq<Se?je=Ut+1:pt=Ut}((St=Ne[je])==null?void 0:St.seq)===Se?Ne[je]={seq:Se,text:De}:Ne.splice(je,0,{seq:Se,text:De});let ot="";for(let Ut=0;Ut<Ne.length;Ut++)ot+=Ne[Ut].text;return ot},We=(F,Se)=>{let De=Y(Se),Ne=ae.get(F.id),je=Fg(Ne,De);F.rawContent=je;let pt=ne.get(F.id),ot=Ze=>{var re;let Ft=(re=F.content)!=null?re:"";Ze.trim()!==""&&(Ft.trim().length===0||Ze.startsWith(Ft)||Ze.trimStart().startsWith(Ft.trim()))&&(F.content=Ze)},St=()=>{var Ze;if(pt){let Ft=(Ze=pt.close)==null?void 0:Ze.call(pt);Ft instanceof Promise&&Ft.catch(()=>{})}ne.delete(F.id),ae.delete(F.id),F.streaming=!1,g(F)};if(!pt){ot(De),St();return}let Ut=Wo(je);if(Ut!==null&&Ut.trim()!==""){ot(Ut),St();return}let z=Ze=>{var ge;let Ft=typeof Ze=="string"?Ze:(ge=Ze==null?void 0:Ze.text)!=null?ge:null;if(Ft!==null&&Ft.trim()!=="")return Ft;let re=pt.getExtractedText();return re!==null&&re.trim()!==""?re:De},$t;try{$t=pt.processChunk(je)}catch{ot(De),St();return}if($t instanceof Promise){$t.then(Ze=>{ot(z(Ze)),St()}).catch(()=>{ot(De),St()});return}ot(z($t)),St()},de=[],X=!1,$e,Mt=()=>{X||(X=!0,queueMicrotask(()=>{X=!1,$e()}))},pe=new za((F,Se)=>{de.push({payloadType:F,payload:Se}),Mt()}),ie=null,kn=new Map,_t=(cn=this.config.iterationDisplay)!=null?cn:"separate";for($e=()=>{var F,Se,De,Ne,je,pt,ot,St,Ut,z,$t,Ze,Ft,re,ge,wt,qt,en,yn,Tt,Ct,ht,bt,Vt,nt,Dn,Zn,bn,Nn,mt,vr,Fn,yo,Ln,qo,zr,Mr,xt,On,_n,xn,Pt,er,tr,$n,Vr,kr,Kr,jn,Rt,vn,nr,Jr,Lr,Gr,wr,Un,dr,ft,Gt,Xt,qn,Xr,rr,pr,zn,T,Vn,ur,Pr,Cr,xs,mr,gr,fr,Ir,bo,ga,vs,fa,zo,gt,ws,or,Pn,ha,ya,Vo,Wr,ba,xo,Cs,Rr,As,Qr,Yr,xa,va,zi,vo,Zr,wa,Ss,eo,Ca,Ts,to,Es,Aa,Hr,Sa,no,Ht,Ko,Jo,Ms,Ar,Ta,ks,Ls,Ea,Go,Xo,wo,Ma,ka,Ps,Is,Ws,Rs,wn,Kn,Br,st,Hs,Co,hr,La;for(let ro=0;ro<de.length;ro++){let Ke=de[ro].payloadType,S=de[ro].payload;if(Ke==="reason_start"){let j=(F=xe(S,!0))!=null?F:`reason-${l()}`,L=Pe(j);L.reasoning=(Se=L.reasoning)!=null?Se:{id:j,status:"streaming",chunks:[]},L.reasoning.startedAt=(Ne=L.reasoning.startedAt)!=null?Ne:Ve((De=S.startedAt)!=null?De:S.timestamp),L.reasoning.completedAt=void 0,L.reasoning.durationMs=void 0,L.streaming=!0,L.reasoning.status="streaming",g(L)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let j=(pt=(je=xe(S,!1))!=null?je:xe(S,!0))!=null?pt:`reason-${l()}`,L=Pe(j);L.reasoning=(ot=L.reasoning)!=null?ot:{id:j,status:"streaming",chunks:[]},L.reasoning.startedAt=(Ut=L.reasoning.startedAt)!=null?Ut:Ve((St=S.startedAt)!=null?St:S.timestamp);let Z=(Ze=($t=(z=S.reasoningText)!=null?z:S.text)!=null?$t:S.delta)!=null?Ze:"";if(Z&&S.hidden!==!0){let J=typeof S.sequenceIndex=="number"?S.sequenceIndex:void 0;if(J!==void 0){let G=Ye(j,J,String(Z));L.reasoning.chunks=[G]}else L.reasoning.chunks.push(String(Z))}if(L.reasoning.status=S.done?"complete":"streaming",S.done){L.reasoning.completedAt=Ve((Ft=S.completedAt)!=null?Ft:S.timestamp);let J=(re=L.reasoning.startedAt)!=null?re:Date.now();L.reasoning.durationMs=Math.max(0,((ge=L.reasoning.completedAt)!=null?ge:Date.now())-J)}L.streaming=L.reasoning.status!=="complete",g(L)}else if(Ke==="reason_complete"){let j=(qt=(wt=xe(S,!1))!=null?wt:xe(S,!0))!=null?qt:`reason-${l()}`,L=B.get(j);if(L!=null&&L.reasoning){L.reasoning.status="complete",L.reasoning.completedAt=Ve((en=S.completedAt)!=null?en:S.timestamp);let J=(yn=L.reasoning.startedAt)!=null?yn:Date.now();L.reasoning.durationMs=Math.max(0,((Tt=L.reasoning.completedAt)!=null?Tt:Date.now())-J),L.streaming=!1,g(L)}let Z=V(S);Z&&w.byStep.delete(Z)}else if(Ke==="tool_start"){let j=(Ct=he(S,!0))!=null?Ct:`tool-${l()}`,L=(ht=S.toolName)!=null?ht:S.name;if(we(L)){te.add(j);continue}let Z=Ce(j),J=(bt=Z.toolCall)!=null?bt:{id:j,status:"pending"};J.name=L!=null?L:J.name,J.status="running",S.args!==void 0?J.args=S.args:S.parameters!==void 0&&(J.args=S.parameters),J.startedAt=(nt=J.startedAt)!=null?nt:Ve((Vt=S.startedAt)!=null?Vt:S.timestamp),J.completedAt=void 0,J.durationMs=void 0,Z.toolCall=J,Z.streaming=!0;let G=S.agentContext;(G||S.executionId)&&(Z.agentMetadata={executionId:(Dn=G==null?void 0:G.executionId)!=null?Dn:S.executionId,iteration:(Zn=G==null?void 0:G.iteration)!=null?Zn:S.iteration}),g(Z)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let j=(Nn=(bn=he(S,!1))!=null?bn:he(S,!0))!=null?Nn:`tool-${l()}`;if(te.has(j))continue;let L=Ce(j),Z=(mt=L.toolCall)!=null?mt:{id:j,status:"running"};Z.startedAt=(Fn=Z.startedAt)!=null?Fn:Ve((vr=S.startedAt)!=null?vr:S.timestamp);let J=(qo=(Ln=(yo=S.text)!=null?yo:S.delta)!=null?Ln:S.message)!=null?qo:"";J&&(Z.chunks=(zr=Z.chunks)!=null?zr:[],Z.chunks.push(String(J))),Z.status="running",L.toolCall=Z,L.streaming=!0;let G=S.agentContext;(G||S.executionId)&&(L.agentMetadata=(On=L.agentMetadata)!=null?On:{executionId:(Mr=G==null?void 0:G.executionId)!=null?Mr:S.executionId,iteration:(xt=G==null?void 0:G.iteration)!=null?xt:S.iteration}),g(L)}else if(Ke==="tool_complete"){let j=(xn=(_n=he(S,!1))!=null?_n:he(S,!0))!=null?xn:`tool-${l()}`;if(te.has(j)){te.delete(j);continue}let L=Ce(j),Z=(Pt=L.toolCall)!=null?Pt:{id:j,status:"running"};Z.status="complete",S.result!==void 0&&(Z.result=S.result),typeof S.duration=="number"&&(Z.duration=S.duration),Z.completedAt=Ve((er=S.completedAt)!=null?er:S.timestamp);let J=(tr=S.duration)!=null?tr:S.executionTime;if(typeof J=="number")Z.durationMs=J;else{let _e=($n=Z.startedAt)!=null?$n:Date.now();Z.durationMs=Math.max(0,((Vr=Z.completedAt)!=null?Vr:Date.now())-_e)}L.toolCall=Z,L.streaming=!1;let G=S.agentContext;(G||S.executionId)&&(L.agentMetadata=(jn=L.agentMetadata)!=null?jn:{executionId:(kr=G==null?void 0:G.executionId)!=null?kr:S.executionId,iteration:(Kr=G==null?void 0:G.iteration)!=null?Kr:S.iteration}),g(L);let Qe=se(S);Qe&&W.byCall.delete(Qe)}else if(Ke==="step_await"&&S.awaitReason==="local_tool_required"&&S.toolName){let j=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,L=(Rt=j!=null?j:S.toolId)!=null?Rt:`local-${l()}`,Z=Ce(L),J=(vn=Z.toolCall)!=null?vn:{id:L,status:"pending"};J.name=S.toolName,J.args=S.parameters,J.status="complete",J.chunks=(nr=J.chunks)!=null?nr:[],J.startedAt=(Lr=J.startedAt)!=null?Lr:Ve((Jr=S.startedAt)!=null?Jr:S.timestamp),J.completedAt=(Gr=J.completedAt)!=null?Gr:J.startedAt,Z.toolCall=J,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(Un=S.executionId)!=null?Un:(wr=Z.agentMetadata)==null?void 0:wr.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},g(Z)}else if(Ke==="text_start"){if((dr=S.toolContext)!=null&&dr.toolId)continue;let j=S.partId;if(j!==void 0&&A.current!==null&&j!==A.current){let L=u;L&&(L.streaming=!1,g(L),oe=L,u=null,E=!0)}j!==void 0&&(A.current=j)}else if(Ke==="text_end"){if((ft=S.toolContext)!=null&&ft.toolId)continue;let j=u;j&&(j.streaming=!1,g(j),oe=j,u=null,E=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let j=S.stepType,L=S.executionType;if(j==="tool"||L==="context")continue;let Z=S.toolContext;if(Z!=null&&Z.toolId){let _e=String((Xt=(Gt=S.id)!=null?Gt:Z.stepId)!=null?Xt:`step-${l()}`),tt=S.partId!==void 0&&S.partId!==null?String(S.partId):"",Me=`${Z.toolId}::${_e}`,Ge=R.get(Me);if(tt!==""&&Ge!==void 0&&Ge!==""&&Ge!==tt){let At=I.get(_(Z.toolId,_e,Ge));At&&At.streaming!==!1&&(At.streaming=!1,g(At))}tt!==""&&R.set(Me,tt);let It=D(Z.toolId,_e,tt,Z.executionId),on=(pr=(rr=(Xr=(qn=S.text)!=null?qn:S.delta)!=null?Xr:S.content)!=null?rr:S.chunk)!=null?pr:"";on&&(It.content+=String(on),It.streaming=!0,g(It)),S.isComplete&&(It.streaming=!1,g(It));continue}let J=S.partId;if(J!==void 0&&A.current!==null&&J!==A.current){let _e=u;_e&&(_e.streaming=!1,g(_e),oe=_e,u=null,E=!0)}J!==void 0&&(A.current=J);let G=J!==void 0&&(zn=le.get(J))!=null?zn:Fe();J!==void 0&&(G.partId||(G.partId=J),le.set(J,G));let Qe=(Pr=(ur=(Vn=(T=S.text)!=null?T:S.delta)!=null?Vn:S.content)!=null?ur:S.chunk)!=null?Pr:"";if(Qe){let _e=typeof S.seq=="number"?S.seq:void 0,tt=J!=null?J:G.id,Me=_e!==void 0?Ye(tt,_e,String(Qe)):((Cr=ae.get(G.id))!=null?Cr:"")+Qe;G.rawContent=Me,ne.has(G.id)||ne.set(G.id,this.createStreamParser());let Ge=ne.get(G.id),It=Me.trim().startsWith("{")||Me.trim().startsWith("[");if(It&&ae.set(G.id,Me),Ge.__isPlainTextParser===!0){G.content=_e!==void 0?Me:G.content+Qe,ae.delete(G.id),ne.delete(G.id),G.rawContent=void 0,g(G);continue}let At=Ge.processChunk(Me);if(At instanceof Promise)At.then(kt=>{var un;let sn=typeof kt=="string"?kt:(un=kt==null?void 0:kt.text)!=null?un:null;if(sn!==null&&sn.trim()!=="")G.content=sn,g(G);else if(!It&&!Me.trim().startsWith("<")){let Cn=u,Qt=Cn&&Cn.id===G.id?Cn:G;Qt.id===G.id&&(Qt.content=_e!==void 0?Me:Qt.content+Qe,ae.delete(Qt.id),ne.delete(Qt.id),Qt.rawContent=void 0,g(Qt))}}).catch(()=>{G.content=_e!==void 0?Me:G.content+Qe,ae.delete(G.id),ne.delete(G.id),G.rawContent=void 0,g(G)});else{let kt=typeof At=="string"?At:(xs=At==null?void 0:At.text)!=null?xs:null;kt!==null&&kt.trim()!==""?(G.content=kt,g(G)):!It&&!Me.trim().startsWith("<")&&(G.content=_e!==void 0?Me:G.content+Qe,ae.delete(G.id),ne.delete(G.id),G.rawContent=void 0,g(G))}}if(S.isComplete){let _e=(gr=(mr=S.result)==null?void 0:mr.response)!=null?gr:G.content;if(_e){let tt=ae.get(G.id),Me=tt!=null?tt:Y(_e);G.rawContent=Me;let Ge=ne.get(G.id),It=null,on=!1;if(Ge&&(It=Ge.getExtractedText(),It===null&&(It=Wo(Me)),It===null)){let At=Ge.processChunk(Me);At instanceof Promise?(on=!0,At.then(kt=>{var un;let sn=typeof kt=="string"?kt:(un=kt==null?void 0:kt.text)!=null?un:null;if(sn!==null){let Cn=u;Cn&&Cn.id===G.id&&(Cn.content=sn,Cn.streaming=!1,ne.delete(Cn.id),ae.delete(Cn.id),g(Cn))}})):It=typeof At=="string"?At:(fr=At==null?void 0:At.text)!=null?fr:null}if(!on){It!==null&&It.trim()!==""?G.content=It:ae.has(G.id)||(G.content=Y(_e));let At=ne.get(G.id);if(At){let kt=(Ir=At.close)==null?void 0:Ir.call(At);kt instanceof Promise&&kt.catch(()=>{}),ne.delete(G.id)}ae.delete(G.id),G.streaming=!1,g(G)}}}}else if(Ke==="step_complete"){let j=S.stepType,L=S.executionType;if(j==="tool"||L==="context")continue;let Z=S.toolContext;if(Z!=null&&Z.toolId){let _e=String((ga=(bo=S.id)!=null?bo:Z.stepId)!=null?ga:"");if(_e){let tt=$(Z.toolId,_e);for(let[Me,Ge]of I)Me.startsWith(tt)&&Ge.streaming!==!1&&(Ge.streaming=!1,g(Ge));R.delete(`${Z.toolId}::${_e}`)}continue}let J=S.stopReason;if(E){if(u!==null){let Me=u;J&&(Me.stopReason=J),ne.delete(Me.id),ae.delete(Me.id),Me.streaming!==!1&&(Me.streaming=!1,g(Me))}let _e=(vs=S.result)==null?void 0:vs.response,tt=oe;tt&&(J&&(tt.stopReason=J),_e!=null?We(tt,_e):(ne.delete(tt.id),ae.delete(tt.id))),oe=null;continue}let G=(fa=S.result)==null?void 0:fa.response,Qe=Fe();if(J&&(Qe.stopReason=J),G!=null){let _e=ne.get(Qe.id),tt=!1,Me=!1;if(_e){let Ge=_e.getExtractedText(),It=ae.get(Qe.id),on=It!=null?It:Y(G);if(Qe.rawContent=on,Ge!==null&&Ge.trim()!=="")Qe.content=Ge,tt=!0;else{let At=Wo(on);if(At!==null)Qe.content=At,tt=!0;else{let kt=_e.processChunk(on);if(kt instanceof Promise)Me=!0,kt.then(sn=>{var Cn;let un=typeof sn=="string"?sn:(Cn=sn==null?void 0:sn.text)!=null?Cn:null;if(un!==null&&un.trim()!==""){let Qt=u;Qt&&Qt.id===Qe.id&&(Qt.content=un,Qt.streaming=!1,ne.delete(Qt.id),ae.delete(Qt.id),g(Qt))}else{let Qt=_e.getExtractedText(),sr=u;sr&&sr.id===Qe.id&&(Qt!==null&&Qt.trim()!==""?sr.content=Qt:ae.has(sr.id)||(sr.content=Y(G)),sr.streaming=!1,ne.delete(sr.id),ae.delete(sr.id),g(sr))}});else{let sn=typeof kt=="string"?kt:(zo=kt==null?void 0:kt.text)!=null?zo:null;if(sn!==null&&sn.trim()!=="")Qe.content=sn,tt=!0;else{let un=_e.getExtractedText();un!==null&&un.trim()!==""&&(Qe.content=un,tt=!0)}}}}}if(!Me){if(!Qe.rawContent){let Ge=ae.get(Qe.id);Qe.rawContent=Ge!=null?Ge:Y(G)}if(!tt&&!ae.has(Qe.id)&&(Qe.content=Y(G)),_e){let Ge=(gt=_e.close)==null?void 0:gt.call(_e);Ge instanceof Promise&&Ge.catch(()=>{})}ne.delete(Qe.id),ae.delete(Qe.id),Qe.streaming=!1,g(Qe)}}else ne.delete(Qe.id),ae.delete(Qe.id),Qe.streaming=!1,g(Qe)}else if(Ke==="flow_complete"){let j=(ws=S.result)==null?void 0:ws.response;if(E){if(u!==null){let L=u;ne.delete(L.id),ae.delete(L.id),L.streaming!==!1&&(L.streaming=!1,g(L))}}else if(j!=null){let L=Fe(),Z=ae.get(L.id),J=Z!=null?Z:Y(j);L.rawContent=J;let G=Y(j),Qe=ne.get(L.id);if(Qe){let Me=Wo(J);if(Me!==null)G=Me;else{let Ge=Qe.processChunk(J);Ge instanceof Promise&&Ge.then(on=>{var kt;let At=typeof on=="string"?on:(kt=on==null?void 0:on.text)!=null?kt:null;At!==null&&(L.content=At,L.streaming=!1,g(L))});let It=Qe.getExtractedText();It!==null&&(G=It)}}ne.delete(L.id),ae.delete(L.id);let _e=G!==L.content,tt=L.streaming!==!1;_e&&(L.content=G),L.streaming=!1,(_e||tt)&&g(L)}else if(u!==null){let L=u;ne.delete(L.id),ae.delete(L.id),L.streaming!==!1&&(L.streaming=!1,g(L))}t({type:"status",status:"idle"})}else if(Ke==="agent_start")ie={executionId:S.executionId,agentId:(or=S.agentId)!=null?or:"virtual",agentName:(Pn=S.agentName)!=null?Pn:"",status:"running",currentIteration:0,maxTurns:(ha=S.maxTurns)!=null?ha:1,startedAt:Ve(S.startedAt)};else if(Ke==="agent_iteration_start"){if(ie&&(ie.currentIteration=S.iteration),_t==="separate"&&S.iteration>1){let j=u;j&&(j.streaming=!1,g(j),kn.set(S.iteration-1,j),u=null)}}else if(Ke==="agent_turn_start")v=null;else if(Ke==="agent_turn_delta"){if(S.contentType==="text"){let j=Fe();j.content+=(ya=S.delta)!=null?ya:"",j.agentMetadata={executionId:S.executionId,iteration:S.iteration,turnId:S.turnId,agentName:ie==null?void 0:ie.agentName},v=j,g(j)}else if(S.contentType==="thinking"){let j=(Vo=S.turnId)!=null?Vo:`agent-think-${S.iteration}`,L=Pe(j);L.reasoning=(Wr=L.reasoning)!=null?Wr:{id:j,status:"streaming",chunks:[]},L.reasoning.chunks.push((ba=S.delta)!=null?ba:""),L.agentMetadata={executionId:S.executionId,iteration:S.iteration,turnId:S.turnId},g(L)}else if(S.contentType==="tool_input"){let j=(xo=S.toolCallId)!=null?xo:W.lastId;if(j){let L=P.get(j);L!=null&&L.toolCall&&(L.toolCall.chunks=(Cs=L.toolCall.chunks)!=null?Cs:[],L.toolCall.chunks.push((Rr=S.delta)!=null?Rr:""),g(L))}}}else if(Ke==="agent_turn_complete"){let j=S.turnId;if(j){let J=B.get(j);if(J!=null&&J.reasoning){J.reasoning.status="complete",J.reasoning.completedAt=Ve(S.completedAt);let G=(As=J.reasoning.startedAt)!=null?As:Date.now();J.reasoning.durationMs=Math.max(0,((Qr=J.reasoning.completedAt)!=null?Qr:Date.now())-G),J.streaming=!1,g(J)}}let L=S.stopReason,Z=u!=null?u:v;if(L&&Z!==null){let J=S.turnId;(!J||((Yr=Z.agentMetadata)==null?void 0:Yr.turnId)===J)&&(Z.stopReason=L,g(Z))}}else if(Ke==="agent_tool_start"){u&&(u.streaming=!1,g(u),u=null);let j=(xa=S.toolCallId)!=null?xa:`agent-tool-${l()}`;Be(se(S),j);let L=Ce(j),Z=(va=L.toolCall)!=null?va:{id:j,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};Z.name=(vo=(zi=S.toolName)!=null?zi:S.name)!=null?vo:Z.name,Z.status="running",S.parameters!==void 0&&(Z.args=S.parameters),Z.startedAt=Ve((Zr=S.startedAt)!=null?Zr:S.timestamp),L.toolCall=Z,L.streaming=!0,L.agentMetadata={executionId:S.executionId,iteration:S.iteration},g(L)}else if(Ke==="agent_tool_delta"){let j=(wa=S.toolCallId)!=null?wa:W.lastId;if(j){let L=(Ss=P.get(j))!=null?Ss:Ce(j);L.toolCall&&(L.toolCall.chunks=(eo=L.toolCall.chunks)!=null?eo:[],L.toolCall.chunks.push((Ca=S.delta)!=null?Ca:""),L.toolCall.status="running",L.streaming=!0,g(L))}}else if(Ke==="agent_tool_complete"){let j=(Ts=S.toolCallId)!=null?Ts:W.lastId;if(j){let L=(to=P.get(j))!=null?to:Ce(j);if(L.toolCall){L.toolCall.status="complete",S.result!==void 0&&(L.toolCall.result=S.result),typeof S.executionTime=="number"&&(L.toolCall.durationMs=S.executionTime),L.toolCall.completedAt=Ve((Es=S.completedAt)!=null?Es:S.timestamp),L.streaming=!1,g(L);let Z=se(S);Z&&W.byCall.delete(Z)}}}else if(Ke==="agent_media"){let j=Array.isArray(S.media)?S.media:[],L=[];for(let Z of j){if(!Z||typeof Z!="object")continue;let J=Z,G=typeof J.type=="string"?J.type:void 0,Qe=typeof J.mediaType=="string"?J.mediaType.toLowerCase():"",_e=null,tt="";if(G==="media"){let Me=typeof J.data=="string"?J.data:void 0;if(!Me)continue;tt=Qe.length>0?Qe:"application/octet-stream",_e=`data:${tt};base64,${Me}`}else if(G==="image-url"){let Me=typeof J.url=="string"?J.url:void 0;if(!Me)continue;tt=Qe,_e=Me}else if(G==="file-url"){let Me=typeof J.url=="string"?J.url:void 0;if(!Me)continue;tt=Qe,_e=Me}else continue;if(_e)if(G==="image-url"||tt.startsWith("image/"))L.push({type:"image",image:_e,...tt?{mimeType:tt}:{}});else if(tt.startsWith("audio/"))L.push({type:"audio",audio:_e,mimeType:tt});else if(tt.startsWith("video/"))L.push({type:"video",video:_e,mimeType:tt});else{let Me=tt||"application/octet-stream";L.push({type:"file",data:_e,mimeType:Me,filename:Dg(Me)})}}if(L.length>0){let Z=l(),J=S.toolCallId,Qe={id:`agent-media-${typeof J=="string"&&J.length>0?`${J}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:L,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:S.executionId,iteration:S.iteration}};g(Qe);let _e=u;_e&&(_e.streaming=!1,g(_e)),u=null,x.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let j=`agent-reflection-${S.executionId}-${S.iteration}`,L={id:j,role:"assistant",content:(Aa=S.reflection)!=null?Aa:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(Hr=S.reflection)!=null?Hr:""]},agentMetadata:{executionId:S.executionId,iteration:S.iteration}};g(L)}else if(Ke==="agent_complete"){ie&&(ie.status=S.success?"complete":"error",ie.completedAt=Ve(S.completedAt),ie.stopReason=S.stopReason);let j=u;j&&(j.streaming=!1,g(j)),t({type:"status",status:"idle"})}else if(Ke==="agent_error"){let j=typeof S.error=="string"?S.error:(no=(Sa=S.error)==null?void 0:Sa.message)!=null?no:"Agent execution error";S.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):t({type:"error",error:new Error(j)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let j=(Ht=S.approvalId)!=null?Ht:`approval-${l()}`,L={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Ko=ie==null?void 0:ie.agentId)!=null?Ko:"virtual",executionId:(Ms=(Jo=S.executionId)!=null?Jo:ie==null?void 0:ie.executionId)!=null?Ms:"",toolName:(Ar=S.toolName)!=null?Ar:"",toolType:S.toolType,description:(ks=S.description)!=null?ks:`Execute ${(Ta=S.toolName)!=null?Ta:"tool"}`,parameters:S.parameters}};g(L)}else if(Ke==="step_await"&&S.awaitReason==="approval_required"){let j=(Ls=S.approvalId)!=null?Ls:`approval-${l()}`,L={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Ea=ie==null?void 0:ie.agentId)!=null?Ea:"virtual",executionId:(Xo=(Go=S.executionId)!=null?Go:ie==null?void 0:ie.executionId)!=null?Xo:"",toolName:(wo=S.toolName)!=null?wo:"",toolType:S.toolType,description:(ka=S.description)!=null?ka:`Execute ${(Ma=S.toolName)!=null?Ma:"tool"}`,parameters:S.parameters}};g(L)}else if(Ke==="agent_approval_complete"){let j=S.approvalId;if(j){let Z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(Ps=S.decision)!=null?Ps:"approved",agentId:(Is=ie==null?void 0:ie.agentId)!=null?Is:"virtual",executionId:(Rs=(Ws=S.executionId)!=null?Ws:ie==null?void 0:ie.executionId)!=null?Rs:"",toolName:(wn=S.toolName)!=null?wn:"",description:(Kn=S.description)!=null?Kn:"",resolvedAt:Date.now()}};g(Z)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let j=S.artifactType,L=String(S.id),Z=typeof S.title=="string"?S.title:void 0;if(t({type:"artifact_start",id:L,artifactType:j,title:Z,component:typeof S.component=="string"?S.component:void 0}),ce.set(L,{markdown:"",title:Z}),!K.has(L)){K.add(L);let J={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:L,title:Z,artifactType:j,status:"streaming"}})};Ie.set(L,J),g(J)}}else if(Ke==="artifact_delta"){let j=String(S.id),L=typeof S.delta=="string"?S.delta:String((Br=S.delta)!=null?Br:"");t({type:"artifact_delta",id:j,artDelta:L});let Z=ce.get(j);Z&&(Z.markdown+=L)}else if(Ke==="artifact_update"){let j=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};t({type:"artifact_update",id:String(S.id),props:j,component:typeof S.component=="string"?S.component:void 0})}else if(Ke==="artifact_complete"){let j=String(S.id);t({type:"artifact_complete",id:j});let L=Ie.get(j);if(L){L.streaming=!1;try{let Z=JSON.parse((st=L.rawContent)!=null?st:"{}");if(Z.props){Z.props.status="complete";let J=ce.get(j);J!=null&&J.markdown&&(Z.props.markdown=J.markdown)}L.rawContent=JSON.stringify(Z)}catch{}ce.delete(j),g(L),Ie.delete(j)}}}else if(Ke==="transcript_insert"){let j=S.message;if(!j||typeof j!="object")continue;let L=String((Hs=j.id)!=null?Hs:`msg-${l()}`),Z=j.role,G={id:L,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(g(G),G.rawContent)try{let Qe=JSON.parse(G.rawContent),_e=(Co=Qe==null?void 0:Qe.props)==null?void 0:Co.artifactId;typeof _e=="string"&&K.add(_e)}catch{}u=null,x.current=null,ne.delete(L),ae.delete(L)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let j=null;if(S.error instanceof Error)j=S.error;else if(Ke==="dispatch_error"){let L=(hr=S.message)!=null?hr:S.error;L!=null&&L!==""&&(j=new Error(String(L)))}else if(Ke==="step_error"||Ke==="flow_error"){let L=S.error;typeof L=="string"&&L!==""?j=new Error(L):L!=null&&typeof L=="object"&&"message"in L&&(j=new Error(String((La=L.message)!=null?La:L)))}else Ke==="error"&&S.error!=null&&S.error!==""&&(j=new Error(String(S.error)));if(j){t({type:"error",error:j});let L=u;L&&L.streaming&&(L.streaming=!1,g(L)),t({type:"status",status:"idle"})}}}}}de.length=0};;){let{done:F,value:Se}=await s.read();if(F)break;a+=o.decode(Se,{stream:!0});let De=a.split(`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Wo=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ja=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ua=()=>{var t;let e=Bg();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},qa=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=(0,Fr.parse)(n,Fr.STR|Fr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Fa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Fa(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},su=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Fa(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Fa(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:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=(0,Fr.parse)(o,Fr.STR|Fr.OBJ),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},za=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Va=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Dg="https://api.runtype.com/v1/dispatch",Ka="https://api.runtype.com";function Ng(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Yi=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 Fg(e){switch(e){case"json":return qa;case"regex-json":return Ua;case"xml":return za;default:return ja}}var au=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Og(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=au(n);if(!au(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=Wo(e);return Wo(t)!==null&&a===null?t:e}var Ro=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Dg,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Fg(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new ts(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;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 r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.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,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});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(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let I=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:I}),I}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(Yi).map(I=>{var R,w,W;return{id:I.id,role:I.role,content:(W=(w=(R=I.contentParts)!=null?R:I.llmContent)!=null?w:I.rawContent)!=null?W:I.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,u=!!(g&&g.length>0),v=u?nu(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,A=u&&x&&this.lastSentClientToolsFingerprint===v,E=!1,B=null,P;for(let I=0;;I++){let w={...m,...u&&(E||!A)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:r.signal}),P.status===409&&I===0&&u){let W=await P.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}B=W!=null?W:{error:"Chat request failed"}}break}if(!P.ok){let I=B!=null?B:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:w}),w}if(P.status===429){let w=new Error(I.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let R=new Error(I.error||"Failed to send message");throw n({type:"error",error:R}),R}if(!P.body){let I=new Error("No response body received");throw n({type:"error",error:I}),I}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(P.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.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:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.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:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/agents/${t.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:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ka}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Yi).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(t){var o;let r={messages:t.slice().filter(Yi).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=m,s(m),m},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var cn,Bn,Yn,qe;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=F=>{let Se=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,De=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Ne=F.tools?F.tools.map(je=>({...je,chunks:je.chunks?[...je.chunks]:void 0})):void 0;return{...F,reasoning:Se,toolCall:De,tools:Ne}},m=F=>{if(F.role!=="assistant"||F.variant)return!0;let Se=Array.isArray(F.contentParts)&&F.contentParts.length>0,De=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||Se||De||!!F.stopReason},g=F=>{m(F)&&n({type:"message",message:p(F)})},u=null,v=null,x={current:null},A={current:null},E=!1,B=new Map,P=new Map,I=new Map,R=new Map,w={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},$=(F,Se,De="")=>`${F}::${Se}::${De}`,_=(F,Se)=>`${F}::${Se}::`,D=(F,Se,De,Ne)=>{let je=$(F,Se,De),pt=I.get(je);if(pt)return pt;let ot=De?`-${De}`:"",St={id:`nested-${F}-${Se}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Ne,parentToolId:F,parentStepId:Se}};return I.set(je,St),g(St),St},U=F=>{if(F==null)return null;try{return String(F)}catch{return null}},V=F=>{var Se,De,Ne,je,pt;return U((pt=(je=(Ne=(De=(Se=F.stepId)!=null?Se:F.step_id)!=null?De:F.step)!=null?Ne:F.parentId)!=null?je:F.flowStepId)!=null?pt:F.flow_step_id)},se=F=>{var Se,De,Ne,je,pt,ot,St;return U((St=(ot=(pt=(je=(Ne=(De=(Se=F.callId)!=null?Se:F.call_id)!=null?De:F.requestId)!=null?Ne:F.request_id)!=null?je:F.toolCallId)!=null?pt:F.tool_call_id)!=null?ot:F.stepId)!=null?St:F.step_id)},Re=r,Ue=!1,Fe=()=>{if(u)return u;let F;return!Ue&&Re?(F=Re,Ue=!0):Re&&A.current?F=`${Re}_${A.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(u),u},fe=(F,Se)=>{w.lastId=Se,F&&w.byStep.set(F,Se)},xe=(F,Se)=>{var pt;let De=(pt=F.reasoningId)!=null?pt:F.id,Ne=V(F);if(De){let ot=String(De);return fe(Ne,ot),ot}if(Ne){let ot=w.byStep.get(Ne);if(ot)return w.lastId=ot,ot}if(w.lastId&&!Se)return w.lastId;if(!Se)return null;let je=`reason-${l()}`;return fe(Ne,je),je},Pe=F=>{let Se=B.get(F);if(Se)return Se;let De={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return B.set(F,De),g(De),De},Be=(F,Se)=>{W.lastId=Se,F&&W.byCall.set(F,Se)},te=new Set,Ie=new Map,K=new Set,ce=new Map,we=F=>{if(!F)return!1;let Se=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return Se==="emit_artifact_markdown"||Se==="emit_artifact_component"},he=(F,Se)=>{var pt;let De=(pt=F.toolId)!=null?pt:F.id,Ne=se(F);if(De){let ot=String(De);return Be(Ne,ot),ot}if(Ne){let ot=W.byCall.get(Ne);if(ot)return W.lastId=ot,ot}if(W.lastId&&!Se)return W.lastId;if(!Se)return null;let je=`tool-${l()}`;return Be(Ne,je),je},Ce=F=>{let Se=P.get(F);if(Se)return Se;let De={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return P.set(F,De),g(De),De},Ve=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let Se=Number(F);if(!Number.isNaN(Se)&&Number.isFinite(Se))return Se;let De=Date.parse(F);if(!Number.isNaN(De))return De}return Date.now()},Y=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},ne=new Map,ae=new Map,me=new Map,le=new Map,oe=null,Ye=(F,Se,De)=>{var St;let Ne=me.get(F);Ne||(Ne=[],me.set(F,Ne));let je=0,pt=Ne.length;for(;je<pt;){let Ut=je+pt>>>1;Ne[Ut].seq<Se?je=Ut+1:pt=Ut}((St=Ne[je])==null?void 0:St.seq)===Se?Ne[je]={seq:Se,text:De}:Ne.splice(je,0,{seq:Se,text:De});let ot="";for(let Ut=0;Ut<Ne.length;Ut++)ot+=Ne[Ut].text;return ot},We=(F,Se)=>{let De=Y(Se),Ne=ae.get(F.id),je=Og(Ne,De);F.rawContent=je;let pt=ne.get(F.id),ot=Ze=>{var re;let Ft=(re=F.content)!=null?re:"";Ze.trim()!==""&&(Ft.trim().length===0||Ze.startsWith(Ft)||Ze.trimStart().startsWith(Ft.trim()))&&(F.content=Ze)},St=()=>{var Ze;if(pt){let Ft=(Ze=pt.close)==null?void 0:Ze.call(pt);Ft instanceof Promise&&Ft.catch(()=>{})}ne.delete(F.id),ae.delete(F.id),F.streaming=!1,g(F)};if(!pt){ot(De),St();return}let Ut=Wo(je);if(Ut!==null&&Ut.trim()!==""){ot(Ut),St();return}let z=Ze=>{var ge;let Ft=typeof Ze=="string"?Ze:(ge=Ze==null?void 0:Ze.text)!=null?ge:null;if(Ft!==null&&Ft.trim()!=="")return Ft;let re=pt.getExtractedText();return re!==null&&re.trim()!==""?re:De},_t;try{_t=pt.processChunk(je)}catch{ot(De),St();return}if(_t instanceof Promise){_t.then(Ze=>{ot(z(Ze)),St()}).catch(()=>{ot(De),St()});return}ot(z(_t)),St()},de=[],X=!1,_e,Mt=()=>{X||(X=!0,queueMicrotask(()=>{X=!1,_e()}))},pe=new Va((F,Se)=>{de.push({payloadType:F,payload:Se}),Mt()}),ie=null,kn=new Map,$t=(cn=this.config.iterationDisplay)!=null?cn:"separate";for(_e=()=>{var F,Se,De,Ne,je,pt,ot,St,Ut,z,_t,Ze,Ft,re,ge,wt,qt,en,yn,Tt,Ct,ht,bt,Vt,nt,Dn,Zn,bn,Nn,mt,vr,Fn,yo,Ln,qo,zr,Mr,xt,On,$n,xn,Pt,er,tr,_n,Vr,kr,Kr,jn,Rt,vn,nr,Jr,Lr,Gr,wr,Un,dr,ft,Gt,Xt,qn,Xr,rr,pr,zn,T,Vn,ur,Pr,Cr,xs,mr,gr,fr,Ir,bo,fa,vs,ha,zo,gt,ws,or,Pn,ya,ba,Vo,Wr,xa,xo,Cs,Rr,As,Qr,Yr,va,wa,Vi,vo,Zr,Ca,Ss,eo,Aa,Ts,to,Es,Sa,Hr,Ta,no,Ht,Ko,Jo,Ms,Ar,Ea,ks,Ls,Ma,Go,Xo,wo,ka,La,Ps,Is,Ws,Rs,wn,Kn,Br,st,Hs,Co,hr,Pa;for(let ro=0;ro<de.length;ro++){let Ke=de[ro].payloadType,S=de[ro].payload;if(Ke==="reason_start"){let j=(F=xe(S,!0))!=null?F:`reason-${l()}`,L=Pe(j);L.reasoning=(Se=L.reasoning)!=null?Se:{id:j,status:"streaming",chunks:[]},L.reasoning.startedAt=(Ne=L.reasoning.startedAt)!=null?Ne:Ve((De=S.startedAt)!=null?De:S.timestamp),L.reasoning.completedAt=void 0,L.reasoning.durationMs=void 0,L.streaming=!0,L.reasoning.status="streaming",g(L)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let j=(pt=(je=xe(S,!1))!=null?je:xe(S,!0))!=null?pt:`reason-${l()}`,L=Pe(j);L.reasoning=(ot=L.reasoning)!=null?ot:{id:j,status:"streaming",chunks:[]},L.reasoning.startedAt=(Ut=L.reasoning.startedAt)!=null?Ut:Ve((St=S.startedAt)!=null?St:S.timestamp);let Z=(Ze=(_t=(z=S.reasoningText)!=null?z:S.text)!=null?_t:S.delta)!=null?Ze:"";if(Z&&S.hidden!==!0){let J=typeof S.sequenceIndex=="number"?S.sequenceIndex:void 0;if(J!==void 0){let G=Ye(j,J,String(Z));L.reasoning.chunks=[G]}else L.reasoning.chunks.push(String(Z))}if(L.reasoning.status=S.done?"complete":"streaming",S.done){L.reasoning.completedAt=Ve((Ft=S.completedAt)!=null?Ft:S.timestamp);let J=(re=L.reasoning.startedAt)!=null?re:Date.now();L.reasoning.durationMs=Math.max(0,((ge=L.reasoning.completedAt)!=null?ge:Date.now())-J)}L.streaming=L.reasoning.status!=="complete",g(L)}else if(Ke==="reason_complete"){let j=(qt=(wt=xe(S,!1))!=null?wt:xe(S,!0))!=null?qt:`reason-${l()}`,L=B.get(j);if(L!=null&&L.reasoning){L.reasoning.status="complete",L.reasoning.completedAt=Ve((en=S.completedAt)!=null?en:S.timestamp);let J=(yn=L.reasoning.startedAt)!=null?yn:Date.now();L.reasoning.durationMs=Math.max(0,((Tt=L.reasoning.completedAt)!=null?Tt:Date.now())-J),L.streaming=!1,g(L)}let Z=V(S);Z&&w.byStep.delete(Z)}else if(Ke==="tool_start"){let j=(Ct=he(S,!0))!=null?Ct:`tool-${l()}`,L=(ht=S.toolName)!=null?ht:S.name;if(we(L)){te.add(j);continue}let Z=Ce(j),J=(bt=Z.toolCall)!=null?bt:{id:j,status:"pending"};J.name=L!=null?L:J.name,J.status="running",S.args!==void 0?J.args=S.args:S.parameters!==void 0&&(J.args=S.parameters),J.startedAt=(nt=J.startedAt)!=null?nt:Ve((Vt=S.startedAt)!=null?Vt:S.timestamp),J.completedAt=void 0,J.durationMs=void 0,Z.toolCall=J,Z.streaming=!0;let G=S.agentContext;(G||S.executionId)&&(Z.agentMetadata={executionId:(Dn=G==null?void 0:G.executionId)!=null?Dn:S.executionId,iteration:(Zn=G==null?void 0:G.iteration)!=null?Zn:S.iteration}),g(Z)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let j=(Nn=(bn=he(S,!1))!=null?bn:he(S,!0))!=null?Nn:`tool-${l()}`;if(te.has(j))continue;let L=Ce(j),Z=(mt=L.toolCall)!=null?mt:{id:j,status:"running"};Z.startedAt=(Fn=Z.startedAt)!=null?Fn:Ve((vr=S.startedAt)!=null?vr:S.timestamp);let J=(qo=(Ln=(yo=S.text)!=null?yo:S.delta)!=null?Ln:S.message)!=null?qo:"";J&&(Z.chunks=(zr=Z.chunks)!=null?zr:[],Z.chunks.push(String(J))),Z.status="running",L.toolCall=Z,L.streaming=!0;let G=S.agentContext;(G||S.executionId)&&(L.agentMetadata=(On=L.agentMetadata)!=null?On:{executionId:(Mr=G==null?void 0:G.executionId)!=null?Mr:S.executionId,iteration:(xt=G==null?void 0:G.iteration)!=null?xt:S.iteration}),g(L)}else if(Ke==="tool_complete"){let j=(xn=($n=he(S,!1))!=null?$n:he(S,!0))!=null?xn:`tool-${l()}`;if(te.has(j)){te.delete(j);continue}let L=Ce(j),Z=(Pt=L.toolCall)!=null?Pt:{id:j,status:"running"};Z.status="complete",S.result!==void 0&&(Z.result=S.result),typeof S.duration=="number"&&(Z.duration=S.duration),Z.completedAt=Ve((er=S.completedAt)!=null?er:S.timestamp);let J=(tr=S.duration)!=null?tr:S.executionTime;if(typeof J=="number")Z.durationMs=J;else{let $e=(_n=Z.startedAt)!=null?_n:Date.now();Z.durationMs=Math.max(0,((Vr=Z.completedAt)!=null?Vr:Date.now())-$e)}L.toolCall=Z,L.streaming=!1;let G=S.agentContext;(G||S.executionId)&&(L.agentMetadata=(jn=L.agentMetadata)!=null?jn:{executionId:(kr=G==null?void 0:G.executionId)!=null?kr:S.executionId,iteration:(Kr=G==null?void 0:G.iteration)!=null?Kr:S.iteration}),g(L);let Qe=se(S);Qe&&W.byCall.delete(Qe)}else if(Ke==="step_await"&&S.awaitReason==="local_tool_required"&&S.toolName){let j=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,L=(Rt=j!=null?j:S.toolId)!=null?Rt:`local-${l()}`,Z=Ce(L),J=(vn=Z.toolCall)!=null?vn:{id:L,status:"pending"};J.name=S.toolName,J.args=S.parameters,J.status="complete",J.chunks=(nr=J.chunks)!=null?nr:[],J.startedAt=(Lr=J.startedAt)!=null?Lr:Ve((Jr=S.startedAt)!=null?Jr:S.timestamp),J.completedAt=(Gr=J.completedAt)!=null?Gr:J.startedAt,Z.toolCall=J,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(Un=S.executionId)!=null?Un:(wr=Z.agentMetadata)==null?void 0:wr.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},g(Z)}else if(Ke==="text_start"){if((dr=S.toolContext)!=null&&dr.toolId)continue;let j=S.partId;if(j!==void 0&&A.current!==null&&j!==A.current){let L=u;L&&(L.streaming=!1,g(L),oe=L,u=null,E=!0)}j!==void 0&&(A.current=j)}else if(Ke==="text_end"){if((ft=S.toolContext)!=null&&ft.toolId)continue;let j=u;j&&(j.streaming=!1,g(j),oe=j,u=null,E=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let j=S.stepType,L=S.executionType;if(j==="tool"||L==="context")continue;let Z=S.toolContext;if(Z!=null&&Z.toolId){let $e=String((Xt=(Gt=S.id)!=null?Gt:Z.stepId)!=null?Xt:`step-${l()}`),tt=S.partId!==void 0&&S.partId!==null?String(S.partId):"",Me=`${Z.toolId}::${$e}`,Ge=R.get(Me);if(tt!==""&&Ge!==void 0&&Ge!==""&&Ge!==tt){let At=I.get($(Z.toolId,$e,Ge));At&&At.streaming!==!1&&(At.streaming=!1,g(At))}tt!==""&&R.set(Me,tt);let It=D(Z.toolId,$e,tt,Z.executionId),on=(pr=(rr=(Xr=(qn=S.text)!=null?qn:S.delta)!=null?Xr:S.content)!=null?rr:S.chunk)!=null?pr:"";on&&(It.content+=String(on),It.streaming=!0,g(It)),S.isComplete&&(It.streaming=!1,g(It));continue}let J=S.partId;if(J!==void 0&&A.current!==null&&J!==A.current){let $e=u;$e&&($e.streaming=!1,g($e),oe=$e,u=null,E=!0)}J!==void 0&&(A.current=J);let G=J!==void 0&&(zn=le.get(J))!=null?zn:Fe();J!==void 0&&(G.partId||(G.partId=J),le.set(J,G));let Qe=(Pr=(ur=(Vn=(T=S.text)!=null?T:S.delta)!=null?Vn:S.content)!=null?ur:S.chunk)!=null?Pr:"";if(Qe){let $e=typeof S.seq=="number"?S.seq:void 0,tt=J!=null?J:G.id,Me=$e!==void 0?Ye(tt,$e,String(Qe)):((Cr=ae.get(G.id))!=null?Cr:"")+Qe;G.rawContent=Me,ne.has(G.id)||ne.set(G.id,this.createStreamParser());let Ge=ne.get(G.id),It=Me.trim().startsWith("{")||Me.trim().startsWith("[");if(It&&ae.set(G.id,Me),Ge.__isPlainTextParser===!0){G.content=$e!==void 0?Me:G.content+Qe,ae.delete(G.id),ne.delete(G.id),G.rawContent=void 0,g(G);continue}let At=Ge.processChunk(Me);if(At instanceof Promise)At.then(kt=>{var un;let sn=typeof kt=="string"?kt:(un=kt==null?void 0:kt.text)!=null?un:null;if(sn!==null&&sn.trim()!=="")G.content=sn,g(G);else if(!It&&!Me.trim().startsWith("<")){let Cn=u,Qt=Cn&&Cn.id===G.id?Cn:G;Qt.id===G.id&&(Qt.content=$e!==void 0?Me:Qt.content+Qe,ae.delete(Qt.id),ne.delete(Qt.id),Qt.rawContent=void 0,g(Qt))}}).catch(()=>{G.content=$e!==void 0?Me:G.content+Qe,ae.delete(G.id),ne.delete(G.id),G.rawContent=void 0,g(G)});else{let kt=typeof At=="string"?At:(xs=At==null?void 0:At.text)!=null?xs:null;kt!==null&&kt.trim()!==""?(G.content=kt,g(G)):!It&&!Me.trim().startsWith("<")&&(G.content=$e!==void 0?Me:G.content+Qe,ae.delete(G.id),ne.delete(G.id),G.rawContent=void 0,g(G))}}if(S.isComplete){let $e=(gr=(mr=S.result)==null?void 0:mr.response)!=null?gr:G.content;if($e){let tt=ae.get(G.id),Me=tt!=null?tt:Y($e);G.rawContent=Me;let Ge=ne.get(G.id),It=null,on=!1;if(Ge&&(It=Ge.getExtractedText(),It===null&&(It=Wo(Me)),It===null)){let At=Ge.processChunk(Me);At instanceof Promise?(on=!0,At.then(kt=>{var un;let sn=typeof kt=="string"?kt:(un=kt==null?void 0:kt.text)!=null?un:null;if(sn!==null){let Cn=u;Cn&&Cn.id===G.id&&(Cn.content=sn,Cn.streaming=!1,ne.delete(Cn.id),ae.delete(Cn.id),g(Cn))}})):It=typeof At=="string"?At:(fr=At==null?void 0:At.text)!=null?fr:null}if(!on){It!==null&&It.trim()!==""?G.content=It:ae.has(G.id)||(G.content=Y($e));let At=ne.get(G.id);if(At){let kt=(Ir=At.close)==null?void 0:Ir.call(At);kt instanceof Promise&&kt.catch(()=>{}),ne.delete(G.id)}ae.delete(G.id),G.streaming=!1,g(G)}}}}else if(Ke==="step_complete"){let j=S.stepType,L=S.executionType;if(j==="tool"||L==="context")continue;let Z=S.toolContext;if(Z!=null&&Z.toolId){let $e=String((fa=(bo=S.id)!=null?bo:Z.stepId)!=null?fa:"");if($e){let tt=_(Z.toolId,$e);for(let[Me,Ge]of I)Me.startsWith(tt)&&Ge.streaming!==!1&&(Ge.streaming=!1,g(Ge));R.delete(`${Z.toolId}::${$e}`)}continue}let J=S.stopReason;if(E){if(u!==null){let Me=u;J&&(Me.stopReason=J),ne.delete(Me.id),ae.delete(Me.id),Me.streaming!==!1&&(Me.streaming=!1,g(Me))}let $e=(vs=S.result)==null?void 0:vs.response,tt=oe;tt&&(J&&(tt.stopReason=J),$e!=null?We(tt,$e):(ne.delete(tt.id),ae.delete(tt.id))),oe=null;continue}let G=(ha=S.result)==null?void 0:ha.response,Qe=Fe();if(J&&(Qe.stopReason=J),G!=null){let $e=ne.get(Qe.id),tt=!1,Me=!1;if($e){let Ge=$e.getExtractedText(),It=ae.get(Qe.id),on=It!=null?It:Y(G);if(Qe.rawContent=on,Ge!==null&&Ge.trim()!=="")Qe.content=Ge,tt=!0;else{let At=Wo(on);if(At!==null)Qe.content=At,tt=!0;else{let kt=$e.processChunk(on);if(kt instanceof Promise)Me=!0,kt.then(sn=>{var Cn;let un=typeof sn=="string"?sn:(Cn=sn==null?void 0:sn.text)!=null?Cn:null;if(un!==null&&un.trim()!==""){let Qt=u;Qt&&Qt.id===Qe.id&&(Qt.content=un,Qt.streaming=!1,ne.delete(Qt.id),ae.delete(Qt.id),g(Qt))}else{let Qt=$e.getExtractedText(),sr=u;sr&&sr.id===Qe.id&&(Qt!==null&&Qt.trim()!==""?sr.content=Qt:ae.has(sr.id)||(sr.content=Y(G)),sr.streaming=!1,ne.delete(sr.id),ae.delete(sr.id),g(sr))}});else{let sn=typeof kt=="string"?kt:(zo=kt==null?void 0:kt.text)!=null?zo:null;if(sn!==null&&sn.trim()!=="")Qe.content=sn,tt=!0;else{let un=$e.getExtractedText();un!==null&&un.trim()!==""&&(Qe.content=un,tt=!0)}}}}}if(!Me){if(!Qe.rawContent){let Ge=ae.get(Qe.id);Qe.rawContent=Ge!=null?Ge:Y(G)}if(!tt&&!ae.has(Qe.id)&&(Qe.content=Y(G)),$e){let Ge=(gt=$e.close)==null?void 0:gt.call($e);Ge instanceof Promise&&Ge.catch(()=>{})}ne.delete(Qe.id),ae.delete(Qe.id),Qe.streaming=!1,g(Qe)}}else ne.delete(Qe.id),ae.delete(Qe.id),Qe.streaming=!1,g(Qe)}else if(Ke==="flow_complete"){let j=(ws=S.result)==null?void 0:ws.response;if(E){if(u!==null){let L=u;ne.delete(L.id),ae.delete(L.id),L.streaming!==!1&&(L.streaming=!1,g(L))}}else if(j!=null){let L=Fe(),Z=ae.get(L.id),J=Z!=null?Z:Y(j);L.rawContent=J;let G=Y(j),Qe=ne.get(L.id);if(Qe){let Me=Wo(J);if(Me!==null)G=Me;else{let Ge=Qe.processChunk(J);Ge instanceof Promise&&Ge.then(on=>{var kt;let At=typeof on=="string"?on:(kt=on==null?void 0:on.text)!=null?kt:null;At!==null&&(L.content=At,L.streaming=!1,g(L))});let It=Qe.getExtractedText();It!==null&&(G=It)}}ne.delete(L.id),ae.delete(L.id);let $e=G!==L.content,tt=L.streaming!==!1;$e&&(L.content=G),L.streaming=!1,($e||tt)&&g(L)}else if(u!==null){let L=u;ne.delete(L.id),ae.delete(L.id),L.streaming!==!1&&(L.streaming=!1,g(L))}n({type:"status",status:"idle"})}else if(Ke==="agent_start")ie={executionId:S.executionId,agentId:(or=S.agentId)!=null?or:"virtual",agentName:(Pn=S.agentName)!=null?Pn:"",status:"running",currentIteration:0,maxTurns:(ya=S.maxTurns)!=null?ya:1,startedAt:Ve(S.startedAt)};else if(Ke==="agent_iteration_start"){if(ie&&(ie.currentIteration=S.iteration),$t==="separate"&&S.iteration>1){let j=u;j&&(j.streaming=!1,g(j),kn.set(S.iteration-1,j),u=null)}}else if(Ke==="agent_turn_start")v=null;else if(Ke==="agent_turn_delta"){if(S.contentType==="text"){let j=Fe();j.content+=(ba=S.delta)!=null?ba:"",j.agentMetadata={executionId:S.executionId,iteration:S.iteration,turnId:S.turnId,agentName:ie==null?void 0:ie.agentName},v=j,g(j)}else if(S.contentType==="thinking"){let j=(Vo=S.turnId)!=null?Vo:`agent-think-${S.iteration}`,L=Pe(j);L.reasoning=(Wr=L.reasoning)!=null?Wr:{id:j,status:"streaming",chunks:[]},L.reasoning.chunks.push((xa=S.delta)!=null?xa:""),L.agentMetadata={executionId:S.executionId,iteration:S.iteration,turnId:S.turnId},g(L)}else if(S.contentType==="tool_input"){let j=(xo=S.toolCallId)!=null?xo:W.lastId;if(j){let L=P.get(j);L!=null&&L.toolCall&&(L.toolCall.chunks=(Cs=L.toolCall.chunks)!=null?Cs:[],L.toolCall.chunks.push((Rr=S.delta)!=null?Rr:""),g(L))}}}else if(Ke==="agent_turn_complete"){let j=S.turnId;if(j){let J=B.get(j);if(J!=null&&J.reasoning){J.reasoning.status="complete",J.reasoning.completedAt=Ve(S.completedAt);let G=(As=J.reasoning.startedAt)!=null?As:Date.now();J.reasoning.durationMs=Math.max(0,((Qr=J.reasoning.completedAt)!=null?Qr:Date.now())-G),J.streaming=!1,g(J)}}let L=S.stopReason,Z=u!=null?u:v;if(L&&Z!==null){let J=S.turnId;(!J||((Yr=Z.agentMetadata)==null?void 0:Yr.turnId)===J)&&(Z.stopReason=L,g(Z))}}else if(Ke==="agent_tool_start"){u&&(u.streaming=!1,g(u),u=null);let j=(va=S.toolCallId)!=null?va:`agent-tool-${l()}`;Be(se(S),j);let L=Ce(j),Z=(wa=L.toolCall)!=null?wa:{id:j,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};Z.name=(vo=(Vi=S.toolName)!=null?Vi:S.name)!=null?vo:Z.name,Z.status="running",S.parameters!==void 0&&(Z.args=S.parameters),Z.startedAt=Ve((Zr=S.startedAt)!=null?Zr:S.timestamp),L.toolCall=Z,L.streaming=!0,L.agentMetadata={executionId:S.executionId,iteration:S.iteration},g(L)}else if(Ke==="agent_tool_delta"){let j=(Ca=S.toolCallId)!=null?Ca:W.lastId;if(j){let L=(Ss=P.get(j))!=null?Ss:Ce(j);L.toolCall&&(L.toolCall.chunks=(eo=L.toolCall.chunks)!=null?eo:[],L.toolCall.chunks.push((Aa=S.delta)!=null?Aa:""),L.toolCall.status="running",L.streaming=!0,g(L))}}else if(Ke==="agent_tool_complete"){let j=(Ts=S.toolCallId)!=null?Ts:W.lastId;if(j){let L=(to=P.get(j))!=null?to:Ce(j);if(L.toolCall){L.toolCall.status="complete",S.result!==void 0&&(L.toolCall.result=S.result),typeof S.executionTime=="number"&&(L.toolCall.durationMs=S.executionTime),L.toolCall.completedAt=Ve((Es=S.completedAt)!=null?Es:S.timestamp),L.streaming=!1,g(L);let Z=se(S);Z&&W.byCall.delete(Z)}}}else if(Ke==="agent_media"){let j=Array.isArray(S.media)?S.media:[],L=[];for(let Z of j){if(!Z||typeof Z!="object")continue;let J=Z,G=typeof J.type=="string"?J.type:void 0,Qe=typeof J.mediaType=="string"?J.mediaType.toLowerCase():"",$e=null,tt="";if(G==="media"){let Me=typeof J.data=="string"?J.data:void 0;if(!Me)continue;tt=Qe.length>0?Qe:"application/octet-stream",$e=`data:${tt};base64,${Me}`}else if(G==="image-url"){let Me=typeof J.url=="string"?J.url:void 0;if(!Me)continue;tt=Qe,$e=Me}else if(G==="file-url"){let Me=typeof J.url=="string"?J.url:void 0;if(!Me)continue;tt=Qe,$e=Me}else continue;if($e)if(G==="image-url"||tt.startsWith("image/"))L.push({type:"image",image:$e,...tt?{mimeType:tt}:{}});else if(tt.startsWith("audio/"))L.push({type:"audio",audio:$e,mimeType:tt});else if(tt.startsWith("video/"))L.push({type:"video",video:$e,mimeType:tt});else{let Me=tt||"application/octet-stream";L.push({type:"file",data:$e,mimeType:Me,filename:Ng(Me)})}}if(L.length>0){let Z=l(),J=S.toolCallId,Qe={id:`agent-media-${typeof J=="string"&&J.length>0?`${J}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:L,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:S.executionId,iteration:S.iteration}};g(Qe);let $e=u;$e&&($e.streaming=!1,g($e)),u=null,x.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let j=`agent-reflection-${S.executionId}-${S.iteration}`,L={id:j,role:"assistant",content:(Sa=S.reflection)!=null?Sa:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(Hr=S.reflection)!=null?Hr:""]},agentMetadata:{executionId:S.executionId,iteration:S.iteration}};g(L)}else if(Ke==="agent_complete"){ie&&(ie.status=S.success?"complete":"error",ie.completedAt=Ve(S.completedAt),ie.stopReason=S.stopReason);let j=u;j&&(j.streaming=!1,g(j)),n({type:"status",status:"idle"})}else if(Ke==="agent_error"){let j=typeof S.error=="string"?S.error:(no=(Ta=S.error)==null?void 0:Ta.message)!=null?no:"Agent execution error";S.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):n({type:"error",error:new Error(j)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let j=(Ht=S.approvalId)!=null?Ht:`approval-${l()}`,L={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Ko=ie==null?void 0:ie.agentId)!=null?Ko:"virtual",executionId:(Ms=(Jo=S.executionId)!=null?Jo:ie==null?void 0:ie.executionId)!=null?Ms:"",toolName:(Ar=S.toolName)!=null?Ar:"",toolType:S.toolType,description:(ks=S.description)!=null?ks:`Execute ${(Ea=S.toolName)!=null?Ea:"tool"}`,parameters:S.parameters}};g(L)}else if(Ke==="step_await"&&S.awaitReason==="approval_required"){let j=(Ls=S.approvalId)!=null?Ls:`approval-${l()}`,L={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Ma=ie==null?void 0:ie.agentId)!=null?Ma:"virtual",executionId:(Xo=(Go=S.executionId)!=null?Go:ie==null?void 0:ie.executionId)!=null?Xo:"",toolName:(wo=S.toolName)!=null?wo:"",toolType:S.toolType,description:(La=S.description)!=null?La:`Execute ${(ka=S.toolName)!=null?ka:"tool"}`,parameters:S.parameters}};g(L)}else if(Ke==="agent_approval_complete"){let j=S.approvalId;if(j){let Z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(Ps=S.decision)!=null?Ps:"approved",agentId:(Is=ie==null?void 0:ie.agentId)!=null?Is:"virtual",executionId:(Rs=(Ws=S.executionId)!=null?Ws:ie==null?void 0:ie.executionId)!=null?Rs:"",toolName:(wn=S.toolName)!=null?wn:"",description:(Kn=S.description)!=null?Kn:"",resolvedAt:Date.now()}};g(Z)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let j=S.artifactType,L=String(S.id),Z=typeof S.title=="string"?S.title:void 0;if(n({type:"artifact_start",id:L,artifactType:j,title:Z,component:typeof S.component=="string"?S.component:void 0}),ce.set(L,{markdown:"",title:Z}),!K.has(L)){K.add(L);let J={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:L,title:Z,artifactType:j,status:"streaming"}})};Ie.set(L,J),g(J)}}else if(Ke==="artifact_delta"){let j=String(S.id),L=typeof S.delta=="string"?S.delta:String((Br=S.delta)!=null?Br:"");n({type:"artifact_delta",id:j,artDelta:L});let Z=ce.get(j);Z&&(Z.markdown+=L)}else if(Ke==="artifact_update"){let j=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};n({type:"artifact_update",id:String(S.id),props:j,component:typeof S.component=="string"?S.component:void 0})}else if(Ke==="artifact_complete"){let j=String(S.id);n({type:"artifact_complete",id:j});let L=Ie.get(j);if(L){L.streaming=!1;try{let Z=JSON.parse((st=L.rawContent)!=null?st:"{}");if(Z.props){Z.props.status="complete";let J=ce.get(j);J!=null&&J.markdown&&(Z.props.markdown=J.markdown)}L.rawContent=JSON.stringify(Z)}catch{}ce.delete(j),g(L),Ie.delete(j)}}}else if(Ke==="transcript_insert"){let j=S.message;if(!j||typeof j!="object")continue;let L=String((Hs=j.id)!=null?Hs:`msg-${l()}`),Z=j.role,G={id:L,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(g(G),G.rawContent)try{let Qe=JSON.parse(G.rawContent),$e=(Co=Qe==null?void 0:Qe.props)==null?void 0:Co.artifactId;typeof $e=="string"&&K.add($e)}catch{}u=null,x.current=null,ne.delete(L),ae.delete(L)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let j=null;if(S.error instanceof Error)j=S.error;else if(Ke==="dispatch_error"){let L=(hr=S.message)!=null?hr:S.error;L!=null&&L!==""&&(j=new Error(String(L)))}else if(Ke==="step_error"||Ke==="flow_error"){let L=S.error;typeof L=="string"&&L!==""?j=new Error(L):L!=null&&typeof L=="object"&&"message"in L&&(j=new Error(String((Pa=L.message)!=null?Pa:L)))}else Ke==="error"&&S.error!=null&&S.error!==""&&(j=new Error(String(S.error)));if(j){n({type:"error",error:j});let L=u;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}de.length=0};;){let{done:F,value:Se}=await s.read();if(F)break;a+=o.decode(Se,{stream:!0});let De=a.split(`
|
|
10
10
|
|
|
11
11
|
`);a=(Bn=De.pop())!=null?Bn:"";for(let Ne of De){let je=Ne.split(`
|
|
12
|
-
`),pt="message",ot="";for(let z of je)z.startsWith("event:")?pt=z.replace("event:","").trim():z.startsWith("data:")&&(ot+=z.replace("data:","").trim());if(!ot)continue;let St;try{St=JSON.parse(ot)}catch(z){t({type:"error",error:z instanceof Error?z:new Error("Failed to parse chat stream payload")});continue}let Ut=pt!=="message"?pt:(Yn=St.type)!=null?Yn:"message";if((qe=this.onSSEEvent)==null||qe.call(this,Ut,St),this.parseSSEEvent){x.current=u;let z=await this.handleCustomSSEEvent(St,t,x,g,l,A);if(x.current&&x.current!==u&&(u=x.current),z)continue}pe.push(Ut,St),$e()}}pe.flushPending(),$e(),pe.destroy()}};function au(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function rs(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function Ho(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Ka="[Image]";function iu(e){return typeof e=="string"?[{type:"text",text:e}]:e}function lu(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function cu(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function du(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function qs(e){return{type:"text",text:e}}function pu(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function uu(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function mu(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.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: ${n.join(", ")}`}}var gu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Og=["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"],Or=[...gu,...Og];function _g(e){return gu.includes(e)||e.startsWith("image/")}function Ja(e){return _g(e.type)}async function fu(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ja(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function hu(e,n=Or,t=10*1024*1024){return n.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: ${n.join(", ")}`}}function $g(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function yu(e,n){let t=$g(n).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 Ga=class{constructor(n=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=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,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 r=this.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.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 n of this.activeSources)try{n.stop(),n.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(n){this.finishedCallbacks.push(n)}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 n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Xa=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(r==="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 zs=class{constructor(n){this.config=n;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 Xa;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(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;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=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.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 l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let v=!1,x=E=>{v||(v=!0,clearTimeout(A),u(new Error(E)))},A=setTimeout(()=>x("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(A),g())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",E=>{if(!E.wasClean&&!v){let B=E.code!==1006?` (code ${E.code})`:"";x("WebSocket connection failed"+B+"."+m)}},{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(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.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(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ga(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(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("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 n,t,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(s=(r=this.config)==null?void 0:r.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=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("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(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let l=0;l<t.length;l++)r[l]=t.charCodeAt(l);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{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(l=>l("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}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(n=>n.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(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Bo=class{constructor(n={}){this.config=n;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(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.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(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Do(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new zs(e.runtype);case"browser":if(!Bo.isSupported())throw new Error("Browser speech recognition not supported");return new Bo(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Qa(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Do({type:"runtype",runtype:e.runtype});if(Bo.isSupported())return Do({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Vs(e){try{return Qa(e),!0}catch{return!1}}function bu(e,n){let t=e instanceof Error?e:new Error(String(e));if(typeof n=="string")return n;if(typeof n=="function")return n(t);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return t.message?`${r}
|
|
12
|
+
`),pt="message",ot="";for(let z of je)z.startsWith("event:")?pt=z.replace("event:","").trim():z.startsWith("data:")&&(ot+=z.replace("data:","").trim());if(!ot)continue;let St;try{St=JSON.parse(ot)}catch(z){n({type:"error",error:z instanceof Error?z:new Error("Failed to parse chat stream payload")});continue}let Ut=pt!=="message"?pt:(Yn=St.type)!=null?Yn:"message";if((qe=this.onSSEEvent)==null||qe.call(this,Ut,St),this.parseSSEEvent){x.current=u;let z=await this.handleCustomSSEEvent(St,n,x,g,l,A);if(x.current&&x.current!==u&&(u=x.current),z)continue}pe.push(Ut,St),_e()}}pe.flushPending(),_e(),pe.destroy()}};function iu(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function rs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ho(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ja="[Image]";function lu(e){return typeof e=="string"?[{type:"text",text:e}]:e}function cu(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function du(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function pu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function qs(e){return{type:"text",text:e}}function uu(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function mu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function gu(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var fu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],$g=["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"],Or=[...fu,...$g];function _g(e){return fu.includes(e)||e.startsWith("image/")}function Ga(e){return _g(e.type)}async function hu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ga(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function yu(e,t=Or,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function jg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function bu(e,t){let n=jg(t).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]||n||"FILE"}var Xa=class{constructor(t=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=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(n),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.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 t of this.activeSources)try{t.stop(),t.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(t){this.finishedCallbacks.push(t)}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 t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Qa=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(r==="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 zs=class{constructor(t){this.config=t;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 Qa;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(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;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=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.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 l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let v=!1,x=E=>{v||(v=!0,clearTimeout(A),u(new Error(E)))},A=setTimeout(()=>x("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(A),g())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",E=>{if(!E.wasClean&&!v){let B=E.code!==1006?` (code ${E.code})`:"";x("WebSocket connection failed"+B+"."+m)}},{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(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(t.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.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(t.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Xa(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("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 t,n,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(s=(r=this.config)==null?void 0:r.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=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("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(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),s=this.getFormatFromMimeType(t.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];n(a)},s.onerror=r,s.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let l=0;l<n.length;l++)r[l]=n.charCodeAt(l);let s=t.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{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(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}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(t=>t.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(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Bo=class{constructor(t={}){this.config=t;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(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.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(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Do(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new zs(e.runtype);case"browser":if(!Bo.isSupported())throw new Error("Browser speech recognition not supported");return new Bo(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ya(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Do({type:"runtype",runtype:e.runtype});if(Bo.isSupported())return Do({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Vs(e){try{return Ya(e),!0}catch{return!1}}function xu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
|
|
13
13
|
|
|
14
|
-
_Details: ${t.message}_`:r}var os=class e{constructor(n={},t){this.config=n;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.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,s,o,a,i,d,l;if(n.type==="message"){this.upsertMessage(n.message);let p=n.message.toolCall;((t=n.message.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&(p!=null&&p.name)&&$s(p.name)&&this.enqueueWebMcpAwait(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(s=n.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(n.type==="status"){if(this.setStatus(n.status),n.status==="connecting")this.setStreaming(!0);else if(n.status==="idle"||n.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(n.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else n.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,s;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ro(n),this.wireDefaultWebMcpConfirm();for(let o of(s=n.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Vs((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Do(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,g,u,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let A=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(E=>E.role==="assistant"))==null?void 0:v.id;A&&this.ttsSpokenMessageIds.add(A)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),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(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),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(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,l,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=n.browser)==null?void 0:l.language)||"en-US",continuous:(p=n.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new Ro(this.config),this.wireDefaultWebMcpConfirm(),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=n,u={id:a!=null?a:t==="user"?rs():t==="assistant"?Ho():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(u),u}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:g,rawContent:u}=r,x={id:d!=null?d:s==="user"?rs():s==="assistant"?Ho():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(n){let{component:t,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=n,l={text:s,component:t,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(n,t){var l,p,m,g,u;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=rs(),o=Ho(),a={id:s,role:"user",content:r||Ka,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 x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let A=bu(v,this.config.errorMessage);if(A){let E={id:o,role:"assistant",createdAt:new Date().toISOString(),content:A,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,v):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=Ho();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=bu(l,this.config.errorMessage);if(m){let g={id:n,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(n,t){var s,o,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let n=this.config.webmcp;(n==null?void 0:n.enabled)===!0&&!n.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(n){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,n))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:n.toolName,toolType:"webmcp",description:(a=n.description)!=null?a:`Allow the assistant to run ${n.toolName}?`,parameters:n.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(n,t){let r=this.webMcpApprovalResolvers.get(n);if(!r)return;this.webMcpApprovalResolvers.delete(n);let s=this.messages.find(o=>o.id===n);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(n,t){var d,l,p,m;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let g;if(i?g=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):g=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),g){let u=null;if(g instanceof Response){if(!g.ok){let v=await g.json().catch(()=>null);throw new Error((l=v==null?void 0:v.error)!=null?l:`Approval request failed: ${g.status}`)}u=g.body}else g instanceof ReadableStream&&(u=g);u?await this.connectStream(u,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(g){let u=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||(m=(p=this.callbacks).onError)==null||m.call(p,g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var p,m,g,u,v,x,A,E,B,P,I,R;let r=this.messages.find(w=>w.id===n.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=n.agentMetadata)==null?void 0:m.executionId,o=(g=n.toolCall)==null?void 0:g.name;if(!s||!o){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let w=(x=n.toolCall)==null?void 0:x.args,W=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(W.length===1){let _=typeof((A=W[0])==null?void 0:A.question)=="string"?W[0].question:"";_&&(a={[_]:t})}}this.markAskUserQuestionResolved(n,a),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=n.toolCall.id,d=(B=n.toolCall)==null?void 0:B.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof t=="string"?t:Object.entries(t).map(([W,_])=>`${W}: ${Array.isArray(_)?_.join(", "):_}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((W,_)=>{let $=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!$)return;let D=w[$],U=Array.isArray(D)?D.join(", "):typeof D=="string"?D:"";this.appendMessage({id:`ask-user-q-${i}-${_}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${_}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(s,{[o]:t});if(!w.ok){let W=await w.json().catch(()=>null);throw new Error((P=W==null?void 0:W.error)!=null?P:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let W=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(R=(I=this.callbacks).onError)==null||R.call(I,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(n){var o,a;let t=(o=n.agentMetadata)==null?void 0:o.executionId,r=(a=n.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(n)});return}let s=this.webMcpAwaitBatches.get(t);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(n))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let n=this.webMcpEpoch;queueMicrotask(()=>{if(n===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(n){let t=this.webMcpAwaitBatches.get(n);if(!t)return;this.webMcpAwaitBatches.delete(n);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(n,r)}async resolveWebMcpToolCallBatch(n,t){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(t.map(async p=>{var B,P,I,R,w,W,_;let m=(B=p.toolCall)==null?void 0:B.name,g=(P=p.toolCall)==null?void 0:P.id;if(!m||!g)return null;let u=`${n}:${g}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u))return null;this.webMcpInflightKeys.add(u),r.push(u),this.upsertMessage({...p,agentMetadata:{...p.agentMetadata,awaitingLocalTool:!1}});let v=new AbortController;this.webMcpResolveControllers.add(v),s.push(v);let x=(R=(I=p.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?R:m,A=this.client.executeWebMcpToolCall(m,(w=p.toolCall)==null?void 0:w.args,v.signal),E;if(!A)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await A}catch($){return $ instanceof Error&&($.name==="AbortError"||$.message.includes("aborted")||$.message.includes("abort"))||(_=(W=this.callbacks).onError)==null||_.call(W,$ instanceof Error?$:new Error(String($))),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:x,output:E}}));try{let p=a.filter(u=>u!==null);if(p.length===0)return;let m={};for(let u of p)m[u.resumeKey]=u.output;let g=await this.client.resumeFlow(n,m,{signal:o.signal});if(!g.ok){let u=await g.json().catch(()=>null);throw new Error((i=u==null?void 0:u.error)!=null?i:`Resume failed: ${g.status}`)}for(let u of p)this.webMcpResolvedKeys.add(u.dedupeKey);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(p){p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,p instanceof Error?p:new Error(String(p)))}finally{for(let p of r)this.webMcpInflightKeys.delete(p);for(let p of s)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(n){var p,m,g,u,v,x,A,E,B,P,I,R;let t=(p=n.agentMetadata)==null?void 0:p.executionId,r=(m=n.toolCall)==null?void 0:m.name,s=(g=n.toolCall)==null?void 0:g.id;if(!t){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let w=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return;this.webMcpInflightKeys.add(w);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(w)}catch(W){(A=(x=this.callbacks).onError)==null||A.call(x,W instanceof Error?W:new Error(String(W)))}finally{this.webMcpInflightKeys.delete(w)}return}let o=`${t}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(E=n.toolCall)==null?void 0:E.args,l=this.client.executeWebMcpToolCall(r,d,i);try{let w;if(l?w=await l:w={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let W=(P=(B=n.agentMetadata)==null?void 0:B.webMcpToolCallId)!=null?P:r;await this.resumeWithToolOutput(t,W,w,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o)},signal:i})}catch(w){w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"))||(R=(I=this.callbacks).onError)==null||R.call(I,w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(n,t,r,s){var a,i;let o=await this.client.resumeFlow(n,{[t]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let n of this.webMcpResolveControllers)n.abort();this.webMcpResolveControllers.clear();for(let n of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(n,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.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(()=>r.speak(s),50)}static pickBestVoice(n){var r;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=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>{var p,m,g,u,v,x;if(o!==r)return s;let a={...s,...t};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=t.toolCall)==null?void 0:m.name,d=(g=t.agentMetadata)==null?void 0:g.executionId,l=(u=t.toolCall)==null?void 0:u.id;if(i&&$s(i)&&d&&l&&((v=t.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let A=`${d}:${l}`;(this.webMcpInflightKeys.has(A)||this.webMcpResolvedKeys.has(A))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,l;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},Tr=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};var C=require("lucide"),jg={activity:C.Activity,"arrow-down":C.ArrowDown,"arrow-up":C.ArrowUp,"arrow-up-right":C.ArrowUpRight,bot:C.Bot,"chevron-down":C.ChevronDown,"chevron-up":C.ChevronUp,"chevron-right":C.ChevronRight,"chevron-left":C.ChevronLeft,check:C.Check,clipboard:C.Clipboard,"clipboard-copy":C.ClipboardCopy,copy:C.Copy,file:C.File,"file-code":C.FileCode,"file-spreadsheet":C.FileSpreadsheet,"file-text":C.FileText,"image-plus":C.ImagePlus,loader:C.Loader,"loader-circle":C.LoaderCircle,mic:C.Mic,paperclip:C.Paperclip,"refresh-cw":C.RefreshCw,search:C.Search,send:C.Send,"shield-alert":C.ShieldAlert,"shield-check":C.ShieldCheck,"shield-x":C.ShieldX,square:C.Square,"thumbs-down":C.ThumbsDown,"thumbs-up":C.ThumbsUp,upload:C.Upload,"volume-2":C.Volume2,x:C.X,user:C.User,mail:C.Mail,phone:C.Phone,calendar:C.Calendar,clock:C.Clock,building:C.Building,"map-pin":C.MapPin,lock:C.Lock,key:C.Key,"credit-card":C.CreditCard,"at-sign":C.AtSign,hash:C.Hash,globe:C.Globe,link:C.Link,"circle-check":C.CircleCheck,"circle-x":C.CircleX,"triangle-alert":C.TriangleAlert,info:C.Info,ban:C.Ban,shield:C.Shield,"arrow-left":C.ArrowLeft,"arrow-right":C.ArrowRight,"external-link":C.ExternalLink,ellipsis:C.Ellipsis,"ellipsis-vertical":C.EllipsisVertical,menu:C.Menu,house:C.House,plus:C.Plus,minus:C.Minus,pencil:C.Pencil,trash:C.Trash,"trash-2":C.Trash2,save:C.Save,download:C.Download,share:C.Share,funnel:C.Funnel,settings:C.Settings,"rotate-cw":C.RotateCw,maximize:C.Maximize,minimize:C.Minimize,"shopping-cart":C.ShoppingCart,"shopping-bag":C.ShoppingBag,package:C.Package,truck:C.Truck,tag:C.Tag,gift:C.Gift,receipt:C.Receipt,wallet:C.Wallet,store:C.Store,"dollar-sign":C.DollarSign,percent:C.Percent,play:C.Play,pause:C.Pause,"volume-x":C.VolumeX,camera:C.Camera,image:C.Image,film:C.Film,headphones:C.Headphones,"message-circle":C.MessageCircle,"message-square":C.MessageSquare,bell:C.Bell,heart:C.Heart,star:C.Star,eye:C.Eye,"eye-off":C.EyeOff,bookmark:C.Bookmark,"calendar-days":C.CalendarDays,history:C.History,timer:C.Timer,folder:C.Folder,"folder-open":C.FolderOpen,files:C.Files,sparkles:C.Sparkles,zap:C.Zap,sun:C.Sun,moon:C.Moon,flag:C.Flag,monitor:C.Monitor,smartphone:C.Smartphone},be=(e,n=24,t="currentColor",r=2)=>{let s=jg[e];return s?Ug(s,n,t,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Ug(e,n,t,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),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)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),s.appendChild(d)}),s}var Ya={allowedTypes:Or,maxFileSize:10*1024*1024,maxFiles:4};function qg(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function zg(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-code":"file"}var No=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Ya.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Ya.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Ya.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Ya.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let l of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,l,"count");continue}let p=hu(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,m);continue}try{let m=await fu(l),g=Ja(l)?URL.createObjectURL(l):null,u={id:qg(),file:l,previewUrl:g,contentPart:m};this.attachments.push(u),this.renderPreview(u)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=Ja(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.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",r.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=zg(n.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=yu(n.file.type,n.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.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=be("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(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var xu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ks(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];xu(o)&&xu(s)?t[r]=Ks(o,s):t[r]=s}return t}var Xn="min(440px, calc(100vw - 24px))",Za="440px",Nt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Xn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},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 vu(e,n){if(!(!e&&!n))return e?n?Ks(e,n):e:n}function ei(e){var n,t,r,s,o,a,i,d,l,p,m,g,u,v,x,A,E,B,P,I,R;return e?{...Nt,...e,theme:vu(Nt.theme,e.theme),darkTheme:vu(Nt.darkTheme,e.darkTheme),launcher:{...Nt.launcher,...e.launcher,dock:{...(n=Nt.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Nt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Nt.copy,...e.copy},sendButton:{...Nt.sendButton,...e.sendButton},statusIndicator:{...Nt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...e.voiceRecognition},features:(()=>{var xe,Pe,Be,te,Ie,K,ce,we;let w=(xe=Nt.features)==null?void 0:xe.artifacts,W=(Pe=e.features)==null?void 0:Pe.artifacts,_=(Be=Nt.features)==null?void 0:Be.scrollToBottom,$=(te=e.features)==null?void 0:te.scrollToBottom,D=(Ie=Nt.features)==null?void 0:Ie.streamAnimation,U=(K=e.features)==null?void 0:K.streamAnimation,V=(ce=Nt.features)==null?void 0:ce.askUserQuestion,se=(we=e.features)==null?void 0:we.askUserQuestion,Re=w===void 0&&W===void 0?void 0:{...w,...W,layout:{...w==null?void 0:w.layout,...W==null?void 0:W.layout}},Ue=_===void 0&&$===void 0?void 0:{..._,...$},Fe=D===void 0&&U===void 0?void 0:{...D,...U},fe=V===void 0&&se===void 0?void 0:{...V,...se,styles:{...V==null?void 0:V.styles,...se==null?void 0:se.styles}};return{...Nt.features,...e.features,...Ue!==void 0?{scrollToBottom:Ue}:{},...Re!==void 0?{artifacts:Re}:{},...Fe!==void 0?{streamAnimation:Fe}:{},...fe!==void 0?{askUserQuestion:fe}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Nt.suggestionChips,suggestionChipsConfig:{...Nt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Nt.layout,...e.layout,header:{...(a=Nt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Nt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(m=(p=Nt.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(u=(g=e.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(x=(v=Nt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(E=(A=e.layout)==null?void 0:A.messages)==null?void 0:E.timestamp}},slots:{...(B=Nt.layout)==null?void 0:B.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...Nt.markdown,...e.markdown,options:{...(I=Nt.markdown)==null?void 0:I.options,...(R=e.markdown)==null?void 0:R.options}},messageActions:{...Nt.messageActions,...e.messageActions}}:Nt}var Yi={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Zi={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},el={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Xn,maxWidth:Za,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function ss(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ss(e,r):r}function ti(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=ss(e,a);d!==void 0&&(n[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"),n}function tl(e){let n=[],t=[];return e.palette||n.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:n.length===0,errors:n,warnings:t}}function wu(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=wu(o,s):t[r]=s}return t}function Vg(e,n){return n?wu(e,n):e}function as(e,n={}){var s,o,a,i,d,l,p,m,g,u,v,x,A;let t={palette:Yi,semantic:Zi,components:el},r={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,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...t.semantic.colors.feedback,...(v=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(A=e==null?void 0:e.semantic)==null?void 0:A.typography}},components:Vg(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let E=tl(r);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(B=>B.message).join(", ")}`)}if(n.plugins)for(let E of n.plugins)r=E.transform(r);return r}function ni(e){var x,A,E,B,P,I,R,w,W,_,$,D,U,V,se,Re,Ue,Fe,fe,xe,Pe,Be,te,Ie,K,ce,we,he,Ce,Ve,Y,ne,ae,me,le,oe,Ye,We,de,X,$e,Mt,pe,ie,kn,_t,cn,Bn,Yn,qe,F,Se,De,Ne,je,pt,ot,St,Ut,z,$t,Ze,Ft,re,ge,wt,qt,en,yn,Tt,Ct,ht,bt,Vt,nt,Dn,Zn,bn,Nn,mt,vr,Fn,yo,Ln,qo,zr,Mr,xt,On,_n,xn,Pt,er,tr,$n,Vr,kr,Kr,jn,Rt,vn,nr,Jr,Lr,Gr,wr,Un,dr,ft,Gt,Xt,qn,Xr,rr,pr,zn;let n=ti(e),t={};for(let[T,Vn]of Object.entries(n)){let ur=T.replace(/\./g,"-");t[`--persona-${ur}`]=Vn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x: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"]=(E=t["--persona-semantic-colors-accent"])!=null?E:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(B=t["--persona-semantic-colors-surface"])!=null?B:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(P=t["--persona-semantic-colors-background"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(I=t["--persona-semantic-colors-container"])!=null?I:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(R=t["--persona-semantic-colors-text"])!=null?R:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(w=t["--persona-semantic-colors-text-muted"])!=null?w:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(W=t["--persona-semantic-colors-text-inverse"])!=null?W:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(_=t["--persona-semantic-colors-border"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=($=t["--persona-semantic-colors-divider"])!=null?$:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(D=t["--persona-components-voice-recording-indicator"])!=null?D:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(U=t["--persona-components-voice-recording-background"])!=null?U:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(V=t["--persona-components-voice-processing-icon"])!=null?V:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(se=t["--persona-components-voice-speaking-icon"])!=null?se:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Re=t["--persona-components-approval-requested-background"])!=null?Re:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Ue=t["--persona-components-approval-requested-border"])!=null?Ue:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Fe=t["--persona-components-approval-requested-text"])!=null?Fe:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(fe=t["--persona-components-approval-approve-background"])!=null?fe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(xe=t["--persona-components-approval-deny-background"])!=null?xe:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Pe=t["--persona-components-attachment-image-background"])!=null?Pe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Be=t["--persona-components-attachment-image-border"])!=null?Be:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(te=t["--persona-semantic-typography-fontFamily"])!=null?te:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Ie=t["--persona-semantic-typography-fontSize"])!=null?Ie:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(K=t["--persona-semantic-typography-fontWeight"])!=null?K:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ce=t["--persona-semantic-typography-lineHeight"])!=null?ce: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"]=(we=t["--persona-palette-radius-sm"])!=null?we:"0.125rem",t["--persona-radius-md"]=(he=t["--persona-palette-radius-md"])!=null?he:"0.375rem",t["--persona-radius-lg"]=(Ce=t["--persona-palette-radius-lg"])!=null?Ce:"0.5rem",t["--persona-radius-xl"]=(Ve=t["--persona-palette-radius-xl"])!=null?Ve:"0.75rem",t["--persona-radius-full"]=(Y=t["--persona-palette-radius-full"])!=null?Y:"9999px",t["--persona-launcher-radius"]=(ae=(ne=t["--persona-components-launcher-borderRadius"])!=null?ne:t["--persona-palette-radius-full"])!=null?ae:"9999px",t["--persona-launcher-bg"]=(me=t["--persona-components-launcher-background"])!=null?me:t["--persona-primary"],t["--persona-launcher-fg"]=(le=t["--persona-components-launcher-foreground"])!=null?le:t["--persona-text-inverse"],t["--persona-launcher-border"]=(oe=t["--persona-components-launcher-border"])!=null?oe:t["--persona-border"],t["--persona-button-primary-bg"]=(Ye=t["--persona-components-button-primary-background"])!=null?Ye:t["--persona-primary"],t["--persona-button-primary-fg"]=(We=t["--persona-components-button-primary-foreground"])!=null?We:t["--persona-text-inverse"],t["--persona-button-radius"]=(X=(de=t["--persona-components-button-primary-borderRadius"])!=null?de:t["--persona-palette-radius-full"])!=null?X:"9999px",t["--persona-panel-radius"]=(Mt=($e=t["--persona-components-panel-borderRadius"])!=null?$e:t["--persona-radius-xl"])!=null?Mt:"0.75rem",t["--persona-panel-border"]=(pe=t["--persona-components-panel-border"])!=null?pe:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(kn=(ie=t["--persona-components-panel-shadow"])!=null?ie:t["--persona-palette-shadows-xl"])!=null?kn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(cn=(_t=t["--persona-components-input-borderRadius"])!=null?_t:t["--persona-radius-lg"])!=null?cn:"0.5rem",t["--persona-message-user-radius"]=(Yn=(Bn=t["--persona-components-message-user-borderRadius"])!=null?Bn:t["--persona-radius-lg"])!=null?Yn:"0.5rem",t["--persona-message-assistant-radius"]=(F=(qe=t["--persona-components-message-assistant-borderRadius"])!=null?qe:t["--persona-radius-lg"])!=null?F:"0.5rem",t["--persona-header-bg"]=(Se=t["--persona-components-header-background"])!=null?Se:t["--persona-surface"],t["--persona-header-border"]=(De=t["--persona-components-header-border"])!=null?De:t["--persona-divider"],t["--persona-header-icon-bg"]=(Ne=t["--persona-components-header-iconBackground"])!=null?Ne:t["--persona-primary"],t["--persona-header-icon-fg"]=(je=t["--persona-components-header-iconForeground"])!=null?je:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(pt=t["--persona-components-header-titleForeground"])!=null?pt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ot=t["--persona-components-header-subtitleForeground"])!=null?ot:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(St=t["--persona-components-header-actionIconForeground"])!=null?St:t["--persona-muted"];let r=(Ut=e.components)==null?void 0:Ut.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(z=e.components)==null?void 0:z.introCard;t["--persona-intro-card-bg"]=($t=t["--persona-components-introCard-background"])!=null?$t:t["--persona-surface"],t["--persona-intro-card-radius"]=(Ze=t["--persona-components-introCard-borderRadius"])!=null?Ze:"1rem",t["--persona-intro-card-padding"]=(Ft=t["--persona-components-introCard-padding"])!=null?Ft:"1.5rem",t["--persona-intro-card-shadow"]=(ge=(re=s==null?void 0:s.shadow)!=null?re:t["--persona-components-introCard-shadow"])!=null?ge:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(wt=t["--persona-components-input-background"])!=null?wt:t["--persona-surface"],t["--persona-input-placeholder"]=(qt=t["--persona-components-input-placeholder"])!=null?qt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(en=t["--persona-components-message-user-background"])!=null?en:t["--persona-accent"],t["--persona-message-user-text"]=(yn=t["--persona-components-message-user-text"])!=null?yn:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Tt=t["--persona-components-message-user-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Ct=t["--persona-components-message-assistant-background"])!=null?Ct:t["--persona-surface"],t["--persona-message-assistant-text"]=(ht=t["--persona-components-message-assistant-text"])!=null?ht:t["--persona-text"],t["--persona-message-assistant-border"]=(bt=t["--persona-components-message-assistant-border"])!=null?bt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Vt=t["--persona-components-message-assistant-shadow"])!=null?Vt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Dn=(nt=t["--persona-components-scrollToBottom-background"])!=null?nt:t["--persona-button-primary-bg"])!=null?Dn:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(bn=(Zn=t["--persona-components-scrollToBottom-foreground"])!=null?Zn:t["--persona-button-primary-fg"])!=null?bn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Nn=t["--persona-components-scrollToBottom-border"])!=null?Nn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(mt=t["--persona-components-scrollToBottom-size"])!=null?mt:"40px",t["--persona-scroll-to-bottom-radius"]=(yo=(Fn=(vr=t["--persona-components-scrollToBottom-borderRadius"])!=null?vr:t["--persona-button-radius"])!=null?Fn:t["--persona-radius-full"])!=null?yo:"9999px",t["--persona-scroll-to-bottom-shadow"]=(qo=(Ln=t["--persona-components-scrollToBottom-shadow"])!=null?Ln:t["--persona-palette-shadows-sm"])!=null?qo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(zr=t["--persona-components-scrollToBottom-padding"])!=null?zr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Mr=t["--persona-components-scrollToBottom-gap"])!=null?Mr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(On=(xt=t["--persona-components-scrollToBottom-fontSize"])!=null?xt:t["--persona-palette-typography-fontSize-sm"])!=null?On:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(_n=t["--persona-components-scrollToBottom-iconSize"])!=null?_n:"14px",t["--persona-tool-bubble-shadow"]=(xn=t["--persona-components-toolBubble-shadow"])!=null?xn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Pt=t["--persona-components-reasoningBubble-shadow"])!=null?Pt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(er=t["--persona-components-composer-shadow"])!=null?er:"none",t["--persona-md-inline-code-bg"]=(tr=t["--persona-components-markdown-inlineCode-background"])!=null?tr:t["--persona-container"],t["--persona-md-inline-code-color"]=($n=t["--persona-components-markdown-inlineCode-foreground"])!=null?$n:t["--persona-text"],t["--persona-md-link-color"]=(kr=(Vr=t["--persona-components-markdown-link-foreground"])!=null?Vr:t["--persona-accent"])!=null?kr:"#0f0f0f";let o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(Kr=t["--persona-components-markdown-codeBlock-background"])!=null?Kr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(jn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?jn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Rt=t["--persona-components-markdown-codeBlock-textColor"])!=null?Rt:"inherit",t["--persona-md-table-header-bg"]=(vn=t["--persona-components-markdown-table-headerBackground"])!=null?vn:t["--persona-container"],t["--persona-md-table-border-color"]=(nr=t["--persona-components-markdown-table-borderColor"])!=null?nr:t["--persona-border"],t["--persona-md-hr-color"]=(Jr=t["--persona-components-markdown-hr-color"])!=null?Jr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Lr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Lr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Gr=t["--persona-components-markdown-blockquote-background"])!=null?Gr:"transparent",t["--persona-md-blockquote-text-color"]=(wr=t["--persona-components-markdown-blockquote-textColor"])!=null?wr:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Un=t["--persona-components-collapsibleWidget-container"])!=null?Un:t["--persona-surface"],t["--cw-surface"]=(dr=t["--persona-components-collapsibleWidget-surface"])!=null?dr:t["--persona-surface"],t["--cw-border"]=(ft=t["--persona-components-collapsibleWidget-border"])!=null?ft:t["--persona-border"],t["--persona-message-border"]=(Gt=t["--persona-components-message-border"])!=null?Gt:t["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(t["--persona-icon-btn-bg"]=m.background),m.border&&(t["--persona-icon-btn-border"]=m.border),m.color&&(t["--persona-icon-btn-color"]=m.color),m.padding&&(t["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(t["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(t["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(t["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(t["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(t["--persona-label-btn-bg"]=g.background),g.border&&(t["--persona-label-btn-border"]=g.border),g.color&&(t["--persona-label-btn-color"]=g.color),g.padding&&(t["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(t["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(t["--persona-label-btn-gap"]=g.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(t["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(t["--persona-toggle-group-radius"]=u.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let T=v.toolbar;T.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=T.toggleGroupGap),T.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=T.copyBorderRadius),T.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,t["--persona-dropdown-bg"]=(Xt=t["--persona-dropdown-bg"])!=null?Xt:T.copyMenuBackground),T.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,t["--persona-dropdown-border"]=(qn=t["--persona-dropdown-border"])!=null?qn:T.copyMenuBorder),T.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,t["--persona-dropdown-shadow"]=(Xr=t["--persona-dropdown-shadow"])!=null?Xr:T.copyMenuShadow),T.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(rr=t["--persona-dropdown-radius"])!=null?rr:T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(pr=t["--persona-dropdown-item-hover-bg"])!=null?pr:T.copyMenuItemHoverBackground),T.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(v!=null&&v.tab){let T=v.tab;T.background&&(t["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(t["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(t["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(t["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(t["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(t["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(t["--persona-artifact-tab-list-padding"]=T.listPadding)}if(v!=null&&v.pane){let T=v.pane;if(T.toolbarBackground){let Vn=(zn=ss(e,T.toolbarBackground))!=null?zn:T.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Vn}}return t}var Cu={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 Kg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Au=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Js=()=>{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"},Jg=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Js()},nl=e=>Jg(e),Gg=e=>as(e),Xg=e=>{var t;let n=as(void 0,{validate:!1});return as({...e,palette:{...n.palette,colors:{...Kg.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},is=e=>{let n=nl(e),t=Au(e==null?void 0:e.theme),r=Au(e==null?void 0:e.darkTheme);return n==="dark"?Xg(Ks(t!=null?t:{},r!=null?r:{})):Gg(t)},Qg=e=>ni(e),ao=(e,n)=>{var o;let t=is(n),r=Qg(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},ri=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Js())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Js());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};var Su=require("idiomorph"),oi=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Su.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var si={index:-1,draft:""};function Tu(e){let{direction:n,history:t,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(t.length===0)return{handled:!1,state:o};if(n==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<t.length-1){let i=o.index+1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...si}}}function Eu(e,n){var t,r,s,o,a,i,d,l,p,m,g,u,v,x,A,E,B,P,I,R,w,W,_,$,D,U,V,se,Re,Ue,Fe,fe,xe,Pe,Be,te,Ie,K;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(m=e.approval)==null?void 0:m.status)!=null?g:"",(v=(u=e.toolCall)==null?void 0:u.status)!=null?v:"",(A=(x=e.toolCall)==null?void 0:x.name)!=null?A:"",(P=(B=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:B.length)!=null?P:0,(W=(w=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?W:"",typeof((_=e.toolCall)==null?void 0:_.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(V=(U=(D=e.reasoning)==null?void 0:D.chunks)==null?void 0:U.length)!=null?V:0,(Fe=(Ue=(Re=(se=e.reasoning)==null?void 0:se.chunks)==null?void 0:Re[e.reasoning.chunks.length-1])==null?void 0:Ue.length)!=null?Fe:0,(Be=(Pe=(xe=(fe=e.reasoning)==null?void 0:fe.chunks)==null?void 0:xe[e.reasoning.chunks.length-1])==null?void 0:Pe.slice(-32))!=null?Be:"",(Ie=(te=e.contentParts)==null?void 0:te.length)!=null?Ie:0,(K=e.stopReason)!=null?K:"",n].join("\0")}function Mu(){return new Map}function ku(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Lu(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Pu(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function ai(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function Gs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Xs(e,n){return Gs(e)-e.scrollTop<=n}function ii(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=t-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!n&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:n&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:n&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function li(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>0&&r?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,io=hn+1;var Qs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Yg=["pre","code","a","script","style"],ci=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:Qs.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:Qs.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Qs.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Qs.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Qs.buffer}},Wu=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Ys=new Map;for(let e of Wu)Ys.set(e.name,e);var Ru=e=>{Ys.set(e.name,e)},Hu=e=>{Wu.some(n=>n.name===e)||Ys.delete(e)},Bu=()=>Array.from(Ys.keys()),Zs=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Ys.get(e))!=null?r:null},di=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
|
|
15
|
-
`);return o<0?"":e.slice(0,o)}return e},
|
|
14
|
+
_Details: ${n.message}_`:r}var os=class e{constructor(t={},n){this.config=t;this.callbacks=n;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.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,r,s,o,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&_s(p.name)&&this.enqueueWebMcpAwait(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ro(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Vs((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,r,s;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Do(o);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,g,u,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let A=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(E=>E.role==="assistant"))==null?void 0:v.id;A&&this.ttsSpokenMessageIds.add(A)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),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(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,s,o,a,i,d,l,p;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:((s=t.runtype)==null?void 0:s.clientToken)||"",host:(o=t.runtype)==null?void 0:o.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(p=t.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Ro(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=t,u={id:a!=null?a:n==="user"?rs():n==="assistant"?Ho():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(u),u}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:g,rawContent:u}=r,x={id:d!=null?d:s==="user"?rs():s==="assistant"?Ho():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,l={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,m,g,u;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=rs(),o=Ho(),a={id:s,role:"user",content:r||Ja,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.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 x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let A=xu(v,this.config.errorMessage);if(A){let E={id:o,role:"assistant",createdAt:new Date().toISOString(),content:A,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,v):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=Ho();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=xu(l,this.config.errorMessage);if(m){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n){var d,l,p,m;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let g;if(i?g=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):g=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),g){let u=null;if(g instanceof Response){if(!g.ok){let v=await g.json().catch(()=>null);throw new Error((l=v==null?void 0:v.error)!=null?l:`Approval request failed: ${g.status}`)}u=g.body}else g instanceof ReadableStream&&(u=g);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(g){let u=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||(m=(p=this.callbacks).onError)==null||m.call(p,g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,g,u,v,x,A,E,B,P,I,R;let r=this.messages.find(w=>w.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=t.agentMetadata)==null?void 0:m.executionId,o=(g=t.toolCall)==null?void 0:g.name;if(!s||!o){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let w=(x=t.toolCall)==null?void 0:x.args,W=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(W.length===1){let $=typeof((A=W[0])==null?void 0:A.question)=="string"?W[0].question:"";$&&(a={[$]:n})}}this.markAskUserQuestionResolved(t,a),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(B=t.toolCall)==null?void 0:B.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof n=="string"?n:Object.entries(n).map(([W,$])=>`${W}: ${Array.isArray($)?$.join(", "):$}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((W,$)=>{let _=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!_)return;let D=w[_],U=Array.isArray(D)?D.join(", "):typeof D=="string"?D:"";this.appendMessage({id:`ask-user-q-${i}-${$}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${$}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(s,{[o]:n});if(!w.ok){let W=await w.json().catch(()=>null);throw new Error((P=W==null?void 0:W.error)!=null?P:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let W=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(R=(I=this.callbacks).onError)==null||R.call(I,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{var B,P,I,R,w,W,$;let m=(B=p.toolCall)==null?void 0:B.name,g=(P=p.toolCall)==null?void 0:P.id;if(!m||!g)return null;let u=`${t}:${g}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u))return null;this.webMcpInflightKeys.add(u),r.push(u),this.upsertMessage({...p,agentMetadata:{...p.agentMetadata,awaitingLocalTool:!1}});let v=new AbortController;this.webMcpResolveControllers.add(v),s.push(v);let x=(R=(I=p.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?R:m,A=this.client.executeWebMcpToolCall(m,(w=p.toolCall)==null?void 0:w.args,v.signal),E;if(!A)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await A}catch(_){return _ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"))||($=(W=this.callbacks).onError)==null||$.call(W,_ instanceof Error?_:new Error(String(_))),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:x,output:E}}));try{let p=a.filter(u=>u!==null);if(p.length===0)return;let m={};for(let u of p)m[u.resumeKey]=u.output;let g=await this.client.resumeFlow(t,m,{signal:o.signal});if(!g.ok){let u=await g.json().catch(()=>null);throw new Error((i=u==null?void 0:u.error)!=null?i:`Resume failed: ${g.status}`)}for(let u of p)this.webMcpResolvedKeys.add(u.dedupeKey);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(p){p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,p instanceof Error?p:new Error(String(p)))}finally{for(let p of r)this.webMcpInflightKeys.delete(p);for(let p of s)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var p,m,g,u,v,x,A,E,B,P,I,R;let n=(p=t.agentMetadata)==null?void 0:p.executionId,r=(m=t.toolCall)==null?void 0:m.name,s=(g=t.toolCall)==null?void 0:g.id;if(!n){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let w=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return;this.webMcpInflightKeys.add(w);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(w)}catch(W){(A=(x=this.callbacks).onError)==null||A.call(x,W instanceof Error?W:new Error(String(W)))}finally{this.webMcpInflightKeys.delete(w)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(E=t.toolCall)==null?void 0:E.args,l=this.client.executeWebMcpToolCall(r,d,i);try{let w;if(l?w=await l:w={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let W=(P=(B=t.agentMetadata)==null?void 0:B.webMcpToolCallId)!=null?P:r;await this.resumeWithToolOutput(n,W,w,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o)},signal:i})}catch(w){w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"))||(R=(I=this.callbacks).onError)==null||R.call(I,w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t),o=r.getVoices();if(n.voice){let a=o.find(i=>i.name===n.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=n.pickVoice?n.pickVoice(o):e.pickBestVoice(o));n.rate!==void 0&&(s.rate=n.rate),n.pitch!==void 0&&(s.pitch=n.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(t){var r;let n=["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 n){let o=t.find(a=>a.name===s);if(o)return o}return(r=t.find(s=>s.lang.startsWith("en")))!=null?r:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,m,g,u,v,x;if(o!==r)return s;let a={...s,...n};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=n.toolCall)==null?void 0:m.name,d=(g=n.agentMetadata)==null?void 0:g.executionId,l=(u=n.toolCall)==null?void 0:u.id;if(i&&_s(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let A=`${d}:${l}`;(this.webMcpInflightKeys.has(A)||this.webMcpResolvedKeys.has(A))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,l;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Tr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var C=require("lucide"),Ug={activity:C.Activity,"arrow-down":C.ArrowDown,"arrow-up":C.ArrowUp,"arrow-up-right":C.ArrowUpRight,bot:C.Bot,"chevron-down":C.ChevronDown,"chevron-up":C.ChevronUp,"chevron-right":C.ChevronRight,"chevron-left":C.ChevronLeft,check:C.Check,clipboard:C.Clipboard,"clipboard-copy":C.ClipboardCopy,copy:C.Copy,file:C.File,"file-code":C.FileCode,"file-spreadsheet":C.FileSpreadsheet,"file-text":C.FileText,"image-plus":C.ImagePlus,loader:C.Loader,"loader-circle":C.LoaderCircle,mic:C.Mic,paperclip:C.Paperclip,"refresh-cw":C.RefreshCw,search:C.Search,send:C.Send,"shield-alert":C.ShieldAlert,"shield-check":C.ShieldCheck,"shield-x":C.ShieldX,square:C.Square,"thumbs-down":C.ThumbsDown,"thumbs-up":C.ThumbsUp,upload:C.Upload,"volume-2":C.Volume2,x:C.X,user:C.User,mail:C.Mail,phone:C.Phone,calendar:C.Calendar,clock:C.Clock,building:C.Building,"map-pin":C.MapPin,lock:C.Lock,key:C.Key,"credit-card":C.CreditCard,"at-sign":C.AtSign,hash:C.Hash,globe:C.Globe,link:C.Link,"circle-check":C.CircleCheck,"circle-x":C.CircleX,"triangle-alert":C.TriangleAlert,info:C.Info,ban:C.Ban,shield:C.Shield,"arrow-left":C.ArrowLeft,"arrow-right":C.ArrowRight,"external-link":C.ExternalLink,ellipsis:C.Ellipsis,"ellipsis-vertical":C.EllipsisVertical,menu:C.Menu,house:C.House,plus:C.Plus,minus:C.Minus,pencil:C.Pencil,trash:C.Trash,"trash-2":C.Trash2,save:C.Save,download:C.Download,share:C.Share,funnel:C.Funnel,settings:C.Settings,"rotate-cw":C.RotateCw,maximize:C.Maximize,minimize:C.Minimize,"shopping-cart":C.ShoppingCart,"shopping-bag":C.ShoppingBag,package:C.Package,truck:C.Truck,tag:C.Tag,gift:C.Gift,receipt:C.Receipt,wallet:C.Wallet,store:C.Store,"dollar-sign":C.DollarSign,percent:C.Percent,play:C.Play,pause:C.Pause,"volume-x":C.VolumeX,camera:C.Camera,image:C.Image,film:C.Film,headphones:C.Headphones,"message-circle":C.MessageCircle,"message-square":C.MessageSquare,bell:C.Bell,heart:C.Heart,star:C.Star,eye:C.Eye,"eye-off":C.EyeOff,bookmark:C.Bookmark,"calendar-days":C.CalendarDays,history:C.History,timer:C.Timer,folder:C.Folder,"folder-open":C.FolderOpen,files:C.Files,sparkles:C.Sparkles,zap:C.Zap,sun:C.Sun,moon:C.Moon,flag:C.Flag,monitor:C.Monitor,smartphone:C.Smartphone},be=(e,t=24,n="currentColor",r=2)=>{let s=Ug[e];return s?qg(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function qg(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),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)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),s.appendChild(d)}),s}var Za={allowedTypes:Or,maxFileSize:10*1024*1024,maxFiles:4};function zg(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Vg(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-code":"file"}var No=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Za.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Za.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:Za.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Za.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,s,o,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=yu(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,m);continue}try{let m=await hu(l),g=Ga(l)?URL.createObjectURL(l):null,u={id:zg(),file:l,previewUrl:g,contentPart:m};this.attachments.push(u),this.renderPreview(u)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ga(t.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=h("img");a.src=t.previewUrl,a.alt=t.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",r.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=Vg(t.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=bu(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.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=be("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(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var vu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ks(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];vu(o)&&vu(s)?n[r]=Ks(o,s):n[r]=s}return n}var Xn="min(440px, calc(100vw - 24px))",ei="440px",Nt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Xn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},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 wu(e,t){if(!(!e&&!t))return e?t?Ks(e,t):e:t}function ti(e){var t,n,r,s,o,a,i,d,l,p,m,g,u,v,x,A,E,B,P,I,R;return e?{...Nt,...e,theme:wu(Nt.theme,e.theme),darkTheme:wu(Nt.darkTheme,e.darkTheme),launcher:{...Nt.launcher,...e.launcher,dock:{...(t=Nt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Nt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Nt.copy,...e.copy},sendButton:{...Nt.sendButton,...e.sendButton},statusIndicator:{...Nt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...e.voiceRecognition},features:(()=>{var xe,Pe,Be,te,Ie,K,ce,we;let w=(xe=Nt.features)==null?void 0:xe.artifacts,W=(Pe=e.features)==null?void 0:Pe.artifacts,$=(Be=Nt.features)==null?void 0:Be.scrollToBottom,_=(te=e.features)==null?void 0:te.scrollToBottom,D=(Ie=Nt.features)==null?void 0:Ie.streamAnimation,U=(K=e.features)==null?void 0:K.streamAnimation,V=(ce=Nt.features)==null?void 0:ce.askUserQuestion,se=(we=e.features)==null?void 0:we.askUserQuestion,Re=w===void 0&&W===void 0?void 0:{...w,...W,layout:{...w==null?void 0:w.layout,...W==null?void 0:W.layout}},Ue=$===void 0&&_===void 0?void 0:{...$,..._},Fe=D===void 0&&U===void 0?void 0:{...D,...U},fe=V===void 0&&se===void 0?void 0:{...V,...se,styles:{...V==null?void 0:V.styles,...se==null?void 0:se.styles}};return{...Nt.features,...e.features,...Ue!==void 0?{scrollToBottom:Ue}:{},...Re!==void 0?{artifacts:Re}:{},...Fe!==void 0?{streamAnimation:Fe}:{},...fe!==void 0?{askUserQuestion:fe}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Nt.suggestionChips,suggestionChipsConfig:{...Nt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Nt.layout,...e.layout,header:{...(a=Nt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Nt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(m=(p=Nt.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(u=(g=e.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(x=(v=Nt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(E=(A=e.layout)==null?void 0:A.messages)==null?void 0:E.timestamp}},slots:{...(B=Nt.layout)==null?void 0:B.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...Nt.markdown,...e.markdown,options:{...(I=Nt.markdown)==null?void 0:I.options,...(R=e.markdown)==null?void 0:R.options}},messageActions:{...Nt.messageActions,...e.messageActions}}:Nt}var Zi={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},el={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},tl={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Xn,maxWidth:ei,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function ss(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ss(e,r):r}function ni(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=ss(e,a);d!==void 0&&(t[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&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function nl(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Cu(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=Cu(o,s):n[r]=s}return n}function Kg(e,t){return t?Cu(e,t):e}function as(e,t={}){var s,o,a,i,d,l,p,m,g,u,v,x,A;let n={palette:Zi,semantic:el,components:tl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(A=e==null?void 0:e.semantic)==null?void 0:A.typography}},components:Kg(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=nl(r);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(B=>B.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)r=E.transform(r);return r}function ri(e){var x,A,E,B,P,I,R,w,W,$,_,D,U,V,se,Re,Ue,Fe,fe,xe,Pe,Be,te,Ie,K,ce,we,he,Ce,Ve,Y,ne,ae,me,le,oe,Ye,We,de,X,_e,Mt,pe,ie,kn,$t,cn,Bn,Yn,qe,F,Se,De,Ne,je,pt,ot,St,Ut,z,_t,Ze,Ft,re,ge,wt,qt,en,yn,Tt,Ct,ht,bt,Vt,nt,Dn,Zn,bn,Nn,mt,vr,Fn,yo,Ln,qo,zr,Mr,xt,On,$n,xn,Pt,er,tr,_n,Vr,kr,Kr,jn,Rt,vn,nr,Jr,Lr,Gr,wr,Un,dr,ft,Gt,Xt,qn,Xr,rr,pr,zn;let t=ni(e),n={};for(let[T,Vn]of Object.entries(t)){let ur=T.replace(/\./g,"-");n[`--persona-${ur}`]=Vn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(A=n["--persona-semantic-colors-secondary"])!=null?A:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(E=n["--persona-semantic-colors-accent"])!=null?E:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(B=n["--persona-semantic-colors-surface"])!=null?B:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(P=n["--persona-semantic-colors-background"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(I=n["--persona-semantic-colors-container"])!=null?I:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(R=n["--persona-semantic-colors-text"])!=null?R:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(w=n["--persona-semantic-colors-text-muted"])!=null?w:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(W=n["--persona-semantic-colors-text-inverse"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-border"]=($=n["--persona-semantic-colors-border"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(_=n["--persona-semantic-colors-divider"])!=null?_:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(D=n["--persona-components-voice-recording-indicator"])!=null?D:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(U=n["--persona-components-voice-recording-background"])!=null?U:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(V=n["--persona-components-voice-processing-icon"])!=null?V:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(se=n["--persona-components-voice-speaking-icon"])!=null?se:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Re=n["--persona-components-approval-requested-background"])!=null?Re:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Ue=n["--persona-components-approval-requested-border"])!=null?Ue:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Fe=n["--persona-components-approval-requested-text"])!=null?Fe:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(fe=n["--persona-components-approval-approve-background"])!=null?fe:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(xe=n["--persona-components-approval-deny-background"])!=null?xe:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Pe=n["--persona-components-attachment-image-background"])!=null?Pe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(Be=n["--persona-components-attachment-image-border"])!=null?Be:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(te=n["--persona-semantic-typography-fontFamily"])!=null?te:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Ie=n["--persona-semantic-typography-fontSize"])!=null?Ie:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(K=n["--persona-semantic-typography-fontWeight"])!=null?K:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(ce=n["--persona-semantic-typography-lineHeight"])!=null?ce:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(we=n["--persona-palette-radius-sm"])!=null?we:"0.125rem",n["--persona-radius-md"]=(he=n["--persona-palette-radius-md"])!=null?he:"0.375rem",n["--persona-radius-lg"]=(Ce=n["--persona-palette-radius-lg"])!=null?Ce:"0.5rem",n["--persona-radius-xl"]=(Ve=n["--persona-palette-radius-xl"])!=null?Ve:"0.75rem",n["--persona-radius-full"]=(Y=n["--persona-palette-radius-full"])!=null?Y:"9999px",n["--persona-launcher-radius"]=(ae=(ne=n["--persona-components-launcher-borderRadius"])!=null?ne:n["--persona-palette-radius-full"])!=null?ae:"9999px",n["--persona-launcher-bg"]=(me=n["--persona-components-launcher-background"])!=null?me:n["--persona-primary"],n["--persona-launcher-fg"]=(le=n["--persona-components-launcher-foreground"])!=null?le:n["--persona-text-inverse"],n["--persona-launcher-border"]=(oe=n["--persona-components-launcher-border"])!=null?oe:n["--persona-border"],n["--persona-button-primary-bg"]=(Ye=n["--persona-components-button-primary-background"])!=null?Ye:n["--persona-primary"],n["--persona-button-primary-fg"]=(We=n["--persona-components-button-primary-foreground"])!=null?We:n["--persona-text-inverse"],n["--persona-button-radius"]=(X=(de=n["--persona-components-button-primary-borderRadius"])!=null?de:n["--persona-palette-radius-full"])!=null?X:"9999px",n["--persona-panel-radius"]=(Mt=(_e=n["--persona-components-panel-borderRadius"])!=null?_e:n["--persona-radius-xl"])!=null?Mt:"0.75rem",n["--persona-panel-border"]=(pe=n["--persona-components-panel-border"])!=null?pe:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(kn=(ie=n["--persona-components-panel-shadow"])!=null?ie:n["--persona-palette-shadows-xl"])!=null?kn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(cn=($t=n["--persona-components-input-borderRadius"])!=null?$t:n["--persona-radius-lg"])!=null?cn:"0.5rem",n["--persona-message-user-radius"]=(Yn=(Bn=n["--persona-components-message-user-borderRadius"])!=null?Bn:n["--persona-radius-lg"])!=null?Yn:"0.5rem",n["--persona-message-assistant-radius"]=(F=(qe=n["--persona-components-message-assistant-borderRadius"])!=null?qe:n["--persona-radius-lg"])!=null?F:"0.5rem",n["--persona-header-bg"]=(Se=n["--persona-components-header-background"])!=null?Se:n["--persona-surface"],n["--persona-header-border"]=(De=n["--persona-components-header-border"])!=null?De:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ne=n["--persona-components-header-iconBackground"])!=null?Ne:n["--persona-primary"],n["--persona-header-icon-fg"]=(je=n["--persona-components-header-iconForeground"])!=null?je:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(pt=n["--persona-components-header-titleForeground"])!=null?pt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(ot=n["--persona-components-header-subtitleForeground"])!=null?ot:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(St=n["--persona-components-header-actionIconForeground"])!=null?St:n["--persona-muted"];let r=(Ut=e.components)==null?void 0:Ut.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(z=e.components)==null?void 0:z.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(Ze=n["--persona-components-introCard-borderRadius"])!=null?Ze:"1rem",n["--persona-intro-card-padding"]=(Ft=n["--persona-components-introCard-padding"])!=null?Ft:"1.5rem",n["--persona-intro-card-shadow"]=(ge=(re=s==null?void 0:s.shadow)!=null?re:n["--persona-components-introCard-shadow"])!=null?ge:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(wt=n["--persona-components-input-background"])!=null?wt:n["--persona-surface"],n["--persona-input-placeholder"]=(qt=n["--persona-components-input-placeholder"])!=null?qt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(en=n["--persona-components-message-user-background"])!=null?en:n["--persona-accent"],n["--persona-message-user-text"]=(yn=n["--persona-components-message-user-text"])!=null?yn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Tt=n["--persona-components-message-user-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Ct=n["--persona-components-message-assistant-background"])!=null?Ct:n["--persona-surface"],n["--persona-message-assistant-text"]=(ht=n["--persona-components-message-assistant-text"])!=null?ht:n["--persona-text"],n["--persona-message-assistant-border"]=(bt=n["--persona-components-message-assistant-border"])!=null?bt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Vt=n["--persona-components-message-assistant-shadow"])!=null?Vt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Dn=(nt=n["--persona-components-scrollToBottom-background"])!=null?nt:n["--persona-button-primary-bg"])!=null?Dn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(bn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?bn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Nn=n["--persona-components-scrollToBottom-border"])!=null?Nn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(mt=n["--persona-components-scrollToBottom-size"])!=null?mt:"40px",n["--persona-scroll-to-bottom-radius"]=(yo=(Fn=(vr=n["--persona-components-scrollToBottom-borderRadius"])!=null?vr:n["--persona-button-radius"])!=null?Fn:n["--persona-radius-full"])!=null?yo:"9999px",n["--persona-scroll-to-bottom-shadow"]=(qo=(Ln=n["--persona-components-scrollToBottom-shadow"])!=null?Ln:n["--persona-palette-shadows-sm"])!=null?qo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(zr=n["--persona-components-scrollToBottom-padding"])!=null?zr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Mr=n["--persona-components-scrollToBottom-gap"])!=null?Mr:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(On=(xt=n["--persona-components-scrollToBottom-fontSize"])!=null?xt:n["--persona-palette-typography-fontSize-sm"])!=null?On:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=($n=n["--persona-components-scrollToBottom-iconSize"])!=null?$n:"14px",n["--persona-tool-bubble-shadow"]=(xn=n["--persona-components-toolBubble-shadow"])!=null?xn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Pt=n["--persona-components-reasoningBubble-shadow"])!=null?Pt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(er=n["--persona-components-composer-shadow"])!=null?er:"none",n["--persona-md-inline-code-bg"]=(tr=n["--persona-components-markdown-inlineCode-background"])!=null?tr:n["--persona-container"],n["--persona-md-inline-code-color"]=(_n=n["--persona-components-markdown-inlineCode-foreground"])!=null?_n:n["--persona-text"],n["--persona-md-link-color"]=(kr=(Vr=n["--persona-components-markdown-link-foreground"])!=null?Vr:n["--persona-accent"])!=null?kr:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(Kr=n["--persona-components-markdown-codeBlock-background"])!=null?Kr:n["--persona-container"],n["--persona-md-code-block-border-color"]=(jn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?jn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Rt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Rt:"inherit",n["--persona-md-table-header-bg"]=(vn=n["--persona-components-markdown-table-headerBackground"])!=null?vn:n["--persona-container"],n["--persona-md-table-border-color"]=(nr=n["--persona-components-markdown-table-borderColor"])!=null?nr:n["--persona-border"],n["--persona-md-hr-color"]=(Jr=n["--persona-components-markdown-hr-color"])!=null?Jr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Lr=n["--persona-components-markdown-blockquote-borderColor"])!=null?Lr:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Gr=n["--persona-components-markdown-blockquote-background"])!=null?Gr:"transparent",n["--persona-md-blockquote-text-color"]=(wr=n["--persona-components-markdown-blockquote-textColor"])!=null?wr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(Un=n["--persona-components-collapsibleWidget-container"])!=null?Un:n["--persona-surface"],n["--cw-surface"]=(dr=n["--persona-components-collapsibleWidget-surface"])!=null?dr:n["--persona-surface"],n["--cw-border"]=(ft=n["--persona-components-collapsibleWidget-border"])!=null?ft:n["--persona-border"],n["--persona-message-border"]=(Gt=n["--persona-components-message-border"])!=null?Gt:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let T=v.toolbar;T.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=T.toggleGroupGap),T.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=T.copyBorderRadius),T.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,n["--persona-dropdown-bg"]=(Xt=n["--persona-dropdown-bg"])!=null?Xt:T.copyMenuBackground),T.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:T.copyMenuBorder),T.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,n["--persona-dropdown-shadow"]=(Xr=n["--persona-dropdown-shadow"])!=null?Xr:T.copyMenuShadow),T.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(rr=n["--persona-dropdown-radius"])!=null?rr:T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(pr=n["--persona-dropdown-item-hover-bg"])!=null?pr:T.copyMenuItemHoverBackground),T.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(v!=null&&v.tab){let T=v.tab;T.background&&(n["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(n["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(n["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(n["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(n["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(n["--persona-artifact-tab-list-padding"]=T.listPadding)}if(v!=null&&v.pane){let T=v.pane;if(T.toolbarBackground){let Vn=(zn=ss(e,T.toolbarBackground))!=null?zn:T.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Vn}}return n}var Au={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 Jg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Su=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Js=()=>{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"},Gg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Js()},rl=e=>Gg(e),Xg=e=>as(e),Qg=e=>{var n;let t=as(void 0,{validate:!1});return as({...e,palette:{...t.palette,colors:{...Jg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},is=e=>{let t=rl(e),n=Su(e==null?void 0:e.theme),r=Su(e==null?void 0:e.darkTheme);return t==="dark"?Qg(Ks(n!=null?n:{},r!=null?r:{})):Xg(n)},Yg=e=>ri(e),ao=(e,t)=>{var o;let n=is(t),r=Yg(n);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=t==null?void 0:t.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},oi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Js())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Js());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var Tu=require("idiomorph"),si=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Tu.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var ai={index:-1,draft:""};function Eu(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...ai}}}function Mu(e,t){var n,r,s,o,a,i,d,l,p,m,g,u,v,x,A,E,B,P,I,R,w,W,$,_,D,U,V,se,Re,Ue,Fe,fe,xe,Pe,Be,te,Ie,K;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(m=e.approval)==null?void 0:m.status)!=null?g:"",(v=(u=e.toolCall)==null?void 0:u.status)!=null?v:"",(A=(x=e.toolCall)==null?void 0:x.name)!=null?A:"",(P=(B=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:B.length)!=null?P:0,(W=(w=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?W:"",typeof(($=e.toolCall)==null?void 0:$.args)=="string"?e.toolCall.args.length:(_=e.toolCall)!=null&&_.args?JSON.stringify(e.toolCall.args).length:0,(V=(U=(D=e.reasoning)==null?void 0:D.chunks)==null?void 0:U.length)!=null?V:0,(Fe=(Ue=(Re=(se=e.reasoning)==null?void 0:se.chunks)==null?void 0:Re[e.reasoning.chunks.length-1])==null?void 0:Ue.length)!=null?Fe:0,(Be=(Pe=(xe=(fe=e.reasoning)==null?void 0:fe.chunks)==null?void 0:xe[e.reasoning.chunks.length-1])==null?void 0:Pe.slice(-32))!=null?Be:"",(Ie=(te=e.contentParts)==null?void 0:te.length)!=null?Ie:0,(K=e.stopReason)!=null?K:"",t].join("\0")}function ku(){return new Map}function Lu(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Pu(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Iu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ii(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Gs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Xs(e,t){return Gs(e)-e.scrollTop<=t}function li(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function ci(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,io=hn+1;var Qs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Zg=["pre","code","a","script","style"],di=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Qs.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Qs.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Qs.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Qs.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Qs.buffer}},Ru=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Ys=new Map;for(let e of Ru)Ys.set(e.name,e);var Hu=e=>{Ys.set(e.name,e)},Bu=e=>{Ru.some(t=>t.name===e)||Ys.delete(e)},Du=()=>Array.from(Ys.keys()),Zs=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=Ys.get(e))!=null?r:null},pi=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
|
|
15
|
+
`);return o<0?"":e.slice(0,o)}return e},ef=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},tf=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},ol=/\s/,nf=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},rf=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(ol.test(o[i])){let l=i;for(;l<o.length&&ol.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<o.length&&!ol.test(o[p]);)l.appendChild(ef(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}s.replaceChild(a,e)},of=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(tf(r,l,t,n.value)),n.value+=1));s.replaceChild(a,e)},ea=(e,t,n,r)=>{var m,g;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((m=r==null?void 0:r.skipTags)!=null?m:Zg).map(u=>u.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)nf(d,o)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?rf:of;for(let u of i)p(u,n,l);return s.innerHTML},ui=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ta=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Wu=new WeakMap,sf=(e,t)=>{var o;if(!e.styles)return;let n=Wu.get(t);if(n||(n=new Set,Wu.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},sl=new WeakMap,af=(e,t)=>{if(!e.onAttach)return;let n=sl.get(t);if(n||(n=new Map,sl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Nu=e=>{let t=sl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},al=(e,t)=>{sf(e,t),af(e,t)};function il(e,t=hn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var na=0,lo=null;function ll(e=document){var n;if(na++,na===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;lo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,na=Math.max(0,na-1),na===0&&lo)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=lo.originalOverflow,s.style.position=lo.originalPosition,s.style.top=lo.originalTop,s.style.width=lo.originalWidth,o.scrollTo(0,lo.scrollY),lo=null}}}var mi={side:"right",width:"420px",animate:!0,reveal:"resize"},rn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},co=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},ir=e=>{var n,r,s,o,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:mi.side,width:(s=t==null?void 0:t.width)!=null?s:mi.width,animate:(o=t==null?void 0:t.animate)!=null?o:mi.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:mi.reveal}};var xr={"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 ra=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
|
|
16
16
|
<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>
|
|
17
17
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
18
18
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -20,14 +20,14 @@ _Details: ${t.message}_`:r}var os=class e{constructor(n={},t){this.config=n;this
|
|
|
20
20
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
21
21
|
</span>
|
|
22
22
|
<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>
|
|
23
|
-
`,t.addEventListener("click",n);let r=o=>{var P,I,R,w,W,_,$,D,U,V,se,Re,Ue,Fe;let a=(P=o.launcher)!=null?P:{},i=rn(o),d=t.querySelector("[data-role='launcher-title']");if(d){let fe=(I=a.title)!=null?I:"Chat Assistant";d.textContent=fe,d.setAttribute("title",fe)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let fe=(R=a.subtitle)!=null?R:"Get answers fast";l.textContent=fe,l.setAttribute("title",fe)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=t.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let fe=(w=a.agentIconSize)!=null?w:"40px";if(m.style.height=fe,m.style.width=fe,m.innerHTML="",a.agentIconName){let xe=parseFloat(fe)||24,Pe=be(a.agentIconName,xe*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(m.appendChild(Pe),m.style.display=""):(m.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(_=a.agentIconText)!=null?_:"\u{1F4AC}",m.style.display="")}let g=t.querySelector("[data-role='launcher-image']");if(g){let fe=($=a.agentIconSize)!=null?$:"40px";g.style.height=fe,g.style.width=fe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let u=t.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let fe=(D=a.callToActionIconSize)!=null?D:"32px";u.style.height=fe,u.style.width=fe,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let xe=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,xe=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let Pe=parseFloat(fe)||24,Be=Math.max(Pe-xe,8),te=be(a.callToActionIconName,Be,"currentColor",2);te?u.appendChild(te):u.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else u.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let v=a.position&&xr[a.position]?xr[a.position]:xr["bottom-right"],x="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",A="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?A:`${x} ${v}`,i||(t.style.zIndex=String((se=a.zIndex)!=null?se:hn));let E="1px solid var(--persona-border, #e5e7eb)",B="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Re=a.border)!=null?Re:E,t.style.boxShadow=(Ue=a.shadow)!=null?Ue:B,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=(Fe=a.collapsedMaxWidth)!=null?Fe:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var af="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",mi=(e,n={})=>{var x,A,E,B,P,I;let{showClose:t=!0,wrapperClassName:r=af,buttonSize:s,iconSize:o="28px"}=n,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(A=s!=null?s:a.closeButtonSize)!=null?A:"32px",d=h("div",r),l=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");l.style.height=i,l.style.width=i,l.type="button";let p=(E=a.closeButtonTooltipText)!=null?E:"Close chat",m=(B=a.closeButtonShowTooltip)!=null?B:!0;l.setAttribute("aria-label",p),l.style.display=t?"":"none";let g=(P=a.closeButtonIconName)!=null?P:"x",u=(I=a.closeButtonIconText)!=null?I:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let v=be(g,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=u,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let R=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${R} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&p){let R=null,w=()=>{if(R)return;let _=l.ownerDocument,$=_.body;if(!$)return;R=Tr(_,"div","persona-clear-chat-tooltip"),R.textContent=p;let D=Tr(_,"div");D.className="persona-clear-chat-tooltip-arrow",R.appendChild(D);let U=l.getBoundingClientRect();R.style.position="fixed",R.style.zIndex=String(io),R.style.left=`${U.left+U.width/2}px`,R.style.top=`${U.top-8}px`,R.style.transform="translate(-50%, -100%)",$.appendChild(R)},W=()=>{R&&R.parentNode&&(R.parentNode.removeChild(R),R=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",W),l.addEventListener("focus",w),l.addEventListener("blur",W),d._cleanupTooltip=()=>{W(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",W),l.removeEventListener("focus",w),l.removeEventListener("blur",W)}}return{button:l,wrapper:d}},lf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",gi=(e,n={})=>{var R,w,W,_,$,D,U,V,se,Re,Ue,Fe,fe;let{wrapperClassName:t=lf,buttonSize:r,iconSize:s="20px"}=n,a=(w=((R=e==null?void 0:e.launcher)!=null?R:{}).clearChat)!=null?w:{},i=(W=r!=null?r:a.size)!=null?W:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",l=($=a.iconColor)!=null?$:"",p=(D=a.backgroundColor)!=null?D:"",m=(U=a.borderWidth)!=null?U:"",g=(V=a.borderColor)!=null?V:"",u=(se=a.borderRadius)!=null?se:"",v=(Re=a.paddingX)!=null?Re:"",x=(Ue=a.paddingY)!=null?Ue:"",A=(Fe=a.tooltipText)!=null?Fe:"Clear chat",E=(fe=a.showTooltip)!=null?fe:!0,B=h("div",t),P=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");P.style.height=i,P.style.width=i,P.type="button",P.setAttribute("aria-label",A),P.style.color=l||Mn.actionIconColor;let I=be(d,s,"currentColor",1);if(I&&(I.style.display="block",P.appendChild(I)),p&&(P.style.backgroundColor=p,P.classList.remove("hover:persona-bg-gray-100")),m||g){let xe=m||"0px",Pe=g||"transparent";P.style.border=`${xe} solid ${Pe}`,P.classList.remove("persona-border-none")}if(u&&(P.style.borderRadius=u,P.classList.remove("persona-rounded-full")),v&&(P.style.paddingLeft=v,P.style.paddingRight=v),x&&(P.style.paddingTop=x,P.style.paddingBottom=x),B.appendChild(P),E&&A){let xe=null,Pe=()=>{if(xe)return;let te=P.ownerDocument,Ie=te.body;if(!Ie)return;xe=Tr(te,"div","persona-clear-chat-tooltip"),xe.textContent=A;let K=Tr(te,"div");K.className="persona-clear-chat-tooltip-arrow",xe.appendChild(K);let ce=P.getBoundingClientRect();xe.style.position="fixed",xe.style.zIndex=String(io),xe.style.left=`${ce.left+ce.width/2}px`,xe.style.top=`${ce.top-8}px`,xe.style.transform="translate(-50%, -100%)",Ie.appendChild(xe)},Be=()=>{xe&&xe.parentNode&&(xe.parentNode.removeChild(xe),xe=null)};B.addEventListener("mouseenter",Pe),B.addEventListener("mouseleave",Be),P.addEventListener("focus",Pe),P.addEventListener("blur",Be),B._cleanupTooltip=()=>{Be(),B.removeEventListener("mouseenter",Pe),B.removeEventListener("mouseleave",Be),P.removeEventListener("focus",Pe),P.removeEventListener("blur",Be)}}return{button:P,wrapper:B}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},_r=e=>{var R,w,W,_,$,D,U,V,se,Re,Ue,Fe,fe,xe,Pe,Be;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(R=n==null?void 0:n.launcher)!=null?R:{},o=(w=s.headerIconSize)!=null?w:"48px",a=(W=s.closeButtonPlacement)!=null?W:"inline",i=(_=s.headerIconHidden)!=null?_:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let te=parseFloat(o)||24,Ie=be(d,te*.6,"currentColor",1);Ie?l.replaceChildren(Ie):l.textContent=(D=($=n==null?void 0:n.launcher)==null?void 0:$.agentIconText)!=null?D:"\u{1F4AC}"}else if((U=n==null?void 0:n.launcher)!=null&&U.iconUrl){let te=h("img");te.src=n.launcher.iconUrl,te.alt="",te.className="persona-rounded-xl persona-object-cover",te.style.height=o,te.style.width=o,l.replaceChildren(te)}else l.textContent=(se=(V=n==null?void 0:n.launcher)==null?void 0:V.agentIconText)!=null?se:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=h("span","persona-text-base persona-font-semibold");m.style.color=Mn.titleColor,m.textContent=(Ue=(Re=n==null?void 0:n.launcher)==null?void 0:Re.title)!=null?Ue:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=Mn.subtitleColor,g.textContent=(fe=(Fe=n==null?void 0:n.launcher)==null?void 0:Fe.subtitle)!=null?fe:"Here to help you get answers fast",p.append(m,g),i?r.append(p):r.append(l,p);let u=(xe=s.clearChat)!=null?xe:{},v=(Pe=u.enabled)!=null?Pe:!0,x=(Be=u.placement)!=null?Be:"inline",A=null,E=null;if(v){let Ie=gi(n,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});A=Ie.button,E=Ie.wrapper,x==="top-right"&&(E.style.right="48px"),x==="inline"&&r.appendChild(E)}let B=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:I}=mi(n,{showClose:t,wrapperClassName:B});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:l,headerTitle:m,headerSubtitle:g,closeButton:P,closeButtonWrapper:I,clearChatButton:A,clearChatButtonWrapper:E}},Fo=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function po(e){let{items:n,onSelect:t,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(io)):(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 u of n){if(u.dividerBefore){let A=document.createElement("hr");a.appendChild(A)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",u.id),u.destructive&&v.setAttribute("data-destructive",""),u.icon){let A=be(u.icon,16,"currentColor",1.5);A&&v.appendChild(A)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",A=>{A.stopPropagation(),p(),t(u.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let u=r.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:g}}function jt(e){let{icon:n,label:t,size:r,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 l=be(n,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function oa(e){let{icon:n,label:t,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let p=h("button",l);if(p.type="button",p.setAttribute("aria-label",t),n){let g=be(n,o!=null?o:14,"currentColor",2);g&&p.appendChild(g)}let m=h("span");if(m.textContent=t,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))p.setAttribute(g,u);return p}function sa(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of n){let m;p.icon?m=jt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=h("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function l(p){a=p,d()}return{element:o,setSelected:l}}function fi(e){var u,v;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",n);let p=h("span","persona-combo-btn-label");p.textContent=n,l.appendChild(p);let m=be(t,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,A;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(A=d.border)!=null?A:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=po({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let A=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",A?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var ll=e=>{var r;let n=_r({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.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 n};function cf(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){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=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=be(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 l=po({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var cl=e=>{var B,P,I,R,w,W,_,$,D;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(B=n==null?void 0:n.launcher)!=null?B:{},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,l,p;if(d)l=fi({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,p=(I=l.querySelector(".persona-combo-btn-label"))!=null?I:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(R=a.title)!=null?R:"Chat Assistant",l.appendChild(p),cf(l,s==null?void 0:s.trailingActions,(w=s==null?void 0:s.onAction)!=null?w:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=s.onTitleClick;l.addEventListener("click",se=>{se.target.closest("button")||V()}),l.addEventListener("keydown",se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),V())})}let U=s==null?void 0:s.titleRowHover;U&&(l.style.borderRadius=(W=U.borderRadius)!=null?W:"10px",l.style.padding=(_=U.padding)!=null?_:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,se;l.style.backgroundColor=(V=U.background)!=null?V:"",l.style.borderColor=(se=U.border)!=null?se:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=($=a.closeButtonSize)!=null?$:"32px",g=h("div",""),u=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");u.style.height=m,u.style.width=m,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=t?"":"none",u.style.color=a.closeButtonColor||Mn.actionIconColor;let v=(D=a.closeButtonIconName)!=null?D:"x",x=be(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let A=h("div");A.style.display="none";let E=h("span");return E.style.display="none",{header:i,iconHolder:A,headerTitle:p,headerSubtitle:E,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},hi={default:ll,minimal:cl},dl=e=>{var n;return(n=hi[e])!=null?n:hi.default},ls=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let l=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),p=h("div");p.style.display="none";let m=h("span"),g=h("span"),u=h("button");u.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:u,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=dl(r)({config:e,showClose:(d=(i=n==null?void 0:n.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:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var yi=e=>{var a,i;let n=h("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;n.style.maxHeight=`${t*r}px`,n.style.overflowY="auto";let s=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},o=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,s());n.style.height=`${d}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:o}},bi=e=>{var R,w,W,_,$,D,U,V,se,Re,Ue,Fe;let n=(R=e==null?void 0:e.sendButton)!=null?R:{},t=(w=n.useIcon)!=null?w:!1,r=(W=n.iconText)!=null?W:"\u2191",s=n.iconName,o=(_=n.stopIconName)!=null?_:"square",a=($=n.tooltipText)!=null?$:"Send message",i=(D=n.stopTooltipText)!=null?D:"Stop generating",d=(V=(U=e==null?void 0:e.copy)==null?void 0:U.sendButtonLabel)!=null?V:"Send",l=(Re=(se=e==null?void 0:e.copy)==null?void 0:se.stopButtonLabel)!=null?Re:"Stop",p=(Ue=n.showTooltip)!=null?Ue:!1,m=(Fe=n.size)!=null?Fe:"40px",g=n.backgroundColor,u=n.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",t?"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");x.type="submit",x.setAttribute("data-persona-composer-submit","");let A=null,E=null;if(t){x.style.width=m,x.style.height=m,x.style.minWidth=m,x.style.minHeight=m,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",u?x.style.color=u:x.style.color="var(--persona-button-primary-fg, #ffffff)";let fe=parseFloat(m)||24,xe=(u==null?void 0:u.trim())||"currentColor";s?(A=be(s,fe,xe,2),A?x.appendChild(A):x.textContent=r):x.textContent=r,E=be(o,fe,xe,2),g?x.style.backgroundColor=g:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,u?x.style.color=u:x.classList.add("persona-text-white");n.borderWidth&&(x.style.borderWidth=n.borderWidth,x.style.borderStyle="solid"),n.borderColor&&(x.style.borderColor=n.borderColor),n.paddingX?(x.style.paddingLeft=n.paddingX,x.style.paddingRight=n.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),n.paddingY?(x.style.paddingTop=n.paddingY,x.style.paddingBottom=n.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let B=null;p&&a&&(B=h("div","persona-send-button-tooltip"),B.textContent=a,v.appendChild(B)),x.setAttribute("aria-label",a),v.appendChild(x);let P="send";return{button:x,wrapper:v,setMode:fe=>{if(fe===P)return;P=fe;let xe=fe==="stop"?i:a;if(x.setAttribute("aria-label",xe),B&&(B.textContent=xe),t){if(A&&E){let Pe=fe==="stop"?E:A;x.replaceChildren(Pe)}}else x.textContent=fe==="stop"?l:d}}},xi=e=>{var B,P,I,R,w,W,_,$,D,U,V,se;let n=(B=e==null?void 0:e.voiceRecognition)!=null?B:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((P=n.provider)==null?void 0:P.type)==="runtype";if(!(r||s))return null;let a=(R=(I=e==null?void 0:e.sendButton)==null?void 0:I.size)!=null?R:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=n.iconName)!=null?w:"mic",p=(W=n.iconSize)!=null?W:a,m=parseFloat(p)||24,g=($=n.backgroundColor)!=null?$:(_=e==null?void 0:e.sendButton)==null?void 0:_.backgroundColor,u=(U=n.iconColor)!=null?U:(D=e==null?void 0:e.sendButton)==null?void 0:D.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let x=be(l,m,u||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),n.borderWidth&&(d.style.borderWidth=n.borderWidth,d.style.borderStyle="solid"),n.borderColor&&(d.style.borderColor=n.borderColor),n.paddingX&&(d.style.paddingLeft=n.paddingX,d.style.paddingRight=n.paddingX),n.paddingY&&(d.style.paddingTop=n.paddingY,d.style.paddingBottom=n.paddingY),i.appendChild(d);let A=(V=n.tooltipText)!=null?V:"Start voice recognition";if(((se=n.showTooltip)!=null?se:!1)&&A){let Re=h("div","persona-send-button-tooltip");Re.textContent=A,i.appendChild(Re)}return{button:d,wrapper:i}},vi=e=>{var v,x,A,E,B,P,I,R;let n=(v=e==null?void 0:e.attachments)!=null?v:{};if(n.enabled!==!0)return null;let t=(A=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?A:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((E=n.allowedTypes)!=null?E:Or).join(","),s.multiple=((B=n.maxFiles)!=null?B:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(P=n.buttonTooltipText)!=null?P:"Attach file");let i=(I=n.buttonIconName)!=null?I:"paperclip",d=t,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=be(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),s.click()}),o.appendChild(a);let g=(R=n.buttonTooltipText)!=null?R:"Attach file",u=h("div","persona-send-button-tooltip");return u.textContent=g,o.appendChild(u),{button:a,wrapper:o,input:s,previewsContainer:r}},wi=e=>{var a,i,d;let n=(a=e==null?void 0:e.statusIndicator)!=null?a:{},t=n.align==="left"?"persona-text-left":n.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=n.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=n.idleText)!=null?d:"Online";if(n.idleLink){let l=h("a");l.href=n.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},Ci=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var cs=e=>{var v,x,A,E,B,P;let{config:n}=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 r=Ci(),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{textarea:o,attachAutoResize:a}=yi(n);a();let i=bi(n),d=xi(n),l=vi(n),p=wi(n);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let m=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),m.append(g,u),s.append(m),s.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(l==null?void 0:l.button)&&I.target!==(l==null?void 0:l.wrapper)&&o.focus()}),t.append(r,s,p),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(A=l==null?void 0:l.button)!=null?A:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:m,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var Nu=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let n=h("span","persona-pill-peek__icon"),t=be("message-square",16,"currentColor",1.5);t&&n.appendChild(t);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=be("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(n,r,s),{root:e,textNode:r}},Fu=e=>{var v,x,A,E,B,P;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=Ci();r.style.display="none";let s=wi(n);s.style.display="none";let{textarea:o,attachAutoResize:a}=yi(n);o.style.maxHeight="100px",a();let i=bi(n),d=xi(n),l=vi(n);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=h("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let g=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(l==null?void 0:l.button)&&I.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&p.append(l.input),p.append(m,o,g),l&&t.append(l.previewsContainer),t.append(p,r,s);let u=p;return{footer:t,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(A=l==null?void 0:l.button)!=null?A:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:u,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var Ou=e=>{var p,m,g,u,v,x,A,E,B,P,I,R,w,W,_,$,D;let n=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,t=rn(e);if(co(e)){let U=(u=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?u:{},V=h("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=U.expandedSize)!=null?v:"anchored",V.style.zIndex=String((A=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?A:hn);let se=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");se.style.width="100%",V.appendChild(se);let Re=h("div","persona-widget-pill-root");return Re.setAttribute("data-persona-composer-bar",""),Re.dataset.state="collapsed",Re.dataset.expandedSize=(E=U.expandedSize)!=null?E:"anchored",Re.style.zIndex=String((P=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?P:hn),{wrapper:V,panel:se,pillRoot:Re}}if(t){let U=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(V),{wrapper:U,panel:V}}if(!n){let U=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),se=(R=(I=e==null?void 0:e.launcher)==null?void 0:I.width)!=null?R:"100%";return U.style.width=se,V.style.width="100%",U.appendChild(V),{wrapper:U,panel:V}}let s=(w=e==null?void 0:e.launcher)!=null?w:{},o=s.position&&xr[s.position]?xr[s.position]:xr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((_=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?_:hn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(D=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?D:e==null?void 0:e.launcherWidth,l=d!=null?d:Xn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},df=(e,n)=>{var I,R,w,W,_,$,D,U,V;let t=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=mi(e,{showClose:n,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(w=(R=(I=e==null?void 0:e.launcher)==null?void 0:I.clearChat)==null?void 0:R.enabled)!=null?w:!0,a=null,i=null;if(o){let se=gi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=se.button,i=se.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=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");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(_=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?_:"Hello \u{1F44B}";let g=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(D=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",p.append(m,g);let u=h("div","persona-flex persona-flex-col persona-gap-3"),v=(U=e==null?void 0:e.layout)==null?void 0:U.contentMaxWidth;v&&(u.style.maxWidth=v,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,u);let A=h("div","persona-composer-overlay persona-pointer-events-none");A.setAttribute("data-persona-composer-overlay",""),A.style.position="absolute",A.style.left="0",A.style.right="0",A.style.bottom="0",A.style.zIndex="20";let E=Fu({config:e}),{root:B,textNode:P}=Nu();return t.append(d,s,l,A),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:u,composerOverlay:A,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:m,introSubtitle:g,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:B,peekTextNode:P}},_u=(e,n=!0)=>{var A,E,B,P,I,R,w,W,_;if(co(e))return df(e,n);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-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let r=(A=e==null?void 0:e.layout)==null?void 0:A.header,s=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,o=r?ls(e,r,{showClose:n}):_r({config:e,showClose:n}),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=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=rn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(P=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?P:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(R=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",i.append(d,l);let p=h("div","persona-flex persona-flex-col persona-gap-3"),m=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((W=e==null?void 0:e.copy)==null?void 0:W.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let u=cs({config:e}),v=((_=e==null?void 0:e.layout)==null?void 0:_.showFooter)!==!1;s?Fo(t,o,e):(o.header.style.display="none",Fo(t,o,e)),t.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(u.footer.style.display="none"),t.append(u.footer),t.append(x),{container:t,body:a,messagesWrapper:p,composerOverlay:x,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:d,introSubtitle:l,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:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var pf=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},uf=(e,n)=>{if(!e)return null;let t=pf(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},mf=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},gf=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},pl=e=>{let n=e.toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:text/html")||n.startsWith("data:text/javascript")||n.startsWith("data:text/xml")||n.startsWith("data:application/xhtml")||n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:")||!e.includes(":"))},ul=320,ju=320,ff=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),hf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="audio"&&typeof n.audio=="string"&&n.audio.trim().length>0),yf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="video"&&typeof n.video=="string"&&n.video.trim().length>0),bf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="file"&&typeof n.data=="string"&&n.data.trim().length>0),xf=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var m;let l=h("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${ul}px`,l.style.maxHeight=`${ju}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,l.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{p=!0}),gf(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},vf=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(r=>{if(!pl(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${ul}px`,n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},wf=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","video");let t=0;return e.forEach(r=>{if(!pl(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${ul}px`,s.style.maxHeight=`${ju}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Cf=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","files");let t=0;return e.forEach(r=>{if(!pl(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Oo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},ml=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Oo};if(n){let s=n(r);if(s!==null)return s}return Oo()},Af=(e,n)=>{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"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},$u=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Sf=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},gl=(e,n,t)=>{var u,v,x,A,E,B;let r=(u=n.showCopy)!=null?u:!0,s=(v=n.showUpvote)!=null?v:!0,o=(x=n.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let P=h("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let a=(A=n.visibility)!=null?A:"hover",i=(E=n.align)!=null?E:"right",d=(B=n.layout)!=null?B:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let g=(P,I,R)=>{let w=jt({icon:P,label:I,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",R),w};return r&&m.appendChild(g("copy","Copy message","copy")),s&&m.appendChild(g("thumbs-up","Upvote","upvote")),o&&m.appendChild(g("thumbs-down","Downvote","downvote")),m},ds=(e,n,t,r,s,o)=>{var te,Ie,K,ce,we,he,Ce,Ve,Y,ne,ae,me,le,oe,Ye,We,de;let a=t!=null?t:{},i=(te=a.layout)!=null?te:"bubble",d=a.avatar,l=a.timestamp,p=(Ie=d==null?void 0:d.show)!=null?Ie:!1,m=(K=l==null?void 0:l.show)!=null?K:!1,g=(ce=d==null?void 0:d.position)!=null?ce:"left",u=(we=l==null?void 0:l.position)!=null?we:"below",v=Sf(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let A=ff(e),E=(Ce=(he=e.content)==null?void 0:he.trim())!=null?Ce:"",P=A.length>0&&E===Ka,I=ci((Y=(Ve=o==null?void 0:o.widgetConfig)==null?void 0:Ve.features)==null?void 0:Y.streamAnimation),R=(me=(ae=(ne=o==null?void 0:o.widgetConfig)==null?void 0:ne.features)==null?void 0:ae.streamAnimation)==null?void 0:me.plugins,w=e.role==="assistant"&&I.type!=="none"?Zs(I.type,R):null,W=e.role==="assistant"&&((le=w==null?void 0:w.isAnimating)==null?void 0:le.call(w,e))===!0,_=e.role==="assistant"&&w!==null&&(!!e.streaming||W);_&&(w!=null&&w.bubbleClass)&&x.classList.add(w.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),_&&w&&(w.containerClass&&$.classList.add(w.containerClass),$.style.setProperty("--persona-stream-step",`${I.speed}ms`),$.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let D=_?di((oe=e.content)!=null?oe:"",I.buffer,w,e,!!e.streaming):(Ye=e.content)!=null?Ye:"",U=n({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=U;_&&(w==null?void 0:w.wrap)==="char"?V=ea(U,"char",e.id,{skipTags:w.skipTags}):_&&(w==null?void 0:w.wrap)==="word"&&(V=ea(U,"word",e.id,{skipTags:w.skipTags}));let se=null;if(P?(se=document.createElement("div"),se.innerHTML=V,se.style.display="none",$.appendChild(se)):$.innerHTML=V,_&&(w!=null&&w.useCaret)&&!P&&E){let X=pi(),$e=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),Mt=$e[$e.length-1];if(Mt!=null&&Mt.parentNode)Mt.parentNode.insertBefore(X,Mt.nextSibling);else{let pe=$.lastElementChild;pe?pe.appendChild(X):$.appendChild(X)}}if(m&&u==="inline"&&e.createdAt){let X=$u(e,l);X.classList.add("persona-ml-2","persona-inline"),$.appendChild(X)}if(A.length>0){let X=xf(A,!P&&!!E,()=>{P&&se&&(se.style.display="")});X?x.appendChild(X):P&&se&&(se.style.display="")}let Re=hf(e);if(Re.length>0){let X=vf(Re);X&&x.appendChild(X)}let Ue=yf(e);if(Ue.length>0){let X=wf(Ue);X&&x.appendChild(X)}let Fe=bf(e);if(Fe.length>0){let X=Cf(Fe);X&&x.appendChild(X)}if(x.appendChild($),m&&u==="below"&&e.createdAt){let X=$u(e,l);X.classList.add("persona-mt-1"),x.appendChild(X)}let fe=e.role==="assistant"?uf(e.stopReason,(de=(We=o==null?void 0:o.widgetConfig)==null?void 0:We.copy)==null?void 0:de.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(D&&D.trim()),$e=I.placeholder==="skeleton",Mt=$e&&I.buffer==="line"&&X;if(X)Mt&&x.appendChild(ta());else if($e)x.appendChild(ta());else{let pe=ml("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);pe&&x.appendChild(pe)}}if(fe&&e.stopReason&&!e.streaming&&(E||($.style.display="none"),x.appendChild(mf(e.stopReason,fe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=gl(e,r,s);x.appendChild(X)}if(!p||e.role==="system")return x;let Pe=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Be=Af(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Pe.append(x,Be):Pe.append(Be,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Pe},Uu=(e,n,t,r,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}):ds(e,n,t,r,s,o)};var ps=new Set,Tf=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Ef=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
|
|
24
|
-
`):""},
|
|
25
|
-
`);let s=ns(
|
|
26
|
-
`):""},Lf=(e,n)=>{var p,m,g,u,v;let t=e.toolCall,r=(p=n==null?void 0:n.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=kf(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=t?ru(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",d=(u=n==null?void 0:n.toolCall)!=null?u:{},l=a;return s==="tool-name"?l=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Xi(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Xi(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},zu=(e,n,t)=>{var p;let r=us.has(e),s=(p=t==null?void 0:t.toolCall)!=null?p:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=s.toggleTextColor||s.headerTextColor||"currentColor",g=be(r?"chevron-up":"chevron-down",16,m,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},hl=(e,n)=>{var V,se,Re,Ue,Fe,fe,xe,Pe,Be;let t=e.toolCall,r=(V=n==null?void 0:n.toolCall)!=null?V:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=(Re=(se=n==null?void 0:n.features)==null?void 0:se.toolCallDisplay)!=null?Re:{},a=o.expandable!==!1,i=a&&us.has(e.id),{summary:d,previewText:l,isActive:p}=Lf(e,n),m=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(u.style.color=r.headerTextColor);let v=String((Ue=t.startedAt)!=null?Ue:Date.now()),x=()=>{let te=h("span","");return te.setAttribute("data-tool-elapsed",v),te.textContent=Us(t),te},A=(fe=r.renderCollapsedSummary)==null?void 0:fe.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Fe=o.collapsedMode)!=null?Fe:"tool-call",isActive:p,config:n!=null?n:{},elapsed:Us(t),createElapsedElement:x});typeof A=="string"&&A.trim()?(u.textContent=A,g.appendChild(u)):A instanceof HTMLElement?g.appendChild(A):(u.textContent=d,g.appendChild(u));let E=(xe=o.loadingAnimation)!=null?xe:"none",B=r.activeTextTemplate,P=r.completeTextTemplate,I=p?B:P,R=A instanceof HTMLElement,w=(te,Ie,K)=>{let ce=K;for(let we of Ie){let he=h("span","persona-tool-char");he.style.setProperty("--char-index",String(ce)),he.textContent=we===" "?"\xA0":we,te.appendChild(he),ce++}return ce},W=(te,Ie)=>{var he;u.textContent="";let K=((he=t.name)==null?void 0:he.trim())||"tool",ce=_a(te,K),we=0;for(let Ce of ce){let Ve=Ce.styles.length>0?(()=>{let Y=h("span",Ce.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return u.appendChild(Y),Y})():u;if(Ce.isDuration&&p)Ve.appendChild(x());else{let Y=Ce.isDuration?Us(t):Ce.text;Ie?we=w(Ve,Y,we):Ve.appendChild(document.createTextNode(Y))}}};if(!R)if(p&&E!=="none"){let te=(Pe=r.loadingAnimationDuration)!=null?Pe:2e3;if(u.setAttribute("data-preserve-animation","true"),E==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${te}ms`),I&&W(I,!1);else if(u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${te}ms`),E==="shimmer-color"&&(r.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),I)W(I,!0);else{let Ie=u.textContent||d;u.textContent="",w(u,Ie,0)}}else I&&W(I,!1);let _=null;if(a){_=h("div","persona-flex persona-items-center");let te=r.toggleTextColor||r.headerTextColor||"currentColor",Ie=be(i?"chevron-up":"chevron-down",16,te,2);Ie?_.appendChild(Ie):_.textContent=i?"Hide":"Show";let K=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append(_),m.append(g,K)}else m.append(g);let $=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let te=(Be=r.renderCollapsedPreview)==null?void 0:Be.call(r,{message:e,toolCall:t,defaultPreview:l,isActive:p,config:n!=null?n:{}});Mf($,te)||($.textContent=l),$.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,$),s;let D=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(D.style.display=i?"":"none",r.contentBackgroundColor&&(D.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(D.style.color=r.contentTextColor),r.contentPaddingX&&(D.style.paddingLeft=r.contentPaddingX,D.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(D.style.paddingTop=r.contentPaddingY,D.style.paddingBottom=r.contentPaddingY),t.name){let te=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?te.style.color=r.contentTextColor:r.headerTextColor&&(te.style.color=r.headerTextColor),te.textContent=t.name,D.appendChild(te)}if(t.args!==void 0){let te=h("div","persona-space-y-1"),Ie=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ie.style.color=r.labelTextColor),Ie.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",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=ns(t.args),te.append(Ie,K),D.appendChild(te)}if(t.chunks&&t.chunks.length){let te=h("div","persona-space-y-1"),Ie=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ie.style.color=r.labelTextColor),Ie.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",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=t.chunks.join(""),te.append(Ie,K),D.appendChild(te)}if(t.status==="complete"&&t.result!==void 0){let te=h("div","persona-space-y-1"),Ie=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ie.style.color=r.labelTextColor),Ie.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",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=ns(t.result),te.append(Ie,K),D.appendChild(te)}if(t.status==="complete"&&typeof t.duration=="number"){let te=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(te.style.color=r.contentTextColor),te.textContent=`Duration: ${t.duration}ms`,D.appendChild(te)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),_){_.innerHTML="";let te=r.toggleTextColor||r.headerTextColor||"currentColor",Ie=be(i?"chevron-up":"chevron-down",16,te,2);Ie?_.appendChild(Ie):_.textContent=i?"Hide":"Show"}D.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),s.append(m,$,D),s};var uo=require("partial-json");var bl="ask_user_question",yl=8,ms="data-persona-ask-sheet-for",Pf="Other",If="Other\u2026",Ku="Type your own answer here",Ju="Send",Wf="Next",Rf="Back",Hf="Submit all",Bf="Skip",Df=3,xl="data-ask-current-index",vl="data-ask-question-count",Gu="data-ask-answers",wl="data-ask-grouped",Xu="data-ask-layout",Nf=e=>e.layout==="pills"?"pills":"rows",Ff=e=>e.getAttribute(Xu)==="pills"?"pills":"rows",Vu=!1,Qu=e=>e.replace(/["\\]/g,"\\$&"),$r=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===bl,Ai=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},jr=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let s=r.join(""),o=(0,uo.parse)(s,uo.STR|uo.OBJ|uo.ARR);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},aa=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>yl&&!Vu&&(Vu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${yl}.`)),n.slice(0,yl)},Of=e=>{var n;return(n=aa(e)[0])!=null?n:null},_f=(e,n)=>{var t;return(t=aa(e)[n])!=null?t:null},Yu=(e,n)=>{let t=n.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Zu=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(t+1),r.appendChild(s)}return r},$f=(e,n,t,r)=>{let o=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(n)),o.setAttribute("data-option-label",e.label),t==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=Zu(t,r,n);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},jf=e=>{let t=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},Uf=(e,n,t,r)=>{var p,m,g;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!t){for(let u=0;u<Df;u++)o.appendChild(jf(r));return o}if(d.forEach((u,v)=>{o.appendChild($f(u,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=r==="rows"?Pf:If;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),A=document.createElement("input");A.type="text",A.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",A.placeholder=(p=n.freeTextPlaceholder)!=null?p:Ku,A.setAttribute("data-ask-free-text-input","true"),A.setAttribute("aria-label",(m=n.freeTextLabel)!=null?m:u),x.appendChild(A),v.appendChild(x);let E=Zu(r,a,d.length);E&&v.appendChild(E),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=n.freeTextLabel)!=null?g:u,o.appendChild(v)}}return o},em=(e,n)=>{var o,a;let r=h("div",n==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:Ku,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Ju,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},qf=e=>{var r;let n=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");n.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=e.submitLabel)!=null?r:Ju,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},zf=(e,n,t)=>{var l,p,m,g;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=t.backLabel)!=null?l:Rf,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=t.skipLabel)!=null?p:Bf,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===n-1;return i.textContent=d?(m=t.submitAllLabel)!=null?m:Hf:(g=t.nextLabel)!=null?g:Wf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},_o=e=>{let n=e.getAttribute(Gu);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},tm=(e,n)=>{e.setAttribute(Gu,JSON.stringify(n))},lr=e=>{var t;let n=Number((t=e.getAttribute(xl))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},Vf=(e,n)=>{e.setAttribute(xl,String(Math.max(0,Math.floor(n))))},gs=e=>{var t;let n=Number((t=e.getAttribute(vl))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},mo=e=>e.getAttribute(wl)==="true",Kf=(e,n)=>{var s;let t=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Jf=(e,n)=>{var r;let t=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(n-1,Math.floor(t)))},Si=(e,n)=>{let{payload:t}=jr(n),r=aa(t),s=_o(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},nm=e=>{let n=_o(e),t=lr(e),r=n[t],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},rm=e=>{if(!mo(e))return;let n=_o(e),t=lr(e),r=n[t],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Cl=(e,n,t)=>{let r=Ai(t),s=Ff(e),{payload:o,complete:a}=jr(n),i=mo(e),d=lr(e),l=gs(e),p=i?_f(o,d):Of(o),m=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let B=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=B,v.classList.toggle("persona-ask-question-skeleton",!B&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let B=Uf(p,r,a,s);x.replaceWith(B)}if(s!=="rows"){let B=e.querySelector('[data-ask-free-text-row="true"]');B&&B.replaceWith(em(r,s))}let A=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!A?e.appendChild(qf(r)):(!m||i)&&A&&A.remove(),e.setAttribute("data-multi-select",m?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let B=zf(d,l,r);E?E.replaceWith(B):e.appendChild(B)}else E&&E.remove();nm(e),rm(e)},Gf=(e,n,t)=>{let r=Ai(n),s=Nf(r),o=e.toolCall.id,a=aa(t),i=Math.max(1,a.length),d=i>1,l=Kf(e,a),p=d?Jf(e,i):0,m=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(ms,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(vl,String(i)),m.setAttribute(xl,String(p)),m.setAttribute(wl,d?"true":"false"),m.setAttribute(Xu,s),tm(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Yu(m,r);let g=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=h("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),m.appendChild(g);let A=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return A.setAttribute("data-ask-pill-list","true"),A.setAttribute("role","group"),m.appendChild(A),s!=="rows"&&m.appendChild(em(r,s)),Cl(m,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Xf=(e,n,t)=>{let{payload:r}=jr(n),s=Math.max(1,aa(r).length);s>gs(e)&&(e.setAttribute(vl,String(s)),s>1&&!mo(e)&&e.setAttribute(wl,"true")),Cl(e,n,t)},om=(e,n)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let r=Ai(n);Yu(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=jr(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},fs=(e,n,t)=>{if(!t||!$r(e)||Ai(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${ms}]`).forEach(l=>{l.getAttribute(ms)!==s&&l.remove()});let a=t.querySelector(`[${ms}="${Qu(s)}"]`);if(a){Xf(a,e,n);return}let{payload:i}=jr(e),d=Gf(e,n,i);t.appendChild(d)},go=(e,n)=>{if(!e)return;let t=n?`[${ms}="${Qu(n)}"]`:`[${ms}]`;e.querySelectorAll(t).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Al=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(n=>n.getAttribute("data-option-label")).filter(n=>typeof n=="string"&&n.length>0),fo=(e,n)=>{let t=_o(e),r=lr(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,tm(e,t),nm(e),rm(e)},Ti=(e,n,t,r)=>{let s=gs(e),o=Math.max(0,Math.min(s-1,r));Vf(e,o),Cl(e,n,t)};var Sl=(e,n)=>{var x,A,E,B,P,I,R,w,W,_,$,D;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(A=r==null?void 0:r.borderColor)!=null?A:"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",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(E=r==null?void 0:r.titleColor)!=null?E:"currentColor",p=be(d,20,l,2);p&&i.appendChild(p);let m=h("div","persona-flex-1 persona-min-w-0"),g=h("div","persona-flex persona-items-center persona-gap-2"),u=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(u.style.color=r.titleColor),u.textContent=(B=r==null?void 0:r.title)!=null?B:"Approval Required",g.appendChild(u),!s){let U=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");U.setAttribute("data-approval-status",t.status),t.status==="approved"?(U.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",U.style.color="var(--persona-palette-colors-success-700, #15803d)",U.textContent="Approved"):t.status==="denied"?(U.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",U.style.color="var(--persona-palette-colors-error-700, #b91c1c)",U.textContent="Denied"):t.status==="timeout"&&(U.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",U.style.color="var(--persona-palette-colors-warning-700, #b45309)",U.textContent="Timeout"),g.appendChild(U)}m.appendChild(g);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=t.description,m.appendChild(v),t.parameters){let U=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");r!=null&&r.parameterBackgroundColor&&(U.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(U.style.color=r.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=ns(t.parameters),m.appendChild(U)}if(s){let U=h("div","persona-flex persona-gap-2 persona-mt-2");U.setAttribute("data-approval-buttons","true");let V=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");V.type="button",V.style.backgroundColor=(P=r==null?void 0:r.approveButtonColor)!=null?P:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(I=r==null?void 0:r.approveButtonTextColor)!=null?I:"#ffffff",V.setAttribute("data-approval-action","approve");let se=be("shield-check",14,(R=r==null?void 0:r.approveButtonTextColor)!=null?R:"#ffffff",2);se&&(se.style.marginRight="4px",V.appendChild(se));let Re=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");V.appendChild(Re);let Ue=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");Ue.type="button",Ue.style.backgroundColor=(W=r==null?void 0:r.denyButtonColor)!=null?W:"transparent",Ue.style.color=(_=r==null?void 0:r.denyButtonTextColor)!=null?_:"var(--persona-feedback-error, #dc2626)",Ue.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ue.setAttribute("data-approval-action","deny");let Fe=be("shield-x",14,($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",2);Fe&&(Fe.style.marginRight="4px",Ue.appendChild(Fe));let fe=document.createTextNode((D=r==null?void 0:r.denyLabel)!=null?D:"Deny");Ue.appendChild(fe),U.append(V,Ue),m.appendChild(U)}return a.append(i,m),o.appendChild(a),o};var sm=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(u=>u.role==="user"))return;let p=document.createDocumentFragment(),m=s?s.isStreaming():!1,g=u=>{switch(u){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'}};r.forEach(u=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=u,v.disabled=m,i!=null&&i.fontFamily&&(v.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(u))}),p.appendChild(v),n.push(v)}),e.appendChild(p)}}};var ia=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}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 n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var la=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};var Qf=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Yf=new Set(["step_start","execution_start"]),Zf=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),eh=new Set(["step_complete","agent_turn_complete"]),th=new Set(["flow_complete","agent_complete"]),am=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),lm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,$o=(e,n)=>{let t=e[n];return lm(t)?t:void 0};function Tl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ei(e,n){if(!(e<=0||n===void 0||n<250))return e/(n/1e3)}function nh(e,n){return typeof n.type=="string"?n.type:e}function rh(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function oh(e,n){return e==="step_delta"||e==="step_chunk"?n.stepType!=="tool"&&n.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof n.contentType=="string"?n.contentType:typeof n.content_type=="string"?n.content_type:void 0)==="text"}function im(e){var r,s,o,a,i;let n=$o(e,"result"),t=[$o(e,"tokens"),$o(e,"totalTokens"),n?$o(n,"tokens"):void 0,$o(e,"usage"),n?$o(n,"usage"):void 0];for(let d of t){if(!d)continue;let l=(s=(r=Qn(d.output))!=null?r:Qn(d.outputTokens))!=null?s:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Qn(e.outputTokens))!=null?o:Qn(e.completionTokens))!=null?i:n?(a=Qn(n.outputTokens))!=null?a:Qn(n.completionTokens):void 0}function sh(e){var t,r,s,o,a;let n=$o(e,"result");return(a=(s=(r=(t=Qn(e.executionTime))!=null?t:Qn(e.executionTimeMs))!=null?r:Qn(e.execution_time))!=null?s:Qn(e.duration))!=null?a:n?(o=Qn(n.executionTime))!=null?o:Qn(n.executionTimeMs):void 0}function ah(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ca=class{constructor(n=ah){this.metric={status:"idle"};this.run=null;this.now=n}getMetric(){let n=this.run;if(n&&this.metric.status==="running"&&n.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-n.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:Ei(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(n){this.run={startedAt:n,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(n,t){var o;if(!lm(t)){am.has(n)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=nh(n,t),s=this.now();if(Qf.has(r)){this.startRun(s);return}if(Yf.has(r)){this.run||this.startRun(s);return}if(Zf.has(r)){if(!oh(r,t))return;let a=rh(t);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Tl(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ei(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(eh.has(r)){if(!this.run)return;let a=this.run,i=im(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Tl(a.visibleCharCount),p=this.resolveDuration(a,t,s);this.metric={status:"running",tokensPerSecond:Ei(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(th.has(r)){if(!this.run)return;let a=this.run,i=im(t),d=i!=null?i:a.exactOutputTokens+Tl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,t,s);this.metric={status:"complete",tokensPerSecond:Ei(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(am.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(n,t,r){let s=n.firstDeltaAt!==void 0?r-n.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=sh(t);return o!=null?o:r-n.startedAt}};function hs(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var ih={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},lh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ch=["flowName","stepName","reasoningText","text","name","tool","toolName"],dh=100;function ph(e,n){let t={...ih,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return lh}function uh(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function mh(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function gh(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.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 fh(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function hh(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function yh(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function bh(e){let n=[];return e.outputTokens!==void 0&&n.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&n.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&n.push(e.source),n.join(" \xB7 ")}function xh(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.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=r,i.appendChild(d),i}}function El(e,n,t,r,s,o,a,i){var g;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");hs(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(u=>u.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let u=p.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(m()),l;function m(){var V,se;let u=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 x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),A=be(d?"chevron-down":"chevron-right","14px","currentColor",2);A&&x.appendChild(A);let E=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=(V=r.timestampFormat)!=null?V:"relative";E.textContent=B==="relative"?uh(e.timestamp,t):mh(e.timestamp);let P=null;r.showSequenceNumbers!==!1&&(P=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(n+1));let I=ph(e.type,r.badgeColors),R=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");R.style.backgroundColor=I.bg,R.style.color=I.text,R.style.borderColor=I.text+"50",R.textContent=e.type;let w=(se=r.descriptionFields)!=null?se:ch,W=gh(e.payload,w),_=null;W&&(_=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),_.textContent=W);let $=h("div","persona-flex-1 persona-min-w-0"),D=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"),U=be("clipboard","12px","currentColor",1.5);return U&&D.appendChild(U),D.addEventListener("click",async Re=>{Re.stopPropagation(),await fh(hh(e)),D.innerHTML="";let Ue=be("check","12px","currentColor",1.5);Ue&&D.appendChild(Ue),setTimeout(()=>{D.innerHTML="";let Fe=be("clipboard","12px","currentColor",1.5);Fe&&D.appendChild(Fe)},1500)}),v.appendChild(x),v.appendChild(E),P&&v.appendChild(P),v.appendChild(R),_&&v.appendChild(_),v.appendChild($),v.appendChild(D),u.appendChild(v),d&&u.appendChild(xh(e,a,i)),u}}function cm(e){var v,x,A,E,B;let{buffer:n,getFullHistory:t,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(v=s==null?void 0:s.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(A=i==null?void 0:i.label)!=null?A:"",m=(B=(E=s==null?void 0:s.features)==null?void 0:E.eventStream)!=null?B:{},g=o.find(P=>P.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&s){let P=g.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>u().element,onClose:r});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return u();function u(){let P=m.classNames,I=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");hs(I,P==null?void 0:P.panel);let R=[],w="",W="",_=null,$=[],D={},U=0,V=ai(),se=0,Re=0,Ue=!1,Fe=null,fe=!1,xe=0,Pe=new Set,Be=new Map,te="",Ie="",K=null,ce,we,he,Ce,Ve,Y=null,ne=null,ae=null;function me(){let re=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ge=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");hs(ge,P==null?void 0:P.headerBar);let wt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(wt.textContent="Events",ce=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"),ce.textContent="0",a){ne=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let Dn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Dn.textContent="Throughput",Y=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 persona-tabular-nums"),Y.textContent="-- tok/s",ae=h("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ae.style.display="none",ae.style.pointerEvents="none";let Zn=ne,bn=ae,Nn=()=>{if(!bn.textContent)return;let vr=Zn.getBoundingClientRect(),Fn=re.getBoundingClientRect();bn.style.left=`${vr.left-Fn.left}px`,bn.style.top=`${vr.bottom-Fn.top+4}px`,bn.style.display="block"},mt=()=>{bn.style.display="none"};ne.addEventListener("mouseenter",Nn),ne.addEventListener("mouseleave",mt),ne.appendChild(Dn),ne.appendChild(Y)}let qt=h("div","persona-flex-1");we=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 en=h("option","");en.value="",en.textContent="All events",we.appendChild(en),he=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"),he.type="button",he.title="Copy All";let Tt=be("clipboard-copy","12px","currentColor",1.5);Tt&&he.appendChild(Tt);let Ct=h("span","persona-text-xs");Ct.textContent="Copy All",he.appendChild(Ct),ge.appendChild(wt),ge.appendChild(ce),ne&&ge.appendChild(ne),ge.appendChild(qt),ge.appendChild(we),ge.appendChild(he);let ht=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");hs(ht,P==null?void 0:P.searchBar);let bt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),Vt=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");bt&&Vt.appendChild(bt),Ce=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"),hs(Ce,P==null?void 0:P.searchInput),Ce.type="text",Ce.placeholder="Search event payloads...",Ve=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"),Ve.type="button",Ve.style.display="none";let nt=be("x","12px","currentColor",2);return nt&&Ve.appendChild(nt),ht.appendChild(Vt),ht.appendChild(Ce),ht.appendChild(Ve),re.appendChild(ge),re.appendChild(ht),ae&&re.appendChild(ae),re}let le,oe=o.find(re=>re.renderEventStreamToolbar);if(oe!=null&&oe.renderEventStreamToolbar&&s){let re=oe.renderEventStreamToolbar({config:s,defaultRenderer:()=>me(),eventCount:n.getSize(),filteredCount:0,onFilterChange:ge=>{w=ge,Bn(),F()},onSearchChange:ge=>{W=ge,Bn(),F()}});le=re!=null?re:me()}else le=me();let Ye=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");Ye.style.display="none";function We(){if(!a||!Y||!ne)return;let re=a();Y.textContent=yh(re);let ge=bh(re);ae&&(ae.textContent=ge,ge||(ae.style.display="none")),ge?ne.setAttribute("aria-label",ge):ne.removeAttribute("aria-label")}let de=h("div","persona-flex-1 persona-min-h-0 persona-relative"),X=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let $e=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");hs($e,P==null?void 0:P.scrollIndicator),$e.style.display="none",$e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Mt=be(l,"14px","currentColor",2);Mt&&$e.appendChild(Mt);let pe=h("span","");pe.textContent=p,$e.appendChild(pe);let ie=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ie.style.display="none",de.appendChild(X),de.appendChild(ie),de.appendChild($e),I.setAttribute("tabindex","0"),I.appendChild(le),I.appendChild(Ye),I.appendChild(de);function kn(){let re=n.getAll(),ge={};for(let Ct of re)ge[Ct.type]=(ge[Ct.type]||0)+1;let wt=Object.keys(ge).sort(),qt=wt.length!==$.length||!wt.every((Ct,ht)=>Ct===$[ht]),en=!qt&&wt.some(Ct=>ge[Ct]!==D[Ct]),yn=re.length!==Object.values(D).reduce((Ct,ht)=>Ct+ht,0);if(!qt&&!en&&!yn||($=wt,D=ge,!we))return;let Tt=we.value;if(we.options[0].textContent="All events",qt){for(;we.options.length>1;)we.remove(1);for(let Ct of wt){let ht=h("option","");ht.value=Ct,ht.textContent=`${Ct} (${ge[Ct]||0})`,we.appendChild(ht)}Tt&&wt.includes(Tt)?we.value=Tt:Tt&&(we.value="",w="")}else for(let Ct=1;Ct<we.options.length;Ct++){let ht=we.options[Ct];ht.textContent=`${ht.value} (${ge[ht.value]||0})`}}function _t(){let re=n.getAll();if(w&&(re=re.filter(ge=>ge.type===w)),W){let ge=W.toLowerCase();re=re.filter(wt=>wt.type.toLowerCase().includes(ge)||wt.payload.toLowerCase().includes(ge))}return re}function cn(){return w!==""||W!==""}function Bn(){U=0,se=0,V.resume(),$e.style.display="none"}function Yn(re){Pe.has(re)?Pe.delete(re):Pe.add(re),K=re;let ge=X.scrollTop,wt=V.isFollowing();fe=!0,V.pause(),F(),X.scrollTop=ge,wt&&V.resume(),fe=!1}function qe(){return Xs(X,50)}function F(){Re=Date.now(),Ue=!1,We(),kn();let re=n.getEvictedCount();re>0?(Ye.textContent=`${re.toLocaleString()} older events truncated`,Ye.style.display=""):Ye.style.display="none",R=_t();let ge=R.length,wt=n.getSize()>0;ce&&(ce.textContent=String(n.getSize())),ge===0&&wt&&cn()?(ie.textContent=W?`No events matching '${W}'`:"No events matching filter",ie.style.display="",X.style.display="none"):(ie.style.display="none",X.style.display=""),he&&(he.title=cn()?`Copy Filtered (${ge})`:"Copy All"),d&&!V.isFollowing()&&ge>U&&(se+=ge-U,pe.textContent=p?`${p}${se>0?` (${se})`:""}`:"",$e.style.display=""),U=ge;let qt=n.getAll(),en=qt.length>0?qt[0].timestamp:0,yn=new Set(R.map(ht=>ht.id));for(let ht of Pe)yn.has(ht)||Pe.delete(ht);let Tt=w!==te||W!==Ie,Ct=Be.size===0&&R.length>0;if(Tt||Ct||R.length===0){X.innerHTML="",Be.clear();let ht=document.createDocumentFragment();for(let bt=0;bt<R.length;bt++){let Vt=El(R[bt],bt,en,m,Pe,Yn,o,s);Be.set(R[bt].id,Vt),ht.appendChild(Vt)}X.appendChild(ht),te=w,Ie=W,K=null}else{if(K!==null){let bt=Be.get(K);if(bt&&bt.parentNode===X){let Vt=R.findIndex(nt=>nt.id===K);if(Vt>=0){let nt=El(R[Vt],Vt,en,m,Pe,Yn,o,s);X.insertBefore(nt,bt),bt.remove(),Be.set(K,nt)}}K=null}let ht=new Set(R.map(bt=>bt.id));for(let[bt,Vt]of Be)ht.has(bt)||(Vt.remove(),Be.delete(bt));for(let bt=0;bt<R.length;bt++){let Vt=R[bt];if(!Be.has(Vt.id)){let nt=El(Vt,bt,en,m,Pe,Yn,o,s);Be.set(Vt.id,nt),X.appendChild(nt)}}}V.isFollowing()&&(X.scrollTop=X.scrollHeight)}function Se(){if(Date.now()-Re>=dh){Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),F();return}Ue||(Ue=!0,Fe=requestAnimationFrame(()=>{Fe=null,F()}))}let De=(re,ge)=>{if(!he)return;he.innerHTML="";let wt=be(re,"12px","currentColor",1.5);wt&&he.appendChild(wt);let qt=h("span","persona-text-xs");qt.textContent="Copy All",he.appendChild(qt),setTimeout(()=>{he.innerHTML="";let en=be("clipboard-copy","12px","currentColor",1.5);en&&he.appendChild(en);let yn=h("span","persona-text-xs");yn.textContent="Copy All",he.appendChild(yn),he.disabled=!1},ge)},Ne=async()=>{if(he){he.disabled=!0;try{let re;cn()?re=R:t?(re=await t(),re.length===0&&(re=n.getAll())):re=n.getAll();let ge=re.map(wt=>{try{return JSON.parse(wt.payload)}catch{return wt.payload}});await navigator.clipboard.writeText(JSON.stringify(ge,null,2)),De("check",1500)}catch{De("x",1500)}}},je=()=>{we&&(w=we.value,Bn(),F())},pt=()=>{!Ce||!Ve||(Ve.style.display=Ce.value?"":"none",_&&clearTimeout(_),_=setTimeout(()=>{W=Ce.value,Bn(),F()},150))},ot=()=>{!Ce||!Ve||(Ce.value="",W="",Ve.style.display="none",_&&clearTimeout(_),Bn(),F())},St=()=>{if(fe)return;let re=X.scrollTop,{action:ge,nextLastScrollTop:wt}=ii({following:V.isFollowing(),currentScrollTop:re,lastScrollTop:xe,nearBottom:qe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});xe=wt,ge==="resume"?(V.resume(),se=0,$e.style.display="none"):ge==="pause"&&(V.pause(),d&&(pe.textContent=p,$e.style.display=""))},Ut=re=>{let ge=li({following:V.isFollowing(),deltaY:re.deltaY,nearBottom:qe(),resumeWhenNearBottom:!0});ge==="pause"?(V.pause(),d&&(pe.textContent=p,$e.style.display="")):ge==="resume"&&(V.resume(),se=0,$e.style.display="none")},z=()=>{d&&(X.scrollTop=X.scrollHeight,V.resume(),se=0,$e.style.display="none")},$t=re=>{let ge=re.target;if(!ge||ge.closest("button"))return;let wt=ge.closest("[data-event-id]");if(!wt)return;let qt=wt.getAttribute("data-event-id");qt&&Yn(qt)},Ze=re=>{if((re.metaKey||re.ctrlKey)&&re.key==="f"){re.preventDefault(),Ce==null||Ce.focus(),Ce==null||Ce.select();return}re.key==="Escape"&&(Ce&&document.activeElement===Ce?(ot(),Ce.blur(),I.focus()):r&&r())};he&&he.addEventListener("click",Ne),we&&we.addEventListener("change",je),Ce&&Ce.addEventListener("input",pt),Ve&&Ve.addEventListener("click",ot),X.addEventListener("scroll",St),X.addEventListener("wheel",Ut,{passive:!0}),X.addEventListener("click",$t),$e.addEventListener("click",z),I.addEventListener("keydown",Ze);function Ft(){_&&clearTimeout(_),Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),Ue=!1,Be.clear(),he&&he.removeEventListener("click",Ne),we&&we.removeEventListener("change",je),Ce&&Ce.removeEventListener("input",pt),Ve&&Ve.removeEventListener("click",ot),X.removeEventListener("scroll",St),X.removeEventListener("wheel",Ut),X.removeEventListener("click",$t),$e.removeEventListener("click",z),I.removeEventListener("keydown",Ze)}return{element:I,update:Se,destroy:Ft}}}function dm(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);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 l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=t;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(u)}else m.textContent=a;if(l.append(p,m),i.append(d,l),s==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${t}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var pm=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.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",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>dm(e,n)});if(p)return p}return dm(e,n)};var Ml=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},Ur=new Ml;Ur.register("PersonaArtifactCard",pm);function vh(e){var s;let n=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 r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function um(e,n){var we,he,Ce,Ve;let t=(he=(we=e.features)==null?void 0:we.artifacts)==null?void 0:he.layout,s=((Ce=t==null?void 0:t.toolbarPreset)!=null?Ce:"default")==="document",o=(Ve=t==null?void 0:t.panePadding)==null?void 0:Ve.trim(),a=e.markdown?Po(e.markdown):null,i=es(e.sanitize),d=Y=>{let ne=a?a(Y):Io(Y);return i?i(ne):ne},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};l&&l.addEventListener("click",()=>{var Y;p(),(Y=n.onDismiss)==null||Y.call(n)});let m=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");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let g=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&g.classList.add("persona-artifact-toolbar-document");let u=h("span","persona-text-xs persona-font-medium persona-truncate");u.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 Y;p(),(Y=n.onDismiss)==null||Y.call(n)});let x="rendered",A=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=s?jt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):jt({icon:"eye",label:"Rendered view"}),B=s?jt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):jt({icon:"code-2",label:"Source"}),P=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),I=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,R=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,w=t==null?void 0:t.documentToolbarCopyMenuItems,W=!!(R&&w&&w.length>0),_=null,$,D=null,U=null;if(s&&(I||R)&&!W){if($=I?oa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let Y=be("chevron-down",14,"currentColor",2);Y&&$.appendChild(Y)}}else s&&W?(_=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=I?oa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=jt({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"}}),_.append($,D)):s?$=jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=jt({icon:"copy",label:"Copy"});let V=s?jt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):jt({icon:"refresh-cw",label:"Refresh"}),se=s?jt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):jt({icon:"x",label:"Close"}),Re=()=>{var le,oe,Ye;let Y=(le=Be.find(We=>We.id===te))!=null?le:Be[Be.length-1],ne=(oe=Y==null?void 0:Y.id)!=null?oe:null,ae=(Y==null?void 0:Y.artifactType)==="markdown"&&(Ye=Y.markdown)!=null?Ye:"",me=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:ae,jsonPayload:me,id:ne}},Ue=async()=>{var le;let{markdown:Y,jsonPayload:ne}=Re(),ae=(le=Be.find(oe=>oe.id===te))!=null?le:Be[Be.length-1],me=(ae==null?void 0:ae.artifactType)==="markdown"?Y:ae?ne:"";try{await navigator.clipboard.writeText(me)}catch{}};if($.addEventListener("click",async()=>{let Y=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(Y&&W){let{markdown:ne,jsonPayload:ae,id:me}=Re();try{await Y({actionId:"primary",artifactId:me,markdown:ne,jsonPayload:ae})}catch{}return}await Ue()}),D&&(w!=null&&w.length)){let Y=()=>{var ae;return(ae=m.closest("[data-persona-root]"))!=null?ae:document.body},ne=()=>{U=po({items:w.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:me,jsonPayload:le,id:oe}=Re(),Ye=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Ye?await Ye({actionId:ae,artifactId:oe,markdown:me,jsonPayload:le}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(me):ae==="json"||ae==="source"?await navigator.clipboard.writeText(le):await navigator.clipboard.writeText(me||le)}catch{}},anchor:_!=null?_:D,position:"bottom-right",portal:Y()})};m.isConnected?ne():requestAnimationFrame(ne),D.addEventListener("click",ae=>{ae.stopPropagation(),U==null||U.toggle()})}V.addEventListener("click",async()=>{var Y;try{await((Y=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:Y.call(t))}catch{}K()}),se.addEventListener("click",()=>{var Y;p(),(Y=n.onDismiss)==null||Y.call(n)});let Fe=()=>{s&&(E.setAttribute("aria-pressed",x==="rendered"?"true":"false"),B.setAttribute("aria-pressed",x==="source"?"true":"false"))};E.addEventListener("click",()=>{x="rendered",Fe(),K()}),B.addEventListener("click",()=>{x="source",Fe(),K()});let fe=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(g.replaceChildren(),A.append(E,B),_?P.append(_,V,se):P.append($,V,se),g.append(A,fe,P),Fe()):(g.appendChild(u),g.appendChild(v)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let xe=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"),Pe=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(xe.style.paddingLeft=o,xe.style.paddingRight=o,Pe.style.padding=o),m.appendChild(g),m.appendChild(xe),m.appendChild(Pe);let Be=[],te=null,Ie=!1,K=()=>{var me,le,oe,Ye;let Y=s&&Be.length<=1;xe.classList.toggle("persona-hidden",Y),xe.replaceChildren();for(let We of Be){let de=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");de.type="button",de.textContent=We.title||We.id.slice(0,8),We.id===te&&de.classList.add("persona-bg-persona-container","persona-border-persona-border"),de.addEventListener("click",()=>n.onSelect(We.id)),xe.appendChild(de)}Pe.replaceChildren();let ne=te&&Be.find(We=>We.id===te)||Be[Be.length-1];if(!ne)return;if(s){let We=ne.artifactType==="markdown"?"MD":(me=ne.component)!=null?me:"Component",X=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";fe.textContent=`${X} \xB7 ${We}`}else u.textContent="Artifacts";if(ne.artifactType==="markdown"){if(s&&x==="source"){let de=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");de.textContent=(le=ne.markdown)!=null?le:"",Pe.appendChild(de);return}let We=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");We.innerHTML=d((oe=ne.markdown)!=null?oe:""),Pe.appendChild(We);return}let ae=ne.component?Ur.get(ne.component):void 0;if(ae){let de={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=ae((Ye=ne.props)!=null?Ye:{},de);if(X){Pe.appendChild(X);return}}catch{}}Pe.appendChild(vh(ne))},ce=()=>{var ne;let Y=Be.length>0;if(m.classList.toggle("persona-hidden",!Y),l){let ae=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,le=((ne=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&le&&Ie?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(Y){var ne,ae,me;Be=Y.artifacts,te=(me=(ae=Y.selectedId)!=null?ae:(ne=Y.artifacts[Y.artifacts.length-1])==null?void 0:ne.id)!=null?me:null,Be.length>0&&(Ie=!0),K(),ce()},setMobileOpen(Y){Ie=Y,!Y&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):ce()}}}function cr(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function mm(e,n){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"),!cr(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(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();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function wh(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 Mi(e,n){var d,l,p,m,g,u,v,x,A,E;if(!cr(n)){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"),wh(e),mm(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=t==null?void 0:t.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=t==null?void 0:t.paneMaxWidth)!=null?g:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=t==null?void 0:t.paneBackground)==null?void 0:u.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):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=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(A=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:A.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),mm(e,n)}var gm=["panel","seamless"];function ki(e,n){var i,d,l,p,m,g;for(let u of gm)e.classList.remove(`persona-artifact-appearance-${u}`);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"),!cr(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",s=gm.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=t==null?void 0:t.paneShadow)==null?void 0:m.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 u=((g=t.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function fm(e,n){var t,r,s;return!n||!cr(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Ch(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function Ah(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function Sh(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function Th(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function hm(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function ym(e,n,t,r,s,o){let a=Ch(s,200),i=Th(n,t,r,200);i=Math.max(a,i);let d=Ah(o);return d!==null&&(i=Math.min(i,d)),Sh(e,a,i)}var bm={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"}},kl=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,A;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=bm[a])!=null?x:bm.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let E=h("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,d.appendChild(E)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var w,W;let B=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");B.htmlFor=`${n.id}-${a}-${E.name}`;let P=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=E.label,B.appendChild(P);let I=(w=E.type)!=null?w:"text",R;I==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=I),R.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",R.id=`${n.id}-${a}-${E.name}`,R.name=E.name,R.placeholder=(W=E.placeholder)!=null?W:"",E.required&&(R.required=!0),B.appendChild(R),p.appendChild(B)});let m=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=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");u.type="submit",u.textContent=(A=i.submitLabel)!=null?A:"Submit",m.appendChild(g),m.appendChild(u),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async E=>{var R,w;E.preventDefault();let B=(R=t.formEndpoint)!=null?R:"/form",P=new FormData(p),I={};P.forEach((W,_)=>{I[_]=W}),I.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let W=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let _=await W.json();g.textContent=(w=_.message)!=null?w:"Thanks! We'll be in touch soon.",_.success&&_.nextPrompt&&await r.sendMessage(String(_.nextPrompt))}catch(W){g.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var Ll=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},da=new Ll;var xm=()=>{let e=new Map,n=(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:n,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 Eh=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Mh=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},pa=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Eh(e),t=Mh(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Pl=e=>typeof e=="string"?e:e==null?"":String(e),jo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Pl(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=Pl(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Pl(t.text)}}},vm=e=>Array.isArray(e)?e.map(n=>String(n)):[],ua=e=>{let n=new Set(vm(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(vm(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.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((l,p)=>l||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},m=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var kh=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},Lh=e=>e.map(n=>({...n,streaming:!1})),Ph=e=>e.map(n=>({...n,status:"complete"})),Li=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?kh(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?Lh(t.messages):void 0,artifacts:t.artifacts?Ph(t.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var ys=require("partial-json");function Ih(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Wh(e,n){if(!Ih(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function Pi(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=(0,ys.parse)(t,ys.STR|ys.OBJ),o=Wh(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function wm(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ii(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=Ur.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,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 Cm(){let e=Pi();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Am(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let n=e.content.trim();if(n.startsWith("{")||n.startsWith("["))return e.content}return null}function Wi(e){let n=Am(e);if(!n)return!1;try{let t=JSON.parse(n);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Ri(e){let n=Am(e);if(!n)return null;try{let t=JSON.parse(n);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:n}}}catch{}return null}var Rh=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Hi(e){let{onSubmit:n,onDismiss:t,title:r="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:l=Rh}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,u.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,u.appendChild(x),g.appendChild(u);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-csat",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let w=1;w<=5;w++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),W.title=l[w-1],W.dataset.rating=String(w),W.innerHTML=`
|
|
23
|
+
`,n.addEventListener("click",t);let r=o=>{var P,I,R,w,W,$,_,D,U,V,se,Re,Ue,Fe;let a=(P=o.launcher)!=null?P:{},i=rn(o),d=n.querySelector("[data-role='launcher-title']");if(d){let fe=(I=a.title)!=null?I:"Chat Assistant";d.textContent=fe,d.setAttribute("title",fe)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let fe=(R=a.subtitle)!=null?R:"Get answers fast";l.textContent=fe,l.setAttribute("title",fe)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let fe=(w=a.agentIconSize)!=null?w:"40px";if(m.style.height=fe,m.style.width=fe,m.innerHTML="",a.agentIconName){let xe=parseFloat(fe)||24,Pe=be(a.agentIconName,xe*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(m.appendChild(Pe),m.style.display=""):(m.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=($=a.agentIconText)!=null?$:"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let fe=(_=a.agentIconSize)!=null?_:"40px";g.style.height=fe,g.style.width=fe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let u=n.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let fe=(D=a.callToActionIconSize)!=null?D:"32px";u.style.height=fe,u.style.width=fe,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let xe=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,xe=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let Pe=parseFloat(fe)||24,Be=Math.max(Pe-xe,8),te=be(a.callToActionIconName,Be,"currentColor",2);te?u.appendChild(te):u.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else u.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let v=a.position&&xr[a.position]?xr[a.position]:xr["bottom-right"],x="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",A="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";n.className=i?A:`${x} ${v}`,i||(n.style.zIndex=String((se=a.zIndex)!=null?se:hn));let E="1px solid var(--persona-border, #e5e7eb)",B="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Re=a.border)!=null?Re:E,n.style.boxShadow=(Ue=a.shadow)!=null?Ue:B,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(Fe=a.collapsedMaxWidth)!=null?Fe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var lf="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",gi=(e,t={})=>{var x,A,E,B,P,I;let{showClose:n=!0,wrapperClassName:r=lf,buttonSize:s,iconSize:o="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(A=s!=null?s:a.closeButtonSize)!=null?A:"32px",d=h("div",r),l=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");l.style.height=i,l.style.width=i,l.type="button";let p=(E=a.closeButtonTooltipText)!=null?E:"Close chat",m=(B=a.closeButtonShowTooltip)!=null?B:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let g=(P=a.closeButtonIconName)!=null?P:"x",u=(I=a.closeButtonIconText)!=null?I:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let v=be(g,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=u,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let R=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${R} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&p){let R=null,w=()=>{if(R)return;let $=l.ownerDocument,_=$.body;if(!_)return;R=Tr($,"div","persona-clear-chat-tooltip"),R.textContent=p;let D=Tr($,"div");D.className="persona-clear-chat-tooltip-arrow",R.appendChild(D);let U=l.getBoundingClientRect();R.style.position="fixed",R.style.zIndex=String(io),R.style.left=`${U.left+U.width/2}px`,R.style.top=`${U.top-8}px`,R.style.transform="translate(-50%, -100%)",_.appendChild(R)},W=()=>{R&&R.parentNode&&(R.parentNode.removeChild(R),R=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",W),l.addEventListener("focus",w),l.addEventListener("blur",W),d._cleanupTooltip=()=>{W(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",W),l.removeEventListener("focus",w),l.removeEventListener("blur",W)}}return{button:l,wrapper:d}},cf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",fi=(e,t={})=>{var R,w,W,$,_,D,U,V,se,Re,Ue,Fe,fe;let{wrapperClassName:n=cf,buttonSize:r,iconSize:s="20px"}=t,a=(w=((R=e==null?void 0:e.launcher)!=null?R:{}).clearChat)!=null?w:{},i=(W=r!=null?r:a.size)!=null?W:"32px",d=($=a.iconName)!=null?$:"refresh-cw",l=(_=a.iconColor)!=null?_:"",p=(D=a.backgroundColor)!=null?D:"",m=(U=a.borderWidth)!=null?U:"",g=(V=a.borderColor)!=null?V:"",u=(se=a.borderRadius)!=null?se:"",v=(Re=a.paddingX)!=null?Re:"",x=(Ue=a.paddingY)!=null?Ue:"",A=(Fe=a.tooltipText)!=null?Fe:"Clear chat",E=(fe=a.showTooltip)!=null?fe:!0,B=h("div",n),P=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");P.style.height=i,P.style.width=i,P.type="button",P.setAttribute("aria-label",A),P.style.color=l||Mn.actionIconColor;let I=be(d,s,"currentColor",1);if(I&&(I.style.display="block",P.appendChild(I)),p&&(P.style.backgroundColor=p,P.classList.remove("hover:persona-bg-gray-100")),m||g){let xe=m||"0px",Pe=g||"transparent";P.style.border=`${xe} solid ${Pe}`,P.classList.remove("persona-border-none")}if(u&&(P.style.borderRadius=u,P.classList.remove("persona-rounded-full")),v&&(P.style.paddingLeft=v,P.style.paddingRight=v),x&&(P.style.paddingTop=x,P.style.paddingBottom=x),B.appendChild(P),E&&A){let xe=null,Pe=()=>{if(xe)return;let te=P.ownerDocument,Ie=te.body;if(!Ie)return;xe=Tr(te,"div","persona-clear-chat-tooltip"),xe.textContent=A;let K=Tr(te,"div");K.className="persona-clear-chat-tooltip-arrow",xe.appendChild(K);let ce=P.getBoundingClientRect();xe.style.position="fixed",xe.style.zIndex=String(io),xe.style.left=`${ce.left+ce.width/2}px`,xe.style.top=`${ce.top-8}px`,xe.style.transform="translate(-50%, -100%)",Ie.appendChild(xe)},Be=()=>{xe&&xe.parentNode&&(xe.parentNode.removeChild(xe),xe=null)};B.addEventListener("mouseenter",Pe),B.addEventListener("mouseleave",Be),P.addEventListener("focus",Pe),P.addEventListener("blur",Be),B._cleanupTooltip=()=>{Be(),B.removeEventListener("mouseenter",Pe),B.removeEventListener("mouseleave",Be),P.removeEventListener("focus",Pe),P.removeEventListener("blur",Be)}}return{button:P,wrapper:B}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},$r=e=>{var R,w,W,$,_,D,U,V,se,Re,Ue,Fe,fe,xe,Pe,Be;let{config:t,showClose:n=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(R=t==null?void 0:t.launcher)!=null?R:{},o=(w=s.headerIconSize)!=null?w:"48px",a=(W=s.closeButtonPlacement)!=null?W:"inline",i=($=s.headerIconHidden)!=null?$:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let te=parseFloat(o)||24,Ie=be(d,te*.6,"currentColor",1);Ie?l.replaceChildren(Ie):l.textContent=(D=(_=t==null?void 0:t.launcher)==null?void 0:_.agentIconText)!=null?D:"\u{1F4AC}"}else if((U=t==null?void 0:t.launcher)!=null&&U.iconUrl){let te=h("img");te.src=t.launcher.iconUrl,te.alt="",te.className="persona-rounded-xl persona-object-cover",te.style.height=o,te.style.width=o,l.replaceChildren(te)}else l.textContent=(se=(V=t==null?void 0:t.launcher)==null?void 0:V.agentIconText)!=null?se:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=h("span","persona-text-base persona-font-semibold");m.style.color=Mn.titleColor,m.textContent=(Ue=(Re=t==null?void 0:t.launcher)==null?void 0:Re.title)!=null?Ue:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=Mn.subtitleColor,g.textContent=(fe=(Fe=t==null?void 0:t.launcher)==null?void 0:Fe.subtitle)!=null?fe:"Here to help you get answers fast",p.append(m,g),i?r.append(p):r.append(l,p);let u=(xe=s.clearChat)!=null?xe:{},v=(Pe=u.enabled)!=null?Pe:!0,x=(Be=u.placement)!=null?Be:"inline",A=null,E=null;if(v){let Ie=fi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});A=Ie.button,E=Ie.wrapper,x==="top-right"&&(E.style.right="48px"),x==="inline"&&r.appendChild(E)}let B=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:I}=gi(t,{showClose:n,wrapperClassName:B});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:l,headerTitle:m,headerSubtitle:g,closeButton:P,closeButtonWrapper:I,clearChatButton:A,clearChatButtonWrapper:E}},Fo=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function po(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(io)):(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 u of t){if(u.dividerBefore){let A=document.createElement("hr");a.appendChild(A)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",u.id),u.destructive&&v.setAttribute("data-destructive",""),u.icon){let A=be(u.icon,16,"currentColor",1.5);A&&v.appendChild(A)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",A=>{A.stopPropagation(),p(),n(u.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let u=r.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:g}}function jt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=be(t,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function oa(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=be(t,o!=null?o:14,"currentColor",2);g&&p.appendChild(g)}let m=h("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))p.setAttribute(g,u);return p}function sa(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let m;p.icon?m=jt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=h("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function l(p){a=p,d()}return{element:o,setSelected:l}}function hi(e){var u,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=h("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let m=be(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,A;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(A=d.border)!=null?A:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=po({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let A=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",A?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var cl=e=>{var r;let t=$r({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function df(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){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=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=be(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 l=po({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var dl=e=>{var B,P,I,R,w,W,$,_,D;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(B=t==null?void 0:t.launcher)!=null?B:{},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,l,p;if(d)l=hi({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,p=(I=l.querySelector(".persona-combo-btn-label"))!=null?I:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(R=a.title)!=null?R:"Chat Assistant",l.appendChild(p),df(l,s==null?void 0:s.trailingActions,(w=s==null?void 0:s.onAction)!=null?w:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=s.onTitleClick;l.addEventListener("click",se=>{se.target.closest("button")||V()}),l.addEventListener("keydown",se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),V())})}let U=s==null?void 0:s.titleRowHover;U&&(l.style.borderRadius=(W=U.borderRadius)!=null?W:"10px",l.style.padding=($=U.padding)!=null?$:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,se;l.style.backgroundColor=(V=U.background)!=null?V:"",l.style.borderColor=(se=U.border)!=null?se:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(_=a.closeButtonSize)!=null?_:"32px",g=h("div",""),u=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");u.style.height=m,u.style.width=m,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||Mn.actionIconColor;let v=(D=a.closeButtonIconName)!=null?D:"x",x=be(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let A=h("div");A.style.display="none";let E=h("span");return E.style.display="none",{header:i,iconHolder:A,headerTitle:p,headerSubtitle:E,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},yi={default:cl,minimal:dl},pl=e=>{var t;return(t=yi[e])!=null?t:yi.default},ls=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=h("div");p.style.display="none";let m=h("span"),g=h("span"),u=h("button");u.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:u,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=pl(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var bi=e=>{var a,i;let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.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",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:o}},xi=e=>{var R,w,W,$,_,D,U,V,se,Re,Ue,Fe;let t=(R=e==null?void 0:e.sendButton)!=null?R:{},n=(w=t.useIcon)!=null?w:!1,r=(W=t.iconText)!=null?W:"\u2191",s=t.iconName,o=($=t.stopIconName)!=null?$:"square",a=(_=t.tooltipText)!=null?_:"Send message",i=(D=t.stopTooltipText)!=null?D:"Stop generating",d=(V=(U=e==null?void 0:e.copy)==null?void 0:U.sendButtonLabel)!=null?V:"Send",l=(Re=(se=e==null?void 0:e.copy)==null?void 0:se.stopButtonLabel)!=null?Re:"Stop",p=(Ue=t.showTooltip)!=null?Ue:!1,m=(Fe=t.size)!=null?Fe:"40px",g=t.backgroundColor,u=t.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",n?"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");x.type="submit",x.setAttribute("data-persona-composer-submit","");let A=null,E=null;if(n){x.style.width=m,x.style.height=m,x.style.minWidth=m,x.style.minHeight=m,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",u?x.style.color=u:x.style.color="var(--persona-button-primary-fg, #ffffff)";let fe=parseFloat(m)||24,xe=(u==null?void 0:u.trim())||"currentColor";s?(A=be(s,fe,xe,2),A?x.appendChild(A):x.textContent=r):x.textContent=r,E=be(o,fe,xe,2),g?x.style.backgroundColor=g:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,u?x.style.color=u:x.classList.add("persona-text-white");t.borderWidth&&(x.style.borderWidth=t.borderWidth,x.style.borderStyle="solid"),t.borderColor&&(x.style.borderColor=t.borderColor),t.paddingX?(x.style.paddingLeft=t.paddingX,x.style.paddingRight=t.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),t.paddingY?(x.style.paddingTop=t.paddingY,x.style.paddingBottom=t.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let B=null;p&&a&&(B=h("div","persona-send-button-tooltip"),B.textContent=a,v.appendChild(B)),x.setAttribute("aria-label",a),v.appendChild(x);let P="send";return{button:x,wrapper:v,setMode:fe=>{if(fe===P)return;P=fe;let xe=fe==="stop"?i:a;if(x.setAttribute("aria-label",xe),B&&(B.textContent=xe),n){if(A&&E){let Pe=fe==="stop"?E:A;x.replaceChildren(Pe)}}else x.textContent=fe==="stop"?l:d}}},vi=e=>{var B,P,I,R,w,W,$,_,D,U,V,se;let t=(B=e==null?void 0:e.voiceRecognition)!=null?B:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(r||s))return null;let a=(R=(I=e==null?void 0:e.sendButton)==null?void 0:I.size)!=null?R:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=t.iconName)!=null?w:"mic",p=(W=t.iconSize)!=null?W:a,m=parseFloat(p)||24,g=(_=t.backgroundColor)!=null?_:($=e==null?void 0:e.sendButton)==null?void 0:$.backgroundColor,u=(U=t.iconColor)!=null?U:(D=e==null?void 0:e.sendButton)==null?void 0:D.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let x=be(l,m,u||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let A=(V=t.tooltipText)!=null?V:"Start voice recognition";if(((se=t.showTooltip)!=null?se:!1)&&A){let Re=h("div","persona-send-button-tooltip");Re.textContent=A,i.appendChild(Re)}return{button:d,wrapper:i}},wi=e=>{var v,x,A,E,B,P,I,R;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(A=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?A:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((E=t.allowedTypes)!=null?E:Or).join(","),s.multiple=((B=t.maxFiles)!=null?B:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(P=t.buttonTooltipText)!=null?P:"Attach file");let i=(I=t.buttonIconName)!=null?I:"paperclip",d=n,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=be(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),s.click()}),o.appendChild(a);let g=(R=t.buttonTooltipText)!=null?R:"Attach file",u=h("div","persona-send-button-tooltip");return u.textContent=g,o.appendChild(u),{button:a,wrapper:o,input:s,previewsContainer:r}},Ci=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=h("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},Ai=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var cs=e=>{var v,x,A,E,B,P;let{config:t}=e,n=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let r=Ai(),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{textarea:o,attachAutoResize:a}=bi(t);a();let i=xi(t),d=vi(t),l=wi(t),p=Ci(t);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let m=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),m.append(g,u),s.append(m),s.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(l==null?void 0:l.button)&&I.target!==(l==null?void 0:l.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(A=l==null?void 0:l.button)!=null?A:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:m,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var Fu=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=h("span","persona-pill-peek__icon"),n=be("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=be("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},Ou=e=>{var v,x,A,E,B,P;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=Ai();r.style.display="none";let s=Ci(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=bi(t);o.style.maxHeight="100px",a();let i=xi(t),d=vi(t),l=wi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=h("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let g=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(l==null?void 0:l.button)&&I.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&p.append(l.input),p.append(m,o,g),l&&n.append(l.previewsContainer),n.append(p,r,s);let u=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(A=l==null?void 0:l.button)!=null?A:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:u,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var $u=e=>{var p,m,g,u,v,x,A,E,B,P,I,R,w,W,$,_,D;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=rn(e);if(co(e)){let U=(u=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?u:{},V=h("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=U.expandedSize)!=null?v:"anchored",V.style.zIndex=String((A=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?A:hn);let se=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");se.style.width="100%",V.appendChild(se);let Re=h("div","persona-widget-pill-root");return Re.setAttribute("data-persona-composer-bar",""),Re.dataset.state="collapsed",Re.dataset.expandedSize=(E=U.expandedSize)!=null?E:"anchored",Re.style.zIndex=String((P=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?P:hn),{wrapper:V,panel:se,pillRoot:Re}}if(n){let U=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(V),{wrapper:U,panel:V}}if(!t){let U=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),se=(R=(I=e==null?void 0:e.launcher)==null?void 0:I.width)!=null?R:"100%";return U.style.width=se,V.style.width="100%",U.appendChild(V),{wrapper:U,panel:V}}let s=(w=e==null?void 0:e.launcher)!=null?w:{},o=s.position&&xr[s.position]?xr[s.position]:xr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String(($=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?$:hn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(D=(_=e==null?void 0:e.launcher)==null?void 0:_.width)!=null?D:e==null?void 0:e.launcherWidth,l=d!=null?d:Xn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},pf=(e,t)=>{var I,R,w,W,$,_,D,U,V;let n=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=gi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(w=(R=(I=e==null?void 0:e.launcher)==null?void 0:I.clearChat)==null?void 0:R.enabled)!=null?w:!0,a=null,i=null;if(o){let se=fi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=se.button,i=se.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=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");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=($=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?$:"Hello \u{1F44B}";let g=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(D=(_=e==null?void 0:e.copy)==null?void 0:_.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",p.append(m,g);let u=h("div","persona-flex persona-flex-col persona-gap-3"),v=(U=e==null?void 0:e.layout)==null?void 0:U.contentMaxWidth;v&&(u.style.maxWidth=v,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,u);let A=h("div","persona-composer-overlay persona-pointer-events-none");A.setAttribute("data-persona-composer-overlay",""),A.style.position="absolute",A.style.left="0",A.style.right="0",A.style.bottom="0",A.style.zIndex="20";let E=Ou({config:e}),{root:B,textNode:P}=Fu();return n.append(d,s,l,A),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:A,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:m,introSubtitle:g,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:B,peekTextNode:P}},_u=(e,t=!0)=>{var A,E,B,P,I,R,w,W,$;if(co(e))return pf(e,t);let n=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let r=(A=e==null?void 0:e.layout)==null?void 0:A.header,s=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,o=r?ls(e,r,{showClose:t}):$r({config:e,showClose:t}),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=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=rn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(P=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?P:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(R=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",i.append(d,l);let p=h("div","persona-flex persona-flex-col persona-gap-3"),m=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((W=e==null?void 0:e.copy)==null?void 0:W.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let u=cs({config:e}),v=(($=e==null?void 0:e.layout)==null?void 0:$.showFooter)!==!1;s?Fo(n,o,e):(o.header.style.display="none",Fo(n,o,e)),n.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(u.footer.style.display="none"),n.append(u.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:d,introSubtitle:l,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:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var uf=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},mf=(e,t)=>{if(!e)return null;let n=uf(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},gf=(e,t)=>{let n=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},ff=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ul=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},ml=320,Uu=320,hf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),yf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),bf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),xf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),vf=(e,t,n)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let l=h("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${ml}px`,l.style.maxHeight=`${Uu}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,l.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{p=!0}),ff(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},wf=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!ul(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${ml}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Cf=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!ul(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${ml}px`,s.style.maxHeight=`${Uu}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Af=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!ul(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Oo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},gl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Oo};if(t){let s=t(r);if(s!==null)return s}return Oo()},Sf=(e,t)=>{let n=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"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},ju=(e,t)=>{let n=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Tf=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},fl=(e,t,n)=>{var u,v,x,A,E,B;let r=(u=t.showCopy)!=null?u:!0,s=(v=t.showUpvote)!=null?v:!0,o=(x=t.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let P=h("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let a=(A=t.visibility)!=null?A:"hover",i=(E=t.align)!=null?E:"right",d=(B=t.layout)!=null?B:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let g=(P,I,R)=>{let w=jt({icon:P,label:I,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",R),w};return r&&m.appendChild(g("copy","Copy message","copy")),s&&m.appendChild(g("thumbs-up","Upvote","upvote")),o&&m.appendChild(g("thumbs-down","Downvote","downvote")),m},ds=(e,t,n,r,s,o)=>{var te,Ie,K,ce,we,he,Ce,Ve,Y,ne,ae,me,le,oe,Ye,We,de;let a=n!=null?n:{},i=(te=a.layout)!=null?te:"bubble",d=a.avatar,l=a.timestamp,p=(Ie=d==null?void 0:d.show)!=null?Ie:!1,m=(K=l==null?void 0:l.show)!=null?K:!1,g=(ce=d==null?void 0:d.position)!=null?ce:"left",u=(we=l==null?void 0:l.position)!=null?we:"below",v=Tf(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let A=hf(e),E=(Ce=(he=e.content)==null?void 0:he.trim())!=null?Ce:"",P=A.length>0&&E===Ja,I=di((Y=(Ve=o==null?void 0:o.widgetConfig)==null?void 0:Ve.features)==null?void 0:Y.streamAnimation),R=(me=(ae=(ne=o==null?void 0:o.widgetConfig)==null?void 0:ne.features)==null?void 0:ae.streamAnimation)==null?void 0:me.plugins,w=e.role==="assistant"&&I.type!=="none"?Zs(I.type,R):null,W=e.role==="assistant"&&((le=w==null?void 0:w.isAnimating)==null?void 0:le.call(w,e))===!0,$=e.role==="assistant"&&w!==null&&(!!e.streaming||W);$&&(w!=null&&w.bubbleClass)&&x.classList.add(w.bubbleClass);let _=document.createElement("div");_.classList.add("persona-message-content"),$&&w&&(w.containerClass&&_.classList.add(w.containerClass),_.style.setProperty("--persona-stream-step",`${I.speed}ms`),_.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let D=$?pi((oe=e.content)!=null?oe:"",I.buffer,w,e,!!e.streaming):(Ye=e.content)!=null?Ye:"",U=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=U;$&&(w==null?void 0:w.wrap)==="char"?V=ea(U,"char",e.id,{skipTags:w.skipTags}):$&&(w==null?void 0:w.wrap)==="word"&&(V=ea(U,"word",e.id,{skipTags:w.skipTags}));let se=null;if(P?(se=document.createElement("div"),se.innerHTML=V,se.style.display="none",_.appendChild(se)):_.innerHTML=V,$&&(w!=null&&w.useCaret)&&!P&&E){let X=ui(),_e=_.querySelectorAll(".persona-stream-char, .persona-stream-word"),Mt=_e[_e.length-1];if(Mt!=null&&Mt.parentNode)Mt.parentNode.insertBefore(X,Mt.nextSibling);else{let pe=_.lastElementChild;pe?pe.appendChild(X):_.appendChild(X)}}if(m&&u==="inline"&&e.createdAt){let X=ju(e,l);X.classList.add("persona-ml-2","persona-inline"),_.appendChild(X)}if(A.length>0){let X=vf(A,!P&&!!E,()=>{P&&se&&(se.style.display="")});X?x.appendChild(X):P&&se&&(se.style.display="")}let Re=yf(e);if(Re.length>0){let X=wf(Re);X&&x.appendChild(X)}let Ue=bf(e);if(Ue.length>0){let X=Cf(Ue);X&&x.appendChild(X)}let Fe=xf(e);if(Fe.length>0){let X=Af(Fe);X&&x.appendChild(X)}if(x.appendChild(_),m&&u==="below"&&e.createdAt){let X=ju(e,l);X.classList.add("persona-mt-1"),x.appendChild(X)}let fe=e.role==="assistant"?mf(e.stopReason,(de=(We=o==null?void 0:o.widgetConfig)==null?void 0:We.copy)==null?void 0:de.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(D&&D.trim()),_e=I.placeholder==="skeleton",Mt=_e&&I.buffer==="line"&&X;if(X)Mt&&x.appendChild(ta());else if(_e)x.appendChild(ta());else{let pe=gl("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);pe&&x.appendChild(pe)}}if(fe&&e.stopReason&&!e.streaming&&(E||(_.style.display="none"),x.appendChild(gf(e.stopReason,fe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=fl(e,r,s);x.appendChild(X)}if(!p||e.role==="system")return x;let Pe=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Be=Sf(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Pe.append(x,Be):Pe.append(Be,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Pe},qu=(e,t,n,r,s,o)=>{let a=n!=null?n:{};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}):ds(e,t,n,r,s,o)};var ps=new Set,Ef=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Mf=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
+
`):""},zu=(e,t)=>{let n=ps.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),o=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=be(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",o&&(o.style.display=n?"none":o.textContent||o.childNodes.length?"":"none")},hl=(e,t)=>{var Ue,Fe,fe,xe,Pe,Be,te,Ie,K,ce,we;let n=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let s=(Fe=(Ue=t==null?void 0:t.features)==null?void 0:Ue.reasoningDisplay)!=null?Fe:{},o=s.expandable!==!1,a=o&&ps.has(e.id),i=n.status!=="complete",d=Mf(e,(fe=s.previewMaxLines)!=null?fe:3),l=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",u=(xe=t==null?void 0:t.reasoning)!=null?xe:{},v=String((Pe=n.startedAt)!=null?Pe:Date.now()),x=()=>{let he=h("span","");return he.setAttribute("data-tool-elapsed",v),he.textContent=$a(n),he},A=(Be=u.renderCollapsedSummary)==null?void 0:Be.call(u,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:$a(n),createElapsedElement:x});typeof A=="string"&&A.trim()?(m.textContent=A,p.appendChild(m)):A instanceof HTMLElement?p.appendChild(A):(m.textContent=g,p.appendChild(m));let E=h("span","persona-text-xs persona-text-persona-primary");E.textContent=ru(n),p.appendChild(E);let B=(te=s.loadingAnimation)!=null?te:"none",P=u.activeTextTemplate,I=u.completeTextTemplate,R=i?P:I,w=A instanceof HTMLElement,W=(he,Ce,Ve)=>{let Y=Ve;for(let ne of Ce){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(Y)),ae.textContent=ne===" "?"\xA0":ne,he.appendChild(ae),Y++}return Y},$=(he,Ce)=>{m.textContent="";let Ve=_a(he,""),Y=0;for(let ne of Ve){let ae=ne.styles.length>0?(()=>{let me=h("span",ne.styles.map(le=>`persona-tool-text-${le}`).join(" "));return m.appendChild(me),me})():m;if(ne.isDuration&&i)ae.appendChild(x());else{let me=ne.isDuration?$a(n):ne.text;Ce?Y=W(ae,me,Y):ae.appendChild(document.createTextNode(me))}}};if(!w&&R)if(E.style.display="none",m.style.display="",i&&B!=="none"){let he=(Ie=u.loadingAnimationDuration)!=null?Ie:2e3;m.setAttribute("data-preserve-animation","true"),B==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${he}ms`),$(R,!1)):(m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${he}ms`),B==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),$(R,!0))}else $(R,!1);else if(!w&&i&&B!=="none"){m.style.display="";let he=(K=u.loadingAnimationDuration)!=null?K:2e3;if(m.setAttribute("data-preserve-animation","true"),B==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${he}ms`);else{m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${he}ms`),B==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let Ce=m.textContent||g;m.textContent="",W(m,Ce,0)}n.status==="complete"&&(m.style.display="none")}else w||(n.status==="complete"?m.style.display="none":m.style.display="");let _=null;if(o){_=h("div","persona-flex persona-items-center");let Ce=be(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?_.appendChild(Ce):_.textContent=a?"Hide":"Show";let Ve=h("div","persona-flex persona-items-center persona-ml-auto");Ve.append(_),l.append(p,Ve)}else l.append(p);let D=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","reasoning"),D.style.display="none",D.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let he=(we=(ce=t==null?void 0:t.reasoning)==null?void 0:ce.renderCollapsedPreview)==null?void 0:we.call(ce,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Ef(D,he)||(D.textContent=d),D.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,D),r;let U=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");U.style.display=a?"":"none";let V=n.chunks.join(""),se=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return se.textContent=V||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),U.appendChild(se),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),_){_.innerHTML="";let Ce=be(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?_.appendChild(Ce):_.textContent=a?"Hide":"Show"}U.style.display=a?"":"none",D.style.display=a?"none":D.textContent||D.childNodes.length?"":"none"})(),r.append(l,D,U),r};var us=new Set,kf=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Lf=(e,t)=>{var o;let n=e.toolCall;if(!n)return"";let r=((o=n.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
25
|
+
`);let s=ns(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
26
|
+
`):""},Pf=(e,t)=>{var p,m,g,u,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=Lf(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?ou(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(u=t==null?void 0:t.toolCall)!=null?u:{},l=a;return s==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Qi(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Qi(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},Vu=(e,t,n)=>{var p;let r=us.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=s.toggleTextColor||s.headerTextColor||"currentColor",g=be(r?"chevron-up":"chevron-down",16,m,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},yl=(e,t)=>{var V,se,Re,Ue,Fe,fe,xe,Pe,Be;let n=e.toolCall,r=(V=t==null?void 0:t.toolCall)!=null?V:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!n)return s;let o=(Re=(se=t==null?void 0:t.features)==null?void 0:se.toolCallDisplay)!=null?Re:{},a=o.expandable!==!1,i=a&&us.has(e.id),{summary:d,previewText:l,isActive:p}=Pf(e,t),m=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(u.style.color=r.headerTextColor);let v=String((Ue=n.startedAt)!=null?Ue:Date.now()),x=()=>{let te=h("span","");return te.setAttribute("data-tool-elapsed",v),te.textContent=Us(n),te},A=(fe=r.renderCollapsedSummary)==null?void 0:fe.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Fe=o.collapsedMode)!=null?Fe:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Us(n),createElapsedElement:x});typeof A=="string"&&A.trim()?(u.textContent=A,g.appendChild(u)):A instanceof HTMLElement?g.appendChild(A):(u.textContent=d,g.appendChild(u));let E=(xe=o.loadingAnimation)!=null?xe:"none",B=r.activeTextTemplate,P=r.completeTextTemplate,I=p?B:P,R=A instanceof HTMLElement,w=(te,Ie,K)=>{let ce=K;for(let we of Ie){let he=h("span","persona-tool-char");he.style.setProperty("--char-index",String(ce)),he.textContent=we===" "?"\xA0":we,te.appendChild(he),ce++}return ce},W=(te,Ie)=>{var he;u.textContent="";let K=((he=n.name)==null?void 0:he.trim())||"tool",ce=_a(te,K),we=0;for(let Ce of ce){let Ve=Ce.styles.length>0?(()=>{let Y=h("span",Ce.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return u.appendChild(Y),Y})():u;if(Ce.isDuration&&p)Ve.appendChild(x());else{let Y=Ce.isDuration?Us(n):Ce.text;Ie?we=w(Ve,Y,we):Ve.appendChild(document.createTextNode(Y))}}};if(!R)if(p&&E!=="none"){let te=(Pe=r.loadingAnimationDuration)!=null?Pe:2e3;if(u.setAttribute("data-preserve-animation","true"),E==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${te}ms`),I&&W(I,!1);else if(u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${te}ms`),E==="shimmer-color"&&(r.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),I)W(I,!0);else{let Ie=u.textContent||d;u.textContent="",w(u,Ie,0)}}else I&&W(I,!1);let $=null;if(a){$=h("div","persona-flex persona-items-center");let te=r.toggleTextColor||r.headerTextColor||"currentColor",Ie=be(i?"chevron-up":"chevron-down",16,te,2);Ie?$.appendChild(Ie):$.textContent=i?"Hide":"Show";let K=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append($),m.append(g,K)}else m.append(g);let _=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(_.setAttribute("data-persona-collapsed-preview","tool"),_.style.display="none",_.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let te=(Be=r.renderCollapsedPreview)==null?void 0:Be.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});kf(_,te)||(_.textContent=l),_.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,_),s;let D=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(D.style.display=i?"":"none",r.contentBackgroundColor&&(D.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(D.style.color=r.contentTextColor),r.contentPaddingX&&(D.style.paddingLeft=r.contentPaddingX,D.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(D.style.paddingTop=r.contentPaddingY,D.style.paddingBottom=r.contentPaddingY),n.name){let te=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?te.style.color=r.contentTextColor:r.headerTextColor&&(te.style.color=r.headerTextColor),te.textContent=n.name,D.appendChild(te)}if(n.args!==void 0){let te=h("div","persona-space-y-1"),Ie=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ie.style.color=r.labelTextColor),Ie.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",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=ns(n.args),te.append(Ie,K),D.appendChild(te)}if(n.chunks&&n.chunks.length){let te=h("div","persona-space-y-1"),Ie=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ie.style.color=r.labelTextColor),Ie.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",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=n.chunks.join(""),te.append(Ie,K),D.appendChild(te)}if(n.status==="complete"&&n.result!==void 0){let te=h("div","persona-space-y-1"),Ie=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ie.style.color=r.labelTextColor),Ie.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",r.codeBlockBackgroundColor&&(K.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(K.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(K.style.color=r.codeBlockTextColor),K.textContent=ns(n.result),te.append(Ie,K),D.appendChild(te)}if(n.status==="complete"&&typeof n.duration=="number"){let te=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(te.style.color=r.contentTextColor),te.textContent=`Duration: ${n.duration}ms`,D.appendChild(te)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),$){$.innerHTML="";let te=r.toggleTextColor||r.headerTextColor||"currentColor",Ie=be(i?"chevron-up":"chevron-down",16,te,2);Ie?$.appendChild(Ie):$.textContent=i?"Hide":"Show"}D.style.display=i?"":"none",_.style.display=i?"none":_.textContent||_.childNodes.length?"":"none"})(),s.append(m,_,D),s};var uo=require("partial-json");var xl="ask_user_question",bl=8,ms="data-persona-ask-sheet-for",If="Other",Wf="Other\u2026",Ju="Type your own answer here",Gu="Send",Rf="Next",Hf="Back",Bf="Submit all",Df="Skip",Nf=3,vl="data-ask-current-index",wl="data-ask-question-count",Xu="data-ask-answers",Cl="data-ask-grouped",Qu="data-ask-layout",Ff=e=>e.layout==="pills"?"pills":"rows",Of=e=>e.getAttribute(Qu)==="pills"?"pills":"rows",Ku=!1,Yu=e=>e.replace(/["\\]/g,"\\$&"),_r=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===xl,Si=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},jr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=(0,uo.parse)(s,uo.STR|uo.OBJ|uo.ARR);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},aa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>bl&&!Ku&&(Ku=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${bl}.`)),t.slice(0,bl)},$f=e=>{var t;return(t=aa(e)[0])!=null?t:null},_f=(e,t)=>{var n;return(n=aa(e)[t])!=null?n:null},Zu=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},em=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},jf=(e,t,n,r)=>{let o=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=em(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Uf=e=>{let n=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},qf=(e,t,n,r)=>{var p,m,g;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<Nf;u++)o.appendChild(Uf(r));return o}if(d.forEach((u,v)=>{o.appendChild(jf(u,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=r==="rows"?If:Wf;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),A=document.createElement("input");A.type="text",A.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",A.placeholder=(p=t.freeTextPlaceholder)!=null?p:Ju,A.setAttribute("data-ask-free-text-input","true"),A.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:u),x.appendChild(A),v.appendChild(x);let E=em(r,a,d.length);E&&v.appendChild(E),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:u,o.appendChild(v)}}return o},tm=(e,t)=>{var o,a;let r=h("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:Ju,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Gu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},zf=e=>{var r;let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:Gu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Vf=(e,t,n)=>{var l,p,m,g;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=n.backLabel)!=null?l:Hf,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:Df,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:Bf:(g=n.nextLabel)!=null?g:Rf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},$o=e=>{let t=e.getAttribute(Xu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},nm=(e,t)=>{e.setAttribute(Xu,JSON.stringify(t))},lr=e=>{var n;let t=Number((n=e.getAttribute(vl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Kf=(e,t)=>{e.setAttribute(vl,String(Math.max(0,Math.floor(t))))},gs=e=>{var n;let t=Number((n=e.getAttribute(wl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Cl)==="true",Jf=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Gf=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Ti=(e,t)=>{let{payload:n}=jr(t),r=aa(n),s=$o(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},rm=e=>{let t=$o(e),n=lr(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},om=e=>{if(!mo(e))return;let t=$o(e),n=lr(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Al=(e,t,n)=>{let r=Si(n),s=Of(e),{payload:o,complete:a}=jr(t),i=mo(e),d=lr(e),l=gs(e),p=i?_f(o,d):$f(o),m=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let B=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=B,v.classList.toggle("persona-ask-question-skeleton",!B&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let B=qf(p,r,a,s);x.replaceWith(B)}if(s!=="rows"){let B=e.querySelector('[data-ask-free-text-row="true"]');B&&B.replaceWith(tm(r,s))}let A=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!A?e.appendChild(zf(r)):(!m||i)&&A&&A.remove(),e.setAttribute("data-multi-select",m?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let B=Vf(d,l,r);E?E.replaceWith(B):e.appendChild(B)}else E&&E.remove();rm(e),om(e)},Xf=(e,t,n)=>{let r=Si(t),s=Ff(r),o=e.toolCall.id,a=aa(n),i=Math.max(1,a.length),d=i>1,l=Jf(e,a),p=d?Gf(e,i):0,m=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(ms,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(wl,String(i)),m.setAttribute(vl,String(p)),m.setAttribute(Cl,d?"true":"false"),m.setAttribute(Qu,s),nm(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Zu(m,r);let g=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=h("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),m.appendChild(g);let A=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return A.setAttribute("data-ask-pill-list","true"),A.setAttribute("role","group"),m.appendChild(A),s!=="rows"&&m.appendChild(tm(r,s)),Al(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Qf=(e,t,n)=>{let{payload:r}=jr(t),s=Math.max(1,aa(r).length);s>gs(e)&&(e.setAttribute(wl,String(s)),s>1&&!mo(e)&&e.setAttribute(Cl,"true")),Al(e,t,n)},sm=(e,t)=>{let n=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Si(t);Zu(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=jr(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},fs=(e,t,n)=>{if(!n||!_r(e)||Si(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${ms}]`).forEach(l=>{l.getAttribute(ms)!==s&&l.remove()});let a=n.querySelector(`[${ms}="${Yu(s)}"]`);if(a){Qf(a,e,t);return}let{payload:i}=jr(e),d=Xf(e,t,i);n.appendChild(d)},go=(e,t)=>{if(!e)return;let n=t?`[${ms}="${Yu(t)}"]`:`[${ms}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Sl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),fo=(e,t)=>{let n=$o(e),r=lr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,nm(e,n),rm(e),om(e)},Ei=(e,t,n,r)=>{let s=gs(e),o=Math.max(0,Math.min(s-1,r));Kf(e,o),Al(e,t,n)};var Tl=(e,t)=>{var x,A,E,B,P,I,R,w,W,$,_,D;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(A=r==null?void 0:r.borderColor)!=null?A:"var(--persona-approval-border, #fef08a)",!n)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=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(E=r==null?void 0:r.titleColor)!=null?E:"currentColor",p=be(d,20,l,2);p&&i.appendChild(p);let m=h("div","persona-flex-1 persona-min-w-0"),g=h("div","persona-flex persona-items-center persona-gap-2"),u=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(u.style.color=r.titleColor),u.textContent=(B=r==null?void 0:r.title)!=null?B:"Approval Required",g.appendChild(u),!s){let U=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");U.setAttribute("data-approval-status",n.status),n.status==="approved"?(U.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",U.style.color="var(--persona-palette-colors-success-700, #15803d)",U.textContent="Approved"):n.status==="denied"?(U.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",U.style.color="var(--persona-palette-colors-error-700, #b91c1c)",U.textContent="Denied"):n.status==="timeout"&&(U.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",U.style.color="var(--persona-palette-colors-warning-700, #b45309)",U.textContent="Timeout"),g.appendChild(U)}m.appendChild(g);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=n.description,m.appendChild(v),n.parameters){let U=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");r!=null&&r.parameterBackgroundColor&&(U.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(U.style.color=r.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=ns(n.parameters),m.appendChild(U)}if(s){let U=h("div","persona-flex persona-gap-2 persona-mt-2");U.setAttribute("data-approval-buttons","true");let V=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");V.type="button",V.style.backgroundColor=(P=r==null?void 0:r.approveButtonColor)!=null?P:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(I=r==null?void 0:r.approveButtonTextColor)!=null?I:"#ffffff",V.setAttribute("data-approval-action","approve");let se=be("shield-check",14,(R=r==null?void 0:r.approveButtonTextColor)!=null?R:"#ffffff",2);se&&(se.style.marginRight="4px",V.appendChild(se));let Re=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");V.appendChild(Re);let Ue=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");Ue.type="button",Ue.style.backgroundColor=(W=r==null?void 0:r.denyButtonColor)!=null?W:"transparent",Ue.style.color=($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",Ue.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ue.setAttribute("data-approval-action","deny");let Fe=be("shield-x",14,(_=r==null?void 0:r.denyButtonTextColor)!=null?_:"var(--persona-feedback-error, #dc2626)",2);Fe&&(Fe.style.marginRight="4px",Ue.appendChild(Fe));let fe=document.createTextNode((D=r==null?void 0:r.denyLabel)!=null?D:"Deny");Ue.appendChild(fe),U.append(V,Ue),m.appendChild(U)}return a.append(i,m),o.appendChild(a),o};var am=e=>{let t=[];return{buttons:t,render:(r,s,o,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(u=>u.role==="user"))return;let p=document.createDocumentFragment(),m=s?s.isStreaming():!1,g=u=>{switch(u){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'}};r.forEach(u=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=u,v.disabled=m,i!=null&&i.fontFamily&&(v.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(u))}),p.appendChild(v),t.push(v)}),e.appendChild(p)}}};var ia=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}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 t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var la=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var Yf=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Zf=new Set(["step_start","execution_start"]),eh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),th=new Set(["step_complete","agent_turn_complete"]),nh=new Set(["flow_complete","agent_complete"]),im=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),cm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,_o=(e,t)=>{let n=e[t];return cm(n)?n:void 0};function El(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Mi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function rh(e,t){return typeof t.type=="string"?t.type:e}function oh(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function sh(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function lm(e){var r,s,o,a,i;let t=_o(e,"result"),n=[_o(e,"tokens"),_o(e,"totalTokens"),t?_o(t,"tokens"):void 0,_o(e,"usage"),t?_o(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(s=(r=Qn(d.output))!=null?r:Qn(d.outputTokens))!=null?s:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Qn(e.outputTokens))!=null?o:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function ah(e){var n,r,s,o,a;let t=_o(e,"result");return(a=(s=(r=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?r:Qn(e.execution_time))!=null?s:Qn(e.duration))!=null?a:t?(o=Qn(t.executionTime))!=null?o:Qn(t.executionTimeMs):void 0}function ih(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ca=class{constructor(t=ih){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Mi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var o;if(!cm(n)){im.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=rh(t,n),s=this.now();if(Yf.has(r)){this.startRun(s);return}if(Zf.has(r)){this.run||this.startRun(s);return}if(eh.has(r)){if(!sh(r,n))return;let a=oh(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+El(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Mi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(th.has(r)){if(!this.run)return;let a=this.run,i=lm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+El(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:Mi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(nh.has(r)){if(!this.run)return;let a=this.run,i=lm(n),d=i!=null?i:a.exactOutputTokens+El(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:Mi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(im.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=ah(n);return o!=null?o:r-t.startedAt}};function hs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var lh={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},ch={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},dh=["flowName","stepName","reasoningText","text","name","tool","toolName"],ph=100;function uh(e,t){let n={...lh,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return ch}function mh(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function gh(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function fh(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;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 hh(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function yh(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function bh(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function xh(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function vh(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,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=r,i.appendChild(d),i}}function Ml(e,t,n,r,s,o,a,i){var g;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");hs(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(u=>u.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let u=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(m()),l;function m(){var V,se;let u=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 x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),A=be(d?"chevron-down":"chevron-right","14px","currentColor",2);A&&x.appendChild(A);let E=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=(V=r.timestampFormat)!=null?V:"relative";E.textContent=B==="relative"?mh(e.timestamp,n):gh(e.timestamp);let P=null;r.showSequenceNumbers!==!1&&(P=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let I=uh(e.type,r.badgeColors),R=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");R.style.backgroundColor=I.bg,R.style.color=I.text,R.style.borderColor=I.text+"50",R.textContent=e.type;let w=(se=r.descriptionFields)!=null?se:dh,W=fh(e.payload,w),$=null;W&&($=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),$.textContent=W);let _=h("div","persona-flex-1 persona-min-w-0"),D=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"),U=be("clipboard","12px","currentColor",1.5);return U&&D.appendChild(U),D.addEventListener("click",async Re=>{Re.stopPropagation(),await hh(yh(e)),D.innerHTML="";let Ue=be("check","12px","currentColor",1.5);Ue&&D.appendChild(Ue),setTimeout(()=>{D.innerHTML="";let Fe=be("clipboard","12px","currentColor",1.5);Fe&&D.appendChild(Fe)},1500)}),v.appendChild(x),v.appendChild(E),P&&v.appendChild(P),v.appendChild(R),$&&v.appendChild($),v.appendChild(_),v.appendChild(D),u.appendChild(v),d&&u.appendChild(vh(e,a,i)),u}}function dm(e){var v,x,A,E,B;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(v=s==null?void 0:s.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(A=i==null?void 0:i.label)!=null?A:"",m=(B=(E=s==null?void 0:s.features)==null?void 0:E.eventStream)!=null?B:{},g=o.find(P=>P.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&s){let P=g.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>u().element,onClose:r});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return u();function u(){let P=m.classNames,I=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");hs(I,P==null?void 0:P.panel);let R=[],w="",W="",$=null,_=[],D={},U=0,V=ii(),se=0,Re=0,Ue=!1,Fe=null,fe=!1,xe=0,Pe=new Set,Be=new Map,te="",Ie="",K=null,ce,we,he,Ce,Ve,Y=null,ne=null,ae=null;function me(){let re=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ge=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");hs(ge,P==null?void 0:P.headerBar);let wt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(wt.textContent="Events",ce=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"),ce.textContent="0",a){ne=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let Dn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Dn.textContent="Throughput",Y=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 persona-tabular-nums"),Y.textContent="-- tok/s",ae=h("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ae.style.display="none",ae.style.pointerEvents="none";let Zn=ne,bn=ae,Nn=()=>{if(!bn.textContent)return;let vr=Zn.getBoundingClientRect(),Fn=re.getBoundingClientRect();bn.style.left=`${vr.left-Fn.left}px`,bn.style.top=`${vr.bottom-Fn.top+4}px`,bn.style.display="block"},mt=()=>{bn.style.display="none"};ne.addEventListener("mouseenter",Nn),ne.addEventListener("mouseleave",mt),ne.appendChild(Dn),ne.appendChild(Y)}let qt=h("div","persona-flex-1");we=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 en=h("option","");en.value="",en.textContent="All events",we.appendChild(en),he=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"),he.type="button",he.title="Copy All";let Tt=be("clipboard-copy","12px","currentColor",1.5);Tt&&he.appendChild(Tt);let Ct=h("span","persona-text-xs");Ct.textContent="Copy All",he.appendChild(Ct),ge.appendChild(wt),ge.appendChild(ce),ne&&ge.appendChild(ne),ge.appendChild(qt),ge.appendChild(we),ge.appendChild(he);let ht=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");hs(ht,P==null?void 0:P.searchBar);let bt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),Vt=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");bt&&Vt.appendChild(bt),Ce=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"),hs(Ce,P==null?void 0:P.searchInput),Ce.type="text",Ce.placeholder="Search event payloads...",Ve=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"),Ve.type="button",Ve.style.display="none";let nt=be("x","12px","currentColor",2);return nt&&Ve.appendChild(nt),ht.appendChild(Vt),ht.appendChild(Ce),ht.appendChild(Ve),re.appendChild(ge),re.appendChild(ht),ae&&re.appendChild(ae),re}let le,oe=o.find(re=>re.renderEventStreamToolbar);if(oe!=null&&oe.renderEventStreamToolbar&&s){let re=oe.renderEventStreamToolbar({config:s,defaultRenderer:()=>me(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ge=>{w=ge,Bn(),F()},onSearchChange:ge=>{W=ge,Bn(),F()}});le=re!=null?re:me()}else le=me();let Ye=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");Ye.style.display="none";function We(){if(!a||!Y||!ne)return;let re=a();Y.textContent=bh(re);let ge=xh(re);ae&&(ae.textContent=ge,ge||(ae.style.display="none")),ge?ne.setAttribute("aria-label",ge):ne.removeAttribute("aria-label")}let de=h("div","persona-flex-1 persona-min-h-0 persona-relative"),X=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let _e=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");hs(_e,P==null?void 0:P.scrollIndicator),_e.style.display="none",_e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Mt=be(l,"14px","currentColor",2);Mt&&_e.appendChild(Mt);let pe=h("span","");pe.textContent=p,_e.appendChild(pe);let ie=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ie.style.display="none",de.appendChild(X),de.appendChild(ie),de.appendChild(_e),I.setAttribute("tabindex","0"),I.appendChild(le),I.appendChild(Ye),I.appendChild(de);function kn(){let re=t.getAll(),ge={};for(let Ct of re)ge[Ct.type]=(ge[Ct.type]||0)+1;let wt=Object.keys(ge).sort(),qt=wt.length!==_.length||!wt.every((Ct,ht)=>Ct===_[ht]),en=!qt&&wt.some(Ct=>ge[Ct]!==D[Ct]),yn=re.length!==Object.values(D).reduce((Ct,ht)=>Ct+ht,0);if(!qt&&!en&&!yn||(_=wt,D=ge,!we))return;let Tt=we.value;if(we.options[0].textContent="All events",qt){for(;we.options.length>1;)we.remove(1);for(let Ct of wt){let ht=h("option","");ht.value=Ct,ht.textContent=`${Ct} (${ge[Ct]||0})`,we.appendChild(ht)}Tt&&wt.includes(Tt)?we.value=Tt:Tt&&(we.value="",w="")}else for(let Ct=1;Ct<we.options.length;Ct++){let ht=we.options[Ct];ht.textContent=`${ht.value} (${ge[ht.value]||0})`}}function $t(){let re=t.getAll();if(w&&(re=re.filter(ge=>ge.type===w)),W){let ge=W.toLowerCase();re=re.filter(wt=>wt.type.toLowerCase().includes(ge)||wt.payload.toLowerCase().includes(ge))}return re}function cn(){return w!==""||W!==""}function Bn(){U=0,se=0,V.resume(),_e.style.display="none"}function Yn(re){Pe.has(re)?Pe.delete(re):Pe.add(re),K=re;let ge=X.scrollTop,wt=V.isFollowing();fe=!0,V.pause(),F(),X.scrollTop=ge,wt&&V.resume(),fe=!1}function qe(){return Xs(X,50)}function F(){Re=Date.now(),Ue=!1,We(),kn();let re=t.getEvictedCount();re>0?(Ye.textContent=`${re.toLocaleString()} older events truncated`,Ye.style.display=""):Ye.style.display="none",R=$t();let ge=R.length,wt=t.getSize()>0;ce&&(ce.textContent=String(t.getSize())),ge===0&&wt&&cn()?(ie.textContent=W?`No events matching '${W}'`:"No events matching filter",ie.style.display="",X.style.display="none"):(ie.style.display="none",X.style.display=""),he&&(he.title=cn()?`Copy Filtered (${ge})`:"Copy All"),d&&!V.isFollowing()&&ge>U&&(se+=ge-U,pe.textContent=p?`${p}${se>0?` (${se})`:""}`:"",_e.style.display=""),U=ge;let qt=t.getAll(),en=qt.length>0?qt[0].timestamp:0,yn=new Set(R.map(ht=>ht.id));for(let ht of Pe)yn.has(ht)||Pe.delete(ht);let Tt=w!==te||W!==Ie,Ct=Be.size===0&&R.length>0;if(Tt||Ct||R.length===0){X.innerHTML="",Be.clear();let ht=document.createDocumentFragment();for(let bt=0;bt<R.length;bt++){let Vt=Ml(R[bt],bt,en,m,Pe,Yn,o,s);Be.set(R[bt].id,Vt),ht.appendChild(Vt)}X.appendChild(ht),te=w,Ie=W,K=null}else{if(K!==null){let bt=Be.get(K);if(bt&&bt.parentNode===X){let Vt=R.findIndex(nt=>nt.id===K);if(Vt>=0){let nt=Ml(R[Vt],Vt,en,m,Pe,Yn,o,s);X.insertBefore(nt,bt),bt.remove(),Be.set(K,nt)}}K=null}let ht=new Set(R.map(bt=>bt.id));for(let[bt,Vt]of Be)ht.has(bt)||(Vt.remove(),Be.delete(bt));for(let bt=0;bt<R.length;bt++){let Vt=R[bt];if(!Be.has(Vt.id)){let nt=Ml(Vt,bt,en,m,Pe,Yn,o,s);Be.set(Vt.id,nt),X.appendChild(nt)}}}V.isFollowing()&&(X.scrollTop=X.scrollHeight)}function Se(){if(Date.now()-Re>=ph){Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),F();return}Ue||(Ue=!0,Fe=requestAnimationFrame(()=>{Fe=null,F()}))}let De=(re,ge)=>{if(!he)return;he.innerHTML="";let wt=be(re,"12px","currentColor",1.5);wt&&he.appendChild(wt);let qt=h("span","persona-text-xs");qt.textContent="Copy All",he.appendChild(qt),setTimeout(()=>{he.innerHTML="";let en=be("clipboard-copy","12px","currentColor",1.5);en&&he.appendChild(en);let yn=h("span","persona-text-xs");yn.textContent="Copy All",he.appendChild(yn),he.disabled=!1},ge)},Ne=async()=>{if(he){he.disabled=!0;try{let re;cn()?re=R:n?(re=await n(),re.length===0&&(re=t.getAll())):re=t.getAll();let ge=re.map(wt=>{try{return JSON.parse(wt.payload)}catch{return wt.payload}});await navigator.clipboard.writeText(JSON.stringify(ge,null,2)),De("check",1500)}catch{De("x",1500)}}},je=()=>{we&&(w=we.value,Bn(),F())},pt=()=>{!Ce||!Ve||(Ve.style.display=Ce.value?"":"none",$&&clearTimeout($),$=setTimeout(()=>{W=Ce.value,Bn(),F()},150))},ot=()=>{!Ce||!Ve||(Ce.value="",W="",Ve.style.display="none",$&&clearTimeout($),Bn(),F())},St=()=>{if(fe)return;let re=X.scrollTop,{action:ge,nextLastScrollTop:wt}=li({following:V.isFollowing(),currentScrollTop:re,lastScrollTop:xe,nearBottom:qe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});xe=wt,ge==="resume"?(V.resume(),se=0,_e.style.display="none"):ge==="pause"&&(V.pause(),d&&(pe.textContent=p,_e.style.display=""))},Ut=re=>{let ge=ci({following:V.isFollowing(),deltaY:re.deltaY,nearBottom:qe(),resumeWhenNearBottom:!0});ge==="pause"?(V.pause(),d&&(pe.textContent=p,_e.style.display="")):ge==="resume"&&(V.resume(),se=0,_e.style.display="none")},z=()=>{d&&(X.scrollTop=X.scrollHeight,V.resume(),se=0,_e.style.display="none")},_t=re=>{let ge=re.target;if(!ge||ge.closest("button"))return;let wt=ge.closest("[data-event-id]");if(!wt)return;let qt=wt.getAttribute("data-event-id");qt&&Yn(qt)},Ze=re=>{if((re.metaKey||re.ctrlKey)&&re.key==="f"){re.preventDefault(),Ce==null||Ce.focus(),Ce==null||Ce.select();return}re.key==="Escape"&&(Ce&&document.activeElement===Ce?(ot(),Ce.blur(),I.focus()):r&&r())};he&&he.addEventListener("click",Ne),we&&we.addEventListener("change",je),Ce&&Ce.addEventListener("input",pt),Ve&&Ve.addEventListener("click",ot),X.addEventListener("scroll",St),X.addEventListener("wheel",Ut,{passive:!0}),X.addEventListener("click",_t),_e.addEventListener("click",z),I.addEventListener("keydown",Ze);function Ft(){$&&clearTimeout($),Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),Ue=!1,Be.clear(),he&&he.removeEventListener("click",Ne),we&&we.removeEventListener("change",je),Ce&&Ce.removeEventListener("input",pt),Ve&&Ve.removeEventListener("click",ot),X.removeEventListener("scroll",St),X.removeEventListener("wheel",Ut),X.removeEventListener("click",_t),_e.removeEventListener("click",z),I.removeEventListener("keydown",Ze)}return{element:I,update:Se,destroy:Ft}}}function pm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);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 l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(u)}else m.textContent=a;if(l.append(p,m),i.append(d,l),s==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var um=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){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",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>pm(e,t)});if(p)return p}return pm(e,t)};var kl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},Ur=new kl;Ur.register("PersonaArtifactCard",um);function wh(e){var s;let t=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function mm(e,t){var we,he,Ce,Ve;let n=(he=(we=e.features)==null?void 0:we.artifacts)==null?void 0:he.layout,s=((Ce=n==null?void 0:n.toolbarPreset)!=null?Ce:"default")==="document",o=(Ve=n==null?void 0:n.panePadding)==null?void 0:Ve.trim(),a=e.markdown?Po(e.markdown):null,i=es(e.sanitize),d=Y=>{let ne=a?a(Y):Io(Y);return i?i(ne):ne},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};l&&l.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let m=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");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let g=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&g.classList.add("persona-artifact-toolbar-document");let u=h("span","persona-text-xs persona-font-medium persona-truncate");u.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 Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let x="rendered",A=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=s?jt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):jt({icon:"eye",label:"Rendered view"}),B=s?jt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):jt({icon:"code-2",label:"Source"}),P=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),I=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,R=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,w=n==null?void 0:n.documentToolbarCopyMenuItems,W=!!(R&&w&&w.length>0),$=null,_,D=null,U=null;if(s&&(I||R)&&!W){if(_=I?oa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let Y=be("chevron-down",14,"currentColor",2);Y&&_.appendChild(Y)}}else s&&W?($=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),_=I?oa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=jt({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"}}),$.append(_,D)):s?_=jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):_=jt({icon:"copy",label:"Copy"});let V=s?jt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):jt({icon:"refresh-cw",label:"Refresh"}),se=s?jt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):jt({icon:"x",label:"Close"}),Re=()=>{var le,oe,Ye;let Y=(le=Be.find(We=>We.id===te))!=null?le:Be[Be.length-1],ne=(oe=Y==null?void 0:Y.id)!=null?oe:null,ae=(Y==null?void 0:Y.artifactType)==="markdown"&&(Ye=Y.markdown)!=null?Ye:"",me=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:ae,jsonPayload:me,id:ne}},Ue=async()=>{var le;let{markdown:Y,jsonPayload:ne}=Re(),ae=(le=Be.find(oe=>oe.id===te))!=null?le:Be[Be.length-1],me=(ae==null?void 0:ae.artifactType)==="markdown"?Y:ae?ne:"";try{await navigator.clipboard.writeText(me)}catch{}};if(_.addEventListener("click",async()=>{let Y=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Y&&W){let{markdown:ne,jsonPayload:ae,id:me}=Re();try{await Y({actionId:"primary",artifactId:me,markdown:ne,jsonPayload:ae})}catch{}return}await Ue()}),D&&(w!=null&&w.length)){let Y=()=>{var ae;return(ae=m.closest("[data-persona-root]"))!=null?ae:document.body},ne=()=>{U=po({items:w.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:me,jsonPayload:le,id:oe}=Re(),Ye=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ye?await Ye({actionId:ae,artifactId:oe,markdown:me,jsonPayload:le}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(me):ae==="json"||ae==="source"?await navigator.clipboard.writeText(le):await navigator.clipboard.writeText(me||le)}catch{}},anchor:$!=null?$:D,position:"bottom-right",portal:Y()})};m.isConnected?ne():requestAnimationFrame(ne),D.addEventListener("click",ae=>{ae.stopPropagation(),U==null||U.toggle()})}V.addEventListener("click",async()=>{var Y;try{await((Y=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Y.call(n))}catch{}K()}),se.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let Fe=()=>{s&&(E.setAttribute("aria-pressed",x==="rendered"?"true":"false"),B.setAttribute("aria-pressed",x==="source"?"true":"false"))};E.addEventListener("click",()=>{x="rendered",Fe(),K()}),B.addEventListener("click",()=>{x="source",Fe(),K()});let fe=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(g.replaceChildren(),A.append(E,B),$?P.append($,V,se):P.append(_,V,se),g.append(A,fe,P),Fe()):(g.appendChild(u),g.appendChild(v)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let xe=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"),Pe=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(xe.style.paddingLeft=o,xe.style.paddingRight=o,Pe.style.padding=o),m.appendChild(g),m.appendChild(xe),m.appendChild(Pe);let Be=[],te=null,Ie=!1,K=()=>{var me,le,oe,Ye;let Y=s&&Be.length<=1;xe.classList.toggle("persona-hidden",Y),xe.replaceChildren();for(let We of Be){let de=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");de.type="button",de.textContent=We.title||We.id.slice(0,8),We.id===te&&de.classList.add("persona-bg-persona-container","persona-border-persona-border"),de.addEventListener("click",()=>t.onSelect(We.id)),xe.appendChild(de)}Pe.replaceChildren();let ne=te&&Be.find(We=>We.id===te)||Be[Be.length-1];if(!ne)return;if(s){let We=ne.artifactType==="markdown"?"MD":(me=ne.component)!=null?me:"Component",X=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";fe.textContent=`${X} \xB7 ${We}`}else u.textContent="Artifacts";if(ne.artifactType==="markdown"){if(s&&x==="source"){let de=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");de.textContent=(le=ne.markdown)!=null?le:"",Pe.appendChild(de);return}let We=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");We.innerHTML=d((oe=ne.markdown)!=null?oe:""),Pe.appendChild(We);return}let ae=ne.component?Ur.get(ne.component):void 0;if(ae){let de={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=ae((Ye=ne.props)!=null?Ye:{},de);if(X){Pe.appendChild(X);return}}catch{}}Pe.appendChild(wh(ne))},ce=()=>{var ne;let Y=Be.length>0;if(m.classList.toggle("persona-hidden",!Y),l){let ae=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,le=((ne=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&le&&Ie?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(Y){var ne,ae,me;Be=Y.artifacts,te=(me=(ae=Y.selectedId)!=null?ae:(ne=Y.artifacts[Y.artifacts.length-1])==null?void 0:ne.id)!=null?me:null,Be.length>0&&(Ie=!0),K(),ce()},setMobileOpen(Y){Ie=Y,!Y&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):ce()}}}function cr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function gm(e,t){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"),!cr(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Ch(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 ki(e,t){var d,l,p,m,g,u,v,x,A,E;if(!cr(t)){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"),Ch(e),gm(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=n==null?void 0:n.paneBackground)==null?void 0:u.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(A=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:A.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),gm(e,t)}var fm=["panel","seamless"];function Li(e,t){var i,d,l,p,m,g;for(let u of fm)e.classList.remove(`persona-artifact-appearance-${u}`);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"),!cr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",s=fm.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function hm(e,t){var n,r,s;return!t||!cr(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Ah(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Sh(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Th(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Eh(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function ym(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function bm(e,t,n,r,s,o){let a=Ah(s,200),i=Eh(t,n,r,200);i=Math.max(a,i);let d=Sh(o);return d!==null&&(i=Math.min(i,d)),Th(e,a,i)}var xm={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"}},Ll=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,A;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=xm[a])!=null?x:xm.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let E=h("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,d.appendChild(E)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var w,W;let B=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");B.htmlFor=`${t.id}-${a}-${E.name}`;let P=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=E.label,B.appendChild(P);let I=(w=E.type)!=null?w:"text",R;I==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=I),R.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",R.id=`${t.id}-${a}-${E.name}`,R.name=E.name,R.placeholder=(W=E.placeholder)!=null?W:"",E.required&&(R.required=!0),B.appendChild(R),p.appendChild(B)});let m=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=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");u.type="submit",u.textContent=(A=i.submitLabel)!=null?A:"Submit",m.appendChild(g),m.appendChild(u),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async E=>{var R,w;E.preventDefault();let B=(R=n.formEndpoint)!=null?R:"/form",P=new FormData(p),I={};P.forEach((W,$)=>{I[$]=W}),I.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let W=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let $=await W.json();g.textContent=(w=$.message)!=null?w:"Thanks! We'll be in touch soon.",$.success&&$.nextPrompt&&await r.sendMessage(String($.nextPrompt))}catch(W){g.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var Pl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},da=new Pl;var vm=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,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 Mh=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},kh=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},pa=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Mh(e),n=kh(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Il=e=>typeof e=="string"?e:e==null?"":String(e),jo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Il(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=Il(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Il(n.text)}}},wm=e=>Array.isArray(e)?e.map(t=>String(t)):[],ua=e=>{let t=new Set(wm(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(wm(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.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((l,p)=>l||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},m=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Lh=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Ph=e=>e.map(t=>({...t,streaming:!1})),Ih=e=>e.map(t=>({...t,status:"complete"})),Pi=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Lh(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?Ph(n.messages):void 0,artifacts:n.artifacts?Ih(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var ys=require("partial-json");function Wh(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Rh(e,t){if(!Wh(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Ii(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=(0,ys.parse)(n,ys.STR|ys.OBJ),o=Rh(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Cm(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Wi(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=Ur.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,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 Am(){let e=Ii();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Sm(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Ri(e){let t=Sm(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Hi(e){let t=Sm(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Hh=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Bi(e){let{onSubmit:t,onDismiss:n,title:r="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:l=Hh}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,u.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,u.appendChild(x),g.appendChild(u);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-csat",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let w=1;w<=5;w++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),W.title=l[w-1],W.dataset.rating=String(w),W.innerHTML=`
|
|
27
27
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
28
28
|
<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>
|
|
29
29
|
</svg>
|
|
30
|
-
`,W.addEventListener("click",()=>{m=w,E.forEach((_,$)=>{let D=$<w;_.classList.toggle("selected",D),_.setAttribute("aria-checked",$===w-1?"true":"false")})}),E.push(W),A.appendChild(W)}g.appendChild(A);let B=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=o,B.rows=3,B.setAttribute("aria-label","Additional comments"),w.appendChild(B),g.appendChild(w)}let P=document.createElement("div");P.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{t==null||t(),p.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(m===null){A.classList.add("persona-feedback-shake"),setTimeout(()=>A.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let w=(B==null?void 0:B.value.trim())||void 0;await n(m,w),p.remove()}catch(w){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),P.appendChild(I),P.appendChild(R),g.appendChild(P),p.appendChild(g),p}function Bi(e){let{onSubmit:n,onDismiss:t,title:r="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:l="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,u=document.createElement("div");u.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,v.appendChild(A),u.appendChild(v);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let B=document.createElement("div");B.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=l;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=p,B.appendChild(P),B.appendChild(I);let R=document.createElement("div");R.className="persona-feedback-numbers";let w=[];for(let U=0;U<=10;U++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${U} out of 10`),V.textContent=String(U),V.dataset.rating=String(U),U<=6?V.classList.add("persona-feedback-detractor"):U<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{g=U,w.forEach((se,Re)=>{se.classList.toggle("selected",Re===U),se.setAttribute("aria-checked",Re===U?"true":"false")})}),w.push(V),R.appendChild(V)}E.appendChild(B),E.appendChild(R),u.appendChild(E);let W=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=o,W.rows=3,W.setAttribute("aria-label","Additional comments"),U.appendChild(W),u.appendChild(U)}let _=document.createElement("div");_.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{t==null||t(),m.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(g===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let U=(W==null?void 0:W.value.trim())||void 0;await n(g,U),m.remove()}catch(U){D.disabled=!1,D.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),_.appendChild($),_.appendChild(D),u.appendChild(_),m.appendChild(u),m}var bs="persona-chat-history",Hh=30*1e3,Bh={"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 Dh(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(s=Bh[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function Di(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function Nh(e){var n,t,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.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:(l=e.clearOnChatClear)!=null?l:!0}:null}function Fh(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var Il=e=>!e||typeof e!="object"?{}:{...e},Sm=e=>e.map(n=>({...n,streaming:!1})),Tm=(e,n,t)=>{let r=e!=null&&e.markdown?Po(e.markdown):null,s=es(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 l,p,m;let a=(l=o.text)!=null?l:"",i=(p=o.message.rawContent)!=null?p:null;if(n){let g=n.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(m=i!=null?i:o.text)!=null?m:""}):r?d=r(a):d=Io(a),s?s(d):d}};function Em(e){var i,d,l,p;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=be(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let m=h("span","persona-drop-overlay-label");m.textContent=e.label,n.appendChild(m)}return n}var Ni=(e,n,t)=>{var tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,wc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,_c,$c,jc,Uc,qc,zc,Vc,Kc,Jc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=ei(n),s=da.getForInstance(r.plugins);r.components&&Ur.registerAll(r.components);let o=xm(),i=r.persistState===!1?null:(tc=r.storageAdapter)!=null?tc:Li(),d={},l=null,p=!1,m=c=>{if(r.onStateLoaded)try{let f=r.onStateLoaded(c);if(f&&typeof f=="object"&&"state"in f){let{state:y,open:b}=f;return b&&(p=!0),y}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(f=>{let y=f!=null?f:{messages:[],metadata:{}};return m(y)});else{let f=c!=null?c:{messages:[],metadata:{}},y=m(f);y.metadata&&(d=Il(y.metadata)),(nc=y.messages)!=null&&nc.length&&(r={...r,initialMessages:y.messages}),(rc=y.artifacts)!=null&&rc.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(oc=y.selectedArtifactId)!=null?oc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=m({messages:[],metadata:{}});(sc=c.messages)!=null&&sc.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,u=c=>{var y;d=(y=c({...d}))!=null?y:{},Vo()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[pa],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[jo.message,jo.messageAndClick],A=ua({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let E=(ic=(ac=r.launcher)==null?void 0:ac.enabled)!=null?ic:!0,B=(cc=(lc=r.launcher)==null?void 0:lc.autoExpand)!=null?cc:!1,P=(dc=r.autoFocusInput)!=null?dc:!1,I=B,R=E,w=(uc=(pc=r.layout)==null?void 0:pc.header)==null?void 0:uc.layout,W=!1,_=()=>co(r),$=()=>E||_(),D=_()?!1:E?B:!0,U=!1,V=null,se=()=>{U=!0,V&&clearTimeout(V),V=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},Re=Tm(r,A,se),Ue=(gc=(mc=r.features)==null?void 0:mc.showReasoning)!=null?gc:!0,Fe=(hc=(fc=r.features)==null?void 0:fc.showToolCalls)!=null?hc:!0,fe=(bc=(yc=r.features)==null?void 0:yc.showEventStreamToggle)!=null?bc:!1,xe=(vc=(xc=r.features)==null?void 0:xc.scrollToBottom)!=null?vc:{},Be=`${(Cc=typeof r.persistState=="object"?(wc=r.persistState)==null?void 0:wc.keyPrefix:void 0)!=null?Cc:"persona-"}event-stream`,te=fe?new la(Be):null,Ie=(Tc=(Sc=(Ac=r.features)==null?void 0:Ac.eventStream)==null?void 0:Sc.maxEvents)!=null?Tc:2e3,K=fe?new ia(Ie,te):null,ce=fe?new ca:null,we=null,he=!1,Ce=null,Ve=0;te==null||te.open().then(()=>K==null?void 0:K.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Y={onCopy:c=>{var f,y;o.emit("message:copy",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(f=r.messageActions)==null?void 0:f.onCopy)==null||y.call(f,c)},onFeedback:c=>{var f,y;o.emit("message:feedback",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(f=r.messageActions)==null?void 0:f.onFeedback)==null||y.call(f,c)}},ne=(Ec=r.statusIndicator)!=null?Ec:{},ae=c=>{var f,y,b,k;return c==="idle"?(f=ne.idleText)!=null?f:fn.idle:c==="connecting"?(y=ne.connectingText)!=null?y:fn.connecting:c==="connected"?(b=ne.connectedText)!=null?b:fn.connected:c==="error"?(k=ne.errorText)!=null?k:fn.error:fn[c]};function me(c,f,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let k=document.createElement("a");k.href=y.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=f,k.style.color="inherit",k.style.textDecoration="none",c.appendChild(k)}else c.textContent=f}let{wrapper:le,panel:oe,pillRoot:Ye}=Ou(r),We=_u(r,$()),{container:de,body:X,messagesWrapper:$e,suggestions:Mt,textarea:pe,sendButton:ie,sendButtonWrapper:kn,composerForm:_t,statusText:cn,introTitle:Bn,introSubtitle:Yn,closeButton:qe,iconHolder:F,headerTitle:Se,headerSubtitle:De,header:Ne,footer:je,actionsRow:pt,leftActions:ot,rightActions:St}=We,Ut=We.setSendButtonMode,z=We.micButton,$t=We.micButtonWrapper,Ze=We.attachmentButton,Ft=We.attachmentButtonWrapper,re=We.attachmentInput,ge=We.attachmentPreviewsContainer;de.classList.add("persona-relative"),X.classList.add("persona-relative");let wt=12,qt=()=>{var c;return(c=xe.label)!=null?c:""},en=()=>{var c;return(c=xe.iconName)!=null?c:"arrow-down"},yn=()=>xe.enabled!==!1,Tt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let Ct=h("span","persona-flex persona-items-center"),ht=h("span","");Tt.append(Ct,ht),de.appendChild(Tt);let bt=()=>{let f=je.style.display==="none"?0:je.offsetHeight;Tt.style.bottom=`${f+wt}px`};bt();let Vt=()=>{let c=!!qt();Tt.setAttribute("aria-label",qt()||"Jump to latest"),Tt.title=qt(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Ct.innerHTML="";let f=be(en(),"14px","currentColor",2);f?(Ct.appendChild(f),Ct.style.display=""):Ct.style.display="none",ht.textContent=qt(),ht.style.display=c?"":"none"};Vt();let nt=null,Dn=null,Zn=s.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:r,defaultRenderer:()=>{let f=_r({config:r,showClose:$()});return Fo(de,f,r),f.header},onClose:()=>Ht(!1,"user")});if(c){let f=de.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),Ne=c)}}let bn=()=>{var f,y,b,k;if(!K)return;if(he=!0,!we&&K&&(we=cm({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>Nn(),config:r,plugins:s,getThroughput:()=>{var N;return(N=ce==null?void 0:ce.getMetric())!=null?N:{status:"idle"}}})),we&&(X.style.display="none",(f=je.parentNode)==null||f.insertBefore(we.element,je),we.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let N=(k=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:k.toggleButtonActive;N&&N.split(/\s+/).forEach(O=>O&&mt.classList.add(O))}let c=()=>{if(!he)return;let N=Date.now();N-Ve>=200&&(we==null||we.update(),Ve=N),Ce=requestAnimationFrame(c)};Ve=0,Ce=requestAnimationFrame(c),Rr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,f,y;if(he){if(he=!1,we&&we.element.remove(),X.style.display="",mt){mt.style.boxShadow="";let b=(y=(f=(c=r.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(k=>k&&mt.classList.remove(k))}Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Rr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(fe){let c=(kc=(Mc=r.features)==null?void 0:Mc.eventStream)==null?void 0:kc.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");mt=h("button",f),mt.style.width="28px",mt.style.height="28px",mt.style.color=Mn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let y=be("activity","18px","currentColor",1.5);y&&mt.appendChild(y);let b=We.clearChatButtonWrapper,k=We.closeButtonWrapper,N=b||k;N&&N.parentNode===Ne?Ne.insertBefore(mt,N):Ne.appendChild(mt),mt.addEventListener("click",()=>{he?Nn():bn()})}let vr=c=>{var b,k,N;let f=r.attachments;if(!(f!=null&&f.enabled))return;let y=c.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 O=c.querySelector("[data-persona-composer-form]");O!=null&&O.parentNode?O.parentNode.insertBefore(y,O):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let O=h("input");O.type="file",O.accept=((b=f.allowedTypes)!=null?b:Or).join(","),O.multiple=((k=f.maxFiles)!=null?k:4)>1,O.style.display="none",O.setAttribute("aria-label",(N=f.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(O)}},Fn=s.find(c=>c.renderComposer);if(Fn!=null&&Fn.renderComposer){let c=r.composer,f=Fn.renderComposer({config:r,defaultRenderer:()=>cs({config:r}).footer,onSubmit:y=>{var O;if(!T||T.isStreaming())return;let b=y.trim(),k=(O=nt==null?void 0:nt.hasAttachments())!=null?O:!1;if(!b&&!k)return;ks();let N;k&&(N=[],N.push(...nt.getContentParts()),b&&N.push(qs(b))),T.sendMessage(b,{contentParts:N}),k&&nt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{re==null||re.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((Lc=r.voiceRecognition)==null?void 0:Lc.enabled)===!0?()=>{Dn==null||Dn()}:void 0});f&&(je.replaceWith(f),je=f)}let yo=c=>{let f=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),k=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");f&&(_t=f),y&&(pe=y),b&&(ie=b),k&&(z=k,$t=k.parentElement),N&&(cn=N);let O=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Mt=O);let q=c.querySelector(".persona-attachment-button");q&&(Ze=q,Ft=q.parentElement),re=c.querySelector('input[type="file"]'),ge=c.querySelector(".persona-attachment-previews");let H=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");H&&(pt=H)};vr(je),yo(je);let Ln=(Hc=(Pc=r.layout)==null?void 0:Pc.contentMaxWidth)!=null?Hc:_()?(Rc=(Wc=(Ic=r.launcher)==null?void 0:Ic.composerBar)==null?void 0:Wc.contentMaxWidth)!=null?Rc:"720px":void 0;if(Ln&&($e.style.maxWidth=Ln,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%"),Ln&&_t&&!_()&&(_t.style.maxWidth=Ln,_t.style.marginLeft="auto",_t.style.marginRight="auto"),Ln&&Mt&&!_()&&(Mt.style.maxWidth=Ln,Mt.style.marginLeft="auto",Mt.style.marginRight="auto"),Ln&&ge&&!_()&&(ge.style.maxWidth=Ln,ge.style.marginLeft="auto",ge.style.marginRight="auto"),(Bc=r.attachments)!=null&&Bc.enabled&&re&&ge){nt=No.fromConfig(r.attachments),nt.setPreviewsContainer(ge),re.addEventListener("change",y=>{let b=y.target;nt==null||nt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,f=Em(c);de.appendChild(f)}(()=>{var b,k;let c=(k=(b=r.layout)==null?void 0:b.slots)!=null?k:{},f=N=>{switch(N){case"body-top":return de.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return $e;case"footer-top":return Mt;case"composer":return _t;case"footer-bottom":return cn;default:return null}},y=(N,O)=>{var q;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")Ne.insertBefore(O,Ne.firstChild);else if(N==="header-right")Ne.appendChild(O);else{let H=Ne.querySelector(".persona-flex-col");H?(q=H.parentNode)==null||q.insertBefore(O,H.nextSibling):Ne.appendChild(O)}break;case"body-top":{let H=X.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(O):X.insertBefore(O,X.firstChild);break}case"body-bottom":X.appendChild(O);break;case"footer-top":Mt.replaceWith(O);break;case"footer-bottom":cn.replaceWith(O);break;default:break}};for(let[N,O]of Object.entries(c))if(O)try{let q=O({config:r,defaultContent:()=>f(N)});q&&y(N,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,q)}})();let zr=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let k=b.getAttribute("data-message-id");if(!k)return;let N=y.getAttribute("data-bubble-type");N==="reasoning"?(ps.has(k)?ps.delete(k):ps.add(k),qu(k,b)):N==="tool"&&(us.has(k)?us.delete(k):us.add(k),zu(k,b,r)),ur.delete(k)};$e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),zr(c))}),$e.addEventListener("keydown",c=>{let f=c.target;(c.key==="Enter"||c.key===" ")&&f.closest('button[data-expand-header="true"]')&&(c.preventDefault(),zr(c))});let Mr=new Map;$e.addEventListener("click",c=>{var O;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let k=b.getAttribute("data-actions-for");if(!k)return;let N=y.getAttribute("data-action");if(N==="copy"){let H=T.getMessages().find(Ae=>Ae.id===k);if(H&&Y.onCopy){let Ae=H.content||"";navigator.clipboard.writeText(Ae).then(()=>{y.classList.add("persona-message-action-success");let ue=be("check",14,"currentColor",2);ue&&(y.innerHTML="",y.appendChild(ue)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ee=be("copy",14,"currentColor",2);ee&&(y.innerHTML="",y.appendChild(ee))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),Y.onCopy(H)}}else if(N==="upvote"||N==="downvote"){let H=((O=Mr.get(k))!=null?O:null)===N,Ae=N==="upvote"?"thumbs-up":"thumbs-down";if(H){Mr.delete(k),y.classList.remove("persona-message-action-active");let ue=be(Ae,14,"currentColor",2);ue&&(y.innerHTML="",y.appendChild(ue))}else{let ue=N==="upvote"?"downvote":"upvote",ee=b.querySelector(`[data-action="${ue}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Xe=be(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Xe&&(ee.innerHTML="",ee.appendChild(Xe))}Mr.set(k,N),y.classList.add("persona-message-action-active");let ye=be(Ae,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ye)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Oe=T.getMessages().find(rt=>rt.id===k);Oe&&Y.onFeedback&&Y.onFeedback({type:N,messageId:Oe.id,message:Oe})}}}),$e.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let k=b.getAttribute("data-message-id");if(!k)return;let N=y.getAttribute("data-approval-action");if(!N)return;let O=N==="approve"?"approved":"denied",H=T.getMessages().find(ue=>ue.id===k);if(!(H!=null&&H.approval))return;let Ae=b.querySelector("[data-approval-buttons]");Ae&&Ae.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?T.resolveWebMcpApproval(k,O):T.resolveApproval(H.approval,O)});let xt=null,On=null,_n={artifacts:[],selectedId:null},xn=!1,Pt={current:null};$e.addEventListener("click",c=>{var ee,ye,Te,Oe,rt;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((Te=(ye=(ee=r.features)==null?void 0:ee.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:Te.call(ye,{type:"download",artifactId:b}))===!0)return;let N=T.getArtifactById(b),O=N==null?void 0:N.markdown,q=(N==null?void 0:N.title)||"artifact";if(!O){let Xe=y.closest("[data-open-artifact]"),it=Xe==null?void 0:Xe.closest("[data-message-id]"),lt=it==null?void 0:it.getAttribute("data-message-id");if(lt){let ke=T.getMessages().find(ze=>ze.id===lt);if(ke!=null&&ke.rawContent)try{let ze=JSON.parse(ke.rawContent);O=(Oe=ze==null?void 0:ze.props)==null?void 0:Oe.markdown,q=((rt=ze==null?void 0:ze.props)==null?void 0:rt.title)||q}catch{}}}if(!O)return;let H=new Blob([O],{type:"text/markdown"}),Ae=URL.createObjectURL(H),ue=document.createElement("a");ue.href=Ae,ue.download=`${q}.md`,ue.click(),URL.revokeObjectURL(Ae)}),$e.addEventListener("click",c=>{var N,O,q;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((q=(O=(N=r.features)==null?void 0:N.artifacts)==null?void 0:O.onArtifactAction)==null?void 0:q.call(O,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),xn=!1,T.selectArtifact(b),Un())}),$e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let f=c.target;f.hasAttribute("data-open-artifact")&&(c.preventDefault(),f.click())});let er=We.composerOverlay,tr=(c,f,y)=>{var q,H,Ae,ue;let b=f.trim();if(!b||!Pt.current)return;let k=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",N=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:k,answer:b,answers:y.structured,values:(H=y.values)!=null?H:y.source==="multi"?b.split(", "):[b],isFreeText:N,source:y.source},bubbles:!0,composed:!0})),go(er,k);let O=Pt.current.getMessages().find(ee=>{var ye;return((ye=ee.toolCall)==null?void 0:ye.id)===k});(Ae=O==null?void 0:O.agentMetadata)!=null&&Ae.awaitingLocalTool?Pt.current.resolveAskUserQuestion(O,(ue=y.structured)!=null?ue:b):Pt.current.sendMessage(b)},$n=c=>{var k;let f=Pt.current;if(!f)return;let y=(k=c.getAttribute("data-tool-call-id"))!=null?k:"",b=f.getMessages().find(N=>{var O;return((O=N.toolCall)==null?void 0:O.id)===y});b&&f.persistAskUserQuestionProgress(b,{answers:Si(c,b),currentIndex:lr(c)})},Vr=c=>Object.entries(c).map(([f,y])=>`${f}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),kr=c=>{var k,N,O;if(((N=(k=r.features)==null?void 0:k.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let f=lr(c),y=gs(c);if(f>=y-1)return;let b=(O=Pt.current)==null?void 0:O.getMessages().find(q=>{var H;return((H=q.toolCall)==null?void 0:H.id)===c.getAttribute("data-tool-call-id")});b&&(Ti(c,b,r,f+1),$n(c))};er.addEventListener("click",c=>{var N,O,q,H,Ae,ue,ee,ye,Te,Oe,rt,Xe,it,lt;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let k=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),k==="dismiss"){let Le=(N=b.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),go(er,Le);let ke=(O=Pt.current)==null?void 0:O.getMessages().find(ze=>{var M;return((M=ze.toolCall)==null?void 0:M.id)===Le});(q=ke==null?void 0:ke.agentMetadata)!=null&&q.awaitingLocalTool&&((H=Pt.current)==null||H.markAskUserQuestionResolved(ke),(Ae=Pt.current)==null||Ae.resolveAskUserQuestion(ke,"(dismissed)"));return}if(k==="pick"){let Le=y.getAttribute("data-option-label");if(!Le)return;let ke=b.getAttribute("data-multi-select")==="true",ze=mo(b);if(ze&&ke){let M=_o(b)[lr(b)],Ee=new Set(Array.isArray(M)?M:[]);Ee.has(Le)?Ee.delete(Le):Ee.add(Le),fo(b,Array.from(Ee)),$n(b);return}if(ze){fo(b,Le),$n(b),kr(b);return}if(ke){let M=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",M?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!M);let Ee=b.querySelector('[data-ask-user-action="submit-multi"]');Ee&&(Ee.disabled=Al(b).length===0);return}tr(b,Le,{source:"pick",values:[Le]});return}if(k==="submit-multi"){let Le=Al(b);if(Le.length===0)return;tr(b,Le.join(", "),{source:"multi",values:Le});return}if(k==="open-free-text"){let Le=b.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let ke=Le.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus()}return}if(k==="focus-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(k==="submit-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]'),ke=(ue=Le==null?void 0:Le.value)!=null?ue:"";if(!ke.trim())return;if(mo(b)){fo(b,ke.trim()),$n(b),kr(b);return}tr(b,ke,{source:"free-text"});return}if(k==="next"||k==="back"){if(!Pt.current)return;let Le=(ee=b.getAttribute("data-tool-call-id"))!=null?ee:"",ke=Pt.current.getMessages().find(Je=>{var ve;return((ve=Je.toolCall)==null?void 0:ve.id)===Le});if(!ke)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),M=(Te=(ye=ze==null?void 0:ze.value)==null?void 0:ye.trim())!=null?Te:"";if(M){let Je=_o(b)[lr(b)];(typeof Je!="string"||Je!==M)&&fo(b,M)}let Ee=k==="next"?1:-1,He=lr(b)+Ee;Ti(b,ke,r,He),$n(b);return}if(k==="submit-all"){if(!Pt.current)return;let Le=(Oe=b.getAttribute("data-tool-call-id"))!=null?Oe:"",ke=Pt.current.getMessages().find(Je=>{var ve;return((ve=Je.toolCall)==null?void 0:ve.id)===Le});if(!ke)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),M=(Xe=(rt=ze==null?void 0:ze.value)==null?void 0:rt.trim())!=null?Xe:"";M&&fo(b,M);let Ee=Si(b,ke);Pt.current.persistAskUserQuestionProgress(ke,{answers:Ee,currentIndex:lr(b)});let He=Vr(Ee);tr(b,He||"(submitted)",{source:"submit-all",structured:Ee});return}if(k==="skip"){if(!Pt.current)return;let Le=(it=b.getAttribute("data-tool-call-id"))!=null?it:"",ke=Pt.current.getMessages().find(ve=>{var Lt;return((Lt=ve.toolCall)==null?void 0:Lt.id)===Le});if(!ke)return;let ze=mo(b),M=lr(b),Ee=gs(b),He=M>=Ee-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),go(er,Le),(lt=ke.agentMetadata)!=null&<.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(ke),Pt.current.resolveAskUserQuestion(ke,"(dismissed)"));return}fo(b,"");let Je=b.querySelector('[data-ask-free-text-input="true"]');if(Je&&(Je.value=""),He){let ve=Si(b,ke),Lt=Vr(ve);tr(b,Lt||"(skipped)",{source:"submit-all",structured:ve});return}Ti(b,ke,r,M+1),$n(b);return}}),er.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let y=c.target;if(!((N=y.matches)!=null&&N.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let k=y.value;if(k.trim()){if(mo(b)){fo(b,k.trim()),$n(b),kr(b);return}tr(b,k,{source:"free-text"})}});let Kr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let f=c.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let y=er.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),N=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",Kr);let jn=null,Rt=null,vn=null,nr=null,Jr=()=>{};function Lr(){nr==null||nr(),nr=null}let Gr=()=>{var O;if(!jn||!Rt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((O=e.ownerDocument.defaultView)!=null?O:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){Rt.style.removeProperty("position"),Rt.style.removeProperty("left"),Rt.style.removeProperty("top"),Rt.style.removeProperty("bottom"),Rt.style.removeProperty("width"),Rt.style.removeProperty("z-index");return}let b=jn.firstElementChild;if(!b||b===Rt)return;let k=10;Rt.style.position="absolute",Rt.style.top="0",Rt.style.bottom="0",Rt.style.width=`${k}px`,Rt.style.zIndex="5";let N=b.offsetWidth-k/2;Rt.style.left=`${Math.max(0,N)}px`},wr=()=>{},Un=()=>{var y,b,k,N,O;if(!xt||!cr(r))return;Mi(e,r),ki(e,r),wr();let c=(N=(k=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:k.narrowHostMaxWidth)!=null?N:520,f=oe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=c),xt.update(_n),xn?(xt.setMobileOpen(!1),xt.element.classList.add("persona-hidden"),(O=xt.backdrop)==null||O.classList.add("persona-hidden")):_n.artifacts.length>0&&(xt.element.classList.remove("persona-hidden"),xt.setMobileOpen(!0)),Jr()};if(cr(r)){oe.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(de),xt=um(r,{onSelect:y=>{var b;return(b=Pt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{xn=!0,Un()}}),xt.element.classList.add("persona-hidden"),jn=f,f.appendChild(c),f.appendChild(xt.element),xt.backdrop&&oe.appendChild(xt.backdrop),oe.appendChild(f),Jr=()=>{var b,k,N,O;if(!jn||!xt)return;if(!(((N=(k=(b=r.features)==null?void 0:b.artifacts)==null?void 0:k.layout)==null?void 0:N.resizable)===!0)){vn==null||vn(),vn=null,Lr(),Rt&&(Rt.remove(),Rt=null),xt.element.style.removeProperty("width"),xt.element.style.removeProperty("maxWidth");return}if(!Rt){let q=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let H=e.ownerDocument,Ae=(O=H.defaultView)!=null?O:window,ue=ee=>{var it,lt;if(!xt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ae.innerWidth<=640)return;ee.preventDefault(),Lr();let ye=ee.clientX,Te=xt.element.getBoundingClientRect().width,Oe=(lt=(it=r.features)==null?void 0:it.artifacts)==null?void 0:lt.layout,rt=Le=>{let ke=jn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),M=ze?0:hm(jn,Ae),Ee=ze?0:q.getBoundingClientRect().width||6,He=Te-(Le.clientX-ye),Je=ym(He,ke,M,Ee,Oe==null?void 0:Oe.resizableMinWidth,Oe==null?void 0:Oe.resizableMaxWidth);xt.element.style.width=`${Je}px`,xt.element.style.maxWidth="none",Gr()},Xe=()=>{H.removeEventListener("pointermove",rt),H.removeEventListener("pointerup",Xe),H.removeEventListener("pointercancel",Xe),nr=null;try{q.releasePointerCapture(ee.pointerId)}catch{}};nr=Xe,H.addEventListener("pointermove",rt),H.addEventListener("pointerup",Xe),H.addEventListener("pointercancel",Xe);try{q.setPointerCapture(ee.pointerId)}catch{}};q.addEventListener("pointerdown",ue),Rt=q,jn.insertBefore(q,xt.element),vn=()=>{q.removeEventListener("pointerdown",ue)}}if(Rt){let q=_n.artifacts.length>0&&!xn;Rt.classList.toggle("persona-hidden",!q),Gr()}},wr=()=>{var Ae,ue,ee,ye,Te,Oe,rt,Xe,it,lt,Le,ke,ze,M;if(!E||!xt||((ue=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?ue:!1)||rn(r)&&ir(r).reveal==="emerge")return;let b=(ee=e.ownerDocument.defaultView)!=null?ee:window,k=(Te=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?Te:!0,N=(rt=(Oe=r.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?rt:640;if(k&&b.innerWidth<=N||!fm(r,E))return;let O=(lt=(it=(Xe=r.launcher)==null?void 0:Xe.width)!=null?it:r.launcherWidth)!=null?lt:Xn,q=(M=(ze=(ke=(Le=r.features)==null?void 0:Le.artifacts)==null?void 0:ke.layout)==null?void 0:ze.expandedPanelWidth)!=null?M:"min(720px, calc(100vw - 24px))";_n.artifacts.length>0&&!xn?(oe.style.width=q,oe.style.maxWidth=q):(oe.style.width=O,oe.style.maxWidth=O)},typeof ResizeObserver!="undefined"&&(On=new ResizeObserver(()=>{Un()}),On.observe(oe))}else oe.appendChild(de),_()&&Ye&&(We.peekBanner&&Ye.appendChild(We.peekBanner),Ye.appendChild(je));e.appendChild(le),Ye&&e.appendChild(Ye);let dr=()=>{var Je,ve,Lt,at,Yt,dn,Wt,An,pn,et,ct,Sn,mn,Ao,So,To,Yo,Zo,Kt,Eo,so,yt,In,Dr,Tn,Wn,Bt,zt;if(_()){oe.style.width="100%",oe.style.maxWidth="100%";let Dt=(ve=(Je=r.launcher)==null?void 0:Je.composerBar)!=null?ve:{},Jt=le.dataset.state==="expanded",Rn=(Lt=Dt.expandedSize)!=null?Lt:"anchored";if(!(Jt&&Rn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let nn=(Yt=(at=r.theme)==null?void 0:at.components)==null?void 0:Yt.panel,Sr=is(r),Nr=(Mo,Ha)=>{var Ds;return Mo==null||Mo===""?Ha:(Ds=ss(Sr,Mo))!=null?Ds:Mo},Ia="1px solid var(--persona-border)",Wa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ra="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=Nr(nn==null?void 0:nn.border,Ia),de.style.borderRadius=Nr(nn==null?void 0:nn.borderRadius,Ra),de.style.boxShadow=Nr(nn==null?void 0:nn.shadow,Wa),de.style.overflow="hidden";return}let c=rn(r),f=(Wt=(dn=r.launcher)==null?void 0:dn.sidebarMode)!=null?Wt:!1,y=c||f||((pn=(An=r.launcher)==null?void 0:An.fullHeight)!=null?pn:!1),b=((et=r.launcher)==null?void 0:et.enabled)===!1,k=(Sn=(ct=r.theme)==null?void 0:ct.components)==null?void 0:Sn.panel,N=is(r),O=(Dt,Jt)=>{var Rn;return Dt==null||Dt===""?Jt:(Rn=ss(N,Dt))!=null?Rn:Dt},q=(mn=e.ownerDocument.defaultView)!=null?mn:window,H=(So=(Ao=r.launcher)==null?void 0:Ao.mobileFullscreen)!=null?So:!0,Ae=(Yo=(To=r.launcher)==null?void 0:To.mobileBreakpoint)!=null?Yo:640,ue=q.innerWidth<=Ae,ee=H&&ue&&E,ye=(Kt=(Zo=r.launcher)==null?void 0:Zo.position)!=null?Kt:"bottom-left",Te=ye==="bottom-left"||ye==="top-left",Oe=(so=(Eo=r.launcher)==null?void 0:Eo.zIndex)!=null?so:hn,rt=f||ee?"none":"1px solid var(--persona-border)",Xe=ee?"none":f?Te?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Xe="none",rt="none");let it=f||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",lt=O(k==null?void 0:k.border,rt),Le=O(k==null?void 0:k.shadow,Xe),ke=O(k==null?void 0:k.borderRadius,it),ze=X.scrollTop;e.style.cssText="",le.style.cssText="",oe.style.cssText="",de.style.cssText="",X.style.cssText="",je.style.cssText="";let M=()=>{var Jt;if(ze<=0)return;((Jt=X.ownerDocument.defaultView)!=null?Jt:window).requestAnimationFrame(()=>{if(X.scrollTop===ze)return;let Rn=X.scrollHeight-X.clientHeight;Rn<=0||(X.scrollTop=Math.min(ze,Rn))})};if(ee){le.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"),le.style.cssText=`
|
|
30
|
+
`,W.addEventListener("click",()=>{m=w,E.forEach(($,_)=>{let D=_<w;$.classList.toggle("selected",D),$.setAttribute("aria-checked",_===w-1?"true":"false")})}),E.push(W),A.appendChild(W)}g.appendChild(A);let B=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=o,B.rows=3,B.setAttribute("aria-label","Additional comments"),w.appendChild(B),g.appendChild(w)}let P=document.createElement("div");P.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{n==null||n(),p.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(m===null){A.classList.add("persona-feedback-shake"),setTimeout(()=>A.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let w=(B==null?void 0:B.value.trim())||void 0;await t(m,w),p.remove()}catch(w){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),P.appendChild(I),P.appendChild(R),g.appendChild(P),p.appendChild(g),p}function Di(e){let{onSubmit:t,onDismiss:n,title:r="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:l="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,u=document.createElement("div");u.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,v.appendChild(A),u.appendChild(v);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let B=document.createElement("div");B.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=l;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=p,B.appendChild(P),B.appendChild(I);let R=document.createElement("div");R.className="persona-feedback-numbers";let w=[];for(let U=0;U<=10;U++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${U} out of 10`),V.textContent=String(U),V.dataset.rating=String(U),U<=6?V.classList.add("persona-feedback-detractor"):U<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{g=U,w.forEach((se,Re)=>{se.classList.toggle("selected",Re===U),se.setAttribute("aria-checked",Re===U?"true":"false")})}),w.push(V),R.appendChild(V)}E.appendChild(B),E.appendChild(R),u.appendChild(E);let W=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=o,W.rows=3,W.setAttribute("aria-label","Additional comments"),U.appendChild(W),u.appendChild(U)}let $=document.createElement("div");$.className="persona-feedback-actions";let _=document.createElement("button");_.type="button",_.className="persona-feedback-btn persona-feedback-btn-skip",_.textContent=i,_.addEventListener("click",()=>{n==null||n(),m.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(g===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let U=(W==null?void 0:W.value.trim())||void 0;await t(g,U),m.remove()}catch(U){D.disabled=!1,D.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),$.appendChild(_),$.appendChild(D),u.appendChild($),m.appendChild(u),m}var bs="persona-chat-history",Bh=30*1e3,Dh={"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 Nh(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=Dh[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function Ni(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Fh(e){var t,n,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.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:(l=e.clearOnChatClear)!=null?l:!0}:null}function Oh(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Wl=e=>!e||typeof e!="object"?{}:{...e},Tm=e=>e.map(t=>({...t,streaming:!1})),Em=(e,t,n)=>{let r=e!=null&&e.markdown?Po(e.markdown):null,s=es(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 l,p,m;let a=(l=o.text)!=null?l:"",i=(p=o.message.rawContent)!=null?p:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(m=i!=null?i:o.text)!=null?m:""}):r?d=r(a):d=Io(a),s?s(d):d}};function Mm(e){var i,d,l,p;let t=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=be(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let m=h("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var Fi=(e,t,n)=>{var nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,wc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=ti(t),s=da.getForInstance(r.plugins);r.components&&Ur.registerAll(r.components);let o=vm(),i=r.persistState===!1?null:(nc=r.storageAdapter)!=null?nc:Pi(),d={},l=null,p=!1,m=c=>{if(r.onStateLoaded)try{let f=r.onStateLoaded(c);if(f&&typeof f=="object"&&"state"in f){let{state:y,open:b}=f;return b&&(p=!0),y}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(f=>{let y=f!=null?f:{messages:[],metadata:{}};return m(y)});else{let f=c!=null?c:{messages:[],metadata:{}},y=m(f);y.metadata&&(d=Wl(y.metadata)),(rc=y.messages)!=null&&rc.length&&(r={...r,initialMessages:y.messages}),(oc=y.artifacts)!=null&&oc.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(sc=y.selectedArtifactId)!=null?sc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=m({messages:[],metadata:{}});(ac=c.messages)!=null&&ac.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,u=c=>{var y;d=(y=c({...d}))!=null?y:{},Vo()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[pa],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[jo.message,jo.messageAndClick],A=ua({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let E=(lc=(ic=r.launcher)==null?void 0:ic.enabled)!=null?lc:!0,B=(dc=(cc=r.launcher)==null?void 0:cc.autoExpand)!=null?dc:!1,P=(pc=r.autoFocusInput)!=null?pc:!1,I=B,R=E,w=(mc=(uc=r.layout)==null?void 0:uc.header)==null?void 0:mc.layout,W=!1,$=()=>co(r),_=()=>E||$(),D=$()?!1:E?B:!0,U=!1,V=null,se=()=>{U=!0,V&&clearTimeout(V),V=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},Re=Em(r,A,se),Ue=(fc=(gc=r.features)==null?void 0:gc.showReasoning)!=null?fc:!0,Fe=(yc=(hc=r.features)==null?void 0:hc.showToolCalls)!=null?yc:!0,fe=(xc=(bc=r.features)==null?void 0:bc.showEventStreamToggle)!=null?xc:!1,xe=(wc=(vc=r.features)==null?void 0:vc.scrollToBottom)!=null?wc:{},Be=`${(Ac=typeof r.persistState=="object"?(Cc=r.persistState)==null?void 0:Cc.keyPrefix:void 0)!=null?Ac:"persona-"}event-stream`,te=fe?new la(Be):null,Ie=(Ec=(Tc=(Sc=r.features)==null?void 0:Sc.eventStream)==null?void 0:Tc.maxEvents)!=null?Ec:2e3,K=fe?new ia(Ie,te):null,ce=fe?new ca:null,we=null,he=!1,Ce=null,Ve=0;te==null||te.open().then(()=>K==null?void 0:K.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Y={onCopy:c=>{var f,y;o.emit("message:copy",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(f=r.messageActions)==null?void 0:f.onCopy)==null||y.call(f,c)},onFeedback:c=>{var f,y;o.emit("message:feedback",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(f=r.messageActions)==null?void 0:f.onFeedback)==null||y.call(f,c)}},ne=(Mc=r.statusIndicator)!=null?Mc:{},ae=c=>{var f,y,b,k;return c==="idle"?(f=ne.idleText)!=null?f:fn.idle:c==="connecting"?(y=ne.connectingText)!=null?y:fn.connecting:c==="connected"?(b=ne.connectedText)!=null?b:fn.connected:c==="error"?(k=ne.errorText)!=null?k:fn.error:fn[c]};function me(c,f,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let k=document.createElement("a");k.href=y.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=f,k.style.color="inherit",k.style.textDecoration="none",c.appendChild(k)}else c.textContent=f}let{wrapper:le,panel:oe,pillRoot:Ye}=$u(r),We=_u(r,_()),{container:de,body:X,messagesWrapper:_e,suggestions:Mt,textarea:pe,sendButton:ie,sendButtonWrapper:kn,composerForm:$t,statusText:cn,introTitle:Bn,introSubtitle:Yn,closeButton:qe,iconHolder:F,headerTitle:Se,headerSubtitle:De,header:Ne,footer:je,actionsRow:pt,leftActions:ot,rightActions:St}=We,Ut=We.setSendButtonMode,z=We.micButton,_t=We.micButtonWrapper,Ze=We.attachmentButton,Ft=We.attachmentButtonWrapper,re=We.attachmentInput,ge=We.attachmentPreviewsContainer;de.classList.add("persona-relative"),X.classList.add("persona-relative");let wt=12,qt=()=>{var c;return(c=xe.label)!=null?c:""},en=()=>{var c;return(c=xe.iconName)!=null?c:"arrow-down"},yn=()=>xe.enabled!==!1,Tt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let Ct=h("span","persona-flex persona-items-center"),ht=h("span","");Tt.append(Ct,ht),de.appendChild(Tt);let bt=()=>{let f=je.style.display==="none"?0:je.offsetHeight;Tt.style.bottom=`${f+wt}px`};bt();let Vt=()=>{let c=!!qt();Tt.setAttribute("aria-label",qt()||"Jump to latest"),Tt.title=qt(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Ct.innerHTML="";let f=be(en(),"14px","currentColor",2);f?(Ct.appendChild(f),Ct.style.display=""):Ct.style.display="none",ht.textContent=qt(),ht.style.display=c?"":"none"};Vt();let nt=null,Dn=null,Zn=s.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:r,defaultRenderer:()=>{let f=$r({config:r,showClose:_()});return Fo(de,f,r),f.header},onClose:()=>Ht(!1,"user")});if(c){let f=de.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),Ne=c)}}let bn=()=>{var f,y,b,k;if(!K)return;if(he=!0,!we&&K&&(we=dm({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>Nn(),config:r,plugins:s,getThroughput:()=>{var N;return(N=ce==null?void 0:ce.getMetric())!=null?N:{status:"idle"}}})),we&&(X.style.display="none",(f=je.parentNode)==null||f.insertBefore(we.element,je),we.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let N=(k=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:k.toggleButtonActive;N&&N.split(/\s+/).forEach(O=>O&&mt.classList.add(O))}let c=()=>{if(!he)return;let N=Date.now();N-Ve>=200&&(we==null||we.update(),Ve=N),Ce=requestAnimationFrame(c)};Ve=0,Ce=requestAnimationFrame(c),Rr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,f,y;if(he){if(he=!1,we&&we.element.remove(),X.style.display="",mt){mt.style.boxShadow="";let b=(y=(f=(c=r.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(k=>k&&mt.classList.remove(k))}Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Rr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(fe){let c=(Lc=(kc=r.features)==null?void 0:kc.eventStream)==null?void 0:Lc.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");mt=h("button",f),mt.style.width="28px",mt.style.height="28px",mt.style.color=Mn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let y=be("activity","18px","currentColor",1.5);y&&mt.appendChild(y);let b=We.clearChatButtonWrapper,k=We.closeButtonWrapper,N=b||k;N&&N.parentNode===Ne?Ne.insertBefore(mt,N):Ne.appendChild(mt),mt.addEventListener("click",()=>{he?Nn():bn()})}let vr=c=>{var b,k,N;let f=r.attachments;if(!(f!=null&&f.enabled))return;let y=c.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 O=c.querySelector("[data-persona-composer-form]");O!=null&&O.parentNode?O.parentNode.insertBefore(y,O):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let O=h("input");O.type="file",O.accept=((b=f.allowedTypes)!=null?b:Or).join(","),O.multiple=((k=f.maxFiles)!=null?k:4)>1,O.style.display="none",O.setAttribute("aria-label",(N=f.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(O)}},Fn=s.find(c=>c.renderComposer);if(Fn!=null&&Fn.renderComposer){let c=r.composer,f=Fn.renderComposer({config:r,defaultRenderer:()=>cs({config:r}).footer,onSubmit:y=>{var O;if(!T||T.isStreaming())return;let b=y.trim(),k=(O=nt==null?void 0:nt.hasAttachments())!=null?O:!1;if(!b&&!k)return;ks();let N;k&&(N=[],N.push(...nt.getContentParts()),b&&N.push(qs(b))),T.sendMessage(b,{contentParts:N}),k&&nt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{re==null||re.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((Pc=r.voiceRecognition)==null?void 0:Pc.enabled)===!0?()=>{Dn==null||Dn()}:void 0});f&&(je.replaceWith(f),je=f)}let yo=c=>{let f=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),k=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");f&&($t=f),y&&(pe=y),b&&(ie=b),k&&(z=k,_t=k.parentElement),N&&(cn=N);let O=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Mt=O);let q=c.querySelector(".persona-attachment-button");q&&(Ze=q,Ft=q.parentElement),re=c.querySelector('input[type="file"]'),ge=c.querySelector(".persona-attachment-previews");let H=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");H&&(pt=H)};vr(je),yo(je);let Ln=(Bc=(Ic=r.layout)==null?void 0:Ic.contentMaxWidth)!=null?Bc:$()?(Hc=(Rc=(Wc=r.launcher)==null?void 0:Wc.composerBar)==null?void 0:Rc.contentMaxWidth)!=null?Hc:"720px":void 0;if(Ln&&(_e.style.maxWidth=Ln,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%"),Ln&&$t&&!$()&&($t.style.maxWidth=Ln,$t.style.marginLeft="auto",$t.style.marginRight="auto"),Ln&&Mt&&!$()&&(Mt.style.maxWidth=Ln,Mt.style.marginLeft="auto",Mt.style.marginRight="auto"),Ln&&ge&&!$()&&(ge.style.maxWidth=Ln,ge.style.marginLeft="auto",ge.style.marginRight="auto"),(Dc=r.attachments)!=null&&Dc.enabled&&re&&ge){nt=No.fromConfig(r.attachments),nt.setPreviewsContainer(ge),re.addEventListener("change",y=>{let b=y.target;nt==null||nt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,f=Mm(c);de.appendChild(f)}(()=>{var b,k;let c=(k=(b=r.layout)==null?void 0:b.slots)!=null?k:{},f=N=>{switch(N){case"body-top":return de.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return _e;case"footer-top":return Mt;case"composer":return $t;case"footer-bottom":return cn;default:return null}},y=(N,O)=>{var q;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")Ne.insertBefore(O,Ne.firstChild);else if(N==="header-right")Ne.appendChild(O);else{let H=Ne.querySelector(".persona-flex-col");H?(q=H.parentNode)==null||q.insertBefore(O,H.nextSibling):Ne.appendChild(O)}break;case"body-top":{let H=X.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(O):X.insertBefore(O,X.firstChild);break}case"body-bottom":X.appendChild(O);break;case"footer-top":Mt.replaceWith(O);break;case"footer-bottom":cn.replaceWith(O);break;default:break}};for(let[N,O]of Object.entries(c))if(O)try{let q=O({config:r,defaultContent:()=>f(N)});q&&y(N,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,q)}})();let zr=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let k=b.getAttribute("data-message-id");if(!k)return;let N=y.getAttribute("data-bubble-type");N==="reasoning"?(ps.has(k)?ps.delete(k):ps.add(k),zu(k,b)):N==="tool"&&(us.has(k)?us.delete(k):us.add(k),Vu(k,b,r)),ur.delete(k)};_e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),zr(c))}),_e.addEventListener("keydown",c=>{let f=c.target;(c.key==="Enter"||c.key===" ")&&f.closest('button[data-expand-header="true"]')&&(c.preventDefault(),zr(c))});let Mr=new Map;_e.addEventListener("click",c=>{var O;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let k=b.getAttribute("data-actions-for");if(!k)return;let N=y.getAttribute("data-action");if(N==="copy"){let H=T.getMessages().find(Ae=>Ae.id===k);if(H&&Y.onCopy){let Ae=H.content||"";navigator.clipboard.writeText(Ae).then(()=>{y.classList.add("persona-message-action-success");let ue=be("check",14,"currentColor",2);ue&&(y.innerHTML="",y.appendChild(ue)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ee=be("copy",14,"currentColor",2);ee&&(y.innerHTML="",y.appendChild(ee))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),Y.onCopy(H)}}else if(N==="upvote"||N==="downvote"){let H=((O=Mr.get(k))!=null?O:null)===N,Ae=N==="upvote"?"thumbs-up":"thumbs-down";if(H){Mr.delete(k),y.classList.remove("persona-message-action-active");let ue=be(Ae,14,"currentColor",2);ue&&(y.innerHTML="",y.appendChild(ue))}else{let ue=N==="upvote"?"downvote":"upvote",ee=b.querySelector(`[data-action="${ue}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Xe=be(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Xe&&(ee.innerHTML="",ee.appendChild(Xe))}Mr.set(k,N),y.classList.add("persona-message-action-active");let ye=be(Ae,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ye)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Oe=T.getMessages().find(rt=>rt.id===k);Oe&&Y.onFeedback&&Y.onFeedback({type:N,messageId:Oe.id,message:Oe})}}}),_e.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let k=b.getAttribute("data-message-id");if(!k)return;let N=y.getAttribute("data-approval-action");if(!N)return;let O=N==="approve"?"approved":"denied",H=T.getMessages().find(ue=>ue.id===k);if(!(H!=null&&H.approval))return;let Ae=b.querySelector("[data-approval-buttons]");Ae&&Ae.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?T.resolveWebMcpApproval(k,O):T.resolveApproval(H.approval,O)});let xt=null,On=null,$n={artifacts:[],selectedId:null},xn=!1,Pt={current:null};_e.addEventListener("click",c=>{var ee,ye,Te,Oe,rt;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((Te=(ye=(ee=r.features)==null?void 0:ee.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:Te.call(ye,{type:"download",artifactId:b}))===!0)return;let N=T.getArtifactById(b),O=N==null?void 0:N.markdown,q=(N==null?void 0:N.title)||"artifact";if(!O){let Xe=y.closest("[data-open-artifact]"),it=Xe==null?void 0:Xe.closest("[data-message-id]"),lt=it==null?void 0:it.getAttribute("data-message-id");if(lt){let ke=T.getMessages().find(ze=>ze.id===lt);if(ke!=null&&ke.rawContent)try{let ze=JSON.parse(ke.rawContent);O=(Oe=ze==null?void 0:ze.props)==null?void 0:Oe.markdown,q=((rt=ze==null?void 0:ze.props)==null?void 0:rt.title)||q}catch{}}}if(!O)return;let H=new Blob([O],{type:"text/markdown"}),Ae=URL.createObjectURL(H),ue=document.createElement("a");ue.href=Ae,ue.download=`${q}.md`,ue.click(),URL.revokeObjectURL(Ae)}),_e.addEventListener("click",c=>{var N,O,q;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((q=(O=(N=r.features)==null?void 0:N.artifacts)==null?void 0:O.onArtifactAction)==null?void 0:q.call(O,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),xn=!1,T.selectArtifact(b),Un())}),_e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let f=c.target;f.hasAttribute("data-open-artifact")&&(c.preventDefault(),f.click())});let er=We.composerOverlay,tr=(c,f,y)=>{var q,H,Ae,ue;let b=f.trim();if(!b||!Pt.current)return;let k=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",N=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:k,answer:b,answers:y.structured,values:(H=y.values)!=null?H:y.source==="multi"?b.split(", "):[b],isFreeText:N,source:y.source},bubbles:!0,composed:!0})),go(er,k);let O=Pt.current.getMessages().find(ee=>{var ye;return((ye=ee.toolCall)==null?void 0:ye.id)===k});(Ae=O==null?void 0:O.agentMetadata)!=null&&Ae.awaitingLocalTool?Pt.current.resolveAskUserQuestion(O,(ue=y.structured)!=null?ue:b):Pt.current.sendMessage(b)},_n=c=>{var k;let f=Pt.current;if(!f)return;let y=(k=c.getAttribute("data-tool-call-id"))!=null?k:"",b=f.getMessages().find(N=>{var O;return((O=N.toolCall)==null?void 0:O.id)===y});b&&f.persistAskUserQuestionProgress(b,{answers:Ti(c,b),currentIndex:lr(c)})},Vr=c=>Object.entries(c).map(([f,y])=>`${f}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),kr=c=>{var k,N,O;if(((N=(k=r.features)==null?void 0:k.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let f=lr(c),y=gs(c);if(f>=y-1)return;let b=(O=Pt.current)==null?void 0:O.getMessages().find(q=>{var H;return((H=q.toolCall)==null?void 0:H.id)===c.getAttribute("data-tool-call-id")});b&&(Ei(c,b,r,f+1),_n(c))};er.addEventListener("click",c=>{var N,O,q,H,Ae,ue,ee,ye,Te,Oe,rt,Xe,it,lt;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let k=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),k==="dismiss"){let Le=(N=b.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),go(er,Le);let ke=(O=Pt.current)==null?void 0:O.getMessages().find(ze=>{var M;return((M=ze.toolCall)==null?void 0:M.id)===Le});(q=ke==null?void 0:ke.agentMetadata)!=null&&q.awaitingLocalTool&&((H=Pt.current)==null||H.markAskUserQuestionResolved(ke),(Ae=Pt.current)==null||Ae.resolveAskUserQuestion(ke,"(dismissed)"));return}if(k==="pick"){let Le=y.getAttribute("data-option-label");if(!Le)return;let ke=b.getAttribute("data-multi-select")==="true",ze=mo(b);if(ze&&ke){let M=$o(b)[lr(b)],Ee=new Set(Array.isArray(M)?M:[]);Ee.has(Le)?Ee.delete(Le):Ee.add(Le),fo(b,Array.from(Ee)),_n(b);return}if(ze){fo(b,Le),_n(b),kr(b);return}if(ke){let M=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",M?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!M);let Ee=b.querySelector('[data-ask-user-action="submit-multi"]');Ee&&(Ee.disabled=Sl(b).length===0);return}tr(b,Le,{source:"pick",values:[Le]});return}if(k==="submit-multi"){let Le=Sl(b);if(Le.length===0)return;tr(b,Le.join(", "),{source:"multi",values:Le});return}if(k==="open-free-text"){let Le=b.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let ke=Le.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus()}return}if(k==="focus-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(k==="submit-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]'),ke=(ue=Le==null?void 0:Le.value)!=null?ue:"";if(!ke.trim())return;if(mo(b)){fo(b,ke.trim()),_n(b),kr(b);return}tr(b,ke,{source:"free-text"});return}if(k==="next"||k==="back"){if(!Pt.current)return;let Le=(ee=b.getAttribute("data-tool-call-id"))!=null?ee:"",ke=Pt.current.getMessages().find(Je=>{var ve;return((ve=Je.toolCall)==null?void 0:ve.id)===Le});if(!ke)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),M=(Te=(ye=ze==null?void 0:ze.value)==null?void 0:ye.trim())!=null?Te:"";if(M){let Je=$o(b)[lr(b)];(typeof Je!="string"||Je!==M)&&fo(b,M)}let Ee=k==="next"?1:-1,He=lr(b)+Ee;Ei(b,ke,r,He),_n(b);return}if(k==="submit-all"){if(!Pt.current)return;let Le=(Oe=b.getAttribute("data-tool-call-id"))!=null?Oe:"",ke=Pt.current.getMessages().find(Je=>{var ve;return((ve=Je.toolCall)==null?void 0:ve.id)===Le});if(!ke)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),M=(Xe=(rt=ze==null?void 0:ze.value)==null?void 0:rt.trim())!=null?Xe:"";M&&fo(b,M);let Ee=Ti(b,ke);Pt.current.persistAskUserQuestionProgress(ke,{answers:Ee,currentIndex:lr(b)});let He=Vr(Ee);tr(b,He||"(submitted)",{source:"submit-all",structured:Ee});return}if(k==="skip"){if(!Pt.current)return;let Le=(it=b.getAttribute("data-tool-call-id"))!=null?it:"",ke=Pt.current.getMessages().find(ve=>{var Lt;return((Lt=ve.toolCall)==null?void 0:Lt.id)===Le});if(!ke)return;let ze=mo(b),M=lr(b),Ee=gs(b),He=M>=Ee-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),go(er,Le),(lt=ke.agentMetadata)!=null&<.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(ke),Pt.current.resolveAskUserQuestion(ke,"(dismissed)"));return}fo(b,"");let Je=b.querySelector('[data-ask-free-text-input="true"]');if(Je&&(Je.value=""),He){let ve=Ti(b,ke),Lt=Vr(ve);tr(b,Lt||"(skipped)",{source:"submit-all",structured:ve});return}Ei(b,ke,r,M+1),_n(b);return}}),er.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let y=c.target;if(!((N=y.matches)!=null&&N.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let k=y.value;if(k.trim()){if(mo(b)){fo(b,k.trim()),_n(b),kr(b);return}tr(b,k,{source:"free-text"})}});let Kr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let f=c.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let y=er.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),N=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",Kr);let jn=null,Rt=null,vn=null,nr=null,Jr=()=>{};function Lr(){nr==null||nr(),nr=null}let Gr=()=>{var O;if(!jn||!Rt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((O=e.ownerDocument.defaultView)!=null?O:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){Rt.style.removeProperty("position"),Rt.style.removeProperty("left"),Rt.style.removeProperty("top"),Rt.style.removeProperty("bottom"),Rt.style.removeProperty("width"),Rt.style.removeProperty("z-index");return}let b=jn.firstElementChild;if(!b||b===Rt)return;let k=10;Rt.style.position="absolute",Rt.style.top="0",Rt.style.bottom="0",Rt.style.width=`${k}px`,Rt.style.zIndex="5";let N=b.offsetWidth-k/2;Rt.style.left=`${Math.max(0,N)}px`},wr=()=>{},Un=()=>{var y,b,k,N,O;if(!xt||!cr(r))return;ki(e,r),Li(e,r),wr();let c=(N=(k=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:k.narrowHostMaxWidth)!=null?N:520,f=oe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=c),xt.update($n),xn?(xt.setMobileOpen(!1),xt.element.classList.add("persona-hidden"),(O=xt.backdrop)==null||O.classList.add("persona-hidden")):$n.artifacts.length>0&&(xt.element.classList.remove("persona-hidden"),xt.setMobileOpen(!0)),Jr()};if(cr(r)){oe.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(de),xt=mm(r,{onSelect:y=>{var b;return(b=Pt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{xn=!0,Un()}}),xt.element.classList.add("persona-hidden"),jn=f,f.appendChild(c),f.appendChild(xt.element),xt.backdrop&&oe.appendChild(xt.backdrop),oe.appendChild(f),Jr=()=>{var b,k,N,O;if(!jn||!xt)return;if(!(((N=(k=(b=r.features)==null?void 0:b.artifacts)==null?void 0:k.layout)==null?void 0:N.resizable)===!0)){vn==null||vn(),vn=null,Lr(),Rt&&(Rt.remove(),Rt=null),xt.element.style.removeProperty("width"),xt.element.style.removeProperty("maxWidth");return}if(!Rt){let q=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let H=e.ownerDocument,Ae=(O=H.defaultView)!=null?O:window,ue=ee=>{var it,lt;if(!xt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ae.innerWidth<=640)return;ee.preventDefault(),Lr();let ye=ee.clientX,Te=xt.element.getBoundingClientRect().width,Oe=(lt=(it=r.features)==null?void 0:it.artifacts)==null?void 0:lt.layout,rt=Le=>{let ke=jn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),M=ze?0:ym(jn,Ae),Ee=ze?0:q.getBoundingClientRect().width||6,He=Te-(Le.clientX-ye),Je=bm(He,ke,M,Ee,Oe==null?void 0:Oe.resizableMinWidth,Oe==null?void 0:Oe.resizableMaxWidth);xt.element.style.width=`${Je}px`,xt.element.style.maxWidth="none",Gr()},Xe=()=>{H.removeEventListener("pointermove",rt),H.removeEventListener("pointerup",Xe),H.removeEventListener("pointercancel",Xe),nr=null;try{q.releasePointerCapture(ee.pointerId)}catch{}};nr=Xe,H.addEventListener("pointermove",rt),H.addEventListener("pointerup",Xe),H.addEventListener("pointercancel",Xe);try{q.setPointerCapture(ee.pointerId)}catch{}};q.addEventListener("pointerdown",ue),Rt=q,jn.insertBefore(q,xt.element),vn=()=>{q.removeEventListener("pointerdown",ue)}}if(Rt){let q=$n.artifacts.length>0&&!xn;Rt.classList.toggle("persona-hidden",!q),Gr()}},wr=()=>{var Ae,ue,ee,ye,Te,Oe,rt,Xe,it,lt,Le,ke,ze,M;if(!E||!xt||((ue=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?ue:!1)||rn(r)&&ir(r).reveal==="emerge")return;let b=(ee=e.ownerDocument.defaultView)!=null?ee:window,k=(Te=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?Te:!0,N=(rt=(Oe=r.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?rt:640;if(k&&b.innerWidth<=N||!hm(r,E))return;let O=(lt=(it=(Xe=r.launcher)==null?void 0:Xe.width)!=null?it:r.launcherWidth)!=null?lt:Xn,q=(M=(ze=(ke=(Le=r.features)==null?void 0:Le.artifacts)==null?void 0:ke.layout)==null?void 0:ze.expandedPanelWidth)!=null?M:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!xn?(oe.style.width=q,oe.style.maxWidth=q):(oe.style.width=O,oe.style.maxWidth=O)},typeof ResizeObserver!="undefined"&&(On=new ResizeObserver(()=>{Un()}),On.observe(oe))}else oe.appendChild(de),$()&&Ye&&(We.peekBanner&&Ye.appendChild(We.peekBanner),Ye.appendChild(je));e.appendChild(le),Ye&&e.appendChild(Ye);let dr=()=>{var Je,ve,Lt,at,Yt,dn,Wt,An,pn,et,ct,Sn,mn,Ao,So,To,Yo,Zo,Kt,Eo,so,yt,In,Dr,Tn,Wn,Bt,zt;if($()){oe.style.width="100%",oe.style.maxWidth="100%";let Dt=(ve=(Je=r.launcher)==null?void 0:Je.composerBar)!=null?ve:{},Jt=le.dataset.state==="expanded",Rn=(Lt=Dt.expandedSize)!=null?Lt:"anchored";if(!(Jt&&Rn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let nn=(Yt=(at=r.theme)==null?void 0:at.components)==null?void 0:Yt.panel,Sr=is(r),Nr=(Mo,Ba)=>{var Ds;return Mo==null||Mo===""?Ba:(Ds=ss(Sr,Mo))!=null?Ds:Mo},Wa="1px solid var(--persona-border)",Ra="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ha="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=Nr(nn==null?void 0:nn.border,Wa),de.style.borderRadius=Nr(nn==null?void 0:nn.borderRadius,Ha),de.style.boxShadow=Nr(nn==null?void 0:nn.shadow,Ra),de.style.overflow="hidden";return}let c=rn(r),f=(Wt=(dn=r.launcher)==null?void 0:dn.sidebarMode)!=null?Wt:!1,y=c||f||((pn=(An=r.launcher)==null?void 0:An.fullHeight)!=null?pn:!1),b=((et=r.launcher)==null?void 0:et.enabled)===!1,k=(Sn=(ct=r.theme)==null?void 0:ct.components)==null?void 0:Sn.panel,N=is(r),O=(Dt,Jt)=>{var Rn;return Dt==null||Dt===""?Jt:(Rn=ss(N,Dt))!=null?Rn:Dt},q=(mn=e.ownerDocument.defaultView)!=null?mn:window,H=(So=(Ao=r.launcher)==null?void 0:Ao.mobileFullscreen)!=null?So:!0,Ae=(Yo=(To=r.launcher)==null?void 0:To.mobileBreakpoint)!=null?Yo:640,ue=q.innerWidth<=Ae,ee=H&&ue&&E,ye=(Kt=(Zo=r.launcher)==null?void 0:Zo.position)!=null?Kt:"bottom-left",Te=ye==="bottom-left"||ye==="top-left",Oe=(so=(Eo=r.launcher)==null?void 0:Eo.zIndex)!=null?so:hn,rt=f||ee?"none":"1px solid var(--persona-border)",Xe=ee?"none":f?Te?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Xe="none",rt="none");let it=f||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",lt=O(k==null?void 0:k.border,rt),Le=O(k==null?void 0:k.shadow,Xe),ke=O(k==null?void 0:k.borderRadius,it),ze=X.scrollTop;e.style.cssText="",le.style.cssText="",oe.style.cssText="",de.style.cssText="",X.style.cssText="",je.style.cssText="";let M=()=>{var Jt;if(ze<=0)return;((Jt=X.ownerDocument.defaultView)!=null?Jt:window).requestAnimationFrame(()=>{if(X.scrollTop===ze)return;let Rn=X.scrollHeight-X.clientHeight;Rn<=0||(X.scrollTop=Math.min(ze,Rn))})};if(ee){le.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"),le.style.cssText=`
|
|
31
31
|
position: fixed !important;
|
|
32
32
|
inset: 0 !important;
|
|
33
33
|
width: 100% !important;
|
|
@@ -104,23 +104,23 @@ _Details: ${t.message}_`:r}var os=class e{constructor(n={},t){this.config=n;this
|
|
|
104
104
|
flex-shrink: 0 !important;
|
|
105
105
|
border-top: none !important;
|
|
106
106
|
padding: 8px 16px 12px 16px !important;
|
|
107
|
-
`}if(!b&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",Jt=f?"":"padding-top: 1.25em !important;",Rn=f?"":`z-index: ${(zt=(Bt=r.launcher)==null?void 0:Bt.zIndex)!=null?zt:hn} !important;`;le.style.cssText+=Dt+Jt+Rn}M()};dr(),ao(e,r),Mi(e,r),ki(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",Kr)});let Gt=null,Xt=null;ft.push(()=>{Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null}),On&&ft.push(()=>{On==null||On.disconnect(),On=null}),ft.push(()=>{vn==null||vn(),vn=null,Lr(),Rt&&(Rt.remove(),Rt=null),xt==null||xt.element.style.removeProperty("width"),xt==null||xt.element.style.removeProperty("maxWidth")}),fe&&ft.push(()=>{Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),we==null||we.destroy(),we=null,K==null||K.destroy(),K=null,te=null});let qn=null,Xr=()=>{qn&&(qn(),qn=null),r.colorScheme==="auto"&&(qn=ri(()=>{ao(e,r)}))};Xr(),ft.push(()=>{qn&&(qn(),qn=null)});let rr=(Dc=r.features)==null?void 0:Dc.streamAnimation;if(rr!=null&&rr.type&&rr.type!=="none"){let c=Zs(rr.type,rr.plugins);c&&(sl(c,e),ft.push(()=>Du(e)))}let pr=sm(Mt),zn=null,T,Vn=!1,ur=Mu(),Pr=new Map,Cr=new Map,xs=0,mr=ai(),gr=0,fr=null,Ir=!1,bo=!1,ga=4,vs=24,fa=80,zo=new Map,gt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ws=(Fc=(Nc=r.voiceRecognition)==null?void 0:Nc.autoResume)!=null?Fc:!1,or=c=>{o.emit("voice:state",{active:gt.active,source:c,timestamp:Date.now()})},Pn=()=>{u(c=>({...c,voiceState:{active:gt.active,timestamp:Date.now(),manuallyDeactivated:gt.manuallyDeactivated}}))},ha=()=>{var b,k;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=Il(d.voiceState),f=!!c.active,y=Number((k=c.timestamp)!=null?k:0);gt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-y<Hh&&setTimeout(()=>{var N,O;gt.active||(gt.manuallyDeactivated=!1,((O=(N=r.voiceRecognition)==null?void 0:N.provider)==null?void 0:O.type)==="runtype"?T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("restore"),T.isVoiceActive()&&j()}):Co("restore"))},1e3)},ya=()=>T?Sm(T.getMessages()).filter(c=>!c.__skipPersist):[];function Vo(c){if(!(i!=null&&i.save))return;let y={messages:c?Sm(c):T?ya():[],metadata:d,artifacts:_n.artifacts,selectedArtifactId:_n.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Wr=null,ba=()=>le.querySelector("#persona-scroll-container")||X,xo=()=>{Wr!==null&&(cancelAnimationFrame(Wr),Wr=null),Ir=!1},Cs=()=>{fr!==null&&(cancelAnimationFrame(fr),fr=null),bo=!1,xo()},Rr=()=>{if(!yn()||he){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==de&&de.appendChild(Tt),bt();let c=Gs(X)>0;Tt.style.display=mr.isFollowing()||!c?"none":""},As=()=>{mr.pause()&&(Cs(),Rr())},Qr=()=>{mr.resume(),Rr()},Yr=(c=!1)=>{mr.isFollowing()&&(!c&&!Vn||(fr!==null&&(cancelAnimationFrame(fr),fr=null),bo=!0,fr=requestAnimationFrame(()=>{fr=null,bo=!1,mr.isFollowing()&&xa(ba(),c?220:140)})))},xa=(c,f=500)=>{let y=c.scrollTop,b=Gs(c),k=b-y;if(Math.abs(k)<1){gr=c.scrollTop;return}if(Math.abs(k)>=fa){xo(),Ir=!0,c.scrollTop=b,gr=c.scrollTop,Ir=!1;return}xo();let N=performance.now();Ir=!0;let O=H=>1-Math.pow(1-H,3),q=H=>{if(!mr.isFollowing()){xo();return}let Ae=Gs(c);Ae!==b&&(b=Ae,k=b-y);let ue=H-N,ee=Math.min(ue/f,1),ye=O(ee),Te=y+k*ye;c.scrollTop=Te,gr=c.scrollTop,ee<1?Wr=requestAnimationFrame(q):(c.scrollTop=b,gr=c.scrollTop,Wr=null,Ir=!1)};Wr=requestAnimationFrame(q)},va=c=>{let f=new Map;c.forEach(y=>{let b=zo.get(y.id);f.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),zo.clear(),f.forEach((y,b)=>{zo.set(b,y)})},vo=(c,f,y)=>{var Xe,it,lt,Le,ke,ze;let b=document.createElement("div"),N=(()=>{var Ee;let M=s.find(He=>He.renderLoadingIndicator);if(M!=null&&M.renderLoadingIndicator)return M.renderLoadingIndicator;if((Ee=r.loadingIndicator)!=null&&Ee.render)return r.loadingIndicator.render})(),O=(M,Ee)=>Ee==null?!1:typeof Ee=="string"?(M.textContent=Ee,!0):(M.appendChild(Ee),!0),q=new Set,H=new Set,Ae=s.some(M=>M.renderAskUserQuestion),ue=[],ee=[],ye=r.enableComponentStreaming!==!1;if(f.forEach(M=>{var An,pn,et,ct,Sn,mn,Ao,So,To,Yo,Zo,Kt,Eo,so;q.add(M.id);let Ee=Ae&&$r(M),He=!Ee&&M.role==="assistant"&&!M.variant&&ye&&Wi(M);if(!He&&Cr.has(M.id)){let yt=c.querySelector(`#wrapper-${M.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),Cr.delete(M.id)}let Je=$r(M)?`:${(An=M.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(pn=M.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(M.agentMetadata.askUserQuestionAnswers).length:0}`:"",ve=Eu(M,xs)+Je,Lt=Ee||He?null:ku(ur,M.id,ve);if(Lt){b.appendChild(Lt.cloneNode(!0)),$r(M)&&((et=M.toolCall)!=null&&et.id)&&((ct=M.agentMetadata)==null?void 0:ct.awaitingLocalTool)===!0&&!((Sn=M.agentMetadata)!=null&&Sn.askUserQuestionAnswered)&&(H.add(M.toolCall.id),fs(M,r,We.composerOverlay));return}let at=null,Yt=s.find(yt=>!!(M.variant==="reasoning"&&yt.renderReasoning||M.variant==="tool"&&yt.renderToolCall||M.variant==="approval"&&yt.renderApproval||!M.variant&&yt.renderMessage)),dn=(mn=r.layout)==null?void 0:mn.messages;if($r(M)&&((Ao=M.agentMetadata)==null?void 0:Ao.askUserQuestionAnswered)===!0){Pr.delete(M.id);let yt=c.querySelector(`#wrapper-${M.id}`);yt==null||yt.removeAttribute("data-preserve-runtime");return}if($r(M)&&((To=(So=r.features)==null?void 0:So.askUserQuestion)==null?void 0:To.enabled)!==!1){let yt=s.find(In=>typeof In.renderAskUserQuestion=="function");if(yt&&Pt.current){let In=Pr.get(M.id),Dr=In!==ve,Tn=null;if(Dr){let{payload:zt,complete:Dt}=jr(M),Jt=M.id,Rn=()=>{var Jn;return(Jn=Pt.current)==null?void 0:Jn.getMessages().find(nn=>nn.id===Jt)};Tn=yt.renderAskUserQuestion({message:M,payload:zt,complete:Dt,resolve:Jn=>{var Sr;let nn=Rn();nn&&((Sr=Pt.current)==null||Sr.resolveAskUserQuestion(nn,Jn))},dismiss:()=>{var nn,Sr,Nr;let Jn=Rn();(nn=Jn==null?void 0:Jn.agentMetadata)!=null&&nn.awaitingLocalTool&&((Sr=Pt.current)==null||Sr.markAskUserQuestionResolved(Jn),(Nr=Pt.current)==null||Nr.resolveAskUserQuestion(Jn,"(dismissed)"))},config:r})}let Wn=In!=null;if(Dr&&Tn===null&&!Wn){((Yo=M.agentMetadata)==null?void 0:Yo.awaitingLocalTool)===!0&&!((Zo=M.agentMetadata)!=null&&Zo.askUserQuestionAnswered)&&(H.add(M.toolCall.id),fs(M,r,We.composerOverlay));return}let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${M.id}`,Bt.setAttribute("data-wrapper-id",M.id),Bt.setAttribute("data-ask-plugin-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),b.appendChild(Bt),ue.push({messageId:M.id,fingerprint:ve,bubble:Tn});return}else{((Kt=M.agentMetadata)==null?void 0:Kt.awaitingLocalTool)===!0&&!((Eo=M.agentMetadata)!=null&&Eo.askUserQuestionAnswered)&&(H.add(M.toolCall.id),fs(M,r,We.composerOverlay));return}}else if(Yt)if(M.variant==="reasoning"&&M.reasoning&&Yt.renderReasoning){if(!Ue)return;at=Yt.renderReasoning({message:M,defaultRenderer:()=>fl(M,r),config:r})}else if(M.variant==="tool"&&M.toolCall&&Yt.renderToolCall){if(!Fe)return;at=Yt.renderToolCall({message:M,defaultRenderer:()=>hl(M,r),config:r})}else if(M.variant==="approval"&&M.approval&&Yt.renderApproval){if(r.approval===!1)return;at=Yt.renderApproval({message:M,defaultRenderer:()=>Sl(M,r),config:r})}else Yt.renderMessage&&(at=Yt.renderMessage({message:M,defaultRenderer:()=>{let yt=ds(M,y,dn,r.messageActions,Y,{loadingIndicatorRenderer:N,widgetConfig:r});return M.role!=="user"&&kl(yt,M,r,T),yt},config:r}));if(!at&&He){let yt=Ri(M);if(yt){let In=Cr.get(M.id),Dr=In!==ve,Tn=r.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Dr){let Bt=Ii(yt,{config:r,message:M,transform:y});if(Bt)if(Tn){let zt=document.createElement("div");if(zt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),zt.id=`bubble-${M.id}`,zt.setAttribute("data-message-id",M.id),M.content&&M.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=y({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),zt.appendChild(Dt)}zt.appendChild(Bt),Wn=zt}else{let zt=document.createElement("div");if(zt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",zt.id=`bubble-${M.id}`,zt.setAttribute("data-message-id",M.id),zt.setAttribute("data-persona-component-directive","true"),M.content&&M.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=y({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),zt.appendChild(Dt)}zt.appendChild(Bt),Wn=zt}}if(Wn||In!=null){let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${M.id}`,Bt.setAttribute("data-wrapper-id",M.id),Bt.setAttribute("data-component-directive-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),Tn||Bt.classList.add("persona-w-full"),b.appendChild(Bt),ee.push({messageId:M.id,fingerprint:ve,bubble:Wn});return}}}if(!at)if(M.variant==="reasoning"&&M.reasoning){if(!Ue)return;at=fl(M,r)}else if(M.variant==="tool"&&M.toolCall){if(!Fe)return;at=hl(M,r)}else if(M.variant==="approval"&&M.approval){if(r.approval===!1)return;at=Sl(M,r)}else{let yt=(so=r.layout)==null?void 0:so.messages;yt!=null&&yt.renderUserMessage&&M.role==="user"?at=yt.renderUserMessage({message:M,config:r,streaming:!!M.streaming}):yt!=null&&yt.renderAssistantMessage&&M.role==="assistant"?at=yt.renderAssistantMessage({message:M,config:r,streaming:!!M.streaming}):at=ds(M,y,yt,r.messageActions,Y,{loadingIndicatorRenderer:N,widgetConfig:r}),M.role!=="user"&&at&&kl(at,M,r,T)}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${M.id}`,Wt.setAttribute("data-wrapper-id",M.id),M.role==="user"&&Wt.classList.add("persona-justify-end"),(at==null?void 0:at.getAttribute("data-persona-component-directive"))==="true"&&Wt.classList.add("persona-w-full"),Wt.appendChild(at),Lu(ur,M.id,ve,Wt),b.appendChild(Wt)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ee=>{let He=Ee.getAttribute("data-persona-ask-sheet-for");He&&!H.has(He)&&go(We.composerOverlay,He)}),(it=(Xe=r.features)==null?void 0:Xe.toolCallDisplay)!=null&&it.grouped){let M=[],Ee=[];f.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&Fe){Ee.push(He);return}Ee.length>1&&M.push(Ee),Ee=[]}),Ee.length>1&&M.push(Ee),M.forEach((He,Je)=>{var pn,et;let ve=He.map(ct=>Array.from(b.children).find(Sn=>Sn instanceof HTMLElement&&Sn.getAttribute("data-wrapper-id")===ct.id)).filter(ct=>!!ct);if(ve.length<2)return;let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-tool-group-${Je}-${He[0].id}`,Lt.setAttribute("data-wrapper-id",`tool-group-${Je}-${He[0].id}`);let at=document.createElement("div");at.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",at.setAttribute("data-persona-tool-group","true");let Yt=document.createElement("div");Yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${He.length} tools`,Wt=(et=(pn=r.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:et.call(pn,{messages:He,toolCalls:He.map(ct=>ct.toolCall).filter(ct=>!!ct),defaultSummary:dn,config:r});O(Yt,Wt)||(Yt.textContent=dn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",at.append(Yt,An),Lt.appendChild(at),ve[0].before(Lt),ve.forEach((ct,Sn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Sn<ve.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(ct),An.appendChild(mn)})})}Pu(ur,q);let Te=f.some(M=>M.role==="assistant"&&M.streaming),Oe=f[f.length-1],rt=(Oe==null?void 0:Oe.role)==="assistant"&&!Oe.streaming&&Oe.variant!=="approval";if(Vn&&f.some(M=>M.role==="user")&&!Te&&!rt){let M={config:r,streaming:!0,location:"standalone",defaultRenderer:Oo},Ee=s.find(Je=>Je.renderLoadingIndicator),He=null;if(Ee!=null&&Ee.renderLoadingIndicator&&(He=Ee.renderLoadingIndicator(M)),He===null&&((lt=r.loadingIndicator)!=null&<.render)&&(He=r.loadingIndicator.render(M)),He===null&&(He=Oo()),He){let Je=document.createElement("div"),ve=((Le=r.loadingIndicator)==null?void 0:Le.showBubble)!==!1;Je.className=ve?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Je.setAttribute("data-typing-indicator","true"),Je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Je.appendChild(He);let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id="wrapper-typing-indicator",Lt.setAttribute("data-wrapper-id","typing-indicator"),Lt.appendChild(Je),b.appendChild(Lt)}}if(!Vn&&f.length>0){let M=f[f.length-1],Ee={config:r,lastMessage:M,messageCount:f.length},He=s.find(ve=>ve.renderIdleIndicator),Je=null;if(He!=null&&He.renderIdleIndicator&&(Je=He.renderIdleIndicator(Ee)),Je===null&&((ke=r.loadingIndicator)!=null&&ke.renderIdle)&&(Je=r.loadingIndicator.renderIdle(Ee)),Je){let ve=document.createElement("div"),Lt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;ve.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(" "),ve.setAttribute("data-idle-indicator","true"),ve.appendChild(Je);let at=document.createElement("div");at.className="persona-flex",at.id="wrapper-idle-indicator",at.setAttribute("data-wrapper-id","idle-indicator"),at.appendChild(ve),b.appendChild(at)}}if(oi(c,b),ue.length>0)for(let{messageId:M,fingerprint:Ee,bubble:He}of ue){let Je=c.querySelector(`#wrapper-${M}`);Je&&He!==null&&(Je.replaceChildren(He),Je.setAttribute("data-bubble-fp",Ee),Pr.set(M,Ee))}if(Pr.size>0)for(let M of Pr.keys())q.has(M)||Pr.delete(M);if(ee.length>0)for(let{messageId:M,fingerprint:Ee,bubble:He}of ee){let Je=c.querySelector(`#wrapper-${M}`);Je&&He!==null&&(Je.replaceChildren(He),Je.setAttribute("data-bubble-fp",Ee),Cr.set(M,Ee))}if(Cr.size>0)for(let M of Cr.keys())q.has(M)||Cr.delete(M)},Zr=null,wa=()=>{var y;if(Zr)return;let c=b=>{let k=b.composedPath();k.includes(le)||Ye&&k.includes(Ye)||Ht(!1,"user")};Zr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},Ss=()=>{var f;if(!Zr)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Zr,!0),Zr=null};ft.push(()=>Ss());let eo=null,Ca=()=>{var y;if(eo)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Ht(!1,"user"))};eo=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},Ts=()=>{var f;if(!eo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",eo,!0),eo=null};ft.push(()=>Ts());let to=!1,Es=new Set,Aa=()=>{var f,y,b,k;let c=(b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((k=r.features)==null?void 0:k.streamAnimation)},Hr=()=>{var it,lt,Le,ke;if(!_())return;let c=We.peekBanner,f=We.peekTextNode;if(!c||!f)return;if(D){c.classList.remove("persona-pill-peek--visible");return}let y=(it=T==null?void 0:T.getMessages())!=null?it:[],b;for(let ze=y.length-1;ze>=0;ze--){let M=y[ze];if(M.role==="assistant"&&M.content){b=M;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let k=b.content,N=!!b.streaming,O=Aa(),q=ci(O),H=q.type!=="none"?Zs(q.type,O==null?void 0:O.plugins):null,Ae=((lt=H==null?void 0:H.isAnimating)==null?void 0:lt.call(H,b))===!0,ue=H!==null&&(N||Ae);ue&&H&&!Es.has(H.name)&&(sl(H,e),Es.add(H.name));let ee=ue&&(H!=null&&H.containerClass)?H.containerClass:null,ye=(Le=f.dataset.personaPeekStreamClass)!=null?Le:null;ye&&ye!==ee&&(f.classList.remove(ye),delete f.dataset.personaPeekStreamClass),ee&&ye!==ee&&(f.classList.add(ee),f.dataset.personaPeekStreamClass=ee),ue?(f.style.setProperty("--persona-stream-step",`${q.speed}ms`),f.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Te=ue?di(k,q.buffer,H,b,N):k;if(ue&&q.placeholder==="skeleton"&&N&&(!Te||!Te.trim())){let ze=document.createElement("div"),M=ta();M.classList.add("persona-pill-peek__skeleton"),ze.appendChild(M),oi(f,ze)}else{let ze=Math.max(0,Te.length-100),M=Te.length>100?Te.slice(-100):Te,Ee=Io(M);if(!ue||!H){let He=Te.length>100?`\u2026${M}`:M;f.textContent!==He&&(f.textContent=He)}else{let He=Ee;(H.wrap==="char"||H.wrap==="word")&&(He=ea(Ee,H.wrap,`peek-${b.id}`,{skipTags:H.skipTags,startIndex:ze}));let Je=document.createElement("div");if(Je.innerHTML=He,H.useCaret&&M.length>0){let ve=pi(),Lt=Je.querySelectorAll(".persona-stream-char, .persona-stream-word"),at=Lt[Lt.length-1];at!=null&&at.parentNode?at.parentNode.insertBefore(ve,at.nextSibling):Je.appendChild(ve)}oi(f,Je),(ke=H.onAfterRender)==null||ke.call(H,{container:f,bubble:c,messageId:b.id,message:b,speed:q.speed,duration:q.duration})}}let Xe=Vn||to;c.classList.toggle("persona-pill-peek--visible",Xe)};if(_()){let c=We.peekBanner;if(c){let b=k=>{k.preventDefault(),k.stopPropagation(),Ht(!0,"user")};c.addEventListener("pointerdown",b),ft.push(()=>{c.removeEventListener("pointerdown",b)})}let f=()=>{to||(to=!0,Hr())},y=()=>{to&&(to=!1,Hr())};oe.addEventListener("pointerenter",f),oe.addEventListener("pointerleave",y),ft.push(()=>{oe.removeEventListener("pointerenter",f),oe.removeEventListener("pointerleave",y)}),Ye&&(Ye.addEventListener("pointerenter",f),Ye.addEventListener("pointerleave",y),ft.push(()=>{Ye.removeEventListener("pointerenter",f),Ye.removeEventListener("pointerleave",y)}))}let Sa=c=>{var ye,Te,Oe,rt,Xe,it,lt,Le;let f=(Te=(ye=r.launcher)==null?void 0:ye.composerBar)!=null?Te:{},y=(Oe=f.expandedSize)!=null?Oe:"anchored",b=(rt=f.bottomOffset)!=null?rt:"16px",k=f.collapsedMaxWidth,N=(Xe=f.expandedMaxWidth)!=null?Xe:"880px",O=(it=f.expandedTopOffset)!=null?it:"5vh",q=(lt=f.modalMaxWidth)!=null?lt:"880px",H=(Le=f.modalMaxHeight)!=null?Le:"min(90vh, 800px)",Ae="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",ee=le.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Ye){let ke=Ye.style;ke.bottom=b,ke.width=k!=null?k:""}if(c&&y!=="fullscreen"){if(y==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=q,ee.maxWidth=Ae,ee.maxHeight=H,ee.height=H;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${b} + ${ue})`,ee.top=O,ee.width=N,ee.maxWidth=Ae}},no=()=>{var H,Ae,ue,ee,ye,Te,Oe,rt;if(!$())return;if(_()){let it=(ue=((Ae=(H=r.launcher)==null?void 0:H.composerBar)!=null?Ae:{}).expandedSize)!=null?ue:"anchored",lt=D?"expanded":"collapsed";le.dataset.state=lt,le.dataset.expandedSize=it,Ye&&(Ye.dataset.state=lt,Ye.dataset.expandedSize=it),le.style.removeProperty("display"),le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Sa(D),de.style.display=D?"flex":"none",dr(),D?(wa(),Ca()):(Ss(),Ts()),Hr();return}let c=rn(r),f=(ee=e.ownerDocument.defaultView)!=null?ee:window,y=(Te=(ye=r.launcher)==null?void 0:ye.mobileBreakpoint)!=null?Te:640,b=(rt=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?rt:!0,k=f.innerWidth<=y,N=b&&k&&E,O=ir(r).reveal;D?(le.style.removeProperty("display"),le.style.display=c?"flex":"",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-95","persona-opacity-0"),oe.classList.add("persona-scale-100","persona-opacity-100"),Me?Me.element.style.display="none":Ge&&(Ge.style.display="none")):(c?c&&(O==="overlay"||O==="push")&&!N?(le.style.removeProperty("display"),le.style.display="flex",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.setProperty("display","none","important"),le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.display="",le.classList.add("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100"),oe.classList.add("persona-scale-95","persona-opacity-0")),Me?Me.element.style.display=c?"none":"":Ge&&(Ge.style.display=c?"none":""))},Ht=(c,f="user")=>{var N,O;if(!$()||D===c)return;let y=D;D=c,no();let b=(()=>{var Oe,rt,Xe,it,lt,Le,ke,ze,M,Ee;let q=(rt=(Oe=r.launcher)==null?void 0:Oe.sidebarMode)!=null?rt:!1,H=(Xe=e.ownerDocument.defaultView)!=null?Xe:window,Ae=(lt=(it=r.launcher)==null?void 0:it.mobileFullscreen)!=null?lt:!0,ue=(ke=(Le=r.launcher)==null?void 0:Le.mobileBreakpoint)!=null?ke:640,ee=H.innerWidth<=ue,ye=rn(r)&&Ae&&ee,Te=_()&&((Ee=(M=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:M.expandedSize)!=null?Ee:"fullscreen")==="fullscreen";return q||Ae&&ee&&E||ye||Te})();if(D&&b){if(!Gt){let q=e.getRootNode(),H=q instanceof ShadowRoot?q.host:e.closest(".persona-host");H&&(Gt=al(H,(O=(N=r.launcher)==null?void 0:N.zIndex)!=null?O:hn))}Xt||(Xt=il(e.ownerDocument))}else D||(Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null);D&&(It(),Yr(!0));let k={open:D,source:f,timestamp:Date.now()};D&&!y?o.emit("widget:opened",k):!D&&y&&o.emit("widget:closed",k),o.emit("widget:state",{open:D,launcherEnabled:E,voiceActive:gt.active,streaming:T.isStreaming()})},Ko=c=>{Ut(c?"stop":"send"),z&&(z.disabled=c),pr.buttons.forEach(f=>{f.disabled=c}),je.dataset.personaComposerStreaming=c?"true":"false",je.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Jo=()=>{gt.active||pe&&pe.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Jo(),200)});let Ms=()=>{var y,b,k,N,O,q,H,Ae,ue,ee,ye;Bn.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",Yn.textContent=(N=(k=r.copy)==null?void 0:k.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",pe.placeholder=(q=(O=r.copy)==null?void 0:O.inputPlaceholder)!=null?q:"How can I help...";let c=X.querySelector("[data-persona-intro-card]");if(c){let Te=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;c.style.display=Te?"":"none",Te?(X.classList.remove("persona-gap-3"),X.classList.add("persona-gap-6")):(X.classList.remove("persona-gap-6"),X.classList.add("persona-gap-3"))}!((ue=(Ae=r.sendButton)==null?void 0:Ae.useIcon)!=null&&ue)&&!(T!=null&&T.isStreaming())&&(ie.textContent=(ye=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?ye:"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{u(f=>({...f,sessionId:c}))}});let Ar=null,Ta=()=>{Ar==null&&(Ar=setInterval(()=>{let c=$e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ar),Ar=null;return}let f=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=Fa(f-b))})},100))};if(T=new os(r,{onMessagesChanged(c){vo($e,c,Re),Ta(),T&&(c.some(k=>k.role==="user")?pr.render([],T,pe,c):pr.render(r.suggestionChips,T,pe,c,r.suggestionChipsConfig)),Yr(!Vn),va(c);let f=[...c].reverse().find(b=>b.role==="user"),y=gt.lastUserMessageId;f&&f.id!==y&&(gt.lastUserMessageId=f.id,o.emit("user:message",f)),gt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Vo(c),Hr()},onStatusChanged(c){var b;let f=(b=r.statusIndicator)!=null?b:{};me(cn,(k=>{var N,O,q,H;return k==="idle"?(N=f.idleText)!=null?N:fn.idle:k==="connecting"?(O=f.connectingText)!=null?O:fn.connecting:k==="connected"?(q=f.connectedText)!=null?q:fn.connected:k==="error"?(H=f.errorText)!=null?H:fn.error:fn[k]})(c),f,c)},onStreamingChanged(c){Vn=c,Ko(c),T&&vo($e,T.getMessages(),Re),c||Yr(!0),Hr()},onVoiceStatusChanged(c){var f,y;if(((y=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":J(),L();break;case"speaking":J(),Z();break;default:c==="idle"&&T.isBargeInActive()?(J(),j(),z==null||z.setAttribute("aria-label","End voice session")):(gt.active=!1,J(),or("system"),Pn());break}},onArtifactsState(c){_n=c,Un(),Vo()}}),Pt.current=T,((_c=(Oc=r.voiceRecognition)==null?void 0:Oc.provider)==null?void 0:_c.type)==="runtype")try{T.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&T.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||r.onSSEEvent)&&T.setSSEEventCallback((c,f)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,f),ce==null||ce.processEvent(c,f),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(f)})}),l&&l.then(c=>{var f,y,b;c&&(c.metadata&&(d=Il(c.metadata),A.syncFromMetadata()),(f=c.messages)!=null&&f.length&&T.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&T.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ks=()=>{var f,y,b;!_()||D||!((b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Ht(!0,"auto")},Ls=c=>{var k;if(c.preventDefault(),T.isStreaming()){T.cancel(),ce==null||ce.reset(),we==null||we.update();return}let f=pe.value.trim(),y=(k=nt==null?void 0:nt.hasAttachments())!=null?k:!1;if(!f&&!y)return;ks();let b;y&&(b=[],b.push(...nt.getContentParts()),f&&b.push(qs(f))),pe.value="",pe.style.height="auto",wo(),T.sendMessage(f,{contentParts:b}),y&&nt.clearAttachments()},Ea=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Go={...si},Xo=!1,wo=()=>{Go={...si}},Ma=()=>T.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),ka=c=>{if(!pe)return;Xo=!0,pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),Xo=!1;let f=pe.value.length;pe.setSelectionRange(f,f)},Ps=()=>{Xo||wo()},Is=c=>{if(pe){if(Ea()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=pe.selectionStart===0&&pe.selectionEnd===0,y=Tu({direction:c.key==="ArrowUp"?"up":"down",history:Ma(),currentValue:pe.value,atStart:f,state:Go});if(Go=y.state,y.handled){c.preventDefault(),y.value!==void 0&&ka(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(T.isStreaming()){c.preventDefault();return}wo(),c.preventDefault(),ie.click()}}},Ws=c=>{c.key!=="Escape"||c.isComposing||T.isStreaming()&&c.composedPath().includes(de)&&(T.cancel(),ce==null||ce.reset(),we==null||we.update(),wo(),c.preventDefault(),c.stopImmediatePropagation())},Rs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!nt)return;let f=Dh(c.clipboardData);f.length!==0&&(c.preventDefault(),await nt.handleFiles(f))},wn=null,Kn=!1,Br=null,st=null,Hs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Co=(c="user")=>{var N,O,q,H,Ae,ue,ee;if(Kn||T.isStreaming())return;let f=Hs();if(!f)return;wn=new f;let b=(O=((N=r.voiceRecognition)!=null?N:{}).pauseDuration)!=null?O:2e3;wn.continuous=!0,wn.interimResults=!0,wn.lang="en-US";let k=pe.value;wn.onresult=ye=>{let Te="",Oe="";for(let Xe=0;Xe<ye.results.length;Xe++){let it=ye.results[Xe],lt=it[0].transcript;it.isFinal?Te+=lt+" ":Oe=lt}let rt=k+Te+Oe;pe.value=rt,Br&&clearTimeout(Br),(Te||Oe)&&(Br=window.setTimeout(()=>{let Xe=pe.value.trim();Xe&&wn&&Kn&&(hr(),pe.value="",pe.style.height="auto",T.sendMessage(Xe,{viaVoice:!0}))},b))},wn.onerror=ye=>{ye.error!=="no-speech"&&hr()},wn.onend=()=>{if(Kn){let ye=pe.value.trim();ye&&ye!==k.trim()&&(pe.value="",pe.style.height="auto",T.sendMessage(ye,{viaVoice:!0})),hr()}};try{if(wn.start(),Kn=!0,gt.active=!0,c!=="system"&&(gt.manuallyDeactivated=!1),or(c),Pn(),z){let ye=(q=r.voiceRecognition)!=null?q:{};st={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(H=ye.iconName)!=null?H:"mic",iconSize:parseFloat((ee=(ue=ye.iconSize)!=null?ue:(Ae=r.sendButton)==null?void 0:Ae.size)!=null?ee:"40")||24};let Te=ye.recordingBackgroundColor,Oe=ye.recordingIconColor,rt=ye.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=Te!=null?Te:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=Oe!=null?Oe:"var(--persona-voice-recording-indicator, #ffffff)",Oe){let Xe=z.querySelector("svg");Xe&&Xe.setAttribute("stroke",Oe)}rt&&(z.style.borderColor=rt),z.setAttribute("aria-label","Stop voice recognition")}}catch{hr("system")}},hr=(c="user")=>{if(Kn){if(Kn=!1,Br&&(clearTimeout(Br),Br=null),wn){try{wn.stop()}catch{}wn=null}if(gt.active=!1,or(c),Pn(),z){if(z.classList.remove("persona-voice-recording"),st){z.style.backgroundColor=st.backgroundColor,z.style.color=st.color,z.style.borderColor=st.borderColor;let f=z.querySelector("svg");f&&f.setAttribute("stroke",st.color||"currentColor"),st=null}z.setAttribute("aria-label","Start voice recognition")}}},La=(c,f)=>{var it,lt,Le,ke,ze,M,Ee,He;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((it=c==null?void 0:c.provider)==null?void 0:it.type)==="runtype";if(!(y||b))return null;let N=h("div","persona-send-button-wrapper"),O=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let q=(lt=c==null?void 0:c.iconName)!=null?lt:"mic",H=(Le=f==null?void 0:f.size)!=null?Le:"40px",Ae=(ke=c==null?void 0:c.iconSize)!=null?ke:H,ue=parseFloat(Ae)||24,ee=(ze=c==null?void 0:c.backgroundColor)!=null?ze:f==null?void 0:f.backgroundColor,ye=(M=c==null?void 0:c.iconColor)!=null?M:f==null?void 0:f.textColor;O.style.width=Ae,O.style.height=Ae,O.style.minWidth=Ae,O.style.minHeight=Ae,O.style.fontSize="18px",O.style.lineHeight="1",ye?O.style.color=ye:O.style.color="var(--persona-text, #111827)";let Oe=be(q,ue,ye||"currentColor",1.5);Oe?O.appendChild(Oe):O.textContent="\u{1F3A4}",ee?O.style.backgroundColor=ee:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),N.appendChild(O);let rt=(Ee=c==null?void 0:c.tooltipText)!=null?Ee:"Start voice recognition";if(((He=c==null?void 0:c.showTooltip)!=null?He:!1)&&rt){let Je=h("div","persona-send-button-tooltip");Je.textContent=rt,N.appendChild(Je)}return{micButton:O,micButtonWrapper:N}},ro=()=>{var f,y,b,k,N;if(!z||st)return;let c=(f=r.voiceRecognition)!=null?f:{};st={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((N=(k=c.iconSize)!=null?k:(b=r.sendButton)==null?void 0:b.size)!=null?N:"40")||24}},Ke=(c,f)=>{var N,O,q,H,Ae;if(!z)return;let y=z.querySelector("svg");y&&y.remove();let b=(Ae=st==null?void 0:st.iconSize)!=null?Ae:parseFloat((H=(q=(N=r.voiceRecognition)==null?void 0:N.iconSize)!=null?q:(O=r.sendButton)==null?void 0:O.size)!=null?H:"40")||24,k=be(c,b,f,1.5);k&&z.appendChild(k)},S=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},j=()=>{var k;if(!z)return;ro();let c=(k=r.voiceRecognition)!=null?k:{},f=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(S(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let N=z.querySelector("svg");N&&N.setAttribute("stroke",y)}b&&(z.style.borderColor=b),z.setAttribute("aria-label","Stop voice recognition")},L=()=>{var q,H,Ae,ue,ee,ye,Te,Oe;if(!z)return;ro();let c=(q=r.voiceRecognition)!=null?q:{},f=T.getVoiceInterruptionMode(),y=(H=c.processingIconName)!=null?H:"loader",b=(ue=(Ae=c.processingIconColor)!=null?Ae:st==null?void 0:st.color)!=null?ue:"",k=(ye=(ee=c.processingBackgroundColor)!=null?ee:st==null?void 0:st.backgroundColor)!=null?ye:"",N=(Oe=(Te=c.processingBorderColor)!=null?Te:st==null?void 0:st.borderColor)!=null?Oe:"";S(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=k,z.style.borderColor=N;let O=b||"currentColor";z.style.color=O,Ke(y,O),z.setAttribute("aria-label","Processing voice input"),f==="none"&&(z.style.cursor="default")},Z=()=>{var Ae,ue,ee,ye,Te,Oe,rt,Xe,it,lt,Le,ke;if(!z)return;ro();let c=(Ae=r.voiceRecognition)!=null?Ae:{},f=T.getVoiceInterruptionMode(),y=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",b=(ue=c.speakingIconName)!=null?ue:y,k=(Oe=c.speakingIconColor)!=null?Oe:f==="barge-in"?(ye=(ee=c.recordingIconColor)!=null?ee:st==null?void 0:st.color)!=null?ye:"":(Te=st==null?void 0:st.color)!=null?Te:"",N=(it=c.speakingBackgroundColor)!=null?it:f==="barge-in"?(rt=c.recordingBackgroundColor)!=null?rt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=st==null?void 0:st.backgroundColor)!=null?Xe:"",O=(ke=c.speakingBorderColor)!=null?ke:f==="barge-in"?(lt=c.recordingBorderColor)!=null?lt:"":(Le=st==null?void 0:st.borderColor)!=null?Le:"";S(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=N,z.style.borderColor=O;let q=k||"currentColor";z.style.color=q,Ke(b,q);let H=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",H),f==="none"&&(z.style.cursor="default"),f==="barge-in"&&z.classList.add("persona-voice-recording")},J=()=>{var c,f,y;z&&(S(),st&&(z.style.backgroundColor=(c=st.backgroundColor)!=null?c:"",z.style.color=(f=st.color)!=null?f:"",z.style.borderColor=(y=st.borderColor)!=null?y:"",Ke(st.iconName,st.color||"currentColor"),st=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},G=()=>{var c,f;if(((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let y=T.getVoiceStatus(),b=T.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),or("user"),J()});return}T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),gt.manuallyDeactivated=!T.isVoiceActive(),Pn(),or("user"),T.isVoiceActive()?j():J()});return}if(Kn){let y=pe.value.trim();gt.manuallyDeactivated=!0,Pn(),hr("user"),y&&(pe.value="",pe.style.height="auto",T.sendMessage(y))}else gt.manuallyDeactivated=!1,Pn(),Co("user")};Dn=G,z&&(z.addEventListener("click",G),ft.push(()=>{var c,f;((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),J()):hr("system"),z&&z.removeEventListener("click",G)}));let Qe=o.on("assistant:complete",()=>{ws&&(gt.active||gt.manuallyDeactivated||ws==="assistant"&&!gt.lastUserMessageWasVoice||setTimeout(()=>{var c,f;!gt.active&&!gt.manuallyDeactivated&&(((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("auto"),T.isVoiceActive()&&j()}):Co("auto"))},600))});ft.push(Qe);let _e=o.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});ft.push(_e);let tt=()=>{Ht(!D,"user")},Me=null,Ge=null;if(E&&!_()){let c=s.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:r,defaultRenderer:()=>ra(r,tt).element,onToggle:tt});f&&(Ge=f)}Ge||(Me=ra(r,tt))}Me?e.appendChild(Me.element):Ge&&e.appendChild(Ge),no(),pr.render(r.suggestionChips,T,pe,void 0,r.suggestionChipsConfig),Ms(),Ko(T.isStreaming()),Yr(!0),ha(),P&&(!E||_()?setTimeout(()=>Jo(),0):D&&setTimeout(()=>Jo(),200));let It=()=>{var H,Ae,ue,ee,ye,Te,Oe,rt,Xe,it,lt,Le,ke,ze,M,Ee,He,Je,ve,Lt,at,Yt;if(_()){bt(),no();return}let c=rn(r),f=(Ae=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?Ae:!1,y=c||f||((ee=(ue=r.launcher)==null?void 0:ue.fullHeight)!=null?ee:!1),b=(ye=e.ownerDocument.defaultView)!=null?ye:window,k=(Oe=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?Oe:!0,N=(Xe=(rt=r.launcher)==null?void 0:rt.mobileBreakpoint)!=null?Xe:640,O=b.innerWidth<=N,q=k&&O&&E;try{if(q){dr(),ao(e,r);return}if(W&&(W=!1,dr(),ao(e,r)),!E&&!c){oe.style.height="",oe.style.width="";return}if(!f&&!c){let dn=(lt=(it=r==null?void 0:r.launcher)==null?void 0:it.width)!=null?lt:r==null?void 0:r.launcherWidth,Wt=dn!=null?dn:Xn;oe.style.width=Wt,oe.style.maxWidth=Wt}if(wr(),!y){let dn=b.innerHeight,Wt=64,An=(ke=(Le=r.launcher)==null?void 0:Le.heightOffset)!=null?ke:0,pn=Math.max(200,dn-Wt),et=Math.min(640,pn),ct=Math.max(200,et-An);oe.style.height=`${ct}px`}}finally{if(bt(),no(),D&&E){let Wt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((Ee=(M=r.launcher)==null?void 0:M.mobileBreakpoint)!=null?Ee:640),An=(Je=(He=r.launcher)==null?void 0:He.sidebarMode)!=null?Je:!1,pn=(Lt=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Lt:!0,et=rn(r)&&pn&&Wt,ct=An||pn&&Wt&&E||et;if(ct&&!Xt){let Sn=e.getRootNode(),mn=Sn instanceof ShadowRoot?Sn.host:e.closest(".persona-host");mn&&!Gt&&(Gt=al(mn,(Yt=(at=r.launcher)==null?void 0:at.zIndex)!=null?Yt:hn)),Xt=il(e.ownerDocument)}else ct||(Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null)}}};It();let on=($c=e.ownerDocument.defaultView)!=null?$c:window;if(on.addEventListener("resize",It),ft.push(()=>on.removeEventListener("resize",It)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe(je),ft.push(()=>c.disconnect())}gr=X.scrollTop;let At=X.scrollHeight,kt=()=>{let c=X.scrollTop,f=X.scrollHeight,y=f<At;At=f;let{action:b,nextLastScrollTop:k}=ii({following:mr.isFollowing(),currentScrollTop:c,lastScrollTop:gr,nearBottom:Xs(X,vs),userScrollThreshold:ga,isAutoScrolling:Ir||bo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(gr=k,b==="resume"){Qr();return}b==="pause"&&As()};X.addEventListener("scroll",kt,{passive:!0}),ft.push(()=>X.removeEventListener("scroll",kt));let sn=c=>{let f=li({following:mr.isFollowing(),deltaY:c.deltaY,nearBottom:Xs(X,vs),resumeWhenNearBottom:!0});f==="pause"?As():f==="resume"&&Qr()};X.addEventListener("wheel",sn,{passive:!0}),ft.push(()=>X.removeEventListener("wheel",sn)),Tt.addEventListener("click",()=>{X.scrollTop=X.scrollHeight,gr=X.scrollTop,Qr(),Yr(!0)}),ft.push(()=>Tt.remove()),ft.push(()=>{Cs()});let un=()=>{qe&&(zn&&(qe.removeEventListener("click",zn),zn=null),$()?(qe.style.display="",zn=()=>{Ht(!1,"user")},qe.addEventListener("click",zn)):qe.style.display="none")};un(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{T.clearMessages(),ur.clear(),Qr(),go(We.composerOverlay);try{localStorage.removeItem(bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},A.syncFromMetadata(),K==null||K.clear(),ce==null||ce.reset(),we==null||we.update()})})(),_t&&_t.addEventListener("submit",Ls),pe==null||pe.addEventListener("keydown",Is),pe==null||pe.addEventListener("input",Ps),pe==null||pe.addEventListener("paste",Rs);let Qt=(jc=e.ownerDocument)!=null?jc:document;Qt.addEventListener("keydown",Ws,!0);let sr="persona-attachment-drop-active",Bs=0,Vi=()=>{Bs=0,de.classList.remove(sr)},Qo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&nt!==null},Gl=c=>{!Di(c.dataTransfer)||!Qo()||(Bs++,Bs===1&&de.classList.add(sr))},Xl=c=>{!Di(c.dataTransfer)||!Qo()||(Bs--,Bs<=0&&Vi())},Ql=c=>{!Di(c.dataTransfer)||!Qo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Yl=c=>{var y;if(!Di(c.dataTransfer)||!Qo())return;c.preventDefault(),c.stopPropagation(),Vi();let f=Array.from((y=c.dataTransfer.files)!=null?y:[]);f.length!==0&&nt.handleFiles(f)},oo=!0;de.addEventListener("dragenter",Gl,oo),de.addEventListener("dragleave",Xl,oo),e.addEventListener("dragover",Ql,oo),e.addEventListener("drop",Yl,oo);let Pa=e.ownerDocument,Zl=c=>{Qo()&&c.preventDefault()},ec=c=>{Qo()&&c.preventDefault()};Pa.addEventListener("dragover",Zl),Pa.addEventListener("drop",ec),ft.push(()=>{_t&&_t.removeEventListener("submit",Ls),pe==null||pe.removeEventListener("keydown",Is),pe==null||pe.removeEventListener("input",Ps),pe==null||pe.removeEventListener("paste",Rs),Qt.removeEventListener("keydown",Ws,!0)}),ft.push(()=>{de.removeEventListener("dragenter",Gl,oo),de.removeEventListener("dragleave",Xl,oo),e.removeEventListener("dragover",Ql,oo),e.removeEventListener("drop",Yl,oo),Pa.removeEventListener("dragover",Zl),Pa.removeEventListener("drop",ec),Vi()}),ft.push(()=>{T.cancel()}),Me?ft.push(()=>{Me==null||Me.destroy()}):Ge&&ft.push(()=>{Ge==null||Ge.remove()});let tn={update(c){var nn,Sr,Nr,Ia,Wa,Ra,Mo,Ha,Ds,Gc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Fp,Op,_p,$p,jp,Up,qp;let f=r.toolCall,y=r.messageActions,b=(nn=r.layout)==null?void 0:nn.messages,k=r.colorScheme,N=r.loadingIndicator,O=r.iterationDisplay,q=(Sr=r.features)==null?void 0:Sr.showReasoning,H=(Nr=r.features)==null?void 0:Nr.showToolCalls,Ae=(Ia=r.features)==null?void 0:Ia.toolCallDisplay,ue=(Wa=r.features)==null?void 0:Wa.reasoningDisplay;r={...r,...c},dr(),ao(e,r),Mi(e,r),ki(e,r),Un(),r.colorScheme!==k&&Xr();let ee=da.getForInstance(r.plugins);s.length=0,s.push(...ee),E=(Mo=(Ra=r.launcher)==null?void 0:Ra.enabled)!=null?Mo:!0,B=(Ds=(Ha=r.launcher)==null?void 0:Ha.autoExpand)!=null?Ds:!1,Ue=(Xc=(Gc=r.features)==null?void 0:Gc.showReasoning)!=null?Xc:!0,Fe=(Yc=(Qc=r.features)==null?void 0:Qc.showToolCalls)!=null?Yc:!0,xe=(ed=(Zc=r.features)==null?void 0:Zc.scrollToBottom)!=null?ed:{},Vt(),Rr();let ye=fe;if(fe=(nd=(td=r.features)==null?void 0:td.showEventStreamToggle)!=null?nd:!1,fe&&!ye){if(K||(te=new la(Be),K=new ia(Ie,te),ce=ce!=null?ce:new ca,te.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),T.setSSEEventCallback((Q,vt)=>{var Ot;(Ot=r.onSSEEvent)==null||Ot.call(r,Q,vt),ce==null||ce.processEvent(Q,vt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!mt&&Ne){let Q=(od=(rd=r.features)==null?void 0:rd.eventStream)==null?void 0:od.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");mt=h("button",vt),mt.style.width="28px",mt.style.height="28px",mt.style.color=Mn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let Ot=be("activity","18px","currentColor",1.5);Ot&&mt.appendChild(Ot);let dt=We.clearChatButtonWrapper,Et=We.closeButtonWrapper,an=dt||Et;an&&an.parentNode===Ne?Ne.insertBefore(mt,an):Ne.appendChild(mt),mt.addEventListener("click",()=>{he?Nn():bn()})}}else!fe&&ye&&(Nn(),mt&&(mt.remove(),mt=null),K==null||K.clear(),te==null||te.destroy(),K=null,te=null,ce==null||ce.reset(),ce=null);if(((sd=r.launcher)==null?void 0:sd.enabled)===!1&&Me&&(Me.destroy(),Me=null),((ad=r.launcher)==null?void 0:ad.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((id=r.launcher)==null?void 0:id.enabled)!==!1&&!Me&&!Ge){let Q=s.find(vt=>vt.renderLauncher);if(Q!=null&&Q.renderLauncher){let vt=Q.renderLauncher({config:r,defaultRenderer:()=>ra(r,tt).element,onToggle:tt});vt&&(Ge=vt,e.appendChild(Ge))}Ge||(Me=ra(r,tt),e.appendChild(Me.element))}Me&&Me.update(r),Se&&((ld=r.launcher)==null?void 0:ld.title)!==void 0&&(Se.textContent=r.launcher.title),De&&((cd=r.launcher)==null?void 0:cd.subtitle)!==void 0&&(De.textContent=r.launcher.subtitle);let Te=(dd=r.layout)==null?void 0:dd.header;if((Te==null?void 0:Te.layout)!==w&&Ne){let Q=Te?ls(r,Te,{showClose:$(),onClose:()=>Ht(!1,"user")}):_r({config:r,showClose:$(),onClose:()=>Ht(!1,"user")});Ne.replaceWith(Q.header),Ne=Q.header,F=Q.iconHolder,Se=Q.headerTitle,De=Q.headerSubtitle,qe=Q.closeButton,w=Te==null?void 0:Te.layout}else if(Te&&(F&&(F.style.display=Te.showIcon===!1?"none":""),Se&&(Se.style.display=Te.showTitle===!1?"none":""),De&&(De.style.display=Te.showSubtitle===!1?"none":""),qe&&(qe.style.display=Te.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let Q=Te.showClearChat;if(Q!==void 0){We.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:vt}=We;vt&&!vt.classList.contains("persona-absolute")&&(Q?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let rt=((pd=r.layout)==null?void 0:pd.showHeader)!==!1;Ne&&(Ne.style.display=rt?"":"none");let Xe=((ud=r.layout)==null?void 0:ud.showFooter)!==!1;je&&(je.style.display=Xe?"":"none"),bt(),Rr(),E!==R?E?Ht(B,"auto"):(D=!0,no()):B!==I&&Ht(B,"auto"),I=B,R=E,It(),un();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(f),ke=JSON.stringify(r.messageActions)!==JSON.stringify(y),ze=JSON.stringify((md=r.layout)==null?void 0:md.messages)!==JSON.stringify(b),M=((gd=r.loadingIndicator)==null?void 0:gd.render)!==(N==null?void 0:N.render)||((fd=r.loadingIndicator)==null?void 0:fd.renderIdle)!==(N==null?void 0:N.renderIdle)||((hd=r.loadingIndicator)==null?void 0:hd.showBubble)!==(N==null?void 0:N.showBubble),Ee=r.iterationDisplay!==O,He=((bd=(yd=r.features)==null?void 0:yd.showReasoning)!=null?bd:!0)!==(q!=null?q:!0)||((vd=(xd=r.features)==null?void 0:xd.showToolCalls)!=null?vd:!0)!==(H!=null?H:!0)||JSON.stringify((wd=r.features)==null?void 0:wd.toolCallDisplay)!==JSON.stringify(Ae)||JSON.stringify((Cd=r.features)==null?void 0:Cd.reasoningDisplay)!==JSON.stringify(ue);(Le||ke||ze||M||Ee||He)&&T&&(xs++,vo($e,T.getMessages(),Re));let ve=(Ad=r.launcher)!=null?Ad:{},Lt=(Sd=ve.headerIconHidden)!=null?Sd:!1,at=(Ed=(Td=r.layout)==null?void 0:Td.header)==null?void 0:Ed.showIcon,Yt=Lt||at===!1,dn=ve.headerIconName,Wt=(Md=ve.headerIconSize)!=null?Md:"48px";if(F){let Q=de.querySelector(".persona-border-b-persona-divider"),vt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Yt)F.style.display="none",Q&&vt&&!Q.contains(vt)&&Q.insertBefore(vt,Q.firstChild);else{if(F.style.display="",F.style.height=Wt,F.style.width=Wt,Q&&vt&&(Q.contains(F)?F.nextSibling!==vt&&(F.remove(),Q.insertBefore(F,vt)):Q.insertBefore(F,vt)),dn){let dt=parseFloat(Wt)||24,Et=be(dn,dt*.6,"#ffffff",2);Et?F.replaceChildren(Et):F.textContent=(kd=ve.agentIconText)!=null?kd:"\u{1F4AC}"}else if(ve.iconUrl){let dt=F.querySelector("img");if(dt)dt.src=ve.iconUrl,dt.style.height=Wt,dt.style.width=Wt;else{let Et=document.createElement("img");Et.src=ve.iconUrl,Et.alt="",Et.className="persona-rounded-xl persona-object-cover",Et.style.height=Wt,Et.style.width=Wt,F.replaceChildren(Et)}}else{let dt=F.querySelector("svg"),Et=F.querySelector("img");(dt||Et)&&F.replaceChildren(),F.textContent=(Ld=ve.agentIconText)!=null?Ld:"\u{1F4AC}"}let Ot=F.querySelector("img");Ot&&(Ot.style.height=Wt,Ot.style.width=Wt)}}let An=(Id=(Pd=r.layout)==null?void 0:Pd.header)==null?void 0:Id.showTitle,pn=(Rd=(Wd=r.layout)==null?void 0:Wd.header)==null?void 0:Rd.showSubtitle;if(Se&&(Se.style.display=An===!1?"none":""),De&&(De.style.display=pn===!1?"none":""),qe){((Bd=(Hd=r.layout)==null?void 0:Hd.header)==null?void 0:Bd.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let vt=(Dd=ve.closeButtonSize)!=null?Dd:"32px",Ot=(Nd=ve.closeButtonPlacement)!=null?Nd:"inline";qe.style.height=vt,qe.style.width=vt;let{closeButtonWrapper:dt}=We,Et=Ot==="top-right",an=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Et!==an)if(dt.remove(),Et)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",de.style.position="relative",de.appendChild(dt);else{let ut=(Od=(Fd=ve.clearChat)==null?void 0:Fd.placement)!=null?Od:"inline",ln=($d=(_d=ve.clearChat)==null?void 0:_d.enabled)!=null?$d:!0;dt.className=ln&&ut==="inline"?"":"persona-ml-auto";let Hn=de.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(dt)}if(qe.style.color=ve.closeButtonColor||Mn.actionIconColor,ve.closeButtonBackgroundColor?(qe.style.backgroundColor=ve.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),ve.closeButtonBorderWidth||ve.closeButtonBorderColor){let ut=ve.closeButtonBorderWidth||"0px",ln=ve.closeButtonBorderColor||"transparent";qe.style.border=`${ut} solid ${ln}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");ve.closeButtonBorderRadius?(qe.style.borderRadius=ve.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),ve.closeButtonPaddingX?(qe.style.paddingLeft=ve.closeButtonPaddingX,qe.style.paddingRight=ve.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),ve.closeButtonPaddingY?(qe.style.paddingTop=ve.closeButtonPaddingY,qe.style.paddingBottom=ve.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let gn=(jd=ve.closeButtonIconName)!=null?jd:"x",yr=(Ud=ve.closeButtonIconText)!=null?Ud:"\xD7";qe.innerHTML="";let En=be(gn,"28px","currentColor",1);En?qe.appendChild(En):qe.textContent=yr;let Zt=(qd=ve.closeButtonTooltipText)!=null?qd:"Close chat",Gn=(zd=ve.closeButtonShowTooltip)!=null?zd:!0;if(qe.setAttribute("aria-label",Zt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Gn&&Zt)){let ut=null,ln=()=>{if(ut||!qe)return;let ko=qe.ownerDocument,Ns=ko.body;if(!Ns)return;ut=Tr(ko,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let Fs=Tr(ko,"div");Fs.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Fs);let Lo=qe.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(io),ut.style.left=`${Lo.left+Lo.width/2}px`,ut.style.top=`${Lo.top-8}px`,ut.style.transform="translate(-50%, -100%)",Ns.appendChild(ut)},Hn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};dt.addEventListener("mouseenter",ln),dt.addEventListener("mouseleave",Hn),qe.addEventListener("focus",ln),qe.addEventListener("blur",Hn),dt._cleanupTooltip=()=>{Hn(),dt&&(dt.removeEventListener("mouseenter",ln),dt.removeEventListener("mouseleave",Hn)),qe&&(qe.removeEventListener("focus",ln),qe.removeEventListener("blur",Hn))}}}let{clearChatButton:et,clearChatButtonWrapper:ct}=We;if(et){let Q=(Vd=ve.clearChat)!=null?Vd:{},vt=(Kd=Q.enabled)!=null?Kd:!0,Ot=(Gd=(Jd=r.layout)==null?void 0:Jd.header)==null?void 0:Gd.showClearChat,dt=Ot!==void 0?Ot:vt,Et=(Xd=Q.placement)!=null?Xd:"inline";if(ct){ct.style.display=dt?"":"none";let{closeButtonWrapper:an}=We;!_()&&an&&!an.classList.contains("persona-absolute")&&(dt?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let gn=Et==="top-right",yr=ct.classList.contains("persona-absolute");if(!_()&&gn!==yr&&dt){if(ct.remove(),gn)ct.className="persona-absolute persona-top-4 persona-z-50",ct.style.right="48px",de.style.position="relative",de.appendChild(ct);else{ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ct.style.right="";let Zt=de.querySelector(".persona-border-b-persona-divider"),Gn=We.closeButtonWrapper;Zt&&Gn&&Gn.parentElement===Zt?Zt.insertBefore(ct,Gn):Zt&&Zt.appendChild(ct)}let En=We.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(gn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(dt){if(!_()){let ut=(Qd=Q.size)!=null?Qd:"32px";et.style.height=ut,et.style.width=ut}let an=(Yd=Q.iconName)!=null?Yd:"refresh-cw",gn=(Zd=Q.iconColor)!=null?Zd:"";et.style.color=gn||Mn.actionIconColor,et.innerHTML="";let yr=_()?"14px":"20px",En=be(an,yr,"currentColor",2);if(En&&et.appendChild(En),Q.backgroundColor?(et.style.backgroundColor=Q.backgroundColor,et.classList.remove("hover:persona-bg-gray-100")):(et.style.backgroundColor="",et.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let ut=Q.borderWidth||"0px",ln=Q.borderColor||"transparent";et.style.border=`${ut} solid ${ln}`,et.classList.remove("persona-border-none")}else et.style.border="",et.classList.add("persona-border-none");Q.borderRadius?(et.style.borderRadius=Q.borderRadius,et.classList.remove("persona-rounded-full")):(et.style.borderRadius="",et.classList.add("persona-rounded-full")),Q.paddingX?(et.style.paddingLeft=Q.paddingX,et.style.paddingRight=Q.paddingX):(et.style.paddingLeft="",et.style.paddingRight=""),Q.paddingY?(et.style.paddingTop=Q.paddingY,et.style.paddingBottom=Q.paddingY):(et.style.paddingTop="",et.style.paddingBottom="");let Zt=(ep=Q.tooltipText)!=null?ep:"Clear chat",Gn=(tp=Q.showTooltip)!=null?tp:!0;if(et.setAttribute("aria-label",Zt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Gn&&Zt)){let ut=null,ln=()=>{if(ut||!et)return;let ko=et.ownerDocument,Ns=ko.body;if(!Ns)return;ut=Tr(ko,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let Fs=Tr(ko,"div");Fs.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Fs);let Lo=et.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(io),ut.style.left=`${Lo.left+Lo.width/2}px`,ut.style.top=`${Lo.top-8}px`,ut.style.transform="translate(-50%, -100%)",Ns.appendChild(ut)},Hn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};ct.addEventListener("mouseenter",ln),ct.addEventListener("mouseleave",Hn),et.addEventListener("focus",ln),et.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",ln),ct.removeEventListener("mouseleave",Hn)),et&&(et.removeEventListener("focus",ln),et.removeEventListener("blur",Hn))}}}}let Sn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[pa],mn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[jo.message,jo.messageAndClick];A=ua({parsers:Sn,handlers:mn,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Re=Tm(r,A,se),T.updateConfig(r),vo($e,T.getMessages(),Re),pr.render(r.suggestionChips,T,pe,void 0,r.suggestionChipsConfig),Ms(),Ko(T.isStreaming());let Ao=((np=r.voiceRecognition)==null?void 0:np.enabled)===!0,So=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),To=((op=(rp=r.voiceRecognition)==null?void 0:rp.provider)==null?void 0:op.type)==="runtype";if(Ao&&(So||To))if(!z||!$t){let Q=La(r.voiceRecognition,r.sendButton);Q&&(z=Q.micButton,$t=Q.micButtonWrapper,St.insertBefore($t,kn),z.addEventListener("click",G),z.disabled=T.isStreaming())}else{let Q=(sp=r.voiceRecognition)!=null?sp:{},vt=(ap=r.sendButton)!=null?ap:{},Ot=(ip=Q.iconName)!=null?ip:"mic",dt=(lp=vt.size)!=null?lp:"40px",Et=(cp=Q.iconSize)!=null?cp:dt,an=parseFloat(Et)||24;z.style.width=Et,z.style.height=Et,z.style.minWidth=Et,z.style.minHeight=Et;let gn=(pp=(dp=Q.iconColor)!=null?dp:vt.textColor)!=null?pp:"currentColor";z.innerHTML="";let yr=be(Ot,an,gn,2);yr?z.appendChild(yr):z.textContent="\u{1F3A4}";let En=(up=Q.backgroundColor)!=null?up:vt.backgroundColor;En?z.style.backgroundColor=En:z.style.backgroundColor="",gn?z.style.color=gn:z.style.color="var(--persona-text, #111827)",Q.borderWidth?(z.style.borderWidth=Q.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),Q.borderColor?z.style.borderColor=Q.borderColor:z.style.borderColor="",Q.paddingX?(z.style.paddingLeft=Q.paddingX,z.style.paddingRight=Q.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),Q.paddingY?(z.style.paddingTop=Q.paddingY,z.style.paddingBottom=Q.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let Zt=$t==null?void 0:$t.querySelector(".persona-send-button-tooltip"),Gn=(mp=Q.tooltipText)!=null?mp:"Start voice recognition";if(((gp=Q.showTooltip)!=null?gp:!1)&&Gn)if(Zt)Zt.textContent=Gn,Zt.style.display="";else{let ln=document.createElement("div");ln.className="persona-send-button-tooltip",ln.textContent=Gn,$t==null||$t.insertBefore(ln,z)}else Zt&&(Zt.style.display="none");$t.style.display="",z.disabled=T.isStreaming()}else z&&$t&&($t.style.display="none",((hp=(fp=r.voiceRecognition)==null?void 0:fp.provider)==null?void 0:hp.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Kn&&hr());if(((yp=r.attachments)==null?void 0:yp.enabled)===!0)if(!Ft||!Ze){let Q=(bp=r.attachments)!=null?bp:{},Ot=(vp=((xp=r.sendButton)!=null?xp:{}).size)!=null?vp:"40px";ge||(ge=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ge.style.display="none",_t.insertBefore(ge,pe)),re||(re=document.createElement("input"),re.type="file",re.accept=((wp=Q.allowedTypes)!=null?wp:Or).join(","),re.multiple=((Cp=Q.maxFiles)!=null?Cp:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),_t.insertBefore(re,pe)),Ft=h("div","persona-send-button-wrapper"),Ze=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ze.type="button",Ze.setAttribute("aria-label",(Ap=Q.buttonTooltipText)!=null?Ap:"Attach file");let dt=(Sp=Q.buttonIconName)!=null?Sp:"paperclip",Et=Ot,an=parseFloat(Et)||40,gn=Math.round(an*.6);Ze.style.width=Et,Ze.style.height=Et,Ze.style.minWidth=Et,Ze.style.minHeight=Et,Ze.style.fontSize="18px",Ze.style.lineHeight="1",Ze.style.backgroundColor="transparent",Ze.style.color="var(--persona-primary, #111827)",Ze.style.border="none",Ze.style.borderRadius="6px",Ze.style.transition="background-color 0.15s ease",Ze.addEventListener("mouseenter",()=>{Ze.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ze.addEventListener("mouseleave",()=>{Ze.style.backgroundColor="transparent"});let yr=be(dt,gn,"currentColor",1.5);yr?Ze.appendChild(yr):Ze.textContent="\u{1F4CE}",Ze.addEventListener("click",Gn=>{Gn.preventDefault(),re==null||re.click()}),Ft.appendChild(Ze);let En=(Tp=Q.buttonTooltipText)!=null?Tp:"Attach file",Zt=h("div","persona-send-button-tooltip");Zt.textContent=En,Ft.appendChild(Zt),ot.append(Ft),!nt&&re&&ge&&(nt=No.fromConfig(Q),nt.setPreviewsContainer(ge),re.addEventListener("change",async()=>{nt&&(re!=null&&re.files)&&(await nt.handleFileSelect(re.files),re.value="")})),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(Em(Q.dropOverlay))}else{Ft.style.display="";let Q=(Ep=r.attachments)!=null?Ep:{};re&&(re.accept=((Mp=Q.allowedTypes)!=null?Mp:Or).join(","),re.multiple=((kp=Q.maxFiles)!=null?kp:4)>1),nt&&nt.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else Ft&&(Ft.style.display="none"),nt&&nt.clearAttachments(),(Lp=de.querySelector(".persona-attachment-drop-overlay"))==null||Lp.remove();let Kt=(Pp=r.sendButton)!=null?Pp:{},Eo=(Ip=Kt.useIcon)!=null?Ip:!1,so=(Wp=Kt.iconText)!=null?Wp:"\u2191",yt=Kt.iconName,In=(Rp=Kt.tooltipText)!=null?Rp:"Send message",Dr=(Hp=Kt.showTooltip)!=null?Hp:!1,Tn=(Bp=Kt.size)!=null?Bp:"40px",Wn=Kt.backgroundColor,Bt=Kt.textColor;if(Eo){if(ie.style.width=Tn,ie.style.height=Tn,ie.style.minWidth=Tn,ie.style.minHeight=Tn,ie.style.fontSize="18px",ie.style.lineHeight="1",ie.innerHTML="",Bt?ie.style.color=Bt:ie.style.color="var(--persona-button-primary-fg, #ffffff)",yt){let Q=parseFloat(Tn)||24,vt=(Bt==null?void 0:Bt.trim())||"currentColor",Ot=be(yt,Q,vt,2);Ot?ie.appendChild(Ot):ie.textContent=so}else ie.textContent=so;ie.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ie.style.backgroundColor=Wn,ie.classList.remove("persona-bg-persona-primary")):(ie.style.backgroundColor="",ie.classList.add("persona-bg-persona-primary"))}else ie.textContent=(Np=(Dp=r.copy)==null?void 0:Dp.sendButtonLabel)!=null?Np:"Send",ie.style.width="",ie.style.height="",ie.style.minWidth="",ie.style.minHeight="",ie.style.fontSize="",ie.style.lineHeight="",ie.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",Wn?(ie.style.backgroundColor=Wn,ie.classList.remove("persona-bg-persona-accent")):ie.classList.add("persona-bg-persona-accent"),Bt?ie.style.color=Bt:ie.classList.add("persona-text-white");Kt.borderWidth?(ie.style.borderWidth=Kt.borderWidth,ie.style.borderStyle="solid"):(ie.style.borderWidth="",ie.style.borderStyle=""),Kt.borderColor?ie.style.borderColor=Kt.borderColor:ie.style.borderColor="",Kt.paddingX?(ie.style.paddingLeft=Kt.paddingX,ie.style.paddingRight=Kt.paddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),Kt.paddingY?(ie.style.paddingTop=Kt.paddingY,ie.style.paddingBottom=Kt.paddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let zt=kn==null?void 0:kn.querySelector(".persona-send-button-tooltip");if(Dr&&In)if(zt)zt.textContent=In,zt.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=In,kn==null||kn.insertBefore(Q,ie)}else zt&&(zt.style.display="none");let Dt=(jp=(Fp=r.layout)==null?void 0:Fp.contentMaxWidth)!=null?jp:_()?($p=(_p=(Op=r.launcher)==null?void 0:Op.composerBar)==null?void 0:_p.contentMaxWidth)!=null?$p:"720px":void 0;Dt?($e.style.maxWidth=Dt,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",_t&&(_t.style.maxWidth=Dt,_t.style.marginLeft="auto",_t.style.marginRight="auto"),Mt&&(Mt.style.maxWidth=Dt,Mt.style.marginLeft="auto",Mt.style.marginRight="auto")):($e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",_t&&(_t.style.maxWidth="",_t.style.marginLeft="",_t.style.marginRight=""),Mt&&(Mt.style.maxWidth="",Mt.style.marginLeft="",Mt.style.marginRight=""));let Jt=(Up=r.statusIndicator)!=null?Up:{},Rn=(qp=Jt.visible)!=null?qp:!0;if(cn.style.display=Rn?"":"none",T){let Q=T.getStatus();me(cn,(Ot=>{var dt,Et,an,gn;return Ot==="idle"?(dt=Jt.idleText)!=null?dt:fn.idle:Ot==="connecting"?(Et=Jt.connectingText)!=null?Et:fn.connecting:Ot==="connected"?(an=Jt.connectedText)!=null?an:fn.connected:Ot==="error"?(gn=Jt.errorText)!=null?gn:fn.error:fn[Ot]})(Q),Jt,Q)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Jn=Jt.align==="left"?"persona-text-left":Jt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(Jn)},open(){$()&&Ht(!0,"api")},close(){$()&&Ht(!1,"api")},toggle(){$()&&Ht(!D,"api")},clearChat(){xn=!1,T.clearMessages(),ur.clear(),Qr();try{localStorage.removeItem(bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}d={},A.syncFromMetadata(),K==null||K.clear(),ce==null||ce.reset(),we==null||we.update()},setMessage(c){return!pe||T.isStreaming()?!1:(!D&&$()&&Ht(!0,"system"),pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(T.isStreaming())return!1;let f=(c==null?void 0:c.trim())||pe.value.trim();return f?(!D&&$()&&Ht(!0,"system"),pe.value="",pe.style.height="auto",T.sendMessage(f),!0):!1},startVoiceRecognition(){var f,y;return T.isStreaming()?!1:((y=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:y.type)==="runtype"?(T.isVoiceActive()||(!D&&$()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("user"),T.isVoiceActive()&&j()})),!0):Kn?!0:Hs()?(!D&&$()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),Co("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),or("user"),J()}),!0):!1:Kn?(gt.manuallyDeactivated=!0,Pn(),hr("user"),!0):!1},injectMessage(c){return!D&&$()&&Ht(!0,"system"),T.injectMessage(c)},injectAssistantMessage(c){!D&&$()&&Ht(!0,"system");let f=T.injectAssistantMessage(c);return U&&(U=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),f},injectUserMessage(c){return!D&&$()&&Ht(!0,"system"),T.injectUserMessage(c)},injectSystemMessage(c){return!D&&$()&&Ht(!0,"system"),T.injectSystemMessage(c)},injectMessageBatch(c){return!D&&$()&&Ht(!0,"system"),T.injectMessageBatch(c)},injectComponentDirective(c){return!D&&$()&&Ht(!0,"system"),T.injectComponentDirective(c)},injectTestMessage(c){!D&&$()&&Ht(!0,"system"),T.injectTestEvent(c)},async connectStream(c,f){return T.connectStream(c,f)},__pushEventStreamEvent(c){K&&(ce==null||ce.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!fe||!K||bn()},hideEventStream(){he&&Nn()},isEventStreamVisible(){return he},showArtifacts(){cr(r)&&(xn=!1,Un(),xt==null||xt.setMobileOpen(!0))},hideArtifacts(){cr(r)&&(xn=!0,Un())},upsertArtifact(c){return cr(r)?(xn=!1,T.upsertArtifact(c)):null},selectArtifact(c){cr(r)&&T.selectArtifact(c)},clearArtifacts(){cr(r)&&T.clearArtifacts()},getArtifacts(){var c;return(c=T==null?void 0:T.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=T==null?void 0:T.getSelectedArtifactId())!=null?c:null},focusInput(){return E&&!D&&!_()||!pe?!1:(pe.focus(),!0)},async resolveApproval(c,f){let b=T.getMessages().find(k=>{var N;return k.variant==="approval"&&((N=k.approval)==null?void 0:N.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);if(b.approval.toolType==="webmcp"){T.resolveWebMcpApproval(b.id,f);return}return T.resolveApproval(b.approval,f)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){u(c)},on(c,f){return o.on(c,f)},off(c,f){o.off(c,f)},isOpen(){return $()&&D},isVoiceActive(){return gt.active},getState(){return{open:$()&&D,launcherEnabled:E,voiceActive:gt.active,streaming:T.isStreaming()}},showCSATFeedback(c){!D&&$()&&Ht(!0,"system");let f=$e.querySelector(".persona-feedback-container");f&&f.remove();let y=Hi({onSubmit:async(b,k)=>{var N;T.isClientTokenMode()&&await T.submitCSATFeedback(b,k),(N=c==null?void 0:c.onSubmit)==null||N.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!D&&$()&&Ht(!0,"system");let f=$e.querySelector(".persona-feedback-container");f&&f.remove();let y=Bi({onSubmit:async(b,k)=>{var N;T.isClientTokenMode()&&await T.submitNPSFeedback(b,k),(N=c==null?void 0:c.onSubmit)==null||N.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return T.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return T.submitNPSFeedback(c,f)},destroy(){Ar!=null&&(clearInterval(Ar),Ar=null),ft.forEach(c=>c()),le.remove(),Ye==null||Ye.remove(),Me==null||Me.destroy(),Ge==null||Ge.remove(),zn&&qe.removeEventListener("click",zn)}};if((((Uc=t==null?void 0:t.debugTools)!=null?Uc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:y=>y?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=f,ft.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",f),ft.push(()=>{window.removeEventListener("persona:focusInput",f)}),fe){let q=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&tn.showEventStream()},H=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",H),ft.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",H)})}let y=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.showArtifacts()},b=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.hideArtifacts()},k=q=>{let H=q.detail;H!=null&&H.instanceId&&H.instanceId!==c||H!=null&&H.artifact&&tn.upsertArtifact(H.artifact)},N=q=>{let H=q.detail;H!=null&&H.instanceId&&H.instanceId!==c||typeof(H==null?void 0:H.id)=="string"&&tn.selectArtifact(H.id)},O=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",O),ft.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",O)})}let ar=Nh(r.persistState);if(ar&&$()){let c=Fh(ar.storage),f=`${ar.keyPrefix}widget-open`,y=`${ar.keyPrefix}widget-voice`,b=`${ar.keyPrefix}widget-voice-mode`;if(c){let k=((qc=ar.persist)==null?void 0:qc.openState)&&c.getItem(f)==="true",N=((zc=ar.persist)==null?void 0:zc.voiceState)&&c.getItem(y)==="true",O=((Vc=ar.persist)==null?void 0:Vc.voiceState)&&c.getItem(b)==="true";if(k&&setTimeout(()=>{tn.open(),setTimeout(()=>{var q;if(N||O)tn.startVoiceRecognition();else if((q=ar.persist)!=null&&q.focusInput){let H=e.querySelector("textarea");H&&H.focus()}},100)},0),(Kc=ar.persist)!=null&&Kc.openState&&(o.on("widget:opened",()=>{c.setItem(f,"true")}),o.on("widget:closed",()=>{c.setItem(f,"false")})),(Jc=ar.persist)!=null&&Jc.voiceState&&(o.on("voice:state",q=>{c.setItem(y,q.active?"true":"false")}),o.on("user:message",q=>{c.setItem(b,q.viaVoice?"true":"false")})),ar.clearOnChatClear){let q=()=>{c.removeItem(f),c.removeItem(y),c.removeItem(b)},H=()=>q();window.addEventListener("persona:clear-chat",H),ft.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return p&&$()&&setTimeout(()=>{tn.open()},0),Hr(),tn};var Oh=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},Mm=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.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"},Bl=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=""},km=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Bl(e)},Wl=e=>{e.style.transition=""},Rl=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=""},Hl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Fi=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},_h=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},$h=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Lm=(e,n,t,r,s,o,a)=>{var v,x,A,E,B,P;let i=ir(o),d=i.reveal==="push";_h(e,n,t,r,d),$h(e,n,t,r,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 l=e.ownerDocument.defaultView,p=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,m=(E=(A=o==null?void 0:o.launcher)==null?void 0:A.mobileBreakpoint)!=null?E:640,g=l!=null?l.innerWidth<=m:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Rl(n),Wl(r),km(r),Hl(t),Fi(s,r),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",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((P=(B=o==null?void 0:o.launcher)==null?void 0:B.zIndex)!=null?P:hn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.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"),km(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Rl(n),Wl(r),Hl(t),Fi(s,r);let I=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":R;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=I,r.style.transform=w,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.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",Wl(r),Bl(r),Fi(s,r);let I=Oh(i.width,e.clientWidth),R=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",W=i.side==="right"?a?`translateX(-${I}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${I}px)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${R+I}px`,n.style.transition=w,n.style.transform=W,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${R}px`,t.style.maxWidth=`${R}px`,t.style.minWidth=`${R}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Rl(n),Bl(r),Hl(t),Fi(s,r);let I=i.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${R}`,r.style.width=R,r.style.maxWidth=R,r.style.minWidth=R,r.style.minHeight="0",r.style.position="relative",r.style.overflow=I||W?"hidden":"visible",r.style.transition=w,I&&(r.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")}},jh=(e,n)=>{let t=e.ownerDocument.createElement("div");return Mm(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Mm(t,r)},destroy(){t.remove()}}},Uh=(e,n)=>{var B,P,I,R;let{ownerDocument:t}=e,r=e.parentElement;if(!r)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"),l=t.createElement("aside"),p=t.createElement("div"),m=(P=(B=n==null?void 0:n.launcher)==null?void 0:B.enabled)==null||P?(R=(I=n==null?void 0:n.launcher)==null?void 0:I.autoExpand)!=null?R:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,u=()=>{g==null||g.disconnect(),g=null},v=()=>{u(),ir(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Lm(a,i,d,l,p,n,m)}),g.observe(a))},x=()=>{Lm(a,i,d,l,p,n,m),v()},A=a.ownerDocument.defaultView,E=()=>{x()};return A==null||A.addEventListener("resize",E),ir(n).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:p,shell:a,syncWidgetState(w){let W=w.launcherEnabled?w.open:!0;m!==W&&(m=W,x())},updateConfig(w){var W,_;n=w,((_=(W=n==null?void 0:n.launcher)==null?void 0:W.enabled)!=null?_:!0)===!1&&(m=!0),x()},destroy(){A==null||A.removeEventListener("resize",E),u(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},ma=(e,n)=>rn(n)?Uh(e,n):jh(e,n);var Dl={},Pm=!1,qh=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 n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},zh=()=>{try{if(typeof Dl!="undefined"&&Dl.url)return new URL("../widget.css",Dl.url).href}catch{}return null},Im=(e,n)=>{let t=zh(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.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=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},Nl=e=>{let n=qh(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=ma(n,s),a,i=[],d=(A,E)=>{var R,w;let P=!((w=(R=E==null?void 0:E.launcher)==null?void 0:R.enabled)!=null?w:!0)||rn(E),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),P&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),t){let W=A.attachShadow({mode:"open"});W.appendChild(I),Im(W,r)}else A.appendChild(I),Im(A,r);return n.id&&I.setAttribute("data-persona-instance",n.id),I},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},m=()=>{let A=d(o.host,s);a=Ni(A,s,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(A=>A()),i=[],a.destroy()};m(),e.onChatReady?e.onChatReady():e.onReady&&(Pm||(Pm=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let u=A=>{g(),o.destroy(),o=ma(n,A),s=A,m()},v={update(A){var w,W,_,$,D,U;let E={...s,...A,launcher:{...(w=s==null?void 0:s.launcher)!=null?w:{},...(W=A==null?void 0:A.launcher)!=null?W:{},dock:{...($=(_=s==null?void 0:s.launcher)==null?void 0:_.dock)!=null?$:{},...(U=(D=A==null?void 0:A.launcher)==null?void 0:D.dock)!=null?U:{}}}},B=rn(s),P=rn(E),I=co(s),R=co(E);if(B!==P||I!==R){u(E);return}s=E,o.updateConfig(s),a.update(A),l()},destroy(){g(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(A,E,B){if(E==="host")return o.host;if(E in A)return Reflect.get(A,E,B);let P=a[E];return typeof P=="function"?P.bind(a):P}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Dm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Vh=new Set(["button","a","input","select","textarea","details","summary"]),Kh=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Fl=/\b(product|card|item|listing|result)\b/i,_l=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Jh=3e3,Gh=100;function Nm(e){let n=typeof e.className=="string"?e.className:"";if(Fl.test(n)||e.id&&Fl.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Fl.test(r.value))return!0}return!1}function Fm(e){var n;return _l.test(((n=e.textContent)!=null?n:"").trim())}function Om(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Xh(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Wm(e){let n=e.match(_l);return n?n[0]:null}function Rm(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.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 Qh(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var Yh="commerce-card",Zh="result-card";function Hm(e){return!Nm(e)||!Fm(e)||!Om(e)&&!Xh(e)?0:5200}function Bm(e){var r;return!Nm(e)||Fm(e)||!Om(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var $l=[{id:Yh,scoreElement(e){return Hm(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||_l.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,p;if(Hm(e)===0)return null;let{title:t,href:r}=Rm(e),s=(p=(l=Wm(((d=e.textContent)!=null?d:"").trim()))!=null?l:Wm(n.text))!=null?p:"",o=Qh(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
108
|
-
`)}},{id:
|
|
109
|
-
`)}}];function
|
|
107
|
+
`}if(!b&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",Jt=f?"":"padding-top: 1.25em !important;",Rn=f?"":`z-index: ${(zt=(Bt=r.launcher)==null?void 0:Bt.zIndex)!=null?zt:hn} !important;`;le.style.cssText+=Dt+Jt+Rn}M()};dr(),ao(e,r),ki(e,r),Li(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",Kr)});let Gt=null,Xt=null;ft.push(()=>{Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null}),On&&ft.push(()=>{On==null||On.disconnect(),On=null}),ft.push(()=>{vn==null||vn(),vn=null,Lr(),Rt&&(Rt.remove(),Rt=null),xt==null||xt.element.style.removeProperty("width"),xt==null||xt.element.style.removeProperty("maxWidth")}),fe&&ft.push(()=>{Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),we==null||we.destroy(),we=null,K==null||K.destroy(),K=null,te=null});let qn=null,Xr=()=>{qn&&(qn(),qn=null),r.colorScheme==="auto"&&(qn=oi(()=>{ao(e,r)}))};Xr(),ft.push(()=>{qn&&(qn(),qn=null)});let rr=(Nc=r.features)==null?void 0:Nc.streamAnimation;if(rr!=null&&rr.type&&rr.type!=="none"){let c=Zs(rr.type,rr.plugins);c&&(al(c,e),ft.push(()=>Nu(e)))}let pr=am(Mt),zn=null,T,Vn=!1,ur=ku(),Pr=new Map,Cr=new Map,xs=0,mr=ii(),gr=0,fr=null,Ir=!1,bo=!1,fa=4,vs=24,ha=80,zo=new Map,gt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ws=(Oc=(Fc=r.voiceRecognition)==null?void 0:Fc.autoResume)!=null?Oc:!1,or=c=>{o.emit("voice:state",{active:gt.active,source:c,timestamp:Date.now()})},Pn=()=>{u(c=>({...c,voiceState:{active:gt.active,timestamp:Date.now(),manuallyDeactivated:gt.manuallyDeactivated}}))},ya=()=>{var b,k;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=Wl(d.voiceState),f=!!c.active,y=Number((k=c.timestamp)!=null?k:0);gt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-y<Bh&&setTimeout(()=>{var N,O;gt.active||(gt.manuallyDeactivated=!1,((O=(N=r.voiceRecognition)==null?void 0:N.provider)==null?void 0:O.type)==="runtype"?T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("restore"),T.isVoiceActive()&&j()}):Co("restore"))},1e3)},ba=()=>T?Tm(T.getMessages()).filter(c=>!c.__skipPersist):[];function Vo(c){if(!(i!=null&&i.save))return;let y={messages:c?Tm(c):T?ba():[],metadata:d,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Wr=null,xa=()=>le.querySelector("#persona-scroll-container")||X,xo=()=>{Wr!==null&&(cancelAnimationFrame(Wr),Wr=null),Ir=!1},Cs=()=>{fr!==null&&(cancelAnimationFrame(fr),fr=null),bo=!1,xo()},Rr=()=>{if(!yn()||he){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==de&&de.appendChild(Tt),bt();let c=Gs(X)>0;Tt.style.display=mr.isFollowing()||!c?"none":""},As=()=>{mr.pause()&&(Cs(),Rr())},Qr=()=>{mr.resume(),Rr()},Yr=(c=!1)=>{mr.isFollowing()&&(!c&&!Vn||(fr!==null&&(cancelAnimationFrame(fr),fr=null),bo=!0,fr=requestAnimationFrame(()=>{fr=null,bo=!1,mr.isFollowing()&&va(xa(),c?220:140)})))},va=(c,f=500)=>{let y=c.scrollTop,b=Gs(c),k=b-y;if(Math.abs(k)<1){gr=c.scrollTop;return}if(Math.abs(k)>=ha){xo(),Ir=!0,c.scrollTop=b,gr=c.scrollTop,Ir=!1;return}xo();let N=performance.now();Ir=!0;let O=H=>1-Math.pow(1-H,3),q=H=>{if(!mr.isFollowing()){xo();return}let Ae=Gs(c);Ae!==b&&(b=Ae,k=b-y);let ue=H-N,ee=Math.min(ue/f,1),ye=O(ee),Te=y+k*ye;c.scrollTop=Te,gr=c.scrollTop,ee<1?Wr=requestAnimationFrame(q):(c.scrollTop=b,gr=c.scrollTop,Wr=null,Ir=!1)};Wr=requestAnimationFrame(q)},wa=c=>{let f=new Map;c.forEach(y=>{let b=zo.get(y.id);f.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),zo.clear(),f.forEach((y,b)=>{zo.set(b,y)})},vo=(c,f,y)=>{var Xe,it,lt,Le,ke,ze;let b=document.createElement("div"),N=(()=>{var Ee;let M=s.find(He=>He.renderLoadingIndicator);if(M!=null&&M.renderLoadingIndicator)return M.renderLoadingIndicator;if((Ee=r.loadingIndicator)!=null&&Ee.render)return r.loadingIndicator.render})(),O=(M,Ee)=>Ee==null?!1:typeof Ee=="string"?(M.textContent=Ee,!0):(M.appendChild(Ee),!0),q=new Set,H=new Set,Ae=s.some(M=>M.renderAskUserQuestion),ue=[],ee=[],ye=r.enableComponentStreaming!==!1;if(f.forEach(M=>{var An,pn,et,ct,Sn,mn,Ao,So,To,Yo,Zo,Kt,Eo,so;q.add(M.id);let Ee=Ae&&_r(M),He=!Ee&&M.role==="assistant"&&!M.variant&&ye&&Ri(M);if(!He&&Cr.has(M.id)){let yt=c.querySelector(`#wrapper-${M.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),Cr.delete(M.id)}let Je=_r(M)?`:${(An=M.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(pn=M.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(M.agentMetadata.askUserQuestionAnswers).length:0}`:"",ve=Mu(M,xs)+Je,Lt=Ee||He?null:Lu(ur,M.id,ve);if(Lt){b.appendChild(Lt.cloneNode(!0)),_r(M)&&((et=M.toolCall)!=null&&et.id)&&((ct=M.agentMetadata)==null?void 0:ct.awaitingLocalTool)===!0&&!((Sn=M.agentMetadata)!=null&&Sn.askUserQuestionAnswered)&&(H.add(M.toolCall.id),fs(M,r,We.composerOverlay));return}let at=null,Yt=s.find(yt=>!!(M.variant==="reasoning"&&yt.renderReasoning||M.variant==="tool"&&yt.renderToolCall||M.variant==="approval"&&yt.renderApproval||!M.variant&&yt.renderMessage)),dn=(mn=r.layout)==null?void 0:mn.messages;if(_r(M)&&((Ao=M.agentMetadata)==null?void 0:Ao.askUserQuestionAnswered)===!0){Pr.delete(M.id);let yt=c.querySelector(`#wrapper-${M.id}`);yt==null||yt.removeAttribute("data-preserve-runtime");return}if(_r(M)&&((To=(So=r.features)==null?void 0:So.askUserQuestion)==null?void 0:To.enabled)!==!1){let yt=s.find(In=>typeof In.renderAskUserQuestion=="function");if(yt&&Pt.current){let In=Pr.get(M.id),Dr=In!==ve,Tn=null;if(Dr){let{payload:zt,complete:Dt}=jr(M),Jt=M.id,Rn=()=>{var Jn;return(Jn=Pt.current)==null?void 0:Jn.getMessages().find(nn=>nn.id===Jt)};Tn=yt.renderAskUserQuestion({message:M,payload:zt,complete:Dt,resolve:Jn=>{var Sr;let nn=Rn();nn&&((Sr=Pt.current)==null||Sr.resolveAskUserQuestion(nn,Jn))},dismiss:()=>{var nn,Sr,Nr;let Jn=Rn();(nn=Jn==null?void 0:Jn.agentMetadata)!=null&&nn.awaitingLocalTool&&((Sr=Pt.current)==null||Sr.markAskUserQuestionResolved(Jn),(Nr=Pt.current)==null||Nr.resolveAskUserQuestion(Jn,"(dismissed)"))},config:r})}let Wn=In!=null;if(Dr&&Tn===null&&!Wn){((Yo=M.agentMetadata)==null?void 0:Yo.awaitingLocalTool)===!0&&!((Zo=M.agentMetadata)!=null&&Zo.askUserQuestionAnswered)&&(H.add(M.toolCall.id),fs(M,r,We.composerOverlay));return}let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${M.id}`,Bt.setAttribute("data-wrapper-id",M.id),Bt.setAttribute("data-ask-plugin-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),b.appendChild(Bt),ue.push({messageId:M.id,fingerprint:ve,bubble:Tn});return}else{((Kt=M.agentMetadata)==null?void 0:Kt.awaitingLocalTool)===!0&&!((Eo=M.agentMetadata)!=null&&Eo.askUserQuestionAnswered)&&(H.add(M.toolCall.id),fs(M,r,We.composerOverlay));return}}else if(Yt)if(M.variant==="reasoning"&&M.reasoning&&Yt.renderReasoning){if(!Ue)return;at=Yt.renderReasoning({message:M,defaultRenderer:()=>hl(M,r),config:r})}else if(M.variant==="tool"&&M.toolCall&&Yt.renderToolCall){if(!Fe)return;at=Yt.renderToolCall({message:M,defaultRenderer:()=>yl(M,r),config:r})}else if(M.variant==="approval"&&M.approval&&Yt.renderApproval){if(r.approval===!1)return;at=Yt.renderApproval({message:M,defaultRenderer:()=>Tl(M,r),config:r})}else Yt.renderMessage&&(at=Yt.renderMessage({message:M,defaultRenderer:()=>{let yt=ds(M,y,dn,r.messageActions,Y,{loadingIndicatorRenderer:N,widgetConfig:r});return M.role!=="user"&&Ll(yt,M,r,T),yt},config:r}));if(!at&&He){let yt=Hi(M);if(yt){let In=Cr.get(M.id),Dr=In!==ve,Tn=r.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Dr){let Bt=Wi(yt,{config:r,message:M,transform:y});if(Bt)if(Tn){let zt=document.createElement("div");if(zt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),zt.id=`bubble-${M.id}`,zt.setAttribute("data-message-id",M.id),M.content&&M.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=y({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),zt.appendChild(Dt)}zt.appendChild(Bt),Wn=zt}else{let zt=document.createElement("div");if(zt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",zt.id=`bubble-${M.id}`,zt.setAttribute("data-message-id",M.id),zt.setAttribute("data-persona-component-directive","true"),M.content&&M.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=y({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),zt.appendChild(Dt)}zt.appendChild(Bt),Wn=zt}}if(Wn||In!=null){let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${M.id}`,Bt.setAttribute("data-wrapper-id",M.id),Bt.setAttribute("data-component-directive-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),Tn||Bt.classList.add("persona-w-full"),b.appendChild(Bt),ee.push({messageId:M.id,fingerprint:ve,bubble:Wn});return}}}if(!at)if(M.variant==="reasoning"&&M.reasoning){if(!Ue)return;at=hl(M,r)}else if(M.variant==="tool"&&M.toolCall){if(!Fe)return;at=yl(M,r)}else if(M.variant==="approval"&&M.approval){if(r.approval===!1)return;at=Tl(M,r)}else{let yt=(so=r.layout)==null?void 0:so.messages;yt!=null&&yt.renderUserMessage&&M.role==="user"?at=yt.renderUserMessage({message:M,config:r,streaming:!!M.streaming}):yt!=null&&yt.renderAssistantMessage&&M.role==="assistant"?at=yt.renderAssistantMessage({message:M,config:r,streaming:!!M.streaming}):at=ds(M,y,yt,r.messageActions,Y,{loadingIndicatorRenderer:N,widgetConfig:r}),M.role!=="user"&&at&&Ll(at,M,r,T)}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${M.id}`,Wt.setAttribute("data-wrapper-id",M.id),M.role==="user"&&Wt.classList.add("persona-justify-end"),(at==null?void 0:at.getAttribute("data-persona-component-directive"))==="true"&&Wt.classList.add("persona-w-full"),Wt.appendChild(at),Pu(ur,M.id,ve,Wt),b.appendChild(Wt)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ee=>{let He=Ee.getAttribute("data-persona-ask-sheet-for");He&&!H.has(He)&&go(We.composerOverlay,He)}),(it=(Xe=r.features)==null?void 0:Xe.toolCallDisplay)!=null&&it.grouped){let M=[],Ee=[];f.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&Fe){Ee.push(He);return}Ee.length>1&&M.push(Ee),Ee=[]}),Ee.length>1&&M.push(Ee),M.forEach((He,Je)=>{var pn,et;let ve=He.map(ct=>Array.from(b.children).find(Sn=>Sn instanceof HTMLElement&&Sn.getAttribute("data-wrapper-id")===ct.id)).filter(ct=>!!ct);if(ve.length<2)return;let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-tool-group-${Je}-${He[0].id}`,Lt.setAttribute("data-wrapper-id",`tool-group-${Je}-${He[0].id}`);let at=document.createElement("div");at.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",at.setAttribute("data-persona-tool-group","true");let Yt=document.createElement("div");Yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${He.length} tools`,Wt=(et=(pn=r.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:et.call(pn,{messages:He,toolCalls:He.map(ct=>ct.toolCall).filter(ct=>!!ct),defaultSummary:dn,config:r});O(Yt,Wt)||(Yt.textContent=dn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",at.append(Yt,An),Lt.appendChild(at),ve[0].before(Lt),ve.forEach((ct,Sn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Sn<ve.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(ct),An.appendChild(mn)})})}Iu(ur,q);let Te=f.some(M=>M.role==="assistant"&&M.streaming),Oe=f[f.length-1],rt=(Oe==null?void 0:Oe.role)==="assistant"&&!Oe.streaming&&Oe.variant!=="approval";if(Vn&&f.some(M=>M.role==="user")&&!Te&&!rt){let M={config:r,streaming:!0,location:"standalone",defaultRenderer:Oo},Ee=s.find(Je=>Je.renderLoadingIndicator),He=null;if(Ee!=null&&Ee.renderLoadingIndicator&&(He=Ee.renderLoadingIndicator(M)),He===null&&((lt=r.loadingIndicator)!=null&<.render)&&(He=r.loadingIndicator.render(M)),He===null&&(He=Oo()),He){let Je=document.createElement("div"),ve=((Le=r.loadingIndicator)==null?void 0:Le.showBubble)!==!1;Je.className=ve?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Je.setAttribute("data-typing-indicator","true"),Je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Je.appendChild(He);let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id="wrapper-typing-indicator",Lt.setAttribute("data-wrapper-id","typing-indicator"),Lt.appendChild(Je),b.appendChild(Lt)}}if(!Vn&&f.length>0){let M=f[f.length-1],Ee={config:r,lastMessage:M,messageCount:f.length},He=s.find(ve=>ve.renderIdleIndicator),Je=null;if(He!=null&&He.renderIdleIndicator&&(Je=He.renderIdleIndicator(Ee)),Je===null&&((ke=r.loadingIndicator)!=null&&ke.renderIdle)&&(Je=r.loadingIndicator.renderIdle(Ee)),Je){let ve=document.createElement("div"),Lt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;ve.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(" "),ve.setAttribute("data-idle-indicator","true"),ve.appendChild(Je);let at=document.createElement("div");at.className="persona-flex",at.id="wrapper-idle-indicator",at.setAttribute("data-wrapper-id","idle-indicator"),at.appendChild(ve),b.appendChild(at)}}if(si(c,b),ue.length>0)for(let{messageId:M,fingerprint:Ee,bubble:He}of ue){let Je=c.querySelector(`#wrapper-${M}`);Je&&He!==null&&(Je.replaceChildren(He),Je.setAttribute("data-bubble-fp",Ee),Pr.set(M,Ee))}if(Pr.size>0)for(let M of Pr.keys())q.has(M)||Pr.delete(M);if(ee.length>0)for(let{messageId:M,fingerprint:Ee,bubble:He}of ee){let Je=c.querySelector(`#wrapper-${M}`);Je&&He!==null&&(Je.replaceChildren(He),Je.setAttribute("data-bubble-fp",Ee),Cr.set(M,Ee))}if(Cr.size>0)for(let M of Cr.keys())q.has(M)||Cr.delete(M)},Zr=null,Ca=()=>{var y;if(Zr)return;let c=b=>{let k=b.composedPath();k.includes(le)||Ye&&k.includes(Ye)||Ht(!1,"user")};Zr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},Ss=()=>{var f;if(!Zr)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Zr,!0),Zr=null};ft.push(()=>Ss());let eo=null,Aa=()=>{var y;if(eo)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Ht(!1,"user"))};eo=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},Ts=()=>{var f;if(!eo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",eo,!0),eo=null};ft.push(()=>Ts());let to=!1,Es=new Set,Sa=()=>{var f,y,b,k;let c=(b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((k=r.features)==null?void 0:k.streamAnimation)},Hr=()=>{var it,lt,Le,ke;if(!$())return;let c=We.peekBanner,f=We.peekTextNode;if(!c||!f)return;if(D){c.classList.remove("persona-pill-peek--visible");return}let y=(it=T==null?void 0:T.getMessages())!=null?it:[],b;for(let ze=y.length-1;ze>=0;ze--){let M=y[ze];if(M.role==="assistant"&&M.content){b=M;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let k=b.content,N=!!b.streaming,O=Sa(),q=di(O),H=q.type!=="none"?Zs(q.type,O==null?void 0:O.plugins):null,Ae=((lt=H==null?void 0:H.isAnimating)==null?void 0:lt.call(H,b))===!0,ue=H!==null&&(N||Ae);ue&&H&&!Es.has(H.name)&&(al(H,e),Es.add(H.name));let ee=ue&&(H!=null&&H.containerClass)?H.containerClass:null,ye=(Le=f.dataset.personaPeekStreamClass)!=null?Le:null;ye&&ye!==ee&&(f.classList.remove(ye),delete f.dataset.personaPeekStreamClass),ee&&ye!==ee&&(f.classList.add(ee),f.dataset.personaPeekStreamClass=ee),ue?(f.style.setProperty("--persona-stream-step",`${q.speed}ms`),f.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Te=ue?pi(k,q.buffer,H,b,N):k;if(ue&&q.placeholder==="skeleton"&&N&&(!Te||!Te.trim())){let ze=document.createElement("div"),M=ta();M.classList.add("persona-pill-peek__skeleton"),ze.appendChild(M),si(f,ze)}else{let ze=Math.max(0,Te.length-100),M=Te.length>100?Te.slice(-100):Te,Ee=Io(M);if(!ue||!H){let He=Te.length>100?`\u2026${M}`:M;f.textContent!==He&&(f.textContent=He)}else{let He=Ee;(H.wrap==="char"||H.wrap==="word")&&(He=ea(Ee,H.wrap,`peek-${b.id}`,{skipTags:H.skipTags,startIndex:ze}));let Je=document.createElement("div");if(Je.innerHTML=He,H.useCaret&&M.length>0){let ve=ui(),Lt=Je.querySelectorAll(".persona-stream-char, .persona-stream-word"),at=Lt[Lt.length-1];at!=null&&at.parentNode?at.parentNode.insertBefore(ve,at.nextSibling):Je.appendChild(ve)}si(f,Je),(ke=H.onAfterRender)==null||ke.call(H,{container:f,bubble:c,messageId:b.id,message:b,speed:q.speed,duration:q.duration})}}let Xe=Vn||to;c.classList.toggle("persona-pill-peek--visible",Xe)};if($()){let c=We.peekBanner;if(c){let b=k=>{k.preventDefault(),k.stopPropagation(),Ht(!0,"user")};c.addEventListener("pointerdown",b),ft.push(()=>{c.removeEventListener("pointerdown",b)})}let f=()=>{to||(to=!0,Hr())},y=()=>{to&&(to=!1,Hr())};oe.addEventListener("pointerenter",f),oe.addEventListener("pointerleave",y),ft.push(()=>{oe.removeEventListener("pointerenter",f),oe.removeEventListener("pointerleave",y)}),Ye&&(Ye.addEventListener("pointerenter",f),Ye.addEventListener("pointerleave",y),ft.push(()=>{Ye.removeEventListener("pointerenter",f),Ye.removeEventListener("pointerleave",y)}))}let Ta=c=>{var ye,Te,Oe,rt,Xe,it,lt,Le;let f=(Te=(ye=r.launcher)==null?void 0:ye.composerBar)!=null?Te:{},y=(Oe=f.expandedSize)!=null?Oe:"anchored",b=(rt=f.bottomOffset)!=null?rt:"16px",k=f.collapsedMaxWidth,N=(Xe=f.expandedMaxWidth)!=null?Xe:"880px",O=(it=f.expandedTopOffset)!=null?it:"5vh",q=(lt=f.modalMaxWidth)!=null?lt:"880px",H=(Le=f.modalMaxHeight)!=null?Le:"min(90vh, 800px)",Ae="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",ee=le.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Ye){let ke=Ye.style;ke.bottom=b,ke.width=k!=null?k:""}if(c&&y!=="fullscreen"){if(y==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=q,ee.maxWidth=Ae,ee.maxHeight=H,ee.height=H;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${b} + ${ue})`,ee.top=O,ee.width=N,ee.maxWidth=Ae}},no=()=>{var H,Ae,ue,ee,ye,Te,Oe,rt;if(!_())return;if($()){let it=(ue=((Ae=(H=r.launcher)==null?void 0:H.composerBar)!=null?Ae:{}).expandedSize)!=null?ue:"anchored",lt=D?"expanded":"collapsed";le.dataset.state=lt,le.dataset.expandedSize=it,Ye&&(Ye.dataset.state=lt,Ye.dataset.expandedSize=it),le.style.removeProperty("display"),le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ta(D),de.style.display=D?"flex":"none",dr(),D?(Ca(),Aa()):(Ss(),Ts()),Hr();return}let c=rn(r),f=(ee=e.ownerDocument.defaultView)!=null?ee:window,y=(Te=(ye=r.launcher)==null?void 0:ye.mobileBreakpoint)!=null?Te:640,b=(rt=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?rt:!0,k=f.innerWidth<=y,N=b&&k&&E,O=ir(r).reveal;D?(le.style.removeProperty("display"),le.style.display=c?"flex":"",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-95","persona-opacity-0"),oe.classList.add("persona-scale-100","persona-opacity-100"),Me?Me.element.style.display="none":Ge&&(Ge.style.display="none")):(c?c&&(O==="overlay"||O==="push")&&!N?(le.style.removeProperty("display"),le.style.display="flex",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.setProperty("display","none","important"),le.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.display="",le.classList.add("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100"),oe.classList.add("persona-scale-95","persona-opacity-0")),Me?Me.element.style.display=c?"none":"":Ge&&(Ge.style.display=c?"none":""))},Ht=(c,f="user")=>{var N,O;if(!_()||D===c)return;let y=D;D=c,no();let b=(()=>{var Oe,rt,Xe,it,lt,Le,ke,ze,M,Ee;let q=(rt=(Oe=r.launcher)==null?void 0:Oe.sidebarMode)!=null?rt:!1,H=(Xe=e.ownerDocument.defaultView)!=null?Xe:window,Ae=(lt=(it=r.launcher)==null?void 0:it.mobileFullscreen)!=null?lt:!0,ue=(ke=(Le=r.launcher)==null?void 0:Le.mobileBreakpoint)!=null?ke:640,ee=H.innerWidth<=ue,ye=rn(r)&&Ae&&ee,Te=$()&&((Ee=(M=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:M.expandedSize)!=null?Ee:"fullscreen")==="fullscreen";return q||Ae&&ee&&E||ye||Te})();if(D&&b){if(!Gt){let q=e.getRootNode(),H=q instanceof ShadowRoot?q.host:e.closest(".persona-host");H&&(Gt=il(H,(O=(N=r.launcher)==null?void 0:N.zIndex)!=null?O:hn))}Xt||(Xt=ll(e.ownerDocument))}else D||(Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null);D&&(It(),Yr(!0));let k={open:D,source:f,timestamp:Date.now()};D&&!y?o.emit("widget:opened",k):!D&&y&&o.emit("widget:closed",k),o.emit("widget:state",{open:D,launcherEnabled:E,voiceActive:gt.active,streaming:T.isStreaming()})},Ko=c=>{Ut(c?"stop":"send"),z&&(z.disabled=c),pr.buttons.forEach(f=>{f.disabled=c}),je.dataset.personaComposerStreaming=c?"true":"false",je.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Jo=()=>{gt.active||pe&&pe.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Jo(),200)});let Ms=()=>{var y,b,k,N,O,q,H,Ae,ue,ee,ye;Bn.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",Yn.textContent=(N=(k=r.copy)==null?void 0:k.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",pe.placeholder=(q=(O=r.copy)==null?void 0:O.inputPlaceholder)!=null?q:"How can I help...";let c=X.querySelector("[data-persona-intro-card]");if(c){let Te=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;c.style.display=Te?"":"none",Te?(X.classList.remove("persona-gap-3"),X.classList.add("persona-gap-6")):(X.classList.remove("persona-gap-6"),X.classList.add("persona-gap-3"))}!((ue=(Ae=r.sendButton)==null?void 0:Ae.useIcon)!=null&&ue)&&!(T!=null&&T.isStreaming())&&(ie.textContent=(ye=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?ye:"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{u(f=>({...f,sessionId:c}))}});let Ar=null,Ea=()=>{Ar==null&&(Ar=setInterval(()=>{let c=_e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ar),Ar=null;return}let f=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=Oa(f-b))})},100))};if(T=new os(r,{onMessagesChanged(c){vo(_e,c,Re),Ea(),T&&(c.some(k=>k.role==="user")?pr.render([],T,pe,c):pr.render(r.suggestionChips,T,pe,c,r.suggestionChipsConfig)),Yr(!Vn),wa(c);let f=[...c].reverse().find(b=>b.role==="user"),y=gt.lastUserMessageId;f&&f.id!==y&&(gt.lastUserMessageId=f.id,o.emit("user:message",f)),gt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Vo(c),Hr()},onStatusChanged(c){var b;let f=(b=r.statusIndicator)!=null?b:{};me(cn,(k=>{var N,O,q,H;return k==="idle"?(N=f.idleText)!=null?N:fn.idle:k==="connecting"?(O=f.connectingText)!=null?O:fn.connecting:k==="connected"?(q=f.connectedText)!=null?q:fn.connected:k==="error"?(H=f.errorText)!=null?H:fn.error:fn[k]})(c),f,c)},onStreamingChanged(c){Vn=c,Ko(c),T&&vo(_e,T.getMessages(),Re),c||Yr(!0),Hr()},onVoiceStatusChanged(c){var f,y;if(((y=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":J(),L();break;case"speaking":J(),Z();break;default:c==="idle"&&T.isBargeInActive()?(J(),j(),z==null||z.setAttribute("aria-label","End voice session")):(gt.active=!1,J(),or("system"),Pn());break}},onArtifactsState(c){$n=c,Un(),Vo()}}),Pt.current=T,((_c=($c=r.voiceRecognition)==null?void 0:$c.provider)==null?void 0:_c.type)==="runtype")try{T.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&T.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||r.onSSEEvent)&&T.setSSEEventCallback((c,f)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,f),ce==null||ce.processEvent(c,f),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(f)})}),l&&l.then(c=>{var f,y,b;c&&(c.metadata&&(d=Wl(c.metadata),A.syncFromMetadata()),(f=c.messages)!=null&&f.length&&T.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&T.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ks=()=>{var f,y,b;!$()||D||!((b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Ht(!0,"auto")},Ls=c=>{var k;if(c.preventDefault(),T.isStreaming()){T.cancel(),ce==null||ce.reset(),we==null||we.update();return}let f=pe.value.trim(),y=(k=nt==null?void 0:nt.hasAttachments())!=null?k:!1;if(!f&&!y)return;ks();let b;y&&(b=[],b.push(...nt.getContentParts()),f&&b.push(qs(f))),pe.value="",pe.style.height="auto",wo(),T.sendMessage(f,{contentParts:b}),y&&nt.clearAttachments()},Ma=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Go={...ai},Xo=!1,wo=()=>{Go={...ai}},ka=()=>T.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),La=c=>{if(!pe)return;Xo=!0,pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),Xo=!1;let f=pe.value.length;pe.setSelectionRange(f,f)},Ps=()=>{Xo||wo()},Is=c=>{if(pe){if(Ma()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=pe.selectionStart===0&&pe.selectionEnd===0,y=Eu({direction:c.key==="ArrowUp"?"up":"down",history:ka(),currentValue:pe.value,atStart:f,state:Go});if(Go=y.state,y.handled){c.preventDefault(),y.value!==void 0&&La(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(T.isStreaming()){c.preventDefault();return}wo(),c.preventDefault(),ie.click()}}},Ws=c=>{c.key!=="Escape"||c.isComposing||T.isStreaming()&&c.composedPath().includes(de)&&(T.cancel(),ce==null||ce.reset(),we==null||we.update(),wo(),c.preventDefault(),c.stopImmediatePropagation())},Rs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!nt)return;let f=Nh(c.clipboardData);f.length!==0&&(c.preventDefault(),await nt.handleFiles(f))},wn=null,Kn=!1,Br=null,st=null,Hs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Co=(c="user")=>{var N,O,q,H,Ae,ue,ee;if(Kn||T.isStreaming())return;let f=Hs();if(!f)return;wn=new f;let b=(O=((N=r.voiceRecognition)!=null?N:{}).pauseDuration)!=null?O:2e3;wn.continuous=!0,wn.interimResults=!0,wn.lang="en-US";let k=pe.value;wn.onresult=ye=>{let Te="",Oe="";for(let Xe=0;Xe<ye.results.length;Xe++){let it=ye.results[Xe],lt=it[0].transcript;it.isFinal?Te+=lt+" ":Oe=lt}let rt=k+Te+Oe;pe.value=rt,Br&&clearTimeout(Br),(Te||Oe)&&(Br=window.setTimeout(()=>{let Xe=pe.value.trim();Xe&&wn&&Kn&&(hr(),pe.value="",pe.style.height="auto",T.sendMessage(Xe,{viaVoice:!0}))},b))},wn.onerror=ye=>{ye.error!=="no-speech"&&hr()},wn.onend=()=>{if(Kn){let ye=pe.value.trim();ye&&ye!==k.trim()&&(pe.value="",pe.style.height="auto",T.sendMessage(ye,{viaVoice:!0})),hr()}};try{if(wn.start(),Kn=!0,gt.active=!0,c!=="system"&&(gt.manuallyDeactivated=!1),or(c),Pn(),z){let ye=(q=r.voiceRecognition)!=null?q:{};st={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(H=ye.iconName)!=null?H:"mic",iconSize:parseFloat((ee=(ue=ye.iconSize)!=null?ue:(Ae=r.sendButton)==null?void 0:Ae.size)!=null?ee:"40")||24};let Te=ye.recordingBackgroundColor,Oe=ye.recordingIconColor,rt=ye.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=Te!=null?Te:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=Oe!=null?Oe:"var(--persona-voice-recording-indicator, #ffffff)",Oe){let Xe=z.querySelector("svg");Xe&&Xe.setAttribute("stroke",Oe)}rt&&(z.style.borderColor=rt),z.setAttribute("aria-label","Stop voice recognition")}}catch{hr("system")}},hr=(c="user")=>{if(Kn){if(Kn=!1,Br&&(clearTimeout(Br),Br=null),wn){try{wn.stop()}catch{}wn=null}if(gt.active=!1,or(c),Pn(),z){if(z.classList.remove("persona-voice-recording"),st){z.style.backgroundColor=st.backgroundColor,z.style.color=st.color,z.style.borderColor=st.borderColor;let f=z.querySelector("svg");f&&f.setAttribute("stroke",st.color||"currentColor"),st=null}z.setAttribute("aria-label","Start voice recognition")}}},Pa=(c,f)=>{var it,lt,Le,ke,ze,M,Ee,He;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((it=c==null?void 0:c.provider)==null?void 0:it.type)==="runtype";if(!(y||b))return null;let N=h("div","persona-send-button-wrapper"),O=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let q=(lt=c==null?void 0:c.iconName)!=null?lt:"mic",H=(Le=f==null?void 0:f.size)!=null?Le:"40px",Ae=(ke=c==null?void 0:c.iconSize)!=null?ke:H,ue=parseFloat(Ae)||24,ee=(ze=c==null?void 0:c.backgroundColor)!=null?ze:f==null?void 0:f.backgroundColor,ye=(M=c==null?void 0:c.iconColor)!=null?M:f==null?void 0:f.textColor;O.style.width=Ae,O.style.height=Ae,O.style.minWidth=Ae,O.style.minHeight=Ae,O.style.fontSize="18px",O.style.lineHeight="1",ye?O.style.color=ye:O.style.color="var(--persona-text, #111827)";let Oe=be(q,ue,ye||"currentColor",1.5);Oe?O.appendChild(Oe):O.textContent="\u{1F3A4}",ee?O.style.backgroundColor=ee:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),N.appendChild(O);let rt=(Ee=c==null?void 0:c.tooltipText)!=null?Ee:"Start voice recognition";if(((He=c==null?void 0:c.showTooltip)!=null?He:!1)&&rt){let Je=h("div","persona-send-button-tooltip");Je.textContent=rt,N.appendChild(Je)}return{micButton:O,micButtonWrapper:N}},ro=()=>{var f,y,b,k,N;if(!z||st)return;let c=(f=r.voiceRecognition)!=null?f:{};st={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((N=(k=c.iconSize)!=null?k:(b=r.sendButton)==null?void 0:b.size)!=null?N:"40")||24}},Ke=(c,f)=>{var N,O,q,H,Ae;if(!z)return;let y=z.querySelector("svg");y&&y.remove();let b=(Ae=st==null?void 0:st.iconSize)!=null?Ae:parseFloat((H=(q=(N=r.voiceRecognition)==null?void 0:N.iconSize)!=null?q:(O=r.sendButton)==null?void 0:O.size)!=null?H:"40")||24,k=be(c,b,f,1.5);k&&z.appendChild(k)},S=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},j=()=>{var k;if(!z)return;ro();let c=(k=r.voiceRecognition)!=null?k:{},f=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(S(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let N=z.querySelector("svg");N&&N.setAttribute("stroke",y)}b&&(z.style.borderColor=b),z.setAttribute("aria-label","Stop voice recognition")},L=()=>{var q,H,Ae,ue,ee,ye,Te,Oe;if(!z)return;ro();let c=(q=r.voiceRecognition)!=null?q:{},f=T.getVoiceInterruptionMode(),y=(H=c.processingIconName)!=null?H:"loader",b=(ue=(Ae=c.processingIconColor)!=null?Ae:st==null?void 0:st.color)!=null?ue:"",k=(ye=(ee=c.processingBackgroundColor)!=null?ee:st==null?void 0:st.backgroundColor)!=null?ye:"",N=(Oe=(Te=c.processingBorderColor)!=null?Te:st==null?void 0:st.borderColor)!=null?Oe:"";S(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=k,z.style.borderColor=N;let O=b||"currentColor";z.style.color=O,Ke(y,O),z.setAttribute("aria-label","Processing voice input"),f==="none"&&(z.style.cursor="default")},Z=()=>{var Ae,ue,ee,ye,Te,Oe,rt,Xe,it,lt,Le,ke;if(!z)return;ro();let c=(Ae=r.voiceRecognition)!=null?Ae:{},f=T.getVoiceInterruptionMode(),y=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",b=(ue=c.speakingIconName)!=null?ue:y,k=(Oe=c.speakingIconColor)!=null?Oe:f==="barge-in"?(ye=(ee=c.recordingIconColor)!=null?ee:st==null?void 0:st.color)!=null?ye:"":(Te=st==null?void 0:st.color)!=null?Te:"",N=(it=c.speakingBackgroundColor)!=null?it:f==="barge-in"?(rt=c.recordingBackgroundColor)!=null?rt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=st==null?void 0:st.backgroundColor)!=null?Xe:"",O=(ke=c.speakingBorderColor)!=null?ke:f==="barge-in"?(lt=c.recordingBorderColor)!=null?lt:"":(Le=st==null?void 0:st.borderColor)!=null?Le:"";S(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=N,z.style.borderColor=O;let q=k||"currentColor";z.style.color=q,Ke(b,q);let H=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",H),f==="none"&&(z.style.cursor="default"),f==="barge-in"&&z.classList.add("persona-voice-recording")},J=()=>{var c,f,y;z&&(S(),st&&(z.style.backgroundColor=(c=st.backgroundColor)!=null?c:"",z.style.color=(f=st.color)!=null?f:"",z.style.borderColor=(y=st.borderColor)!=null?y:"",Ke(st.iconName,st.color||"currentColor"),st=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},G=()=>{var c,f;if(((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let y=T.getVoiceStatus(),b=T.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),or("user"),J()});return}T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),gt.manuallyDeactivated=!T.isVoiceActive(),Pn(),or("user"),T.isVoiceActive()?j():J()});return}if(Kn){let y=pe.value.trim();gt.manuallyDeactivated=!0,Pn(),hr("user"),y&&(pe.value="",pe.style.height="auto",T.sendMessage(y))}else gt.manuallyDeactivated=!1,Pn(),Co("user")};Dn=G,z&&(z.addEventListener("click",G),ft.push(()=>{var c,f;((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),J()):hr("system"),z&&z.removeEventListener("click",G)}));let Qe=o.on("assistant:complete",()=>{ws&&(gt.active||gt.manuallyDeactivated||ws==="assistant"&&!gt.lastUserMessageWasVoice||setTimeout(()=>{var c,f;!gt.active&&!gt.manuallyDeactivated&&(((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("auto"),T.isVoiceActive()&&j()}):Co("auto"))},600))});ft.push(Qe);let $e=o.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});ft.push($e);let tt=()=>{Ht(!D,"user")},Me=null,Ge=null;if(E&&!$()){let c=s.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:r,defaultRenderer:()=>ra(r,tt).element,onToggle:tt});f&&(Ge=f)}Ge||(Me=ra(r,tt))}Me?e.appendChild(Me.element):Ge&&e.appendChild(Ge),no(),pr.render(r.suggestionChips,T,pe,void 0,r.suggestionChipsConfig),Ms(),Ko(T.isStreaming()),Yr(!0),ya(),P&&(!E||$()?setTimeout(()=>Jo(),0):D&&setTimeout(()=>Jo(),200));let It=()=>{var H,Ae,ue,ee,ye,Te,Oe,rt,Xe,it,lt,Le,ke,ze,M,Ee,He,Je,ve,Lt,at,Yt;if($()){bt(),no();return}let c=rn(r),f=(Ae=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?Ae:!1,y=c||f||((ee=(ue=r.launcher)==null?void 0:ue.fullHeight)!=null?ee:!1),b=(ye=e.ownerDocument.defaultView)!=null?ye:window,k=(Oe=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?Oe:!0,N=(Xe=(rt=r.launcher)==null?void 0:rt.mobileBreakpoint)!=null?Xe:640,O=b.innerWidth<=N,q=k&&O&&E;try{if(q){dr(),ao(e,r);return}if(W&&(W=!1,dr(),ao(e,r)),!E&&!c){oe.style.height="",oe.style.width="";return}if(!f&&!c){let dn=(lt=(it=r==null?void 0:r.launcher)==null?void 0:it.width)!=null?lt:r==null?void 0:r.launcherWidth,Wt=dn!=null?dn:Xn;oe.style.width=Wt,oe.style.maxWidth=Wt}if(wr(),!y){let dn=b.innerHeight,Wt=64,An=(ke=(Le=r.launcher)==null?void 0:Le.heightOffset)!=null?ke:0,pn=Math.max(200,dn-Wt),et=Math.min(640,pn),ct=Math.max(200,et-An);oe.style.height=`${ct}px`}}finally{if(bt(),no(),D&&E){let Wt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((Ee=(M=r.launcher)==null?void 0:M.mobileBreakpoint)!=null?Ee:640),An=(Je=(He=r.launcher)==null?void 0:He.sidebarMode)!=null?Je:!1,pn=(Lt=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Lt:!0,et=rn(r)&&pn&&Wt,ct=An||pn&&Wt&&E||et;if(ct&&!Xt){let Sn=e.getRootNode(),mn=Sn instanceof ShadowRoot?Sn.host:e.closest(".persona-host");mn&&!Gt&&(Gt=il(mn,(Yt=(at=r.launcher)==null?void 0:at.zIndex)!=null?Yt:hn)),Xt=ll(e.ownerDocument)}else ct||(Gt==null||Gt(),Gt=null,Xt==null||Xt(),Xt=null)}}};It();let on=(jc=e.ownerDocument.defaultView)!=null?jc:window;if(on.addEventListener("resize",It),ft.push(()=>on.removeEventListener("resize",It)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe(je),ft.push(()=>c.disconnect())}gr=X.scrollTop;let At=X.scrollHeight,kt=()=>{let c=X.scrollTop,f=X.scrollHeight,y=f<At;At=f;let{action:b,nextLastScrollTop:k}=li({following:mr.isFollowing(),currentScrollTop:c,lastScrollTop:gr,nearBottom:Xs(X,vs),userScrollThreshold:fa,isAutoScrolling:Ir||bo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(gr=k,b==="resume"){Qr();return}b==="pause"&&As()};X.addEventListener("scroll",kt,{passive:!0}),ft.push(()=>X.removeEventListener("scroll",kt));let sn=c=>{let f=ci({following:mr.isFollowing(),deltaY:c.deltaY,nearBottom:Xs(X,vs),resumeWhenNearBottom:!0});f==="pause"?As():f==="resume"&&Qr()};X.addEventListener("wheel",sn,{passive:!0}),ft.push(()=>X.removeEventListener("wheel",sn)),Tt.addEventListener("click",()=>{X.scrollTop=X.scrollHeight,gr=X.scrollTop,Qr(),Yr(!0)}),ft.push(()=>Tt.remove()),ft.push(()=>{Cs()});let un=()=>{qe&&(zn&&(qe.removeEventListener("click",zn),zn=null),_()?(qe.style.display="",zn=()=>{Ht(!1,"user")},qe.addEventListener("click",zn)):qe.style.display="none")};un(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{T.clearMessages(),ur.clear(),Qr(),go(We.composerOverlay);try{localStorage.removeItem(bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},A.syncFromMetadata(),K==null||K.clear(),ce==null||ce.reset(),we==null||we.update()})})(),$t&&$t.addEventListener("submit",Ls),pe==null||pe.addEventListener("keydown",Is),pe==null||pe.addEventListener("input",Ps),pe==null||pe.addEventListener("paste",Rs);let Qt=(Uc=e.ownerDocument)!=null?Uc:document;Qt.addEventListener("keydown",Ws,!0);let sr="persona-attachment-drop-active",Bs=0,Ki=()=>{Bs=0,de.classList.remove(sr)},Qo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&nt!==null},Xl=c=>{!Ni(c.dataTransfer)||!Qo()||(Bs++,Bs===1&&de.classList.add(sr))},Ql=c=>{!Ni(c.dataTransfer)||!Qo()||(Bs--,Bs<=0&&Ki())},Yl=c=>{!Ni(c.dataTransfer)||!Qo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Zl=c=>{var y;if(!Ni(c.dataTransfer)||!Qo())return;c.preventDefault(),c.stopPropagation(),Ki();let f=Array.from((y=c.dataTransfer.files)!=null?y:[]);f.length!==0&&nt.handleFiles(f)},oo=!0;de.addEventListener("dragenter",Xl,oo),de.addEventListener("dragleave",Ql,oo),e.addEventListener("dragover",Yl,oo),e.addEventListener("drop",Zl,oo);let Ia=e.ownerDocument,ec=c=>{Qo()&&c.preventDefault()},tc=c=>{Qo()&&c.preventDefault()};Ia.addEventListener("dragover",ec),Ia.addEventListener("drop",tc),ft.push(()=>{$t&&$t.removeEventListener("submit",Ls),pe==null||pe.removeEventListener("keydown",Is),pe==null||pe.removeEventListener("input",Ps),pe==null||pe.removeEventListener("paste",Rs),Qt.removeEventListener("keydown",Ws,!0)}),ft.push(()=>{de.removeEventListener("dragenter",Xl,oo),de.removeEventListener("dragleave",Ql,oo),e.removeEventListener("dragover",Yl,oo),e.removeEventListener("drop",Zl,oo),Ia.removeEventListener("dragover",ec),Ia.removeEventListener("drop",tc),Ki()}),ft.push(()=>{T.cancel()}),Me?ft.push(()=>{Me==null||Me.destroy()}):Ge&&ft.push(()=>{Ge==null||Ge.remove()});let tn={update(c){var nn,Sr,Nr,Wa,Ra,Ha,Mo,Ba,Ds,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,$d,_d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Fp,Op,$p,_p,jp,Up,qp,zp;let f=r.toolCall,y=r.messageActions,b=(nn=r.layout)==null?void 0:nn.messages,k=r.colorScheme,N=r.loadingIndicator,O=r.iterationDisplay,q=(Sr=r.features)==null?void 0:Sr.showReasoning,H=(Nr=r.features)==null?void 0:Nr.showToolCalls,Ae=(Wa=r.features)==null?void 0:Wa.toolCallDisplay,ue=(Ra=r.features)==null?void 0:Ra.reasoningDisplay;r={...r,...c},dr(),ao(e,r),ki(e,r),Li(e,r),Un(),r.colorScheme!==k&&Xr();let ee=da.getForInstance(r.plugins);s.length=0,s.push(...ee),E=(Mo=(Ha=r.launcher)==null?void 0:Ha.enabled)!=null?Mo:!0,B=(Ds=(Ba=r.launcher)==null?void 0:Ba.autoExpand)!=null?Ds:!1,Ue=(Qc=(Xc=r.features)==null?void 0:Xc.showReasoning)!=null?Qc:!0,Fe=(Zc=(Yc=r.features)==null?void 0:Yc.showToolCalls)!=null?Zc:!0,xe=(td=(ed=r.features)==null?void 0:ed.scrollToBottom)!=null?td:{},Vt(),Rr();let ye=fe;if(fe=(rd=(nd=r.features)==null?void 0:nd.showEventStreamToggle)!=null?rd:!1,fe&&!ye){if(K||(te=new la(Be),K=new ia(Ie,te),ce=ce!=null?ce:new ca,te.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),T.setSSEEventCallback((Q,vt)=>{var Ot;(Ot=r.onSSEEvent)==null||Ot.call(r,Q,vt),ce==null||ce.processEvent(Q,vt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!mt&&Ne){let Q=(sd=(od=r.features)==null?void 0:od.eventStream)==null?void 0:sd.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");mt=h("button",vt),mt.style.width="28px",mt.style.height="28px",mt.style.color=Mn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let Ot=be("activity","18px","currentColor",1.5);Ot&&mt.appendChild(Ot);let dt=We.clearChatButtonWrapper,Et=We.closeButtonWrapper,an=dt||Et;an&&an.parentNode===Ne?Ne.insertBefore(mt,an):Ne.appendChild(mt),mt.addEventListener("click",()=>{he?Nn():bn()})}}else!fe&&ye&&(Nn(),mt&&(mt.remove(),mt=null),K==null||K.clear(),te==null||te.destroy(),K=null,te=null,ce==null||ce.reset(),ce=null);if(((ad=r.launcher)==null?void 0:ad.enabled)===!1&&Me&&(Me.destroy(),Me=null),((id=r.launcher)==null?void 0:id.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((ld=r.launcher)==null?void 0:ld.enabled)!==!1&&!Me&&!Ge){let Q=s.find(vt=>vt.renderLauncher);if(Q!=null&&Q.renderLauncher){let vt=Q.renderLauncher({config:r,defaultRenderer:()=>ra(r,tt).element,onToggle:tt});vt&&(Ge=vt,e.appendChild(Ge))}Ge||(Me=ra(r,tt),e.appendChild(Me.element))}Me&&Me.update(r),Se&&((cd=r.launcher)==null?void 0:cd.title)!==void 0&&(Se.textContent=r.launcher.title),De&&((dd=r.launcher)==null?void 0:dd.subtitle)!==void 0&&(De.textContent=r.launcher.subtitle);let Te=(pd=r.layout)==null?void 0:pd.header;if((Te==null?void 0:Te.layout)!==w&&Ne){let Q=Te?ls(r,Te,{showClose:_(),onClose:()=>Ht(!1,"user")}):$r({config:r,showClose:_(),onClose:()=>Ht(!1,"user")});Ne.replaceWith(Q.header),Ne=Q.header,F=Q.iconHolder,Se=Q.headerTitle,De=Q.headerSubtitle,qe=Q.closeButton,w=Te==null?void 0:Te.layout}else if(Te&&(F&&(F.style.display=Te.showIcon===!1?"none":""),Se&&(Se.style.display=Te.showTitle===!1?"none":""),De&&(De.style.display=Te.showSubtitle===!1?"none":""),qe&&(qe.style.display=Te.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let Q=Te.showClearChat;if(Q!==void 0){We.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:vt}=We;vt&&!vt.classList.contains("persona-absolute")&&(Q?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let rt=((ud=r.layout)==null?void 0:ud.showHeader)!==!1;Ne&&(Ne.style.display=rt?"":"none");let Xe=((md=r.layout)==null?void 0:md.showFooter)!==!1;je&&(je.style.display=Xe?"":"none"),bt(),Rr(),E!==R?E?Ht(B,"auto"):(D=!0,no()):B!==I&&Ht(B,"auto"),I=B,R=E,It(),un();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(f),ke=JSON.stringify(r.messageActions)!==JSON.stringify(y),ze=JSON.stringify((gd=r.layout)==null?void 0:gd.messages)!==JSON.stringify(b),M=((fd=r.loadingIndicator)==null?void 0:fd.render)!==(N==null?void 0:N.render)||((hd=r.loadingIndicator)==null?void 0:hd.renderIdle)!==(N==null?void 0:N.renderIdle)||((yd=r.loadingIndicator)==null?void 0:yd.showBubble)!==(N==null?void 0:N.showBubble),Ee=r.iterationDisplay!==O,He=((xd=(bd=r.features)==null?void 0:bd.showReasoning)!=null?xd:!0)!==(q!=null?q:!0)||((wd=(vd=r.features)==null?void 0:vd.showToolCalls)!=null?wd:!0)!==(H!=null?H:!0)||JSON.stringify((Cd=r.features)==null?void 0:Cd.toolCallDisplay)!==JSON.stringify(Ae)||JSON.stringify((Ad=r.features)==null?void 0:Ad.reasoningDisplay)!==JSON.stringify(ue);(Le||ke||ze||M||Ee||He)&&T&&(xs++,vo(_e,T.getMessages(),Re));let ve=(Sd=r.launcher)!=null?Sd:{},Lt=(Td=ve.headerIconHidden)!=null?Td:!1,at=(Md=(Ed=r.layout)==null?void 0:Ed.header)==null?void 0:Md.showIcon,Yt=Lt||at===!1,dn=ve.headerIconName,Wt=(kd=ve.headerIconSize)!=null?kd:"48px";if(F){let Q=de.querySelector(".persona-border-b-persona-divider"),vt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Yt)F.style.display="none",Q&&vt&&!Q.contains(vt)&&Q.insertBefore(vt,Q.firstChild);else{if(F.style.display="",F.style.height=Wt,F.style.width=Wt,Q&&vt&&(Q.contains(F)?F.nextSibling!==vt&&(F.remove(),Q.insertBefore(F,vt)):Q.insertBefore(F,vt)),dn){let dt=parseFloat(Wt)||24,Et=be(dn,dt*.6,"#ffffff",2);Et?F.replaceChildren(Et):F.textContent=(Ld=ve.agentIconText)!=null?Ld:"\u{1F4AC}"}else if(ve.iconUrl){let dt=F.querySelector("img");if(dt)dt.src=ve.iconUrl,dt.style.height=Wt,dt.style.width=Wt;else{let Et=document.createElement("img");Et.src=ve.iconUrl,Et.alt="",Et.className="persona-rounded-xl persona-object-cover",Et.style.height=Wt,Et.style.width=Wt,F.replaceChildren(Et)}}else{let dt=F.querySelector("svg"),Et=F.querySelector("img");(dt||Et)&&F.replaceChildren(),F.textContent=(Pd=ve.agentIconText)!=null?Pd:"\u{1F4AC}"}let Ot=F.querySelector("img");Ot&&(Ot.style.height=Wt,Ot.style.width=Wt)}}let An=(Wd=(Id=r.layout)==null?void 0:Id.header)==null?void 0:Wd.showTitle,pn=(Hd=(Rd=r.layout)==null?void 0:Rd.header)==null?void 0:Hd.showSubtitle;if(Se&&(Se.style.display=An===!1?"none":""),De&&(De.style.display=pn===!1?"none":""),qe){((Dd=(Bd=r.layout)==null?void 0:Bd.header)==null?void 0:Dd.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let vt=(Nd=ve.closeButtonSize)!=null?Nd:"32px",Ot=(Fd=ve.closeButtonPlacement)!=null?Fd:"inline";qe.style.height=vt,qe.style.width=vt;let{closeButtonWrapper:dt}=We,Et=Ot==="top-right",an=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Et!==an)if(dt.remove(),Et)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",de.style.position="relative",de.appendChild(dt);else{let ut=($d=(Od=ve.clearChat)==null?void 0:Od.placement)!=null?$d:"inline",ln=(jd=(_d=ve.clearChat)==null?void 0:_d.enabled)!=null?jd:!0;dt.className=ln&&ut==="inline"?"":"persona-ml-auto";let Hn=de.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(dt)}if(qe.style.color=ve.closeButtonColor||Mn.actionIconColor,ve.closeButtonBackgroundColor?(qe.style.backgroundColor=ve.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),ve.closeButtonBorderWidth||ve.closeButtonBorderColor){let ut=ve.closeButtonBorderWidth||"0px",ln=ve.closeButtonBorderColor||"transparent";qe.style.border=`${ut} solid ${ln}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");ve.closeButtonBorderRadius?(qe.style.borderRadius=ve.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),ve.closeButtonPaddingX?(qe.style.paddingLeft=ve.closeButtonPaddingX,qe.style.paddingRight=ve.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),ve.closeButtonPaddingY?(qe.style.paddingTop=ve.closeButtonPaddingY,qe.style.paddingBottom=ve.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let gn=(Ud=ve.closeButtonIconName)!=null?Ud:"x",yr=(qd=ve.closeButtonIconText)!=null?qd:"\xD7";qe.innerHTML="";let En=be(gn,"28px","currentColor",1);En?qe.appendChild(En):qe.textContent=yr;let Zt=(zd=ve.closeButtonTooltipText)!=null?zd:"Close chat",Gn=(Vd=ve.closeButtonShowTooltip)!=null?Vd:!0;if(qe.setAttribute("aria-label",Zt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Gn&&Zt)){let ut=null,ln=()=>{if(ut||!qe)return;let ko=qe.ownerDocument,Ns=ko.body;if(!Ns)return;ut=Tr(ko,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let Fs=Tr(ko,"div");Fs.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Fs);let Lo=qe.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(io),ut.style.left=`${Lo.left+Lo.width/2}px`,ut.style.top=`${Lo.top-8}px`,ut.style.transform="translate(-50%, -100%)",Ns.appendChild(ut)},Hn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};dt.addEventListener("mouseenter",ln),dt.addEventListener("mouseleave",Hn),qe.addEventListener("focus",ln),qe.addEventListener("blur",Hn),dt._cleanupTooltip=()=>{Hn(),dt&&(dt.removeEventListener("mouseenter",ln),dt.removeEventListener("mouseleave",Hn)),qe&&(qe.removeEventListener("focus",ln),qe.removeEventListener("blur",Hn))}}}let{clearChatButton:et,clearChatButtonWrapper:ct}=We;if(et){let Q=(Kd=ve.clearChat)!=null?Kd:{},vt=(Jd=Q.enabled)!=null?Jd:!0,Ot=(Xd=(Gd=r.layout)==null?void 0:Gd.header)==null?void 0:Xd.showClearChat,dt=Ot!==void 0?Ot:vt,Et=(Qd=Q.placement)!=null?Qd:"inline";if(ct){ct.style.display=dt?"":"none";let{closeButtonWrapper:an}=We;!$()&&an&&!an.classList.contains("persona-absolute")&&(dt?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let gn=Et==="top-right",yr=ct.classList.contains("persona-absolute");if(!$()&&gn!==yr&&dt){if(ct.remove(),gn)ct.className="persona-absolute persona-top-4 persona-z-50",ct.style.right="48px",de.style.position="relative",de.appendChild(ct);else{ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ct.style.right="";let Zt=de.querySelector(".persona-border-b-persona-divider"),Gn=We.closeButtonWrapper;Zt&&Gn&&Gn.parentElement===Zt?Zt.insertBefore(ct,Gn):Zt&&Zt.appendChild(ct)}let En=We.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(gn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(dt){if(!$()){let ut=(Yd=Q.size)!=null?Yd:"32px";et.style.height=ut,et.style.width=ut}let an=(Zd=Q.iconName)!=null?Zd:"refresh-cw",gn=(ep=Q.iconColor)!=null?ep:"";et.style.color=gn||Mn.actionIconColor,et.innerHTML="";let yr=$()?"14px":"20px",En=be(an,yr,"currentColor",2);if(En&&et.appendChild(En),Q.backgroundColor?(et.style.backgroundColor=Q.backgroundColor,et.classList.remove("hover:persona-bg-gray-100")):(et.style.backgroundColor="",et.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let ut=Q.borderWidth||"0px",ln=Q.borderColor||"transparent";et.style.border=`${ut} solid ${ln}`,et.classList.remove("persona-border-none")}else et.style.border="",et.classList.add("persona-border-none");Q.borderRadius?(et.style.borderRadius=Q.borderRadius,et.classList.remove("persona-rounded-full")):(et.style.borderRadius="",et.classList.add("persona-rounded-full")),Q.paddingX?(et.style.paddingLeft=Q.paddingX,et.style.paddingRight=Q.paddingX):(et.style.paddingLeft="",et.style.paddingRight=""),Q.paddingY?(et.style.paddingTop=Q.paddingY,et.style.paddingBottom=Q.paddingY):(et.style.paddingTop="",et.style.paddingBottom="");let Zt=(tp=Q.tooltipText)!=null?tp:"Clear chat",Gn=(np=Q.showTooltip)!=null?np:!0;if(et.setAttribute("aria-label",Zt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Gn&&Zt)){let ut=null,ln=()=>{if(ut||!et)return;let ko=et.ownerDocument,Ns=ko.body;if(!Ns)return;ut=Tr(ko,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let Fs=Tr(ko,"div");Fs.className="persona-clear-chat-tooltip-arrow",ut.appendChild(Fs);let Lo=et.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(io),ut.style.left=`${Lo.left+Lo.width/2}px`,ut.style.top=`${Lo.top-8}px`,ut.style.transform="translate(-50%, -100%)",Ns.appendChild(ut)},Hn=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};ct.addEventListener("mouseenter",ln),ct.addEventListener("mouseleave",Hn),et.addEventListener("focus",ln),et.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",ln),ct.removeEventListener("mouseleave",Hn)),et&&(et.removeEventListener("focus",ln),et.removeEventListener("blur",Hn))}}}}let Sn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[pa],mn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[jo.message,jo.messageAndClick];A=ua({parsers:Sn,handlers:mn,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Re=Em(r,A,se),T.updateConfig(r),vo(_e,T.getMessages(),Re),pr.render(r.suggestionChips,T,pe,void 0,r.suggestionChipsConfig),Ms(),Ko(T.isStreaming());let Ao=((rp=r.voiceRecognition)==null?void 0:rp.enabled)===!0,So=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),To=((sp=(op=r.voiceRecognition)==null?void 0:op.provider)==null?void 0:sp.type)==="runtype";if(Ao&&(So||To))if(!z||!_t){let Q=Pa(r.voiceRecognition,r.sendButton);Q&&(z=Q.micButton,_t=Q.micButtonWrapper,St.insertBefore(_t,kn),z.addEventListener("click",G),z.disabled=T.isStreaming())}else{let Q=(ap=r.voiceRecognition)!=null?ap:{},vt=(ip=r.sendButton)!=null?ip:{},Ot=(lp=Q.iconName)!=null?lp:"mic",dt=(cp=vt.size)!=null?cp:"40px",Et=(dp=Q.iconSize)!=null?dp:dt,an=parseFloat(Et)||24;z.style.width=Et,z.style.height=Et,z.style.minWidth=Et,z.style.minHeight=Et;let gn=(up=(pp=Q.iconColor)!=null?pp:vt.textColor)!=null?up:"currentColor";z.innerHTML="";let yr=be(Ot,an,gn,2);yr?z.appendChild(yr):z.textContent="\u{1F3A4}";let En=(mp=Q.backgroundColor)!=null?mp:vt.backgroundColor;En?z.style.backgroundColor=En:z.style.backgroundColor="",gn?z.style.color=gn:z.style.color="var(--persona-text, #111827)",Q.borderWidth?(z.style.borderWidth=Q.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),Q.borderColor?z.style.borderColor=Q.borderColor:z.style.borderColor="",Q.paddingX?(z.style.paddingLeft=Q.paddingX,z.style.paddingRight=Q.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),Q.paddingY?(z.style.paddingTop=Q.paddingY,z.style.paddingBottom=Q.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let Zt=_t==null?void 0:_t.querySelector(".persona-send-button-tooltip"),Gn=(gp=Q.tooltipText)!=null?gp:"Start voice recognition";if(((fp=Q.showTooltip)!=null?fp:!1)&&Gn)if(Zt)Zt.textContent=Gn,Zt.style.display="";else{let ln=document.createElement("div");ln.className="persona-send-button-tooltip",ln.textContent=Gn,_t==null||_t.insertBefore(ln,z)}else Zt&&(Zt.style.display="none");_t.style.display="",z.disabled=T.isStreaming()}else z&&_t&&(_t.style.display="none",((yp=(hp=r.voiceRecognition)==null?void 0:hp.provider)==null?void 0:yp.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Kn&&hr());if(((bp=r.attachments)==null?void 0:bp.enabled)===!0)if(!Ft||!Ze){let Q=(xp=r.attachments)!=null?xp:{},Ot=(wp=((vp=r.sendButton)!=null?vp:{}).size)!=null?wp:"40px";ge||(ge=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ge.style.display="none",$t.insertBefore(ge,pe)),re||(re=document.createElement("input"),re.type="file",re.accept=((Cp=Q.allowedTypes)!=null?Cp:Or).join(","),re.multiple=((Ap=Q.maxFiles)!=null?Ap:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),$t.insertBefore(re,pe)),Ft=h("div","persona-send-button-wrapper"),Ze=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ze.type="button",Ze.setAttribute("aria-label",(Sp=Q.buttonTooltipText)!=null?Sp:"Attach file");let dt=(Tp=Q.buttonIconName)!=null?Tp:"paperclip",Et=Ot,an=parseFloat(Et)||40,gn=Math.round(an*.6);Ze.style.width=Et,Ze.style.height=Et,Ze.style.minWidth=Et,Ze.style.minHeight=Et,Ze.style.fontSize="18px",Ze.style.lineHeight="1",Ze.style.backgroundColor="transparent",Ze.style.color="var(--persona-primary, #111827)",Ze.style.border="none",Ze.style.borderRadius="6px",Ze.style.transition="background-color 0.15s ease",Ze.addEventListener("mouseenter",()=>{Ze.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ze.addEventListener("mouseleave",()=>{Ze.style.backgroundColor="transparent"});let yr=be(dt,gn,"currentColor",1.5);yr?Ze.appendChild(yr):Ze.textContent="\u{1F4CE}",Ze.addEventListener("click",Gn=>{Gn.preventDefault(),re==null||re.click()}),Ft.appendChild(Ze);let En=(Ep=Q.buttonTooltipText)!=null?Ep:"Attach file",Zt=h("div","persona-send-button-tooltip");Zt.textContent=En,Ft.appendChild(Zt),ot.append(Ft),!nt&&re&&ge&&(nt=No.fromConfig(Q),nt.setPreviewsContainer(ge),re.addEventListener("change",async()=>{nt&&(re!=null&&re.files)&&(await nt.handleFileSelect(re.files),re.value="")})),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(Mm(Q.dropOverlay))}else{Ft.style.display="";let Q=(Mp=r.attachments)!=null?Mp:{};re&&(re.accept=((kp=Q.allowedTypes)!=null?kp:Or).join(","),re.multiple=((Lp=Q.maxFiles)!=null?Lp:4)>1),nt&&nt.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else Ft&&(Ft.style.display="none"),nt&&nt.clearAttachments(),(Pp=de.querySelector(".persona-attachment-drop-overlay"))==null||Pp.remove();let Kt=(Ip=r.sendButton)!=null?Ip:{},Eo=(Wp=Kt.useIcon)!=null?Wp:!1,so=(Rp=Kt.iconText)!=null?Rp:"\u2191",yt=Kt.iconName,In=(Hp=Kt.tooltipText)!=null?Hp:"Send message",Dr=(Bp=Kt.showTooltip)!=null?Bp:!1,Tn=(Dp=Kt.size)!=null?Dp:"40px",Wn=Kt.backgroundColor,Bt=Kt.textColor;if(Eo){if(ie.style.width=Tn,ie.style.height=Tn,ie.style.minWidth=Tn,ie.style.minHeight=Tn,ie.style.fontSize="18px",ie.style.lineHeight="1",ie.innerHTML="",Bt?ie.style.color=Bt:ie.style.color="var(--persona-button-primary-fg, #ffffff)",yt){let Q=parseFloat(Tn)||24,vt=(Bt==null?void 0:Bt.trim())||"currentColor",Ot=be(yt,Q,vt,2);Ot?ie.appendChild(Ot):ie.textContent=so}else ie.textContent=so;ie.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ie.style.backgroundColor=Wn,ie.classList.remove("persona-bg-persona-primary")):(ie.style.backgroundColor="",ie.classList.add("persona-bg-persona-primary"))}else ie.textContent=(Fp=(Np=r.copy)==null?void 0:Np.sendButtonLabel)!=null?Fp:"Send",ie.style.width="",ie.style.height="",ie.style.minWidth="",ie.style.minHeight="",ie.style.fontSize="",ie.style.lineHeight="",ie.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",Wn?(ie.style.backgroundColor=Wn,ie.classList.remove("persona-bg-persona-accent")):ie.classList.add("persona-bg-persona-accent"),Bt?ie.style.color=Bt:ie.classList.add("persona-text-white");Kt.borderWidth?(ie.style.borderWidth=Kt.borderWidth,ie.style.borderStyle="solid"):(ie.style.borderWidth="",ie.style.borderStyle=""),Kt.borderColor?ie.style.borderColor=Kt.borderColor:ie.style.borderColor="",Kt.paddingX?(ie.style.paddingLeft=Kt.paddingX,ie.style.paddingRight=Kt.paddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),Kt.paddingY?(ie.style.paddingTop=Kt.paddingY,ie.style.paddingBottom=Kt.paddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let zt=kn==null?void 0:kn.querySelector(".persona-send-button-tooltip");if(Dr&&In)if(zt)zt.textContent=In,zt.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=In,kn==null||kn.insertBefore(Q,ie)}else zt&&(zt.style.display="none");let Dt=(Up=(Op=r.layout)==null?void 0:Op.contentMaxWidth)!=null?Up:$()?(jp=(_p=($p=r.launcher)==null?void 0:$p.composerBar)==null?void 0:_p.contentMaxWidth)!=null?jp:"720px":void 0;Dt?(_e.style.maxWidth=Dt,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%",$t&&($t.style.maxWidth=Dt,$t.style.marginLeft="auto",$t.style.marginRight="auto"),Mt&&(Mt.style.maxWidth=Dt,Mt.style.marginLeft="auto",Mt.style.marginRight="auto")):(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight="",_e.style.width="",$t&&($t.style.maxWidth="",$t.style.marginLeft="",$t.style.marginRight=""),Mt&&(Mt.style.maxWidth="",Mt.style.marginLeft="",Mt.style.marginRight=""));let Jt=(qp=r.statusIndicator)!=null?qp:{},Rn=(zp=Jt.visible)!=null?zp:!0;if(cn.style.display=Rn?"":"none",T){let Q=T.getStatus();me(cn,(Ot=>{var dt,Et,an,gn;return Ot==="idle"?(dt=Jt.idleText)!=null?dt:fn.idle:Ot==="connecting"?(Et=Jt.connectingText)!=null?Et:fn.connecting:Ot==="connected"?(an=Jt.connectedText)!=null?an:fn.connected:Ot==="error"?(gn=Jt.errorText)!=null?gn:fn.error:fn[Ot]})(Q),Jt,Q)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Jn=Jt.align==="left"?"persona-text-left":Jt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(Jn)},open(){_()&&Ht(!0,"api")},close(){_()&&Ht(!1,"api")},toggle(){_()&&Ht(!D,"api")},clearChat(){xn=!1,T.clearMessages(),ur.clear(),Qr();try{localStorage.removeItem(bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}d={},A.syncFromMetadata(),K==null||K.clear(),ce==null||ce.reset(),we==null||we.update()},setMessage(c){return!pe||T.isStreaming()?!1:(!D&&_()&&Ht(!0,"system"),pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(T.isStreaming())return!1;let f=(c==null?void 0:c.trim())||pe.value.trim();return f?(!D&&_()&&Ht(!0,"system"),pe.value="",pe.style.height="auto",T.sendMessage(f),!0):!1},startVoiceRecognition(){var f,y;return T.isStreaming()?!1:((y=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:y.type)==="runtype"?(T.isVoiceActive()||(!D&&_()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),T.toggleVoice().then(()=>{gt.active=T.isVoiceActive(),or("user"),T.isVoiceActive()&&j()})),!0):Kn?!0:Hs()?(!D&&_()&&Ht(!0,"system"),gt.manuallyDeactivated=!1,Pn(),Co("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Pn(),or("user"),J()}),!0):!1:Kn?(gt.manuallyDeactivated=!0,Pn(),hr("user"),!0):!1},injectMessage(c){return!D&&_()&&Ht(!0,"system"),T.injectMessage(c)},injectAssistantMessage(c){!D&&_()&&Ht(!0,"system");let f=T.injectAssistantMessage(c);return U&&(U=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),f},injectUserMessage(c){return!D&&_()&&Ht(!0,"system"),T.injectUserMessage(c)},injectSystemMessage(c){return!D&&_()&&Ht(!0,"system"),T.injectSystemMessage(c)},injectMessageBatch(c){return!D&&_()&&Ht(!0,"system"),T.injectMessageBatch(c)},injectComponentDirective(c){return!D&&_()&&Ht(!0,"system"),T.injectComponentDirective(c)},injectTestMessage(c){!D&&_()&&Ht(!0,"system"),T.injectTestEvent(c)},async connectStream(c,f){return T.connectStream(c,f)},__pushEventStreamEvent(c){K&&(ce==null||ce.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!fe||!K||bn()},hideEventStream(){he&&Nn()},isEventStreamVisible(){return he},showArtifacts(){cr(r)&&(xn=!1,Un(),xt==null||xt.setMobileOpen(!0))},hideArtifacts(){cr(r)&&(xn=!0,Un())},upsertArtifact(c){return cr(r)?(xn=!1,T.upsertArtifact(c)):null},selectArtifact(c){cr(r)&&T.selectArtifact(c)},clearArtifacts(){cr(r)&&T.clearArtifacts()},getArtifacts(){var c;return(c=T==null?void 0:T.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=T==null?void 0:T.getSelectedArtifactId())!=null?c:null},focusInput(){return E&&!D&&!$()||!pe?!1:(pe.focus(),!0)},async resolveApproval(c,f){let b=T.getMessages().find(k=>{var N;return k.variant==="approval"&&((N=k.approval)==null?void 0:N.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);if(b.approval.toolType==="webmcp"){T.resolveWebMcpApproval(b.id,f);return}return T.resolveApproval(b.approval,f)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){u(c)},on(c,f){return o.on(c,f)},off(c,f){o.off(c,f)},isOpen(){return _()&&D},isVoiceActive(){return gt.active},getState(){return{open:_()&&D,launcherEnabled:E,voiceActive:gt.active,streaming:T.isStreaming()}},showCSATFeedback(c){!D&&_()&&Ht(!0,"system");let f=_e.querySelector(".persona-feedback-container");f&&f.remove();let y=Bi({onSubmit:async(b,k)=>{var N;T.isClientTokenMode()&&await T.submitCSATFeedback(b,k),(N=c==null?void 0:c.onSubmit)==null||N.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!D&&_()&&Ht(!0,"system");let f=_e.querySelector(".persona-feedback-container");f&&f.remove();let y=Di({onSubmit:async(b,k)=>{var N;T.isClientTokenMode()&&await T.submitNPSFeedback(b,k),(N=c==null?void 0:c.onSubmit)==null||N.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return T.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return T.submitNPSFeedback(c,f)},destroy(){Ar!=null&&(clearInterval(Ar),Ar=null),ft.forEach(c=>c()),le.remove(),Ye==null||Ye.remove(),Me==null||Me.destroy(),Ge==null||Ge.remove(),zn&&qe.removeEventListener("click",zn)}};if((((qc=n==null?void 0:n.debugTools)!=null?qc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:y=>y?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=f,ft.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",f),ft.push(()=>{window.removeEventListener("persona:focusInput",f)}),fe){let q=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&tn.showEventStream()},H=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",H),ft.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",H)})}let y=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.showArtifacts()},b=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.hideArtifacts()},k=q=>{let H=q.detail;H!=null&&H.instanceId&&H.instanceId!==c||H!=null&&H.artifact&&tn.upsertArtifact(H.artifact)},N=q=>{let H=q.detail;H!=null&&H.instanceId&&H.instanceId!==c||typeof(H==null?void 0:H.id)=="string"&&tn.selectArtifact(H.id)},O=q=>{let H=q.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",O),ft.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",O)})}let ar=Fh(r.persistState);if(ar&&_()){let c=Oh(ar.storage),f=`${ar.keyPrefix}widget-open`,y=`${ar.keyPrefix}widget-voice`,b=`${ar.keyPrefix}widget-voice-mode`;if(c){let k=((zc=ar.persist)==null?void 0:zc.openState)&&c.getItem(f)==="true",N=((Vc=ar.persist)==null?void 0:Vc.voiceState)&&c.getItem(y)==="true",O=((Kc=ar.persist)==null?void 0:Kc.voiceState)&&c.getItem(b)==="true";if(k&&setTimeout(()=>{tn.open(),setTimeout(()=>{var q;if(N||O)tn.startVoiceRecognition();else if((q=ar.persist)!=null&&q.focusInput){let H=e.querySelector("textarea");H&&H.focus()}},100)},0),(Jc=ar.persist)!=null&&Jc.openState&&(o.on("widget:opened",()=>{c.setItem(f,"true")}),o.on("widget:closed",()=>{c.setItem(f,"false")})),(Gc=ar.persist)!=null&&Gc.voiceState&&(o.on("voice:state",q=>{c.setItem(y,q.active?"true":"false")}),o.on("user:message",q=>{c.setItem(b,q.viaVoice?"true":"false")})),ar.clearOnChatClear){let q=()=>{c.removeItem(f),c.removeItem(y),c.removeItem(b)},H=()=>q();window.addEventListener("persona:clear-chat",H),ft.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return p&&_()&&setTimeout(()=>{tn.open()},0),Hr(),tn};var $h=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},km=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Dl=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=""},Lm=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Dl(e)},Rl=e=>{e.style.transition=""},Hl=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=""},Bl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Oi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},_h=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},jh=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Pm=(e,t,n,r,s,o,a)=>{var v,x,A,E,B,P;let i=ir(o),d=i.reveal==="push";_h(e,t,n,r,d),jh(e,t,n,r,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",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.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 l=e.ownerDocument.defaultView,p=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,m=(E=(A=o==null?void 0:o.launcher)==null?void 0:A.mobileBreakpoint)!=null?E:640,g=l!=null?l.innerWidth<=m:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Hl(t),Rl(r),Lm(r),Bl(n),Oi(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((P=(B=o==null?void 0:o.launcher)==null?void 0:B.zIndex)!=null?P:hn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Lm(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Hl(t),Rl(r),Bl(n),Oi(s,r);let I=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":R;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=I,r.style.transform=w,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.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",Rl(r),Dl(r),Oi(s,r);let I=$h(i.width,e.clientWidth),R=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",W=i.side==="right"?a?`translateX(-${I}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${I}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${R+I}px`,t.style.transition=w,t.style.transform=W,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${R}px`,n.style.maxWidth=`${R}px`,n.style.minWidth=`${R}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Hl(t),Dl(r),Bl(n),Oi(s,r);let I=i.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${R}`,r.style.width=R,r.style.maxWidth=R,r.style.minWidth=R,r.style.minHeight="0",r.style.position="relative",r.style.overflow=I||W?"hidden":"visible",r.style.transition=w,I&&(r.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")}},Uh=(e,t)=>{let n=e.ownerDocument.createElement("div");return km(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){km(n,r)},destroy(){n.remove()}}},qh=(e,t)=>{var B,P,I,R;let{ownerDocument:n}=e,r=e.parentElement;if(!r)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=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),m=(P=(B=t==null?void 0:t.launcher)==null?void 0:B.enabled)==null||P?(R=(I=t==null?void 0:t.launcher)==null?void 0:I.autoExpand)!=null?R:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,u=()=>{g==null||g.disconnect(),g=null},v=()=>{u(),ir(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Pm(a,i,d,l,p,t,m)}),g.observe(a))},x=()=>{Pm(a,i,d,l,p,t,m),v()},A=a.ownerDocument.defaultView,E=()=>{x()};return A==null||A.addEventListener("resize",E),ir(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:p,shell:a,syncWidgetState(w){let W=w.launcherEnabled?w.open:!0;m!==W&&(m=W,x())},updateConfig(w){var W,$;t=w,(($=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)!=null?$:!0)===!1&&(m=!0),x()},destroy(){A==null||A.removeEventListener("resize",E),u(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},ma=(e,t)=>rn(t)?qh(e,t):Uh(e,t);var Nl={},Im=!1,zh=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 t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Vh=()=>{try{if(typeof Nl!="undefined"&&Nl.url)return new URL("../widget.css",Nl.url).href}catch{}return null},Wm=(e,t)=>{let n=Vh(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},Fl=e=>{let t=zh(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=ma(t,s),a,i=[],d=(A,E)=>{var R,w;let P=!((w=(R=E==null?void 0:E.launcher)==null?void 0:R.enabled)!=null?w:!0)||rn(E),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),P&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let W=A.attachShadow({mode:"open"});W.appendChild(I),Wm(W,r)}else A.appendChild(I),Wm(A,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},m=()=>{let A=d(o.host,s);a=Fi(A,s,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(A=>A()),i=[],a.destroy()};m(),e.onChatReady?e.onChatReady():e.onReady&&(Im||(Im=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let u=A=>{g(),o.destroy(),o=ma(t,A),s=A,m()},v={update(A){var w,W,$,_,D,U;let E={...s,...A,launcher:{...(w=s==null?void 0:s.launcher)!=null?w:{},...(W=A==null?void 0:A.launcher)!=null?W:{},dock:{...(_=($=s==null?void 0:s.launcher)==null?void 0:$.dock)!=null?_:{},...(U=(D=A==null?void 0:A.launcher)==null?void 0:D.dock)!=null?U:{}}}},B=rn(s),P=rn(E),I=co(s),R=co(E);if(B!==P||I!==R){u(E);return}s=E,o.updateConfig(s),a.update(A),l()},destroy(){g(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(A,E,B){if(E==="host")return o.host;if(E in A)return Reflect.get(A,E,B);let P=a[E];return typeof P=="function"?P.bind(a):P}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Nm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Kh=new Set(["button","a","input","select","textarea","details","summary"]),Jh=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ol=/\b(product|card|item|listing|result)\b/i,_l=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Gh=3e3,Xh=100;function Fm(e){let t=typeof e.className=="string"?e.className:"";if(Ol.test(t)||e.id&&Ol.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Ol.test(r.value))return!0}return!1}function Om(e){var t;return _l.test(((t=e.textContent)!=null?t:"").trim())}function $m(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Qh(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Rm(e){let t=e.match(_l);return t?t[0]:null}function Hm(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Yh(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var Zh="commerce-card",ey="result-card";function Bm(e){return!Fm(e)||!Om(e)||!$m(e)&&!Qh(e)?0:5200}function Dm(e){var r;return!Fm(e)||Om(e)||!$m(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var jl=[{id:Zh,scoreElement(e){return Bm(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||_l.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(Bm(e)===0)return null;let{title:n,href:r}=Hm(e),s=(p=(l=Rm(((d=e.textContent)!=null?d:"").trim()))!=null?l:Rm(t.text))!=null?p:"",o=Yh(e);return[r&&n?`[${n}](${r})${s?` \u2014 ${s}`:""}`:n?`${n}${s?` \u2014 ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
108
|
+
`)}},{id:ey,scoreElement(e){return Dm(e)},formatSummary(e,t){if(Dm(e)===0)return null;let{title:n,href:r}=Hm(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
109
|
+
`)}}];function ty(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function ny(e){var p,m,g,u,v,x,A,E,B,P,I,R,w;let t=(p=e.options)!=null?p:{},n=(g=(m=t.maxElements)!=null?m:e.maxElements)!=null?g:80,r=(v=(u=t.excludeSelector)!=null?u:e.excludeSelector)!=null?v:".persona-host",s=(A=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?A:200,o=(B=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?B:!0,a=(P=t.root)!=null?P:e.root,i=(I=t.mode)!=null?I:"structured",d=(R=t.maxCandidates)!=null?R:Math.max(500,n*10),l=(w=e.rules)!=null?w:jl;return i==="simple"&&e.rules&&e.rules.length>0?(ty(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function $l(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var ry=["data-testid","data-product","data-action","data-id","data-name","data-type"];function oy(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||Kh.has(t)||n&&Jh.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function _m(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function sy(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Ul(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${$l(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of ry){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${$l(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>$l(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 > ${t}`)).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 r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function ay(e){return e==="static"?Xh:Gh}function jm(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:Ul(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:oy(e),attributes:sy(e)}}function iy(e,t,n,r){let s=ay(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function ly(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function cy(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(Nm.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!_m(l)){i=a.nextNode();continue}let m=jm(l,e.maxTextLength),g=m.text.length>0,u=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(A=>A==="role");if(!g&&!u){i=a.nextNode();continue}if(r.has(m.selector)){i=a.nextNode();continue}r.add(m.selector);let{score:v,formattingRule:x}=iy(l,m,e.rules,n);s.push({el:l,domIndex:o,enriched:m,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;ly(d,l)||d.push(l)}return d.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:m===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var g;let p;if((g=l.formattingRule)!=null&&g.formatSummary){let u=l.formattingRule.formatSummary(l.el,l.enriched,n);u&&(p=u)}let m={...l.enriched};return p&&(m.formattedSummary=p),m})}function dy(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(Nm.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!_m(d)){o=s.nextNode();continue}let p=jm(d,e.maxTextLength),m=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(u=>u==="role");if(!m&&!g){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}o=s.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Um(e={}){var r;let t=ny(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?dy(t,n):cy(t,n):[]}var $i=100;function qm(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
|
|
110
110
|
${a.map(i=>`- ${i.split(`
|
|
111
111
|
`).join(`
|
|
112
112
|
`)}`).join(`
|
|
113
|
-
`)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)
|
|
113
|
+
`)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="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,$i)}" (clickable)`);r.push(`Interactive elements:
|
|
114
114
|
${a.join(`
|
|
115
|
-
`)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0
|
|
115
|
+
`)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,$i)}" (navigable)`);r.push(`Navigation links:
|
|
116
116
|
${a.join(`
|
|
117
|
-
`)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0
|
|
117
|
+
`)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,$i)}" (input)`);r.push(`Form inputs:
|
|
118
118
|
${a.join(`
|
|
119
|
-
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0
|
|
119
|
+
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,$i)}"`);r.push(`Content:
|
|
120
120
|
${a.join(`
|
|
121
121
|
`)}`)}return r.join(`
|
|
122
122
|
|
|
123
|
-
`)}var
|
|
123
|
+
`)}var zm={name:"@runtypelabs/persona",version:"3.29.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"},"./codegen":{types:"./dist/codegen.d.ts",import:"./dist/codegen.js",require:"./dist/codegen.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:launcher && pnpm run build:theme-ref && pnpm run build:codegen && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --minify --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:codegen":"tsup src/codegen.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 --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting","build:launcher":`tsup src/launcher-global.ts --format iife --global-name AgentWidgetLauncher --minify --sourcemap --splitting false --out-dir dist && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/launcher-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/launcher'+ext);}"`,lint:"eslint . --ext .ts",typecheck:"pnpm run check:runtype-types && tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit","fetch:runtype-openapi":"node scripts/fetch-runtype-openapi.mjs","generate:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs","check:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs --check"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",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:{"@size-limit/file":"^12.1.0","@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","size-limit":"^12.1.0",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 Uo=zm.version;function Vm(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Km(){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 Jm(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Er(e.colors.primary,.95),100:Er(e.colors.primary,.9),200:Er(e.colors.primary,.8),300:Er(e.colors.primary,.7),400:Er(e.colors.primary,.6),500:e.colors.primary,600:Er(e.colors.primary,.8),700:Er(e.colors.primary,.7),800:Er(e.colors.primary,.6),900:Er(e.colors.primary,.5),950:Er(e.colors.primary,.45)}}),{...t,palette:n}}}}function Gm(){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 Xm(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Er(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Qm(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var uy={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"}}},Ym={components:{panel:{borderRadius:"0",shadow:"none"}}},ql={id:"shop",label:"Shopping Assistant",config:{theme:uy,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Xn},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?"]}},zl={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ym}},Vl={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ym}},Kl={shop:ql,minimal:zl,fullscreen:Vl};function Zm(e){return Kl[e]}var eg=Fl;function qr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function my(e){if(e)return{getHeaders:qr(e.getHeaders),onFeedback:qr(e.onFeedback),onCopy:qr(e.onCopy),requestMiddleware:qr(e.requestMiddleware),actionHandlers:qr(e.actionHandlers),actionParsers:qr(e.actionParsers),postprocessMessage:qr(e.postprocessMessage),contextProviders:qr(e.contextProviders),streamParser:qr(e.streamParser)}}var tg=`({ text, message }: any) => {
|
|
124
124
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
125
125
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
126
126
|
let cleanJson = jsonSource
|
|
@@ -133,7 +133,7 @@ ${a.join(`
|
|
|
133
133
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
134
134
|
} catch (e) { return null; }
|
|
135
135
|
return null;
|
|
136
|
-
}`,
|
|
136
|
+
}`,ng=`function(ctx) {
|
|
137
137
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
138
138
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
139
139
|
var cleanJson = jsonSource
|
|
@@ -146,7 +146,7 @@ ${a.join(`
|
|
|
146
146
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
147
147
|
} catch (e) { return null; }
|
|
148
148
|
return null;
|
|
149
|
-
}`,
|
|
149
|
+
}`,rg=`(action: any, context: any) => {
|
|
150
150
|
if (action.type !== 'nav_then_click') return;
|
|
151
151
|
const payload = action.payload || action.raw || {};
|
|
152
152
|
const url = payload?.page;
|
|
@@ -163,7 +163,7 @@ ${a.join(`
|
|
|
163
163
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
164
164
|
window.location.href = targetUrl;
|
|
165
165
|
return { handled: true, displayText: text };
|
|
166
|
-
}`,
|
|
166
|
+
}`,og=`function(action, context) {
|
|
167
167
|
if (action.type !== 'nav_then_click') return;
|
|
168
168
|
var payload = action.payload || action.raw || {};
|
|
169
169
|
var url = payload.page;
|
|
@@ -180,26 +180,26 @@ ${a.join(`
|
|
|
180
180
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
181
181
|
window.location.href = targetUrl;
|
|
182
182
|
return { handled: true, displayText: text };
|
|
183
|
-
}`,
|
|
183
|
+
}`,gy=`(parsed: any) => {
|
|
184
184
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
185
185
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
186
186
|
if (parsed.action === 'message') return parsed.text || '';
|
|
187
187
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
188
188
|
return parsed.text || null;
|
|
189
|
-
}`,
|
|
189
|
+
}`,fy=`function(parsed) {
|
|
190
190
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
191
191
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
192
192
|
if (parsed.action === 'message') return parsed.text || '';
|
|
193
193
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
194
194
|
return parsed.text || null;
|
|
195
|
-
}`;function
|
|
196
|
-
`)}function
|
|
197
|
-
`)}function by(e,n){let t=n==null?void 0:n.hooks,r=["// 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&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ho(r,"theme",e.theme," "),e.launcher&&ho(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...$i(e," ")),r.push(...ji(e," ",t)),r.push(...Ui(e," ")),r.push(...qi(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${my}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${eg}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${eg}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${ng}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${ng}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
198
|
-
`)}function
|
|
199
|
-
`)}function
|
|
195
|
+
}`;function hy(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function _i(e){var t,n;return(n=(t=e.parserType)!=null?t:hy(e.streamParser))!=null?n:"plain"}function ji(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&n.push(`${t} ${r}: "${s}",`)}),n.push(`${t}},`)),n}function Ui(e,t,n){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(s||o)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function qi(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function zi(e,t){let n=[];if(e.layout){let r=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");(r||s)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?n.push(`${t} ${d}: "${l}",`):typeof l=="boolean"&&n.push(`${t} ${d}: ${l},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Jl(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function sg(e,t,n){Object.entries(t).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${r}: {`),sg(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function ho(e,t,n,r){n&&(e.push(`${r}${t}: {`),sg(e,n,`${r} `),e.push(`${r}},`))}function ga(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function ag(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:my(n.hooks)}:void 0;return t==="esm"?yy(r,s):t==="script-installer"?vy(r,s):t==="script-advanced"?Cy(r,s):t==="react-component"?by(r,s):t==="react-advanced"?xy(r,s):wy(r,s)}function yy(e,t){let n=t==null?void 0:t.hooks,r=_i(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${ga(t)}',`," 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: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ho(o,"theme",e.theme," "),e.launcher&&ho(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(...ji(e," ")),o.push(...Ui(e," ",n)),o.push(...qi(e," ")),o.push(...zi(e," ")),o.push(...Jl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
|
|
196
|
+
`)}function by(e,t){let n=t==null?void 0:t.hooks,r=_i(e),s=r!=="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: '${ga(t)}',`," 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: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ho(o,"theme",e.theme," "),e.launcher&&ho(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(...ji(e," ")),o.push(...Ui(e," ",n)),o.push(...qi(e," ")),o.push(...zi(e," ")),o.push(...Jl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.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(`
|
|
197
|
+
`)}function xy(e,t){let n=t==null?void 0:t.hooks,r=["// 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: '${ga(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ho(r,"theme",e.theme," "),e.launcher&&ho(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...ji(e," ")),r.push(...Ui(e," ",n)),r.push(...qi(e," ")),r.push(...zi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${gy}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${tg}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${tg}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${rg}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${rg}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
198
|
+
`)}function ig(e){var s;let t=_i(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.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&&(r.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&&(r.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&&(r.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 l={};Object.entries(d).forEach(([p,m])=>{p!=="format"&&(typeof m=="string"||typeof m=="boolean")&&(l[p]=m)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function vy(e,t){let n=ig(e),s=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,o=JSON.stringify(s,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Uo}/dist/install.global.js" data-config='${o}'></script>`}function wy(e,t){let n=t==null?void 0:t.hooks,r=_i(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Uo}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Uo}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${ga(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," 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: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ho(o,"theme",e.theme," "),e.launcher&&ho(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(...ji(e," ")),o.push(...Ui(e," ",n)),o.push(...qi(e," ")),o.push(...zi(e," ")),o.push(...Jl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
|
|
199
|
+
`)}function Cy(e,t){let n=t==null?void 0:t.hooks,r=ig(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
|
|
200
200
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
201
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Uo}/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
|
|
202
|
-
`)}var
|
|
201
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Uo}/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 n!=null&&n.getHeaders&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${fy});`),o.push(" };")),o.push(""),n!=null&&n.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${n.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${ng}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${ng}`),o.push(" ];")),o.push(""),n!=null&&n.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${n.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${og}`),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(` ${og}`),o.push(" ];")),o.push(""),n!=null&&n.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${n.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(""),n!=null&&n.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${n.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: '${ga(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," 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(`
|
|
202
|
+
`)}var lg={desktop:{w:1280,h:800},mobile:{w:390,h:844}},cg=.1,dg=.15,pg=1.5,Gl=24,ug=40,Ay=`
|
|
203
203
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
204
204
|
.persona-dc-root {
|
|
205
205
|
display: flex;
|
|
@@ -350,7 +350,7 @@ ${a.join(`
|
|
|
350
350
|
.persona-dc-stage {
|
|
351
351
|
height: 550px;
|
|
352
352
|
min-height: 400px;
|
|
353
|
-
padding: ${
|
|
353
|
+
padding: ${Gl}px;
|
|
354
354
|
overflow: auto;
|
|
355
355
|
background: #f0f1f3;
|
|
356
356
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -440,5 +440,5 @@ ${a.join(`
|
|
|
440
440
|
min-height: 300px;
|
|
441
441
|
}
|
|
442
442
|
}
|
|
443
|
-
`;function
|
|
443
|
+
`;function Sy(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Ay,document.head.appendChild(e)}function Ty(e,t){let n=e.clientWidth-Gl*2-ug,r=e.clientHeight-Gl*2-ug;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Ey(e,t,n,r,s){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function mg(e,t){let{items:n,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Sy();let p=Math.max(0,Math.min(r,n.length-1)),m=s,g=o,u=null,v=1,x=!1,A=h("div","persona-dc-root"),E=h("div","persona-dc-toolbar"),B=h("div","persona-dc-toolbar-lead"),P=h("div","persona-dc-toolbar-trail"),I=jt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ce(-1)}),R=h("div");R.style.position="relative";let w=h("button","persona-dc-title-btn");w.type="button",w.setAttribute("aria-expanded","false"),w.setAttribute("aria-haspopup","listbox");let W=h("span","persona-dc-title-text"),$=h("span","persona-dc-title-chevron"),_=be("chevron-down",12,"currentColor",2);_&&$.appendChild(_),w.append(W,$);let D=h("div","persona-dc-dropdown");D.setAttribute("role","listbox"),D.style.display="none";let U=!1;function V(){D.innerHTML="";for(let me=0;me<n.length;me++){let le=n[me],oe=h("button","persona-dc-dropdown-item");oe.type="button",oe.setAttribute("role","option"),oe.setAttribute("aria-current",me===p?"true":"false");let Ye=h("span");if(Ye.textContent=le.title,oe.appendChild(Ye),le.description){let We=h("span","persona-dc-dropdown-desc");We.textContent=le.description,oe.appendChild(We)}oe.addEventListener("click",()=>{Re(),Ve(me)}),D.appendChild(oe)}}function se(){U=!U,D.style.display=U?"":"none",w.setAttribute("aria-expanded",U?"true":"false"),U&&V()}function Re(){U&&(U=!1,D.style.display="none",w.setAttribute("aria-expanded","false"))}w.addEventListener("click",me=>{me.stopPropagation(),se()});let Ue=()=>Re();document.addEventListener("click",Ue),R.append(w,D);let Fe=jt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ce(1)}),fe=h("span","persona-dc-counter");B.append(I,R,Fe,fe);let xe=null;i&&(xe=sa({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:me=>{m=me,K.dataset.device=m,u=null,Y()}}),P.appendChild(xe.element));let Pe=null;if(a){let me=h("div","persona-dc-zoom-controls"),le=jt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let We=u!=null?u:v;u=Math.max(dg,We-cg),Y()}});Pe=h("span","persona-dc-zoom-level"),Pe.title="Reset to 100%",Pe.style.cursor="pointer",Pe.addEventListener("click",()=>{u=1,Y()});let oe=jt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let We=u!=null?u:v;u=Math.min(pg,We+cg),Y()}}),Ye=jt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{u=null,Y()}});me.append(le,Pe,oe,Ye),P.appendChild(me)}if(d){let me=h("div","persona-dc-separator");P.appendChild(me);let le=sa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:oe=>{g=oe,K.dataset.colorScheme=g,we()}});P.appendChild(le.element)}let Be=h("div","persona-dc-separator");P.appendChild(Be);let te=jt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});P.appendChild(te),E.append(B,P);let Ie=h("div","persona-dc-stage"),K=h("div","persona-dc-iframe-wrapper");K.dataset.device=m,K.dataset.colorScheme=g;let ce=h("iframe","persona-dc-iframe");ce.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ce.setAttribute("loading","lazy"),ce.title=n[p].title,K.appendChild(ce),Ie.appendChild(K),A.append(E,Ie),e.appendChild(A);function we(){var me;try{let le=(me=ce.contentDocument)==null?void 0:me.body;if(!le)return;g==="dark"?le.classList.add("theme-dark"):le.classList.remove("theme-dark")}catch{}}ce.addEventListener("load",()=>we());function he(){let me=n[p];W.textContent=me.title,fe.textContent=`${p+1} / ${n.length}`,ce.title=me.title}function Ce(me){let le=((p+me)%n.length+n.length)%n.length;Ve(le)}function Ve(me){me<0||me>=n.length||(p=me,ce.src=n[p].url,he(),l==null||l(p,n[p]))}function Y(){var oe;if(x)return;let me=(oe=lg[m])!=null?oe:lg.desktop;v=Ty(Ie,me);let le=Math.max(dg,Math.min(pg,u!=null?u:v));Ey(K,ce,me,le,m),Pe&&(Pe.textContent=`${Math.round(le*100)}%`)}let ne=new ResizeObserver(()=>Y());ne.observe(Ie),he(),ce.src=n[p].url,requestAnimationFrame(()=>Y());function ae(){x||(x=!0,ne.disconnect(),document.removeEventListener("click",Ue),A.remove())}return{element:A,goTo:Ve,next:()=>Ce(1),prev:()=>Ce(-1),getIndex:()=>p,setDevice(me){m=me,K.dataset.device=me,xe==null||xe.setSelected(me),u=null,Y()},setColorScheme(me){g=me,K.dataset.colorScheme=me},setZoom(me){u=me,Y()},destroy:ae}}0&&(module.exports={ASK_USER_QUESTION_TOOL_NAME,AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createAskUserQuestionBubble,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,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,isWebMcpToolName,listRegisteredStreamAnimations,markdownPostprocessor,mergeWithDefaults,normalizeContent,parseAskUserQuestionPayload,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveDockConfig,resolveSanitizer,resolveTokens,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
|
|
444
444
|
//# sourceMappingURL=index.cjs.map
|