@runtypelabs/persona 3.31.1 → 3.34.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.
Files changed (51) hide show
  1. package/README.md +17 -10
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-quh7NmYD.d.cts → types-CthJFfNx.d.cts} +7 -0
  5. package/dist/animations/{types-quh7NmYD.d.ts → types-CthJFfNx.d.ts} +7 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +1 -1
  9. package/dist/codegen.js +1 -1
  10. package/dist/index.cjs +43 -43
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +320 -8
  13. package/dist/index.d.ts +320 -8
  14. package/dist/index.global.js +193 -192
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +43 -43
  17. package/dist/index.js.map +1 -1
  18. package/dist/launcher.global.js +117 -117
  19. package/dist/launcher.global.js.map +1 -1
  20. package/dist/smart-dom-reader.d.cts +110 -2
  21. package/dist/smart-dom-reader.d.ts +110 -2
  22. package/dist/theme-editor.cjs +30 -30
  23. package/dist/theme-editor.d.cts +124 -5
  24. package/dist/theme-editor.d.ts +124 -5
  25. package/dist/theme-editor.js +30 -30
  26. package/package.json +3 -3
  27. package/src/ask-user-question-tool.test.ts +148 -0
  28. package/src/ask-user-question-tool.ts +138 -0
  29. package/src/client.ts +43 -9
  30. package/src/codegen.test.ts +0 -14
  31. package/src/components/messages.ts +10 -0
  32. package/src/components/suggestions.ts +49 -6
  33. package/src/index-core.ts +15 -0
  34. package/src/runtime/host-layout.test.ts +206 -9
  35. package/src/runtime/host-layout.ts +121 -8
  36. package/src/runtime/init.test.ts +2 -2
  37. package/src/session.ts +188 -32
  38. package/src/session.webmcp.test.ts +48 -0
  39. package/src/suggest-replies-tool.test.ts +445 -0
  40. package/src/suggest-replies-tool.ts +152 -0
  41. package/src/theme-editor/index.ts +2 -0
  42. package/src/theme-editor/webmcp/index.ts +2 -0
  43. package/src/theme-editor/webmcp/types.ts +16 -3
  44. package/src/types.ts +108 -2
  45. package/src/ui.docked.test.ts +2 -2
  46. package/src/ui.suggest-replies.test.ts +237 -0
  47. package/src/ui.ts +57 -13
  48. package/src/utils/dock.test.ts +23 -1
  49. package/src/utils/dock.ts +2 -0
  50. package/src/voice/voice.test.ts +0 -51
  51. package/src/install-config.test.ts +0 -38
package/dist/index.cjs CHANGED
@@ -1,18 +1,18 @@
1
- "use strict";var of=Object.create;var za=Object.defineProperty;var sf=Object.getOwnPropertyDescriptor;var af=Object.getOwnPropertyNames;var lf=Object.getPrototypeOf,cf=Object.prototype.hasOwnProperty;var df=(e,t)=>{for(var n in t)za(e,n,{get:t[n],enumerable:!0})},wu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of af(t))!cf.call(e,o)&&o!==n&&za(e,o,{get:()=>t[o],enumerable:!(r=sf(t,o))||r.enumerable});return e};var Cu=(e,t,n)=>(n=e!=null?of(lf(e)):{},wu(t||!e||!e.__esModule?za(n,"default",{value:e,enumerable:!0}):n,e)),pf=e=>wu(za({},"__esModule",{value:!0}),e);var yy={};df(yy,{ASK_USER_QUESTION_TOOL_NAME:()=>Bl,AgentWidgetClient:()=>zo,AgentWidgetSession:()=>vs,AttachmentManager:()=>Go,DEFAULT_COMPONENTS:()=>bl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>di,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>er,DEFAULT_PALETTE:()=>fl,DEFAULT_SEMANTIC:()=>hl,DEFAULT_WIDGET_CONFIG:()=>Ft,PRESETS:()=>lc,PRESET_FULLSCREEN:()=>ic,PRESET_MINIMAL:()=>ac,PRESET_SHOP:()=>sc,THEME_ZONES:()=>tm,VERSION:()=>ns,WEBMCP_TOOL_PREFIX:()=>Kr,WebMcpBridge:()=>bs,accessibilityPlugin:()=>Ig,animationsPlugin:()=>Wg,applyThemeVariables:()=>xo,attachHeaderToContainer:()=>Qo,brandPlugin:()=>Rg,buildComposer:()=>Ts,buildDefaultHeader:()=>Tl,buildHeader:()=>Qr,buildHeaderWithLayout:()=>Ss,buildMinimalHeader:()=>El,collectEnrichedPageContext:()=>kg,componentRegistry:()=>eo,createActionManager:()=>Ta,createAgentExperience:()=>Xi,createAskUserQuestionBubble:()=>$m,createBestAvailableVoiceProvider:()=>li,createBubbleWithLayout:()=>Tm,createCSATFeedback:()=>Ki,createComboButton:()=>Ei,createComponentMiddleware:()=>lg,createComponentStreamParser:()=>Ui,createDefaultSanitizer:()=>dl,createDemoCarousel:()=>Yg,createDirectivePostprocessor:()=>Mu,createDropdownMenu:()=>Ao,createFlexibleJsonStreamParser:()=>Du,createIconButton:()=>Kt,createImagePart:()=>Uu,createJsonStreamParser:()=>ei,createLabelButton:()=>ba,createLocalStorageAdapter:()=>ji,createMarkdownProcessor:()=>ta,createMarkdownProcessorFromConfig:()=>jo,createMessageActions:()=>Il,createNPSFeedback:()=>Ji,createPlainTextParser:()=>Ya,createPlugin:()=>Dg,createRegexJsonParser:()=>Za,createStandardBubble:()=>Es,createTextPart:()=>oa,createTheme:()=>Cs,createThemeObserver:()=>gi,createToggleGroup:()=>ya,createTypingIndicator:()=>Yo,createVoiceProvider:()=>Jo,createWidgetHostLayout:()=>Ea,createXmlParser:()=>ti,default:()=>Fg,defaultActionHandlers:()=>ts,defaultJsonActionParser:()=>Sa,defaultParseRules:()=>rc,detectColorScheme:()=>ca,directivePostprocessor:()=>ku,ensureAskUserQuestionSheet:()=>Is,escapeHtml:()=>Uo,extractComponentDirectiveFromMessage:()=>Vi,fileToImagePart:()=>qu,formatEnrichedContext:()=>Lg,generateAssistantMessageId:()=>Vo,generateCodeSnippet:()=>zg,generateMessageId:()=>Ou,generateStableSelector:()=>oc,generateUserMessageId:()=>xs,getActiveTheme:()=>As,getColorScheme:()=>xl,getDisplayText:()=>$u,getHeaderLayout:()=>Ml,getImageParts:()=>ju,getPreset:()=>Og,hasComponentDirective:()=>zi,hasImages:()=>_u,headerLayouts:()=>Mi,highContrastPlugin:()=>Bg,initAgentWidget:()=>Zl,isAskUserQuestionMessage:()=>Yr,isComponentDirectiveType:()=>ig,isDockedMountMode:()=>gn,isVoiceSupported:()=>aa,isWebMcpToolName:()=>yo,listRegisteredStreamAnimations:()=>bm,markdownPostprocessor:()=>cl,mergeWithDefaults:()=>pi,normalizeContent:()=>Fu,parseAskUserQuestionPayload:()=>Zr,pluginRegistry:()=>Aa,reducedMotionPlugin:()=>Hg,registerStreamAnimationPlugin:()=>fm,removeAskUserQuestionSheet:()=>Eo,renderComponentDirective:()=>qi,renderLoadingIndicatorWithFallback:()=>Pl,renderLucideIcon:()=>Ce,resolveDockConfig:()=>mr,resolveSanitizer:()=>hs,resolveTokens:()=>ui,stripWebMcpPrefix:()=>Ka,themeToCssVariables:()=>mi,unregisterStreamAnimationPlugin:()=>hm,validateImageFile:()=>zu,validateTheme:()=>yl});module.exports=pf(yy);var Su=require("marked"),uf=e=>{if(e)return e},ta=e=>{var o,s;let t=e==null?void 0:e.markedOptions,n=new Su.Marked({gfm:(o=t==null?void 0:t.gfm)!=null?o:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),r=uf(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},jo=e=>e?ta({markedOptions:e.options,renderer:e.renderer}):ta(),mf=ta(),cl=e=>mf(e),Uo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Tu=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Au=e=>`%%FORM_PLACEHOLDER_${e}%%`,Eu=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Au(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Au(t.length);return t.push({token:s,type:o}),s}),n},Mu=e=>{let t=jo(e);return n=>{let r=[],o=Eu(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Tu(i)}"></div>`;s=s.replace(d,p)}),s}},ku=e=>{let t=[],n=Eu(e,t),r=cl(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Tu(s)}"></div>`;r=r.replace(a,d)}),r};var Lu=Cu(require("dompurify"),1),gf={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"]},ff=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,dl=()=>{let e=(0,Lu.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:")&&!ff.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,gf)},hs=e=>e===!1?null:typeof e=="function"?e:dl();var Kr="webmcp:",pl=new Map,Pu=e=>{var t;pl.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&pl.set(n.name,r)}},ul=e=>pl.get(Ka(e)),Va={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Iu=null;function Ru(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${hf(t.join(""))}`}function Wu(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,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 hf(e){let t=Wu(e,0).toString(36),n=Wu(e,2654435761).toString(36);return`${t}.${n}`}var bs=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(o){return Va.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",o),[]}Pu(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=yf(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return Ar("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return Ar(v?"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 s=Ka(t),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return Ar(`Failed to read WebMCP registry: ${x}`)}Pu(a);let i=a.find(v=>v.name===s);if(!i)return Ar(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ar(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return Ar("Aborted by cancel()");let d=ul(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Ar("User declined the tool call.");if(r!=null&&r.aborted)return Ar("Aborted by cancel()");let p=new AbortController,u=!1,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),m=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",m,{once:!0}));try{let v=await o.executeTool(i,Cf(n),{signal:p.signal});return xf(v)}catch(v){if(u)return Ar(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return Ar("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return Ar(x)}finally{clearTimeout(f),r&&r.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Iu?await Iu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Va.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,Va.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:vf;try{return await n(t)}catch(o){return Va.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>bf(t,r))}},Ka=e=>e.startsWith(Kr)?e.slice(Kr.length):e,yo=e=>e.startsWith(Kr),bf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},yf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},xf=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:Af(t)}]}},Ar=e=>({isError:!0,content:[{type:"text",text:e}]}),vf=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=wf(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var yf=Object.create;var Xa=Object.defineProperty;var xf=Object.getOwnPropertyDescriptor;var vf=Object.getOwnPropertyNames;var wf=Object.getPrototypeOf,Cf=Object.prototype.hasOwnProperty;var Af=(e,t)=>{for(var n in t)Xa(e,n,{get:t[n],enumerable:!0})},Iu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vf(t))!Cf.call(e,o)&&o!==n&&Xa(e,o,{get:()=>t[o],enumerable:!(r=xf(t,o))||r.enumerable});return e};var Ru=(e,t,n)=>(n=e!=null?yf(wf(e)):{},Iu(t||!e||!e.__esModule?Xa(n,"default",{value:e,enumerable:!0}):n,e)),Sf=e=>Iu(Xa({},"__esModule",{value:!0}),e);var Dy={};Af(Dy,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Ll,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>kl,ASK_USER_QUESTION_TOOL_NAME:()=>sa,AgentWidgetClient:()=>Go,AgentWidgetSession:()=>Es,AttachmentManager:()=>Yo,DEFAULT_COMPONENTS:()=>Hl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>wi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>nr,DEFAULT_PALETTE:()=>Rl,DEFAULT_SEMANTIC:()=>Wl,DEFAULT_WIDGET_CONFIG:()=>Nt,PRESETS:()=>yc,PRESET_FULLSCREEN:()=>bc,PRESET_MINIMAL:()=>hc,PRESET_SHOP:()=>fc,SUGGEST_REPLIES_CLIENT_TOOL:()=>ri,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Tl,SUGGEST_REPLIES_TOOL_NAME:()=>Sr,THEME_ZONES:()=>Em,VERSION:()=>os,WEBMCP_TOOL_PREFIX:()=>Gr,WebMcpBridge:()=>vs,accessibilityPlugin:()=>jg,animationsPlugin:()=>qg,applyThemeVariables:()=>Ao,attachHeaderToContainer:()=>es,brandPlugin:()=>zg,buildComposer:()=>Is,buildDefaultHeader:()=>Ul,buildHeader:()=>eo,buildHeaderWithLayout:()=>Ps,buildMinimalHeader:()=>jl,builtInClientToolsForDispatch:()=>la,collectEnrichedPageContext:()=>_g,componentRegistry:()=>to,createActionManager:()=>Ra,createAgentExperience:()=>rl,createAskUserQuestionBubble:()=>nm,createBestAvailableVoiceProvider:()=>xi,createBubbleWithLayout:()=>Qm,createCSATFeedback:()=>el,createComboButton:()=>Di,createComponentMiddleware:()=>vg,createComponentStreamParser:()=>Qi,createDefaultSanitizer:()=>bl,createDemoCarousel:()=>pf,createDirectivePostprocessor:()=>Ou,createDropdownMenu:()=>Mo,createFlexibleJsonStreamParser:()=>am,createIconButton:()=>Vt,createImagePart:()=>mm,createJsonStreamParser:()=>pi,createLabelButton:()=>Ta,createLocalStorageAdapter:()=>Ji,createMarkdownProcessor:()=>ra,createMarkdownProcessorFromConfig:()=>jo,createMessageActions:()=>Gl,createNPSFeedback:()=>tl,createPlainTextParser:()=>ci,createPlugin:()=>Gg,createRegexJsonParser:()=>di,createStandardBubble:()=>Rs,createTextPart:()=>pa,createTheme:()=>ks,createThemeObserver:()=>Ti,createToggleGroup:()=>Ea,createTypingIndicator:()=>ts,createVoiceProvider:()=>Xo,createWidgetHostLayout:()=>Wa,createXmlParser:()=>ui,default:()=>Xg,defaultActionHandlers:()=>rs,defaultJsonActionParser:()=>Ia,defaultParseRules:()=>mc,detectColorScheme:()=>ha,directivePostprocessor:()=>Nu,ensureAskUserQuestionSheet:()=>As,escapeHtml:()=>qo,extractComponentDirectiveFromMessage:()=>Zi,fileToImagePart:()=>gm,formatEnrichedContext:()=>$g,generateAssistantMessageId:()=>Jo,generateCodeSnippet:()=>rf,generateMessageId:()=>lm,generateStableSelector:()=>gc,generateUserMessageId:()=>Ts,getActiveTheme:()=>Ls,getColorScheme:()=>Dl,getDisplayText:()=>dm,getHeaderLayout:()=>ql,getImageParts:()=>um,getPreset:()=>Qg,hasComponentDirective:()=>Yi,hasImages:()=>pm,headerLayouts:()=>Oi,highContrastPlugin:()=>Kg,initAgentWidget:()=>cc,isAskUserQuestionMessage:()=>Jr,isComponentDirectiveType:()=>xg,isDockedMountMode:()=>mn,isSuggestRepliesMessage:()=>ia,isVoiceSupported:()=>ma,isWebMcpToolName:()=>zo,latestAgentSuggestions:()=>oi,listRegisteredStreamAnimations:()=>Um,markdownPostprocessor:()=>hl,mergeWithDefaults:()=>Ci,normalizeContent:()=>cm,parseAskUserQuestionPayload:()=>Qr,parseSuggestRepliesPayload:()=>Ml,pluginRegistry:()=>Pa,reducedMotionPlugin:()=>Vg,registerStreamAnimationPlugin:()=>_m,removeAskUserQuestionSheet:()=>wo,renderComponentDirective:()=>Xi,renderLoadingIndicatorWithFallback:()=>Kl,renderLucideIcon:()=>Ce,resolveDockConfig:()=>rr,resolveSanitizer:()=>xs,resolveTokens:()=>Ai,stripWebMcpPrefix:()=>Za,themeToCssVariables:()=>Si,unregisterStreamAnimationPlugin:()=>$m,validateImageFile:()=>fm,validateTheme:()=>Bl});module.exports=Sf(Dy);var Hu=require("marked"),Tf=e=>{if(e)return e},ra=e=>{var o,s;let t=e==null?void 0:e.markedOptions,n=new Hu.Marked({gfm:(o=t==null?void 0:t.gfm)!=null?o:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),r=Tf(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},jo=e=>e?ra({markedOptions:e.options,renderer:e.renderer}):ra(),Ef=ra(),hl=e=>Ef(e),qo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Bu=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Wu=e=>`%%FORM_PLACEHOLDER_${e}%%`,Du=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Wu(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Wu(t.length);return t.push({token:s,type:o}),s}),n},Ou=e=>{let t=jo(e);return n=>{let r=[],o=Du(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Bu(i)}"></div>`;s=s.replace(d,p)}),s}},Nu=e=>{let t=[],n=Du(e,t),r=hl(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Bu(s)}"></div>`;r=r.replace(a,d)}),r};var Fu=Ru(require("dompurify"),1),Mf={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"]},kf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,bl=()=>{let e=(0,Fu.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:")&&!kf.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Mf)},xs=e=>e===!1?null:typeof e=="function"?e:bl();var Gr="webmcp:",yl=new Map,_u=e=>{var t;yl.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&yl.set(n.name,r)}},xl=e=>yl.get(Za(e)),Ya={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},$u=null;function ju(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Lf(t.join(""))}`}function Uu(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,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 Lf(e){let t=Uu(e,0).toString(36),n=Uu(e,2654435761).toString(36);return`${t}.${n}`}var vs=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(o){return Ya.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",o),[]}_u(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=If(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return Ar("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return Ar(v?"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 s=Za(t),a;try{a=await o.getTools()}catch(v){let y=v instanceof Error?v.message:String(v);return Ar(`Failed to read WebMCP registry: ${y}`)}_u(a);let i=a.find(v=>v.name===s);if(!i)return Ar(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ar(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return Ar("Aborted by cancel()");let d=xl(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Ar("User declined the tool call.");if(r!=null&&r.aborted)return Ar("Aborted by cancel()");let p=new AbortController,u=!1,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),g=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",g,{once:!0}));try{let v=await o.executeTool(i,Bf(n),{signal:p.signal});return Rf(v)}catch(v){if(u)return Ar(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return Ar("Aborted by cancel()");let y=v instanceof Error?v.message:String(v);return Ar(y)}finally{clearTimeout(f),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}($u?await $u():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ya.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,Ya.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:Wf;try{return await n(t)}catch(o){return Ya.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>Pf(t,r))}},Za=e=>e.startsWith(Gr)?e.slice(Gr.length):e,zo=e=>e.startsWith(Gr),Pf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},If=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Rf=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:Df(t)}]}},Ar=e=>({isError:!0,content:[{type:"text",text:e}]}),Wf=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Hf(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(n)},wf=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)}},Cf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Af=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Jr=require("partial-json"),Ja=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ys=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)}},Sf=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Hu=e=>e.status==="complete"?Sf(e):e.status==="pending"?"Waiting":"",Tf=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s: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 Bu=e=>e.status==="complete"?Tf(e):"Using tool...",Ga=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ra=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Ga(t)},Xa=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Ga(t)},ml=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=ra(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Qa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&na(r,n.slice(s,a.index),[]),a[1]!==void 0?na(r,a[1],["bold"]):a[2]!==void 0?na(r,a[2],["italic"]):a[3]!==void 0&&na(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&na(r,n.slice(s),[]),r},na=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Ef=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
6
+ ${e.description}`:"");return window.confirm(n)},Hf=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)}},Bf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Df=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var xo=require("partial-json");var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Dr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var sa="ask_user_question",oa=8,ws="data-persona-ask-sheet-for",Of="Other",Nf="Other\u2026",zu="Type your own answer here",Vu="Send",Ff="Next",_f="Back",$f="Submit all",Uf="Skip",jf=3,vl="data-ask-current-index",wl="data-ask-question-count",Ku="data-ask-answers",Cl="data-ask-grouped",Gu="data-ask-layout",qf=e=>e.layout==="pills"?"pills":"rows",zf=e=>e.getAttribute(Gu)==="pills"?"pills":"rows",qu=!1,Ju=e=>e.replace(/["\\]/g,"\\$&"),Jr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===sa,ei=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Qr=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 o=r.join(""),s=(0,xo.parse)(o,xo.STR|xo.OBJ|xo.ARR);if(s&&typeof s=="object")return{payload:s,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>oa&&!qu&&(qu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${oa}.`)),t.slice(0,oa)},Vf=e=>{var t;return(t=aa(e)[0])!=null?t:null},Kf=(e,t)=>{var n;return(n=aa(e)[t])!=null?n:null},Qu=(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))},Xu=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=h("span","persona-ask-row-check");r.appendChild(o)}else{let o=h("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},Gf=(e,t,n,r)=>{let s=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.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)}s.appendChild(a);let d=Xu(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Jf=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,u,f;let s=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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<jf;g++)s.appendChild(Jf(r));return s}if(d.forEach((g,v)=>{s.appendChild(Gf(g,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Of:Nf;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 y=h("span","persona-ask-row-content"),w=document.createElement("input");w.type="text",w.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",w.placeholder=(p=t.freeTextPlaceholder)!=null?p:zu,w.setAttribute("data-ask-free-text-input","true"),w.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),y.appendChild(w),v.appendChild(y);let S=Xu(r,a,d.length);S&&v.appendChild(S),s.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=(f=t.freeTextLabel)!=null?f:g,s.appendChild(v)}}return s},Yu=(e,t)=>{var s,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 o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:zu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),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:Vu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Xf=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:Vu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Yf=(e,t,n)=>{var l,p,u,f;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 o=h("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:_f,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=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:Uf,a.setAttribute("data-ask-user-action","skip"),s.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?(u=n.submitAllLabel)!=null?u:$f:(f=n.nextLabel)!=null?f:Ff,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Vo=e=>{let t=e.getAttribute(Ku);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Zu=(e,t)=>{e.setAttribute(Ku,JSON.stringify(t))},mr=e=>{var n;let t=Number((n=e.getAttribute(vl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Zf=(e,t)=>{e.setAttribute(vl,String(Math.max(0,Math.floor(t))))},Cs=e=>{var n;let t=Number((n=e.getAttribute(wl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},vo=e=>e.getAttribute(Cl)==="true",eh=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},th=(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}=Qr(t),r=aa(n),o=Vo(e),s={},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(o,d)&&(s[l]=o[d]))}),s},em=e=>{let t=Vo(e),n=mr(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).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=""},tm=e=>{if(!vo(e))return;let t=Vo(e),n=mr(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);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=ei(n),o=zf(e),{payload:s,complete:a}=Qr(t),i=vo(e),d=mr(e),l=Cs(e),p=i?Kf(s,d):Vf(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let O=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=O,v.classList.toggle("persona-ask-question-skeleton",!O&&!a)}let y=e.querySelector('[data-ask-pill-list="true"]');if(y){let O=Qf(p,r,a,o);y.replaceWith(O)}if(o!=="rows"){let O=e.querySelector('[data-ask-free-text-row="true"]');O&&O.replaceWith(Yu(r,o))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!w?e.appendChild(Xf(r)):(!u||i)&&w&&w.remove(),e.setAttribute("data-multi-select",u?"true":"false");let S=e.querySelector('[data-ask-nav-row="true"]');if(i){let O=Yf(d,l,r);S?S.replaceWith(O):e.appendChild(O)}else S&&S.remove();em(e),tm(e)},nh=(e,t,n)=>{let r=ei(t),o=qf(r),s=e.toolCall.id,a=aa(n),i=Math.max(1,a.length),d=i>1,l=eh(e,a),p=d?th(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ws,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(wl,String(i)),u.setAttribute(vl,String(p)),u.setAttribute(Cl,d?"true":"false"),u.setAttribute(Gu,o),Zu(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Qu(u,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),u.appendChild(f);let w=h("div",o==="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 w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),u.appendChild(w),o!=="rows"&&u.appendChild(Yu(r,o)),Al(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},rh=(e,t,n)=>{let{payload:r}=Qr(t),o=Math.max(1,aa(r).length);o>Cs(e)&&(e.setAttribute(wl,String(o)),o>1&&!vo(e)&&e.setAttribute(Cl,"true")),Al(e,t,n)},nm=(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=ei(t);Qu(n,r);let o=h("span","persona-ask-stub-label"),{complete:s}=Qr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},As=(e,t,n)=>{if(!n||!Jr(e)||ei(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ws}]`).forEach(l=>{l.getAttribute(ws)!==o&&l.remove()});let a=n.querySelector(`[${ws}="${Ju(o)}"]`);if(a){rh(a,e,t);return}let{payload:i}=Qr(e),d=nh(e,t,i);n.appendChild(d)},wo=(e,t)=>{if(!e)return;let n=t?`[${ws}="${Ju(t)}"]`:`[${ws}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s: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),Co=(e,t)=>{let n=Vo(e),r=mr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Zu(e,n),em(e),tm(e)},ni=(e,t,n,r)=>{let o=Cs(e),s=Math.max(0,Math.min(o-1,r));Zf(e,s),Al(e,t,n)};var Sr="suggest_replies";var Tl={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},ri={name:Sr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown \u2014 do not add further commentary after calling this tool; end your turn.`,parametersSchema:Tl,origin:"sdk",annotations:{readOnlyHint:!0}},El=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ia=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Sr},Ml=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},oi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!ia(r))continue;let o=Ml((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},rm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var kl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:oa,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option \u2014 free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Ll={name:sa,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make \u2014 a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:kl,origin:"sdk",annotations:{readOnlyHint:!0}},la=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Ll),rm(e)&&t.push(ri),t};var Xr=require("partial-json"),si=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ss=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)}},oh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},om=e=>e.status==="complete"?oh(e):e.status==="pending"?"Waiting":"",sh=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s: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 sm=e=>e.status==="complete"?sh(e):"Using tool...",ai=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},da=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ai(t)},ii=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ai(t)},Pl=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=da(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},li=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&ca(r,n.slice(s,a.index),[]),a[1]!==void 0?ca(r,a[1],["bold"]):a[2]!==void 0?ca(r,a[2],["italic"]):a[3]!==void 0&&ca(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ca(r,n.slice(s),[]),r},ca=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},ah=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[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<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},qo=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ya=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Za=()=>{var t;let e=Ef();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)}},ei=()=>{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 o=(0,Jr.parse)(n,Jr.STR|Jr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Ja(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Ja(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Du=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Ja(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ja(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Jr.parse)(s,Jr.STR|Jr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ti=()=>{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 ni=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 s,a,i;let r=(i=(s=n==null?void 0:n.seq)!=null?s: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 o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.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 Mf="https://api.runtype.com/v1/dispatch",ri="https://api.runtype.com";function kf(e){var s,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 o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var gl=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 Lf(e){switch(e){case"json":return ei;case"regex-json":return Za;case"xml":return ti;default:return Ya}}var Nu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Pf(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 o=Nu(n);if(!Nu(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=qo(e);return qo(t)!==null&&a===null?t:e}var zo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;this.apiUrl=(n=t.apiUrl)!=null?n:Mf,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Lf(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new bs(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$/,""))||ri}/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 s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||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 o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.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$/,""))||ri}/v1/client/feedback`}async sendFeedback(t){var s,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 o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),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 o,s,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(),(s=(o=this.config).onSessionExpired)==null||s.call(o);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,u={sessionId:d.sessionId,messages:t.messages.filter(gl).map(I=>{var W,S,k;return{id:I.id,role:I.role,content:(k=(S=(W=I.contentParts)!=null?W:I.llmContent)!=null?S:I.rawContent)!=null?k: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}},f=l.clientTools,m=!!(f&&f.length>0),v=m?Ru(f):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,w=m&&x&&this.lastSentClientToolsFingerprint===v,T=!1,N=null,M;for(let I=0;;I++){let S={...u,...m&&(T||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:r.signal}),M.status===409&&I===0&&m){let k=await M.json().catch(()=>null);if((k==null?void 0:k.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}N=k!=null?k:{error:"Chat request failed"}}break}if(!M.ok){let I=N!=null?N:await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let S=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:S}),S}if(M.status===429){let S=new Error(I.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let W=new Error(I.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!M.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(M.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 o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...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:s,body:JSON.stringify(o),signal:r.signal},o)}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:s,body:JSON.stringify(o),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 o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...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:s,body:JSON.stringify(o),signal:r.signal},o)}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:s,body:JSON.stringify(o),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 o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ri}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ri}/resume`,a;o&&(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(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(gl).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}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(r.clientTools=o),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 s;let r={messages:t.slice().filter(gl).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}},o=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(o&&o.length>0&&(r.clientTools=o),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,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},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,o(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,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(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 Bt,ln,nr,Tr;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=R=>{let pe=R.reasoning?{...R.reasoning,chunks:[...R.reasoning.chunks]}:void 0,Ne=R.toolCall?{...R.toolCall,chunks:R.toolCall.chunks?[...R.toolCall.chunks]:void 0}:void 0,Ge=R.tools?R.tools.map($e=>({...$e,chunks:$e.chunks?[...$e.chunks]:void 0})):void 0;return{...R,reasoning:pe,toolCall:Ne,tools:Ge}},u=R=>{if(R.role!=="assistant"||R.variant)return!0;let pe=Array.isArray(R.contentParts)&&R.contentParts.length>0,Ne=typeof R.rawContent=="string"&&R.rawContent.trim()!=="";return typeof R.content=="string"&&R.content.trim()!==""||pe||Ne||!!R.stopReason},f=R=>{u(R)&&n({type:"message",message:p(R)})},m=null,v=null,x={current:null},w={current:null},T=!1,N=new Map,M=new Map,I=new Map,W=new Map,S={lastId:null,byStep:new Map},k={lastId:null,byCall:new Map},$=(R,pe,Ne="")=>`${R}::${pe}::${Ne}`,O=(R,pe)=>`${R}::${pe}::`,H=(R,pe,Ne,Ge)=>{let $e=$(R,pe,Ne),je=I.get($e);if(je)return je;let st=Ne?`-${Ne}`:"",It={id:`nested-${R}-${pe}${st}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ne?{partId:Ne}:{},agentMetadata:{executionId:Ge,parentToolId:R,parentStepId:pe}};return I.set($e,It),f(It),It},U=R=>{if(R==null)return null;try{return String(R)}catch{return null}},J=R=>{var pe,Ne,Ge,$e,je;return U((je=($e=(Ge=(Ne=(pe=R.stepId)!=null?pe:R.step_id)!=null?Ne:R.step)!=null?Ge:R.parentId)!=null?$e:R.flowStepId)!=null?je:R.flow_step_id)},ce=R=>{var pe,Ne,Ge,$e,je,st,It;return U((It=(st=(je=($e=(Ge=(Ne=(pe=R.callId)!=null?pe:R.call_id)!=null?Ne:R.requestId)!=null?Ge:R.request_id)!=null?$e:R.toolCallId)!=null?je:R.tool_call_id)!=null?st:R.stepId)!=null?It:R.step_id)},Me=r,ze=!1,Ae=()=>{if(m)return m;let R;return!ze&&Me?(R=Me,ze=!0):Me&&w.current?R=`${Me}_${w.current}`:R=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:R,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},We=(R,pe)=>{S.lastId=pe,R&&S.byStep.set(R,pe)},be=(R,pe)=>{var je;let Ne=(je=R.reasoningId)!=null?je:R.id,Ge=J(R);if(Ne){let st=String(Ne);return We(Ge,st),st}if(Ge){let st=S.byStep.get(Ge);if(st)return S.lastId=st,st}if(S.lastId&&!pe)return S.lastId;if(!pe)return null;let $e=`reason-${l()}`;return We(Ge,$e),$e},ke=R=>{let pe=N.get(R);if(pe)return pe;let Ne={id:`reason-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:R,status:"streaming",chunks:[]}};return N.set(R,Ne),f(Ne),Ne},Re=(R,pe)=>{k.lastId=pe,R&&k.byCall.set(R,pe)},de=new Set,Q=new Map,re=new Set,le=new Map,ge=R=>{if(!R)return!1;let pe=R.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},V=(R,pe)=>{var je;let Ne=(je=R.toolId)!=null?je:R.id,Ge=ce(R);if(Ne){let st=String(Ne);return Re(Ge,st),st}if(Ge){let st=k.byCall.get(Ge);if(st)return k.lastId=st,st}if(k.lastId&&!pe)return k.lastId;if(!pe)return null;let $e=`tool-${l()}`;return Re(Ge,$e),$e},se=R=>{let pe=M.get(R);if(pe)return pe;let Ne={id:`tool-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:R,status:"pending"}};return M.set(R,Ne),f(Ne),Ne},He=R=>{if(typeof R=="number"&&Number.isFinite(R))return R;if(typeof R=="string"){let pe=Number(R);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let Ne=Date.parse(R);if(!Number.isNaN(Ne))return Ne}return Date.now()},Z=R=>{if(typeof R=="string")return R;if(R==null)return"";try{return JSON.stringify(R)}catch{return String(R)}},ee=new Map,ae=new Map,Se=new Map,Ze=new Map,ve=null,fe=(R,pe,Ne)=>{var It;let Ge=Se.get(R);Ge||(Ge=[],Se.set(R,Ge));let $e=0,je=Ge.length;for(;$e<je;){let Jt=$e+je>>>1;Ge[Jt].seq<pe?$e=Jt+1:je=Jt}((It=Ge[$e])==null?void 0:It.seq)===pe?Ge[$e]={seq:pe,text:Ne}:Ge.splice($e,0,{seq:pe,text:Ne});let st="";for(let Jt=0;Jt<Ge.length;Jt++)st+=Ge[Jt].text;return st},Je=(R,pe)=>{let Ne=Z(pe),Ge=ae.get(R.id),$e=Pf(Ge,Ne);R.rawContent=$e;let je=ee.get(R.id),st=vt=>{var we;let it=(we=R.content)!=null?we:"";vt.trim()!==""&&(it.trim().length===0||vt.startsWith(it)||vt.trimStart().startsWith(it.trim()))&&(R.content=vt)},It=()=>{var vt;if(je){let it=(vt=je.close)==null?void 0:vt.call(je);it instanceof Promise&&it.catch(()=>{})}ee.delete(R.id),ae.delete(R.id),R.streaming=!1,f(R)};if(!je){st(Ne),It();return}let Jt=qo($e);if(Jt!==null&&Jt.trim()!==""){st(Jt),It();return}let Yt=vt=>{var ie;let it=typeof vt=="string"?vt:(ie=vt==null?void 0:vt.text)!=null?ie:null;if(it!==null&&it.trim()!=="")return it;let we=je.getExtractedText();return we!==null&&we.trim()!==""?we:Ne},K;try{K=je.processChunk($e)}catch{st(Ne),It();return}if(K instanceof Promise){K.then(vt=>{st(Yt(vt)),It()}).catch(()=>{st(Ne),It()});return}st(Yt(K)),It()},De=[],z=!1,ue,rt=()=>{z||(z=!0,queueMicrotask(()=>{z=!1,ue()}))},kt=new ni((R,pe)=>{De.push({payloadType:R,payload:pe}),rt()}),te=null,Ve=new Map,Bn=(Bt=this.config.iterationDisplay)!=null?Bt:"separate";for(ue=()=>{var R,pe,Ne,Ge,$e,je,st,It,Jt,Yt,K,vt,it,we,ie,nt,Zt,Gt,kn,xn,ft,Lt,et,zt,cn,wn,Cn,yn,Er,St,_n,jn,Nr,hr,wt,Lo,Mr,Po,Dn,rs,no,Or,Tt,Un,qn,Ln,Pt,rr,or,zn,ro,Fr,oo,Vn,Dt,Pn,sr,so,$r,ao,kr,Kn,br,bt,en,tn,Jn,io,ye,ar,ir,_,Lr,_r,jr,Pr,yr,Bs,Gn,Xn,xr,vr,Io,Ur,An,Ir,os,Wo,ss,ka,as,La,is,xt,Ds,lr,Nn,Pa,Ia,ls,qr,Ns,lo,Os,Fs,$s,_s,On,cs,Wr,Rr,js,Wa,Us,qs,Ro,Ra,Ha,Ba,Da,ol,Ho,co,Na,zs,po,Oa,Vs,uo,Ks,Fa,zr,$a,mo,Nt,ds,ps,Js;for(let cr=0;cr<De.length;cr++){let Xe=De[cr].payloadType,A=De[cr].payload;if(Xe==="reason_start"){let j=(R=be(A,!0))!=null?R:`reason-${l()}`,L=ke(j);L.reasoning=(pe=L.reasoning)!=null?pe:{id:j,status:"streaming",chunks:[]},L.reasoning.startedAt=(Ge=L.reasoning.startedAt)!=null?Ge:He((Ne=A.startedAt)!=null?Ne:A.timestamp),L.reasoning.completedAt=void 0,L.reasoning.durationMs=void 0,L.streaming=!0,L.reasoning.status="streaming",f(L)}else if(Xe==="reason_delta"||Xe==="reason_chunk"){let j=(je=($e=be(A,!1))!=null?$e:be(A,!0))!=null?je:`reason-${l()}`,L=ke(j);L.reasoning=(st=L.reasoning)!=null?st:{id:j,status:"streaming",chunks:[]},L.reasoning.startedAt=(Jt=L.reasoning.startedAt)!=null?Jt:He((It=A.startedAt)!=null?It:A.timestamp);let Y=(vt=(K=(Yt=A.reasoningText)!=null?Yt:A.text)!=null?K:A.delta)!=null?vt:"";if(Y&&A.hidden!==!0){let oe=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(oe!==void 0){let G=fe(j,oe,String(Y));L.reasoning.chunks=[G]}else L.reasoning.chunks.push(String(Y))}if(L.reasoning.status=A.done?"complete":"streaming",A.done){L.reasoning.completedAt=He((it=A.completedAt)!=null?it:A.timestamp);let oe=(we=L.reasoning.startedAt)!=null?we:Date.now();L.reasoning.durationMs=Math.max(0,((ie=L.reasoning.completedAt)!=null?ie:Date.now())-oe)}L.streaming=L.reasoning.status!=="complete",f(L)}else if(Xe==="reason_complete"){let j=(Zt=(nt=be(A,!1))!=null?nt:be(A,!0))!=null?Zt:`reason-${l()}`,L=N.get(j);if(L!=null&&L.reasoning){L.reasoning.status="complete",L.reasoning.completedAt=He((Gt=A.completedAt)!=null?Gt:A.timestamp);let oe=(kn=L.reasoning.startedAt)!=null?kn:Date.now();L.reasoning.durationMs=Math.max(0,((xn=L.reasoning.completedAt)!=null?xn:Date.now())-oe),L.streaming=!1,f(L)}let Y=J(A);Y&&S.byStep.delete(Y)}else if(Xe==="tool_start"){let j=(ft=V(A,!0))!=null?ft:`tool-${l()}`,L=(Lt=A.toolName)!=null?Lt:A.name;if(ge(L)){de.add(j);continue}let Y=se(j),oe=(et=Y.toolCall)!=null?et:{id:j,status:"pending"};oe.name=L!=null?L:oe.name,oe.status="running",A.args!==void 0?oe.args=A.args:A.parameters!==void 0&&(oe.args=A.parameters),oe.startedAt=(cn=oe.startedAt)!=null?cn:He((zt=A.startedAt)!=null?zt:A.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,Y.toolCall=oe,Y.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(Y.agentMetadata={executionId:(wn=G==null?void 0:G.executionId)!=null?wn:A.executionId,iteration:(Cn=G==null?void 0:G.iteration)!=null?Cn:A.iteration}),f(Y)}else if(Xe==="tool_chunk"||Xe==="tool_delta"){let j=(Er=(yn=V(A,!1))!=null?yn:V(A,!0))!=null?Er:`tool-${l()}`;if(de.has(j))continue;let L=se(j),Y=(St=L.toolCall)!=null?St:{id:j,status:"running"};Y.startedAt=(jn=Y.startedAt)!=null?jn:He((_n=A.startedAt)!=null?_n:A.timestamp);let oe=(wt=(hr=(Nr=A.text)!=null?Nr:A.delta)!=null?hr:A.message)!=null?wt:"";oe&&(Y.chunks=(Lo=Y.chunks)!=null?Lo:[],Y.chunks.push(String(oe))),Y.status="running",L.toolCall=Y,L.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(L.agentMetadata=(Dn=L.agentMetadata)!=null?Dn:{executionId:(Mr=G==null?void 0:G.executionId)!=null?Mr:A.executionId,iteration:(Po=G==null?void 0:G.iteration)!=null?Po:A.iteration}),f(L)}else if(Xe==="tool_complete"){let j=(no=(rs=V(A,!1))!=null?rs:V(A,!0))!=null?no:`tool-${l()}`;if(de.has(j)){de.delete(j);continue}let L=se(j),Y=(Or=L.toolCall)!=null?Or:{id:j,status:"running"};Y.status="complete",A.result!==void 0&&(Y.result=A.result),typeof A.duration=="number"&&(Y.duration=A.duration),Y.completedAt=He((Tt=A.completedAt)!=null?Tt:A.timestamp);let oe=(Un=A.duration)!=null?Un:A.executionTime;if(typeof oe=="number")Y.durationMs=oe;else{let Fe=(qn=Y.startedAt)!=null?qn:Date.now();Y.durationMs=Math.max(0,((Ln=Y.completedAt)!=null?Ln:Date.now())-Fe)}L.toolCall=Y,L.streaming=!1;let G=A.agentContext;(G||A.executionId)&&(L.agentMetadata=(or=L.agentMetadata)!=null?or:{executionId:(Pt=G==null?void 0:G.executionId)!=null?Pt:A.executionId,iteration:(rr=G==null?void 0:G.iteration)!=null?rr:A.iteration}),f(L);let Pe=ce(A);Pe&&k.byCall.delete(Pe)}else if(Xe==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let j=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,L=(zn=j!=null?j:A.toolId)!=null?zn:`local-${l()}`,Y=se(L),oe=A.toolName,G=yo(oe),Pe=(ro=Y.toolCall)!=null?ro:{id:L,status:"pending"};Pe.name=oe,Pe.args=A.parameters,Pe.status=G?"running":"complete",Pe.chunks=(Fr=Pe.chunks)!=null?Fr:[],Pe.startedAt=(Vn=Pe.startedAt)!=null?Vn:He((oo=A.startedAt)!=null?oo:A.timestamp),G?(Pe.completedAt=void 0,Pe.duration=void 0,Pe.durationMs=void 0):Pe.completedAt=(Dt=Pe.completedAt)!=null?Dt:Pe.startedAt,Y.toolCall=Pe,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(sr=A.executionId)!=null?sr:(Pn=Y.agentMetadata)==null?void 0:Pn.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},f(Y)}else if(Xe==="text_start"){if((so=A.toolContext)!=null&&so.toolId)continue;let j=A.partId;if(j!==void 0&&w.current!==null&&j!==w.current){let L=m;L&&(L.streaming=!1,f(L),ve=L,m=null,T=!0)}j!==void 0&&(w.current=j)}else if(Xe==="text_end"){if(($r=A.toolContext)!=null&&$r.toolId)continue;let j=m;j&&(j.streaming=!1,f(j),ve=j,m=null,T=!0)}else if(Xe==="step_chunk"||Xe==="step_delta"){let j=A.stepType,L=A.executionType;if(j==="tool"||L==="context")continue;let Y=A.toolContext;if(Y!=null&&Y.toolId){let Fe=String((kr=(ao=A.id)!=null?ao:Y.stepId)!=null?kr:`step-${l()}`),lt=A.partId!==void 0&&A.partId!==null?String(A.partId):"",tt=`${Y.toolId}::${Fe}`,Ht=W.get(tt);if(lt!==""&&Ht!==void 0&&Ht!==""&&Ht!==lt){let ct=I.get($(Y.toolId,Fe,Ht));ct&&ct.streaming!==!1&&(ct.streaming=!1,f(ct))}lt!==""&&W.set(tt,lt);let jt=H(Y.toolId,Fe,lt,Y.executionId),$t=(en=(bt=(br=(Kn=A.text)!=null?Kn:A.delta)!=null?br:A.content)!=null?bt:A.chunk)!=null?en:"";$t&&(jt.content+=String($t),jt.streaming=!0,f(jt)),A.isComplete&&(jt.streaming=!1,f(jt));continue}let oe=A.partId;if(oe!==void 0&&w.current!==null&&oe!==w.current){let Fe=m;Fe&&(Fe.streaming=!1,f(Fe),ve=Fe,m=null,T=!0)}oe!==void 0&&(w.current=oe);let G=oe!==void 0&&(tn=Ze.get(oe))!=null?tn:Ae();oe!==void 0&&(G.partId||(G.partId=oe),Ze.set(oe,G));let Pe=(ar=(ye=(io=(Jn=A.text)!=null?Jn:A.delta)!=null?io:A.content)!=null?ye:A.chunk)!=null?ar:"";if(Pe){let Fe=typeof A.seq=="number"?A.seq:void 0,lt=oe!=null?oe:G.id,tt=Fe!==void 0?fe(lt,Fe,String(Pe)):((ir=ae.get(G.id))!=null?ir:"")+Pe;G.rawContent=tt,ee.has(G.id)||ee.set(G.id,this.createStreamParser());let Ht=ee.get(G.id),jt=tt.trim().startsWith("{")||tt.trim().startsWith("[");if(jt&&ae.set(G.id,tt),Ht.__isPlainTextParser===!0){G.content=Fe!==void 0?tt:G.content+Pe,ae.delete(G.id),ee.delete(G.id),G.rawContent=void 0,f(G);continue}let ct=Ht.processChunk(tt);if(ct instanceof Promise)ct.then(Et=>{var Sn;let Ue=typeof Et=="string"?Et:(Sn=Et==null?void 0:Et.text)!=null?Sn:null;if(Ue!==null&&Ue.trim()!=="")G.content=Ue,f(G);else if(!jt&&!tt.trim().startsWith("<")){let fn=m,Ut=fn&&fn.id===G.id?fn:G;Ut.id===G.id&&(Ut.content=Fe!==void 0?tt:Ut.content+Pe,ae.delete(Ut.id),ee.delete(Ut.id),Ut.rawContent=void 0,f(Ut))}}).catch(()=>{G.content=Fe!==void 0?tt:G.content+Pe,ae.delete(G.id),ee.delete(G.id),G.rawContent=void 0,f(G)});else{let Et=typeof ct=="string"?ct:(_=ct==null?void 0:ct.text)!=null?_:null;Et!==null&&Et.trim()!==""?(G.content=Et,f(G)):!jt&&!tt.trim().startsWith("<")&&(G.content=Fe!==void 0?tt:G.content+Pe,ae.delete(G.id),ee.delete(G.id),G.rawContent=void 0,f(G))}}if(A.isComplete){let Fe=(_r=(Lr=A.result)==null?void 0:Lr.response)!=null?_r:G.content;if(Fe){let lt=ae.get(G.id),tt=lt!=null?lt:Z(Fe);G.rawContent=tt;let Ht=ee.get(G.id),jt=null,$t=!1;if(Ht&&(jt=Ht.getExtractedText(),jt===null&&(jt=qo(tt)),jt===null)){let ct=Ht.processChunk(tt);ct instanceof Promise?($t=!0,ct.then(Et=>{var Sn;let Ue=typeof Et=="string"?Et:(Sn=Et==null?void 0:Et.text)!=null?Sn:null;if(Ue!==null){let fn=m;fn&&fn.id===G.id&&(fn.content=Ue,fn.streaming=!1,ee.delete(fn.id),ae.delete(fn.id),f(fn))}})):jt=typeof ct=="string"?ct:(jr=ct==null?void 0:ct.text)!=null?jr:null}if(!$t){jt!==null&&jt.trim()!==""?G.content=jt:ae.has(G.id)||(G.content=Z(Fe));let ct=ee.get(G.id);if(ct){let Et=(Pr=ct.close)==null?void 0:Pr.call(ct);Et instanceof Promise&&Et.catch(()=>{}),ee.delete(G.id)}ae.delete(G.id),G.streaming=!1,f(G)}}}}else if(Xe==="step_complete"){let j=A.stepType,L=A.executionType;if(j==="tool"||L==="context")continue;let Y=A.toolContext;if(Y!=null&&Y.toolId){let Fe=String((Bs=(yr=A.id)!=null?yr:Y.stepId)!=null?Bs:"");if(Fe){let lt=O(Y.toolId,Fe);for(let[tt,Ht]of I)tt.startsWith(lt)&&Ht.streaming!==!1&&(Ht.streaming=!1,f(Ht));W.delete(`${Y.toolId}::${Fe}`)}continue}let oe=A.stopReason;if(T){if(m!==null){let tt=m;oe&&(tt.stopReason=oe),ee.delete(tt.id),ae.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,f(tt))}let Fe=(Gn=A.result)==null?void 0:Gn.response,lt=ve;lt&&(oe&&(lt.stopReason=oe),Fe!=null?Je(lt,Fe):(ee.delete(lt.id),ae.delete(lt.id))),ve=null;continue}let G=(Xn=A.result)==null?void 0:Xn.response,Pe=Ae();if(oe&&(Pe.stopReason=oe),G!=null){let Fe=ee.get(Pe.id),lt=!1,tt=!1;if(Fe){let Ht=Fe.getExtractedText(),jt=ae.get(Pe.id),$t=jt!=null?jt:Z(G);if(Pe.rawContent=$t,Ht!==null&&Ht.trim()!=="")Pe.content=Ht,lt=!0;else{let ct=qo($t);if(ct!==null)Pe.content=ct,lt=!0;else{let Et=Fe.processChunk($t);if(Et instanceof Promise)tt=!0,Et.then(Ue=>{var fn;let Sn=typeof Ue=="string"?Ue:(fn=Ue==null?void 0:Ue.text)!=null?fn:null;if(Sn!==null&&Sn.trim()!==""){let Ut=m;Ut&&Ut.id===Pe.id&&(Ut.content=Sn,Ut.streaming=!1,ee.delete(Ut.id),ae.delete(Ut.id),f(Ut))}else{let Ut=Fe.getExtractedText(),wr=m;wr&&wr.id===Pe.id&&(Ut!==null&&Ut.trim()!==""?wr.content=Ut:ae.has(wr.id)||(wr.content=Z(G)),wr.streaming=!1,ee.delete(wr.id),ae.delete(wr.id),f(wr))}});else{let Ue=typeof Et=="string"?Et:(xr=Et==null?void 0:Et.text)!=null?xr:null;if(Ue!==null&&Ue.trim()!=="")Pe.content=Ue,lt=!0;else{let Sn=Fe.getExtractedText();Sn!==null&&Sn.trim()!==""&&(Pe.content=Sn,lt=!0)}}}}}if(!tt){if(!Pe.rawContent){let Ht=ae.get(Pe.id);Pe.rawContent=Ht!=null?Ht:Z(G)}if(!lt&&!ae.has(Pe.id)&&(Pe.content=Z(G)),Fe){let Ht=(vr=Fe.close)==null?void 0:vr.call(Fe);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(Pe.id),ae.delete(Pe.id),Pe.streaming=!1,f(Pe)}}else ee.delete(Pe.id),ae.delete(Pe.id),Pe.streaming=!1,f(Pe)}else if(Xe==="flow_complete"){let j=(Io=A.result)==null?void 0:Io.response;if(T){if(m!==null){let L=m;ee.delete(L.id),ae.delete(L.id),L.streaming!==!1&&(L.streaming=!1,f(L))}}else if(j!=null){let L=Ae(),Y=ae.get(L.id),oe=Y!=null?Y:Z(j);L.rawContent=oe;let G=Z(j),Pe=ee.get(L.id);if(Pe){let tt=qo(oe);if(tt!==null)G=tt;else{let Ht=Pe.processChunk(oe);Ht instanceof Promise&&Ht.then($t=>{var Et;let ct=typeof $t=="string"?$t:(Et=$t==null?void 0:$t.text)!=null?Et:null;ct!==null&&(L.content=ct,L.streaming=!1,f(L))});let jt=Pe.getExtractedText();jt!==null&&(G=jt)}}ee.delete(L.id),ae.delete(L.id);let Fe=G!==L.content,lt=L.streaming!==!1;Fe&&(L.content=G),L.streaming=!1,(Fe||lt)&&f(L)}else if(m!==null){let L=m;ee.delete(L.id),ae.delete(L.id),L.streaming!==!1&&(L.streaming=!1,f(L))}n({type:"status",status:"idle"})}else if(Xe==="agent_start")te={executionId:A.executionId,agentId:(Ur=A.agentId)!=null?Ur:"virtual",agentName:(An=A.agentName)!=null?An:"",status:"running",currentIteration:0,maxTurns:(Ir=A.maxTurns)!=null?Ir:1,startedAt:He(A.startedAt)};else if(Xe==="agent_iteration_start"){if(te&&(te.currentIteration=A.iteration),Bn==="separate"&&A.iteration>1){let j=m;j&&(j.streaming=!1,f(j),Ve.set(A.iteration-1,j),m=null)}}else if(Xe==="agent_turn_start")v=null;else if(Xe==="agent_turn_delta"){if(A.contentType==="text"){let j=Ae();j.content+=(os=A.delta)!=null?os:"",j.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:te==null?void 0:te.agentName},v=j,f(j)}else if(A.contentType==="thinking"){let j=(Wo=A.turnId)!=null?Wo:`agent-think-${A.iteration}`,L=ke(j);L.reasoning=(ss=L.reasoning)!=null?ss:{id:j,status:"streaming",chunks:[]},L.reasoning.chunks.push((ka=A.delta)!=null?ka:""),L.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},f(L)}else if(A.contentType==="tool_input"){let j=(as=A.toolCallId)!=null?as:k.lastId;if(j){let L=M.get(j);L!=null&&L.toolCall&&(L.toolCall.chunks=(La=L.toolCall.chunks)!=null?La:[],L.toolCall.chunks.push((is=A.delta)!=null?is:""),f(L))}}}else if(Xe==="agent_turn_complete"){let j=A.turnId;if(j){let oe=N.get(j);if(oe!=null&&oe.reasoning){oe.reasoning.status="complete",oe.reasoning.completedAt=He(A.completedAt);let G=(xt=oe.reasoning.startedAt)!=null?xt:Date.now();oe.reasoning.durationMs=Math.max(0,((Ds=oe.reasoning.completedAt)!=null?Ds:Date.now())-G),oe.streaming=!1,f(oe)}}let L=A.stopReason,Y=m!=null?m:v;if(L&&Y!==null){let oe=A.turnId;(!oe||((lr=Y.agentMetadata)==null?void 0:lr.turnId)===oe)&&(Y.stopReason=L,f(Y))}}else if(Xe==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let j=(Nn=A.toolCallId)!=null?Nn:`agent-tool-${l()}`;Re(ce(A),j);let L=se(j),Y=(Pa=L.toolCall)!=null?Pa:{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};Y.name=(ls=(Ia=A.toolName)!=null?Ia:A.name)!=null?ls:Y.name,Y.status="running",A.parameters!==void 0&&(Y.args=A.parameters),Y.startedAt=He((qr=A.startedAt)!=null?qr:A.timestamp),L.toolCall=Y,L.streaming=!0,L.agentMetadata={executionId:A.executionId,iteration:A.iteration},f(L)}else if(Xe==="agent_tool_delta"){let j=(Ns=A.toolCallId)!=null?Ns:k.lastId;if(j){let L=(lo=M.get(j))!=null?lo:se(j);L.toolCall&&(L.toolCall.chunks=(Os=L.toolCall.chunks)!=null?Os:[],L.toolCall.chunks.push((Fs=A.delta)!=null?Fs:""),L.toolCall.status="running",L.streaming=!0,f(L))}}else if(Xe==="agent_tool_complete"){let j=($s=A.toolCallId)!=null?$s:k.lastId;if(j){let L=(_s=M.get(j))!=null?_s:se(j);if(L.toolCall){L.toolCall.status="complete",A.result!==void 0&&(L.toolCall.result=A.result),typeof A.executionTime=="number"&&(L.toolCall.durationMs=A.executionTime),L.toolCall.completedAt=He((On=A.completedAt)!=null?On:A.timestamp),L.streaming=!1,f(L);let Y=ce(A);Y&&k.byCall.delete(Y)}}}else if(Xe==="agent_media"){let j=Array.isArray(A.media)?A.media:[],L=[];for(let Y of j){if(!Y||typeof Y!="object")continue;let oe=Y,G=typeof oe.type=="string"?oe.type:void 0,Pe=typeof oe.mediaType=="string"?oe.mediaType.toLowerCase():"",Fe=null,lt="";if(G==="media"){let tt=typeof oe.data=="string"?oe.data:void 0;if(!tt)continue;lt=Pe.length>0?Pe:"application/octet-stream",Fe=`data:${lt};base64,${tt}`}else if(G==="image-url"){let tt=typeof oe.url=="string"?oe.url:void 0;if(!tt)continue;lt=Pe,Fe=tt}else if(G==="file-url"){let tt=typeof oe.url=="string"?oe.url:void 0;if(!tt)continue;lt=Pe,Fe=tt}else continue;if(Fe)if(G==="image-url"||lt.startsWith("image/"))L.push({type:"image",image:Fe,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))L.push({type:"audio",audio:Fe,mimeType:lt});else if(lt.startsWith("video/"))L.push({type:"video",video:Fe,mimeType:lt});else{let tt=lt||"application/octet-stream";L.push({type:"file",data:Fe,mimeType:tt,filename:kf(tt)})}}if(L.length>0){let Y=l(),oe=A.toolCallId,Pe={id:`agent-media-${typeof oe=="string"&&oe.length>0?`${oe}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:L,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(Pe);let Fe=m;Fe&&(Fe.streaming=!1,f(Fe)),m=null,x.current=null}}else if(Xe!=="agent_iteration_complete"){if(Xe==="agent_reflection"||Xe==="agent_reflect"){let j=`agent-reflection-${A.executionId}-${A.iteration}`,L={id:j,role:"assistant",content:(cs=A.reflection)!=null?cs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(Wr=A.reflection)!=null?Wr:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(L)}else if(Xe==="agent_complete"){te&&(te.status=A.success?"complete":"error",te.completedAt=He(A.completedAt),te.stopReason=A.stopReason);let j=m;j&&(j.streaming=!1,f(j)),n({type:"status",status:"idle"})}else if(Xe==="agent_error"){let j=typeof A.error=="string"?A.error:(js=(Rr=A.error)==null?void 0:Rr.message)!=null?js:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):n({type:"error",error:new Error(j)})}else if(Xe!=="agent_ping"){if(Xe==="agent_approval_start"){let j=(Wa=A.approvalId)!=null?Wa:`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:(Us=te==null?void 0:te.agentId)!=null?Us:"virtual",executionId:(Ro=(qs=A.executionId)!=null?qs:te==null?void 0:te.executionId)!=null?Ro:"",toolName:(Ra=A.toolName)!=null?Ra:"",toolType:A.toolType,description:(Ba=A.description)!=null?Ba:`Execute ${(Ha=A.toolName)!=null?Ha:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};f(L)}else if(Xe==="step_await"&&A.awaitReason==="approval_required"){let j=(Da=A.approvalId)!=null?Da:`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:(ol=te==null?void 0:te.agentId)!=null?ol:"virtual",executionId:(co=(Ho=A.executionId)!=null?Ho:te==null?void 0:te.executionId)!=null?co:"",toolName:(Na=A.toolName)!=null?Na:"",toolType:A.toolType,description:(po=A.description)!=null?po:`Execute ${(zs=A.toolName)!=null?zs:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};f(L)}else if(Xe==="agent_approval_complete"){let j=A.approvalId;if(j){let Y={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(Oa=A.decision)!=null?Oa:"approved",agentId:(Vs=te==null?void 0:te.agentId)!=null?Vs:"virtual",executionId:(Ks=(uo=A.executionId)!=null?uo:te==null?void 0:te.executionId)!=null?Ks:"",toolName:(Fa=A.toolName)!=null?Fa:"",description:(zr=A.description)!=null?zr:"",resolvedAt:Date.now()}};f(Y)}}else if(Xe==="artifact_start"||Xe==="artifact_delta"||Xe==="artifact_update"||Xe==="artifact_complete"){if(Xe==="artifact_start"){let j=A.artifactType,L=String(A.id),Y=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:L,artifactType:j,title:Y,component:typeof A.component=="string"?A.component:void 0}),le.set(L,{markdown:"",title:Y}),!re.has(L)){re.add(L);let oe={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:L,title:Y,artifactType:j,status:"streaming"}})};Q.set(L,oe),f(oe)}}else if(Xe==="artifact_delta"){let j=String(A.id),L=typeof A.delta=="string"?A.delta:String(($a=A.delta)!=null?$a:"");n({type:"artifact_delta",id:j,artDelta:L});let Y=le.get(j);Y&&(Y.markdown+=L)}else if(Xe==="artifact_update"){let j=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:j,component:typeof A.component=="string"?A.component:void 0})}else if(Xe==="artifact_complete"){let j=String(A.id);n({type:"artifact_complete",id:j});let L=Q.get(j);if(L){L.streaming=!1;try{let Y=JSON.parse((mo=L.rawContent)!=null?mo:"{}");if(Y.props){Y.props.status="complete";let oe=le.get(j);oe!=null&&oe.markdown&&(Y.props.markdown=oe.markdown)}L.rawContent=JSON.stringify(Y)}catch{}le.delete(j),f(L),Q.delete(j)}}}else if(Xe==="transcript_insert"){let j=A.message;if(!j||typeof j!="object")continue;let L=String((Nt=j.id)!=null?Nt:`msg-${l()}`),Y=j.role,G={id:L,role:Y==="user"?"user":Y==="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(f(G),G.rawContent)try{let Pe=JSON.parse(G.rawContent),Fe=(ds=Pe==null?void 0:Pe.props)==null?void 0:ds.artifactId;typeof Fe=="string"&&re.add(Fe)}catch{}m=null,x.current=null,ee.delete(L),ae.delete(L)}else if(Xe==="error"||Xe==="step_error"||Xe==="dispatch_error"||Xe==="flow_error"){let j=null;if(A.error instanceof Error)j=A.error;else if(Xe==="dispatch_error"){let L=(ps=A.message)!=null?ps:A.error;L!=null&&L!==""&&(j=new Error(String(L)))}else if(Xe==="step_error"||Xe==="flow_error"){let L=A.error;typeof L=="string"&&L!==""?j=new Error(L):L!=null&&typeof L=="object"&&"message"in L&&(j=new Error(String((Js=L.message)!=null?Js:L)))}else Xe==="error"&&A.error!=null&&A.error!==""&&(j=new Error(String(A.error)));if(j){n({type:"error",error:j});let L=m;L&&L.streaming&&(L.streaming=!1,f(L)),n({type:"status",status:"idle"})}}}}}De.length=0};;){let{done:R,value:pe}=await o.read();if(R)break;a+=s.decode(pe,{stream:!0});let Ne=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 o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Ko=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ci=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=ah();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)}},pi=()=>{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 o=(0,Xr.parse)(n,Xr.STR|Xr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?si(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=si(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},am=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?si(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?si(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Xr.parse)(s,Xr.STR|Xr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ui=()=>{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 mi=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 s,a,i;let r=(i=(s=n==null?void 0:n.seq)!=null?s: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 o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.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 ih="https://api.runtype.com/v1/dispatch",gi="https://api.runtype.com";function lh(e){var s,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 o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Il=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 ch(e){switch(e){case"json":return pi;case"regex-json":return di;case"xml":return ui;default:return ci}}var im=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function dh(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 o=im(n);if(!im(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Ko(e);return Ko(t)!==null&&a===null?t:e}var Go=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;this.apiUrl=(n=t.apiUrl)!=null?n:ih,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:ch(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new vs(t.webmcp):null}updateConfig(t){this.config=t}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$/,""))||gi}/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 s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||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 o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.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$/,""))||gi}/v1/client/feedback`}async sendFeedback(t){var s,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 o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),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 o,s,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(),(s=(o=this.config).onSessionExpired)==null||s.call(o);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,u={sessionId:d.sessionId,messages:t.messages.filter(Il).map(I=>{var R,T,W;return{id:I.id,role:I.role,content:(W=(T=(R=I.contentParts)!=null?R:I.llmContent)!=null?T: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}},f=l.clientTools,g=!!(f&&f.length>0),v=g?ju(f):void 0,y=this.clientToolsFingerprintSessionId===d.sessionId,w=g&&y&&this.lastSentClientToolsFingerprint===v,S=!1,O=null,k;for(let I=0;;I++){let T={...u,...g&&(S||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",T),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T),signal:r.signal}),k.status===409&&I===0&&g){let W=await k.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){S=!0,this.lastSentClientToolsFingerprint=null;continue}O=W!=null?W:{error:"Chat request failed"}}break}if(!k.ok){let I=O!=null?O:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let T=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:T}),T}if(k.status===429){let T=new Error(I.hint||"Message limit reached for this session.");throw n({type:"error",error:T}),T}let R=new Error(I.error||"Failed to send message");throw n({type:"error",error:R}),R}if(!k.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(k.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 o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...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:s,body:JSON.stringify(o),signal:r.signal},o)}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:s,body:JSON.stringify(o),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 o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...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:s,body:JSON.stringify(o),signal:r.signal},o)}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:s,body:JSON.stringify(o),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 o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||gi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||gi}/resume`,a;o&&(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(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Il).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...la(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var s,a;let r={messages:t.slice().filter(Il).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...la(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},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,o(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,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(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 Ht,cn,sr,Er;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=H=>{let pe=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,Oe=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,Qe=H.tools?H.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...H,reasoning:pe,toolCall:Oe,tools:Qe}},u=H=>{if(H.role!=="assistant"||H.variant)return!0;let pe=Array.isArray(H.contentParts)&&H.contentParts.length>0,Oe=typeof H.rawContent=="string"&&H.rawContent.trim()!=="";return typeof H.content=="string"&&H.content.trim()!==""||pe||Oe||!!H.stopReason},f=H=>{u(H)&&n({type:"message",message:p(H)})},g=null,v=null,y={current:null},w={current:null},S=!1,O=new Map,k=new Map,I=new Map,R=new Map,T={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},_=(H,pe,Oe="")=>`${H}::${pe}::${Oe}`,F=(H,pe)=>`${H}::${pe}::`,M=(H,pe,Oe,Qe)=>{let _e=_(H,pe,Oe),Ue=I.get(_e);if(Ue)return Ue;let at=Oe?`-${Oe}`:"",Pt={id:`nested-${H}-${pe}${at}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Oe?{partId:Oe}:{},agentMetadata:{executionId:Qe,parentToolId:H,parentStepId:pe}};return I.set(_e,Pt),f(Pt),Pt},j=H=>{if(H==null)return null;try{return String(H)}catch{return null}},z=H=>{var pe,Oe,Qe,_e,Ue;return j((Ue=(_e=(Qe=(Oe=(pe=H.stepId)!=null?pe:H.step_id)!=null?Oe:H.step)!=null?Qe:H.parentId)!=null?_e:H.flowStepId)!=null?Ue:H.flow_step_id)},oe=H=>{var pe,Oe,Qe,_e,Ue,at,Pt;return j((Pt=(at=(Ue=(_e=(Qe=(Oe=(pe=H.callId)!=null?pe:H.call_id)!=null?Oe:H.requestId)!=null?Qe:H.request_id)!=null?_e:H.toolCallId)!=null?Ue:H.tool_call_id)!=null?at:H.stepId)!=null?Pt:H.step_id)},ke=r,ze=!1,Ae=()=>{if(g)return g;let H;return!ze&&ke?(H=ke,ze=!0):ke&&w.current?H=`${ke}_${w.current}`:H=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:H,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(g),g},Re=(H,pe)=>{T.lastId=pe,H&&T.byStep.set(H,pe)},be=(H,pe)=>{var Ue;let Oe=(Ue=H.reasoningId)!=null?Ue:H.id,Qe=z(H);if(Oe){let at=String(Oe);return Re(Qe,at),at}if(Qe){let at=T.byStep.get(Qe);if(at)return T.lastId=at,at}if(T.lastId&&!pe)return T.lastId;if(!pe)return null;let _e=`reason-${l()}`;return Re(Qe,_e),_e},Le=H=>{let pe=O.get(H);if(pe)return pe;let Oe={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:H,status:"streaming",chunks:[]}};return O.set(H,Oe),f(Oe),Oe},We=(H,pe)=>{W.lastId=pe,H&&W.byCall.set(H,pe)},de=new Set,X=new Map,re=new Set,ce=new Map,ge=H=>{if(!H)return!1;let pe=H.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},K=(H,pe)=>{var Ue;let Oe=(Ue=H.toolId)!=null?Ue:H.id,Qe=oe(H);if(Oe){let at=String(Oe);return We(Qe,at),at}if(Qe){let at=W.byCall.get(Qe);if(at)return W.lastId=at,at}if(W.lastId&&!pe)return W.lastId;if(!pe)return null;let _e=`tool-${l()}`;return We(Qe,_e),_e},ae=H=>{let pe=k.get(H);if(pe)return pe;let Oe={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:H,status:"pending"}};return k.set(H,Oe),f(Oe),Oe},He=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let pe=Number(H);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let Oe=Date.parse(H);if(!Number.isNaN(Oe))return Oe}return Date.now()},Y=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},ee=new Map,ie=new Map,Se=new Map,Ze=new Map,ve=null,fe=(H,pe,Oe)=>{var Pt;let Qe=Se.get(H);Qe||(Qe=[],Se.set(H,Qe));let _e=0,Ue=Qe.length;for(;_e<Ue;){let Kt=_e+Ue>>>1;Qe[Kt].seq<pe?_e=Kt+1:Ue=Kt}((Pt=Qe[_e])==null?void 0:Pt.seq)===pe?Qe[_e]={seq:pe,text:Oe}:Qe.splice(_e,0,{seq:pe,text:Oe});let at="";for(let Kt=0;Kt<Qe.length;Kt++)at+=Qe[Kt].text;return at},Je=(H,pe)=>{let Oe=Y(pe),Qe=ie.get(H.id),_e=dh(Qe,Oe);H.rawContent=_e;let Ue=ee.get(H.id),at=xt=>{var we;let lt=(we=H.content)!=null?we:"";xt.trim()!==""&&(lt.trim().length===0||xt.startsWith(lt)||xt.trimStart().startsWith(lt.trim()))&&(H.content=xt)},Pt=()=>{var xt;if(Ue){let lt=(xt=Ue.close)==null?void 0:xt.call(Ue);lt instanceof Promise&&lt.catch(()=>{})}ee.delete(H.id),ie.delete(H.id),H.streaming=!1,f(H)};if(!Ue){at(Oe),Pt();return}let Kt=Ko(_e);if(Kt!==null&&Kt.trim()!==""){at(Kt),Pt();return}let Zt=xt=>{var le;let lt=typeof xt=="string"?xt:(le=xt==null?void 0:xt.text)!=null?le:null;if(lt!==null&&lt.trim()!=="")return lt;let we=Ue.getExtractedText();return we!==null&&we.trim()!==""?we:Oe},G;try{G=Ue.processChunk(_e)}catch{at(Oe),Pt();return}if(G instanceof Promise){G.then(xt=>{at(Zt(xt)),Pt()}).catch(()=>{at(Oe),Pt()});return}at(Zt(G)),Pt()},De=[],V=!1,ue,ot=()=>{V||(V=!0,queueMicrotask(()=>{V=!1,ue()}))},Et=new mi((H,pe)=>{De.push({payloadType:H,payload:pe}),ot()}),ne=null,Ve=new Map,Nn=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(ue=()=>{var H,pe,Oe,Qe,_e,Ue,at,Pt,Kt,Zt,G,xt,lt,we,le,nt,tn,Gt,Pn,wn,mt,Mt,et,qt,dn,An,Sn,yn,Mr,At,jn,qn,Nr,fr,vt,Lo,kr,Po,Fn,ss,ro,Fr,St,zn,Vn,In,Lt,ar,ir,Kn,oo,_r,so,Gn,Bt,Rn,lr,ao,$r,io,Lr,Jn,hr,ft,nn,rn,Qn,lo,ye,br,cr,$,as,Pr,Ur,jr,Ir,yr,Ns,Xn,Yn,xr,vr,Io,qr,Tn,Rr,is,Ro,ls,Ba,cs,Da,ds,yt,Fs,dr,_n,Oa,Na,ps,zr,_s,co,$s,Us,js,qs,$n,us,Wr,Hr,zs,Fa,Vs,Ks,Wo,_a,$a,Ua,ja,pl,Ho,po,qa,Gs,uo,za,Js,mo,Qs,Va,Vr,Ka,go,Dt,ms,gs;for(let Bo=0;Bo<De.length;Bo++){let je=De[Bo].payloadType,A=De[Bo].payload;if(je==="reason_start"){let U=(H=be(A,!0))!=null?H:`reason-${l()}`,L=Le(U);L.reasoning=(pe=L.reasoning)!=null?pe:{id:U,status:"streaming",chunks:[]},L.reasoning.startedAt=(Qe=L.reasoning.startedAt)!=null?Qe:He((Oe=A.startedAt)!=null?Oe:A.timestamp),L.reasoning.completedAt=void 0,L.reasoning.durationMs=void 0,L.streaming=!0,L.reasoning.status="streaming",f(L)}else if(je==="reason_delta"||je==="reason_chunk"){let U=(Ue=(_e=be(A,!1))!=null?_e:be(A,!0))!=null?Ue:`reason-${l()}`,L=Le(U);L.reasoning=(at=L.reasoning)!=null?at:{id:U,status:"streaming",chunks:[]},L.reasoning.startedAt=(Kt=L.reasoning.startedAt)!=null?Kt:He((Pt=A.startedAt)!=null?Pt:A.timestamp);let Z=(xt=(G=(Zt=A.reasoningText)!=null?Zt:A.text)!=null?G:A.delta)!=null?xt:"";if(Z&&A.hidden!==!0){let se=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(se!==void 0){let J=fe(U,se,String(Z));L.reasoning.chunks=[J]}else L.reasoning.chunks.push(String(Z))}if(L.reasoning.status=A.done?"complete":"streaming",A.done){L.reasoning.completedAt=He((lt=A.completedAt)!=null?lt:A.timestamp);let se=(we=L.reasoning.startedAt)!=null?we:Date.now();L.reasoning.durationMs=Math.max(0,((le=L.reasoning.completedAt)!=null?le:Date.now())-se)}L.streaming=L.reasoning.status!=="complete",f(L)}else if(je==="reason_complete"){let U=(tn=(nt=be(A,!1))!=null?nt:be(A,!0))!=null?tn:`reason-${l()}`,L=O.get(U);if(L!=null&&L.reasoning){L.reasoning.status="complete",L.reasoning.completedAt=He((Gt=A.completedAt)!=null?Gt:A.timestamp);let se=(Pn=L.reasoning.startedAt)!=null?Pn:Date.now();L.reasoning.durationMs=Math.max(0,((wn=L.reasoning.completedAt)!=null?wn:Date.now())-se),L.streaming=!1,f(L)}let Z=z(A);Z&&T.byStep.delete(Z)}else if(je==="tool_start"){let U=(mt=K(A,!0))!=null?mt:`tool-${l()}`,L=(Mt=A.toolName)!=null?Mt:A.name;if(ge(L)){de.add(U);continue}let Z=ae(U),se=(et=Z.toolCall)!=null?et:{id:U,status:"pending"};se.name=L!=null?L:se.name,se.status="running",A.args!==void 0?se.args=A.args:A.parameters!==void 0&&(se.args=A.parameters),se.startedAt=(dn=se.startedAt)!=null?dn:He((qt=A.startedAt)!=null?qt:A.timestamp),se.completedAt=void 0,se.durationMs=void 0,Z.toolCall=se,Z.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(Z.agentMetadata={executionId:(An=J==null?void 0:J.executionId)!=null?An:A.executionId,iteration:(Sn=J==null?void 0:J.iteration)!=null?Sn:A.iteration}),f(Z)}else if(je==="tool_chunk"||je==="tool_delta"){let U=(Mr=(yn=K(A,!1))!=null?yn:K(A,!0))!=null?Mr:`tool-${l()}`;if(de.has(U))continue;let L=ae(U),Z=(At=L.toolCall)!=null?At:{id:U,status:"running"};Z.startedAt=(qn=Z.startedAt)!=null?qn:He((jn=A.startedAt)!=null?jn:A.timestamp);let se=(vt=(fr=(Nr=A.text)!=null?Nr:A.delta)!=null?fr:A.message)!=null?vt:"";se&&(Z.chunks=(Lo=Z.chunks)!=null?Lo:[],Z.chunks.push(String(se))),Z.status="running",L.toolCall=Z,L.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(L.agentMetadata=(Fn=L.agentMetadata)!=null?Fn:{executionId:(kr=J==null?void 0:J.executionId)!=null?kr:A.executionId,iteration:(Po=J==null?void 0:J.iteration)!=null?Po:A.iteration}),f(L)}else if(je==="tool_complete"){let U=(ro=(ss=K(A,!1))!=null?ss:K(A,!0))!=null?ro:`tool-${l()}`;if(de.has(U)){de.delete(U);continue}let L=ae(U),Z=(Fr=L.toolCall)!=null?Fr:{id:U,status:"running"};Z.status="complete",A.result!==void 0&&(Z.result=A.result),typeof A.duration=="number"&&(Z.duration=A.duration),Z.completedAt=He((St=A.completedAt)!=null?St:A.timestamp);let se=(zn=A.duration)!=null?zn:A.executionTime;if(typeof se=="number")Z.durationMs=se;else{let Fe=(Vn=Z.startedAt)!=null?Vn:Date.now();Z.durationMs=Math.max(0,((In=Z.completedAt)!=null?In:Date.now())-Fe)}L.toolCall=Z,L.streaming=!1;let J=A.agentContext;(J||A.executionId)&&(L.agentMetadata=(ir=L.agentMetadata)!=null?ir:{executionId:(Lt=J==null?void 0:J.executionId)!=null?Lt:A.executionId,iteration:(ar=J==null?void 0:J.iteration)!=null?ar:A.iteration}),f(L);let Me=oe(A);Me&&W.byCall.delete(Me)}else if(je==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,L=(Kn=U!=null?U:A.toolId)!=null?Kn:`local-${l()}`,Z=ae(L),se=A.toolName,J=zo(se),Me=(oo=Z.toolCall)!=null?oo:{id:L,status:"pending"};Me.name=se,Me.args=A.parameters,Me.status=J?"running":"complete",Me.chunks=(_r=Me.chunks)!=null?_r:[],Me.startedAt=(Gn=Me.startedAt)!=null?Gn:He((so=A.startedAt)!=null?so:A.timestamp),J?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=(Bt=Me.completedAt)!=null?Bt:Me.startedAt,Z.toolCall=Me,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(lr=A.executionId)!=null?lr:(Rn=Z.agentMetadata)==null?void 0:Rn.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(Z)}else if(je==="text_start"){if((ao=A.toolContext)!=null&&ao.toolId)continue;let U=A.partId;if(U!==void 0&&w.current!==null&&U!==w.current){let L=g;L&&(L.streaming=!1,f(L),ve=L,g=null,S=!0)}U!==void 0&&(w.current=U)}else if(je==="text_end"){if(($r=A.toolContext)!=null&&$r.toolId)continue;let U=g;U&&(U.streaming=!1,f(U),ve=U,g=null,S=!0)}else if(je==="step_chunk"||je==="step_delta"){let U=A.stepType,L=A.executionType;if(U==="tool"||L==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Lr=(io=A.id)!=null?io:Z.stepId)!=null?Lr:`step-${l()}`),ct=A.partId!==void 0&&A.partId!==null?String(A.partId):"",tt=`${Z.toolId}::${Fe}`,Wt=R.get(tt);if(ct!==""&&Wt!==void 0&&Wt!==""&&Wt!==ct){let it=I.get(_(Z.toolId,Fe,Wt));it&&it.streaming!==!1&&(it.streaming=!1,f(it))}ct!==""&&R.set(tt,ct);let $t=M(Z.toolId,Fe,ct,Z.executionId),gn=(nn=(ft=(hr=(Jn=A.text)!=null?Jn:A.delta)!=null?hr:A.content)!=null?ft:A.chunk)!=null?nn:"";gn&&($t.content+=String(gn),$t.streaming=!0,f($t)),A.isComplete&&($t.streaming=!1,f($t));continue}let se=A.partId;if(se!==void 0&&w.current!==null&&se!==w.current){let Fe=g;Fe&&(Fe.streaming=!1,f(Fe),ve=Fe,g=null,S=!0)}se!==void 0&&(w.current=se);let J=se!==void 0&&(rn=Ze.get(se))!=null?rn:Ae();se!==void 0&&(J.partId||(J.partId=se),Ze.set(se,J));let Me=(br=(ye=(lo=(Qn=A.text)!=null?Qn:A.delta)!=null?lo:A.content)!=null?ye:A.chunk)!=null?br:"";if(Me){let Fe=typeof A.seq=="number"?A.seq:void 0,ct=se!=null?se:J.id,tt=Fe!==void 0?fe(ct,Fe,String(Me)):((cr=ie.get(J.id))!=null?cr:"")+Me;J.rawContent=tt,ee.has(J.id)||ee.set(J.id,this.createStreamParser());let Wt=ee.get(J.id),$t=tt.trim().startsWith("{")||tt.trim().startsWith("[");if($t&&ie.set(J.id,tt),Wt.__isPlainTextParser===!0){J.content=Fe!==void 0?tt:J.content+Me,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,f(J);continue}let it=Wt.processChunk(tt);if(it instanceof Promise)it.then(ht=>{var Ge;let en=typeof ht=="string"?ht:(Ge=ht==null?void 0:ht.text)!=null?Ge:null;if(en!==null&&en.trim()!=="")J.content=en,f(J);else if(!$t&&!tt.trim().startsWith("<")){let Cn=g,Qt=Cn&&Cn.id===J.id?Cn:J;Qt.id===J.id&&(Qt.content=Fe!==void 0?tt:Qt.content+Me,ie.delete(Qt.id),ee.delete(Qt.id),Qt.rawContent=void 0,f(Qt))}}).catch(()=>{J.content=Fe!==void 0?tt:J.content+Me,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,f(J)});else{let ht=typeof it=="string"?it:($=it==null?void 0:it.text)!=null?$:null;ht!==null&&ht.trim()!==""?(J.content=ht,f(J)):!$t&&!tt.trim().startsWith("<")&&(J.content=Fe!==void 0?tt:J.content+Me,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,f(J))}}if(A.isComplete){let Fe=(Pr=(as=A.result)==null?void 0:as.response)!=null?Pr:J.content;if(Fe){let ct=ie.get(J.id),tt=ct!=null?ct:Y(Fe);J.rawContent=tt;let Wt=ee.get(J.id),$t=null,gn=!1;if(Wt&&($t=Wt.getExtractedText(),$t===null&&($t=Ko(tt)),$t===null)){let it=Wt.processChunk(tt);it instanceof Promise?(gn=!0,it.then(ht=>{var Ge;let en=typeof ht=="string"?ht:(Ge=ht==null?void 0:ht.text)!=null?Ge:null;if(en!==null){let Cn=g;Cn&&Cn.id===J.id&&(Cn.content=en,Cn.streaming=!1,ee.delete(Cn.id),ie.delete(Cn.id),f(Cn))}})):$t=typeof it=="string"?it:(Ur=it==null?void 0:it.text)!=null?Ur:null}if(!gn){$t!==null&&$t.trim()!==""?J.content=$t:ie.has(J.id)||(J.content=Y(Fe));let it=ee.get(J.id);if(it){let ht=(jr=it.close)==null?void 0:jr.call(it);ht instanceof Promise&&ht.catch(()=>{}),ee.delete(J.id)}ie.delete(J.id),J.streaming=!1,f(J)}}}}else if(je==="step_complete"){let U=A.stepType,L=A.executionType;if(U==="tool"||L==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Fe=String((yr=(Ir=A.id)!=null?Ir:Z.stepId)!=null?yr:"");if(Fe){let ct=F(Z.toolId,Fe);for(let[tt,Wt]of I)tt.startsWith(ct)&&Wt.streaming!==!1&&(Wt.streaming=!1,f(Wt));R.delete(`${Z.toolId}::${Fe}`)}continue}let se=A.stopReason;if(S){if(g!==null){let tt=g;se&&(tt.stopReason=se),ee.delete(tt.id),ie.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,f(tt))}let Fe=(Ns=A.result)==null?void 0:Ns.response,ct=ve;ct&&(se&&(ct.stopReason=se),Fe!=null?Je(ct,Fe):(ee.delete(ct.id),ie.delete(ct.id))),ve=null;continue}let J=(Xn=A.result)==null?void 0:Xn.response,Me=Ae();if(se&&(Me.stopReason=se),J!=null){let Fe=ee.get(Me.id),ct=!1,tt=!1;if(Fe){let Wt=Fe.getExtractedText(),$t=ie.get(Me.id),gn=$t!=null?$t:Y(J);if(Me.rawContent=gn,Wt!==null&&Wt.trim()!=="")Me.content=Wt,ct=!0;else{let it=Ko(gn);if(it!==null)Me.content=it,ct=!0;else{let ht=Fe.processChunk(gn);if(ht instanceof Promise)tt=!0,ht.then(en=>{var Cn;let Ge=typeof en=="string"?en:(Cn=en==null?void 0:en.text)!=null?Cn:null;if(Ge!==null&&Ge.trim()!==""){let Qt=g;Qt&&Qt.id===Me.id&&(Qt.content=Ge,Qt.streaming=!1,ee.delete(Qt.id),ie.delete(Qt.id),f(Qt))}else{let Qt=Fe.getExtractedText(),xn=g;xn&&xn.id===Me.id&&(Qt!==null&&Qt.trim()!==""?xn.content=Qt:ie.has(xn.id)||(xn.content=Y(J)),xn.streaming=!1,ee.delete(xn.id),ie.delete(xn.id),f(xn))}});else{let en=typeof ht=="string"?ht:(Yn=ht==null?void 0:ht.text)!=null?Yn:null;if(en!==null&&en.trim()!=="")Me.content=en,ct=!0;else{let Ge=Fe.getExtractedText();Ge!==null&&Ge.trim()!==""&&(Me.content=Ge,ct=!0)}}}}}if(!tt){if(!Me.rawContent){let Wt=ie.get(Me.id);Me.rawContent=Wt!=null?Wt:Y(J)}if(!ct&&!ie.has(Me.id)&&(Me.content=Y(J)),Fe){let Wt=(xr=Fe.close)==null?void 0:xr.call(Fe);Wt instanceof Promise&&Wt.catch(()=>{})}ee.delete(Me.id),ie.delete(Me.id),Me.streaming=!1,f(Me)}}else ee.delete(Me.id),ie.delete(Me.id),Me.streaming=!1,f(Me)}else if(je==="flow_complete"){let U=(vr=A.result)==null?void 0:vr.response;if(S){if(g!==null){let L=g;ee.delete(L.id),ie.delete(L.id),L.streaming!==!1&&(L.streaming=!1,f(L))}}else if(U!=null){let L=Ae(),Z=ie.get(L.id),se=Z!=null?Z:Y(U);L.rawContent=se;let J=Y(U),Me=ee.get(L.id);if(Me){let tt=Ko(se);if(tt!==null)J=tt;else{let Wt=Me.processChunk(se);Wt instanceof Promise&&Wt.then(gn=>{var ht;let it=typeof gn=="string"?gn:(ht=gn==null?void 0:gn.text)!=null?ht:null;it!==null&&(L.content=it,L.streaming=!1,f(L))});let $t=Me.getExtractedText();$t!==null&&(J=$t)}}ee.delete(L.id),ie.delete(L.id);let Fe=J!==L.content,ct=L.streaming!==!1;Fe&&(L.content=J),L.streaming=!1,(Fe||ct)&&f(L)}else if(g!==null){let L=g;ee.delete(L.id),ie.delete(L.id),L.streaming!==!1&&(L.streaming=!1,f(L))}n({type:"status",status:"idle"})}else if(je==="agent_start")ne={executionId:A.executionId,agentId:(Io=A.agentId)!=null?Io:"virtual",agentName:(qr=A.agentName)!=null?qr:"",status:"running",currentIteration:0,maxTurns:(Tn=A.maxTurns)!=null?Tn:1,startedAt:He(A.startedAt)};else if(je==="agent_iteration_start"){if(ne&&(ne.currentIteration=A.iteration),Nn==="separate"&&A.iteration>1){let U=g;U&&(U.streaming=!1,f(U),Ve.set(A.iteration-1,U),g=null)}}else if(je==="agent_turn_start")v=null;else if(je==="agent_turn_delta"){if(A.contentType==="text"){let U=Ae();U.content+=(Rr=A.delta)!=null?Rr:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ne==null?void 0:ne.agentName},v=U,f(U)}else if(A.contentType==="thinking"){let U=(is=A.turnId)!=null?is:`agent-think-${A.iteration}`,L=Le(U);L.reasoning=(Ro=L.reasoning)!=null?Ro:{id:U,status:"streaming",chunks:[]},L.reasoning.chunks.push((ls=A.delta)!=null?ls:""),L.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},f(L)}else if(A.contentType==="tool_input"){let U=(Ba=A.toolCallId)!=null?Ba:W.lastId;if(U){let L=k.get(U);L!=null&&L.toolCall&&(L.toolCall.chunks=(cs=L.toolCall.chunks)!=null?cs:[],L.toolCall.chunks.push((Da=A.delta)!=null?Da:""),f(L))}}}else if(je==="agent_turn_complete"){let U=A.turnId;if(U){let se=O.get(U);if(se!=null&&se.reasoning){se.reasoning.status="complete",se.reasoning.completedAt=He(A.completedAt);let J=(ds=se.reasoning.startedAt)!=null?ds:Date.now();se.reasoning.durationMs=Math.max(0,((yt=se.reasoning.completedAt)!=null?yt:Date.now())-J),se.streaming=!1,f(se)}}let L=A.stopReason,Z=g!=null?g:v;if(L&&Z!==null){let se=A.turnId;(!se||((Fs=Z.agentMetadata)==null?void 0:Fs.turnId)===se)&&(Z.stopReason=L,f(Z))}}else if(je==="agent_tool_start"){g&&(g.streaming=!1,f(g),g=null);let U=(dr=A.toolCallId)!=null?dr:`agent-tool-${l()}`;We(oe(A),U);let L=ae(U),Z=(_n=L.toolCall)!=null?_n:{id:U,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=(Na=(Oa=A.toolName)!=null?Oa:A.name)!=null?Na:Z.name,Z.status="running",A.parameters!==void 0&&(Z.args=A.parameters),Z.startedAt=He((ps=A.startedAt)!=null?ps:A.timestamp),L.toolCall=Z,L.streaming=!0,L.agentMetadata={executionId:A.executionId,iteration:A.iteration},f(L)}else if(je==="agent_tool_delta"){let U=(zr=A.toolCallId)!=null?zr:W.lastId;if(U){let L=(_s=k.get(U))!=null?_s:ae(U);L.toolCall&&(L.toolCall.chunks=(co=L.toolCall.chunks)!=null?co:[],L.toolCall.chunks.push(($s=A.delta)!=null?$s:""),L.toolCall.status="running",L.streaming=!0,f(L))}}else if(je==="agent_tool_complete"){let U=(Us=A.toolCallId)!=null?Us:W.lastId;if(U){let L=(js=k.get(U))!=null?js:ae(U);if(L.toolCall){L.toolCall.status="complete",A.result!==void 0&&(L.toolCall.result=A.result),typeof A.executionTime=="number"&&(L.toolCall.durationMs=A.executionTime),L.toolCall.completedAt=He((qs=A.completedAt)!=null?qs:A.timestamp),L.streaming=!1,f(L);let Z=oe(A);Z&&W.byCall.delete(Z)}}}else if(je==="agent_media"){let U=Array.isArray(A.media)?A.media:[],L=[];for(let Z of U){if(!Z||typeof Z!="object")continue;let se=Z,J=typeof se.type=="string"?se.type:void 0,Me=typeof se.mediaType=="string"?se.mediaType.toLowerCase():"",Fe=null,ct="";if(J==="media"){let tt=typeof se.data=="string"?se.data:void 0;if(!tt)continue;ct=Me.length>0?Me:"application/octet-stream",Fe=`data:${ct};base64,${tt}`}else if(J==="image-url"){let tt=typeof se.url=="string"?se.url:void 0;if(!tt)continue;ct=Me,Fe=tt}else if(J==="file-url"){let tt=typeof se.url=="string"?se.url:void 0;if(!tt)continue;ct=Me,Fe=tt}else continue;if(Fe)if(J==="image-url"||ct.startsWith("image/"))L.push({type:"image",image:Fe,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))L.push({type:"audio",audio:Fe,mimeType:ct});else if(ct.startsWith("video/"))L.push({type:"video",video:Fe,mimeType:ct});else{let tt=ct||"application/octet-stream";L.push({type:"file",data:Fe,mimeType:tt,filename:lh(tt)})}}if(L.length>0){let Z=l(),se=A.toolCallId,Me={id:`agent-media-${typeof se=="string"&&se.length>0?`${se}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:L,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(Me);let Fe=g;Fe&&(Fe.streaming=!1,f(Fe)),g=null,y.current=null}}else if(je!=="agent_iteration_complete"){if(je==="agent_reflection"||je==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,L={id:U,role:"assistant",content:($n=A.reflection)!=null?$n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(us=A.reflection)!=null?us:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(L)}else if(je==="agent_complete"){ne&&(ne.status=A.success?"complete":"error",ne.completedAt=He(A.completedAt),ne.stopReason=A.stopReason);let U=g;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if(je==="agent_error"){let U=typeof A.error=="string"?A.error:(Hr=(Wr=A.error)==null?void 0:Wr.message)!=null?Hr:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(je!=="agent_ping"){if(je==="agent_approval_start"){let U=(zs=A.approvalId)!=null?zs:`approval-${l()}`,L={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Fa=ne==null?void 0:ne.agentId)!=null?Fa:"virtual",executionId:(Ks=(Vs=A.executionId)!=null?Vs:ne==null?void 0:ne.executionId)!=null?Ks:"",toolName:(Wo=A.toolName)!=null?Wo:"",toolType:A.toolType,description:($a=A.description)!=null?$a:`Execute ${(_a=A.toolName)!=null?_a:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};f(L)}else if(je==="step_await"&&A.awaitReason==="approval_required"){let U=(Ua=A.approvalId)!=null?Ua:`approval-${l()}`,L={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ja=ne==null?void 0:ne.agentId)!=null?ja:"virtual",executionId:(Ho=(pl=A.executionId)!=null?pl:ne==null?void 0:ne.executionId)!=null?Ho:"",toolName:(po=A.toolName)!=null?po:"",toolType:A.toolType,description:(Gs=A.description)!=null?Gs:`Execute ${(qa=A.toolName)!=null?qa:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};f(L)}else if(je==="agent_approval_complete"){let U=A.approvalId;if(U){let Z={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(uo=A.decision)!=null?uo:"approved",agentId:(za=ne==null?void 0:ne.agentId)!=null?za:"virtual",executionId:(mo=(Js=A.executionId)!=null?Js:ne==null?void 0:ne.executionId)!=null?mo:"",toolName:(Qs=A.toolName)!=null?Qs:"",description:(Va=A.description)!=null?Va:"",resolvedAt:Date.now()}};f(Z)}}else if(je==="artifact_start"||je==="artifact_delta"||je==="artifact_update"||je==="artifact_complete"){if(je==="artifact_start"){let U=A.artifactType,L=String(A.id),Z=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:L,artifactType:U,title:Z,component:typeof A.component=="string"?A.component:void 0}),ce.set(L,{markdown:"",title:Z}),!re.has(L)){re.add(L);let se={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:U,status:"streaming"}})};X.set(L,se),f(se)}}else if(je==="artifact_delta"){let U=String(A.id),L=typeof A.delta=="string"?A.delta:String((Vr=A.delta)!=null?Vr:"");n({type:"artifact_delta",id:U,artDelta:L});let Z=ce.get(U);Z&&(Z.markdown+=L)}else if(je==="artifact_update"){let U=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:U,component:typeof A.component=="string"?A.component:void 0})}else if(je==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let L=X.get(U);if(L){L.streaming=!1;try{let Z=JSON.parse((Ka=L.rawContent)!=null?Ka:"{}");if(Z.props){Z.props.status="complete";let se=ce.get(U);se!=null&&se.markdown&&(Z.props.markdown=se.markdown)}L.rawContent=JSON.stringify(Z)}catch{}ce.delete(U),f(L),X.delete(U)}}}else if(je==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let L=String((go=U.id)!=null?go:`msg-${l()}`),Z=U.role,J={id:L,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(J),J.rawContent)try{let Me=JSON.parse(J.rawContent),Fe=(Dt=Me==null?void 0:Me.props)==null?void 0:Dt.artifactId;typeof Fe=="string"&&re.add(Fe)}catch{}g=null,y.current=null,ee.delete(L),ie.delete(L)}else if(je==="error"||je==="step_error"||je==="dispatch_error"||je==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(je==="dispatch_error"){let L=(ms=A.message)!=null?ms:A.error;L!=null&&L!==""&&(U=new Error(String(L)))}else if(je==="step_error"||je==="flow_error"){let L=A.error;typeof L=="string"&&L!==""?U=new Error(L):L!=null&&typeof L=="object"&&"message"in L&&(U=new Error(String((gs=L.message)!=null?gs:L)))}else je==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let L=g;L&&L.streaming&&(L.streaming=!1,f(L)),n({type:"status",status:"idle"})}}}}}De.length=0};;){let{done:H,value:pe}=await o.read();if(H)break;a+=s.decode(pe,{stream:!0});let Oe=a.split(`
10
10
 
11
- `);a=(ln=Ne.pop())!=null?ln:"";for(let Ge of Ne){let $e=Ge.split(`
12
- `),je="message",st="";for(let Yt of $e)Yt.startsWith("event:")?je=Yt.replace("event:","").trim():Yt.startsWith("data:")&&(st+=Yt.replace("data:","").trim());if(!st)continue;let It;try{It=JSON.parse(st)}catch(Yt){n({type:"error",error:Yt instanceof Error?Yt:new Error("Failed to parse chat stream payload")});continue}let Jt=je!=="message"?je:(nr=It.type)!=null?nr:"message";if((Tr=this.onSSEEvent)==null||Tr.call(this,Jt,It),this.parseSSEEvent){x.current=m;let Yt=await this.handleCustomSSEEvent(It,n,x,f,l,w);if(x.current&&x.current!==m&&(m=x.current),Yt)continue}kt.push(Jt,It),ue()}}kt.flushPending(),ue(),kt.destroy()}};function Ou(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function xs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Vo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var oi="[Image]";function Fu(e){return typeof e=="string"?[{type:"text",text:e}]:e}function $u(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function _u(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ju(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function oa(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 qu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function zu(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 Vu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],If=["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"],Gr=[...Vu,...If];function Wf(e){return Vu.includes(e)||e.startsWith("image/")}function si(e){return Wf(e.type)}async function Ku(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;si(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Ju(e,t=Gr,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 Rf(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Gu(e,t){let n=Rf(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 ai=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(),o=this.pcmToFloat32(n),s=r.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=r.createBufferSource();a.buffer=s,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.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),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}};var ii=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,o,s){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<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):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 sa=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 ii;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 o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.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=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,x=T=>{v||(v=!0,clearTimeout(w),m(new Error(T)))},w=setTimeout(()=>x("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(w),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!v){let N=T.code!==1006?` (code ${T.code})`:"";x("WebSocket connection failed"+N+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}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(o=>o({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(o=>o("speaking")),this.playAudio(t.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(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(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(t.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ai(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,o;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 s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(o=(r=this.config)==null?void 0:r.silenceThreshold)!=null?o:.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(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}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 s,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=(s=this.config)==null?void 0:s.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),o=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];n(a)},o.onerror=r,o.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 o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([r],{type:s}),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 Ko=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=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("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 Jo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new sa(e.runtype);case"browser":if(!Ko.isSupported())throw new Error("Browser speech recognition not supported");return new Ko(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function li(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Jo({type:"runtype",runtype:e.runtype});if(Ko.isSupported())return Jo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function aa(e){try{return li(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}
11
+ `);a=(cn=Oe.pop())!=null?cn:"";for(let Qe of Oe){let _e=Qe.split(`
12
+ `),Ue="message",at="";for(let Zt of _e)Zt.startsWith("event:")?Ue=Zt.replace("event:","").trim():Zt.startsWith("data:")&&(at+=Zt.replace("data:","").trim());if(!at)continue;let Pt;try{Pt=JSON.parse(at)}catch(Zt){n({type:"error",error:Zt instanceof Error?Zt:new Error("Failed to parse chat stream payload")});continue}let Kt=Ue!=="message"?Ue:(sr=Pt.type)!=null?sr:"message";if((Er=this.onSSEEvent)==null||Er.call(this,Kt,Pt),this.parseSSEEvent){y.current=g;let Zt=await this.handleCustomSSEEvent(Pt,n,y,f,l,w);if(y.current&&y.current!==g&&(g=y.current),Zt)continue}Et.push(Kt,Pt),ue()}}Et.flushPending(),ue(),Et.destroy()}};function lm(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ts(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Jo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var fi="[Image]";function cm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function dm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function pm(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function um(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function pa(e){return{type:"text",text:e}}function mm(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 gm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function fm(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 hm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ph=["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"],Yr=[...hm,...ph];function uh(e){return hm.includes(e)||e.startsWith("image/")}function hi(e){return uh(e.type)}async function bm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;hi(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function ym(e,t=Yr,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 mh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function xm(e,t){let n=mh(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 bi=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(),o=this.pcmToFloat32(n),s=r.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=r.createBufferSource();a.buffer=s,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.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),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}};var yi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,o,s){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<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):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 ua=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 yi;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 o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.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=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let v=!1,y=S=>{v||(v=!0,clearTimeout(w),g(new Error(S)))},w=setTimeout(()=>y("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(w),f())},{once:!0}),this.ws.addEventListener("error",()=>{y("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!v){let O=S.code!==1006?` (code ${S.code})`:"";y("WebSocket connection failed"+O+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}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(o=>o({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(o=>o("speaking")),this.playAudio(t.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(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(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(t.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new bi(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,o;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 s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(o=(r=this.config)==null?void 0:r.silenceThreshold)!=null?o:.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(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}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 s,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=(s=this.config)==null?void 0:s.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),o=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];n(a)},o.onerror=r,o.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 o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([r],{type:s}),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 Qo=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=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("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 Xo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ua(e.runtype);case"browser":if(!Qo.isSupported())throw new Error("Browser speech recognition not supported");return new Qo(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function xi(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Xo({type:"runtype",runtype:e.runtype});if(Qo.isSupported())return Xo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function ma(e){try{return xi(e),!0}catch{return!1}}var gh=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function fh(e,t){return gh.some(n=>e[n]!==t[n])}function vm(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: ${n.message}_`:r}var ia=e=>({isError:!0,content:[{type:"text",text:e}]}),Qu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,vs=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,o,s,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)&&yo(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:(o=t.message.agentMetadata.agentName)!=null?o:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s: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,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new zo(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,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 aa((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,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Jo(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"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,u,f,m,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}):(u=l.transcript)!=null&&u.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let w=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:v.id;w&&this.ttsSpokenMessageIds.add(w)}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,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}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,o,s,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:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.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 zo(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:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,m={id:a!=null?a:n==="user"?xs():n==="assistant"?Vo():`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,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(m),m}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:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:m}=r,x={id:d!=null?d:o==="user"?xs():o==="assistant"?Vo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...m!==void 0&&{rawContent:m}};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:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,u,f,m;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 o=xs(),s=Vo(),a={id:o,role:"user",content:r||oi,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:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let w=Xu(v,this.config.errorMessage);if(w){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Vo();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 u=Xu(l,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.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=(s=this.callbacks).onError)==null||a.call(s,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 o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,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 o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,m,v;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),x){let w=null;if(x instanceof Response){if(!x.ok){let T=await x.json().catch(()=>null);throw new Error((f=T==null?void 0:T.error)!=null?f:`Approval request failed: ${x.status}`)}w=x.body}else x instanceof ReadableStream&&(w=x);w?await this.connectStream(w,{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(x){let w=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,w||(v=(m=this.callbacks).onError)==null||v.call(m,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,m,v,x,w,T,N,M,I,W;let r=this.messages.find(S=>S.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(v=(m=this.callbacks).onError)==null||v.call(m,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 S=(x=t.toolCall)==null?void 0:x.args,k=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(k.length===1){let $=typeof((w=k[0])==null?void 0:w.question)=="string"?k[0].question:"";$&&(a={[$]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(N=t.toolCall)==null?void 0:N.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let S=typeof n=="string"?n:Object.entries(n).map(([k,$])=>`${k}: ${Array.isArray($)?$.join(", "):$}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let S=a!=null?a:{};l.forEach((k,$)=>{let O=typeof(k==null?void 0:k.question)=="string"?k.question:"";if(!O)return;let H=S[O],U=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${$}`,role:"assistant",content:O,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 S=await this.client.resumeFlow(o,{[s]:n});if(!S.ok){let k=await S.json().catch(()=>null);throw new Error((M=k==null?void 0:k.error)!=null?M:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let k=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(W=(I=this.callbacks).onError)==null||W.call(I,S instanceof Error?S:new Error(String(S)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.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 o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.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)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=Date.now()){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var I,W,S,k,$,O,H;let f=(I=u.toolCall)==null?void 0:I.name,m=(W=u.toolCall)==null?void 0:W.id;if(!f||!m)return null;let v=`${t}:${m}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return null;this.webMcpInflightKeys.add(v),r.push(v);let x=this.markWebMcpToolRunning(u),w=new AbortController;this.webMcpResolveControllers.add(w),o.push(w);let T=(k=(S=u.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?k:f,N=this.client.executeWebMcpToolCall(f,($=u.toolCall)==null?void 0:$.args,w.signal),M;if(!N)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await N}catch(U){let J=U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")||U.message.includes("abort"));return J||(H=(O=this.callbacks).onError)==null||H.call(O,U instanceof Error?U:new Error(String(U))),this.markWebMcpToolComplete(u,ia(J?"Aborted by cancel()":Qu(U)),x),this.webMcpInflightKeys.delete(v),null}return w.signal.aborted?(this.markWebMcpToolComplete(u,ia("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:M,toolMessage:u,startedAt:x,completedAt:Date.now()}})),i=[];try{if(i=a.filter(m=>m!==null),i.length===0)return;let u={};for(let m of i)u[m.resumeKey]=m.output;let f=await this.client.resumeFlow(t,u,{signal:s.signal});if(!f.ok){let m=await f.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Resume failed: ${f.status}`)}for(let m of i)this.webMcpResolvedKeys.add(m.dedupeKey),this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(p=(l=this.callbacks).onError)==null||p.call(l,u instanceof Error?u:new Error(String(u)));else for(let m of i)this.markWebMcpToolComplete(m.toolMessage,ia("Aborted by cancel()"),m.startedAt)}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of o)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var m,v,x,w,T,N,M,I,W,S,k,$;let n=(m=t.agentMetadata)==null?void 0:m.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(x=t.toolCall)==null?void 0:x.id;if(!n){(T=(w=this.callbacks).onError)==null||T.call(w,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!o){let O=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(O)||this.webMcpResolvedKeys.has(O))return;this.webMcpInflightKeys.add(O);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(O)}catch(H){(M=(N=this.callbacks).onError)==null||M.call(N,H instanceof Error?H:new Error(String(H)))}finally{this.webMcpInflightKeys.delete(O)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(I=t.toolCall)==null?void 0:I.args,p=this.client.executeWebMcpToolCall(r,l,d),u="execute",f=a;try{let O;if(p?O=await p:O={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ia("Aborted by cancel()"),a);return}let H=(S=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?S:r;u="resume",await this.resumeWithToolOutput(n,H,O,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,O,a,f)},signal:d})}catch(O){let H=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));(u==="execute"||H||d.aborted)&&this.markWebMcpToolComplete(t,ia(H||d.aborted?"Aborted by cancel()":Qu(O)),a),H||($=(k=this.callbacks).onError)==null||$.call(k,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.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 o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};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 o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.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 o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o: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(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=r.content;o.trim()&&this.speak(o,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t),s=r.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(o.rate=n.rate),n.pitch!==void 0&&(o.pitch=n.pitch),setTimeout(()=>r.speak(o),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 o of n){let s=t.find(a=>a.name===o);if(s)return s}return(r=t.find(o=>o.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(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,m,v,x,w,T,N,M,I,W,S;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let k=o.approval,$=n.approval;a.approval={...k,...$,executionId:$.executionId||k.executionId,toolName:$.toolName||k.toolName,description:$.description||k.description,toolType:(u=$.toolType)!=null?u:k.toolType,reason:(f=$.reason)!=null?f:k.reason,parameters:(m=$.parameters)!=null?m:k.parameters}}let i=(v=n.toolCall)==null?void 0:v.name,d=(x=n.agentMetadata)==null?void 0:x.executionId,l=(w=n.toolCall)==null?void 0:w.id;if(i&&yo(i)&&d&&l&&((T=n.agentMetadata)==null?void 0:T.awaitingLocalTool)===!0){let k=`${d}:${l}`,$=this.webMcpInflightKeys.has(k),O=this.webMcpResolvedKeys.has(k),H=(N=o.toolCall)==null?void 0:N.name,U=((M=o.agentMetadata)==null?void 0:M.executionId)===d&&((I=o.toolCall)==null?void 0:I.id)===l&&H!==void 0&&yo(H)&&((W=o.toolCall)==null?void 0:W.status)==="complete";($||O||U)&&(a.agentMetadata={...(S=a.agentMetadata)!=null?S:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}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 o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;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},Br=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var C=require("lucide"),Hf={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},Ce=(e,t=24,n="currentColor",r=2)=>{let o=Hf[e];return o?Bf(o,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 Bf(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[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))}),o.appendChild(d)}),o}var ci={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function Df(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Nf(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 Go=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ci.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ci.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:ci.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:ci.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,o,s,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=Ju(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await Ku(l),f=si(l)?URL.createObjectURL(l):null,m={id:Df(),file:l,previewUrl:f,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,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 o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.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=si(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=Nf(t.file.type),d=Ce(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Gu(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 o=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ce("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),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 Yu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function la(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Yu(s)&&Yu(o)?n[r]=la(s,o):n[r]=o}return n}var er="min(440px, calc(100vw - 24px))",di="440px",Ft={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:er,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:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},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 Zu(e,t){if(!(!e&&!t))return e?t?la(e,t):e:t}function pi(e){var t,n,r,o,s,a,i,d,l,p,u,f,m,v,x,w,T,N,M,I,W;return e?{...Ft,...e,theme:Zu(Ft.theme,e.theme),darkTheme:Zu(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(t=Ft.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Ft.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Ft.copy,...e.copy},sendButton:{...Ft.sendButton,...e.sendButton},statusIndicator:{...Ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var de,Q,re,le,ge,V,se,He,Z,ee;let S=(de=Ft.features)==null?void 0:de.artifacts,k=(Q=e.features)==null?void 0:Q.artifacts,$=(re=Ft.features)==null?void 0:re.scrollToBottom,O=(le=e.features)==null?void 0:le.scrollToBottom,H=(ge=Ft.features)==null?void 0:ge.scrollBehavior,U=(V=e.features)==null?void 0:V.scrollBehavior,J=(se=Ft.features)==null?void 0:se.streamAnimation,ce=(He=e.features)==null?void 0:He.streamAnimation,Me=(Z=Ft.features)==null?void 0:Z.askUserQuestion,ze=(ee=e.features)==null?void 0:ee.askUserQuestion,Ae=S===void 0&&k===void 0?void 0:{...S,...k,layout:{...S==null?void 0:S.layout,...k==null?void 0:k.layout}},We=$===void 0&&O===void 0?void 0:{...$,...O},be=H===void 0&&U===void 0?void 0:{...H,...U},ke=J===void 0&&ce===void 0?void 0:{...J,...ce},Re=Me===void 0&&ze===void 0?void 0:{...Me,...ze,styles:{...Me==null?void 0:Me.styles,...ze==null?void 0:ze.styles}};return{...Ft.features,...e.features,...We!==void 0?{scrollToBottom:We}:{},...be!==void 0?{scrollBehavior:be}:{},...Ae!==void 0?{artifacts:Ae}:{},...ke!==void 0?{streamAnimation:ke}:{},...Re!==void 0?{askUserQuestion:Re}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Ft.suggestionChips,suggestionChipsConfig:{...Ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ft.layout,...e.layout,header:{...(a=Ft.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ft.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Ft.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=Ft.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(T=(w=e.layout)==null?void 0:w.messages)==null?void 0:T.timestamp}},slots:{...(N=Ft.layout)==null?void 0:N.slots,...(M=e.layout)==null?void 0:M.slots}},markdown:{...Ft.markdown,...e.markdown,options:{...(I=Ft.markdown)==null?void 0:I.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...Ft.messageActions,...e.messageActions}}:Ft}var fl={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"}},hl={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"}},bl={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:er,maxWidth:di,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:"palette.shadows.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",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},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 ws(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ws(e,r):r}function ui(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=ws(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.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 yl(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 em(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=em(s,o):n[r]=o}return n}function Of(e,t){return t?em(e,t):e}function Cs(e,t={}){var o,s,a,i,d,l,p,u,f,m,v,x,w;let n={palette:fl,semantic:hl,components:bl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.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,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.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,...(w=e==null?void 0:e.semantic)==null?void 0:w.typography}},components:Of(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=yl(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(N=>N.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function mi(e){var x,w,T,N,M,I,W,S,k,$,O,H,U,J,ce,Me,ze,Ae,We,be,ke,Re,de,Q,re,le,ge,V,se,He,Z,ee,ae,Se,Ze,ve,fe,Je,De,z,ue,rt,kt,te,Ve,Bn,Bt,ln,nr,Tr,R,pe,Ne,Ge,$e,je,st,It,Jt,Yt,K,vt,it,we,ie,nt,Zt,Gt,kn,xn,ft,Lt,et,zt,cn,wn,Cn,yn,Er,St,_n,jn,Nr,hr,wt,Lo,Mr,Po,Dn,rs,no,Or,Tt,Un,qn,Ln,Pt,rr,or,zn,ro,Fr,oo,Vn,Dt,Pn,sr,so,$r,ao,kr,Kn,br,bt,en,tn,Jn,io;let t=ui(e),n={};for(let[ye,ar]of Object.entries(t)){let ir=ye.replace(/\./g,"-");n[`--persona-${ir}`]=ar.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(w=n["--persona-semantic-colors-secondary"])!=null?w:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(N=n["--persona-semantic-colors-surface"])!=null?N:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(M=n["--persona-semantic-colors-background"])!=null?M: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"]=(W=n["--persona-semantic-colors-text"])!=null?W:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(S=n["--persona-semantic-colors-text-muted"])!=null?S:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(k=n["--persona-semantic-colors-text-inverse"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-border"]=($=n["--persona-semantic-colors-border"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(O=n["--persona-semantic-colors-divider"])!=null?O:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(H=n["--persona-components-voice-recording-indicator"])!=null?H: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"]=(J=n["--persona-components-voice-processing-icon"])!=null?J:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(ce=n["--persona-components-voice-speaking-icon"])!=null?ce:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Me=n["--persona-components-approval-requested-background"])!=null?Me:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(ze=n["--persona-components-approval-requested-border"])!=null?ze:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ae=n["--persona-components-approval-requested-text"])!=null?Ae:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(We=n["--persona-components-approval-requested-shadow"])!=null?We:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(be=n["--persona-components-approval-approve-background"])!=null?be:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(ke=n["--persona-components-approval-deny-background"])!=null?ke:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Re=n["--persona-components-attachment-image-background"])!=null?Re:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(de=n["--persona-components-attachment-image-border"])!=null?de:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Q=n["--persona-semantic-typography-fontFamily"])!=null?Q:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(re=n["--persona-semantic-typography-fontSize"])!=null?re:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(le=n["--persona-semantic-typography-fontWeight"])!=null?le:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(ge=n["--persona-semantic-typography-lineHeight"])!=null?ge: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"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(se=n["--persona-palette-radius-md"])!=null?se:"0.375rem",n["--persona-radius-lg"]=(He=n["--persona-palette-radius-lg"])!=null?He:"0.5rem",n["--persona-radius-xl"]=(Z=n["--persona-palette-radius-xl"])!=null?Z:"0.75rem",n["--persona-radius-full"]=(ee=n["--persona-palette-radius-full"])!=null?ee:"9999px",n["--persona-launcher-radius"]=(Se=(ae=n["--persona-components-launcher-borderRadius"])!=null?ae:n["--persona-palette-radius-full"])!=null?Se:"9999px",n["--persona-launcher-bg"]=(Ze=n["--persona-components-launcher-background"])!=null?Ze:n["--persona-primary"],n["--persona-launcher-fg"]=(ve=n["--persona-components-launcher-foreground"])!=null?ve:n["--persona-text-inverse"],n["--persona-launcher-border"]=(fe=n["--persona-components-launcher-border"])!=null?fe:n["--persona-border"],n["--persona-button-primary-bg"]=(Je=n["--persona-components-button-primary-background"])!=null?Je:n["--persona-primary"],n["--persona-button-primary-fg"]=(De=n["--persona-components-button-primary-foreground"])!=null?De:n["--persona-text-inverse"],n["--persona-button-radius"]=(ue=(z=n["--persona-components-button-primary-borderRadius"])!=null?z:n["--persona-palette-radius-full"])!=null?ue:"9999px",n["--persona-panel-radius"]=(kt=(rt=n["--persona-components-panel-borderRadius"])!=null?rt:n["--persona-radius-xl"])!=null?kt:"0.75rem",n["--persona-panel-border"]=(te=n["--persona-components-panel-border"])!=null?te:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Bn=(Ve=n["--persona-components-panel-shadow"])!=null?Ve:n["--persona-palette-shadows-xl"])!=null?Bn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Bt=n["--persona-components-launcher-shadow"])!=null?Bt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(nr=(ln=n["--persona-components-input-borderRadius"])!=null?ln:n["--persona-radius-lg"])!=null?nr:"0.5rem",n["--persona-message-user-radius"]=(R=(Tr=n["--persona-components-message-user-borderRadius"])!=null?Tr:n["--persona-radius-lg"])!=null?R:"0.5rem",n["--persona-message-assistant-radius"]=(Ne=(pe=n["--persona-components-message-assistant-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?Ne:"0.5rem",n["--persona-header-bg"]=(Ge=n["--persona-components-header-background"])!=null?Ge:n["--persona-surface"],n["--persona-header-border"]=($e=n["--persona-components-header-border"])!=null?$e:n["--persona-divider"],n["--persona-header-icon-bg"]=(je=n["--persona-components-header-iconBackground"])!=null?je:n["--persona-primary"],n["--persona-header-icon-fg"]=(st=n["--persona-components-header-iconForeground"])!=null?st:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(It=n["--persona-components-header-titleForeground"])!=null?It:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Jt=n["--persona-components-header-subtitleForeground"])!=null?Jt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Yt=n["--persona-components-header-actionIconForeground"])!=null?Yt:n["--persona-muted"];let r=(K=e.components)==null?void 0:K.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(vt=e.components)==null?void 0:vt.introCard;n["--persona-intro-card-bg"]=(it=n["--persona-components-introCard-background"])!=null?it:n["--persona-surface"],n["--persona-intro-card-radius"]=(we=n["--persona-components-introCard-borderRadius"])!=null?we:"1rem",n["--persona-intro-card-padding"]=(ie=n["--persona-components-introCard-padding"])!=null?ie:"1.5rem",n["--persona-intro-card-shadow"]=(Zt=(nt=o==null?void 0:o.shadow)!=null?nt:n["--persona-components-introCard-shadow"])!=null?Zt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Gt=n["--persona-components-input-background"])!=null?Gt:n["--persona-surface"],n["--persona-input-placeholder"]=(kn=n["--persona-components-input-placeholder"])!=null?kn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(xn=n["--persona-components-message-user-background"])!=null?xn:n["--persona-accent"],n["--persona-message-user-text"]=(ft=n["--persona-components-message-user-text"])!=null?ft:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Lt=n["--persona-components-message-user-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(et=n["--persona-components-message-assistant-background"])!=null?et:n["--persona-surface"],n["--persona-message-assistant-text"]=(zt=n["--persona-components-message-assistant-text"])!=null?zt:n["--persona-text"],n["--persona-message-assistant-border"]=(cn=n["--persona-components-message-assistant-border"])!=null?cn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(wn=n["--persona-components-message-assistant-shadow"])!=null?wn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(yn=(Cn=n["--persona-components-scrollToBottom-background"])!=null?Cn:n["--persona-button-primary-bg"])!=null?yn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(St=(Er=n["--persona-components-scrollToBottom-foreground"])!=null?Er:n["--persona-button-primary-fg"])!=null?St:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(_n=n["--persona-components-scrollToBottom-border"])!=null?_n:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(jn=n["--persona-components-scrollToBottom-size"])!=null?jn:"40px",n["--persona-scroll-to-bottom-radius"]=(wt=(hr=(Nr=n["--persona-components-scrollToBottom-borderRadius"])!=null?Nr:n["--persona-button-radius"])!=null?hr:n["--persona-radius-full"])!=null?wt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Mr=(Lo=n["--persona-components-scrollToBottom-shadow"])!=null?Lo:n["--persona-palette-shadows-sm"])!=null?Mr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Po=n["--persona-components-scrollToBottom-padding"])!=null?Po:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Dn=n["--persona-components-scrollToBottom-gap"])!=null?Dn:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(no=(rs=n["--persona-components-scrollToBottom-fontSize"])!=null?rs:n["--persona-palette-typography-fontSize-sm"])!=null?no:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Or=n["--persona-components-scrollToBottom-iconSize"])!=null?Or:"14px",n["--persona-tool-bubble-shadow"]=(Tt=n["--persona-components-toolBubble-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Un=n["--persona-components-reasoningBubble-shadow"])!=null?Un:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(qn=n["--persona-components-composer-shadow"])!=null?qn:"none",n["--persona-md-inline-code-bg"]=(Ln=n["--persona-components-markdown-inlineCode-background"])!=null?Ln:n["--persona-container"],n["--persona-md-inline-code-color"]=(Pt=n["--persona-components-markdown-inlineCode-foreground"])!=null?Pt:n["--persona-text"],n["--persona-md-link-color"]=(or=(rr=n["--persona-components-markdown-link-foreground"])!=null?rr:n["--persona-accent"])!=null?or:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);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"]=(zn=n["--persona-components-markdown-codeBlock-background"])!=null?zn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(ro=n["--persona-components-markdown-codeBlock-borderColor"])!=null?ro:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Fr=n["--persona-components-markdown-codeBlock-textColor"])!=null?Fr:"inherit",n["--persona-md-table-header-bg"]=(oo=n["--persona-components-markdown-table-headerBackground"])!=null?oo:n["--persona-container"],n["--persona-md-table-border-color"]=(Vn=n["--persona-components-markdown-table-borderColor"])!=null?Vn:n["--persona-border"],n["--persona-md-hr-color"]=(Dt=n["--persona-components-markdown-hr-color"])!=null?Dt:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Pn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Pn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(sr=n["--persona-components-markdown-blockquote-background"])!=null?sr:"transparent",n["--persona-md-blockquote-text-color"]=(so=n["--persona-components-markdown-blockquote-textColor"])!=null?so:n["--persona-palette-colors-gray-500"],n["--cw-container"]=($r=n["--persona-components-collapsibleWidget-container"])!=null?$r:n["--persona-surface"],n["--cw-surface"]=(ao=n["--persona-components-collapsibleWidget-surface"])!=null?ao:n["--persona-surface"],n["--cw-border"]=(kr=n["--persona-components-collapsibleWidget-border"])!=null?kr:n["--persona-border"],n["--persona-message-border"]=(Kn=n["--persona-components-message-border"])!=null?Kn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let ye=v.toolbar;ye.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,n["--persona-dropdown-bg"]=(br=n["--persona-dropdown-bg"])!=null?br:ye.copyMenuBackground),ye.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,n["--persona-dropdown-border"]=(bt=n["--persona-dropdown-border"])!=null?bt:ye.copyMenuBorder),ye.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,n["--persona-dropdown-shadow"]=(en=n["--persona-dropdown-shadow"])!=null?en:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(tn=n["--persona-dropdown-radius"])!=null?tn:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Jn=n["--persona-dropdown-item-hover-bg"])!=null?Jn:ye.copyMenuItemHoverBackground),ye.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(v!=null&&v.tab){let ye=v.tab;ye.background&&(n["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(n["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(n["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(n["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(n["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(n["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(n["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(v!=null&&v.pane){let ye=v.pane;if(ye.toolbarBackground){let ar=(io=ws(e,ye.toolbarBackground))!=null?io:ye.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ar}}return n}var tm={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 Ff={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"}}},nm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ca=()=>{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"},$f=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ca()},xl=e=>$f(e),_f=e=>Cs(e),jf=e=>{var n;let t=Cs(void 0,{validate:!1});return Cs({...e,palette:{...t.palette,colors:{...Ff.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},As=e=>{let t=xl(e),n=nm(e==null?void 0:e.theme),r=nm(e==null?void 0:e.darkTheme);return t==="dark"?jf(la(n!=null?n:{},r!=null?r:{})):_f(n)},Uf=e=>mi(e),xo=(e,t)=>{let n=As(t),r=Uf(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},gi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ca())});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(ca());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 rm=require("idiomorph"),fi=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;rm.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var hi={index:-1,draft:""};function om(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...hi}}}function sm(e,t){var n,r,o,s,a,i,d,l,p,u,f,m,v,x,w,T,N,M,I,W,S,k,$,O,H,U,J,ce,Me,ze,Ae,We,be,ke,Re,de,Q,re;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",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,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(w=(x=e.toolCall)==null?void 0:x.name)!=null?w:"",(M=(N=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:N.length)!=null?M:0,(k=(S=(W=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?k:"",typeof(($=e.toolCall)==null?void 0:$.args)=="string"?e.toolCall.args.length:(O=e.toolCall)!=null&&O.args?JSON.stringify(e.toolCall.args).length:0,(J=(U=(H=e.reasoning)==null?void 0:H.chunks)==null?void 0:U.length)!=null?J:0,(Ae=(ze=(Me=(ce=e.reasoning)==null?void 0:ce.chunks)==null?void 0:Me[e.reasoning.chunks.length-1])==null?void 0:ze.length)!=null?Ae:0,(Re=(ke=(be=(We=e.reasoning)==null?void 0:We.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:ke.slice(-32))!=null?Re:"",(Q=(de=e.contentParts)==null?void 0:de.length)!=null?Q:0,(re=e.stopReason)!=null?re:"",t].join("\0")}function am(){return new Map}function im(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function lm(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function cm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function bi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Xr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Xo(e,t){return Xr(e)-e.scrollTop<=t}function yi(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function xi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function dm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function pm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function um(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var En={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Mn=1e5,vo=Mn+1;var da={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},qf=["pre","code","a","script","style"],vi=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:da.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:da.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:da.speed,duration:(o=e==null?void 0:e.duration)!=null?o:da.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:da.buffer}},gm=[{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"}],pa=new Map;for(let e of gm)pa.set(e.name,e);var fm=e=>{pa.set(e.name,e)},hm=e=>{gm.some(t=>t.name===e)||pa.delete(e)},bm=()=>Array.from(pa.keys()),ua=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=pa.get(e))!=null?r:null},wi=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
15
- `);return s<0?"":e.slice(0,s)}return e},zf=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},Vf=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},vl=/\s/,Kf=(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},Jf=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(vl.test(s[i])){let l=i;for(;l<s.length&&vl.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!vl.test(s[p]);)l.appendChild(zf(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Gf=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(Vf(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},ma=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:qf).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Kf(d,s)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?Jf:Gf;for(let m of i)p(m,n,l);return o.innerHTML},Ci=(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},ga=(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},mm=new WeakMap,Xf=(e,t)=>{var s;if(!e.styles)return;let n=mm.get(t);if(n||(n=new Set,mm.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 o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},wl=new WeakMap,Qf=(e,t)=>{if(!e.onAttach)return;let n=wl.get(t);if(n||(n=new Map,wl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},ym=e=>{let t=wl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Cl=(e,t)=>{Xf(e,t),Qf(e,t)};function Al(e,t=Mn){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.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=o}}var fa=0,wo=null;function Sl(e=document){var n;if(fa++,fa===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;wo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,fa=Math.max(0,fa-1),fa===0&&wo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=wo.originalOverflow,o.style.position=wo.originalPosition,o.style.top=wo.originalTop,o.style.width=wo.originalWidth,s.scrollTo(0,wo.scrollY),wo=null}}}var Ai={side:"right",width:"420px",animate:!0,reveal:"resize"},gn=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"},mr=e=>{var n,r,o,s,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:Ai.side,width:(o=t==null?void 0:t.width)!=null?o:Ai.width,animate:(s=t==null?void 0:t.animate)!=null?s:Ai.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Ai.reveal}};var Sr={"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 ha=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
14
+ _Details: ${n.message}_`:r}var ga=e=>({isError:!0,content:[{type:"text",text:e}]}),wm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Cm=e=>zo(e)||e===Sr,Es=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,o,s,a,i,d,l,p,u;if(t.type==="message"){this.upsertMessage(t.message);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(zo(f.name)||f.name===Sr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.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:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i: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 f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Go(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,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 ma((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,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Xo(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"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,u,f,g,v,y;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}):(u=l.transcript)!=null&&u.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=l.text)!=null&&g.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let w=(y=this.pendingVoiceAssistantMessageId)!=null?y:(v=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:v.id;w&&this.ttsSpokenMessageIds.add(w)}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,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}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,o,s,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:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.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){let n={...this.config,...t};if(!fh(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new Go(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}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:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?Ts():n==="assistant"?Jo():`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,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}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:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,y={id:d!=null?d:o==="user"?Ts():o==="assistant"?Jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(y)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,u,f,g;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 o=Ts(),s=Jo(),a={id:o,role:"user",content:r||fi,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:s},this.handleEvent)}catch(v){let y=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!y){let w=vm(v,this.config.errorMessage);if(w){let S={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(S)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Jo();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 u=vm(l,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.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=(s=this.callbacks).onError)==null||a.call(s,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 o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,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 o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,v;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(y=>y.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let y;if(l?y=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):y=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),y){let w=null;if(y instanceof Response){if(!y.ok){let S=await y.json().catch(()=>null);throw new Error((f=S==null?void 0:S.error)!=null?f:`Approval request failed: ${y.status}`)}w=y.body}else y instanceof ReadableStream&&(w=y);w?await this.connectStream(w,{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(y){let w=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));this.setStreaming(!1),this.abortController=null,w||(v=(g=this.callbacks).onError)==null||v.call(g,y instanceof Error?y:new Error(String(y)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,v,y,w,S,O,k,I,R;let r=this.messages.find(T=>T.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(v=(g=this.callbacks).onError)==null||v.call(g,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 T=(y=t.toolCall)==null?void 0:y.args,W=Array.isArray(T==null?void 0:T.questions)?T.questions:[];if(W.length===1){let _=typeof((w=W[0])==null?void 0:w.question)=="string"?W[0].question:"";_&&(a={[_]:n})}}this.markAskUserQuestionResolved(t,a),(S=this.abortController)==null||S.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(O=t.toolCall)==null?void 0:O.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let T=typeof n=="string"?n:Object.entries(n).map(([W,_])=>`${W}: ${Array.isArray(_)?_.join(", "):_}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let T=a!=null?a:{};l.forEach((W,_)=>{let F=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!F)return;let M=T[F],j=Array.isArray(M)?M.join(", "):typeof M=="string"?M:"";this.appendMessage({id:`ask-user-q-${i}-${_}`,role:"assistant",content:F,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${_}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let T=await this.client.resumeFlow(o,{[s]:n});if(!T.ok){let W=await T.json().catch(()=>null);throw new Error((k=W==null?void 0:W.error)!=null?k:`Resume failed: ${T.status}`)}T.body?await this.connectStream(T.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(T){let W=T instanceof Error&&(T.name==="AbortError"||T.message.includes("aborted")||T.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(R=(I=this.callbacks).onError)==null||R.call(I,T instanceof Error?T:new Error(String(T)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.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 o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.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)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Sr)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var R,T,W,_,F,M,j;let g=(R=f.toolCall)==null?void 0:R.name,v=(T=f.toolCall)==null?void 0:T.id;if(!g||!v)return null;let y=`${t}:${v}`;if(this.webMcpInflightKeys.has(y)||this.webMcpResolvedKeys.has(y)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(y),r.push(y);let w=this.markWebMcpToolRunning(f),S=(_=(W=f.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?_:g;if(g===Sr)return{dedupeKey:y,resumeKey:S,output:El(),toolMessage:f,startedAt:w,completedAt:Date.now()};let O=new AbortController;this.webMcpResolveControllers.add(O),o.push(O);let k=this.client.executeWebMcpToolCall(g,(F=f.toolCall)==null?void 0:F.args,O.signal),I;if(!k)I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{I=await k}catch(z){let oe=z instanceof Error&&(z.name==="AbortError"||z.message.includes("aborted")||z.message.includes("abort"));return oe||(j=(M=this.callbacks).onError)==null||j.call(M,z instanceof Error?z:new Error(String(z))),this.markWebMcpToolComplete(f,ga(oe?"Aborted by cancel()":wm(z)),w),this.webMcpInflightKeys.delete(y),null}return O.signal.aborted?(this.markWebMcpToolComplete(f,ga("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(y),null):{dedupeKey:y,resumeKey:S,output:I,toolMessage:f,startedAt:w,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let f={};for(let v of i)f[v.resumeKey]=v.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let v=await g.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${g.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((l=v.toolMessage.toolCall)==null?void 0:l.name)===Sr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ga("Aborted by cancel()"),v.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var v,y,w,S,O,k,I,R,T,W,_,F;let n=(v=t.agentMetadata)==null?void 0:v.executionId,r=(y=t.toolCall)==null?void 0:y.name,o=(w=t.toolCall)==null?void 0:w.id;if(!n){(O=(S=this.callbacks).onError)==null||O.call(S,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!o){let M=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))return;this.webMcpInflightKeys.add(M);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(M)}catch(j){(I=(k=this.callbacks).onError)==null||I.call(k,j instanceof Error?j:new Error(String(j)))}finally{this.webMcpInflightKeys.delete(M)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=r===Sr,p=(R=t.toolCall)==null?void 0:R.args,u=l?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let M;if(l?M=El():u?M=await u:M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ga("Aborted by cancel()"),a);return}let j=(W=(T=t.agentMetadata)==null?void 0:T.webMcpToolCallId)!=null?W:r;f="resume",await this.resumeWithToolOutput(n,j,M,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,M,a,g,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(M){let j=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));(f==="execute"||j||d.aborted)&&this.markWebMcpToolComplete(t,ga(j||d.aborted?"Aborted by cancel()":wm(M)),a),j||(F=(_=this.callbacks).onError)==null||F.call(_,M instanceof Error?M:new Error(String(M)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.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 o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};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 o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.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 o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o: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(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=r.content;o.trim()&&this.speak(o,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t),s=r.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(o.rate=n.rate),n.pitch!==void 0&&(o.pitch=n.pitch),setTimeout(()=>r.speak(o),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 o of n){let s=t.find(a=>a.name===o);if(s)return s}return(r=t.find(o=>o.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(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,v,y,w,S,O,k,I,R,T,W,_;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let F=o.approval,M=n.approval;a.approval={...F,...M,executionId:M.executionId||F.executionId,toolName:M.toolName||F.toolName,description:M.description||F.description,toolType:(g=M.toolType)!=null?g:F.toolType,reason:(v=M.reason)!=null?v:F.reason,parameters:(y=M.parameters)!=null?y:F.parameters}}let i=(w=n.toolCall)==null?void 0:w.name,d=(S=n.agentMetadata)==null?void 0:S.executionId,l=(O=n.toolCall)==null?void 0:O.id;if(i&&Cm(i)&&d&&l&&((k=n.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let F=`${d}:${l}`,M=this.webMcpInflightKeys.has(F),j=this.webMcpResolvedKeys.has(F),z=(I=o.toolCall)==null?void 0:I.name,oe=((R=o.agentMetadata)==null?void 0:R.executionId)===d&&((T=o.toolCall)==null?void 0:T.id)===l&&z!==void 0&&Cm(z)&&((W=o.toolCall)==null?void 0:W.status)==="complete";(M||j||oe)&&(a.agentMetadata={...(_=a.agentMetadata)!=null?_:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}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 o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;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 C=require("lucide"),hh={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},Ce=(e,t=24,n="currentColor",r=2)=>{let o=hh[e];return o?bh(o,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 bh(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[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))}),o.appendChild(d)}),o}var vi={allowedTypes:Yr,maxFileSize:10*1024*1024,maxFiles:4};function yh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xh(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 Yo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:vi.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:vi.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:vi.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:vi.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,o,s,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=ym(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await bm(l),f=hi(l)?URL.createObjectURL(l):null,g={id:yh(),file:l,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,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 o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.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=hi(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=xh(t.file.type),d=Ce(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=xm(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 o=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ce("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),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 Am=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function fa(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Am(s)&&Am(o)?n[r]=fa(s,o):n[r]=o}return n}var nr="min(440px, calc(100vw - 24px))",wi="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:nr,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:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},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 Sm(e,t){if(!(!e&&!t))return e?t?fa(e,t):e:t}function Ci(e){var t,n,r,o,s,a,i,d,l,p,u,f,g,v,y,w,S,O,k,I,R;return e?{...Nt,...e,theme:Sm(Nt.theme,e.theme),darkTheme:Sm(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,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Nt.copy,...e.copy},sendButton:{...Nt.sendButton,...e.sendButton},statusIndicator:{...Nt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...e.voiceRecognition},features:(()=>{var de,X,re,ce,ge,K,ae,He,Y,ee;let T=(de=Nt.features)==null?void 0:de.artifacts,W=(X=e.features)==null?void 0:X.artifacts,_=(re=Nt.features)==null?void 0:re.scrollToBottom,F=(ce=e.features)==null?void 0:ce.scrollToBottom,M=(ge=Nt.features)==null?void 0:ge.scrollBehavior,j=(K=e.features)==null?void 0:K.scrollBehavior,z=(ae=Nt.features)==null?void 0:ae.streamAnimation,oe=(He=e.features)==null?void 0:He.streamAnimation,ke=(Y=Nt.features)==null?void 0:Y.askUserQuestion,ze=(ee=e.features)==null?void 0:ee.askUserQuestion,Ae=T===void 0&&W===void 0?void 0:{...T,...W,layout:{...T==null?void 0:T.layout,...W==null?void 0:W.layout}},Re=_===void 0&&F===void 0?void 0:{..._,...F},be=M===void 0&&j===void 0?void 0:{...M,...j},Le=z===void 0&&oe===void 0?void 0:{...z,...oe},We=ke===void 0&&ze===void 0?void 0:{...ke,...ze,styles:{...ke==null?void 0:ke.styles,...ze==null?void 0:ze.styles}};return{...Nt.features,...e.features,...Re!==void 0?{scrollToBottom:Re}:{},...be!==void 0?{scrollBehavior:be}:{},...Ae!==void 0?{artifacts:Ae}:{},...Le!==void 0?{streamAnimation:Le}:{},...We!==void 0?{askUserQuestion:We}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s: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:{...(u=(p=Nt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(y=(v=Nt.layout)==null?void 0:v.messages)==null?void 0:y.timestamp,...(S=(w=e.layout)==null?void 0:w.messages)==null?void 0:S.timestamp}},slots:{...(O=Nt.layout)==null?void 0:O.slots,...(k=e.layout)==null?void 0:k.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 Rl={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"}},Wl={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"}},Hl={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:nr,maxWidth:wi,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:"palette.shadows.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",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},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 Ms(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Ms(e,r):r}function Ai(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ms(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.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 Bl(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 Tm(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Tm(s,o):n[r]=o}return n}function vh(e,t){return t?Tm(e,t):e}function ks(e,t={}){var o,s,a,i,d,l,p,u,f,g,v,y,w;let n={palette:Rl,semantic:Wl,components:Hl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.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,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(v=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(y=e==null?void 0:e.semantic)==null?void 0:y.spacing},typography:{...n.semantic.typography,...(w=e==null?void 0:e.semantic)==null?void 0:w.typography}},components:vh(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let S=Bl(r);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(O=>O.message).join(", ")}`)}if(t.plugins)for(let S of t.plugins)r=S.transform(r);return r}function Si(e){var y,w,S,O,k,I,R,T,W,_,F,M,j,z,oe,ke,ze,Ae,Re,be,Le,We,de,X,re,ce,ge,K,ae,He,Y,ee,ie,Se,Ze,ve,fe,Je,De,V,ue,ot,Et,ne,Ve,Nn,Ht,cn,sr,Er,H,pe,Oe,Qe,_e,Ue,at,Pt,Kt,Zt,G,xt,lt,we,le,nt,tn,Gt,Pn,wn,mt,Mt,et,qt,dn,An,Sn,yn,Mr,At,jn,qn,Nr,fr,vt,Lo,kr,Po,Fn,ss,ro,Fr,St,zn,Vn,In,Lt,ar,ir,Kn,oo,_r,so,Gn,Bt,Rn,lr,ao,$r,io,Lr,Jn,hr,ft,nn,rn,Qn,lo;let t=Ai(e),n={};for(let[ye,br]of Object.entries(t)){let cr=ye.replace(/\./g,"-");n[`--persona-${cr}`]=br.value}n["--persona-primary"]=(y=n["--persona-semantic-colors-primary"])!=null?y:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(w=n["--persona-semantic-colors-secondary"])!=null?w:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(S=n["--persona-semantic-colors-accent"])!=null?S:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(O=n["--persona-semantic-colors-surface"])!=null?O:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(k=n["--persona-semantic-colors-background"])!=null?k: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"]=(T=n["--persona-semantic-colors-text-muted"])!=null?T: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"]=(F=n["--persona-semantic-colors-divider"])!=null?F:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(M=n["--persona-components-voice-recording-indicator"])!=null?M:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(j=n["--persona-components-voice-recording-background"])!=null?j:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(z=n["--persona-components-voice-processing-icon"])!=null?z:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(oe=n["--persona-components-voice-speaking-icon"])!=null?oe:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(ke=n["--persona-components-approval-requested-background"])!=null?ke:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(ze=n["--persona-components-approval-requested-border"])!=null?ze:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ae=n["--persona-components-approval-requested-text"])!=null?Ae:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Re=n["--persona-components-approval-requested-shadow"])!=null?Re:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(be=n["--persona-components-approval-approve-background"])!=null?be:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(Le=n["--persona-components-approval-deny-background"])!=null?Le:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(We=n["--persona-components-attachment-image-background"])!=null?We:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(de=n["--persona-components-attachment-image-border"])!=null?de:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(X=n["--persona-semantic-typography-fontFamily"])!=null?X:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(re=n["--persona-semantic-typography-fontSize"])!=null?re:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ce=n["--persona-semantic-typography-fontWeight"])!=null?ce:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(ge=n["--persona-semantic-typography-lineHeight"])!=null?ge: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"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(ae=n["--persona-palette-radius-md"])!=null?ae:"0.375rem",n["--persona-radius-lg"]=(He=n["--persona-palette-radius-lg"])!=null?He:"0.5rem",n["--persona-radius-xl"]=(Y=n["--persona-palette-radius-xl"])!=null?Y:"0.75rem",n["--persona-radius-full"]=(ee=n["--persona-palette-radius-full"])!=null?ee:"9999px",n["--persona-launcher-radius"]=(Se=(ie=n["--persona-components-launcher-borderRadius"])!=null?ie:n["--persona-palette-radius-full"])!=null?Se:"9999px",n["--persona-launcher-bg"]=(Ze=n["--persona-components-launcher-background"])!=null?Ze:n["--persona-primary"],n["--persona-launcher-fg"]=(ve=n["--persona-components-launcher-foreground"])!=null?ve:n["--persona-text-inverse"],n["--persona-launcher-border"]=(fe=n["--persona-components-launcher-border"])!=null?fe:n["--persona-border"],n["--persona-button-primary-bg"]=(Je=n["--persona-components-button-primary-background"])!=null?Je:n["--persona-primary"],n["--persona-button-primary-fg"]=(De=n["--persona-components-button-primary-foreground"])!=null?De:n["--persona-text-inverse"],n["--persona-button-radius"]=(ue=(V=n["--persona-components-button-primary-borderRadius"])!=null?V:n["--persona-palette-radius-full"])!=null?ue:"9999px",n["--persona-panel-radius"]=(Et=(ot=n["--persona-components-panel-borderRadius"])!=null?ot:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(ne=n["--persona-components-panel-border"])!=null?ne:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Nn=(Ve=n["--persona-components-panel-shadow"])!=null?Ve:n["--persona-palette-shadows-xl"])!=null?Nn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Ht=n["--persona-components-launcher-shadow"])!=null?Ht:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(sr=(cn=n["--persona-components-input-borderRadius"])!=null?cn:n["--persona-radius-lg"])!=null?sr:"0.5rem",n["--persona-message-user-radius"]=(H=(Er=n["--persona-components-message-user-borderRadius"])!=null?Er:n["--persona-radius-lg"])!=null?H:"0.5rem",n["--persona-message-assistant-radius"]=(Oe=(pe=n["--persona-components-message-assistant-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?Oe:"0.5rem",n["--persona-header-bg"]=(Qe=n["--persona-components-header-background"])!=null?Qe:n["--persona-surface"],n["--persona-header-border"]=(_e=n["--persona-components-header-border"])!=null?_e:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ue=n["--persona-components-header-iconBackground"])!=null?Ue:n["--persona-primary"],n["--persona-header-icon-fg"]=(at=n["--persona-components-header-iconForeground"])!=null?at: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"]=(Kt=n["--persona-components-header-subtitleForeground"])!=null?Kt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Zt=n["--persona-components-header-actionIconForeground"])!=null?Zt:n["--persona-muted"];let r=(G=e.components)==null?void 0:G.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(xt=e.components)==null?void 0:xt.introCard;n["--persona-intro-card-bg"]=(lt=n["--persona-components-introCard-background"])!=null?lt:n["--persona-surface"],n["--persona-intro-card-radius"]=(we=n["--persona-components-introCard-borderRadius"])!=null?we:"1rem",n["--persona-intro-card-padding"]=(le=n["--persona-components-introCard-padding"])!=null?le:"1.5rem",n["--persona-intro-card-shadow"]=(tn=(nt=o==null?void 0:o.shadow)!=null?nt:n["--persona-components-introCard-shadow"])!=null?tn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Gt=n["--persona-components-input-background"])!=null?Gt:n["--persona-surface"],n["--persona-input-placeholder"]=(Pn=n["--persona-components-input-placeholder"])!=null?Pn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(wn=n["--persona-components-message-user-background"])!=null?wn:n["--persona-accent"],n["--persona-message-user-text"]=(mt=n["--persona-components-message-user-text"])!=null?mt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Mt=n["--persona-components-message-user-shadow"])!=null?Mt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(et=n["--persona-components-message-assistant-background"])!=null?et:n["--persona-surface"],n["--persona-message-assistant-text"]=(qt=n["--persona-components-message-assistant-text"])!=null?qt:n["--persona-text"],n["--persona-message-assistant-border"]=(dn=n["--persona-components-message-assistant-border"])!=null?dn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(An=n["--persona-components-message-assistant-shadow"])!=null?An:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(yn=(Sn=n["--persona-components-scrollToBottom-background"])!=null?Sn:n["--persona-button-primary-bg"])!=null?yn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(At=(Mr=n["--persona-components-scrollToBottom-foreground"])!=null?Mr:n["--persona-button-primary-fg"])!=null?At:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(jn=n["--persona-components-scrollToBottom-border"])!=null?jn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(qn=n["--persona-components-scrollToBottom-size"])!=null?qn:"40px",n["--persona-scroll-to-bottom-radius"]=(vt=(fr=(Nr=n["--persona-components-scrollToBottom-borderRadius"])!=null?Nr:n["--persona-button-radius"])!=null?fr:n["--persona-radius-full"])!=null?vt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(kr=(Lo=n["--persona-components-scrollToBottom-shadow"])!=null?Lo:n["--persona-palette-shadows-sm"])!=null?kr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Po=n["--persona-components-scrollToBottom-padding"])!=null?Po:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Fn=n["--persona-components-scrollToBottom-gap"])!=null?Fn:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(ro=(ss=n["--persona-components-scrollToBottom-fontSize"])!=null?ss:n["--persona-palette-typography-fontSize-sm"])!=null?ro:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Fr=n["--persona-components-scrollToBottom-iconSize"])!=null?Fr:"14px",n["--persona-tool-bubble-shadow"]=(St=n["--persona-components-toolBubble-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(zn=n["--persona-components-reasoningBubble-shadow"])!=null?zn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Vn=n["--persona-components-composer-shadow"])!=null?Vn:"none",n["--persona-md-inline-code-bg"]=(In=n["--persona-components-markdown-inlineCode-background"])!=null?In:n["--persona-container"],n["--persona-md-inline-code-color"]=(Lt=n["--persona-components-markdown-inlineCode-foreground"])!=null?Lt:n["--persona-text"],n["--persona-md-link-color"]=(ir=(ar=n["--persona-components-markdown-link-foreground"])!=null?ar:n["--persona-accent"])!=null?ir:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);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"]=(Kn=n["--persona-components-markdown-codeBlock-background"])!=null?Kn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(oo=n["--persona-components-markdown-codeBlock-borderColor"])!=null?oo:n["--persona-border"],n["--persona-md-code-block-text-color"]=(_r=n["--persona-components-markdown-codeBlock-textColor"])!=null?_r:"inherit",n["--persona-md-table-header-bg"]=(so=n["--persona-components-markdown-table-headerBackground"])!=null?so:n["--persona-container"],n["--persona-md-table-border-color"]=(Gn=n["--persona-components-markdown-table-borderColor"])!=null?Gn:n["--persona-border"],n["--persona-md-hr-color"]=(Bt=n["--persona-components-markdown-hr-color"])!=null?Bt:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Rn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Rn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(lr=n["--persona-components-markdown-blockquote-background"])!=null?lr:"transparent",n["--persona-md-blockquote-text-color"]=(ao=n["--persona-components-markdown-blockquote-textColor"])!=null?ao:n["--persona-palette-colors-gray-500"],n["--cw-container"]=($r=n["--persona-components-collapsibleWidget-container"])!=null?$r:n["--persona-surface"],n["--cw-surface"]=(io=n["--persona-components-collapsibleWidget-surface"])!=null?io:n["--persona-surface"],n["--cw-border"]=(Lr=n["--persona-components-collapsibleWidget-border"])!=null?Lr:n["--persona-border"],n["--persona-message-border"]=(Jn=n["--persona-components-message-border"])!=null?Jn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let ye=v.toolbar;ye.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,n["--persona-dropdown-bg"]=(hr=n["--persona-dropdown-bg"])!=null?hr:ye.copyMenuBackground),ye.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,n["--persona-dropdown-border"]=(ft=n["--persona-dropdown-border"])!=null?ft:ye.copyMenuBorder),ye.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,n["--persona-dropdown-shadow"]=(nn=n["--persona-dropdown-shadow"])!=null?nn:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(rn=n["--persona-dropdown-radius"])!=null?rn:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Qn=n["--persona-dropdown-item-hover-bg"])!=null?Qn:ye.copyMenuItemHoverBackground),ye.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(v!=null&&v.tab){let ye=v.tab;ye.background&&(n["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(n["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(n["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(n["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(n["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(n["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(n["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(v!=null&&v.pane){let ye=v.pane;if(ye.toolbarBackground){let br=(lo=Ms(e,ye.toolbarBackground))!=null?lo:ye.toolbarBackground;n["--persona-artifact-toolbar-bg"]=br}}return n}var Em={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 wh={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"}}},Mm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ha=()=>{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"},Ch=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ha()},Dl=e=>Ch(e),Ah=e=>ks(e),Sh=e=>{var n;let t=ks(void 0,{validate:!1});return ks({...e,palette:{...t.palette,colors:{...wh.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ls=e=>{let t=Dl(e),n=Mm(e==null?void 0:e.theme),r=Mm(e==null?void 0:e.darkTheme);return t==="dark"?Sh(fa(n!=null?n:{},r!=null?r:{})):Ah(n)},Th=e=>Si(e),Ao=(e,t)=>{let n=Ls(t),r=Th(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},Ti=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ha())});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(ha());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 km=require("idiomorph"),Ei=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;km.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Mi={index:-1,draft:""};function Lm(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Mi}}}function Pm(e,t){var n,r,o,s,a,i,d,l,p,u,f,g,v,y,w,S,O,k,I,R,T,W,_,F,M,j,z,oe,ke,ze,Ae,Re,be,Le,We,de,X,re;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",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,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(v=(g=e.toolCall)==null?void 0:g.status)!=null?v:"",(w=(y=e.toolCall)==null?void 0:y.name)!=null?w:"",(k=(O=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:O.length)!=null?k:0,(W=(T=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R[e.toolCall.chunks.length-1])==null?void 0:T.slice(-32))!=null?W:"",typeof((_=e.toolCall)==null?void 0:_.args)=="string"?e.toolCall.args.length:(F=e.toolCall)!=null&&F.args?JSON.stringify(e.toolCall.args).length:0,(z=(j=(M=e.reasoning)==null?void 0:M.chunks)==null?void 0:j.length)!=null?z:0,(Ae=(ze=(ke=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:ke[e.reasoning.chunks.length-1])==null?void 0:ze.length)!=null?Ae:0,(We=(Le=(be=(Re=e.reasoning)==null?void 0:Re.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Le.slice(-32))!=null?We:"",(X=(de=e.contentParts)==null?void 0:de.length)!=null?X:0,(re=e.stopReason)!=null?re:"",t].join("\0")}function Im(){return new Map}function Rm(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Wm(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Hm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ki(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Zr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Zo(e,t){return Zr(e)-e.scrollTop<=t}function Li(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Pi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function Bm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Dm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Om(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var kn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Ln=1e5,So=Ln+1;var ba={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Eh=["pre","code","a","script","style"],Ii=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ba.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ba.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ba.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ba.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ba.buffer}},Fm=[{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"}],ya=new Map;for(let e of Fm)ya.set(e.name,e);var _m=e=>{ya.set(e.name,e)},$m=e=>{Fm.some(t=>t.name===e)||ya.delete(e)},Um=()=>Array.from(ya.keys()),xa=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=ya.get(e))!=null?r:null},Ri=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
15
+ `);return s<0?"":e.slice(0,s)}return e},Mh=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},kh=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},Ol=/\s/,Lh=(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},Ph=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Ol.test(s[i])){let l=i;for(;l<s.length&&Ol.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Ol.test(s[p]);)l.appendChild(Mh(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Ih=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(kh(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},va=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:Eh).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Lh(d,s)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?Ph:Ih;for(let g of i)p(g,n,l);return o.innerHTML},Wi=(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},wa=(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},Nm=new WeakMap,Rh=(e,t)=>{var s;if(!e.styles)return;let n=Nm.get(t);if(n||(n=new Set,Nm.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 o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},Nl=new WeakMap,Wh=(e,t)=>{if(!e.onAttach)return;let n=Nl.get(t);if(n||(n=new Map,Nl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},jm=e=>{let t=Nl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Fl=(e,t)=>{Rh(e,t),Wh(e,t)};function _l(e,t=Ln){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.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=o}}var Ca=0,To=null;function $l(e=document){var n;if(Ca++,Ca===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;To={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,Ca=Math.max(0,Ca-1),Ca===0&&To)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=To.originalOverflow,o.style.position=To.originalPosition,o.style.top=To.originalTop,o.style.width=To.originalWidth,s.scrollTo(0,To.scrollY),To=null}}}var Aa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},mn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Eo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},rr=e=>{var n,r,o,s,a,i;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:Aa.side,width:(o=t==null?void 0:t.width)!=null?o:Aa.width,animate:(s=t==null?void 0:t.animate)!=null?s:Aa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Aa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Aa.maxHeight}};var Tr={"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 Sa=(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: ${n.message}_`:r}var ia=e=>({isError:!0,content:[{type:"text",text:e}]
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
- `,n.addEventListener("click",t);let r=s=>{var M,I,W,S,k,$,O,H,U,J,ce,Me,ze;let a=(M=s.launcher)!=null?M:{},i=gn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let Ae=(I=a.title)!=null?I:"Chat Assistant";d.textContent=Ae,d.setAttribute("title",Ae)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let Ae=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=Ae,l.setAttribute("title",Ae)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let Ae=(S=a.agentIconSize)!=null?S:"40px";if(u.style.height=Ae,u.style.width=Ae,u.innerHTML="",a.agentIconName){let We=parseFloat(Ae)||24,be=Ce(a.agentIconName,We*.6,"var(--persona-text-inverse, #ffffff)",2);be?(u.appendChild(be),u.style.display=""):(u.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=($=a.agentIconText)!=null?$:"\u{1F4AC}",u.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let Ae=(O=a.agentIconSize)!=null?O:"40px";f.style.height=Ae,f.style.width=Ae,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ae=(H=a.callToActionIconSize)!=null?H:"32px";m.style.height=Ae,m.style.width=Ae,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let We=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,We=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let be=parseFloat(Ae)||24,ke=Math.max(be-We,8),Re=Ce(a.callToActionIconName,ke,"currentColor",2);Re?m.appendChild(Re):m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else m.textContent=(J=a.callToActionIconText)!=null?J:"\u2197"}let v=a.position&&Sr[a.position]?Sr[a.position]:Sr["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",w="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?w:`${x} ${v}`,i||(n.style.zIndex=String((ce=a.zIndex)!=null?ce:Mn));let T="1px solid var(--persona-border, #e5e7eb)",N="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Me=a.border)!=null?Me:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:N,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=(ze=a.collapsedMaxWidth)!=null?ze:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Yf="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Si=(e,t={})=>{var x,w,T,N,M,I;let{showClose:n=!0,wrapperClassName:r=Yf,buttonSize:o,iconSize:s="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(w=o!=null?o:a.closeButtonSize)!=null?w:"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=(T=a.closeButtonTooltipText)!=null?T:"Close chat",u=(N=a.closeButtonShowTooltip)!=null?N:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let f=(M=a.closeButtonIconName)!=null?M:"x",m=(I=a.closeButtonIconText)!=null?I:"\xD7";l.style.color=a.closeButtonColor||Hn.actionIconColor;let v=Ce(f,s,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=m,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 W=a.closeButtonBorderWidth||"0px",S=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${S}`,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),u&&p){let W=null,S=()=>{if(W)return;let $=l.ownerDocument,O=$.body;if(!O)return;W=Br($,"div","persona-clear-chat-tooltip"),W.textContent=p;let H=Br($,"div");H.className="persona-clear-chat-tooltip-arrow",W.appendChild(H);let U=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(vo),W.style.left=`${U.left+U.width/2}px`,W.style.top=`${U.top-8}px`,W.style.transform="translate(-50%, -100%)",O.appendChild(W)},k=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",S),d.addEventListener("mouseleave",k),l.addEventListener("focus",S),l.addEventListener("blur",k),d._cleanupTooltip=()=>{k(),d.removeEventListener("mouseenter",S),d.removeEventListener("mouseleave",k),l.removeEventListener("focus",S),l.removeEventListener("blur",k)}}return{button:l,wrapper:d}},Zf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ti=(e,t={})=>{var W,S,k,$,O,H,U,J,ce,Me,ze,Ae,We;let{wrapperClassName:n=Zf,buttonSize:r,iconSize:o="20px"}=t,a=(S=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?S:{},i=(k=r!=null?r:a.size)!=null?k:"32px",d=($=a.iconName)!=null?$:"refresh-cw",l=(O=a.iconColor)!=null?O:"",p=(H=a.backgroundColor)!=null?H:"",u=(U=a.borderWidth)!=null?U:"",f=(J=a.borderColor)!=null?J:"",m=(ce=a.borderRadius)!=null?ce:"",v=(Me=a.paddingX)!=null?Me:"",x=(ze=a.paddingY)!=null?ze:"",w=(Ae=a.tooltipText)!=null?Ae:"Clear chat",T=(We=a.showTooltip)!=null?We:!0,N=h("div",n),M=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");M.style.height=i,M.style.width=i,M.type="button",M.setAttribute("aria-label",w),M.style.color=l||Hn.actionIconColor;let I=Ce(d,o,"currentColor",1);if(I&&(I.style.display="block",M.appendChild(I)),p&&(M.style.backgroundColor=p,M.classList.remove("hover:persona-bg-gray-100")),u||f){let be=u||"0px",ke=f||"transparent";M.style.border=`${be} solid ${ke}`,M.classList.remove("persona-border-none")}if(m&&(M.style.borderRadius=m,M.classList.remove("persona-rounded-full")),v&&(M.style.paddingLeft=v,M.style.paddingRight=v),x&&(M.style.paddingTop=x,M.style.paddingBottom=x),N.appendChild(M),T&&w){let be=null,ke=()=>{if(be)return;let de=M.ownerDocument,Q=de.body;if(!Q)return;be=Br(de,"div","persona-clear-chat-tooltip"),be.textContent=w;let re=Br(de,"div");re.className="persona-clear-chat-tooltip-arrow",be.appendChild(re);let le=M.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(vo),be.style.left=`${le.left+le.width/2}px`,be.style.top=`${le.top-8}px`,be.style.transform="translate(-50%, -100%)",Q.appendChild(be)},Re=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};N.addEventListener("mouseenter",ke),N.addEventListener("mouseleave",Re),M.addEventListener("focus",ke),M.addEventListener("blur",Re),N._cleanupTooltip=()=>{Re(),N.removeEventListener("mouseenter",ke),N.removeEventListener("mouseleave",Re),M.removeEventListener("focus",ke),M.removeEventListener("blur",Re)}}return{button:M,wrapper:N}};var Hn={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))"},Qr=e=>{var W,S,k,$,O,H,U,J,ce,Me,ze,Ae,We,be,ke,Re;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 o=(W=t==null?void 0:t.launcher)!=null?W:{},s=(S=o.headerIconSize)!=null?S:"48px",a=(k=o.closeButtonPlacement)!=null?k:"inline",i=($=o.headerIconHidden)!=null?$:!1,d=o.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,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 de=parseFloat(s)||24,Q=Ce(d,de*.6,"currentColor",1);Q?l.replaceChildren(Q):l.textContent=(H=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?H:"\u{1F4AC}"}else if((U=t==null?void 0:t.launcher)!=null&&U.iconUrl){let de=h("img");de.src=t.launcher.iconUrl,de.alt="",de.className="persona-rounded-xl persona-object-cover",de.style.height=s,de.style.width=s,l.replaceChildren(de)}else l.textContent=(ce=(J=t==null?void 0:t.launcher)==null?void 0:J.agentIconText)!=null?ce:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=h("span","persona-text-base persona-font-semibold");u.style.color=Hn.titleColor,u.textContent=(ze=(Me=t==null?void 0:t.launcher)==null?void 0:Me.title)!=null?ze:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Hn.subtitleColor,f.textContent=(We=(Ae=t==null?void 0:t.launcher)==null?void 0:Ae.subtitle)!=null?We:"Here to help you get answers fast",p.append(u,f),i?r.append(p):r.append(l,p);let m=(be=o.clearChat)!=null?be:{},v=(ke=m.enabled)!=null?ke:!0,x=(Re=m.placement)!=null?Re:"inline",w=null,T=null;if(v){let Q=Ti(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=Q.button,T=Q.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let N=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:M,wrapper:I}=Si(t,{showClose:n,wrapperClassName:N});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:M,closeButtonWrapper:I,clearChatButton:w,clearChatButtonWrapper:T}},Qo=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Ao(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(vo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let w=document.createElement("hr");a.appendChild(w)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let w=Ce(m.icon,16,"currentColor",1.5);w&&v.appendChild(w)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",w=>{w.stopPropagation(),p(),n(m.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:f}}function Kt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ce(t,r!=null?r:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function ba(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let f=Ce(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=h("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))p.setAttribute(f,m);return p}function ya(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=h("div","persona-toggle-group"+(o?" "+o:""));s.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 u;p.icon?u=Kt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=h("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Ei(e){var m,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="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 u=Ce(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"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,w;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(w=d.border)!=null?w:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Ao({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let w=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",w?"false":"true"),f.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"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var Tl=e=>{var r;let t=Qr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function eh(e,t,n){var r,o,s;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",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Ce(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=h("div","persona-relative");d.appendChild(i);let l=Ao({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 El=e=>{var N,M,I,W,S,k,$,O,H;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(N=t==null?void 0:t.launcher)!=null?N:{},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=o==null?void 0:o.titleMenu,l,p;if(d)l=Ei({label:(M=a.title)!=null?M:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Hn.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=Hn.titleColor,p.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(p),eh(l,o==null?void 0:o.trailingActions,(S=o==null?void 0:o.onAction)!=null?S:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let J=o.onTitleClick;l.addEventListener("click",ce=>{ce.target.closest("button")||J()}),l.addEventListener("keydown",ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),J())})}let U=o==null?void 0:o.titleRowHover;U&&(l.style.borderRadius=(k=U.borderRadius)!=null?k:"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 J,ce;l.style.backgroundColor=(J=U.background)!=null?J:"",l.style.borderColor=(ce=U.border)!=null?ce:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(O=a.closeButtonSize)!=null?O:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Hn.actionIconColor;let v=(H=a.closeButtonIconName)!=null?H:"x",x=Ce(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),f.appendChild(m),i.appendChild(f);let w=h("div");w.style.display="none";let T=h("span");return T.style.display="none",{header:i,iconHolder:w,headerTitle:p,headerSubtitle:T,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Mi={default:Tl,minimal:El},Ml=e=>{var t;return(t=Mi[e])!=null?t:Mi.default},Ss=(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 u=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=Ml(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&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ki=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 o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());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:s}},Li=e=>{var W,S,k,$,O,H,U,J,ce,Me,ze,Ae;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(S=t.useIcon)!=null?S:!1,r=(k=t.iconText)!=null?k:"\u2191",o=t.iconName,s=($=t.stopIconName)!=null?$:"square",a=(O=t.tooltipText)!=null?O:"Send message",i=(H=t.stopTooltipText)!=null?H:"Stop generating",d=(J=(U=e==null?void 0:e.copy)==null?void 0:U.sendButtonLabel)!=null?J:"Send",l=(Me=(ce=e==null?void 0:e.copy)==null?void 0:ce.stopButtonLabel)!=null?Me:"Stop",p=(ze=t.showTooltip)!=null?ze:!1,u=(Ae=t.size)!=null?Ae:"40px",f=t.backgroundColor,m=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 w=null,T=null;if(n){x.style.width=u,x.style.height=u,x.style.minWidth=u,x.style.minHeight=u,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",m?x.style.color=m:x.style.color="var(--persona-button-primary-fg, #ffffff)";let We=parseFloat(u)||24,be=(m==null?void 0:m.trim())||"currentColor";o?(w=Ce(o,We,be,2),w?x.appendChild(w):x.textContent=r):x.textContent=r,T=Ce(s,We,be,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,m?x.style.color=m: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 N=null;p&&a&&(N=h("div","persona-send-button-tooltip"),N.textContent=a,v.appendChild(N)),x.setAttribute("aria-label",a),v.appendChild(x);let M="send";return{button:x,wrapper:v,setMode:We=>{if(We===M)return;M=We;let be=We==="stop"?i:a;if(x.setAttribute("aria-label",be),N&&(N.textContent=be),n){if(w&&T){let ke=We==="stop"?T:w;x.replaceChildren(ke)}}else x.textContent=We==="stop"?l:d}}},Pi=e=>{var N,M,I,W,S,k,$,O,H,U,J,ce;let t=(N=e==null?void 0:e.voiceRecognition)!=null?N:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((M=t.provider)==null?void 0:M.type)==="runtype";if(!(r||o))return null;let a=(W=(I=e==null?void 0:e.sendButton)==null?void 0:I.size)!=null?W:"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=(S=t.iconName)!=null?S:"mic",p=(k=t.iconSize)!=null?k:a,u=parseFloat(p)||24,f=(O=t.backgroundColor)!=null?O:($=e==null?void 0:e.sendButton)==null?void 0:$.backgroundColor,m=(U=t.iconColor)!=null?U:(H=e==null?void 0:e.sendButton)==null?void 0:H.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",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=Ce(l,u,m||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),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 w=(J=t.tooltipText)!=null?J:"Start voice recognition";if(((ce=t.showTooltip)!=null?ce:!1)&&w){let Me=h("div","persona-send-button-tooltip");Me.textContent=w,i.appendChild(Me)}return{button:d,wrapper:i}},Ii=e=>{var v,x,w,T,N,M,I,W;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(w=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?w:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let o=h("input");o.type="file",o.accept=((T=t.allowedTypes)!=null?T:Gr).join(","),o.multiple=((N=t.maxFiles)!=null?N:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=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",(M=t.buttonTooltipText)!=null?M:"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 u=Ce(i,p,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",S=>{S.preventDefault(),o.click()}),s.appendChild(a);let f=(W=t.buttonTooltipText)!=null?W:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,s.appendChild(m),{button:a,wrapper:s,input:o,previewsContainer:r}},Wi=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 o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(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=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},Ri=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ts=e=>{var v,x,w,T,N,M;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=Ri(),o=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");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=ki(t);a();let i=Li(t),d=Pi(t),l=Ii(t),p=Wi(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),u.append(f,m),o.append(u),o.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)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,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:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(N=l==null?void 0:l.input)!=null?N:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:u,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var xm=()=>{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=Ce("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),o=h("span","persona-pill-peek__caret"),s=Ce("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},vm=e=>{var v,x,w,T,N,M;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=Ri();r.style.display="none";let o=Wi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=ki(t);s.style.maxHeight="100px",a();let i=Li(t),d=Pi(t),l=Ii(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 u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.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)&&s.focus()}),l&&p.append(l.input),p.append(u,s,f),l&&n.append(l.previewsContainer),n.append(p,r,o);let m=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,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:o,attachmentButton:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(N=l==null?void 0:l.input)!=null?N:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var wm=e=>{var p,u,f,m,v,x,w,T,N,M,I,W,S,k,$,O,H;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=gn(e);if(Co(e)){let U=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},J=h("div","persona-widget-wrapper persona-fixed persona-transition");J.setAttribute("data-persona-composer-bar",""),J.dataset.state="collapsed",J.dataset.expandedSize=(v=U.expandedSize)!=null?v:"anchored",J.style.zIndex=String((w=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?w:Mn);let ce=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ce.style.width="100%",J.appendChild(ce);let Me=h("div","persona-widget-pill-root");return Me.setAttribute("data-persona-composer-bar",""),Me.dataset.state="collapsed",Me.dataset.expandedSize=(T=U.expandedSize)!=null?T:"anchored",Me.style.zIndex=String((M=(N=e==null?void 0:e.launcher)==null?void 0:N.zIndex)!=null?M:Mn),{wrapper:J,panel:ce,pillRoot:Me}}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"),J=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(J),{wrapper:U,panel:J}}if(!t){let U=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),J=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ce=(W=(I=e==null?void 0:e.launcher)==null?void 0:I.width)!=null?W:"100%";return U.style.width=ce,J.style.width="100%",U.appendChild(J),{wrapper:U,panel:J}}let o=(S=e==null?void 0:e.launcher)!=null?S:{},s=o.position&&Sr[o.position]?Sr[o.position]:Sr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(($=(k=e==null?void 0:e.launcher)==null?void 0:k.zIndex)!=null?$:Mn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=(O=e==null?void 0:e.launcher)==null?void 0:O.width)!=null?H:e==null?void 0:e.launcherWidth,l=d!=null?d:er;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},th=(e,t)=>{var I,W,S,k,$,O,H,U,J;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:o}=Si(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(S=(W=(I=e==null?void 0:e.launcher)==null?void 0:I.clearChat)==null?void 0:W.enabled)!=null?S:!0,a=null,i=null;if(s){let ce=Ti(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ce.button,i=ce.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"),l.style.setProperty("scrollbar-gutter","stable");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 u=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=($=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?$:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(H=(O=e==null?void 0:e.copy)==null?void 0:O.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",p.append(u,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),v=(U=e==null?void 0:e.layout)==null?void 0:U.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((J=e==null?void 0:e.copy)==null?void 0:J.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,m);let w=h("div","persona-composer-overlay persona-pointer-events-none");w.setAttribute("data-persona-composer-overlay",""),w.style.position="absolute",w.style.left="0",w.style.right="0",w.style.bottom="0",w.style.zIndex="20";let T=vm({config:e}),{root:N,textNode:M}=xm();return n.append(d,o,l,w),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:w,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:u,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:N,peekTextNode:M}},Cm=(e,t=!0)=>{var w,T,N,M,I,W,S,k,$;if(Co(e))return th(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=(w=e==null?void 0:e.layout)==null?void 0:w.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?Ss(e,r,{showClose:t}):Qr({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"),a.style.setProperty("scrollbar-gutter","stable");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=gn(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=(M=(N=e==null?void 0:e.copy)==null?void 0:N.welcomeTitle)!=null?M:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let p=h("div","persona-flex persona-flex-col persona-gap-3"),u=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((k=e==null?void 0:e.copy)==null?void 0:k.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let m=Ts({config:e}),v=(($=e==null?void 0:e.layout)==null?void 0:$.showFooter)!==!1;o?Qo(n,s,e):(s.header.style.display="none",Qo(n,s,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||(m.footer.style.display="none"),n.append(m.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var nh=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}},rh=(e,t)=>{if(!e)return null;let n=nh(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},oh=(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},sh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},kl=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(":"))},Ll=320,Sm=320,ah=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),ih=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),lh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),ch=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),dh=(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 o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let l=h("img");l.alt=((u=i.alt)==null?void 0:u.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=`${Ll}px`,l.style.maxHeight=`${Sm}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;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),sh(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},ph=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(!kl(r.audio))return;let o=h("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ll}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},uh=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(!kl(r.video))return;let o=h("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ll}px`,o.style.maxHeight=`${Sm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},mh=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(!kl(r.data))return;let o=h("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Yo=()=>{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 o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},Pl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Yo};if(t){let o=t(r);if(o!==null)return o}return Yo()},gh=(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 o=h("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}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},Am=(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},fh=(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},Il=(e,t,n)=>{var m,v,x,w,T,N;let r=(m=t.showCopy)!=null?m:!0,o=(v=t.showUpvote)!=null?v:!0,s=(x=t.showDownvote)!=null?x:!0;if(!r&&!o&&!s){let M=h("div");return M.style.display="none",M.id=`actions-${e.id}`,M.setAttribute("data-actions-for",e.id),M}let a=(w=t.visibility)!=null?w:"hover",i=(T=t.align)!=null?T:"right",d=(N=t.layout)!=null?N:"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],u=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let f=(M,I,W)=>{let S=Kt({icon:M,label:I,size:14,className:"persona-message-action-btn"});return S.setAttribute("data-action",W),S};return r&&u.appendChild(f("copy","Copy message","copy")),o&&u.appendChild(f("thumbs-up","Upvote","upvote")),s&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},Es=(e,t,n,r,o,s)=>{var de,Q,re,le,ge,V,se,He,Z,ee,ae,Se,Ze,ve,fe,Je,De;let a=n!=null?n:{},i=(de=a.layout)!=null?de:"bubble",d=a.avatar,l=a.timestamp,p=(Q=d==null?void 0:d.show)!=null?Q:!1,u=(re=l==null?void 0:l.show)!=null?re:!1,f=(le=d==null?void 0:d.position)!=null?le:"left",m=(ge=l==null?void 0:l.position)!=null?ge:"below",v=fh(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 w=ah(e),T=(se=(V=e.content)==null?void 0:V.trim())!=null?se:"",M=w.length>0&&T===oi,I=vi((Z=(He=s==null?void 0:s.widgetConfig)==null?void 0:He.features)==null?void 0:Z.streamAnimation),W=(Se=(ae=(ee=s==null?void 0:s.widgetConfig)==null?void 0:ee.features)==null?void 0:ae.streamAnimation)==null?void 0:Se.plugins,S=e.role==="assistant"&&I.type!=="none"?ua(I.type,W):null,k=e.role==="assistant"&&((Ze=S==null?void 0:S.isAnimating)==null?void 0:Ze.call(S,e))===!0,$=e.role==="assistant"&&S!==null&&(!!e.streaming||k);$&&(S!=null&&S.bubbleClass)&&x.classList.add(S.bubbleClass);let O=document.createElement("div");O.classList.add("persona-message-content"),$&&S&&(S.containerClass&&O.classList.add(S.containerClass),O.style.setProperty("--persona-stream-step",`${I.speed}ms`),O.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let H=$?wi((ve=e.content)!=null?ve:"",I.buffer,S,e,!!e.streaming):(fe=e.content)!=null?fe:"",U=t({text:H,message:e,streaming:!!e.streaming,raw:e.rawContent}),J=U;$&&(S==null?void 0:S.wrap)==="char"?J=ma(U,"char",e.id,{skipTags:S.skipTags}):$&&(S==null?void 0:S.wrap)==="word"&&(J=ma(U,"word",e.id,{skipTags:S.skipTags}));let ce=null;if(M?(ce=document.createElement("div"),ce.innerHTML=J,ce.style.display="none",O.appendChild(ce)):O.innerHTML=J,$&&(S!=null&&S.useCaret)&&!M&&T){let z=Ci(),ue=O.querySelectorAll(".persona-stream-char, .persona-stream-word"),rt=ue[ue.length-1];if(rt!=null&&rt.parentNode)rt.parentNode.insertBefore(z,rt.nextSibling);else{let kt=O.lastElementChild;kt?kt.appendChild(z):O.appendChild(z)}}if(u&&m==="inline"&&e.createdAt){let z=Am(e,l);z.classList.add("persona-ml-2","persona-inline"),O.appendChild(z)}if(w.length>0){let z=dh(w,!M&&!!T,()=>{M&&ce&&(ce.style.display="")});z?x.appendChild(z):M&&ce&&(ce.style.display="")}let Me=ih(e);if(Me.length>0){let z=ph(Me);z&&x.appendChild(z)}let ze=lh(e);if(ze.length>0){let z=uh(ze);z&&x.appendChild(z)}let Ae=ch(e);if(Ae.length>0){let z=mh(Ae);z&&x.appendChild(z)}if(x.appendChild(O),u&&m==="below"&&e.createdAt){let z=Am(e,l);z.classList.add("persona-mt-1"),x.appendChild(z)}let We=e.role==="assistant"?rh(e.stopReason,(De=(Je=s==null?void 0:s.widgetConfig)==null?void 0:Je.copy)==null?void 0:De.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let z=!!(H&&H.trim()),ue=I.placeholder==="skeleton",rt=ue&&I.buffer==="line"&&z;if(z)rt&&x.appendChild(ga());else if(ue)x.appendChild(ga());else{let kt=Pl("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);kt&&x.appendChild(kt)}}if(We&&e.stopReason&&!e.streaming&&(T||(O.style.display="none"),x.appendChild(oh(e.stopReason,We))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let z=Il(e,r,o);x.appendChild(z)}if(!p||e.role==="system")return x;let ke=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Re=gh(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ke.append(x,Re):ke.append(Re,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ke},Tm=(e,t,n,r,o,s)=>{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}):Es(e,t,n,r,o,s)};var Ms=new Set,hh=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),bh=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
24
- `):""},Em=(e,t)=>{let n=Ms.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)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=Ce(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Wl=(e,t)=>{var ze,Ae,We,be,ke,Re,de,Q,re,le,ge;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 o=(Ae=(ze=t==null?void 0:t.features)==null?void 0:ze.reasoningDisplay)!=null?Ae:{},s=o.expandable!==!1,a=s&&Ms.has(e.id),i=n.status!=="complete",d=bh(e,(We=o.previewMaxLines)!=null?We:3),l=h("button",s?"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",s&&(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"),u=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(be=t==null?void 0:t.reasoning)!=null?be:{},v=String((ke=n.startedAt)!=null?ke:Date.now()),x=()=>{let V=h("span","");return V.setAttribute("data-tool-elapsed",v),V.textContent=Xa(n),V},w=(Re=m.renderCollapsedSummary)==null?void 0:Re.call(m,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Xa(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(u.textContent=w,p.appendChild(u)):w instanceof HTMLElement?p.appendChild(w):(u.textContent=f,p.appendChild(u));let T=h("span","persona-text-xs persona-text-persona-primary");T.textContent=Hu(n),p.appendChild(T);let N=(de=o.loadingAnimation)!=null?de:"none",M=m.activeTextTemplate,I=m.completeTextTemplate,W=i?M:I,S=w instanceof HTMLElement,k=(V,se,He)=>{let Z=He;for(let ee of se){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(Z)),ae.textContent=ee===" "?"\xA0":ee,V.appendChild(ae),Z++}return Z},$=(V,se)=>{u.textContent="";let He=Qa(V,""),Z=0;for(let ee of He){let ae=ee.styles.length>0?(()=>{let Se=h("span",ee.styles.map(Ze=>`persona-tool-text-${Ze}`).join(" "));return u.appendChild(Se),Se})():u;if(ee.isDuration&&i)ae.appendChild(x());else{let Se=ee.isDuration?Xa(n):ee.text;se?Z=k(ae,Se,Z):ae.appendChild(document.createTextNode(Se))}}};if(!S&&W)if(T.style.display="none",u.style.display="",i&&N!=="none"){let V=(Q=m.loadingAnimationDuration)!=null?Q:2e3;u.setAttribute("data-preserve-animation","true"),N==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),$(W,!1)):(u.classList.add(`persona-tool-loading-${N}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),N==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),$(W,!0))}else $(W,!1);else if(!S&&i&&N!=="none"){u.style.display="";let V=(re=m.loadingAnimationDuration)!=null?re:2e3;if(u.setAttribute("data-preserve-animation","true"),N==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{u.classList.add(`persona-tool-loading-${N}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),N==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let se=u.textContent||f;u.textContent="",k(u,se,0)}n.status==="complete"&&(u.style.display="none")}else S||(n.status==="complete"?u.style.display="none":u.style.display="");let O=null;if(s){O=h("div","persona-flex persona-items-center");let se=Ce(a?"chevron-up":"chevron-down",16,"currentColor",2);se?O.appendChild(se):O.textContent=a?"Hide":"Show";let He=h("div","persona-flex persona-items-center persona-ml-auto");He.append(O),l.append(p,He)}else l.append(p);let H=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","reasoning"),H.style.display="none",H.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=(ge=(le=t==null?void 0:t.reasoning)==null?void 0:le.renderCollapsedPreview)==null?void 0:ge.call(le,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});hh(H,V)||(H.textContent=d),H.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,H),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 J=n.chunks.join(""),ce=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ce.textContent=J||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),U.appendChild(ce),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),O){O.innerHTML="";let se=Ce(a?"chevron-up":"chevron-down",16,"currentColor",2);se?O.appendChild(se):O.textContent=a?"Hide":"Show"}U.style.display=a?"":"none",H.style.display=a?"none":H.textContent||H.childNodes.length?"":"none"})(),r.append(l,H,U),r};var ks=new Set,yh=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),xh=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
- `);let o=ys(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},vh=(e,t)=>{var p,u,f,m,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=xh(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?Bu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return o==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=ml(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ml(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Mm=(e,t,n)=>{var p;let r=ks.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"currentColor",f=Ce(r?"chevron-up":"chevron-down",16,u,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Rl=(e,t)=>{var J,ce,Me,ze,Ae,We,be,ke,Re;let n=e.toolCall,r=(J=t==null?void 0:t.toolCall)!=null?J:{},o=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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Me=(ce=t==null?void 0:t.features)==null?void 0:ce.toolCallDisplay)!=null?Me:{},a=s.expandable!==!1,i=a&&ks.has(e.id),{summary:d,previewText:l,isActive:p}=vh(e,t),u=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");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((ze=n.startedAt)!=null?ze:Date.now()),x=()=>{let de=h("span","");return de.setAttribute("data-tool-elapsed",v),de.textContent=ra(n),de},w=(We=r.renderCollapsedSummary)==null?void 0:We.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Ae=s.collapsedMode)!=null?Ae:"tool-call",isActive:p,config:t!=null?t:{},elapsed:ra(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(m.textContent=w,f.appendChild(m)):w instanceof HTMLElement?f.appendChild(w):(m.textContent=d,f.appendChild(m));let T=(be=s.loadingAnimation)!=null?be:"none",N=r.activeTextTemplate,M=r.completeTextTemplate,I=p?N:M,W=w instanceof HTMLElement,S=(de,Q,re)=>{let le=re;for(let ge of Q){let V=h("span","persona-tool-char");V.style.setProperty("--char-index",String(le)),V.textContent=ge===" "?"\xA0":ge,de.appendChild(V),le++}return le},k=(de,Q)=>{var V;m.textContent="";let re=((V=n.name)==null?void 0:V.trim())||"tool",le=Qa(de,re),ge=0;for(let se of le){let He=se.styles.length>0?(()=>{let Z=h("span",se.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(Z),Z})():m;if(se.isDuration&&p)He.appendChild(x());else{let Z=se.isDuration?ra(n):se.text;Q?ge=S(He,Z,ge):He.appendChild(document.createTextNode(Z))}}};if(!W)if(p&&T!=="none"){let de=(ke=r.loadingAnimationDuration)!=null?ke:2e3;if(m.setAttribute("data-preserve-animation","true"),T==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),I&&k(I,!1);else if(m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),I)k(I,!0);else{let Q=m.textContent||d;m.textContent="",S(m,Q,0)}}else I&&k(I,!1);let $=null;if(a){$=h("div","persona-flex persona-items-center");let de=r.toggleTextColor||r.headerTextColor||"currentColor",Q=Ce(i?"chevron-up":"chevron-down",16,de,2);Q?$.appendChild(Q):$.textContent=i?"Hide":"Show";let re=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");re.append($),u.append(f,re)}else u.append(f);let O=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","tool"),O.style.display="none",O.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let de=(Re=r.renderCollapsedPreview)==null?void 0:Re.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});yh(O,de)||(O.textContent=l),O.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,O),o;let H=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=i?"":"none",r.contentBackgroundColor&&(H.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(H.style.color=r.contentTextColor),r.contentPaddingX&&(H.style.paddingLeft=r.contentPaddingX,H.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(H.style.paddingTop=r.contentPaddingY,H.style.paddingBottom=r.contentPaddingY),n.name){let de=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?de.style.color=r.contentTextColor:r.headerTextColor&&(de.style.color=r.headerTextColor),de.textContent=n.name,H.appendChild(de)}if(n.args!==void 0){let de=h("div","persona-space-y-1"),Q=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Arguments";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(re.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(re.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(re.style.color=r.codeBlockTextColor),re.textContent=ys(n.args),de.append(Q,re),H.appendChild(de)}if(n.chunks&&n.chunks.length){let de=h("div","persona-space-y-1"),Q=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Activity";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(re.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(re.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(re.style.color=r.codeBlockTextColor),re.textContent=n.chunks.join(""),de.append(Q,re),H.appendChild(de)}if(n.status==="complete"&&n.result!==void 0){let de=h("div","persona-space-y-1"),Q=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Result";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(re.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(re.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(re.style.color=r.codeBlockTextColor),re.textContent=ys(n.result),de.append(Q,re),H.appendChild(de)}if(n.status==="complete"&&typeof n.duration=="number"){let de=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(de.style.color=r.contentTextColor),de.textContent=`Duration: ${n.duration}ms`,H.appendChild(de)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),$){$.innerHTML="";let de=r.toggleTextColor||r.headerTextColor||"currentColor",Q=Ce(i?"chevron-up":"chevron-down",16,de,2);Q?$.appendChild(Q):$.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",O.style.display=i?"none":O.textContent||O.childNodes.length?"":"none"})(),o.append(u,O,H),o};var So=require("partial-json");var Bl="ask_user_question",Hl=8,Ls="data-persona-ask-sheet-for",wh="Other",Ch="Other\u2026",Lm="Type your own answer here",Pm="Send",Ah="Next",Sh="Back",Th="Submit all",Eh="Skip",Mh=3,Dl="data-ask-current-index",Nl="data-ask-question-count",Im="data-ask-answers",Ol="data-ask-grouped",Wm="data-ask-layout",kh=e=>e.layout==="pills"?"pills":"rows",Lh=e=>e.getAttribute(Wm)==="pills"?"pills":"rows",km=!1,Rm=e=>e.replace(/["\\]/g,"\\$&"),Yr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Bl,Hi=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Zr=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 o=r.join(""),s=(0,So.parse)(o,So.STR|So.OBJ|So.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},xa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Hl&&!km&&(km=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Hl}.`)),t.slice(0,Hl)},Ph=e=>{var t;return(t=xa(e)[0])!=null?t:null},Ih=(e,t)=>{var n;return(n=xa(e)[t])!=null?n:null},Hm=(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))},Bm=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=h("span","persona-ask-row-check");r.appendChild(o)}else{let o=h("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},Wh=(e,t,n,r)=>{let s=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.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)}s.appendChild(a);let d=Bm(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Rh=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},Hh=(e,t,n,r)=>{var p,u,f;let s=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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<Mh;m++)s.appendChild(Rh(r));return s}if(d.forEach((m,v)=>{s.appendChild(Wh(m,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?wh:Ch;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"),w=document.createElement("input");w.type="text",w.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",w.placeholder=(p=t.freeTextPlaceholder)!=null?p:Lm,w.setAttribute("data-ask-free-text-input","true"),w.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:m),x.appendChild(w),v.appendChild(x);let T=Bm(r,a,d.length);T&&v.appendChild(T),s.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=(f=t.freeTextLabel)!=null?f:m,s.appendChild(v)}}return s},Dm=(e,t)=>{var s,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 o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:Lm,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),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:Pm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Bh=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:Pm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Dh=(e,t,n)=>{var l,p,u,f;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 o=h("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:Sh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=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:Eh,a.setAttribute("data-ask-user-action","skip"),s.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?(u=n.submitAllLabel)!=null?u:Th:(f=n.nextLabel)!=null?f:Ah,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Zo=e=>{let t=e.getAttribute(Im);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Nm=(e,t)=>{e.setAttribute(Im,JSON.stringify(t))},gr=e=>{var n;let t=Number((n=e.getAttribute(Dl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Nh=(e,t)=>{e.setAttribute(Dl,String(Math.max(0,Math.floor(t))))},Ps=e=>{var n;let t=Number((n=e.getAttribute(Nl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},To=e=>e.getAttribute(Ol)==="true",Oh=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Fh=(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)))},Bi=(e,t)=>{let{payload:n}=Zr(t),r=xa(n),o=Zo(e),s={},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(o,d)&&(s[l]=o[d]))}),s},Om=e=>{let t=Zo(e),n=gr(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).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=""},Fm=e=>{if(!To(e))return;let t=Zo(e),n=gr(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);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}},Fl=(e,t,n)=>{let r=Hi(n),o=Lh(e),{payload:s,complete:a}=Zr(t),i=To(e),d=gr(e),l=Ps(e),p=i?Ih(s,d):Ph(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let N=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=N,v.classList.toggle("persona-ask-question-skeleton",!N&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let N=Hh(p,r,a,o);x.replaceWith(N)}if(o!=="rows"){let N=e.querySelector('[data-ask-free-text-row="true"]');N&&N.replaceWith(Dm(r,o))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!w?e.appendChild(Bh(r)):(!u||i)&&w&&w.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let N=Dh(d,l,r);T?T.replaceWith(N):e.appendChild(N)}else T&&T.remove();Om(e),Fm(e)},$h=(e,t,n)=>{let r=Hi(t),o=kh(r),s=e.toolCall.id,a=xa(n),i=Math.max(1,a.length),d=i>1,l=Oh(e,a),p=d?Fh(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ls,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Nl,String(i)),u.setAttribute(Dl,String(p)),u.setAttribute(Ol,d?"true":"false"),u.setAttribute(Wm,o),Nm(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Hm(u,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=h("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),u.appendChild(f);let w=h("div",o==="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 w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),u.appendChild(w),o!=="rows"&&u.appendChild(Dm(r,o)),Fl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},_h=(e,t,n)=>{let{payload:r}=Zr(t),o=Math.max(1,xa(r).length);o>Ps(e)&&(e.setAttribute(Nl,String(o)),o>1&&!To(e)&&e.setAttribute(Ol,"true")),Fl(e,t,n)},$m=(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=Hi(t);Hm(n,r);let o=h("span","persona-ask-stub-label"),{complete:s}=Zr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Is=(e,t,n)=>{if(!n||!Yr(e)||Hi(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${Ls}]`).forEach(l=>{l.getAttribute(Ls)!==o&&l.remove()});let a=n.querySelector(`[${Ls}="${Rm(o)}"]`);if(a){_h(a,e,t);return}let{payload:i}=Zr(e),d=$h(e,t,i);n.appendChild(d)},Eo=(e,t)=>{if(!e)return;let n=t?`[${Ls}="${Rm(t)}"]`:`[${Ls}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},$l=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),Mo=(e,t)=>{let n=Zo(e),r=gr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Nm(e,n),Om(e),Fm(e)},Di=(e,t,n,r)=>{let o=Ps(e),s=Math.max(0,Math.min(o-1,r));Nh(e,s),Fl(e,t,n)};var Ni=new Map,jh=e=>{let n=(e.startsWith(Kr)?e.slice(Kr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},_m=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,jm=(e,t)=>{var r,o,s;let n=(o=(r=_m(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ni.get(e))!=null?s:n==="expanded"},Um=(e,t,n)=>{var a,i;let r=_m(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ce(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},qm=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=jm(e,n);Um(r,s,n),o.style.display=s?"":"none"};var Oi=(e,t)=>{var k,$,O,H,U,J,ce,Me,ze,Ae,We,be,ke,Re,de;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=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(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(k=r==null?void 0:r.backgroundColor)!=null?k:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=($=r==null?void 0:r.borderColor)!=null?$:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;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)":(O=r==null?void 0:r.titleColor)!=null?O:"currentColor",p=Ce(d,20,l,2);p&&i.appendChild(p);let u=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(H=r==null?void 0:r.title)!=null?H:"Approval Required",f.appendChild(m),!o){let Q=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");Q.setAttribute("data-approval-status",n.status),n.status==="approved"?(Q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",Q.style.color="var(--persona-palette-colors-success-700, #15803d)",Q.textContent="Approved"):n.status==="denied"?(Q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",Q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",Q.textContent="Denied"):n.status==="timeout"&&(Q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",Q.style.color="var(--persona-palette-colors-warning-700, #b45309)",Q.textContent="Timeout"),f.appendChild(Q)}u.appendChild(f);let x=n.toolType==="webmcp"||n.toolName.startsWith(Kr)?ul(n.toolName):void 0,w=(U=r==null?void 0:r.formatDescription)==null?void 0:U.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,N=w||(T?n.description:`The assistant wants to use \u201C${x!=null?x:jh(n.toolName)}\u201D.`),M=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(M.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(M.style.color=r.descriptionColor),M.textContent=N,u.appendChild(M),n.reason){let Q=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");Q.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?Q.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor);let re=h("span","persona-font-medium");re.textContent=`${(J=r==null?void 0:r.reasonLabel)!=null?J:"Agent's stated reason:"} `,Q.appendChild(re),Q.appendChild(document.createTextNode(n.reason)),u.appendChild(Q)}let I=(ce=r==null?void 0:r.detailsDisplay)!=null?ce:"collapsed",W=!!n.description&&!T,S=W||!!n.parameters;if(I!=="hidden"&&S){let Q=jm(e.id,t),re=h("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");re.type="button",re.setAttribute("data-expand-header","true"),re.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(re.style.color=r.descriptionColor);let le=h("span");le.setAttribute("data-approval-details-label","true");let ge=h("span","persona-inline-flex persona-items-center");ge.setAttribute("data-approval-details-chevron","true"),re.append(le,ge),Um(re,Q,t),u.appendChild(re);let V=h("div");if(V.setAttribute("data-approval-details","true"),V.style.display=Q?"":"none",W){let se=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor),se.textContent=n.description,V.appendChild(se)}if(n.parameters){let se=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&&(se.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(se.style.color=r.parameterTextColor),se.style.fontSize="0.75rem",se.style.lineHeight="1rem",se.textContent=ys(n.parameters),V.appendChild(se)}u.appendChild(V)}if(o){let Q=h("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let re=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");re.type="button",re.style.backgroundColor=(Me=r==null?void 0:r.approveButtonColor)!=null?Me:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(ze=r==null?void 0:r.approveButtonTextColor)!=null?ze:"#ffffff",re.setAttribute("data-approval-action","approve");let le=Ce("shield-check",14,(Ae=r==null?void 0:r.approveButtonTextColor)!=null?Ae:"#ffffff",2);le&&(le.style.marginRight="4px",re.appendChild(le));let ge=document.createTextNode((We=r==null?void 0:r.approveLabel)!=null?We:"Approve");re.appendChild(ge);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-cursor-pointer");V.type="button",V.style.backgroundColor=(be=r==null?void 0:r.denyButtonColor)!=null?be:"transparent",V.style.color=(ke=r==null?void 0:r.denyButtonTextColor)!=null?ke:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let se=Ce("shield-x",14,(Re=r==null?void 0:r.denyButtonTextColor)!=null?Re:"var(--persona-feedback-error, #dc2626)",2);se&&(se.style.marginRight="4px",V.appendChild(se));let He=document.createTextNode((de=r==null?void 0:r.denyLabel)!=null?de:"Deny");V.appendChild(He),Q.append(re,V),u.appendChild(Q)}return a.append(i,u),s.appendChild(a),s};var zm=e=>{let t=[];return{buttons:t,render:(r,o,s,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:o?o.getMessages():[]).some(m=>m.role==="user"))return;let p=document.createDocumentFragment(),u=o?o.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(m=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=u,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(m))}),p.appendChild(v),t.push(v)}),e.appendChild(p)}}};var va=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 wa=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 o=r.result;o.objectStoreNames.contains(this.storeName)||o.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 o of t)r.put(o)}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 s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.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 o of t)r.put(o)}catch{}}};var Uh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),qh=new Set(["step_start","execution_start"]),zh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Vh=new Set(["step_complete","agent_turn_complete"]),Kh=new Set(["flow_complete","agent_complete"]),Vm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Jm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,es=(e,t)=>{let n=e[t];return Jm(n)?n:void 0};function _l(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Fi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Jh(e,t){return typeof t.type=="string"?t.type:e}function Gh(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 Xh(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 Km(e){var r,o,s,a,i;let t=es(e,"result"),n=[es(e,"tokens"),es(e,"totalTokens"),t?es(t,"tokens"):void 0,es(e,"usage"),t?es(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=tr(d.output))!=null?r:tr(d.outputTokens))!=null?o:tr(d.completionTokens);if(l!==void 0)return l}return(i=(s=tr(e.outputTokens))!=null?s:tr(e.completionTokens))!=null?i:t?(a=tr(t.outputTokens))!=null?a:tr(t.completionTokens):void 0}function Qh(e){var n,r,o,s,a;let t=es(e,"result");return(a=(o=(r=(n=tr(e.executionTime))!=null?n:tr(e.executionTimeMs))!=null?r:tr(e.execution_time))!=null?o:tr(e.duration))!=null?a:t?(s=tr(t.executionTime))!=null?s:tr(t.executionTimeMs):void 0}function Yh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ca=class{constructor(t=Yh){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:Fi(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 s;if(!Jm(n)){Vm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Jh(t,n),o=this.now();if(Uh.has(r)){this.startRun(o);return}if(qh.has(r)){this.run||this.startRun(o);return}if(zh.has(r)){if(!Xh(r,n))return;let a=Gh(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+_l(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Fi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Vh.has(r)){if(!this.run)return;let a=this.run,i=Km(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+_l(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:Fi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Kh.has(r)){if(!this.run)return;let a=this.run,i=Km(n),d=i!=null?i:a.exactOutputTokens+_l(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:Fi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Vm.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Qh(n);return s!=null?s:r-t.startedAt}};function Ws(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Zh={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)"}},eb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},tb=["flowName","stepName","reasoningText","text","name","tool","toolName"],nb=100;function rb(e,t){let n={...Zh,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return eb}function ob(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function sb(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function ab(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function ib(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 lb(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 cb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function db(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 pb(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});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 jl(e,t,n,r,o,s,a,i){var f;let d=o.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Ws(l,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(u()),l;function u(){var J,ce;let m=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let 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"),w=Ce(d?"chevron-down":"chevron-right","14px","currentColor",2);w&&x.appendChild(w);let T=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),N=(J=r.timestampFormat)!=null?J:"relative";T.textContent=N==="relative"?ob(e.timestamp,n):sb(e.timestamp);let M=null;r.showSequenceNumbers!==!1&&(M=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(t+1));let I=rb(e.type,r.badgeColors),W=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");W.style.backgroundColor=I.bg,W.style.color=I.text,W.style.borderColor=I.text+"50",W.textContent=e.type;let S=(ce=r.descriptionFields)!=null?ce:tb,k=ab(e.payload,S),$=null;k&&($=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),$.textContent=k);let O=h("div","persona-flex-1 persona-min-w-0"),H=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=Ce("clipboard","12px","currentColor",1.5);return U&&H.appendChild(U),H.addEventListener("click",async Me=>{Me.stopPropagation(),await ib(lb(e)),H.innerHTML="";let ze=Ce("check","12px","currentColor",1.5);ze&&H.appendChild(ze),setTimeout(()=>{H.innerHTML="";let Ae=Ce("clipboard","12px","currentColor",1.5);Ae&&H.appendChild(Ae)},1500)}),v.appendChild(x),v.appendChild(T),M&&v.appendChild(M),v.appendChild(W),$&&v.appendChild($),v.appendChild(O),v.appendChild(H),m.appendChild(v),d&&m.appendChild(pb(e,a,i)),m}}function Gm(e){var v,x,w,T,N;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(v=o==null?void 0:o.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=(w=i==null?void 0:i.label)!=null?w:"",u=(N=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?N:{},f=s.find(M=>M.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let M=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return m();function m(){let M=u.classNames,I=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ws(I,M==null?void 0:M.panel);let W=[],S="",k="",$=null,O=[],H={},U=0,J=bi(),ce=0,Me=0,ze=!1,Ae=null,We=!1,be=0,ke=new Set,Re=new Map,de="",Q="",re=null,le,ge,V,se,He,Z=null,ee=null,ae=null;function Se(){let we=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ie=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");Ws(ie,M==null?void 0:M.headerBar);let nt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(nt.textContent="Events",le=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"),le.textContent="0",a){ee=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let wn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");wn.textContent="Throughput",Z=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"),Z.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 Cn=ee,yn=ae,Er=()=>{if(!yn.textContent)return;let _n=Cn.getBoundingClientRect(),jn=we.getBoundingClientRect();yn.style.left=`${_n.left-jn.left}px`,yn.style.top=`${_n.bottom-jn.top+4}px`,yn.style.display="block"},St=()=>{yn.style.display="none"};ee.addEventListener("mouseenter",Er),ee.addEventListener("mouseleave",St),ee.appendChild(wn),ee.appendChild(Z)}let Zt=h("div","persona-flex-1");ge=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 Gt=h("option","");Gt.value="",Gt.textContent="All events",ge.appendChild(Gt),V=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"),V.type="button",V.title="Copy All";let xn=Ce("clipboard-copy","12px","currentColor",1.5);xn&&V.appendChild(xn);let ft=h("span","persona-text-xs");ft.textContent="Copy All",V.appendChild(ft),ie.appendChild(nt),ie.appendChild(le),ee&&ie.appendChild(ee),ie.appendChild(Zt),ie.appendChild(ge),ie.appendChild(V);let Lt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ws(Lt,M==null?void 0:M.searchBar);let et=Ce("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=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");et&&zt.appendChild(et),se=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"),Ws(se,M==null?void 0:M.searchInput),se.type="text",se.placeholder="Search event payloads...",He=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"),He.type="button",He.style.display="none";let cn=Ce("x","12px","currentColor",2);return cn&&He.appendChild(cn),Lt.appendChild(zt),Lt.appendChild(se),Lt.appendChild(He),we.appendChild(ie),we.appendChild(Lt),ae&&we.appendChild(ae),we}let Ze,ve=s.find(we=>we.renderEventStreamToolbar);if(ve!=null&&ve.renderEventStreamToolbar&&o){let we=ve.renderEventStreamToolbar({config:o,defaultRenderer:()=>Se(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ie=>{S=ie,ln(),R()},onSearchChange:ie=>{k=ie,ln(),R()}});Ze=we!=null?we:Se()}else Ze=Se();let fe=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");fe.style.display="none";function Je(){if(!a||!Z||!ee)return;let we=a();Z.textContent=cb(we);let ie=db(we);ae&&(ae.textContent=ie,ie||(ae.style.display="none")),ie?ee.setAttribute("aria-label",ie):ee.removeAttribute("aria-label")}let De=h("div","persona-flex-1 persona-min-h-0 persona-relative"),z=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");z.style.height="100%";let ue=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");Ws(ue,M==null?void 0:M.scrollIndicator),ue.style.display="none",ue.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let rt=Ce(l,"14px","currentColor",2);rt&&ue.appendChild(rt);let kt=h("span","");kt.textContent=p,ue.appendChild(kt);let te=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");te.style.display="none",De.appendChild(z),De.appendChild(te),De.appendChild(ue),I.setAttribute("tabindex","0"),I.appendChild(Ze),I.appendChild(fe),I.appendChild(De);function Ve(){let we=t.getAll(),ie={};for(let ft of we)ie[ft.type]=(ie[ft.type]||0)+1;let nt=Object.keys(ie).sort(),Zt=nt.length!==O.length||!nt.every((ft,Lt)=>ft===O[Lt]),Gt=!Zt&&nt.some(ft=>ie[ft]!==H[ft]),kn=we.length!==Object.values(H).reduce((ft,Lt)=>ft+Lt,0);if(!Zt&&!Gt&&!kn||(O=nt,H=ie,!ge))return;let xn=ge.value;if(ge.options[0].textContent="All events",Zt){for(;ge.options.length>1;)ge.remove(1);for(let ft of nt){let Lt=h("option","");Lt.value=ft,Lt.textContent=`${ft} (${ie[ft]||0})`,ge.appendChild(Lt)}xn&&nt.includes(xn)?ge.value=xn:xn&&(ge.value="",S="")}else for(let ft=1;ft<ge.options.length;ft++){let Lt=ge.options[ft];Lt.textContent=`${Lt.value} (${ie[Lt.value]||0})`}}function Bn(){let we=t.getAll();if(S&&(we=we.filter(ie=>ie.type===S)),k){let ie=k.toLowerCase();we=we.filter(nt=>nt.type.toLowerCase().includes(ie)||nt.payload.toLowerCase().includes(ie))}return we}function Bt(){return S!==""||k!==""}function ln(){U=0,ce=0,J.resume(),ue.style.display="none"}function nr(we){ke.has(we)?ke.delete(we):ke.add(we),re=we;let ie=z.scrollTop,nt=J.isFollowing();We=!0,J.pause(),R(),z.scrollTop=ie,nt&&J.resume(),We=!1}function Tr(){return Xo(z,50)}function R(){Me=Date.now(),ze=!1,Je(),Ve();let we=t.getEvictedCount();we>0?(fe.textContent=`${we.toLocaleString()} older events truncated`,fe.style.display=""):fe.style.display="none",W=Bn();let ie=W.length,nt=t.getSize()>0;le&&(le.textContent=String(t.getSize())),ie===0&&nt&&Bt()?(te.textContent=k?`No events matching '${k}'`:"No events matching filter",te.style.display="",z.style.display="none"):(te.style.display="none",z.style.display=""),V&&(V.title=Bt()?`Copy Filtered (${ie})`:"Copy All"),d&&!J.isFollowing()&&ie>U&&(ce+=ie-U,kt.textContent=p?`${p}${ce>0?` (${ce})`:""}`:"",ue.style.display=""),U=ie;let Zt=t.getAll(),Gt=Zt.length>0?Zt[0].timestamp:0,kn=new Set(W.map(Lt=>Lt.id));for(let Lt of ke)kn.has(Lt)||ke.delete(Lt);let xn=S!==de||k!==Q,ft=Re.size===0&&W.length>0;if(xn||ft||W.length===0){z.innerHTML="",Re.clear();let Lt=document.createDocumentFragment();for(let et=0;et<W.length;et++){let zt=jl(W[et],et,Gt,u,ke,nr,s,o);Re.set(W[et].id,zt),Lt.appendChild(zt)}z.appendChild(Lt),de=S,Q=k,re=null}else{if(re!==null){let et=Re.get(re);if(et&&et.parentNode===z){let zt=W.findIndex(cn=>cn.id===re);if(zt>=0){let cn=jl(W[zt],zt,Gt,u,ke,nr,s,o);z.insertBefore(cn,et),et.remove(),Re.set(re,cn)}}re=null}let Lt=new Set(W.map(et=>et.id));for(let[et,zt]of Re)Lt.has(et)||(zt.remove(),Re.delete(et));for(let et=0;et<W.length;et++){let zt=W[et];if(!Re.has(zt.id)){let cn=jl(zt,et,Gt,u,ke,nr,s,o);Re.set(zt.id,cn),z.appendChild(cn)}}}J.isFollowing()&&(z.scrollTop=z.scrollHeight)}function pe(){if(Date.now()-Me>=nb){Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),R();return}ze||(ze=!0,Ae=requestAnimationFrame(()=>{Ae=null,R()}))}let Ne=(we,ie)=>{if(!V)return;V.innerHTML="";let nt=Ce(we,"12px","currentColor",1.5);nt&&V.appendChild(nt);let Zt=h("span","persona-text-xs");Zt.textContent="Copy All",V.appendChild(Zt),setTimeout(()=>{V.innerHTML="";let Gt=Ce("clipboard-copy","12px","currentColor",1.5);Gt&&V.appendChild(Gt);let kn=h("span","persona-text-xs");kn.textContent="Copy All",V.appendChild(kn),V.disabled=!1},ie)},Ge=async()=>{if(V){V.disabled=!0;try{let we;Bt()?we=W:n?(we=await n(),we.length===0&&(we=t.getAll())):we=t.getAll();let ie=we.map(nt=>{try{return JSON.parse(nt.payload)}catch{return nt.payload}});await navigator.clipboard.writeText(JSON.stringify(ie,null,2)),Ne("check",1500)}catch{Ne("x",1500)}}},$e=()=>{ge&&(S=ge.value,ln(),R())},je=()=>{!se||!He||(He.style.display=se.value?"":"none",$&&clearTimeout($),$=setTimeout(()=>{k=se.value,ln(),R()},150))},st=()=>{!se||!He||(se.value="",k="",He.style.display="none",$&&clearTimeout($),ln(),R())},It=()=>{if(We)return;let we=z.scrollTop,{action:ie,nextLastScrollTop:nt}=yi({following:J.isFollowing(),currentScrollTop:we,lastScrollTop:be,nearBottom:Tr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=nt,ie==="resume"?(J.resume(),ce=0,ue.style.display="none"):ie==="pause"&&(J.pause(),d&&(kt.textContent=p,ue.style.display=""))},Jt=we=>{let ie=xi({following:J.isFollowing(),deltaY:we.deltaY,nearBottom:Tr(),resumeWhenNearBottom:!0});ie==="pause"?(J.pause(),d&&(kt.textContent=p,ue.style.display="")):ie==="resume"&&(J.resume(),ce=0,ue.style.display="none")},Yt=()=>{d&&(z.scrollTop=z.scrollHeight,J.resume(),ce=0,ue.style.display="none")},K=we=>{let ie=we.target;if(!ie||ie.closest("button"))return;let nt=ie.closest("[data-event-id]");if(!nt)return;let Zt=nt.getAttribute("data-event-id");Zt&&nr(Zt)},vt=we=>{if((we.metaKey||we.ctrlKey)&&we.key==="f"){we.preventDefault(),se==null||se.focus(),se==null||se.select();return}we.key==="Escape"&&(se&&document.activeElement===se?(st(),se.blur(),I.focus()):r&&r())};V&&V.addEventListener("click",Ge),ge&&ge.addEventListener("change",$e),se&&se.addEventListener("input",je),He&&He.addEventListener("click",st),z.addEventListener("scroll",It),z.addEventListener("wheel",Jt,{passive:!0}),z.addEventListener("click",K),ue.addEventListener("click",Yt),I.addEventListener("keydown",vt);function it(){$&&clearTimeout($),Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),ze=!1,Re.clear(),V&&V.removeEventListener("click",Ge),ge&&ge.removeEventListener("change",$e),se&&se.removeEventListener("input",je),He&&He.removeEventListener("click",st),z.removeEventListener("scroll",It),z.removeEventListener("wheel",Jt),z.removeEventListener("click",K),ue.removeEventListener("click",Yt),I.removeEventListener("keydown",vt)}return{element:I,update:pe,destroy:it}}}function Xm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=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 u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Qm=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.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:()=>Xm(e,t)});if(p)return p}return Xm(e,t)};var Ul=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)})}},eo=new Ul;eo.register("PersonaArtifactCard",Qm);function ub(e){var o;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((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function Ym(e,t){var ge,V,se,He;let n=(V=(ge=e.features)==null?void 0:ge.artifacts)==null?void 0:V.layout,o=((se=n==null?void 0:n.toolbarPreset)!=null?se:"default")==="document",s=(He=n==null?void 0:n.panePadding)==null?void 0:He.trim(),a=e.markdown?jo(e.markdown):null,i=hs(e.sanitize),d=Z=>{let ee=a?a(Z):Uo(Z);return i?i(ee):ee},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"),u.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};l&&l.addEventListener("click",()=>{var Z;p(),(Z=t.onDismiss)==null||Z.call(t)});let u=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var Z;p(),(Z=t.onDismiss)==null||Z.call(t)});let x="rendered",w=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Kt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Kt({icon:"eye",label:"Rendered view"}),N=o?Kt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Kt({icon:"code-2",label:"Source"}),M=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),I=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,S=n==null?void 0:n.documentToolbarCopyMenuItems,k=!!(W&&S&&S.length>0),$=null,O,H=null,U=null;if(o&&(I||W)&&!k){if(O=I?ba({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let Z=Ce("chevron-down",14,"currentColor",2);Z&&O.appendChild(Z)}}else o&&k?($=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),O=I?ba({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=Kt({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(O,H)):o?O=Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):O=Kt({icon:"copy",label:"Copy"});let J=o?Kt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"refresh-cw",label:"Refresh"}),ce=o?Kt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"x",label:"Close"}),Me=()=>{var Ze,ve,fe;let Z=(Ze=Re.find(Je=>Je.id===de))!=null?Ze:Re[Re.length-1],ee=(ve=Z==null?void 0:Z.id)!=null?ve:null,ae=(Z==null?void 0:Z.artifactType)==="markdown"&&(fe=Z.markdown)!=null?fe:"",Se=Z?JSON.stringify({component:Z.component,props:Z.props},null,2):"";return{markdown:ae,jsonPayload:Se,id:ee}},ze=async()=>{var Ze;let{markdown:Z,jsonPayload:ee}=Me(),ae=(Ze=Re.find(ve=>ve.id===de))!=null?Ze:Re[Re.length-1],Se=(ae==null?void 0:ae.artifactType)==="markdown"?Z:ae?ee:"";try{await navigator.clipboard.writeText(Se)}catch{}};if(O.addEventListener("click",async()=>{let Z=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Z&&k){let{markdown:ee,jsonPayload:ae,id:Se}=Me();try{await Z({actionId:"primary",artifactId:Se,markdown:ee,jsonPayload:ae})}catch{}return}await ze()}),H&&(S!=null&&S.length)){let Z=()=>{var ae;return(ae=u.closest("[data-persona-root]"))!=null?ae:document.body},ee=()=>{U=Ao({items:S.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:Se,jsonPayload:Ze,id:ve}=Me(),fe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{fe?await fe({actionId:ae,artifactId:ve,markdown:Se,jsonPayload:Ze}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(Se):ae==="json"||ae==="source"?await navigator.clipboard.writeText(Ze):await navigator.clipboard.writeText(Se||Ze)}catch{}},anchor:$!=null?$:H,position:"bottom-right",portal:Z()})};u.isConnected?ee():requestAnimationFrame(ee),H.addEventListener("click",ae=>{ae.stopPropagation(),U==null||U.toggle()})}J.addEventListener("click",async()=>{var Z;try{await((Z=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Z.call(n))}catch{}re()}),ce.addEventListener("click",()=>{var Z;p(),(Z=t.onDismiss)==null||Z.call(t)});let Ae=()=>{o&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),N.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Ae(),re()}),N.addEventListener("click",()=>{x="source",Ae(),re()});let We=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");o?(f.replaceChildren(),w.append(T,N),$?M.append($,J,ce):M.append(O,J,ce),f.append(w,We,M),Ae()):(f.appendChild(m),f.appendChild(v)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let be=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(be.style.paddingLeft=s,be.style.paddingRight=s,ke.style.padding=s),u.appendChild(f),u.appendChild(be),u.appendChild(ke);let Re=[],de=null,Q=!1,re=()=>{var Se,Ze,ve,fe;let Z=o&&Re.length<=1;be.classList.toggle("persona-hidden",Z),be.replaceChildren();for(let Je of Re){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=Je.title||Je.id.slice(0,8),Je.id===de&&De.classList.add("persona-bg-persona-container","persona-border-persona-border"),De.addEventListener("click",()=>t.onSelect(Je.id)),be.appendChild(De)}ke.replaceChildren();let ee=de&&Re.find(Je=>Je.id===de)||Re[Re.length-1];if(!ee)return;if(o){let Je=ee.artifactType==="markdown"?"MD":(Se=ee.component)!=null?Se:"Component",z=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";We.textContent=`${z} \xB7 ${Je}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(o&&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=(Ze=ee.markdown)!=null?Ze:"",ke.appendChild(De);return}let Je=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Je.innerHTML=d((ve=ee.markdown)!=null?ve:""),ke.appendChild(Je);return}let ae=ee.component?eo.get(ee.component):void 0;if(ae){let De={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let z=ae((fe=ee.props)!=null?fe:{},De);if(z){ke.appendChild(z);return}}catch{}}ke.appendChild(ub(ee))},le=()=>{var ee;let Z=Re.length>0;if(u.classList.toggle("persona-hidden",!Z),l){let ae=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ze=((ee=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Z&&Ze&&Q?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(Z){var ee,ae,Se;Re=Z.artifacts,de=(Se=(ae=Z.selectedId)!=null?ae:(ee=Z.artifacts[Z.artifacts.length-1])==null?void 0:ee.id)!=null?Se:null,Re.length>0&&(Q=!0),re(),le()},setMobileOpen(Z){Q=Z,!Z&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):le()}}}function fr(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 Zm(e,t){var s,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"),!fr(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(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)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function mb(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 $i(e,t){var d,l,p,u,f,m,v,x,w,T;if(!fr(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"),mb(e),Zm(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",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"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=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(w=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:w.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Zm(e,t)}var eg=["panel","seamless"];function _i(e,t){var i,d,l,p,u,f;for(let m of eg)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!fr(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",o=eg.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.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 m=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function tg(e,t){var n,r,o;return!t||!fr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function gb(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 fb(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 hb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function bb(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function ng(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function rg(e,t,n,r,o,s){let a=gb(o,200),i=bb(t,n,r,200);i=Math.max(a,i);let d=fb(s);return d!==null&&(i=Math.min(i,d)),hb(e,a,i)}var og={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"}},ql=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,w;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=og[a])!=null?x:og.init;s.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 T=h("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var S,k;let N=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");N.htmlFor=`${t.id}-${a}-${T.name}`;let M=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=T.label,N.appendChild(M);let I=(S=T.type)!=null?S:"text",W;I==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=I),W.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",W.id=`${t.id}-${a}-${T.name}`,W.name=T.name,W.placeholder=(k=T.placeholder)!=null?k:"",T.required&&(W.required=!0),N.appendChild(W),p.appendChild(N)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(w=i.submitLabel)!=null?w:"Submit",u.appendChild(f),u.appendChild(m),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var W,S;T.preventDefault();let N=(W=n.formEndpoint)!=null?W:"/form",M=new FormData(p),I={};M.forEach((k,$)=>{I[$]=k}),I.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let k=await fetch(N,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let $=await k.json();f.textContent=(S=$.message)!=null?S:"Thanks! We'll be in touch soon.",$.success&&$.nextPrompt&&await r.sendMessage(String($.nextPrompt))}catch(k){f.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var zl=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,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Aa=new zl;var sg=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var yb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},xb=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Sa=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=yb(e),n=xb(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Vl=e=>typeof e=="string"?e:e==null?"":String(e),ts={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Vl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Vl(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Vl(n.text)}}},ag=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ta=e=>{let t=new Set(ag(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ag(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.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:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var vb=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}},wb=e=>e.map(t=>({...t,streaming:!1})),Cb=e=>e.map(t=>({...t,status:"complete"})),ji=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?vb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?wb(n.messages):void 0,artifacts:n.artifacts?Cb(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},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 Rs=require("partial-json");function Ab(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Sb(e,t){if(!Ab(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 Ui(){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 o=(0,Rs.parse)(n,Rs.STR|Rs.OBJ),s=Sb(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function ig(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function qi(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=eo.get(e.component);if(!s)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=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function lg(){let e=Ui();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function cg(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 zi(e){let t=cg(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 Vi(e){let t=cg(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 Tb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ki(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Tb}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,m.appendChild(x),f.appendChild(m);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let S=1;S<=5;S++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${l[S-1]}`),k.title=l[S-1],k.dataset.rating=String(S),k.innerHTML=`
23
+ `,n.addEventListener("click",t);let r=s=>{var k,I,R,T,W,_,F,M,j,z,oe,ke,ze;let a=(k=s.launcher)!=null?k:{},i=mn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let Ae=(I=a.title)!=null?I:"Chat Assistant";d.textContent=Ae,d.setAttribute("title",Ae)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let Ae=(R=a.subtitle)!=null?R:"Get answers fast";l.textContent=Ae,l.setAttribute("title",Ae)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let Ae=(T=a.agentIconSize)!=null?T:"40px";if(u.style.height=Ae,u.style.width=Ae,u.innerHTML="",a.agentIconName){let Re=parseFloat(Ae)||24,be=Ce(a.agentIconName,Re*.6,"var(--persona-text-inverse, #ffffff)",2);be?(u.appendChild(be),u.style.display=""):(u.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(_=a.agentIconText)!=null?_:"\u{1F4AC}",u.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let Ae=(F=a.agentIconSize)!=null?F:"40px";f.style.height=Ae,f.style.width=Ae,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let Ae=(M=a.callToActionIconSize)!=null?M:"32px";g.style.height=Ae,g.style.width=Ae,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Re=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Re=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let be=parseFloat(Ae)||24,Le=Math.max(be-Re,8),We=Ce(a.callToActionIconName,Le,"currentColor",2);We?g.appendChild(We):g.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else g.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let v=a.position&&Tr[a.position]?Tr[a.position]:Tr["bottom-right"],y="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",w="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?w:`${y} ${v}`,i||(n.style.zIndex=String((oe=a.zIndex)!=null?oe:Ln));let S="1px solid var(--persona-border, #e5e7eb)",O="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(ke=a.border)!=null?ke:S,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:O,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=(ze=a.collapsedMaxWidth)!=null?ze:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Hh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Hi=(e,t={})=>{var y,w,S,O,k,I;let{showClose:n=!0,wrapperClassName:r=Hh,buttonSize:o,iconSize:s="28px"}=t,a=(y=e==null?void 0:e.launcher)!=null?y:{},i=(w=o!=null?o:a.closeButtonSize)!=null?w:"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=(S=a.closeButtonTooltipText)!=null?S:"Close chat",u=(O=a.closeButtonShowTooltip)!=null?O:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let f=(k=a.closeButtonIconName)!=null?k:"x",g=(I=a.closeButtonIconText)!=null?I:"\xD7";l.style.color=a.closeButtonColor||On.actionIconColor;let v=Ce(f,s,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=g,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",T=a.closeButtonBorderColor||"transparent";l.style.border=`${R} solid ${T}`,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),u&&p){let R=null,T=()=>{if(R)return;let _=l.ownerDocument,F=_.body;if(!F)return;R=Dr(_,"div","persona-clear-chat-tooltip"),R.textContent=p;let M=Dr(_,"div");M.className="persona-clear-chat-tooltip-arrow",R.appendChild(M);let j=l.getBoundingClientRect();R.style.position="fixed",R.style.zIndex=String(So),R.style.left=`${j.left+j.width/2}px`,R.style.top=`${j.top-8}px`,R.style.transform="translate(-50%, -100%)",F.appendChild(R)},W=()=>{R&&R.parentNode&&(R.parentNode.removeChild(R),R=null)};d.addEventListener("mouseenter",T),d.addEventListener("mouseleave",W),l.addEventListener("focus",T),l.addEventListener("blur",W),d._cleanupTooltip=()=>{W(),d.removeEventListener("mouseenter",T),d.removeEventListener("mouseleave",W),l.removeEventListener("focus",T),l.removeEventListener("blur",W)}}return{button:l,wrapper:d}},Bh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Bi=(e,t={})=>{var R,T,W,_,F,M,j,z,oe,ke,ze,Ae,Re;let{wrapperClassName:n=Bh,buttonSize:r,iconSize:o="20px"}=t,a=(T=((R=e==null?void 0:e.launcher)!=null?R:{}).clearChat)!=null?T:{},i=(W=r!=null?r:a.size)!=null?W:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",l=(F=a.iconColor)!=null?F:"",p=(M=a.backgroundColor)!=null?M:"",u=(j=a.borderWidth)!=null?j:"",f=(z=a.borderColor)!=null?z:"",g=(oe=a.borderRadius)!=null?oe:"",v=(ke=a.paddingX)!=null?ke:"",y=(ze=a.paddingY)!=null?ze:"",w=(Ae=a.tooltipText)!=null?Ae:"Clear chat",S=(Re=a.showTooltip)!=null?Re:!0,O=h("div",n),k=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");k.style.height=i,k.style.width=i,k.type="button",k.setAttribute("aria-label",w),k.style.color=l||On.actionIconColor;let I=Ce(d,o,"currentColor",1);if(I&&(I.style.display="block",k.appendChild(I)),p&&(k.style.backgroundColor=p,k.classList.remove("hover:persona-bg-gray-100")),u||f){let be=u||"0px",Le=f||"transparent";k.style.border=`${be} solid ${Le}`,k.classList.remove("persona-border-none")}if(g&&(k.style.borderRadius=g,k.classList.remove("persona-rounded-full")),v&&(k.style.paddingLeft=v,k.style.paddingRight=v),y&&(k.style.paddingTop=y,k.style.paddingBottom=y),O.appendChild(k),S&&w){let be=null,Le=()=>{if(be)return;let de=k.ownerDocument,X=de.body;if(!X)return;be=Dr(de,"div","persona-clear-chat-tooltip"),be.textContent=w;let re=Dr(de,"div");re.className="persona-clear-chat-tooltip-arrow",be.appendChild(re);let ce=k.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(So),be.style.left=`${ce.left+ce.width/2}px`,be.style.top=`${ce.top-8}px`,be.style.transform="translate(-50%, -100%)",X.appendChild(be)},We=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};O.addEventListener("mouseenter",Le),O.addEventListener("mouseleave",We),k.addEventListener("focus",Le),k.addEventListener("blur",We),O._cleanupTooltip=()=>{We(),O.removeEventListener("mouseenter",Le),O.removeEventListener("mouseleave",We),k.removeEventListener("focus",Le),k.removeEventListener("blur",We)}}return{button:k,wrapper:O}};var On={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))"},eo=e=>{var R,T,W,_,F,M,j,z,oe,ke,ze,Ae,Re,be,Le,We;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 o=(R=t==null?void 0:t.launcher)!=null?R:{},s=(T=o.headerIconSize)!=null?T:"48px",a=(W=o.closeButtonPlacement)!=null?W:"inline",i=(_=o.headerIconHidden)!=null?_:!1,d=o.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,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 de=parseFloat(s)||24,X=Ce(d,de*.6,"currentColor",1);X?l.replaceChildren(X):l.textContent=(M=(F=t==null?void 0:t.launcher)==null?void 0:F.agentIconText)!=null?M:"\u{1F4AC}"}else if((j=t==null?void 0:t.launcher)!=null&&j.iconUrl){let de=h("img");de.src=t.launcher.iconUrl,de.alt="",de.className="persona-rounded-xl persona-object-cover",de.style.height=s,de.style.width=s,l.replaceChildren(de)}else l.textContent=(oe=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?oe:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=h("span","persona-text-base persona-font-semibold");u.style.color=On.titleColor,u.textContent=(ze=(ke=t==null?void 0:t.launcher)==null?void 0:ke.title)!=null?ze:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=On.subtitleColor,f.textContent=(Re=(Ae=t==null?void 0:t.launcher)==null?void 0:Ae.subtitle)!=null?Re:"Here to help you get answers fast",p.append(u,f),i?r.append(p):r.append(l,p);let g=(be=o.clearChat)!=null?be:{},v=(Le=g.enabled)!=null?Le:!0,y=(We=g.placement)!=null?We:"inline",w=null,S=null;if(v){let X=Bi(t,{wrapperClassName:y==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=X.button,S=X.wrapper,y==="top-right"&&(S.style.right="48px"),y==="inline"&&r.appendChild(S)}let O=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&y==="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:k,wrapper:I}=Hi(t,{showClose:n,wrapperClassName:O});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:k,closeButtonWrapper:I,clearChatButton:w,clearChatButtonWrapper:S}},es=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Mo(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(So)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let w=document.createElement("hr");a.appendChild(w)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let w=Ce(g.icon,16,"currentColor",1.5);w&&v.appendChild(w)}let y=document.createElement("span");y.textContent=g.label,v.appendChild(y),v.addEventListener("click",w=>{w.stopPropagation(),p(),n(g.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:f}}function Vt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ce(t,r!=null?r:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function Ta(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let f=Ce(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=h("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function Ea(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=h("div","persona-toggle-group"+(o?" "+o:""));s.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 u;p.icon?u=Vt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=h("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Di(e){var g,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="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 u=Ce(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(g=d.borderRadius)!=null?g:"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 y,w;l.style.backgroundColor=(y=d.background)!=null?y:"",l.style.borderColor=(w=d.border)!=null?w:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Mo({items:r,onSelect:y=>{l.setAttribute("aria-expanded","false"),o(y)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",y=>{y.stopPropagation();let w=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",w?"false":"true"),f.toggle()}),l.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),l.click())}),{element:l,setLabel:y=>{p.textContent=y,l.setAttribute("aria-label",y)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let y=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",y?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var Ul=e=>{var r;let t=eo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Dh(e,t,n){var r,o,s;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",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Ce(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=h("div","persona-relative");d.appendChild(i);let l=Mo({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 jl=e=>{var O,k,I,R,T,W,_,F,M;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(O=t==null?void 0:t.launcher)!=null?O:{},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=o==null?void 0:o.titleMenu,l,p;if(d)l=Di({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=On.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=On.titleColor,p.textContent=(R=a.title)!=null?R:"Chat Assistant",l.appendChild(p),Dh(l,o==null?void 0:o.trailingActions,(T=o==null?void 0:o.onAction)!=null?T:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let z=o.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||z()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),z())})}let j=o==null?void 0:o.titleRowHover;j&&(l.style.borderRadius=(W=j.borderRadius)!=null?W:"10px",l.style.padding=(_=j.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 z,oe;l.style.backgroundColor=(z=j.background)!=null?z:"",l.style.borderColor=(oe=j.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(F=a.closeButtonSize)!=null?F:"32px",f=h("div",""),g=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");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||On.actionIconColor;let v=(M=a.closeButtonIconName)!=null?M:"x",y=Ce(v,"28px","currentColor",1);y?g.appendChild(y):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let w=h("div");w.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:w,headerTitle:p,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Oi={default:Ul,minimal:jl},ql=e=>{var t;return(t=Oi[e])!=null?t:Oi.default},Ps=(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 u=h("span"),f=h("span"),g=h("button");g.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:g,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=ql(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&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ni=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 o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());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:s}},Fi=e=>{var R,T,W,_,F,M,j,z,oe,ke,ze,Ae;let t=(R=e==null?void 0:e.sendButton)!=null?R:{},n=(T=t.useIcon)!=null?T:!1,r=(W=t.iconText)!=null?W:"\u2191",o=t.iconName,s=(_=t.stopIconName)!=null?_:"square",a=(F=t.tooltipText)!=null?F:"Send message",i=(M=t.stopTooltipText)!=null?M:"Stop generating",d=(z=(j=e==null?void 0:e.copy)==null?void 0:j.sendButtonLabel)!=null?z:"Send",l=(ke=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?ke:"Stop",p=(ze=t.showTooltip)!=null?ze:!1,u=(Ae=t.size)!=null?Ae:"40px",f=t.backgroundColor,g=t.textColor,v=h("div","persona-send-button-wrapper"),y=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");y.type="submit",y.setAttribute("data-persona-composer-submit","");let w=null,S=null;if(n){y.style.width=u,y.style.height=u,y.style.minWidth=u,y.style.minHeight=u,y.style.fontSize="18px",y.style.lineHeight="1",y.innerHTML="",g?y.style.color=g:y.style.color="var(--persona-button-primary-fg, #ffffff)";let Re=parseFloat(u)||24,be=(g==null?void 0:g.trim())||"currentColor";o?(w=Ce(o,Re,be,2),w?y.appendChild(w):y.textContent=r):y.textContent=r,S=Ce(s,Re,be,2),f?y.style.backgroundColor=f:y.classList.add("persona-bg-persona-primary")}else y.textContent=d,g?y.style.color=g:y.classList.add("persona-text-white");t.borderWidth&&(y.style.borderWidth=t.borderWidth,y.style.borderStyle="solid"),t.borderColor&&(y.style.borderColor=t.borderColor),t.paddingX?(y.style.paddingLeft=t.paddingX,y.style.paddingRight=t.paddingX):(y.style.paddingLeft="",y.style.paddingRight=""),t.paddingY?(y.style.paddingTop=t.paddingY,y.style.paddingBottom=t.paddingY):(y.style.paddingTop="",y.style.paddingBottom="");let O=null;p&&a&&(O=h("div","persona-send-button-tooltip"),O.textContent=a,v.appendChild(O)),y.setAttribute("aria-label",a),v.appendChild(y);let k="send";return{button:y,wrapper:v,setMode:Re=>{if(Re===k)return;k=Re;let be=Re==="stop"?i:a;if(y.setAttribute("aria-label",be),O&&(O.textContent=be),n){if(w&&S){let Le=Re==="stop"?S:w;y.replaceChildren(Le)}}else y.textContent=Re==="stop"?l:d}}},_i=e=>{var O,k,I,R,T,W,_,F,M,j,z,oe;let t=(O=e==null?void 0:e.voiceRecognition)!=null?O:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(r||o))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=(T=t.iconName)!=null?T:"mic",p=(W=t.iconSize)!=null?W:a,u=parseFloat(p)||24,f=(F=t.backgroundColor)!=null?F:(_=e==null?void 0:e.sendButton)==null?void 0:_.backgroundColor,g=(j=t.iconColor)!=null?j:(M=e==null?void 0:e.sendButton)==null?void 0:M.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",g?d.style.color=g:d.style.color="var(--persona-text, #111827)";let y=Ce(l,u,g||"currentColor",1.5);y?d.appendChild(y):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),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 w=(z=t.tooltipText)!=null?z:"Start voice recognition";if(((oe=t.showTooltip)!=null?oe:!1)&&w){let ke=h("div","persona-send-button-tooltip");ke.textContent=w,i.appendChild(ke)}return{button:d,wrapper:i}},$i=e=>{var v,y,w,S,O,k,I,R;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(w=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?w:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let o=h("input");o.type="file",o.accept=((S=t.allowedTypes)!=null?S:Yr).join(","),o.multiple=((O=t.maxFiles)!=null?O:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=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",(k=t.buttonTooltipText)!=null?k:"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 u=Ce(i,p,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",T=>{T.preventDefault(),o.click()}),s.appendChild(a);let f=(R=t.buttonTooltipText)!=null?R:"Attach file",g=h("div","persona-send-button-tooltip");return g.textContent=f,s.appendChild(g),{button:a,wrapper:s,input:o,previewsContainer:r}},Ui=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 o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(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=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},ji=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Is=e=>{var v,y,w,S,O,k;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=ji(),o=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");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=Ni(t);a();let i=Fi(t),d=_i(t),l=$i(t),p=Ui(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),u.append(f,g),o.append(u),o.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)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(y=d==null?void 0:d.wrapper)!=null?y:null,statusText:p,attachmentButton:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(O=l==null?void 0:l.input)!=null?O:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var qm=()=>{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=Ce("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),o=h("span","persona-pill-peek__caret"),s=Ce("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},zm=e=>{var v,y,w,S,O,k;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=ji();r.style.display="none";let o=Ui(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=Ni(t);s.style.maxHeight="100px",a();let i=Fi(t),d=_i(t),l=$i(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 u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.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)&&s.focus()}),l&&p.append(l.input),p.append(u,s,f),l&&n.append(l.previewsContainer),n.append(p,r,o);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(y=d==null?void 0:d.wrapper)!=null?y:null,statusText:o,attachmentButton:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(O=l==null?void 0:l.input)!=null?O:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:g,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var Vm=e=>{var p,u,f,g,v,y,w,S,O,k,I,R,T,W,_,F,M;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=mn(e);if(Eo(e)){let j=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},z=h("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(v=j.expandedSize)!=null?v:"anchored",z.style.zIndex=String((w=(y=e==null?void 0:e.launcher)==null?void 0:y.zIndex)!=null?w:Ln);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",z.appendChild(oe);let ke=h("div","persona-widget-pill-root");return ke.setAttribute("data-persona-composer-bar",""),ke.dataset.state="collapsed",ke.dataset.expandedSize=(S=j.expandedSize)!=null?S:"anchored",ke.style.zIndex=String((k=(O=e==null?void 0:e.launcher)==null?void 0:O.zIndex)!=null?k:Ln),{wrapper:z,panel:oe,pillRoot:ke}}if(n){let j=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(z),{wrapper:j,panel:z}}if(!t){let j=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(R=(I=e==null?void 0:e.launcher)==null?void 0:I.width)!=null?R:"100%";return j.style.width=oe,z.style.width="100%",j.appendChild(z),{wrapper:j,panel:z}}let o=(T=e==null?void 0:e.launcher)!=null?T:{},s=o.position&&Tr[o.position]?Tr[o.position]:Tr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((_=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?_:Ln);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(M=(F=e==null?void 0:e.launcher)==null?void 0:F.width)!=null?M:e==null?void 0:e.launcherWidth,l=d!=null?d:nr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Oh=(e,t)=>{var I,R,T,W,_,F,M,j,z;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:o}=Hi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(T=(R=(I=e==null?void 0:e.launcher)==null?void 0:I.clearChat)==null?void 0:R.enabled)!=null?T:!0,a=null,i=null;if(s){let oe=Bi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.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"),l.style.setProperty("scrollbar-gutter","stable");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 u=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(_=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?_:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(M=(F=e==null?void 0:e.copy)==null?void 0:F.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",p.append(u,f);let g=h("div","persona-flex persona-flex-col persona-gap-3"),v=(j=e==null?void 0:e.layout)==null?void 0:j.contentMaxWidth;v&&(g.style.maxWidth=v,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,g);let w=h("div","persona-composer-overlay persona-pointer-events-none");w.setAttribute("data-persona-composer-overlay",""),w.style.position="absolute",w.style.left="0",w.style.right="0",w.style.bottom="0",w.style.zIndex="20";let S=zm({config:e}),{root:O,textNode:k}=qm();return n.append(d,o,l,w),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:g,composerOverlay:w,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,introTitle:u,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode,peekBanner:O,peekTextNode:k}},Km=(e,t=!0)=>{var w,S,O,k,I,R,T,W,_;if(Eo(e))return Oh(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=(w=e==null?void 0:e.layout)==null?void 0:w.header,o=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,s=r?Ps(e,r,{showClose:t}):eo({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"),a.style.setProperty("scrollbar-gutter","stable");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=mn(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=(k=(O=e==null?void 0:e.copy)==null?void 0:O.welcomeTitle)!=null?k:"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"),u=(T=e==null?void 0:e.layout)==null?void 0:T.contentMaxWidth;u&&(p.style.maxWidth=u,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 g=Is({config:e}),v=((_=e==null?void 0:e.layout)==null?void 0:_.showFooter)!==!1;o?es(n,s,e):(s.header.style.display="none",es(n,s,e)),n.append(a);let y=h("div","persona-composer-overlay persona-pointer-events-none");return y.setAttribute("data-persona-composer-overlay",""),y.style.position="absolute",y.style.left="0",y.style.right="0",y.style.bottom="0",y.style.zIndex="20",v||(g.footer.style.display="none"),n.append(g.footer),n.append(y),{container:n,body:a,messagesWrapper:p,composerOverlay:y,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var Nh=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}},Fh=(e,t)=>{if(!e)return null;let n=Nh(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},_h=(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},$h=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},zl=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(":"))},Vl=320,Jm=320,Uh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),jh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),qh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),zh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Vh=(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 o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let l=h("img");l.alt=((u=i.alt)==null?void 0:u.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=`${Vl}px`,l.style.maxHeight=`${Jm}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;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),$h(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Kh=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(!zl(r.audio))return;let o=h("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Vl}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Gh=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(!zl(r.video))return;let o=h("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Vl}px`,o.style.maxHeight=`${Jm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Jh=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(!zl(r.data))return;let o=h("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ts=()=>{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 o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},Kl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ts};if(t){let o=t(r);if(o!==null)return o}return ts()},Qh=(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 o=h("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}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},Gm=(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},Xh=(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},Gl=(e,t,n)=>{var g,v,y,w,S,O;let r=(g=t.showCopy)!=null?g:!0,o=(v=t.showUpvote)!=null?v:!0,s=(y=t.showDownvote)!=null?y:!0;if(!r&&!o&&!s){let k=h("div");return k.style.display="none",k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id),k}let a=(w=t.visibility)!=null?w:"hover",i=(S=t.align)!=null?S:"right",d=(O=t.layout)!=null?O:"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],u=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let f=(k,I,R)=>{let T=Vt({icon:k,label:I,size:14,className:"persona-message-action-btn"});return T.setAttribute("data-action",R),T};return r&&u.appendChild(f("copy","Copy message","copy")),o&&u.appendChild(f("thumbs-up","Upvote","upvote")),s&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},Rs=(e,t,n,r,o,s)=>{var de,X,re,ce,ge,K,ae,He,Y,ee,ie,Se,Ze,ve,fe,Je,De;let a=n!=null?n:{},i=(de=a.layout)!=null?de:"bubble",d=a.avatar,l=a.timestamp,p=(X=d==null?void 0:d.show)!=null?X:!1,u=(re=l==null?void 0:l.show)!=null?re:!1,f=(ce=d==null?void 0:d.position)!=null?ce:"left",g=(ge=l==null?void 0:l.position)!=null?ge:"below",v=Xh(e.role,i),y=h("div",v.join(" "));y.id=`bubble-${e.id}`,y.setAttribute("data-message-id",e.id),y.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(y.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",y.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(y.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",y.style.color="var(--persona-message-assistant-text, var(--persona-text))");let w=Uh(e),S=(ae=(K=e.content)==null?void 0:K.trim())!=null?ae:"",k=w.length>0&&S===fi,I=Ii((Y=(He=s==null?void 0:s.widgetConfig)==null?void 0:He.features)==null?void 0:Y.streamAnimation),R=(Se=(ie=(ee=s==null?void 0:s.widgetConfig)==null?void 0:ee.features)==null?void 0:ie.streamAnimation)==null?void 0:Se.plugins,T=e.role==="assistant"&&I.type!=="none"?xa(I.type,R):null,W=e.role==="assistant"&&((Ze=T==null?void 0:T.isAnimating)==null?void 0:Ze.call(T,e))===!0,_=e.role==="assistant"&&T!==null&&(!!e.streaming||W);_&&(T!=null&&T.bubbleClass)&&y.classList.add(T.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),_&&T&&(T.containerClass&&F.classList.add(T.containerClass),F.style.setProperty("--persona-stream-step",`${I.speed}ms`),F.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let M=_?Ri((ve=e.content)!=null?ve:"",I.buffer,T,e,!!e.streaming):(fe=e.content)!=null?fe:"",j=t({text:M,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=j;_&&(T==null?void 0:T.wrap)==="char"?z=va(j,"char",e.id,{skipTags:T.skipTags}):_&&(T==null?void 0:T.wrap)==="word"&&(z=va(j,"word",e.id,{skipTags:T.skipTags}));let oe=null;if(k?(oe=document.createElement("div"),oe.innerHTML=z,oe.style.display="none",F.appendChild(oe)):F.innerHTML=z,_&&(T!=null&&T.useCaret)&&!k&&S){let V=Wi(),ue=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),ot=ue[ue.length-1];if(ot!=null&&ot.parentNode)ot.parentNode.insertBefore(V,ot.nextSibling);else{let Et=F.lastElementChild;Et?Et.appendChild(V):F.appendChild(V)}}if(u&&g==="inline"&&e.createdAt){let V=Gm(e,l);V.classList.add("persona-ml-2","persona-inline"),F.appendChild(V)}if(w.length>0){let V=Vh(w,!k&&!!S,()=>{k&&oe&&(oe.style.display="")});V?y.appendChild(V):k&&oe&&(oe.style.display="")}let ke=jh(e);if(ke.length>0){let V=Kh(ke);V&&y.appendChild(V)}let ze=qh(e);if(ze.length>0){let V=Gh(ze);V&&y.appendChild(V)}let Ae=zh(e);if(Ae.length>0){let V=Jh(Ae);V&&y.appendChild(V)}if(y.appendChild(F),u&&g==="below"&&e.createdAt){let V=Gm(e,l);V.classList.add("persona-mt-1"),y.appendChild(V)}let Re=e.role==="assistant"?Fh(e.stopReason,(De=(Je=s==null?void 0:s.widgetConfig)==null?void 0:Je.copy)==null?void 0:De.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let V=!!(M&&M.trim()),ue=I.placeholder==="skeleton",ot=ue&&I.buffer==="line"&&V;if(V)ot&&y.appendChild(wa());else if(ue)y.appendChild(wa());else{let Et=Kl("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Et&&y.appendChild(Et)}}if(Re&&e.stopReason&&!e.streaming&&(S||(F.style.display="none"),y.appendChild(_h(e.stopReason,Re))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let V=Gl(e,r,o);y.appendChild(V)}if(!p||e.role==="system")return y;let Le=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),We=Qh(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Le.append(y,We):Le.append(We,y),y.classList.remove("persona-max-w-[85%]"),y.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Le},Qm=(e,t,n,r,o,s)=>{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}):Rs(e,t,n,r,o,s)};var Ws=new Set,Yh=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Zh=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
24
+ `):""},Xm=(e,t)=>{let n=Ws.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)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=Ce(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Jl=(e,t)=>{var ze,Ae,Re,be,Le,We,de,X,re,ce,ge;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 o=(Ae=(ze=t==null?void 0:t.features)==null?void 0:ze.reasoningDisplay)!=null?Ae:{},s=o.expandable!==!1,a=s&&Ws.has(e.id),i=n.status!=="complete",d=Zh(e,(Re=o.previewMaxLines)!=null?Re:3),l=h("button",s?"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",s&&(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"),u=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(be=t==null?void 0:t.reasoning)!=null?be:{},v=String((Le=n.startedAt)!=null?Le:Date.now()),y=()=>{let K=h("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=ii(n),K},w=(We=g.renderCollapsedSummary)==null?void 0:We.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:ii(n),createElapsedElement:y});typeof w=="string"&&w.trim()?(u.textContent=w,p.appendChild(u)):w instanceof HTMLElement?p.appendChild(w):(u.textContent=f,p.appendChild(u));let S=h("span","persona-text-xs persona-text-persona-primary");S.textContent=om(n),p.appendChild(S);let O=(de=o.loadingAnimation)!=null?de:"none",k=g.activeTextTemplate,I=g.completeTextTemplate,R=i?k:I,T=w instanceof HTMLElement,W=(K,ae,He)=>{let Y=He;for(let ee of ae){let ie=h("span","persona-tool-char");ie.style.setProperty("--char-index",String(Y)),ie.textContent=ee===" "?"\xA0":ee,K.appendChild(ie),Y++}return Y},_=(K,ae)=>{u.textContent="";let He=li(K,""),Y=0;for(let ee of He){let ie=ee.styles.length>0?(()=>{let Se=h("span",ee.styles.map(Ze=>`persona-tool-text-${Ze}`).join(" "));return u.appendChild(Se),Se})():u;if(ee.isDuration&&i)ie.appendChild(y());else{let Se=ee.isDuration?ii(n):ee.text;ae?Y=W(ie,Se,Y):ie.appendChild(document.createTextNode(Se))}}};if(!T&&R)if(S.style.display="none",u.style.display="",i&&O!=="none"){let K=(X=g.loadingAnimationDuration)!=null?X:2e3;u.setAttribute("data-preserve-animation","true"),O==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),_(R,!1)):(u.classList.add(`persona-tool-loading-${O}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),O==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),_(R,!0))}else _(R,!1);else if(!T&&i&&O!=="none"){u.style.display="";let K=(re=g.loadingAnimationDuration)!=null?re:2e3;if(u.setAttribute("data-preserve-animation","true"),O==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{u.classList.add(`persona-tool-loading-${O}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),O==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let ae=u.textContent||f;u.textContent="",W(u,ae,0)}n.status==="complete"&&(u.style.display="none")}else T||(n.status==="complete"?u.style.display="none":u.style.display="");let F=null;if(s){F=h("div","persona-flex persona-items-center");let ae=Ce(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?F.appendChild(ae):F.textContent=a?"Hide":"Show";let He=h("div","persona-flex persona-items-center persona-ml-auto");He.append(F),l.append(p,He)}else l.append(p);let M=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(M.setAttribute("data-persona-collapsed-preview","reasoning"),M.style.display="none",M.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let K=(ge=(ce=t==null?void 0:t.reasoning)==null?void 0:ce.renderCollapsedPreview)==null?void 0:ge.call(ce,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Yh(M,K)||(M.textContent=d),M.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,M),r;let j=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let z=n.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=z||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),F){F.innerHTML="";let ae=Ce(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?F.appendChild(ae):F.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",M.style.display=a?"none":M.textContent||M.childNodes.length?"":"none"})(),r.append(l,M,j),r};var Hs=new Set,eb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),tb=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
+ `);let o=Ss(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},nb=(e,t)=>{var p,u,f,g,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=tb(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?sm(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},l=a;return o==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Pl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Pl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Ym=(e,t,n)=>{var p;let r=Hs.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"currentColor",f=Ce(r?"chevron-up":"chevron-down",16,u,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Ql=(e,t)=>{var z,oe,ke,ze,Ae,Re,be,Le,We;let n=e.toolCall,r=(z=t==null?void 0:t.toolCall)!=null?z:{},o=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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(ke=(oe=t==null?void 0:t.features)==null?void 0:oe.toolCallDisplay)!=null?ke:{},a=s.expandable!==!1,i=a&&Hs.has(e.id),{summary:d,previewText:l,isActive:p}=nb(e,t),u=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");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let v=String((ze=n.startedAt)!=null?ze:Date.now()),y=()=>{let de=h("span","");return de.setAttribute("data-tool-elapsed",v),de.textContent=da(n),de},w=(Re=r.renderCollapsedSummary)==null?void 0:Re.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Ae=s.collapsedMode)!=null?Ae:"tool-call",isActive:p,config:t!=null?t:{},elapsed:da(n),createElapsedElement:y});typeof w=="string"&&w.trim()?(g.textContent=w,f.appendChild(g)):w instanceof HTMLElement?f.appendChild(w):(g.textContent=d,f.appendChild(g));let S=(be=s.loadingAnimation)!=null?be:"none",O=r.activeTextTemplate,k=r.completeTextTemplate,I=p?O:k,R=w instanceof HTMLElement,T=(de,X,re)=>{let ce=re;for(let ge of X){let K=h("span","persona-tool-char");K.style.setProperty("--char-index",String(ce)),K.textContent=ge===" "?"\xA0":ge,de.appendChild(K),ce++}return ce},W=(de,X)=>{var K;g.textContent="";let re=((K=n.name)==null?void 0:K.trim())||"tool",ce=li(de,re),ge=0;for(let ae of ce){let He=ae.styles.length>0?(()=>{let Y=h("span",ae.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return g.appendChild(Y),Y})():g;if(ae.isDuration&&p)He.appendChild(y());else{let Y=ae.isDuration?da(n):ae.text;X?ge=T(He,Y,ge):He.appendChild(document.createTextNode(Y))}}};if(!R)if(p&&S!=="none"){let de=(Le=r.loadingAnimationDuration)!=null?Le:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${de}ms`),I&&W(I,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${de}ms`),S==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),I)W(I,!0);else{let X=g.textContent||d;g.textContent="",T(g,X,0)}}else I&&W(I,!1);let _=null;if(a){_=h("div","persona-flex persona-items-center");let de=r.toggleTextColor||r.headerTextColor||"currentColor",X=Ce(i?"chevron-up":"chevron-down",16,de,2);X?_.appendChild(X):_.textContent=i?"Hide":"Show";let re=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");re.append(_),u.append(f,re)}else u.append(f);let F=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","tool"),F.style.display="none",F.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let de=(We=r.renderCollapsedPreview)==null?void 0:We.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});eb(F,de)||(F.textContent=l),F.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,F),o;let M=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(M.style.display=i?"":"none",r.contentBackgroundColor&&(M.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(M.style.color=r.contentTextColor),r.contentPaddingX&&(M.style.paddingLeft=r.contentPaddingX,M.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(M.style.paddingTop=r.contentPaddingY,M.style.paddingBottom=r.contentPaddingY),n.name){let de=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?de.style.color=r.contentTextColor:r.headerTextColor&&(de.style.color=r.headerTextColor),de.textContent=n.name,M.appendChild(de)}if(n.args!==void 0){let de=h("div","persona-space-y-1"),X=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Arguments";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(re.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(re.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(re.style.color=r.codeBlockTextColor),re.textContent=Ss(n.args),de.append(X,re),M.appendChild(de)}if(n.chunks&&n.chunks.length){let de=h("div","persona-space-y-1"),X=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Activity";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(re.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(re.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(re.style.color=r.codeBlockTextColor),re.textContent=n.chunks.join(""),de.append(X,re),M.appendChild(de)}if(n.status==="complete"&&n.result!==void 0){let de=h("div","persona-space-y-1"),X=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Result";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(re.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(re.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(re.style.color=r.codeBlockTextColor),re.textContent=Ss(n.result),de.append(X,re),M.appendChild(de)}if(n.status==="complete"&&typeof n.duration=="number"){let de=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(de.style.color=r.contentTextColor),de.textContent=`Duration: ${n.duration}ms`,M.appendChild(de)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),_){_.innerHTML="";let de=r.toggleTextColor||r.headerTextColor||"currentColor",X=Ce(i?"chevron-up":"chevron-down",16,de,2);X?_.appendChild(X):_.textContent=i?"Hide":"Show"}M.style.display=i?"":"none",F.style.display=i?"none":F.textContent||F.childNodes.length?"":"none"})(),o.append(u,F,M),o};var qi=new Map,rb=e=>{let n=(e.startsWith(Gr)?e.slice(Gr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Zm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,eg=(e,t)=>{var r,o,s;let n=(o=(r=Zm(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=qi.get(e))!=null?s:n==="expanded"},tg=(e,t,n)=>{var a,i;let r=Zm(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ce(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},ng=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=eg(e,n);tg(r,s,n),o.style.display=s?"":"none"};var zi=(e,t)=>{var W,_,F,M,j,z,oe,ke,ze,Ae,Re,be,Le,We,de;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=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(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(W=r==null?void 0:r.backgroundColor)!=null?W:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(_=r==null?void 0:r.borderColor)!=null?_:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;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)":(F=r==null?void 0:r.titleColor)!=null?F:"currentColor",p=Ce(d,20,l,2);p&&i.appendChild(p);let u=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(M=r==null?void 0:r.title)!=null?M:"Approval Required",f.appendChild(g),!o){let X=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",n.status),n.status==="approved"?(X.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",X.style.color="var(--persona-palette-colors-success-700, #15803d)",X.textContent="Approved"):n.status==="denied"?(X.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",X.style.color="var(--persona-palette-colors-error-700, #b91c1c)",X.textContent="Denied"):n.status==="timeout"&&(X.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",X.style.color="var(--persona-palette-colors-warning-700, #b45309)",X.textContent="Timeout"),f.appendChild(X)}u.appendChild(f);let y=n.toolType==="webmcp"||n.toolName.startsWith(Gr)?xl(n.toolName):void 0,w=(j=r==null?void 0:r.formatDescription)==null?void 0:j.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...y?{displayTitle:y}:{},...n.reason?{reason:n.reason}:{}}),S=!n.toolName,O=w||(S?n.description:`The assistant wants to use \u201C${y!=null?y:rb(n.toolName)}\u201D.`),k=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=O,u.appendChild(k),n.reason){let X=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?X.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor);let re=h("span","persona-font-medium");re.textContent=`${(z=r==null?void 0:r.reasonLabel)!=null?z:"Agent's stated reason:"} `,X.appendChild(re),X.appendChild(document.createTextNode(n.reason)),u.appendChild(X)}let I=(oe=r==null?void 0:r.detailsDisplay)!=null?oe:"collapsed",R=!!n.description&&!S,T=R||!!n.parameters;if(I!=="hidden"&&T){let X=eg(e.id,t),re=h("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");re.type="button",re.setAttribute("data-expand-header","true"),re.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(re.style.color=r.descriptionColor);let ce=h("span");ce.setAttribute("data-approval-details-label","true");let ge=h("span","persona-inline-flex persona-items-center");ge.setAttribute("data-approval-details-chevron","true"),re.append(ce,ge),tg(re,X,t),u.appendChild(re);let K=h("div");if(K.setAttribute("data-approval-details","true"),K.style.display=X?"":"none",R){let ae=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor),ae.textContent=n.description,K.appendChild(ae)}if(n.parameters){let ae=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&&(ae.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ae.style.color=r.parameterTextColor),ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",ae.textContent=Ss(n.parameters),K.appendChild(ae)}u.appendChild(K)}if(o){let X=h("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let re=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");re.type="button",re.style.backgroundColor=(ke=r==null?void 0:r.approveButtonColor)!=null?ke:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(ze=r==null?void 0:r.approveButtonTextColor)!=null?ze:"#ffffff",re.setAttribute("data-approval-action","approve");let ce=Ce("shield-check",14,(Ae=r==null?void 0:r.approveButtonTextColor)!=null?Ae:"#ffffff",2);ce&&(ce.style.marginRight="4px",re.appendChild(ce));let ge=document.createTextNode((Re=r==null?void 0:r.approveLabel)!=null?Re:"Approve");re.appendChild(ge);let K=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");K.type="button",K.style.backgroundColor=(be=r==null?void 0:r.denyButtonColor)!=null?be:"transparent",K.style.color=(Le=r==null?void 0:r.denyButtonTextColor)!=null?Le:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let ae=Ce("shield-x",14,(We=r==null?void 0:r.denyButtonTextColor)!=null?We:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",K.appendChild(ae));let He=document.createTextNode((de=r==null?void 0:r.denyLabel)!=null?de:"Deny");K.appendChild(He),X.append(re,K),u.appendChild(X)}return a.append(i,u),s.appendChild(a),s};var rg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(w=>w.role==="user"))return;let u=document.createDocumentFragment(),f=s?s.isStreaming():!1,g=v=>{switch(v){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'}};if(o.forEach(v=>{let y=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");y.type="button",y.textContent=v,y.disabled=f,d!=null&&d.fontFamily&&(y.style.fontFamily=g(d.fontFamily)),d!=null&&d.fontWeight&&(y.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(y.style.paddingLeft=d.paddingX,y.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(y.style.paddingTop=d.paddingY,y.style.paddingBottom=d.paddingY),y.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(y),t.push(y)}),e.appendChild(u),p){let v=JSON.stringify(o);v!==n&&(n=v,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Ma=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 ka=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 o=r.result;o.objectStoreNames.contains(this.storeName)||o.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 o of t)r.put(o)}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 s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.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 o of t)r.put(o)}catch{}}};var ob=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),sb=new Set(["step_start","execution_start"]),ab=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),ib=new Set(["step_complete","agent_turn_complete"]),lb=new Set(["flow_complete","agent_complete"]),og=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),ag=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),or=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ns=(e,t)=>{let n=e[t];return ag(n)?n:void 0};function Xl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Vi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function cb(e,t){return typeof t.type=="string"?t.type:e}function db(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 pb(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 sg(e){var r,o,s,a,i;let t=ns(e,"result"),n=[ns(e,"tokens"),ns(e,"totalTokens"),t?ns(t,"tokens"):void 0,ns(e,"usage"),t?ns(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=or(d.output))!=null?r:or(d.outputTokens))!=null?o:or(d.completionTokens);if(l!==void 0)return l}return(i=(s=or(e.outputTokens))!=null?s:or(e.completionTokens))!=null?i:t?(a=or(t.outputTokens))!=null?a:or(t.completionTokens):void 0}function ub(e){var n,r,o,s,a;let t=ns(e,"result");return(a=(o=(r=(n=or(e.executionTime))!=null?n:or(e.executionTimeMs))!=null?r:or(e.execution_time))!=null?o:or(e.duration))!=null?a:t?(s=or(t.executionTime))!=null?s:or(t.executionTimeMs):void 0}function mb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var La=class{constructor(t=mb){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:Vi(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 s;if(!ag(n)){og.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=cb(t,n),o=this.now();if(ob.has(r)){this.startRun(o);return}if(sb.has(r)){this.run||this.startRun(o);return}if(ab.has(r)){if(!pb(r,n))return;let a=db(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Xl(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Vi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(ib.has(r)){if(!this.run)return;let a=this.run,i=sg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Xl(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:Vi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(lb.has(r)){if(!this.run)return;let a=this.run,i=sg(n),d=i!=null?i:a.exactOutputTokens+Xl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:Vi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(og.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=ub(n);return s!=null?s:r-t.startedAt}};function Bs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var gb={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)"}},fb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},hb=["flowName","stepName","reasoningText","text","name","tool","toolName"],bb=100;function yb(e,t){let n={...gb,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return fb}function xb(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function vb(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function wb(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Cb(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 Ab(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 Sb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Tb(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 Eb(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});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 Yl(e,t,n,r,o,s,a,i){var f;let d=o.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Bs(l,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(u()),l;function u(){var z,oe;let g=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 y=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),w=Ce(d?"chevron-down":"chevron-right","14px","currentColor",2);w&&y.appendChild(w);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),O=(z=r.timestampFormat)!=null?z:"relative";S.textContent=O==="relative"?xb(e.timestamp,n):vb(e.timestamp);let k=null;r.showSequenceNumbers!==!1&&(k=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let I=yb(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 T=(oe=r.descriptionFields)!=null?oe:hb,W=wb(e.payload,T),_=null;W&&(_=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),_.textContent=W);let F=h("div","persona-flex-1 persona-min-w-0"),M=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"),j=Ce("clipboard","12px","currentColor",1.5);return j&&M.appendChild(j),M.addEventListener("click",async ke=>{ke.stopPropagation(),await Cb(Ab(e)),M.innerHTML="";let ze=Ce("check","12px","currentColor",1.5);ze&&M.appendChild(ze),setTimeout(()=>{M.innerHTML="";let Ae=Ce("clipboard","12px","currentColor",1.5);Ae&&M.appendChild(Ae)},1500)}),v.appendChild(y),v.appendChild(S),k&&v.appendChild(k),v.appendChild(R),_&&v.appendChild(_),v.appendChild(F),v.appendChild(M),g.appendChild(v),d&&g.appendChild(Eb(e,a,i)),g}}function ig(e){var v,y,w,S,O;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(y=i==null?void 0:i.iconName)!=null?y:"arrow-down",p=(w=i==null?void 0:i.label)!=null?w:"",u=(O=(S=o==null?void 0:o.features)==null?void 0:S.eventStream)!=null?O:{},f=s.find(k=>k.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let k=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return g();function g(){let k=u.classNames,I=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Bs(I,k==null?void 0:k.panel);let R=[],T="",W="",_=null,F=[],M={},j=0,z=ki(),oe=0,ke=0,ze=!1,Ae=null,Re=!1,be=0,Le=new Set,We=new Map,de="",X="",re=null,ce,ge,K,ae,He,Y=null,ee=null,ie=null;function Se(){let we=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),le=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");Bs(le,k==null?void 0:k.headerBar);let nt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(nt.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){ee=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let An=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");An.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",ie=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"),ie.style.display="none",ie.style.pointerEvents="none";let Sn=ee,yn=ie,Mr=()=>{if(!yn.textContent)return;let jn=Sn.getBoundingClientRect(),qn=we.getBoundingClientRect();yn.style.left=`${jn.left-qn.left}px`,yn.style.top=`${jn.bottom-qn.top+4}px`,yn.style.display="block"},At=()=>{yn.style.display="none"};ee.addEventListener("mouseenter",Mr),ee.addEventListener("mouseleave",At),ee.appendChild(An),ee.appendChild(Y)}let tn=h("div","persona-flex-1");ge=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 Gt=h("option","");Gt.value="",Gt.textContent="All events",ge.appendChild(Gt),K=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"),K.type="button",K.title="Copy All";let wn=Ce("clipboard-copy","12px","currentColor",1.5);wn&&K.appendChild(wn);let mt=h("span","persona-text-xs");mt.textContent="Copy All",K.appendChild(mt),le.appendChild(nt),le.appendChild(ce),ee&&le.appendChild(ee),le.appendChild(tn),le.appendChild(ge),le.appendChild(K);let Mt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Bs(Mt,k==null?void 0:k.searchBar);let et=Ce("search","14px","var(--persona-muted, #9ca3af)",1.5),qt=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");et&&qt.appendChild(et),ae=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"),Bs(ae,k==null?void 0:k.searchInput),ae.type="text",ae.placeholder="Search event payloads...",He=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"),He.type="button",He.style.display="none";let dn=Ce("x","12px","currentColor",2);return dn&&He.appendChild(dn),Mt.appendChild(qt),Mt.appendChild(ae),Mt.appendChild(He),we.appendChild(le),we.appendChild(Mt),ie&&we.appendChild(ie),we}let Ze,ve=s.find(we=>we.renderEventStreamToolbar);if(ve!=null&&ve.renderEventStreamToolbar&&o){let we=ve.renderEventStreamToolbar({config:o,defaultRenderer:()=>Se(),eventCount:t.getSize(),filteredCount:0,onFilterChange:le=>{T=le,cn(),H()},onSearchChange:le=>{W=le,cn(),H()}});Ze=we!=null?we:Se()}else Ze=Se();let fe=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");fe.style.display="none";function Je(){if(!a||!Y||!ee)return;let we=a();Y.textContent=Sb(we);let le=Tb(we);ie&&(ie.textContent=le,le||(ie.style.display="none")),le?ee.setAttribute("aria-label",le):ee.removeAttribute("aria-label")}let De=h("div","persona-flex-1 persona-min-h-0 persona-relative"),V=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");V.style.height="100%";let ue=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");Bs(ue,k==null?void 0:k.scrollIndicator),ue.style.display="none",ue.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let ot=Ce(l,"14px","currentColor",2);ot&&ue.appendChild(ot);let Et=h("span","");Et.textContent=p,ue.appendChild(Et);let ne=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ne.style.display="none",De.appendChild(V),De.appendChild(ne),De.appendChild(ue),I.setAttribute("tabindex","0"),I.appendChild(Ze),I.appendChild(fe),I.appendChild(De);function Ve(){let we=t.getAll(),le={};for(let mt of we)le[mt.type]=(le[mt.type]||0)+1;let nt=Object.keys(le).sort(),tn=nt.length!==F.length||!nt.every((mt,Mt)=>mt===F[Mt]),Gt=!tn&&nt.some(mt=>le[mt]!==M[mt]),Pn=we.length!==Object.values(M).reduce((mt,Mt)=>mt+Mt,0);if(!tn&&!Gt&&!Pn||(F=nt,M=le,!ge))return;let wn=ge.value;if(ge.options[0].textContent="All events",tn){for(;ge.options.length>1;)ge.remove(1);for(let mt of nt){let Mt=h("option","");Mt.value=mt,Mt.textContent=`${mt} (${le[mt]||0})`,ge.appendChild(Mt)}wn&&nt.includes(wn)?ge.value=wn:wn&&(ge.value="",T="")}else for(let mt=1;mt<ge.options.length;mt++){let Mt=ge.options[mt];Mt.textContent=`${Mt.value} (${le[Mt.value]||0})`}}function Nn(){let we=t.getAll();if(T&&(we=we.filter(le=>le.type===T)),W){let le=W.toLowerCase();we=we.filter(nt=>nt.type.toLowerCase().includes(le)||nt.payload.toLowerCase().includes(le))}return we}function Ht(){return T!==""||W!==""}function cn(){j=0,oe=0,z.resume(),ue.style.display="none"}function sr(we){Le.has(we)?Le.delete(we):Le.add(we),re=we;let le=V.scrollTop,nt=z.isFollowing();Re=!0,z.pause(),H(),V.scrollTop=le,nt&&z.resume(),Re=!1}function Er(){return Zo(V,50)}function H(){ke=Date.now(),ze=!1,Je(),Ve();let we=t.getEvictedCount();we>0?(fe.textContent=`${we.toLocaleString()} older events truncated`,fe.style.display=""):fe.style.display="none",R=Nn();let le=R.length,nt=t.getSize()>0;ce&&(ce.textContent=String(t.getSize())),le===0&&nt&&Ht()?(ne.textContent=W?`No events matching '${W}'`:"No events matching filter",ne.style.display="",V.style.display="none"):(ne.style.display="none",V.style.display=""),K&&(K.title=Ht()?`Copy Filtered (${le})`:"Copy All"),d&&!z.isFollowing()&&le>j&&(oe+=le-j,Et.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",ue.style.display=""),j=le;let tn=t.getAll(),Gt=tn.length>0?tn[0].timestamp:0,Pn=new Set(R.map(Mt=>Mt.id));for(let Mt of Le)Pn.has(Mt)||Le.delete(Mt);let wn=T!==de||W!==X,mt=We.size===0&&R.length>0;if(wn||mt||R.length===0){V.innerHTML="",We.clear();let Mt=document.createDocumentFragment();for(let et=0;et<R.length;et++){let qt=Yl(R[et],et,Gt,u,Le,sr,s,o);We.set(R[et].id,qt),Mt.appendChild(qt)}V.appendChild(Mt),de=T,X=W,re=null}else{if(re!==null){let et=We.get(re);if(et&&et.parentNode===V){let qt=R.findIndex(dn=>dn.id===re);if(qt>=0){let dn=Yl(R[qt],qt,Gt,u,Le,sr,s,o);V.insertBefore(dn,et),et.remove(),We.set(re,dn)}}re=null}let Mt=new Set(R.map(et=>et.id));for(let[et,qt]of We)Mt.has(et)||(qt.remove(),We.delete(et));for(let et=0;et<R.length;et++){let qt=R[et];if(!We.has(qt.id)){let dn=Yl(qt,et,Gt,u,Le,sr,s,o);We.set(qt.id,dn),V.appendChild(dn)}}}z.isFollowing()&&(V.scrollTop=V.scrollHeight)}function pe(){if(Date.now()-ke>=bb){Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),H();return}ze||(ze=!0,Ae=requestAnimationFrame(()=>{Ae=null,H()}))}let Oe=(we,le)=>{if(!K)return;K.innerHTML="";let nt=Ce(we,"12px","currentColor",1.5);nt&&K.appendChild(nt);let tn=h("span","persona-text-xs");tn.textContent="Copy All",K.appendChild(tn),setTimeout(()=>{K.innerHTML="";let Gt=Ce("clipboard-copy","12px","currentColor",1.5);Gt&&K.appendChild(Gt);let Pn=h("span","persona-text-xs");Pn.textContent="Copy All",K.appendChild(Pn),K.disabled=!1},le)},Qe=async()=>{if(K){K.disabled=!0;try{let we;Ht()?we=R:n?(we=await n(),we.length===0&&(we=t.getAll())):we=t.getAll();let le=we.map(nt=>{try{return JSON.parse(nt.payload)}catch{return nt.payload}});await navigator.clipboard.writeText(JSON.stringify(le,null,2)),Oe("check",1500)}catch{Oe("x",1500)}}},_e=()=>{ge&&(T=ge.value,cn(),H())},Ue=()=>{!ae||!He||(He.style.display=ae.value?"":"none",_&&clearTimeout(_),_=setTimeout(()=>{W=ae.value,cn(),H()},150))},at=()=>{!ae||!He||(ae.value="",W="",He.style.display="none",_&&clearTimeout(_),cn(),H())},Pt=()=>{if(Re)return;let we=V.scrollTop,{action:le,nextLastScrollTop:nt}=Li({following:z.isFollowing(),currentScrollTop:we,lastScrollTop:be,nearBottom:Er(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=nt,le==="resume"?(z.resume(),oe=0,ue.style.display="none"):le==="pause"&&(z.pause(),d&&(Et.textContent=p,ue.style.display=""))},Kt=we=>{let le=Pi({following:z.isFollowing(),deltaY:we.deltaY,nearBottom:Er(),resumeWhenNearBottom:!0});le==="pause"?(z.pause(),d&&(Et.textContent=p,ue.style.display="")):le==="resume"&&(z.resume(),oe=0,ue.style.display="none")},Zt=()=>{d&&(V.scrollTop=V.scrollHeight,z.resume(),oe=0,ue.style.display="none")},G=we=>{let le=we.target;if(!le||le.closest("button"))return;let nt=le.closest("[data-event-id]");if(!nt)return;let tn=nt.getAttribute("data-event-id");tn&&sr(tn)},xt=we=>{if((we.metaKey||we.ctrlKey)&&we.key==="f"){we.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}we.key==="Escape"&&(ae&&document.activeElement===ae?(at(),ae.blur(),I.focus()):r&&r())};K&&K.addEventListener("click",Qe),ge&&ge.addEventListener("change",_e),ae&&ae.addEventListener("input",Ue),He&&He.addEventListener("click",at),V.addEventListener("scroll",Pt),V.addEventListener("wheel",Kt,{passive:!0}),V.addEventListener("click",G),ue.addEventListener("click",Zt),I.addEventListener("keydown",xt);function lt(){_&&clearTimeout(_),Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),ze=!1,We.clear(),K&&K.removeEventListener("click",Qe),ge&&ge.removeEventListener("change",_e),ae&&ae.removeEventListener("input",Ue),He&&He.removeEventListener("click",at),V.removeEventListener("scroll",Pt),V.removeEventListener("wheel",Kt),V.removeEventListener("click",G),ue.removeEventListener("click",Zt),I.removeEventListener("keydown",xt)}return{element:I,update:pe,destroy:lt}}}function lg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=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 u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(g)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var cg=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.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:()=>lg(e,t)});if(p)return p}return lg(e,t)};var Zl=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)})}},to=new Zl;to.register("PersonaArtifactCard",cg);function Mb(e){var o;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((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function dg(e,t){var ge,K,ae,He;let n=(K=(ge=e.features)==null?void 0:ge.artifacts)==null?void 0:K.layout,o=((ae=n==null?void 0:n.toolbarPreset)!=null?ae:"default")==="document",s=(He=n==null?void 0:n.panePadding)==null?void 0:He.trim(),a=e.markdown?jo(e.markdown):null,i=xs(e.sanitize),d=Y=>{let ee=a?a(Y):qo(Y);return i?i(ee):ee},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"),u.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};l&&l.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let u=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let g=h("span","persona-text-xs persona-font-medium persona-truncate");g.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 y="rendered",w=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=o?Vt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Vt({icon:"eye",label:"Rendered view"}),O=o?Vt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Vt({icon:"code-2",label:"Source"}),k=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,T=n==null?void 0:n.documentToolbarCopyMenuItems,W=!!(R&&T&&T.length>0),_=null,F,M=null,j=null;if(o&&(I||R)&&!W){if(F=I?Ta({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let Y=Ce("chevron-down",14,"currentColor",2);Y&&F.appendChild(Y)}}else o&&W?(_=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),F=I?Ta({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),M=Vt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),_.append(F,M)):o?F=Vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):F=Vt({icon:"copy",label:"Copy"});let z=o?Vt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Vt({icon:"refresh-cw",label:"Refresh"}),oe=o?Vt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Vt({icon:"x",label:"Close"}),ke=()=>{var Ze,ve,fe;let Y=(Ze=We.find(Je=>Je.id===de))!=null?Ze:We[We.length-1],ee=(ve=Y==null?void 0:Y.id)!=null?ve:null,ie=(Y==null?void 0:Y.artifactType)==="markdown"&&(fe=Y.markdown)!=null?fe:"",Se=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:ie,jsonPayload:Se,id:ee}},ze=async()=>{var Ze;let{markdown:Y,jsonPayload:ee}=ke(),ie=(Ze=We.find(ve=>ve.id===de))!=null?Ze:We[We.length-1],Se=(ie==null?void 0:ie.artifactType)==="markdown"?Y:ie?ee:"";try{await navigator.clipboard.writeText(Se)}catch{}};if(F.addEventListener("click",async()=>{let Y=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Y&&W){let{markdown:ee,jsonPayload:ie,id:Se}=ke();try{await Y({actionId:"primary",artifactId:Se,markdown:ee,jsonPayload:ie})}catch{}return}await ze()}),M&&(T!=null&&T.length)){let Y=()=>{var ie;return(ie=u.closest("[data-persona-root]"))!=null?ie:document.body},ee=()=>{j=Mo({items:T.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:Se,jsonPayload:Ze,id:ve}=ke(),fe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{fe?await fe({actionId:ie,artifactId:ve,markdown:Se,jsonPayload:Ze}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(Se):ie==="json"||ie==="source"?await navigator.clipboard.writeText(Ze):await navigator.clipboard.writeText(Se||Ze)}catch{}},anchor:_!=null?_:M,position:"bottom-right",portal:Y()})};u.isConnected?ee():requestAnimationFrame(ee),M.addEventListener("click",ie=>{ie.stopPropagation(),j==null||j.toggle()})}z.addEventListener("click",async()=>{var Y;try{await((Y=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Y.call(n))}catch{}re()}),oe.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let Ae=()=>{o&&(S.setAttribute("aria-pressed",y==="rendered"?"true":"false"),O.setAttribute("aria-pressed",y==="source"?"true":"false"))};S.addEventListener("click",()=>{y="rendered",Ae(),re()}),O.addEventListener("click",()=>{y="source",Ae(),re()});let Re=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");o?(f.replaceChildren(),w.append(S,O),_?k.append(_,z,oe):k.append(F,z,oe),f.append(w,Re,k),Ae()):(f.appendChild(g),f.appendChild(v)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let be=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(be.style.paddingLeft=s,be.style.paddingRight=s,Le.style.padding=s),u.appendChild(f),u.appendChild(be),u.appendChild(Le);let We=[],de=null,X=!1,re=()=>{var Se,Ze,ve,fe;let Y=o&&We.length<=1;be.classList.toggle("persona-hidden",Y),be.replaceChildren();for(let Je of We){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=Je.title||Je.id.slice(0,8),Je.id===de&&De.classList.add("persona-bg-persona-container","persona-border-persona-border"),De.addEventListener("click",()=>t.onSelect(Je.id)),be.appendChild(De)}Le.replaceChildren();let ee=de&&We.find(Je=>Je.id===de)||We[We.length-1];if(!ee)return;if(o){let Je=ee.artifactType==="markdown"?"MD":(Se=ee.component)!=null?Se:"Component",V=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Re.textContent=`${V} \xB7 ${Je}`}else g.textContent="Artifacts";if(ee.artifactType==="markdown"){if(o&&y==="source"){let De=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");De.textContent=(Ze=ee.markdown)!=null?Ze:"",Le.appendChild(De);return}let Je=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Je.innerHTML=d((ve=ee.markdown)!=null?ve:""),Le.appendChild(Je);return}let ie=ee.component?to.get(ee.component):void 0;if(ie){let De={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let V=ie((fe=ee.props)!=null?fe:{},De);if(V){Le.appendChild(V);return}}catch{}}Le.appendChild(Mb(ee))},ce=()=>{var ee;let Y=We.length>0;if(u.classList.toggle("persona-hidden",!Y),l){let ie=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ze=((ee=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&Ze&&X?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(Y){var ee,ie,Se;We=Y.artifacts,de=(Se=(ie=Y.selectedId)!=null?ie:(ee=Y.artifacts[Y.artifacts.length-1])==null?void 0:ee.id)!=null?Se:null,We.length>0&&(X=!0),re(),ce()},setMobileOpen(Y){X=Y,!Y&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):ce()}}}function gr(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 pg(e,t){var s,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"),!gr(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(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)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function kb(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,u,f,g,v,y,w,S;if(!gr(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"),kb(e),pg(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",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"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=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(y=n==null?void 0:n.documentToolbarIconColor)==null?void 0:y.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(w=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:w.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),pg(e,t)}var ug=["panel","seamless"];function Gi(e,t){var i,d,l,p,u,f;for(let g of ug)e.classList.remove(`persona-artifact-appearance-${g}`);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"),!gr(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",o=ug.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.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 g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function mg(e,t){var n,r,o;return!t||!gr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Lb(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 Pb(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 Ib(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Rb(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function gg(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function fg(e,t,n,r,o,s){let a=Lb(o,200),i=Rb(t,n,r,200);i=Math.max(a,i);let d=Pb(s);return d!==null&&(i=Math.min(i,d)),Ib(e,a,i)}var hg={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"}},ec=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,y,w;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(y=hg[a])!=null?y:hg.init;s.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 S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,d.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var T,W;let O=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");O.htmlFor=`${t.id}-${a}-${S.name}`;let k=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=S.label,O.appendChild(k);let I=(T=S.type)!=null?T:"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}-${S.name}`,R.name=S.name,R.placeholder=(W=S.placeholder)!=null?W:"",S.required&&(R.required=!0),O.appendChild(R),p.appendChild(O)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=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");g.type="submit",g.textContent=(w=i.submitLabel)!=null?w:"Submit",u.appendChild(f),u.appendChild(g),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async S=>{var R,T;S.preventDefault();let O=(R=n.formEndpoint)!=null?R:"/form",k=new FormData(p),I={};k.forEach((W,_)=>{I[_]=W}),I.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let W=await fetch(O,{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();f.textContent=(T=_.message)!=null?T:"Thanks! We'll be in touch soon.",_.success&&_.nextPrompt&&await r.sendMessage(String(_.nextPrompt))}catch(W){f.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var tc=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,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Pa=new tc;var bg=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Wb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Hb=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Ia=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Wb(e),n=Hb(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},nc=e=>typeof e=="string"?e:e==null?"":String(e),rs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:nc(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=nc(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:nc(n.text)}}},yg=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ra=e=>{let t=new Set(yg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(yg(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.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:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Bb=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}},Db=e=>e.map(t=>({...t,streaming:!1})),Ob=e=>e.map(t=>({...t,status:"complete"})),Ji=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Bb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?Db(n.messages):void 0,artifacts:n.artifacts?Ob(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},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 Ds=require("partial-json");function Nb(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Fb(e,t){if(!Nb(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 Qi(){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 o=(0,Ds.parse)(n,Ds.STR|Ds.OBJ),s=Fb(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function xg(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Xi(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=to.get(e.component);if(!s)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=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function vg(){let e=Qi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function wg(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 Yi(e){let t=wg(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 Zi(e){let t=wg(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 _b=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function el(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=_b}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,g.appendChild(v);let y=document.createElement("p");y.className="persona-feedback-subtitle",y.textContent=o,g.appendChild(y),f.appendChild(g);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let T=1;T<=5;T++){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",`${T} star${T>1?"s":""}: ${l[T-1]}`),W.title=l[T-1],W.dataset.rating=String(T),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
- `,k.addEventListener("click",()=>{u=S,T.forEach(($,O)=>{let H=O<S;$.classList.toggle("selected",H),$.setAttribute("aria-checked",O===S-1?"true":"false")})}),T.push(k),w.appendChild(k)}f.appendChild(w);let N=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",N=document.createElement("textarea"),N.className="persona-feedback-comment",N.placeholder=s,N.rows=3,N.setAttribute("aria-label","Additional comments"),S.appendChild(N),f.appendChild(S)}let M=document.createElement("div");M.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 W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(u===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let S=(N==null?void 0:N.value.trim())||void 0;await t(u,S),p.remove()}catch(S){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),M.appendChild(I),M.appendChild(W),f.appendChild(M),p.appendChild(f),p}function Ji(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=o,v.appendChild(w),m.appendChild(v);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let N=document.createElement("div");N.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=l;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=p,N.appendChild(M),N.appendChild(I);let W=document.createElement("div");W.className="persona-feedback-numbers";let S=[];for(let U=0;U<=10;U++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-number-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`Rating ${U} out of 10`),J.textContent=String(U),J.dataset.rating=String(U),U<=6?J.classList.add("persona-feedback-detractor"):U<=8?J.classList.add("persona-feedback-passive"):J.classList.add("persona-feedback-promoter"),J.addEventListener("click",()=>{f=U,S.forEach((ce,Me)=>{ce.classList.toggle("selected",Me===U),ce.setAttribute("aria-checked",Me===U?"true":"false")})}),S.push(J),W.appendChild(J)}T.appendChild(N),T.appendChild(W),m.appendChild(T);let k=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),U.appendChild(k),m.appendChild(U)}let $=document.createElement("div");$.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=i,O.addEventListener("click",()=>{n==null||n(),u.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(f===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let U=(k==null?void 0:k.value.trim())||void 0;await t(f,U),u.remove()}catch(U){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),$.appendChild(O),$.appendChild(H),m.appendChild($),u.appendChild(m),u}var Hs="persona-chat-history",Eb=30*1e3,Mb={"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 kb(e){var r,o,s;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=(o=Mb[i.type])!=null?o:"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((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Gi(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 Lb(e){var t,n,r,o,s,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:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.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 Pb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Kl=e=>!e||typeof e!="object"?{}:{...e},dg=e=>e.map(t=>({...t,streaming:!1})),pg=(e,t,n)=>{let r=e!=null&&e.markdown?jo(e.markdown):null,o=hs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(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."),s=>{var l,p,u;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(u=i!=null?i:s.text)!=null?u:""}):r?d=r(a):d=Uo(a),o?o(d):d}};function ug(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",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=Ce(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=h("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var Xi=(e,t,n)=>{var Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Oc,Fc,$c,_c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,xd,vd,wd;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=pi(t),o=Aa.getForInstance(r.plugins);r.components&&eo.registerAll(r.components);let s=sg(),i=r.persistState===!1?null:(Ec=r.storageAdapter)!=null?Ec:ji(),d={},l=null,p=!1,u=c=>{if(r.onStateLoaded)try{let g=r.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:y}=g;return y&&(p=!0),b}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let b=g!=null?g:{messages:[],metadata:{}};return u(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=u(g);b.metadata&&(d=Kl(b.metadata)),(Mc=b.messages)!=null&&Mc.length&&(r={...r,initialMessages:b.messages}),(kc=b.artifacts)!=null&&kc.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Lc=b.selectedArtifactId)!=null?Lc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=u({messages:[],metadata:{}});(Pc=c.messages)!=null&&Pc.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var b;d=(b=c({...d}))!=null?b:{},ls()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Sa],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ts.message,ts.messageAndClick],w=Ta({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let T=(Wc=(Ic=r.launcher)==null?void 0:Ic.enabled)!=null?Wc:!0,N=(Hc=(Rc=r.launcher)==null?void 0:Rc.autoExpand)!=null?Hc:!1,M=(Bc=r.autoFocusInput)!=null?Bc:!1,I=N,W=T,S=(Nc=(Dc=r.layout)==null?void 0:Dc.header)==null?void 0:Nc.layout,k=!1,$=()=>Co(r),O=()=>T||$(),H=$()?!1:T?N:!0,U=!1,J=null,ce=()=>{U=!0,J&&clearTimeout(J),J=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},Me=pg(r,w,ce),ze=(Fc=(Oc=r.features)==null?void 0:Oc.showReasoning)!=null?Fc:!0,Ae=(_c=($c=r.features)==null?void 0:$c.showToolCalls)!=null?_c:!0,We=(Uc=(jc=r.features)==null?void 0:jc.showEventStreamToggle)!=null?Uc:!1,be=(zc=(qc=r.features)==null?void 0:qc.scrollToBottom)!=null?zc:{},ke=(Kc=(Vc=r.features)==null?void 0:Vc.scrollBehavior)!=null?Kc:{},de=`${(Gc=typeof r.persistState=="object"?(Jc=r.persistState)==null?void 0:Jc.keyPrefix:void 0)!=null?Gc:"persona-"}event-stream`,Q=We?new wa(de):null,re=(Yc=(Qc=(Xc=r.features)==null?void 0:Xc.eventStream)==null?void 0:Qc.maxEvents)!=null?Yc:2e3,le=We?new va(re,Q):null,ge=We?new Ca:null,V=null,se=!1,He=null,Z=0;Q==null||Q.open().then(()=>le==null?void 0:le.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ee={onCopy:c=>{var g,b;s.emit("message:copy",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(b=(g=r.messageActions)==null?void 0:g.onCopy)==null||b.call(g,c)},onFeedback:c=>{var g,b;s.emit("message:feedback",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.messageId,c.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(b=(g=r.messageActions)==null?void 0:g.onFeedback)==null||b.call(g,c)}},ae=(Zc=r.statusIndicator)!=null?Zc:{},Se=c=>{var g,b,y,E;return c==="idle"?(g=ae.idleText)!=null?g:En.idle:c==="connecting"?(b=ae.connectingText)!=null?b:En.connecting:c==="connected"?(y=ae.connectedText)!=null?y:En.connected:c==="error"?(E=ae.errorText)!=null?E:En.error:En[c]};function Ze(c,g,b,y){if(y==="idle"&&b.idleLink){c.textContent="";let E=document.createElement("a");E.href=b.idleLink,E.target="_blank",E.rel="noopener noreferrer",E.textContent=g,E.style.color="inherit",E.style.textDecoration="none",c.appendChild(E)}else c.textContent=g}let{wrapper:ve,panel:fe,pillRoot:Je}=wm(r),De=Cm(r,O()),{container:z,body:ue,messagesWrapper:rt,suggestions:kt,textarea:te,sendButton:Ve,sendButtonWrapper:Bn,composerForm:Bt,statusText:ln,introTitle:nr,introSubtitle:Tr,closeButton:R,iconHolder:pe,headerTitle:Ne,headerSubtitle:Ge,header:$e,footer:je,actionsRow:st,leftActions:It,rightActions:Jt}=De,Yt=De.setSendButtonMode,K=De.micButton,vt=De.micButtonWrapper,it=De.attachmentButton,we=De.attachmentButtonWrapper,ie=De.attachmentInput,nt=De.attachmentPreviewsContainer;z.classList.add("persona-relative"),ue.classList.add("persona-relative");let Zt=12,Gt=()=>{var c;return(c=be.label)!=null?c:""},kn=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},xn=()=>be.enabled!==!1,ft=()=>{var c;return(c=ke.mode)!=null?c:"follow"},Lt=()=>{var c;return(c=ke.anchorTopOffset)!=null?c:16},et=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");et.type="button",et.style.display="none",et.setAttribute("data-persona-scroll-to-bottom","true");let zt=h("span","persona-flex persona-items-center"),cn=h("span",""),wn=h("span","");wn.setAttribute("data-persona-scroll-to-bottom-count",""),wn.style.display="none",et.append(zt,cn,wn),z.appendChild(et);let Cn=h("div","persona-stream-anchor-spacer");Cn.setAttribute("aria-hidden","true"),Cn.setAttribute("data-persona-anchor-spacer",""),Cn.style.flexShrink="0",Cn.style.pointerEvents="none",Cn.style.height="0px",ue.appendChild(Cn);let yn=()=>{let g=je.style.display==="none"?0:je.offsetHeight;et.style.bottom=`${g+Zt}px`};yn();let Er=()=>{let c=!!Gt();et.setAttribute("aria-label",Gt()||"Jump to latest"),et.title=Gt(),et.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),zt.innerHTML="";let g=Ce(kn(),"14px","currentColor",2);g?(zt.appendChild(g),zt.style.display=""):zt.style.display="none",cn.textContent=Gt(),cn.style.display=c?"":"none"};Er();let St=null,_n=null,jn=o.find(c=>c.renderHeader);if(jn!=null&&jn.renderHeader){let c=jn.renderHeader({config:r,defaultRenderer:()=>{let g=Qr({config:r,showClose:O()});return Qo(z,g,r),g.header},onClose:()=>Nt(!1,"user")});if(c){let g=z.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),$e=c)}}let Nr=()=>{var g,b,y,E;if(!le)return;if(se=!0,!V&&le&&(V=Gm({buffer:le,getFullHistory:()=>le.getAllFromStore(),onClose:()=>hr(),config:r,plugins:o,getThroughput:()=>{var D;return(D=ge==null?void 0:ge.getMetric())!=null?D:{status:"idle"}}})),V&&(ue.style.display="none",(g=je.parentNode)==null||g.insertBefore(V.element,je),V.update()),wt){wt.style.boxShadow=`inset 0 0 0 1.5px ${Hn.actionIconColor}`;let D=(E=(y=(b=r.features)==null?void 0:b.eventStream)==null?void 0:y.classNames)==null?void 0:E.toggleButtonActive;D&&D.split(/\s+/).forEach(F=>F&&wt.classList.add(F))}let c=()=>{if(!se)return;let D=Date.now();D-Z>=200&&(V==null||V.update(),Z=D),He=requestAnimationFrame(c)};Z=0,He=requestAnimationFrame(c),On(),s.emit("eventStream:opened",{timestamp:Date.now()})},hr=()=>{var c,g,b;if(se){if(se=!1,V&&V.element.remove(),ue.style.display="",wt){wt.style.boxShadow="";let y=(b=(g=(c=r.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:b.toggleButtonActive;y&&y.split(/\s+/).forEach(E=>E&&wt.classList.remove(E))}He!==null&&(cancelAnimationFrame(He),He=null),On(),s.emit("eventStream:closed",{timestamp:Date.now()})}},wt=null;if(We){let c=(td=(ed=r.features)==null?void 0:ed.eventStream)==null?void 0:td.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");wt=h("button",g),wt.style.width="28px",wt.style.height="28px",wt.style.color=Hn.actionIconColor,wt.type="button",wt.setAttribute("aria-label","Event Stream"),wt.title="Event Stream";let b=Ce("activity","18px","currentColor",1.5);b&&wt.appendChild(b);let y=De.clearChatButtonWrapper,E=De.closeButtonWrapper,D=y||E;D&&D.parentNode===$e?$e.insertBefore(wt,D):$e.appendChild(wt),wt.addEventListener("click",()=>{se?hr():Nr()})}let Lo=c=>{var y,E,D;let g=r.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let F=c.querySelector("[data-persona-composer-form]");F!=null&&F.parentNode?F.parentNode.insertBefore(b,F):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let F=h("input");F.type="file",F.accept=((y=g.allowedTypes)!=null?y:Gr).join(","),F.multiple=((E=g.maxFiles)!=null?E:4)>1,F.style.display="none",F.setAttribute("aria-label",(D=g.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(F)}},Mr=o.find(c=>c.renderComposer);if(Mr!=null&&Mr.renderComposer){let c=r.composer,g=Mr.renderComposer({config:r,defaultRenderer:()=>Ts({config:r}).footer,onSubmit:b=>{var F;if(!_||_.isStreaming())return;let y=b.trim(),E=(F=St==null?void 0:St.hasAttachments())!=null?F:!1;if(!y&&!E)return;A();let D;E&&(D=[],D.push(...St.getContentParts()),y&&D.push(oa(y))),_.sendMessage(y,{contentParts:D}),E&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ie==null||ie.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:b=>{r.composer={...r.composer,selectedModelId:b},r.agent&&(r.agent={...r.agent,model:b})},onVoiceToggle:((nd=r.voiceRecognition)==null?void 0:nd.enabled)===!0?()=>{_n==null||_n()}:void 0});g&&(je.replaceWith(g),je=g)}let Po=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),E=c.querySelector("[data-persona-composer-mic]"),D=c.querySelector("[data-persona-composer-status]");g&&(Bt=g),b&&(te=b),y&&(Ve=y),E&&(K=E,vt=E.parentElement),D&&(ln=D);let F=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(kt=F);let q=c.querySelector(".persona-attachment-button");q&&(it=q,we=q.parentElement),ie=c.querySelector('input[type="file"]'),nt=c.querySelector(".persona-attachment-previews");let B=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&(st=B)};Lo(je),Po(je);let Dn=(id=(rd=r.layout)==null?void 0:rd.contentMaxWidth)!=null?id:$()?(ad=(sd=(od=r.launcher)==null?void 0:od.composerBar)==null?void 0:sd.contentMaxWidth)!=null?ad:"720px":void 0;if(Dn&&(rt.style.maxWidth=Dn,rt.style.marginLeft="auto",rt.style.marginRight="auto",rt.style.width="100%"),Dn&&Bt&&!$()&&(Bt.style.maxWidth=Dn,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),Dn&&kt&&!$()&&(kt.style.maxWidth=Dn,kt.style.marginLeft="auto",kt.style.marginRight="auto"),Dn&&nt&&!$()&&(nt.style.maxWidth=Dn,nt.style.marginLeft="auto",nt.style.marginRight="auto"),(ld=r.attachments)!=null&&ld.enabled&&ie&&nt){St=Go.fromConfig(r.attachments),St.setPreviewsContainer(nt),ie.addEventListener("change",b=>{let y=b.target;St==null||St.handleFileSelect(y.files),y.value=""});let c=r.attachments.dropOverlay,g=ug(c);z.appendChild(g)}(()=>{var y,E;let c=(E=(y=r.layout)==null?void 0:y.slots)!=null?E:{},g=D=>{switch(D){case"body-top":return z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return rt;case"footer-top":return kt;case"composer":return Bt;case"footer-bottom":return ln;default:return null}},b=(D,F)=>{var q;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")$e.insertBefore(F,$e.firstChild);else if(D==="header-right")$e.appendChild(F);else{let B=$e.querySelector(".persona-flex-col");B?(q=B.parentNode)==null||q.insertBefore(F,B.nextSibling):$e.appendChild(F)}break;case"body-top":{let B=ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(F):ue.insertBefore(F,ue.firstChild);break}case"body-bottom":ue.appendChild(F);break;case"footer-top":kt.replaceWith(F);break;case"footer-bottom":ln.replaceWith(F);break;default:break}};for(let[D,F]of Object.entries(c))if(F)try{let q=F({config:r,defaultContent:()=>g(D)});q&&b(D,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,q)}})();let no=c=>{var F,q;let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let y=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let E=y.getAttribute("data-message-id");if(!E)return;let D=b.getAttribute("data-bubble-type");if(D==="reasoning")Ms.has(E)?Ms.delete(E):Ms.add(E),Em(E,y);else if(D==="tool")ks.has(E)?ks.delete(E):ks.add(E),Mm(E,y,r);else if(D==="approval"){let B=r.approval!==!1?r.approval:void 0,xe=((F=B==null?void 0:B.detailsDisplay)!=null?F:"collapsed")==="expanded",me=(q=Ni.get(E))!=null?q:xe;Ni.set(E,!me),qm(E,y,r)}_r.delete(E)};rt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),no(c))}),rt.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),no(c))});let Or=new Map;rt.addEventListener("click",c=>{var F;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest("[data-actions-for]");if(!y)return;let E=y.getAttribute("data-actions-for");if(!E)return;let D=b.getAttribute("data-action");if(D==="copy"){let B=_.getMessages().find(xe=>xe.id===E);if(B&&ee.onCopy){let xe=B.content||"";navigator.clipboard.writeText(xe).then(()=>{b.classList.add("persona-message-action-success");let me=Ce("check",14,"currentColor",2);me&&(b.innerHTML="",b.appendChild(me)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let ne=Ce("copy",14,"currentColor",2);ne&&(b.innerHTML="",b.appendChild(ne))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),ee.onCopy(B)}}else if(D==="upvote"||D==="downvote"){let B=((F=Or.get(E))!=null?F:null)===D,xe=D==="upvote"?"thumbs-up":"thumbs-down";if(B){Or.delete(E),b.classList.remove("persona-message-action-active");let me=Ce(xe,14,"currentColor",2);me&&(b.innerHTML="",b.appendChild(me))}else{let me=D==="upvote"?"downvote":"upvote",ne=y.querySelector(`[data-action="${me}"]`);if(ne){ne.classList.remove("persona-message-action-active");let Ke=Ce(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ke&&(ne.innerHTML="",ne.appendChild(Ke))}Or.set(E,D),b.classList.add("persona-message-action-active");let Ee=Ce(xe,14,"currentColor",2);Ee&&(Ee.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Ee)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Te=_.getMessages().find(ot=>ot.id===E);Te&&ee.onFeedback&&ee.onFeedback({type:D,messageId:Te.id,message:Te})}}}),rt.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest(".persona-approval-bubble");if(!y)return;let E=y.getAttribute("data-message-id");if(!E)return;let D=b.getAttribute("data-approval-action");if(!D)return;let F=D==="approve"?"approved":"denied",B=_.getMessages().find(me=>me.id===E);if(!(B!=null&&B.approval))return;let xe=y.querySelector("[data-approval-buttons]");xe&&xe.querySelectorAll("button").forEach(ne=>{ne.disabled=!0,ne.style.opacity="0.5",ne.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?_.resolveWebMcpApproval(E,F):_.resolveApproval(B.approval,F)});let Tt=null,Un=null,qn={artifacts:[],selectedId:null},Ln=!1,Pt={current:null};rt.addEventListener("click",c=>{var ne,Ee,_e,Te,ot;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.getAttribute("data-download-artifact");if(!y||((_e=(Ee=(ne=r.features)==null?void 0:ne.artifacts)==null?void 0:Ee.onArtifactAction)==null?void 0:_e.call(Ee,{type:"download",artifactId:y}))===!0)return;let D=_.getArtifactById(y),F=D==null?void 0:D.markdown,q=(D==null?void 0:D.title)||"artifact";if(!F){let Ke=b.closest("[data-open-artifact]"),dt=Ke==null?void 0:Ke.closest("[data-message-id]"),pt=dt==null?void 0:dt.getAttribute("data-message-id");if(pt){let Le=_.getMessages().find(qe=>qe.id===pt);if(Le!=null&&Le.rawContent)try{let qe=JSON.parse(Le.rawContent);F=(Te=qe==null?void 0:qe.props)==null?void 0:Te.markdown,q=((ot=qe==null?void 0:qe.props)==null?void 0:ot.title)||q}catch{}}}if(!F)return;let B=new Blob([F],{type:"text/markdown"}),xe=URL.createObjectURL(B),me=document.createElement("a");me.href=xe,me.download=`${q}.md`,me.click(),URL.revokeObjectURL(xe)}),rt.addEventListener("click",c=>{var D,F,q;let b=c.target.closest("[data-open-artifact]");if(!b)return;let y=b.getAttribute("data-open-artifact");!y||((q=(F=(D=r.features)==null?void 0:D.artifacts)==null?void 0:F.onArtifactAction)==null?void 0:q.call(F,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Ln=!1,_.selectArtifact(y),Kn())}),rt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let rr=De.composerOverlay,or=(c,g,b)=>{var q,B,xe,me;let y=g.trim();if(!y||!Pt.current)return;let E=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",D=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:E,answer:y,answers:b.structured,values:(B=b.values)!=null?B:b.source==="multi"?y.split(", "):[y],isFreeText:D,source:b.source},bubbles:!0,composed:!0})),Eo(rr,E);let F=Pt.current.getMessages().find(ne=>{var Ee;return((Ee=ne.toolCall)==null?void 0:Ee.id)===E});(xe=F==null?void 0:F.agentMetadata)!=null&&xe.awaitingLocalTool?Pt.current.resolveAskUserQuestion(F,(me=b.structured)!=null?me:y):Pt.current.sendMessage(y)},zn=c=>{var E;let g=Pt.current;if(!g)return;let b=(E=c.getAttribute("data-tool-call-id"))!=null?E:"",y=g.getMessages().find(D=>{var F;return((F=D.toolCall)==null?void 0:F.id)===b});y&&g.persistAskUserQuestionProgress(y,{answers:Bi(c,y),currentIndex:gr(c)})},ro=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Fr=c=>{var E,D,F;if(((D=(E=r.features)==null?void 0:E.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let g=gr(c),b=Ps(c);if(g>=b-1)return;let y=(F=Pt.current)==null?void 0:F.getMessages().find(q=>{var B;return((B=q.toolCall)==null?void 0:B.id)===c.getAttribute("data-tool-call-id")});y&&(Di(c,y,r,g+1),zn(c))};rr.addEventListener("click",c=>{var D,F,q,B,xe,me,ne,Ee,_e,Te,ot,Ke,dt,pt;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;let E=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),E==="dismiss"){let Ie=(D=y.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Eo(rr,Ie);let Le=(F=Pt.current)==null?void 0:F.getMessages().find(qe=>{var Qe;return((Qe=qe.toolCall)==null?void 0:Qe.id)===Ie});(q=Le==null?void 0:Le.agentMetadata)!=null&&q.awaitingLocalTool&&((B=Pt.current)==null||B.markAskUserQuestionResolved(Le),(xe=Pt.current)==null||xe.resolveAskUserQuestion(Le,"(dismissed)"));return}if(E==="pick"){let Ie=b.getAttribute("data-option-label");if(!Ie)return;let Le=y.getAttribute("data-multi-select")==="true",qe=To(y);if(qe&&Le){let Qe=Zo(y)[gr(y)],Ct=new Set(Array.isArray(Qe)?Qe:[]);Ct.has(Ie)?Ct.delete(Ie):Ct.add(Ie),Mo(y,Array.from(Ct)),zn(y);return}if(qe){Mo(y,Ie),zn(y),Fr(y);return}if(Le){let Qe=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",Qe?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!Qe);let Ct=y.querySelector('[data-ask-user-action="submit-multi"]');Ct&&(Ct.disabled=$l(y).length===0);return}or(y,Ie,{source:"pick",values:[Ie]});return}if(E==="submit-multi"){let Ie=$l(y);if(Ie.length===0)return;or(y,Ie.join(", "),{source:"multi",values:Ie});return}if(E==="open-free-text"){let Ie=y.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Le=Ie.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(E==="focus-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(E==="submit-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]'),Le=(me=Ie==null?void 0:Ie.value)!=null?me:"";if(!Le.trim())return;if(To(y)){Mo(y,Le.trim()),zn(y),Fr(y);return}or(y,Le,{source:"free-text"});return}if(E==="next"||E==="back"){if(!Pt.current)return;let Ie=(ne=y.getAttribute("data-tool-call-id"))!=null?ne:"",Le=Pt.current.getMessages().find(Be=>{var Oe;return((Oe=Be.toolCall)==null?void 0:Oe.id)===Ie});if(!Le)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(_e=(Ee=qe==null?void 0:qe.value)==null?void 0:Ee.trim())!=null?_e:"";if(Qe){let Be=Zo(y)[gr(y)];(typeof Be!="string"||Be!==Qe)&&Mo(y,Qe)}let Ct=E==="next"?1:-1,P=gr(y)+Ct;Di(y,Le,r,P),zn(y);return}if(E==="submit-all"){if(!Pt.current)return;let Ie=(Te=y.getAttribute("data-tool-call-id"))!=null?Te:"",Le=Pt.current.getMessages().find(Be=>{var Oe;return((Oe=Be.toolCall)==null?void 0:Oe.id)===Ie});if(!Le)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(Ke=(ot=qe==null?void 0:qe.value)==null?void 0:ot.trim())!=null?Ke:"";Qe&&Mo(y,Qe);let Ct=Bi(y,Le);Pt.current.persistAskUserQuestionProgress(Le,{answers:Ct,currentIndex:gr(y)});let P=ro(Ct);or(y,P||"(submitted)",{source:"submit-all",structured:Ct});return}if(E==="skip"){if(!Pt.current)return;let Ie=(dt=y.getAttribute("data-tool-call-id"))!=null?dt:"",Le=Pt.current.getMessages().find(Oe=>{var he;return((he=Oe.toolCall)==null?void 0:he.id)===Ie});if(!Le)return;let qe=To(y),Qe=gr(y),Ct=Ps(y),P=Qe>=Ct-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Eo(rr,Ie),(pt=Le.agentMetadata)!=null&&pt.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(Le),Pt.current.resolveAskUserQuestion(Le,"(dismissed)"));return}Mo(y,"");let Be=y.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),P){let Oe=Bi(y,Le),he=ro(Oe);or(y,he||"(skipped)",{source:"submit-all",structured:Oe});return}Di(y,Le,r,Qe+1),zn(y);return}}),rr.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let b=c.target;if(!((D=b.matches)!=null&&D.call(b,'[data-ask-free-text-input="true"]')))return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let E=b.value;if(E.trim()){if(To(y)){Mo(y,E.trim()),zn(y),Fr(y);return}or(y,E,{source:"free-text"})}});let oo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let b=rr.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),D=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",oo);let Vn=null,Dt=null,Pn=null,sr=null,so=()=>{};function $r(){sr==null||sr(),sr=null}let ao=()=>{var F;if(!Vn||!Dt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),b=((F=e.ownerDocument.defaultView)!=null?F:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||b){Dt.style.removeProperty("position"),Dt.style.removeProperty("left"),Dt.style.removeProperty("top"),Dt.style.removeProperty("bottom"),Dt.style.removeProperty("width"),Dt.style.removeProperty("z-index");return}let y=Vn.firstElementChild;if(!y||y===Dt)return;let E=10;Dt.style.position="absolute",Dt.style.top="0",Dt.style.bottom="0",Dt.style.width=`${E}px`,Dt.style.zIndex="5";let D=y.offsetWidth-E/2;Dt.style.left=`${Math.max(0,D)}px`},kr=()=>{},Kn=()=>{var b,y,E,D,F;if(!Tt||!fr(r))return;$i(e,r),_i(e,r),kr();let c=(D=(E=(y=(b=r.features)==null?void 0:b.artifacts)==null?void 0:y.layout)==null?void 0:E.narrowHostMaxWidth)!=null?D:520,g=fe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),Tt.update(qn),Ln?(Tt.setMobileOpen(!1),Tt.element.classList.add("persona-hidden"),(F=Tt.backdrop)==null||F.classList.add("persona-hidden")):qn.artifacts.length>0&&(Tt.element.classList.remove("persona-hidden"),Tt.setMobileOpen(!0)),so()};if(fr(r)){fe.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(z),Tt=Ym(r,{onSelect:b=>{var y;return(y=Pt.current)==null?void 0:y.selectArtifact(b)},onDismiss:()=>{Ln=!0,Kn()}}),Tt.element.classList.add("persona-hidden"),Vn=g,g.appendChild(c),g.appendChild(Tt.element),Tt.backdrop&&fe.appendChild(Tt.backdrop),fe.appendChild(g),so=()=>{var y,E,D,F;if(!Vn||!Tt)return;if(!(((D=(E=(y=r.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:D.resizable)===!0)){Pn==null||Pn(),Pn=null,$r(),Dt&&(Dt.remove(),Dt=null),Tt.element.style.removeProperty("width"),Tt.element.style.removeProperty("maxWidth");return}if(!Dt){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 B=e.ownerDocument,xe=(F=B.defaultView)!=null?F:window,me=ne=>{var dt,pt;if(!Tt||ne.button!==0||e.classList.contains("persona-artifact-narrow-host")||xe.innerWidth<=640)return;ne.preventDefault(),$r();let Ee=ne.clientX,_e=Tt.element.getBoundingClientRect().width,Te=(pt=(dt=r.features)==null?void 0:dt.artifacts)==null?void 0:pt.layout,ot=Ie=>{let Le=Vn.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Qe=qe?0:ng(Vn,xe),Ct=qe?0:q.getBoundingClientRect().width||6,P=_e-(Ie.clientX-Ee),Be=rg(P,Le,Qe,Ct,Te==null?void 0:Te.resizableMinWidth,Te==null?void 0:Te.resizableMaxWidth);Tt.element.style.width=`${Be}px`,Tt.element.style.maxWidth="none",ao()},Ke=()=>{B.removeEventListener("pointermove",ot),B.removeEventListener("pointerup",Ke),B.removeEventListener("pointercancel",Ke),sr=null;try{q.releasePointerCapture(ne.pointerId)}catch{}};sr=Ke,B.addEventListener("pointermove",ot),B.addEventListener("pointerup",Ke),B.addEventListener("pointercancel",Ke);try{q.setPointerCapture(ne.pointerId)}catch{}};q.addEventListener("pointerdown",me),Dt=q,Vn.insertBefore(q,Tt.element),Pn=()=>{q.removeEventListener("pointerdown",me)}}if(Dt){let q=qn.artifacts.length>0&&!Ln;Dt.classList.toggle("persona-hidden",!q),ao()}},kr=()=>{var xe,me,ne,Ee,_e,Te,ot,Ke,dt,pt,Ie,Le,qe,Qe;if(!T||!Tt||((me=(xe=r.launcher)==null?void 0:xe.sidebarMode)!=null?me:!1)||gn(r)&&mr(r).reveal==="emerge")return;let y=(ne=e.ownerDocument.defaultView)!=null?ne:window,E=(_e=(Ee=r.launcher)==null?void 0:Ee.mobileFullscreen)!=null?_e:!0,D=(ot=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?ot:640;if(E&&y.innerWidth<=D||!tg(r,T))return;let F=(pt=(dt=(Ke=r.launcher)==null?void 0:Ke.width)!=null?dt:r.launcherWidth)!=null?pt:er,q=(Qe=(qe=(Le=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:Le.layout)==null?void 0:qe.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";qn.artifacts.length>0&&!Ln?(fe.style.width=q,fe.style.maxWidth=q):(fe.style.width=F,fe.style.maxWidth=F)},typeof ResizeObserver!="undefined"&&(Un=new ResizeObserver(()=>{Kn()}),Un.observe(fe))}else fe.appendChild(z),$()&&Je&&(De.peekBanner&&Je.appendChild(De.peekBanner),Je.appendChild(je));e.appendChild(ve),Je&&e.appendChild(Je);let br=()=>{var Be,Oe,he,_t,Ot,Xt,At,Vt,Qn,sn,Ye,Wt,pn,pr,Yn,Bo,Do,gs,fs,Qt,No,ho,bo,Vr,at,vn,In,an;if($()){fe.style.width="100%",fe.style.maxWidth="100%";let ut=(Oe=(Be=r.launcher)==null?void 0:Be.composerBar)!=null?Oe:{},yt=ve.dataset.state==="expanded",mt=(he=ut.expandedSize)!=null?he:"anchored";if(!(yt&&mt!=="fullscreen")){z.style.background="",z.style.border="",z.style.borderRadius="",z.style.overflow="",z.style.boxShadow="";return}let un=(Ot=(_t=r.theme)==null?void 0:_t.components)==null?void 0:Ot.panel,Hr=As(r),mn=(Fo,qa)=>{var Ys;return Fo==null||Fo===""?qa:(Ys=ws(Hr,Fo))!=null?Ys:Fo},Wn="1px solid var(--persona-border)",ur="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Oo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";z.style.background="var(--persona-surface, #ffffff)",z.style.border=mn(un==null?void 0:un.border,Wn),z.style.borderRadius=mn(un==null?void 0:un.borderRadius,Oo),z.style.boxShadow=mn(un==null?void 0:un.shadow,ur),z.style.overflow="hidden";return}let c=gn(r),g=(At=(Xt=r.launcher)==null?void 0:Xt.sidebarMode)!=null?At:!1,b=c||g||((Qn=(Vt=r.launcher)==null?void 0:Vt.fullHeight)!=null?Qn:!1),y=((sn=r.launcher)==null?void 0:sn.enabled)===!1,E=(Wt=(Ye=r.theme)==null?void 0:Ye.components)==null?void 0:Wt.panel,D=As(r),F=(ut,yt)=>{var mt;return ut==null||ut===""?yt:(mt=ws(D,ut))!=null?mt:ut},q=(pn=e.ownerDocument.defaultView)!=null?pn:window,B=(Yn=(pr=r.launcher)==null?void 0:pr.mobileFullscreen)!=null?Yn:!0,xe=(Do=(Bo=r.launcher)==null?void 0:Bo.mobileBreakpoint)!=null?Do:640,me=q.innerWidth<=xe,ne=B&&me&&T,Ee=(fs=(gs=r.launcher)==null?void 0:gs.position)!=null?fs:"bottom-left",_e=Ee==="bottom-left"||Ee==="top-left",Te=(No=(Qt=r.launcher)==null?void 0:Qt.zIndex)!=null?No:Mn,ot=g||ne?"none":"1px solid var(--persona-border)",Ke=ne?"none":g?_e?"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&&!ne&&(Ke="none",ot="none");let dt=g||ne?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",pt=F(E==null?void 0:E.border,ot),Ie=F(E==null?void 0:E.shadow,Ke),Le=F(E==null?void 0:E.borderRadius,dt),qe=ue.scrollTop;e.style.cssText="",ve.style.cssText="",fe.style.cssText="",z.style.cssText="",ue.style.cssText="",je.style.cssText="";let Qe=()=>{var yt;if(qe<=0)return;((yt=ue.ownerDocument.defaultView)!=null?yt:window).requestAnimationFrame(()=>{if(ue.scrollTop===qe)return;let mt=ue.scrollHeight-ue.clientHeight;mt<=0||(ue.scrollTop=Math.min(qe,mt))})};if(ne){ve.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"),ve.style.cssText=`
30
+ `,W.addEventListener("click",()=>{u=T,S.forEach((_,F)=>{let M=F<T;_.classList.toggle("selected",M),_.setAttribute("aria-checked",F===T-1?"true":"false")})}),S.push(W),w.appendChild(W)}f.appendChild(w);let O=null;if(d){let T=document.createElement("div");T.className="persona-feedback-comment-container",O=document.createElement("textarea"),O.className="persona-feedback-comment",O.placeholder=s,O.rows=3,O.setAttribute("aria-label","Additional comments"),T.appendChild(O),f.appendChild(T)}let k=document.createElement("div");k.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(u===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let T=(O==null?void 0:O.value.trim())||void 0;await t(u,T),p.remove()}catch(T){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",T)}}),k.appendChild(I),k.appendChild(R),f.appendChild(k),p.appendChild(f),p}function tl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=r,v.appendChild(y);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=o,v.appendChild(w),g.appendChild(v);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let O=document.createElement("div");O.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=p,O.appendChild(k),O.appendChild(I);let R=document.createElement("div");R.className="persona-feedback-numbers";let T=[];for(let j=0;j<=10;j++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${j} out of 10`),z.textContent=String(j),z.dataset.rating=String(j),j<=6?z.classList.add("persona-feedback-detractor"):j<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{f=j,T.forEach((oe,ke)=>{oe.classList.toggle("selected",ke===j),oe.setAttribute("aria-checked",ke===j?"true":"false")})}),T.push(z),R.appendChild(z)}S.appendChild(O),S.appendChild(R),g.appendChild(S);let W=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),j.appendChild(W),g.appendChild(j)}let _=document.createElement("div");_.className="persona-feedback-actions";let F=document.createElement("button");F.type="button",F.className="persona-feedback-btn persona-feedback-btn-skip",F.textContent=i,F.addEventListener("click",()=>{n==null||n(),u.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=a,M.addEventListener("click",async()=>{if(f===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}M.disabled=!0,M.textContent="Submitting...";try{let j=(W==null?void 0:W.value.trim())||void 0;await t(f,j),u.remove()}catch(j){M.disabled=!1,M.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),_.appendChild(F),_.appendChild(M),g.appendChild(_),u.appendChild(g),u}var Os="persona-chat-history",$b=30*1e3,Ub={"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 jb(e){var r,o,s;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=(o=Ub[i.type])!=null?o:"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((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function nl(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 qb(e){var t,n,r,o,s,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:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.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 zb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var rc=e=>!e||typeof e!="object"?{}:{...e},Cg=e=>e.map(t=>({...t,streaming:!1})),Ag=(e,t,n)=>{let r=e!=null&&e.markdown?jo(e.markdown):null,o=xs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(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."),s=>{var l,p,u;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(u=i!=null?i:s.text)!=null?u:""}):r?d=r(a):d=qo(a),o?o(d):d}};function Sg(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",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=Ce(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=h("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var rl=(e,t,n)=>{var Dc,Oc,Nc,Fc,_c,$c,Uc,jc,qc,zc,Vc,Kc,Gc,Jc,Qc,Xc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id;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=Ci(t),o=Pa.getForInstance(r.plugins);r.components&&to.registerAll(r.components);let s=bg(),i=r.persistState===!1?null:(Dc=r.storageAdapter)!=null?Dc:Ji(),d={},l=null,p=!1,u=c=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:b,open:x}=m;return x&&(p=!0),b}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(m=>{let b=m!=null?m:{messages:[],metadata:{}};return u(b)});else{let m=c!=null?c:{messages:[],metadata:{}},b=u(m);b.metadata&&(d=rc(b.metadata)),(Oc=b.messages)!=null&&Oc.length&&(r={...r,initialMessages:b.messages}),(Nc=b.artifacts)!=null&&Nc.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Fc=b.selectedArtifactId)!=null?Fc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=u({messages:[],metadata:{}});(_c=c.messages)!=null&&_c.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,g=c=>{var b;d=(b=c({...d}))!=null?b:{},ps()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ia],y=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[rs.message,rs.messageAndClick],w=Ra({parsers:v,handlers:y,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let S=(Uc=($c=r.launcher)==null?void 0:$c.enabled)!=null?Uc:!0,O=(qc=(jc=r.launcher)==null?void 0:jc.autoExpand)!=null?qc:!1,k=(zc=r.autoFocusInput)!=null?zc:!1,I=O,R=S,T=(Kc=(Vc=r.layout)==null?void 0:Vc.header)==null?void 0:Kc.layout,W=!1,_=()=>Eo(r),F=()=>S||_(),M=_()?!1:S?O:!0,j=!1,z=null,oe=()=>{j=!0,z&&clearTimeout(z),z=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},ke=Ag(r,w,oe),ze=(Jc=(Gc=r.features)==null?void 0:Gc.showReasoning)!=null?Jc:!0,Ae=(Xc=(Qc=r.features)==null?void 0:Qc.showToolCalls)!=null?Xc:!0,Re=(Zc=(Yc=r.features)==null?void 0:Yc.showEventStreamToggle)!=null?Zc:!1,be=(td=(ed=r.features)==null?void 0:ed.scrollToBottom)!=null?td:{},Le=(rd=(nd=r.features)==null?void 0:nd.scrollBehavior)!=null?rd:{},de=`${(sd=typeof r.persistState=="object"?(od=r.persistState)==null?void 0:od.keyPrefix:void 0)!=null?sd:"persona-"}event-stream`,X=Re?new ka(de):null,re=(ld=(id=(ad=r.features)==null?void 0:ad.eventStream)==null?void 0:id.maxEvents)!=null?ld:2e3,ce=Re?new Ma(re,X):null,ge=Re?new La:null,K=null,ae=!1,He=null,Y=0;X==null||X.open().then(()=>ce==null?void 0:ce.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ee={onCopy:c=>{var m,b;s.emit("message:copy",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.id,"copy").catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",x)}),(b=(m=r.messageActions)==null?void 0:m.onCopy)==null||b.call(m,c)},onFeedback:c=>{var m,b;s.emit("message:feedback",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.messageId,c.type).catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",x)}),(b=(m=r.messageActions)==null?void 0:m.onFeedback)==null||b.call(m,c)}},ie=(cd=r.statusIndicator)!=null?cd:{},Se=c=>{var m,b,x,E;return c==="idle"?(m=ie.idleText)!=null?m:kn.idle:c==="connecting"?(b=ie.connectingText)!=null?b:kn.connecting:c==="connected"?(x=ie.connectedText)!=null?x:kn.connected:c==="error"?(E=ie.errorText)!=null?E:kn.error:kn[c]};function Ze(c,m,b,x){if(x==="idle"&&b.idleLink){c.textContent="";let E=document.createElement("a");E.href=b.idleLink,E.target="_blank",E.rel="noopener noreferrer",E.textContent=m,E.style.color="inherit",E.style.textDecoration="none",c.appendChild(E)}else c.textContent=m}let{wrapper:ve,panel:fe,pillRoot:Je}=Vm(r),De=Km(r,F()),{container:V,body:ue,messagesWrapper:ot,suggestions:Et,textarea:ne,sendButton:Ve,sendButtonWrapper:Nn,composerForm:Ht,statusText:cn,introTitle:sr,introSubtitle:Er,closeButton:H,iconHolder:pe,headerTitle:Oe,headerSubtitle:Qe,header:_e,footer:Ue,actionsRow:at,leftActions:Pt,rightActions:Kt}=De,Zt=De.setSendButtonMode,G=De.micButton,xt=De.micButtonWrapper,lt=De.attachmentButton,we=De.attachmentButtonWrapper,le=De.attachmentInput,nt=De.attachmentPreviewsContainer;V.classList.add("persona-relative"),ue.classList.add("persona-relative");let tn=12,Gt=()=>{var c;return(c=be.label)!=null?c:""},Pn=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},wn=()=>be.enabled!==!1,mt=()=>{var c;return(c=Le.mode)!=null?c:"follow"},Mt=()=>{var c;return(c=Le.anchorTopOffset)!=null?c:16},et=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");et.type="button",et.style.display="none",et.setAttribute("data-persona-scroll-to-bottom","true");let qt=h("span","persona-flex persona-items-center"),dn=h("span",""),An=h("span","");An.setAttribute("data-persona-scroll-to-bottom-count",""),An.style.display="none",et.append(qt,dn,An),V.appendChild(et);let Sn=h("div","persona-stream-anchor-spacer");Sn.setAttribute("aria-hidden","true"),Sn.setAttribute("data-persona-anchor-spacer",""),Sn.style.flexShrink="0",Sn.style.pointerEvents="none",Sn.style.height="0px",ue.appendChild(Sn);let yn=()=>{let m=Ue.style.display==="none"?0:Ue.offsetHeight;et.style.bottom=`${m+tn}px`};yn();let Mr=()=>{let c=!!Gt();et.setAttribute("aria-label",Gt()||"Jump to latest"),et.title=Gt(),et.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),qt.innerHTML="";let m=Ce(Pn(),"14px","currentColor",2);m?(qt.appendChild(m),qt.style.display=""):qt.style.display="none",dn.textContent=Gt(),dn.style.display=c?"":"none"};Mr();let At=null,jn=null,qn=o.find(c=>c.renderHeader);if(qn!=null&&qn.renderHeader){let c=qn.renderHeader({config:r,defaultRenderer:()=>{let m=eo({config:r,showClose:F()});return es(V,m,r),m.header},onClose:()=>Dt(!1,"user")});if(c){let m=V.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),_e=c)}}let Nr=()=>{var m,b,x,E;if(!ce)return;if(ae=!0,!K&&ce&&(K=ig({buffer:ce,getFullHistory:()=>ce.getAllFromStore(),onClose:()=>fr(),config:r,plugins:o,getThroughput:()=>{var D;return(D=ge==null?void 0:ge.getMetric())!=null?D:{status:"idle"}}})),K&&(ue.style.display="none",(m=Ue.parentNode)==null||m.insertBefore(K.element,Ue),K.update()),vt){vt.style.boxShadow=`inset 0 0 0 1.5px ${On.actionIconColor}`;let D=(E=(x=(b=r.features)==null?void 0:b.eventStream)==null?void 0:x.classNames)==null?void 0:E.toggleButtonActive;D&&D.split(/\s+/).forEach(N=>N&&vt.classList.add(N))}let c=()=>{if(!ae)return;let D=Date.now();D-Y>=200&&(K==null||K.update(),Y=D),He=requestAnimationFrame(c)};Y=0,He=requestAnimationFrame(c),$n(),s.emit("eventStream:opened",{timestamp:Date.now()})},fr=()=>{var c,m,b;if(ae){if(ae=!1,K&&K.element.remove(),ue.style.display="",vt){vt.style.boxShadow="";let x=(b=(m=(c=r.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:b.toggleButtonActive;x&&x.split(/\s+/).forEach(E=>E&&vt.classList.remove(E))}He!==null&&(cancelAnimationFrame(He),He=null),$n(),s.emit("eventStream:closed",{timestamp:Date.now()})}},vt=null;if(Re){let c=(pd=(dd=r.features)==null?void 0:dd.eventStream)==null?void 0:pd.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");vt=h("button",m),vt.style.width="28px",vt.style.height="28px",vt.style.color=On.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let b=Ce("activity","18px","currentColor",1.5);b&&vt.appendChild(b);let x=De.clearChatButtonWrapper,E=De.closeButtonWrapper,D=x||E;D&&D.parentNode===_e?_e.insertBefore(vt,D):_e.appendChild(vt),vt.addEventListener("click",()=>{ae?fr():Nr()})}let Lo=c=>{var x,E,D;let m=r.attachments;if(!(m!=null&&m.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(b,N):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=h("input");N.type="file",N.accept=((x=m.allowedTypes)!=null?x:Yr).join(","),N.multiple=((E=m.maxFiles)!=null?E:4)>1,N.style.display="none",N.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(N)}},kr=o.find(c=>c.renderComposer);if(kr!=null&&kr.renderComposer){let c=r.composer,m=kr.renderComposer({config:r,defaultRenderer:()=>Is({config:r}).footer,onSubmit:b=>{var N;if(!$||$.isStreaming())return;let x=b.trim(),E=(N=At==null?void 0:At.hasAttachments())!=null?N:!1;if(!x&&!E)return;U();let D;E&&(D=[],D.push(...At.getContentParts()),x&&D.push(pa(x))),$.sendMessage(x,{contentParts:D}),E&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{le==null||le.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:b=>{r.composer={...r.composer,selectedModelId:b},r.agent&&(r.agent={...r.agent,model:b})},onVoiceToggle:((ud=r.voiceRecognition)==null?void 0:ud.enabled)===!0?()=>{jn==null||jn()}:void 0});m&&(Ue.replaceWith(m),Ue=m)}let Po=c=>{let m=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),x=c.querySelector("[data-persona-composer-submit]"),E=c.querySelector("[data-persona-composer-mic]"),D=c.querySelector("[data-persona-composer-status]");m&&(Ht=m),b&&(ne=b),x&&(Ve=x),E&&(G=E,xt=E.parentElement),D&&(cn=D);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Et=N);let q=c.querySelector(".persona-attachment-button");q&&(lt=q,we=q.parentElement),le=c.querySelector('input[type="file"]'),nt=c.querySelector(".persona-attachment-previews");let B=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&(at=B)};Lo(Ue),Po(Ue);let Fn=(bd=(md=r.layout)==null?void 0:md.contentMaxWidth)!=null?bd:_()?(hd=(fd=(gd=r.launcher)==null?void 0:gd.composerBar)==null?void 0:fd.contentMaxWidth)!=null?hd:"720px":void 0;if(Fn&&(ot.style.maxWidth=Fn,ot.style.marginLeft="auto",ot.style.marginRight="auto",ot.style.width="100%"),Fn&&Ht&&!_()&&(Ht.style.maxWidth=Fn,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Fn&&Et&&!_()&&(Et.style.maxWidth=Fn,Et.style.marginLeft="auto",Et.style.marginRight="auto"),Fn&&nt&&!_()&&(nt.style.maxWidth=Fn,nt.style.marginLeft="auto",nt.style.marginRight="auto"),(yd=r.attachments)!=null&&yd.enabled&&le&&nt){At=Yo.fromConfig(r.attachments),At.setPreviewsContainer(nt),le.addEventListener("change",b=>{let x=b.target;At==null||At.handleFileSelect(x.files),x.value=""});let c=r.attachments.dropOverlay,m=Sg(c);V.appendChild(m)}(()=>{var x,E;let c=(E=(x=r.layout)==null?void 0:x.slots)!=null?E:{},m=D=>{switch(D){case"body-top":return V.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ot;case"footer-top":return Et;case"composer":return Ht;case"footer-bottom":return cn;default:return null}},b=(D,N)=>{var q;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")_e.insertBefore(N,_e.firstChild);else if(D==="header-right")_e.appendChild(N);else{let B=_e.querySelector(".persona-flex-col");B?(q=B.parentNode)==null||q.insertBefore(N,B.nextSibling):_e.appendChild(N)}break;case"body-top":{let B=ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(N):ue.insertBefore(N,ue.firstChild);break}case"body-bottom":ue.appendChild(N);break;case"footer-top":Et.replaceWith(N);break;case"footer-bottom":cn.replaceWith(N);break;default:break}};for(let[D,N]of Object.entries(c))if(N)try{let q=N({config:r,defaultContent:()=>m(D)});q&&b(D,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,q)}})();let ro=c=>{var N,q;let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let x=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let E=x.getAttribute("data-message-id");if(!E)return;let D=b.getAttribute("data-bubble-type");if(D==="reasoning")Ws.has(E)?Ws.delete(E):Ws.add(E),Xm(E,x);else if(D==="tool")Hs.has(E)?Hs.delete(E):Hs.add(E),Ym(E,x,r);else if(D==="approval"){let B=r.approval!==!1?r.approval:void 0,xe=((N=B==null?void 0:B.detailsDisplay)!=null?N:"collapsed")==="expanded",me=(q=qi.get(E))!=null?q:xe;qi.set(E,!me),ng(E,x,r)}Ur.delete(E)};ot.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),ro(c))}),ot.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),ro(c))});let Fr=new Map;ot.addEventListener("click",c=>{var N;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let x=b.closest("[data-actions-for]");if(!x)return;let E=x.getAttribute("data-actions-for");if(!E)return;let D=b.getAttribute("data-action");if(D==="copy"){let B=$.getMessages().find(xe=>xe.id===E);if(B&&ee.onCopy){let xe=B.content||"";navigator.clipboard.writeText(xe).then(()=>{b.classList.add("persona-message-action-success");let me=Ce("check",14,"currentColor",2);me&&(b.innerHTML="",b.appendChild(me)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let te=Ce("copy",14,"currentColor",2);te&&(b.innerHTML="",b.appendChild(te))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),ee.onCopy(B)}}else if(D==="upvote"||D==="downvote"){let B=((N=Fr.get(E))!=null?N:null)===D,xe=D==="upvote"?"thumbs-up":"thumbs-down";if(B){Fr.delete(E),b.classList.remove("persona-message-action-active");let me=Ce(xe,14,"currentColor",2);me&&(b.innerHTML="",b.appendChild(me))}else{let me=D==="upvote"?"downvote":"upvote",te=x.querySelector(`[data-action="${me}"]`);if(te){te.classList.remove("persona-message-action-active");let Ke=Ce(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ke&&(te.innerHTML="",te.appendChild(Ke))}Fr.set(E,D),b.classList.add("persona-message-action-active");let Ee=Ce(xe,14,"currentColor",2);Ee&&(Ee.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Ee)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Te=$.getMessages().find(st=>st.id===E);Te&&ee.onFeedback&&ee.onFeedback({type:D,messageId:Te.id,message:Te})}}}),ot.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let x=b.closest(".persona-approval-bubble");if(!x)return;let E=x.getAttribute("data-message-id");if(!E)return;let D=b.getAttribute("data-approval-action");if(!D)return;let N=D==="approve"?"approved":"denied",B=$.getMessages().find(me=>me.id===E);if(!(B!=null&&B.approval))return;let xe=x.querySelector("[data-approval-buttons]");xe&&xe.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?$.resolveWebMcpApproval(E,N):$.resolveApproval(B.approval,N)});let St=null,zn=null,Vn={artifacts:[],selectedId:null},In=!1,Lt={current:null};ot.addEventListener("click",c=>{var te,Ee,$e,Te,st;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let x=b.getAttribute("data-download-artifact");if(!x||(($e=(Ee=(te=r.features)==null?void 0:te.artifacts)==null?void 0:Ee.onArtifactAction)==null?void 0:$e.call(Ee,{type:"download",artifactId:x}))===!0)return;let D=$.getArtifactById(x),N=D==null?void 0:D.markdown,q=(D==null?void 0:D.title)||"artifact";if(!N){let Ke=b.closest("[data-open-artifact]"),dt=Ke==null?void 0:Ke.closest("[data-message-id]"),pt=dt==null?void 0:dt.getAttribute("data-message-id");if(pt){let Pe=$.getMessages().find(qe=>qe.id===pt);if(Pe!=null&&Pe.rawContent)try{let qe=JSON.parse(Pe.rawContent);N=(Te=qe==null?void 0:qe.props)==null?void 0:Te.markdown,q=((st=qe==null?void 0:qe.props)==null?void 0:st.title)||q}catch{}}}if(!N)return;let B=new Blob([N],{type:"text/markdown"}),xe=URL.createObjectURL(B),me=document.createElement("a");me.href=xe,me.download=`${q}.md`,me.click(),URL.revokeObjectURL(xe)}),ot.addEventListener("click",c=>{var D,N,q;let b=c.target.closest("[data-open-artifact]");if(!b)return;let x=b.getAttribute("data-open-artifact");!x||((q=(N=(D=r.features)==null?void 0:D.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:q.call(N,{type:"open",artifactId:x}))===!0||(c.preventDefault(),c.stopPropagation(),In=!1,$.selectArtifact(x),Jn())}),ot.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let ar=De.composerOverlay,ir=(c,m,b)=>{var q,B,xe,me;let x=m.trim();if(!x||!Lt.current)return;let E=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",D=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:E,answer:x,answers:b.structured,values:(B=b.values)!=null?B:b.source==="multi"?x.split(", "):[x],isFreeText:D,source:b.source},bubbles:!0,composed:!0})),wo(ar,E);let N=Lt.current.getMessages().find(te=>{var Ee;return((Ee=te.toolCall)==null?void 0:Ee.id)===E});(xe=N==null?void 0:N.agentMetadata)!=null&&xe.awaitingLocalTool?Lt.current.resolveAskUserQuestion(N,(me=b.structured)!=null?me:x):Lt.current.sendMessage(x)},Kn=c=>{var E;let m=Lt.current;if(!m)return;let b=(E=c.getAttribute("data-tool-call-id"))!=null?E:"",x=m.getMessages().find(D=>{var N;return((N=D.toolCall)==null?void 0:N.id)===b});x&&m.persistAskUserQuestionProgress(x,{answers:ti(c,x),currentIndex:mr(c)})},oo=c=>Object.entries(c).map(([m,b])=>`${m}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),_r=c=>{var E,D,N;if(((D=(E=r.features)==null?void 0:E.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let m=mr(c),b=Cs(c);if(m>=b-1)return;let x=(N=Lt.current)==null?void 0:N.getMessages().find(q=>{var B;return((B=q.toolCall)==null?void 0:B.id)===c.getAttribute("data-tool-call-id")});x&&(ni(c,x,r,m+1),Kn(c))};ar.addEventListener("click",c=>{var D,N,q,B,xe,me,te,Ee,$e,Te,st,Ke,dt,pt;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let x=b.closest("[data-persona-ask-sheet-for]");if(!x)return;let E=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),E==="dismiss"){let Ie=(D=x.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),wo(ar,Ie);let Pe=(N=Lt.current)==null?void 0:N.getMessages().find(qe=>{var Xe;return((Xe=qe.toolCall)==null?void 0:Xe.id)===Ie});(q=Pe==null?void 0:Pe.agentMetadata)!=null&&q.awaitingLocalTool&&((B=Lt.current)==null||B.markAskUserQuestionResolved(Pe),(xe=Lt.current)==null||xe.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(E==="pick"){let Ie=b.getAttribute("data-option-label");if(!Ie)return;let Pe=x.getAttribute("data-multi-select")==="true",qe=vo(x);if(qe&&Pe){let Xe=Vo(x)[mr(x)],wt=new Set(Array.isArray(Xe)?Xe:[]);wt.has(Ie)?wt.delete(Ie):wt.add(Ie),Co(x,Array.from(wt)),Kn(x);return}if(qe){Co(x,Ie),Kn(x),_r(x);return}if(Pe){let Xe=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",Xe?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!Xe);let wt=x.querySelector('[data-ask-user-action="submit-multi"]');wt&&(wt.disabled=Sl(x).length===0);return}ir(x,Ie,{source:"pick",values:[Ie]});return}if(E==="submit-multi"){let Ie=Sl(x);if(Ie.length===0)return;ir(x,Ie.join(", "),{source:"multi",values:Ie});return}if(E==="open-free-text"){let Ie=x.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Pe=Ie.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(E==="focus-free-text"){let Ie=x.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(E==="submit-free-text"){let Ie=x.querySelector('[data-ask-free-text-input="true"]'),Pe=(me=Ie==null?void 0:Ie.value)!=null?me:"";if(!Pe.trim())return;if(vo(x)){Co(x,Pe.trim()),Kn(x),_r(x);return}ir(x,Pe,{source:"free-text"});return}if(E==="next"||E==="back"){if(!Lt.current)return;let Ie=(te=x.getAttribute("data-tool-call-id"))!=null?te:"",Pe=Lt.current.getMessages().find(Be=>{var Ne;return((Ne=Be.toolCall)==null?void 0:Ne.id)===Ie});if(!Pe)return;let qe=x.querySelector('[data-ask-free-text-input="true"]'),Xe=($e=(Ee=qe==null?void 0:qe.value)==null?void 0:Ee.trim())!=null?$e:"";if(Xe){let Be=Vo(x)[mr(x)];(typeof Be!="string"||Be!==Xe)&&Co(x,Xe)}let wt=E==="next"?1:-1,P=mr(x)+wt;ni(x,Pe,r,P),Kn(x);return}if(E==="submit-all"){if(!Lt.current)return;let Ie=(Te=x.getAttribute("data-tool-call-id"))!=null?Te:"",Pe=Lt.current.getMessages().find(Be=>{var Ne;return((Ne=Be.toolCall)==null?void 0:Ne.id)===Ie});if(!Pe)return;let qe=x.querySelector('[data-ask-free-text-input="true"]'),Xe=(Ke=(st=qe==null?void 0:qe.value)==null?void 0:st.trim())!=null?Ke:"";Xe&&Co(x,Xe);let wt=ti(x,Pe);Lt.current.persistAskUserQuestionProgress(Pe,{answers:wt,currentIndex:mr(x)});let P=oo(wt);ir(x,P||"(submitted)",{source:"submit-all",structured:wt});return}if(E==="skip"){if(!Lt.current)return;let Ie=(dt=x.getAttribute("data-tool-call-id"))!=null?dt:"",Pe=Lt.current.getMessages().find(Ne=>{var he;return((he=Ne.toolCall)==null?void 0:he.id)===Ie});if(!Pe)return;let qe=vo(x),Xe=mr(x),wt=Cs(x),P=Xe>=wt-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),wo(ar,Ie),(pt=Pe.agentMetadata)!=null&&pt.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Pe),Lt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}Co(x,"");let Be=x.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),P){let Ne=ti(x,Pe),he=oo(Ne);ir(x,he||"(skipped)",{source:"submit-all",structured:Ne});return}ni(x,Pe,r,Xe+1),Kn(x);return}}),ar.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let b=c.target;if(!((D=b.matches)!=null&&D.call(b,'[data-ask-free-text-input="true"]')))return;let x=b.closest("[data-persona-ask-sheet-for]");if(!x)return;c.preventDefault();let E=b.value;if(E.trim()){if(vo(x)){Co(x,E.trim()),Kn(x),_r(x);return}ir(x,E,{source:"free-text"})}});let so=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let b=ar.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let x=Number(c.key),D=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",so);let Gn=null,Bt=null,Rn=null,lr=null,ao=()=>{};function $r(){lr==null||lr(),lr=null}let io=()=>{var N;if(!Gn||!Bt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),b=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||b){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let x=Gn.firstElementChild;if(!x||x===Bt)return;let E=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${E}px`,Bt.style.zIndex="5";let D=x.offsetWidth-E/2;Bt.style.left=`${Math.max(0,D)}px`},Lr=()=>{},Jn=()=>{var b,x,E,D,N;if(!St||!gr(r))return;Ki(e,r),Gi(e,r),Lr();let c=(D=(E=(x=(b=r.features)==null?void 0:b.artifacts)==null?void 0:x.layout)==null?void 0:E.narrowHostMaxWidth)!=null?D:520,m=fe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),St.update(Vn),In?(St.setMobileOpen(!1),St.element.classList.add("persona-hidden"),(N=St.backdrop)==null||N.classList.add("persona-hidden")):Vn.artifacts.length>0&&(St.element.classList.remove("persona-hidden"),St.setMobileOpen(!0)),ao()};if(gr(r)){fe.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(V),St=dg(r,{onSelect:b=>{var x;return(x=Lt.current)==null?void 0:x.selectArtifact(b)},onDismiss:()=>{In=!0,Jn()}}),St.element.classList.add("persona-hidden"),Gn=m,m.appendChild(c),m.appendChild(St.element),St.backdrop&&fe.appendChild(St.backdrop),fe.appendChild(m),ao=()=>{var x,E,D,N;if(!Gn||!St)return;if(!(((D=(E=(x=r.features)==null?void 0:x.artifacts)==null?void 0:E.layout)==null?void 0:D.resizable)===!0)){Rn==null||Rn(),Rn=null,$r(),Bt&&(Bt.remove(),Bt=null),St.element.style.removeProperty("width"),St.element.style.removeProperty("maxWidth");return}if(!Bt){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 B=e.ownerDocument,xe=(N=B.defaultView)!=null?N:window,me=te=>{var dt,pt;if(!St||te.button!==0||e.classList.contains("persona-artifact-narrow-host")||xe.innerWidth<=640)return;te.preventDefault(),$r();let Ee=te.clientX,$e=St.element.getBoundingClientRect().width,Te=(pt=(dt=r.features)==null?void 0:dt.artifacts)==null?void 0:pt.layout,st=Ie=>{let Pe=Gn.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Xe=qe?0:gg(Gn,xe),wt=qe?0:q.getBoundingClientRect().width||6,P=$e-(Ie.clientX-Ee),Be=fg(P,Pe,Xe,wt,Te==null?void 0:Te.resizableMinWidth,Te==null?void 0:Te.resizableMaxWidth);St.element.style.width=`${Be}px`,St.element.style.maxWidth="none",io()},Ke=()=>{B.removeEventListener("pointermove",st),B.removeEventListener("pointerup",Ke),B.removeEventListener("pointercancel",Ke),lr=null;try{q.releasePointerCapture(te.pointerId)}catch{}};lr=Ke,B.addEventListener("pointermove",st),B.addEventListener("pointerup",Ke),B.addEventListener("pointercancel",Ke);try{q.setPointerCapture(te.pointerId)}catch{}};q.addEventListener("pointerdown",me),Bt=q,Gn.insertBefore(q,St.element),Rn=()=>{q.removeEventListener("pointerdown",me)}}if(Bt){let q=Vn.artifacts.length>0&&!In;Bt.classList.toggle("persona-hidden",!q),io()}},Lr=()=>{var xe,me,te,Ee,$e,Te,st,Ke,dt,pt,Ie,Pe,qe,Xe;if(!S||!St||((me=(xe=r.launcher)==null?void 0:xe.sidebarMode)!=null?me:!1)||mn(r)&&rr(r).reveal==="emerge")return;let x=(te=e.ownerDocument.defaultView)!=null?te:window,E=($e=(Ee=r.launcher)==null?void 0:Ee.mobileFullscreen)!=null?$e:!0,D=(st=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?st:640;if(E&&x.innerWidth<=D||!mg(r,S))return;let N=(pt=(dt=(Ke=r.launcher)==null?void 0:Ke.width)!=null?dt:r.launcherWidth)!=null?pt:nr,q=(Xe=(qe=(Pe=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:Pe.layout)==null?void 0:qe.expandedPanelWidth)!=null?Xe:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!In?(fe.style.width=q,fe.style.maxWidth=q):(fe.style.width=N,fe.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(zn=new ResizeObserver(()=>{Jn()}),zn.observe(fe))}else fe.appendChild(V),_()&&Je&&(De.peekBanner&&Je.appendChild(De.peekBanner),Je.appendChild(Ue));e.appendChild(ve),Je&&e.appendChild(Je);let hr=()=>{var Be,Ne,he,Ft,Ot,Jt,Ct,zt,Zn,ln,Ye,It,un,ur,er,Do,Oo,bs,ys,Xt,No,bo,yo,Kr,Fo,wr,rt,fn;if(_()){fe.style.width="100%",fe.style.maxWidth="100%";let Ut=(Ne=(Be=r.launcher)==null?void 0:Be.composerBar)!=null?Ne:{},_t=ve.dataset.state==="expanded",bt=(he=Ut.expandedSize)!=null?he:"anchored";if(!(_t&&bt!=="fullscreen")){V.style.background="",V.style.border="",V.style.borderRadius="",V.style.overflow="",V.style.boxShadow="";return}let kt=(Ot=(Ft=r.theme)==null?void 0:Ft.components)==null?void 0:Ot.panel,En=Ls(r),Wn=(Bn,_o)=>{var ea;return Bn==null||Bn===""?_o:(ea=Ms(En,Bn))!=null?ea:Bn},Br="1px solid var(--persona-border)",vn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Hn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";V.style.background="var(--persona-surface, #ffffff)",V.style.border=Wn(kt==null?void 0:kt.border,Br),V.style.borderRadius=Wn(kt==null?void 0:kt.borderRadius,Hn),V.style.boxShadow=Wn(kt==null?void 0:kt.shadow,vn),V.style.overflow="hidden";return}let c=mn(r),m=(Ct=(Jt=r.launcher)==null?void 0:Jt.sidebarMode)!=null?Ct:!1,b=c||m||((Zn=(zt=r.launcher)==null?void 0:zt.fullHeight)!=null?Zn:!1),x=((ln=r.launcher)==null?void 0:ln.enabled)===!1,E=(It=(Ye=r.theme)==null?void 0:Ye.components)==null?void 0:It.panel,D=Ls(r),N=(Ut,_t)=>{var bt;return Ut==null||Ut===""?_t:(bt=Ms(D,Ut))!=null?bt:Ut},q=(un=e.ownerDocument.defaultView)!=null?un:window,B=(er=(ur=r.launcher)==null?void 0:ur.mobileFullscreen)!=null?er:!0,xe=(Oo=(Do=r.launcher)==null?void 0:Do.mobileBreakpoint)!=null?Oo:640,me=q.innerWidth<=xe,te=B&&me&&S,Ee=(ys=(bs=r.launcher)==null?void 0:bs.position)!=null?ys:"bottom-left",$e=Ee==="bottom-left"||Ee==="top-left",Te=(No=(Xt=r.launcher)==null?void 0:Xt.zIndex)!=null?No:Ln,st=m||te?"none":"1px solid var(--persona-border)",Ke=te?"none":m?$e?"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&&!te&&(Ke="none",st="none");let dt=m||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",pt=N(E==null?void 0:E.border,st),Ie=N(E==null?void 0:E.shadow,Ke),Pe=N(E==null?void 0:E.borderRadius,dt),qe=ue.scrollTop;e.style.cssText="",ve.style.cssText="",fe.style.cssText="",V.style.cssText="",ue.style.cssText="",Ue.style.cssText="";let Xe=()=>{var _t;if(qe<=0)return;((_t=ue.ownerDocument.defaultView)!=null?_t:window).requestAnimationFrame(()=>{if(ue.scrollTop===qe)return;let bt=ue.scrollHeight-ue.clientHeight;bt<=0||(ue.scrollTop=Math.min(qe,bt))})};if(te){ve.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"),ve.style.cssText=`
31
31
  position: fixed !important;
32
32
  inset: 0 !important;
33
33
  width: 100% !important;
@@ -52,7 +52,7 @@ _Details: ${n.message}_`:r}var ia=e=>({isError:!0,content:[{type:"text",text:e}]
52
52
  padding: 0 !important;
53
53
  box-shadow: none !important;
54
54
  border-radius: 0 !important;
55
- `,z.style.cssText=`
55
+ `,V.style.cssText=`
56
56
  display: flex !important;
57
57
  flex-direction: column !important;
58
58
  flex: 1 1 0% !important;
@@ -63,11 +63,11 @@ _Details: ${n.message}_`:r}var ia=e=>({isError:!0,content:[{type:"text",text:e}]
63
63
  overflow: hidden !important;
64
64
  border-radius: 0 !important;
65
65
  border: none !important;
66
- `,ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",je.style.flexShrink="0",k=!0,Qe();return}let Ct=(bo=(ho=r==null?void 0:r.launcher)==null?void 0:ho.width)!=null?bo:r==null?void 0:r.launcherWidth,P=Ct!=null?Ct:er;if(!g&&!c)y&&b?(fe.style.width="100%",fe.style.maxWidth="100%"):(fe.style.width=P,fe.style.maxWidth=P);else if(c)if(mr(r).reveal==="emerge"){let yt=mr(r).width;fe.style.width=yt,fe.style.maxWidth=yt}else fe.style.width="100%",fe.style.maxWidth="100%";if(kr(),fe.style.boxShadow=Ie,fe.style.borderRadius=Le,z.style.border=pt,z.style.borderRadius=Le,c&&!ne&&(E==null?void 0:E.border)===void 0&&(z.style.border="none",mr(r).side==="right"?z.style.borderLeft="1px solid var(--persona-border)":z.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.height="100%",y&&(ve.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",fe.style.overflow="hidden",z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.overflow="hidden",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",je.style.flexShrink="0"),ve.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!y&&!c&&((Vr=Sr[Ee])!=null?Vr:Sr["bottom-right"]).split(" ").forEach(yt=>ve.classList.add(yt)),g){let ut=(vn=(at=r.launcher)==null?void 0:at.sidebarWidth)!=null?vn:"420px";ve.style.cssText=`
66
+ `,ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",Ue.style.flexShrink="0",W=!0,Xe();return}let wt=(yo=(bo=r==null?void 0:r.launcher)==null?void 0:bo.width)!=null?yo:r==null?void 0:r.launcherWidth,P=wt!=null?wt:nr;if(!m&&!c)x&&b?(fe.style.width="100%",fe.style.maxWidth="100%"):(fe.style.width=P,fe.style.maxWidth=P);else if(c)if(rr(r).reveal==="emerge"){let _t=rr(r).width;fe.style.width=_t,fe.style.maxWidth=_t}else fe.style.width="100%",fe.style.maxWidth="100%";if(Lr(),fe.style.boxShadow=Ie,fe.style.borderRadius=Pe,V.style.border=pt,V.style.borderRadius=Pe,c&&!te&&(E==null?void 0:E.border)===void 0&&(V.style.border="none",rr(r).side==="right"?V.style.borderLeft="1px solid var(--persona-border)":V.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.height="100%",x&&(ve.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",fe.style.overflow="hidden",V.style.display="flex",V.style.flexDirection="column",V.style.flex="1 1 0%",V.style.minHeight="0",V.style.maxHeight="100%",V.style.overflow="hidden",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",Ue.style.flexShrink="0"),ve.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!x&&!c&&((Kr=Tr[Ee])!=null?Kr:Tr["bottom-right"]).split(" ").forEach(_t=>ve.classList.add(_t)),m){let Ut=(wr=(Fo=r.launcher)==null?void 0:Fo.sidebarWidth)!=null?wr:"420px";ve.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
70
- width: ${ut} !important;
70
+ width: ${Ut} !important;
71
71
  height: 100vh !important;
72
72
  max-height: 100vh !important;
73
73
  margin: 0 !important;
@@ -75,7 +75,7 @@ _Details: ${n.message}_`:r}var ia=e=>({isError:!0,content:[{type:"text",text:e}]
75
75
  display: flex !important;
76
76
  flex-direction: column !important;
77
77
  z-index: ${Te} !important;
78
- ${_e?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
78
+ ${$e?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
79
  `,fe.style.cssText=`
80
80
  position: relative !important;
81
81
  display: flex !important;
@@ -88,8 +88,8 @@ _Details: ${n.message}_`:r}var ia=e=>({isError:!0,content:[{type:"text",text:e}]
88
88
  margin: 0 !important;
89
89
  padding: 0 !important;
90
90
  box-shadow: ${Ie} !important;
91
- border-radius: ${Le} !important;
92
- `,fe.style.setProperty("width","100%","important"),fe.style.setProperty("max-width","100%","important"),z.style.cssText=`
91
+ border-radius: ${Pe} !important;
92
+ `,fe.style.setProperty("width","100%","important"),fe.style.setProperty("max-width","100%","important"),V.style.cssText=`
93
93
  display: flex !important;
94
94
  flex-direction: column !important;
95
95
  flex: 1 1 0% !important;
@@ -98,29 +98,29 @@ _Details: ${n.message}_`:r}var ia=e=>({isError:!0,content:[{type:"text",text:e}]
98
98
  min-height: 0 !important;
99
99
  max-height: 100% !important;
100
100
  overflow: hidden !important;
101
- border-radius: ${Le} !important;
101
+ border-radius: ${Pe} !important;
102
102
  border: ${pt} !important;
103
- `,je.style.cssText=`
103
+ `,Ue.style.cssText=`
104
104
  flex-shrink: 0 !important;
105
105
  border-top: none !important;
106
106
  padding: 8px 16px 12px 16px !important;
107
- `}if(!y&&!c){let ut="max-height: -moz-available !important; max-height: stretch !important;",yt=g?"":"padding-top: 1.25em !important;",mt=g?"":`z-index: ${(an=(In=r.launcher)==null?void 0:In.zIndex)!=null?an:Mn} !important;`;ve.style.cssText+=ut+yt+mt}Qe()};br(),xo(e,r),$i(e,r),_i(e,r);let bt=[];bt.push(()=>{document.removeEventListener("keydown",oo)});let en=null,tn=null;bt.push(()=>{en==null||en(),en=null,tn==null||tn(),tn=null}),Un&&bt.push(()=>{Un==null||Un.disconnect(),Un=null}),bt.push(()=>{Pn==null||Pn(),Pn=null,$r(),Dt&&(Dt.remove(),Dt=null),Tt==null||Tt.element.style.removeProperty("width"),Tt==null||Tt.element.style.removeProperty("maxWidth")}),We&&bt.push(()=>{He!==null&&(cancelAnimationFrame(He),He=null),V==null||V.destroy(),V=null,le==null||le.destroy(),le=null,Q=null});let Jn=null,io=()=>{Jn&&(Jn(),Jn=null),r.colorScheme==="auto"&&(Jn=gi(()=>{xo(e,r)}))};io(),bt.push(()=>{Jn&&(Jn(),Jn=null)});let ye=(cd=r.features)==null?void 0:cd.streamAnimation;if(ye!=null&&ye.type&&ye.type!=="none"){let c=ua(ye.type,ye.plugins);c&&(Cl(c,e),bt.push(()=>ym(e)))}let ar=zm(kt),ir=null,_,Lr=!1,_r=am(),jr=new Map,Pr=new Map,yr=new Map,Bs=0,Gn=bi(),Xn=0,xr=null,vr=!1,Io=!1,Ur=0,An=null,Ir=null,os=!1,Wo=!1,ss=null,ka=4,as=24,La=80,is=new Map,xt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ds=(pd=(dd=r.voiceRecognition)==null?void 0:dd.autoResume)!=null?pd:!1,lr=c=>{s.emit("voice:state",{active:xt.active,source:c,timestamp:Date.now()})},Nn=()=>{m(c=>({...c,voiceState:{active:xt.active,timestamp:Date.now(),manuallyDeactivated:xt.manuallyDeactivated}}))},Pa=()=>{var y,E;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Kl(d.voiceState),g=!!c.active,b=Number((E=c.timestamp)!=null?E:0);xt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<Eb&&setTimeout(()=>{var D,F;xt.active||(xt.manuallyDeactivated=!1,((F=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:F.type)==="runtype"?_.toggleVoice().then(()=>{xt.active=_.isVoiceActive(),lr("restore"),_.isVoiceActive()&&Gs()}):fn("restore"))},1e3)},Ia=()=>_?dg(_.getMessages()).filter(c=>!c.__skipPersist):[];function ls(c){if(!(i!=null&&i.save))return;let b={messages:c?dg(c):_?Ia():[],metadata:d,artifacts:qn.artifacts,selectedArtifactId:qn.selectedId};try{let y=i.save(b);y instanceof Promise&&y.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let qr=null,Ns=()=>ve.querySelector("#persona-scroll-container")||ue,lo=()=>{qr!==null&&(cancelAnimationFrame(qr),qr=null),vr=!1},Os=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null),Io=!1,lo()},Fs=()=>{Ur>0?(wn.textContent=String(Ur),wn.style.display="",et.setAttribute("aria-label",`${Gt()||"Jump to latest"} (${Ur} new)`)):(wn.textContent="",wn.style.display="none",et.setAttribute("aria-label",Gt()||"Jump to latest"))},$s=()=>{Ur!==0&&(Ur=0,Fs())},_s=()=>ft()==="follow"?!Gn.isFollowing():!Xo(ue,as),On=()=>{if(!xn()||se){et.parentNode&&et.remove(),et.style.display="none";return}et.parentNode!==z&&z.appendChild(et),yn();let g=Xr(ue)>0&&_s();g||$s(),et.style.display=g?"":"none"},cs=()=>{Gn.pause()&&(Os(),On())},Wr=()=>{Gn.resume(),$s(),On()},Rr=(c=!1)=>{ft()==="follow"&&Gn.isFollowing()&&(!c&&!Lr||(xr!==null&&(cancelAnimationFrame(xr),xr=null),Io=!0,xr=requestAnimationFrame(()=>{xr=null,Io=!1,Gn.isFollowing()&&Wa(Ns(),c?220:140)})))},js=(c,g,b,y=()=>!0)=>{let E=c.scrollTop,D=g(),F=D-E;lo();let q=performance.now();vr=!0;let B=me=>1-Math.pow(1-me,3),xe=me=>{if(!y()){lo();return}let ne=g();ne!==D&&(D=ne,F=D-E);let Ee=me-q,_e=Math.min(Ee/b,1),Te=B(_e),ot=E+F*Te;c.scrollTop=ot,Xn=c.scrollTop,_e<1?qr=requestAnimationFrame(xe):(c.scrollTop=D,Xn=c.scrollTop,qr=null,vr=!1)};qr=requestAnimationFrame(xe)},Wa=(c,g=500)=>{let b=Xr(c)-c.scrollTop;if(Math.abs(b)<1){Xn=c.scrollTop;return}if(Math.abs(b)>=La){lo(),vr=!0,c.scrollTop=Xr(c),Xn=c.scrollTop,vr=!1;return}js(c,()=>Xr(c),g,()=>Gn.isFollowing())},Us=()=>{let c=Ns();vr=!0,c.scrollTop=Xr(c),Xn=c.scrollTop,vr=!1,On()},qs=c=>{Cn.style.height=`${Math.max(0,Math.round(c))}px`,An&&(An.spacerHeight=Math.max(0,c))},Ro=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),lo(),An=null,Cn.style.height="0px"},Ra=c=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=requestAnimationFrame(()=>{var xe;Ir=null;let g=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=ue.querySelector(`[data-message-id="${g}"]`);if(!b)return;let y=0,E=b;for(;E&&E!==ue;)y+=E.offsetTop,E=E.offsetParent;let D=(xe=An==null?void 0:An.spacerHeight)!=null?xe:0,F=ue.scrollHeight-D,{targetScrollTop:q,spacerHeight:B}=pm({anchorOffsetTop:y,topOffset:Lt(),viewportHeight:ue.clientHeight,contentHeight:F});An={initialSpacerHeight:B,contentHeightAtAnchor:F,spacerHeight:B},qs(B),js(ue,()=>q,220)})},Ha=()=>{if(ft()==="follow"){if(!Gn.isFollowing()||Xo(ue,1))return;Rr(!Lr);return}if(An&&An.initialSpacerHeight>0){let c=ue.scrollHeight-An.spacerHeight,g=um({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:c});g!==An.spacerHeight&&qs(g)}On()},Ba=c=>{let g=ft();g==="follow"?(Wr(),Rr(!0)):g==="anchor-top"&&Ra(c)},Da=c=>{let g=new Map;c.forEach(b=>{let y=is.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!y&&b.role==="assistant"&&(s.emit("assistant:message",b),!Wo&&ft()!=="anchor-top"&&_s()&&(Ur+=1,Fs(),On())),b.role==="assistant"&&(y!=null&&y.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(y?b.approval.status!=="pending"&&s.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):s.emit("approval:requested",{approval:b.approval,message:b}))}),is.clear(),g.forEach((b,y)=>{is.set(y,b)})},Ho=(c,g,b)=>{var pt,Ie,Le,qe,Qe,Ct;let y=document.createElement("div"),D=(()=>{var Be;let P=o.find(Oe=>Oe.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),F=(P,Be)=>Be==null?!1:typeof Be=="string"?(P.textContent=Be,!0):(P.appendChild(Be),!0),q=new Set,B=new Set,xe=o.some(P=>P.renderAskUserQuestion),me=[],ne=[],Ee=r.enableComponentStreaming!==!1,_e=o.some(P=>P.renderApproval)&&r.approval!==!1,Te=[];if(g.forEach(P=>{var Ye,Wt,pn,pr,Yn,Bo,Do,gs,fs,Qt,No,ho,bo,Vr;q.add(P.id);let Be=xe&&Yr(P),Oe=_e&&P.variant==="approval"&&!!P.approval,he=!Be&&P.role==="assistant"&&!P.variant&&Ee&&zi(P);if(!Oe&&yr.has(P.id)){let at=c.querySelector(`#wrapper-${P.id}`);at==null||at.removeAttribute("data-preserve-runtime"),yr.delete(P.id)}if(!he&&Pr.has(P.id)){let at=c.querySelector(`#wrapper-${P.id}`);at==null||at.removeAttribute("data-preserve-runtime"),Pr.delete(P.id)}let _t=Yr(P)?`:${(Ye=P.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Wt=P.agentMetadata)!=null&&Wt.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=sm(P,Bs)+_t,Xt=Be||Oe||he?null:im(_r,P.id,Ot);if(Xt){y.appendChild(Xt.cloneNode(!0)),Yr(P)&&((pn=P.toolCall)!=null&&pn.id)&&((pr=P.agentMetadata)==null?void 0:pr.awaitingLocalTool)===!0&&!((Yn=P.agentMetadata)!=null&&Yn.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Is(P,r,De.composerOverlay));return}let At=null,Vt=o.find(at=>!!(P.variant==="reasoning"&&at.renderReasoning||P.variant==="tool"&&at.renderToolCall||!P.variant&&at.renderMessage)),Qn=(Bo=r.layout)==null?void 0:Bo.messages;if(Yr(P)&&((Do=P.agentMetadata)==null?void 0:Do.askUserQuestionAnswered)===!0){jr.delete(P.id);let at=c.querySelector(`#wrapper-${P.id}`);at==null||at.removeAttribute("data-preserve-runtime");return}if(Yr(P)&&((fs=(gs=r.features)==null?void 0:gs.askUserQuestion)==null?void 0:fs.enabled)!==!1){let at=o.find(vn=>typeof vn.renderAskUserQuestion=="function");if(at&&Pt.current){let vn=jr.get(P.id),In=vn!==Ot,an=null;if(In){let{payload:mt,complete:Fn}=Zr(P),un=P.id,Hr=()=>{var mn;return(mn=Pt.current)==null?void 0:mn.getMessages().find(Wn=>Wn.id===un)};an=at.renderAskUserQuestion({message:P,payload:mt,complete:Fn,resolve:mn=>{var ur;let Wn=Hr();Wn&&((ur=Pt.current)==null||ur.resolveAskUserQuestion(Wn,mn))},dismiss:()=>{var Wn,ur,Oo;let mn=Hr();(Wn=mn==null?void 0:mn.agentMetadata)!=null&&Wn.awaitingLocalTool&&((ur=Pt.current)==null||ur.markAskUserQuestionResolved(mn),(Oo=Pt.current)==null||Oo.resolveAskUserQuestion(mn,"(dismissed)"))},config:r})}let ut=vn!=null;if(In&&an===null&&!ut){((Qt=P.agentMetadata)==null?void 0:Qt.awaitingLocalTool)===!0&&!((No=P.agentMetadata)!=null&&No.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Is(P,r,De.composerOverlay));return}let yt=document.createElement("div");yt.className="persona-flex",yt.id=`wrapper-${P.id}`,yt.setAttribute("data-wrapper-id",P.id),yt.setAttribute("data-ask-plugin-stub","true"),yt.setAttribute("data-preserve-runtime","true"),y.appendChild(yt),me.push({messageId:P.id,fingerprint:Ot,bubble:an});return}else{((ho=P.agentMetadata)==null?void 0:ho.awaitingLocalTool)===!0&&!((bo=P.agentMetadata)!=null&&bo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Is(P,r,De.composerOverlay));return}}else if(Oe){let at=o.find(ut=>typeof ut.renderApproval=="function"),In=yr.get(P.id)!==Ot,an=null;if(In&&(at!=null&&at.renderApproval)){let ut=P.id,yt=(mt,Fn)=>{var Hr,mn,Wn;let un=(Hr=Pt.current)==null?void 0:Hr.getMessages().find(ur=>ur.id===ut);un!=null&&un.approval&&(un.approval.toolType==="webmcp"?(mn=Pt.current)==null||mn.resolveWebMcpApproval(un.id,mt):(Wn=Pt.current)==null||Wn.resolveApproval(un.approval,mt,Fn))};an=at.renderApproval({message:P,defaultRenderer:()=>Oi(P,r),config:r,approve:mt=>yt("approved",mt),deny:mt=>yt("denied",mt)})}if(In&&an===null){let ut=c.querySelector(`#wrapper-${P.id}`);ut==null||ut.removeAttribute("data-preserve-runtime"),yr.delete(P.id),At=Oi(P,r)}else{let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-${P.id}`,ut.setAttribute("data-wrapper-id",P.id),ut.setAttribute("data-approval-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),y.appendChild(ut),Te.push({messageId:P.id,fingerprint:Ot,bubble:an});return}}else if(Vt)if(P.variant==="reasoning"&&P.reasoning&&Vt.renderReasoning){if(!ze)return;At=Vt.renderReasoning({message:P,defaultRenderer:()=>Wl(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&Vt.renderToolCall){if(!Ae)return;At=Vt.renderToolCall({message:P,defaultRenderer:()=>Rl(P,r),config:r})}else Vt.renderMessage&&(At=Vt.renderMessage({message:P,defaultRenderer:()=>{let at=Es(P,b,Qn,r.messageActions,ee,{loadingIndicatorRenderer:D,widgetConfig:r});return P.role!=="user"&&ql(at,P,r,_),at},config:r}));if(!At&&he){let at=Vi(P);if(at){let vn=Pr.get(P.id),In=vn!==Ot,an=r.wrapComponentDirectiveInBubble!==!1,ut=null;if(In){let yt=qi(at,{config:r,message:P,transform:b});if(yt)if(an){let mt=document.createElement("div");if(mt.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(" "),mt.id=`bubble-${P.id}`,mt.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let Fn=document.createElement("div");Fn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Fn.innerHTML=b({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),mt.appendChild(Fn)}mt.appendChild(yt),ut=mt}else{let mt=document.createElement("div");if(mt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",mt.id=`bubble-${P.id}`,mt.setAttribute("data-message-id",P.id),mt.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let Fn=document.createElement("div");Fn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Fn.innerHTML=b({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),mt.appendChild(Fn)}mt.appendChild(yt),ut=mt}}if(ut||vn!=null){let yt=document.createElement("div");yt.className="persona-flex",yt.id=`wrapper-${P.id}`,yt.setAttribute("data-wrapper-id",P.id),yt.setAttribute("data-component-directive-stub","true"),yt.setAttribute("data-preserve-runtime","true"),an||yt.classList.add("persona-w-full"),y.appendChild(yt),ne.push({messageId:P.id,fingerprint:Ot,bubble:ut});return}}}if(!At)if(P.variant==="reasoning"&&P.reasoning){if(!ze)return;At=Wl(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!Ae)return;At=Rl(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;At=Oi(P,r)}else{let at=(Vr=r.layout)==null?void 0:Vr.messages;at!=null&&at.renderUserMessage&&P.role==="user"?At=at.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):at!=null&&at.renderAssistantMessage&&P.role==="assistant"?At=at.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):At=Es(P,b,at,r.messageActions,ee,{loadingIndicatorRenderer:D,widgetConfig:r}),P.role!=="user"&&At&&ql(At,P,r,_)}let sn=document.createElement("div");sn.className="persona-flex",sn.id=`wrapper-${P.id}`,sn.setAttribute("data-wrapper-id",P.id),P.role==="user"&&sn.classList.add("persona-justify-end"),(At==null?void 0:At.getAttribute("data-persona-component-directive"))==="true"&&sn.classList.add("persona-w-full"),sn.appendChild(At),lm(_r,P.id,Ot,sn),y.appendChild(sn)}),De.composerOverlay&&De.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Oe=Be.getAttribute("data-persona-ask-sheet-for");Oe&&!B.has(Oe)&&Eo(De.composerOverlay,Oe)}),(Ie=(pt=r.features)==null?void 0:pt.toolCallDisplay)!=null&&Ie.grouped){let P=[],Be=[];g.forEach(Oe=>{if(Oe.variant==="tool"&&Oe.toolCall&&Ae){Be.push(Oe);return}Be.length>1&&P.push(Be),Be=[]}),Be.length>1&&P.push(Be),P.forEach((Oe,he)=>{var Ye,Wt;let _t=Oe.map(pn=>Array.from(y.children).find(pr=>pr instanceof HTMLElement&&pr.getAttribute("data-wrapper-id")===pn.id)).filter(pn=>!!pn);if(_t.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${he}-${Oe[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${he}-${Oe[0].id}`);let Xt=document.createElement("div");Xt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Xt.setAttribute("data-persona-tool-group","true");let At=document.createElement("div");At.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Vt=`Called ${Oe.length} tools`,Qn=(Wt=(Ye=r.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Wt.call(Ye,{messages:Oe,toolCalls:Oe.map(pn=>pn.toolCall).filter(pn=>!!pn),defaultSummary:Vt,config:r});F(At,Qn)||(At.textContent=Vt);let sn=document.createElement("div");sn.className="persona-tool-group-stack persona-flex persona-flex-col",Xt.append(At,sn),Ot.appendChild(Xt),_t[0].before(Ot),_t.forEach((pn,pr)=>{let Yn=document.createElement("div");Yn.className="persona-tool-group-item persona-relative",Yn.setAttribute("data-persona-tool-group-item","true"),pr<_t.length-1&&Yn.setAttribute("data-persona-tool-group-connector","true"),Yn.appendChild(pn),sn.appendChild(Yn)})})}cm(_r,q);let ot=g.some(P=>P.role==="assistant"&&P.streaming),Ke=g[g.length-1],dt=(Ke==null?void 0:Ke.role)==="assistant"&&!Ke.streaming&&Ke.variant!=="approval";if(Lr&&g.some(P=>P.role==="user")&&!ot&&!dt){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:Yo},Be=o.find(he=>he.renderLoadingIndicator),Oe=null;if(Be!=null&&Be.renderLoadingIndicator&&(Oe=Be.renderLoadingIndicator(P)),Oe===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(Oe=r.loadingIndicator.render(P)),Oe===null&&(Oe=Yo()),Oe){let he=document.createElement("div"),_t=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;he.className=_t?["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(" "),he.setAttribute("data-typing-indicator","true"),he.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",he.appendChild(Oe);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(he),y.appendChild(Ot)}}if(!Lr&&g.length>0){let P=g[g.length-1],Be={config:r,lastMessage:P,messageCount:g.length},Oe=o.find(_t=>_t.renderIdleIndicator),he=null;if(Oe!=null&&Oe.renderIdleIndicator&&(he=Oe.renderIdleIndicator(Be)),he===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(he=r.loadingIndicator.renderIdle(Be)),he){let _t=document.createElement("div"),Ot=((Ct=r.loadingIndicator)==null?void 0:Ct.showBubble)!==!1;_t.className=Ot?["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(" "),_t.setAttribute("data-idle-indicator","true"),_t.appendChild(he);let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id="wrapper-idle-indicator",Xt.setAttribute("data-wrapper-id","idle-indicator"),Xt.appendChild(_t),y.appendChild(Xt)}}if(fi(c,y),me.length>0)for(let{messageId:P,fingerprint:Be,bubble:Oe}of me){let he=c.querySelector(`#wrapper-${P}`);he&&Oe!==null&&(he.replaceChildren(Oe),he.setAttribute("data-bubble-fp",Be),jr.set(P,Be))}if(jr.size>0)for(let P of jr.keys())q.has(P)||jr.delete(P);if(ne.length>0)for(let{messageId:P,fingerprint:Be,bubble:Oe}of ne){let he=c.querySelector(`#wrapper-${P}`);he&&Oe!==null&&(he.replaceChildren(Oe),he.setAttribute("data-bubble-fp",Be),Pr.set(P,Be))}if(Pr.size>0)for(let P of Pr.keys())q.has(P)||Pr.delete(P);if(Te.length>0)for(let{messageId:P,fingerprint:Be,bubble:Oe}of Te){let he=c.querySelector(`#wrapper-${P}`);he&&Oe!==null&&(he.replaceChildren(Oe),he.setAttribute("data-bubble-fp",Be),yr.set(P,Be))}if(yr.size>0)for(let P of yr.keys())q.has(P)||yr.delete(P)},co=null,Na=()=>{var b;if(co)return;let c=y=>{let E=y.composedPath();E.includes(ve)||Je&&E.includes(Je)||Nt(!1,"user")};co=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},zs=()=>{var g;if(!co)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",co,!0),co=null};bt.push(()=>zs());let po=null,Oa=()=>{var b;if(po)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Nt(!1,"user"))};po=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Vs=()=>{var g;if(!po)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",po,!0),po=null};bt.push(()=>Vs());let uo=!1,Ks=new Set,Fa=()=>{var g,b,y,E;let c=(y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:y.streamAnimation;return c||((E=r.features)==null?void 0:E.streamAnimation)},zr=()=>{var dt,pt,Ie,Le;if(!$())return;let c=De.peekBanner,g=De.peekTextNode;if(!c||!g)return;if(H){c.classList.remove("persona-pill-peek--visible");return}let b=(dt=_==null?void 0:_.getMessages())!=null?dt:[],y;for(let qe=b.length-1;qe>=0;qe--){let Qe=b[qe];if(Qe.role==="assistant"&&Qe.content){y=Qe;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let E=y.content,D=!!y.streaming,F=Fa(),q=vi(F),B=q.type!=="none"?ua(q.type,F==null?void 0:F.plugins):null,xe=((pt=B==null?void 0:B.isAnimating)==null?void 0:pt.call(B,y))===!0,me=B!==null&&(D||xe);me&&B&&!Ks.has(B.name)&&(Cl(B,e),Ks.add(B.name));let ne=me&&(B!=null&&B.containerClass)?B.containerClass:null,Ee=(Ie=g.dataset.personaPeekStreamClass)!=null?Ie:null;Ee&&Ee!==ne&&(g.classList.remove(Ee),delete g.dataset.personaPeekStreamClass),ne&&Ee!==ne&&(g.classList.add(ne),g.dataset.personaPeekStreamClass=ne),me?(g.style.setProperty("--persona-stream-step",`${q.speed}ms`),g.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let _e=me?wi(E,q.buffer,B,y,D):E;if(me&&q.placeholder==="skeleton"&&D&&(!_e||!_e.trim())){let qe=document.createElement("div"),Qe=ga();Qe.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Qe),fi(g,qe)}else{let qe=Math.max(0,_e.length-100),Qe=_e.length>100?_e.slice(-100):_e,Ct=Uo(Qe);if(!me||!B){let P=_e.length>100?`\u2026${Qe}`:Qe;g.textContent!==P&&(g.textContent=P)}else{let P=Ct;(B.wrap==="char"||B.wrap==="word")&&(P=ma(Ct,B.wrap,`peek-${y.id}`,{skipTags:B.skipTags,startIndex:qe}));let Be=document.createElement("div");if(Be.innerHTML=P,B.useCaret&&Qe.length>0){let Oe=Ci(),he=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),_t=he[he.length-1];_t!=null&&_t.parentNode?_t.parentNode.insertBefore(Oe,_t.nextSibling):Be.appendChild(Oe)}fi(g,Be),(Le=B.onAfterRender)==null||Le.call(B,{container:g,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let Ke=Lr||uo;c.classList.toggle("persona-pill-peek--visible",Ke)};if($()){let c=De.peekBanner;if(c){let y=E=>{E.preventDefault(),E.stopPropagation(),Nt(!0,"user")};c.addEventListener("pointerdown",y),bt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{uo||(uo=!0,zr())},b=()=>{uo&&(uo=!1,zr())};fe.addEventListener("pointerenter",g),fe.addEventListener("pointerleave",b),bt.push(()=>{fe.removeEventListener("pointerenter",g),fe.removeEventListener("pointerleave",b)}),Je&&(Je.addEventListener("pointerenter",g),Je.addEventListener("pointerleave",b),bt.push(()=>{Je.removeEventListener("pointerenter",g),Je.removeEventListener("pointerleave",b)}))}let $a=c=>{var Ee,_e,Te,ot,Ke,dt,pt,Ie;let g=(_e=(Ee=r.launcher)==null?void 0:Ee.composerBar)!=null?_e:{},b=(Te=g.expandedSize)!=null?Te:"anchored",y=(ot=g.bottomOffset)!=null?ot:"16px",E=g.collapsedMaxWidth,D=(Ke=g.expandedMaxWidth)!=null?Ke:"880px",F=(dt=g.expandedTopOffset)!=null?dt:"5vh",q=(pt=g.modalMaxWidth)!=null?pt:"880px",B=(Ie=g.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",xe="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",ne=ve.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",Je){let Le=Je.style;Le.bottom=y,Le.width=E!=null?E:""}if(c&&b!=="fullscreen"){if(b==="modal"){ne.top="50%",ne.left="50%",ne.transform="translate(-50%, -50%)",ne.bottom="auto",ne.right="auto",ne.width=q,ne.maxWidth=xe,ne.maxHeight=B,ne.height=B;return}ne.left="50%",ne.transform="translateX(-50%)",ne.bottom=`calc(${y} + ${me})`,ne.top=F,ne.width=D,ne.maxWidth=xe}},mo=()=>{var B,xe,me,ne,Ee,_e,Te,ot;if(!O())return;if($()){let dt=(me=((xe=(B=r.launcher)==null?void 0:B.composerBar)!=null?xe:{}).expandedSize)!=null?me:"anchored",pt=H?"expanded":"collapsed";ve.dataset.state=pt,ve.dataset.expandedSize=dt,Je&&(Je.dataset.state=pt,Je.dataset.expandedSize=dt),ve.style.removeProperty("display"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),$a(H),z.style.display=H?"flex":"none",br(),H?(Na(),Oa()):(zs(),Vs()),zr();return}let c=gn(r),g=(ne=e.ownerDocument.defaultView)!=null?ne:window,b=(_e=(Ee=r.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?_e:640,y=(ot=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?ot:!0,E=g.innerWidth<=b,D=y&&E&&T,F=mr(r).reveal;H?(ve.style.removeProperty("display"),ve.style.display=c?"flex":"",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0"),fe.classList.add("persona-scale-100","persona-opacity-100"),nn?nn.element.style.display="none":rn&&(rn.style.display="none")):(c?c&&(F==="overlay"||F==="push")&&!D?(ve.style.removeProperty("display"),ve.style.display="flex",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.setProperty("display","none","important"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.display="",ve.classList.add("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100"),fe.classList.add("persona-scale-95","persona-opacity-0")),nn?nn.element.style.display=c?"none":"":rn&&(rn.style.display=c?"none":""))},Nt=(c,g="user")=>{var D,F;if(!O()||H===c)return;let b=H;H=c,mo();let y=(()=>{var Te,ot,Ke,dt,pt,Ie,Le,qe,Qe,Ct;let q=(ot=(Te=r.launcher)==null?void 0:Te.sidebarMode)!=null?ot:!1,B=(Ke=e.ownerDocument.defaultView)!=null?Ke:window,xe=(pt=(dt=r.launcher)==null?void 0:dt.mobileFullscreen)!=null?pt:!0,me=(Le=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Le:640,ne=B.innerWidth<=me,Ee=gn(r)&&xe&&ne,_e=$()&&((Ct=(Qe=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Qe.expandedSize)!=null?Ct:"fullscreen")==="fullscreen";return q||xe&&ne&&T||Ee||_e})();if(H&&y){if(!en){let q=e.getRootNode(),B=q instanceof ShadowRoot?q.host:e.closest(".persona-host");B&&(en=Al(B,(F=(D=r.launcher)==null?void 0:D.zIndex)!=null?F:Mn))}tn||(tn=Sl(e.ownerDocument))}else H||(en==null||en(),en=null,tn==null||tn(),tn=null);H&&(Xs(),ft()==="follow"?Rr(!0):Us());let E={open:H,source:g,timestamp:Date.now()};H&&!b?s.emit("widget:opened",E):!H&&b&&s.emit("widget:closed",E),s.emit("widget:state",{open:H,launcherEnabled:T,voiceActive:xt.active,streaming:_.isStreaming()})},ds=c=>{Yt(c?"stop":"send"),K&&(K.disabled=c),ar.buttons.forEach(g=>{g.disabled=c}),je.dataset.personaComposerStreaming=c?"true":"false",je.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},ps=()=>{xt.active||te&&te.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>ps(),200)});let Js=()=>{var b,y,E,D,F,q,B,xe,me,ne,Ee;nr.textContent=(y=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?y:"Hello \u{1F44B}",Tr.textContent=(D=(E=r.copy)==null?void 0:E.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",te.placeholder=(q=(F=r.copy)==null?void 0:F.inputPlaceholder)!=null?q:"How can I help...";let c=ue.querySelector("[data-persona-intro-card]");if(c){let _e=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;c.style.display=_e?"":"none",_e?(ue.classList.remove("persona-gap-3"),ue.classList.add("persona-gap-6")):(ue.classList.remove("persona-gap-6"),ue.classList.add("persona-gap-3"))}!((me=(xe=r.sendButton)==null?void 0:xe.useIcon)!=null&&me)&&!(_!=null&&_.isStreaming())&&(Ve.textContent=(Ee=(ne=r.copy)==null?void 0:ne.sendButtonLabel)!=null?Ee:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.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=>{m(g=>({...g,sessionId:c}))}});let cr=null,Xe=()=>{cr==null&&(cr=setInterval(()=>{let c=rt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(cr),cr=null;return}let g=Date.now();c.forEach(b=>{let y=Number(b.getAttribute("data-tool-elapsed"));y&&(b.textContent=Ga(g-y))})},100))};if(_=new vs(r,{onMessagesChanged(c){var y;Ho(rt,c,Me),Xe(),_&&(c.some(D=>D.role==="user")?ar.render([],_,te,c):ar.render(r.suggestionChips,_,te,c,r.suggestionChipsConfig)),Rr(!Lr),Da(c);let g=[...c].reverse().find(E=>E.role==="user");c.length===0&&Ro(),!os||Wo?(os=!0,ss=(y=g==null?void 0:g.id)!=null?y:null):g&&g.id!==ss&&(ss=g.id,Ba(g.id));let b=xt.lastUserMessageId;g&&g.id!==b&&(xt.lastUserMessageId=g.id,s.emit("user:message",g)),xt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),ls(c),zr()},onStatusChanged(c){var y;let g=(y=r.statusIndicator)!=null?y:{};Ze(ln,(E=>{var D,F,q,B;return E==="idle"?(D=g.idleText)!=null?D:En.idle:E==="connecting"?(F=g.connectingText)!=null?F:En.connecting:E==="connected"?(q=g.connectedText)!=null?q:En.connected:E==="error"?(B=g.errorText)!=null?B:En.error:En[E]})(c),g,c)},onStreamingChanged(c){Lr=c,ds(c),_&&Ho(rt,_.getMessages(),Me),c||Rr(!0),zr()},onVoiceStatusChanged(c){var g,b;if(((b=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype")switch(c){case"listening":break;case"processing":go(),Zg();break;case"speaking":go(),ef();break;default:c==="idle"&&_.isBargeInActive()?(go(),Gs(),K==null||K.setAttribute("aria-label","End voice session")):(xt.active=!1,go(),lr("system"),Nn());break}},onArtifactsState(c){qn=c,Kn(),ls()}}),Pt.current=_,os=!0,((md=(ud=r.voiceRecognition)==null?void 0:ud.provider)==null?void 0:md.type)==="runtype")try{_.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&_.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(le||r.onSSEEvent)&&_.setSSEEventCallback((c,g)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,g),ge==null||ge.processEvent(c,g),le==null||le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,b,y;if(c){if(c.metadata&&(d=Kl(c.metadata),w.syncFromMetadata()),(g=c.messages)!=null&&g.length){Wo=!0;try{_.hydrateMessages(c.messages)}finally{Wo=!1}}(b=c.artifacts)!=null&&b.length&&_.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let A=()=>{var g,b,y;!$()||H||!((y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||y)||Nt(!0,"auto")},j=c=>{var E;if(c.preventDefault(),_.isStreaming()){_.cancel(),ge==null||ge.reset(),V==null||V.update();return}let g=te.value.trim(),b=(E=St==null?void 0:St.hasAttachments())!=null?E:!1;if(!g&&!b)return;A();let y;b&&(y=[],y.push(...St.getContentParts()),g&&y.push(oa(g))),te.value="",te.style.height="auto",G(),_.sendMessage(g,{contentParts:y}),b&&St.clearAttachments()},L=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Y={...hi},oe=!1,G=()=>{Y={...hi}},Pe=()=>_.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),Fe=c=>{if(!te)return;oe=!0,te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),oe=!1;let g=te.value.length;te.setSelectionRange(g,g)},lt=()=>{oe||G()},tt=c=>{if(te){if(L()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=te.selectionStart===0&&te.selectionEnd===0,b=om({direction:c.key==="ArrowUp"?"up":"down",history:Pe(),currentValue:te.value,atStart:g,state:Y});if(Y=b.state,b.handled){c.preventDefault(),b.value!==void 0&&Fe(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(_.isStreaming()){c.preventDefault();return}G(),c.preventDefault(),Ve.click()}}},Ht=c=>{c.key!=="Escape"||c.isComposing||_.isStreaming()&&c.composedPath().includes(z)&&(_.cancel(),ge==null||ge.reset(),V==null||V.update(),G(),c.preventDefault(),c.stopImmediatePropagation())},jt=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!St)return;let g=kb(c.clipboardData);g.length!==0&&(c.preventDefault(),await St.handleFiles(g))},$t=null,ct=!1,Et=null,Ue=null,Sn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,fn=(c="user")=>{var D,F,q,B,xe,me,ne;if(ct||_.isStreaming())return;let g=Sn();if(!g)return;$t=new g;let y=(F=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?F:2e3;$t.continuous=!0,$t.interimResults=!0,$t.lang="en-US";let E=te.value;$t.onresult=Ee=>{let _e="",Te="";for(let Ke=0;Ke<Ee.results.length;Ke++){let dt=Ee.results[Ke],pt=dt[0].transcript;dt.isFinal?_e+=pt+" ":Te=pt}let ot=E+_e+Te;te.value=ot,Et&&clearTimeout(Et),(_e||Te)&&(Et=window.setTimeout(()=>{let Ke=te.value.trim();Ke&&$t&&ct&&(Ut(),te.value="",te.style.height="auto",_.sendMessage(Ke,{viaVoice:!0}))},y))},$t.onerror=Ee=>{Ee.error!=="no-speech"&&Ut()},$t.onend=()=>{if(ct){let Ee=te.value.trim();Ee&&Ee!==E.trim()&&(te.value="",te.style.height="auto",_.sendMessage(Ee,{viaVoice:!0})),Ut()}};try{if($t.start(),ct=!0,xt.active=!0,c!=="system"&&(xt.manuallyDeactivated=!1),lr(c),Nn(),K){let Ee=(q=r.voiceRecognition)!=null?q:{};Ue={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(B=Ee.iconName)!=null?B:"mic",iconSize:parseFloat((ne=(me=Ee.iconSize)!=null?me:(xe=r.sendButton)==null?void 0:xe.size)!=null?ne:"40")||24};let _e=Ee.recordingBackgroundColor,Te=Ee.recordingIconColor,ot=Ee.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=_e!=null?_e:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let Ke=K.querySelector("svg");Ke&&Ke.setAttribute("stroke",Te)}ot&&(K.style.borderColor=ot),K.setAttribute("aria-label","Stop voice recognition")}}catch{Ut("system")}},Ut=(c="user")=>{if(ct){if(ct=!1,Et&&(clearTimeout(Et),Et=null),$t){try{$t.stop()}catch{}$t=null}if(xt.active=!1,lr(c),Nn(),K){if(K.classList.remove("persona-voice-recording"),Ue){K.style.backgroundColor=Ue.backgroundColor,K.style.color=Ue.color,K.style.borderColor=Ue.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",Ue.color||"currentColor"),Ue=null}K.setAttribute("aria-label","Start voice recognition")}}},wr=(c,g)=>{var dt,pt,Ie,Le,qe,Qe,Ct,P;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((dt=c==null?void 0:c.provider)==null?void 0:dt.type)==="runtype";if(!(b||y))return null;let D=h("div","persona-send-button-wrapper"),F=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let q=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",B=(Ie=g==null?void 0:g.size)!=null?Ie:"40px",xe=(Le=c==null?void 0:c.iconSize)!=null?Le:B,me=parseFloat(xe)||24,ne=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,Ee=(Qe=c==null?void 0:c.iconColor)!=null?Qe:g==null?void 0:g.textColor;F.style.width=xe,F.style.height=xe,F.style.minWidth=xe,F.style.minHeight=xe,F.style.fontSize="18px",F.style.lineHeight="1",Ee?F.style.color=Ee:F.style.color="var(--persona-text, #111827)";let Te=Ce(q,me,Ee||"currentColor",1.5);Te?F.appendChild(Te):F.textContent="\u{1F3A4}",ne?F.style.backgroundColor=ne:F.style.backgroundColor="",c!=null&&c.borderWidth&&(F.style.borderWidth=c.borderWidth,F.style.borderStyle="solid"),c!=null&&c.borderColor&&(F.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(F.style.paddingLeft=c.paddingX,F.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(F.style.paddingTop=c.paddingY,F.style.paddingBottom=c.paddingY),D.appendChild(F);let ot=(Ct=c==null?void 0:c.tooltipText)!=null?Ct:"Start voice recognition";if(((P=c==null?void 0:c.showTooltip)!=null?P:!1)&&ot){let Be=h("div","persona-send-button-tooltip");Be.textContent=ot,D.appendChild(Be)}return{micButton:F,micButtonWrapper:D}},sl=()=>{var g,b,y,E,D;if(!K||Ue)return;let c=(g=r.voiceRecognition)!=null?g:{};Ue={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((D=(E=c.iconSize)!=null?E:(y=r.sendButton)==null?void 0:y.size)!=null?D:"40")||24}},al=(c,g)=>{var D,F,q,B,xe;if(!K)return;let b=K.querySelector("svg");b&&b.remove();let y=(xe=Ue==null?void 0:Ue.iconSize)!=null?xe:parseFloat((B=(q=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?q:(F=r.sendButton)==null?void 0:F.size)!=null?B:"40")||24,E=Ce(c,y,g,1.5);E&&K.appendChild(E)},_a=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Gs=()=>{var E;if(!K)return;sl();let c=(E=r.voiceRecognition)!=null?E:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,y=c.recordingBorderColor;if(_a(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let D=K.querySelector("svg");D&&D.setAttribute("stroke",b)}y&&(K.style.borderColor=y),K.setAttribute("aria-label","Stop voice recognition")},Zg=()=>{var q,B,xe,me,ne,Ee,_e,Te;if(!K)return;sl();let c=(q=r.voiceRecognition)!=null?q:{},g=_.getVoiceInterruptionMode(),b=(B=c.processingIconName)!=null?B:"loader",y=(me=(xe=c.processingIconColor)!=null?xe:Ue==null?void 0:Ue.color)!=null?me:"",E=(Ee=(ne=c.processingBackgroundColor)!=null?ne:Ue==null?void 0:Ue.backgroundColor)!=null?Ee:"",D=(Te=(_e=c.processingBorderColor)!=null?_e:Ue==null?void 0:Ue.borderColor)!=null?Te:"";_a(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=E,K.style.borderColor=D;let F=y||"currentColor";K.style.color=F,al(b,F),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},ef=()=>{var xe,me,ne,Ee,_e,Te,ot,Ke,dt,pt,Ie,Le;if(!K)return;sl();let c=(xe=r.voiceRecognition)!=null?xe:{},g=_.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(me=c.speakingIconName)!=null?me:b,E=(Te=c.speakingIconColor)!=null?Te:g==="barge-in"?(Ee=(ne=c.recordingIconColor)!=null?ne:Ue==null?void 0:Ue.color)!=null?Ee:"":(_e=Ue==null?void 0:Ue.color)!=null?_e:"",D=(dt=c.speakingBackgroundColor)!=null?dt:g==="barge-in"?(ot=c.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":(Ke=Ue==null?void 0:Ue.backgroundColor)!=null?Ke:"",F=(Le=c.speakingBorderColor)!=null?Le:g==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(Ie=Ue==null?void 0:Ue.borderColor)!=null?Ie:"";_a(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=D,K.style.borderColor=F;let q=E||"currentColor";K.style.color=q,al(y,q);let B=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",B),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},go=()=>{var c,g,b;K&&(_a(),Ue&&(K.style.backgroundColor=(c=Ue.backgroundColor)!=null?c:"",K.style.color=(g=Ue.color)!=null?g:"",K.style.borderColor=(b=Ue.borderColor)!=null?b:"",al(Ue.iconName,Ue.color||"currentColor"),Ue=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},ja=()=>{var c,g;if(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=_.getVoiceStatus(),y=_.getVoiceInterruptionMode();if(y==="none"&&(b==="processing"||b==="speaking"))return;if(y==="cancel"&&(b==="processing"||b==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{xt.active=!1,xt.manuallyDeactivated=!0,Nn(),lr("user"),go()});return}_.toggleVoice().then(()=>{xt.active=_.isVoiceActive(),xt.manuallyDeactivated=!_.isVoiceActive(),Nn(),lr("user"),_.isVoiceActive()?Gs():go()});return}if(ct){let b=te.value.trim();xt.manuallyDeactivated=!0,Nn(),Ut("user"),b&&(te.value="",te.style.height="auto",_.sendMessage(b))}else xt.manuallyDeactivated=!1,Nn(),fn("user")};_n=ja,K&&(K.addEventListener("click",ja),bt.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),go()):Ut("system"),K&&K.removeEventListener("click",ja)}));let tf=s.on("assistant:complete",()=>{Ds&&(xt.active||xt.manuallyDeactivated||Ds==="assistant"&&!xt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!xt.active&&!xt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?_.toggleVoice().then(()=>{xt.active=_.isVoiceActive(),lr("auto"),_.isVoiceActive()&&Gs()}):fn("auto"))},600))});bt.push(tf);let nf=s.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});bt.push(nf);let us=()=>{Nt(!H,"user")},nn=null,rn=null;if(T&&!$()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>ha(r,us).element,onToggle:us});g&&(rn=g)}rn||(nn=ha(r,us))}nn?e.appendChild(nn.element):rn&&e.appendChild(rn),mo(),ar.render(r.suggestionChips,_,te,void 0,r.suggestionChipsConfig),Js(),ds(_.isStreaming()),ft()==="follow"?Rr(!0):Us(),Pa(),M&&(!T||$()?setTimeout(()=>ps(),0):H&&setTimeout(()=>ps(),200));let Xs=()=>{var B,xe,me,ne,Ee,_e,Te,ot,Ke,dt,pt,Ie,Le,qe,Qe,Ct,P,Be,Oe,he,_t,Ot;if($()){yn(),mo();return}let c=gn(r),g=(xe=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?xe:!1,b=c||g||((ne=(me=r.launcher)==null?void 0:me.fullHeight)!=null?ne:!1),y=(Ee=e.ownerDocument.defaultView)!=null?Ee:window,E=(Te=(_e=r.launcher)==null?void 0:_e.mobileFullscreen)!=null?Te:!0,D=(Ke=(ot=r.launcher)==null?void 0:ot.mobileBreakpoint)!=null?Ke:640,F=y.innerWidth<=D,q=E&&F&&T;try{if(q){br(),xo(e,r);return}if(k&&(k=!1,br(),xo(e,r)),!T&&!c){fe.style.height="",fe.style.width="";return}if(!g&&!c){let Xt=(pt=(dt=r==null?void 0:r.launcher)==null?void 0:dt.width)!=null?pt:r==null?void 0:r.launcherWidth,At=Xt!=null?Xt:er;fe.style.width=At,fe.style.maxWidth=At}if(kr(),!b){let Xt=y.innerHeight,At=64,Vt=(Le=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Le:0,Qn=Math.max(200,Xt-At),sn=Math.min(640,Qn),Ye=Math.max(200,sn-Vt);fe.style.height=`${Ye}px`}}finally{if(yn(),mo(),H&&T){let At=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((Ct=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?Ct:640),Vt=(Be=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Be:!1,Qn=(he=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?he:!0,sn=gn(r)&&Qn&&At,Ye=Vt||Qn&&At&&T||sn;if(Ye&&!tn){let Wt=e.getRootNode(),pn=Wt instanceof ShadowRoot?Wt.host:e.closest(".persona-host");pn&&!en&&(en=Al(pn,(Ot=(_t=r.launcher)==null?void 0:_t.zIndex)!=null?Ot:Mn)),tn=Sl(e.ownerDocument)}else Ye||(en==null||en(),en=null,tn==null||tn(),tn=null)}}};Xs();let pc=(gd=e.ownerDocument.defaultView)!=null?gd:window;if(pc.addEventListener("resize",Xs),bt.push(()=>pc.removeEventListener("resize",Xs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yn()});c.observe(je),bt.push(()=>c.disconnect())}Xn=ue.scrollTop;let uc=Xr(ue),rf=()=>{let c=ue.getRootNode(),g=typeof c.getSelection=="function"?c.getSelection():null;return g!=null?g:ue.ownerDocument.getSelection()},il=()=>dm(rf(),ue),mc=()=>{let c=ue.scrollTop,g=Xr(ue),b=g<uc;if(uc=g,ft()!=="follow"){Xn=c,On();return}let{action:y,nextLastScrollTop:E}=yi({following:Gn.isFollowing(),currentScrollTop:c,lastScrollTop:Xn,nearBottom:Xo(ue,as),userScrollThreshold:ka,isAutoScrolling:vr||Io||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Xn=E,y==="resume"){il()||Wr();return}y==="pause"&&cs()};if(ue.addEventListener("scroll",mc,{passive:!0}),bt.push(()=>ue.removeEventListener("scroll",mc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Ha()});c.observe(rt),c.observe(ue),bt.push(()=>c.disconnect())}let gc=()=>{ft()==="follow"&&Gn.isFollowing()&&il()&&cs()},fc=ue.ownerDocument;fc.addEventListener("selectionchange",gc),bt.push(()=>{fc.removeEventListener("selectionchange",gc)});let hc=c=>{if(ft()!=="follow")return;let g=xi({following:Gn.isFollowing(),deltaY:c.deltaY,nearBottom:Xo(ue,as),resumeWhenNearBottom:!0});g==="pause"?cs():g==="resume"&&!il()&&Wr()};ue.addEventListener("wheel",hc,{passive:!0}),bt.push(()=>ue.removeEventListener("wheel",hc)),et.addEventListener("click",()=>{Ro(),ue.scrollTop=ue.scrollHeight,Xn=ue.scrollTop,Wr(),Rr(!0),On()}),bt.push(()=>et.remove()),bt.push(()=>{Os(),Ro()});let bc=()=>{R&&(ir&&(R.removeEventListener("click",ir),ir=null),O()?(R.style.display="",ir=()=>{Nt(!1,"user")},R.addEventListener("click",ir)):R.style.display="none")};bc(),(()=>{let{clearChatButton:c}=De;c&&c.addEventListener("click",()=>{_.clearMessages(),_r.clear(),Wr(),Eo(De.composerOverlay);try{localStorage.removeItem(Hs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Hs}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Hs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},w.syncFromMetadata(),le==null||le.clear(),ge==null||ge.reset(),V==null||V.update()})})(),Bt&&Bt.addEventListener("submit",j),te==null||te.addEventListener("keydown",tt),te==null||te.addEventListener("input",lt),te==null||te.addEventListener("paste",jt);let yc=(fd=e.ownerDocument)!=null?fd:document;yc.addEventListener("keydown",Ht,!0);let xc="persona-attachment-drop-active",Qs=0,ll=()=>{Qs=0,z.classList.remove(xc)},ms=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&St!==null},vc=c=>{!Gi(c.dataTransfer)||!ms()||(Qs++,Qs===1&&z.classList.add(xc))},wc=c=>{!Gi(c.dataTransfer)||!ms()||(Qs--,Qs<=0&&ll())},Cc=c=>{!Gi(c.dataTransfer)||!ms()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Ac=c=>{var b;if(!Gi(c.dataTransfer)||!ms())return;c.preventDefault(),c.stopPropagation(),ll();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&St.handleFiles(g)},fo=!0;z.addEventListener("dragenter",vc,fo),z.addEventListener("dragleave",wc,fo),e.addEventListener("dragover",Cc,fo),e.addEventListener("drop",Ac,fo);let Ua=e.ownerDocument,Sc=c=>{ms()&&c.preventDefault()},Tc=c=>{ms()&&c.preventDefault()};Ua.addEventListener("dragover",Sc),Ua.addEventListener("drop",Tc),bt.push(()=>{Bt&&Bt.removeEventListener("submit",j),te==null||te.removeEventListener("keydown",tt),te==null||te.removeEventListener("input",lt),te==null||te.removeEventListener("paste",jt),yc.removeEventListener("keydown",Ht,!0)}),bt.push(()=>{z.removeEventListener("dragenter",vc,fo),z.removeEventListener("dragleave",wc,fo),e.removeEventListener("dragover",Cc,fo),e.removeEventListener("drop",Ac,fo),Ua.removeEventListener("dragover",Sc),Ua.removeEventListener("drop",Tc),ll()}),bt.push(()=>{_.cancel()}),nn?bt.push(()=>{nn==null||nn.destroy()}):rn&&bt.push(()=>{rn==null||rn.remove()});let dn={update(c){var Hr,mn,Wn,ur,Oo,Fo,qa,Ys,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Od,Fd,$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,bp,yp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Op,Fp,$p,_p,jp,Up,qp,zp,Vp,Kp,Jp,Gp,Xp,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,bu,yu,xu,vu;let g=r.toolCall,b=r.messageActions,y=(Hr=r.layout)==null?void 0:Hr.messages,E=r.colorScheme,D=r.loadingIndicator,F=r.iterationDisplay,q=(mn=r.features)==null?void 0:mn.showReasoning,B=(Wn=r.features)==null?void 0:Wn.showToolCalls,xe=(ur=r.features)==null?void 0:ur.toolCallDisplay,me=(Oo=r.features)==null?void 0:Oo.reasoningDisplay;r={...r,...c},br(),xo(e,r),$i(e,r),_i(e,r),Kn(),r.colorScheme!==E&&io();let ne=Aa.getForInstance(r.plugins);o.length=0,o.push(...ne),T=(qa=(Fo=r.launcher)==null?void 0:Fo.enabled)!=null?qa:!0,N=(Cd=(Ys=r.launcher)==null?void 0:Ys.autoExpand)!=null?Cd:!1,ze=(Sd=(Ad=r.features)==null?void 0:Ad.showReasoning)!=null?Sd:!0,Ae=(Ed=(Td=r.features)==null?void 0:Td.showToolCalls)!=null?Ed:!0,be=(kd=(Md=r.features)==null?void 0:Md.scrollToBottom)!=null?kd:{};let Ee=ft();ke=(Pd=(Ld=r.features)==null?void 0:Ld.scrollBehavior)!=null?Pd:{},Ee!==ft()&&(Ro(),Wr()),Er(),On();let _e=We;if(We=(Wd=(Id=r.features)==null?void 0:Id.showEventStreamToggle)!=null?Wd:!1,We&&!_e){if(le||(Q=new wa(de),le=new va(re,Q),ge=ge!=null?ge:new Ca,Q.open().then(()=>le==null?void 0:le.restore()).catch(()=>{}),_.setSSEEventCallback((X,Mt)=>{var qt;(qt=r.onSSEEvent)==null||qt.call(r,X,Mt),ge==null||ge.processEvent(X,Mt),le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(Mt)})})),!wt&&$e){let X=(Hd=(Rd=r.features)==null?void 0:Rd.eventStream)==null?void 0:Hd.classNames,Mt="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"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");wt=h("button",Mt),wt.style.width="28px",wt.style.height="28px",wt.style.color=Hn.actionIconColor,wt.type="button",wt.setAttribute("aria-label","Event Stream"),wt.title="Event Stream";let qt=Ce("activity","18px","currentColor",1.5);qt&&wt.appendChild(qt);let gt=De.clearChatButtonWrapper,Rt=De.closeButtonWrapper,hn=gt||Rt;hn&&hn.parentNode===$e?$e.insertBefore(wt,hn):$e.appendChild(wt),wt.addEventListener("click",()=>{se?hr():Nr()})}}else!We&&_e&&(hr(),wt&&(wt.remove(),wt=null),le==null||le.clear(),Q==null||Q.destroy(),le=null,Q=null,ge==null||ge.reset(),ge=null);if(((Bd=r.launcher)==null?void 0:Bd.enabled)===!1&&nn&&(nn.destroy(),nn=null),((Dd=r.launcher)==null?void 0:Dd.enabled)===!1&&rn&&(rn.remove(),rn=null),((Nd=r.launcher)==null?void 0:Nd.enabled)!==!1&&!nn&&!rn){let X=o.find(Mt=>Mt.renderLauncher);if(X!=null&&X.renderLauncher){let Mt=X.renderLauncher({config:r,defaultRenderer:()=>ha(r,us).element,onToggle:us});Mt&&(rn=Mt,e.appendChild(rn))}rn||(nn=ha(r,us),e.appendChild(nn.element))}nn&&nn.update(r),Ne&&((Od=r.launcher)==null?void 0:Od.title)!==void 0&&(Ne.textContent=r.launcher.title),Ge&&((Fd=r.launcher)==null?void 0:Fd.subtitle)!==void 0&&(Ge.textContent=r.launcher.subtitle);let Te=($d=r.layout)==null?void 0:$d.header;if((Te==null?void 0:Te.layout)!==S&&$e){let X=Te?Ss(r,Te,{showClose:O(),onClose:()=>Nt(!1,"user")}):Qr({config:r,showClose:O(),onClose:()=>Nt(!1,"user")});$e.replaceWith(X.header),$e=X.header,pe=X.iconHolder,Ne=X.headerTitle,Ge=X.headerSubtitle,R=X.closeButton,S=Te==null?void 0:Te.layout}else if(Te&&(pe&&(pe.style.display=Te.showIcon===!1?"none":""),Ne&&(Ne.style.display=Te.showTitle===!1?"none":""),Ge&&(Ge.style.display=Te.showSubtitle===!1?"none":""),R&&(R.style.display=Te.showCloseButton===!1?"none":""),De.clearChatButtonWrapper)){let X=Te.showClearChat;if(X!==void 0){De.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:Mt}=De;Mt&&!Mt.classList.contains("persona-absolute")&&(X?Mt.classList.remove("persona-ml-auto"):Mt.classList.add("persona-ml-auto"))}}let Ke=((_d=r.layout)==null?void 0:_d.showHeader)!==!1;$e&&($e.style.display=Ke?"":"none");let dt=((jd=r.layout)==null?void 0:jd.showFooter)!==!1;je&&(je.style.display=dt?"":"none"),yn(),On(),T!==W?T?Nt(N,"auto"):(H=!0,mo()):N!==I&&Nt(N,"auto"),I=N,W=T,Xs(),bc();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(g),qe=JSON.stringify(r.messageActions)!==JSON.stringify(b),Qe=JSON.stringify((Ud=r.layout)==null?void 0:Ud.messages)!==JSON.stringify(y),Ct=((qd=r.loadingIndicator)==null?void 0:qd.render)!==(D==null?void 0:D.render)||((zd=r.loadingIndicator)==null?void 0:zd.renderIdle)!==(D==null?void 0:D.renderIdle)||((Vd=r.loadingIndicator)==null?void 0:Vd.showBubble)!==(D==null?void 0:D.showBubble),P=r.iterationDisplay!==F,Be=((Jd=(Kd=r.features)==null?void 0:Kd.showReasoning)!=null?Jd:!0)!==(q!=null?q:!0)||((Xd=(Gd=r.features)==null?void 0:Gd.showToolCalls)!=null?Xd:!0)!==(B!=null?B:!0)||JSON.stringify((Qd=r.features)==null?void 0:Qd.toolCallDisplay)!==JSON.stringify(xe)||JSON.stringify((Yd=r.features)==null?void 0:Yd.reasoningDisplay)!==JSON.stringify(me);(Le||qe||Qe||Ct||P||Be)&&_&&(Bs++,Ho(rt,_.getMessages(),Me));let he=(Zd=r.launcher)!=null?Zd:{},_t=(ep=he.headerIconHidden)!=null?ep:!1,Ot=(np=(tp=r.layout)==null?void 0:tp.header)==null?void 0:np.showIcon,Xt=_t||Ot===!1,At=he.headerIconName,Vt=(rp=he.headerIconSize)!=null?rp:"48px";if(pe){let X=z.querySelector(".persona-border-b-persona-divider"),Mt=X==null?void 0:X.querySelector(".persona-flex-col");if(Xt)pe.style.display="none",X&&Mt&&!X.contains(Mt)&&X.insertBefore(Mt,X.firstChild);else{if(pe.style.display="",pe.style.height=Vt,pe.style.width=Vt,X&&Mt&&(X.contains(pe)?pe.nextSibling!==Mt&&(pe.remove(),X.insertBefore(pe,Mt)):X.insertBefore(pe,Mt)),At){let gt=parseFloat(Vt)||24,Rt=Ce(At,gt*.6,"#ffffff",2);Rt?pe.replaceChildren(Rt):pe.textContent=(op=he.agentIconText)!=null?op:"\u{1F4AC}"}else if(he.iconUrl){let gt=pe.querySelector("img");if(gt)gt.src=he.iconUrl,gt.style.height=Vt,gt.style.width=Vt;else{let Rt=document.createElement("img");Rt.src=he.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=Vt,Rt.style.width=Vt,pe.replaceChildren(Rt)}}else{let gt=pe.querySelector("svg"),Rt=pe.querySelector("img");(gt||Rt)&&pe.replaceChildren(),pe.textContent=(sp=he.agentIconText)!=null?sp:"\u{1F4AC}"}let qt=pe.querySelector("img");qt&&(qt.style.height=Vt,qt.style.width=Vt)}}let Qn=(ip=(ap=r.layout)==null?void 0:ap.header)==null?void 0:ip.showTitle,sn=(cp=(lp=r.layout)==null?void 0:lp.header)==null?void 0:cp.showSubtitle;if(Ne&&(Ne.style.display=Qn===!1?"none":""),Ge&&(Ge.style.display=sn===!1?"none":""),R){((pp=(dp=r.layout)==null?void 0:dp.header)==null?void 0:pp.showCloseButton)===!1?R.style.display="none":R.style.display="";let Mt=(up=he.closeButtonSize)!=null?up:"32px",qt=(mp=he.closeButtonPlacement)!=null?mp:"inline";R.style.height=Mt,R.style.width=Mt;let{closeButtonWrapper:gt}=De,Rt=qt==="top-right",hn=gt==null?void 0:gt.classList.contains("persona-absolute");if(gt&&Rt!==hn)if(gt.remove(),Rt)gt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",z.style.position="relative",z.appendChild(gt);else{let ht=(fp=(gp=he.clearChat)==null?void 0:gp.placement)!=null?fp:"inline",bn=(bp=(hp=he.clearChat)==null?void 0:hp.enabled)!=null?bp:!0;gt.className=bn&&ht==="inline"?"":"persona-ml-auto";let $n=z.querySelector(".persona-border-b-persona-divider");$n&&$n.appendChild(gt)}if(R.style.color=he.closeButtonColor||Hn.actionIconColor,he.closeButtonBackgroundColor?(R.style.backgroundColor=he.closeButtonBackgroundColor,R.classList.remove("hover:persona-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let ht=he.closeButtonBorderWidth||"0px",bn=he.closeButtonBorderColor||"transparent";R.style.border=`${ht} solid ${bn}`,R.classList.remove("persona-border-none")}else R.style.border="",R.classList.add("persona-border-none");he.closeButtonBorderRadius?(R.style.borderRadius=he.closeButtonBorderRadius,R.classList.remove("persona-rounded-full")):(R.style.borderRadius="",R.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(R.style.paddingLeft=he.closeButtonPaddingX,R.style.paddingRight=he.closeButtonPaddingX):(R.style.paddingLeft="",R.style.paddingRight=""),he.closeButtonPaddingY?(R.style.paddingTop=he.closeButtonPaddingY,R.style.paddingBottom=he.closeButtonPaddingY):(R.style.paddingTop="",R.style.paddingBottom="");let Tn=(yp=he.closeButtonIconName)!=null?yp:"x",Cr=(xp=he.closeButtonIconText)!=null?xp:"\xD7";R.innerHTML="";let Rn=Ce(Tn,"28px","currentColor",1);Rn?R.appendChild(Rn):R.textContent=Cr;let on=(vp=he.closeButtonTooltipText)!=null?vp:"Close chat",Zn=(wp=he.closeButtonShowTooltip)!=null?wp:!0;if(R.setAttribute("aria-label",on),gt&&(gt._cleanupTooltip&&(gt._cleanupTooltip(),delete gt._cleanupTooltip),Zn&&on)){let ht=null,bn=()=>{if(ht||!R)return;let $o=R.ownerDocument,Zs=$o.body;if(!Zs)return;ht=Br($o,"div","persona-clear-chat-tooltip"),ht.textContent=on;let ea=Br($o,"div");ea.className="persona-clear-chat-tooltip-arrow",ht.appendChild(ea);let _o=R.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(vo),ht.style.left=`${_o.left+_o.width/2}px`,ht.style.top=`${_o.top-8}px`,ht.style.transform="translate(-50%, -100%)",Zs.appendChild(ht)},$n=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};gt.addEventListener("mouseenter",bn),gt.addEventListener("mouseleave",$n),R.addEventListener("focus",bn),R.addEventListener("blur",$n),gt._cleanupTooltip=()=>{$n(),gt&&(gt.removeEventListener("mouseenter",bn),gt.removeEventListener("mouseleave",$n)),R&&(R.removeEventListener("focus",bn),R.removeEventListener("blur",$n))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Wt}=De;if(Ye){let X=(Cp=he.clearChat)!=null?Cp:{},Mt=(Ap=X.enabled)!=null?Ap:!0,qt=(Tp=(Sp=r.layout)==null?void 0:Sp.header)==null?void 0:Tp.showClearChat,gt=qt!==void 0?qt:Mt,Rt=(Ep=X.placement)!=null?Ep:"inline";if(Wt){Wt.style.display=gt?"":"none";let{closeButtonWrapper:hn}=De;!$()&&hn&&!hn.classList.contains("persona-absolute")&&(gt?hn.classList.remove("persona-ml-auto"):hn.classList.add("persona-ml-auto"));let Tn=Rt==="top-right",Cr=Wt.classList.contains("persona-absolute");if(!$()&&Tn!==Cr&&gt){if(Wt.remove(),Tn)Wt.className="persona-absolute persona-top-4 persona-z-50",Wt.style.right="48px",z.style.position="relative",z.appendChild(Wt);else{Wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wt.style.right="";let on=z.querySelector(".persona-border-b-persona-divider"),Zn=De.closeButtonWrapper;on&&Zn&&Zn.parentElement===on?on.insertBefore(Wt,Zn):on&&on.appendChild(Wt)}let Rn=De.closeButtonWrapper;Rn&&!Rn.classList.contains("persona-absolute")&&(Tn?Rn.classList.add("persona-ml-auto"):Rn.classList.remove("persona-ml-auto"))}}if(gt){if(!$()){let ht=(Mp=X.size)!=null?Mp:"32px";Ye.style.height=ht,Ye.style.width=ht}let hn=(kp=X.iconName)!=null?kp:"refresh-cw",Tn=(Lp=X.iconColor)!=null?Lp:"";Ye.style.color=Tn||Hn.actionIconColor,Ye.innerHTML="";let Cr=$()?"14px":"20px",Rn=Ce(hn,Cr,"currentColor",2);if(Rn&&Ye.appendChild(Rn),X.backgroundColor?(Ye.style.backgroundColor=X.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let ht=X.borderWidth||"0px",bn=X.borderColor||"transparent";Ye.style.border=`${ht} solid ${bn}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");X.borderRadius?(Ye.style.borderRadius=X.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),X.paddingX?(Ye.style.paddingLeft=X.paddingX,Ye.style.paddingRight=X.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),X.paddingY?(Ye.style.paddingTop=X.paddingY,Ye.style.paddingBottom=X.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let on=(Pp=X.tooltipText)!=null?Pp:"Clear chat",Zn=(Ip=X.showTooltip)!=null?Ip:!0;if(Ye.setAttribute("aria-label",on),Wt&&(Wt._cleanupTooltip&&(Wt._cleanupTooltip(),delete Wt._cleanupTooltip),Zn&&on)){let ht=null,bn=()=>{if(ht||!Ye)return;let $o=Ye.ownerDocument,Zs=$o.body;if(!Zs)return;ht=Br($o,"div","persona-clear-chat-tooltip"),ht.textContent=on;let ea=Br($o,"div");ea.className="persona-clear-chat-tooltip-arrow",ht.appendChild(ea);let _o=Ye.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(vo),ht.style.left=`${_o.left+_o.width/2}px`,ht.style.top=`${_o.top-8}px`,ht.style.transform="translate(-50%, -100%)",Zs.appendChild(ht)},$n=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};Wt.addEventListener("mouseenter",bn),Wt.addEventListener("mouseleave",$n),Ye.addEventListener("focus",bn),Ye.addEventListener("blur",$n),Wt._cleanupTooltip=()=>{$n(),Wt&&(Wt.removeEventListener("mouseenter",bn),Wt.removeEventListener("mouseleave",$n)),Ye&&(Ye.removeEventListener("focus",bn),Ye.removeEventListener("blur",$n))}}}}let pn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Sa],pr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ts.message,ts.messageAndClick];w=Ta({parsers:pn,handlers:pr,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Me=pg(r,w,ce),_.updateConfig(r),Ho(rt,_.getMessages(),Me),ar.render(r.suggestionChips,_,te,void 0,r.suggestionChipsConfig),Js(),ds(_.isStreaming());let Yn=((Wp=r.voiceRecognition)==null?void 0:Wp.enabled)===!0,Bo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Do=((Hp=(Rp=r.voiceRecognition)==null?void 0:Rp.provider)==null?void 0:Hp.type)==="runtype";if(Yn&&(Bo||Do))if(!K||!vt){let X=wr(r.voiceRecognition,r.sendButton);X&&(K=X.micButton,vt=X.micButtonWrapper,Jt.insertBefore(vt,Bn),K.addEventListener("click",ja),K.disabled=_.isStreaming())}else{let X=(Bp=r.voiceRecognition)!=null?Bp:{},Mt=(Dp=r.sendButton)!=null?Dp:{},qt=(Np=X.iconName)!=null?Np:"mic",gt=(Op=Mt.size)!=null?Op:"40px",Rt=(Fp=X.iconSize)!=null?Fp:gt,hn=parseFloat(Rt)||24;K.style.width=Rt,K.style.height=Rt,K.style.minWidth=Rt,K.style.minHeight=Rt;let Tn=(_p=($p=X.iconColor)!=null?$p:Mt.textColor)!=null?_p:"currentColor";K.innerHTML="";let Cr=Ce(qt,hn,Tn,2);Cr?K.appendChild(Cr):K.textContent="\u{1F3A4}";let Rn=(jp=X.backgroundColor)!=null?jp:Mt.backgroundColor;Rn?K.style.backgroundColor=Rn:K.style.backgroundColor="",Tn?K.style.color=Tn:K.style.color="var(--persona-text, #111827)",X.borderWidth?(K.style.borderWidth=X.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),X.borderColor?K.style.borderColor=X.borderColor:K.style.borderColor="",X.paddingX?(K.style.paddingLeft=X.paddingX,K.style.paddingRight=X.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),X.paddingY?(K.style.paddingTop=X.paddingY,K.style.paddingBottom=X.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let on=vt==null?void 0:vt.querySelector(".persona-send-button-tooltip"),Zn=(Up=X.tooltipText)!=null?Up:"Start voice recognition";if(((qp=X.showTooltip)!=null?qp:!1)&&Zn)if(on)on.textContent=Zn,on.style.display="";else{let bn=document.createElement("div");bn.className="persona-send-button-tooltip",bn.textContent=Zn,vt==null||vt.insertBefore(bn,K)}else on&&(on.style.display="none");vt.style.display="",K.disabled=_.isStreaming()}else K&&vt&&(vt.style.display="none",((Vp=(zp=r.voiceRecognition)==null?void 0:zp.provider)==null?void 0:Vp.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():ct&&Ut());if(((Kp=r.attachments)==null?void 0:Kp.enabled)===!0)if(!we||!it){let X=(Jp=r.attachments)!=null?Jp:{},qt=(Xp=((Gp=r.sendButton)!=null?Gp:{}).size)!=null?Xp:"40px";nt||(nt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),nt.style.display="none",Bt.insertBefore(nt,te)),ie||(ie=document.createElement("input"),ie.type="file",ie.accept=((Qp=X.allowedTypes)!=null?Qp:Gr).join(","),ie.multiple=((Yp=X.maxFiles)!=null?Yp:4)>1,ie.style.display="none",ie.setAttribute("aria-label","Attach files"),Bt.insertBefore(ie,te)),we=h("div","persona-send-button-wrapper"),it=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",(Zp=X.buttonTooltipText)!=null?Zp:"Attach file");let gt=(eu=X.buttonIconName)!=null?eu:"paperclip",Rt=qt,hn=parseFloat(Rt)||40,Tn=Math.round(hn*.6);it.style.width=Rt,it.style.height=Rt,it.style.minWidth=Rt,it.style.minHeight=Rt,it.style.fontSize="18px",it.style.lineHeight="1",it.style.backgroundColor="transparent",it.style.color="var(--persona-primary, #111827)",it.style.border="none",it.style.borderRadius="6px",it.style.transition="background-color 0.15s ease",it.addEventListener("mouseenter",()=>{it.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),it.addEventListener("mouseleave",()=>{it.style.backgroundColor="transparent"});let Cr=Ce(gt,Tn,"currentColor",1.5);Cr?it.appendChild(Cr):it.textContent="\u{1F4CE}",it.addEventListener("click",Zn=>{Zn.preventDefault(),ie==null||ie.click()}),we.appendChild(it);let Rn=(tu=X.buttonTooltipText)!=null?tu:"Attach file",on=h("div","persona-send-button-tooltip");on.textContent=Rn,we.appendChild(on),It.append(we),!St&&ie&&nt&&(St=Go.fromConfig(X),St.setPreviewsContainer(nt),ie.addEventListener("change",async()=>{St&&(ie!=null&&ie.files)&&(await St.handleFileSelect(ie.files),ie.value="")})),z.querySelector(".persona-attachment-drop-overlay")||z.appendChild(ug(X.dropOverlay))}else{we.style.display="";let X=(nu=r.attachments)!=null?nu:{};ie&&(ie.accept=((ru=X.allowedTypes)!=null?ru:Gr).join(","),ie.multiple=((ou=X.maxFiles)!=null?ou:4)>1),St&&St.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else we&&(we.style.display="none"),St&&St.clearAttachments(),(su=z.querySelector(".persona-attachment-drop-overlay"))==null||su.remove();let Qt=(au=r.sendButton)!=null?au:{},No=(iu=Qt.useIcon)!=null?iu:!1,ho=(lu=Qt.iconText)!=null?lu:"\u2191",bo=Qt.iconName,Vr=(cu=Qt.tooltipText)!=null?cu:"Send message",at=(du=Qt.showTooltip)!=null?du:!1,vn=(pu=Qt.size)!=null?pu:"40px",In=Qt.backgroundColor,an=Qt.textColor;if(No){if(Ve.style.width=vn,Ve.style.height=vn,Ve.style.minWidth=vn,Ve.style.minHeight=vn,Ve.style.fontSize="18px",Ve.style.lineHeight="1",Ve.innerHTML="",an?Ve.style.color=an:Ve.style.color="var(--persona-button-primary-fg, #ffffff)",bo){let X=parseFloat(vn)||24,Mt=(an==null?void 0:an.trim())||"currentColor",qt=Ce(bo,X,Mt,2);qt?Ve.appendChild(qt):Ve.textContent=ho}else Ve.textContent=ho;Ve.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",In?(Ve.style.backgroundColor=In,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=(mu=(uu=r.copy)==null?void 0:uu.sendButtonLabel)!=null?mu:"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.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",In?(Ve.style.backgroundColor=In,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),an?Ve.style.color=an:Ve.classList.add("persona-text-white");Qt.borderWidth?(Ve.style.borderWidth=Qt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),Qt.borderColor?Ve.style.borderColor=Qt.borderColor:Ve.style.borderColor="",Qt.paddingX?(Ve.style.paddingLeft=Qt.paddingX,Ve.style.paddingRight=Qt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),Qt.paddingY?(Ve.style.paddingTop=Qt.paddingY,Ve.style.paddingBottom=Qt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let ut=Bn==null?void 0:Bn.querySelector(".persona-send-button-tooltip");if(at&&Vr)if(ut)ut.textContent=Vr,ut.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=Vr,Bn==null||Bn.insertBefore(X,Ve)}else ut&&(ut.style.display="none");let yt=(yu=(gu=r.layout)==null?void 0:gu.contentMaxWidth)!=null?yu:$()?(bu=(hu=(fu=r.launcher)==null?void 0:fu.composerBar)==null?void 0:hu.contentMaxWidth)!=null?bu:"720px":void 0;yt?(rt.style.maxWidth=yt,rt.style.marginLeft="auto",rt.style.marginRight="auto",rt.style.width="100%",Bt&&(Bt.style.maxWidth=yt,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),kt&&(kt.style.maxWidth=yt,kt.style.marginLeft="auto",kt.style.marginRight="auto")):(rt.style.maxWidth="",rt.style.marginLeft="",rt.style.marginRight="",rt.style.width="",Bt&&(Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight=""),kt&&(kt.style.maxWidth="",kt.style.marginLeft="",kt.style.marginRight=""));let mt=(xu=r.statusIndicator)!=null?xu:{},Fn=(vu=mt.visible)!=null?vu:!0;if(ln.style.display=Fn?"":"none",_){let X=_.getStatus();Ze(ln,(qt=>{var gt,Rt,hn,Tn;return qt==="idle"?(gt=mt.idleText)!=null?gt:En.idle:qt==="connecting"?(Rt=mt.connectingText)!=null?Rt:En.connecting:qt==="connected"?(hn=mt.connectedText)!=null?hn:En.connected:qt==="error"?(Tn=mt.errorText)!=null?Tn:En.error:En[qt]})(X),mt,X)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let un=mt.align==="left"?"persona-text-left":mt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(un)},open(){O()&&Nt(!0,"api")},close(){O()&&Nt(!1,"api")},toggle(){O()&&Nt(!H,"api")},clearChat(){Ln=!1,_.clearMessages(),_r.clear(),Wr();try{localStorage.removeItem(Hs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Hs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Hs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},w.syncFromMetadata(),le==null||le.clear(),ge==null||ge.reset(),V==null||V.update()},setMessage(c){return!te||_.isStreaming()?!1:(!H&&O()&&Nt(!0,"system"),te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let g=(c==null?void 0:c.trim())||te.value.trim();return g?(!H&&O()&&Nt(!0,"system"),te.value="",te.style.height="auto",_.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return _.isStreaming()?!1:((b=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(_.isVoiceActive()||(!H&&O()&&Nt(!0,"system"),xt.manuallyDeactivated=!1,Nn(),_.toggleVoice().then(()=>{xt.active=_.isVoiceActive(),lr("user"),_.isVoiceActive()&&Gs()})),!0):ct?!0:Sn()?(!H&&O()&&Nt(!0,"system"),xt.manuallyDeactivated=!1,Nn(),fn("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{xt.active=!1,xt.manuallyDeactivated=!0,Nn(),lr("user"),go()}),!0):!1:ct?(xt.manuallyDeactivated=!0,Nn(),Ut("user"),!0):!1},injectMessage(c){return!H&&O()&&Nt(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!H&&O()&&Nt(!0,"system");let g=_.injectAssistantMessage(c);return U&&(U=!1,J&&(clearTimeout(J),J=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(c){return!H&&O()&&Nt(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!H&&O()&&Nt(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!H&&O()&&Nt(!0,"system"),_.injectMessageBatch(c)},injectComponentDirective(c){return!H&&O()&&Nt(!0,"system"),_.injectComponentDirective(c)},injectTestMessage(c){!H&&O()&&Nt(!0,"system"),_.injectTestEvent(c)},async connectStream(c,g){return _.connectStream(c,g)},__pushEventStreamEvent(c){le&&(ge==null||ge.processEvent(c.type,c.payload),le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!We||!le||Nr()},hideEventStream(){se&&hr()},isEventStreamVisible(){return se},showArtifacts(){fr(r)&&(Ln=!1,Kn(),Tt==null||Tt.setMobileOpen(!0))},hideArtifacts(){fr(r)&&(Ln=!0,Kn())},upsertArtifact(c){return fr(r)?(Ln=!1,_.upsertArtifact(c)):null},selectArtifact(c){fr(r)&&_.selectArtifact(c)},clearArtifacts(){fr(r)&&_.clearArtifacts()},getArtifacts(){var c;return(c=_==null?void 0:_.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=_==null?void 0:_.getSelectedArtifactId())!=null?c:null},focusInput(){return T&&!H&&!$()||!te?!1:(te.focus(),!0)},async resolveApproval(c,g,b){let E=_.getMessages().find(D=>{var F;return D.variant==="approval"&&((F=D.approval)==null?void 0:F.id)===c});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${c}`);if(E.approval.toolType==="webmcp"){_.resolveWebMcpApproval(E.id,g);return}return _.resolveApproval(E.approval,g,b)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return O()&&H},isVoiceActive(){return xt.active},getState(){return{open:O()&&H,launcherEnabled:T,voiceActive:xt.active,streaming:_.isStreaming()}},showCSATFeedback(c){!H&&O()&&Nt(!0,"system");let g=rt.querySelector(".persona-feedback-container");g&&g.remove();let b=Ki({onSubmit:async(y,E)=>{var D;_.isClientTokenMode()&&await _.submitCSATFeedback(y,E),(D=c==null?void 0:c.onSubmit)==null||D.call(c,y,E)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!H&&O()&&Nt(!0,"system");let g=rt.querySelector(".persona-feedback-container");g&&g.remove();let b=Ji({onSubmit:async(y,E)=>{var D;_.isClientTokenMode()&&await _.submitNPSFeedback(y,E),(D=c==null?void 0:c.onSubmit)==null||D.call(c,y,E)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return _.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return _.submitNPSFeedback(c,g)},destroy(){cr!=null&&(clearInterval(cr),cr=null),bt.forEach(c=>c()),ve.remove(),Je==null||Je.remove(),nn==null||nn.destroy(),rn==null||rn.remove(),ir&&R.removeEventListener("click",ir)}};if((((hd=n==null?void 0:n.debugTools)!=null?hd:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:dn,getMessages:dn.getMessages,getStatus:dn.getStatus,getMetadata:dn.getPersistentMetadata,updateMetadata:dn.updatePersistentMetadata,clearHistory:()=>dn.clearChat(),setVoiceActive:b=>b?dn.startVoiceRecognition():dn.stopVoiceRecognition()};window.AgentWidgetBrowser=g,bt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&dn.focusInput()};if(window.addEventListener("persona:focusInput",g),bt.push(()=>{window.removeEventListener("persona:focusInput",g)}),We){let q=xe=>{let me=xe.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&dn.showEventStream()},B=xe=>{let me=xe.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&dn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",B),bt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",B)})}let b=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&dn.showArtifacts()},y=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&dn.hideArtifacts()},E=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||B!=null&&B.artifact&&dn.upsertArtifact(B.artifact)},D=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||typeof(B==null?void 0:B.id)=="string"&&dn.selectArtifact(B.id)},F=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&dn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",E),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",F),bt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",E),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",F)})}let dr=Lb(r.persistState);if(dr&&O()){let c=Pb(dr.storage),g=`${dr.keyPrefix}widget-open`,b=`${dr.keyPrefix}widget-voice`,y=`${dr.keyPrefix}widget-voice-mode`;if(c){let E=((bd=dr.persist)==null?void 0:bd.openState)&&c.getItem(g)==="true",D=((yd=dr.persist)==null?void 0:yd.voiceState)&&c.getItem(b)==="true",F=((xd=dr.persist)==null?void 0:xd.voiceState)&&c.getItem(y)==="true";if(E&&setTimeout(()=>{dn.open(),setTimeout(()=>{var q;if(D||F)dn.startVoiceRecognition();else if((q=dr.persist)!=null&&q.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(vd=dr.persist)!=null&&vd.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(wd=dr.persist)!=null&&wd.voiceState&&(s.on("voice:state",q=>{c.setItem(b,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(y,q.viaVoice?"true":"false")})),dr.clearOnChatClear){let q=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(y)},B=()=>q();window.addEventListener("persona:clear-chat",B),bt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return p&&O()&&setTimeout(()=>{dn.open()},0),zr(),dn};var Ib=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},mg=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!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"},Ql=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=""},gg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Ql(e)},Jl=e=>{e.style.transition=""},Gl=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=""},Xl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Qi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Wb=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Rb=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},fg=(e,t,n,r,o,s,a)=>{var v,x,w,T,N,M;let i=mr(s),d=i.reveal==="push";Wb(e,t,n,r,d),Rb(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",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,u=(T=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileBreakpoint)!=null?T:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Gl(t),Jl(r),gg(r),Xl(n),Qi(o,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((M=(N=s==null?void 0:s.launcher)==null?void 0:N.zIndex)!=null?M:Mn),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"),gg(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Gl(t),Jl(r),Xl(n),Qi(o,r);let I=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":W;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=S,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",Jl(r),Ql(r),Qi(o,r);let I=Ib(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),S=i.animate?"transform 180ms ease":"none",k=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=`${W+I}px`,t.style.transition=S,t.style.transform=k,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${W}px`,n.style.maxWidth=`${W}px`,n.style.minWidth=`${W}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="",Gl(t),Ql(r),Xl(n),Qi(o,r);let I=i.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",k=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${W}`,r.style.width=W,r.style.maxWidth=W,r.style.minWidth=W,r.style.minHeight="0",r.style.position="relative",r.style.overflow=I||k?"hidden":"visible",r.style.transition=S,I&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Hb=(e,t)=>{let n=e.ownerDocument.createElement("div");return mg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){mg(n,r)},destroy(){n.remove()}}},Bb=(e,t)=>{var N,M,I,W;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(M=(N=t==null?void 0:t.launcher)==null?void 0:N.enabled)==null||M?(W=(I=t==null?void 0:t.launcher)==null?void 0:I.autoExpand)!=null?W:!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 f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),mr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{fg(a,i,d,l,p,t,u)}),f.observe(a))},x=()=>{fg(a,i,d,l,p,t,u),v()},w=a.ownerDocument.defaultView,T=()=>{x()};return w==null||w.addEventListener("resize",T),mr(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(S){let k=S.launcherEnabled?S.open:!0;u!==k&&(u=k,x())},updateConfig(S){var k,$;t=S,(($=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)!=null?$:!0)===!1&&(u=!0),x()},destroy(){w==null||w.removeEventListener("resize",T),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Ea=(e,t)=>gn(t)?Bb(e,t):Hb(e,t);var Yl={},hg=!1,Db=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},Nb=()=>{try{if(typeof Yl!="undefined"&&Yl.url)return new URL("../widget.css",Yl.url).href}catch{}return null},bg=(e,t)=>{let n=Nb(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},Zl=e=>{let t=Db(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Ea(t,o),a,i=[],d=(w,T)=>{var W,S;let M=!((S=(W=T==null?void 0:T.launcher)==null?void 0:W.enabled)!=null?S:!0)||gn(T),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),M&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let k=w.attachShadow({mode:"open"});k.appendChild(I),bg(k,r)}else w.appendChild(I),bg(w,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let w=d(s.host,o);a=Xi(w,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(hg||(hg=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let m=w=>{f(),s.destroy(),s=Ea(t,w),o=w,u()},v={update(w){var S,k,$,O,H,U;let T={...o,...w,launcher:{...(S=o==null?void 0:o.launcher)!=null?S:{},...(k=w==null?void 0:w.launcher)!=null?k:{},dock:{...(O=($=o==null?void 0:o.launcher)==null?void 0:$.dock)!=null?O:{},...(U=(H=w==null?void 0:w.launcher)==null?void 0:H.dock)!=null?U:{}}}},N=gn(o),M=gn(T),I=Co(o),W=Co(T);if(N!==M||I!==W){m(T);return}o=T,s.updateConfig(o),a.update(w),l()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(w,T,N){if(T==="host")return s.host;if(T in w)return Reflect.get(w,T,N);let M=a[T];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Cg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Ob=new Set(["button","a","input","select","textarea","details","summary"]),Fb=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ec=/\b(product|card|item|listing|result)\b/i,nc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,$b=3e3,_b=100;function Ag(e){let t=typeof e.className=="string"?e.className:"";if(ec.test(t)||e.id&&ec.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&ec.test(r.value))return!0}return!1}function Sg(e){var t;return nc.test(((t=e.textContent)!=null?t:"").trim())}function Tg(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function jb(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function yg(e){let t=e.match(nc);return t?t[0]:null}function xg(e){var r,o,s;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&&((o=t.textContent)!=null&&o.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(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Ub(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var qb="commerce-card",zb="result-card";function vg(e){return!Ag(e)||!Sg(e)||!Tg(e)&&!jb(e)?0:5200}function wg(e){var r;return!Ag(e)||Sg(e)||!Tg(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 rc=[{id:qb,scoreElement(e){return vg(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||nc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(vg(e)===0)return null;let{title:n,href:r}=xg(e),o=(p=(l=yg(((d=e.textContent)!=null?d:"").trim()))!=null?l:yg(t.text))!=null?p:"",s=Ub(e);return[r&&n?`[${n}](${r})${o?` \u2014 ${o}`:""}`:n?`${n}${o?` \u2014 ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
108
- `)}},{id:zb,scoreElement(e){return wg(e)},formatSummary(e,t){if(wg(e)===0)return null;let{title:n,href:r}=xg(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
- `)}}];function Vb(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Kb(e){var p,u,f,m,v,x,w,T,N,M,I,W,S;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(v=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",o=(w=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?w:200,s=(N=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?N:!0,a=(M=t.root)!=null?M:e.root,i=(I=t.mode)!=null?I:"structured",d=(W=t.maxCandidates)!=null?W:Math.max(500,n*10),l=(S=e.rules)!=null?S:rc;return i==="simple"&&e.rules&&e.rules.length>0?(Vb(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function tc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Jb=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Gb(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"||Ob.has(t)||n&&Fb.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Eg(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 Xb(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);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 oc(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${tc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of Jb){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${tc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>tc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function Qb(e){return e==="static"?_b:$b}function Mg(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:oc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Gb(e),attributes:Xb(e)}}function Yb(e,t,n,r){let o=Qb(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function Zb(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 ey(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(Cg.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Eg(l)){i=a.nextNode();continue}let u=Mg(l,e.maxTextLength),f=u.text.length>0,m=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(w=>w==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:v,formattingRule:x}=Yb(l,u,e.rules,n);o.push({el:l,domIndex:s,enriched:u,score:v,formattingRule:x}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=e.maxElements)break;Zb(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var f;let p;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,n);m&&(p=m)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function ty(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(Cg.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Eg(d)){s=o.nextNode();continue}let p=Mg(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!u&&!f){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.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 kg(e={}){var r;let t=Kb(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?ty(t,n):ey(t,n):[]}var Yi=100;function Lg(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"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:
107
+ `}if(!x&&!c){let Ut="max-height: -moz-available !important; max-height: stretch !important;",_t=m?"":"padding-top: 1.25em !important;",bt=m?"":`z-index: ${(fn=(rt=r.launcher)==null?void 0:rt.zIndex)!=null?fn:Ln} !important;`;ve.style.cssText+=Ut+_t+bt}Xe()};hr(),Ao(e,r),Ki(e,r),Gi(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",so)});let nn=null,rn=null;ft.push(()=>{nn==null||nn(),nn=null,rn==null||rn(),rn=null}),zn&&ft.push(()=>{zn==null||zn.disconnect(),zn=null}),ft.push(()=>{Rn==null||Rn(),Rn=null,$r(),Bt&&(Bt.remove(),Bt=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),Re&&ft.push(()=>{He!==null&&(cancelAnimationFrame(He),He=null),K==null||K.destroy(),K=null,ce==null||ce.destroy(),ce=null,X=null});let Qn=null,lo=()=>{Qn&&(Qn(),Qn=null),r.colorScheme==="auto"&&(Qn=Ti(()=>{Ao(e,r)}))};lo(),ft.push(()=>{Qn&&(Qn(),Qn=null)});let ye=(xd=r.features)==null?void 0:xd.streamAnimation;if(ye!=null&&ye.type&&ye.type!=="none"){let c=xa(ye.type,ye.plugins);c&&(Fl(c,e),ft.push(()=>jm(e)))}let br=rg(Et),cr=null,$,as=c=>{var x,E;if(!$)return;let m=c!=null?c:$.getMessages(),b=((E=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:E.enabled)!==!1?oi(m):null;b?br.render(b,$,ne,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(D=>D.role==="user")?br.render([],$,ne,m):br.render(r.suggestionChips,$,ne,m,r.suggestionChipsConfig)},Pr=!1,Ur=Im(),jr=new Map,Ir=new Map,yr=new Map,Ns=0,Xn=ki(),Yn=0,xr=null,vr=!1,Io=!1,qr=0,Tn=null,Rr=null,is=!1,Ro=!1,ls=null,Ba=4,cs=24,Da=80,ds=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Fs=(wd=(vd=r.voiceRecognition)==null?void 0:vd.autoResume)!=null?wd:!1,dr=c=>{s.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},_n=()=>{g(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Oa=()=>{var x,E;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let c=rc(d.voiceState),m=!!c.active,b=Number((E=c.timestamp)!=null?E:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-b<$b&&setTimeout(()=>{var D,N;yt.active||(yt.manuallyDeactivated=!1,((N=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:N.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),dr("restore"),$.isVoiceActive()&&Xs()}):Qt("restore"))},1e3)},Na=()=>$?Cg($.getMessages()).filter(c=>!c.__skipPersist):[];function ps(c){if(!(i!=null&&i.save))return;let b={messages:c?Cg(c):$?Na():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let x=i.save(b);x instanceof Promise&&x.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)}}let zr=null,_s=()=>ve.querySelector("#persona-scroll-container")||ue,co=()=>{zr!==null&&(cancelAnimationFrame(zr),zr=null),vr=!1},$s=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null),Io=!1,co()},Us=()=>{qr>0?(An.textContent=String(qr),An.style.display="",et.setAttribute("aria-label",`${Gt()||"Jump to latest"} (${qr} new)`)):(An.textContent="",An.style.display="none",et.setAttribute("aria-label",Gt()||"Jump to latest"))},js=()=>{qr!==0&&(qr=0,Us())},qs=()=>mt()==="follow"?!Xn.isFollowing():!Zo(ue,cs),$n=()=>{if(!wn()||ae){et.parentNode&&et.remove(),et.style.display="none";return}et.parentNode!==V&&V.appendChild(et),yn();let m=Zr(ue)>0&&qs();m||js(),et.style.display=m?"":"none"},us=()=>{Xn.pause()&&($s(),$n())},Wr=()=>{Xn.resume(),js(),$n()},Hr=(c=!1)=>{mt()==="follow"&&Xn.isFollowing()&&(!c&&!Pr||(xr!==null&&(cancelAnimationFrame(xr),xr=null),Io=!0,xr=requestAnimationFrame(()=>{xr=null,Io=!1,Xn.isFollowing()&&Fa(_s(),c?220:140)})))},zs=(c,m,b,x=()=>!0)=>{let E=c.scrollTop,D=m(),N=D-E;co();let q=performance.now();vr=!0;let B=me=>1-Math.pow(1-me,3),xe=me=>{if(!x()){co();return}let te=m();te!==D&&(D=te,N=D-E);let Ee=me-q,$e=Math.min(Ee/b,1),Te=B($e),st=E+N*Te;c.scrollTop=st,Yn=c.scrollTop,$e<1?zr=requestAnimationFrame(xe):(c.scrollTop=D,Yn=c.scrollTop,zr=null,vr=!1)};zr=requestAnimationFrame(xe)},Fa=(c,m=500)=>{let b=Zr(c)-c.scrollTop;if(Math.abs(b)<1){Yn=c.scrollTop;return}if(Math.abs(b)>=Da){co(),vr=!0,c.scrollTop=Zr(c),Yn=c.scrollTop,vr=!1;return}zs(c,()=>Zr(c),m,()=>Xn.isFollowing())},Vs=()=>{let c=_s();vr=!0,c.scrollTop=Zr(c),Yn=c.scrollTop,vr=!1,$n()},Ks=c=>{Sn.style.height=`${Math.max(0,Math.round(c))}px`,Tn&&(Tn.spacerHeight=Math.max(0,c))},Wo=()=>{Rr!==null&&(cancelAnimationFrame(Rr),Rr=null),co(),Tn=null,Sn.style.height="0px"},_a=c=>{Rr!==null&&cancelAnimationFrame(Rr),Rr=requestAnimationFrame(()=>{var xe;Rr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=ue.querySelector(`[data-message-id="${m}"]`);if(!b)return;let x=0,E=b;for(;E&&E!==ue;)x+=E.offsetTop,E=E.offsetParent;let D=(xe=Tn==null?void 0:Tn.spacerHeight)!=null?xe:0,N=ue.scrollHeight-D,{targetScrollTop:q,spacerHeight:B}=Dm({anchorOffsetTop:x,topOffset:Mt(),viewportHeight:ue.clientHeight,contentHeight:N});Tn={initialSpacerHeight:B,contentHeightAtAnchor:N,spacerHeight:B},Ks(B),zs(ue,()=>q,220)})},$a=()=>{if(mt()==="follow"){if(!Xn.isFollowing()||Zo(ue,1))return;Hr(!Pr);return}if(Tn&&Tn.initialSpacerHeight>0){let c=ue.scrollHeight-Tn.spacerHeight,m=Om({initialSpacerHeight:Tn.initialSpacerHeight,contentHeightAtAnchor:Tn.contentHeightAtAnchor,currentContentHeight:c});m!==Tn.spacerHeight&&Ks(m)}$n()},Ua=c=>{let m=mt();m==="follow"?(Wr(),Hr(!0)):m==="anchor-top"&&_a(c)},ja=c=>{let m=new Map;c.forEach(b=>{let x=ds.get(b.id);m.set(b.id,{streaming:b.streaming,role:b.role}),!x&&b.role==="assistant"&&(s.emit("assistant:message",b),!Ro&&mt()!=="anchor-top"&&qs()&&(qr+=1,Us(),$n())),b.role==="assistant"&&(x!=null&&x.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(x?b.approval.status!=="pending"&&s.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):s.emit("approval:requested",{approval:b.approval,message:b}))}),ds.clear(),m.forEach((b,x)=>{ds.set(x,b)})},Ho=(c,m,b)=>{var pt,Ie,Pe,qe,Xe,wt;let x=document.createElement("div"),D=(()=>{var Be;let P=o.find(Ne=>Ne.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),N=(P,Be)=>Be==null?!1:typeof Be=="string"?(P.textContent=Be,!0):(P.appendChild(Be),!0),q=new Set,B=new Set,xe=o.some(P=>P.renderAskUserQuestion),me=[],te=[],Ee=r.enableComponentStreaming!==!1,$e=o.some(P=>P.renderApproval)&&r.approval!==!1,Te=[];if(m.forEach(P=>{var Ye,It,un,ur,er,Do,Oo,bs,ys,Xt,No,bo,yo,Kr,Fo,wr;q.add(P.id);let Be=xe&&Jr(P),Ne=$e&&P.variant==="approval"&&!!P.approval,he=!Be&&P.role==="assistant"&&!P.variant&&Ee&&Yi(P);if(!Ne&&yr.has(P.id)){let rt=c.querySelector(`#wrapper-${P.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),yr.delete(P.id)}if(!he&&Ir.has(P.id)){let rt=c.querySelector(`#wrapper-${P.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),Ir.delete(P.id)}let Ft=Jr(P)?`:${(Ye=P.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(It=P.agentMetadata)!=null&&It.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=Pm(P,Ns)+Ft,Jt=Be||Ne||he?null:Rm(Ur,P.id,Ot);if(Jt){x.appendChild(Jt.cloneNode(!0)),Jr(P)&&((un=P.toolCall)!=null&&un.id)&&((ur=P.agentMetadata)==null?void 0:ur.awaitingLocalTool)===!0&&!((er=P.agentMetadata)!=null&&er.askUserQuestionAnswered)&&(B.add(P.toolCall.id),As(P,r,De.composerOverlay));return}let Ct=null,zt=o.find(rt=>!!(P.variant==="reasoning"&&rt.renderReasoning||P.variant==="tool"&&rt.renderToolCall||!P.variant&&rt.renderMessage)),Zn=(Do=r.layout)==null?void 0:Do.messages;if(Jr(P)&&((Oo=P.agentMetadata)==null?void 0:Oo.askUserQuestionAnswered)===!0){jr.delete(P.id);let rt=c.querySelector(`#wrapper-${P.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(ia(P)&&((ys=(bs=r.features)==null?void 0:bs.suggestReplies)==null?void 0:ys.enabled)!==!1)return;if(Jr(P)&&((No=(Xt=r.features)==null?void 0:Xt.askUserQuestion)==null?void 0:No.enabled)!==!1){let rt=o.find(fn=>typeof fn.renderAskUserQuestion=="function");if(rt&&Lt.current){let fn=jr.get(P.id),Ut=fn!==Ot,_t=null;if(Ut){let{payload:kt,complete:En}=Qr(P),Wn=P.id,Br=()=>{var vn;return(vn=Lt.current)==null?void 0:vn.getMessages().find(Hn=>Hn.id===Wn)};_t=rt.renderAskUserQuestion({message:P,payload:kt,complete:En,resolve:vn=>{var Bn;let Hn=Br();Hn&&((Bn=Lt.current)==null||Bn.resolveAskUserQuestion(Hn,vn))},dismiss:()=>{var Hn,Bn,_o;let vn=Br();(Hn=vn==null?void 0:vn.agentMetadata)!=null&&Hn.awaitingLocalTool&&((Bn=Lt.current)==null||Bn.markAskUserQuestionResolved(vn),(_o=Lt.current)==null||_o.resolveAskUserQuestion(vn,"(dismissed)"))},config:r})}let bt=fn!=null;if(Ut&&_t===null&&!bt){((bo=P.agentMetadata)==null?void 0:bo.awaitingLocalTool)===!0&&!((yo=P.agentMetadata)!=null&&yo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),As(P,r,De.composerOverlay));return}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${P.id}`,Yt.setAttribute("data-wrapper-id",P.id),Yt.setAttribute("data-ask-plugin-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),x.appendChild(Yt),me.push({messageId:P.id,fingerprint:Ot,bubble:_t});return}else{((Kr=P.agentMetadata)==null?void 0:Kr.awaitingLocalTool)===!0&&!((Fo=P.agentMetadata)!=null&&Fo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),As(P,r,De.composerOverlay));return}}else if(Ne){let rt=o.find(bt=>typeof bt.renderApproval=="function"),Ut=yr.get(P.id)!==Ot,_t=null;if(Ut&&(rt!=null&&rt.renderApproval)){let bt=P.id,Yt=(kt,En)=>{var Br,vn,Hn;let Wn=(Br=Lt.current)==null?void 0:Br.getMessages().find(Bn=>Bn.id===bt);Wn!=null&&Wn.approval&&(Wn.approval.toolType==="webmcp"?(vn=Lt.current)==null||vn.resolveWebMcpApproval(Wn.id,kt):(Hn=Lt.current)==null||Hn.resolveApproval(Wn.approval,kt,En))};_t=rt.renderApproval({message:P,defaultRenderer:()=>zi(P,r),config:r,approve:kt=>Yt("approved",kt),deny:kt=>Yt("denied",kt)})}if(Ut&&_t===null){let bt=c.querySelector(`#wrapper-${P.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),yr.delete(P.id),Ct=zi(P,r)}else{let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${P.id}`,bt.setAttribute("data-wrapper-id",P.id),bt.setAttribute("data-approval-plugin-stub","true"),bt.setAttribute("data-preserve-runtime","true"),x.appendChild(bt),Te.push({messageId:P.id,fingerprint:Ot,bubble:_t});return}}else if(zt)if(P.variant==="reasoning"&&P.reasoning&&zt.renderReasoning){if(!ze)return;Ct=zt.renderReasoning({message:P,defaultRenderer:()=>Jl(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&zt.renderToolCall){if(!Ae)return;Ct=zt.renderToolCall({message:P,defaultRenderer:()=>Ql(P,r),config:r})}else zt.renderMessage&&(Ct=zt.renderMessage({message:P,defaultRenderer:()=>{let rt=Rs(P,b,Zn,r.messageActions,ee,{loadingIndicatorRenderer:D,widgetConfig:r});return P.role!=="user"&&ec(rt,P,r,$),rt},config:r}));if(!Ct&&he){let rt=Zi(P);if(rt){let fn=Ir.get(P.id),Ut=fn!==Ot,_t=r.wrapComponentDirectiveInBubble!==!1,bt=null;if(Ut){let Yt=Xi(rt,{config:r,message:P,transform:b});if(Yt)if(_t){let kt=document.createElement("div");if(kt.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(" "),kt.id=`bubble-${P.id}`,kt.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let En=document.createElement("div");En.className="persona-mb-3 persona-text-sm persona-leading-relaxed",En.innerHTML=b({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),kt.appendChild(En)}kt.appendChild(Yt),bt=kt}else{let kt=document.createElement("div");if(kt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",kt.id=`bubble-${P.id}`,kt.setAttribute("data-message-id",P.id),kt.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let En=document.createElement("div");En.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",En.innerHTML=b({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),kt.appendChild(En)}kt.appendChild(Yt),bt=kt}}if(bt||fn!=null){let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${P.id}`,Yt.setAttribute("data-wrapper-id",P.id),Yt.setAttribute("data-component-directive-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),_t||Yt.classList.add("persona-w-full"),x.appendChild(Yt),te.push({messageId:P.id,fingerprint:Ot,bubble:bt});return}}}if(!Ct)if(P.variant==="reasoning"&&P.reasoning){if(!ze)return;Ct=Jl(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!Ae)return;Ct=Ql(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;Ct=zi(P,r)}else{let rt=(wr=r.layout)==null?void 0:wr.messages;rt!=null&&rt.renderUserMessage&&P.role==="user"?Ct=rt.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):rt!=null&&rt.renderAssistantMessage&&P.role==="assistant"?Ct=rt.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):Ct=Rs(P,b,rt,r.messageActions,ee,{loadingIndicatorRenderer:D,widgetConfig:r}),P.role!=="user"&&Ct&&ec(Ct,P,r,$)}let ln=document.createElement("div");ln.className="persona-flex",ln.id=`wrapper-${P.id}`,ln.setAttribute("data-wrapper-id",P.id),P.role==="user"&&ln.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&ln.classList.add("persona-w-full"),ln.appendChild(Ct),Wm(Ur,P.id,Ot,ln),x.appendChild(ln)}),De.composerOverlay&&De.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Ne=Be.getAttribute("data-persona-ask-sheet-for");Ne&&!B.has(Ne)&&wo(De.composerOverlay,Ne)}),(Ie=(pt=r.features)==null?void 0:pt.toolCallDisplay)!=null&&Ie.grouped){let P=[],Be=[];m.forEach(Ne=>{if(Ne.variant==="tool"&&Ne.toolCall&&Ae){Be.push(Ne);return}Be.length>1&&P.push(Be),Be=[]}),Be.length>1&&P.push(Be),P.forEach((Ne,he)=>{var Ye,It;let Ft=Ne.map(un=>Array.from(x.children).find(ur=>ur instanceof HTMLElement&&ur.getAttribute("data-wrapper-id")===un.id)).filter(un=>!!un);if(Ft.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${he}-${Ne[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${he}-${Ne[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Ne.length} tools`,Zn=(It=(Ye=r.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:It.call(Ye,{messages:Ne,toolCalls:Ne.map(un=>un.toolCall).filter(un=>!!un),defaultSummary:zt,config:r});N(Ct,Zn)||(Ct.textContent=zt);let ln=document.createElement("div");ln.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(Ct,ln),Ot.appendChild(Jt),Ft[0].before(Ot),Ft.forEach((un,ur)=>{let er=document.createElement("div");er.className="persona-tool-group-item persona-relative",er.setAttribute("data-persona-tool-group-item","true"),ur<Ft.length-1&&er.setAttribute("data-persona-tool-group-connector","true"),er.appendChild(un),ln.appendChild(er)})})}Hm(Ur,q);let st=m.some(P=>P.role==="assistant"&&P.streaming),Ke=m[m.length-1],dt=(Ke==null?void 0:Ke.role)==="assistant"&&!Ke.streaming&&Ke.variant!=="approval";if(Pr&&m.some(P=>P.role==="user")&&!st&&!dt){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:ts},Be=o.find(he=>he.renderLoadingIndicator),Ne=null;if(Be!=null&&Be.renderLoadingIndicator&&(Ne=Be.renderLoadingIndicator(P)),Ne===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(Ne=r.loadingIndicator.render(P)),Ne===null&&(Ne=ts()),Ne){let he=document.createElement("div"),Ft=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;he.className=Ft?["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(" "),he.setAttribute("data-typing-indicator","true"),he.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",he.appendChild(Ne);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(he),x.appendChild(Ot)}}if(!Pr&&m.length>0){let P=m[m.length-1],Be={config:r,lastMessage:P,messageCount:m.length},Ne=o.find(Ft=>Ft.renderIdleIndicator),he=null;if(Ne!=null&&Ne.renderIdleIndicator&&(he=Ne.renderIdleIndicator(Be)),he===null&&((Xe=r.loadingIndicator)!=null&&Xe.renderIdle)&&(he=r.loadingIndicator.renderIdle(Be)),he){let Ft=document.createElement("div"),Ot=((wt=r.loadingIndicator)==null?void 0:wt.showBubble)!==!1;Ft.className=Ot?["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(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(he);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(Ft),x.appendChild(Jt)}}if(Ei(c,x),me.length>0)for(let{messageId:P,fingerprint:Be,bubble:Ne}of me){let he=c.querySelector(`#wrapper-${P}`);he&&Ne!==null&&(he.replaceChildren(Ne),he.setAttribute("data-bubble-fp",Be),jr.set(P,Be))}if(jr.size>0)for(let P of jr.keys())q.has(P)||jr.delete(P);if(te.length>0)for(let{messageId:P,fingerprint:Be,bubble:Ne}of te){let he=c.querySelector(`#wrapper-${P}`);he&&Ne!==null&&(he.replaceChildren(Ne),he.setAttribute("data-bubble-fp",Be),Ir.set(P,Be))}if(Ir.size>0)for(let P of Ir.keys())q.has(P)||Ir.delete(P);if(Te.length>0)for(let{messageId:P,fingerprint:Be,bubble:Ne}of Te){let he=c.querySelector(`#wrapper-${P}`);he&&Ne!==null&&(he.replaceChildren(Ne),he.setAttribute("data-bubble-fp",Be),yr.set(P,Be))}if(yr.size>0)for(let P of yr.keys())q.has(P)||yr.delete(P)},po=null,qa=()=>{var b;if(po)return;let c=x=>{let E=x.composedPath();E.includes(ve)||Je&&E.includes(Je)||Dt(!1,"user")};po=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},Gs=()=>{var m;if(!po)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",po,!0),po=null};ft.push(()=>Gs());let uo=null,za=()=>{var b;if(uo)return;let c=x=>{x.key==="Escape"&&(x.isComposing||Dt(!1,"user"))};uo=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Js=()=>{var m;if(!uo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",uo,!0),uo=null};ft.push(()=>Js());let mo=!1,Qs=new Set,Va=()=>{var m,b,x,E;let c=(x=(b=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:b.peek)==null?void 0:x.streamAnimation;return c||((E=r.features)==null?void 0:E.streamAnimation)},Vr=()=>{var dt,pt,Ie,Pe;if(!_())return;let c=De.peekBanner,m=De.peekTextNode;if(!c||!m)return;if(M){c.classList.remove("persona-pill-peek--visible");return}let b=(dt=$==null?void 0:$.getMessages())!=null?dt:[],x;for(let qe=b.length-1;qe>=0;qe--){let Xe=b[qe];if(Xe.role==="assistant"&&Xe.content){x=Xe;break}}if(!x){c.classList.remove("persona-pill-peek--visible");return}let E=x.content,D=!!x.streaming,N=Va(),q=Ii(N),B=q.type!=="none"?xa(q.type,N==null?void 0:N.plugins):null,xe=((pt=B==null?void 0:B.isAnimating)==null?void 0:pt.call(B,x))===!0,me=B!==null&&(D||xe);me&&B&&!Qs.has(B.name)&&(Fl(B,e),Qs.add(B.name));let te=me&&(B!=null&&B.containerClass)?B.containerClass:null,Ee=(Ie=m.dataset.personaPeekStreamClass)!=null?Ie:null;Ee&&Ee!==te&&(m.classList.remove(Ee),delete m.dataset.personaPeekStreamClass),te&&Ee!==te&&(m.classList.add(te),m.dataset.personaPeekStreamClass=te),me?(m.style.setProperty("--persona-stream-step",`${q.speed}ms`),m.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let $e=me?Ri(E,q.buffer,B,x,D):E;if(me&&q.placeholder==="skeleton"&&D&&(!$e||!$e.trim())){let qe=document.createElement("div"),Xe=wa();Xe.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Xe),Ei(m,qe)}else{let qe=Math.max(0,$e.length-100),Xe=$e.length>100?$e.slice(-100):$e,wt=qo(Xe);if(!me||!B){let P=$e.length>100?`\u2026${Xe}`:Xe;m.textContent!==P&&(m.textContent=P)}else{let P=wt;(B.wrap==="char"||B.wrap==="word")&&(P=va(wt,B.wrap,`peek-${x.id}`,{skipTags:B.skipTags,startIndex:qe}));let Be=document.createElement("div");if(Be.innerHTML=P,B.useCaret&&Xe.length>0){let Ne=Wi(),he=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=he[he.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(Ne,Ft.nextSibling):Be.appendChild(Ne)}Ei(m,Be),(Pe=B.onAfterRender)==null||Pe.call(B,{container:m,bubble:c,messageId:x.id,message:x,speed:q.speed,duration:q.duration})}}let Ke=Pr||mo;c.classList.toggle("persona-pill-peek--visible",Ke)};if(_()){let c=De.peekBanner;if(c){let x=E=>{E.preventDefault(),E.stopPropagation(),Dt(!0,"user")};c.addEventListener("pointerdown",x),ft.push(()=>{c.removeEventListener("pointerdown",x)})}let m=()=>{mo||(mo=!0,Vr())},b=()=>{mo&&(mo=!1,Vr())};fe.addEventListener("pointerenter",m),fe.addEventListener("pointerleave",b),ft.push(()=>{fe.removeEventListener("pointerenter",m),fe.removeEventListener("pointerleave",b)}),Je&&(Je.addEventListener("pointerenter",m),Je.addEventListener("pointerleave",b),ft.push(()=>{Je.removeEventListener("pointerenter",m),Je.removeEventListener("pointerleave",b)}))}let Ka=c=>{var Ee,$e,Te,st,Ke,dt,pt,Ie;let m=($e=(Ee=r.launcher)==null?void 0:Ee.composerBar)!=null?$e:{},b=(Te=m.expandedSize)!=null?Te:"anchored",x=(st=m.bottomOffset)!=null?st:"16px",E=m.collapsedMaxWidth,D=(Ke=m.expandedMaxWidth)!=null?Ke:"880px",N=(dt=m.expandedTopOffset)!=null?dt:"5vh",q=(pt=m.modalMaxWidth)!=null?pt:"880px",B=(Ie=m.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",xe="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",te=ve.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",Je){let Pe=Je.style;Pe.bottom=x,Pe.width=E!=null?E:""}if(c&&b!=="fullscreen"){if(b==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=q,te.maxWidth=xe,te.maxHeight=B,te.height=B;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${x} + ${me})`,te.top=N,te.width=D,te.maxWidth=xe}},go=()=>{var B,xe,me,te,Ee,$e,Te,st;if(!F())return;if(_()){let dt=(me=((xe=(B=r.launcher)==null?void 0:B.composerBar)!=null?xe:{}).expandedSize)!=null?me:"anchored",pt=M?"expanded":"collapsed";ve.dataset.state=pt,ve.dataset.expandedSize=dt,Je&&(Je.dataset.state=pt,Je.dataset.expandedSize=dt),ve.style.removeProperty("display"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ka(M),V.style.display=M?"flex":"none",hr(),M?(qa(),za()):(Gs(),Js()),Vr();return}let c=mn(r),m=(te=e.ownerDocument.defaultView)!=null?te:window,b=($e=(Ee=r.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?$e:640,x=(st=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?st:!0,E=m.innerWidth<=b,D=x&&E&&S,N=rr(r).reveal;M?(ve.style.removeProperty("display"),ve.style.display=c?"flex":"",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0"),fe.classList.add("persona-scale-100","persona-opacity-100"),on?on.element.style.display="none":sn&&(sn.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!D?(ve.style.removeProperty("display"),ve.style.display="flex",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.setProperty("display","none","important"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.display="",ve.classList.add("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100"),fe.classList.add("persona-scale-95","persona-opacity-0")),on?on.element.style.display=c?"none":"":sn&&(sn.style.display=c?"none":""))},Dt=(c,m="user")=>{var D,N;if(!F()||M===c)return;let b=M;M=c,go();let x=(()=>{var Te,st,Ke,dt,pt,Ie,Pe,qe,Xe,wt;let q=(st=(Te=r.launcher)==null?void 0:Te.sidebarMode)!=null?st:!1,B=(Ke=e.ownerDocument.defaultView)!=null?Ke:window,xe=(pt=(dt=r.launcher)==null?void 0:dt.mobileFullscreen)!=null?pt:!0,me=(Pe=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Pe:640,te=B.innerWidth<=me,Ee=mn(r)&&xe&&te,$e=_()&&((wt=(Xe=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Xe.expandedSize)!=null?wt:"fullscreen")==="fullscreen";return q||xe&&te&&S||Ee||$e})();if(M&&x){if(!nn){let q=e.getRootNode(),B=q instanceof ShadowRoot?q.host:e.closest(".persona-host");B&&(nn=_l(B,(N=(D=r.launcher)==null?void 0:D.zIndex)!=null?N:Ln))}rn||(rn=$l(e.ownerDocument))}else M||(nn==null||nn(),nn=null,rn==null||rn(),rn=null);M&&(Ys(),mt()==="follow"?Hr(!0):Vs());let E={open:M,source:m,timestamp:Date.now()};M&&!b?s.emit("widget:opened",E):!M&&b&&s.emit("widget:closed",E),s.emit("widget:state",{open:M,launcherEnabled:S,voiceActive:yt.active,streaming:$.isStreaming()})},ms=c=>{Zt(c?"stop":"send"),G&&(G.disabled=c),br.buttons.forEach(m=>{m.disabled=c}),Ue.dataset.personaComposerStreaming=c?"true":"false",Ue.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},gs=()=>{yt.active||ne&&ne.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>gs(),200)});let Bo=()=>{var b,x,E,D,N,q,B,xe,me,te,Ee;sr.textContent=(x=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?x:"Hello \u{1F44B}",Er.textContent=(D=(E=r.copy)==null?void 0:E.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",ne.placeholder=(q=(N=r.copy)==null?void 0:N.inputPlaceholder)!=null?q:"How can I help...";let c=ue.querySelector("[data-persona-intro-card]");if(c){let $e=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;c.style.display=$e?"":"none",$e?(ue.classList.remove("persona-gap-3"),ue.classList.add("persona-gap-6")):(ue.classList.remove("persona-gap-6"),ue.classList.add("persona-gap-3"))}!((me=(xe=r.sendButton)==null?void 0:xe.useIcon)!=null&&me)&&!($!=null&&$.isStreaming())&&(Ve.textContent=(Ee=(te=r.copy)==null?void 0:te.sendButtonLabel)!=null?Ee:"Send"),ne.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ne.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=>{g(m=>({...m,sessionId:c}))}});let je=null,A=()=>{je==null&&(je=setInterval(()=>{let c=ot.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(je),je=null;return}let m=Date.now();c.forEach(b=>{let x=Number(b.getAttribute("data-tool-elapsed"));x&&(b.textContent=ai(m-x))})},100))};if($=new Es(r,{onMessagesChanged(c){var x;Ho(ot,c,ke),A(),as(c),Hr(!Pr),ja(c);let m=[...c].reverse().find(E=>E.role==="user");c.length===0&&Wo(),!is||Ro?(is=!0,ls=(x=m==null?void 0:m.id)!=null?x:null):m&&m.id!==ls&&(ls=m.id,Ua(m.id));let b=yt.lastUserMessageId;m&&m.id!==b&&(yt.lastUserMessageId=m.id,s.emit("user:message",m)),yt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),ps(c),Vr()},onStatusChanged(c){var x;let m=(x=r.statusIndicator)!=null?x:{};Ze(cn,(E=>{var D,N,q,B;return E==="idle"?(D=m.idleText)!=null?D:kn.idle:E==="connecting"?(N=m.connectingText)!=null?N:kn.connecting:E==="connected"?(q=m.connectedText)!=null?q:kn.connected:E==="error"?(B=m.errorText)!=null?B:kn.error:kn[E]})(c),m,c)},onStreamingChanged(c){Pr=c,ms(c),$&&Ho(ot,$.getMessages(),ke),c||Hr(!0),Vr()},onVoiceStatusChanged(c){var m,b;if(((b=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:b.type)==="runtype")switch(c){case"listening":break;case"processing":fo(),mf();break;case"speaking":fo(),gf();break;default:c==="idle"&&$.isBargeInActive()?(fo(),Xs(),G==null||G.setAttribute("aria-label","End voice session")):(yt.active=!1,fo(),dr("system"),_n());break}},onArtifactsState(c){Vn=c,Jn(),ps()}}),Lt.current=$,is=!0,((Ad=(Cd=r.voiceRecognition)==null?void 0:Cd.provider)==null?void 0:Ad.type)==="runtype")try{$.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&$.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(ce||r.onSSEEvent)&&$.setSSEEventCallback((c,m)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,m),ge==null||ge.processEvent(c,m),ce==null||ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),l&&l.then(c=>{var m,b,x;if(c){if(c.metadata&&(d=rc(c.metadata),w.syncFromMetadata()),(m=c.messages)!=null&&m.length){Ro=!0;try{$.hydrateMessages(c.messages)}finally{Ro=!1}}(b=c.artifacts)!=null&&b.length&&$.hydrateArtifacts(c.artifacts,(x=c.selectedArtifactId)!=null?x:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let U=()=>{var m,b,x;!_()||M||!((x=(b=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:b.expandOnSubmit)==null||x)||Dt(!0,"auto")},L=c=>{var E;if(c.preventDefault(),$.isStreaming()){$.cancel(),ge==null||ge.reset(),K==null||K.update();return}let m=ne.value.trim(),b=(E=At==null?void 0:At.hasAttachments())!=null?E:!1;if(!m&&!b)return;U();let x;b&&(x=[],x.push(...At.getContentParts()),m&&x.push(pa(m))),ne.value="",ne.style.height="auto",Me(),$.sendMessage(m,{contentParts:x}),b&&At.clearAttachments()},Z=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},se={...Mi},J=!1,Me=()=>{se={...Mi}},Fe=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),ct=c=>{if(!ne)return;J=!0,ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),J=!1;let m=ne.value.length;ne.setSelectionRange(m,m)},tt=()=>{J||Me()},Wt=c=>{if(ne){if(Z()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=ne.selectionStart===0&&ne.selectionEnd===0,b=Lm({direction:c.key==="ArrowUp"?"up":"down",history:Fe(),currentValue:ne.value,atStart:m,state:se});if(se=b.state,b.handled){c.preventDefault(),b.value!==void 0&&ct(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}Me(),c.preventDefault(),Ve.click()}}},$t=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(V)&&($.cancel(),ge==null||ge.reset(),K==null||K.update(),Me(),c.preventDefault(),c.stopImmediatePropagation())},gn=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!At)return;let m=jb(c.clipboardData);m.length!==0&&(c.preventDefault(),await At.handleFiles(m))},it=null,ht=!1,en=null,Ge=null,Cn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Qt=(c="user")=>{var D,N,q,B,xe,me,te;if(ht||$.isStreaming())return;let m=Cn();if(!m)return;it=new m;let x=(N=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?N:2e3;it.continuous=!0,it.interimResults=!0,it.lang="en-US";let E=ne.value;it.onresult=Ee=>{let $e="",Te="";for(let Ke=0;Ke<Ee.results.length;Ke++){let dt=Ee.results[Ke],pt=dt[0].transcript;dt.isFinal?$e+=pt+" ":Te=pt}let st=E+$e+Te;ne.value=st,en&&clearTimeout(en),($e||Te)&&(en=window.setTimeout(()=>{let Ke=ne.value.trim();Ke&&it&&ht&&(xn(),ne.value="",ne.style.height="auto",$.sendMessage(Ke,{viaVoice:!0}))},x))},it.onerror=Ee=>{Ee.error!=="no-speech"&&xn()},it.onend=()=>{if(ht){let Ee=ne.value.trim();Ee&&Ee!==E.trim()&&(ne.value="",ne.style.height="auto",$.sendMessage(Ee,{viaVoice:!0})),xn()}};try{if(it.start(),ht=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),dr(c),_n(),G){let Ee=(q=r.voiceRecognition)!=null?q:{};Ge={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(B=Ee.iconName)!=null?B:"mic",iconSize:parseFloat((te=(me=Ee.iconSize)!=null?me:(xe=r.sendButton)==null?void 0:xe.size)!=null?te:"40")||24};let $e=Ee.recordingBackgroundColor,Te=Ee.recordingIconColor,st=Ee.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=$e!=null?$e:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let Ke=G.querySelector("svg");Ke&&Ke.setAttribute("stroke",Te)}st&&(G.style.borderColor=st),G.setAttribute("aria-label","Stop voice recognition")}}catch{xn("system")}},xn=(c="user")=>{if(ht){if(ht=!1,en&&(clearTimeout(en),en=null),it){try{it.stop()}catch{}it=null}if(yt.active=!1,dr(c),_n(),G){if(G.classList.remove("persona-voice-recording"),Ge){G.style.backgroundColor=Ge.backgroundColor,G.style.color=Ge.color,G.style.borderColor=Ge.borderColor;let m=G.querySelector("svg");m&&m.setAttribute("stroke",Ge.color||"currentColor"),Ge=null}G.setAttribute("aria-label","Start voice recognition")}}},uf=(c,m)=>{var dt,pt,Ie,Pe,qe,Xe,wt,P;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((dt=c==null?void 0:c.provider)==null?void 0:dt.type)==="runtype";if(!(b||x))return null;let D=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let q=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",B=(Ie=m==null?void 0:m.size)!=null?Ie:"40px",xe=(Pe=c==null?void 0:c.iconSize)!=null?Pe:B,me=parseFloat(xe)||24,te=(qe=c==null?void 0:c.backgroundColor)!=null?qe:m==null?void 0:m.backgroundColor,Ee=(Xe=c==null?void 0:c.iconColor)!=null?Xe:m==null?void 0:m.textColor;N.style.width=xe,N.style.height=xe,N.style.minWidth=xe,N.style.minHeight=xe,N.style.fontSize="18px",N.style.lineHeight="1",Ee?N.style.color=Ee:N.style.color="var(--persona-text, #111827)";let Te=Ce(q,me,Ee||"currentColor",1.5);Te?N.appendChild(Te):N.textContent="\u{1F3A4}",te?N.style.backgroundColor=te:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),D.appendChild(N);let st=(wt=c==null?void 0:c.tooltipText)!=null?wt:"Start voice recognition";if(((P=c==null?void 0:c.showTooltip)!=null?P:!1)&&st){let Be=h("div","persona-send-button-tooltip");Be.textContent=st,D.appendChild(Be)}return{micButton:N,micButtonWrapper:D}},ul=()=>{var m,b,x,E,D;if(!G||Ge)return;let c=(m=r.voiceRecognition)!=null?m:{};Ge={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((D=(E=c.iconSize)!=null?E:(x=r.sendButton)==null?void 0:x.size)!=null?D:"40")||24}},ml=(c,m)=>{var D,N,q,B,xe;if(!G)return;let b=G.querySelector("svg");b&&b.remove();let x=(xe=Ge==null?void 0:Ge.iconSize)!=null?xe:parseFloat((B=(q=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?q:(N=r.sendButton)==null?void 0:N.size)!=null?B:"40")||24,E=Ce(c,x,m,1.5);E&&G.appendChild(E)},Ga=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Xs=()=>{var E;if(!G)return;ul();let c=(E=r.voiceRecognition)!=null?E:{},m=c.recordingBackgroundColor,b=c.recordingIconColor,x=c.recordingBorderColor;if(Ga(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let D=G.querySelector("svg");D&&D.setAttribute("stroke",b)}x&&(G.style.borderColor=x),G.setAttribute("aria-label","Stop voice recognition")},mf=()=>{var q,B,xe,me,te,Ee,$e,Te;if(!G)return;ul();let c=(q=r.voiceRecognition)!=null?q:{},m=$.getVoiceInterruptionMode(),b=(B=c.processingIconName)!=null?B:"loader",x=(me=(xe=c.processingIconColor)!=null?xe:Ge==null?void 0:Ge.color)!=null?me:"",E=(Ee=(te=c.processingBackgroundColor)!=null?te:Ge==null?void 0:Ge.backgroundColor)!=null?Ee:"",D=(Te=($e=c.processingBorderColor)!=null?$e:Ge==null?void 0:Ge.borderColor)!=null?Te:"";Ga(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=E,G.style.borderColor=D;let N=x||"currentColor";G.style.color=N,ml(b,N),G.setAttribute("aria-label","Processing voice input"),m==="none"&&(G.style.cursor="default")},gf=()=>{var xe,me,te,Ee,$e,Te,st,Ke,dt,pt,Ie,Pe;if(!G)return;ul();let c=(xe=r.voiceRecognition)!=null?xe:{},m=$.getVoiceInterruptionMode(),b=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(me=c.speakingIconName)!=null?me:b,E=(Te=c.speakingIconColor)!=null?Te:m==="barge-in"?(Ee=(te=c.recordingIconColor)!=null?te:Ge==null?void 0:Ge.color)!=null?Ee:"":($e=Ge==null?void 0:Ge.color)!=null?$e:"",D=(dt=c.speakingBackgroundColor)!=null?dt:m==="barge-in"?(st=c.recordingBackgroundColor)!=null?st:"var(--persona-voice-recording-bg, #ef4444)":(Ke=Ge==null?void 0:Ge.backgroundColor)!=null?Ke:"",N=(Pe=c.speakingBorderColor)!=null?Pe:m==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(Ie=Ge==null?void 0:Ge.borderColor)!=null?Ie:"";Ga(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=D,G.style.borderColor=N;let q=E||"currentColor";G.style.color=q,ml(x,q);let B=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",B),m==="none"&&(G.style.cursor="default"),m==="barge-in"&&G.classList.add("persona-voice-recording")},fo=()=>{var c,m,b;G&&(Ga(),Ge&&(G.style.backgroundColor=(c=Ge.backgroundColor)!=null?c:"",G.style.color=(m=Ge.color)!=null?m:"",G.style.borderColor=(b=Ge.borderColor)!=null?b:"",ml(Ge.iconName,Ge.color||"currentColor"),Ge=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Ja=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let b=$.getVoiceStatus(),x=$.getVoiceInterruptionMode();if(x==="none"&&(b==="processing"||b==="speaking"))return;if(x==="cancel"&&(b==="processing"||b==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,_n(),dr("user"),fo()});return}$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),yt.manuallyDeactivated=!$.isVoiceActive(),_n(),dr("user"),$.isVoiceActive()?Xs():fo()});return}if(ht){let b=ne.value.trim();yt.manuallyDeactivated=!0,_n(),xn("user"),b&&(ne.value="",ne.style.height="auto",$.sendMessage(b))}else yt.manuallyDeactivated=!1,_n(),Qt("user")};jn=Ja,G&&(G.addEventListener("click",Ja),ft.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),fo()):xn("system"),G&&G.removeEventListener("click",Ja)}));let ff=s.on("assistant:complete",()=>{Fs&&(yt.active||yt.manuallyDeactivated||Fs==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!yt.active&&!yt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),dr("auto"),$.isVoiceActive()&&Xs()}):Qt("auto"))},600))});ft.push(ff);let hf=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});ft.push(hf);let fs=()=>{Dt(!M,"user")},on=null,sn=null;if(S&&!_()){let c=o.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>Sa(r,fs).element,onToggle:fs});m&&(sn=m)}sn||(on=Sa(r,fs))}on?e.appendChild(on.element):sn&&e.appendChild(sn),go(),as(),Bo(),ms($.isStreaming()),mt()==="follow"?Hr(!0):Vs(),Oa(),k&&(!S||_()?setTimeout(()=>gs(),0):M&&setTimeout(()=>gs(),200));let Ys=()=>{var B,xe,me,te,Ee,$e,Te,st,Ke,dt,pt,Ie,Pe,qe,Xe,wt,P,Be,Ne,he,Ft,Ot;if(_()){yn(),go();return}let c=mn(r),m=(xe=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?xe:!1,b=c||m||((te=(me=r.launcher)==null?void 0:me.fullHeight)!=null?te:!1),x=(Ee=e.ownerDocument.defaultView)!=null?Ee:window,E=(Te=($e=r.launcher)==null?void 0:$e.mobileFullscreen)!=null?Te:!0,D=(Ke=(st=r.launcher)==null?void 0:st.mobileBreakpoint)!=null?Ke:640,N=x.innerWidth<=D,q=E&&N&&S;try{if(q){hr(),Ao(e,r);return}if(W&&(W=!1,hr(),Ao(e,r)),!S&&!c){fe.style.height="",fe.style.width="";return}if(!m&&!c){let Jt=(pt=(dt=r==null?void 0:r.launcher)==null?void 0:dt.width)!=null?pt:r==null?void 0:r.launcherWidth,Ct=Jt!=null?Jt:nr;fe.style.width=Ct,fe.style.maxWidth=Ct}if(Lr(),!b){let Jt=x.innerHeight,Ct=64,zt=(Pe=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Pe:0,Zn=Math.max(200,Jt-Ct),ln=Math.min(640,Zn),Ye=Math.max(200,ln-zt);fe.style.height=`${Ye}px`}}finally{if(yn(),go(),M&&S){let Ct=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((wt=(Xe=r.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?wt:640),zt=(Be=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Be:!1,Zn=(he=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?he:!0,ln=mn(r)&&Zn&&Ct,Ye=zt||Zn&&Ct&&S||ln;if(Ye&&!rn){let It=e.getRootNode(),un=It instanceof ShadowRoot?It.host:e.closest(".persona-host");un&&!nn&&(nn=_l(un,(Ot=(Ft=r.launcher)==null?void 0:Ft.zIndex)!=null?Ot:Ln)),rn=$l(e.ownerDocument)}else Ye||(nn==null||nn(),nn=null,rn==null||rn(),rn=null)}}};Ys();let wc=(Sd=e.ownerDocument.defaultView)!=null?Sd:window;if(wc.addEventListener("resize",Ys),ft.push(()=>wc.removeEventListener("resize",Ys)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yn()});c.observe(Ue),ft.push(()=>c.disconnect())}Yn=ue.scrollTop;let Cc=Zr(ue),bf=()=>{let c=ue.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:ue.ownerDocument.getSelection()},gl=()=>Bm(bf(),ue),Ac=()=>{let c=ue.scrollTop,m=Zr(ue),b=m<Cc;if(Cc=m,mt()!=="follow"){Yn=c,$n();return}let{action:x,nextLastScrollTop:E}=Li({following:Xn.isFollowing(),currentScrollTop:c,lastScrollTop:Yn,nearBottom:Zo(ue,cs),userScrollThreshold:Ba,isAutoScrolling:vr||Io||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Yn=E,x==="resume"){gl()||Wr();return}x==="pause"&&us()};if(ue.addEventListener("scroll",Ac,{passive:!0}),ft.push(()=>ue.removeEventListener("scroll",Ac)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{$a()});c.observe(ot),c.observe(ue),ft.push(()=>c.disconnect())}let Sc=()=>{mt()==="follow"&&Xn.isFollowing()&&gl()&&us()},Tc=ue.ownerDocument;Tc.addEventListener("selectionchange",Sc),ft.push(()=>{Tc.removeEventListener("selectionchange",Sc)});let Ec=c=>{if(mt()!=="follow")return;let m=Pi({following:Xn.isFollowing(),deltaY:c.deltaY,nearBottom:Zo(ue,cs),resumeWhenNearBottom:!0});m==="pause"?us():m==="resume"&&!gl()&&Wr()};ue.addEventListener("wheel",Ec,{passive:!0}),ft.push(()=>ue.removeEventListener("wheel",Ec)),et.addEventListener("click",()=>{Wo(),ue.scrollTop=ue.scrollHeight,Yn=ue.scrollTop,Wr(),Hr(!0),$n()}),ft.push(()=>et.remove()),ft.push(()=>{$s(),Wo()});let Mc=()=>{H&&(cr&&(H.removeEventListener("click",cr),cr=null),F()?(H.style.display="",cr=()=>{Dt(!1,"user")},H.addEventListener("click",cr)):H.style.display="none")};Mc(),(()=>{let{clearChatButton:c}=De;c&&c.addEventListener("click",()=>{$.clearMessages(),Ur.clear(),Wr(),wo(De.composerOverlay);try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},w.syncFromMetadata(),ce==null||ce.clear(),ge==null||ge.reset(),K==null||K.update()})})(),Ht&&Ht.addEventListener("submit",L),ne==null||ne.addEventListener("keydown",Wt),ne==null||ne.addEventListener("input",tt),ne==null||ne.addEventListener("paste",gn);let kc=(Td=e.ownerDocument)!=null?Td:document;kc.addEventListener("keydown",$t,!0);let Lc="persona-attachment-drop-active",Zs=0,fl=()=>{Zs=0,V.classList.remove(Lc)},hs=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&At!==null},Pc=c=>{!nl(c.dataTransfer)||!hs()||(Zs++,Zs===1&&V.classList.add(Lc))},Ic=c=>{!nl(c.dataTransfer)||!hs()||(Zs--,Zs<=0&&fl())},Rc=c=>{!nl(c.dataTransfer)||!hs()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Wc=c=>{var b;if(!nl(c.dataTransfer)||!hs())return;c.preventDefault(),c.stopPropagation(),fl();let m=Array.from((b=c.dataTransfer.files)!=null?b:[]);m.length!==0&&At.handleFiles(m)},ho=!0;V.addEventListener("dragenter",Pc,ho),V.addEventListener("dragleave",Ic,ho),e.addEventListener("dragover",Rc,ho),e.addEventListener("drop",Wc,ho);let Qa=e.ownerDocument,Hc=c=>{hs()&&c.preventDefault()},Bc=c=>{hs()&&c.preventDefault()};Qa.addEventListener("dragover",Hc),Qa.addEventListener("drop",Bc),ft.push(()=>{Ht&&Ht.removeEventListener("submit",L),ne==null||ne.removeEventListener("keydown",Wt),ne==null||ne.removeEventListener("input",tt),ne==null||ne.removeEventListener("paste",gn),kc.removeEventListener("keydown",$t,!0)}),ft.push(()=>{V.removeEventListener("dragenter",Pc,ho),V.removeEventListener("dragleave",Ic,ho),e.removeEventListener("dragover",Rc,ho),e.removeEventListener("drop",Wc,ho),Qa.removeEventListener("dragover",Hc),Qa.removeEventListener("drop",Bc),fl()}),ft.push(()=>{$.cancel()}),on?ft.push(()=>{on==null||on.destroy()}):sn&&ft.push(()=>{sn==null||sn.remove()});let pn={update(c){var En,Wn,Br,vn,Hn,Bn,_o,ea,Rd,Wd,Hd,Bd,Dd,Od,Nd,Fd,_d,$d,Ud,jd,qd,zd,Vd,Kd,Gd,Jd,Qd,Xd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Op,Np,Fp,_p,$p,Up,jp,qp,zp,Vp,Kp,Gp,Jp,Qp,Xp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,bu,yu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu;let m=r.toolCall,b=r.messageActions,x=(En=r.layout)==null?void 0:En.messages,E=r.colorScheme,D=r.loadingIndicator,N=r.iterationDisplay,q=(Wn=r.features)==null?void 0:Wn.showReasoning,B=(Br=r.features)==null?void 0:Br.showToolCalls,xe=(vn=r.features)==null?void 0:vn.toolCallDisplay,me=(Hn=r.features)==null?void 0:Hn.reasoningDisplay;r={...r,...c},hr(),Ao(e,r),Ki(e,r),Gi(e,r),Jn(),r.colorScheme!==E&&lo();let te=Pa.getForInstance(r.plugins);o.length=0,o.push(...te),S=(_o=(Bn=r.launcher)==null?void 0:Bn.enabled)!=null?_o:!0,O=(Rd=(ea=r.launcher)==null?void 0:ea.autoExpand)!=null?Rd:!1,ze=(Hd=(Wd=r.features)==null?void 0:Wd.showReasoning)!=null?Hd:!0,Ae=(Dd=(Bd=r.features)==null?void 0:Bd.showToolCalls)!=null?Dd:!0,be=(Nd=(Od=r.features)==null?void 0:Od.scrollToBottom)!=null?Nd:{};let Ee=mt();Le=(_d=(Fd=r.features)==null?void 0:Fd.scrollBehavior)!=null?_d:{},Ee!==mt()&&(Wo(),Wr()),Mr(),$n();let $e=Re;if(Re=(Ud=($d=r.features)==null?void 0:$d.showEventStreamToggle)!=null?Ud:!1,Re&&!$e){if(ce||(X=new ka(de),ce=new Ma(re,X),ge=ge!=null?ge:new La,X.open().then(()=>ce==null?void 0:ce.restore()).catch(()=>{}),$.setSSEEventCallback((Q,Tt)=>{var jt;(jt=r.onSSEEvent)==null||jt.call(r,Q,Tt),ge==null||ge.processEvent(Q,Tt),ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!vt&&_e){let Q=(qd=(jd=r.features)==null?void 0:jd.eventStream)==null?void 0:qd.classNames,Tt="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:"");vt=h("button",Tt),vt.style.width="28px",vt.style.height="28px",vt.style.color=On.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let jt=Ce("activity","18px","currentColor",1.5);jt&&vt.appendChild(jt);let ut=De.clearChatButtonWrapper,Rt=De.closeButtonWrapper,hn=ut||Rt;hn&&hn.parentNode===_e?_e.insertBefore(vt,hn):_e.appendChild(vt),vt.addEventListener("click",()=>{ae?fr():Nr()})}}else!Re&&$e&&(fr(),vt&&(vt.remove(),vt=null),ce==null||ce.clear(),X==null||X.destroy(),ce=null,X=null,ge==null||ge.reset(),ge=null);if(((zd=r.launcher)==null?void 0:zd.enabled)===!1&&on&&(on.destroy(),on=null),((Vd=r.launcher)==null?void 0:Vd.enabled)===!1&&sn&&(sn.remove(),sn=null),((Kd=r.launcher)==null?void 0:Kd.enabled)!==!1&&!on&&!sn){let Q=o.find(Tt=>Tt.renderLauncher);if(Q!=null&&Q.renderLauncher){let Tt=Q.renderLauncher({config:r,defaultRenderer:()=>Sa(r,fs).element,onToggle:fs});Tt&&(sn=Tt,e.appendChild(sn))}sn||(on=Sa(r,fs),e.appendChild(on.element))}on&&on.update(r),Oe&&((Gd=r.launcher)==null?void 0:Gd.title)!==void 0&&(Oe.textContent=r.launcher.title),Qe&&((Jd=r.launcher)==null?void 0:Jd.subtitle)!==void 0&&(Qe.textContent=r.launcher.subtitle);let Te=(Qd=r.layout)==null?void 0:Qd.header;if((Te==null?void 0:Te.layout)!==T&&_e){let Q=Te?Ps(r,Te,{showClose:F(),onClose:()=>Dt(!1,"user")}):eo({config:r,showClose:F(),onClose:()=>Dt(!1,"user")});_e.replaceWith(Q.header),_e=Q.header,pe=Q.iconHolder,Oe=Q.headerTitle,Qe=Q.headerSubtitle,H=Q.closeButton,T=Te==null?void 0:Te.layout}else if(Te&&(pe&&(pe.style.display=Te.showIcon===!1?"none":""),Oe&&(Oe.style.display=Te.showTitle===!1?"none":""),Qe&&(Qe.style.display=Te.showSubtitle===!1?"none":""),H&&(H.style.display=Te.showCloseButton===!1?"none":""),De.clearChatButtonWrapper)){let Q=Te.showClearChat;if(Q!==void 0){De.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:Tt}=De;Tt&&!Tt.classList.contains("persona-absolute")&&(Q?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let Ke=((Xd=r.layout)==null?void 0:Xd.showHeader)!==!1;_e&&(_e.style.display=Ke?"":"none");let dt=((Yd=r.layout)==null?void 0:Yd.showFooter)!==!1;Ue&&(Ue.style.display=dt?"":"none"),yn(),$n(),S!==R?S?Dt(O,"auto"):(M=!0,go()):O!==I&&Dt(O,"auto"),I=O,R=S,Ys(),Mc();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(m),qe=JSON.stringify(r.messageActions)!==JSON.stringify(b),Xe=JSON.stringify((Zd=r.layout)==null?void 0:Zd.messages)!==JSON.stringify(x),wt=((ep=r.loadingIndicator)==null?void 0:ep.render)!==(D==null?void 0:D.render)||((tp=r.loadingIndicator)==null?void 0:tp.renderIdle)!==(D==null?void 0:D.renderIdle)||((np=r.loadingIndicator)==null?void 0:np.showBubble)!==(D==null?void 0:D.showBubble),P=r.iterationDisplay!==N,Be=((op=(rp=r.features)==null?void 0:rp.showReasoning)!=null?op:!0)!==(q!=null?q:!0)||((ap=(sp=r.features)==null?void 0:sp.showToolCalls)!=null?ap:!0)!==(B!=null?B:!0)||JSON.stringify((ip=r.features)==null?void 0:ip.toolCallDisplay)!==JSON.stringify(xe)||JSON.stringify((lp=r.features)==null?void 0:lp.reasoningDisplay)!==JSON.stringify(me);(Pe||qe||Xe||wt||P||Be)&&$&&(Ns++,Ho(ot,$.getMessages(),ke));let he=(cp=r.launcher)!=null?cp:{},Ft=(dp=he.headerIconHidden)!=null?dp:!1,Ot=(up=(pp=r.layout)==null?void 0:pp.header)==null?void 0:up.showIcon,Jt=Ft||Ot===!1,Ct=he.headerIconName,zt=(mp=he.headerIconSize)!=null?mp:"48px";if(pe){let Q=V.querySelector(".persona-border-b-persona-divider"),Tt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Jt)pe.style.display="none",Q&&Tt&&!Q.contains(Tt)&&Q.insertBefore(Tt,Q.firstChild);else{if(pe.style.display="",pe.style.height=zt,pe.style.width=zt,Q&&Tt&&(Q.contains(pe)?pe.nextSibling!==Tt&&(pe.remove(),Q.insertBefore(pe,Tt)):Q.insertBefore(pe,Tt)),Ct){let ut=parseFloat(zt)||24,Rt=Ce(Ct,ut*.6,"#ffffff",2);Rt?pe.replaceChildren(Rt):pe.textContent=(gp=he.agentIconText)!=null?gp:"\u{1F4AC}"}else if(he.iconUrl){let ut=pe.querySelector("img");if(ut)ut.src=he.iconUrl,ut.style.height=zt,ut.style.width=zt;else{let Rt=document.createElement("img");Rt.src=he.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=zt,Rt.style.width=zt,pe.replaceChildren(Rt)}}else{let ut=pe.querySelector("svg"),Rt=pe.querySelector("img");(ut||Rt)&&pe.replaceChildren(),pe.textContent=(fp=he.agentIconText)!=null?fp:"\u{1F4AC}"}let jt=pe.querySelector("img");jt&&(jt.style.height=zt,jt.style.width=zt)}}let Zn=(bp=(hp=r.layout)==null?void 0:hp.header)==null?void 0:bp.showTitle,ln=(xp=(yp=r.layout)==null?void 0:yp.header)==null?void 0:xp.showSubtitle;if(Oe&&(Oe.style.display=Zn===!1?"none":""),Qe&&(Qe.style.display=ln===!1?"none":""),H){((wp=(vp=r.layout)==null?void 0:vp.header)==null?void 0:wp.showCloseButton)===!1?H.style.display="none":H.style.display="";let Tt=(Cp=he.closeButtonSize)!=null?Cp:"32px",jt=(Ap=he.closeButtonPlacement)!=null?Ap:"inline";H.style.height=Tt,H.style.width=Tt;let{closeButtonWrapper:ut}=De,Rt=jt==="top-right",hn=ut==null?void 0:ut.classList.contains("persona-absolute");if(ut&&Rt!==hn)if(ut.remove(),Rt)ut.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",V.style.position="relative",V.appendChild(ut);else{let gt=(Tp=(Sp=he.clearChat)==null?void 0:Sp.placement)!=null?Tp:"inline",bn=(Mp=(Ep=he.clearChat)==null?void 0:Ep.enabled)!=null?Mp:!0;ut.className=bn&&gt==="inline"?"":"persona-ml-auto";let Un=V.querySelector(".persona-border-b-persona-divider");Un&&Un.appendChild(ut)}if(H.style.color=he.closeButtonColor||On.actionIconColor,he.closeButtonBackgroundColor?(H.style.backgroundColor=he.closeButtonBackgroundColor,H.classList.remove("hover:persona-bg-gray-100")):(H.style.backgroundColor="",H.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let gt=he.closeButtonBorderWidth||"0px",bn=he.closeButtonBorderColor||"transparent";H.style.border=`${gt} solid ${bn}`,H.classList.remove("persona-border-none")}else H.style.border="",H.classList.add("persona-border-none");he.closeButtonBorderRadius?(H.style.borderRadius=he.closeButtonBorderRadius,H.classList.remove("persona-rounded-full")):(H.style.borderRadius="",H.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(H.style.paddingLeft=he.closeButtonPaddingX,H.style.paddingRight=he.closeButtonPaddingX):(H.style.paddingLeft="",H.style.paddingRight=""),he.closeButtonPaddingY?(H.style.paddingTop=he.closeButtonPaddingY,H.style.paddingBottom=he.closeButtonPaddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Mn=(kp=he.closeButtonIconName)!=null?kp:"x",Cr=(Lp=he.closeButtonIconText)!=null?Lp:"\xD7";H.innerHTML="";let Dn=Ce(Mn,"28px","currentColor",1);Dn?H.appendChild(Dn):H.textContent=Cr;let an=(Pp=he.closeButtonTooltipText)!=null?Pp:"Close chat",tr=(Ip=he.closeButtonShowTooltip)!=null?Ip:!0;if(H.setAttribute("aria-label",an),ut&&(ut._cleanupTooltip&&(ut._cleanupTooltip(),delete ut._cleanupTooltip),tr&&an)){let gt=null,bn=()=>{if(gt||!H)return;let $o=H.ownerDocument,ta=$o.body;if(!ta)return;gt=Dr($o,"div","persona-clear-chat-tooltip"),gt.textContent=an;let na=Dr($o,"div");na.className="persona-clear-chat-tooltip-arrow",gt.appendChild(na);let Uo=H.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(So),gt.style.left=`${Uo.left+Uo.width/2}px`,gt.style.top=`${Uo.top-8}px`,gt.style.transform="translate(-50%, -100%)",ta.appendChild(gt)},Un=()=>{gt&&gt.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};ut.addEventListener("mouseenter",bn),ut.addEventListener("mouseleave",Un),H.addEventListener("focus",bn),H.addEventListener("blur",Un),ut._cleanupTooltip=()=>{Un(),ut&&(ut.removeEventListener("mouseenter",bn),ut.removeEventListener("mouseleave",Un)),H&&(H.removeEventListener("focus",bn),H.removeEventListener("blur",Un))}}}let{clearChatButton:Ye,clearChatButtonWrapper:It}=De;if(Ye){let Q=(Rp=he.clearChat)!=null?Rp:{},Tt=(Wp=Q.enabled)!=null?Wp:!0,jt=(Bp=(Hp=r.layout)==null?void 0:Hp.header)==null?void 0:Bp.showClearChat,ut=jt!==void 0?jt:Tt,Rt=(Dp=Q.placement)!=null?Dp:"inline";if(It){It.style.display=ut?"":"none";let{closeButtonWrapper:hn}=De;!_()&&hn&&!hn.classList.contains("persona-absolute")&&(ut?hn.classList.remove("persona-ml-auto"):hn.classList.add("persona-ml-auto"));let Mn=Rt==="top-right",Cr=It.classList.contains("persona-absolute");if(!_()&&Mn!==Cr&&ut){if(It.remove(),Mn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",V.style.position="relative",V.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let an=V.querySelector(".persona-border-b-persona-divider"),tr=De.closeButtonWrapper;an&&tr&&tr.parentElement===an?an.insertBefore(It,tr):an&&an.appendChild(It)}let Dn=De.closeButtonWrapper;Dn&&!Dn.classList.contains("persona-absolute")&&(Mn?Dn.classList.add("persona-ml-auto"):Dn.classList.remove("persona-ml-auto"))}}if(ut){if(!_()){let gt=(Op=Q.size)!=null?Op:"32px";Ye.style.height=gt,Ye.style.width=gt}let hn=(Np=Q.iconName)!=null?Np:"refresh-cw",Mn=(Fp=Q.iconColor)!=null?Fp:"";Ye.style.color=Mn||On.actionIconColor,Ye.innerHTML="";let Cr=_()?"14px":"20px",Dn=Ce(hn,Cr,"currentColor",2);if(Dn&&Ye.appendChild(Dn),Q.backgroundColor?(Ye.style.backgroundColor=Q.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let gt=Q.borderWidth||"0px",bn=Q.borderColor||"transparent";Ye.style.border=`${gt} solid ${bn}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");Q.borderRadius?(Ye.style.borderRadius=Q.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),Q.paddingX?(Ye.style.paddingLeft=Q.paddingX,Ye.style.paddingRight=Q.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),Q.paddingY?(Ye.style.paddingTop=Q.paddingY,Ye.style.paddingBottom=Q.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let an=(_p=Q.tooltipText)!=null?_p:"Clear chat",tr=($p=Q.showTooltip)!=null?$p:!0;if(Ye.setAttribute("aria-label",an),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),tr&&an)){let gt=null,bn=()=>{if(gt||!Ye)return;let $o=Ye.ownerDocument,ta=$o.body;if(!ta)return;gt=Dr($o,"div","persona-clear-chat-tooltip"),gt.textContent=an;let na=Dr($o,"div");na.className="persona-clear-chat-tooltip-arrow",gt.appendChild(na);let Uo=Ye.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(So),gt.style.left=`${Uo.left+Uo.width/2}px`,gt.style.top=`${Uo.top-8}px`,gt.style.transform="translate(-50%, -100%)",ta.appendChild(gt)},Un=()=>{gt&&gt.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};It.addEventListener("mouseenter",bn),It.addEventListener("mouseleave",Un),Ye.addEventListener("focus",bn),Ye.addEventListener("blur",Un),It._cleanupTooltip=()=>{Un(),It&&(It.removeEventListener("mouseenter",bn),It.removeEventListener("mouseleave",Un)),Ye&&(Ye.removeEventListener("focus",bn),Ye.removeEventListener("blur",Un))}}}}let un=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ia],ur=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[rs.message,rs.messageAndClick];w=Ra({parsers:un,handlers:ur,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ke=Ag(r,w,oe),$.updateConfig(r),Ho(ot,$.getMessages(),ke),as(),Bo(),ms($.isStreaming());let er=((Up=r.voiceRecognition)==null?void 0:Up.enabled)===!0,Do=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Oo=((qp=(jp=r.voiceRecognition)==null?void 0:jp.provider)==null?void 0:qp.type)==="runtype";if(er&&(Do||Oo))if(!G||!xt){let Q=uf(r.voiceRecognition,r.sendButton);Q&&(G=Q.micButton,xt=Q.micButtonWrapper,Kt.insertBefore(xt,Nn),G.addEventListener("click",Ja),G.disabled=$.isStreaming())}else{let Q=(zp=r.voiceRecognition)!=null?zp:{},Tt=(Vp=r.sendButton)!=null?Vp:{},jt=(Kp=Q.iconName)!=null?Kp:"mic",ut=(Gp=Tt.size)!=null?Gp:"40px",Rt=(Jp=Q.iconSize)!=null?Jp:ut,hn=parseFloat(Rt)||24;G.style.width=Rt,G.style.height=Rt,G.style.minWidth=Rt,G.style.minHeight=Rt;let Mn=(Xp=(Qp=Q.iconColor)!=null?Qp:Tt.textColor)!=null?Xp:"currentColor";G.innerHTML="";let Cr=Ce(jt,hn,Mn,2);Cr?G.appendChild(Cr):G.textContent="\u{1F3A4}";let Dn=(Yp=Q.backgroundColor)!=null?Yp:Tt.backgroundColor;Dn?G.style.backgroundColor=Dn:G.style.backgroundColor="",Mn?G.style.color=Mn:G.style.color="var(--persona-text, #111827)",Q.borderWidth?(G.style.borderWidth=Q.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),Q.borderColor?G.style.borderColor=Q.borderColor:G.style.borderColor="",Q.paddingX?(G.style.paddingLeft=Q.paddingX,G.style.paddingRight=Q.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),Q.paddingY?(G.style.paddingTop=Q.paddingY,G.style.paddingBottom=Q.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let an=xt==null?void 0:xt.querySelector(".persona-send-button-tooltip"),tr=(Zp=Q.tooltipText)!=null?Zp:"Start voice recognition";if(((eu=Q.showTooltip)!=null?eu:!1)&&tr)if(an)an.textContent=tr,an.style.display="";else{let bn=document.createElement("div");bn.className="persona-send-button-tooltip",bn.textContent=tr,xt==null||xt.insertBefore(bn,G)}else an&&(an.style.display="none");xt.style.display="",G.disabled=$.isStreaming()}else G&&xt&&(xt.style.display="none",((nu=(tu=r.voiceRecognition)==null?void 0:tu.provider)==null?void 0:nu.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():ht&&xn());if(((ru=r.attachments)==null?void 0:ru.enabled)===!0)if(!we||!lt){let Q=(ou=r.attachments)!=null?ou:{},jt=(au=((su=r.sendButton)!=null?su:{}).size)!=null?au:"40px";nt||(nt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),nt.style.display="none",Ht.insertBefore(nt,ne)),le||(le=document.createElement("input"),le.type="file",le.accept=((iu=Q.allowedTypes)!=null?iu:Yr).join(","),le.multiple=((lu=Q.maxFiles)!=null?lu:4)>1,le.style.display="none",le.setAttribute("aria-label","Attach files"),Ht.insertBefore(le,ne)),we=h("div","persona-send-button-wrapper"),lt=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),lt.type="button",lt.setAttribute("aria-label",(cu=Q.buttonTooltipText)!=null?cu:"Attach file");let ut=(du=Q.buttonIconName)!=null?du:"paperclip",Rt=jt,hn=parseFloat(Rt)||40,Mn=Math.round(hn*.6);lt.style.width=Rt,lt.style.height=Rt,lt.style.minWidth=Rt,lt.style.minHeight=Rt,lt.style.fontSize="18px",lt.style.lineHeight="1",lt.style.backgroundColor="transparent",lt.style.color="var(--persona-primary, #111827)",lt.style.border="none",lt.style.borderRadius="6px",lt.style.transition="background-color 0.15s ease",lt.addEventListener("mouseenter",()=>{lt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),lt.addEventListener("mouseleave",()=>{lt.style.backgroundColor="transparent"});let Cr=Ce(ut,Mn,"currentColor",1.5);Cr?lt.appendChild(Cr):lt.textContent="\u{1F4CE}",lt.addEventListener("click",tr=>{tr.preventDefault(),le==null||le.click()}),we.appendChild(lt);let Dn=(pu=Q.buttonTooltipText)!=null?pu:"Attach file",an=h("div","persona-send-button-tooltip");an.textContent=Dn,we.appendChild(an),Pt.append(we),!At&&le&&nt&&(At=Yo.fromConfig(Q),At.setPreviewsContainer(nt),le.addEventListener("change",async()=>{At&&(le!=null&&le.files)&&(await At.handleFileSelect(le.files),le.value="")})),V.querySelector(".persona-attachment-drop-overlay")||V.appendChild(Sg(Q.dropOverlay))}else{we.style.display="";let Q=(uu=r.attachments)!=null?uu:{};le&&(le.accept=((mu=Q.allowedTypes)!=null?mu:Yr).join(","),le.multiple=((gu=Q.maxFiles)!=null?gu:4)>1),At&&At.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else we&&(we.style.display="none"),At&&At.clearAttachments(),(fu=V.querySelector(".persona-attachment-drop-overlay"))==null||fu.remove();let Xt=(hu=r.sendButton)!=null?hu:{},No=(bu=Xt.useIcon)!=null?bu:!1,bo=(yu=Xt.iconText)!=null?yu:"\u2191",yo=Xt.iconName,Kr=(xu=Xt.tooltipText)!=null?xu:"Send message",Fo=(vu=Xt.showTooltip)!=null?vu:!1,wr=(wu=Xt.size)!=null?wu:"40px",rt=Xt.backgroundColor,fn=Xt.textColor;if(No){if(Ve.style.width=wr,Ve.style.height=wr,Ve.style.minWidth=wr,Ve.style.minHeight=wr,Ve.style.fontSize="18px",Ve.style.lineHeight="1",Ve.innerHTML="",fn?Ve.style.color=fn:Ve.style.color="var(--persona-button-primary-fg, #ffffff)",yo){let Q=parseFloat(wr)||24,Tt=(fn==null?void 0:fn.trim())||"currentColor",jt=Ce(yo,Q,Tt,2);jt?Ve.appendChild(jt):Ve.textContent=bo}else Ve.textContent=bo;Ve.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rt?(Ve.style.backgroundColor=rt,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=(Au=(Cu=r.copy)==null?void 0:Cu.sendButtonLabel)!=null?Au:"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.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",rt?(Ve.style.backgroundColor=rt,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),fn?Ve.style.color=fn:Ve.classList.add("persona-text-white");Xt.borderWidth?(Ve.style.borderWidth=Xt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),Xt.borderColor?Ve.style.borderColor=Xt.borderColor:Ve.style.borderColor="",Xt.paddingX?(Ve.style.paddingLeft=Xt.paddingX,Ve.style.paddingRight=Xt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),Xt.paddingY?(Ve.style.paddingTop=Xt.paddingY,Ve.style.paddingBottom=Xt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Ut=Nn==null?void 0:Nn.querySelector(".persona-send-button-tooltip");if(Fo&&Kr)if(Ut)Ut.textContent=Kr,Ut.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Kr,Nn==null||Nn.insertBefore(Q,Ve)}else Ut&&(Ut.style.display="none");let _t=(ku=(Su=r.layout)==null?void 0:Su.contentMaxWidth)!=null?ku:_()?(Mu=(Eu=(Tu=r.launcher)==null?void 0:Tu.composerBar)==null?void 0:Eu.contentMaxWidth)!=null?Mu:"720px":void 0;_t?(ot.style.maxWidth=_t,ot.style.marginLeft="auto",ot.style.marginRight="auto",ot.style.width="100%",Ht&&(Ht.style.maxWidth=_t,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Et&&(Et.style.maxWidth=_t,Et.style.marginLeft="auto",Et.style.marginRight="auto")):(ot.style.maxWidth="",ot.style.marginLeft="",ot.style.marginRight="",ot.style.width="",Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let bt=(Lu=r.statusIndicator)!=null?Lu:{},Yt=(Pu=bt.visible)!=null?Pu:!0;if(cn.style.display=Yt?"":"none",$){let Q=$.getStatus();Ze(cn,(jt=>{var ut,Rt,hn,Mn;return jt==="idle"?(ut=bt.idleText)!=null?ut:kn.idle:jt==="connecting"?(Rt=bt.connectingText)!=null?Rt:kn.connecting:jt==="connected"?(hn=bt.connectedText)!=null?hn:kn.connected:jt==="error"?(Mn=bt.errorText)!=null?Mn:kn.error:kn[jt]})(Q),bt,Q)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let kt=bt.align==="left"?"persona-text-left":bt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(kt)},open(){F()&&Dt(!0,"api")},close(){F()&&Dt(!1,"api")},toggle(){F()&&Dt(!M,"api")},clearChat(){In=!1,$.clearMessages(),Ur.clear(),Wr();try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let m=i.clear();m instanceof Promise&&m.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}d={},w.syncFromMetadata(),ce==null||ce.clear(),ge==null||ge.reset(),K==null||K.update()},setMessage(c){return!ne||$.isStreaming()?!1:(!M&&F()&&Dt(!0,"system"),ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let m=(c==null?void 0:c.trim())||ne.value.trim();return m?(!M&&F()&&Dt(!0,"system"),ne.value="",ne.style.height="auto",$.sendMessage(m),!0):!1},startVoiceRecognition(){var m,b;return $.isStreaming()?!1:((b=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:b.type)==="runtype"?($.isVoiceActive()||(!M&&F()&&Dt(!0,"system"),yt.manuallyDeactivated=!1,_n(),$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),dr("user"),$.isVoiceActive()&&Xs()})),!0):ht?!0:Cn()?(!M&&F()&&Dt(!0,"system"),yt.manuallyDeactivated=!1,_n(),Qt("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,_n(),dr("user"),fo()}),!0):!1:ht?(yt.manuallyDeactivated=!0,_n(),xn("user"),!0):!1},injectMessage(c){return!M&&F()&&Dt(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!M&&F()&&Dt(!0,"system");let m=$.injectAssistantMessage(c);return j&&(j=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(c){return!M&&F()&&Dt(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!M&&F()&&Dt(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!M&&F()&&Dt(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!M&&F()&&Dt(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!M&&F()&&Dt(!0,"system"),$.injectTestEvent(c)},async connectStream(c,m){return $.connectStream(c,m)},__pushEventStreamEvent(c){ce&&(ge==null||ge.processEvent(c.type,c.payload),ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Re||!ce||Nr()},hideEventStream(){ae&&fr()},isEventStreamVisible(){return ae},showArtifacts(){gr(r)&&(In=!1,Jn(),St==null||St.setMobileOpen(!0))},hideArtifacts(){gr(r)&&(In=!0,Jn())},upsertArtifact(c){return gr(r)?(In=!1,$.upsertArtifact(c)):null},selectArtifact(c){gr(r)&&$.selectArtifact(c)},clearArtifacts(){gr(r)&&$.clearArtifacts()},getArtifacts(){var c;return(c=$==null?void 0:$.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=$==null?void 0:$.getSelectedArtifactId())!=null?c:null},focusInput(){return S&&!M&&!_()||!ne?!1:(ne.focus(),!0)},async resolveApproval(c,m,b){let E=$.getMessages().find(D=>{var N;return D.variant==="approval"&&((N=D.approval)==null?void 0:N.id)===c});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${c}`);if(E.approval.toolType==="webmcp"){$.resolveWebMcpApproval(E.id,m);return}return $.resolveApproval(E.approval,m,b)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return s.on(c,m)},off(c,m){s.off(c,m)},isOpen(){return F()&&M},isVoiceActive(){return yt.active},getState(){return{open:F()&&M,launcherEnabled:S,voiceActive:yt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!M&&F()&&Dt(!0,"system");let m=ot.querySelector(".persona-feedback-container");m&&m.remove();let b=el({onSubmit:async(x,E)=>{var D;$.isClientTokenMode()&&await $.submitCSATFeedback(x,E),(D=c==null?void 0:c.onSubmit)==null||D.call(c,x,E)},onDismiss:c==null?void 0:c.onDismiss,...c});ot.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!M&&F()&&Dt(!0,"system");let m=ot.querySelector(".persona-feedback-container");m&&m.remove();let b=tl({onSubmit:async(x,E)=>{var D;$.isClientTokenMode()&&await $.submitNPSFeedback(x,E),(D=c==null?void 0:c.onSubmit)==null||D.call(c,x,E)},onDismiss:c==null?void 0:c.onDismiss,...c});ot.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return $.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return $.submitNPSFeedback(c,m)},destroy(){je!=null&&(clearInterval(je),je=null),ft.forEach(c=>c()),ve.remove(),Je==null||Je.remove(),on==null||on.destroy(),sn==null||sn.remove(),cr&&H.removeEventListener("click",cr)}};if((((Ed=n==null?void 0:n.debugTools)!=null?Ed:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:pn,getMessages:pn.getMessages,getStatus:pn.getStatus,getMetadata:pn.getPersistentMetadata,updateMetadata:pn.updatePersistentMetadata,clearHistory:()=>pn.clearChat(),setVoiceActive:b=>b?pn.startVoiceRecognition():pn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,ft.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.focusInput()};if(window.addEventListener("persona:focusInput",m),ft.push(()=>{window.removeEventListener("persona:focusInput",m)}),Re){let q=xe=>{let me=xe.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&pn.showEventStream()},B=xe=>{let me=xe.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&pn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",B),ft.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",B)})}let b=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.showArtifacts()},x=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.hideArtifacts()},E=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||B!=null&&B.artifact&&pn.upsertArtifact(B.artifact)},D=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||typeof(B==null?void 0:B.id)=="string"&&pn.selectArtifact(B.id)},N=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",E),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",N),ft.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",E),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",N)})}let pr=qb(r.persistState);if(pr&&F()){let c=zb(pr.storage),m=`${pr.keyPrefix}widget-open`,b=`${pr.keyPrefix}widget-voice`,x=`${pr.keyPrefix}widget-voice-mode`;if(c){let E=((Md=pr.persist)==null?void 0:Md.openState)&&c.getItem(m)==="true",D=((kd=pr.persist)==null?void 0:kd.voiceState)&&c.getItem(b)==="true",N=((Ld=pr.persist)==null?void 0:Ld.voiceState)&&c.getItem(x)==="true";if(E&&setTimeout(()=>{pn.open(),setTimeout(()=>{var q;if(D||N)pn.startVoiceRecognition();else if((q=pr.persist)!=null&&q.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(Pd=pr.persist)!=null&&Pd.openState&&(s.on("widget:opened",()=>{c.setItem(m,"true")}),s.on("widget:closed",()=>{c.setItem(m,"false")})),(Id=pr.persist)!=null&&Id.voiceState&&(s.on("voice:state",q=>{c.setItem(b,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(x,q.viaVoice?"true":"false")})),pr.clearOnChatClear){let q=()=>{c.removeItem(m),c.removeItem(b),c.removeItem(x)},B=()=>q();window.addEventListener("persona:clear-chat",B),ft.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return p&&F()&&setTimeout(()=>{pn.open()},0),Vr(),pn};var Vb=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},Kb=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Gb=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Jb=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Tg=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!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"},ic=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=""},Eg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ic(e)},oc=e=>{e.style.transition=""},sc=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="",e.style.marginLeft=""},ac=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ol=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Qb=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Xb=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Mg=(e,t,n,r,o,s,a)=>{var v,y,w,S,O,k;let i=rr(s),d=i.reveal==="push";Qb(e,t,n,r,d),Xb(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",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(y=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?y:!0,u=(S=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileBreakpoint)!=null?S:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),sc(t),oc(r),Eg(r),ac(n),ol(o,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((k=(O=s==null?void 0:s.launcher)==null?void 0:O.zIndex)!=null?k:Ln),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.marginLeft="0",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"),Eg(r),Kb(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",sc(t),oc(r),ac(n),ol(o,r);let I=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",T=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=T,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",oc(r),ic(r),ol(o,r);let I=Vb(i.width,e.clientWidth),R=Math.max(0,e.clientWidth),T=i.animate?"margin-left 180ms ease":"none",W=i.side==="right"?a?-I:0:a?0:-I;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=T,t.style.marginLeft=`${W}px`,t.style.transform="",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.top="",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="",sc(t),ic(r),ac(n),ol(o,r);let I=i.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",T=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",Gb(r,i.maxHeight),r.style.overflow=I||W?"hidden":"visible",r.style.transition=T,I&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Yb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Tg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Tg(n,r)},destroy(){n.remove()}}},Zb=(e,t)=>{var k,I,R,T;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(I=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)==null||I?(T=(R=t==null?void 0:t.launcher)==null?void 0:R.autoExpand)!=null?T:!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 f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),rr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Mg(a,i,d,l,p,t,u)}),f.observe(a))},y=!1,w=()=>{Mg(a,i,d,l,p,t,u),v(),u&&!y&&a.dataset.personaDockMobileFullscreen!=="true"&&(y=!0,Jb(a,rr(t)))},S=a.ownerDocument.defaultView,O=()=>{w()};return S==null||S.addEventListener("resize",O),rr(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),w(),{mode:"docked",host:p,shell:a,syncWidgetState(W){let _=W.launcherEnabled?W.open:!0;u!==_&&(u=_,w())},updateConfig(W){var _,F;t=W,((F=(_=t==null?void 0:t.launcher)==null?void 0:_.enabled)!=null?F:!0)===!1&&(u=!0),w()},destroy(){S==null||S.removeEventListener("resize",O),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Wa=(e,t)=>mn(t)?Zb(e,t):Yb(e,t);var lc={},kg=!1,ey=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},ty=()=>{try{if(typeof lc!="undefined"&&lc.url)return new URL("../widget.css",lc.url).href}catch{}return null},Lg=(e,t)=>{let n=ty(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},cc=e=>{let t=ey(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Wa(t,o),a,i=[],d=(w,S)=>{var R,T;let k=!((T=(R=S==null?void 0:S.launcher)==null?void 0:R.enabled)!=null?T:!0)||mn(S),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),k&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let W=w.attachShadow({mode:"open"});W.appendChild(I),Lg(W,r)}else w.appendChild(I),Lg(w,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let w=d(s.host,o);a=rl(w,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(kg||(kg=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let g=w=>{f(),s.destroy(),s=Wa(t,w),o=w,u()},v={update(w){var T,W,_,F,M,j;let S={...o,...w,launcher:{...(T=o==null?void 0:o.launcher)!=null?T:{},...(W=w==null?void 0:w.launcher)!=null?W:{},dock:{...(F=(_=o==null?void 0:o.launcher)==null?void 0:_.dock)!=null?F:{},...(j=(M=w==null?void 0:w.launcher)==null?void 0:M.dock)!=null?j:{}}}},O=mn(o),k=mn(S),I=Eo(o),R=Eo(S);if(O!==k||I!==R){g(S);return}o=S,s.updateConfig(o),a.update(w),l()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},y=new Proxy(v,{get(w,S,O){if(S==="host")return s.host;if(S in w)return Reflect.get(w,S,O);let k=a[S];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=y),y};var Hg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),ny=new Set(["button","a","input","select","textarea","details","summary"]),ry=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),dc=/\b(product|card|item|listing|result)\b/i,uc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,oy=3e3,sy=100;function Bg(e){let t=typeof e.className=="string"?e.className:"";if(dc.test(t)||e.id&&dc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&dc.test(r.value))return!0}return!1}function Dg(e){var t;return uc.test(((t=e.textContent)!=null?t:"").trim())}function Og(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function ay(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Pg(e){let t=e.match(uc);return t?t[0]:null}function Ig(e){var r,o,s;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&&((o=t.textContent)!=null&&o.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(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function iy(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var ly="commerce-card",cy="result-card";function Rg(e){return!Bg(e)||!Dg(e)||!Og(e)&&!ay(e)?0:5200}function Wg(e){var r;return!Bg(e)||Dg(e)||!Og(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 mc=[{id:ly,scoreElement(e){return Rg(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||uc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(Rg(e)===0)return null;let{title:n,href:r}=Ig(e),o=(p=(l=Pg(((d=e.textContent)!=null?d:"").trim()))!=null?l:Pg(t.text))!=null?p:"",s=iy(e);return[r&&n?`[${n}](${r})${o?` \u2014 ${o}`:""}`:n?`${n}${o?` \u2014 ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
108
+ `)}},{id:cy,scoreElement(e){return Wg(e)},formatSummary(e,t){if(Wg(e)===0)return null;let{title:n,href:r}=Ig(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
+ `)}}];function dy(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function py(e){var p,u,f,g,v,y,w,S,O,k,I,R,T;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(v=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?v:".persona-host",o=(w=(y=t.maxTextLength)!=null?y:e.maxTextLength)!=null?w:200,s=(O=(S=t.visibleOnly)!=null?S:e.visibleOnly)!=null?O:!0,a=(k=t.root)!=null?k:e.root,i=(I=t.mode)!=null?I:"structured",d=(R=t.maxCandidates)!=null?R:Math.max(500,n*10),l=(T=e.rules)!=null?T:mc;return i==="simple"&&e.rules&&e.rules.length>0?(dy(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function pc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var uy=["data-testid","data-product","data-action","data-id","data-name","data-type"];function my(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"||ny.has(t)||n&&ry.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Ng(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 gy(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);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 gc(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${pc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of uy){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${pc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>pc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function fy(e){return e==="static"?sy:oy}function Fg(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:gc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:my(e),attributes:gy(e)}}function hy(e,t,n,r){let o=fy(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function by(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 yy(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(Hg.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Ng(l)){i=a.nextNode();continue}let u=Fg(l,e.maxTextLength),f=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(w=>w==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:v,formattingRule:y}=hy(l,u,e.rules,n);o.push({el:l,domIndex:s,enriched:u,score:v,formattingRule:y}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=e.maxElements)break;by(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var f;let p;if((f=l.formattingRule)!=null&&f.formatSummary){let g=l.formattingRule.formatSummary(l.el,l.enriched,n);g&&(p=g)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function xy(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(Hg.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Ng(d)){s=o.nextNode();continue}let p=Fg(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!u&&!f){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.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 _g(e={}){var r;let t=py(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?xy(t,n):yy(t,n):[]}var sl=100;function $g(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"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 o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Yi)}" (clickable)`);r.push(`Interactive elements:
113
+ `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,sl)}" (clickable)`);r.push(`Interactive elements:
114
114
  ${a.join(`
115
- `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Yi)}" (navigable)`);r.push(`Navigation links:
115
+ `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,sl)}" (navigable)`);r.push(`Navigation links:
116
116
  ${a.join(`
117
- `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Yi)}" (input)`);r.push(`Form inputs:
117
+ `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,sl)}" (input)`);r.push(`Form inputs:
118
118
  ${a.join(`
119
- `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Yi)}"`);r.push(`Content:
119
+ `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,sl)}"`);r.push(`Content:
120
120
  ${a.join(`
121
121
  `)}`)}return r.join(`
122
122
 
123
- `)}var Pg="3.31.1";var ns=Pg;function Ig(){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 Wg(){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 Rg(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:Dr(e.colors.primary,.95),100:Dr(e.colors.primary,.9),200:Dr(e.colors.primary,.8),300:Dr(e.colors.primary,.7),400:Dr(e.colors.primary,.6),500:e.colors.primary,600:Dr(e.colors.primary,.8),700:Dr(e.colors.primary,.7),800:Dr(e.colors.primary,.6),900:Dr(e.colors.primary,.5),950:Dr(e.colors.primary,.45)}}),{...t,palette:n}}}}function Hg(){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 Bg(){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 Dr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Dg(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var ry={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"}}},Ng={components:{panel:{borderRadius:"0",shadow:"none"}}},sc={id:"shop",label:"Shopping Assistant",config:{theme:ry,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:er},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?"]}},ac={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ng}},ic={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ng}},lc={shop:sc,minimal:ac,fullscreen:ic};function Og(e){return lc[e]}var Fg=Zl;function to(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function oy(e){if(e)return{getHeaders:to(e.getHeaders),onFeedback:to(e.onFeedback),onCopy:to(e.onCopy),requestMiddleware:to(e.requestMiddleware),actionHandlers:to(e.actionHandlers),actionParsers:to(e.actionParsers),postprocessMessage:to(e.postprocessMessage),contextProviders:to(e.contextProviders),streamParser:to(e.streamParser)}}var $g=`({ text, message }: any) => {
123
+ `)}var Ug="3.34.0";var os=Ug;function jg(){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 qg(){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 zg(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:Or(e.colors.primary,.95),100:Or(e.colors.primary,.9),200:Or(e.colors.primary,.8),300:Or(e.colors.primary,.7),400:Or(e.colors.primary,.6),500:e.colors.primary,600:Or(e.colors.primary,.8),700:Or(e.colors.primary,.7),800:Or(e.colors.primary,.6),900:Or(e.colors.primary,.5),950:Or(e.colors.primary,.45)}}),{...t,palette:n}}}}function Vg(){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 Kg(){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 Or(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Gg(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var wy={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"}}},Jg={components:{panel:{borderRadius:"0",shadow:"none"}}},fc={id:"shop",label:"Shopping Assistant",config:{theme:wy,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:nr},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?"]}},hc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Jg}},bc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Jg}},yc={shop:fc,minimal:hc,fullscreen:bc};function Qg(e){return yc[e]}var Xg=cc;function no(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function Cy(e){if(e)return{getHeaders:no(e.getHeaders),onFeedback:no(e.onFeedback),onCopy:no(e.onCopy),requestMiddleware:no(e.requestMiddleware),actionHandlers:no(e.actionHandlers),actionParsers:no(e.actionParsers),postprocessMessage:no(e.postprocessMessage),contextProviders:no(e.contextProviders),streamParser:no(e.streamParser)}}var Yg=`({ 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
- }`,_g=`function(ctx) {
136
+ }`,Zg=`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
- }`,jg=`(action: any, context: any) => {
149
+ }`,ef=`(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
- }`,Ug=`function(action, context) {
166
+ }`,tf=`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
- }`,sy=`(parsed: any) => {
183
+ }`,Ay=`(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
- }`,ay=`function(parsed) {
189
+ }`,Sy=`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 iy(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 Zi(e){var t,n;return(n=(t=e.parserType)!=null?t:iy(e.streamParser))!=null?n:"plain"}function el(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function tl(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(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 nl(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function rl(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),o&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="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} },`)):s==="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} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function cc(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 qg(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),qg(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function ko(e,t,n,r){n&&(e.push(`${r}${t}: {`),qg(e,n,`${r} `),e.push(`${r}},`))}function Ma(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function zg(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:oy(n.hooks)}:void 0;return t==="esm"?ly(r,o):t==="script-installer"?py(r,o):t==="script-advanced"?my(r,o):t==="react-component"?cy(r,o):t==="react-advanced"?dy(r,o):uy(r,o)}function ly(e,t){let n=t==null?void 0:t.hooks,r=Zi(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ma(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...el(e," ")),s.push(...tl(e," ",n)),s.push(...nl(e," ")),s.push(...rl(e," ")),s.push(...cc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
196
- `)}function cy(e,t){let n=t==null?void 0:t.hooks,r=Zi(e),o=r!=="plain",s=["// 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: '${Ma(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...el(e," ")),s.push(...tl(e," ",n)),s.push(...nl(e," ")),s.push(...rl(e," ")),s.push(...cc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
197
- `)}function dy(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: '${Ma(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&&ko(r,"theme",e.theme," "),e.launcher&&ko(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),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(...el(e," ")),r.push(...tl(e," ",n)),r.push(...nl(e," ")),r.push(...rl(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(${sy}),`)),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(` ${$g}`),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(` ${$g}`),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(` ${jg}`),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(` ${jg}`),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 Vg(e){var o;let t=Zi(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),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};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&&(s.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,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(l[p]=u)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function py(e,t){let n=Vg(e),o=!!(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,s=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ns}/dist/install.global.js" data-config='${s}'></script>`}function uy(e,t){let n=t==null?void 0:t.hooks,r=Zi(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ns}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ns}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ma(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...el(e," ")),s.push(...tl(e," ",n)),s.push(...nl(e," ")),s.push(...rl(e," ")),s.push(...cc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
199
- `)}function my(e,t){let n=t==null?void 0:t.hooks,r=Vg(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
195
+ }`;function Ty(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 al(e){var t,n;return(n=(t=e.parserType)!=null?t:Ty(e.streamParser))!=null?n:"plain"}function il(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function ll(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(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 cl(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function dl(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),o&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="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} },`)):s==="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} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function xc(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 nf(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),nf(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function ko(e,t,n,r){n&&(e.push(`${r}${t}: {`),nf(e,n,`${r} `),e.push(`${r}},`))}function Ha(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function rf(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:Cy(n.hooks)}:void 0;return t==="esm"?Ey(r,o):t==="script-installer"?Ly(r,o):t==="script-advanced"?Iy(r,o):t==="react-component"?My(r,o):t==="react-advanced"?ky(r,o):Py(r,o)}function Ey(e,t){let n=t==null?void 0:t.hooks,r=al(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ha(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...il(e," ")),s.push(...ll(e," ",n)),s.push(...cl(e," ")),s.push(...dl(e," ")),s.push(...xc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
196
+ `)}function My(e,t){let n=t==null?void 0:t.hooks,r=al(e),o=r!=="plain",s=["// 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: '${Ha(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...il(e," ")),s.push(...ll(e," ",n)),s.push(...cl(e," ")),s.push(...dl(e," ")),s.push(...xc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
197
+ `)}function ky(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: '${Ha(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&&ko(r,"theme",e.theme," "),e.launcher&&ko(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),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(...il(e," ")),r.push(...ll(e," ",n)),r.push(...cl(e," ")),r.push(...dl(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(${Ay}),`)),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(` ${Yg}`),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(` ${Yg}`),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(` ${ef}`),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(` ${ef}`),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 of(e){var o;let t=al(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),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};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&&(s.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,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(l[p]=u)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function Ly(e,t){let n=of(e),o=!!(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,s=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/install.global.js" data-config='${s}'></script>`}function Py(e,t){let n=t==null?void 0:t.hooks,r=al(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ha(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...il(e," ")),s.push(...ll(e," ",n)),s.push(...cl(e," ")),s.push(...dl(e," ")),s.push(...xc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
199
+ `)}function Iy(e,t){let n=t==null?void 0:t.hooks,r=of(e),s=["<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@${ns}/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&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&n.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${ay});`),s.push(" };")),s.push(""),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${_g}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${_g}`),s.push(" ];")),s.push(""),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Ug}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Ug}`),s.push(" ];")),s.push(""),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n!=null&&n.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.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: '${Ma(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>"),s.join(`
202
- `)}var Kg={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Jg=.1,Gg=.15,Xg=1.5,dc=24,Qg=40,gy=`
201
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/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&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&n.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${Sy});`),s.push(" };")),s.push(""),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Zg}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Zg}`),s.push(" ];")),s.push(""),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${tf}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${tf}`),s.push(" ];")),s.push(""),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n!=null&&n.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.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: '${Ha(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>"),s.join(`
202
+ `)}var sf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},af=.1,lf=.15,cf=1.5,vc=24,df=40,Ry=`
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: ${dc}px;
353
+ padding: ${vc}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 fy(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=gy,document.head.appendChild(e)}function hy(e,t){let n=e.clientWidth-dc*2-Qg,r=e.clientHeight-dc*2-Qg;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function by(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="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 Yg(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="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");fy();let p=Math.max(0,Math.min(r,n.length-1)),u=o,f=s,m=null,v=1,x=!1,w=h("div","persona-dc-root"),T=h("div","persona-dc-toolbar"),N=h("div","persona-dc-toolbar-lead"),M=h("div","persona-dc-toolbar-trail"),I=Kt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>se(-1)}),W=h("div");W.style.position="relative";let S=h("button","persona-dc-title-btn");S.type="button",S.setAttribute("aria-expanded","false"),S.setAttribute("aria-haspopup","listbox");let k=h("span","persona-dc-title-text"),$=h("span","persona-dc-title-chevron"),O=Ce("chevron-down",12,"currentColor",2);O&&$.appendChild(O),S.append(k,$);let H=h("div","persona-dc-dropdown");H.setAttribute("role","listbox"),H.style.display="none";let U=!1;function J(){H.innerHTML="";for(let Se=0;Se<n.length;Se++){let Ze=n[Se],ve=h("button","persona-dc-dropdown-item");ve.type="button",ve.setAttribute("role","option"),ve.setAttribute("aria-current",Se===p?"true":"false");let fe=h("span");if(fe.textContent=Ze.title,ve.appendChild(fe),Ze.description){let Je=h("span","persona-dc-dropdown-desc");Je.textContent=Ze.description,ve.appendChild(Je)}ve.addEventListener("click",()=>{Me(),He(Se)}),H.appendChild(ve)}}function ce(){U=!U,H.style.display=U?"":"none",S.setAttribute("aria-expanded",U?"true":"false"),U&&J()}function Me(){U&&(U=!1,H.style.display="none",S.setAttribute("aria-expanded","false"))}S.addEventListener("click",Se=>{Se.stopPropagation(),ce()});let ze=()=>Me();document.addEventListener("click",ze),W.append(S,H);let Ae=Kt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>se(1)}),We=h("span","persona-dc-counter");N.append(I,W,Ae,We);let be=null;i&&(be=ya({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:Se=>{u=Se,re.dataset.device=u,m=null,Z()}}),M.appendChild(be.element));let ke=null;if(a){let Se=h("div","persona-dc-zoom-controls"),Ze=Kt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Je=m!=null?m:v;m=Math.max(Gg,Je-Jg),Z()}});ke=h("span","persona-dc-zoom-level"),ke.title="Reset to 100%",ke.style.cursor="pointer",ke.addEventListener("click",()=>{m=1,Z()});let ve=Kt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Je=m!=null?m:v;m=Math.min(Xg,Je+Jg),Z()}}),fe=Kt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,Z()}});Se.append(Ze,ke,ve,fe),M.appendChild(Se)}if(d){let Se=h("div","persona-dc-separator");M.appendChild(Se);let Ze=ya({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ve=>{f=ve,re.dataset.colorScheme=f,ge()}});M.appendChild(Ze.element)}let Re=h("div","persona-dc-separator");M.appendChild(Re);let de=Kt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});M.appendChild(de),T.append(N,M);let Q=h("div","persona-dc-stage"),re=h("div","persona-dc-iframe-wrapper");re.dataset.device=u,re.dataset.colorScheme=f;let le=h("iframe","persona-dc-iframe");le.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),le.setAttribute("loading","lazy"),le.title=n[p].title,re.appendChild(le),Q.appendChild(re),w.append(T,Q),e.appendChild(w);function ge(){var Se;try{let Ze=(Se=le.contentDocument)==null?void 0:Se.body;if(!Ze)return;f==="dark"?Ze.classList.add("theme-dark"):Ze.classList.remove("theme-dark")}catch{}}le.addEventListener("load",()=>ge());function V(){let Se=n[p];k.textContent=Se.title,We.textContent=`${p+1} / ${n.length}`,le.title=Se.title}function se(Se){let Ze=((p+Se)%n.length+n.length)%n.length;He(Ze)}function He(Se){Se<0||Se>=n.length||(p=Se,le.src=n[p].url,V(),l==null||l(p,n[p]))}function Z(){var ve;if(x)return;let Se=(ve=Kg[u])!=null?ve:Kg.desktop;v=hy(Q,Se);let Ze=Math.max(Gg,Math.min(Xg,m!=null?m:v));by(re,le,Se,Ze,u),ke&&(ke.textContent=`${Math.round(Ze*100)}%`)}let ee=new ResizeObserver(()=>Z());ee.observe(Q),V(),le.src=n[p].url,requestAnimationFrame(()=>Z());function ae(){x||(x=!0,ee.disconnect(),document.removeEventListener("click",ze),w.remove())}return{element:w,goTo:He,next:()=>se(1),prev:()=>se(-1),getIndex:()=>p,setDevice(Se){u=Se,re.dataset.device=Se,be==null||be.setSelected(Se),m=null,Z()},setColorScheme(Se){f=Se,re.dataset.colorScheme=Se},setZoom(Se){m=Se,Z()},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});
443
+ `;function Wy(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Ry,document.head.appendChild(e)}function Hy(e,t){let n=e.clientWidth-vc*2-df,r=e.clientHeight-vc*2-df;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function By(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="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 pf(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="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");Wy();let p=Math.max(0,Math.min(r,n.length-1)),u=o,f=s,g=null,v=1,y=!1,w=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),O=h("div","persona-dc-toolbar-lead"),k=h("div","persona-dc-toolbar-trail"),I=Vt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>ae(-1)}),R=h("div");R.style.position="relative";let T=h("button","persona-dc-title-btn");T.type="button",T.setAttribute("aria-expanded","false"),T.setAttribute("aria-haspopup","listbox");let W=h("span","persona-dc-title-text"),_=h("span","persona-dc-title-chevron"),F=Ce("chevron-down",12,"currentColor",2);F&&_.appendChild(F),T.append(W,_);let M=h("div","persona-dc-dropdown");M.setAttribute("role","listbox"),M.style.display="none";let j=!1;function z(){M.innerHTML="";for(let Se=0;Se<n.length;Se++){let Ze=n[Se],ve=h("button","persona-dc-dropdown-item");ve.type="button",ve.setAttribute("role","option"),ve.setAttribute("aria-current",Se===p?"true":"false");let fe=h("span");if(fe.textContent=Ze.title,ve.appendChild(fe),Ze.description){let Je=h("span","persona-dc-dropdown-desc");Je.textContent=Ze.description,ve.appendChild(Je)}ve.addEventListener("click",()=>{ke(),He(Se)}),M.appendChild(ve)}}function oe(){j=!j,M.style.display=j?"":"none",T.setAttribute("aria-expanded",j?"true":"false"),j&&z()}function ke(){j&&(j=!1,M.style.display="none",T.setAttribute("aria-expanded","false"))}T.addEventListener("click",Se=>{Se.stopPropagation(),oe()});let ze=()=>ke();document.addEventListener("click",ze),R.append(T,M);let Ae=Vt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>ae(1)}),Re=h("span","persona-dc-counter");O.append(I,R,Ae,Re);let be=null;i&&(be=Ea({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:Se=>{u=Se,re.dataset.device=u,g=null,Y()}}),k.appendChild(be.element));let Le=null;if(a){let Se=h("div","persona-dc-zoom-controls"),Ze=Vt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Je=g!=null?g:v;g=Math.max(lf,Je-af),Y()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{g=1,Y()});let ve=Vt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Je=g!=null?g:v;g=Math.min(cf,Je+af),Y()}}),fe=Vt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,Y()}});Se.append(Ze,Le,ve,fe),k.appendChild(Se)}if(d){let Se=h("div","persona-dc-separator");k.appendChild(Se);let Ze=Ea({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ve=>{f=ve,re.dataset.colorScheme=f,ge()}});k.appendChild(Ze.element)}let We=h("div","persona-dc-separator");k.appendChild(We);let de=Vt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});k.appendChild(de),S.append(O,k);let X=h("div","persona-dc-stage"),re=h("div","persona-dc-iframe-wrapper");re.dataset.device=u,re.dataset.colorScheme=f;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,re.appendChild(ce),X.appendChild(re),w.append(S,X),e.appendChild(w);function ge(){var Se;try{let Ze=(Se=ce.contentDocument)==null?void 0:Se.body;if(!Ze)return;f==="dark"?Ze.classList.add("theme-dark"):Ze.classList.remove("theme-dark")}catch{}}ce.addEventListener("load",()=>ge());function K(){let Se=n[p];W.textContent=Se.title,Re.textContent=`${p+1} / ${n.length}`,ce.title=Se.title}function ae(Se){let Ze=((p+Se)%n.length+n.length)%n.length;He(Ze)}function He(Se){Se<0||Se>=n.length||(p=Se,ce.src=n[p].url,K(),l==null||l(p,n[p]))}function Y(){var ve;if(y)return;let Se=(ve=sf[u])!=null?ve:sf.desktop;v=Hy(X,Se);let Ze=Math.max(lf,Math.min(cf,g!=null?g:v));By(re,ce,Se,Ze,u),Le&&(Le.textContent=`${Math.round(Ze*100)}%`)}let ee=new ResizeObserver(()=>Y());ee.observe(X),K(),ce.src=n[p].url,requestAnimationFrame(()=>Y());function ie(){y||(y=!0,ee.disconnect(),document.removeEventListener("click",ze),w.remove())}return{element:w,goTo:He,next:()=>ae(1),prev:()=>ae(-1),getIndex:()=>p,setDevice(Se){u=Se,re.dataset.device=Se,be==null||be.setSelected(Se),g=null,Y()},setColorScheme(Se){f=Se,re.dataset.colorScheme=Se},setZoom(Se){g=Se,Y()},destroy:ie}}0&&(module.exports={ASK_USER_QUESTION_CLIENT_TOOL,ASK_USER_QUESTION_PARAMETERS_SCHEMA,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,SUGGEST_REPLIES_CLIENT_TOOL,SUGGEST_REPLIES_PARAMETERS_SCHEMA,SUGGEST_REPLIES_TOOL_NAME,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,builtInClientToolsForDispatch,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,isSuggestRepliesMessage,isVoiceSupported,isWebMcpToolName,latestAgentSuggestions,listRegisteredStreamAnimations,markdownPostprocessor,mergeWithDefaults,normalizeContent,parseAskUserQuestionPayload,parseSuggestRepliesPayload,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveDockConfig,resolveSanitizer,resolveTokens,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
444
444
  //# sourceMappingURL=index.cjs.map